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