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