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