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