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