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