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