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