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