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