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