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