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