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