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