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