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