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