cleaning
[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 plaintext_hash;
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_hash (&ph->sequence_number,
2028                       esize - sizeof (GNUNET_HashCode), 
2029                       &ph->plaintext_hash);
2030   GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
2031 #if DEBUG_HANDSHAKE
2032   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2033               "Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
2034               (unsigned int) (esize - sizeof (GNUNET_HashCode)),
2035               GNUNET_h2s (&ph->plaintext_hash),
2036               (int) ph->iv_seed);
2037 #endif
2038   /* encrypt */
2039 #if DEBUG_HANDSHAKE
2040   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2041               "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2042               (unsigned int) esize,
2043               GNUNET_i2s(&n->peer),
2044               (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2045 #endif
2046   GNUNET_assert (GNUNET_OK ==
2047                  do_encrypt (n,
2048                              &iv,
2049                              &ph->plaintext_hash,
2050                              &em->plaintext_hash, esize));
2051   /* append to transmission list */
2052   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2053                                      n->encrypted_tail,
2054                                      n->encrypted_tail,
2055                                      me);
2056   process_encrypted_neighbour_queue (n);
2057 }
2058
2059
2060 /**
2061  * Function that recalculates the bandwidth quota for the
2062  * given neighbour and transmits it to the transport service.
2063  * 
2064  * @param cls neighbour for the quota update
2065  * @param tc context
2066  */
2067 static void
2068 neighbour_quota_update (void *cls,
2069                         const struct GNUNET_SCHEDULER_TaskContext *tc);
2070
2071
2072 /**
2073  * Schedule the task that will recalculate the bandwidth
2074  * quota for this peer (and possibly force a disconnect of
2075  * idle peers by calculating a bandwidth of zero).
2076  */
2077 static void
2078 schedule_quota_update (struct Neighbour *n)
2079 {
2080   GNUNET_assert (n->quota_update_task ==
2081                  GNUNET_SCHEDULER_NO_TASK);
2082   n->quota_update_task
2083     = GNUNET_SCHEDULER_add_delayed (sched,
2084                                     QUOTA_UPDATE_FREQUENCY,
2085                                     &neighbour_quota_update,
2086                                     n);
2087 }
2088
2089
2090 /**
2091  * Initialize a new 'struct Neighbour'.
2092  *
2093  * @param pid ID of the new neighbour
2094  * @return handle for the new neighbour
2095  */
2096 static struct Neighbour *
2097 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2098 {
2099   struct Neighbour *n;
2100   struct GNUNET_TIME_Absolute now;
2101
2102 #if DEBUG_CORE
2103   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2104               "Creating neighbour entry for peer `%4s'\n",
2105               GNUNET_i2s (pid));
2106 #endif
2107   n = GNUNET_malloc (sizeof (struct Neighbour));
2108   n->next = neighbours;
2109   neighbours = n;
2110   neighbour_count++;
2111   GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2112   n->peer = *pid;
2113   GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2114   now = GNUNET_TIME_absolute_get ();
2115   n->encrypt_key_created = now;
2116   n->last_activity = now;
2117   n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2118   n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2119   n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2120   n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2121   n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2122   n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2123                                                 UINT32_MAX);
2124   neighbour_quota_update (n, NULL);
2125   consider_free_neighbour (n);
2126   return n;
2127 }
2128
2129
2130 /**
2131  * Handle CORE_SEND request.
2132  *
2133  * @param cls unused
2134  * @param client the client issuing the request
2135  * @param message the "struct SendMessage"
2136  */
2137 static void
2138 handle_client_send (void *cls,
2139                     struct GNUNET_SERVER_Client *client,
2140                     const struct GNUNET_MessageHeader *message)
2141 {
2142   const struct SendMessage *sm;
2143   struct Neighbour *n;
2144   struct MessageEntry *prev;
2145   struct MessageEntry *pos;
2146   struct MessageEntry *e; 
2147   struct MessageEntry *min_prio_entry;
2148   struct MessageEntry *min_prio_prev;
2149   unsigned int min_prio;
2150   unsigned int queue_size;
2151   uint16_t msize;
2152
2153   msize = ntohs (message->size);
2154   if (msize <
2155       sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2156     {
2157       GNUNET_break (0);
2158       if (client != NULL)
2159         GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2160       return;
2161     }
2162   sm = (const struct SendMessage *) message;
2163   msize -= sizeof (struct SendMessage);
2164   if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2165     {
2166       /* FIXME: should we not allow loopback-injection here? */
2167       GNUNET_break (0);
2168       if (client != NULL)
2169         GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2170       return;
2171     }
2172   n = find_neighbour (&sm->peer);
2173   if (n == NULL)
2174     n = create_neighbour (&sm->peer);
2175 #if DEBUG_CORE
2176   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2177               "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2178               "SEND",
2179               (unsigned int) msize, 
2180               GNUNET_i2s (&sm->peer));
2181 #endif
2182   /* bound queue size */
2183   discard_expired_messages (n);
2184   min_prio = UINT32_MAX;
2185   min_prio_entry = NULL;
2186   min_prio_prev = NULL;
2187   queue_size = 0;
2188   prev = NULL;
2189   pos = n->messages;
2190   while (pos != NULL) 
2191     {
2192       if (pos->priority < min_prio)
2193         {
2194           min_prio_entry = pos;
2195           min_prio_prev = prev;
2196           min_prio = pos->priority;
2197         }
2198       queue_size++;
2199       prev = pos;
2200       pos = pos->next;
2201     }
2202   if (queue_size >= MAX_PEER_QUEUE_SIZE)
2203     {
2204       /* queue full */
2205       if (ntohl(sm->priority) <= min_prio)
2206         {
2207           /* discard new entry */
2208 #if DEBUG_CORE
2209           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2210                       "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2211                       queue_size,
2212                       (unsigned int) MAX_PEER_QUEUE_SIZE,
2213                       (unsigned int) msize,
2214                       (unsigned int) ntohs (message->type));
2215 #endif
2216           if (client != NULL)
2217             GNUNET_SERVER_receive_done (client, GNUNET_OK);
2218           return;
2219         }
2220       /* discard "min_prio_entry" */
2221 #if DEBUG_CORE
2222       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2223                   "Queue full, discarding existing older request\n");
2224 #endif
2225       if (min_prio_prev == NULL)
2226         n->messages = min_prio_entry->next;
2227       else
2228         min_prio_prev->next = min_prio_entry->next;      
2229       GNUNET_free (min_prio_entry);     
2230     }
2231
2232 #if DEBUG_CORE
2233   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2234               "Adding transmission request for `%4s' of size %u to queue\n",
2235               GNUNET_i2s (&sm->peer),
2236               (unsigned int) msize);
2237 #endif  
2238   e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2239   e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2240   e->priority = ntohl (sm->priority);
2241   e->size = msize;
2242   memcpy (&e[1], &sm[1], msize);
2243
2244   /* insert, keep list sorted by deadline */
2245   prev = NULL;
2246   pos = n->messages;
2247   while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2248     {
2249       prev = pos;
2250       pos = pos->next;
2251     }
2252   if (prev == NULL)
2253     n->messages = e;
2254   else
2255     prev->next = e;
2256   e->next = pos;
2257
2258   /* consider scheduling now */
2259   process_plaintext_neighbour_queue (n);
2260   if (client != NULL)
2261     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2262 }
2263
2264
2265 /**
2266  * Function called when the transport service is ready to
2267  * receive a message.  Only resets 'n->th' to NULL.
2268  *
2269  * @param cls neighbour to use message from
2270  * @param size number of bytes we can transmit
2271  * @param buf where to copy the message
2272  * @return number of bytes transmitted
2273  */
2274 static size_t
2275 notify_transport_connect_done (void *cls, size_t size, void *buf)
2276 {
2277   struct Neighbour *n = cls;
2278
2279   n->th = NULL;
2280   if (buf == NULL)
2281     {
2282       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2283                   _("Failed to connect to `%4s': transport failed to connect\n"),
2284                   GNUNET_i2s (&n->peer));
2285       return 0;
2286     }
2287   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2288               _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2289               GNUNET_i2s (&n->peer));
2290   if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2291     GNUNET_SCHEDULER_cancel (sched,
2292                              n->retry_set_key_task);
2293   n->retry_set_key_task = GNUNET_SCHEDULER_add_now (sched, 
2294                                                     &set_key_retry_task,
2295                                                     n);
2296   return 0;
2297 }
2298
2299
2300 /**
2301  * Handle CORE_REQUEST_CONNECT request.
2302  *
2303  * @param cls unused
2304  * @param client the client issuing the request
2305  * @param message the "struct ConnectMessage"
2306  */
2307 static void
2308 handle_client_request_connect (void *cls,
2309                                struct GNUNET_SERVER_Client *client,
2310                                const struct GNUNET_MessageHeader *message)
2311 {
2312   const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2313   struct Neighbour *n;
2314   struct GNUNET_TIME_Relative timeout;
2315
2316   if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2317     {
2318       GNUNET_break (0);
2319       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2320       return;
2321     }
2322   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2323   n = find_neighbour (&cm->peer);
2324   if (n == NULL)
2325     n = create_neighbour (&cm->peer);
2326   if ( (GNUNET_YES == n->is_connected) ||
2327        (n->th != NULL) )
2328     return; /* already connected, or at least trying */
2329   GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2330 #if DEBUG_CORE
2331   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2332               "Core received `%s' request for `%4s', will try to establish connection\n",
2333               "REQUEST_CONNECT",
2334               GNUNET_i2s (&cm->peer));
2335 #endif
2336   timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2337   /* ask transport to connect to the peer */
2338   n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2339                                                   &cm->peer,
2340                                                   sizeof (struct GNUNET_MessageHeader), 0,
2341                                                   timeout,
2342                                                   &notify_transport_connect_done,
2343                                                   n);
2344   GNUNET_break (NULL != n->th);
2345 }
2346
2347
2348 /**
2349  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
2350  * the neighbour's struct and retry send_key.  Or, if we did not get a
2351  * HELLO, just do nothing.
2352  *
2353  * @param cls the 'struct Neighbour' to retry sending the key for
2354  * @param peer the peer for which this is the HELLO
2355  * @param hello HELLO message of that peer
2356  * @param trust amount of trust we currently have in that peer
2357  */
2358 static void
2359 process_hello_retry_send_key (void *cls,
2360                               const struct GNUNET_PeerIdentity *peer,
2361                               const struct GNUNET_HELLO_Message *hello,
2362                               uint32_t trust)
2363 {
2364   struct Neighbour *n = cls;
2365
2366   if (peer == NULL)
2367     {
2368 #if DEBUG_CORE
2369       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2370                   "Entered `%s' and `%s' is NULL!\n",
2371                   "process_hello_retry_send_key",
2372                   "peer");
2373 #endif
2374       n->pitr = NULL;
2375       if (n->public_key != NULL)
2376         {
2377           if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2378             {
2379               GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2380               n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2381             }      
2382           GNUNET_STATISTICS_update (stats,
2383                                     gettext_noop ("# SET_KEY messages deferred (need public key)"), 
2384                                     -1, 
2385                                     GNUNET_NO);
2386           send_key (n);
2387         }
2388       else
2389         {
2390           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2391                       _("Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n"),
2392                       GNUNET_i2s (&n->peer));
2393           GNUNET_STATISTICS_update (stats,
2394                                     gettext_noop ("# Delayed connecting due to lack of public key"),
2395                                     1,
2396                                     GNUNET_NO);      
2397           if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2398             n->retry_set_key_task
2399               = GNUNET_SCHEDULER_add_delayed (sched,
2400                                               n->set_key_retry_frequency,
2401                                               &set_key_retry_task, n);
2402         }
2403       return;
2404     }
2405
2406 #if DEBUG_CORE
2407   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2408               "Entered `%s' for peer `%4s'\n",
2409               "process_hello_retry_send_key",
2410               GNUNET_i2s (peer));
2411 #endif
2412   if (n->public_key != NULL)
2413     {
2414       /* already have public key, why are we here? */
2415       GNUNET_break (0);
2416       return;
2417     }
2418
2419 #if DEBUG_CORE
2420   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2421               "Received new `%s' message for `%4s', initiating key exchange.\n",
2422               "HELLO",
2423               GNUNET_i2s (peer));
2424 #endif
2425   n->public_key =
2426     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2427   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2428     {
2429       GNUNET_STATISTICS_update (stats,
2430                                 gettext_noop ("# Error extracting public key from HELLO"),
2431                                 1,
2432                                 GNUNET_NO);      
2433       GNUNET_free (n->public_key);
2434       n->public_key = NULL;
2435 #if DEBUG_CORE
2436   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2437               "GNUNET_HELLO_get_key returned awfully\n");
2438 #endif
2439       return;
2440     }
2441 }
2442
2443
2444 /**
2445  * Send our key (and encrypted PING) to the other peer.
2446  *
2447  * @param n the other peer
2448  */
2449 static void
2450 send_key (struct Neighbour *n)
2451 {
2452   struct MessageEntry *pos;
2453   struct SetKeyMessage *sm;
2454   struct MessageEntry *me;
2455   struct PingMessage pp;
2456   struct PingMessage *pm;
2457
2458   if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2459     {
2460       GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2461       n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2462     }        
2463   if (n->pitr != NULL)
2464     {
2465 #if DEBUG_CORE
2466       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2467                   "Key exchange in progress with `%4s'.\n",
2468                   GNUNET_i2s (&n->peer));
2469 #endif
2470       return; /* already in progress */
2471     }
2472   if (GNUNET_YES != n->is_connected)
2473     {
2474 #if DEBUG_CORE
2475       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2476                   "Not yet connected to peer `%4s'!\n",
2477                   GNUNET_i2s (&n->peer));
2478 #endif
2479       if (NULL == n->th)
2480         {
2481           GNUNET_STATISTICS_update (stats, 
2482                                     gettext_noop ("# Asking transport to connect (for SET_KEY)"), 
2483                                     1, 
2484                                     GNUNET_NO);
2485           n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2486                                                           &n->peer,
2487                                                           sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2488                                                           0,
2489                                                           GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2490                                                           &notify_encrypted_transmit_ready,
2491                                                           n);
2492         }
2493       return; 
2494     }
2495 #if DEBUG_CORE
2496   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2497               "Asked to perform key exchange with `%4s'.\n",
2498               GNUNET_i2s (&n->peer));
2499 #endif
2500   if (n->public_key == NULL)
2501     {
2502       /* lookup n's public key, then try again */
2503 #if DEBUG_CORE
2504       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2505                   "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2506                   GNUNET_i2s (&n->peer));
2507 #endif
2508       GNUNET_assert (n->pitr == NULL);
2509       n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2510                                          &n->peer,
2511                                          0,
2512                                          GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2513                                          &process_hello_retry_send_key, n);
2514       return;
2515     }
2516   pos = n->encrypted_head;
2517   while (pos != NULL)
2518     {
2519       if (GNUNET_YES == pos->is_setkey)
2520         {
2521           if (pos->sender_status == n->status)
2522             {
2523 #if DEBUG_CORE
2524               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2525                           "`%s' message for `%4s' queued already\n",
2526                           "SET_KEY",
2527                           GNUNET_i2s (&n->peer));
2528 #endif
2529               goto trigger_processing;
2530             }
2531           GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2532                                        n->encrypted_tail,
2533                                        pos);
2534           GNUNET_free (pos);
2535 #if DEBUG_CORE
2536           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2537                       "Removing queued `%s' message for `%4s', will create a new one\n",
2538                       "SET_KEY",
2539                       GNUNET_i2s (&n->peer));
2540 #endif
2541           break;
2542         }
2543       pos = pos->next;
2544     }
2545
2546   /* update status */
2547   switch (n->status)
2548     {
2549     case PEER_STATE_DOWN:
2550       n->status = PEER_STATE_KEY_SENT;
2551       break;
2552     case PEER_STATE_KEY_SENT:
2553       break;
2554     case PEER_STATE_KEY_RECEIVED:
2555       break;
2556     case PEER_STATE_KEY_CONFIRMED:
2557       break;
2558     default:
2559       GNUNET_break (0);
2560       break;
2561     }
2562   
2563
2564   /* first, set key message */
2565   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2566                       sizeof (struct SetKeyMessage) +
2567                       sizeof (struct PingMessage));
2568   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2569   me->priority = SET_KEY_PRIORITY;
2570   me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
2571   me->is_setkey = GNUNET_YES;
2572   me->got_slack = GNUNET_YES; /* do not defer this one! */
2573   me->sender_status = n->status;
2574   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2575                                      n->encrypted_tail,
2576                                      n->encrypted_tail,
2577                                      me);
2578   sm = (struct SetKeyMessage *) &me[1];
2579   sm->header.size = htons (sizeof (struct SetKeyMessage));
2580   sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2581   sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2582                                         PEER_STATE_KEY_SENT : n->status));
2583   sm->purpose.size =
2584     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2585            sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2586            sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2587            sizeof (struct GNUNET_PeerIdentity));
2588   sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2589   sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2590   sm->target = n->peer;
2591   GNUNET_assert (GNUNET_OK ==
2592                  GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2593                                             sizeof (struct
2594                                                     GNUNET_CRYPTO_AesSessionKey),
2595                                             n->public_key,
2596                                             &sm->encrypted_key));
2597   GNUNET_assert (GNUNET_OK ==
2598                  GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2599                                          &sm->signature));  
2600   pm = (struct PingMessage *) &sm[1];
2601   pm->header.size = htons (sizeof (struct PingMessage));
2602   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2603   pp.challenge = htonl (n->ping_challenge);
2604   pp.target = n->peer;
2605 #if DEBUG_HANDSHAKE
2606   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2607               "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u.\n",
2608               "SET_KEY", "PING",
2609               (unsigned int) n->ping_challenge,
2610               GNUNET_i2s (&n->peer),
2611               (unsigned int) n->encrypt_key.crc32);
2612 #endif
2613   do_encrypt (n,
2614               &n->peer.hashPubKey,
2615               &pp.challenge,
2616               &pm->challenge,
2617               sizeof (struct PingMessage) -
2618               sizeof (struct GNUNET_MessageHeader));
2619   GNUNET_STATISTICS_update (stats, 
2620                             gettext_noop ("# SET_KEY and PING messages created"), 
2621                             1, 
2622                             GNUNET_NO);
2623 #if DEBUG_CORE
2624   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2625               "Have %llu ms left for `%s' transmission.\n",
2626               (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2627               "SET_KEY");
2628 #endif
2629  trigger_processing:
2630   /* trigger queue processing */
2631   process_encrypted_neighbour_queue (n);
2632   if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2633        (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2634     n->retry_set_key_task
2635       = GNUNET_SCHEDULER_add_delayed (sched,
2636                                       n->set_key_retry_frequency,
2637                                       &set_key_retry_task, n);    
2638 }
2639
2640
2641 /**
2642  * We received a SET_KEY message.  Validate and update
2643  * our key material and status.
2644  *
2645  * @param n the neighbour from which we received message m
2646  * @param m the set key message we received
2647  */
2648 static void
2649 handle_set_key (struct Neighbour *n,
2650                 const struct SetKeyMessage *m);
2651
2652
2653 /**
2654  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
2655  * the neighbour's struct and retry handling the set_key message.  Or,
2656  * if we did not get a HELLO, just free the set key message.
2657  *
2658  * @param cls pointer to the set key message
2659  * @param peer the peer for which this is the HELLO
2660  * @param hello HELLO message of that peer
2661  * @param trust amount of trust we currently have in that peer
2662  */
2663 static void
2664 process_hello_retry_handle_set_key (void *cls,
2665                                     const struct GNUNET_PeerIdentity *peer,
2666                                     const struct GNUNET_HELLO_Message *hello,
2667                                     uint32_t trust)
2668 {
2669   struct Neighbour *n = cls;
2670   struct SetKeyMessage *sm = n->skm;
2671
2672   if (peer == NULL)
2673     {
2674       n->skm = NULL;
2675       n->pitr = NULL;
2676       if (n->public_key != NULL)
2677         {
2678 #if DEBUG_CORE
2679           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2680                       "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2681                       "HELLO",
2682                       GNUNET_i2s (&n->peer),
2683                       "SET_KEY");
2684 #endif
2685           handle_set_key (n, sm);
2686         }
2687       else
2688         {
2689           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2690                       _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
2691                       "SET_KEY",
2692                       GNUNET_i2s (&n->peer));
2693         }
2694       GNUNET_free (sm);
2695       return;
2696     }
2697   if (n->public_key != NULL)
2698     return;                     /* multiple HELLOs match!? */
2699   n->public_key =
2700     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2701   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2702     {
2703       GNUNET_break_op (0);
2704       GNUNET_free (n->public_key);
2705       n->public_key = NULL;
2706     }
2707 }
2708
2709
2710 /**
2711  * We received a PING message.  Validate and transmit
2712  * PONG.
2713  *
2714  * @param n sender of the PING
2715  * @param m the encrypted PING message itself
2716  */
2717 static void
2718 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2719 {
2720   struct PingMessage t;
2721   struct PongMessage tx;
2722   struct PongMessage *tp;
2723   struct MessageEntry *me;
2724
2725 #if DEBUG_CORE
2726   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2727               "Core service receives `%s' request from `%4s'.\n",
2728               "PING", GNUNET_i2s (&n->peer));
2729 #endif
2730   if (GNUNET_OK !=
2731       do_decrypt (n,
2732                   &my_identity.hashPubKey,
2733                   &m->challenge,
2734                   &t.challenge,
2735                   sizeof (struct PingMessage) -
2736                   sizeof (struct GNUNET_MessageHeader)))
2737     return;
2738 #if DEBUG_HANDSHAKE
2739   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2740               "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2741               "PING",
2742               GNUNET_i2s (&t.target),
2743               (unsigned int) ntohl (t.challenge), 
2744               (unsigned int) n->decrypt_key.crc32);
2745 #endif
2746   GNUNET_STATISTICS_update (stats,
2747                             gettext_noop ("# PING messages decrypted"), 
2748                             1,
2749                             GNUNET_NO);
2750   if (0 != memcmp (&t.target,
2751                    &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2752     {
2753       GNUNET_break_op (0);
2754       return;
2755     }
2756   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2757                       sizeof (struct PongMessage));
2758   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2759                                      n->encrypted_tail,
2760                                      n->encrypted_tail,
2761                                      me);
2762   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2763   me->priority = PONG_PRIORITY;
2764   me->size = sizeof (struct PongMessage);
2765   tx.reserved = htonl (0);
2766   tx.inbound_bw_limit = n->bw_in;
2767   tx.challenge = t.challenge;
2768   tx.target = t.target;
2769   tp = (struct PongMessage *) &me[1];
2770   tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2771   tp->header.size = htons (sizeof (struct PongMessage));
2772   do_encrypt (n,
2773               &my_identity.hashPubKey,
2774               &tx.challenge,
2775               &tp->challenge,
2776               sizeof (struct PongMessage) -
2777               sizeof (struct GNUNET_MessageHeader));
2778   GNUNET_STATISTICS_update (stats, 
2779                             gettext_noop ("# PONG messages created"), 
2780                             1, 
2781                             GNUNET_NO);
2782 #if DEBUG_HANDSHAKE
2783   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2784               "Encrypting `%s' with challenge %u using key %u\n",
2785               "PONG",
2786               (unsigned int) ntohl (t.challenge),
2787               (unsigned int) n->encrypt_key.crc32);
2788 #endif
2789   /* trigger queue processing */
2790   process_encrypted_neighbour_queue (n);
2791 }
2792
2793
2794 /**
2795  * We received a PONG message.  Validate and update our status.
2796  *
2797  * @param n sender of the PONG
2798  * @param m the encrypted PONG message itself
2799  */
2800 static void
2801 handle_pong (struct Neighbour *n, 
2802              const struct PongMessage *m)
2803 {
2804   struct PongMessage t;
2805   struct ConnectNotifyMessage cnm;
2806
2807 #if DEBUG_CORE
2808   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2809               "Core service receives `%s' response from `%4s'.\n",
2810               "PONG", GNUNET_i2s (&n->peer));
2811 #endif
2812   /* mark as garbage, just to be sure */
2813   memset (&t, 255, sizeof (t));
2814   if (GNUNET_OK !=
2815       do_decrypt (n,
2816                   &n->peer.hashPubKey,
2817                   &m->challenge,
2818                   &t.challenge,
2819                   sizeof (struct PongMessage) -
2820                   sizeof (struct GNUNET_MessageHeader)))
2821     {
2822       GNUNET_break_op (0);
2823       return;
2824     }
2825   GNUNET_STATISTICS_update (stats, 
2826                             gettext_noop ("# PONG messages decrypted"), 
2827                             1, 
2828                             GNUNET_NO);
2829   if (0 != ntohl (t.reserved))
2830     {
2831       GNUNET_break_op (0);
2832       return;
2833     }
2834 #if DEBUG_HANDSHAKE
2835   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2836               "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2837               "PONG",
2838               GNUNET_i2s (&t.target),
2839               (unsigned int) ntohl (t.challenge),
2840               (unsigned int) n->decrypt_key.crc32);
2841 #endif
2842   if ((0 != memcmp (&t.target,
2843                     &n->peer,
2844                     sizeof (struct GNUNET_PeerIdentity))) ||
2845       (n->ping_challenge != ntohl (t.challenge)))
2846     {
2847       /* PONG malformed */
2848 #if DEBUG_CORE
2849       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2850                   "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2851                   "PONG", 
2852                   GNUNET_i2s (&n->peer),
2853                   (unsigned int) n->ping_challenge);
2854       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2855                   "Received malformed `%s' received from `%4s' with challenge %u\n",
2856                   "PONG", GNUNET_i2s (&t.target), 
2857                   (unsigned int) ntohl (t.challenge));
2858 #endif
2859       GNUNET_break_op (0);
2860       return;
2861     }
2862   switch (n->status)
2863     {
2864     case PEER_STATE_DOWN:
2865       GNUNET_break (0);         /* should be impossible */
2866       return;
2867     case PEER_STATE_KEY_SENT:
2868       GNUNET_break (0);         /* should be impossible, how did we decrypt? */
2869       return;
2870     case PEER_STATE_KEY_RECEIVED:
2871       GNUNET_STATISTICS_update (stats, 
2872                                 gettext_noop ("# Session keys confirmed via PONG"), 
2873                                 1, 
2874                                 GNUNET_NO);
2875       n->status = PEER_STATE_KEY_CONFIRMED;
2876       if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2877         {
2878           n->bw_out_external_limit = t.inbound_bw_limit;
2879           n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2880                                                   n->bw_out_internal_limit);
2881           GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2882                                                  n->bw_out);       
2883           GNUNET_TRANSPORT_set_quota (transport,
2884                                       &n->peer,
2885                                       n->bw_in,
2886                                       n->bw_out,
2887                                       GNUNET_TIME_UNIT_FOREVER_REL,
2888                                       NULL, NULL); 
2889         }
2890 #if DEBUG_CORE
2891       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2892                   "Confirmed key via `%s' message for peer `%4s'\n",
2893                   "PONG", GNUNET_i2s (&n->peer));
2894 #endif      
2895       if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2896         {
2897           GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2898           n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2899         }      
2900       cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2901       cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2902       cnm.distance = htonl (n->last_distance);
2903       cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2904       cnm.peer = n->peer;
2905       send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2906       process_encrypted_neighbour_queue (n);
2907       /* fall-through! */
2908     case PEER_STATE_KEY_CONFIRMED:
2909       n->last_activity = GNUNET_TIME_absolute_get ();
2910       if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2911         GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2912       n->keep_alive_task 
2913         = GNUNET_SCHEDULER_add_delayed (sched, 
2914                                         GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2915                                         &send_keep_alive,
2916                                         n);
2917       break;
2918     default:
2919       GNUNET_break (0);
2920       break;
2921     }
2922 }
2923
2924
2925 /**
2926  * We received a SET_KEY message.  Validate and update
2927  * our key material and status.
2928  *
2929  * @param n the neighbour from which we received message m
2930  * @param m the set key message we received
2931  */
2932 static void
2933 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2934 {
2935   struct SetKeyMessage *m_cpy;
2936   struct GNUNET_TIME_Absolute t;
2937   struct GNUNET_CRYPTO_AesSessionKey k;
2938   struct PingMessage *ping;
2939   struct PongMessage *pong;
2940   enum PeerStateMachine sender_status;
2941
2942 #if DEBUG_CORE
2943   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2944               "Core service receives `%s' request from `%4s'.\n",
2945               "SET_KEY", GNUNET_i2s (&n->peer));
2946 #endif
2947   if (n->public_key == NULL)
2948     {
2949       if (n->pitr != NULL)
2950         {
2951 #if DEBUG_CORE
2952           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2953                       "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2954                       "SET_KEY");
2955 #endif
2956           return;
2957         }
2958 #if DEBUG_CORE
2959       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2960                   "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2961 #endif
2962       m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2963       memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2964       /* lookup n's public key, then try again */
2965       GNUNET_assert (n->skm == NULL);
2966       n->skm = m_cpy;
2967       n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2968                                          &n->peer,
2969                                          0,
2970                                          GNUNET_TIME_UNIT_MINUTES,
2971                                          &process_hello_retry_handle_set_key, n);
2972       GNUNET_STATISTICS_update (stats, 
2973                                 gettext_noop ("# SET_KEY messages deferred (need public key)"), 
2974                                 1, 
2975                                 GNUNET_NO);
2976       return;
2977     }
2978   if (0 != memcmp (&m->target,
2979                    &my_identity,
2980                    sizeof (struct GNUNET_PeerIdentity)))
2981     {
2982       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2983                   _("Received `%s' message that was for `%s', not for me.  Ignoring.\n"),
2984                   "SET_KEY",
2985                   GNUNET_i2s (&m->target));
2986       return;
2987     }
2988   if ((ntohl (m->purpose.size) !=
2989        sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2990        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2991        sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2992        sizeof (struct GNUNET_PeerIdentity)) ||
2993       (GNUNET_OK !=
2994        GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2995                                  &m->purpose, &m->signature, n->public_key)))
2996     {
2997       /* invalid signature */
2998       GNUNET_break_op (0);
2999       return;
3000     }
3001   t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3002   if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3003        (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3004       (t.value < n->decrypt_key_created.value))
3005     {
3006       /* this could rarely happen due to massive re-ordering of
3007          messages on the network level, but is most likely either
3008          a bug or some adversary messing with us.  Report. */
3009       GNUNET_break_op (0);
3010       return;
3011     }
3012 #if DEBUG_CORE
3013   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
3014               "Decrypting key material.\n");
3015 #endif  
3016   if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3017                                   &m->encrypted_key,
3018                                   &k,
3019                                   sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3020        != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3021       (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3022     {
3023       /* failed to decrypt !? */
3024       GNUNET_break_op (0);
3025       return;
3026     }
3027   GNUNET_STATISTICS_update (stats, 
3028                             gettext_noop ("# SET_KEY messages decrypted"), 
3029                             1, 
3030                             GNUNET_NO);
3031   n->decrypt_key = k;
3032   if (n->decrypt_key_created.value != t.value)
3033     {
3034       /* fresh key, reset sequence numbers */
3035       n->last_sequence_number_received = 0;
3036       n->last_packets_bitmap = 0;
3037       n->decrypt_key_created = t;
3038     }
3039   sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3040   switch (n->status)
3041     {
3042     case PEER_STATE_DOWN:
3043       n->status = PEER_STATE_KEY_RECEIVED;
3044 #if DEBUG_CORE
3045       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3046                   "Responding to `%s' with my own key.\n", "SET_KEY");
3047 #endif
3048       send_key (n);
3049       break;
3050     case PEER_STATE_KEY_SENT:
3051     case PEER_STATE_KEY_RECEIVED:
3052       n->status = PEER_STATE_KEY_RECEIVED;
3053       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3054           (sender_status != PEER_STATE_KEY_CONFIRMED))
3055         {
3056 #if DEBUG_CORE
3057           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3058                       "Responding to `%s' with my own key (other peer has status %u).\n",
3059                       "SET_KEY",
3060                       (unsigned int) sender_status);
3061 #endif
3062           send_key (n);
3063         }
3064       break;
3065     case PEER_STATE_KEY_CONFIRMED:
3066       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3067           (sender_status != PEER_STATE_KEY_CONFIRMED))
3068         {         
3069 #if DEBUG_CORE
3070           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3071                       "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3072                       "SET_KEY", 
3073                       (unsigned int) sender_status);
3074 #endif
3075           send_key (n);
3076         }
3077       break;
3078     default:
3079       GNUNET_break (0);
3080       break;
3081     }
3082   if (n->pending_ping != NULL)
3083     {
3084       ping = n->pending_ping;
3085       n->pending_ping = NULL;
3086       handle_ping (n, ping);
3087       GNUNET_free (ping);
3088     }
3089   if (n->pending_pong != NULL)
3090     {
3091       pong = n->pending_pong;
3092       n->pending_pong = NULL;
3093       handle_pong (n, pong);
3094       GNUNET_free (pong);
3095     }
3096 }
3097
3098
3099 /**
3100  * Send a P2P message to a client.
3101  *
3102  * @param sender who sent us the message?
3103  * @param client who should we give the message to?
3104  * @param m contains the message to transmit
3105  * @param msize number of bytes in buf to transmit
3106  */
3107 static void
3108 send_p2p_message_to_client (struct Neighbour *sender,
3109                             struct Client *client,
3110                             const void *m, size_t msize)
3111 {
3112   char buf[msize + sizeof (struct NotifyTrafficMessage)];
3113   struct NotifyTrafficMessage *ntm;
3114
3115 #if DEBUG_CORE
3116   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3117               "Core service passes message from `%4s' of type %u to client.\n",
3118               GNUNET_i2s(&sender->peer),
3119               (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3120 #endif
3121   ntm = (struct NotifyTrafficMessage *) buf;
3122   ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3123   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3124   ntm->distance = htonl (sender->last_distance);
3125   ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3126   ntm->peer = sender->peer;
3127   memcpy (&ntm[1], m, msize);
3128   send_to_client (client, &ntm->header, GNUNET_YES);
3129 }
3130
3131
3132 /**
3133  * Deliver P2P message to interested clients.
3134  *
3135  * @param sender who sent us the message?
3136  * @param m the message
3137  * @param msize size of the message (including header)
3138  */
3139 static void
3140 deliver_message (struct Neighbour *sender,
3141                  const struct GNUNET_MessageHeader *m, size_t msize)
3142 {
3143   char buf[256];
3144   struct Client *cpos;
3145   uint16_t type;
3146   unsigned int tpos;
3147   int deliver_full;
3148   int dropped;
3149
3150   type = ntohs (m->type);
3151 #if DEBUG_CORE
3152   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3153               "Received encapsulated message of type %u and size %u from `%4s'\n",
3154               (unsigned int) type,
3155               ntohs (m->size),
3156               GNUNET_i2s (&sender->peer));
3157 #endif
3158   GNUNET_snprintf (buf,
3159                    sizeof(buf),
3160                    gettext_noop ("# bytes of messages of type %u received"),
3161                    (unsigned int) type);
3162   GNUNET_STATISTICS_set (stats,
3163                          buf,
3164                          msize,
3165                          GNUNET_NO);     
3166   dropped = GNUNET_YES;
3167   cpos = clients;
3168   while (cpos != NULL)
3169     {
3170       deliver_full = GNUNET_NO;
3171       if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3172         deliver_full = GNUNET_YES;
3173       else
3174         {
3175           for (tpos = 0; tpos < cpos->tcnt; tpos++)
3176             {
3177               if (type != cpos->types[tpos])
3178                 continue;
3179               deliver_full = GNUNET_YES;
3180               break;
3181             }
3182         }
3183       if (GNUNET_YES == deliver_full)
3184         {
3185           send_p2p_message_to_client (sender, cpos, m, msize);
3186           dropped = GNUNET_NO;
3187         }
3188       else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3189         {
3190           send_p2p_message_to_client (sender, cpos, m,
3191                                       sizeof (struct GNUNET_MessageHeader));
3192         }
3193       cpos = cpos->next;
3194     }
3195   if (dropped == GNUNET_YES)
3196     {
3197 #if DEBUG_CORE
3198       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3199                   "Message of type %u from `%4s' not delivered to any client.\n",
3200                   (unsigned int) type,
3201                   GNUNET_i2s (&sender->peer));
3202 #endif
3203       GNUNET_STATISTICS_update (stats,
3204                                 gettext_noop ("# messages not delivered to any client"), 
3205                                 1, GNUNET_NO);
3206     }
3207 }
3208
3209
3210 /**
3211  * Align P2P message and then deliver to interested clients.
3212  *
3213  * @param sender who sent us the message?
3214  * @param buffer unaligned (!) buffer containing message
3215  * @param msize size of the message (including header)
3216  */
3217 static void
3218 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
3219 {
3220   char abuf[msize];
3221
3222   /* TODO: call to statistics? */
3223   memcpy (abuf, buffer, msize);
3224   deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
3225 }
3226
3227
3228 /**
3229  * Deliver P2P messages to interested clients.
3230  *
3231  * @param sender who sent us the message?
3232  * @param buffer buffer containing messages, can be modified
3233  * @param buffer_size size of the buffer (overall)
3234  * @param offset offset where messages in the buffer start
3235  */
3236 static void
3237 deliver_messages (struct Neighbour *sender,
3238                   const char *buffer, size_t buffer_size, size_t offset)
3239 {
3240   struct GNUNET_MessageHeader *mhp;
3241   struct GNUNET_MessageHeader mh;
3242   uint16_t msize;
3243   int need_align;
3244
3245   while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
3246     {     
3247       if (0 != offset % sizeof (uint16_t))
3248         {
3249           /* outch, need to copy to access header */
3250           memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
3251           mhp = &mh;
3252         }
3253       else
3254         {
3255           /* can access header directly */
3256           mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
3257         }
3258       msize = ntohs (mhp->size);
3259       if (msize + offset > buffer_size)
3260         {
3261           /* malformed message, header says it is larger than what
3262              would fit into the overall buffer */
3263           GNUNET_break_op (0);
3264           break;
3265         }
3266 #if HAVE_UNALIGNED_64_ACCESS
3267       need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
3268 #else
3269       need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
3270 #endif
3271 #if DEBUG_CORE
3272       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3273                   "Delivering %u bytes of message at offset %u/%u to clients.\n",
3274                   (unsigned int) msize,
3275                   (unsigned int) offset,
3276                   (unsigned int) buffer_size);
3277 #endif
3278
3279       if (GNUNET_YES == need_align)
3280         align_and_deliver (sender, &buffer[offset], msize);
3281       else
3282         deliver_message (sender,
3283                          (const struct GNUNET_MessageHeader *)
3284                          &buffer[offset], msize);
3285       offset += msize;
3286     }
3287 }
3288
3289
3290 /**
3291  * We received an encrypted message.  Decrypt, validate and
3292  * pass on to the appropriate clients.
3293  */
3294 static void
3295 handle_encrypted_message (struct Neighbour *n,
3296                           const struct EncryptedMessage *m)
3297 {
3298   size_t size = ntohs (m->header.size);
3299   char buf[size];
3300   struct EncryptedMessage *pt;  /* plaintext */
3301   GNUNET_HashCode ph;
3302   uint32_t snum;
3303   struct GNUNET_TIME_Absolute t;
3304   GNUNET_HashCode iv;
3305
3306 #if DEBUG_CORE
3307   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3308               "Core service receives `%s' request from `%4s'.\n",
3309               "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3310 #endif  
3311   GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3312   /* decrypt */
3313   if (GNUNET_OK !=
3314       do_decrypt (n,
3315                   &iv,
3316                   &m->plaintext_hash,
3317                   &buf[ENCRYPTED_HEADER_SIZE], 
3318                   size - ENCRYPTED_HEADER_SIZE))
3319     return;
3320   pt = (struct EncryptedMessage *) buf;
3321   /* validate hash */
3322   GNUNET_CRYPTO_hash (&pt->sequence_number,
3323                       size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3324 #if DEBUG_HANDSHAKE 
3325   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3326               "V-Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
3327               (unsigned int) (size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode)),
3328               GNUNET_h2s (&ph),
3329               (int) m->iv_seed);
3330 #endif
3331   if (0 != memcmp (&ph, 
3332                    &pt->plaintext_hash, 
3333                    sizeof (GNUNET_HashCode)))
3334     {
3335       /* checksum failed */
3336       GNUNET_break_op (0);
3337       return;
3338     }
3339
3340   /* validate sequence number */
3341   snum = ntohl (pt->sequence_number);
3342   if (n->last_sequence_number_received == snum)
3343     {
3344       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3345                   "Received duplicate message, ignoring.\n");
3346       /* duplicate, ignore */
3347       GNUNET_STATISTICS_set (stats,
3348                              gettext_noop ("# bytes dropped (duplicates)"),
3349                              size,
3350                              GNUNET_NO);      
3351       return;
3352     }
3353   if ((n->last_sequence_number_received > snum) &&
3354       (n->last_sequence_number_received - snum > 32))
3355     {
3356       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3357                   "Received ancient out of sequence message, ignoring.\n");
3358       /* ancient out of sequence, ignore */
3359       GNUNET_STATISTICS_set (stats,
3360                              gettext_noop ("# bytes dropped (out of sequence)"),
3361                              size,
3362                              GNUNET_NO);      
3363       return;
3364     }
3365   if (n->last_sequence_number_received > snum)
3366     {
3367       unsigned int rotbit =
3368         1 << (n->last_sequence_number_received - snum - 1);
3369       if ((n->last_packets_bitmap & rotbit) != 0)
3370         {
3371           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3372                       "Received duplicate message, ignoring.\n");
3373           GNUNET_STATISTICS_set (stats,
3374                                  gettext_noop ("# bytes dropped (duplicates)"),
3375                                  size,
3376                                  GNUNET_NO);      
3377           /* duplicate, ignore */
3378           return;
3379         }
3380       n->last_packets_bitmap |= rotbit;
3381     }
3382   if (n->last_sequence_number_received < snum)
3383     {
3384       n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3385       n->last_sequence_number_received = snum;
3386     }
3387
3388   /* check timestamp */
3389   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3390   if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3391     {
3392       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3393                   _
3394                   ("Message received far too old (%llu ms). Content ignored.\n"),
3395                   GNUNET_TIME_absolute_get_duration (t).value);
3396       GNUNET_STATISTICS_set (stats,
3397                              gettext_noop ("# bytes dropped (ancient message)"),
3398                              size,
3399                              GNUNET_NO);      
3400       return;
3401     }
3402
3403   /* process decrypted message(s) */
3404   if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3405     {
3406 #if DEBUG_CORE_SET_QUOTA
3407       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3408                   "Received %u b/s as new inbound limit for peer `%4s'\n",
3409                   (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3410                   GNUNET_i2s (&n->peer));
3411 #endif
3412       n->bw_out_external_limit = pt->inbound_bw_limit;
3413       n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3414                                               n->bw_out_internal_limit);
3415       GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3416                                              n->bw_out);
3417       GNUNET_TRANSPORT_set_quota (transport,
3418                                   &n->peer,
3419                                   n->bw_in,
3420                                   n->bw_out,
3421                                   GNUNET_TIME_UNIT_FOREVER_REL,
3422                                   NULL, NULL); 
3423     }
3424   n->last_activity = GNUNET_TIME_absolute_get ();
3425   if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3426     GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3427   n->keep_alive_task 
3428     = GNUNET_SCHEDULER_add_delayed (sched, 
3429                                     GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3430                                     &send_keep_alive,
3431                                     n);
3432   GNUNET_STATISTICS_set (stats,
3433                          gettext_noop ("# bytes of payload decrypted"),
3434                          size - sizeof (struct EncryptedMessage),
3435                          GNUNET_NO);      
3436   deliver_messages (n, buf, size, sizeof (struct EncryptedMessage));
3437 }
3438
3439
3440 /**
3441  * Function called by the transport for each received message.
3442  *
3443  * @param cls closure
3444  * @param peer (claimed) identity of the other peer
3445  * @param message the message
3446  * @param latency estimated latency for communicating with the
3447  *             given peer (round-trip)
3448  * @param distance in overlay hops, as given by transport plugin
3449  */
3450 static void
3451 handle_transport_receive (void *cls,
3452                           const struct GNUNET_PeerIdentity *peer,
3453                           const struct GNUNET_MessageHeader *message,
3454                           struct GNUNET_TIME_Relative latency,
3455                           unsigned int distance)
3456 {
3457   struct Neighbour *n;
3458   struct GNUNET_TIME_Absolute now;
3459   int up;
3460   uint16_t type;
3461   uint16_t size;
3462
3463 #if DEBUG_CORE
3464   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3465               "Received message of type %u from `%4s', demultiplexing.\n",
3466               (unsigned int) ntohs (message->type), 
3467               GNUNET_i2s (peer));
3468 #endif
3469   if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3470     {
3471       GNUNET_break (0);
3472       return;
3473     }
3474   n = find_neighbour (peer);
3475   if (n == NULL)
3476     n = create_neighbour (peer);
3477   n->last_latency = latency;
3478   n->last_distance = distance;
3479   up = (n->status == PEER_STATE_KEY_CONFIRMED);
3480   type = ntohs (message->type);
3481   size = ntohs (message->size);
3482   switch (type)
3483     {
3484     case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3485       if (size != sizeof (struct SetKeyMessage))
3486         {
3487           GNUNET_break_op (0);
3488           return;
3489         }
3490       GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3491       handle_set_key (n, (const struct SetKeyMessage *) message);
3492       break;
3493     case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3494       if (size < sizeof (struct EncryptedMessage) +
3495           sizeof (struct GNUNET_MessageHeader))
3496         {
3497           GNUNET_break_op (0);
3498           return;
3499         }
3500       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3501           (n->status != PEER_STATE_KEY_CONFIRMED))
3502         {
3503           GNUNET_break_op (0);
3504           return;
3505         }
3506       handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3507       break;
3508     case GNUNET_MESSAGE_TYPE_CORE_PING:
3509       if (size != sizeof (struct PingMessage))
3510         {
3511           GNUNET_break_op (0);
3512           return;
3513         }
3514       GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3515       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3516           (n->status != PEER_STATE_KEY_CONFIRMED))
3517         {
3518 #if DEBUG_CORE
3519           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3520                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3521                       "PING", GNUNET_i2s (&n->peer));
3522 #endif
3523           GNUNET_free_non_null (n->pending_ping);
3524           n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3525           memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3526           return;
3527         }
3528       handle_ping (n, (const struct PingMessage *) message);
3529       break;
3530     case GNUNET_MESSAGE_TYPE_CORE_PONG:
3531       if (size != sizeof (struct PongMessage))
3532         {
3533           GNUNET_break_op (0);
3534           return;
3535         }
3536       GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3537       if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3538            (n->status != PEER_STATE_KEY_CONFIRMED) )
3539         {
3540 #if DEBUG_CORE
3541           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3542                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3543                       "PONG", GNUNET_i2s (&n->peer));
3544 #endif
3545           GNUNET_free_non_null (n->pending_pong);
3546           n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3547           memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3548           return;
3549         }
3550       handle_pong (n, (const struct PongMessage *) message);
3551       break;
3552     default:
3553       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3554                   _("Unsupported message of type %u received.\n"),
3555                   (unsigned int) type);
3556       return;
3557     }
3558   if (n->status == PEER_STATE_KEY_CONFIRMED)
3559     {
3560       now = GNUNET_TIME_absolute_get ();
3561       n->last_activity = now;
3562       if (!up)
3563         {
3564           GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3565           n->time_established = now;
3566         }
3567       if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3568         GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3569       n->keep_alive_task 
3570         = GNUNET_SCHEDULER_add_delayed (sched, 
3571                                         GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3572                                         &send_keep_alive,
3573                                         n);
3574     }
3575 }
3576
3577
3578 /**
3579  * Function that recalculates the bandwidth quota for the
3580  * given neighbour and transmits it to the transport service.
3581  * 
3582  * @param cls neighbour for the quota update
3583  * @param tc context
3584  */
3585 static void
3586 neighbour_quota_update (void *cls,
3587                         const struct GNUNET_SCHEDULER_TaskContext *tc)
3588 {
3589   struct Neighbour *n = cls;
3590   struct GNUNET_BANDWIDTH_Value32NBO q_in;
3591   double pref_rel;
3592   double share;
3593   unsigned long long distributable;
3594   uint64_t need_per_peer;
3595   uint64_t need_per_second;
3596
3597 #if DEBUG_CORE
3598   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3599               "Neighbour quota update calculation running for peer `%4s'\n",
3600               GNUNET_i2s (&n->peer));  
3601 #endif
3602   n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3603   /* calculate relative preference among all neighbours;
3604      divides by a bit more to avoid division by zero AND to
3605      account for possibility of new neighbours joining any time 
3606      AND to convert to double... */
3607   if (preference_sum == 0)
3608     {
3609       pref_rel = 1.0 / (double) neighbour_count;
3610     }
3611   else
3612     {
3613       pref_rel = n->current_preference / preference_sum;
3614     }
3615   need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3616                                                               GNUNET_TIME_UNIT_SECONDS);  
3617   need_per_second = need_per_peer * neighbour_count;
3618   distributable = 0;
3619   if (bandwidth_target_out_bps > need_per_second)
3620     distributable = bandwidth_target_out_bps - need_per_second;
3621   share = distributable * pref_rel;
3622   if (share + need_per_peer > UINT32_MAX)
3623     q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
3624   else
3625     q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3626   /* check if we want to disconnect for good due to inactivity */
3627   if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3628        (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3629     {
3630 #if DEBUG_CORE
3631       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3632                   "Forcing disconnect of `%4s' due to inactivity\n",
3633                   GNUNET_i2s (&n->peer));
3634 #endif
3635       q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3636     }
3637 #if DEBUG_CORE_QUOTA
3638   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3639               "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3640               GNUNET_i2s (&n->peer),
3641               (unsigned int) ntohl (q_in.value__),
3642               bandwidth_target_out_bps,
3643               (unsigned int) ntohl (n->bw_in.value__),
3644               (unsigned int) ntohl (n->bw_out.value__),
3645               (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3646 #endif
3647   if (n->bw_in.value__ != q_in.value__) 
3648     {
3649       n->bw_in = q_in;
3650       if (GNUNET_YES == n->is_connected)
3651         GNUNET_TRANSPORT_set_quota (transport,
3652                                     &n->peer,
3653                                     n->bw_in,
3654                                     n->bw_out,
3655                                     GNUNET_TIME_UNIT_FOREVER_REL,
3656                                     NULL, NULL);
3657     }
3658   schedule_quota_update (n);
3659 }
3660
3661
3662 /**
3663  * Function called by transport to notify us that
3664  * a peer connected to us (on the network level).
3665  *
3666  * @param cls closure
3667  * @param peer the peer that connected
3668  * @param latency current latency of the connection
3669  * @param distance in overlay hops, as given by transport plugin
3670  */
3671 static void
3672 handle_transport_notify_connect (void *cls,
3673                                  const struct GNUNET_PeerIdentity *peer,
3674                                  struct GNUNET_TIME_Relative latency,
3675                                  unsigned int distance)
3676 {
3677   struct Neighbour *n;
3678
3679   if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3680     {
3681       GNUNET_break (0);
3682       return;
3683     }
3684   n = find_neighbour (peer);
3685   if (n != NULL)
3686     {
3687       if (GNUNET_YES == n->is_connected)
3688         {
3689           /* duplicate connect notification!? */
3690           GNUNET_break (0);
3691           return;
3692         }
3693     }
3694   else
3695     {
3696       n = create_neighbour (peer);
3697     }
3698   GNUNET_STATISTICS_update (stats, 
3699                             gettext_noop ("# peers connected (transport)"), 
3700                             1, 
3701                             GNUNET_NO);
3702   n->is_connected = GNUNET_YES;      
3703   n->last_latency = latency;
3704   n->last_distance = distance;
3705   GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3706                                  n->bw_out,
3707                                  MAX_WINDOW_TIME_S);
3708   GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3709                                  n->bw_in,
3710                                  MAX_WINDOW_TIME_S);  
3711 #if DEBUG_CORE
3712   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3713               "Received connection from `%4s'.\n",
3714               GNUNET_i2s (&n->peer));
3715 #endif
3716   GNUNET_TRANSPORT_set_quota (transport,
3717                               &n->peer,
3718                               n->bw_in,
3719                               n->bw_out,
3720                               GNUNET_TIME_UNIT_FOREVER_REL,
3721                               NULL, NULL);
3722   send_key (n); 
3723 }
3724
3725
3726 /**
3727  * Function called by transport telling us that a peer
3728  * disconnected.
3729  *
3730  * @param cls closure
3731  * @param peer the peer that disconnected
3732  */
3733 static void
3734 handle_transport_notify_disconnect (void *cls,
3735                                     const struct GNUNET_PeerIdentity *peer)
3736 {
3737   struct DisconnectNotifyMessage cnm;
3738   struct Neighbour *n;
3739
3740 #if DEBUG_CORE
3741   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3742               "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3743 #endif
3744   n = find_neighbour (peer);
3745   if (n == NULL)
3746     {
3747       GNUNET_break (0);
3748       return;
3749     }
3750   GNUNET_break (n->is_connected);
3751   cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3752   cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3753   cnm.peer = *peer;
3754   send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3755   n->is_connected = GNUNET_NO;
3756   GNUNET_STATISTICS_update (stats, 
3757                             gettext_noop ("# peers connected (transport)"), 
3758                             -1, 
3759                             GNUNET_NO);
3760 }
3761
3762
3763 /**
3764  * Last task run during shutdown.  Disconnects us from
3765  * the transport.
3766  */
3767 static void
3768 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3769 {
3770   struct Neighbour *n;
3771   struct Client *c;
3772
3773 #if DEBUG_CORE
3774   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3775               "Core service shutting down.\n");
3776 #endif
3777   GNUNET_assert (transport != NULL);
3778   GNUNET_TRANSPORT_disconnect (transport);
3779   transport = NULL;
3780   while (NULL != (n = neighbours))
3781     {
3782       neighbours = n->next;
3783       GNUNET_assert (neighbour_count > 0);
3784       neighbour_count--;
3785       free_neighbour (n);
3786     }
3787   GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
3788   GNUNET_SERVER_notification_context_destroy (notifier);
3789   notifier = NULL;
3790   while (NULL != (c = clients))
3791     handle_client_disconnect (NULL, c->client_handle);
3792   if (my_private_key != NULL)
3793     GNUNET_CRYPTO_rsa_key_free (my_private_key);
3794   if (stats != NULL)
3795     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3796   if (peerinfo != NULL)
3797     GNUNET_PEERINFO_disconnect (peerinfo);
3798 }
3799
3800
3801 /**
3802  * Initiate core service.
3803  *
3804  * @param cls closure
3805  * @param s scheduler to use
3806  * @param server the initialized server
3807  * @param c configuration to use
3808  */
3809 static void
3810 run (void *cls,
3811      struct GNUNET_SCHEDULER_Handle *s,
3812      struct GNUNET_SERVER_Handle *server,
3813      const struct GNUNET_CONFIGURATION_Handle *c)
3814 {
3815   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3816     {&handle_client_init, NULL,
3817      GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
3818     {&handle_client_request_info, NULL,
3819      GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
3820      sizeof (struct RequestInfoMessage)},
3821     {&handle_client_send, NULL,
3822      GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
3823     {&handle_client_request_connect, NULL,
3824      GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
3825      sizeof (struct ConnectMessage)},
3826     {NULL, NULL, 0, 0}
3827   };
3828   char *keyfile;
3829
3830   sched = s;
3831   cfg = c;  
3832   /* parse configuration */
3833   if (
3834        (GNUNET_OK !=
3835         GNUNET_CONFIGURATION_get_value_number (c,
3836                                                "CORE",
3837                                                "TOTAL_QUOTA_IN",
3838                                                &bandwidth_target_in_bps)) ||
3839        (GNUNET_OK !=
3840         GNUNET_CONFIGURATION_get_value_number (c,
3841                                                "CORE",
3842                                                "TOTAL_QUOTA_OUT",
3843                                                &bandwidth_target_out_bps)) ||
3844        (GNUNET_OK !=
3845         GNUNET_CONFIGURATION_get_value_filename (c,
3846                                                  "GNUNETD",
3847                                                  "HOSTKEY", &keyfile)))
3848     {
3849       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3850                   _
3851                   ("Core service is lacking key configuration settings.  Exiting.\n"));
3852       GNUNET_SCHEDULER_shutdown (s);
3853       return;
3854     }
3855   peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
3856   if (NULL == peerinfo)
3857     {
3858       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3859                   _("Could not access PEERINFO service.  Exiting.\n"));
3860       GNUNET_SCHEDULER_shutdown (s);
3861       GNUNET_free (keyfile);
3862       return;
3863     }
3864   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3865   GNUNET_free (keyfile);
3866   if (my_private_key == NULL)
3867     {
3868       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3869                   _("Core service could not access hostkey.  Exiting.\n"));
3870       GNUNET_PEERINFO_disconnect (peerinfo);
3871       GNUNET_SCHEDULER_shutdown (s);
3872       return;
3873     }
3874   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3875   GNUNET_CRYPTO_hash (&my_public_key,
3876                       sizeof (my_public_key), &my_identity.hashPubKey);
3877   /* setup notification */
3878   notifier = GNUNET_SERVER_notification_context_create (server, 
3879                                                         MAX_NOTIFY_QUEUE);
3880   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3881   /* setup transport connection */
3882   transport = GNUNET_TRANSPORT_connect (sched,
3883                                         cfg,
3884                                         NULL,
3885                                         &handle_transport_receive,
3886                                         &handle_transport_notify_connect,
3887                                         &handle_transport_notify_disconnect);
3888   GNUNET_assert (NULL != transport);
3889   stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3890   GNUNET_SCHEDULER_add_delayed (sched,
3891                                 GNUNET_TIME_UNIT_FOREVER_REL,
3892                                 &cleaning_task, NULL);
3893   /* process client requests */
3894   GNUNET_SERVER_add_handlers (server, handlers);
3895   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3896               _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3897 }
3898
3899
3900
3901 /**
3902  * The main function for the transport service.
3903  *
3904  * @param argc number of arguments from the command line
3905  * @param argv command line arguments
3906  * @return 0 ok, 1 on error
3907  */
3908 int
3909 main (int argc, char *const *argv)
3910 {
3911   return (GNUNET_OK ==
3912           GNUNET_SERVICE_run (argc,
3913                               argv,
3914                               "core",
3915                               GNUNET_SERVICE_OPTION_NONE,
3916                               &run, NULL)) ? 0 : 1;
3917 }
3918
3919 /* end of gnunet-service-core.c */