(no commit message)
[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
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
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_CONTAINER_DLL_remove (n->active_client_request_head,
1379                                n->active_client_request_tail,
1380                                car);
1381   GNUNET_free (car);
1382   return GNUNET_YES;
1383 }
1384
1385
1386 /**
1387  * A client disconnected, clean up.
1388  *
1389  * @param cls closure
1390  * @param client identification of the client
1391  */
1392 static void
1393 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1394 {
1395   struct Client *pos;
1396   struct Client *prev;
1397
1398   if (client == NULL)
1399     return;
1400 #if DEBUG_CORE_CLIENT
1401   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1402               "Client %p has disconnected from core service.\n",
1403               client);
1404 #endif
1405   prev = NULL;
1406   pos = clients;
1407   while (pos != NULL)
1408     {
1409       if (client == pos->client_handle)
1410         break;
1411       prev = pos;
1412       pos = pos->next;
1413     }
1414   if (pos == NULL)
1415     {
1416       /* client never sent INIT */
1417       return;
1418     }
1419   if (prev == NULL)
1420     clients = pos->next;
1421   else
1422     prev->next = pos->next;
1423   if (pos->requests != NULL)
1424     {
1425       GNUNET_CONTAINER_multihashmap_iterate (pos->requests,
1426                                              &destroy_active_client_request,
1427                                              NULL);
1428       GNUNET_CONTAINER_multihashmap_destroy (pos->requests);
1429     }
1430   GNUNET_free (pos);
1431 }
1432
1433
1434 /**
1435  * Helper function for handle_client_iterate_peers.
1436  */
1437 static int
1438 queue_connect_message (void *cls,
1439                        const GNUNET_HashCode *key,
1440                        void *value)
1441 {
1442   struct GNUNET_SERVER_TransmitContext *tc = cls;
1443   struct Neighbour *n = value;
1444   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1445   struct GNUNET_TRANSPORT_ATS_Information *ats;
1446   size_t size;
1447   struct ConnectNotifyMessage *cnm;
1448
1449   cnm = (struct ConnectNotifyMessage*) buf;
1450   if (n->status != PEER_STATE_KEY_CONFIRMED)
1451     return GNUNET_OK;
1452   size = sizeof (struct ConnectNotifyMessage) +
1453     (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1454   if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1455     {
1456       GNUNET_break (0);
1457       /* recovery strategy: throw away performance data */
1458       GNUNET_array_grow (n->ats,
1459                          n->ats_count,
1460                          0);
1461       size = sizeof (struct PeerStatusNotifyMessage) +
1462         n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1463     }
1464   cnm = (struct ConnectNotifyMessage*) buf;
1465   cnm->header.size = htons (size);
1466   cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1467   cnm->ats_count = htonl (n->ats_count);
1468   ats = &cnm->ats;
1469   memcpy (ats,
1470           n->ats,
1471           n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
1472   ats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
1473   ats[n->ats_count].value = htonl (0);    
1474 #if DEBUG_CORE_CLIENT
1475   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1476               "Sending `%s' message to client.\n",
1477               "NOTIFY_CONNECT");
1478 #endif
1479   cnm->peer = n->peer;
1480   GNUNET_SERVER_transmit_context_append_message (tc, 
1481                                                  &cnm->header);
1482   return GNUNET_OK;
1483 }
1484
1485
1486 /**
1487  * Handle CORE_ITERATE_PEERS request.
1488  *
1489  * @param cls unused
1490  * @param client client sending the iteration request
1491  * @param message iteration request message
1492  */
1493 static void
1494 handle_client_iterate_peers (void *cls,
1495                              struct GNUNET_SERVER_Client *client,
1496                              const struct GNUNET_MessageHeader *message)
1497
1498 {
1499   struct GNUNET_MessageHeader done_msg;
1500   struct GNUNET_SERVER_TransmitContext *tc;
1501
1502   /* notify new client about existing neighbours */
1503   tc = GNUNET_SERVER_transmit_context_create (client);
1504   GNUNET_CONTAINER_multihashmap_iterate (neighbours, &queue_connect_message, tc);
1505   done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
1506   done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
1507   GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
1508   GNUNET_SERVER_transmit_context_run (tc,
1509                                       GNUNET_TIME_UNIT_FOREVER_REL);
1510 }
1511
1512
1513 /**
1514  * Handle REQUEST_INFO request.
1515  */
1516 static void
1517 handle_client_request_info (void *cls,
1518                             struct GNUNET_SERVER_Client *client,
1519                             const struct GNUNET_MessageHeader *message)
1520 {
1521   const struct RequestInfoMessage *rcm;
1522   struct Client *pos;
1523   struct Neighbour *n;
1524   struct ConfigurationInfoMessage cim;
1525   int32_t want_reserv;
1526   int32_t got_reserv;
1527   unsigned long long old_preference;
1528
1529 #if DEBUG_CORE_CLIENT
1530   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1531               "Core service receives `%s' request.\n", "REQUEST_INFO");
1532 #endif
1533   pos = clients;
1534   while (pos != NULL)
1535     {
1536       if (client == pos->client_handle)
1537         break;
1538       pos = pos->next;
1539     }
1540   if (pos == NULL)
1541     {
1542       GNUNET_break (0);
1543       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1544       return;
1545     }
1546
1547   rcm = (const struct RequestInfoMessage *) message;
1548   n = find_neighbour (&rcm->peer);
1549   memset (&cim, 0, sizeof (cim));
1550   if (n != NULL) 
1551     {
1552       want_reserv = ntohl (rcm->reserve_inbound);
1553       if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1554         {
1555           n->bw_out_internal_limit = rcm->limit_outbound;
1556           if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1557                                                                n->bw_out_external_limit).value__)
1558             {
1559               n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1560                                                       n->bw_out_external_limit);
1561               GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1562                                                      n->bw_out);
1563               GNUNET_TRANSPORT_set_quota (transport,
1564                                           &n->peer,
1565                                           n->bw_in,
1566                                           n->bw_out,
1567                                           GNUNET_TIME_UNIT_FOREVER_REL,
1568                                           NULL, NULL); 
1569               handle_peer_status_change (n);
1570             }
1571         }
1572       if (want_reserv < 0)
1573         {
1574           got_reserv = want_reserv;
1575         }
1576       else if (want_reserv > 0)
1577         {
1578           if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1579                                                   want_reserv).rel_value == 0)
1580             got_reserv = want_reserv;
1581           else
1582             got_reserv = 0; /* all or nothing */
1583         }
1584       else
1585         got_reserv = 0;
1586       GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1587                                         got_reserv);
1588       old_preference = n->current_preference;
1589       n->current_preference += GNUNET_ntohll(rcm->preference_change);
1590       if (old_preference > n->current_preference) 
1591         {
1592           /* overflow; cap at maximum value */
1593           n->current_preference = ULLONG_MAX;
1594         }
1595       update_preference_sum (n->current_preference - old_preference);
1596 #if DEBUG_CORE_QUOTA
1597       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1598                   "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1599                   (int) want_reserv,
1600                   GNUNET_i2s (&rcm->peer),
1601                   (int) got_reserv);
1602 #endif
1603       cim.reserved_amount = htonl (got_reserv);
1604       cim.rim_id = rcm->rim_id;
1605       cim.bw_out = n->bw_out;
1606       cim.preference = n->current_preference;
1607     }
1608   cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1609   cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1610   cim.peer = rcm->peer;
1611 #if DEBUG_CORE_CLIENT
1612   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1613               "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1614 #endif
1615   send_to_client (pos, &cim.header, GNUNET_NO);
1616   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1617 }
1618
1619
1620 /**
1621  * Free the given entry for the neighbour (it has
1622  * already been removed from the list at this point).
1623  *
1624  * @param n neighbour to free
1625  */
1626 static void
1627 free_neighbour (struct Neighbour *n)
1628 {
1629   struct MessageEntry *m;
1630   struct ClientActiveRequest *car;
1631
1632 #if DEBUG_CORE
1633   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1634               "Destroying neighbour entry for peer `%4s'\n",
1635               GNUNET_i2s (&n->peer));
1636 #endif
1637   if (n->pitr != NULL)
1638     {
1639       GNUNET_PEERINFO_iterate_cancel (n->pitr);
1640       n->pitr = NULL;
1641     }
1642   if (n->skm != NULL)
1643     {
1644       GNUNET_free (n->skm);
1645       n->skm = NULL;
1646     }
1647   while (NULL != (m = n->messages))
1648     {
1649       n->messages = m->next;
1650       GNUNET_free (m);
1651     }
1652   while (NULL != (m = n->encrypted_head))
1653     {
1654       GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1655                                    n->encrypted_tail,
1656                                    m);
1657       GNUNET_free (m);
1658     }
1659   while (NULL != (car = n->active_client_request_head))
1660     {
1661       GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1662                                    n->active_client_request_tail,
1663                                    car);
1664       GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
1665                                             &n->peer.hashPubKey,
1666                                             car);
1667       GNUNET_free (car);
1668     }
1669   if (NULL != n->th)
1670     {
1671       GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1672       n->th = NULL;
1673     }
1674   if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1675     GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
1676   if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1677     GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
1678   if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1679     GNUNET_SCHEDULER_cancel (n->quota_update_task);
1680   if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1681     GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1682   if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)    
1683       GNUNET_SCHEDULER_cancel (n->keep_alive_task);
1684   if (n->status == PEER_STATE_KEY_CONFIRMED)
1685     GNUNET_STATISTICS_update (stats, 
1686                               gettext_noop ("# established sessions"), 
1687                               -1, 
1688                               GNUNET_NO);
1689   GNUNET_array_grow (n->ats, n->ats_count, 0);
1690   GNUNET_free_non_null (n->public_key);
1691   GNUNET_free_non_null (n->pending_ping);
1692   GNUNET_free_non_null (n->pending_pong);
1693   GNUNET_free (n);
1694 }
1695
1696
1697 /**
1698  * Check if we have encrypted messages for the specified neighbour
1699  * pending, and if so, check with the transport about sending them
1700  * out.
1701  *
1702  * @param n neighbour to check.
1703  */
1704 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1705
1706
1707 /**
1708  * Encrypt size bytes from in and write the result to out.  Use the
1709  * key for outbound traffic of the given neighbour.
1710  *
1711  * @param n neighbour we are sending to
1712  * @param iv initialization vector to use
1713  * @param in ciphertext
1714  * @param out plaintext
1715  * @param size size of in/out
1716  * @return GNUNET_OK on success
1717  */
1718 static int
1719 do_encrypt (struct Neighbour *n,
1720             const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1721             const void *in, void *out, size_t size)
1722 {
1723   if (size != (uint16_t) size)
1724     {
1725       GNUNET_break (0);
1726       return GNUNET_NO;
1727     }
1728   GNUNET_assert (size ==
1729                  GNUNET_CRYPTO_aes_encrypt (in,
1730                                             (uint16_t) size,
1731                                             &n->encrypt_key,
1732                                             iv, out));
1733   GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1734 #if DEBUG_CORE
1735   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1736               "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
1737               (unsigned int) size,
1738               GNUNET_i2s (&n->peer),
1739               (unsigned int) n->encrypt_key.crc32,
1740               GNUNET_CRYPTO_crc32_n (iv, sizeof(iv)));
1741 #endif
1742   return GNUNET_OK;
1743 }
1744
1745
1746 /**
1747  * Consider freeing the given neighbour since we may not need
1748  * to keep it around anymore.
1749  *
1750  * @param n neighbour to consider discarding
1751  */
1752 static void
1753 consider_free_neighbour (struct Neighbour *n);
1754
1755
1756 /**
1757  * Task triggered when a neighbour entry is about to time out 
1758  * (and we should prevent this by sending a PING).
1759  *
1760  * @param cls the 'struct Neighbour'
1761  * @param tc scheduler context (not used)
1762  */
1763 static void
1764 send_keep_alive (void *cls,
1765                  const struct GNUNET_SCHEDULER_TaskContext *tc)
1766 {
1767   struct Neighbour *n = cls;
1768   struct GNUNET_TIME_Relative retry;
1769   struct GNUNET_TIME_Relative left;
1770   struct MessageEntry *me;
1771   struct PingMessage pp;
1772   struct PingMessage *pm;
1773   struct GNUNET_CRYPTO_AesInitializationVector iv;
1774
1775   n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1776   /* send PING */
1777   me = GNUNET_malloc (sizeof (struct MessageEntry) +
1778                       sizeof (struct PingMessage));
1779   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1780   me->priority = PING_PRIORITY;
1781   me->size = sizeof (struct PingMessage);
1782   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1783                                      n->encrypted_tail,
1784                                      n->encrypted_tail,
1785                                      me);
1786   pm = (struct PingMessage *) &me[1];
1787   pm->header.size = htons (sizeof (struct PingMessage));
1788   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1789   pm->iv_seed = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1790       UINT32_MAX);
1791   derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
1792   pp.challenge = n->ping_challenge;
1793   pp.target = n->peer;
1794 #if DEBUG_HANDSHAKE
1795   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1796               "Encrypting `%s' message with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
1797               "PING", 
1798               (unsigned int) n->ping_challenge,
1799               GNUNET_i2s (&n->peer),
1800               (unsigned int) n->encrypt_key.crc32,
1801               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
1802               pm->iv_seed);
1803 #endif
1804   do_encrypt (n,
1805               &iv,
1806               &pp.target,
1807               &pm->target,
1808               sizeof (struct PingMessage) -
1809               ((void *) &pm->target - (void *) pm));
1810   process_encrypted_neighbour_queue (n);
1811   /* reschedule PING job */
1812   left = GNUNET_TIME_absolute_get_remaining (get_neighbour_timeout (n));
1813   retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1814                                     MIN_PING_FREQUENCY);
1815   n->keep_alive_task 
1816     = GNUNET_SCHEDULER_add_delayed (retry,
1817                                     &send_keep_alive,
1818                                     n);
1819
1820 }
1821
1822
1823 /**
1824  * Task triggered when a neighbour entry might have gotten stale.
1825  *
1826  * @param cls the 'struct Neighbour'
1827  * @param tc scheduler context (not used)
1828  */
1829 static void
1830 consider_free_task (void *cls,
1831                     const struct GNUNET_SCHEDULER_TaskContext *tc)
1832 {
1833   struct Neighbour *n = cls;
1834
1835   n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1836   consider_free_neighbour (n);
1837 }
1838
1839
1840 /**
1841  * Consider freeing the given neighbour since we may not need
1842  * to keep it around anymore.
1843  *
1844  * @param n neighbour to consider discarding
1845  */
1846 static void
1847 consider_free_neighbour (struct Neighbour *n)
1848
1849   struct GNUNET_TIME_Relative left;
1850
1851   if ( (n->th != NULL) ||
1852        (n->pitr != NULL) ||
1853        (GNUNET_YES == n->is_connected) )
1854     return; /* no chance */
1855     
1856   left = GNUNET_TIME_absolute_get_remaining (get_neighbour_timeout (n));
1857   if (left.rel_value > 0)
1858     {
1859       if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1860         GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1861       n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (left,
1862                                                          &consider_free_task,
1863                                                          n);
1864       return;
1865     }
1866   /* actually free the neighbour... */
1867   GNUNET_assert (GNUNET_OK ==
1868                  GNUNET_CONTAINER_multihashmap_remove (neighbours,
1869                                                        &n->peer.hashPubKey,
1870                                                        n));
1871   GNUNET_STATISTICS_set (stats,
1872                          gettext_noop ("# neighbour entries allocated"), 
1873                          GNUNET_CONTAINER_multihashmap_size (neighbours),
1874                          GNUNET_NO);
1875   free_neighbour (n);
1876 }
1877
1878
1879 /**
1880  * Function called when the transport service is ready to
1881  * receive an encrypted message for the respective peer
1882  *
1883  * @param cls neighbour to use message from
1884  * @param size number of bytes we can transmit
1885  * @param buf where to copy the message
1886  * @return number of bytes transmitted
1887  */
1888 static size_t
1889 notify_encrypted_transmit_ready (void *cls, 
1890                                  size_t size, 
1891                                  void *buf)
1892 {
1893   struct Neighbour *n = cls;
1894   struct MessageEntry *m;
1895   size_t ret;
1896   char *cbuf;
1897
1898   n->th = NULL;
1899   m = n->encrypted_head;
1900   if (m == NULL)
1901     {
1902 #if DEBUG_CORE
1903       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1904                   "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1905                   GNUNET_i2s (&n->peer));
1906 #endif
1907       return 0;
1908     }
1909   GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1910                                n->encrypted_tail,
1911                                m);
1912   ret = 0;
1913   cbuf = buf;
1914   if (buf != NULL)
1915     {
1916       GNUNET_assert (size >= m->size);
1917       memcpy (cbuf, &m[1], m->size);
1918       ret = m->size;
1919       GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1920                                         m->size);
1921 #if DEBUG_CORE
1922       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1923                   "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1924                   (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1925                   (unsigned int) ret, 
1926                   GNUNET_i2s (&n->peer));
1927 #endif
1928       process_encrypted_neighbour_queue (n);
1929     }
1930   else
1931     {
1932 #if DEBUG_CORE
1933       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1934                   "Transmission of message of type %u and size %u failed\n",
1935                   (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1936                   (unsigned int) m->size);
1937 #endif
1938     }
1939   GNUNET_free (m);
1940   consider_free_neighbour (n);
1941   GNUNET_STATISTICS_update (stats, 
1942                             gettext_noop ("# encrypted bytes given to transport"), 
1943                             ret, 
1944                             GNUNET_NO);
1945   return ret;
1946 }
1947
1948
1949 /**
1950  * Check if we have plaintext messages for the specified neighbour
1951  * pending, and if so, consider batching and encrypting them (and
1952  * then trigger processing of the encrypted queue if needed).
1953  *
1954  * @param n neighbour to check.
1955  */
1956 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1957
1958
1959 /**
1960  * Check if we have encrypted messages for the specified neighbour
1961  * pending, and if so, check with the transport about sending them
1962  * out.
1963  *
1964  * @param n neighbour to check.
1965  */
1966 static void
1967 process_encrypted_neighbour_queue (struct Neighbour *n)
1968 {
1969   struct MessageEntry *m;
1970  
1971   if (n->th != NULL)
1972     return;  /* request already pending */
1973   m = n->encrypted_head;
1974   if (m == NULL)
1975     {
1976       /* encrypted queue empty, try plaintext instead */
1977       process_plaintext_neighbour_queue (n);
1978       return;
1979     }
1980 #if DEBUG_CORE
1981   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1982               "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1983               (unsigned int) m->size,
1984               GNUNET_i2s (&n->peer),
1985               (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).rel_value);
1986 #endif
1987   n->th =
1988     GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1989                                             m->size,
1990                                             m->priority,
1991                                             GNUNET_TIME_absolute_get_remaining
1992                                             (m->deadline),
1993                                             &notify_encrypted_transmit_ready,
1994                                             n);
1995   if (n->th == NULL)
1996     {
1997       /* message request too large or duplicate request */
1998       GNUNET_break (0);
1999       /* discard encrypted message */
2000       GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2001                                    n->encrypted_tail,
2002                                    m);
2003       GNUNET_free (m);
2004       process_encrypted_neighbour_queue (n);
2005     }
2006 }
2007
2008
2009 /**
2010  * Decrypt size bytes from in and write the result to out.  Use the
2011  * key for inbound traffic of the given neighbour.  This function does
2012  * NOT do any integrity-checks on the result.
2013  *
2014  * @param n neighbour we are receiving from
2015  * @param iv initialization vector to use
2016  * @param in ciphertext
2017  * @param out plaintext
2018  * @param size size of in/out
2019  * @return GNUNET_OK on success
2020  */
2021 static int
2022 do_decrypt (struct Neighbour *n,
2023             const struct GNUNET_CRYPTO_AesInitializationVector * iv,
2024             const void *in, void *out, size_t size)
2025 {
2026   if (size != (uint16_t) size)
2027     {
2028       GNUNET_break (0);
2029       return GNUNET_NO;
2030     }
2031   if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2032       (n->status != PEER_STATE_KEY_CONFIRMED))
2033     {
2034       GNUNET_break_op (0);
2035       return GNUNET_SYSERR;
2036     }
2037   if (size !=
2038       GNUNET_CRYPTO_aes_decrypt (in,
2039                                  (uint16_t) size,
2040                                  &n->decrypt_key,
2041                                  iv,
2042                                  out))
2043     {
2044       GNUNET_break (0);
2045       return GNUNET_SYSERR;
2046     }
2047   GNUNET_STATISTICS_update (stats, 
2048                             gettext_noop ("# bytes decrypted"), 
2049                             size, 
2050                             GNUNET_NO);
2051 #if DEBUG_CORE
2052   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2053               "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
2054               (unsigned int) size, 
2055               GNUNET_i2s (&n->peer),
2056               (unsigned int) n->decrypt_key.crc32,
2057               GNUNET_CRYPTO_crc32_n (iv, sizeof(*iv)));
2058 #endif
2059   return GNUNET_OK;
2060 }
2061
2062
2063 /**
2064  * Select messages for transmission.  This heuristic uses a combination
2065  * of earliest deadline first (EDF) scheduling (with bounded horizon)
2066  * and priority-based discard (in case no feasible schedule exist) and
2067  * speculative optimization (defer any kind of transmission until
2068  * we either create a batch of significant size, 25% of max, or until
2069  * we are close to a deadline).  Furthermore, when scheduling the
2070  * heuristic also packs as many messages into the batch as possible,
2071  * starting with those with the earliest deadline.  Yes, this is fun.
2072  *
2073  * @param n neighbour to select messages from
2074  * @param size number of bytes to select for transmission
2075  * @param retry_time set to the time when we should try again
2076  *        (only valid if this function returns zero)
2077  * @return number of bytes selected, or 0 if we decided to
2078  *         defer scheduling overall; in that case, retry_time is set.
2079  */
2080 static size_t
2081 select_messages (struct Neighbour *n,
2082                  size_t size, struct GNUNET_TIME_Relative *retry_time)
2083 {
2084   struct MessageEntry *pos;
2085   struct MessageEntry *min;
2086   struct MessageEntry *last;
2087   unsigned int min_prio;
2088   struct GNUNET_TIME_Absolute t;
2089   struct GNUNET_TIME_Absolute now;
2090   struct GNUNET_TIME_Relative delta;
2091   uint64_t avail;
2092   struct GNUNET_TIME_Relative slack;     /* how long could we wait before missing deadlines? */
2093   size_t off;
2094   uint64_t tsize;
2095   unsigned int queue_size;
2096   int discard_low_prio;
2097
2098   GNUNET_assert (NULL != n->messages);
2099   now = GNUNET_TIME_absolute_get ();
2100   /* last entry in linked list of messages processed */
2101   last = NULL;
2102   /* should we remove the entry with the lowest
2103      priority from consideration for scheduling at the
2104      end of the loop? */
2105   queue_size = 0;
2106   tsize = 0;
2107   pos = n->messages;
2108   while (pos != NULL)
2109     {
2110       queue_size++;
2111       tsize += pos->size;
2112       pos = pos->next;
2113     }
2114   discard_low_prio = GNUNET_YES;
2115   while (GNUNET_YES == discard_low_prio)
2116     {
2117       min = NULL;
2118       min_prio = UINT_MAX;
2119       discard_low_prio = GNUNET_NO;
2120       /* calculate number of bytes available for transmission at time "t" */
2121       avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
2122       t = now;
2123       /* how many bytes have we (hypothetically) scheduled so far */
2124       off = 0;
2125       /* maximum time we can wait before transmitting anything
2126          and still make all of our deadlines */
2127       slack = GNUNET_TIME_UNIT_FOREVER_REL;
2128       pos = n->messages;
2129       /* note that we use "*2" here because we want to look
2130          a bit further into the future; much more makes no
2131          sense since new message might be scheduled in the
2132          meantime... */
2133       while ((pos != NULL) && (off < size * 2))
2134         {         
2135           if (pos->do_transmit == GNUNET_YES)
2136             {
2137               /* already removed from consideration */
2138               pos = pos->next;
2139               continue;
2140             }
2141           if (discard_low_prio == GNUNET_NO)
2142             {
2143               delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
2144               if (delta.rel_value > 0)
2145                 {
2146                   // FIXME: HUH? Check!
2147                   t = pos->deadline;
2148                   avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
2149                                                                        delta);
2150                 }
2151               if (avail < pos->size)
2152                 {
2153                   // FIXME: HUH? Check!
2154                   discard_low_prio = GNUNET_YES;        /* we could not schedule this one! */
2155                 }
2156               else
2157                 {
2158                   avail -= pos->size;
2159                   /* update slack, considering both its absolute deadline
2160                      and relative deadlines caused by other messages
2161                      with their respective load */
2162                   slack = GNUNET_TIME_relative_min (slack,
2163                                                     GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
2164                                                                                           avail));
2165                   if (pos->deadline.abs_value <= now.abs_value) 
2166                     {
2167                       /* now or never */
2168                       slack = GNUNET_TIME_UNIT_ZERO;
2169                     }
2170                   else if (GNUNET_YES == pos->got_slack)
2171                     {
2172                       /* should be soon now! */
2173                       slack = GNUNET_TIME_relative_min (slack,
2174                                                         GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
2175                     }
2176                   else
2177                     {
2178                       slack =
2179                         GNUNET_TIME_relative_min (slack, 
2180                                                   GNUNET_TIME_absolute_get_difference (now, pos->deadline));
2181                       pos->got_slack = GNUNET_YES;
2182                       pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
2183                                                                       GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
2184                     }
2185                 }
2186             }
2187           off += pos->size;
2188           t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
2189           if (pos->priority <= min_prio)
2190             {
2191               /* update min for discard */
2192               min_prio = pos->priority;
2193               min = pos;
2194             }
2195           pos = pos->next;
2196         }
2197       if (discard_low_prio)
2198         {
2199           GNUNET_assert (min != NULL);
2200           /* remove lowest-priority entry from consideration */
2201           min->do_transmit = GNUNET_YES;        /* means: discard (for now) */
2202         }
2203       last = pos;
2204     }
2205   /* guard against sending "tiny" messages with large headers without
2206      urgent deadlines */
2207   if ( (slack.rel_value > GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value) && 
2208        (size > 4 * off) &&
2209        (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
2210     {
2211       /* less than 25% of message would be filled with deadlines still
2212          being met if we delay by one second or more; so just wait for
2213          more data; but do not wait longer than 1s (since we don't want
2214          to delay messages for a really long time either). */
2215       *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
2216       /* reset do_transmit values for next time */
2217       while (pos != last)
2218         {
2219           pos->do_transmit = GNUNET_NO;   
2220           pos = pos->next;
2221         }
2222       GNUNET_STATISTICS_update (stats, 
2223                                 gettext_noop ("# transmissions delayed due to corking"), 
2224                                 1, GNUNET_NO);
2225 #if DEBUG_CORE
2226       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2227                   "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
2228                   (unsigned long long) retry_time->rel_value,
2229                   (unsigned int) off,
2230                   (unsigned int) size);
2231 #endif
2232       return 0;
2233     }
2234   /* select marked messages (up to size) for transmission */
2235   off = 0;
2236   pos = n->messages;
2237   while (pos != last)
2238     {
2239       if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
2240         {
2241           pos->do_transmit = GNUNET_YES;        /* mark for transmission */
2242           off += pos->size;
2243           size -= pos->size;
2244 #if DEBUG_CORE
2245           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2246                       "Selecting message of size %u for transmission\n",
2247                       (unsigned int) pos->size);
2248 #endif
2249         }
2250       else
2251         {
2252 #if DEBUG_CORE
2253           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2254                       "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
2255                       (unsigned int) pos->size,
2256                       size);
2257 #endif
2258           pos->do_transmit = GNUNET_NO;   /* mark for not transmitting! */
2259         }
2260       pos = pos->next;
2261     }
2262 #if DEBUG_CORE
2263   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2264               "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
2265               (unsigned long long) off, (unsigned long long) tsize,
2266               queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
2267               GNUNET_i2s (&n->peer));
2268 #endif
2269   return off;
2270 }
2271
2272
2273 /**
2274  * Batch multiple messages into a larger buffer.
2275  *
2276  * @param n neighbour to take messages from
2277  * @param buf target buffer
2278  * @param size size of buf
2279  * @param deadline set to transmission deadline for the result
2280  * @param retry_time set to the time when we should try again
2281  *        (only valid if this function returns zero)
2282  * @param priority set to the priority of the batch
2283  * @return number of bytes written to buf (can be zero)
2284  */
2285 static size_t
2286 batch_message (struct Neighbour *n,
2287                char *buf,
2288                size_t size,
2289                struct GNUNET_TIME_Absolute *deadline,
2290                struct GNUNET_TIME_Relative *retry_time,
2291                unsigned int *priority)
2292 {
2293   char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
2294   struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
2295   struct MessageEntry *pos;
2296   struct MessageEntry *prev;
2297   struct MessageEntry *next;
2298   size_t ret;
2299   
2300   ret = 0;
2301   *priority = 0;
2302   *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2303   *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
2304   if (0 == select_messages (n, size, retry_time))
2305     {
2306 #if DEBUG_CORE
2307       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2308                   "No messages selected, will try again in %llu ms\n",
2309                   retry_time->rel_value);
2310 #endif
2311       return 0;
2312     }
2313   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
2314   ntm->ats_count = htonl (0);
2315   ntm->ats.type = htonl (0);
2316   ntm->ats.value = htonl (0);
2317   ntm->peer = n->peer;
2318   pos = n->messages;
2319   prev = NULL;
2320   while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
2321     {
2322       next = pos->next;
2323       if (GNUNET_YES == pos->do_transmit)
2324         {
2325           GNUNET_assert (pos->size <= size);
2326           /* do notifications */
2327           /* FIXME: track if we have *any* client that wants
2328              full notifications and only do this if that is
2329              actually true */
2330           if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
2331             {
2332               memcpy (&ntm[1], &pos[1], pos->size);
2333               ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) + 
2334                                         sizeof (struct GNUNET_MessageHeader));
2335               send_to_all_clients (&ntm->header,
2336                                    GNUNET_YES,
2337                                    GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
2338             }
2339           else
2340             {
2341               /* message too large for 'full' notifications, we do at
2342                  least the 'hdr' type */
2343               memcpy (&ntm[1],
2344                       &pos[1],
2345                       sizeof (struct GNUNET_MessageHeader));
2346             }
2347           ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) + 
2348                                     pos->size);
2349           send_to_all_clients (&ntm->header,
2350                                GNUNET_YES,
2351                                GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);   
2352 #if DEBUG_HANDSHAKE
2353           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2354                       "Encrypting %u bytes with message of type %u and size %u\n",
2355                       pos->size,
2356                       (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
2357                       (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
2358 #endif
2359           /* copy for encrypted transmission */
2360           memcpy (&buf[ret], &pos[1], pos->size);
2361           ret += pos->size;
2362           size -= pos->size;
2363           *priority += pos->priority;
2364 #if DEBUG_CORE
2365           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2366                       "Adding plaintext message of size %u with deadline %llu ms to batch\n",
2367                       (unsigned int) pos->size,
2368                       (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).rel_value);
2369 #endif
2370           deadline->abs_value = GNUNET_MIN (deadline->abs_value, pos->deadline.abs_value);
2371           GNUNET_free (pos);
2372           if (prev == NULL)
2373             n->messages = next;
2374           else
2375             prev->next = next;
2376         }
2377       else
2378         {
2379           prev = pos;
2380         }
2381       pos = next;
2382     }
2383 #if DEBUG_CORE
2384   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2385               "Deadline for message batch is %llu ms\n",
2386               GNUNET_TIME_absolute_get_remaining (*deadline).rel_value);
2387 #endif
2388   return ret;
2389 }
2390
2391
2392 /**
2393  * Remove messages with deadlines that have long expired from
2394  * the queue.
2395  *
2396  * @param n neighbour to inspect
2397  */
2398 static void
2399 discard_expired_messages (struct Neighbour *n)
2400 {
2401   struct MessageEntry *prev;
2402   struct MessageEntry *next;
2403   struct MessageEntry *pos;
2404   struct GNUNET_TIME_Absolute now;
2405   struct GNUNET_TIME_Relative delta;
2406   int disc;
2407
2408   disc = GNUNET_NO;
2409   now = GNUNET_TIME_absolute_get ();
2410   prev = NULL;
2411   pos = n->messages;
2412   while (pos != NULL) 
2413     {
2414       next = pos->next;
2415       delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
2416       if (delta.rel_value > PAST_EXPIRATION_DISCARD_TIME.rel_value)
2417         {
2418 #if DEBUG_CORE
2419           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2420                       "Message is %llu ms past due, discarding.\n",
2421                       delta.rel_value);
2422 #endif
2423           if (prev == NULL)
2424             n->messages = next;
2425           else
2426             prev->next = next;
2427           GNUNET_STATISTICS_update (stats, 
2428                                     gettext_noop ("# messages discarded (expired prior to transmission)"), 
2429                                     1, 
2430                                     GNUNET_NO);
2431           disc = GNUNET_YES;
2432           GNUNET_free (pos);
2433         }
2434       else
2435         prev = pos;
2436       pos = next;
2437     }
2438   if (GNUNET_YES == disc)
2439     schedule_peer_messages (n);
2440 }
2441
2442
2443 /**
2444  * Signature of the main function of a task.
2445  *
2446  * @param cls closure
2447  * @param tc context information (why was this task triggered now)
2448  */
2449 static void
2450 retry_plaintext_processing (void *cls,
2451                             const struct GNUNET_SCHEDULER_TaskContext *tc)
2452 {
2453   struct Neighbour *n = cls;
2454
2455   n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2456   process_plaintext_neighbour_queue (n);
2457 }
2458
2459
2460 /**
2461  * Send our key (and encrypted PING) to the other peer.
2462  *
2463  * @param n the other peer
2464  */
2465 static void send_key (struct Neighbour *n);
2466
2467 /**
2468  * Task that will retry "send_key" if our previous attempt failed
2469  * to yield a PONG.
2470  */
2471 static void
2472 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2473 {
2474   struct Neighbour *n = cls;
2475
2476 #if DEBUG_CORE
2477   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2478               "Retrying key transmission to `%4s'\n",
2479               GNUNET_i2s (&n->peer));
2480 #endif
2481   n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2482   n->set_key_retry_frequency =
2483     GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2484   send_key (n);
2485 }
2486
2487
2488 /**
2489  * Check if we have plaintext messages for the specified neighbour
2490  * pending, and if so, consider batching and encrypting them (and
2491  * then trigger processing of the encrypted queue if needed).
2492  *
2493  * @param n neighbour to check.
2494  */
2495 static void
2496 process_plaintext_neighbour_queue (struct Neighbour *n)
2497 {
2498   char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)];        /* plaintext */
2499   size_t used;
2500   struct EncryptedMessage *em;  /* encrypted message */
2501   struct EncryptedMessage *ph;  /* plaintext header */
2502   struct MessageEntry *me;
2503   unsigned int priority;
2504   struct GNUNET_TIME_Absolute deadline;
2505   struct GNUNET_TIME_Relative retry_time;
2506   struct GNUNET_CRYPTO_AesInitializationVector iv;
2507   struct GNUNET_CRYPTO_AuthKey auth_key;
2508
2509   if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2510     {
2511       GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
2512       n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2513     }
2514   switch (n->status)
2515     {
2516     case PEER_STATE_DOWN:
2517       send_key (n);
2518 #if DEBUG_CORE
2519       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2520                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2521                   GNUNET_i2s(&n->peer));
2522 #endif
2523       return;
2524     case PEER_STATE_KEY_SENT:
2525       if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2526         n->retry_set_key_task
2527           = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2528                                           &set_key_retry_task, n);    
2529 #if DEBUG_CORE
2530       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2531                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2532                   GNUNET_i2s(&n->peer));
2533 #endif
2534       return;
2535     case PEER_STATE_KEY_RECEIVED:
2536       if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)        
2537         n->retry_set_key_task
2538           = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2539                                           &set_key_retry_task, n);        
2540 #if DEBUG_CORE
2541       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2542                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2543                   GNUNET_i2s(&n->peer));
2544 #endif
2545       return;
2546     case PEER_STATE_KEY_CONFIRMED:
2547       /* ready to continue */
2548       break;
2549     }
2550   discard_expired_messages (n);
2551   if (n->messages == NULL)
2552     {
2553 #if DEBUG_CORE
2554       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2555                   "Plaintext message queue for `%4s' is empty.\n",
2556                   GNUNET_i2s(&n->peer));
2557 #endif
2558       return;                   /* no pending messages */
2559     }
2560   if (n->encrypted_head != NULL)
2561     {
2562 #if DEBUG_CORE
2563       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2564                   "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2565                   GNUNET_i2s(&n->peer));
2566 #endif
2567       return;                   /* wait for messages already encrypted to be
2568                                    processed first! */
2569     }
2570   ph = (struct EncryptedMessage *) pbuf;
2571   deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2572   priority = 0;
2573   used = sizeof (struct EncryptedMessage);
2574   used += batch_message (n,
2575                          &pbuf[used],
2576                          GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2577                          &deadline, &retry_time, &priority);
2578   if (used == sizeof (struct EncryptedMessage))
2579     {
2580 #if DEBUG_CORE
2581       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2582                   "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2583                   GNUNET_i2s(&n->peer));
2584 #endif
2585       /* no messages selected for sending, try again later... */
2586       n->retry_plaintext_task =
2587         GNUNET_SCHEDULER_add_delayed (retry_time,
2588                                       &retry_plaintext_processing, n);
2589       return;
2590     }
2591 #if DEBUG_CORE_QUOTA
2592   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2593               "Sending %u b/s as new limit to peer `%4s'\n",
2594               (unsigned int) ntohl (n->bw_in.value__),
2595               GNUNET_i2s (&n->peer));
2596 #endif
2597   ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
2598   ph->sequence_number = htonl (++n->last_sequence_number_sent);
2599   ph->inbound_bw_limit = n->bw_in;
2600   ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2601
2602   /* setup encryption message header */
2603   me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2604   me->deadline = deadline;
2605   me->priority = priority;
2606   me->size = used;
2607   em = (struct EncryptedMessage *) &me[1];
2608   em->header.size = htons (used);
2609   em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2610   em->iv_seed = ph->iv_seed;
2611   derive_iv (&iv, &n->encrypt_key, ph->iv_seed, &n->peer);
2612   /* encrypt */
2613 #if DEBUG_HANDSHAKE
2614   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2615               "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2616               (unsigned int) used - ENCRYPTED_HEADER_SIZE,
2617               GNUNET_i2s(&n->peer),
2618               (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).rel_value);
2619 #endif
2620   GNUNET_assert (GNUNET_OK ==
2621                  do_encrypt (n,
2622                              &iv,
2623                              &ph->sequence_number,
2624                              &em->sequence_number, used - ENCRYPTED_HEADER_SIZE));
2625   derive_auth_key (&auth_key,
2626                    &n->encrypt_key,
2627                    ph->iv_seed,
2628                    n->encrypt_key_created);
2629   GNUNET_CRYPTO_hmac (&auth_key,
2630                       &em->sequence_number,
2631                       used - ENCRYPTED_HEADER_SIZE,
2632                       &em->hmac);
2633 #if DEBUG_HANDSHAKE
2634   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2635               "Authenticated %u bytes of ciphertext %u: `%s'\n",
2636               used - ENCRYPTED_HEADER_SIZE,
2637               GNUNET_CRYPTO_crc32_n (&em->sequence_number,
2638                   used - ENCRYPTED_HEADER_SIZE),
2639               GNUNET_h2s (&em->hmac));
2640 #endif
2641   /* append to transmission list */
2642   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2643                                      n->encrypted_tail,
2644                                      n->encrypted_tail,
2645                                      me);
2646   process_encrypted_neighbour_queue (n);
2647   schedule_peer_messages (n);
2648 }
2649
2650
2651 /**
2652  * Function that recalculates the bandwidth quota for the
2653  * given neighbour and transmits it to the transport service.
2654  * 
2655  * @param cls neighbour for the quota update
2656  * @param tc context
2657  */
2658 static void
2659 neighbour_quota_update (void *cls,
2660                         const struct GNUNET_SCHEDULER_TaskContext *tc);
2661
2662
2663 /**
2664  * Schedule the task that will recalculate the bandwidth
2665  * quota for this peer (and possibly force a disconnect of
2666  * idle peers by calculating a bandwidth of zero).
2667  */
2668 static void
2669 schedule_quota_update (struct Neighbour *n)
2670 {
2671   GNUNET_assert (n->quota_update_task ==
2672                  GNUNET_SCHEDULER_NO_TASK);
2673   n->quota_update_task
2674     = GNUNET_SCHEDULER_add_delayed (QUOTA_UPDATE_FREQUENCY,
2675                                     &neighbour_quota_update,
2676                                     n);
2677 }
2678
2679
2680 /**
2681  * Initialize a new 'struct Neighbour'.
2682  *
2683  * @param pid ID of the new neighbour
2684  * @return handle for the new neighbour
2685  */
2686 static struct Neighbour *
2687 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2688 {
2689   struct Neighbour *n;
2690   struct GNUNET_TIME_Absolute now;
2691
2692 #if DEBUG_CORE
2693   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2694               "Creating neighbour entry for peer `%4s'\n",
2695               GNUNET_i2s (pid));
2696 #endif
2697   n = GNUNET_malloc (sizeof (struct Neighbour));
2698   n->peer = *pid;
2699   GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2700   now = GNUNET_TIME_absolute_get ();
2701   n->encrypt_key_created = now;
2702   n->last_activity = now;
2703   n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2704   n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2705   n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2706   n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2707   n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2708   n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
2709                                                 UINT32_MAX);
2710   GNUNET_assert (GNUNET_OK == 
2711                  GNUNET_CONTAINER_multihashmap_put (neighbours,
2712                                                     &n->peer.hashPubKey,
2713                                                     n,
2714                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2715   GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), 
2716                          GNUNET_CONTAINER_multihashmap_size (neighbours), GNUNET_NO);
2717   neighbour_quota_update (n, NULL);
2718   consider_free_neighbour (n);
2719   return n;
2720 }
2721
2722
2723 /**
2724  * Handle CORE_SEND request.
2725  *
2726  * @param cls unused
2727  * @param client the client issuing the request
2728  * @param message the "struct SendMessage"
2729  */
2730 static void
2731 handle_client_send (void *cls,
2732                     struct GNUNET_SERVER_Client *client,
2733                     const struct GNUNET_MessageHeader *message)
2734 {
2735   const struct SendMessage *sm;
2736   struct Neighbour *n;
2737   struct MessageEntry *prev;
2738   struct MessageEntry *pos;
2739   struct MessageEntry *e; 
2740   struct MessageEntry *min_prio_entry;
2741   struct MessageEntry *min_prio_prev;
2742   unsigned int min_prio;
2743   unsigned int queue_size;
2744   uint16_t msize;
2745
2746   msize = ntohs (message->size);
2747   if (msize <
2748       sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2749     {
2750       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));
2751       GNUNET_break (0);
2752       if (client != NULL)
2753         GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2754       return;
2755     }
2756   sm = (const struct SendMessage *) message;
2757   msize -= sizeof (struct SendMessage);
2758   if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2759     {
2760       /* loopback */
2761       GNUNET_SERVER_mst_receive (mst,
2762                                  &self,
2763                                  (const char*) &sm[1],
2764                                  msize,
2765                                  GNUNET_YES,
2766                                  GNUNET_NO);
2767       if (client != NULL)
2768         GNUNET_SERVER_receive_done (client, GNUNET_OK);
2769       return;
2770     }
2771   n = find_neighbour (&sm->peer);
2772   if (n == NULL)
2773     n = create_neighbour (&sm->peer);
2774 #if DEBUG_CORE
2775   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2776               "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2777               "SEND",
2778               (unsigned int) msize, 
2779               GNUNET_i2s (&sm->peer));
2780 #endif
2781   discard_expired_messages (n);
2782   /* bound queue size */
2783   /* NOTE: this entire block to bound the queue size should be
2784      obsolete with the new client-request code and the
2785      'schedule_peer_messages' mechanism; we still have this code in
2786      here for now as a sanity check for the new mechanmism;
2787      ultimately, we should probably simply reject SEND messages that
2788      are not 'approved' (or provide a new core API for very unreliable
2789      delivery that always sends with priority 0).  Food for thought. */
2790   min_prio = UINT32_MAX;
2791   min_prio_entry = NULL;
2792   min_prio_prev = NULL;
2793   queue_size = 0;
2794   prev = NULL;
2795   pos = n->messages;
2796   while (pos != NULL) 
2797     {
2798       if (pos->priority <= min_prio)
2799         {
2800           min_prio_entry = pos;
2801           min_prio_prev = prev;
2802           min_prio = pos->priority;
2803         }
2804       queue_size++;
2805       prev = pos;
2806       pos = pos->next;
2807     }
2808   if (queue_size >= MAX_PEER_QUEUE_SIZE)
2809     {
2810       /* queue full */
2811       if (ntohl(sm->priority) <= min_prio)
2812         {
2813           /* discard new entry; this should no longer happen! */
2814           GNUNET_break (0);
2815 #if DEBUG_CORE
2816           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2817                       "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2818                       queue_size,
2819                       (unsigned int) MAX_PEER_QUEUE_SIZE,
2820                       (unsigned int) msize,
2821                       (unsigned int) ntohs (message->type));
2822 #endif
2823           GNUNET_STATISTICS_update (stats, 
2824                                     gettext_noop ("# discarded CORE_SEND requests"), 
2825                                     1, GNUNET_NO);
2826
2827           if (client != NULL)
2828             GNUNET_SERVER_receive_done (client, GNUNET_OK);
2829           return;
2830         }
2831       GNUNET_assert (min_prio_entry != NULL);
2832       /* discard "min_prio_entry" */
2833 #if DEBUG_CORE
2834       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2835                   "Queue full, discarding existing older request\n");
2836 #endif
2837           GNUNET_STATISTICS_update (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 1, GNUNET_NO);
2838       if (min_prio_prev == NULL)
2839         n->messages = min_prio_entry->next;
2840       else
2841         min_prio_prev->next = min_prio_entry->next;      
2842       GNUNET_free (min_prio_entry);     
2843     }
2844
2845 #if DEBUG_CORE
2846   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2847               "Adding transmission request for `%4s' of size %u to queue\n",
2848               GNUNET_i2s (&sm->peer),
2849               (unsigned int) msize);
2850 #endif  
2851   e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2852   e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2853   e->priority = ntohl (sm->priority);
2854   e->size = msize;
2855   memcpy (&e[1], &sm[1], msize);
2856
2857   /* insert, keep list sorted by deadline */
2858   prev = NULL;
2859   pos = n->messages;
2860   while ((pos != NULL) && (pos->deadline.abs_value < e->deadline.abs_value))
2861     {
2862       prev = pos;
2863       pos = pos->next;
2864     }
2865   if (prev == NULL)
2866     n->messages = e;
2867   else
2868     prev->next = e;
2869   e->next = pos;
2870
2871   /* consider scheduling now */
2872   process_plaintext_neighbour_queue (n);
2873   if (client != NULL)
2874     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2875 }
2876
2877
2878 /**
2879  * Function called when the transport service is ready to
2880  * receive a message.  Only resets 'n->th' to NULL.
2881  *
2882  * @param cls neighbour to use message from
2883  * @param size number of bytes we can transmit
2884  * @param buf where to copy the message
2885  * @return number of bytes transmitted
2886  */
2887 static size_t
2888 notify_transport_connect_done (void *cls,
2889                                size_t size,
2890                                void *buf)
2891 {
2892   struct Neighbour *n = cls;
2893
2894   n->th = NULL;
2895   if (GNUNET_YES != n->is_connected)
2896     {
2897       /* transport should only call us to transmit a message after
2898        * telling us about a successful connection to the respective peer */
2899 #if DEBUG_CORE
2900       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
2901                   "Timeout on notify connect!\n");
2902 #endif
2903       GNUNET_STATISTICS_update (stats, 
2904                                 gettext_noop ("# connection requests timed out in transport"), 
2905                                 1,
2906                                 GNUNET_NO);
2907       return 0;
2908     }
2909   if (buf == NULL)
2910     {
2911       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2912                   _("Failed to connect to `%4s': transport failed to connect\n"),
2913                   GNUNET_i2s (&n->peer));
2914       return 0;
2915     }
2916   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2917               _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2918               GNUNET_i2s (&n->peer));
2919   if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2920     GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2921   n->retry_set_key_task = GNUNET_SCHEDULER_add_now (&set_key_retry_task,
2922                                                     n);
2923   return 0;
2924 }
2925
2926
2927 /**
2928  * Handle CORE_REQUEST_CONNECT request.
2929  *
2930  * @param cls unused
2931  * @param client the client issuing the request
2932  * @param message the "struct ConnectMessage"
2933  */
2934 static void
2935 handle_client_request_connect (void *cls,
2936                                struct GNUNET_SERVER_Client *client,
2937                                const struct GNUNET_MessageHeader *message)
2938 {
2939   const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2940   struct Neighbour *n;
2941   struct GNUNET_TIME_Relative timeout;
2942
2943   if (0 == memcmp (&cm->peer, 
2944                    &my_identity, 
2945                    sizeof (struct GNUNET_PeerIdentity)))
2946     {
2947       /* In this case a client has asked us to connect to ourselves, not really an error! */
2948       GNUNET_SERVER_receive_done (client, GNUNET_OK);
2949       return;
2950     }
2951   GNUNET_break (ntohl (cm->reserved) == 0);
2952   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2953   n = find_neighbour (&cm->peer);
2954   if (n == NULL)
2955     n = create_neighbour (&cm->peer);
2956   if ( (GNUNET_YES == n->is_connected) ||
2957        (n->th != NULL) )
2958     {
2959       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2960                  "Core received `%s' request for `%4s', already connected!\n",
2961                  "REQUEST_CONNECT",
2962                  GNUNET_i2s (&cm->peer));
2963       if (GNUNET_YES == n->is_connected) 
2964         GNUNET_STATISTICS_update (stats, 
2965                                   gettext_noop ("# connection requests ignored (already connected)"), 
2966                                   1,
2967                                   GNUNET_NO);
2968       else
2969         GNUNET_STATISTICS_update (stats, 
2970                                   gettext_noop ("# connection requests ignored (already trying)"), 
2971                                   1,
2972                                   GNUNET_NO);
2973       return; /* already connected, or at least trying */
2974     }
2975   GNUNET_STATISTICS_update (stats, 
2976                             gettext_noop ("# connection requests received"), 
2977                             1,
2978                             GNUNET_NO);
2979
2980   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2981               "Core received `%s' request for `%4s', will try to establish connection\n",
2982               "REQUEST_CONNECT",
2983               GNUNET_i2s (&cm->peer));
2984
2985   timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2986   /* ask transport to connect to the peer */
2987   n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2988                                                   &cm->peer,
2989                                                   sizeof (struct GNUNET_MessageHeader), 0,
2990                                                   timeout,
2991                                                   &notify_transport_connect_done,
2992                                                   n);
2993   GNUNET_break (NULL != n->th);
2994 }
2995
2996
2997 /**
2998  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
2999  * the neighbour's struct and retry send_key.  Or, if we did not get a
3000  * HELLO, just do nothing.
3001  *
3002  * @param cls the 'struct Neighbour' to retry sending the key for
3003  * @param peer the peer for which this is the HELLO
3004  * @param hello HELLO message of that peer
3005  * @param err_msg NULL if successful, otherwise contains error message
3006  */
3007 static void
3008 process_hello_retry_send_key (void *cls,
3009                               const struct GNUNET_PeerIdentity *peer,
3010                               const struct GNUNET_HELLO_Message *hello,
3011                               const char *err_msg)
3012 {
3013   struct Neighbour *n = cls;
3014
3015   if (err_msg != NULL)
3016   {
3017     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3018                 _("Error in communication with PEERINFO service\n"));
3019     /* return; */
3020   }
3021
3022   if (peer == NULL)
3023     {
3024 #if DEBUG_CORE
3025       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3026                   "Entered `%s' and `%s' is NULL!\n",
3027                   "process_hello_retry_send_key",
3028                   "peer");
3029 #endif
3030       n->pitr = NULL;
3031       if (n->public_key != NULL)
3032         {
3033           if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3034             {
3035               GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3036               n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3037             }      
3038           GNUNET_STATISTICS_update (stats,
3039                                     gettext_noop ("# SET_KEY messages deferred (need public key)"), 
3040                                     -1, 
3041                                     GNUNET_NO);
3042           send_key (n);
3043         }
3044       else
3045         {
3046 #if DEBUG_CORE
3047           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3048                       "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
3049                       GNUNET_i2s (&n->peer));
3050 #endif
3051           GNUNET_STATISTICS_update (stats,
3052                                     gettext_noop ("# Delayed connecting due to lack of public key"),
3053                                     1,
3054                                     GNUNET_NO);      
3055           if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
3056             n->retry_set_key_task
3057               = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3058                                               &set_key_retry_task, n);
3059         }
3060       return;
3061     }
3062
3063 #if DEBUG_CORE
3064   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3065               "Entered `%s' for peer `%4s'\n",
3066               "process_hello_retry_send_key",
3067               GNUNET_i2s (peer));
3068 #endif
3069   if (n->public_key != NULL)
3070     {
3071       /* already have public key, why are we here? */
3072       GNUNET_break (0);
3073       return;
3074     }
3075
3076 #if DEBUG_CORE
3077   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3078               "Received new `%s' message for `%4s', initiating key exchange.\n",
3079               "HELLO",
3080               GNUNET_i2s (peer));
3081 #endif
3082   n->public_key =
3083     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3084   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3085     {
3086       GNUNET_STATISTICS_update (stats,
3087                                 gettext_noop ("# Error extracting public key from HELLO"),
3088                                 1,
3089                                 GNUNET_NO);      
3090       GNUNET_free (n->public_key);
3091       n->public_key = NULL;
3092 #if DEBUG_CORE
3093   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3094               "GNUNET_HELLO_get_key returned awfully\n");
3095 #endif
3096       return;
3097     }
3098 }
3099
3100
3101 /**
3102  * Send our key (and encrypted PING) to the other peer.
3103  *
3104  * @param n the other peer
3105  */
3106 static void
3107 send_key (struct Neighbour *n)
3108 {
3109   struct MessageEntry *pos;
3110   struct SetKeyMessage *sm;
3111   struct MessageEntry *me;
3112   struct PingMessage pp;
3113   struct PingMessage *pm;
3114   struct GNUNET_CRYPTO_AesInitializationVector iv;
3115
3116   if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3117     {
3118       GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3119       n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3120     }        
3121   if (n->pitr != NULL)
3122     {
3123 #if DEBUG_CORE
3124       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3125                   "Key exchange in progress with `%4s'.\n",
3126                   GNUNET_i2s (&n->peer));
3127 #endif
3128       return; /* already in progress */
3129     }
3130   if (GNUNET_YES != n->is_connected)
3131     {
3132 #if DEBUG_CORE
3133       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3134                   "Not yet connected to peer `%4s'!\n",
3135                   GNUNET_i2s (&n->peer));
3136 #endif
3137       if (NULL == n->th)
3138         {
3139           GNUNET_STATISTICS_update (stats, 
3140                                     gettext_noop ("# Asking transport to connect (for SET_KEY)"), 
3141                                     1, 
3142                                     GNUNET_NO);
3143           n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
3144                                                           &n->peer,
3145                                                           sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
3146                                                           0,
3147                                                           GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3148                                                           &notify_encrypted_transmit_ready,
3149                                                           n);
3150         }
3151       return; 
3152     }
3153 #if DEBUG_CORE
3154   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3155               "Asked to perform key exchange with `%4s'.\n",
3156               GNUNET_i2s (&n->peer));
3157 #endif
3158   if (n->public_key == NULL)
3159     {
3160       /* lookup n's public key, then try again */
3161 #if DEBUG_CORE
3162       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3163                   "Lacking public key for `%4s', trying to obtain one (send_key).\n",
3164                   GNUNET_i2s (&n->peer));
3165 #endif
3166       GNUNET_assert (n->pitr == NULL);
3167       n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3168                                          &n->peer,
3169                                          GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
3170                                          &process_hello_retry_send_key, n);
3171       return;
3172     }
3173   pos = n->encrypted_head;
3174   while (pos != NULL)
3175     {
3176       if (GNUNET_YES == pos->is_setkey)
3177         {
3178           if (pos->sender_status == n->status)
3179             {
3180 #if DEBUG_CORE
3181               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3182                           "`%s' message for `%4s' queued already\n",
3183                           "SET_KEY",
3184                           GNUNET_i2s (&n->peer));
3185 #endif
3186               goto trigger_processing;
3187             }
3188           GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
3189                                        n->encrypted_tail,
3190                                        pos);
3191           GNUNET_free (pos);
3192 #if DEBUG_CORE
3193           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3194                       "Removing queued `%s' message for `%4s', will create a new one\n",
3195                       "SET_KEY",
3196                       GNUNET_i2s (&n->peer));
3197 #endif
3198           break;
3199         }
3200       pos = pos->next;
3201     }
3202
3203   /* update status */
3204   switch (n->status)
3205     {
3206     case PEER_STATE_DOWN:
3207       n->status = PEER_STATE_KEY_SENT;
3208       break;
3209     case PEER_STATE_KEY_SENT:
3210       break;
3211     case PEER_STATE_KEY_RECEIVED:
3212       break;
3213     case PEER_STATE_KEY_CONFIRMED:
3214       break;
3215     default:
3216       GNUNET_break (0);
3217       break;
3218     }
3219   
3220
3221   /* first, set key message */
3222   me = GNUNET_malloc (sizeof (struct MessageEntry) +
3223                       sizeof (struct SetKeyMessage) +
3224                       sizeof (struct PingMessage));
3225   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
3226   me->priority = SET_KEY_PRIORITY;
3227   me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
3228   me->is_setkey = GNUNET_YES;
3229   me->got_slack = GNUNET_YES; /* do not defer this one! */
3230   me->sender_status = n->status;
3231   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3232                                      n->encrypted_tail,
3233                                      n->encrypted_tail,
3234                                      me);
3235   sm = (struct SetKeyMessage *) &me[1];
3236   sm->header.size = htons (sizeof (struct SetKeyMessage));
3237   sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
3238   sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
3239                                         PEER_STATE_KEY_SENT : n->status));
3240   sm->purpose.size =
3241     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3242            sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3243            sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3244            sizeof (struct GNUNET_PeerIdentity));
3245   sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
3246   sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
3247   sm->target = n->peer;
3248   GNUNET_assert (GNUNET_OK ==
3249                  GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
3250                                             sizeof (struct
3251                                                     GNUNET_CRYPTO_AesSessionKey),
3252                                             n->public_key,
3253                                             &sm->encrypted_key));
3254   GNUNET_assert (GNUNET_OK ==
3255                  GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
3256                                          &sm->signature));  
3257   pm = (struct PingMessage *) &sm[1];
3258   pm->header.size = htons (sizeof (struct PingMessage));
3259   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
3260   pm->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3261   derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
3262   pp.challenge = n->ping_challenge;
3263   pp.target = n->peer;
3264 #if DEBUG_HANDSHAKE
3265   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3266               "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
3267               "SET_KEY", "PING",
3268               (unsigned int) n->ping_challenge,
3269               GNUNET_i2s (&n->peer),
3270               (unsigned int) n->encrypt_key.crc32,
3271               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3272               pm->iv_seed);
3273 #endif
3274   do_encrypt (n,
3275               &iv,
3276               &pp.target,
3277               &pm->target,
3278               sizeof (struct PingMessage) -
3279               ((void *) &pm->target - (void *) pm));
3280   GNUNET_STATISTICS_update (stats, 
3281                             gettext_noop ("# SET_KEY and PING messages created"), 
3282                             1, 
3283                             GNUNET_NO);
3284 #if DEBUG_CORE
3285   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3286               "Have %llu ms left for `%s' transmission.\n",
3287               (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).rel_value,
3288               "SET_KEY");
3289 #endif
3290  trigger_processing:
3291   /* trigger queue processing */
3292   process_encrypted_neighbour_queue (n);
3293   if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
3294        (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
3295     n->retry_set_key_task
3296       = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3297                                       &set_key_retry_task, n);    
3298 }
3299
3300
3301 /**
3302  * We received a SET_KEY message.  Validate and update
3303  * our key material and status.
3304  *
3305  * @param n the neighbour from which we received message m
3306  * @param m the set key message we received
3307  * @param ats performance data
3308  * @param ats_count number of entries in ats (excluding 0-termination)
3309  */
3310 static void
3311 handle_set_key (struct Neighbour *n,
3312                 const struct SetKeyMessage *m,
3313                 const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3314                 uint32_t ats_count);
3315
3316
3317
3318 /**
3319  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
3320  * the neighbour's struct and retry handling the set_key message.  Or,
3321  * if we did not get a HELLO, just free the set key message.
3322  *
3323  * @param cls pointer to the set key message
3324  * @param peer the peer for which this is the HELLO
3325  * @param hello HELLO message of that peer
3326  * @param err_msg NULL if successful, otherwise contains error message
3327  */
3328 static void
3329 process_hello_retry_handle_set_key (void *cls,
3330                                     const struct GNUNET_PeerIdentity *peer,
3331                                     const struct GNUNET_HELLO_Message *hello,
3332                                     const char *err_msg)
3333 {
3334   struct Neighbour *n = cls;
3335   struct SetKeyMessage *sm = n->skm;
3336
3337   if (err_msg != NULL)
3338   {
3339           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3340                       _("Error in communication with PEERINFO service\n"));
3341         /* return; */
3342   }
3343
3344   if (peer == NULL)
3345     {
3346       n->skm = NULL;
3347       n->pitr = NULL;
3348       if (n->public_key != NULL)
3349         {
3350 #if DEBUG_CORE
3351           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3352                       "Received `%s' for `%4s', continuing processing of `%s' message.\n",
3353                       "HELLO",
3354                       GNUNET_i2s (&n->peer),
3355                       "SET_KEY");
3356 #endif
3357           handle_set_key (n, sm, NULL, 0);
3358         }
3359       else
3360         {
3361           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3362                       _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
3363                       "SET_KEY",
3364                       GNUNET_i2s (&n->peer));
3365         }
3366       GNUNET_free (sm);
3367       return;
3368     }
3369   if (n->public_key != NULL)
3370     return;                     /* multiple HELLOs match!? */
3371   n->public_key =
3372     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3373   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3374     {
3375       GNUNET_break_op (0);
3376       GNUNET_free (n->public_key);
3377       n->public_key = NULL;
3378     }
3379 }
3380
3381
3382 /**
3383  * Merge the given performance data with the data we currently
3384  * track for the given neighbour.
3385  *
3386  * @param n neighbour
3387  * @param ats new performance data
3388  * @param ats_count number of records in ats
3389  */
3390 static void
3391 update_neighbour_performance (struct Neighbour *n,
3392                               const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3393                               uint32_t ats_count)
3394 {
3395   uint32_t i;
3396   unsigned int j;
3397
3398   if (ats_count == 0)
3399     return;
3400   for (i = 0; i < ats_count; i++)
3401     {
3402       for (j=0;j < n->ats_count; j++)
3403         {
3404           if (n->ats[j].type == ats[i].type)
3405             {
3406               n->ats[j].value = ats[i].value;
3407               break;
3408             }
3409         }
3410       if (j == n->ats_count)
3411         {
3412           GNUNET_array_append (n->ats,
3413                                n->ats_count,
3414                                ats[i]);
3415         }
3416     }
3417 }
3418
3419
3420 /**
3421  * We received a PING message.  Validate and transmit
3422  * PONG.
3423  *
3424  * @param n sender of the PING
3425  * @param m the encrypted PING message itself
3426  * @param ats performance data
3427  * @param ats_count number of entries in ats (excluding 0-termination)
3428  */
3429 static void
3430 handle_ping (struct Neighbour *n,
3431              const struct PingMessage *m,
3432              const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3433              uint32_t ats_count)
3434 {
3435   struct PingMessage t;
3436   struct PongMessage tx;
3437   struct PongMessage *tp;
3438   struct MessageEntry *me;
3439   struct GNUNET_CRYPTO_AesInitializationVector iv;
3440
3441 #if DEBUG_CORE
3442   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3443               "Core service receives `%s' request from `%4s'.\n",
3444               "PING", GNUNET_i2s (&n->peer));
3445 #endif
3446   derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3447   if (GNUNET_OK !=
3448       do_decrypt (n,
3449                   &iv,
3450                   &m->target,
3451                   &t.target,
3452                   sizeof (struct PingMessage) -
3453                   ((void *) &m->target - (void *) m)))
3454     return;
3455 #if DEBUG_HANDSHAKE
3456   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3457               "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u, IV %u (salt %u)\n",
3458               "PING",
3459               GNUNET_i2s (&t.target),
3460               (unsigned int) t.challenge,
3461               (unsigned int) n->decrypt_key.crc32,
3462               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3463               m->iv_seed);
3464 #endif
3465   GNUNET_STATISTICS_update (stats,
3466                             gettext_noop ("# PING messages decrypted"), 
3467                             1,
3468                             GNUNET_NO);
3469   if (0 != memcmp (&t.target,
3470                    &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3471     {
3472       GNUNET_break_op (0);
3473       return;
3474     }
3475   update_neighbour_performance (n, ats, ats_count);
3476   me = GNUNET_malloc (sizeof (struct MessageEntry) +
3477                       sizeof (struct PongMessage));
3478   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3479                                      n->encrypted_tail,
3480                                      n->encrypted_tail,
3481                                      me);
3482   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
3483   me->priority = PONG_PRIORITY;
3484   me->size = sizeof (struct PongMessage);
3485   tx.inbound_bw_limit = n->bw_in;
3486   tx.challenge = t.challenge;
3487   tx.target = t.target;
3488   tp = (struct PongMessage *) &me[1];
3489   tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
3490   tp->header.size = htons (sizeof (struct PongMessage));
3491   tp->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3492   derive_pong_iv (&iv, &n->encrypt_key, tp->iv_seed, t.challenge, &n->peer);
3493   do_encrypt (n,
3494               &iv,
3495               &tx.challenge,
3496               &tp->challenge,
3497               sizeof (struct PongMessage) -
3498               ((void *) &tp->challenge - (void *) tp));
3499   GNUNET_STATISTICS_update (stats, 
3500                             gettext_noop ("# PONG messages created"), 
3501                             1, 
3502                             GNUNET_NO);
3503 #if DEBUG_HANDSHAKE
3504   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3505               "Encrypting `%s' with challenge %u using key %u, IV %u (salt %u)\n",
3506               "PONG",
3507               (unsigned int) t.challenge,
3508               (unsigned int) n->encrypt_key.crc32,
3509               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3510               tp->iv_seed);
3511 #endif
3512   /* trigger queue processing */
3513   process_encrypted_neighbour_queue (n);
3514 }
3515
3516
3517 /**
3518  * We received a PONG message.  Validate and update our status.
3519  *
3520  * @param n sender of the PONG
3521  * @param m the encrypted PONG message itself
3522  * @param ats performance data
3523  * @param ats_count number of entries in ats (excluding 0-termination)
3524  */
3525 static void
3526 handle_pong (struct Neighbour *n, 
3527              const struct PongMessage *m,
3528              const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3529              uint32_t ats_count)
3530 {
3531   struct PongMessage t;
3532   struct ConnectNotifyMessage *cnm;
3533   struct GNUNET_CRYPTO_AesInitializationVector iv;
3534   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
3535   struct GNUNET_TRANSPORT_ATS_Information *mats;
3536   size_t size;
3537
3538 #if DEBUG_CORE
3539   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3540               "Core service receives `%s' response from `%4s'.\n",
3541               "PONG", GNUNET_i2s (&n->peer));
3542 #endif
3543   /* mark as garbage, just to be sure */
3544   memset (&t, 255, sizeof (t));
3545   derive_pong_iv (&iv, &n->decrypt_key, m->iv_seed, n->ping_challenge,
3546       &my_identity);
3547   if (GNUNET_OK !=
3548       do_decrypt (n,
3549                   &iv,
3550                   &m->challenge,
3551                   &t.challenge,
3552                   sizeof (struct PongMessage) -
3553                   ((void *) &m->challenge - (void *) m)))
3554     {
3555       GNUNET_break_op (0);
3556       return;
3557     }
3558   GNUNET_STATISTICS_update (stats, 
3559                             gettext_noop ("# PONG messages decrypted"), 
3560                             1, 
3561                             GNUNET_NO);
3562 #if DEBUG_HANDSHAKE
3563   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3564               "Decrypted `%s' from `%4s' with challenge %u using key %u, IV %u (salt %u)\n",
3565               "PONG",
3566               GNUNET_i2s (&t.target),
3567               (unsigned int) t.challenge,
3568               (unsigned int) n->decrypt_key.crc32,
3569               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3570               m->iv_seed);
3571 #endif
3572   if ((0 != memcmp (&t.target,
3573                     &n->peer,
3574                     sizeof (struct GNUNET_PeerIdentity))) ||
3575       (n->ping_challenge != t.challenge))
3576     {
3577       /* PONG malformed */
3578 #if DEBUG_CORE
3579       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3580                   "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
3581                   "PONG", 
3582                   GNUNET_i2s (&n->peer),
3583                   (unsigned int) n->ping_challenge);
3584       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3585                   "Received malformed `%s' received from `%4s' with challenge %u\n",
3586                   "PONG", GNUNET_i2s (&t.target), 
3587                   (unsigned int) t.challenge);
3588 #endif
3589       GNUNET_break_op (n->ping_challenge != t.challenge);
3590       return;
3591     }
3592   switch (n->status)
3593     {
3594     case PEER_STATE_DOWN:
3595       GNUNET_break (0);         /* should be impossible */
3596       return;
3597     case PEER_STATE_KEY_SENT:
3598       GNUNET_break (0);         /* should be impossible, how did we decrypt? */
3599       return;
3600     case PEER_STATE_KEY_RECEIVED:
3601       GNUNET_STATISTICS_update (stats, 
3602                                 gettext_noop ("# Session keys confirmed via PONG"), 
3603                                 1, 
3604                                 GNUNET_NO);
3605       n->status = PEER_STATE_KEY_CONFIRMED;
3606       if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
3607         {
3608           n->bw_out_external_limit = t.inbound_bw_limit;
3609           n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3610                                                   n->bw_out_internal_limit);
3611           GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3612                                                  n->bw_out);       
3613           GNUNET_TRANSPORT_set_quota (transport,
3614                                       &n->peer,
3615                                       n->bw_in,
3616                                       n->bw_out,
3617                                       GNUNET_TIME_UNIT_FOREVER_REL,
3618                                       NULL, NULL); 
3619         }
3620 #if DEBUG_CORE
3621       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3622                   "Confirmed key via `%s' message for peer `%4s'\n",
3623                   "PONG", GNUNET_i2s (&n->peer));
3624 #endif      
3625       if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3626         {
3627           GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3628           n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3629         }      
3630       update_neighbour_performance (n, ats, ats_count);      
3631       size = sizeof (struct ConnectNotifyMessage) +
3632         (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3633       if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3634         {
3635           GNUNET_break (0);
3636           /* recovery strategy: throw away performance data */
3637           GNUNET_array_grow (n->ats,
3638                              n->ats_count,
3639                              0);
3640           size = sizeof (struct PeerStatusNotifyMessage) +
3641             n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3642         }
3643       cnm = (struct ConnectNotifyMessage*) buf;
3644       cnm->header.size = htons (size);
3645       cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3646       cnm->ats_count = htonl (n->ats_count);
3647       cnm->peer = n->peer;
3648       mats = &cnm->ats;
3649       memcpy (mats,
3650               n->ats,
3651               n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
3652       mats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3653       mats[n->ats_count].value = htonl (0);      
3654       send_to_all_clients (&cnm->header, 
3655                            GNUNET_NO, 
3656                            GNUNET_CORE_OPTION_SEND_CONNECT);
3657       process_encrypted_neighbour_queue (n);
3658       /* fall-through! */
3659     case PEER_STATE_KEY_CONFIRMED:
3660       n->last_activity = GNUNET_TIME_absolute_get ();
3661       if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3662         GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3663       n->keep_alive_task 
3664         = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3665                                         &send_keep_alive,
3666                                         n);
3667       handle_peer_status_change (n);
3668       break;
3669     default:
3670       GNUNET_break (0);
3671       break;
3672     }
3673 }
3674
3675
3676 /**
3677  * We received a SET_KEY message.  Validate and update
3678  * our key material and status.
3679  *
3680  * @param n the neighbour from which we received message m
3681  * @param m the set key message we received
3682  * @param ats performance data
3683  * @param ats_count number of entries in ats (excluding 0-termination)
3684  */
3685 static void
3686 handle_set_key (struct Neighbour *n, 
3687                 const struct SetKeyMessage *m,
3688                 const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3689                 uint32_t ats_count)
3690 {
3691   struct SetKeyMessage *m_cpy;
3692   struct GNUNET_TIME_Absolute t;
3693   struct GNUNET_CRYPTO_AesSessionKey k;
3694   struct PingMessage *ping;
3695   struct PongMessage *pong;
3696   enum PeerStateMachine sender_status;
3697
3698 #if DEBUG_CORE
3699   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3700               "Core service receives `%s' request from `%4s'.\n",
3701               "SET_KEY", GNUNET_i2s (&n->peer));
3702 #endif
3703   if (n->public_key == NULL)
3704     {
3705       if (n->pitr != NULL)
3706         {
3707 #if DEBUG_CORE
3708           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3709                       "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3710                       "SET_KEY");
3711 #endif
3712           return;
3713         }
3714 #if DEBUG_CORE
3715       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3716                   "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3717 #endif
3718       m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3719       memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3720       /* lookup n's public key, then try again */
3721       GNUNET_assert (n->skm == NULL);
3722       n->skm = m_cpy;
3723       n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3724                                          &n->peer,
3725                                          GNUNET_TIME_UNIT_MINUTES,
3726                                          &process_hello_retry_handle_set_key, n);
3727       GNUNET_STATISTICS_update (stats, 
3728                                 gettext_noop ("# SET_KEY messages deferred (need public key)"), 
3729                                 1, 
3730                                 GNUNET_NO);
3731       return;
3732     }
3733   if (0 != memcmp (&m->target,
3734                    &my_identity,
3735                    sizeof (struct GNUNET_PeerIdentity)))
3736     {
3737       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3738                   _("Received `%s' message that was for `%s', not for me.  Ignoring.\n"),
3739                   "SET_KEY",
3740                   GNUNET_i2s (&m->target));
3741       return;
3742     }
3743   if ((ntohl (m->purpose.size) !=
3744        sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3745        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3746        sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3747        sizeof (struct GNUNET_PeerIdentity)) ||
3748       (GNUNET_OK !=
3749        GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3750                                  &m->purpose, &m->signature, n->public_key)))
3751     {
3752       /* invalid signature */
3753       GNUNET_break_op (0);
3754       return;
3755     }
3756   t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3757   if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3758        (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3759       (t.abs_value < n->decrypt_key_created.abs_value))
3760     {
3761       /* this could rarely happen due to massive re-ordering of
3762          messages on the network level, but is most likely either
3763          a bug or some adversary messing with us.  Report. */
3764       GNUNET_break_op (0);
3765       return;
3766     }
3767 #if DEBUG_CORE
3768   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
3769               "Decrypting key material.\n");
3770 #endif  
3771   if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3772                                   &m->encrypted_key,
3773                                   &k,
3774                                   sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3775        != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3776       (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3777     {
3778       /* failed to decrypt !? */
3779       GNUNET_break_op (0);
3780       return;
3781     }
3782   GNUNET_STATISTICS_update (stats, 
3783                             gettext_noop ("# SET_KEY messages decrypted"), 
3784                             1, 
3785                             GNUNET_NO);
3786   n->decrypt_key = k;
3787   if (n->decrypt_key_created.abs_value != t.abs_value)
3788     {
3789       /* fresh key, reset sequence numbers */
3790       n->last_sequence_number_received = 0;
3791       n->last_packets_bitmap = 0;
3792       n->decrypt_key_created = t;
3793     }
3794   update_neighbour_performance (n, ats, ats_count);
3795   sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3796   switch (n->status)
3797     {
3798     case PEER_STATE_DOWN:
3799       n->status = PEER_STATE_KEY_RECEIVED;
3800 #if DEBUG_CORE
3801       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3802                   "Responding to `%s' with my own key.\n", "SET_KEY");
3803 #endif
3804       send_key (n);
3805       break;
3806     case PEER_STATE_KEY_SENT:
3807     case PEER_STATE_KEY_RECEIVED:
3808       n->status = PEER_STATE_KEY_RECEIVED;
3809       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3810           (sender_status != PEER_STATE_KEY_CONFIRMED))
3811         {
3812 #if DEBUG_CORE
3813           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3814                       "Responding to `%s' with my own key (other peer has status %u).\n",
3815                       "SET_KEY",
3816                       (unsigned int) sender_status);
3817 #endif
3818           send_key (n);
3819         }
3820       break;
3821     case PEER_STATE_KEY_CONFIRMED:
3822       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3823           (sender_status != PEER_STATE_KEY_CONFIRMED))
3824         {         
3825 #if DEBUG_CORE
3826           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3827                       "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3828                       "SET_KEY", 
3829                       (unsigned int) sender_status);
3830 #endif
3831           send_key (n);
3832         }
3833       break;
3834     default:
3835       GNUNET_break (0);
3836       break;
3837     }
3838   if (n->pending_ping != NULL)
3839     {
3840       ping = n->pending_ping;
3841       n->pending_ping = NULL;
3842       handle_ping (n, ping, NULL, 0);
3843       GNUNET_free (ping);
3844     }
3845   if (n->pending_pong != NULL)
3846     {
3847       pong = n->pending_pong;
3848       n->pending_pong = NULL;
3849       handle_pong (n, pong, NULL, 0);
3850       GNUNET_free (pong);
3851     }
3852 }
3853
3854
3855 /**
3856  * Send a P2P message to a client.
3857  *
3858  * @param sender who sent us the message?
3859  * @param client who should we give the message to?
3860  * @param m contains the message to transmit
3861  * @param msize number of bytes in buf to transmit
3862  */
3863 static void
3864 send_p2p_message_to_client (struct Neighbour *sender,
3865                             struct Client *client,
3866                             const void *m, size_t msize)
3867 {
3868   size_t size = msize + sizeof (struct NotifyTrafficMessage) +
3869     (sender->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3870   char buf[size];
3871   struct NotifyTrafficMessage *ntm;
3872   struct GNUNET_TRANSPORT_ATS_Information *ats;
3873
3874   if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3875     {
3876       GNUNET_break (0);
3877       /* recovery strategy: throw performance data away... */
3878       GNUNET_array_grow (sender->ats,
3879                          sender->ats_count,
3880                          0);
3881       size = msize + sizeof (struct NotifyTrafficMessage) +
3882         (sender->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3883     }
3884 #if DEBUG_CORE
3885   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3886               "Core service passes message from `%4s' of type %u to client.\n",
3887               GNUNET_i2s(&sender->peer),
3888               (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3889 #endif
3890   ntm = (struct NotifyTrafficMessage *) buf;
3891   ntm->header.size = htons (size);
3892   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3893   ntm->ats_count = htonl (sender->ats_count);
3894   ntm->peer = sender->peer;
3895   ats = &ntm->ats;
3896   memcpy (ats,
3897           sender->ats,
3898           sizeof (struct GNUNET_TRANSPORT_ATS_Information) * sender->ats_count);
3899   ats[sender->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3900   ats[sender->ats_count].value = htonl (0);  
3901   memcpy (&ats[sender->ats_count+1],
3902           m, 
3903           msize);
3904   send_to_client (client, &ntm->header, GNUNET_YES);
3905 }
3906
3907
3908 /**
3909  * Deliver P2P message to interested clients.
3910  *
3911  * @param cls always NULL
3912  * @param client who sent us the message (struct Neighbour)
3913  * @param m the message
3914  */
3915 static void
3916 deliver_message (void *cls,
3917                  void *client,
3918                  const struct GNUNET_MessageHeader *m)
3919 {
3920   struct Neighbour *sender = client;
3921   size_t msize = ntohs (m->size);
3922   char buf[256];
3923   struct Client *cpos;
3924   uint16_t type;
3925   unsigned int tpos;
3926   int deliver_full;
3927   int dropped;
3928
3929   type = ntohs (m->type);
3930 #if DEBUG_CORE
3931   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3932               "Received encapsulated message of type %u and size %u from `%4s'\n",
3933               (unsigned int) type,
3934               ntohs (m->size),
3935               GNUNET_i2s (&sender->peer));
3936 #endif
3937   GNUNET_snprintf (buf,
3938                    sizeof(buf),
3939                    gettext_noop ("# bytes of messages of type %u received"),
3940                    (unsigned int) type);
3941   GNUNET_STATISTICS_set (stats,
3942                          buf,
3943                          msize,
3944                          GNUNET_NO);     
3945   dropped = GNUNET_YES;
3946   cpos = clients;
3947   while (cpos != NULL)
3948     {
3949       deliver_full = GNUNET_NO;
3950       if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3951         deliver_full = GNUNET_YES;
3952       else
3953         {
3954           for (tpos = 0; tpos < cpos->tcnt; tpos++)
3955             {
3956               if (type != cpos->types[tpos])
3957                 continue;
3958               deliver_full = GNUNET_YES;
3959               break;
3960             }
3961         }
3962       if (GNUNET_YES == deliver_full)
3963         {
3964           send_p2p_message_to_client (sender, cpos, m, msize);
3965           dropped = GNUNET_NO;
3966         }
3967       else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3968         {
3969           send_p2p_message_to_client (sender, cpos, m,
3970                                       sizeof (struct GNUNET_MessageHeader));
3971         }
3972       cpos = cpos->next;
3973     }
3974   if (dropped == GNUNET_YES)
3975     {
3976 #if DEBUG_CORE
3977       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3978                   "Message of type %u from `%4s' not delivered to any client.\n",
3979                   (unsigned int) type,
3980                   GNUNET_i2s (&sender->peer));
3981 #endif
3982       GNUNET_STATISTICS_update (stats,
3983                                 gettext_noop ("# messages not delivered to any client"), 
3984                                 1, GNUNET_NO);
3985     }
3986 }
3987
3988
3989 /**
3990  * We received an encrypted message.  Decrypt, validate and
3991  * pass on to the appropriate clients.
3992  *
3993  * @param n target of the message
3994  * @param m encrypted message
3995  * @param ats performance data
3996  * @param ats_count number of entries in ats (excluding 0-termination)
3997  */
3998 static void
3999 handle_encrypted_message (struct Neighbour *n,
4000                           const struct EncryptedMessage *m,
4001                           const struct GNUNET_TRANSPORT_ATS_Information *ats, 
4002                           uint32_t ats_count)
4003 {
4004   size_t size = ntohs (m->header.size);
4005   char buf[size];
4006   struct EncryptedMessage *pt;  /* plaintext */
4007   GNUNET_HashCode ph;
4008   uint32_t snum;
4009   struct GNUNET_TIME_Absolute t;
4010   struct GNUNET_CRYPTO_AesInitializationVector iv;
4011   struct GNUNET_CRYPTO_AuthKey auth_key;
4012
4013 #if DEBUG_CORE
4014   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4015               "Core service receives `%s' request from `%4s'.\n",
4016               "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
4017 #endif  
4018   /* validate hash */
4019   derive_auth_key (&auth_key,
4020                    &n->decrypt_key,
4021                    m->iv_seed,
4022                    n->decrypt_key_created);
4023   GNUNET_CRYPTO_hmac (&auth_key,
4024                       &m->sequence_number,
4025                       size - ENCRYPTED_HEADER_SIZE, &ph);
4026 #if DEBUG_HANDSHAKE
4027   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4028               "Re-Authenticated %u bytes of ciphertext (`%u'): `%s'\n",
4029               (unsigned int) size - ENCRYPTED_HEADER_SIZE,
4030               GNUNET_CRYPTO_crc32_n (&m->sequence_number,
4031                   size - ENCRYPTED_HEADER_SIZE),
4032               GNUNET_h2s (&ph));
4033 #endif
4034
4035   if (0 != memcmp (&ph,
4036                    &m->hmac,
4037                    sizeof (GNUNET_HashCode)))
4038     {
4039       /* checksum failed */
4040       GNUNET_break_op (0);
4041       return;
4042     }
4043   derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
4044   /* decrypt */
4045   if (GNUNET_OK !=
4046       do_decrypt (n,
4047                   &iv,
4048                   &m->sequence_number,
4049                   &buf[ENCRYPTED_HEADER_SIZE],
4050                   size - ENCRYPTED_HEADER_SIZE))
4051     return;
4052   pt = (struct EncryptedMessage *) buf;
4053
4054   /* validate sequence number */
4055   snum = ntohl (pt->sequence_number);
4056   if (n->last_sequence_number_received == snum)
4057     {
4058       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4059                   "Received duplicate message, ignoring.\n");
4060       /* duplicate, ignore */
4061       GNUNET_STATISTICS_set (stats,
4062                              gettext_noop ("# bytes dropped (duplicates)"),
4063                              size,
4064                              GNUNET_NO);      
4065       return;
4066     }
4067   if ((n->last_sequence_number_received > snum) &&
4068       (n->last_sequence_number_received - snum > 32))
4069     {
4070       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4071                   "Received ancient out of sequence message, ignoring.\n");
4072       /* ancient out of sequence, ignore */
4073       GNUNET_STATISTICS_set (stats,
4074                              gettext_noop ("# bytes dropped (out of sequence)"),
4075                              size,
4076                              GNUNET_NO);      
4077       return;
4078     }
4079   if (n->last_sequence_number_received > snum)
4080     {
4081       unsigned int rotbit =
4082         1 << (n->last_sequence_number_received - snum - 1);
4083       if ((n->last_packets_bitmap & rotbit) != 0)
4084         {
4085           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4086                       "Received duplicate message, ignoring.\n");
4087           GNUNET_STATISTICS_set (stats,
4088                                  gettext_noop ("# bytes dropped (duplicates)"),
4089                                  size,
4090                                  GNUNET_NO);      
4091           /* duplicate, ignore */
4092           return;
4093         }
4094       n->last_packets_bitmap |= rotbit;
4095     }
4096   if (n->last_sequence_number_received < snum)
4097     {
4098       int shift = (snum - n->last_sequence_number_received);
4099       if (shift >= 8 * sizeof(n->last_packets_bitmap))
4100         n->last_packets_bitmap = 0;
4101       else
4102         n->last_packets_bitmap <<= shift;
4103       n->last_sequence_number_received = snum;
4104     }
4105
4106   /* check timestamp */
4107   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
4108   if (GNUNET_TIME_absolute_get_duration (t).rel_value > MAX_MESSAGE_AGE.rel_value)
4109     {
4110       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4111                   _
4112                   ("Message received far too old (%llu ms). Content ignored.\n"),
4113                   GNUNET_TIME_absolute_get_duration (t).rel_value);
4114       GNUNET_STATISTICS_set (stats,
4115                              gettext_noop ("# bytes dropped (ancient message)"),
4116                              size,
4117                              GNUNET_NO);      
4118       return;
4119     }
4120
4121   /* process decrypted message(s) */
4122   if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
4123     {
4124 #if DEBUG_CORE_SET_QUOTA
4125       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4126                   "Received %u b/s as new inbound limit for peer `%4s'\n",
4127                   (unsigned int) ntohl (pt->inbound_bw_limit.value__),
4128                   GNUNET_i2s (&n->peer));
4129 #endif
4130       n->bw_out_external_limit = pt->inbound_bw_limit;
4131       n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
4132                                               n->bw_out_internal_limit);
4133       GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
4134                                              n->bw_out);
4135       GNUNET_TRANSPORT_set_quota (transport,
4136                                   &n->peer,
4137                                   n->bw_in,
4138                                   n->bw_out,
4139                                   GNUNET_TIME_UNIT_FOREVER_REL,
4140                                   NULL, NULL); 
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
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
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
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
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                                     GNUNET_TIME_UNIT_FOREVER_REL,
4423                                     NULL, NULL);
4424       handle_peer_status_change (n);
4425     }
4426   schedule_quota_update (n);
4427 }
4428
4429
4430 /**
4431  * Function called by transport to notify us that
4432  * a peer connected to us (on the network level).
4433  *
4434  * @param cls closure
4435  * @param peer the peer that connected
4436  * @param ats performance data
4437  * @param ats_count number of entries in ats (excluding 0-termination)
4438  */
4439 static void
4440 handle_transport_notify_connect (void *cls,
4441                                  const struct GNUNET_PeerIdentity *peer,
4442                                  const struct GNUNET_TRANSPORT_ATS_Information *ats,
4443                                  uint32_t ats_count)
4444 {
4445   struct Neighbour *n;
4446
4447   if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4448     {
4449       GNUNET_break (0);
4450       return;
4451     }
4452   n = find_neighbour (peer);
4453   if (n != NULL)
4454     {
4455       if (GNUNET_YES == n->is_connected)
4456         {
4457           /* duplicate connect notification!? */
4458           GNUNET_break (0);
4459           return;
4460         }
4461     }
4462   else
4463     {
4464       n = create_neighbour (peer);
4465     }
4466   GNUNET_STATISTICS_update (stats, 
4467                             gettext_noop ("# peers connected (transport)"), 
4468                             1, 
4469                             GNUNET_NO);
4470   n->is_connected = GNUNET_YES;      
4471   update_neighbour_performance (n, ats, ats_count);
4472   GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
4473                                  n->bw_out,
4474                                  MAX_WINDOW_TIME_S);
4475   GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
4476                                  n->bw_in,
4477                                  MAX_WINDOW_TIME_S);  
4478 #if DEBUG_CORE
4479   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4480               "Received connection from `%4s'.\n",
4481               GNUNET_i2s (&n->peer));
4482 #endif
4483   GNUNET_TRANSPORT_set_quota (transport,
4484                               &n->peer,
4485                               n->bw_in,
4486                               n->bw_out,
4487                               GNUNET_TIME_UNIT_FOREVER_REL,
4488                               NULL, NULL);
4489   send_key (n); 
4490 }
4491
4492
4493 /**
4494  * Function called by transport telling us that a peer
4495  * disconnected.
4496  *
4497  * @param cls closure
4498  * @param peer the peer that disconnected
4499  */
4500 static void
4501 handle_transport_notify_disconnect (void *cls,
4502                                     const struct GNUNET_PeerIdentity *peer)
4503 {
4504   struct DisconnectNotifyMessage cnm;
4505   struct Neighbour *n;
4506   struct ClientActiveRequest *car;
4507   struct GNUNET_TIME_Relative left;
4508
4509 #if DEBUG_CORE
4510   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4511               "Peer `%4s' disconnected from us; received notification from transport.\n", 
4512               GNUNET_i2s (peer));
4513 #endif
4514   n = find_neighbour (peer);
4515   if (n == NULL)
4516     {
4517       GNUNET_break (0);
4518       return;
4519     }
4520   GNUNET_break (n->is_connected == GNUNET_YES);
4521   if (n->status == PEER_STATE_KEY_CONFIRMED)
4522     {
4523       cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
4524       cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
4525       cnm.reserved = htonl (0);
4526       cnm.peer = *peer;
4527       send_to_all_clients (&cnm.header, GNUNET_NO, GNUNET_CORE_OPTION_SEND_DISCONNECT);
4528       GNUNET_STATISTICS_update (stats, 
4529                                 gettext_noop ("# established sessions"), 
4530                                 -1, 
4531                                 GNUNET_NO);
4532     }
4533
4534   /* On transport disconnect transport doesn't cancel requests, so must do so here. */
4535   if (n->th != NULL)
4536     {
4537       GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
4538       n->th = NULL;
4539     }
4540   n->is_connected = GNUNET_NO;
4541   n->status = PEER_STATE_DOWN;
4542   while (NULL != (car = n->active_client_request_head))
4543     {
4544       GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
4545                                    n->active_client_request_tail,
4546                                    car);
4547       GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
4548                                             &n->peer.hashPubKey,
4549                                             car);
4550       GNUNET_free (car);
4551     }
4552
4553   GNUNET_STATISTICS_update (stats, 
4554                             gettext_noop ("# peers connected (transport)"), 
4555                             -1, 
4556                             GNUNET_NO);
4557   if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
4558     GNUNET_SCHEDULER_cancel (n->dead_clean_task);
4559   left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4560                                         GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
4561   n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (), 
4562                                                     left);
4563   n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
4564                                                      &consider_free_task,
4565                                                      n);
4566 }
4567
4568
4569 /**
4570  * Wrapper around 'free_neighbour'; helper for 'cleaning_task'.
4571  */
4572 static int
4573 free_neighbour_helper (void *cls,
4574                        const GNUNET_HashCode *key,
4575                        void *value)
4576 {
4577   struct Neighbour *n = value;
4578
4579   free_neighbour (n);
4580   return GNUNET_OK;
4581 }
4582
4583
4584 /**
4585  * Last task run during shutdown.  Disconnects us from
4586  * the transport.
4587  */
4588 static void
4589 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4590 {
4591   struct Client *c;
4592
4593 #if DEBUG_CORE
4594   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4595               "Core service shutting down.\n");
4596 #endif
4597   GNUNET_CONTAINER_multihashmap_iterate (neighbours,
4598                                          &free_neighbour_helper,
4599                                          NULL);
4600   GNUNET_CONTAINER_multihashmap_destroy (neighbours);
4601   neighbours = NULL;
4602   GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), 0, GNUNET_NO);
4603   GNUNET_assert (transport != NULL);
4604   GNUNET_TRANSPORT_disconnect (transport);
4605   transport = NULL;
4606   GNUNET_SERVER_notification_context_destroy (notifier);
4607   notifier = NULL;
4608   while (NULL != (c = clients))
4609     handle_client_disconnect (NULL, c->client_handle);
4610   if (my_private_key != NULL)
4611     GNUNET_CRYPTO_rsa_key_free (my_private_key);
4612   if (stats != NULL)
4613     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4614   if (peerinfo != NULL)
4615     GNUNET_PEERINFO_disconnect (peerinfo);
4616   if (mst != NULL)
4617     GNUNET_SERVER_mst_destroy (mst);
4618 }
4619
4620
4621 /**
4622  * Initiate core service.
4623  *
4624  * @param cls closure
4625  * @param server the initialized server
4626  * @param c configuration to use
4627  */
4628 static void
4629 run (void *cls,
4630      struct GNUNET_SERVER_Handle *server,
4631      const struct GNUNET_CONFIGURATION_Handle *c)
4632 {
4633   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4634     {&handle_client_init, NULL,
4635      GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
4636     {&handle_client_iterate_peers, NULL,
4637      GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
4638      sizeof (struct GNUNET_MessageHeader)},
4639     {&handle_client_request_info, NULL,
4640      GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
4641      sizeof (struct RequestInfoMessage)},
4642     {&handle_client_send_request, NULL,
4643      GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST,
4644      sizeof (struct SendMessageRequest)},
4645     {&handle_client_send, NULL,
4646      GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
4647     {&handle_client_request_connect, NULL,
4648      GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
4649      sizeof (struct ConnectMessage)},
4650     {NULL, NULL, 0, 0}
4651   };
4652   char *keyfile;
4653
4654   cfg = c;    
4655   /* parse configuration */
4656   if (
4657        (GNUNET_OK !=
4658         GNUNET_CONFIGURATION_get_value_number (c,
4659                                                "CORE",
4660                                                "TOTAL_QUOTA_IN",
4661                                                &bandwidth_target_in_bps)) ||
4662        (GNUNET_OK !=
4663         GNUNET_CONFIGURATION_get_value_number (c,
4664                                                "CORE",
4665                                                "TOTAL_QUOTA_OUT",
4666                                                &bandwidth_target_out_bps)) ||
4667        (GNUNET_OK !=
4668         GNUNET_CONFIGURATION_get_value_filename (c,
4669                                                  "GNUNETD",
4670                                                  "HOSTKEY", &keyfile)))
4671     {
4672       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4673                   _
4674                   ("Core service is lacking key configuration settings.  Exiting.\n"));
4675       GNUNET_SCHEDULER_shutdown ();
4676       return;
4677     }
4678   peerinfo = GNUNET_PEERINFO_connect (cfg);
4679   if (NULL == peerinfo)
4680     {
4681       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4682                   _("Could not access PEERINFO service.  Exiting.\n"));
4683       GNUNET_SCHEDULER_shutdown ();
4684       GNUNET_free (keyfile);
4685       return;
4686     }
4687   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4688   GNUNET_free (keyfile);
4689   if (my_private_key == NULL)
4690     {
4691       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4692                   _("Core service could not access hostkey.  Exiting.\n"));
4693       GNUNET_PEERINFO_disconnect (peerinfo);
4694       GNUNET_SCHEDULER_shutdown ();
4695       return;
4696     }
4697   neighbours = GNUNET_CONTAINER_multihashmap_create (128);
4698   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4699   GNUNET_CRYPTO_hash (&my_public_key,
4700                       sizeof (my_public_key), &my_identity.hashPubKey);
4701   self.public_key = &my_public_key;
4702   self.peer = my_identity;
4703   self.last_activity = GNUNET_TIME_UNIT_FOREVER_ABS;
4704   self.status = PEER_STATE_KEY_CONFIRMED;
4705   self.is_connected = GNUNET_YES;
4706   /* setup notification */
4707   notifier = GNUNET_SERVER_notification_context_create (server, 
4708                                                         MAX_NOTIFY_QUEUE);
4709   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4710   /* setup transport connection */
4711   transport = GNUNET_TRANSPORT_connect (cfg,
4712                                         &my_identity,
4713                                         NULL,
4714                                         &handle_transport_receive,
4715                                         &handle_transport_notify_connect,
4716                                         &handle_transport_notify_disconnect);
4717   GNUNET_assert (NULL != transport);
4718   stats = GNUNET_STATISTICS_create ("core", cfg);
4719
4720   GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded CORE_SEND requests"), 0, GNUNET_NO);
4721   GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 0, GNUNET_NO);
4722
4723   mst = GNUNET_SERVER_mst_create (&deliver_message,
4724                                   NULL);
4725   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4726                                 &cleaning_task, NULL);
4727   /* process client requests */
4728   GNUNET_SERVER_add_handlers (server, handlers);
4729   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4730               _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
4731 }
4732
4733
4734
4735 /**
4736  * The main function for the transport service.
4737  *
4738  * @param argc number of arguments from the command line
4739  * @param argv command line arguments
4740  * @return 0 ok, 1 on error
4741  */
4742 int
4743 main (int argc, char *const *argv)
4744 {
4745   return (GNUNET_OK ==
4746           GNUNET_SERVICE_run (argc,
4747                               argv,
4748                               "core",
4749                               GNUNET_SERVICE_OPTION_NONE,
4750                               &run, NULL)) ? 0 : 1;
4751 }
4752
4753 /* end of gnunet-service-core.c */