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