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