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