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