die strtok_r
[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 static int
1438 queue_connect_message (void *cls,
1439                        const GNUNET_HashCode *key,
1440                        void *value)
1441 {
1442   struct GNUNET_SERVER_TransmitContext *tc = cls;
1443   struct Neighbour *n = value;
1444   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1445   struct GNUNET_TRANSPORT_ATS_Information *ats;
1446   size_t size;
1447   struct ConnectNotifyMessage *cnm;
1448
1449   cnm = (struct ConnectNotifyMessage*) buf;
1450   if (n->status != PEER_STATE_KEY_CONFIRMED)
1451     return GNUNET_OK;
1452   size = sizeof (struct ConnectNotifyMessage) +
1453     (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1454   if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1455     {
1456       GNUNET_break (0);
1457       /* recovery strategy: throw away performance data */
1458       GNUNET_array_grow (n->ats,
1459                          n->ats_count,
1460                          0);
1461       size = sizeof (struct PeerStatusNotifyMessage) +
1462         n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1463     }
1464   cnm = (struct ConnectNotifyMessage*) buf;
1465   cnm->header.size = htons (size);
1466   cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1467   cnm->ats_count = htonl (n->ats_count);
1468   ats = &cnm->ats;
1469   memcpy (ats,
1470           n->ats,
1471           n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
1472   ats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
1473   ats[n->ats_count].value = htonl (0);    
1474 #if DEBUG_CORE_CLIENT
1475   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1476               "Sending `%s' message to client.\n",
1477               "NOTIFY_CONNECT");
1478 #endif
1479   cnm->peer = n->peer;
1480   GNUNET_SERVER_transmit_context_append_message (tc, 
1481                                                  &cnm->header);
1482   return GNUNET_OK;
1483 }
1484
1485
1486 /**
1487  * Handle CORE_ITERATE_PEERS request.
1488  *
1489  * @param cls unused
1490  * @param client client sending the iteration request
1491  * @param message iteration request message
1492  */
1493 static void
1494 handle_client_iterate_peers (void *cls,
1495                              struct GNUNET_SERVER_Client *client,
1496                              const struct GNUNET_MessageHeader *message)
1497
1498 {
1499   struct GNUNET_MessageHeader done_msg;
1500   struct GNUNET_SERVER_TransmitContext *tc;
1501   int msize;
1502   /* notify new client about existing neighbours */
1503
1504   msize = ntohs(message->size);
1505   tc = GNUNET_SERVER_transmit_context_create (client);
1506   if (msize == sizeof(struct GNUNET_MessageHeader))
1507     GNUNET_CONTAINER_multihashmap_iterate (neighbours, &queue_connect_message, tc);
1508   else
1509     GNUNET_break(0);
1510
1511   done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
1512   done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
1513   GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
1514   GNUNET_SERVER_transmit_context_run (tc,
1515                                       GNUNET_TIME_UNIT_FOREVER_REL);
1516 }
1517
1518 /**
1519  * Handle CORE_ITERATE_PEERS request.
1520  *
1521  * @param cls unused
1522  * @param client client sending the iteration request
1523  * @param message iteration request message
1524  */
1525 static void
1526 handle_client_have_peer (void *cls,
1527                              struct GNUNET_SERVER_Client *client,
1528                              const struct GNUNET_MessageHeader *message)
1529
1530 {
1531   struct GNUNET_MessageHeader done_msg;
1532   struct GNUNET_SERVER_TransmitContext *tc;
1533   struct GNUNET_PeerIdentity *peer;
1534   int msize;
1535   /* notify new client about existing neighbours */
1536
1537   msize = ntohs(message->size);
1538   tc = GNUNET_SERVER_transmit_context_create (client);
1539
1540   peer = (struct GNUNET_PeerIdentity *)&message[1];
1541   GNUNET_CONTAINER_multihashmap_get_multiple(neighbours, &peer->hashPubKey, &queue_connect_message, tc);
1542
1543   done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
1544   done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
1545   GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
1546   GNUNET_SERVER_transmit_context_run (tc,
1547                                       GNUNET_TIME_UNIT_FOREVER_REL);
1548 }
1549
1550
1551 /**
1552  * Handle REQUEST_INFO request.
1553  */
1554 static void
1555 handle_client_request_info (void *cls,
1556                             struct GNUNET_SERVER_Client *client,
1557                             const struct GNUNET_MessageHeader *message)
1558 {
1559   const struct RequestInfoMessage *rcm;
1560   struct Client *pos;
1561   struct Neighbour *n;
1562   struct ConfigurationInfoMessage cim;
1563   int32_t want_reserv;
1564   int32_t got_reserv;
1565   unsigned long long old_preference;
1566
1567 #if DEBUG_CORE_CLIENT
1568   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1569               "Core service receives `%s' request.\n", "REQUEST_INFO");
1570 #endif
1571   pos = clients;
1572   while (pos != NULL)
1573     {
1574       if (client == pos->client_handle)
1575         break;
1576       pos = pos->next;
1577     }
1578   if (pos == NULL)
1579     {
1580       GNUNET_break (0);
1581       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1582       return;
1583     }
1584
1585   rcm = (const struct RequestInfoMessage *) message;
1586   n = find_neighbour (&rcm->peer);
1587   memset (&cim, 0, sizeof (cim));
1588   if (n != NULL) 
1589     {
1590       want_reserv = ntohl (rcm->reserve_inbound);
1591       if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1592         {
1593           n->bw_out_internal_limit = rcm->limit_outbound;
1594           if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1595                                                                n->bw_out_external_limit).value__)
1596             {
1597               n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1598                                                       n->bw_out_external_limit);
1599               GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1600                                                      n->bw_out);
1601               GNUNET_TRANSPORT_set_quota (transport,
1602                                           &n->peer,
1603                                           n->bw_in,
1604                                           n->bw_out,
1605                                           GNUNET_TIME_UNIT_FOREVER_REL,
1606                                           NULL, NULL); 
1607               handle_peer_status_change (n);
1608             }
1609         }
1610       if (want_reserv < 0)
1611         {
1612           got_reserv = want_reserv;
1613         }
1614       else if (want_reserv > 0)
1615         {
1616           if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1617                                                   want_reserv).rel_value == 0)
1618             got_reserv = want_reserv;
1619           else
1620             got_reserv = 0; /* all or nothing */
1621         }
1622       else
1623         got_reserv = 0;
1624       GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1625                                         got_reserv);
1626       old_preference = n->current_preference;
1627       n->current_preference += GNUNET_ntohll(rcm->preference_change);
1628       if (old_preference > n->current_preference) 
1629         {
1630           /* overflow; cap at maximum value */
1631           n->current_preference = ULLONG_MAX;
1632         }
1633       update_preference_sum (n->current_preference - old_preference);
1634 #if DEBUG_CORE_QUOTA
1635       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1636                   "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1637                   (int) want_reserv,
1638                   GNUNET_i2s (&rcm->peer),
1639                   (int) got_reserv);
1640 #endif
1641       cim.reserved_amount = htonl (got_reserv);
1642       cim.rim_id = rcm->rim_id;
1643       cim.bw_out = n->bw_out;
1644       cim.preference = n->current_preference;
1645     }
1646   cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1647   cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1648   cim.peer = rcm->peer;
1649 #if DEBUG_CORE_CLIENT
1650   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1651               "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1652 #endif
1653   send_to_client (pos, &cim.header, GNUNET_NO);
1654   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1655 }
1656
1657
1658 /**
1659  * Free the given entry for the neighbour (it has
1660  * already been removed from the list at this point).
1661  *
1662  * @param n neighbour to free
1663  */
1664 static void
1665 free_neighbour (struct Neighbour *n)
1666 {
1667   struct MessageEntry *m;
1668   struct ClientActiveRequest *car;
1669
1670 #if DEBUG_CORE
1671   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1672               "Destroying neighbour entry for peer `%4s'\n",
1673               GNUNET_i2s (&n->peer));
1674 #endif
1675   if (n->pitr != NULL)
1676     {
1677       GNUNET_PEERINFO_iterate_cancel (n->pitr);
1678       n->pitr = NULL;
1679     }
1680   if (n->skm != NULL)
1681     {
1682       GNUNET_free (n->skm);
1683       n->skm = NULL;
1684     }
1685   while (NULL != (m = n->messages))
1686     {
1687       n->messages = m->next;
1688       GNUNET_free (m);
1689     }
1690   while (NULL != (m = n->encrypted_head))
1691     {
1692       GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1693                                    n->encrypted_tail,
1694                                    m);
1695       GNUNET_free (m);
1696     }
1697   while (NULL != (car = n->active_client_request_head))
1698     {
1699       GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1700                                    n->active_client_request_tail,
1701                                    car);
1702       GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
1703                                             &n->peer.hashPubKey,
1704                                             car);
1705       GNUNET_free (car);
1706     }
1707   if (NULL != n->th)
1708     {
1709       GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1710       n->th = NULL;
1711     }
1712   if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1713     GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
1714   if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1715     GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
1716   if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1717     GNUNET_SCHEDULER_cancel (n->quota_update_task);
1718   if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1719     GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1720   if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)    
1721       GNUNET_SCHEDULER_cancel (n->keep_alive_task);
1722   if (n->status == PEER_STATE_KEY_CONFIRMED)
1723     GNUNET_STATISTICS_update (stats, 
1724                               gettext_noop ("# established sessions"), 
1725                               -1, 
1726                               GNUNET_NO);
1727   GNUNET_array_grow (n->ats, n->ats_count, 0);
1728   GNUNET_free_non_null (n->public_key);
1729   GNUNET_free_non_null (n->pending_ping);
1730   GNUNET_free_non_null (n->pending_pong);
1731   GNUNET_free (n);
1732 }
1733
1734
1735 /**
1736  * Check if we have encrypted messages for the specified neighbour
1737  * pending, and if so, check with the transport about sending them
1738  * out.
1739  *
1740  * @param n neighbour to check.
1741  */
1742 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1743
1744
1745 /**
1746  * Encrypt size bytes from in and write the result to out.  Use the
1747  * key for outbound traffic of the given neighbour.
1748  *
1749  * @param n neighbour we are sending to
1750  * @param iv initialization vector to use
1751  * @param in ciphertext
1752  * @param out plaintext
1753  * @param size size of in/out
1754  * @return GNUNET_OK on success
1755  */
1756 static int
1757 do_encrypt (struct Neighbour *n,
1758             const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1759             const void *in, void *out, size_t size)
1760 {
1761   if (size != (uint16_t) size)
1762     {
1763       GNUNET_break (0);
1764       return GNUNET_NO;
1765     }
1766   GNUNET_assert (size ==
1767                  GNUNET_CRYPTO_aes_encrypt (in,
1768                                             (uint16_t) size,
1769                                             &n->encrypt_key,
1770                                             iv, out));
1771   GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1772 #if DEBUG_CORE
1773   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1774               "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
1775               (unsigned int) size,
1776               GNUNET_i2s (&n->peer),
1777               (unsigned int) n->encrypt_key.crc32,
1778               GNUNET_CRYPTO_crc32_n (iv, sizeof(iv)));
1779 #endif
1780   return GNUNET_OK;
1781 }
1782
1783
1784 /**
1785  * Consider freeing the given neighbour since we may not need
1786  * to keep it around anymore.
1787  *
1788  * @param n neighbour to consider discarding
1789  */
1790 static void
1791 consider_free_neighbour (struct Neighbour *n);
1792
1793
1794 /**
1795  * Task triggered when a neighbour entry is about to time out 
1796  * (and we should prevent this by sending a PING).
1797  *
1798  * @param cls the 'struct Neighbour'
1799  * @param tc scheduler context (not used)
1800  */
1801 static void
1802 send_keep_alive (void *cls,
1803                  const struct GNUNET_SCHEDULER_TaskContext *tc)
1804 {
1805   struct Neighbour *n = cls;
1806   struct GNUNET_TIME_Relative retry;
1807   struct GNUNET_TIME_Relative left;
1808   struct MessageEntry *me;
1809   struct PingMessage pp;
1810   struct PingMessage *pm;
1811   struct GNUNET_CRYPTO_AesInitializationVector iv;
1812
1813   n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1814   /* send PING */
1815   me = GNUNET_malloc (sizeof (struct MessageEntry) +
1816                       sizeof (struct PingMessage));
1817   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1818   me->priority = PING_PRIORITY;
1819   me->size = sizeof (struct PingMessage);
1820   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1821                                      n->encrypted_tail,
1822                                      n->encrypted_tail,
1823                                      me);
1824   pm = (struct PingMessage *) &me[1];
1825   pm->header.size = htons (sizeof (struct PingMessage));
1826   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1827   pm->iv_seed = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1828       UINT32_MAX);
1829   derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
1830   pp.challenge = n->ping_challenge;
1831   pp.target = n->peer;
1832 #if DEBUG_HANDSHAKE
1833   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1834               "Encrypting `%s' message with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
1835               "PING", 
1836               (unsigned int) n->ping_challenge,
1837               GNUNET_i2s (&n->peer),
1838               (unsigned int) n->encrypt_key.crc32,
1839               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
1840               pm->iv_seed);
1841 #endif
1842   do_encrypt (n,
1843               &iv,
1844               &pp.target,
1845               &pm->target,
1846               sizeof (struct PingMessage) -
1847               ((void *) &pm->target - (void *) pm));
1848   process_encrypted_neighbour_queue (n);
1849   /* reschedule PING job */
1850   left = GNUNET_TIME_absolute_get_remaining (get_neighbour_timeout (n));
1851   retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1852                                     MIN_PING_FREQUENCY);
1853   n->keep_alive_task 
1854     = GNUNET_SCHEDULER_add_delayed (retry,
1855                                     &send_keep_alive,
1856                                     n);
1857
1858 }
1859
1860
1861 /**
1862  * Task triggered when a neighbour entry might have gotten stale.
1863  *
1864  * @param cls the 'struct Neighbour'
1865  * @param tc scheduler context (not used)
1866  */
1867 static void
1868 consider_free_task (void *cls,
1869                     const struct GNUNET_SCHEDULER_TaskContext *tc)
1870 {
1871   struct Neighbour *n = cls;
1872
1873   n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1874   consider_free_neighbour (n);
1875 }
1876
1877
1878 /**
1879  * Consider freeing the given neighbour since we may not need
1880  * to keep it around anymore.
1881  *
1882  * @param n neighbour to consider discarding
1883  */
1884 static void
1885 consider_free_neighbour (struct Neighbour *n)
1886
1887   struct GNUNET_TIME_Relative left;
1888
1889   if ( (n->th != NULL) ||
1890        (n->pitr != NULL) ||
1891        (GNUNET_YES == n->is_connected) )
1892     return; /* no chance */
1893     
1894   left = GNUNET_TIME_absolute_get_remaining (get_neighbour_timeout (n));
1895   if (left.rel_value > 0)
1896     {
1897       if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1898         GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1899       n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (left,
1900                                                          &consider_free_task,
1901                                                          n);
1902       return;
1903     }
1904   /* actually free the neighbour... */
1905   GNUNET_assert (GNUNET_OK ==
1906                  GNUNET_CONTAINER_multihashmap_remove (neighbours,
1907                                                        &n->peer.hashPubKey,
1908                                                        n));
1909   GNUNET_STATISTICS_set (stats,
1910                          gettext_noop ("# neighbour entries allocated"), 
1911                          GNUNET_CONTAINER_multihashmap_size (neighbours),
1912                          GNUNET_NO);
1913   free_neighbour (n);
1914 }
1915
1916
1917 /**
1918  * Function called when the transport service is ready to
1919  * receive an encrypted message for the respective peer
1920  *
1921  * @param cls neighbour to use message from
1922  * @param size number of bytes we can transmit
1923  * @param buf where to copy the message
1924  * @return number of bytes transmitted
1925  */
1926 static size_t
1927 notify_encrypted_transmit_ready (void *cls, 
1928                                  size_t size, 
1929                                  void *buf)
1930 {
1931   struct Neighbour *n = cls;
1932   struct MessageEntry *m;
1933   size_t ret;
1934   char *cbuf;
1935
1936   n->th = NULL;
1937   m = n->encrypted_head;
1938   if (m == NULL)
1939     {
1940 #if DEBUG_CORE
1941       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1942                   "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1943                   GNUNET_i2s (&n->peer));
1944 #endif
1945       return 0;
1946     }
1947   GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1948                                n->encrypted_tail,
1949                                m);
1950   ret = 0;
1951   cbuf = buf;
1952   if (buf != NULL)
1953     {
1954       GNUNET_assert (size >= m->size);
1955       memcpy (cbuf, &m[1], m->size);
1956       ret = m->size;
1957       GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1958                                         m->size);
1959 #if DEBUG_CORE
1960       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1961                   "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1962                   (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1963                   (unsigned int) ret, 
1964                   GNUNET_i2s (&n->peer));
1965 #endif
1966       process_encrypted_neighbour_queue (n);
1967     }
1968   else
1969     {
1970 #if DEBUG_CORE
1971       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1972                   "Transmission of message of type %u and size %u failed\n",
1973                   (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1974                   (unsigned int) m->size);
1975 #endif
1976     }
1977   GNUNET_free (m);
1978   consider_free_neighbour (n);
1979   GNUNET_STATISTICS_update (stats, 
1980                             gettext_noop ("# encrypted bytes given to transport"), 
1981                             ret, 
1982                             GNUNET_NO);
1983   return ret;
1984 }
1985
1986
1987 /**
1988  * Check if we have plaintext messages for the specified neighbour
1989  * pending, and if so, consider batching and encrypting them (and
1990  * then trigger processing of the encrypted queue if needed).
1991  *
1992  * @param n neighbour to check.
1993  */
1994 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1995
1996
1997 /**
1998  * Check if we have encrypted messages for the specified neighbour
1999  * pending, and if so, check with the transport about sending them
2000  * out.
2001  *
2002  * @param n neighbour to check.
2003  */
2004 static void
2005 process_encrypted_neighbour_queue (struct Neighbour *n)
2006 {
2007   struct MessageEntry *m;
2008  
2009   if (n->th != NULL)
2010     return;  /* request already pending */
2011   m = n->encrypted_head;
2012   if (m == NULL)
2013     {
2014       /* encrypted queue empty, try plaintext instead */
2015       process_plaintext_neighbour_queue (n);
2016       return;
2017     }
2018 #if DEBUG_CORE
2019   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2020               "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
2021               (unsigned int) m->size,
2022               GNUNET_i2s (&n->peer),
2023               (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).rel_value);
2024 #endif
2025   n->th =
2026     GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
2027                                             m->size,
2028                                             m->priority,
2029                                             GNUNET_TIME_absolute_get_remaining
2030                                             (m->deadline),
2031                                             &notify_encrypted_transmit_ready,
2032                                             n);
2033   if (n->th == NULL)
2034     {
2035       /* message request too large or duplicate request */
2036       GNUNET_break (0);
2037       /* discard encrypted message */
2038       GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2039                                    n->encrypted_tail,
2040                                    m);
2041       GNUNET_free (m);
2042       process_encrypted_neighbour_queue (n);
2043     }
2044 }
2045
2046
2047 /**
2048  * Decrypt size bytes from in and write the result to out.  Use the
2049  * key for inbound traffic of the given neighbour.  This function does
2050  * NOT do any integrity-checks on the result.
2051  *
2052  * @param n neighbour we are receiving from
2053  * @param iv initialization vector to use
2054  * @param in ciphertext
2055  * @param out plaintext
2056  * @param size size of in/out
2057  * @return GNUNET_OK on success
2058  */
2059 static int
2060 do_decrypt (struct Neighbour *n,
2061             const struct GNUNET_CRYPTO_AesInitializationVector * iv,
2062             const void *in, void *out, size_t size)
2063 {
2064   if (size != (uint16_t) size)
2065     {
2066       GNUNET_break (0);
2067       return GNUNET_NO;
2068     }
2069   if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2070       (n->status != PEER_STATE_KEY_CONFIRMED))
2071     {
2072       GNUNET_break_op (0);
2073       return GNUNET_SYSERR;
2074     }
2075   if (size !=
2076       GNUNET_CRYPTO_aes_decrypt (in,
2077                                  (uint16_t) size,
2078                                  &n->decrypt_key,
2079                                  iv,
2080                                  out))
2081     {
2082       GNUNET_break (0);
2083       return GNUNET_SYSERR;
2084     }
2085   GNUNET_STATISTICS_update (stats, 
2086                             gettext_noop ("# bytes decrypted"), 
2087                             size, 
2088                             GNUNET_NO);
2089 #if DEBUG_CORE
2090   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2091               "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
2092               (unsigned int) size, 
2093               GNUNET_i2s (&n->peer),
2094               (unsigned int) n->decrypt_key.crc32,
2095               GNUNET_CRYPTO_crc32_n (iv, sizeof(*iv)));
2096 #endif
2097   return GNUNET_OK;
2098 }
2099
2100
2101 /**
2102  * Select messages for transmission.  This heuristic uses a combination
2103  * of earliest deadline first (EDF) scheduling (with bounded horizon)
2104  * and priority-based discard (in case no feasible schedule exist) and
2105  * speculative optimization (defer any kind of transmission until
2106  * we either create a batch of significant size, 25% of max, or until
2107  * we are close to a deadline).  Furthermore, when scheduling the
2108  * heuristic also packs as many messages into the batch as possible,
2109  * starting with those with the earliest deadline.  Yes, this is fun.
2110  *
2111  * @param n neighbour to select messages from
2112  * @param size number of bytes to select for transmission
2113  * @param retry_time set to the time when we should try again
2114  *        (only valid if this function returns zero)
2115  * @return number of bytes selected, or 0 if we decided to
2116  *         defer scheduling overall; in that case, retry_time is set.
2117  */
2118 static size_t
2119 select_messages (struct Neighbour *n,
2120                  size_t size, struct GNUNET_TIME_Relative *retry_time)
2121 {
2122   struct MessageEntry *pos;
2123   struct MessageEntry *min;
2124   struct MessageEntry *last;
2125   unsigned int min_prio;
2126   struct GNUNET_TIME_Absolute t;
2127   struct GNUNET_TIME_Absolute now;
2128   struct GNUNET_TIME_Relative delta;
2129   uint64_t avail;
2130   struct GNUNET_TIME_Relative slack;     /* how long could we wait before missing deadlines? */
2131   size_t off;
2132   uint64_t tsize;
2133   unsigned int queue_size;
2134   int discard_low_prio;
2135
2136   GNUNET_assert (NULL != n->messages);
2137   now = GNUNET_TIME_absolute_get ();
2138   /* last entry in linked list of messages processed */
2139   last = NULL;
2140   /* should we remove the entry with the lowest
2141      priority from consideration for scheduling at the
2142      end of the loop? */
2143   queue_size = 0;
2144   tsize = 0;
2145   pos = n->messages;
2146   while (pos != NULL)
2147     {
2148       queue_size++;
2149       tsize += pos->size;
2150       pos = pos->next;
2151     }
2152   discard_low_prio = GNUNET_YES;
2153   while (GNUNET_YES == discard_low_prio)
2154     {
2155       min = NULL;
2156       min_prio = UINT_MAX;
2157       discard_low_prio = GNUNET_NO;
2158       /* calculate number of bytes available for transmission at time "t" */
2159       avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
2160       t = now;
2161       /* how many bytes have we (hypothetically) scheduled so far */
2162       off = 0;
2163       /* maximum time we can wait before transmitting anything
2164          and still make all of our deadlines */
2165       slack = GNUNET_TIME_UNIT_FOREVER_REL;
2166       pos = n->messages;
2167       /* note that we use "*2" here because we want to look
2168          a bit further into the future; much more makes no
2169          sense since new message might be scheduled in the
2170          meantime... */
2171       while ((pos != NULL) && (off < size * 2))
2172         {         
2173           if (pos->do_transmit == GNUNET_YES)
2174             {
2175               /* already removed from consideration */
2176               pos = pos->next;
2177               continue;
2178             }
2179           if (discard_low_prio == GNUNET_NO)
2180             {
2181               delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
2182               if (delta.rel_value > 0)
2183                 {
2184                   // FIXME: HUH? Check!
2185                   t = pos->deadline;
2186                   avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
2187                                                                        delta);
2188                 }
2189               if (avail < pos->size)
2190                 {
2191                   // FIXME: HUH? Check!
2192                   discard_low_prio = GNUNET_YES;        /* we could not schedule this one! */
2193                 }
2194               else
2195                 {
2196                   avail -= pos->size;
2197                   /* update slack, considering both its absolute deadline
2198                      and relative deadlines caused by other messages
2199                      with their respective load */
2200                   slack = GNUNET_TIME_relative_min (slack,
2201                                                     GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
2202                                                                                           avail));
2203                   if (pos->deadline.abs_value <= now.abs_value) 
2204                     {
2205                       /* now or never */
2206                       slack = GNUNET_TIME_UNIT_ZERO;
2207                     }
2208                   else if (GNUNET_YES == pos->got_slack)
2209                     {
2210                       /* should be soon now! */
2211                       slack = GNUNET_TIME_relative_min (slack,
2212                                                         GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
2213                     }
2214                   else
2215                     {
2216                       slack =
2217                         GNUNET_TIME_relative_min (slack, 
2218                                                   GNUNET_TIME_absolute_get_difference (now, pos->deadline));
2219                       pos->got_slack = GNUNET_YES;
2220                       pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
2221                                                                       GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
2222                     }
2223                 }
2224             }
2225           off += pos->size;
2226           t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
2227           if (pos->priority <= min_prio)
2228             {
2229               /* update min for discard */
2230               min_prio = pos->priority;
2231               min = pos;
2232             }
2233           pos = pos->next;
2234         }
2235       if (discard_low_prio)
2236         {
2237           GNUNET_assert (min != NULL);
2238           /* remove lowest-priority entry from consideration */
2239           min->do_transmit = GNUNET_YES;        /* means: discard (for now) */
2240         }
2241       last = pos;
2242     }
2243   /* guard against sending "tiny" messages with large headers without
2244      urgent deadlines */
2245   if ( (slack.rel_value > GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value) && 
2246        (size > 4 * off) &&
2247        (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
2248     {
2249       /* less than 25% of message would be filled with deadlines still
2250          being met if we delay by one second or more; so just wait for
2251          more data; but do not wait longer than 1s (since we don't want
2252          to delay messages for a really long time either). */
2253       *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
2254       /* reset do_transmit values for next time */
2255       while (pos != last)
2256         {
2257           pos->do_transmit = GNUNET_NO;   
2258           pos = pos->next;
2259         }
2260       GNUNET_STATISTICS_update (stats, 
2261                                 gettext_noop ("# transmissions delayed due to corking"), 
2262                                 1, GNUNET_NO);
2263 #if DEBUG_CORE
2264       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2265                   "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
2266                   (unsigned long long) retry_time->rel_value,
2267                   (unsigned int) off,
2268                   (unsigned int) size);
2269 #endif
2270       return 0;
2271     }
2272   /* select marked messages (up to size) for transmission */
2273   off = 0;
2274   pos = n->messages;
2275   while (pos != last)
2276     {
2277       if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
2278         {
2279           pos->do_transmit = GNUNET_YES;        /* mark for transmission */
2280           off += pos->size;
2281           size -= pos->size;
2282 #if DEBUG_CORE
2283           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2284                       "Selecting message of size %u for transmission\n",
2285                       (unsigned int) pos->size);
2286 #endif
2287         }
2288       else
2289         {
2290 #if DEBUG_CORE
2291           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2292                       "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
2293                       (unsigned int) pos->size,
2294                       size);
2295 #endif
2296           pos->do_transmit = GNUNET_NO;   /* mark for not transmitting! */
2297         }
2298       pos = pos->next;
2299     }
2300 #if DEBUG_CORE
2301   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2302               "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
2303               (unsigned long long) off, (unsigned long long) tsize,
2304               queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
2305               GNUNET_i2s (&n->peer));
2306 #endif
2307   return off;
2308 }
2309
2310
2311 /**
2312  * Batch multiple messages into a larger buffer.
2313  *
2314  * @param n neighbour to take messages from
2315  * @param buf target buffer
2316  * @param size size of buf
2317  * @param deadline set to transmission deadline for the result
2318  * @param retry_time set to the time when we should try again
2319  *        (only valid if this function returns zero)
2320  * @param priority set to the priority of the batch
2321  * @return number of bytes written to buf (can be zero)
2322  */
2323 static size_t
2324 batch_message (struct Neighbour *n,
2325                char *buf,
2326                size_t size,
2327                struct GNUNET_TIME_Absolute *deadline,
2328                struct GNUNET_TIME_Relative *retry_time,
2329                unsigned int *priority)
2330 {
2331   char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
2332   struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
2333   struct MessageEntry *pos;
2334   struct MessageEntry *prev;
2335   struct MessageEntry *next;
2336   size_t ret;
2337   
2338   ret = 0;
2339   *priority = 0;
2340   *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2341   *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
2342   if (0 == select_messages (n, size, retry_time))
2343     {
2344 #if DEBUG_CORE
2345       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2346                   "No messages selected, will try again in %llu ms\n",
2347                   retry_time->rel_value);
2348 #endif
2349       return 0;
2350     }
2351   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
2352   ntm->ats_count = htonl (0);
2353   ntm->ats.type = htonl (0);
2354   ntm->ats.value = htonl (0);
2355   ntm->peer = n->peer;
2356   pos = n->messages;
2357   prev = NULL;
2358   while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
2359     {
2360       next = pos->next;
2361       if (GNUNET_YES == pos->do_transmit)
2362         {
2363           GNUNET_assert (pos->size <= size);
2364           /* do notifications */
2365           /* FIXME: track if we have *any* client that wants
2366              full notifications and only do this if that is
2367              actually true */
2368           if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
2369             {
2370               memcpy (&ntm[1], &pos[1], pos->size);
2371               ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) + 
2372                                         sizeof (struct GNUNET_MessageHeader));
2373               send_to_all_clients (&ntm->header,
2374                                    GNUNET_YES,
2375                                    GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
2376             }
2377           else
2378             {
2379               /* message too large for 'full' notifications, we do at
2380                  least the 'hdr' type */
2381               memcpy (&ntm[1],
2382                       &pos[1],
2383                       sizeof (struct GNUNET_MessageHeader));
2384             }
2385           ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) + 
2386                                     pos->size);
2387           send_to_all_clients (&ntm->header,
2388                                GNUNET_YES,
2389                                GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);   
2390 #if DEBUG_HANDSHAKE
2391           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2392                       "Encrypting %u bytes with message of type %u and size %u\n",
2393                       pos->size,
2394                       (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
2395                       (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
2396 #endif
2397           /* copy for encrypted transmission */
2398           memcpy (&buf[ret], &pos[1], pos->size);
2399           ret += pos->size;
2400           size -= pos->size;
2401           *priority += pos->priority;
2402 #if DEBUG_CORE
2403           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2404                       "Adding plaintext message of size %u with deadline %llu ms to batch\n",
2405                       (unsigned int) pos->size,
2406                       (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).rel_value);
2407 #endif
2408           deadline->abs_value = GNUNET_MIN (deadline->abs_value, pos->deadline.abs_value);
2409           GNUNET_free (pos);
2410           if (prev == NULL)
2411             n->messages = next;
2412           else
2413             prev->next = next;
2414         }
2415       else
2416         {
2417           prev = pos;
2418         }
2419       pos = next;
2420     }
2421 #if DEBUG_CORE
2422   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2423               "Deadline for message batch is %llu ms\n",
2424               GNUNET_TIME_absolute_get_remaining (*deadline).rel_value);
2425 #endif
2426   return ret;
2427 }
2428
2429
2430 /**
2431  * Remove messages with deadlines that have long expired from
2432  * the queue.
2433  *
2434  * @param n neighbour to inspect
2435  */
2436 static void
2437 discard_expired_messages (struct Neighbour *n)
2438 {
2439   struct MessageEntry *prev;
2440   struct MessageEntry *next;
2441   struct MessageEntry *pos;
2442   struct GNUNET_TIME_Absolute now;
2443   struct GNUNET_TIME_Relative delta;
2444   int disc;
2445
2446   disc = GNUNET_NO;
2447   now = GNUNET_TIME_absolute_get ();
2448   prev = NULL;
2449   pos = n->messages;
2450   while (pos != NULL) 
2451     {
2452       next = pos->next;
2453       delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
2454       if (delta.rel_value > PAST_EXPIRATION_DISCARD_TIME.rel_value)
2455         {
2456 #if DEBUG_CORE
2457           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2458                       "Message is %llu ms past due, discarding.\n",
2459                       delta.rel_value);
2460 #endif
2461           if (prev == NULL)
2462             n->messages = next;
2463           else
2464             prev->next = next;
2465           GNUNET_STATISTICS_update (stats, 
2466                                     gettext_noop ("# messages discarded (expired prior to transmission)"), 
2467                                     1, 
2468                                     GNUNET_NO);
2469           disc = GNUNET_YES;
2470           GNUNET_free (pos);
2471         }
2472       else
2473         prev = pos;
2474       pos = next;
2475     }
2476   if (GNUNET_YES == disc)
2477     schedule_peer_messages (n);
2478 }
2479
2480
2481 /**
2482  * Signature of the main function of a task.
2483  *
2484  * @param cls closure
2485  * @param tc context information (why was this task triggered now)
2486  */
2487 static void
2488 retry_plaintext_processing (void *cls,
2489                             const struct GNUNET_SCHEDULER_TaskContext *tc)
2490 {
2491   struct Neighbour *n = cls;
2492
2493   n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2494   process_plaintext_neighbour_queue (n);
2495 }
2496
2497
2498 /**
2499  * Send our key (and encrypted PING) to the other peer.
2500  *
2501  * @param n the other peer
2502  */
2503 static void send_key (struct Neighbour *n);
2504
2505 /**
2506  * Task that will retry "send_key" if our previous attempt failed
2507  * to yield a PONG.
2508  */
2509 static void
2510 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2511 {
2512   struct Neighbour *n = cls;
2513
2514 #if DEBUG_CORE
2515   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2516               "Retrying key transmission to `%4s'\n",
2517               GNUNET_i2s (&n->peer));
2518 #endif
2519   n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2520   n->set_key_retry_frequency =
2521     GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2522   send_key (n);
2523 }
2524
2525
2526 /**
2527  * Check if we have plaintext messages for the specified neighbour
2528  * pending, and if so, consider batching and encrypting them (and
2529  * then trigger processing of the encrypted queue if needed).
2530  *
2531  * @param n neighbour to check.
2532  */
2533 static void
2534 process_plaintext_neighbour_queue (struct Neighbour *n)
2535 {
2536   char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)];        /* plaintext */
2537   size_t used;
2538   struct EncryptedMessage *em;  /* encrypted message */
2539   struct EncryptedMessage *ph;  /* plaintext header */
2540   struct MessageEntry *me;
2541   unsigned int priority;
2542   struct GNUNET_TIME_Absolute deadline;
2543   struct GNUNET_TIME_Relative retry_time;
2544   struct GNUNET_CRYPTO_AesInitializationVector iv;
2545   struct GNUNET_CRYPTO_AuthKey auth_key;
2546
2547   if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2548     {
2549       GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
2550       n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2551     }
2552   switch (n->status)
2553     {
2554     case PEER_STATE_DOWN:
2555       send_key (n);
2556 #if DEBUG_CORE
2557       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2558                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2559                   GNUNET_i2s(&n->peer));
2560 #endif
2561       return;
2562     case PEER_STATE_KEY_SENT:
2563       if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2564         n->retry_set_key_task
2565           = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2566                                           &set_key_retry_task, n);    
2567 #if DEBUG_CORE
2568       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2569                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2570                   GNUNET_i2s(&n->peer));
2571 #endif
2572       return;
2573     case PEER_STATE_KEY_RECEIVED:
2574       if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)        
2575         n->retry_set_key_task
2576           = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2577                                           &set_key_retry_task, n);        
2578 #if DEBUG_CORE
2579       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2580                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2581                   GNUNET_i2s(&n->peer));
2582 #endif
2583       return;
2584     case PEER_STATE_KEY_CONFIRMED:
2585       /* ready to continue */
2586       break;
2587     }
2588   discard_expired_messages (n);
2589   if (n->messages == NULL)
2590     {
2591 #if DEBUG_CORE
2592       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2593                   "Plaintext message queue for `%4s' is empty.\n",
2594                   GNUNET_i2s(&n->peer));
2595 #endif
2596       return;                   /* no pending messages */
2597     }
2598   if (n->encrypted_head != NULL)
2599     {
2600 #if DEBUG_CORE
2601       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2602                   "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2603                   GNUNET_i2s(&n->peer));
2604 #endif
2605       return;                   /* wait for messages already encrypted to be
2606                                    processed first! */
2607     }
2608   ph = (struct EncryptedMessage *) pbuf;
2609   deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2610   priority = 0;
2611   used = sizeof (struct EncryptedMessage);
2612   used += batch_message (n,
2613                          &pbuf[used],
2614                          GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2615                          &deadline, &retry_time, &priority);
2616   if (used == sizeof (struct EncryptedMessage))
2617     {
2618 #if DEBUG_CORE
2619       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2620                   "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2621                   GNUNET_i2s(&n->peer));
2622 #endif
2623       /* no messages selected for sending, try again later... */
2624       n->retry_plaintext_task =
2625         GNUNET_SCHEDULER_add_delayed (retry_time,
2626                                       &retry_plaintext_processing, n);
2627       return;
2628     }
2629 #if DEBUG_CORE_QUOTA
2630   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2631               "Sending %u b/s as new limit to peer `%4s'\n",
2632               (unsigned int) ntohl (n->bw_in.value__),
2633               GNUNET_i2s (&n->peer));
2634 #endif
2635   ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
2636   ph->sequence_number = htonl (++n->last_sequence_number_sent);
2637   ph->inbound_bw_limit = n->bw_in;
2638   ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2639
2640   /* setup encryption message header */
2641   me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2642   me->deadline = deadline;
2643   me->priority = priority;
2644   me->size = used;
2645   em = (struct EncryptedMessage *) &me[1];
2646   em->header.size = htons (used);
2647   em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2648   em->iv_seed = ph->iv_seed;
2649   derive_iv (&iv, &n->encrypt_key, ph->iv_seed, &n->peer);
2650   /* encrypt */
2651 #if DEBUG_HANDSHAKE
2652   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2653               "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2654               (unsigned int) used - ENCRYPTED_HEADER_SIZE,
2655               GNUNET_i2s(&n->peer),
2656               (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).rel_value);
2657 #endif
2658   GNUNET_assert (GNUNET_OK ==
2659                  do_encrypt (n,
2660                              &iv,
2661                              &ph->sequence_number,
2662                              &em->sequence_number, used - ENCRYPTED_HEADER_SIZE));
2663   derive_auth_key (&auth_key,
2664                    &n->encrypt_key,
2665                    ph->iv_seed,
2666                    n->encrypt_key_created);
2667   GNUNET_CRYPTO_hmac (&auth_key,
2668                       &em->sequence_number,
2669                       used - ENCRYPTED_HEADER_SIZE,
2670                       &em->hmac);
2671 #if DEBUG_HANDSHAKE
2672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2673               "Authenticated %u bytes of ciphertext %u: `%s'\n",
2674               used - ENCRYPTED_HEADER_SIZE,
2675               GNUNET_CRYPTO_crc32_n (&em->sequence_number,
2676                   used - ENCRYPTED_HEADER_SIZE),
2677               GNUNET_h2s (&em->hmac));
2678 #endif
2679   /* append to transmission list */
2680   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2681                                      n->encrypted_tail,
2682                                      n->encrypted_tail,
2683                                      me);
2684   process_encrypted_neighbour_queue (n);
2685   schedule_peer_messages (n);
2686 }
2687
2688
2689 /**
2690  * Function that recalculates the bandwidth quota for the
2691  * given neighbour and transmits it to the transport service.
2692  * 
2693  * @param cls neighbour for the quota update
2694  * @param tc context
2695  */
2696 static void
2697 neighbour_quota_update (void *cls,
2698                         const struct GNUNET_SCHEDULER_TaskContext *tc);
2699
2700
2701 /**
2702  * Schedule the task that will recalculate the bandwidth
2703  * quota for this peer (and possibly force a disconnect of
2704  * idle peers by calculating a bandwidth of zero).
2705  */
2706 static void
2707 schedule_quota_update (struct Neighbour *n)
2708 {
2709   GNUNET_assert (n->quota_update_task ==
2710                  GNUNET_SCHEDULER_NO_TASK);
2711   n->quota_update_task
2712     = GNUNET_SCHEDULER_add_delayed (QUOTA_UPDATE_FREQUENCY,
2713                                     &neighbour_quota_update,
2714                                     n);
2715 }
2716
2717
2718 /**
2719  * Initialize a new 'struct Neighbour'.
2720  *
2721  * @param pid ID of the new neighbour
2722  * @return handle for the new neighbour
2723  */
2724 static struct Neighbour *
2725 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2726 {
2727   struct Neighbour *n;
2728   struct GNUNET_TIME_Absolute now;
2729
2730 #if DEBUG_CORE
2731   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2732               "Creating neighbour entry for peer `%4s'\n",
2733               GNUNET_i2s (pid));
2734 #endif
2735   n = GNUNET_malloc (sizeof (struct Neighbour));
2736   n->peer = *pid;
2737   GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2738   now = GNUNET_TIME_absolute_get ();
2739   n->encrypt_key_created = now;
2740   n->last_activity = now;
2741   n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2742   n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2743   n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2744   n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2745   n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2746   n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
2747                                                 UINT32_MAX);
2748   GNUNET_assert (GNUNET_OK == 
2749                  GNUNET_CONTAINER_multihashmap_put (neighbours,
2750                                                     &n->peer.hashPubKey,
2751                                                     n,
2752                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2753   GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), 
2754                          GNUNET_CONTAINER_multihashmap_size (neighbours), GNUNET_NO);
2755   neighbour_quota_update (n, NULL);
2756   consider_free_neighbour (n);
2757   return n;
2758 }
2759
2760
2761 /**
2762  * Handle CORE_SEND request.
2763  *
2764  * @param cls unused
2765  * @param client the client issuing the request
2766  * @param message the "struct SendMessage"
2767  */
2768 static void
2769 handle_client_send (void *cls,
2770                     struct GNUNET_SERVER_Client *client,
2771                     const struct GNUNET_MessageHeader *message)
2772 {
2773   const struct SendMessage *sm;
2774   struct Neighbour *n;
2775   struct MessageEntry *prev;
2776   struct MessageEntry *pos;
2777   struct MessageEntry *e; 
2778   struct MessageEntry *min_prio_entry;
2779   struct MessageEntry *min_prio_prev;
2780   unsigned int min_prio;
2781   unsigned int queue_size;
2782   uint16_t msize;
2783
2784   msize = ntohs (message->size);
2785   if (msize <
2786       sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2787     {
2788       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));
2789       GNUNET_break (0);
2790       if (client != NULL)
2791         GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2792       return;
2793     }
2794   sm = (const struct SendMessage *) message;
2795   msize -= sizeof (struct SendMessage);
2796   if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2797     {
2798       /* loopback */
2799       GNUNET_SERVER_mst_receive (mst,
2800                                  &self,
2801                                  (const char*) &sm[1],
2802                                  msize,
2803                                  GNUNET_YES,
2804                                  GNUNET_NO);
2805       if (client != NULL)
2806         GNUNET_SERVER_receive_done (client, GNUNET_OK);
2807       return;
2808     }
2809   n = find_neighbour (&sm->peer);
2810   if (n == NULL)
2811     n = create_neighbour (&sm->peer);
2812 #if DEBUG_CORE
2813   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2814               "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2815               "SEND",
2816               (unsigned int) msize, 
2817               GNUNET_i2s (&sm->peer));
2818 #endif
2819   discard_expired_messages (n);
2820   /* bound queue size */
2821   /* NOTE: this entire block to bound the queue size should be
2822      obsolete with the new client-request code and the
2823      'schedule_peer_messages' mechanism; we still have this code in
2824      here for now as a sanity check for the new mechanmism;
2825      ultimately, we should probably simply reject SEND messages that
2826      are not 'approved' (or provide a new core API for very unreliable
2827      delivery that always sends with priority 0).  Food for thought. */
2828   min_prio = UINT32_MAX;
2829   min_prio_entry = NULL;
2830   min_prio_prev = NULL;
2831   queue_size = 0;
2832   prev = NULL;
2833   pos = n->messages;
2834   while (pos != NULL) 
2835     {
2836       if (pos->priority <= min_prio)
2837         {
2838           min_prio_entry = pos;
2839           min_prio_prev = prev;
2840           min_prio = pos->priority;
2841         }
2842       queue_size++;
2843       prev = pos;
2844       pos = pos->next;
2845     }
2846   if (queue_size >= MAX_PEER_QUEUE_SIZE)
2847     {
2848       /* queue full */
2849       if (ntohl(sm->priority) <= min_prio)
2850         {
2851           /* discard new entry; this should no longer happen! */
2852           GNUNET_break (0);
2853 #if DEBUG_CORE
2854           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2855                       "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2856                       queue_size,
2857                       (unsigned int) MAX_PEER_QUEUE_SIZE,
2858                       (unsigned int) msize,
2859                       (unsigned int) ntohs (message->type));
2860 #endif
2861           GNUNET_STATISTICS_update (stats, 
2862                                     gettext_noop ("# discarded CORE_SEND requests"), 
2863                                     1, GNUNET_NO);
2864
2865           if (client != NULL)
2866             GNUNET_SERVER_receive_done (client, GNUNET_OK);
2867           return;
2868         }
2869       GNUNET_assert (min_prio_entry != NULL);
2870       /* discard "min_prio_entry" */
2871 #if DEBUG_CORE
2872       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2873                   "Queue full, discarding existing older request\n");
2874 #endif
2875           GNUNET_STATISTICS_update (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 1, GNUNET_NO);
2876       if (min_prio_prev == NULL)
2877         n->messages = min_prio_entry->next;
2878       else
2879         min_prio_prev->next = min_prio_entry->next;      
2880       GNUNET_free (min_prio_entry);     
2881     }
2882
2883 #if DEBUG_CORE
2884   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2885               "Adding transmission request for `%4s' of size %u to queue\n",
2886               GNUNET_i2s (&sm->peer),
2887               (unsigned int) msize);
2888 #endif  
2889   e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2890   e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2891   e->priority = ntohl (sm->priority);
2892   e->size = msize;
2893   memcpy (&e[1], &sm[1], msize);
2894
2895   /* insert, keep list sorted by deadline */
2896   prev = NULL;
2897   pos = n->messages;
2898   while ((pos != NULL) && (pos->deadline.abs_value < e->deadline.abs_value))
2899     {
2900       prev = pos;
2901       pos = pos->next;
2902     }
2903   if (prev == NULL)
2904     n->messages = e;
2905   else
2906     prev->next = e;
2907   e->next = pos;
2908
2909   /* consider scheduling now */
2910   process_plaintext_neighbour_queue (n);
2911   if (client != NULL)
2912     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2913 }
2914
2915
2916 /**
2917  * Function called when the transport service is ready to
2918  * receive a message.  Only resets 'n->th' to NULL.
2919  *
2920  * @param cls neighbour to use message from
2921  * @param size number of bytes we can transmit
2922  * @param buf where to copy the message
2923  * @return number of bytes transmitted
2924  */
2925 static size_t
2926 notify_transport_connect_done (void *cls,
2927                                size_t size,
2928                                void *buf)
2929 {
2930   struct Neighbour *n = cls;
2931
2932   n->th = NULL;
2933   if (GNUNET_YES != n->is_connected)
2934     {
2935       /* transport should only call us to transmit a message after
2936        * telling us about a successful connection to the respective peer */
2937 #if DEBUG_CORE
2938       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
2939                   "Timeout on notify connect!\n");
2940 #endif
2941       GNUNET_STATISTICS_update (stats, 
2942                                 gettext_noop ("# connection requests timed out in transport"), 
2943                                 1,
2944                                 GNUNET_NO);
2945       return 0;
2946     }
2947   if (buf == NULL)
2948     {
2949       GNUNET_STATISTICS_update (stats,
2950                                 gettext_noop ("# connection requests timed out in transport"),
2951                                 1,
2952                                 GNUNET_NO);
2953       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2954                   _("Failed to connect to `%4s': transport failed to connect\n"),
2955                   GNUNET_i2s (&n->peer));
2956       return 0;
2957     }
2958   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2959               _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2960               GNUNET_i2s (&n->peer));
2961   if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2962     GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2963   n->retry_set_key_task = GNUNET_SCHEDULER_add_now (&set_key_retry_task,
2964                                                     n);
2965   return 0;
2966 }
2967
2968
2969 /**
2970  * Handle CORE_REQUEST_CONNECT request.
2971  *
2972  * @param cls unused
2973  * @param client the client issuing the request
2974  * @param message the "struct ConnectMessage"
2975  */
2976 static void
2977 handle_client_request_connect (void *cls,
2978                                struct GNUNET_SERVER_Client *client,
2979                                const struct GNUNET_MessageHeader *message)
2980 {
2981   const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2982   struct Neighbour *n;
2983   struct GNUNET_TIME_Relative timeout;
2984
2985   if (0 == memcmp (&cm->peer, 
2986                    &my_identity, 
2987                    sizeof (struct GNUNET_PeerIdentity)))
2988     {
2989       /* In this case a client has asked us to connect to ourselves, not really an error! */
2990       GNUNET_SERVER_receive_done (client, GNUNET_OK);
2991       return;
2992     }
2993   timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2994   GNUNET_break (ntohl (cm->reserved) == 0);
2995   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2996   n = find_neighbour (&cm->peer);
2997   if (n == NULL)
2998     n = create_neighbour (&cm->peer);
2999   if ( (GNUNET_YES == n->is_connected) ||
3000        (n->th != NULL) )
3001     {
3002       if (GNUNET_YES == n->is_connected) 
3003         GNUNET_STATISTICS_update (stats, 
3004                                   gettext_noop ("# connection requests ignored (already connected)"), 
3005                                   1,
3006                                   GNUNET_NO);
3007       else
3008         {
3009           GNUNET_TRANSPORT_notify_transmit_ready_cancel(n->th);
3010           n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
3011                                                           &cm->peer,
3012                                                           sizeof (struct GNUNET_MessageHeader), 0,
3013                                                           timeout,
3014                                                           &notify_transport_connect_done,
3015                                                           n);
3016           GNUNET_break (NULL != n->th);
3017           GNUNET_STATISTICS_update (stats,
3018                                     gettext_noop ("# connection requests retried (due to repeat request connect)"),
3019                                     1,
3020                                     GNUNET_NO);
3021         }
3022       return; /* already connected, or at least trying */
3023     }
3024   GNUNET_STATISTICS_update (stats, 
3025                             gettext_noop ("# connection requests received"), 
3026                             1,
3027                             GNUNET_NO);
3028
3029 #if DEBUG_CORE
3030   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3031               "Core received `%s' request for `%4s', will try to establish connection\n",
3032               "REQUEST_CONNECT",
3033               GNUNET_i2s (&cm->peer));
3034 #endif
3035
3036   /* ask transport to connect to the peer */
3037   n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
3038                                                   &cm->peer,
3039                                                   sizeof (struct GNUNET_MessageHeader), 0,
3040                                                   timeout,
3041                                                   &notify_transport_connect_done,
3042                                                   n);
3043   GNUNET_break (NULL != n->th);
3044 }
3045
3046
3047 /**
3048  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
3049  * the neighbour's struct and retry send_key.  Or, if we did not get a
3050  * HELLO, just do nothing.
3051  *
3052  * @param cls the 'struct Neighbour' to retry sending the key for
3053  * @param peer the peer for which this is the HELLO
3054  * @param hello HELLO message of that peer
3055  * @param err_msg NULL if successful, otherwise contains error message
3056  */
3057 static void
3058 process_hello_retry_send_key (void *cls,
3059                               const struct GNUNET_PeerIdentity *peer,
3060                               const struct GNUNET_HELLO_Message *hello,
3061                               const char *err_msg)
3062 {
3063   struct Neighbour *n = cls;
3064
3065   if (err_msg != NULL)
3066   {
3067     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3068                 _("Error in communication with PEERINFO service\n"));
3069     /* return; */
3070   }
3071
3072   if (peer == NULL)
3073     {
3074 #if DEBUG_CORE
3075       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3076                   "Entered `%s' and `%s' is NULL!\n",
3077                   "process_hello_retry_send_key",
3078                   "peer");
3079 #endif
3080       n->pitr = NULL;
3081       if (n->public_key != NULL)
3082         {
3083           if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3084             {
3085               GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3086               n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3087             }      
3088           GNUNET_STATISTICS_update (stats,
3089                                     gettext_noop ("# SET_KEY messages deferred (need public key)"), 
3090                                     -1, 
3091                                     GNUNET_NO);
3092           send_key (n);
3093         }
3094       else
3095         {
3096 #if DEBUG_CORE
3097           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3098                       "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
3099                       GNUNET_i2s (&n->peer));
3100 #endif
3101           GNUNET_STATISTICS_update (stats,
3102                                     gettext_noop ("# Delayed connecting due to lack of public key"),
3103                                     1,
3104                                     GNUNET_NO);      
3105           if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
3106             n->retry_set_key_task
3107               = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3108                                               &set_key_retry_task, n);
3109         }
3110       return;
3111     }
3112
3113 #if DEBUG_CORE
3114   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3115               "Entered `%s' for peer `%4s'\n",
3116               "process_hello_retry_send_key",
3117               GNUNET_i2s (peer));
3118 #endif
3119   if (n->public_key != NULL)
3120     {
3121       /* already have public key, why are we here? */
3122       GNUNET_break (0);
3123       return;
3124     }
3125
3126 #if DEBUG_CORE
3127   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3128               "Received new `%s' message for `%4s', initiating key exchange.\n",
3129               "HELLO",
3130               GNUNET_i2s (peer));
3131 #endif
3132   n->public_key =
3133     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3134   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3135     {
3136       GNUNET_STATISTICS_update (stats,
3137                                 gettext_noop ("# Error extracting public key from HELLO"),
3138                                 1,
3139                                 GNUNET_NO);      
3140       GNUNET_free (n->public_key);
3141       n->public_key = NULL;
3142 #if DEBUG_CORE
3143   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3144               "GNUNET_HELLO_get_key returned awfully\n");
3145 #endif
3146       return;
3147     }
3148 }
3149
3150
3151 /**
3152  * Send our key (and encrypted PING) to the other peer.
3153  *
3154  * @param n the other peer
3155  */
3156 static void
3157 send_key (struct Neighbour *n)
3158 {
3159   struct MessageEntry *pos;
3160   struct SetKeyMessage *sm;
3161   struct MessageEntry *me;
3162   struct PingMessage pp;
3163   struct PingMessage *pm;
3164   struct GNUNET_CRYPTO_AesInitializationVector iv;
3165
3166   if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3167     {
3168       GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3169       n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3170     }        
3171   if (n->pitr != NULL)
3172     {
3173 #if DEBUG_CORE
3174       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3175                   "Key exchange in progress with `%4s'.\n",
3176                   GNUNET_i2s (&n->peer));
3177 #endif
3178       return; /* already in progress */
3179     }
3180   if (GNUNET_YES != n->is_connected)
3181     {
3182 #if DEBUG_CORE
3183       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3184                   "Not yet connected to peer `%4s'!\n",
3185                   GNUNET_i2s (&n->peer));
3186 #endif
3187       if (NULL == n->th)
3188         {
3189           GNUNET_STATISTICS_update (stats, 
3190                                     gettext_noop ("# Asking transport to connect (for SET_KEY)"), 
3191                                     1, 
3192                                     GNUNET_NO);
3193           n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
3194                                                           &n->peer,
3195                                                           sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
3196                                                           0,
3197                                                           GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3198                                                           &notify_encrypted_transmit_ready,
3199                                                           n);
3200         }
3201       return; 
3202     }
3203 #if DEBUG_CORE
3204   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3205               "Asked to perform key exchange with `%4s'.\n",
3206               GNUNET_i2s (&n->peer));
3207 #endif
3208   if (n->public_key == NULL)
3209     {
3210       /* lookup n's public key, then try again */
3211 #if DEBUG_CORE
3212       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3213                   "Lacking public key for `%4s', trying to obtain one (send_key).\n",
3214                   GNUNET_i2s (&n->peer));
3215 #endif
3216       GNUNET_assert (n->pitr == NULL);
3217       n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3218                                          &n->peer,
3219                                          GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
3220                                          &process_hello_retry_send_key, n);
3221       return;
3222     }
3223   pos = n->encrypted_head;
3224   while (pos != NULL)
3225     {
3226       if (GNUNET_YES == pos->is_setkey)
3227         {
3228           if (pos->sender_status == n->status)
3229             {
3230 #if DEBUG_CORE
3231               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3232                           "`%s' message for `%4s' queued already\n",
3233                           "SET_KEY",
3234                           GNUNET_i2s (&n->peer));
3235 #endif
3236               goto trigger_processing;
3237             }
3238           GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
3239                                        n->encrypted_tail,
3240                                        pos);
3241           GNUNET_free (pos);
3242 #if DEBUG_CORE
3243           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3244                       "Removing queued `%s' message for `%4s', will create a new one\n",
3245                       "SET_KEY",
3246                       GNUNET_i2s (&n->peer));
3247 #endif
3248           break;
3249         }
3250       pos = pos->next;
3251     }
3252
3253   /* update status */
3254   switch (n->status)
3255     {
3256     case PEER_STATE_DOWN:
3257       n->status = PEER_STATE_KEY_SENT;
3258       break;
3259     case PEER_STATE_KEY_SENT:
3260       break;
3261     case PEER_STATE_KEY_RECEIVED:
3262       break;
3263     case PEER_STATE_KEY_CONFIRMED:
3264       break;
3265     default:
3266       GNUNET_break (0);
3267       break;
3268     }
3269   
3270
3271   /* first, set key message */
3272   me = GNUNET_malloc (sizeof (struct MessageEntry) +
3273                       sizeof (struct SetKeyMessage) +
3274                       sizeof (struct PingMessage));
3275   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
3276   me->priority = SET_KEY_PRIORITY;
3277   me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
3278   me->is_setkey = GNUNET_YES;
3279   me->got_slack = GNUNET_YES; /* do not defer this one! */
3280   me->sender_status = n->status;
3281   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3282                                      n->encrypted_tail,
3283                                      n->encrypted_tail,
3284                                      me);
3285   sm = (struct SetKeyMessage *) &me[1];
3286   sm->header.size = htons (sizeof (struct SetKeyMessage));
3287   sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
3288   sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
3289                                         PEER_STATE_KEY_SENT : n->status));
3290   sm->purpose.size =
3291     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3292            sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3293            sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3294            sizeof (struct GNUNET_PeerIdentity));
3295   sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
3296   sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
3297   sm->target = n->peer;
3298   GNUNET_assert (GNUNET_OK ==
3299                  GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
3300                                             sizeof (struct
3301                                                     GNUNET_CRYPTO_AesSessionKey),
3302                                             n->public_key,
3303                                             &sm->encrypted_key));
3304   GNUNET_assert (GNUNET_OK ==
3305                  GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
3306                                          &sm->signature));  
3307   pm = (struct PingMessage *) &sm[1];
3308   pm->header.size = htons (sizeof (struct PingMessage));
3309   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
3310   pm->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3311   derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
3312   pp.challenge = n->ping_challenge;
3313   pp.target = n->peer;
3314 #if DEBUG_HANDSHAKE
3315   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3316               "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
3317               "SET_KEY", "PING",
3318               (unsigned int) n->ping_challenge,
3319               GNUNET_i2s (&n->peer),
3320               (unsigned int) n->encrypt_key.crc32,
3321               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3322               pm->iv_seed);
3323 #endif
3324   do_encrypt (n,
3325               &iv,
3326               &pp.target,
3327               &pm->target,
3328               sizeof (struct PingMessage) -
3329               ((void *) &pm->target - (void *) pm));
3330   GNUNET_STATISTICS_update (stats, 
3331                             gettext_noop ("# SET_KEY and PING messages created"), 
3332                             1, 
3333                             GNUNET_NO);
3334 #if DEBUG_CORE
3335   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3336               "Have %llu ms left for `%s' transmission.\n",
3337               (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).rel_value,
3338               "SET_KEY");
3339 #endif
3340  trigger_processing:
3341   /* trigger queue processing */
3342   process_encrypted_neighbour_queue (n);
3343   if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
3344        (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
3345     n->retry_set_key_task
3346       = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3347                                       &set_key_retry_task, n);    
3348 }
3349
3350
3351 /**
3352  * We received a SET_KEY message.  Validate and update
3353  * our key material and status.
3354  *
3355  * @param n the neighbour from which we received message m
3356  * @param m the set key message we received
3357  * @param ats performance data
3358  * @param ats_count number of entries in ats (excluding 0-termination)
3359  */
3360 static void
3361 handle_set_key (struct Neighbour *n,
3362                 const struct SetKeyMessage *m,
3363                 const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3364                 uint32_t ats_count);
3365
3366
3367
3368 /**
3369  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
3370  * the neighbour's struct and retry handling the set_key message.  Or,
3371  * if we did not get a HELLO, just free the set key message.
3372  *
3373  * @param cls pointer to the set key message
3374  * @param peer the peer for which this is the HELLO
3375  * @param hello HELLO message of that peer
3376  * @param err_msg NULL if successful, otherwise contains error message
3377  */
3378 static void
3379 process_hello_retry_handle_set_key (void *cls,
3380                                     const struct GNUNET_PeerIdentity *peer,
3381                                     const struct GNUNET_HELLO_Message *hello,
3382                                     const char *err_msg)
3383 {
3384   struct Neighbour *n = cls;
3385   struct SetKeyMessage *sm = n->skm;
3386
3387   if (err_msg != NULL)
3388   {
3389     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3390                 _("Error in communication with PEERINFO service\n"));
3391     /* return; */
3392   }
3393
3394   if (peer == NULL)
3395     {
3396       n->skm = NULL;
3397       n->pitr = NULL;
3398       if (n->public_key != NULL)
3399         {
3400 #if DEBUG_CORE
3401           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3402                       "Received `%s' for `%4s', continuing processing of `%s' message.\n",
3403                       "HELLO",
3404                       GNUNET_i2s (&n->peer),
3405                       "SET_KEY");
3406 #endif
3407           handle_set_key (n, sm, NULL, 0);
3408         }
3409       else
3410         {
3411           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3412                       _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
3413                       "SET_KEY",
3414                       GNUNET_i2s (&n->peer));
3415         }
3416       GNUNET_free (sm);
3417       return;
3418     }
3419   if (n->public_key != NULL)
3420     return;                     /* multiple HELLOs match!? */
3421   n->public_key =
3422     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3423   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3424     {
3425       GNUNET_break_op (0);
3426       GNUNET_free (n->public_key);
3427       n->public_key = NULL;
3428     }
3429 }
3430
3431
3432 /**
3433  * Merge the given performance data with the data we currently
3434  * track for the given neighbour.
3435  *
3436  * @param n neighbour
3437  * @param ats new performance data
3438  * @param ats_count number of records in ats
3439  */
3440 static void
3441 update_neighbour_performance (struct Neighbour *n,
3442                               const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3443                               uint32_t ats_count)
3444 {
3445   uint32_t i;
3446   unsigned int j;
3447
3448   if (ats_count == 0)
3449     return;
3450   for (i = 0; i < ats_count; i++)
3451     {
3452       for (j=0;j < n->ats_count; j++)
3453         {
3454           if (n->ats[j].type == ats[i].type)
3455             {
3456               n->ats[j].value = ats[i].value;
3457               break;
3458             }
3459         }
3460       if (j == n->ats_count)
3461         {
3462           GNUNET_array_append (n->ats,
3463                                n->ats_count,
3464                                ats[i]);
3465         }
3466     }
3467 }
3468
3469
3470 /**
3471  * We received a PING message.  Validate and transmit
3472  * PONG.
3473  *
3474  * @param n sender of the PING
3475  * @param m the encrypted PING message itself
3476  * @param ats performance data
3477  * @param ats_count number of entries in ats (excluding 0-termination)
3478  */
3479 static void
3480 handle_ping (struct Neighbour *n,
3481              const struct PingMessage *m,
3482              const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3483              uint32_t ats_count)
3484 {
3485   struct PingMessage t;
3486   struct PongMessage tx;
3487   struct PongMessage *tp;
3488   struct MessageEntry *me;
3489   struct GNUNET_CRYPTO_AesInitializationVector iv;
3490
3491 #if DEBUG_CORE
3492   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3493               "Core service receives `%s' request from `%4s'.\n",
3494               "PING", GNUNET_i2s (&n->peer));
3495 #endif
3496   derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3497   if (GNUNET_OK !=
3498       do_decrypt (n,
3499                   &iv,
3500                   &m->target,
3501                   &t.target,
3502                   sizeof (struct PingMessage) -
3503                   ((void *) &m->target - (void *) m)))
3504     return;
3505 #if DEBUG_HANDSHAKE
3506   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3507               "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u, IV %u (salt %u)\n",
3508               "PING",
3509               GNUNET_i2s (&t.target),
3510               (unsigned int) t.challenge,
3511               (unsigned int) n->decrypt_key.crc32,
3512               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3513               m->iv_seed);
3514 #endif
3515   GNUNET_STATISTICS_update (stats,
3516                             gettext_noop ("# PING messages decrypted"), 
3517                             1,
3518                             GNUNET_NO);
3519   if (0 != memcmp (&t.target,
3520                    &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3521     {
3522       GNUNET_break_op (0);
3523       return;
3524     }
3525   update_neighbour_performance (n, ats, ats_count);
3526   me = GNUNET_malloc (sizeof (struct MessageEntry) +
3527                       sizeof (struct PongMessage));
3528   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3529                                      n->encrypted_tail,
3530                                      n->encrypted_tail,
3531                                      me);
3532   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
3533   me->priority = PONG_PRIORITY;
3534   me->size = sizeof (struct PongMessage);
3535   tx.inbound_bw_limit = n->bw_in;
3536   tx.challenge = t.challenge;
3537   tx.target = t.target;
3538   tp = (struct PongMessage *) &me[1];
3539   tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
3540   tp->header.size = htons (sizeof (struct PongMessage));
3541   tp->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3542   derive_pong_iv (&iv, &n->encrypt_key, tp->iv_seed, t.challenge, &n->peer);
3543   do_encrypt (n,
3544               &iv,
3545               &tx.challenge,
3546               &tp->challenge,
3547               sizeof (struct PongMessage) -
3548               ((void *) &tp->challenge - (void *) tp));
3549   GNUNET_STATISTICS_update (stats, 
3550                             gettext_noop ("# PONG messages created"), 
3551                             1, 
3552                             GNUNET_NO);
3553 #if DEBUG_HANDSHAKE
3554   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3555               "Encrypting `%s' with challenge %u using key %u, IV %u (salt %u)\n",
3556               "PONG",
3557               (unsigned int) t.challenge,
3558               (unsigned int) n->encrypt_key.crc32,
3559               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3560               tp->iv_seed);
3561 #endif
3562   /* trigger queue processing */
3563   process_encrypted_neighbour_queue (n);
3564 }
3565
3566
3567 /**
3568  * We received a PONG message.  Validate and update our status.
3569  *
3570  * @param n sender of the PONG
3571  * @param m the encrypted PONG message itself
3572  * @param ats performance data
3573  * @param ats_count number of entries in ats (excluding 0-termination)
3574  */
3575 static void
3576 handle_pong (struct Neighbour *n, 
3577              const struct PongMessage *m,
3578              const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3579              uint32_t ats_count)
3580 {
3581   struct PongMessage t;
3582   struct ConnectNotifyMessage *cnm;
3583   struct GNUNET_CRYPTO_AesInitializationVector iv;
3584   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
3585   struct GNUNET_TRANSPORT_ATS_Information *mats;
3586   size_t size;
3587
3588 #if DEBUG_CORE
3589   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3590               "Core service receives `%s' response from `%4s'.\n",
3591               "PONG", GNUNET_i2s (&n->peer));
3592 #endif
3593   /* mark as garbage, just to be sure */
3594   memset (&t, 255, sizeof (t));
3595   derive_pong_iv (&iv, &n->decrypt_key, m->iv_seed, n->ping_challenge,
3596       &my_identity);
3597   if (GNUNET_OK !=
3598       do_decrypt (n,
3599                   &iv,
3600                   &m->challenge,
3601                   &t.challenge,
3602                   sizeof (struct PongMessage) -
3603                   ((void *) &m->challenge - (void *) m)))
3604     {
3605       GNUNET_break_op (0);
3606       return;
3607     }
3608   GNUNET_STATISTICS_update (stats, 
3609                             gettext_noop ("# PONG messages decrypted"), 
3610                             1, 
3611                             GNUNET_NO);
3612 #if DEBUG_HANDSHAKE
3613   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3614               "Decrypted `%s' from `%4s' with challenge %u using key %u, IV %u (salt %u)\n",
3615               "PONG",
3616               GNUNET_i2s (&t.target),
3617               (unsigned int) t.challenge,
3618               (unsigned int) n->decrypt_key.crc32,
3619               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3620               m->iv_seed);
3621 #endif
3622   if ((0 != memcmp (&t.target,
3623                     &n->peer,
3624                     sizeof (struct GNUNET_PeerIdentity))) ||
3625       (n->ping_challenge != t.challenge))
3626     {
3627       /* PONG malformed */
3628 #if DEBUG_CORE
3629       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3630                   "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
3631                   "PONG", 
3632                   GNUNET_i2s (&n->peer),
3633                   (unsigned int) n->ping_challenge);
3634       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3635                   "Received malformed `%s' received from `%4s' with challenge %u\n",
3636                   "PONG", GNUNET_i2s (&t.target), 
3637                   (unsigned int) t.challenge);
3638 #endif
3639       GNUNET_break_op (n->ping_challenge != t.challenge);
3640       return;
3641     }
3642   switch (n->status)
3643     {
3644     case PEER_STATE_DOWN:
3645       GNUNET_break (0);         /* should be impossible */
3646       return;
3647     case PEER_STATE_KEY_SENT:
3648       GNUNET_break (0);         /* should be impossible, how did we decrypt? */
3649       return;
3650     case PEER_STATE_KEY_RECEIVED:
3651       GNUNET_STATISTICS_update (stats, 
3652                                 gettext_noop ("# Session keys confirmed via PONG"), 
3653                                 1, 
3654                                 GNUNET_NO);
3655       n->status = PEER_STATE_KEY_CONFIRMED;
3656       if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
3657         {
3658           n->bw_out_external_limit = t.inbound_bw_limit;
3659           n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3660                                                   n->bw_out_internal_limit);
3661           GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3662                                                  n->bw_out);       
3663           GNUNET_TRANSPORT_set_quota (transport,
3664                                       &n->peer,
3665                                       n->bw_in,
3666                                       n->bw_out,
3667                                       GNUNET_TIME_UNIT_FOREVER_REL,
3668                                       NULL, NULL); 
3669         }
3670 #if DEBUG_CORE
3671       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3672                   "Confirmed key via `%s' message for peer `%4s'\n",
3673                   "PONG", GNUNET_i2s (&n->peer));
3674 #endif      
3675       if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3676         {
3677           GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3678           n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3679         }      
3680       update_neighbour_performance (n, ats, ats_count);      
3681       size = sizeof (struct ConnectNotifyMessage) +
3682         (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3683       if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3684         {
3685           GNUNET_break (0);
3686           /* recovery strategy: throw away performance data */
3687           GNUNET_array_grow (n->ats,
3688                              n->ats_count,
3689                              0);
3690           size = sizeof (struct PeerStatusNotifyMessage) +
3691             n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3692         }
3693       cnm = (struct ConnectNotifyMessage*) buf;
3694       cnm->header.size = htons (size);
3695       cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3696       cnm->ats_count = htonl (n->ats_count);
3697       cnm->peer = n->peer;
3698       mats = &cnm->ats;
3699       memcpy (mats,
3700               n->ats,
3701               n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
3702       mats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3703       mats[n->ats_count].value = htonl (0);      
3704       send_to_all_clients (&cnm->header, 
3705                            GNUNET_NO, 
3706                            GNUNET_CORE_OPTION_SEND_CONNECT);
3707       process_encrypted_neighbour_queue (n);
3708       /* fall-through! */
3709     case PEER_STATE_KEY_CONFIRMED:
3710       n->last_activity = GNUNET_TIME_absolute_get ();
3711       if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3712         GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3713       n->keep_alive_task 
3714         = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3715                                         &send_keep_alive,
3716                                         n);
3717       handle_peer_status_change (n);
3718       break;
3719     default:
3720       GNUNET_break (0);
3721       break;
3722     }
3723 }
3724
3725
3726 /**
3727  * We received a SET_KEY message.  Validate and update
3728  * our key material and status.
3729  *
3730  * @param n the neighbour from which we received message m
3731  * @param m the set key message we received
3732  * @param ats performance data
3733  * @param ats_count number of entries in ats (excluding 0-termination)
3734  */
3735 static void
3736 handle_set_key (struct Neighbour *n, 
3737                 const struct SetKeyMessage *m,
3738                 const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3739                 uint32_t ats_count)
3740 {
3741   struct SetKeyMessage *m_cpy;
3742   struct GNUNET_TIME_Absolute t;
3743   struct GNUNET_CRYPTO_AesSessionKey k;
3744   struct PingMessage *ping;
3745   struct PongMessage *pong;
3746   enum PeerStateMachine sender_status;
3747
3748 #if DEBUG_CORE
3749   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3750               "Core service receives `%s' request from `%4s'.\n",
3751               "SET_KEY", GNUNET_i2s (&n->peer));
3752 #endif
3753   if (n->public_key == NULL)
3754     {
3755       if (n->pitr != NULL)
3756         {
3757 #if DEBUG_CORE
3758           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3759                       "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3760                       "SET_KEY");
3761 #endif
3762           return;
3763         }
3764 #if DEBUG_CORE
3765       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3766                   "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3767 #endif
3768       m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3769       memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3770       /* lookup n's public key, then try again */
3771       GNUNET_assert (n->skm == NULL);
3772       n->skm = m_cpy;
3773       n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3774                                          &n->peer,
3775                                          GNUNET_TIME_UNIT_MINUTES,
3776                                          &process_hello_retry_handle_set_key, n);
3777       GNUNET_STATISTICS_update (stats, 
3778                                 gettext_noop ("# SET_KEY messages deferred (need public key)"), 
3779                                 1, 
3780                                 GNUNET_NO);
3781       return;
3782     }
3783   if (0 != memcmp (&m->target,
3784                    &my_identity,
3785                    sizeof (struct GNUNET_PeerIdentity)))
3786     {
3787       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3788                   _("Received `%s' message that was for `%s', not for me.  Ignoring.\n"),
3789                   "SET_KEY",
3790                   GNUNET_i2s (&m->target));
3791       return;
3792     }
3793   if ((ntohl (m->purpose.size) !=
3794        sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3795        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3796        sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3797        sizeof (struct GNUNET_PeerIdentity)) ||
3798       (GNUNET_OK !=
3799        GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3800                                  &m->purpose, &m->signature, n->public_key)))
3801     {
3802       /* invalid signature */
3803       GNUNET_break_op (0);
3804       return;
3805     }
3806   t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3807   if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3808        (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3809       (t.abs_value < n->decrypt_key_created.abs_value))
3810     {
3811       /* this could rarely happen due to massive re-ordering of
3812          messages on the network level, but is most likely either
3813          a bug or some adversary messing with us.  Report. */
3814       GNUNET_break_op (0);
3815       return;
3816     }
3817 #if DEBUG_CORE
3818   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
3819               "Decrypting key material.\n");
3820 #endif  
3821   if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3822                                   &m->encrypted_key,
3823                                   &k,
3824                                   sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3825        != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3826       (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3827     {
3828       /* failed to decrypt !? */
3829       GNUNET_break_op (0);
3830       return;
3831     }
3832   GNUNET_STATISTICS_update (stats, 
3833                             gettext_noop ("# SET_KEY messages decrypted"), 
3834                             1, 
3835                             GNUNET_NO);
3836   n->decrypt_key = k;
3837   if (n->decrypt_key_created.abs_value != t.abs_value)
3838     {
3839       /* fresh key, reset sequence numbers */
3840       n->last_sequence_number_received = 0;
3841       n->last_packets_bitmap = 0;
3842       n->decrypt_key_created = t;
3843     }
3844   update_neighbour_performance (n, ats, ats_count);
3845   sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3846   switch (n->status)
3847     {
3848     case PEER_STATE_DOWN:
3849       n->status = PEER_STATE_KEY_RECEIVED;
3850 #if DEBUG_CORE
3851       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3852                   "Responding to `%s' with my own key.\n", "SET_KEY");
3853 #endif
3854       send_key (n);
3855       break;
3856     case PEER_STATE_KEY_SENT:
3857     case PEER_STATE_KEY_RECEIVED:
3858       n->status = PEER_STATE_KEY_RECEIVED;
3859       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3860           (sender_status != PEER_STATE_KEY_CONFIRMED))
3861         {
3862 #if DEBUG_CORE
3863           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3864                       "Responding to `%s' with my own key (other peer has status %u).\n",
3865                       "SET_KEY",
3866                       (unsigned int) sender_status);
3867 #endif
3868           send_key (n);
3869         }
3870       break;
3871     case PEER_STATE_KEY_CONFIRMED:
3872       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3873           (sender_status != PEER_STATE_KEY_CONFIRMED))
3874         {         
3875 #if DEBUG_CORE
3876           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3877                       "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3878                       "SET_KEY", 
3879                       (unsigned int) sender_status);
3880 #endif
3881           send_key (n);
3882         }
3883       break;
3884     default:
3885       GNUNET_break (0);
3886       break;
3887     }
3888   if (n->pending_ping != NULL)
3889     {
3890       ping = n->pending_ping;
3891       n->pending_ping = NULL;
3892       handle_ping (n, ping, NULL, 0);
3893       GNUNET_free (ping);
3894     }
3895   if (n->pending_pong != NULL)
3896     {
3897       pong = n->pending_pong;
3898       n->pending_pong = NULL;
3899       handle_pong (n, pong, NULL, 0);
3900       GNUNET_free (pong);
3901     }
3902 }
3903
3904
3905 /**
3906  * Send a P2P message to a client.
3907  *
3908  * @param sender who sent us the message?
3909  * @param client who should we give the message to?
3910  * @param m contains the message to transmit
3911  * @param msize number of bytes in buf to transmit
3912  */
3913 static void
3914 send_p2p_message_to_client (struct Neighbour *sender,
3915                             struct Client *client,
3916                             const void *m, size_t msize)
3917 {
3918   size_t size = msize + sizeof (struct NotifyTrafficMessage) +
3919     (sender->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3920   char buf[size];
3921   struct NotifyTrafficMessage *ntm;
3922   struct GNUNET_TRANSPORT_ATS_Information *ats;
3923
3924   if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3925     {
3926       GNUNET_break (0);
3927       /* recovery strategy: throw performance data away... */
3928       GNUNET_array_grow (sender->ats,
3929                          sender->ats_count,
3930                          0);
3931       size = msize + sizeof (struct NotifyTrafficMessage) +
3932         (sender->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3933     }
3934 #if DEBUG_CORE
3935   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3936               "Core service passes message from `%4s' of type %u to client.\n",
3937               GNUNET_i2s(&sender->peer),
3938               (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3939 #endif
3940   ntm = (struct NotifyTrafficMessage *) buf;
3941   ntm->header.size = htons (size);
3942   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3943   ntm->ats_count = htonl (sender->ats_count);
3944   ntm->peer = sender->peer;
3945   ats = &ntm->ats;
3946   memcpy (ats,
3947           sender->ats,
3948           sizeof (struct GNUNET_TRANSPORT_ATS_Information) * sender->ats_count);
3949   ats[sender->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3950   ats[sender->ats_count].value = htonl (0);  
3951   memcpy (&ats[sender->ats_count+1],
3952           m, 
3953           msize);
3954   send_to_client (client, &ntm->header, GNUNET_YES);
3955 }
3956
3957
3958 /**
3959  * Deliver P2P message to interested clients.
3960  *
3961  * @param cls always NULL
3962  * @param client who sent us the message (struct Neighbour)
3963  * @param m the message
3964  */
3965 static void
3966 deliver_message (void *cls,
3967                  void *client,
3968                  const struct GNUNET_MessageHeader *m)
3969 {
3970   struct Neighbour *sender = client;
3971   size_t msize = ntohs (m->size);
3972   char buf[256];
3973   struct Client *cpos;
3974   uint16_t type;
3975   unsigned int tpos;
3976   int deliver_full;
3977   int dropped;
3978
3979   type = ntohs (m->type);
3980 #if DEBUG_CORE
3981   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3982               "Received encapsulated message of type %u and size %u from `%4s'\n",
3983               (unsigned int) type,
3984               ntohs (m->size),
3985               GNUNET_i2s (&sender->peer));
3986 #endif
3987   GNUNET_snprintf (buf,
3988                    sizeof(buf),
3989                    gettext_noop ("# bytes of messages of type %u received"),
3990                    (unsigned int) type);
3991   GNUNET_STATISTICS_set (stats,
3992                          buf,
3993                          msize,
3994                          GNUNET_NO);     
3995   dropped = GNUNET_YES;
3996   cpos = clients;
3997   while (cpos != NULL)
3998     {
3999       deliver_full = GNUNET_NO;
4000       if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
4001         deliver_full = GNUNET_YES;
4002       else
4003         {
4004           for (tpos = 0; tpos < cpos->tcnt; tpos++)
4005             {
4006               if (type != cpos->types[tpos])
4007                 continue;
4008               deliver_full = GNUNET_YES;
4009               break;
4010             }
4011         }
4012       if (GNUNET_YES == deliver_full)
4013         {
4014           send_p2p_message_to_client (sender, cpos, m, msize);
4015           dropped = GNUNET_NO;
4016         }
4017       else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
4018         {
4019           send_p2p_message_to_client (sender, cpos, m,
4020                                       sizeof (struct GNUNET_MessageHeader));
4021         }
4022       cpos = cpos->next;
4023     }
4024   if (dropped == GNUNET_YES)
4025     {
4026 #if DEBUG_CORE
4027       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4028                   "Message of type %u from `%4s' not delivered to any client.\n",
4029                   (unsigned int) type,
4030                   GNUNET_i2s (&sender->peer));
4031 #endif
4032       GNUNET_STATISTICS_update (stats,
4033                                 gettext_noop ("# messages not delivered to any client"), 
4034                                 1, GNUNET_NO);
4035     }
4036 }
4037
4038
4039 /**
4040  * We received an encrypted message.  Decrypt, validate and
4041  * pass on to the appropriate clients.
4042  *
4043  * @param n target of the message
4044  * @param m encrypted message
4045  * @param ats performance data
4046  * @param ats_count number of entries in ats (excluding 0-termination)
4047  */
4048 static void
4049 handle_encrypted_message (struct Neighbour *n,
4050                           const struct EncryptedMessage *m,
4051                           const struct GNUNET_TRANSPORT_ATS_Information *ats, 
4052                           uint32_t ats_count)
4053 {
4054   size_t size = ntohs (m->header.size);
4055   char buf[size];
4056   struct EncryptedMessage *pt;  /* plaintext */
4057   GNUNET_HashCode ph;
4058   uint32_t snum;
4059   struct GNUNET_TIME_Absolute t;
4060   struct GNUNET_CRYPTO_AesInitializationVector iv;
4061   struct GNUNET_CRYPTO_AuthKey auth_key;
4062
4063 #if DEBUG_CORE
4064   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4065               "Core service receives `%s' request from `%4s'.\n",
4066               "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
4067 #endif  
4068   /* validate hash */
4069   derive_auth_key (&auth_key,
4070                    &n->decrypt_key,
4071                    m->iv_seed,
4072                    n->decrypt_key_created);
4073   GNUNET_CRYPTO_hmac (&auth_key,
4074                       &m->sequence_number,
4075                       size - ENCRYPTED_HEADER_SIZE, &ph);
4076 #if DEBUG_HANDSHAKE
4077   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4078               "Re-Authenticated %u bytes of ciphertext (`%u'): `%s'\n",
4079               (unsigned int) size - ENCRYPTED_HEADER_SIZE,
4080               GNUNET_CRYPTO_crc32_n (&m->sequence_number,
4081                   size - ENCRYPTED_HEADER_SIZE),
4082               GNUNET_h2s (&ph));
4083 #endif
4084
4085   if (0 != memcmp (&ph,
4086                    &m->hmac,
4087                    sizeof (GNUNET_HashCode)))
4088     {
4089       /* checksum failed */
4090       GNUNET_break_op (0);
4091       return;
4092     }
4093   derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
4094   /* decrypt */
4095   if (GNUNET_OK !=
4096       do_decrypt (n,
4097                   &iv,
4098                   &m->sequence_number,
4099                   &buf[ENCRYPTED_HEADER_SIZE],
4100                   size - ENCRYPTED_HEADER_SIZE))
4101     return;
4102   pt = (struct EncryptedMessage *) buf;
4103
4104   /* validate sequence number */
4105   snum = ntohl (pt->sequence_number);
4106   if (n->last_sequence_number_received == snum)
4107     {
4108       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4109                   "Received duplicate message, ignoring.\n");
4110       /* duplicate, ignore */
4111       GNUNET_STATISTICS_set (stats,
4112                              gettext_noop ("# bytes dropped (duplicates)"),
4113                              size,
4114                              GNUNET_NO);      
4115       return;
4116     }
4117   if ((n->last_sequence_number_received > snum) &&
4118       (n->last_sequence_number_received - snum > 32))
4119     {
4120       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4121                   "Received ancient out of sequence message, ignoring.\n");
4122       /* ancient out of sequence, ignore */
4123       GNUNET_STATISTICS_set (stats,
4124                              gettext_noop ("# bytes dropped (out of sequence)"),
4125                              size,
4126                              GNUNET_NO);      
4127       return;
4128     }
4129   if (n->last_sequence_number_received > snum)
4130     {
4131       unsigned int rotbit =
4132         1 << (n->last_sequence_number_received - snum - 1);
4133       if ((n->last_packets_bitmap & rotbit) != 0)
4134         {
4135           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4136                       "Received duplicate message, ignoring.\n");
4137           GNUNET_STATISTICS_set (stats,
4138                                  gettext_noop ("# bytes dropped (duplicates)"),
4139                                  size,
4140                                  GNUNET_NO);      
4141           /* duplicate, ignore */
4142           return;
4143         }
4144       n->last_packets_bitmap |= rotbit;
4145     }
4146   if (n->last_sequence_number_received < snum)
4147     {
4148       int shift = (snum - n->last_sequence_number_received);
4149       if (shift >= 8 * sizeof(n->last_packets_bitmap))
4150         n->last_packets_bitmap = 0;
4151       else
4152         n->last_packets_bitmap <<= shift;
4153       n->last_sequence_number_received = snum;
4154     }
4155
4156   /* check timestamp */
4157   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
4158   if (GNUNET_TIME_absolute_get_duration (t).rel_value > MAX_MESSAGE_AGE.rel_value)
4159     {
4160       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4161                   _
4162                   ("Message received far too old (%llu ms). Content ignored.\n"),
4163                   GNUNET_TIME_absolute_get_duration (t).rel_value);
4164       GNUNET_STATISTICS_set (stats,
4165                              gettext_noop ("# bytes dropped (ancient message)"),
4166                              size,
4167                              GNUNET_NO);      
4168       return;
4169     }
4170
4171   /* process decrypted message(s) */
4172   if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
4173     {
4174 #if DEBUG_CORE_SET_QUOTA
4175       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4176                   "Received %u b/s as new inbound limit for peer `%4s'\n",
4177                   (unsigned int) ntohl (pt->inbound_bw_limit.value__),
4178                   GNUNET_i2s (&n->peer));
4179 #endif
4180       n->bw_out_external_limit = pt->inbound_bw_limit;
4181       n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
4182                                               n->bw_out_internal_limit);
4183       GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
4184                                              n->bw_out);
4185       GNUNET_TRANSPORT_set_quota (transport,
4186                                   &n->peer,
4187                                   n->bw_in,
4188                                   n->bw_out,
4189                                   GNUNET_TIME_UNIT_FOREVER_REL,
4190                                   NULL, NULL); 
4191     }
4192   n->last_activity = GNUNET_TIME_absolute_get ();
4193   if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
4194     GNUNET_SCHEDULER_cancel (n->keep_alive_task);
4195   n->keep_alive_task 
4196     = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
4197                                     &send_keep_alive,
4198                                     n);
4199   GNUNET_STATISTICS_set (stats,
4200                          gettext_noop ("# bytes of payload decrypted"),
4201                          size - sizeof (struct EncryptedMessage),
4202                          GNUNET_NO);
4203   handle_peer_status_change (n);
4204   update_neighbour_performance (n, ats, ats_count);
4205   if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst, 
4206                                               n,
4207                                               &buf[sizeof (struct EncryptedMessage)], 
4208                                               size - sizeof (struct EncryptedMessage),
4209                                               GNUNET_YES, GNUNET_NO))
4210     GNUNET_break_op (0);
4211 }
4212
4213
4214 /**
4215  * Function called by the transport for each received message.
4216  *
4217  * @param cls closure
4218  * @param peer (claimed) identity of the other peer
4219  * @param message the message
4220  * @param ats performance data
4221  * @param ats_count number of entries in ats (excluding 0-termination)
4222  */
4223 static void
4224 handle_transport_receive (void *cls,
4225                           const struct GNUNET_PeerIdentity *peer,
4226                           const struct GNUNET_MessageHeader *message,
4227                           const struct GNUNET_TRANSPORT_ATS_Information *ats, 
4228                           uint32_t ats_count)
4229 {
4230   struct Neighbour *n;
4231   struct GNUNET_TIME_Absolute now;
4232   int up;
4233   uint16_t type;
4234   uint16_t size;
4235   int changed;
4236
4237 #if DEBUG_CORE
4238   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4239               "Received message of type %u from `%4s', demultiplexing.\n",
4240               (unsigned int) ntohs (message->type), 
4241               GNUNET_i2s (peer));
4242 #endif
4243   if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4244     {
4245       GNUNET_break (0);
4246       return;
4247     }
4248   n = find_neighbour (peer);
4249   if (n == NULL)
4250     n = create_neighbour (peer);
4251   changed = GNUNET_NO;
4252   up = (n->status == PEER_STATE_KEY_CONFIRMED);
4253   type = ntohs (message->type);
4254   size = ntohs (message->size);
4255   switch (type)
4256     {
4257     case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
4258       if (size != sizeof (struct SetKeyMessage))
4259         {
4260           GNUNET_break_op (0);
4261           return;
4262         }
4263       GNUNET_STATISTICS_update (stats,
4264                                 gettext_noop ("# session keys received"), 
4265                                 1, 
4266                                 GNUNET_NO);
4267       handle_set_key (n,
4268                       (const struct SetKeyMessage *) message,
4269                       ats, ats_count);
4270       break;
4271     case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
4272       if (size < sizeof (struct EncryptedMessage) +
4273           sizeof (struct GNUNET_MessageHeader))
4274         {
4275           GNUNET_break_op (0);
4276           return;
4277         }
4278       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
4279           (n->status != PEER_STATE_KEY_CONFIRMED))
4280         {
4281           GNUNET_STATISTICS_update (stats,
4282                                     gettext_noop ("# failed to decrypt message (no session key)"), 
4283                                     1, 
4284                                     GNUNET_NO);
4285           send_key (n);
4286           return;
4287         }
4288       handle_encrypted_message (n, 
4289                                 (const struct EncryptedMessage *) message,
4290                                 ats, ats_count);
4291       break;
4292     case GNUNET_MESSAGE_TYPE_CORE_PING:
4293       if (size != sizeof (struct PingMessage))
4294         {
4295           GNUNET_break_op (0);
4296           return;
4297         }
4298       GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
4299       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
4300           (n->status != PEER_STATE_KEY_CONFIRMED))
4301         {
4302 #if DEBUG_CORE
4303           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4304                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
4305                       "PING", GNUNET_i2s (&n->peer));
4306 #endif
4307           GNUNET_free_non_null (n->pending_ping);
4308           n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
4309           memcpy (n->pending_ping, message, sizeof (struct PingMessage));
4310           return;
4311         }
4312       handle_ping (n, (const struct PingMessage *) message,
4313                    ats, ats_count);
4314       break;
4315     case GNUNET_MESSAGE_TYPE_CORE_PONG:
4316       if (size != sizeof (struct PongMessage))
4317         {
4318           GNUNET_break_op (0);
4319           return;
4320         }
4321       GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
4322       if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
4323            (n->status != PEER_STATE_KEY_CONFIRMED) )
4324         {
4325 #if DEBUG_CORE
4326           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4327                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
4328                       "PONG", GNUNET_i2s (&n->peer));
4329 #endif
4330           GNUNET_free_non_null (n->pending_pong);
4331           n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
4332           memcpy (n->pending_pong, message, sizeof (struct PongMessage));
4333           return;
4334         }
4335       handle_pong (n, (const struct PongMessage *) message,
4336                    ats, ats_count);
4337       break;
4338     default:
4339       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4340                   _("Unsupported message of type %u received.\n"),
4341                   (unsigned int) type);
4342       return;
4343     }
4344   if (n->status == PEER_STATE_KEY_CONFIRMED)
4345     {
4346       now = GNUNET_TIME_absolute_get ();
4347       n->last_activity = now;
4348       changed = GNUNET_YES;
4349       if (!up)
4350         {
4351           GNUNET_STATISTICS_update (stats, 
4352                                     gettext_noop ("# established sessions"), 
4353                                     1, 
4354                                     GNUNET_NO);
4355           n->time_established = now;
4356         }
4357       if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
4358         GNUNET_SCHEDULER_cancel (n->keep_alive_task);
4359       n->keep_alive_task 
4360         = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
4361                                         &send_keep_alive,
4362                                         n);
4363     }
4364   if (changed)
4365     handle_peer_status_change (n);
4366 }
4367
4368
4369 /**
4370  * Function that recalculates the bandwidth quota for the
4371  * given neighbour and transmits it to the transport service.
4372  * 
4373  * @param cls neighbour for the quota update
4374  * @param tc context
4375  */
4376 static void
4377 neighbour_quota_update (void *cls,
4378                         const struct GNUNET_SCHEDULER_TaskContext *tc)
4379 {
4380   struct Neighbour *n = cls;
4381   struct GNUNET_BANDWIDTH_Value32NBO q_in;
4382   struct GNUNET_BANDWIDTH_Value32NBO q_out;
4383   struct GNUNET_BANDWIDTH_Value32NBO q_out_min;
4384   double pref_rel;
4385   double share;
4386   unsigned long long distributable;
4387   uint64_t need_per_peer;
4388   uint64_t need_per_second;
4389   unsigned int neighbour_count;
4390
4391 #if DEBUG_CORE
4392   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4393               "Neighbour quota update calculation running for peer `%4s'\n",
4394               GNUNET_i2s (&n->peer));  
4395 #endif
4396   n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
4397   /* calculate relative preference among all neighbours;
4398      divides by a bit more to avoid division by zero AND to
4399      account for possibility of new neighbours joining any time 
4400      AND to convert to double... */
4401   neighbour_count = GNUNET_CONTAINER_multihashmap_size (neighbours);
4402   if (neighbour_count == 0)
4403     return;
4404   if (preference_sum == 0)
4405     {
4406       pref_rel = 1.0 / (double) neighbour_count;
4407     }
4408   else
4409     {
4410       pref_rel = n->current_preference / preference_sum;
4411     }
4412   need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
4413                                                               GNUNET_TIME_UNIT_SECONDS);  
4414   need_per_second = need_per_peer * neighbour_count;
4415
4416   /* calculate inbound bandwidth per peer */
4417   distributable = 0;
4418   if (bandwidth_target_in_bps > need_per_second)
4419     distributable = bandwidth_target_in_bps - need_per_second;
4420   share = distributable * pref_rel;
4421   if (share + need_per_peer > UINT32_MAX)
4422     q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4423   else
4424     q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4425
4426   /* calculate outbound bandwidth per peer */
4427   distributable = 0;
4428   if (bandwidth_target_out_bps > need_per_second)
4429     distributable = bandwidth_target_out_bps - need_per_second;
4430   share = distributable * pref_rel;
4431   if (share + need_per_peer > UINT32_MAX)
4432     q_out = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4433   else
4434     q_out = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4435   n->bw_out_internal_limit = q_out;
4436
4437   q_out_min = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit, n->bw_out_internal_limit);
4438   GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window, n->bw_out);
4439
4440   /* check if we want to disconnect for good due to inactivity */
4441   if ( (GNUNET_TIME_absolute_get_duration (get_neighbour_timeout (n)).rel_value > 0) &&
4442        (GNUNET_TIME_absolute_get_duration (n->time_established).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) )
4443     {
4444 #if DEBUG_CORE
4445       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4446                   "Forcing disconnect of `%4s' due to inactivity\n",
4447                   GNUNET_i2s (&n->peer));
4448 #endif
4449       q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
4450     }
4451 #if DEBUG_CORE_QUOTA
4452   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4453               "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
4454               GNUNET_i2s (&n->peer),
4455               (unsigned int) ntohl (q_in.value__),
4456               bandwidth_target_out_bps,
4457               (unsigned int) ntohl (n->bw_in.value__),
4458               (unsigned int) ntohl (n->bw_out.value__),
4459               (unsigned int) ntohl (n->bw_out_internal_limit.value__));
4460   #endif
4461   if ((n->bw_in.value__ != q_in.value__) || (n->bw_out.value__ != q_out_min.value__))
4462     {
4463           if (n->bw_in.value__ != q_in.value__)
4464                   n->bw_in = q_in;
4465           if (n->bw_out.value__ != q_out_min.value__)
4466                   n->bw_out = q_out_min;
4467       if (GNUNET_YES == n->is_connected)
4468         GNUNET_TRANSPORT_set_quota (transport,
4469                                     &n->peer,
4470                                     n->bw_in,
4471                                     n->bw_out,
4472                                     GNUNET_TIME_UNIT_FOREVER_REL,
4473                                     NULL, NULL);
4474       handle_peer_status_change (n);
4475     }
4476   schedule_quota_update (n);
4477 }
4478
4479
4480 /**
4481  * Function called by transport to notify us that
4482  * a peer connected to us (on the network level).
4483  *
4484  * @param cls closure
4485  * @param peer the peer that connected
4486  * @param ats performance data
4487  * @param ats_count number of entries in ats (excluding 0-termination)
4488  */
4489 static void
4490 handle_transport_notify_connect (void *cls,
4491                                  const struct GNUNET_PeerIdentity *peer,
4492                                  const struct GNUNET_TRANSPORT_ATS_Information *ats,
4493                                  uint32_t ats_count)
4494 {
4495   struct Neighbour *n;
4496
4497   if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4498     {
4499       GNUNET_break (0);
4500       return;
4501     }
4502   n = find_neighbour (peer);
4503   if (n != NULL)
4504     {
4505       if (GNUNET_YES == n->is_connected)
4506         {
4507           /* duplicate connect notification!? */
4508           GNUNET_break (0);
4509           return;
4510         }
4511     }
4512   else
4513     {
4514       n = create_neighbour (peer);
4515     }
4516   GNUNET_STATISTICS_update (stats, 
4517                             gettext_noop ("# peers connected (transport)"), 
4518                             1, 
4519                             GNUNET_NO);
4520   n->is_connected = GNUNET_YES;      
4521   update_neighbour_performance (n, ats, ats_count);
4522   GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
4523                                  n->bw_out,
4524                                  MAX_WINDOW_TIME_S);
4525   GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
4526                                  n->bw_in,
4527                                  MAX_WINDOW_TIME_S);  
4528 #if DEBUG_CORE
4529   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4530               "Received connection from `%4s'.\n",
4531               GNUNET_i2s (&n->peer));
4532 #endif
4533   GNUNET_TRANSPORT_set_quota (transport,
4534                               &n->peer,
4535                               n->bw_in,
4536                               n->bw_out,
4537                               GNUNET_TIME_UNIT_FOREVER_REL,
4538                               NULL, NULL);
4539   send_key (n); 
4540 }
4541
4542
4543 /**
4544  * Function called by transport telling us that a peer
4545  * disconnected.
4546  *
4547  * @param cls closure
4548  * @param peer the peer that disconnected
4549  */
4550 static void
4551 handle_transport_notify_disconnect (void *cls,
4552                                     const struct GNUNET_PeerIdentity *peer)
4553 {
4554   struct DisconnectNotifyMessage cnm;
4555   struct Neighbour *n;
4556   struct ClientActiveRequest *car;
4557   struct GNUNET_TIME_Relative left;
4558
4559 #if DEBUG_CORE
4560   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4561               "Peer `%4s' disconnected from us; received notification from transport.\n", 
4562               GNUNET_i2s (peer));
4563 #endif
4564   n = find_neighbour (peer);
4565   if (n == NULL)
4566     {
4567       GNUNET_break (0);
4568       return;
4569     }
4570   GNUNET_break (n->is_connected == GNUNET_YES);
4571   if (n->status == PEER_STATE_KEY_CONFIRMED)
4572     {
4573       cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
4574       cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
4575       cnm.reserved = htonl (0);
4576       cnm.peer = *peer;
4577       send_to_all_clients (&cnm.header, GNUNET_NO, GNUNET_CORE_OPTION_SEND_DISCONNECT);
4578       GNUNET_STATISTICS_update (stats, 
4579                                 gettext_noop ("# established sessions"), 
4580                                 -1, 
4581                                 GNUNET_NO);
4582     }
4583
4584   /* On transport disconnect transport doesn't cancel requests, so must do so here. */
4585   if (n->th != NULL)
4586     {
4587       GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
4588       n->th = NULL;
4589     }
4590   n->is_connected = GNUNET_NO;
4591   n->status = PEER_STATE_DOWN;
4592   while (NULL != (car = n->active_client_request_head))
4593     {
4594       GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
4595                                    n->active_client_request_tail,
4596                                    car);
4597       GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
4598                                             &n->peer.hashPubKey,
4599                                             car);
4600       GNUNET_free (car);
4601     }
4602
4603   GNUNET_STATISTICS_update (stats, 
4604                             gettext_noop ("# peers connected (transport)"), 
4605                             -1, 
4606                             GNUNET_NO);
4607   if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
4608     GNUNET_SCHEDULER_cancel (n->dead_clean_task);
4609   left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4610                                         GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
4611   n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (), 
4612                                                     left);
4613   n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
4614                                                      &consider_free_task,
4615                                                      n);
4616 }
4617
4618
4619 /**
4620  * Wrapper around 'free_neighbour'; helper for 'cleaning_task'.
4621  */
4622 static int
4623 free_neighbour_helper (void *cls,
4624                        const GNUNET_HashCode *key,
4625                        void *value)
4626 {
4627   struct Neighbour *n = value;
4628
4629   free_neighbour (n);
4630   return GNUNET_OK;
4631 }
4632
4633
4634 /**
4635  * Last task run during shutdown.  Disconnects us from
4636  * the transport.
4637  */
4638 static void
4639 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4640 {
4641   struct Client *c;
4642
4643 #if DEBUG_CORE
4644   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4645               "Core service shutting down.\n");
4646 #endif
4647   GNUNET_CONTAINER_multihashmap_iterate (neighbours,
4648                                          &free_neighbour_helper,
4649                                          NULL);
4650   GNUNET_CONTAINER_multihashmap_destroy (neighbours);
4651   neighbours = NULL;
4652   GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), 0, GNUNET_NO);
4653   GNUNET_assert (transport != NULL);
4654   GNUNET_TRANSPORT_disconnect (transport);
4655   transport = NULL;
4656   GNUNET_SERVER_notification_context_destroy (notifier);
4657   notifier = NULL;
4658   while (NULL != (c = clients))
4659     handle_client_disconnect (NULL, c->client_handle);
4660   if (my_private_key != NULL)
4661     GNUNET_CRYPTO_rsa_key_free (my_private_key);
4662   if (stats != NULL)
4663     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4664   if (peerinfo != NULL)
4665     GNUNET_PEERINFO_disconnect (peerinfo);
4666   if (mst != NULL)
4667     GNUNET_SERVER_mst_destroy (mst);
4668 }
4669
4670
4671 /**
4672  * Initiate core service.
4673  *
4674  * @param cls closure
4675  * @param server the initialized server
4676  * @param c configuration to use
4677  */
4678 static void
4679 run (void *cls,
4680      struct GNUNET_SERVER_Handle *server,
4681      const struct GNUNET_CONFIGURATION_Handle *c)
4682 {
4683   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4684     {&handle_client_init, NULL,
4685      GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
4686     {&handle_client_iterate_peers, NULL,
4687      GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
4688      sizeof (struct GNUNET_MessageHeader)},
4689     {&handle_client_have_peer, NULL,
4690      GNUNET_MESSAGE_TYPE_CORE_PEER_CONNECTED,
4691      sizeof (struct GNUNET_MessageHeader) + sizeof(struct GNUNET_PeerIdentity)},
4692     {&handle_client_request_info, NULL,
4693      GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
4694      sizeof (struct RequestInfoMessage)},
4695     {&handle_client_send_request, NULL,
4696      GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST,
4697      sizeof (struct SendMessageRequest)},
4698     {&handle_client_send, NULL,
4699      GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
4700     {&handle_client_request_connect, NULL,
4701      GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
4702      sizeof (struct ConnectMessage)},
4703     {NULL, NULL, 0, 0}
4704   };
4705   char *keyfile;
4706
4707   cfg = c;    
4708   /* parse configuration */
4709   if (
4710        (GNUNET_OK !=
4711         GNUNET_CONFIGURATION_get_value_number (c,
4712                                                "CORE",
4713                                                "TOTAL_QUOTA_IN",
4714                                                &bandwidth_target_in_bps)) ||
4715        (GNUNET_OK !=
4716         GNUNET_CONFIGURATION_get_value_number (c,
4717                                                "CORE",
4718                                                "TOTAL_QUOTA_OUT",
4719                                                &bandwidth_target_out_bps)) ||
4720        (GNUNET_OK !=
4721         GNUNET_CONFIGURATION_get_value_filename (c,
4722                                                  "GNUNETD",
4723                                                  "HOSTKEY", &keyfile)))
4724     {
4725       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4726                   _
4727                   ("Core service is lacking key configuration settings.  Exiting.\n"));
4728       GNUNET_SCHEDULER_shutdown ();
4729       return;
4730     }
4731   peerinfo = GNUNET_PEERINFO_connect (cfg);
4732   if (NULL == peerinfo)
4733     {
4734       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4735                   _("Could not access PEERINFO service.  Exiting.\n"));
4736       GNUNET_SCHEDULER_shutdown ();
4737       GNUNET_free (keyfile);
4738       return;
4739     }
4740   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4741   GNUNET_free (keyfile);
4742   if (my_private_key == NULL)
4743     {
4744       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4745                   _("Core service could not access hostkey.  Exiting.\n"));
4746       GNUNET_PEERINFO_disconnect (peerinfo);
4747       GNUNET_SCHEDULER_shutdown ();
4748       return;
4749     }
4750   neighbours = GNUNET_CONTAINER_multihashmap_create (128);
4751   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4752   GNUNET_CRYPTO_hash (&my_public_key,
4753                       sizeof (my_public_key), &my_identity.hashPubKey);
4754   self.public_key = &my_public_key;
4755   self.peer = my_identity;
4756   self.last_activity = GNUNET_TIME_UNIT_FOREVER_ABS;
4757   self.status = PEER_STATE_KEY_CONFIRMED;
4758   self.is_connected = GNUNET_YES;
4759   /* setup notification */
4760   notifier = GNUNET_SERVER_notification_context_create (server, 
4761                                                         MAX_NOTIFY_QUEUE);
4762   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4763   /* setup transport connection */
4764   transport = GNUNET_TRANSPORT_connect (cfg,
4765                                         &my_identity,
4766                                         NULL,
4767                                         &handle_transport_receive,
4768                                         &handle_transport_notify_connect,
4769                                         &handle_transport_notify_disconnect);
4770   GNUNET_assert (NULL != transport);
4771   stats = GNUNET_STATISTICS_create ("core", cfg);
4772
4773   GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded CORE_SEND requests"), 0, GNUNET_NO);
4774   GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 0, GNUNET_NO);
4775
4776   mst = GNUNET_SERVER_mst_create (&deliver_message,
4777                                   NULL);
4778   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4779                                 &cleaning_task, NULL);
4780   /* process client requests */
4781   GNUNET_SERVER_add_handlers (server, handlers);
4782   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4783               _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
4784 }
4785
4786
4787
4788 /**
4789  * The main function for the transport service.
4790  *
4791  * @param argc number of arguments from the command line
4792  * @param argv command line arguments
4793  * @return 0 ok, 1 on error
4794  */
4795 int
4796 main (int argc, char *const *argv)
4797 {
4798   return (GNUNET_OK ==
4799           GNUNET_SERVICE_run (argc,
4800                               argv,
4801                               "core",
4802                               GNUNET_SERVICE_OPTION_NONE,
4803                               &run, NULL)) ? 0 : 1;
4804 }
4805
4806 /* end of gnunet-service-core.c */