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