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