81df377c526c25c690f0e4cbb532b89524cee441
[oweals/gnunet.git] / src / core / gnunet-service-core.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file core/gnunet-service-core.c
23  * @brief high-level P2P messaging
24  * @author Christian Grothoff
25  *
26  * Considerations for later:
27  * - check that hostkey used by transport (for HELLOs) is the
28  *   same as the hostkey that we are using!
29  * - add code to send PINGs if we are about to time-out otherwise
30  * - optimize lookup (many O(n) list traversals
31  *   could ideally be changed to O(1) hash map lookups)
32  */
33 #include "platform.h"
34 #include "gnunet_constants.h"
35 #include "gnunet_util_lib.h"
36 #include "gnunet_hello_lib.h"
37 #include "gnunet_peerinfo_service.h"
38 #include "gnunet_protocols.h"
39 #include "gnunet_signatures.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet_transport_service.h"
42 #include "core.h"
43
44
45 #define DEBUG_HANDSHAKE GNUNET_NO
46
47 #define DEBUG_CORE_QUOTA GNUNET_NO
48
49 /**
50  * Receive and send buffer windows grow over time.  For
51  * how long can 'unused' bandwidth accumulate before we
52  * need to cap it?  (specified in seconds).
53  */
54 #define MAX_WINDOW_TIME_S (5 * 60)
55
56 /**
57  * How many messages do we queue up at most for optional
58  * notifications to a client?  (this can cause notifications
59  * about outgoing messages to be dropped).
60  */
61 #define MAX_NOTIFY_QUEUE 1024
62
63 /**
64  * Minimum bandwidth (out) to assign to any connected peer.
65  * Should be rather low; values larger than DEFAULT_BW_IN_OUT make no
66  * sense.
67  */
68 #define MIN_BANDWIDTH_PER_PEER GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT
69
70 /**
71  * After how much time past the "official" expiration time do
72  * we discard messages?  Should not be zero since we may 
73  * intentionally defer transmission until close to the deadline
74  * and then may be slightly past the deadline due to inaccuracy
75  * in sleep and our own CPU consumption.
76  */
77 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
78
79 /**
80  * What is the maximum delay for a SET_KEY message?
81  */
82 #define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
83
84 /**
85  * How long do we wait for SET_KEY confirmation initially?
86  */
87 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 1)
88
89 /**
90  * What is the maximum delay for a PING message?
91  */
92 #define MAX_PING_DELAY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 2)
93
94 /**
95  * What is the maximum delay for a PONG message?
96  */
97 #define MAX_PONG_DELAY GNUNET_TIME_relative_multiply (MAX_PING_DELAY, 2)
98
99 /**
100  * What is the minimum frequency for a PING message?
101  */
102 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
103
104 /**
105  * How often do we recalculate bandwidth quotas?
106  */
107 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
108
109 /**
110  * What is the priority for a SET_KEY message?
111  */
112 #define SET_KEY_PRIORITY 0xFFFFFF
113
114 /**
115  * What is the priority for a PING message?
116  */
117 #define PING_PRIORITY 0xFFFFFF
118
119 /**
120  * What is the priority for a PONG message?
121  */
122 #define PONG_PRIORITY 0xFFFFFF
123
124 /**
125  * How many messages do we queue per peer at most?  Must be at
126  * least two.
127  */
128 #define MAX_PEER_QUEUE_SIZE 16
129
130 /**
131  * How many non-mandatory messages do we queue per client at most?
132  */
133 #define MAX_CLIENT_QUEUE_SIZE 32
134
135 /**
136  * What is the maximum age of a message for us to consider
137  * processing it?  Note that this looks at the timestamp used
138  * by the other peer, so clock skew between machines does
139  * come into play here.  So this should be picked high enough
140  * so that a little bit of clock skew does not prevent peers
141  * from connecting to us.
142  */
143 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
144
145
146 /**
147  * State machine for our P2P encryption handshake.  Everyone starts in
148  * "DOWN", if we receive the other peer's key (other peer initiated)
149  * we start in state RECEIVED (since we will immediately send our
150  * own); otherwise we start in SENT.  If we get back a PONG from
151  * within either state, we move up to CONFIRMED (the PONG will always
152  * be sent back encrypted with the key we sent to the other peer).
153  */
154 enum PeerStateMachine
155 {
156   /**
157    * No handshake yet.
158    */
159   PEER_STATE_DOWN,
160
161   /**
162    * We've sent our session key.
163    */
164   PEER_STATE_KEY_SENT,
165   
166   /**
167    * We've received the other peers session key.
168    */
169   PEER_STATE_KEY_RECEIVED,
170
171   /**
172    * The other peer has confirmed our session key with a message
173    * encrypted with his session key (which we got).  Session is now fully up.
174    */
175   PEER_STATE_KEY_CONFIRMED
176 };
177
178
179 /**
180  * Encapsulation for encrypted messages exchanged between
181  * peers.  Followed by the actual encrypted data.
182  */
183 struct EncryptedMessage
184 {
185   /**
186    * Message type is either CORE_ENCRYPTED_MESSAGE.
187    */
188   struct GNUNET_MessageHeader header;
189
190   /**
191    * Random value used for IV generation.
192    */
193   uint32_t iv_seed GNUNET_PACKED;
194
195   /**
196    * MAC of the encrypted message (starting at 'sequence_number'),
197    * used to verify message integrity. Everything after this value
198    * (excluding this value itself) will be encrypted and authenticated.
199    * ENCRYPTED_HEADER_SIZE must be set to the offset of the *next* field.
200    */
201   GNUNET_HashCode hmac;
202
203   /**
204    * Sequence number, in network byte order.  This field
205    * must be the first encrypted/decrypted field
206    */
207   uint32_t sequence_number GNUNET_PACKED;
208
209   /**
210    * Desired bandwidth (how much we should send to this peer / how
211    * much is the sender willing to receive)?
212    */
213   struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
214
215   /**
216    * Timestamp.  Used to prevent reply of ancient messages
217    * (recent messages are caught with the sequence number).
218    */
219   struct GNUNET_TIME_AbsoluteNBO timestamp;
220
221 };
222
223
224 /**
225  * Number of bytes (at the beginning) of "struct EncryptedMessage"
226  * that are NOT encrypted.
227  */
228 #define ENCRYPTED_HEADER_SIZE (offsetof(struct EncryptedMessage, sequence_number))
229
230
231 /**
232  * We're sending an (encrypted) PING to the other peer to check if he
233  * can decrypt.  The other peer should respond with a PONG with the
234  * same content, except this time encrypted with the receiver's key.
235  */
236 struct PingMessage
237 {
238   /**
239    * Message type is CORE_PING.
240    */
241   struct GNUNET_MessageHeader header;
242   
243   /**
244    * Seed for the IV
245    */
246   uint32_t iv_seed GNUNET_PACKED;
247
248   /**
249    * Intended target of the PING, used primarily to check
250    * that decryption actually worked.
251    */
252   struct GNUNET_PeerIdentity target;
253
254   /**
255    * Random number chosen to make reply harder.
256    */
257   uint32_t challenge GNUNET_PACKED;
258 };
259
260
261
262 /**
263  * Response to a PING.  Includes data from the original PING
264  * plus initial bandwidth quota information.
265  */
266 struct PongMessage
267 {
268   /**
269    * Message type is CORE_PONG.
270    */
271   struct GNUNET_MessageHeader header;
272     
273   /**
274    * Seed for the IV
275    */
276   uint32_t iv_seed GNUNET_PACKED;
277
278   /**
279    * Random number to make faking the reply harder.  Must be
280    * first field after header (this is where we start to encrypt!).
281    */
282   uint32_t challenge GNUNET_PACKED;
283
284   /**
285    * Desired bandwidth (how much we should send to this
286    * peer / how much is the sender willing to receive).
287    */
288   struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
289
290   /**
291    * Intended target of the PING, used primarily to check
292    * that decryption actually worked.
293    */
294   struct GNUNET_PeerIdentity target;
295 };
296
297
298 /**
299  * Message transmitted to set (or update) a session key.
300  */
301 struct SetKeyMessage
302 {
303
304   /**
305    * Message type is either CORE_SET_KEY.
306    */
307   struct GNUNET_MessageHeader header;
308
309   /**
310    * Status of the sender (should be in "enum PeerStateMachine"), nbo.
311    */
312   int32_t sender_status GNUNET_PACKED;
313
314   /**
315    * Purpose of the signature, will be
316    * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
317    */
318   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
319
320   /**
321    * At what time was this key created?
322    */
323   struct GNUNET_TIME_AbsoluteNBO creation_time;
324
325   /**
326    * The encrypted session key.
327    */
328   struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
329
330   /**
331    * Who is the intended recipient?
332    */
333   struct GNUNET_PeerIdentity target;
334
335   /**
336    * Signature of the stuff above (starting at purpose).
337    */
338   struct GNUNET_CRYPTO_RsaSignature signature;
339
340 };
341
342
343 /**
344  * Message waiting for transmission. This struct
345  * is followed by the actual content of the message.
346  */
347 struct MessageEntry
348 {
349
350   /**
351    * We keep messages in a doubly linked list.
352    */
353   struct MessageEntry *next;
354
355   /**
356    * We keep messages in a doubly linked list.
357    */
358   struct MessageEntry *prev;
359
360   /**
361    * By when are we supposed to transmit this message?
362    */
363   struct GNUNET_TIME_Absolute deadline;
364
365   /**
366    * By when are we supposed to transmit this message (after
367    * giving slack)?
368    */
369   struct GNUNET_TIME_Absolute slack_deadline;
370
371   /**
372    * How important is this message to us?
373    */
374   unsigned int priority;
375
376   /**
377    * If this is a SET_KEY message, what was our connection status when this
378    * message was queued?
379    */
380   enum PeerStateMachine sender_status;
381
382   /**
383    * Is this a SET_KEY message?
384    */
385   int is_setkey;
386
387   /**
388    * How long is the message? (number of bytes following
389    * the "struct MessageEntry", but not including the
390    * size of "struct MessageEntry" itself!)
391    */
392   uint16_t size;
393
394   /**
395    * Was this message selected for transmission in the
396    * current round? GNUNET_YES or GNUNET_NO.
397    */
398   int8_t do_transmit;
399
400   /**
401    * Did we give this message some slack (delayed sending) previously
402    * (and hence should not give it any more slack)? GNUNET_YES or
403    * GNUNET_NO.
404    */
405   int8_t got_slack;
406
407 };
408
409
410 /**
411  * Record kept for each request for transmission issued by a 
412  * client that is still pending.
413  */
414 struct ClientActiveRequest;
415
416 /**
417  * Data kept per neighbouring peer.
418  */
419 struct Neighbour
420 {
421
422   /**
423    * Unencrypted messages destined for this peer.
424    */
425   struct MessageEntry *messages;
426
427   /**
428    * Head of the batched, encrypted message queue (already ordered,
429    * transmit starting with the head).
430    */
431   struct MessageEntry *encrypted_head;
432
433   /**
434    * Tail of the batched, encrypted message queue (already ordered,
435    * append new messages to tail)
436    */
437   struct MessageEntry *encrypted_tail;
438
439   /**
440    * Head of list of requests from clients for transmission to 
441    * this peer.
442    */
443   struct ClientActiveRequest *active_client_request_head;
444
445   /**
446    * Tail of list of requests from clients for transmission to 
447    * this peer.
448    */
449   struct ClientActiveRequest *active_client_request_tail;
450
451   /**
452    * Handle for pending requests for transmission to this peer
453    * with the transport service.  NULL if no request is pending.
454    */
455   struct GNUNET_TRANSPORT_TransmitHandle *th;
456
457   /**
458    * Public key of the neighbour, NULL if we don't have it yet.
459    */
460   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
461
462   /**
463    * We received a PING message before we got the "public_key"
464    * (or the SET_KEY).  We keep it here until we have a key
465    * to decrypt it.  NULL if no PING is pending.
466    */
467   struct PingMessage *pending_ping;
468
469   /**
470    * We received a PONG message before we got the "public_key"
471    * (or the SET_KEY).  We keep it here until we have a key
472    * to decrypt it.  NULL if no PONG is pending.
473    */
474   struct PongMessage *pending_pong;
475
476   /**
477    * Non-NULL if we are currently looking up HELLOs for this peer.
478    * for this peer.
479    */
480   struct GNUNET_PEERINFO_IteratorContext *pitr;
481
482   /**
483    * SetKeyMessage to transmit, NULL if we are not currently trying
484    * to send one.
485    */
486   struct SetKeyMessage *skm;
487
488   /**
489    * Performance data for the peer.
490    */ 
491   struct GNUNET_TRANSPORT_ATS_Information *ats;
492
493   /**
494    * Identity of the neighbour.
495    */
496   struct GNUNET_PeerIdentity peer;
497
498   /**
499    * Key we use to encrypt our messages for the other peer
500    * (initialized by us when we do the handshake).
501    */
502   struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
503
504   /**
505    * Key we use to decrypt messages from the other peer
506    * (given to us by the other peer during the handshake).
507    */
508   struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
509
510   /**
511    * ID of task used for re-trying plaintext scheduling.
512    */
513   GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
514
515   /**
516    * ID of task used for re-trying SET_KEY and PING message.
517    */
518   GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
519
520   /**
521    * ID of task used for updating bandwidth quota for this neighbour.
522    */
523   GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
524
525   /**
526    * ID of task used for sending keep-alive pings.
527    */
528   GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
529
530   /**
531    * ID of task used for cleaning up dead neighbour entries.
532    */
533   GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
534
535   /**
536    * At what time did we generate our encryption key?
537    */
538   struct GNUNET_TIME_Absolute encrypt_key_created;
539
540   /**
541    * At what time did the other peer generate the decryption key?
542    */
543   struct GNUNET_TIME_Absolute decrypt_key_created;
544
545   /**
546    * At what time did we initially establish (as in, complete session
547    * key handshake) this connection?  Should be zero if status != KEY_CONFIRMED.
548    */
549   struct GNUNET_TIME_Absolute time_established;
550
551   /**
552    * At what time did we last receive an encrypted message from the
553    * other peer?  Should be zero if status != KEY_CONFIRMED.
554    */
555   struct GNUNET_TIME_Absolute last_activity;
556
557   /**
558    * At what frequency are we currently re-trying SET_KEY messages?
559    */
560   struct GNUNET_TIME_Relative set_key_retry_frequency;
561
562   /**
563    * Tracking bandwidth for sending to this peer.
564    */
565   struct GNUNET_BANDWIDTH_Tracker available_send_window;
566
567   /**
568    * Tracking bandwidth for receiving from this peer.
569    */
570   struct GNUNET_BANDWIDTH_Tracker available_recv_window;
571
572   /**
573    * How valueable were the messages of this peer recently?
574    */
575   unsigned long long current_preference;
576
577   /**
578    * Number of entries in 'ats'.
579    */ 
580   unsigned int ats_count;
581
582   /**
583    * Bit map indicating which of the 32 sequence numbers before the last
584    * were received (good for accepting out-of-order packets and
585    * estimating reliability of the connection)
586    */
587   unsigned int last_packets_bitmap;
588
589   /**
590    * last sequence number received on this connection (highest)
591    */
592   uint32_t last_sequence_number_received;
593
594   /**
595    * last sequence number transmitted
596    */
597   uint32_t last_sequence_number_sent;
598
599   /**
600    * Available bandwidth in for this peer (current target).
601    */
602   struct GNUNET_BANDWIDTH_Value32NBO bw_in;    
603
604   /**
605    * Available bandwidth out for this peer (current target).
606    */
607   struct GNUNET_BANDWIDTH_Value32NBO bw_out;  
608
609   /**
610    * Internal bandwidth limit set for this peer (initially typically
611    * set to "-1").  Actual "bw_out" is MIN of
612    * "bpm_out_internal_limit" and "bw_out_external_limit".
613    */
614   struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
615
616   /**
617    * External bandwidth limit set for this peer by the
618    * peer that we are communicating with.  "bw_out" is MIN of
619    * "bw_out_internal_limit" and "bw_out_external_limit".
620    */
621   struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
622
623   /**
624    * What was our PING challenge number (for this peer)?
625    */
626   uint32_t ping_challenge;
627
628   /**
629    * What is our connection status?
630    */
631   enum PeerStateMachine status;
632
633   /**
634    * Are we currently connected to this neighbour?
635    */ 
636   int is_connected;
637
638 };
639
640
641 /**
642  * Data structure for each client connected to the core service.
643  */
644 struct Client
645 {
646   /**
647    * Clients are kept in a linked list.
648    */
649   struct Client *next;
650
651   /**
652    * Handle for the client with the server API.
653    */
654   struct GNUNET_SERVER_Client *client_handle;
655
656   /**
657    * Array of the types of messages this peer cares
658    * about (with "tcnt" entries).  Allocated as part
659    * of this client struct, do not free!
660    */
661   const uint16_t *types;
662
663   /**
664    * Map of peer identities to active transmission requests of this
665    * client to the peer (of type 'struct ClientActiveRequest').
666    */
667   struct GNUNET_CONTAINER_MultiHashMap *requests;
668
669   /**
670    * Options for messages this client cares about,
671    * see GNUNET_CORE_OPTION_ values.
672    */
673   uint32_t options;
674
675   /**
676    * Number of types of incoming messages this client
677    * specifically cares about.  Size of the "types" array.
678    */
679   unsigned int tcnt;
680
681 };
682
683
684 /**
685  * Record kept for each request for transmission issued by a 
686  * client that is still pending.
687  */
688 struct ClientActiveRequest
689 {
690
691   /**
692    * Active requests are kept in a doubly-linked list of
693    * the respective target peer.
694    */
695   struct ClientActiveRequest *next;
696
697   /**
698    * Active requests are kept in a doubly-linked list of
699    * the respective target peer.
700    */
701   struct ClientActiveRequest *prev;
702
703   /**
704    * Handle to the client.
705    */
706   struct Client *client;
707
708   /**
709    * By what time would the client want to see this message out?
710    */
711   struct GNUNET_TIME_Absolute deadline;
712
713   /**
714    * How important is this request.
715    */
716   uint32_t priority;
717
718   /**
719    * How many more requests does this client have?
720    */
721   uint32_t queue_size;
722
723   /**
724    * How many bytes does the client intend to send?
725    */
726   uint16_t msize;
727
728   /**
729    * Unique request ID (in big endian).
730    */
731   uint16_t smr_id;
732   
733 };
734
735
736
737 /**
738  * Our public key.
739  */
740 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
741
742 /**
743  * Our identity.
744  */
745 static struct GNUNET_PeerIdentity my_identity;
746
747 /**
748  * Our private key.
749  */
750 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
751
752
753 /**
754  * Handle to peerinfo service.
755  */
756 static struct GNUNET_PEERINFO_Handle *peerinfo;
757
758 /**
759  * Our message stream tokenizer (for encrypted payload).
760  */
761 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
762
763 /**
764  * Our configuration.
765  */
766 const struct GNUNET_CONFIGURATION_Handle *cfg;
767
768 /**
769  * Transport service.
770  */
771 static struct GNUNET_TRANSPORT_Handle *transport;
772
773 /**
774  * Linked list of our clients.
775  */
776 static struct Client *clients;
777
778 /**
779  * Context for notifications we need to send to our clients.
780  */
781 static struct GNUNET_SERVER_NotificationContext *notifier;
782
783 /**
784  * Map of peer identities to 'struct Neighbour'.
785  */
786 static struct GNUNET_CONTAINER_MultiHashMap *neighbours;
787
788 /**
789  * Neighbour entry for "this" peer.
790  */
791 static struct Neighbour self;
792
793 /**
794  * For creating statistics.
795  */
796 static struct GNUNET_STATISTICS_Handle *stats;
797
798 /**
799  * Sum of all preferences among all neighbours.
800  */
801 static unsigned long long preference_sum;
802
803 /**
804  * How much inbound bandwidth are we supposed to be using per second?
805  */
806 static unsigned long long bandwidth_target_in_bps;
807
808 /**
809  * How much outbound bandwidth are we supposed to be using per second?
810  */
811 static unsigned long long bandwidth_target_out_bps;
812
813 /**
814  * Derive an authentication key from "set key" information
815  */
816 static void
817 derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
818     const struct GNUNET_CRYPTO_AesSessionKey *skey,
819     uint32_t seed,
820     struct GNUNET_TIME_Absolute creation_time)
821 {
822   static const char ctx[] = "authentication key";
823   struct GNUNET_TIME_AbsoluteNBO ctbe;
824
825
826   ctbe = GNUNET_TIME_absolute_hton (creation_time);
827   GNUNET_CRYPTO_hmac_derive_key (akey,
828                                  skey,
829                                  &seed,
830                                  sizeof(seed),
831                                  &skey->key,
832                                  sizeof(skey->key),
833                                  &ctbe,
834                                  sizeof(ctbe),
835                                  ctx,
836                                  sizeof(ctx), NULL);
837 }
838
839
840 /**
841  * Derive an IV from packet information
842  */
843 static void
844 derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
845     const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
846     const struct GNUNET_PeerIdentity *identity)
847 {
848   static const char ctx[] = "initialization vector";
849
850   GNUNET_CRYPTO_aes_derive_iv (iv,
851                                skey,
852                                &seed,
853                                sizeof(seed),
854                                &identity->hashPubKey.bits,
855                                sizeof(identity->hashPubKey.bits),
856                                ctx,
857                                sizeof(ctx), NULL);
858 }
859
860 /**
861  * Derive an IV from pong packet information
862  */
863 static void
864 derive_pong_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
865     const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
866     uint32_t challenge, const struct GNUNET_PeerIdentity *identity)
867 {
868   static const char ctx[] = "pong initialization vector";
869
870   GNUNET_CRYPTO_aes_derive_iv (iv,
871                                skey,
872                                &seed,
873                                sizeof(seed),
874                                &identity->hashPubKey.bits,
875                                sizeof(identity->hashPubKey.bits),
876                                &challenge,
877                                sizeof(challenge),
878                                ctx,
879                                sizeof(ctx), NULL);
880 }
881
882
883 /**
884  * At what time should the connection to the given neighbour
885  * time out (given no further activity?)
886  *
887  * @param n neighbour in question
888  * @return absolute timeout
889  */
890 static struct GNUNET_TIME_Absolute 
891 get_neighbour_timeout (struct Neighbour *n)
892 {
893   return GNUNET_TIME_absolute_add (n->last_activity,
894                                    GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
895 }
896
897
898 /**
899  * Helper function for update_preference_sum.
900  */
901 static int
902 update_preference (void *cls,
903                    const GNUNET_HashCode *key,
904                    void *value)
905 {
906   unsigned long long *ps = cls;
907   struct Neighbour *n = value;
908
909   n->current_preference /= 2;
910   *ps += n->current_preference;
911   return GNUNET_OK;
912 }    
913
914
915 /**
916  * A preference value for a neighbour was update.  Update
917  * the preference sum accordingly.
918  *
919  * @param inc how much was a preference value increased?
920  */
921 static void
922 update_preference_sum (unsigned long long inc)
923 {
924   unsigned long long os;
925
926   os = preference_sum;
927   preference_sum += inc;
928   if (preference_sum >= os)
929     return; /* done! */
930   /* overflow! compensate by cutting all values in half! */
931   preference_sum = 0;
932   GNUNET_CONTAINER_multihashmap_iterate (neighbours,
933                                          &update_preference,
934                                          &preference_sum);
935   GNUNET_STATISTICS_set (stats, gettext_noop ("# total peer preference"), preference_sum, GNUNET_NO);
936 }
937
938
939 /**
940  * Find the entry for the given neighbour.
941  *
942  * @param peer identity of the neighbour
943  * @return NULL if we are not connected, otherwise the
944  *         neighbour's entry.
945  */
946 static struct Neighbour *
947 find_neighbour (const struct GNUNET_PeerIdentity *peer)
948 {
949   return GNUNET_CONTAINER_multihashmap_get (neighbours, &peer->hashPubKey);
950 }
951
952
953 /**
954  * Send a message to one of our clients.
955  *
956  * @param client target for the message
957  * @param msg message to transmit
958  * @param can_drop could this message be dropped if the
959  *        client's queue is getting too large?
960  */
961 static void
962 send_to_client (struct Client *client,
963                 const struct GNUNET_MessageHeader *msg, 
964                 int can_drop)
965 {
966 #if DEBUG_CORE_CLIENT
967   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
968               "Preparing to send %u bytes of message of type %u to client.\n",
969               (unsigned int) ntohs (msg->size),
970               (unsigned int) ntohs (msg->type));
971 #endif  
972   GNUNET_SERVER_notification_context_unicast (notifier,
973                                               client->client_handle,
974                                               msg,
975                                               can_drop);
976 }
977
978
979 /**
980  * Send a message to all of our current clients that have
981  * the right options set.
982  * 
983  * @param msg message to multicast
984  * @param can_drop can this message be discarded if the queue is too long
985  * @param options mask to use 
986  */
987 static void
988 send_to_all_clients (const struct GNUNET_MessageHeader *msg, 
989                      int can_drop,
990                      int options)
991 {
992   struct Client *c;
993
994   c = clients;
995   while (c != NULL)
996     {
997       if (0 != (c->options & options))
998         {
999 #if DEBUG_CORE_CLIENT
1000           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1001                       "Sending message of type %u to client.\n",
1002                       (unsigned int) ntohs (msg->type));
1003 #endif
1004           send_to_client (c, msg, can_drop);
1005         }
1006       c = c->next;
1007     }
1008 }
1009
1010
1011 /**
1012  * Function called by transport telling us that a peer
1013  * changed status.
1014  *
1015  * @param n the peer that changed status
1016  */
1017 static void
1018 handle_peer_status_change (struct Neighbour *n)
1019 {
1020   struct PeerStatusNotifyMessage *psnm;
1021   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1022   struct GNUNET_TRANSPORT_ATS_Information *ats;
1023   size_t size;
1024
1025   if ( (! n->is_connected) ||
1026        (n->status != PEER_STATE_KEY_CONFIRMED) )
1027     return;
1028 #if DEBUG_CORE
1029   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1030               "Peer `%4s' changed status\n",
1031               GNUNET_i2s (&n->peer));
1032 #endif
1033   size = sizeof (struct PeerStatusNotifyMessage) +
1034     n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1035   if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1036     {
1037       GNUNET_break (0);
1038       /* recovery strategy: throw away performance data */
1039       GNUNET_array_grow (n->ats,
1040                          n->ats_count,
1041                          0);
1042       size = sizeof (struct PeerStatusNotifyMessage) +
1043         n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1044     }
1045   psnm = (struct PeerStatusNotifyMessage*) buf;
1046   psnm->header.size = htons (size);
1047   psnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_STATUS_CHANGE);
1048   psnm->timeout = GNUNET_TIME_absolute_hton (get_neighbour_timeout (n));
1049   psnm->bandwidth_in = n->bw_in;
1050   psnm->bandwidth_out = n->bw_out;
1051   psnm->peer = n->peer;
1052   psnm->ats_count = htonl (n->ats_count);
1053   ats = &psnm->ats;
1054   memcpy (ats,
1055           n->ats,
1056           n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
1057   ats[n->ats_count].type = htonl (0);
1058   ats[n->ats_count].value = htonl (0);
1059   send_to_all_clients (&psnm->header, 
1060                        GNUNET_YES, 
1061                        GNUNET_CORE_OPTION_SEND_STATUS_CHANGE);
1062   GNUNET_STATISTICS_update (stats, 
1063                             gettext_noop ("# peer status changes"), 
1064                             1, 
1065                             GNUNET_NO);
1066 }
1067
1068
1069 /**
1070  * Go over our message queue and if it is not too long, go
1071  * over the pending requests from clients for this
1072  * neighbour and send some clients a 'READY' notification.
1073  *
1074  * @param n which peer to process
1075  */
1076 static void
1077 schedule_peer_messages (struct Neighbour *n)
1078 {
1079   struct SendMessageReady smr;
1080   struct ClientActiveRequest *car;
1081   struct ClientActiveRequest *pos;
1082   struct Client *c;
1083   struct MessageEntry *mqe;
1084   unsigned int queue_size;
1085   
1086   /* check if neighbour queue is empty enough! */
1087   if (n != &self)
1088     {
1089       queue_size = 0;
1090       mqe = n->messages;
1091       while (mqe != NULL) 
1092         {
1093           queue_size++;
1094           mqe = mqe->next;
1095         }
1096       if (queue_size >= MAX_PEER_QUEUE_SIZE)
1097         {
1098 #if DEBUG_CORE_CLIENT
1099           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1100                       "Not considering client transmission requests: queue full\n");
1101 #endif
1102           return; /* queue still full */
1103         }
1104       /* find highest priority request */
1105       pos = n->active_client_request_head;
1106       car = NULL;
1107       while (pos != NULL)
1108         {
1109           if ( (car == NULL) ||
1110                (pos->priority > car->priority) )
1111             car = pos;
1112           pos = pos->next;
1113         }
1114     }
1115   else
1116     {
1117       car = n->active_client_request_head;
1118     }
1119   if (car == NULL)
1120     return; /* no pending requests */
1121 #if DEBUG_CORE_CLIENT
1122   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1123               "Permitting client transmission request to `%s'\n",
1124               GNUNET_i2s (&n->peer));
1125 #endif
1126   c = car->client;
1127   GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1128                                n->active_client_request_tail,
1129                                car);
1130   GNUNET_assert (GNUNET_YES ==
1131                  GNUNET_CONTAINER_multihashmap_remove (c->requests,
1132                                                        &n->peer.hashPubKey,
1133                                                        car));  
1134   smr.header.size = htons (sizeof (struct SendMessageReady));
1135   smr.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND_READY);
1136   smr.size = htons (car->msize);
1137   smr.smr_id = car->smr_id;
1138   smr.peer = n->peer;
1139   send_to_client (c, &smr.header, GNUNET_NO);
1140   GNUNET_free (car);
1141 }
1142
1143
1144 /**
1145  * Handle CORE_SEND_REQUEST message.
1146  */
1147 static void
1148 handle_client_send_request (void *cls,
1149                             struct GNUNET_SERVER_Client *client,
1150                             const struct GNUNET_MessageHeader *message)
1151 {
1152   const struct SendMessageRequest *req;
1153   struct Neighbour *n;
1154   struct Client *c;
1155   struct ClientActiveRequest *car;
1156
1157   req = (const struct SendMessageRequest*) message;
1158   if (0 == memcmp (&req->peer,
1159                    &my_identity,
1160                    sizeof (struct GNUNET_PeerIdentity)))
1161     n = &self;
1162   else
1163     n = find_neighbour (&req->peer);
1164   if ( (n == NULL) ||
1165        (GNUNET_YES != n->is_connected) ||
1166        (n->status != PEER_STATE_KEY_CONFIRMED) )
1167     { 
1168       /* neighbour must have disconnected since request was issued,
1169          ignore (client will realize it once it processes the 
1170          disconnect notification) */
1171 #if DEBUG_CORE_CLIENT
1172   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1173               "Dropped client request for transmission (am disconnected)\n");
1174 #endif
1175       GNUNET_STATISTICS_update (stats, 
1176                                 gettext_noop ("# send requests dropped (disconnected)"), 
1177                                 1, 
1178                                 GNUNET_NO);
1179       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1180       return;
1181     }
1182   c = clients;
1183   while ( (c != NULL) &&
1184           (c->client_handle != client) )
1185     c = c->next;
1186   if (c == NULL)
1187     {
1188       /* client did not send INIT first! */
1189       GNUNET_break (0);
1190       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1191       return;
1192     }
1193   if (c->requests == NULL)
1194     c->requests = GNUNET_CONTAINER_multihashmap_create (16);
1195 #if DEBUG_CORE_CLIENT
1196   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1197               "Received client transmission request. queueing\n");
1198 #endif
1199   car = GNUNET_CONTAINER_multihashmap_get (c->requests,
1200                                            &req->peer.hashPubKey);
1201   if (car == NULL)
1202     {
1203       /* create new entry */
1204       car = GNUNET_malloc (sizeof (struct ClientActiveRequest));
1205       GNUNET_assert (GNUNET_OK ==
1206                      GNUNET_CONTAINER_multihashmap_put (c->requests,
1207                                                         &req->peer.hashPubKey,
1208                                                         car,
1209                                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1210       GNUNET_CONTAINER_DLL_insert (n->active_client_request_head,
1211                                    n->active_client_request_tail,
1212                                    car);
1213       car->client = c;
1214     }
1215   car->deadline = GNUNET_TIME_absolute_ntoh (req->deadline);
1216   car->priority = ntohl (req->priority);
1217   car->queue_size = ntohl (req->queue_size);
1218   car->msize = ntohs (req->size);
1219   car->smr_id = req->smr_id;
1220   schedule_peer_messages (n);
1221   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1222 }
1223
1224
1225 /**
1226  * Notify client about an existing connection to one of our neighbours.
1227  */
1228 static int
1229 notify_client_about_neighbour (void *cls,
1230                                const GNUNET_HashCode *key,
1231                                void *value)
1232 {
1233   struct Client *c = cls;
1234   struct Neighbour *n = value;
1235   size_t size;
1236   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1237   struct GNUNET_TRANSPORT_ATS_Information *ats;
1238   struct ConnectNotifyMessage *cnm;
1239
1240   size = sizeof (struct ConnectNotifyMessage) +
1241     (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1242   if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1243     {
1244       GNUNET_break (0);
1245       /* recovery strategy: throw away performance data */
1246       GNUNET_array_grow (n->ats,
1247                          n->ats_count,
1248                          0);
1249       size = sizeof (struct ConnectNotifyMessage) +
1250         (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1251     }
1252   cnm = (struct ConnectNotifyMessage*) buf;       
1253   cnm->header.size = htons (size);
1254   cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1255   cnm->ats_count = htonl (n->ats_count);
1256   ats = &cnm->ats;
1257   memcpy (ats,
1258           n->ats,
1259           sizeof (struct GNUNET_TRANSPORT_ATS_Information) * n->ats_count);
1260   ats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
1261   ats[n->ats_count].value = htonl (0);
1262   if (n->status == PEER_STATE_KEY_CONFIRMED)
1263     {
1264 #if DEBUG_CORE_CLIENT
1265       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1266                   "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
1267 #endif
1268       cnm->peer = n->peer;
1269       send_to_client (c, &cnm->header, GNUNET_NO);
1270     }
1271   return GNUNET_OK;
1272 }
1273
1274
1275
1276 /**
1277  * Handle CORE_INIT request.
1278  */
1279 static void
1280 handle_client_init (void *cls,
1281                     struct GNUNET_SERVER_Client *client,
1282                     const struct GNUNET_MessageHeader *message)
1283 {
1284   const struct InitMessage *im;
1285   struct InitReplyMessage irm;
1286   struct Client *c;
1287   uint16_t msize;
1288   const uint16_t *types;
1289   uint16_t *wtypes;
1290   unsigned int i;
1291
1292 #if DEBUG_CORE_CLIENT
1293   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1294               "Client connecting to core service with `%s' message\n",
1295               "INIT");
1296 #endif
1297   /* check that we don't have an entry already */
1298   c = clients;
1299   while (c != NULL)
1300     {
1301       if (client == c->client_handle)
1302         {
1303           GNUNET_break (0);
1304           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1305           return;
1306         }
1307       c = c->next;
1308     }
1309   msize = ntohs (message->size);
1310   if (msize < sizeof (struct InitMessage))
1311     {
1312       GNUNET_break (0);
1313       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1314       return;
1315     }
1316   GNUNET_SERVER_notification_context_add (notifier, client);
1317   im = (const struct InitMessage *) message;
1318   types = (const uint16_t *) &im[1];
1319   msize -= sizeof (struct InitMessage);
1320   c = GNUNET_malloc (sizeof (struct Client) + msize);
1321   c->client_handle = client;
1322   c->next = clients;
1323   clients = c;
1324   c->tcnt = msize / sizeof (uint16_t);
1325   c->types = (const uint16_t *) &c[1];
1326   wtypes = (uint16_t *) &c[1];
1327   for (i=0;i<c->tcnt;i++)
1328     wtypes[i] = ntohs (types[i]);
1329   c->options = ntohl (im->options);
1330 #if DEBUG_CORE_CLIENT
1331   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1332               "Client %p is interested in %u message types\n",
1333               c,
1334               (unsigned int) c->tcnt);
1335 #endif
1336   /* send init reply message */
1337   irm.header.size = htons (sizeof (struct InitReplyMessage));
1338   irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
1339   irm.reserved = htonl (0);
1340   memcpy (&irm.publicKey,
1341           &my_public_key,
1342           sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1343 #if DEBUG_CORE_CLIENT
1344   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1345               "Sending `%s' message to client.\n", "INIT_REPLY");
1346 #endif
1347   send_to_client (c, &irm.header, GNUNET_NO);
1348   if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
1349     {
1350       /* notify new client about existing neighbours */
1351       GNUNET_CONTAINER_multihashmap_iterate (neighbours,
1352                                              &notify_client_about_neighbour,
1353                                              c);
1354     }
1355   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1356 }
1357
1358
1359 /**
1360  * Free client request records.
1361  *
1362  * @param cls NULL
1363  * @param key identity of peer for which this is an active request
1364  * @param value the 'struct ClientActiveRequest' to free
1365  * @return GNUNET_YES (continue iteration)
1366  */
1367 static int
1368 destroy_active_client_request (void *cls,
1369                                const GNUNET_HashCode *key,
1370                                void *value)
1371 {
1372   struct ClientActiveRequest *car = value;
1373   struct Neighbour *n;
1374   struct GNUNET_PeerIdentity peer;
1375
1376   peer.hashPubKey = *key;
1377   n = find_neighbour (&peer);
1378   GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1379                                n->active_client_request_tail,
1380                                car);
1381   GNUNET_free (car);
1382   return GNUNET_YES;
1383 }
1384
1385
1386 /**
1387  * A client disconnected, clean up.
1388  *
1389  * @param cls closure
1390  * @param client identification of the client
1391  */
1392 static void
1393 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1394 {
1395   struct Client *pos;
1396   struct Client *prev;
1397
1398   if (client == NULL)
1399     return;
1400 #if DEBUG_CORE_CLIENT
1401   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1402               "Client %p has disconnected from core service.\n",
1403               client);
1404 #endif
1405   prev = NULL;
1406   pos = clients;
1407   while (pos != NULL)
1408     {
1409       if (client == pos->client_handle)
1410         break;
1411       prev = pos;
1412       pos = pos->next;
1413     }
1414   if (pos == NULL)
1415     {
1416       /* client never sent INIT */
1417       return;
1418     }
1419   if (prev == NULL)
1420     clients = pos->next;
1421   else
1422     prev->next = pos->next;
1423   if (pos->requests != NULL)
1424     {
1425       GNUNET_CONTAINER_multihashmap_iterate (pos->requests,
1426                                              &destroy_active_client_request,
1427                                              NULL);
1428       GNUNET_CONTAINER_multihashmap_destroy (pos->requests);
1429     }
1430   GNUNET_free (pos);
1431 }
1432
1433
1434 /**
1435  * Helper function for handle_client_iterate_peers.
1436  *
1437  * @param cls the 'struct GNUNET_SERVER_TransmitContext' to queue replies
1438  * @param key identity of the connected peer
1439  * @param value the 'struct Neighbour' for the peer
1440  * @return GNUNET_OK (continue to iterate)
1441  */
1442 static int
1443 queue_connect_message (void *cls,
1444                        const GNUNET_HashCode *key,
1445                        void *value)
1446 {
1447   struct GNUNET_SERVER_TransmitContext *tc = cls;
1448   struct Neighbour *n = value;
1449   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1450   struct GNUNET_TRANSPORT_ATS_Information *ats;
1451   size_t size;
1452   struct ConnectNotifyMessage *cnm;
1453
1454   cnm = (struct ConnectNotifyMessage*) buf;
1455   if (n->status != PEER_STATE_KEY_CONFIRMED)
1456     return GNUNET_OK;
1457   size = sizeof (struct ConnectNotifyMessage) +
1458     (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1459   if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1460     {
1461       GNUNET_break (0);
1462       /* recovery strategy: throw away performance data */
1463       GNUNET_array_grow (n->ats,
1464                          n->ats_count,
1465                          0);
1466       size = sizeof (struct PeerStatusNotifyMessage) +
1467         n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1468     }
1469   cnm = (struct ConnectNotifyMessage*) buf;
1470   cnm->header.size = htons (size);
1471   cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1472   cnm->ats_count = htonl (n->ats_count);
1473   ats = &cnm->ats;
1474   memcpy (ats,
1475           n->ats,
1476           n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
1477   ats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
1478   ats[n->ats_count].value = htonl (0);    
1479 #if DEBUG_CORE_CLIENT
1480   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1481               "Sending `%s' message to client.\n",
1482               "NOTIFY_CONNECT");
1483 #endif
1484   cnm->peer = n->peer;
1485   GNUNET_SERVER_transmit_context_append_message (tc, 
1486                                                  &cnm->header);
1487   return GNUNET_OK;
1488 }
1489
1490
1491 /**
1492  * Handle CORE_ITERATE_PEERS request.
1493  *
1494  * @param cls unused
1495  * @param client client sending the iteration request
1496  * @param message iteration request message
1497  */
1498 static void
1499 handle_client_iterate_peers (void *cls,
1500                              struct GNUNET_SERVER_Client *client,
1501                              const struct GNUNET_MessageHeader *message)
1502
1503 {
1504   struct GNUNET_MessageHeader done_msg;
1505   struct GNUNET_SERVER_TransmitContext *tc;
1506   int msize;
1507   /* notify new client about existing neighbours */
1508
1509   msize = ntohs(message->size);
1510   tc = GNUNET_SERVER_transmit_context_create (client);
1511   if (msize == sizeof(struct GNUNET_MessageHeader))
1512     GNUNET_CONTAINER_multihashmap_iterate (neighbours, &queue_connect_message, tc);
1513   else
1514     GNUNET_break(0);
1515
1516   done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
1517   done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
1518   GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
1519   GNUNET_SERVER_transmit_context_run (tc,
1520                                       GNUNET_TIME_UNIT_FOREVER_REL);
1521 }
1522
1523 /**
1524  * Handle CORE_ITERATE_PEERS request.  Notify client about existing neighbours.
1525  *
1526  * @param cls unused
1527  * @param client client sending the iteration request
1528  * @param message iteration request message
1529  */
1530 static void
1531 handle_client_have_peer (void *cls,
1532                              struct GNUNET_SERVER_Client *client,
1533                              const struct GNUNET_MessageHeader *message)
1534
1535 {
1536   struct GNUNET_MessageHeader done_msg;
1537   struct GNUNET_SERVER_TransmitContext *tc;
1538   struct GNUNET_PeerIdentity *peer;
1539
1540   tc = GNUNET_SERVER_transmit_context_create (client);
1541   peer = (struct GNUNET_PeerIdentity *) &message[1];
1542   GNUNET_CONTAINER_multihashmap_get_multiple(neighbours,
1543                                              &peer->hashPubKey, 
1544                                              &queue_connect_message, 
1545                                              tc);
1546   done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
1547   done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
1548   GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
1549   GNUNET_SERVER_transmit_context_run (tc,
1550                                       GNUNET_TIME_UNIT_FOREVER_REL);
1551 }
1552
1553
1554 /**
1555  * Handle REQUEST_INFO request.
1556  *
1557  * @param cls unused
1558  * @param client client sending the request
1559  * @param message iteration request message
1560  */
1561 static void
1562 handle_client_request_info (void *cls,
1563                             struct GNUNET_SERVER_Client *client,
1564                             const struct GNUNET_MessageHeader *message)
1565 {
1566   const struct RequestInfoMessage *rcm;
1567   struct Client *pos;
1568   struct Neighbour *n;
1569   struct ConfigurationInfoMessage cim;
1570   int32_t want_reserv;
1571   int32_t got_reserv;
1572   unsigned long long old_preference;
1573
1574 #if DEBUG_CORE_CLIENT
1575   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1576               "Core service receives `%s' request.\n", "REQUEST_INFO");
1577 #endif
1578   pos = clients;
1579   while (pos != NULL)
1580     {
1581       if (client == pos->client_handle)
1582         break;
1583       pos = pos->next;
1584     }
1585   if (pos == NULL)
1586     {
1587       GNUNET_break (0);
1588       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1589       return;
1590     }
1591
1592   rcm = (const struct RequestInfoMessage *) message;
1593   n = find_neighbour (&rcm->peer);
1594   memset (&cim, 0, sizeof (cim));
1595   if (n != NULL) 
1596     {
1597       want_reserv = ntohl (rcm->reserve_inbound);
1598       if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1599         {
1600           n->bw_out_internal_limit = rcm->limit_outbound;
1601           if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1602                                                                n->bw_out_external_limit).value__)
1603             {
1604               n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1605                                                       n->bw_out_external_limit);
1606               GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1607                                                      n->bw_out);
1608               GNUNET_TRANSPORT_set_quota (transport,
1609                                           &n->peer,
1610                                           n->bw_in,
1611                                           n->bw_out,
1612                                           GNUNET_TIME_UNIT_FOREVER_REL,
1613                                           NULL, NULL); 
1614               handle_peer_status_change (n);
1615             }
1616         }
1617       if (want_reserv < 0)
1618         {
1619           got_reserv = want_reserv;
1620         }
1621       else if (want_reserv > 0)
1622         {
1623           if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1624                                                   want_reserv).rel_value == 0)
1625             got_reserv = want_reserv;
1626           else
1627             got_reserv = 0; /* all or nothing */
1628         }
1629       else
1630         got_reserv = 0;
1631       GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1632                                         got_reserv);
1633       old_preference = n->current_preference;
1634       n->current_preference += GNUNET_ntohll(rcm->preference_change);
1635       if (old_preference > n->current_preference) 
1636         {
1637           /* overflow; cap at maximum value */
1638           n->current_preference = ULLONG_MAX;
1639         }
1640       update_preference_sum (n->current_preference - old_preference);
1641 #if DEBUG_CORE_QUOTA
1642       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1643                   "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1644                   (int) want_reserv,
1645                   GNUNET_i2s (&rcm->peer),
1646                   (int) got_reserv);
1647 #endif
1648       cim.reserved_amount = htonl (got_reserv);
1649       cim.rim_id = rcm->rim_id;
1650       cim.bw_out = n->bw_out;
1651       cim.preference = n->current_preference;
1652     }
1653   cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1654   cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1655   cim.peer = rcm->peer;
1656 #if DEBUG_CORE_CLIENT
1657   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1658               "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1659 #endif
1660   send_to_client (pos, &cim.header, GNUNET_NO);
1661   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1662 }
1663
1664
1665 /**
1666  * Free the given entry for the neighbour (it has
1667  * already been removed from the list at this point).
1668  *
1669  * @param n neighbour to free
1670  */
1671 static void
1672 free_neighbour (struct Neighbour *n)
1673 {
1674   struct MessageEntry *m;
1675   struct ClientActiveRequest *car;
1676
1677 #if DEBUG_CORE
1678   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1679               "Destroying neighbour entry for peer `%4s'\n",
1680               GNUNET_i2s (&n->peer));
1681 #endif
1682   if (n->pitr != NULL)
1683     {
1684       GNUNET_PEERINFO_iterate_cancel (n->pitr);
1685       n->pitr = NULL;
1686     }
1687   if (n->skm != NULL)
1688     {
1689       GNUNET_free (n->skm);
1690       n->skm = NULL;
1691     }
1692   while (NULL != (m = n->messages))
1693     {
1694       n->messages = m->next;
1695       GNUNET_free (m);
1696     }
1697   while (NULL != (m = n->encrypted_head))
1698     {
1699       GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1700                                    n->encrypted_tail,
1701                                    m);
1702       GNUNET_free (m);
1703     }
1704   while (NULL != (car = n->active_client_request_head))
1705     {
1706       GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1707                                    n->active_client_request_tail,
1708                                    car);
1709       GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
1710                                             &n->peer.hashPubKey,
1711                                             car);
1712       GNUNET_free (car);
1713     }
1714   if (NULL != n->th)
1715     {
1716       GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1717       n->th = NULL;
1718     }
1719   if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1720     GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
1721   if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1722     GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
1723   if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1724     GNUNET_SCHEDULER_cancel (n->quota_update_task);
1725   if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1726     GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1727   if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)    
1728       GNUNET_SCHEDULER_cancel (n->keep_alive_task);
1729   if (n->status == PEER_STATE_KEY_CONFIRMED)
1730     GNUNET_STATISTICS_update (stats, 
1731                               gettext_noop ("# established sessions"), 
1732                               -1, 
1733                               GNUNET_NO);
1734   GNUNET_array_grow (n->ats, n->ats_count, 0);
1735   GNUNET_free_non_null (n->public_key);
1736   GNUNET_free_non_null (n->pending_ping);
1737   GNUNET_free_non_null (n->pending_pong);
1738   GNUNET_free (n);
1739 }
1740
1741
1742 /**
1743  * Check if we have encrypted messages for the specified neighbour
1744  * pending, and if so, check with the transport about sending them
1745  * out.
1746  *
1747  * @param n neighbour to check.
1748  */
1749 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1750
1751
1752 /**
1753  * Encrypt size bytes from in and write the result to out.  Use the
1754  * key for outbound traffic of the given neighbour.
1755  *
1756  * @param n neighbour we are sending to
1757  * @param iv initialization vector to use
1758  * @param in ciphertext
1759  * @param out plaintext
1760  * @param size size of in/out
1761  * @return GNUNET_OK on success
1762  */
1763 static int
1764 do_encrypt (struct Neighbour *n,
1765             const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1766             const void *in, void *out, size_t size)
1767 {
1768   if (size != (uint16_t) size)
1769     {
1770       GNUNET_break (0);
1771       return GNUNET_NO;
1772     }
1773   GNUNET_assert (size ==
1774                  GNUNET_CRYPTO_aes_encrypt (in,
1775                                             (uint16_t) size,
1776                                             &n->encrypt_key,
1777                                             iv, out));
1778   GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1779 #if DEBUG_CORE
1780   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1781               "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
1782               (unsigned int) size,
1783               GNUNET_i2s (&n->peer),
1784               (unsigned int) n->encrypt_key.crc32,
1785               GNUNET_CRYPTO_crc32_n (iv, sizeof(iv)));
1786 #endif
1787   return GNUNET_OK;
1788 }
1789
1790
1791 /**
1792  * Consider freeing the given neighbour since we may not need
1793  * to keep it around anymore.
1794  *
1795  * @param n neighbour to consider discarding
1796  */
1797 static void
1798 consider_free_neighbour (struct Neighbour *n);
1799
1800
1801 /**
1802  * Task triggered when a neighbour entry is about to time out 
1803  * (and we should prevent this by sending a PING).
1804  *
1805  * @param cls the 'struct Neighbour'
1806  * @param tc scheduler context (not used)
1807  */
1808 static void
1809 send_keep_alive (void *cls,
1810                  const struct GNUNET_SCHEDULER_TaskContext *tc)
1811 {
1812   struct Neighbour *n = cls;
1813   struct GNUNET_TIME_Relative retry;
1814   struct GNUNET_TIME_Relative left;
1815   struct MessageEntry *me;
1816   struct PingMessage pp;
1817   struct PingMessage *pm;
1818   struct GNUNET_CRYPTO_AesInitializationVector iv;
1819
1820   n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1821   /* send PING */
1822   me = GNUNET_malloc (sizeof (struct MessageEntry) +
1823                       sizeof (struct PingMessage));
1824   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1825   me->priority = PING_PRIORITY;
1826   me->size = sizeof (struct PingMessage);
1827   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1828                                      n->encrypted_tail,
1829                                      n->encrypted_tail,
1830                                      me);
1831   pm = (struct PingMessage *) &me[1];
1832   pm->header.size = htons (sizeof (struct PingMessage));
1833   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1834   pm->iv_seed = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1835       UINT32_MAX);
1836   derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
1837   pp.challenge = n->ping_challenge;
1838   pp.target = n->peer;
1839 #if DEBUG_HANDSHAKE
1840   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1841               "Encrypting `%s' message with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
1842               "PING", 
1843               (unsigned int) n->ping_challenge,
1844               GNUNET_i2s (&n->peer),
1845               (unsigned int) n->encrypt_key.crc32,
1846               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
1847               pm->iv_seed);
1848 #endif
1849   do_encrypt (n,
1850               &iv,
1851               &pp.target,
1852               &pm->target,
1853               sizeof (struct PingMessage) -
1854               ((void *) &pm->target - (void *) pm));
1855   process_encrypted_neighbour_queue (n);
1856   /* reschedule PING job */
1857   left = GNUNET_TIME_absolute_get_remaining (get_neighbour_timeout (n));
1858   retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1859                                     MIN_PING_FREQUENCY);
1860   n->keep_alive_task 
1861     = GNUNET_SCHEDULER_add_delayed (retry,
1862                                     &send_keep_alive,
1863                                     n);
1864
1865 }
1866
1867
1868 /**
1869  * Task triggered when a neighbour entry might have gotten stale.
1870  *
1871  * @param cls the 'struct Neighbour'
1872  * @param tc scheduler context (not used)
1873  */
1874 static void
1875 consider_free_task (void *cls,
1876                     const struct GNUNET_SCHEDULER_TaskContext *tc)
1877 {
1878   struct Neighbour *n = cls;
1879
1880   n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1881   consider_free_neighbour (n);
1882 }
1883
1884
1885 /**
1886  * Consider freeing the given neighbour since we may not need
1887  * to keep it around anymore.
1888  *
1889  * @param n neighbour to consider discarding
1890  */
1891 static void
1892 consider_free_neighbour (struct Neighbour *n)
1893
1894   struct GNUNET_TIME_Relative left;
1895
1896   if ( (n->th != NULL) ||
1897        (n->pitr != NULL) ||
1898        (GNUNET_YES == n->is_connected) )
1899     return; /* no chance */
1900     
1901   left = GNUNET_TIME_absolute_get_remaining (get_neighbour_timeout (n));
1902   if (left.rel_value > 0)
1903     {
1904       if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1905         GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1906       n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (left,
1907                                                          &consider_free_task,
1908                                                          n);
1909       return;
1910     }
1911   /* actually free the neighbour... */
1912   GNUNET_assert (GNUNET_OK ==
1913                  GNUNET_CONTAINER_multihashmap_remove (neighbours,
1914                                                        &n->peer.hashPubKey,
1915                                                        n));
1916   GNUNET_STATISTICS_set (stats,
1917                          gettext_noop ("# neighbour entries allocated"), 
1918                          GNUNET_CONTAINER_multihashmap_size (neighbours),
1919                          GNUNET_NO);
1920   free_neighbour (n);
1921 }
1922
1923
1924 /**
1925  * Function called when the transport service is ready to
1926  * receive an encrypted message for the respective peer
1927  *
1928  * @param cls neighbour to use message from
1929  * @param size number of bytes we can transmit
1930  * @param buf where to copy the message
1931  * @return number of bytes transmitted
1932  */
1933 static size_t
1934 notify_encrypted_transmit_ready (void *cls, 
1935                                  size_t size, 
1936                                  void *buf)
1937 {
1938   struct Neighbour *n = cls;
1939   struct MessageEntry *m;
1940   size_t ret;
1941   char *cbuf;
1942
1943   n->th = NULL;
1944   m = n->encrypted_head;
1945   if (m == NULL)
1946     {
1947 #if DEBUG_CORE
1948       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1949                   "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1950                   GNUNET_i2s (&n->peer));
1951 #endif
1952       return 0;
1953     }
1954   GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1955                                n->encrypted_tail,
1956                                m);
1957   ret = 0;
1958   cbuf = buf;
1959   if (buf != NULL)
1960     {
1961       GNUNET_assert (size >= m->size);
1962       memcpy (cbuf, &m[1], m->size);
1963       ret = m->size;
1964       GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1965                                         m->size);
1966 #if DEBUG_CORE
1967       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1968                   "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1969                   (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1970                   (unsigned int) ret, 
1971                   GNUNET_i2s (&n->peer));
1972 #endif
1973       process_encrypted_neighbour_queue (n);
1974     }
1975   else
1976     {
1977 #if DEBUG_CORE
1978       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1979                   "Transmission of message of type %u and size %u failed\n",
1980                   (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1981                   (unsigned int) m->size);
1982 #endif
1983     }
1984   GNUNET_free (m);
1985   consider_free_neighbour (n);
1986   GNUNET_STATISTICS_update (stats, 
1987                             gettext_noop ("# encrypted bytes given to transport"), 
1988                             ret, 
1989                             GNUNET_NO);
1990   return ret;
1991 }
1992
1993
1994 /**
1995  * Check if we have plaintext messages for the specified neighbour
1996  * pending, and if so, consider batching and encrypting them (and
1997  * then trigger processing of the encrypted queue if needed).
1998  *
1999  * @param n neighbour to check.
2000  */
2001 static void process_plaintext_neighbour_queue (struct Neighbour *n);
2002
2003
2004 /**
2005  * Check if we have encrypted messages for the specified neighbour
2006  * pending, and if so, check with the transport about sending them
2007  * out.
2008  *
2009  * @param n neighbour to check.
2010  */
2011 static void
2012 process_encrypted_neighbour_queue (struct Neighbour *n)
2013 {
2014   struct MessageEntry *m;
2015  
2016   if (n->th != NULL)
2017     return;  /* request already pending */
2018   m = n->encrypted_head;
2019   if (m == NULL)
2020     {
2021       /* encrypted queue empty, try plaintext instead */
2022       process_plaintext_neighbour_queue (n);
2023       return;
2024     }
2025 #if DEBUG_CORE
2026   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2027               "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
2028               (unsigned int) m->size,
2029               GNUNET_i2s (&n->peer),
2030               (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).rel_value);
2031 #endif
2032   n->th =
2033     GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
2034                                             m->size,
2035                                             m->priority,
2036                                             GNUNET_TIME_absolute_get_remaining
2037                                             (m->deadline),
2038                                             &notify_encrypted_transmit_ready,
2039                                             n);
2040   if (n->th == NULL)
2041     {
2042       /* message request too large or duplicate request */
2043       GNUNET_break (0);
2044       /* discard encrypted message */
2045       GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2046                                    n->encrypted_tail,
2047                                    m);
2048       GNUNET_free (m);
2049       process_encrypted_neighbour_queue (n);
2050     }
2051 }
2052
2053
2054 /**
2055  * Decrypt size bytes from in and write the result to out.  Use the
2056  * key for inbound traffic of the given neighbour.  This function does
2057  * NOT do any integrity-checks on the result.
2058  *
2059  * @param n neighbour we are receiving from
2060  * @param iv initialization vector to use
2061  * @param in ciphertext
2062  * @param out plaintext
2063  * @param size size of in/out
2064  * @return GNUNET_OK on success
2065  */
2066 static int
2067 do_decrypt (struct Neighbour *n,
2068             const struct GNUNET_CRYPTO_AesInitializationVector * iv,
2069             const void *in, void *out, size_t size)
2070 {
2071   if (size != (uint16_t) size)
2072     {
2073       GNUNET_break (0);
2074       return GNUNET_NO;
2075     }
2076   if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2077       (n->status != PEER_STATE_KEY_CONFIRMED))
2078     {
2079       GNUNET_break_op (0);
2080       return GNUNET_SYSERR;
2081     }
2082   if (size !=
2083       GNUNET_CRYPTO_aes_decrypt (in,
2084                                  (uint16_t) size,
2085                                  &n->decrypt_key,
2086                                  iv,
2087                                  out))
2088     {
2089       GNUNET_break (0);
2090       return GNUNET_SYSERR;
2091     }
2092   GNUNET_STATISTICS_update (stats, 
2093                             gettext_noop ("# bytes decrypted"), 
2094                             size, 
2095                             GNUNET_NO);
2096 #if DEBUG_CORE
2097   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2098               "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
2099               (unsigned int) size, 
2100               GNUNET_i2s (&n->peer),
2101               (unsigned int) n->decrypt_key.crc32,
2102               GNUNET_CRYPTO_crc32_n (iv, sizeof(*iv)));
2103 #endif
2104   return GNUNET_OK;
2105 }
2106
2107
2108 /**
2109  * Select messages for transmission.  This heuristic uses a combination
2110  * of earliest deadline first (EDF) scheduling (with bounded horizon)
2111  * and priority-based discard (in case no feasible schedule exist) and
2112  * speculative optimization (defer any kind of transmission until
2113  * we either create a batch of significant size, 25% of max, or until
2114  * we are close to a deadline).  Furthermore, when scheduling the
2115  * heuristic also packs as many messages into the batch as possible,
2116  * starting with those with the earliest deadline.  Yes, this is fun.
2117  *
2118  * @param n neighbour to select messages from
2119  * @param size number of bytes to select for transmission
2120  * @param retry_time set to the time when we should try again
2121  *        (only valid if this function returns zero)
2122  * @return number of bytes selected, or 0 if we decided to
2123  *         defer scheduling overall; in that case, retry_time is set.
2124  */
2125 static size_t
2126 select_messages (struct Neighbour *n,
2127                  size_t size, struct GNUNET_TIME_Relative *retry_time)
2128 {
2129   struct MessageEntry *pos;
2130   struct MessageEntry *min;
2131   struct MessageEntry *last;
2132   unsigned int min_prio;
2133   struct GNUNET_TIME_Absolute t;
2134   struct GNUNET_TIME_Absolute now;
2135   struct GNUNET_TIME_Relative delta;
2136   uint64_t avail;
2137   struct GNUNET_TIME_Relative slack;     /* how long could we wait before missing deadlines? */
2138   size_t off;
2139   uint64_t tsize;
2140   unsigned int queue_size;
2141   int discard_low_prio;
2142
2143   GNUNET_assert (NULL != n->messages);
2144   now = GNUNET_TIME_absolute_get ();
2145   /* last entry in linked list of messages processed */
2146   last = NULL;
2147   /* should we remove the entry with the lowest
2148      priority from consideration for scheduling at the
2149      end of the loop? */
2150   queue_size = 0;
2151   tsize = 0;
2152   pos = n->messages;
2153   while (pos != NULL)
2154     {
2155       queue_size++;
2156       tsize += pos->size;
2157       pos = pos->next;
2158     }
2159   discard_low_prio = GNUNET_YES;
2160   while (GNUNET_YES == discard_low_prio)
2161     {
2162       min = NULL;
2163       min_prio = UINT_MAX;
2164       discard_low_prio = GNUNET_NO;
2165       /* calculate number of bytes available for transmission at time "t" */
2166       avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
2167       t = now;
2168       /* how many bytes have we (hypothetically) scheduled so far */
2169       off = 0;
2170       /* maximum time we can wait before transmitting anything
2171          and still make all of our deadlines */
2172       slack = GNUNET_TIME_UNIT_FOREVER_REL;
2173       pos = n->messages;
2174       /* note that we use "*2" here because we want to look
2175          a bit further into the future; much more makes no
2176          sense since new message might be scheduled in the
2177          meantime... */
2178       while ((pos != NULL) && (off < size * 2))
2179         {         
2180           if (pos->do_transmit == GNUNET_YES)
2181             {
2182               /* already removed from consideration */
2183               pos = pos->next;
2184               continue;
2185             }
2186           if (discard_low_prio == GNUNET_NO)
2187             {
2188               delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
2189               if (delta.rel_value > 0)
2190                 {
2191                   // FIXME: HUH? Check!
2192                   t = pos->deadline;
2193                   avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
2194                                                                        delta);
2195                 }
2196               if (avail < pos->size)
2197                 {
2198                   // FIXME: HUH? Check!
2199                   discard_low_prio = GNUNET_YES;        /* we could not schedule this one! */
2200                 }
2201               else
2202                 {
2203                   avail -= pos->size;
2204                   /* update slack, considering both its absolute deadline
2205                      and relative deadlines caused by other messages
2206                      with their respective load */
2207                   slack = GNUNET_TIME_relative_min (slack,
2208                                                     GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
2209                                                                                           avail));
2210                   if (pos->deadline.abs_value <= now.abs_value) 
2211                     {
2212                       /* now or never */
2213                       slack = GNUNET_TIME_UNIT_ZERO;
2214                     }
2215                   else if (GNUNET_YES == pos->got_slack)
2216                     {
2217                       /* should be soon now! */
2218                       slack = GNUNET_TIME_relative_min (slack,
2219                                                         GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
2220                     }
2221                   else
2222                     {
2223                       slack =
2224                         GNUNET_TIME_relative_min (slack, 
2225                                                   GNUNET_TIME_absolute_get_difference (now, pos->deadline));
2226                       pos->got_slack = GNUNET_YES;
2227                       pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
2228                                                                       GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
2229                     }
2230                 }
2231             }
2232           off += pos->size;
2233           t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
2234           if (pos->priority <= min_prio)
2235             {
2236               /* update min for discard */
2237               min_prio = pos->priority;
2238               min = pos;
2239             }
2240           pos = pos->next;
2241         }
2242       if (discard_low_prio)
2243         {
2244           GNUNET_assert (min != NULL);
2245           /* remove lowest-priority entry from consideration */
2246           min->do_transmit = GNUNET_YES;        /* means: discard (for now) */
2247         }
2248       last = pos;
2249     }
2250   /* guard against sending "tiny" messages with large headers without
2251      urgent deadlines */
2252   if ( (slack.rel_value > GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value) && 
2253        (size > 4 * off) &&
2254        (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
2255     {
2256       /* less than 25% of message would be filled with deadlines still
2257          being met if we delay by one second or more; so just wait for
2258          more data; but do not wait longer than 1s (since we don't want
2259          to delay messages for a really long time either). */
2260       *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
2261       /* reset do_transmit values for next time */
2262       while (pos != last)
2263         {
2264           pos->do_transmit = GNUNET_NO;   
2265           pos = pos->next;
2266         }
2267       GNUNET_STATISTICS_update (stats, 
2268                                 gettext_noop ("# transmissions delayed due to corking"), 
2269                                 1, GNUNET_NO);
2270 #if DEBUG_CORE
2271       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2272                   "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
2273                   (unsigned long long) retry_time->rel_value,
2274                   (unsigned int) off,
2275                   (unsigned int) size);
2276 #endif
2277       return 0;
2278     }
2279   /* select marked messages (up to size) for transmission */
2280   off = 0;
2281   pos = n->messages;
2282   while (pos != last)
2283     {
2284       if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
2285         {
2286           pos->do_transmit = GNUNET_YES;        /* mark for transmission */
2287           off += pos->size;
2288           size -= pos->size;
2289 #if DEBUG_CORE
2290           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2291                       "Selecting message of size %u for transmission\n",
2292                       (unsigned int) pos->size);
2293 #endif
2294         }
2295       else
2296         {
2297 #if DEBUG_CORE
2298           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2299                       "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
2300                       (unsigned int) pos->size,
2301                       size);
2302 #endif
2303           pos->do_transmit = GNUNET_NO;   /* mark for not transmitting! */
2304         }
2305       pos = pos->next;
2306     }
2307 #if DEBUG_CORE
2308   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2309               "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
2310               (unsigned long long) off, (unsigned long long) tsize,
2311               queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
2312               GNUNET_i2s (&n->peer));
2313 #endif
2314   return off;
2315 }
2316
2317
2318 /**
2319  * Batch multiple messages into a larger buffer.
2320  *
2321  * @param n neighbour to take messages from
2322  * @param buf target buffer
2323  * @param size size of buf
2324  * @param deadline set to transmission deadline for the result
2325  * @param retry_time set to the time when we should try again
2326  *        (only valid if this function returns zero)
2327  * @param priority set to the priority of the batch
2328  * @return number of bytes written to buf (can be zero)
2329  */
2330 static size_t
2331 batch_message (struct Neighbour *n,
2332                char *buf,
2333                size_t size,
2334                struct GNUNET_TIME_Absolute *deadline,
2335                struct GNUNET_TIME_Relative *retry_time,
2336                unsigned int *priority)
2337 {
2338   char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
2339   struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
2340   struct MessageEntry *pos;
2341   struct MessageEntry *prev;
2342   struct MessageEntry *next;
2343   size_t ret;
2344   
2345   ret = 0;
2346   *priority = 0;
2347   *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2348   *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
2349   if (0 == select_messages (n, size, retry_time))
2350     {
2351 #if DEBUG_CORE
2352       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2353                   "No messages selected, will try again in %llu ms\n",
2354                   retry_time->rel_value);
2355 #endif
2356       return 0;
2357     }
2358   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
2359   ntm->ats_count = htonl (0);
2360   ntm->ats.type = htonl (0);
2361   ntm->ats.value = htonl (0);
2362   ntm->peer = n->peer;
2363   pos = n->messages;
2364   prev = NULL;
2365   while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
2366     {
2367       next = pos->next;
2368       if (GNUNET_YES == pos->do_transmit)
2369         {
2370           GNUNET_assert (pos->size <= size);
2371           /* do notifications */
2372           /* FIXME: track if we have *any* client that wants
2373              full notifications and only do this if that is
2374              actually true */
2375           if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
2376             {
2377               memcpy (&ntm[1], &pos[1], pos->size);
2378               ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) + 
2379                                         sizeof (struct GNUNET_MessageHeader));
2380               send_to_all_clients (&ntm->header,
2381                                    GNUNET_YES,
2382                                    GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
2383             }
2384           else
2385             {
2386               /* message too large for 'full' notifications, we do at
2387                  least the 'hdr' type */
2388               memcpy (&ntm[1],
2389                       &pos[1],
2390                       sizeof (struct GNUNET_MessageHeader));
2391             }
2392           ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) + 
2393                                     pos->size);
2394           send_to_all_clients (&ntm->header,
2395                                GNUNET_YES,
2396                                GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);   
2397 #if DEBUG_HANDSHAKE
2398           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2399                       "Encrypting %u bytes with message of type %u and size %u\n",
2400                       pos->size,
2401                       (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
2402                       (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
2403 #endif
2404           /* copy for encrypted transmission */
2405           memcpy (&buf[ret], &pos[1], pos->size);
2406           ret += pos->size;
2407           size -= pos->size;
2408           *priority += pos->priority;
2409 #if DEBUG_CORE
2410           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2411                       "Adding plaintext message of size %u with deadline %llu ms to batch\n",
2412                       (unsigned int) pos->size,
2413                       (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).rel_value);
2414 #endif
2415           deadline->abs_value = GNUNET_MIN (deadline->abs_value, pos->deadline.abs_value);
2416           GNUNET_free (pos);
2417           if (prev == NULL)
2418             n->messages = next;
2419           else
2420             prev->next = next;
2421         }
2422       else
2423         {
2424           prev = pos;
2425         }
2426       pos = next;
2427     }
2428 #if DEBUG_CORE
2429   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2430               "Deadline for message batch is %llu ms\n",
2431               GNUNET_TIME_absolute_get_remaining (*deadline).rel_value);
2432 #endif
2433   return ret;
2434 }
2435
2436
2437 /**
2438  * Remove messages with deadlines that have long expired from
2439  * the queue.
2440  *
2441  * @param n neighbour to inspect
2442  */
2443 static void
2444 discard_expired_messages (struct Neighbour *n)
2445 {
2446   struct MessageEntry *prev;
2447   struct MessageEntry *next;
2448   struct MessageEntry *pos;
2449   struct GNUNET_TIME_Absolute now;
2450   struct GNUNET_TIME_Relative delta;
2451   int disc;
2452
2453   disc = GNUNET_NO;
2454   now = GNUNET_TIME_absolute_get ();
2455   prev = NULL;
2456   pos = n->messages;
2457   while (pos != NULL) 
2458     {
2459       next = pos->next;
2460       delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
2461       if (delta.rel_value > PAST_EXPIRATION_DISCARD_TIME.rel_value)
2462         {
2463 #if DEBUG_CORE
2464           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2465                       "Message is %llu ms past due, discarding.\n",
2466                       delta.rel_value);
2467 #endif
2468           if (prev == NULL)
2469             n->messages = next;
2470           else
2471             prev->next = next;
2472           GNUNET_STATISTICS_update (stats, 
2473                                     gettext_noop ("# messages discarded (expired prior to transmission)"), 
2474                                     1, 
2475                                     GNUNET_NO);
2476           disc = GNUNET_YES;
2477           GNUNET_free (pos);
2478         }
2479       else
2480         prev = pos;
2481       pos = next;
2482     }
2483   if (GNUNET_YES == disc)
2484     schedule_peer_messages (n);
2485 }
2486
2487
2488 /**
2489  * Signature of the main function of a task.
2490  *
2491  * @param cls closure
2492  * @param tc context information (why was this task triggered now)
2493  */
2494 static void
2495 retry_plaintext_processing (void *cls,
2496                             const struct GNUNET_SCHEDULER_TaskContext *tc)
2497 {
2498   struct Neighbour *n = cls;
2499
2500   n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2501   process_plaintext_neighbour_queue (n);
2502 }
2503
2504
2505 /**
2506  * Send our key (and encrypted PING) to the other peer.
2507  *
2508  * @param n the other peer
2509  */
2510 static void send_key (struct Neighbour *n);
2511
2512 /**
2513  * Task that will retry "send_key" if our previous attempt failed
2514  * to yield a PONG.
2515  */
2516 static void
2517 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2518 {
2519   struct Neighbour *n = cls;
2520
2521 #if DEBUG_CORE
2522   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2523               "Retrying key transmission to `%4s'\n",
2524               GNUNET_i2s (&n->peer));
2525 #endif
2526   n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2527   n->set_key_retry_frequency =
2528     GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2529   send_key (n);
2530 }
2531
2532
2533 /**
2534  * Check if we have plaintext messages for the specified neighbour
2535  * pending, and if so, consider batching and encrypting them (and
2536  * then trigger processing of the encrypted queue if needed).
2537  *
2538  * @param n neighbour to check.
2539  */
2540 static void
2541 process_plaintext_neighbour_queue (struct Neighbour *n)
2542 {
2543   char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)];        /* plaintext */
2544   size_t used;
2545   struct EncryptedMessage *em;  /* encrypted message */
2546   struct EncryptedMessage *ph;  /* plaintext header */
2547   struct MessageEntry *me;
2548   unsigned int priority;
2549   struct GNUNET_TIME_Absolute deadline;
2550   struct GNUNET_TIME_Relative retry_time;
2551   struct GNUNET_CRYPTO_AesInitializationVector iv;
2552   struct GNUNET_CRYPTO_AuthKey auth_key;
2553
2554   if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2555     {
2556       GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
2557       n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2558     }
2559   switch (n->status)
2560     {
2561     case PEER_STATE_DOWN:
2562       send_key (n);
2563 #if DEBUG_CORE
2564       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2565                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2566                   GNUNET_i2s(&n->peer));
2567 #endif
2568       return;
2569     case PEER_STATE_KEY_SENT:
2570       if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2571         n->retry_set_key_task
2572           = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2573                                           &set_key_retry_task, n);    
2574 #if DEBUG_CORE
2575       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2576                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2577                   GNUNET_i2s(&n->peer));
2578 #endif
2579       return;
2580     case PEER_STATE_KEY_RECEIVED:
2581       if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)        
2582         n->retry_set_key_task
2583           = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2584                                           &set_key_retry_task, n);        
2585 #if DEBUG_CORE
2586       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2587                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2588                   GNUNET_i2s(&n->peer));
2589 #endif
2590       return;
2591     case PEER_STATE_KEY_CONFIRMED:
2592       /* ready to continue */
2593       break;
2594     }
2595   discard_expired_messages (n);
2596   if (n->messages == NULL)
2597     {
2598 #if DEBUG_CORE
2599       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2600                   "Plaintext message queue for `%4s' is empty.\n",
2601                   GNUNET_i2s(&n->peer));
2602 #endif
2603       return;                   /* no pending messages */
2604     }
2605   if (n->encrypted_head != NULL)
2606     {
2607 #if DEBUG_CORE
2608       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2609                   "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2610                   GNUNET_i2s(&n->peer));
2611 #endif
2612       return;                   /* wait for messages already encrypted to be
2613                                    processed first! */
2614     }
2615   ph = (struct EncryptedMessage *) pbuf;
2616   deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2617   priority = 0;
2618   used = sizeof (struct EncryptedMessage);
2619   used += batch_message (n,
2620                          &pbuf[used],
2621                          GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2622                          &deadline, &retry_time, &priority);
2623   if (used == sizeof (struct EncryptedMessage))
2624     {
2625 #if DEBUG_CORE
2626       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2627                   "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2628                   GNUNET_i2s(&n->peer));
2629 #endif
2630       /* no messages selected for sending, try again later... */
2631       n->retry_plaintext_task =
2632         GNUNET_SCHEDULER_add_delayed (retry_time,
2633                                       &retry_plaintext_processing, n);
2634       return;
2635     }
2636 #if DEBUG_CORE_QUOTA
2637   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2638               "Sending %u b/s as new limit to peer `%4s'\n",
2639               (unsigned int) ntohl (n->bw_in.value__),
2640               GNUNET_i2s (&n->peer));
2641 #endif
2642   ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
2643   ph->sequence_number = htonl (++n->last_sequence_number_sent);
2644   ph->inbound_bw_limit = n->bw_in;
2645   ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2646
2647   /* setup encryption message header */
2648   me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2649   me->deadline = deadline;
2650   me->priority = priority;
2651   me->size = used;
2652   em = (struct EncryptedMessage *) &me[1];
2653   em->header.size = htons (used);
2654   em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2655   em->iv_seed = ph->iv_seed;
2656   derive_iv (&iv, &n->encrypt_key, ph->iv_seed, &n->peer);
2657   /* encrypt */
2658 #if DEBUG_HANDSHAKE
2659   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2660               "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2661               (unsigned int) used - ENCRYPTED_HEADER_SIZE,
2662               GNUNET_i2s(&n->peer),
2663               (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).rel_value);
2664 #endif
2665   GNUNET_assert (GNUNET_OK ==
2666                  do_encrypt (n,
2667                              &iv,
2668                              &ph->sequence_number,
2669                              &em->sequence_number, used - ENCRYPTED_HEADER_SIZE));
2670   derive_auth_key (&auth_key,
2671                    &n->encrypt_key,
2672                    ph->iv_seed,
2673                    n->encrypt_key_created);
2674   GNUNET_CRYPTO_hmac (&auth_key,
2675                       &em->sequence_number,
2676                       used - ENCRYPTED_HEADER_SIZE,
2677                       &em->hmac);
2678 #if DEBUG_HANDSHAKE
2679   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2680               "Authenticated %u bytes of ciphertext %u: `%s'\n",
2681               used - ENCRYPTED_HEADER_SIZE,
2682               GNUNET_CRYPTO_crc32_n (&em->sequence_number,
2683                   used - ENCRYPTED_HEADER_SIZE),
2684               GNUNET_h2s (&em->hmac));
2685 #endif
2686   /* append to transmission list */
2687   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2688                                      n->encrypted_tail,
2689                                      n->encrypted_tail,
2690                                      me);
2691   process_encrypted_neighbour_queue (n);
2692   schedule_peer_messages (n);
2693 }
2694
2695
2696 /**
2697  * Function that recalculates the bandwidth quota for the
2698  * given neighbour and transmits it to the transport service.
2699  * 
2700  * @param cls neighbour for the quota update
2701  * @param tc context
2702  */
2703 static void
2704 neighbour_quota_update (void *cls,
2705                         const struct GNUNET_SCHEDULER_TaskContext *tc);
2706
2707
2708 /**
2709  * Schedule the task that will recalculate the bandwidth
2710  * quota for this peer (and possibly force a disconnect of
2711  * idle peers by calculating a bandwidth of zero).
2712  */
2713 static void
2714 schedule_quota_update (struct Neighbour *n)
2715 {
2716   GNUNET_assert (n->quota_update_task ==
2717                  GNUNET_SCHEDULER_NO_TASK);
2718   n->quota_update_task
2719     = GNUNET_SCHEDULER_add_delayed (QUOTA_UPDATE_FREQUENCY,
2720                                     &neighbour_quota_update,
2721                                     n);
2722 }
2723
2724
2725 /**
2726  * Initialize a new 'struct Neighbour'.
2727  *
2728  * @param pid ID of the new neighbour
2729  * @return handle for the new neighbour
2730  */
2731 static struct Neighbour *
2732 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2733 {
2734   struct Neighbour *n;
2735   struct GNUNET_TIME_Absolute now;
2736
2737 #if DEBUG_CORE
2738   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2739               "Creating neighbour entry for peer `%4s'\n",
2740               GNUNET_i2s (pid));
2741 #endif
2742   n = GNUNET_malloc (sizeof (struct Neighbour));
2743   n->peer = *pid;
2744   GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2745   now = GNUNET_TIME_absolute_get ();
2746   n->encrypt_key_created = now;
2747   n->last_activity = now;
2748   n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2749   n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2750   n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2751   n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2752   n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2753   n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
2754                                                 UINT32_MAX);
2755   GNUNET_assert (GNUNET_OK == 
2756                  GNUNET_CONTAINER_multihashmap_put (neighbours,
2757                                                     &n->peer.hashPubKey,
2758                                                     n,
2759                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2760   GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), 
2761                          GNUNET_CONTAINER_multihashmap_size (neighbours), GNUNET_NO);
2762   neighbour_quota_update (n, NULL);
2763   consider_free_neighbour (n);
2764   return n;
2765 }
2766
2767
2768 /**
2769  * Handle CORE_SEND request.
2770  *
2771  * @param cls unused
2772  * @param client the client issuing the request
2773  * @param message the "struct SendMessage"
2774  */
2775 static void
2776 handle_client_send (void *cls,
2777                     struct GNUNET_SERVER_Client *client,
2778                     const struct GNUNET_MessageHeader *message)
2779 {
2780   const struct SendMessage *sm;
2781   struct Neighbour *n;
2782   struct MessageEntry *prev;
2783   struct MessageEntry *pos;
2784   struct MessageEntry *e; 
2785   struct MessageEntry *min_prio_entry;
2786   struct MessageEntry *min_prio_prev;
2787   unsigned int min_prio;
2788   unsigned int queue_size;
2789   uint16_t msize;
2790
2791   msize = ntohs (message->size);
2792   if (msize <
2793       sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2794     {
2795       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "about to assert fail, msize is %d, should be at least %d\n", msize, sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader));
2796       GNUNET_break (0);
2797       if (client != NULL)
2798         GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2799       return;
2800     }
2801   sm = (const struct SendMessage *) message;
2802   msize -= sizeof (struct SendMessage);
2803   if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2804     {
2805       /* loopback */
2806       GNUNET_SERVER_mst_receive (mst,
2807                                  &self,
2808                                  (const char*) &sm[1],
2809                                  msize,
2810                                  GNUNET_YES,
2811                                  GNUNET_NO);
2812       if (client != NULL)
2813         GNUNET_SERVER_receive_done (client, GNUNET_OK);
2814       return;
2815     }
2816   n = find_neighbour (&sm->peer);
2817   if (n == NULL)
2818     n = create_neighbour (&sm->peer);
2819 #if DEBUG_CORE
2820   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2821               "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2822               "SEND",
2823               (unsigned int) msize, 
2824               GNUNET_i2s (&sm->peer));
2825 #endif
2826   discard_expired_messages (n);
2827   /* bound queue size */
2828   /* NOTE: this entire block to bound the queue size should be
2829      obsolete with the new client-request code and the
2830      'schedule_peer_messages' mechanism; we still have this code in
2831      here for now as a sanity check for the new mechanmism;
2832      ultimately, we should probably simply reject SEND messages that
2833      are not 'approved' (or provide a new core API for very unreliable
2834      delivery that always sends with priority 0).  Food for thought. */
2835   min_prio = UINT32_MAX;
2836   min_prio_entry = NULL;
2837   min_prio_prev = NULL;
2838   queue_size = 0;
2839   prev = NULL;
2840   pos = n->messages;
2841   while (pos != NULL) 
2842     {
2843       if (pos->priority <= min_prio)
2844         {
2845           min_prio_entry = pos;
2846           min_prio_prev = prev;
2847           min_prio = pos->priority;
2848         }
2849       queue_size++;
2850       prev = pos;
2851       pos = pos->next;
2852     }
2853   if (queue_size >= MAX_PEER_QUEUE_SIZE)
2854     {
2855       /* queue full */
2856       if (ntohl(sm->priority) <= min_prio)
2857         {
2858           /* discard new entry; this should no longer happen! */
2859           GNUNET_break (0);
2860 #if DEBUG_CORE
2861           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2862                       "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2863                       queue_size,
2864                       (unsigned int) MAX_PEER_QUEUE_SIZE,
2865                       (unsigned int) msize,
2866                       (unsigned int) ntohs (message->type));
2867 #endif
2868           GNUNET_STATISTICS_update (stats, 
2869                                     gettext_noop ("# discarded CORE_SEND requests"), 
2870                                     1, GNUNET_NO);
2871
2872           if (client != NULL)
2873             GNUNET_SERVER_receive_done (client, GNUNET_OK);
2874           return;
2875         }
2876       GNUNET_assert (min_prio_entry != NULL);
2877       /* discard "min_prio_entry" */
2878 #if DEBUG_CORE
2879       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2880                   "Queue full, discarding existing older request\n");
2881 #endif
2882           GNUNET_STATISTICS_update (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 1, GNUNET_NO);
2883       if (min_prio_prev == NULL)
2884         n->messages = min_prio_entry->next;
2885       else
2886         min_prio_prev->next = min_prio_entry->next;      
2887       GNUNET_free (min_prio_entry);     
2888     }
2889
2890 #if DEBUG_CORE
2891   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2892               "Adding transmission request for `%4s' of size %u to queue\n",
2893               GNUNET_i2s (&sm->peer),
2894               (unsigned int) msize);
2895 #endif  
2896   GNUNET_break (0 == ntohl (sm->reserved));
2897   e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2898   e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2899   e->priority = ntohl (sm->priority);
2900   e->size = msize;
2901   if (GNUNET_YES != (int) ntohl (sm->cork))
2902     e->got_slack = GNUNET_YES;
2903   memcpy (&e[1], &sm[1], msize);
2904
2905   /* insert, keep list sorted by deadline */
2906   prev = NULL;
2907   pos = n->messages;
2908   while ((pos != NULL) && (pos->deadline.abs_value < e->deadline.abs_value))
2909     {
2910       prev = pos;
2911       pos = pos->next;
2912     }
2913   if (prev == NULL)
2914     n->messages = e;
2915   else
2916     prev->next = e;
2917   e->next = pos;
2918
2919   /* consider scheduling now */
2920   process_plaintext_neighbour_queue (n);
2921   if (client != NULL)
2922     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2923 }
2924
2925
2926 /**
2927  * Function called when the transport service is ready to
2928  * receive a message.  Only resets 'n->th' to NULL.
2929  *
2930  * @param cls neighbour to use message from
2931  * @param size number of bytes we can transmit
2932  * @param buf where to copy the message
2933  * @return number of bytes transmitted
2934  */
2935 static size_t
2936 notify_transport_connect_done (void *cls,
2937                                size_t size,
2938                                void *buf)
2939 {
2940   struct Neighbour *n = cls;
2941
2942   n->th = NULL;
2943   if (GNUNET_YES != n->is_connected)
2944     {
2945       /* transport should only call us to transmit a message after
2946        * telling us about a successful connection to the respective peer */
2947 #if DEBUG_CORE
2948       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
2949                   "Timeout on notify connect!\n");
2950 #endif
2951       GNUNET_STATISTICS_update (stats, 
2952                                 gettext_noop ("# connection requests timed out in transport"), 
2953                                 1,
2954                                 GNUNET_NO);
2955       return 0;
2956     }
2957   if (buf == NULL)
2958     {
2959       GNUNET_STATISTICS_update (stats,
2960                                 gettext_noop ("# connection requests timed out in transport"),
2961                                 1,
2962                                 GNUNET_NO);
2963       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2964                   _("Failed to connect to `%4s': transport failed to connect\n"),
2965                   GNUNET_i2s (&n->peer));
2966       return 0;
2967     }
2968   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2969               _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2970               GNUNET_i2s (&n->peer));
2971   if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2972     GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2973   n->retry_set_key_task = GNUNET_SCHEDULER_add_now (&set_key_retry_task,
2974                                                     n);
2975   return 0;
2976 }
2977
2978
2979 /**
2980  * Handle CORE_REQUEST_CONNECT request.
2981  *
2982  * @param cls unused
2983  * @param client the client issuing the request
2984  * @param message the "struct ConnectMessage"
2985  */
2986 static void
2987 handle_client_request_connect (void *cls,
2988                                struct GNUNET_SERVER_Client *client,
2989                                const struct GNUNET_MessageHeader *message)
2990 {
2991   const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2992   struct Neighbour *n;
2993   struct GNUNET_TIME_Relative timeout;
2994
2995   if (0 == memcmp (&cm->peer, 
2996                    &my_identity, 
2997                    sizeof (struct GNUNET_PeerIdentity)))
2998     {
2999       /* In this case a client has asked us to connect to ourselves, not really an error! */
3000       GNUNET_SERVER_receive_done (client, GNUNET_OK);
3001       return;
3002     }
3003   timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
3004   GNUNET_break (ntohl (cm->reserved) == 0);
3005   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3006   n = find_neighbour (&cm->peer);
3007   if (n == NULL)
3008     n = create_neighbour (&cm->peer);
3009   if ( (GNUNET_YES == n->is_connected) ||
3010        (n->th != NULL) )
3011     {
3012       if (GNUNET_YES == n->is_connected) 
3013         GNUNET_STATISTICS_update (stats, 
3014                                   gettext_noop ("# connection requests ignored (already connected)"), 
3015                                   1,
3016                                   GNUNET_NO);
3017       else
3018         {
3019           GNUNET_TRANSPORT_notify_transmit_ready_cancel(n->th);
3020           n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
3021                                                           &cm->peer,
3022                                                           sizeof (struct GNUNET_MessageHeader), 0,
3023                                                           timeout,
3024                                                           &notify_transport_connect_done,
3025                                                           n);
3026           GNUNET_break (NULL != n->th);
3027           GNUNET_STATISTICS_update (stats,
3028                                     gettext_noop ("# connection requests retried (due to repeat request connect)"),
3029                                     1,
3030                                     GNUNET_NO);
3031         }
3032       return; /* already connected, or at least trying */
3033     }
3034   GNUNET_STATISTICS_update (stats, 
3035                             gettext_noop ("# connection requests received"), 
3036                             1,
3037                             GNUNET_NO);
3038
3039 #if DEBUG_CORE
3040   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3041               "Core received `%s' request for `%4s', will try to establish connection\n",
3042               "REQUEST_CONNECT",
3043               GNUNET_i2s (&cm->peer));
3044 #endif
3045
3046   /* ask transport to connect to the peer */
3047   n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
3048                                                   &cm->peer,
3049                                                   sizeof (struct GNUNET_MessageHeader), 0,
3050                                                   timeout,
3051                                                   &notify_transport_connect_done,
3052                                                   n);
3053   GNUNET_break (NULL != n->th);
3054 }
3055
3056
3057 /**
3058  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
3059  * the neighbour's struct and retry send_key.  Or, if we did not get a
3060  * HELLO, just do nothing.
3061  *
3062  * @param cls the 'struct Neighbour' to retry sending the key for
3063  * @param peer the peer for which this is the HELLO
3064  * @param hello HELLO message of that peer
3065  * @param err_msg NULL if successful, otherwise contains error message
3066  */
3067 static void
3068 process_hello_retry_send_key (void *cls,
3069                               const struct GNUNET_PeerIdentity *peer,
3070                               const struct GNUNET_HELLO_Message *hello,
3071                               const char *err_msg)
3072 {
3073   struct Neighbour *n = cls;
3074
3075   if (err_msg != NULL)
3076   {
3077     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3078                 _("Error in communication with PEERINFO service\n"));
3079     /* return; */
3080   }
3081
3082   if (peer == NULL)
3083     {
3084 #if DEBUG_CORE
3085       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3086                   "Entered `%s' and `%s' is NULL!\n",
3087                   "process_hello_retry_send_key",
3088                   "peer");
3089 #endif
3090       n->pitr = NULL;
3091       if (n->public_key != NULL)
3092         {
3093           if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3094             {
3095               GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3096               n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3097             }      
3098           GNUNET_STATISTICS_update (stats,
3099                                     gettext_noop ("# SET_KEY messages deferred (need public key)"), 
3100                                     -1, 
3101                                     GNUNET_NO);
3102           send_key (n);
3103         }
3104       else
3105         {
3106 #if DEBUG_CORE
3107           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3108                       "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
3109                       GNUNET_i2s (&n->peer));
3110 #endif
3111           GNUNET_STATISTICS_update (stats,
3112                                     gettext_noop ("# Delayed connecting due to lack of public key"),
3113                                     1,
3114                                     GNUNET_NO);      
3115           if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
3116             n->retry_set_key_task
3117               = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3118                                               &set_key_retry_task, n);
3119         }
3120       return;
3121     }
3122
3123 #if DEBUG_CORE
3124   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3125               "Entered `%s' for peer `%4s'\n",
3126               "process_hello_retry_send_key",
3127               GNUNET_i2s (peer));
3128 #endif
3129   if (n->public_key != NULL)
3130     {
3131       /* already have public key, why are we here? */
3132       GNUNET_break (0);
3133       return;
3134     }
3135
3136 #if DEBUG_CORE
3137   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3138               "Received new `%s' message for `%4s', initiating key exchange.\n",
3139               "HELLO",
3140               GNUNET_i2s (peer));
3141 #endif
3142   n->public_key =
3143     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3144   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3145     {
3146       GNUNET_STATISTICS_update (stats,
3147                                 gettext_noop ("# Error extracting public key from HELLO"),
3148                                 1,
3149                                 GNUNET_NO);      
3150       GNUNET_free (n->public_key);
3151       n->public_key = NULL;
3152 #if DEBUG_CORE
3153   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3154               "GNUNET_HELLO_get_key returned awfully\n");
3155 #endif
3156       return;
3157     }
3158 }
3159
3160
3161 /**
3162  * Send our key (and encrypted PING) to the other peer.
3163  *
3164  * @param n the other peer
3165  */
3166 static void
3167 send_key (struct Neighbour *n)
3168 {
3169   struct MessageEntry *pos;
3170   struct SetKeyMessage *sm;
3171   struct MessageEntry *me;
3172   struct PingMessage pp;
3173   struct PingMessage *pm;
3174   struct GNUNET_CRYPTO_AesInitializationVector iv;
3175
3176   if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3177     {
3178       GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3179       n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3180     }        
3181   if (n->pitr != NULL)
3182     {
3183 #if DEBUG_CORE
3184       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3185                   "Key exchange in progress with `%4s'.\n",
3186                   GNUNET_i2s (&n->peer));
3187 #endif
3188       return; /* already in progress */
3189     }
3190   if (GNUNET_YES != n->is_connected)
3191     {
3192 #if DEBUG_CORE
3193       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3194                   "Not yet connected to peer `%4s'!\n",
3195                   GNUNET_i2s (&n->peer));
3196 #endif
3197       if (NULL == n->th)
3198         {
3199           GNUNET_STATISTICS_update (stats, 
3200                                     gettext_noop ("# Asking transport to connect (for SET_KEY)"), 
3201                                     1, 
3202                                     GNUNET_NO);
3203           n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
3204                                                           &n->peer,
3205                                                           sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
3206                                                           0,
3207                                                           GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3208                                                           &notify_encrypted_transmit_ready,
3209                                                           n);
3210         }
3211       return; 
3212     }
3213 #if DEBUG_CORE
3214   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3215               "Asked to perform key exchange with `%4s'.\n",
3216               GNUNET_i2s (&n->peer));
3217 #endif
3218   if (n->public_key == NULL)
3219     {
3220       /* lookup n's public key, then try again */
3221 #if DEBUG_CORE
3222       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3223                   "Lacking public key for `%4s', trying to obtain one (send_key).\n",
3224                   GNUNET_i2s (&n->peer));
3225 #endif
3226       GNUNET_assert (n->pitr == NULL);
3227       n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3228                                          &n->peer,
3229                                          GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
3230                                          &process_hello_retry_send_key, n);
3231       return;
3232     }
3233   pos = n->encrypted_head;
3234   while (pos != NULL)
3235     {
3236       if (GNUNET_YES == pos->is_setkey)
3237         {
3238           if (pos->sender_status == n->status)
3239             {
3240 #if DEBUG_CORE
3241               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3242                           "`%s' message for `%4s' queued already\n",
3243                           "SET_KEY",
3244                           GNUNET_i2s (&n->peer));
3245 #endif
3246               goto trigger_processing;
3247             }
3248           GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
3249                                        n->encrypted_tail,
3250                                        pos);
3251           GNUNET_free (pos);
3252 #if DEBUG_CORE
3253           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3254                       "Removing queued `%s' message for `%4s', will create a new one\n",
3255                       "SET_KEY",
3256                       GNUNET_i2s (&n->peer));
3257 #endif
3258           break;
3259         }
3260       pos = pos->next;
3261     }
3262
3263   /* update status */
3264   switch (n->status)
3265     {
3266     case PEER_STATE_DOWN:
3267       n->status = PEER_STATE_KEY_SENT;
3268       break;
3269     case PEER_STATE_KEY_SENT:
3270       break;
3271     case PEER_STATE_KEY_RECEIVED:
3272       break;
3273     case PEER_STATE_KEY_CONFIRMED:
3274       break;
3275     default:
3276       GNUNET_break (0);
3277       break;
3278     }
3279   
3280
3281   /* first, set key message */
3282   me = GNUNET_malloc (sizeof (struct MessageEntry) +
3283                       sizeof (struct SetKeyMessage) +
3284                       sizeof (struct PingMessage));
3285   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
3286   me->priority = SET_KEY_PRIORITY;
3287   me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
3288   me->is_setkey = GNUNET_YES;
3289   me->got_slack = GNUNET_YES; /* do not defer this one! */
3290   me->sender_status = n->status;
3291   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3292                                      n->encrypted_tail,
3293                                      n->encrypted_tail,
3294                                      me);
3295   sm = (struct SetKeyMessage *) &me[1];
3296   sm->header.size = htons (sizeof (struct SetKeyMessage));
3297   sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
3298   sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
3299                                         PEER_STATE_KEY_SENT : n->status));
3300   sm->purpose.size =
3301     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3302            sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3303            sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3304            sizeof (struct GNUNET_PeerIdentity));
3305   sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
3306   sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
3307   sm->target = n->peer;
3308   GNUNET_assert (GNUNET_OK ==
3309                  GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
3310                                             sizeof (struct
3311                                                     GNUNET_CRYPTO_AesSessionKey),
3312                                             n->public_key,
3313                                             &sm->encrypted_key));
3314   GNUNET_assert (GNUNET_OK ==
3315                  GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
3316                                          &sm->signature));  
3317   pm = (struct PingMessage *) &sm[1];
3318   pm->header.size = htons (sizeof (struct PingMessage));
3319   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
3320   pm->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3321   derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
3322   pp.challenge = n->ping_challenge;
3323   pp.target = n->peer;
3324 #if DEBUG_HANDSHAKE
3325   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3326               "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
3327               "SET_KEY", "PING",
3328               (unsigned int) n->ping_challenge,
3329               GNUNET_i2s (&n->peer),
3330               (unsigned int) n->encrypt_key.crc32,
3331               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3332               pm->iv_seed);
3333 #endif
3334   do_encrypt (n,
3335               &iv,
3336               &pp.target,
3337               &pm->target,
3338               sizeof (struct PingMessage) -
3339               ((void *) &pm->target - (void *) pm));
3340   GNUNET_STATISTICS_update (stats, 
3341                             gettext_noop ("# SET_KEY and PING messages created"), 
3342                             1, 
3343                             GNUNET_NO);
3344 #if DEBUG_CORE
3345   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3346               "Have %llu ms left for `%s' transmission.\n",
3347               (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).rel_value,
3348               "SET_KEY");
3349 #endif
3350  trigger_processing:
3351   /* trigger queue processing */
3352   process_encrypted_neighbour_queue (n);
3353   if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
3354        (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
3355     n->retry_set_key_task
3356       = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3357                                       &set_key_retry_task, n);    
3358 }
3359
3360
3361 /**
3362  * We received a SET_KEY message.  Validate and update
3363  * our key material and status.
3364  *
3365  * @param n the neighbour from which we received message m
3366  * @param m the set key message we received
3367  * @param ats performance data
3368  * @param ats_count number of entries in ats (excluding 0-termination)
3369  */
3370 static void
3371 handle_set_key (struct Neighbour *n,
3372                 const struct SetKeyMessage *m,
3373                 const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3374                 uint32_t ats_count);
3375
3376
3377
3378 /**
3379  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
3380  * the neighbour's struct and retry handling the set_key message.  Or,
3381  * if we did not get a HELLO, just free the set key message.
3382  *
3383  * @param cls pointer to the set key message
3384  * @param peer the peer for which this is the HELLO
3385  * @param hello HELLO message of that peer
3386  * @param err_msg NULL if successful, otherwise contains error message
3387  */
3388 static void
3389 process_hello_retry_handle_set_key (void *cls,
3390                                     const struct GNUNET_PeerIdentity *peer,
3391                                     const struct GNUNET_HELLO_Message *hello,
3392                                     const char *err_msg)
3393 {
3394   struct Neighbour *n = cls;
3395   struct SetKeyMessage *sm = n->skm;
3396
3397   if (err_msg != NULL)
3398   {
3399     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3400                 _("Error in communication with PEERINFO service\n"));
3401     /* return; */
3402   }
3403
3404   if (peer == NULL)
3405     {
3406       n->skm = NULL;
3407       n->pitr = NULL;
3408       if (n->public_key != NULL)
3409         {
3410 #if DEBUG_CORE
3411           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3412                       "Received `%s' for `%4s', continuing processing of `%s' message.\n",
3413                       "HELLO",
3414                       GNUNET_i2s (&n->peer),
3415                       "SET_KEY");
3416 #endif
3417           handle_set_key (n, sm, NULL, 0);
3418         }
3419       else
3420         {
3421           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3422                       _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
3423                       "SET_KEY",
3424                       GNUNET_i2s (&n->peer));
3425         }
3426       GNUNET_free (sm);
3427       return;
3428     }
3429   if (n->public_key != NULL)
3430     return;                     /* multiple HELLOs match!? */
3431   n->public_key =
3432     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3433   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3434     {
3435       GNUNET_break_op (0);
3436       GNUNET_free (n->public_key);
3437       n->public_key = NULL;
3438     }
3439 }
3440
3441
3442 /**
3443  * Merge the given performance data with the data we currently
3444  * track for the given neighbour.
3445  *
3446  * @param n neighbour
3447  * @param ats new performance data
3448  * @param ats_count number of records in ats
3449  */
3450 static void
3451 update_neighbour_performance (struct Neighbour *n,
3452                               const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3453                               uint32_t ats_count)
3454 {
3455   uint32_t i;
3456   unsigned int j;
3457
3458   if (ats_count == 0)
3459     return;
3460   for (i = 0; i < ats_count; i++)
3461     {
3462       for (j=0;j < n->ats_count; j++)
3463         {
3464           if (n->ats[j].type == ats[i].type)
3465             {
3466               n->ats[j].value = ats[i].value;
3467               break;
3468             }
3469         }
3470       if (j == n->ats_count)
3471         {
3472           GNUNET_array_append (n->ats,
3473                                n->ats_count,
3474                                ats[i]);
3475         }
3476     }
3477 }
3478
3479
3480 /**
3481  * We received a PING message.  Validate and transmit
3482  * PONG.
3483  *
3484  * @param n sender of the PING
3485  * @param m the encrypted PING message itself
3486  * @param ats performance data
3487  * @param ats_count number of entries in ats (excluding 0-termination)
3488  */
3489 static void
3490 handle_ping (struct Neighbour *n,
3491              const struct PingMessage *m,
3492              const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3493              uint32_t ats_count)
3494 {
3495   struct PingMessage t;
3496   struct PongMessage tx;
3497   struct PongMessage *tp;
3498   struct MessageEntry *me;
3499   struct GNUNET_CRYPTO_AesInitializationVector iv;
3500
3501 #if DEBUG_CORE
3502   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3503               "Core service receives `%s' request from `%4s'.\n",
3504               "PING", GNUNET_i2s (&n->peer));
3505 #endif
3506   derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3507   if (GNUNET_OK !=
3508       do_decrypt (n,
3509                   &iv,
3510                   &m->target,
3511                   &t.target,
3512                   sizeof (struct PingMessage) -
3513                   ((void *) &m->target - (void *) m)))
3514     return;
3515 #if DEBUG_HANDSHAKE
3516   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3517               "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u, IV %u (salt %u)\n",
3518               "PING",
3519               GNUNET_i2s (&t.target),
3520               (unsigned int) t.challenge,
3521               (unsigned int) n->decrypt_key.crc32,
3522               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3523               m->iv_seed);
3524 #endif
3525   GNUNET_STATISTICS_update (stats,
3526                             gettext_noop ("# PING messages decrypted"), 
3527                             1,
3528                             GNUNET_NO);
3529   if (0 != memcmp (&t.target,
3530                    &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3531     {
3532       GNUNET_break_op (0);
3533       return;
3534     }
3535   update_neighbour_performance (n, ats, ats_count);
3536   me = GNUNET_malloc (sizeof (struct MessageEntry) +
3537                       sizeof (struct PongMessage));
3538   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3539                                      n->encrypted_tail,
3540                                      n->encrypted_tail,
3541                                      me);
3542   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
3543   me->priority = PONG_PRIORITY;
3544   me->size = sizeof (struct PongMessage);
3545   tx.inbound_bw_limit = n->bw_in;
3546   tx.challenge = t.challenge;
3547   tx.target = t.target;
3548   tp = (struct PongMessage *) &me[1];
3549   tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
3550   tp->header.size = htons (sizeof (struct PongMessage));
3551   tp->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3552   derive_pong_iv (&iv, &n->encrypt_key, tp->iv_seed, t.challenge, &n->peer);
3553   do_encrypt (n,
3554               &iv,
3555               &tx.challenge,
3556               &tp->challenge,
3557               sizeof (struct PongMessage) -
3558               ((void *) &tp->challenge - (void *) tp));
3559   GNUNET_STATISTICS_update (stats, 
3560                             gettext_noop ("# PONG messages created"), 
3561                             1, 
3562                             GNUNET_NO);
3563 #if DEBUG_HANDSHAKE
3564   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3565               "Encrypting `%s' with challenge %u using key %u, IV %u (salt %u)\n",
3566               "PONG",
3567               (unsigned int) t.challenge,
3568               (unsigned int) n->encrypt_key.crc32,
3569               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3570               tp->iv_seed);
3571 #endif
3572   /* trigger queue processing */
3573   process_encrypted_neighbour_queue (n);
3574 }
3575
3576
3577 /**
3578  * We received a PONG message.  Validate and update our status.
3579  *
3580  * @param n sender of the PONG
3581  * @param m the encrypted PONG message itself
3582  * @param ats performance data
3583  * @param ats_count number of entries in ats (excluding 0-termination)
3584  */
3585 static void
3586 handle_pong (struct Neighbour *n, 
3587              const struct PongMessage *m,
3588              const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3589              uint32_t ats_count)
3590 {
3591   struct PongMessage t;
3592   struct ConnectNotifyMessage *cnm;
3593   struct GNUNET_CRYPTO_AesInitializationVector iv;
3594   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
3595   struct GNUNET_TRANSPORT_ATS_Information *mats;
3596   size_t size;
3597
3598 #if DEBUG_CORE
3599   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3600               "Core service receives `%s' response from `%4s'.\n",
3601               "PONG", GNUNET_i2s (&n->peer));
3602 #endif
3603   /* mark as garbage, just to be sure */
3604   memset (&t, 255, sizeof (t));
3605   derive_pong_iv (&iv, &n->decrypt_key, m->iv_seed, n->ping_challenge,
3606       &my_identity);
3607   if (GNUNET_OK !=
3608       do_decrypt (n,
3609                   &iv,
3610                   &m->challenge,
3611                   &t.challenge,
3612                   sizeof (struct PongMessage) -
3613                   ((void *) &m->challenge - (void *) m)))
3614     {
3615       GNUNET_break_op (0);
3616       return;
3617     }
3618   GNUNET_STATISTICS_update (stats, 
3619                             gettext_noop ("# PONG messages decrypted"), 
3620                             1, 
3621                             GNUNET_NO);
3622 #if DEBUG_HANDSHAKE
3623   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3624               "Decrypted `%s' from `%4s' with challenge %u using key %u, IV %u (salt %u)\n",
3625               "PONG",
3626               GNUNET_i2s (&t.target),
3627               (unsigned int) t.challenge,
3628               (unsigned int) n->decrypt_key.crc32,
3629               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3630               m->iv_seed);
3631 #endif
3632   if ((0 != memcmp (&t.target,
3633                     &n->peer,
3634                     sizeof (struct GNUNET_PeerIdentity))) ||
3635       (n->ping_challenge != t.challenge))
3636     {
3637       /* PONG malformed */
3638 #if DEBUG_CORE
3639       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3640                   "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
3641                   "PONG", 
3642                   GNUNET_i2s (&n->peer),
3643                   (unsigned int) n->ping_challenge);
3644       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3645                   "Received malformed `%s' received from `%4s' with challenge %u\n",
3646                   "PONG", GNUNET_i2s (&t.target), 
3647                   (unsigned int) t.challenge);
3648 #endif
3649       GNUNET_break_op (n->ping_challenge != t.challenge);
3650       return;
3651     }
3652   switch (n->status)
3653     {
3654     case PEER_STATE_DOWN:
3655       GNUNET_break (0);         /* should be impossible */
3656       return;
3657     case PEER_STATE_KEY_SENT:
3658       GNUNET_break (0);         /* should be impossible, how did we decrypt? */
3659       return;
3660     case PEER_STATE_KEY_RECEIVED:
3661       GNUNET_STATISTICS_update (stats, 
3662                                 gettext_noop ("# Session keys confirmed via PONG"), 
3663                                 1, 
3664                                 GNUNET_NO);
3665       n->status = PEER_STATE_KEY_CONFIRMED;
3666       if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
3667         {
3668           n->bw_out_external_limit = t.inbound_bw_limit;
3669           n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3670                                                   n->bw_out_internal_limit);
3671           GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3672                                                  n->bw_out);       
3673           GNUNET_TRANSPORT_set_quota (transport,
3674                                       &n->peer,
3675                                       n->bw_in,
3676                                       n->bw_out,
3677                                       GNUNET_TIME_UNIT_FOREVER_REL,
3678                                       NULL, NULL); 
3679         }
3680 #if DEBUG_CORE
3681       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3682                   "Confirmed key via `%s' message for peer `%4s'\n",
3683                   "PONG", GNUNET_i2s (&n->peer));
3684 #endif      
3685       if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3686         {
3687           GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3688           n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3689         }      
3690       update_neighbour_performance (n, ats, ats_count);      
3691       size = sizeof (struct ConnectNotifyMessage) +
3692         (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3693       if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3694         {
3695           GNUNET_break (0);
3696           /* recovery strategy: throw away performance data */
3697           GNUNET_array_grow (n->ats,
3698                              n->ats_count,
3699                              0);
3700           size = sizeof (struct PeerStatusNotifyMessage) +
3701             n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3702         }
3703       cnm = (struct ConnectNotifyMessage*) buf;
3704       cnm->header.size = htons (size);
3705       cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3706       cnm->ats_count = htonl (n->ats_count);
3707       cnm->peer = n->peer;
3708       mats = &cnm->ats;
3709       memcpy (mats,
3710               n->ats,
3711               n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
3712       mats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3713       mats[n->ats_count].value = htonl (0);      
3714       send_to_all_clients (&cnm->header, 
3715                            GNUNET_NO, 
3716                            GNUNET_CORE_OPTION_SEND_CONNECT);
3717       process_encrypted_neighbour_queue (n);
3718       /* fall-through! */
3719     case PEER_STATE_KEY_CONFIRMED:
3720       n->last_activity = GNUNET_TIME_absolute_get ();
3721       if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3722         GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3723       n->keep_alive_task 
3724         = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3725                                         &send_keep_alive,
3726                                         n);
3727       handle_peer_status_change (n);
3728       break;
3729     default:
3730       GNUNET_break (0);
3731       break;
3732     }
3733 }
3734
3735
3736 /**
3737  * We received a SET_KEY message.  Validate and update
3738  * our key material and status.
3739  *
3740  * @param n the neighbour from which we received message m
3741  * @param m the set key message we received
3742  * @param ats performance data
3743  * @param ats_count number of entries in ats (excluding 0-termination)
3744  */
3745 static void
3746 handle_set_key (struct Neighbour *n, 
3747                 const struct SetKeyMessage *m,
3748                 const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3749                 uint32_t ats_count)
3750 {
3751   struct SetKeyMessage *m_cpy;
3752   struct GNUNET_TIME_Absolute t;
3753   struct GNUNET_CRYPTO_AesSessionKey k;
3754   struct PingMessage *ping;
3755   struct PongMessage *pong;
3756   enum PeerStateMachine sender_status;
3757
3758 #if DEBUG_CORE
3759   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3760               "Core service receives `%s' request from `%4s'.\n",
3761               "SET_KEY", GNUNET_i2s (&n->peer));
3762 #endif
3763   if (n->public_key == NULL)
3764     {
3765       if (n->pitr != NULL)
3766         {
3767 #if DEBUG_CORE
3768           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3769                       "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3770                       "SET_KEY");
3771 #endif
3772           return;
3773         }
3774 #if DEBUG_CORE
3775       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3776                   "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3777 #endif
3778       m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3779       memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3780       /* lookup n's public key, then try again */
3781       GNUNET_assert (n->skm == NULL);
3782       n->skm = m_cpy;
3783       n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3784                                          &n->peer,
3785                                          GNUNET_TIME_UNIT_MINUTES,
3786                                          &process_hello_retry_handle_set_key, n);
3787       GNUNET_STATISTICS_update (stats, 
3788                                 gettext_noop ("# SET_KEY messages deferred (need public key)"), 
3789                                 1, 
3790                                 GNUNET_NO);
3791       return;
3792     }
3793   if (0 != memcmp (&m->target,
3794                    &my_identity,
3795                    sizeof (struct GNUNET_PeerIdentity)))
3796     {
3797       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3798                   _("Received `%s' message that was for `%s', not for me.  Ignoring.\n"),
3799                   "SET_KEY",
3800                   GNUNET_i2s (&m->target));
3801       return;
3802     }
3803   if ((ntohl (m->purpose.size) !=
3804        sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3805        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3806        sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3807        sizeof (struct GNUNET_PeerIdentity)) ||
3808       (GNUNET_OK !=
3809        GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3810                                  &m->purpose, &m->signature, n->public_key)))
3811     {
3812       /* invalid signature */
3813       GNUNET_break_op (0);
3814       return;
3815     }
3816   t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3817   if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3818        (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3819       (t.abs_value < n->decrypt_key_created.abs_value))
3820     {
3821       /* this could rarely happen due to massive re-ordering of
3822          messages on the network level, but is most likely either
3823          a bug or some adversary messing with us.  Report. */
3824       GNUNET_break_op (0);
3825       return;
3826     }
3827 #if DEBUG_CORE
3828   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
3829               "Decrypting key material.\n");
3830 #endif  
3831   if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3832                                   &m->encrypted_key,
3833                                   &k,
3834                                   sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3835        != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3836       (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3837     {
3838       /* failed to decrypt !? */
3839       GNUNET_break_op (0);
3840       return;
3841     }
3842   GNUNET_STATISTICS_update (stats, 
3843                             gettext_noop ("# SET_KEY messages decrypted"), 
3844                             1, 
3845                             GNUNET_NO);
3846   n->decrypt_key = k;
3847   if (n->decrypt_key_created.abs_value != t.abs_value)
3848     {
3849       /* fresh key, reset sequence numbers */
3850       n->last_sequence_number_received = 0;
3851       n->last_packets_bitmap = 0;
3852       n->decrypt_key_created = t;
3853     }
3854   update_neighbour_performance (n, ats, ats_count);
3855   sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3856   switch (n->status)
3857     {
3858     case PEER_STATE_DOWN:
3859       n->status = PEER_STATE_KEY_RECEIVED;
3860 #if DEBUG_CORE
3861       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3862                   "Responding to `%s' with my own key.\n", "SET_KEY");
3863 #endif
3864       send_key (n);
3865       break;
3866     case PEER_STATE_KEY_SENT:
3867     case PEER_STATE_KEY_RECEIVED:
3868       n->status = PEER_STATE_KEY_RECEIVED;
3869       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3870           (sender_status != PEER_STATE_KEY_CONFIRMED))
3871         {
3872 #if DEBUG_CORE
3873           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3874                       "Responding to `%s' with my own key (other peer has status %u).\n",
3875                       "SET_KEY",
3876                       (unsigned int) sender_status);
3877 #endif
3878           send_key (n);
3879         }
3880       break;
3881     case PEER_STATE_KEY_CONFIRMED:
3882       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3883           (sender_status != PEER_STATE_KEY_CONFIRMED))
3884         {         
3885 #if DEBUG_CORE
3886           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3887                       "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3888                       "SET_KEY", 
3889                       (unsigned int) sender_status);
3890 #endif
3891           send_key (n);
3892         }
3893       break;
3894     default:
3895       GNUNET_break (0);
3896       break;
3897     }
3898   if (n->pending_ping != NULL)
3899     {
3900       ping = n->pending_ping;
3901       n->pending_ping = NULL;
3902       handle_ping (n, ping, NULL, 0);
3903       GNUNET_free (ping);
3904     }
3905   if (n->pending_pong != NULL)
3906     {
3907       pong = n->pending_pong;
3908       n->pending_pong = NULL;
3909       handle_pong (n, pong, NULL, 0);
3910       GNUNET_free (pong);
3911     }
3912 }
3913
3914
3915 /**
3916  * Send a P2P message to a client.
3917  *
3918  * @param sender who sent us the message?
3919  * @param client who should we give the message to?
3920  * @param m contains the message to transmit
3921  * @param msize number of bytes in buf to transmit
3922  */
3923 static void
3924 send_p2p_message_to_client (struct Neighbour *sender,
3925                             struct Client *client,
3926                             const void *m, size_t msize)
3927 {
3928   size_t size = msize + sizeof (struct NotifyTrafficMessage) +
3929     (sender->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3930   char buf[size];
3931   struct NotifyTrafficMessage *ntm;
3932   struct GNUNET_TRANSPORT_ATS_Information *ats;
3933
3934   if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3935     {
3936       GNUNET_break (0);
3937       /* recovery strategy: throw performance data away... */
3938       GNUNET_array_grow (sender->ats,
3939                          sender->ats_count,
3940                          0);
3941       size = msize + sizeof (struct NotifyTrafficMessage) +
3942         (sender->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3943     }
3944 #if DEBUG_CORE
3945   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3946               "Core service passes message from `%4s' of type %u to client.\n",
3947               GNUNET_i2s(&sender->peer),
3948               (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3949 #endif
3950   ntm = (struct NotifyTrafficMessage *) buf;
3951   ntm->header.size = htons (size);
3952   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3953   ntm->ats_count = htonl (sender->ats_count);
3954   ntm->peer = sender->peer;
3955   ats = &ntm->ats;
3956   memcpy (ats,
3957           sender->ats,
3958           sizeof (struct GNUNET_TRANSPORT_ATS_Information) * sender->ats_count);
3959   ats[sender->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3960   ats[sender->ats_count].value = htonl (0);  
3961   memcpy (&ats[sender->ats_count+1],
3962           m, 
3963           msize);
3964   send_to_client (client, &ntm->header, GNUNET_YES);
3965 }
3966
3967
3968 /**
3969  * Deliver P2P message to interested clients.
3970  *
3971  * @param cls always NULL
3972  * @param client who sent us the message (struct Neighbour)
3973  * @param m the message
3974  */
3975 static void
3976 deliver_message (void *cls,
3977                  void *client,
3978                  const struct GNUNET_MessageHeader *m)
3979 {
3980   struct Neighbour *sender = client;
3981   size_t msize = ntohs (m->size);
3982   char buf[256];
3983   struct Client *cpos;
3984   uint16_t type;
3985   unsigned int tpos;
3986   int deliver_full;
3987   int dropped;
3988
3989   type = ntohs (m->type);
3990 #if DEBUG_CORE
3991   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3992               "Received encapsulated message of type %u and size %u from `%4s'\n",
3993               (unsigned int) type,
3994               ntohs (m->size),
3995               GNUNET_i2s (&sender->peer));
3996 #endif
3997   GNUNET_snprintf (buf,
3998                    sizeof(buf),
3999                    gettext_noop ("# bytes of messages of type %u received"),
4000                    (unsigned int) type);
4001   GNUNET_STATISTICS_set (stats,
4002                          buf,
4003                          msize,
4004                          GNUNET_NO);     
4005   dropped = GNUNET_YES;
4006   cpos = clients;
4007   while (cpos != NULL)
4008     {
4009       deliver_full = GNUNET_NO;
4010       if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
4011         deliver_full = GNUNET_YES;
4012       else
4013         {
4014           for (tpos = 0; tpos < cpos->tcnt; tpos++)
4015             {
4016               if (type != cpos->types[tpos])
4017                 continue;
4018               deliver_full = GNUNET_YES;
4019               break;
4020             }
4021         }
4022       if (GNUNET_YES == deliver_full)
4023         {
4024           send_p2p_message_to_client (sender, cpos, m, msize);
4025           dropped = GNUNET_NO;
4026         }
4027       else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
4028         {
4029           send_p2p_message_to_client (sender, cpos, m,
4030                                       sizeof (struct GNUNET_MessageHeader));
4031         }
4032       cpos = cpos->next;
4033     }
4034   if (dropped == GNUNET_YES)
4035     {
4036 #if DEBUG_CORE
4037       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4038                   "Message of type %u from `%4s' not delivered to any client.\n",
4039                   (unsigned int) type,
4040                   GNUNET_i2s (&sender->peer));
4041 #endif
4042       GNUNET_STATISTICS_update (stats,
4043                                 gettext_noop ("# messages not delivered to any client"), 
4044                                 1, GNUNET_NO);
4045     }
4046 }
4047
4048
4049 /**
4050  * We received an encrypted message.  Decrypt, validate and
4051  * pass on to the appropriate clients.
4052  *
4053  * @param n target of the message
4054  * @param m encrypted message
4055  * @param ats performance data
4056  * @param ats_count number of entries in ats (excluding 0-termination)
4057  */
4058 static void
4059 handle_encrypted_message (struct Neighbour *n,
4060                           const struct EncryptedMessage *m,
4061                           const struct GNUNET_TRANSPORT_ATS_Information *ats, 
4062                           uint32_t ats_count)
4063 {
4064   size_t size = ntohs (m->header.size);
4065   char buf[size];
4066   struct EncryptedMessage *pt;  /* plaintext */
4067   GNUNET_HashCode ph;
4068   uint32_t snum;
4069   struct GNUNET_TIME_Absolute t;
4070   struct GNUNET_CRYPTO_AesInitializationVector iv;
4071   struct GNUNET_CRYPTO_AuthKey auth_key;
4072
4073 #if DEBUG_CORE
4074   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4075               "Core service receives `%s' request from `%4s'.\n",
4076               "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
4077 #endif  
4078   /* validate hash */
4079   derive_auth_key (&auth_key,
4080                    &n->decrypt_key,
4081                    m->iv_seed,
4082                    n->decrypt_key_created);
4083   GNUNET_CRYPTO_hmac (&auth_key,
4084                       &m->sequence_number,
4085                       size - ENCRYPTED_HEADER_SIZE, &ph);
4086 #if DEBUG_HANDSHAKE
4087   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4088               "Re-Authenticated %u bytes of ciphertext (`%u'): `%s'\n",
4089               (unsigned int) size - ENCRYPTED_HEADER_SIZE,
4090               GNUNET_CRYPTO_crc32_n (&m->sequence_number,
4091                   size - ENCRYPTED_HEADER_SIZE),
4092               GNUNET_h2s (&ph));
4093 #endif
4094
4095   if (0 != memcmp (&ph,
4096                    &m->hmac,
4097                    sizeof (GNUNET_HashCode)))
4098     {
4099       /* checksum failed */
4100       GNUNET_break_op (0);
4101       return;
4102     }
4103   derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
4104   /* decrypt */
4105   if (GNUNET_OK !=
4106       do_decrypt (n,
4107                   &iv,
4108                   &m->sequence_number,
4109                   &buf[ENCRYPTED_HEADER_SIZE],
4110                   size - ENCRYPTED_HEADER_SIZE))
4111     return;
4112   pt = (struct EncryptedMessage *) buf;
4113
4114   /* validate sequence number */
4115   snum = ntohl (pt->sequence_number);
4116   if (n->last_sequence_number_received == snum)
4117     {
4118       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4119                   "Received duplicate message, ignoring.\n");
4120       /* duplicate, ignore */
4121       GNUNET_STATISTICS_set (stats,
4122                              gettext_noop ("# bytes dropped (duplicates)"),
4123                              size,
4124                              GNUNET_NO);      
4125       return;
4126     }
4127   if ((n->last_sequence_number_received > snum) &&
4128       (n->last_sequence_number_received - snum > 32))
4129     {
4130       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4131                   "Received ancient out of sequence message, ignoring.\n");
4132       /* ancient out of sequence, ignore */
4133       GNUNET_STATISTICS_set (stats,
4134                              gettext_noop ("# bytes dropped (out of sequence)"),
4135                              size,
4136                              GNUNET_NO);      
4137       return;
4138     }
4139   if (n->last_sequence_number_received > snum)
4140     {
4141       unsigned int rotbit =
4142         1 << (n->last_sequence_number_received - snum - 1);
4143       if ((n->last_packets_bitmap & rotbit) != 0)
4144         {
4145           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4146                       "Received duplicate message, ignoring.\n");
4147           GNUNET_STATISTICS_set (stats,
4148                                  gettext_noop ("# bytes dropped (duplicates)"),
4149                                  size,
4150                                  GNUNET_NO);      
4151           /* duplicate, ignore */
4152           return;
4153         }
4154       n->last_packets_bitmap |= rotbit;
4155     }
4156   if (n->last_sequence_number_received < snum)
4157     {
4158       int shift = (snum - n->last_sequence_number_received);
4159       if (shift >= 8 * sizeof(n->last_packets_bitmap))
4160         n->last_packets_bitmap = 0;
4161       else
4162         n->last_packets_bitmap <<= shift;
4163       n->last_sequence_number_received = snum;
4164     }
4165
4166   /* check timestamp */
4167   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
4168   if (GNUNET_TIME_absolute_get_duration (t).rel_value > MAX_MESSAGE_AGE.rel_value)
4169     {
4170       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4171                   _
4172                   ("Message received far too old (%llu ms). Content ignored.\n"),
4173                   GNUNET_TIME_absolute_get_duration (t).rel_value);
4174       GNUNET_STATISTICS_set (stats,
4175                              gettext_noop ("# bytes dropped (ancient message)"),
4176                              size,
4177                              GNUNET_NO);      
4178       return;
4179     }
4180
4181   /* process decrypted message(s) */
4182   if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
4183     {
4184 #if DEBUG_CORE_SET_QUOTA
4185       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4186                   "Received %u b/s as new inbound limit for peer `%4s'\n",
4187                   (unsigned int) ntohl (pt->inbound_bw_limit.value__),
4188                   GNUNET_i2s (&n->peer));
4189 #endif
4190       n->bw_out_external_limit = pt->inbound_bw_limit;
4191       n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
4192                                               n->bw_out_internal_limit);
4193       GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
4194                                              n->bw_out);
4195       GNUNET_TRANSPORT_set_quota (transport,
4196                                   &n->peer,
4197                                   n->bw_in,
4198                                   n->bw_out,
4199                                   GNUNET_TIME_UNIT_FOREVER_REL,
4200                                   NULL, NULL); 
4201     }
4202   n->last_activity = GNUNET_TIME_absolute_get ();
4203   if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
4204     GNUNET_SCHEDULER_cancel (n->keep_alive_task);
4205   n->keep_alive_task 
4206     = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
4207                                     &send_keep_alive,
4208                                     n);
4209   GNUNET_STATISTICS_set (stats,
4210                          gettext_noop ("# bytes of payload decrypted"),
4211                          size - sizeof (struct EncryptedMessage),
4212                          GNUNET_NO);
4213   handle_peer_status_change (n);
4214   update_neighbour_performance (n, ats, ats_count);
4215   if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst, 
4216                                               n,
4217                                               &buf[sizeof (struct EncryptedMessage)], 
4218                                               size - sizeof (struct EncryptedMessage),
4219                                               GNUNET_YES, GNUNET_NO))
4220     GNUNET_break_op (0);
4221 }
4222
4223
4224 /**
4225  * Function called by the transport for each received message.
4226  *
4227  * @param cls closure
4228  * @param peer (claimed) identity of the other peer
4229  * @param message the message
4230  * @param ats performance data
4231  * @param ats_count number of entries in ats (excluding 0-termination)
4232  */
4233 static void
4234 handle_transport_receive (void *cls,
4235                           const struct GNUNET_PeerIdentity *peer,
4236                           const struct GNUNET_MessageHeader *message,
4237                           const struct GNUNET_TRANSPORT_ATS_Information *ats, 
4238                           uint32_t ats_count)
4239 {
4240   struct Neighbour *n;
4241   struct GNUNET_TIME_Absolute now;
4242   int up;
4243   uint16_t type;
4244   uint16_t size;
4245   int changed;
4246
4247 #if DEBUG_CORE
4248   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4249               "Received message of type %u from `%4s', demultiplexing.\n",
4250               (unsigned int) ntohs (message->type), 
4251               GNUNET_i2s (peer));
4252 #endif
4253   if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4254     {
4255       GNUNET_break (0);
4256       return;
4257     }
4258   n = find_neighbour (peer);
4259   if (n == NULL)
4260     n = create_neighbour (peer);
4261   changed = GNUNET_NO;
4262   up = (n->status == PEER_STATE_KEY_CONFIRMED);
4263   type = ntohs (message->type);
4264   size = ntohs (message->size);
4265   switch (type)
4266     {
4267     case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
4268       if (size != sizeof (struct SetKeyMessage))
4269         {
4270           GNUNET_break_op (0);
4271           return;
4272         }
4273       GNUNET_STATISTICS_update (stats,
4274                                 gettext_noop ("# session keys received"), 
4275                                 1, 
4276                                 GNUNET_NO);
4277       handle_set_key (n,
4278                       (const struct SetKeyMessage *) message,
4279                       ats, ats_count);
4280       break;
4281     case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
4282       if (size < sizeof (struct EncryptedMessage) +
4283           sizeof (struct GNUNET_MessageHeader))
4284         {
4285           GNUNET_break_op (0);
4286           return;
4287         }
4288       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
4289           (n->status != PEER_STATE_KEY_CONFIRMED))
4290         {
4291           GNUNET_STATISTICS_update (stats,
4292                                     gettext_noop ("# failed to decrypt message (no session key)"), 
4293                                     1, 
4294                                     GNUNET_NO);
4295           send_key (n);
4296           return;
4297         }
4298       handle_encrypted_message (n, 
4299                                 (const struct EncryptedMessage *) message,
4300                                 ats, ats_count);
4301       break;
4302     case GNUNET_MESSAGE_TYPE_CORE_PING:
4303       if (size != sizeof (struct PingMessage))
4304         {
4305           GNUNET_break_op (0);
4306           return;
4307         }
4308       GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
4309       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
4310           (n->status != PEER_STATE_KEY_CONFIRMED))
4311         {
4312 #if DEBUG_CORE
4313           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4314                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
4315                       "PING", GNUNET_i2s (&n->peer));
4316 #endif
4317           GNUNET_free_non_null (n->pending_ping);
4318           n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
4319           memcpy (n->pending_ping, message, sizeof (struct PingMessage));
4320           return;
4321         }
4322       handle_ping (n, (const struct PingMessage *) message,
4323                    ats, ats_count);
4324       break;
4325     case GNUNET_MESSAGE_TYPE_CORE_PONG:
4326       if (size != sizeof (struct PongMessage))
4327         {
4328           GNUNET_break_op (0);
4329           return;
4330         }
4331       GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
4332       if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
4333            (n->status != PEER_STATE_KEY_CONFIRMED) )
4334         {
4335 #if DEBUG_CORE
4336           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4337                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
4338                       "PONG", GNUNET_i2s (&n->peer));
4339 #endif
4340           GNUNET_free_non_null (n->pending_pong);
4341           n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
4342           memcpy (n->pending_pong, message, sizeof (struct PongMessage));
4343           return;
4344         }
4345       handle_pong (n, (const struct PongMessage *) message,
4346                    ats, ats_count);
4347       break;
4348     default:
4349       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4350                   _("Unsupported message of type %u received.\n"),
4351                   (unsigned int) type);
4352       return;
4353     }
4354   if (n->status == PEER_STATE_KEY_CONFIRMED)
4355     {
4356       now = GNUNET_TIME_absolute_get ();
4357       n->last_activity = now;
4358       changed = GNUNET_YES;
4359       if (!up)
4360         {
4361           GNUNET_STATISTICS_update (stats, 
4362                                     gettext_noop ("# established sessions"), 
4363                                     1, 
4364                                     GNUNET_NO);
4365           n->time_established = now;
4366         }
4367       if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
4368         GNUNET_SCHEDULER_cancel (n->keep_alive_task);
4369       n->keep_alive_task 
4370         = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
4371                                         &send_keep_alive,
4372                                         n);
4373     }
4374   if (changed)
4375     handle_peer_status_change (n);
4376 }
4377
4378
4379 /**
4380  * Function that recalculates the bandwidth quota for the
4381  * given neighbour and transmits it to the transport service.
4382  * 
4383  * @param cls neighbour for the quota update
4384  * @param tc context
4385  */
4386 static void
4387 neighbour_quota_update (void *cls,
4388                         const struct GNUNET_SCHEDULER_TaskContext *tc)
4389 {
4390   struct Neighbour *n = cls;
4391   struct GNUNET_BANDWIDTH_Value32NBO q_in;
4392   struct GNUNET_BANDWIDTH_Value32NBO q_out;
4393   struct GNUNET_BANDWIDTH_Value32NBO q_out_min;
4394   double pref_rel;
4395   double share;
4396   unsigned long long distributable;
4397   uint64_t need_per_peer;
4398   uint64_t need_per_second;
4399   unsigned int neighbour_count;
4400
4401 #if DEBUG_CORE
4402   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4403               "Neighbour quota update calculation running for peer `%4s'\n",
4404               GNUNET_i2s (&n->peer));  
4405 #endif
4406   n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
4407   /* calculate relative preference among all neighbours;
4408      divides by a bit more to avoid division by zero AND to
4409      account for possibility of new neighbours joining any time 
4410      AND to convert to double... */
4411   neighbour_count = GNUNET_CONTAINER_multihashmap_size (neighbours);
4412   if (neighbour_count == 0)
4413     return;
4414   if (preference_sum == 0)
4415     {
4416       pref_rel = 1.0 / (double) neighbour_count;
4417     }
4418   else
4419     {
4420       pref_rel = n->current_preference / preference_sum;
4421     }
4422   need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
4423                                                               GNUNET_TIME_UNIT_SECONDS);  
4424   need_per_second = need_per_peer * neighbour_count;
4425
4426   /* calculate inbound bandwidth per peer */
4427   distributable = 0;
4428   if (bandwidth_target_in_bps > need_per_second)
4429     distributable = bandwidth_target_in_bps - need_per_second;
4430   share = distributable * pref_rel;
4431   if (share + need_per_peer > UINT32_MAX)
4432     q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4433   else
4434     q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4435
4436   /* calculate outbound bandwidth per peer */
4437   distributable = 0;
4438   if (bandwidth_target_out_bps > need_per_second)
4439     distributable = bandwidth_target_out_bps - need_per_second;
4440   share = distributable * pref_rel;
4441   if (share + need_per_peer > UINT32_MAX)
4442     q_out = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4443   else
4444     q_out = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4445   n->bw_out_internal_limit = q_out;
4446
4447   q_out_min = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit, n->bw_out_internal_limit);
4448   GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window, n->bw_out);
4449
4450   /* check if we want to disconnect for good due to inactivity */
4451   if ( (GNUNET_TIME_absolute_get_duration (get_neighbour_timeout (n)).rel_value > 0) &&
4452        (GNUNET_TIME_absolute_get_duration (n->time_established).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) )
4453     {
4454 #if DEBUG_CORE
4455       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4456                   "Forcing disconnect of `%4s' due to inactivity\n",
4457                   GNUNET_i2s (&n->peer));
4458 #endif
4459       q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
4460     }
4461 #if DEBUG_CORE_QUOTA
4462   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4463               "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
4464               GNUNET_i2s (&n->peer),
4465               (unsigned int) ntohl (q_in.value__),
4466               bandwidth_target_out_bps,
4467               (unsigned int) ntohl (n->bw_in.value__),
4468               (unsigned int) ntohl (n->bw_out.value__),
4469               (unsigned int) ntohl (n->bw_out_internal_limit.value__));
4470   #endif
4471   if ((n->bw_in.value__ != q_in.value__) || (n->bw_out.value__ != q_out_min.value__))
4472     {
4473           if (n->bw_in.value__ != q_in.value__)
4474                   n->bw_in = q_in;
4475           if (n->bw_out.value__ != q_out_min.value__)
4476                   n->bw_out = q_out_min;
4477       if (GNUNET_YES == n->is_connected)
4478         GNUNET_TRANSPORT_set_quota (transport,
4479                                     &n->peer,
4480                                     n->bw_in,
4481                                     n->bw_out,
4482                                     GNUNET_TIME_UNIT_FOREVER_REL,
4483                                     NULL, NULL);
4484       handle_peer_status_change (n);
4485     }
4486   schedule_quota_update (n);
4487 }
4488
4489
4490 /**
4491  * Function called by transport to notify us that
4492  * a peer connected to us (on the network level).
4493  *
4494  * @param cls closure
4495  * @param peer the peer that connected
4496  * @param ats performance data
4497  * @param ats_count number of entries in ats (excluding 0-termination)
4498  */
4499 static void
4500 handle_transport_notify_connect (void *cls,
4501                                  const struct GNUNET_PeerIdentity *peer,
4502                                  const struct GNUNET_TRANSPORT_ATS_Information *ats,
4503                                  uint32_t ats_count)
4504 {
4505   struct Neighbour *n;
4506
4507   if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4508     {
4509       GNUNET_break (0);
4510       return;
4511     }
4512   n = find_neighbour (peer);
4513   if (n != NULL)
4514     {
4515       if (GNUNET_YES == n->is_connected)
4516         {
4517           /* duplicate connect notification!? */
4518           GNUNET_break (0);
4519           return;
4520         }
4521     }
4522   else
4523     {
4524       n = create_neighbour (peer);
4525     }
4526   GNUNET_STATISTICS_update (stats, 
4527                             gettext_noop ("# peers connected (transport)"), 
4528                             1, 
4529                             GNUNET_NO);
4530   n->is_connected = GNUNET_YES;      
4531   update_neighbour_performance (n, ats, ats_count);
4532   GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
4533                                  n->bw_out,
4534                                  MAX_WINDOW_TIME_S);
4535   GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
4536                                  n->bw_in,
4537                                  MAX_WINDOW_TIME_S);  
4538 #if DEBUG_CORE
4539   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4540               "Received connection from `%4s'.\n",
4541               GNUNET_i2s (&n->peer));
4542 #endif
4543   GNUNET_TRANSPORT_set_quota (transport,
4544                               &n->peer,
4545                               n->bw_in,
4546                               n->bw_out,
4547                               GNUNET_TIME_UNIT_FOREVER_REL,
4548                               NULL, NULL);
4549   send_key (n); 
4550 }
4551
4552
4553 /**
4554  * Function called by transport telling us that a peer
4555  * disconnected.
4556  *
4557  * @param cls closure
4558  * @param peer the peer that disconnected
4559  */
4560 static void
4561 handle_transport_notify_disconnect (void *cls,
4562                                     const struct GNUNET_PeerIdentity *peer)
4563 {
4564   struct DisconnectNotifyMessage cnm;
4565   struct Neighbour *n;
4566   struct ClientActiveRequest *car;
4567   struct GNUNET_TIME_Relative left;
4568
4569 #if DEBUG_CORE
4570   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4571               "Peer `%4s' disconnected from us; received notification from transport.\n", 
4572               GNUNET_i2s (peer));
4573 #endif
4574   n = find_neighbour (peer);
4575   if (n == NULL)
4576     {
4577       GNUNET_break (0);
4578       return;
4579     }
4580   GNUNET_break (n->is_connected == GNUNET_YES);
4581   if (n->status == PEER_STATE_KEY_CONFIRMED)
4582     {
4583       cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
4584       cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
4585       cnm.reserved = htonl (0);
4586       cnm.peer = *peer;
4587       send_to_all_clients (&cnm.header, GNUNET_NO, GNUNET_CORE_OPTION_SEND_DISCONNECT);
4588       GNUNET_STATISTICS_update (stats, 
4589                                 gettext_noop ("# established sessions"), 
4590                                 -1, 
4591                                 GNUNET_NO);
4592     }
4593
4594   /* On transport disconnect transport doesn't cancel requests, so must do so here. */
4595   if (n->th != NULL)
4596     {
4597       GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
4598       n->th = NULL;
4599     }
4600   n->is_connected = GNUNET_NO;
4601   n->status = PEER_STATE_DOWN;
4602   while (NULL != (car = n->active_client_request_head))
4603     {
4604       GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
4605                                    n->active_client_request_tail,
4606                                    car);
4607       GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
4608                                             &n->peer.hashPubKey,
4609                                             car);
4610       GNUNET_free (car);
4611     }
4612
4613   GNUNET_STATISTICS_update (stats, 
4614                             gettext_noop ("# peers connected (transport)"), 
4615                             -1, 
4616                             GNUNET_NO);
4617   if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
4618     GNUNET_SCHEDULER_cancel (n->dead_clean_task);
4619   left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4620                                         GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
4621   n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (), 
4622                                                     left);
4623   n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
4624                                                      &consider_free_task,
4625                                                      n);
4626 }
4627
4628
4629 /**
4630  * Wrapper around 'free_neighbour'; helper for 'cleaning_task'.
4631  */
4632 static int
4633 free_neighbour_helper (void *cls,
4634                        const GNUNET_HashCode *key,
4635                        void *value)
4636 {
4637   struct Neighbour *n = value;
4638
4639   free_neighbour (n);
4640   return GNUNET_OK;
4641 }
4642
4643
4644 /**
4645  * Last task run during shutdown.  Disconnects us from
4646  * the transport.
4647  */
4648 static void
4649 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4650 {
4651   struct Client *c;
4652
4653 #if DEBUG_CORE
4654   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4655               "Core service shutting down.\n");
4656 #endif
4657   GNUNET_CONTAINER_multihashmap_iterate (neighbours,
4658                                          &free_neighbour_helper,
4659                                          NULL);
4660   GNUNET_CONTAINER_multihashmap_destroy (neighbours);
4661   neighbours = NULL;
4662   GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), 0, GNUNET_NO);
4663   GNUNET_assert (transport != NULL);
4664   GNUNET_TRANSPORT_disconnect (transport);
4665   transport = NULL;
4666   GNUNET_SERVER_notification_context_destroy (notifier);
4667   notifier = NULL;
4668   while (NULL != (c = clients))
4669     handle_client_disconnect (NULL, c->client_handle);
4670   if (my_private_key != NULL)
4671     GNUNET_CRYPTO_rsa_key_free (my_private_key);
4672   if (stats != NULL)
4673     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4674   if (peerinfo != NULL)
4675     GNUNET_PEERINFO_disconnect (peerinfo);
4676   if (mst != NULL)
4677     GNUNET_SERVER_mst_destroy (mst);
4678 }
4679
4680
4681 /**
4682  * Initiate core service.
4683  *
4684  * @param cls closure
4685  * @param server the initialized server
4686  * @param c configuration to use
4687  */
4688 static void
4689 run (void *cls,
4690      struct GNUNET_SERVER_Handle *server,
4691      const struct GNUNET_CONFIGURATION_Handle *c)
4692 {
4693   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4694     {&handle_client_init, NULL,
4695      GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
4696     {&handle_client_iterate_peers, NULL,
4697      GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
4698      sizeof (struct GNUNET_MessageHeader)},
4699     {&handle_client_have_peer, NULL,
4700      GNUNET_MESSAGE_TYPE_CORE_PEER_CONNECTED,
4701      sizeof (struct GNUNET_MessageHeader) + sizeof(struct GNUNET_PeerIdentity)},
4702     {&handle_client_request_info, NULL,
4703      GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
4704      sizeof (struct RequestInfoMessage)},
4705     {&handle_client_send_request, NULL,
4706      GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST,
4707      sizeof (struct SendMessageRequest)},
4708     {&handle_client_send, NULL,
4709      GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
4710     {&handle_client_request_connect, NULL,
4711      GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
4712      sizeof (struct ConnectMessage)},
4713     {NULL, NULL, 0, 0}
4714   };
4715   char *keyfile;
4716
4717   cfg = c;    
4718   /* parse configuration */
4719   if (
4720        (GNUNET_OK !=
4721         GNUNET_CONFIGURATION_get_value_number (c,
4722                                                "CORE",
4723                                                "TOTAL_QUOTA_IN",
4724                                                &bandwidth_target_in_bps)) ||
4725        (GNUNET_OK !=
4726         GNUNET_CONFIGURATION_get_value_number (c,
4727                                                "CORE",
4728                                                "TOTAL_QUOTA_OUT",
4729                                                &bandwidth_target_out_bps)) ||
4730        (GNUNET_OK !=
4731         GNUNET_CONFIGURATION_get_value_filename (c,
4732                                                  "GNUNETD",
4733                                                  "HOSTKEY", &keyfile)))
4734     {
4735       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4736                   _
4737                   ("Core service is lacking key configuration settings.  Exiting.\n"));
4738       GNUNET_SCHEDULER_shutdown ();
4739       return;
4740     }
4741   peerinfo = GNUNET_PEERINFO_connect (cfg);
4742   if (NULL == peerinfo)
4743     {
4744       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4745                   _("Could not access PEERINFO service.  Exiting.\n"));
4746       GNUNET_SCHEDULER_shutdown ();
4747       GNUNET_free (keyfile);
4748       return;
4749     }
4750   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4751   GNUNET_free (keyfile);
4752   if (my_private_key == NULL)
4753     {
4754       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4755                   _("Core service could not access hostkey.  Exiting.\n"));
4756       GNUNET_PEERINFO_disconnect (peerinfo);
4757       GNUNET_SCHEDULER_shutdown ();
4758       return;
4759     }
4760   neighbours = GNUNET_CONTAINER_multihashmap_create (128);
4761   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4762   GNUNET_CRYPTO_hash (&my_public_key,
4763                       sizeof (my_public_key), &my_identity.hashPubKey);
4764   self.public_key = &my_public_key;
4765   self.peer = my_identity;
4766   self.last_activity = GNUNET_TIME_UNIT_FOREVER_ABS;
4767   self.status = PEER_STATE_KEY_CONFIRMED;
4768   self.is_connected = GNUNET_YES;
4769   /* setup notification */
4770   notifier = GNUNET_SERVER_notification_context_create (server, 
4771                                                         MAX_NOTIFY_QUEUE);
4772   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4773   /* setup transport connection */
4774   transport = GNUNET_TRANSPORT_connect (cfg,
4775                                         &my_identity,
4776                                         NULL,
4777                                         &handle_transport_receive,
4778                                         &handle_transport_notify_connect,
4779                                         &handle_transport_notify_disconnect);
4780   GNUNET_assert (NULL != transport);
4781   stats = GNUNET_STATISTICS_create ("core", cfg);
4782
4783   GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded CORE_SEND requests"), 0, GNUNET_NO);
4784   GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 0, GNUNET_NO);
4785
4786   mst = GNUNET_SERVER_mst_create (&deliver_message,
4787                                   NULL);
4788   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4789                                 &cleaning_task, NULL);
4790   /* process client requests */
4791   GNUNET_SERVER_add_handlers (server, handlers);
4792   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4793               _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
4794 }
4795
4796
4797
4798 /**
4799  * The main function for the transport service.
4800  *
4801  * @param argc number of arguments from the command line
4802  * @param argv command line arguments
4803  * @return 0 ok, 1 on error
4804  */
4805 int
4806 main (int argc, char *const *argv)
4807 {
4808   return (GNUNET_OK ==
4809           GNUNET_SERVICE_run (argc,
4810                               argv,
4811                               "core",
4812                               GNUNET_SERVICE_OPTION_NONE,
4813                               &run, NULL)) ? 0 : 1;
4814 }
4815
4816 /* end of gnunet-service-core.c */