fixing iteration code to handle ATS structs
[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+1) * 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+1) * 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         GNUNET_array_append (n->ats,
3311                              n->ats_count,
3312                              *ats);     
3313     }
3314 }
3315
3316
3317 /**
3318  * We received a PING message.  Validate and transmit
3319  * PONG.
3320  *
3321  * @param n sender of the PING
3322  * @param m the encrypted PING message itself
3323  * @param ats performance data
3324  * @param ats_count number of entries in ats (excluding 0-termination)
3325  */
3326 static void
3327 handle_ping (struct Neighbour *n,
3328              const struct PingMessage *m,
3329              const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3330              uint32_t ats_count)
3331 {
3332   struct PingMessage t;
3333   struct PongMessage tx;
3334   struct PongMessage *tp;
3335   struct MessageEntry *me;
3336   struct GNUNET_CRYPTO_AesInitializationVector iv;
3337
3338 #if DEBUG_CORE
3339   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3340               "Core service receives `%s' request from `%4s'.\n",
3341               "PING", GNUNET_i2s (&n->peer));
3342 #endif
3343   derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3344   if (GNUNET_OK !=
3345       do_decrypt (n,
3346                   &iv,
3347                   &m->target,
3348                   &t.target,
3349                   sizeof (struct PingMessage) -
3350                   ((void *) &m->target - (void *) m)))
3351     return;
3352 #if DEBUG_HANDSHAKE
3353   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3354               "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u, IV %u (salt %u)\n",
3355               "PING",
3356               GNUNET_i2s (&t.target),
3357               (unsigned int) t.challenge,
3358               (unsigned int) n->decrypt_key.crc32,
3359               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3360               m->iv_seed);
3361 #endif
3362   GNUNET_STATISTICS_update (stats,
3363                             gettext_noop ("# PING messages decrypted"), 
3364                             1,
3365                             GNUNET_NO);
3366   if (0 != memcmp (&t.target,
3367                    &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3368     {
3369       GNUNET_break_op (0);
3370       return;
3371     }
3372   update_neighbour_performance (n, ats, ats_count);
3373   me = GNUNET_malloc (sizeof (struct MessageEntry) +
3374                       sizeof (struct PongMessage));
3375   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3376                                      n->encrypted_tail,
3377                                      n->encrypted_tail,
3378                                      me);
3379   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
3380   me->priority = PONG_PRIORITY;
3381   me->size = sizeof (struct PongMessage);
3382   tx.inbound_bw_limit = n->bw_in;
3383   tx.challenge = t.challenge;
3384   tx.target = t.target;
3385   tp = (struct PongMessage *) &me[1];
3386   tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
3387   tp->header.size = htons (sizeof (struct PongMessage));
3388   tp->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3389   derive_pong_iv (&iv, &n->encrypt_key, tp->iv_seed, t.challenge, &n->peer);
3390   do_encrypt (n,
3391               &iv,
3392               &tx.challenge,
3393               &tp->challenge,
3394               sizeof (struct PongMessage) -
3395               ((void *) &tp->challenge - (void *) tp));
3396   GNUNET_STATISTICS_update (stats, 
3397                             gettext_noop ("# PONG messages created"), 
3398                             1, 
3399                             GNUNET_NO);
3400 #if DEBUG_HANDSHAKE
3401   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3402               "Encrypting `%s' with challenge %u using key %u, IV %u (salt %u)\n",
3403               "PONG",
3404               (unsigned int) t.challenge,
3405               (unsigned int) n->encrypt_key.crc32,
3406               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3407               tp->iv_seed);
3408 #endif
3409   /* trigger queue processing */
3410   process_encrypted_neighbour_queue (n);
3411 }
3412
3413
3414 /**
3415  * We received a PONG message.  Validate and update our status.
3416  *
3417  * @param n sender of the PONG
3418  * @param m the encrypted PONG message itself
3419  * @param ats performance data
3420  * @param ats_count number of entries in ats (excluding 0-termination)
3421  */
3422 static void
3423 handle_pong (struct Neighbour *n, 
3424              const struct PongMessage *m,
3425              const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3426              uint32_t ats_count)
3427 {
3428   struct PongMessage t;
3429   struct ConnectNotifyMessage *cnm;
3430   struct GNUNET_CRYPTO_AesInitializationVector iv;
3431   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
3432   struct GNUNET_TRANSPORT_ATS_Information *mats;
3433   size_t size;
3434
3435 #if DEBUG_CORE
3436   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3437               "Core service receives `%s' response from `%4s'.\n",
3438               "PONG", GNUNET_i2s (&n->peer));
3439 #endif
3440   /* mark as garbage, just to be sure */
3441   memset (&t, 255, sizeof (t));
3442   derive_pong_iv (&iv, &n->decrypt_key, m->iv_seed, n->ping_challenge,
3443       &my_identity);
3444   if (GNUNET_OK !=
3445       do_decrypt (n,
3446                   &iv,
3447                   &m->challenge,
3448                   &t.challenge,
3449                   sizeof (struct PongMessage) -
3450                   ((void *) &m->challenge - (void *) m)))
3451     {
3452       GNUNET_break_op (0);
3453       return;
3454     }
3455   GNUNET_STATISTICS_update (stats, 
3456                             gettext_noop ("# PONG messages decrypted"), 
3457                             1, 
3458                             GNUNET_NO);
3459 #if DEBUG_HANDSHAKE
3460   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3461               "Decrypted `%s' from `%4s' with challenge %u using key %u, IV %u (salt %u)\n",
3462               "PONG",
3463               GNUNET_i2s (&t.target),
3464               (unsigned int) t.challenge,
3465               (unsigned int) n->decrypt_key.crc32,
3466               GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3467               m->iv_seed);
3468 #endif
3469   if ((0 != memcmp (&t.target,
3470                     &n->peer,
3471                     sizeof (struct GNUNET_PeerIdentity))) ||
3472       (n->ping_challenge != t.challenge))
3473     {
3474       /* PONG malformed */
3475 #if DEBUG_CORE
3476       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3477                   "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
3478                   "PONG", 
3479                   GNUNET_i2s (&n->peer),
3480                   (unsigned int) n->ping_challenge);
3481       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3482                   "Received malformed `%s' received from `%4s' with challenge %u\n",
3483                   "PONG", GNUNET_i2s (&t.target), 
3484                   (unsigned int) t.challenge);
3485 #endif
3486       GNUNET_break_op (n->ping_challenge != t.challenge);
3487       return;
3488     }
3489   switch (n->status)
3490     {
3491     case PEER_STATE_DOWN:
3492       GNUNET_break (0);         /* should be impossible */
3493       return;
3494     case PEER_STATE_KEY_SENT:
3495       GNUNET_break (0);         /* should be impossible, how did we decrypt? */
3496       return;
3497     case PEER_STATE_KEY_RECEIVED:
3498       GNUNET_STATISTICS_update (stats, 
3499                                 gettext_noop ("# Session keys confirmed via PONG"), 
3500                                 1, 
3501                                 GNUNET_NO);
3502       n->status = PEER_STATE_KEY_CONFIRMED;
3503       if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
3504         {
3505           n->bw_out_external_limit = t.inbound_bw_limit;
3506           n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3507                                                   n->bw_out_internal_limit);
3508           GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3509                                                  n->bw_out);       
3510           GNUNET_TRANSPORT_set_quota (transport,
3511                                       &n->peer,
3512                                       n->bw_in,
3513                                       n->bw_out,
3514                                       GNUNET_TIME_UNIT_FOREVER_REL,
3515                                       NULL, NULL); 
3516         }
3517 #if DEBUG_CORE
3518       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3519                   "Confirmed key via `%s' message for peer `%4s'\n",
3520                   "PONG", GNUNET_i2s (&n->peer));
3521 #endif      
3522       if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3523         {
3524           GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3525           n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3526         }      
3527       update_neighbour_performance (n, ats, ats_count);      
3528       size = sizeof (struct ConnectNotifyMessage) +
3529         (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3530       if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3531         {
3532           GNUNET_break (0);
3533           /* recovery strategy: throw away performance data */
3534           GNUNET_array_grow (n->ats,
3535                              n->ats_count,
3536                              0);
3537           size = sizeof (struct PeerStatusNotifyMessage) +
3538             (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3539         }
3540       cnm = (struct ConnectNotifyMessage*) buf;
3541       cnm->header.size = htons (size);
3542       cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3543       cnm->ats_count = htonl (n->ats_count);
3544       mats = &cnm->ats;
3545       memcpy (mats,
3546               n->ats,
3547               n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
3548       mats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3549       mats[n->ats_count].value = htonl (0);      
3550       send_to_all_clients (&cnm->header, 
3551                            GNUNET_NO, 
3552                            GNUNET_CORE_OPTION_SEND_CONNECT);
3553       process_encrypted_neighbour_queue (n);
3554       /* fall-through! */
3555     case PEER_STATE_KEY_CONFIRMED:
3556       n->last_activity = GNUNET_TIME_absolute_get ();
3557       if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3558         GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3559       n->keep_alive_task 
3560         = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3561                                         &send_keep_alive,
3562                                         n);
3563       handle_peer_status_change (n);
3564       break;
3565     default:
3566       GNUNET_break (0);
3567       break;
3568     }
3569 }
3570
3571
3572 /**
3573  * We received a SET_KEY message.  Validate and update
3574  * our key material and status.
3575  *
3576  * @param n the neighbour from which we received message m
3577  * @param m the set key message we received
3578  * @param ats performance data
3579  * @param ats_count number of entries in ats (excluding 0-termination)
3580  */
3581 static void
3582 handle_set_key (struct Neighbour *n, 
3583                 const struct SetKeyMessage *m,
3584                 const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3585                 uint32_t ats_count)
3586 {
3587   struct SetKeyMessage *m_cpy;
3588   struct GNUNET_TIME_Absolute t;
3589   struct GNUNET_CRYPTO_AesSessionKey k;
3590   struct PingMessage *ping;
3591   struct PongMessage *pong;
3592   enum PeerStateMachine sender_status;
3593
3594 #if DEBUG_CORE
3595   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3596               "Core service receives `%s' request from `%4s'.\n",
3597               "SET_KEY", GNUNET_i2s (&n->peer));
3598 #endif
3599   if (n->public_key == NULL)
3600     {
3601       if (n->pitr != NULL)
3602         {
3603 #if DEBUG_CORE
3604           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3605                       "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3606                       "SET_KEY");
3607 #endif
3608           return;
3609         }
3610 #if DEBUG_CORE
3611       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3612                   "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3613 #endif
3614       m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3615       memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3616       /* lookup n's public key, then try again */
3617       GNUNET_assert (n->skm == NULL);
3618       n->skm = m_cpy;
3619       n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3620                                          &n->peer,
3621                                          GNUNET_TIME_UNIT_MINUTES,
3622                                          &process_hello_retry_handle_set_key, n);
3623       GNUNET_STATISTICS_update (stats, 
3624                                 gettext_noop ("# SET_KEY messages deferred (need public key)"), 
3625                                 1, 
3626                                 GNUNET_NO);
3627       return;
3628     }
3629   if (0 != memcmp (&m->target,
3630                    &my_identity,
3631                    sizeof (struct GNUNET_PeerIdentity)))
3632     {
3633       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3634                   _("Received `%s' message that was for `%s', not for me.  Ignoring.\n"),
3635                   "SET_KEY",
3636                   GNUNET_i2s (&m->target));
3637       return;
3638     }
3639   if ((ntohl (m->purpose.size) !=
3640        sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3641        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3642        sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3643        sizeof (struct GNUNET_PeerIdentity)) ||
3644       (GNUNET_OK !=
3645        GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3646                                  &m->purpose, &m->signature, n->public_key)))
3647     {
3648       /* invalid signature */
3649       GNUNET_break_op (0);
3650       return;
3651     }
3652   t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3653   if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3654        (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3655       (t.abs_value < n->decrypt_key_created.abs_value))
3656     {
3657       /* this could rarely happen due to massive re-ordering of
3658          messages on the network level, but is most likely either
3659          a bug or some adversary messing with us.  Report. */
3660       GNUNET_break_op (0);
3661       return;
3662     }
3663 #if DEBUG_CORE
3664   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
3665               "Decrypting key material.\n");
3666 #endif  
3667   if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3668                                   &m->encrypted_key,
3669                                   &k,
3670                                   sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3671        != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3672       (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3673     {
3674       /* failed to decrypt !? */
3675       GNUNET_break_op (0);
3676       return;
3677     }
3678   GNUNET_STATISTICS_update (stats, 
3679                             gettext_noop ("# SET_KEY messages decrypted"), 
3680                             1, 
3681                             GNUNET_NO);
3682   n->decrypt_key = k;
3683   if (n->decrypt_key_created.abs_value != t.abs_value)
3684     {
3685       /* fresh key, reset sequence numbers */
3686       n->last_sequence_number_received = 0;
3687       n->last_packets_bitmap = 0;
3688       n->decrypt_key_created = t;
3689     }
3690   update_neighbour_performance (n, ats, ats_count);
3691   sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3692   switch (n->status)
3693     {
3694     case PEER_STATE_DOWN:
3695       n->status = PEER_STATE_KEY_RECEIVED;
3696 #if DEBUG_CORE
3697       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3698                   "Responding to `%s' with my own key.\n", "SET_KEY");
3699 #endif
3700       send_key (n);
3701       break;
3702     case PEER_STATE_KEY_SENT:
3703     case PEER_STATE_KEY_RECEIVED:
3704       n->status = PEER_STATE_KEY_RECEIVED;
3705       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3706           (sender_status != PEER_STATE_KEY_CONFIRMED))
3707         {
3708 #if DEBUG_CORE
3709           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3710                       "Responding to `%s' with my own key (other peer has status %u).\n",
3711                       "SET_KEY",
3712                       (unsigned int) sender_status);
3713 #endif
3714           send_key (n);
3715         }
3716       break;
3717     case PEER_STATE_KEY_CONFIRMED:
3718       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3719           (sender_status != PEER_STATE_KEY_CONFIRMED))
3720         {         
3721 #if DEBUG_CORE
3722           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3723                       "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3724                       "SET_KEY", 
3725                       (unsigned int) sender_status);
3726 #endif
3727           send_key (n);
3728         }
3729       break;
3730     default:
3731       GNUNET_break (0);
3732       break;
3733     }
3734   if (n->pending_ping != NULL)
3735     {
3736       ping = n->pending_ping;
3737       n->pending_ping = NULL;
3738       handle_ping (n, ping, NULL, 0);
3739       GNUNET_free (ping);
3740     }
3741   if (n->pending_pong != NULL)
3742     {
3743       pong = n->pending_pong;
3744       n->pending_pong = NULL;
3745       handle_pong (n, pong, NULL, 0);
3746       GNUNET_free (pong);
3747     }
3748 }
3749
3750
3751 /**
3752  * Send a P2P message to a client.
3753  *
3754  * @param sender who sent us the message?
3755  * @param client who should we give the message to?
3756  * @param m contains the message to transmit
3757  * @param msize number of bytes in buf to transmit
3758  */
3759 static void
3760 send_p2p_message_to_client (struct Neighbour *sender,
3761                             struct Client *client,
3762                             const void *m, size_t msize)
3763 {
3764   size_t size = msize + sizeof (struct NotifyTrafficMessage) +
3765     (sender->ats_count+1) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3766   char buf[size];
3767   struct NotifyTrafficMessage *ntm;
3768   struct GNUNET_TRANSPORT_ATS_Information *ats;
3769
3770   if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3771     {
3772       GNUNET_break (0);
3773       /* recovery strategy: throw performance data away... */
3774       GNUNET_array_grow (sender->ats,
3775                          sender->ats_count,
3776                          0);
3777       size = msize + sizeof (struct NotifyTrafficMessage) +
3778         (sender->ats_count+1) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3779     }
3780 #if DEBUG_CORE
3781   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3782               "Core service passes message from `%4s' of type %u to client.\n",
3783               GNUNET_i2s(&sender->peer),
3784               (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3785 #endif
3786   ntm = (struct NotifyTrafficMessage *) buf;
3787   ntm->header.size = htons (size);
3788   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3789   ntm->ats_count = htonl (sender->ats_count);
3790   ntm->peer = sender->peer;
3791   ats = &ntm->ats;
3792   memcpy (ats,
3793           sender->ats,
3794           sizeof (struct GNUNET_TRANSPORT_ATS_Information) * sender->ats_count);
3795   ats[sender->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3796   ats[sender->ats_count].value = htonl (0);  
3797   memcpy (&ats[sender->ats_count+1],
3798           m, 
3799           msize);
3800   send_to_client (client, &ntm->header, GNUNET_YES);
3801 }
3802
3803
3804 /**
3805  * Deliver P2P message to interested clients.
3806  *
3807  * @param cls always NULL
3808  * @param client who sent us the message (struct Neighbour)
3809  * @param m the message
3810  */
3811 static void
3812 deliver_message (void *cls,
3813                  void *client,
3814                  const struct GNUNET_MessageHeader *m)
3815 {
3816   struct Neighbour *sender = client;
3817   size_t msize = ntohs (m->size);
3818   char buf[256];
3819   struct Client *cpos;
3820   uint16_t type;
3821   unsigned int tpos;
3822   int deliver_full;
3823   int dropped;
3824
3825   type = ntohs (m->type);
3826 #if DEBUG_CORE
3827   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3828               "Received encapsulated message of type %u and size %u from `%4s'\n",
3829               (unsigned int) type,
3830               ntohs (m->size),
3831               GNUNET_i2s (&sender->peer));
3832 #endif
3833   GNUNET_snprintf (buf,
3834                    sizeof(buf),
3835                    gettext_noop ("# bytes of messages of type %u received"),
3836                    (unsigned int) type);
3837   GNUNET_STATISTICS_set (stats,
3838                          buf,
3839                          msize,
3840                          GNUNET_NO);     
3841   dropped = GNUNET_YES;
3842   cpos = clients;
3843   while (cpos != NULL)
3844     {
3845       deliver_full = GNUNET_NO;
3846       if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3847         deliver_full = GNUNET_YES;
3848       else
3849         {
3850           for (tpos = 0; tpos < cpos->tcnt; tpos++)
3851             {
3852               if (type != cpos->types[tpos])
3853                 continue;
3854               deliver_full = GNUNET_YES;
3855               break;
3856             }
3857         }
3858       if (GNUNET_YES == deliver_full)
3859         {
3860           send_p2p_message_to_client (sender, cpos, m, msize);
3861           dropped = GNUNET_NO;
3862         }
3863       else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3864         {
3865           send_p2p_message_to_client (sender, cpos, m,
3866                                       sizeof (struct GNUNET_MessageHeader));
3867         }
3868       cpos = cpos->next;
3869     }
3870   if (dropped == GNUNET_YES)
3871     {
3872 #if DEBUG_CORE
3873       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3874                   "Message of type %u from `%4s' not delivered to any client.\n",
3875                   (unsigned int) type,
3876                   GNUNET_i2s (&sender->peer));
3877 #endif
3878       GNUNET_STATISTICS_update (stats,
3879                                 gettext_noop ("# messages not delivered to any client"), 
3880                                 1, GNUNET_NO);
3881     }
3882 }
3883
3884
3885 /**
3886  * We received an encrypted message.  Decrypt, validate and
3887  * pass on to the appropriate clients.
3888  *
3889  * @param n target of the message
3890  * @param m encrypted message
3891  * @param ats performance data
3892  * @param ats_count number of entries in ats (excluding 0-termination)
3893  */
3894 static void
3895 handle_encrypted_message (struct Neighbour *n,
3896                           const struct EncryptedMessage *m,
3897                           const struct GNUNET_TRANSPORT_ATS_Information *ats, 
3898                           uint32_t ats_count)
3899 {
3900   size_t size = ntohs (m->header.size);
3901   char buf[size];
3902   struct EncryptedMessage *pt;  /* plaintext */
3903   GNUNET_HashCode ph;
3904   uint32_t snum;
3905   struct GNUNET_TIME_Absolute t;
3906   struct GNUNET_CRYPTO_AesInitializationVector iv;
3907   struct GNUNET_CRYPTO_AuthKey auth_key;
3908
3909 #if DEBUG_CORE
3910   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3911               "Core service receives `%s' request from `%4s'.\n",
3912               "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3913 #endif  
3914   /* validate hash */
3915   derive_auth_key (&auth_key,
3916                    &n->decrypt_key,
3917                    m->iv_seed,
3918                    n->decrypt_key_created);
3919   GNUNET_CRYPTO_hmac (&auth_key,
3920                       &m->sequence_number,
3921                       size - ENCRYPTED_HEADER_SIZE, &ph);
3922 #if DEBUG_HANDSHAKE
3923   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3924               "Re-Authenticated %u bytes of ciphertext (`%u'): `%s'\n",
3925               (unsigned int) size - ENCRYPTED_HEADER_SIZE,
3926               GNUNET_CRYPTO_crc32_n (&m->sequence_number,
3927                   size - ENCRYPTED_HEADER_SIZE),
3928               GNUNET_h2s (&ph));
3929 #endif
3930
3931   if (0 != memcmp (&ph,
3932                    &m->hmac,
3933                    sizeof (GNUNET_HashCode)))
3934     {
3935       /* checksum failed */
3936       GNUNET_break_op (0);
3937       return;
3938     }
3939   derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3940   /* decrypt */
3941   if (GNUNET_OK !=
3942       do_decrypt (n,
3943                   &iv,
3944                   &m->sequence_number,
3945                   &buf[ENCRYPTED_HEADER_SIZE],
3946                   size - ENCRYPTED_HEADER_SIZE))
3947     return;
3948   pt = (struct EncryptedMessage *) buf;
3949
3950   /* validate sequence number */
3951   snum = ntohl (pt->sequence_number);
3952   if (n->last_sequence_number_received == snum)
3953     {
3954       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3955                   "Received duplicate message, ignoring.\n");
3956       /* duplicate, ignore */
3957       GNUNET_STATISTICS_set (stats,
3958                              gettext_noop ("# bytes dropped (duplicates)"),
3959                              size,
3960                              GNUNET_NO);      
3961       return;
3962     }
3963   if ((n->last_sequence_number_received > snum) &&
3964       (n->last_sequence_number_received - snum > 32))
3965     {
3966       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3967                   "Received ancient out of sequence message, ignoring.\n");
3968       /* ancient out of sequence, ignore */
3969       GNUNET_STATISTICS_set (stats,
3970                              gettext_noop ("# bytes dropped (out of sequence)"),
3971                              size,
3972                              GNUNET_NO);      
3973       return;
3974     }
3975   if (n->last_sequence_number_received > snum)
3976     {
3977       unsigned int rotbit =
3978         1 << (n->last_sequence_number_received - snum - 1);
3979       if ((n->last_packets_bitmap & rotbit) != 0)
3980         {
3981           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3982                       "Received duplicate message, ignoring.\n");
3983           GNUNET_STATISTICS_set (stats,
3984                                  gettext_noop ("# bytes dropped (duplicates)"),
3985                                  size,
3986                                  GNUNET_NO);      
3987           /* duplicate, ignore */
3988           return;
3989         }
3990       n->last_packets_bitmap |= rotbit;
3991     }
3992   if (n->last_sequence_number_received < snum)
3993     {
3994       int shift = (snum - n->last_sequence_number_received);
3995       if (shift >= 8 * sizeof(n->last_packets_bitmap))
3996         n->last_packets_bitmap = 0;
3997       else
3998         n->last_packets_bitmap <<= shift;
3999       n->last_sequence_number_received = snum;
4000     }
4001
4002   /* check timestamp */
4003   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
4004   if (GNUNET_TIME_absolute_get_duration (t).rel_value > MAX_MESSAGE_AGE.rel_value)
4005     {
4006       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4007                   _
4008                   ("Message received far too old (%llu ms). Content ignored.\n"),
4009                   GNUNET_TIME_absolute_get_duration (t).rel_value);
4010       GNUNET_STATISTICS_set (stats,
4011                              gettext_noop ("# bytes dropped (ancient message)"),
4012                              size,
4013                              GNUNET_NO);      
4014       return;
4015     }
4016
4017   /* process decrypted message(s) */
4018   if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
4019     {
4020 #if DEBUG_CORE_SET_QUOTA
4021       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4022                   "Received %u b/s as new inbound limit for peer `%4s'\n",
4023                   (unsigned int) ntohl (pt->inbound_bw_limit.value__),
4024                   GNUNET_i2s (&n->peer));
4025 #endif
4026       n->bw_out_external_limit = pt->inbound_bw_limit;
4027       n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
4028                                               n->bw_out_internal_limit);
4029       GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
4030                                              n->bw_out);
4031       GNUNET_TRANSPORT_set_quota (transport,
4032                                   &n->peer,
4033                                   n->bw_in,
4034                                   n->bw_out,
4035                                   GNUNET_TIME_UNIT_FOREVER_REL,
4036                                   NULL, NULL); 
4037     }
4038   n->last_activity = GNUNET_TIME_absolute_get ();
4039   if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
4040     GNUNET_SCHEDULER_cancel (n->keep_alive_task);
4041   n->keep_alive_task 
4042     = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
4043                                     &send_keep_alive,
4044                                     n);
4045   GNUNET_STATISTICS_set (stats,
4046                          gettext_noop ("# bytes of payload decrypted"),
4047                          size - sizeof (struct EncryptedMessage),
4048                          GNUNET_NO);
4049   handle_peer_status_change (n);
4050   update_neighbour_performance (n, ats, ats_count);
4051   if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst, 
4052                                               n,
4053                                               &buf[sizeof (struct EncryptedMessage)], 
4054                                               size - sizeof (struct EncryptedMessage),
4055                                               GNUNET_YES, GNUNET_NO))
4056     GNUNET_break_op (0);
4057 }
4058
4059
4060 /**
4061  * Function called by the transport for each received message.
4062  *
4063  * @param cls closure
4064  * @param peer (claimed) identity of the other peer
4065  * @param message the message
4066  * @param ats performance data
4067  * @param ats_count number of entries in ats (excluding 0-termination)
4068  */
4069 static void
4070 handle_transport_receive (void *cls,
4071                           const struct GNUNET_PeerIdentity *peer,
4072                           const struct GNUNET_MessageHeader *message,
4073                           const struct GNUNET_TRANSPORT_ATS_Information *ats, 
4074                           uint32_t ats_count)
4075 {
4076   struct Neighbour *n;
4077   struct GNUNET_TIME_Absolute now;
4078   int up;
4079   uint16_t type;
4080   uint16_t size;
4081   int changed;
4082
4083 #if DEBUG_CORE
4084   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4085               "Received message of type %u from `%4s', demultiplexing.\n",
4086               (unsigned int) ntohs (message->type), 
4087               GNUNET_i2s (peer));
4088 #endif
4089   if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4090     {
4091       GNUNET_break (0);
4092       return;
4093     }
4094   n = find_neighbour (peer);
4095   if (n == NULL)
4096     n = create_neighbour (peer);
4097   changed = GNUNET_YES; /* FIXME... */
4098   up = (n->status == PEER_STATE_KEY_CONFIRMED);
4099   type = ntohs (message->type);
4100   size = ntohs (message->size);
4101   switch (type)
4102     {
4103     case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
4104       if (size != sizeof (struct SetKeyMessage))
4105         {
4106           GNUNET_break_op (0);
4107           return;
4108         }
4109       GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
4110       handle_set_key (n,
4111                       (const struct SetKeyMessage *) message,
4112                       ats, ats_count);
4113       break;
4114     case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
4115       if (size < sizeof (struct EncryptedMessage) +
4116           sizeof (struct GNUNET_MessageHeader))
4117         {
4118           GNUNET_break_op (0);
4119           return;
4120         }
4121       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
4122           (n->status != PEER_STATE_KEY_CONFIRMED))
4123         {
4124           GNUNET_break_op (0);
4125           return;
4126         }
4127       handle_encrypted_message (n, 
4128                                 (const struct EncryptedMessage *) message,
4129                                 ats, ats_count);
4130       break;
4131     case GNUNET_MESSAGE_TYPE_CORE_PING:
4132       if (size != sizeof (struct PingMessage))
4133         {
4134           GNUNET_break_op (0);
4135           return;
4136         }
4137       GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
4138       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
4139           (n->status != PEER_STATE_KEY_CONFIRMED))
4140         {
4141 #if DEBUG_CORE
4142           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4143                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
4144                       "PING", GNUNET_i2s (&n->peer));
4145 #endif
4146           GNUNET_free_non_null (n->pending_ping);
4147           n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
4148           memcpy (n->pending_ping, message, sizeof (struct PingMessage));
4149           return;
4150         }
4151       handle_ping (n, (const struct PingMessage *) message,
4152                    ats, ats_count);
4153       break;
4154     case GNUNET_MESSAGE_TYPE_CORE_PONG:
4155       if (size != sizeof (struct PongMessage))
4156         {
4157           GNUNET_break_op (0);
4158           return;
4159         }
4160       GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
4161       if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
4162            (n->status != PEER_STATE_KEY_CONFIRMED) )
4163         {
4164 #if DEBUG_CORE
4165           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4166                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
4167                       "PONG", GNUNET_i2s (&n->peer));
4168 #endif
4169           GNUNET_free_non_null (n->pending_pong);
4170           n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
4171           memcpy (n->pending_pong, message, sizeof (struct PongMessage));
4172           return;
4173         }
4174       handle_pong (n, (const struct PongMessage *) message,
4175                    ats, ats_count);
4176       break;
4177     default:
4178       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4179                   _("Unsupported message of type %u received.\n"),
4180                   (unsigned int) type);
4181       return;
4182     }
4183   if (n->status == PEER_STATE_KEY_CONFIRMED)
4184     {
4185       now = GNUNET_TIME_absolute_get ();
4186       n->last_activity = now;
4187       changed = GNUNET_YES;
4188       if (!up)
4189         {
4190           GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
4191           n->time_established = now;
4192         }
4193       if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
4194         GNUNET_SCHEDULER_cancel (n->keep_alive_task);
4195       n->keep_alive_task 
4196         = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
4197                                         &send_keep_alive,
4198                                         n);
4199     }
4200   if (changed)
4201     handle_peer_status_change (n);
4202 }
4203
4204
4205 /**
4206  * Function that recalculates the bandwidth quota for the
4207  * given neighbour and transmits it to the transport service.
4208  * 
4209  * @param cls neighbour for the quota update
4210  * @param tc context
4211  */
4212 static void
4213 neighbour_quota_update (void *cls,
4214                         const struct GNUNET_SCHEDULER_TaskContext *tc)
4215 {
4216   struct Neighbour *n = cls;
4217   struct GNUNET_BANDWIDTH_Value32NBO q_in;
4218   struct GNUNET_BANDWIDTH_Value32NBO q_out;
4219   struct GNUNET_BANDWIDTH_Value32NBO q_out_min;
4220   double pref_rel;
4221   double share;
4222   unsigned long long distributable;
4223   uint64_t need_per_peer;
4224   uint64_t need_per_second;
4225
4226 #if DEBUG_CORE
4227   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4228               "Neighbour quota update calculation running for peer `%4s'\n",
4229               GNUNET_i2s (&n->peer));  
4230 #endif
4231   n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
4232   /* calculate relative preference among all neighbours;
4233      divides by a bit more to avoid division by zero AND to
4234      account for possibility of new neighbours joining any time 
4235      AND to convert to double... */
4236   if (preference_sum == 0)
4237     {
4238       pref_rel = 1.0 / (double) neighbour_count;
4239     }
4240   else
4241     {
4242       pref_rel = n->current_preference / preference_sum;
4243     }
4244   need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
4245                                                               GNUNET_TIME_UNIT_SECONDS);  
4246   need_per_second = need_per_peer * neighbour_count;
4247
4248   /* calculate inbound bandwidth per peer */
4249   distributable = 0;
4250   if (bandwidth_target_in_bps > need_per_second)
4251     distributable = bandwidth_target_in_bps - need_per_second;
4252   share = distributable * pref_rel;
4253   if (share + need_per_peer > UINT32_MAX)
4254     q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4255   else
4256     q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4257
4258   /* calculate outbound bandwidth per peer */
4259   distributable = 0;
4260   if (bandwidth_target_out_bps > need_per_second)
4261     distributable = bandwidth_target_out_bps - need_per_second;
4262   share = distributable * pref_rel;
4263   if (share + need_per_peer > UINT32_MAX)
4264     q_out = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4265   else
4266     q_out = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4267   n->bw_out_internal_limit = q_out;
4268
4269   q_out_min = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit, n->bw_out_internal_limit);
4270   GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window, n->bw_out);
4271
4272   /* check if we want to disconnect for good due to inactivity */
4273   if ( (GNUNET_TIME_absolute_get_duration (get_neighbour_timeout (n)).rel_value > 0) &&
4274        (GNUNET_TIME_absolute_get_duration (n->time_established).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) )
4275     {
4276 #if DEBUG_CORE
4277       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4278                   "Forcing disconnect of `%4s' due to inactivity\n",
4279                   GNUNET_i2s (&n->peer));
4280 #endif
4281       q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
4282     }
4283 #if DEBUG_CORE_QUOTA
4284   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4285               "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
4286               GNUNET_i2s (&n->peer),
4287               (unsigned int) ntohl (q_in.value__),
4288               bandwidth_target_out_bps,
4289               (unsigned int) ntohl (n->bw_in.value__),
4290               (unsigned int) ntohl (n->bw_out.value__),
4291               (unsigned int) ntohl (n->bw_out_internal_limit.value__));
4292   #endif
4293   if ((n->bw_in.value__ != q_in.value__) || (n->bw_out.value__ != q_out_min.value__))
4294     {
4295           if (n->bw_in.value__ != q_in.value__)
4296                   n->bw_in = q_in;
4297           if (n->bw_out.value__ != q_out_min.value__)
4298                   n->bw_out = q_out_min;
4299       if (GNUNET_YES == n->is_connected)
4300         GNUNET_TRANSPORT_set_quota (transport,
4301                                     &n->peer,
4302                                     n->bw_in,
4303                                     n->bw_out,
4304                                     GNUNET_TIME_UNIT_FOREVER_REL,
4305                                     NULL, NULL);
4306       handle_peer_status_change (n);
4307     }
4308   schedule_quota_update (n);
4309 }
4310
4311
4312 /**
4313  * Function called by transport to notify us that
4314  * a peer connected to us (on the network level).
4315  *
4316  * @param cls closure
4317  * @param peer the peer that connected
4318  * @param ats performance data
4319  * @param ats_count number of entries in ats (excluding 0-termination)
4320  */
4321 static void
4322 handle_transport_notify_connect (void *cls,
4323                                  const struct GNUNET_PeerIdentity *peer,
4324                                  const struct GNUNET_TRANSPORT_ATS_Information *ats,
4325                                  uint32_t ats_count)
4326 {
4327   struct Neighbour *n;
4328
4329   if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4330     {
4331       GNUNET_break (0);
4332       return;
4333     }
4334   n = find_neighbour (peer);
4335   if (n != NULL)
4336     {
4337       if (GNUNET_YES == n->is_connected)
4338         {
4339           /* duplicate connect notification!? */
4340           GNUNET_break (0);
4341           return;
4342         }
4343     }
4344   else
4345     {
4346       n = create_neighbour (peer);
4347     }
4348   GNUNET_STATISTICS_update (stats, 
4349                             gettext_noop ("# peers connected (transport)"), 
4350                             1, 
4351                             GNUNET_NO);
4352   n->is_connected = GNUNET_YES;      
4353   update_neighbour_performance (n, ats, ats_count);
4354   GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
4355                                  n->bw_out,
4356                                  MAX_WINDOW_TIME_S);
4357   GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
4358                                  n->bw_in,
4359                                  MAX_WINDOW_TIME_S);  
4360 #if DEBUG_CORE
4361   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4362               "Received connection from `%4s'.\n",
4363               GNUNET_i2s (&n->peer));
4364 #endif
4365   GNUNET_TRANSPORT_set_quota (transport,
4366                               &n->peer,
4367                               n->bw_in,
4368                               n->bw_out,
4369                               GNUNET_TIME_UNIT_FOREVER_REL,
4370                               NULL, NULL);
4371   send_key (n); 
4372 }
4373
4374
4375 /**
4376  * Function called by transport telling us that a peer
4377  * disconnected.
4378  *
4379  * @param cls closure
4380  * @param peer the peer that disconnected
4381  */
4382 static void
4383 handle_transport_notify_disconnect (void *cls,
4384                                     const struct GNUNET_PeerIdentity *peer)
4385 {
4386   struct DisconnectNotifyMessage cnm;
4387   struct Neighbour *n;
4388   struct ClientActiveRequest *car;
4389   struct GNUNET_TIME_Relative left;
4390
4391 #if DEBUG_CORE
4392   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4393               "Peer `%4s' disconnected from us; received notification from transport.\n", GNUNET_i2s (peer));
4394 #endif
4395
4396   n = find_neighbour (peer);
4397   if (n == NULL)
4398     {
4399       GNUNET_break (0);
4400       return;
4401     }
4402   GNUNET_break (n->is_connected);
4403   if (n->status == PEER_STATE_KEY_CONFIRMED)
4404     {
4405       cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
4406       cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
4407       cnm.peer = *peer;
4408       send_to_all_clients (&cnm.header, GNUNET_NO, GNUNET_CORE_OPTION_SEND_DISCONNECT);
4409     }
4410
4411   /* On transport disconnect transport doesn't cancel requests, so must do so here. */
4412   if (n->th != NULL)
4413     {
4414       GNUNET_TRANSPORT_notify_transmit_ready_cancel(n->th);
4415     }
4416   n->th = NULL;
4417
4418   n->is_connected = GNUNET_NO;
4419   n->status = PEER_STATE_DOWN;
4420   while (NULL != (car = n->active_client_request_head))
4421     {
4422       GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
4423                                    n->active_client_request_tail,
4424                                    car);
4425       GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
4426                                             &n->peer.hashPubKey,
4427                                             car);
4428       GNUNET_free (car);
4429     }
4430
4431   GNUNET_STATISTICS_update (stats, 
4432                             gettext_noop ("# peers connected (transport)"), 
4433                             -1, 
4434                             GNUNET_NO);
4435   if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
4436     GNUNET_SCHEDULER_cancel (n->dead_clean_task);
4437   left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4438                                         GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
4439   n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (), 
4440                                                     left);
4441   n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
4442                                                      &consider_free_task,
4443                                                      n);
4444 }
4445
4446
4447 /**
4448  * Last task run during shutdown.  Disconnects us from
4449  * the transport.
4450  */
4451 static void
4452 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4453 {
4454   struct Neighbour *n;
4455   struct Client *c;
4456
4457 #if DEBUG_CORE
4458   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4459               "Core service shutting down.\n");
4460 #endif
4461   while (NULL != (n = neighbours))
4462     {
4463       neighbours = n->next;
4464       GNUNET_assert (neighbour_count > 0);
4465       neighbour_count--;
4466       free_neighbour (n);
4467     }
4468   GNUNET_assert (transport != NULL);
4469   GNUNET_TRANSPORT_disconnect (transport);
4470   transport = NULL;
4471   GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
4472   GNUNET_SERVER_notification_context_destroy (notifier);
4473   notifier = NULL;
4474   while (NULL != (c = clients))
4475     handle_client_disconnect (NULL, c->client_handle);
4476   if (my_private_key != NULL)
4477     GNUNET_CRYPTO_rsa_key_free (my_private_key);
4478   if (stats != NULL)
4479     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4480   if (peerinfo != NULL)
4481     GNUNET_PEERINFO_disconnect (peerinfo);
4482   if (mst != NULL)
4483     GNUNET_SERVER_mst_destroy (mst);
4484 }
4485
4486
4487 /**
4488  * Initiate core service.
4489  *
4490  * @param cls closure
4491  * @param server the initialized server
4492  * @param c configuration to use
4493  */
4494 static void
4495 run (void *cls,
4496      struct GNUNET_SERVER_Handle *server,
4497      const struct GNUNET_CONFIGURATION_Handle *c)
4498 {
4499   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4500     {&handle_client_init, NULL,
4501      GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
4502     {&handle_client_iterate_peers, NULL,
4503      GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
4504      sizeof (struct GNUNET_MessageHeader)},
4505     {&handle_client_request_info, NULL,
4506      GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
4507      sizeof (struct RequestInfoMessage)},
4508     {&handle_client_send_request, NULL,
4509      GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST,
4510      sizeof (struct SendMessageRequest)},
4511     {&handle_client_send, NULL,
4512      GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
4513     {&handle_client_request_connect, NULL,
4514      GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
4515      sizeof (struct ConnectMessage)},
4516     {NULL, NULL, 0, 0}
4517   };
4518   char *keyfile;
4519
4520   cfg = c;  
4521   /* parse configuration */
4522   if (
4523        (GNUNET_OK !=
4524         GNUNET_CONFIGURATION_get_value_number (c,
4525                                                "CORE",
4526                                                "TOTAL_QUOTA_IN",
4527                                                &bandwidth_target_in_bps)) ||
4528        (GNUNET_OK !=
4529         GNUNET_CONFIGURATION_get_value_number (c,
4530                                                "CORE",
4531                                                "TOTAL_QUOTA_OUT",
4532                                                &bandwidth_target_out_bps)) ||
4533        (GNUNET_OK !=
4534         GNUNET_CONFIGURATION_get_value_filename (c,
4535                                                  "GNUNETD",
4536                                                  "HOSTKEY", &keyfile)))
4537     {
4538       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4539                   _
4540                   ("Core service is lacking key configuration settings.  Exiting.\n"));
4541       GNUNET_SCHEDULER_shutdown ();
4542       return;
4543     }
4544   peerinfo = GNUNET_PEERINFO_connect (cfg);
4545   if (NULL == peerinfo)
4546     {
4547       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4548                   _("Could not access PEERINFO service.  Exiting.\n"));
4549       GNUNET_SCHEDULER_shutdown ();
4550       GNUNET_free (keyfile);
4551       return;
4552     }
4553   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4554   GNUNET_free (keyfile);
4555   if (my_private_key == NULL)
4556     {
4557       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4558                   _("Core service could not access hostkey.  Exiting.\n"));
4559       GNUNET_PEERINFO_disconnect (peerinfo);
4560       GNUNET_SCHEDULER_shutdown ();
4561       return;
4562     }
4563   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4564   GNUNET_CRYPTO_hash (&my_public_key,
4565                       sizeof (my_public_key), &my_identity.hashPubKey);
4566   /* setup notification */
4567   notifier = GNUNET_SERVER_notification_context_create (server, 
4568                                                         MAX_NOTIFY_QUEUE);
4569   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4570   /* setup transport connection */
4571   transport = GNUNET_TRANSPORT_connect (cfg,
4572                                         &my_identity,
4573                                         NULL,
4574                                         &handle_transport_receive,
4575                                         &handle_transport_notify_connect,
4576                                         &handle_transport_notify_disconnect);
4577   GNUNET_assert (NULL != transport);
4578   stats = GNUNET_STATISTICS_create ("core", cfg);
4579
4580   GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded CORE_SEND requests"), 0, GNUNET_NO);
4581   GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 0, GNUNET_NO);
4582
4583   mst = GNUNET_SERVER_mst_create (&deliver_message,
4584                                   NULL);
4585   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4586                                 &cleaning_task, NULL);
4587   /* process client requests */
4588   GNUNET_SERVER_add_handlers (server, handlers);
4589   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4590               _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
4591 }
4592
4593
4594
4595 /**
4596  * The main function for the transport service.
4597  *
4598  * @param argc number of arguments from the command line
4599  * @param argv command line arguments
4600  * @return 0 ok, 1 on error
4601  */
4602 int
4603 main (int argc, char *const *argv)
4604 {
4605   return (GNUNET_OK ==
4606           GNUNET_SERVICE_run (argc,
4607                               argv,
4608                               "core",
4609                               GNUNET_SERVICE_OPTION_NONE,
4610                               &run, NULL)) ? 0 : 1;
4611 }
4612
4613 /* end of gnunet-service-core.c */