nodeb
[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   const 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   uint16_t *wtypes;
820   struct Neighbour *n;
821   struct ConnectNotifyMessage cnm;
822   unsigned int i;
823
824 #if DEBUG_CORE_CLIENT
825   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
826               "Client connecting to core service with `%s' message\n",
827               "INIT");
828 #endif
829   /* check that we don't have an entry already */
830   c = clients;
831   while (c != NULL)
832     {
833       if (client == c->client_handle)
834         {
835           GNUNET_break (0);
836           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
837           return;
838         }
839       c = c->next;
840     }
841   msize = ntohs (message->size);
842   if (msize < sizeof (struct InitMessage))
843     {
844       GNUNET_break (0);
845       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
846       return;
847     }
848   GNUNET_SERVER_notification_context_add (notifier, client);
849   im = (const struct InitMessage *) message;
850   types = (const uint16_t *) &im[1];
851   msize -= sizeof (struct InitMessage);
852   c = GNUNET_malloc (sizeof (struct Client) + msize);
853   c->client_handle = client;
854   c->next = clients;
855   clients = c;
856   c->tcnt = msize / sizeof (uint16_t);
857   c->types = (const uint16_t *) &c[1];
858   wtypes = (uint16_t *) &c[1];
859   for (i=0;i<c->tcnt;i++)
860     wtypes[i] = ntohs (types[i]);
861   c->options = ntohl (im->options);
862 #if DEBUG_CORE_CLIENT
863   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
864               "Client %p is interested in %u message types\n",
865               c,
866               c->tcnt);
867 #endif
868   /* send init reply message */
869   irm.header.size = htons (sizeof (struct InitReplyMessage));
870   irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
871   irm.reserved = htonl (0);
872   memcpy (&irm.publicKey,
873           &my_public_key,
874           sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
875 #if DEBUG_CORE_CLIENT
876   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
877               "Sending `%s' message to client.\n", "INIT_REPLY");
878 #endif
879   send_to_client (c, &irm.header, GNUNET_NO);
880   /* notify new client about existing neighbours */
881   cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
882   cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
883   n = neighbours;
884   while (n != NULL)
885     {
886       if (n->status == PEER_STATE_KEY_CONFIRMED)
887         {
888 #if DEBUG_CORE_CLIENT
889           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
890                       "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
891 #endif
892           cnm.distance = htonl (n->last_distance);
893           cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
894           cnm.peer = n->peer;
895           send_to_client (c, &cnm.header, GNUNET_NO);
896         }
897       n = n->next;
898     }
899   GNUNET_SERVER_receive_done (client, GNUNET_OK);
900 }
901
902
903 /**
904  * A client disconnected, clean up.
905  *
906  * @param cls closure
907  * @param client identification of the client
908  */
909 static void
910 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
911 {
912   struct Client *pos;
913   struct Client *prev;
914
915   if (client == NULL)
916     return;
917 #if DEBUG_CORE_CLIENT
918   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
919               "Client %p has disconnected from core service.\n",
920               client);
921 #endif
922   prev = NULL;
923   pos = clients;
924   while (pos != NULL)
925     {
926       if (client == pos->client_handle)
927         {
928           if (prev == NULL)
929             clients = pos->next;
930           else
931             prev->next = pos->next;
932           GNUNET_free (pos);
933           return;
934         }
935       prev = pos;
936       pos = pos->next;
937     }
938   /* client never sent INIT */
939 }
940
941
942 /**
943  * Handle REQUEST_INFO request.
944  */
945 static void
946 handle_client_request_info (void *cls,
947                             struct GNUNET_SERVER_Client *client,
948                             const struct GNUNET_MessageHeader *message)
949 {
950   const struct RequestInfoMessage *rcm;
951   struct Neighbour *n;
952   struct ConfigurationInfoMessage cim;
953   int want_reserv;
954   int got_reserv;
955   unsigned long long old_preference;
956   struct GNUNET_SERVER_TransmitContext *tc;
957
958 #if DEBUG_CORE_CLIENT
959   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
960               "Core service receives `%s' request.\n", "REQUEST_INFO");
961 #endif
962   rcm = (const struct RequestInfoMessage *) message;
963   n = find_neighbour (&rcm->peer);
964   memset (&cim, 0, sizeof (cim));
965   if (n != NULL) 
966     {
967       update_window (GNUNET_YES,
968                      &n->available_send_window,
969                      &n->last_asw_update,
970                      n->bpm_out);
971       n->bpm_out_internal_limit = ntohl (rcm->limit_outbound_bpm);
972       n->bpm_out = GNUNET_MAX (n->bpm_out_internal_limit,
973                                n->bpm_out_external_limit);
974       want_reserv = ntohl (rcm->reserve_inbound);
975       if (want_reserv < 0)
976         {
977           n->available_recv_window += want_reserv;
978         }
979       else if (want_reserv > 0)
980         {
981           update_window (GNUNET_NO,
982                          &n->available_recv_window,
983                          &n->last_arw_update, n->bpm_in);
984           if (n->available_recv_window < want_reserv)
985             got_reserv = 0; /* all or nothing */
986           else
987             got_reserv = want_reserv;
988           n->available_recv_window -= got_reserv;
989         }
990       old_preference = n->current_preference;
991       n->current_preference += GNUNET_ntohll(rcm->preference_change);
992       if (old_preference > n->current_preference) 
993         {
994           /* overflow; cap at maximum value */
995           n->current_preference = (unsigned long long) -1;
996         }
997       update_preference_sum (n->current_preference - old_preference);
998       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
999                   "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1000                   want_reserv,
1001                   GNUNET_i2s (&rcm->peer),
1002                   got_reserv);
1003       cim.reserved_amount = htonl (got_reserv);
1004       cim.bpm_in = htonl (n->bpm_in);
1005       cim.bpm_out = htonl (n->bpm_out);
1006       cim.preference = n->current_preference;
1007     }
1008   cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1009   cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1010   cim.peer = rcm->peer;
1011
1012 #if DEBUG_CORE_CLIENT
1013   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1014               "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1015 #endif
1016   tc = GNUNET_SERVER_transmit_context_create (client);
1017   GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1018   GNUNET_SERVER_transmit_context_run (tc,
1019                                       GNUNET_TIME_UNIT_FOREVER_REL);
1020 }
1021
1022
1023 /**
1024  * Free the given entry for the neighbour (it has
1025  * already been removed from the list at this point).
1026  *
1027  * @param n neighbour to free
1028  */
1029 static void
1030 free_neighbour (struct Neighbour *n)
1031 {
1032   struct MessageEntry *m;
1033
1034   if (n->pitr != NULL)
1035     {
1036       GNUNET_PEERINFO_iterate_cancel (n->pitr);
1037       n->pitr = NULL;
1038     }
1039   if (n->skm != NULL)
1040     {
1041       GNUNET_free (n->skm);
1042       n->skm = NULL;
1043     }
1044   while (NULL != (m = n->messages))
1045     {
1046       n->messages = m->next;
1047       GNUNET_free (m);
1048     }
1049   while (NULL != (m = n->encrypted_head))
1050     {
1051       GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1052                                    n->encrypted_tail,
1053                                    m);
1054       GNUNET_free (m);
1055     }
1056   if (NULL != n->th)
1057     {
1058       GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1059       n->th = NULL;
1060     }
1061   if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1062     GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1063   if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1064     GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1065   if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1066     GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1067   if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1068     GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1069   GNUNET_free_non_null (n->public_key);
1070   GNUNET_free_non_null (n->pending_ping);
1071   GNUNET_free_non_null (n->pending_pong);
1072   GNUNET_free (n);
1073 }
1074
1075
1076 /**
1077  * Consider freeing the given neighbour since we may not need
1078  * to keep it around anymore.
1079  *
1080  * @param n neighbour to consider discarding
1081  */
1082 static void
1083 consider_free_neighbour (struct Neighbour *n);
1084
1085
1086 /**
1087  * Task triggered when a neighbour entry might have gotten stale.
1088  *
1089  * @param cls the 'struct Neighbour'
1090  * @param tc scheduler context (not used)
1091  */
1092 static void
1093 consider_free_task (void *cls,
1094                     const struct GNUNET_SCHEDULER_TaskContext *tc)
1095 {
1096   struct Neighbour *n = cls;
1097   n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1098   consider_free_neighbour (n);
1099 }
1100
1101
1102 /**
1103  * Consider freeing the given neighbour since we may not need
1104  * to keep it around anymore.
1105  *
1106  * @param n neighbour to consider discarding
1107  */
1108 static void
1109 consider_free_neighbour (struct Neighbour *n)
1110
1111   struct Neighbour *pos;
1112   struct Neighbour *prev;
1113   struct GNUNET_TIME_Relative left;
1114
1115   if ( (n->th != NULL) ||
1116        (n->pitr != NULL) ||
1117        (n->status == PEER_STATE_KEY_CONFIRMED) ||
1118        (GNUNET_YES == n->is_connected) )
1119     return; /* no chance */
1120   
1121   left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1122                                                                        MAX_PONG_DELAY));
1123   if (left.value > 0)
1124     {
1125       if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1126         GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1127       n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1128                                                          left,
1129                                                          &consider_free_task,
1130                                                          n);
1131       return;
1132     }
1133   /* actually free the neighbour... */
1134   prev = NULL;
1135   pos = neighbours;
1136   while (pos != n)
1137     {
1138       prev = pos;
1139       pos = pos->next;
1140     }
1141   if (prev == NULL)
1142     neighbours = n->next;
1143   else
1144     prev->next = n->next;
1145   GNUNET_assert (neighbour_count > 0);
1146   neighbour_count--;
1147   free_neighbour (n);
1148 }
1149
1150
1151 /**
1152  * Check if we have encrypted messages for the specified neighbour
1153  * pending, and if so, check with the transport about sending them
1154  * out.
1155  *
1156  * @param n neighbour to check.
1157  */
1158 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1159
1160
1161 /**
1162  * Function called when the transport service is ready to
1163  * receive an encrypted message for the respective peer
1164  *
1165  * @param cls neighbour to use message from
1166  * @param size number of bytes we can transmit
1167  * @param buf where to copy the message
1168  * @return number of bytes transmitted
1169  */
1170 static size_t
1171 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1172 {
1173   struct Neighbour *n = cls;
1174   struct MessageEntry *m;
1175   size_t ret;
1176   char *cbuf;
1177
1178   n->th = NULL;
1179   GNUNET_assert (NULL != (m = n->encrypted_head));
1180   GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1181                                n->encrypted_tail,
1182                                m);
1183   ret = 0;
1184   cbuf = buf;
1185   if (buf != NULL)
1186     {
1187       GNUNET_assert (size >= m->size);
1188       memcpy (cbuf, &m[1], m->size);
1189       ret = m->size;
1190       n->available_send_window -= m->size;
1191       process_encrypted_neighbour_queue (n);
1192
1193 #if DEBUG_CORE
1194       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1195                   "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1196                   ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1197                   ret, GNUNET_i2s (&n->peer));
1198 #endif
1199     }
1200   else
1201     {
1202 #if DEBUG_CORE
1203       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1204                   "Transmission of message of type %u and size %u failed\n",
1205                   ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1206                   m->size);
1207 #endif
1208     }
1209   GNUNET_free (m);
1210   consider_free_neighbour (n);
1211   return ret;
1212 }
1213
1214
1215 /**
1216  * Check if we have plaintext messages for the specified neighbour
1217  * pending, and if so, consider batching and encrypting them (and
1218  * then trigger processing of the encrypted queue if needed).
1219  *
1220  * @param n neighbour to check.
1221  */
1222 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1223
1224
1225 /**
1226  * Check if we have encrypted messages for the specified neighbour
1227  * pending, and if so, check with the transport about sending them
1228  * out.
1229  *
1230  * @param n neighbour to check.
1231  */
1232 static void
1233 process_encrypted_neighbour_queue (struct Neighbour *n)
1234 {
1235   struct MessageEntry *m;
1236  
1237   if (n->th != NULL)
1238     return;  /* request already pending */
1239   m = n->encrypted_head;
1240   if (m == NULL)
1241     {
1242       /* encrypted queue empty, try plaintext instead */
1243       process_plaintext_neighbour_queue (n);
1244       return;
1245     }
1246 #if DEBUG_CORE
1247   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1248               "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1249               m->size,
1250               GNUNET_i2s (&n->peer),
1251               GNUNET_TIME_absolute_get_remaining (m->deadline).
1252               value);
1253 #endif
1254   n->th =
1255     GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1256                                             m->size,
1257                                             m->priority,
1258                                             GNUNET_TIME_absolute_get_remaining
1259                                             (m->deadline),
1260                                             &notify_encrypted_transmit_ready,
1261                                             n);
1262   if (n->th == NULL)
1263     {
1264       /* message request too large or duplicate request */
1265       GNUNET_break (0);
1266       /* discard encrypted message */
1267       GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1268                                    n->encrypted_tail,
1269                                    m);
1270       GNUNET_free (m);
1271       process_encrypted_neighbour_queue (n);
1272     }
1273 }
1274
1275
1276 /**
1277  * Decrypt size bytes from in and write the result to out.  Use the
1278  * key for inbound traffic of the given neighbour.  This function does
1279  * NOT do any integrity-checks on the result.
1280  *
1281  * @param n neighbour we are receiving from
1282  * @param iv initialization vector to use
1283  * @param in ciphertext
1284  * @param out plaintext
1285  * @param size size of in/out
1286  * @return GNUNET_OK on success
1287  */
1288 static int
1289 do_decrypt (struct Neighbour *n,
1290             const GNUNET_HashCode * iv,
1291             const void *in, void *out, size_t size)
1292 {
1293   if (size != (uint16_t) size)
1294     {
1295       GNUNET_break (0);
1296       return GNUNET_NO;
1297     }
1298   if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1299       (n->status != PEER_STATE_KEY_CONFIRMED))
1300     {
1301       GNUNET_break_op (0);
1302       return GNUNET_SYSERR;
1303     }
1304   if (size !=
1305       GNUNET_CRYPTO_aes_decrypt (in,
1306                                  (uint16_t) size,
1307                                  &n->decrypt_key,
1308                                  (const struct
1309                                   GNUNET_CRYPTO_AesInitializationVector *) iv,
1310                                  out))
1311     {
1312       GNUNET_break (0);
1313       return GNUNET_SYSERR;
1314     }
1315 #if DEBUG_CORE
1316   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1317               "Decrypted %u bytes from `%4s' using key %u\n",
1318               size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1319 #endif
1320   return GNUNET_OK;
1321 }
1322
1323
1324 /**
1325  * Encrypt size bytes from in and write the result to out.  Use the
1326  * key for outbound traffic of the given neighbour.
1327  *
1328  * @param n neighbour we are sending to
1329  * @param iv initialization vector to use
1330  * @param in ciphertext
1331  * @param out plaintext
1332  * @param size size of in/out
1333  * @return GNUNET_OK on success
1334  */
1335 static int
1336 do_encrypt (struct Neighbour *n,
1337             const GNUNET_HashCode * iv,
1338             const void *in, void *out, size_t size)
1339 {
1340   if (size != (uint16_t) size)
1341     {
1342       GNUNET_break (0);
1343       return GNUNET_NO;
1344     }
1345   GNUNET_assert (size ==
1346                  GNUNET_CRYPTO_aes_encrypt (in,
1347                                             (uint16_t) size,
1348                                             &n->encrypt_key,
1349                                             (const struct
1350                                              GNUNET_CRYPTO_AesInitializationVector
1351                                              *) iv, out));
1352 #if DEBUG_CORE
1353   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1354               "Encrypted %u bytes for `%4s' using key %u\n", size,
1355               GNUNET_i2s (&n->peer), n->encrypt_key.crc32);
1356 #endif
1357   return GNUNET_OK;
1358 }
1359
1360
1361 /**
1362  * Select messages for transmission.  This heuristic uses a combination
1363  * of earliest deadline first (EDF) scheduling (with bounded horizon)
1364  * and priority-based discard (in case no feasible schedule exist) and
1365  * speculative optimization (defer any kind of transmission until
1366  * we either create a batch of significant size, 25% of max, or until
1367  * we are close to a deadline).  Furthermore, when scheduling the
1368  * heuristic also packs as many messages into the batch as possible,
1369  * starting with those with the earliest deadline.  Yes, this is fun.
1370  *
1371  * @param n neighbour to select messages from
1372  * @param size number of bytes to select for transmission
1373  * @param retry_time set to the time when we should try again
1374  *        (only valid if this function returns zero)
1375  * @return number of bytes selected, or 0 if we decided to
1376  *         defer scheduling overall; in that case, retry_time is set.
1377  */
1378 static size_t
1379 select_messages (struct Neighbour *n,
1380                  size_t size, struct GNUNET_TIME_Relative *retry_time)
1381 {
1382   struct MessageEntry *pos;
1383   struct MessageEntry *min;
1384   struct MessageEntry *last;
1385   unsigned int min_prio;
1386   struct GNUNET_TIME_Absolute t;
1387   struct GNUNET_TIME_Absolute now;
1388   uint64_t delta;
1389   uint64_t avail;
1390   unsigned long long slack;     /* how long could we wait before missing deadlines? */
1391   size_t off;
1392   int discard_low_prio;
1393
1394   GNUNET_assert (NULL != n->messages);
1395   now = GNUNET_TIME_absolute_get ();
1396   /* last entry in linked list of messages processed */
1397   last = NULL;
1398   /* should we remove the entry with the lowest
1399      priority from consideration for scheduling at the
1400      end of the loop? */
1401   discard_low_prio = GNUNET_YES;
1402   while (GNUNET_YES == discard_low_prio)
1403     {
1404       min = NULL;
1405       min_prio = -1;
1406       discard_low_prio = GNUNET_NO;
1407       /* calculate number of bytes available for transmission at time "t" */
1408       update_window (GNUNET_NO,
1409                      &n->available_send_window,
1410                      &n->last_asw_update,
1411                      n->bpm_out);
1412       avail = n->available_send_window;
1413       t = n->last_asw_update;
1414       /* how many bytes have we (hypothetically) scheduled so far */
1415       off = 0;
1416       /* maximum time we can wait before transmitting anything
1417          and still make all of our deadlines */
1418       slack = -1;
1419
1420       pos = n->messages;
1421       /* note that we use "*2" here because we want to look
1422          a bit further into the future; much more makes no
1423          sense since new message might be scheduled in the
1424          meantime... */
1425       while ((pos != NULL) && (off < size * 2))
1426         {
1427           if (pos->do_transmit == GNUNET_YES)
1428             {
1429               /* already removed from consideration */
1430               pos = pos->next;
1431               continue;
1432             }
1433           if (discard_low_prio == GNUNET_NO)
1434             {
1435               delta = pos->deadline.value;
1436               if (delta < t.value)
1437                 delta = 0;
1438               else
1439                 delta = t.value - delta;
1440               avail += delta * n->bpm_out / 1000 / 60;
1441               if (avail < pos->size)
1442                 {
1443                   discard_low_prio = GNUNET_YES;        /* we could not schedule this one! */
1444                 }
1445               else
1446                 {
1447                   avail -= pos->size;
1448                   /* update slack, considering both its absolute deadline
1449                      and relative deadlines caused by other messages
1450                      with their respective load */
1451                   slack = GNUNET_MIN (slack, avail / n->bpm_out);
1452                   if ( (pos->deadline.value < now.value) ||
1453                        (GNUNET_YES == pos->got_slack) )                
1454                     {
1455                       slack = 0;
1456                     }
1457                   else
1458                     {
1459                       slack =
1460                         GNUNET_MIN (slack, pos->deadline.value - now.value);
1461                       pos->got_slack = GNUNET_YES;
1462                     }
1463                 }
1464             }
1465
1466           off += pos->size;
1467           t.value = GNUNET_MAX (pos->deadline.value, t.value);
1468           if (pos->priority <= min_prio)
1469             {
1470               /* update min for discard */
1471               min_prio = pos->priority;
1472               min = pos;
1473             }
1474           pos = pos->next;
1475         }
1476       if (discard_low_prio)
1477         {
1478           GNUNET_assert (min != NULL);
1479           /* remove lowest-priority entry from consideration */
1480           min->do_transmit = GNUNET_YES;        /* means: discard (for now) */
1481         }
1482       last = pos;
1483     }
1484   /* guard against sending "tiny" messages with large headers without
1485      urgent deadlines */
1486   if ( (slack > 1000) && (size > 4 * off) )
1487     {
1488       /* less than 25% of message would be filled with deadlines still
1489          being met if we delay by one second or more; so just wait for
1490          more data; but do not wait longer than 1s (since we don't want
1491          to delay messages for a really long time either). */
1492       retry_time->value = 1000;
1493       /* reset do_transmit values for next time */
1494       while (pos != last)
1495         {
1496           pos->do_transmit = GNUNET_NO;   
1497           pos = pos->next;
1498         }
1499 #if DEBUG_CORE
1500       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1501                   "Deferring transmission for 1s due to underfull message buffer size\n");
1502 #endif
1503       return 0;
1504     }
1505   /* select marked messages (up to size) for transmission */
1506   off = 0;
1507   pos = n->messages;
1508   while (pos != last)
1509     {
1510       if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1511         {
1512           pos->do_transmit = GNUNET_YES;        /* mark for transmission */
1513           off += pos->size;
1514           size -= pos->size;
1515         }
1516       else
1517         pos->do_transmit = GNUNET_NO;   /* mark for not transmitting! */
1518       pos = pos->next;
1519     }
1520 #if DEBUG_CORE
1521   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1522               "Selected %u bytes of plaintext messages for transmission to `%4s'.\n",
1523               off, GNUNET_i2s (&n->peer));
1524 #endif
1525   return off;
1526 }
1527
1528
1529 /**
1530  * Batch multiple messages into a larger buffer.
1531  *
1532  * @param n neighbour to take messages from
1533  * @param buf target buffer
1534  * @param size size of buf
1535  * @param deadline set to transmission deadline for the result
1536  * @param retry_time set to the time when we should try again
1537  *        (only valid if this function returns zero)
1538  * @param priority set to the priority of the batch
1539  * @return number of bytes written to buf (can be zero)
1540  */
1541 static size_t
1542 batch_message (struct Neighbour *n,
1543                char *buf,
1544                size_t size,
1545                struct GNUNET_TIME_Absolute *deadline,
1546                struct GNUNET_TIME_Relative *retry_time,
1547                unsigned int *priority)
1548 {
1549   char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1550   struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1551   struct MessageEntry *pos;
1552   struct MessageEntry *prev;
1553   struct MessageEntry *next;
1554   size_t ret;
1555   
1556   ret = 0;
1557   *priority = 0;
1558   *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1559   *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1560   if (0 == select_messages (n, size, retry_time))
1561     {
1562       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1563                   "No messages selected, will try again in %llu ms\n",
1564                   retry_time->value);
1565       return 0;
1566     }
1567   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1568   ntm->distance = htonl (n->last_distance);
1569   ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1570   ntm->peer = n->peer;
1571   
1572   pos = n->messages;
1573   prev = NULL;
1574   while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1575     {
1576       next = pos->next;
1577       if (GNUNET_YES == pos->do_transmit)
1578         {
1579           GNUNET_assert (pos->size <= size);
1580           /* do notifications */
1581           /* FIXME: track if we have *any* client that wants
1582              full notifications and only do this if that is
1583              actually true */
1584           if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1585             {
1586               memcpy (&ntm[1], &pos[1], pos->size);
1587               ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) + 
1588                                         sizeof (struct GNUNET_MessageHeader));
1589               send_to_all_clients (&ntm->header,
1590                                    GNUNET_YES,
1591                                    GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1592             }
1593           else
1594             {
1595               /* message too large for 'full' notifications, we do at
1596                  least the 'hdr' type */
1597               memcpy (&ntm[1],
1598                       &pos[1],
1599                       sizeof (struct GNUNET_MessageHeader));
1600             }
1601           ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) + 
1602                                     pos->size);
1603           send_to_all_clients (&ntm->header,
1604                                GNUNET_YES,
1605                                GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);   
1606 #if DEBUG_HANDSHAKE
1607           fprintf (stderr,
1608                    "Encrypting message of type %u\n",
1609                    ntohs(((struct GNUNET_MessageHeader*)&pos[1])->type));
1610 #endif
1611           /* copy for encrypted transmission */
1612           memcpy (&buf[ret], &pos[1], pos->size);
1613           ret += pos->size;
1614           size -= pos->size;
1615           *priority += pos->priority;
1616 #if DEBUG_CORE
1617           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1618                       "Adding plaintext message with deadline %llu ms to batch\n",
1619                       GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1620 #endif
1621           deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1622           GNUNET_free (pos);
1623           if (prev == NULL)
1624             n->messages = next;
1625           else
1626             prev->next = next;
1627         }
1628       else
1629         {
1630           prev = pos;
1631         }
1632       pos = next;
1633     }
1634 #if DEBUG_CORE
1635   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1636               "Deadline for message batch is %llu ms\n",
1637               GNUNET_TIME_absolute_get_remaining (*deadline).value);
1638 #endif
1639   return ret;
1640 }
1641
1642
1643 /**
1644  * Remove messages with deadlines that have long expired from
1645  * the queue.
1646  *
1647  * @param n neighbour to inspect
1648  */
1649 static void
1650 discard_expired_messages (struct Neighbour *n)
1651 {
1652   struct MessageEntry *prev;
1653   struct MessageEntry *next;
1654   struct MessageEntry *pos;
1655   struct GNUNET_TIME_Absolute now;
1656   struct GNUNET_TIME_Relative delta;
1657
1658   now = GNUNET_TIME_absolute_get ();
1659   prev = NULL;
1660   pos = n->messages;
1661   while (pos != NULL) 
1662     {
1663       next = pos->next;
1664       delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1665       if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1666         {
1667 #if DEBUG_CORE
1668           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1669                       "Message is %llu ms past due, discarding.\n",
1670                       delta.value);
1671 #endif
1672           if (prev == NULL)
1673             n->messages = next;
1674           else
1675             prev->next = next;
1676           GNUNET_free (pos);
1677         }
1678       else
1679         prev = pos;
1680       pos = next;
1681     }
1682 }
1683
1684
1685 /**
1686  * Signature of the main function of a task.
1687  *
1688  * @param cls closure
1689  * @param tc context information (why was this task triggered now)
1690  */
1691 static void
1692 retry_plaintext_processing (void *cls,
1693                             const struct GNUNET_SCHEDULER_TaskContext *tc)
1694 {
1695   struct Neighbour *n = cls;
1696
1697   n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1698   process_plaintext_neighbour_queue (n);
1699 }
1700
1701
1702 /**
1703  * Send our key (and encrypted PING) to the other peer.
1704  *
1705  * @param n the other peer
1706  */
1707 static void send_key (struct Neighbour *n);
1708
1709 /**
1710  * Task that will retry "send_key" if our previous attempt failed
1711  * to yield a PONG.
1712  */
1713 static void
1714 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1715 {
1716   struct Neighbour *n = cls;
1717
1718   n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1719   n->set_key_retry_frequency =
1720     GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1721   send_key (n);
1722 }
1723
1724
1725 /**
1726  * Check if we have plaintext messages for the specified neighbour
1727  * pending, and if so, consider batching and encrypting them (and
1728  * then trigger processing of the encrypted queue if needed).
1729  *
1730  * @param n neighbour to check.
1731  */
1732 static void
1733 process_plaintext_neighbour_queue (struct Neighbour *n)
1734 {
1735   char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE];        /* plaintext */
1736   size_t used;
1737   size_t esize;
1738   struct EncryptedMessage *em;  /* encrypted message */
1739   struct EncryptedMessage *ph;  /* plaintext header */
1740   struct MessageEntry *me;
1741   unsigned int priority;
1742   struct GNUNET_TIME_Absolute deadline;
1743   struct GNUNET_TIME_Relative retry_time;
1744   GNUNET_HashCode iv;
1745
1746   if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1747     {
1748       GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1749       n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1750     }
1751   switch (n->status)
1752     {
1753     case PEER_STATE_DOWN:
1754       send_key (n);
1755 #if DEBUG_CORE
1756       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1757                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1758                   GNUNET_i2s(&n->peer));
1759 #endif
1760       return;
1761     case PEER_STATE_KEY_SENT:
1762       if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1763         n->retry_set_key_task
1764           = GNUNET_SCHEDULER_add_delayed (sched,
1765                                           n->set_key_retry_frequency,
1766                                           &set_key_retry_task, n);    
1767 #if DEBUG_CORE
1768       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1769                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1770                   GNUNET_i2s(&n->peer));
1771 #endif
1772       return;
1773     case PEER_STATE_KEY_RECEIVED:
1774       if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)        
1775         n->retry_set_key_task
1776           = GNUNET_SCHEDULER_add_delayed (sched,
1777                                           n->set_key_retry_frequency,
1778                                           &set_key_retry_task, n);        
1779 #if DEBUG_CORE
1780       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1781                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1782                   GNUNET_i2s(&n->peer));
1783 #endif
1784       return;
1785     case PEER_STATE_KEY_CONFIRMED:
1786       /* ready to continue */
1787       break;
1788     }
1789   discard_expired_messages (n);
1790   if (n->messages == NULL)
1791     {
1792 #if DEBUG_CORE
1793       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1794                   "Plaintext message queue for `%4s' is empty.\n",
1795                   GNUNET_i2s(&n->peer));
1796 #endif
1797       return;                   /* no pending messages */
1798     }
1799   if (n->encrypted_head != NULL)
1800     {
1801 #if DEBUG_CORE
1802       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1803                   "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1804                   GNUNET_i2s(&n->peer));
1805 #endif
1806       return;                   /* wait for messages already encrypted to be
1807                                    processed first! */
1808     }
1809   ph = (struct EncryptedMessage *) pbuf;
1810   deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1811   priority = 0;
1812   used = sizeof (struct EncryptedMessage);
1813   used += batch_message (n,
1814                          &pbuf[used],
1815                          MAX_ENCRYPTED_MESSAGE_SIZE - used,
1816                          &deadline, &retry_time, &priority);
1817   if (used == sizeof (struct EncryptedMessage))
1818     {
1819 #if DEBUG_CORE
1820       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1821                   "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1822                   GNUNET_i2s(&n->peer));
1823 #endif
1824       /* no messages selected for sending, try again later... */
1825       n->retry_plaintext_task =
1826         GNUNET_SCHEDULER_add_delayed (sched,
1827                                       retry_time,
1828                                       &retry_plaintext_processing, n);
1829       return;
1830     }
1831   ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1));
1832   ph->sequence_number = htonl (++n->last_sequence_number_sent);
1833   ph->inbound_bpm_limit = htonl (n->bpm_in);
1834   ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1835
1836   /* setup encryption message header */
1837   me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1838   me->deadline = deadline;
1839   me->priority = priority;
1840   me->size = used;
1841   em = (struct EncryptedMessage *) &me[1];
1842   em->header.size = htons (used);
1843   em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1844   em->iv_seed = ph->iv_seed;
1845   esize = used - ENCRYPTED_HEADER_SIZE;
1846   GNUNET_CRYPTO_hash (&ph->sequence_number,
1847                       esize - sizeof (GNUNET_HashCode), 
1848                       &ph->plaintext_hash);
1849   GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
1850   /* encrypt */
1851 #if DEBUG_CORE
1852   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1853               "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
1854               esize,
1855               GNUNET_i2s(&n->peer),
1856               (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
1857 #endif
1858   GNUNET_assert (GNUNET_OK ==
1859                  do_encrypt (n,
1860                              &iv,
1861                              &ph->plaintext_hash,
1862                              &em->plaintext_hash, esize));
1863   /* append to transmission list */
1864   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1865                                      n->encrypted_tail,
1866                                      n->encrypted_tail,
1867                                      me);
1868   process_encrypted_neighbour_queue (n);
1869 }
1870
1871
1872 /**
1873  * Function that recalculates the bandwidth quota for the
1874  * given neighbour and transmits it to the transport service.
1875  * 
1876  * @param cls neighbour for the quota update
1877  * @param tc context
1878  */
1879 static void
1880 neighbour_quota_update (void *cls,
1881                         const struct GNUNET_SCHEDULER_TaskContext *tc);
1882
1883
1884 /**
1885  * Schedule the task that will recalculate the bandwidth
1886  * quota for this peer (and possibly force a disconnect of
1887  * idle peers by calculating a bandwidth of zero).
1888  */
1889 static void
1890 schedule_quota_update (struct Neighbour *n)
1891 {
1892   GNUNET_assert (n->quota_update_task ==
1893                  GNUNET_SCHEDULER_NO_TASK);
1894   n->quota_update_task
1895     = GNUNET_SCHEDULER_add_delayed (sched,
1896                                     QUOTA_UPDATE_FREQUENCY,
1897                                     &neighbour_quota_update,
1898                                     n);
1899 }
1900
1901
1902 /**
1903  * Initialize a new 'struct Neighbour'.
1904  *
1905  * @param pid ID of the new neighbour
1906  * @return handle for the new neighbour
1907  */
1908 static struct Neighbour *
1909 create_neighbour (const struct GNUNET_PeerIdentity *pid)
1910 {
1911   struct Neighbour *n;
1912   struct GNUNET_TIME_Absolute now;
1913
1914   n = GNUNET_malloc (sizeof (struct Neighbour));
1915   n->next = neighbours;
1916   neighbours = n;
1917   neighbour_count++;
1918   n->peer = *pid;
1919   GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
1920   now = GNUNET_TIME_absolute_get ();
1921   n->encrypt_key_created = now;
1922   n->last_activity = now;
1923   n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
1924   n->bpm_in = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
1925   n->bpm_out = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
1926   n->bpm_out_internal_limit = (uint32_t) - 1;
1927   n->bpm_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
1928   n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1929                                                 (uint32_t) - 1);
1930   schedule_quota_update (n);
1931   return n;
1932 }
1933
1934
1935
1936
1937
1938 /**
1939  * Handle CORE_SEND request.
1940  *
1941  * @param cls unused
1942  * @param client the client issuing the request
1943  * @param message the "struct SendMessage"
1944  */
1945 static void
1946 handle_client_send (void *cls,
1947                     struct GNUNET_SERVER_Client *client,
1948                     const struct GNUNET_MessageHeader *message)
1949 {
1950   const struct SendMessage *sm;
1951   const struct GNUNET_MessageHeader *mh;
1952   struct Neighbour *n;
1953   struct MessageEntry *prev;
1954   struct MessageEntry *pos;
1955   struct MessageEntry *e; 
1956   struct MessageEntry *min_prio_entry;
1957   struct MessageEntry *min_prio_prev;
1958   unsigned int min_prio;
1959   unsigned int queue_size;
1960   uint16_t msize;
1961
1962   msize = ntohs (message->size);
1963   if (msize <
1964       sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
1965     {
1966       GNUNET_break (0);
1967       if (client != NULL)
1968         GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1969       return;
1970     }
1971   sm = (const struct SendMessage *) message;
1972   msize -= sizeof (struct SendMessage);
1973   mh = (const struct GNUNET_MessageHeader *) &sm[1];
1974   if (msize != ntohs (mh->size))
1975     {
1976       GNUNET_break (0);
1977       if (client != NULL)
1978         GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1979       return;
1980     }
1981   n = find_neighbour (&sm->peer);
1982   if (n == NULL)
1983     n = create_neighbour (&sm->peer);
1984 #if DEBUG_CORE
1985   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1986               "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
1987               "SEND",
1988               msize, 
1989               GNUNET_i2s (&sm->peer));
1990 #endif
1991   /* bound queue size */
1992   discard_expired_messages (n);
1993   min_prio = (unsigned int) -1;
1994   min_prio_entry = NULL;
1995   min_prio_prev = NULL;
1996   queue_size = 0;
1997   prev = NULL;
1998   pos = n->messages;
1999   while (pos != NULL) 
2000     {
2001       if (pos->priority < min_prio)
2002         {
2003           min_prio_entry = pos;
2004           min_prio_prev = prev;
2005           min_prio = pos->priority;
2006         }
2007       queue_size++;
2008       prev = pos;
2009       pos = pos->next;
2010     }
2011   if (queue_size >= MAX_PEER_QUEUE_SIZE)
2012     {
2013       /* queue full */
2014       if (ntohl(sm->priority) <= min_prio)
2015         {
2016           /* discard new entry */
2017 #if DEBUG_CORE
2018           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2019                       "Queue full, discarding new request\n");
2020 #endif
2021           if (client != NULL)
2022             GNUNET_SERVER_receive_done (client, GNUNET_OK);
2023           return;
2024         }
2025       /* discard "min_prio_entry" */
2026 #if DEBUG_CORE
2027       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2028                   "Queue full, discarding existing older request\n");
2029 #endif
2030       if (min_prio_prev == NULL)
2031         n->messages = min_prio_entry->next;
2032       else
2033         min_prio_prev->next = min_prio_entry->next;      
2034       GNUNET_free (min_prio_entry);     
2035     }
2036
2037 #if DEBUG_CORE
2038   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2039               "Adding transmission request for `%4s' to queue\n",
2040               GNUNET_i2s (&sm->peer));
2041 #endif  
2042   e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2043   e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2044   e->priority = ntohl (sm->priority);
2045   e->size = msize;
2046   memcpy (&e[1], mh, msize);
2047
2048   /* insert, keep list sorted by deadline */
2049   prev = NULL;
2050   pos = n->messages;
2051   while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2052     {
2053       prev = pos;
2054       pos = pos->next;
2055     }
2056   if (prev == NULL)
2057     n->messages = e;
2058   else
2059     prev->next = e;
2060   e->next = pos;
2061
2062   /* consider scheduling now */
2063   process_plaintext_neighbour_queue (n);
2064   if (client != NULL)
2065     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2066 }
2067
2068
2069 /**
2070  * Function called when the transport service is ready to
2071  * receive a message.  Only resets 'n->th' to NULL.
2072  *
2073  * @param cls neighbour to use message from
2074  * @param size number of bytes we can transmit
2075  * @param buf where to copy the message
2076  * @return number of bytes transmitted
2077  */
2078 static size_t
2079 notify_transport_connect_done (void *cls, size_t size, void *buf)
2080 {
2081   struct Neighbour *n = cls;
2082   n->th = NULL;
2083   send_key (n);
2084   return 0;
2085 }
2086
2087
2088 /**
2089  * Handle CORE_REQUEST_CONNECT request.
2090  *
2091  * @param cls unused
2092  * @param client the client issuing the request
2093  * @param message the "struct ConnectMessage"
2094  */
2095 static void
2096 handle_client_request_connect (void *cls,
2097                                struct GNUNET_SERVER_Client *client,
2098                                const struct GNUNET_MessageHeader *message)
2099 {
2100   const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2101   struct Neighbour *n;
2102   struct GNUNET_TIME_Relative timeout;
2103
2104   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2105   n = find_neighbour (&cm->peer);
2106   if (n == NULL)
2107     n = create_neighbour (&cm->peer);
2108   if ( (n->is_connected) ||
2109        (n->th != NULL) )
2110     return; /* already connected, or at least trying */
2111 #if DEBUG_CORE
2112   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2113               "Core received `%s' request for `%4s', will try to establish connection\n",
2114               "REQUEST_CONNECT",
2115               GNUNET_i2s (&cm->peer));
2116 #endif
2117   timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2118   /* ask transport to connect to the peer */
2119   n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2120                                                   &cm->peer,
2121                                                   sizeof (struct GNUNET_MessageHeader), 0,
2122                                                   timeout,
2123                                                   &notify_transport_connect_done,
2124                                                   n);
2125   GNUNET_break (NULL != n->th);
2126 }
2127
2128
2129 /**
2130  * List of handlers for the messages understood by this
2131  * service.
2132  */
2133 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2134   {&handle_client_init, NULL,
2135    GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2136   {&handle_client_request_info, NULL,
2137    GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2138    sizeof (struct RequestInfoMessage)},
2139   {&handle_client_send, NULL,
2140    GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2141   {&handle_client_request_connect, NULL,
2142    GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2143    sizeof (struct ConnectMessage)},
2144   {NULL, NULL, 0, 0}
2145 };
2146
2147
2148 /**
2149  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
2150  * the neighbour's struct and retry send_key.  Or, if we did not get a
2151  * HELLO, just do nothing.
2152  *
2153  * @param cls the 'struct Neighbour' to retry sending the key for
2154  * @param peer the peer for which this is the HELLO
2155  * @param hello HELLO message of that peer
2156  * @param trust amount of trust we currently have in that peer
2157  */
2158 static void
2159 process_hello_retry_send_key (void *cls,
2160                               const struct GNUNET_PeerIdentity *peer,
2161                               const struct GNUNET_HELLO_Message *hello,
2162                               uint32_t trust)
2163 {
2164   struct Neighbour *n = cls;
2165
2166   if (peer == NULL)
2167     {
2168 #if DEBUG_CORE
2169       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2170                   "Entered `process_hello_retry_send_key' and `peer' is NULL!\n");
2171 #endif
2172       n->pitr = NULL;
2173       if (n->public_key != NULL)
2174         {
2175           send_key (n);
2176         }
2177       else
2178         {
2179           if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2180             n->retry_set_key_task
2181               = GNUNET_SCHEDULER_add_delayed (sched,
2182                                               n->set_key_retry_frequency,
2183                                               &set_key_retry_task, n);
2184         }
2185       return;
2186     }
2187
2188 #if DEBUG_CORE
2189   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2190               "Entered `process_hello_retry_send_key' for peer `%4s'\n",
2191               GNUNET_i2s (peer));
2192 #endif
2193   if (n->public_key != NULL)
2194     {
2195 #if DEBUG_CORE
2196       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2197               "already have public key for peer %s!! (so why are we here?)\n",
2198               GNUNET_i2s (peer));
2199 #endif
2200       return;
2201     }
2202
2203 #if DEBUG_CORE
2204   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2205               "Received new `%s' message for `%4s', initiating key exchange.\n",
2206               "HELLO",
2207               GNUNET_i2s (peer));
2208 #endif
2209   n->public_key =
2210     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2211   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2212     {
2213       GNUNET_free (n->public_key);
2214       n->public_key = NULL;
2215 #if DEBUG_CORE
2216   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2217               "GNUNET_HELLO_get_key returned awfully\n");
2218 #endif
2219       return;
2220     }
2221 }
2222
2223
2224 /**
2225  * Send our key (and encrypted PING) to the other peer.
2226  *
2227  * @param n the other peer
2228  */
2229 static void
2230 send_key (struct Neighbour *n)
2231 {
2232   struct SetKeyMessage *sm;
2233   struct MessageEntry *me;
2234   struct PingMessage pp;
2235   struct PingMessage *pm;
2236
2237   if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2238        (n->pitr != NULL) )
2239     {
2240 #if DEBUG_CORE
2241       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2242                   "Key exchange in progress with `%4s'.\n",
2243                   GNUNET_i2s (&n->peer));
2244 #endif
2245       return; /* already in progress */
2246     }
2247
2248 #if DEBUG_CORE
2249   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2250               "Asked to perform key exchange with `%4s'.\n",
2251               GNUNET_i2s (&n->peer));
2252 #endif
2253   if (n->public_key == NULL)
2254     {
2255       /* lookup n's public key, then try again */
2256 #if DEBUG_CORE
2257       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2258                   "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2259                   GNUNET_i2s (&n->peer));
2260 #endif
2261       GNUNET_assert (n->pitr == NULL);
2262       n->pitr = GNUNET_PEERINFO_iterate (cfg,
2263                                          sched,
2264                                          &n->peer,
2265                                          0,
2266                                          GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2267                                          &process_hello_retry_send_key, n);
2268       return;
2269     }
2270   /* first, set key message */
2271   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2272                       sizeof (struct SetKeyMessage));
2273   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2274   me->priority = SET_KEY_PRIORITY;
2275   me->size = sizeof (struct SetKeyMessage);
2276   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2277                                      n->encrypted_tail,
2278                                      n->encrypted_tail,
2279                                      me);
2280   sm = (struct SetKeyMessage *) &me[1];
2281   sm->header.size = htons (sizeof (struct SetKeyMessage));
2282   sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2283   sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2284                                         PEER_STATE_KEY_SENT : n->status));
2285   sm->purpose.size =
2286     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2287            sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2288            sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2289            sizeof (struct GNUNET_PeerIdentity));
2290   sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2291   sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2292   sm->target = n->peer;
2293   GNUNET_assert (GNUNET_OK ==
2294                  GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2295                                             sizeof (struct
2296                                                     GNUNET_CRYPTO_AesSessionKey),
2297                                             n->public_key,
2298                                             &sm->encrypted_key));
2299   GNUNET_assert (GNUNET_OK ==
2300                  GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2301                                          &sm->signature));
2302
2303   /* second, encrypted PING message */
2304   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2305                       sizeof (struct PingMessage));
2306   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2307   me->priority = PING_PRIORITY;
2308   me->size = sizeof (struct PingMessage);
2309   n->encrypted_tail->next = me;
2310   n->encrypted_tail = me;
2311   pm = (struct PingMessage *) &me[1];
2312   pm->header.size = htons (sizeof (struct PingMessage));
2313   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2314   pp.challenge = htonl (n->ping_challenge);
2315   pp.target = n->peer;
2316 #if DEBUG_CORE
2317   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2318               "Encrypting `%s' and `%s' messages for `%4s'.\n",
2319               "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2320   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2321               "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2322               "PING",
2323               GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2324 #endif
2325   do_encrypt (n,
2326               &n->peer.hashPubKey,
2327               &pp.challenge,
2328               &pm->challenge,
2329               sizeof (struct PingMessage) -
2330               sizeof (struct GNUNET_MessageHeader));
2331   /* update status */
2332   switch (n->status)
2333     {
2334     case PEER_STATE_DOWN:
2335       n->status = PEER_STATE_KEY_SENT;
2336       break;
2337     case PEER_STATE_KEY_SENT:
2338       break;
2339     case PEER_STATE_KEY_RECEIVED:
2340       break;
2341     case PEER_STATE_KEY_CONFIRMED:
2342       break;
2343     default:
2344       GNUNET_break (0);
2345       break;
2346     }
2347 #if DEBUG_CORE
2348   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2349               "Have %llu ms left for `%s' transmission.\n",
2350               (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2351               "SET_KEY");
2352 #endif
2353   /* trigger queue processing */
2354   process_encrypted_neighbour_queue (n);
2355   if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2356        (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2357     n->retry_set_key_task
2358       = GNUNET_SCHEDULER_add_delayed (sched,
2359                                       n->set_key_retry_frequency,
2360                                       &set_key_retry_task, n);    
2361 }
2362
2363
2364 /**
2365  * We received a SET_KEY message.  Validate and update
2366  * our key material and status.
2367  *
2368  * @param n the neighbour from which we received message m
2369  * @param m the set key message we received
2370  */
2371 static void
2372 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2373
2374
2375 /**
2376  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
2377  * the neighbour's struct and retry handling the set_key message.  Or,
2378  * if we did not get a HELLO, just free the set key message.
2379  *
2380  * @param cls pointer to the set key message
2381  * @param peer the peer for which this is the HELLO
2382  * @param hello HELLO message of that peer
2383  * @param trust amount of trust we currently have in that peer
2384  */
2385 static void
2386 process_hello_retry_handle_set_key (void *cls,
2387                                     const struct GNUNET_PeerIdentity *peer,
2388                                     const struct GNUNET_HELLO_Message *hello,
2389                                     uint32_t trust)
2390 {
2391   struct Neighbour *n = cls;
2392   struct SetKeyMessage *sm = n->skm;
2393
2394   if (peer == NULL)
2395     {
2396       GNUNET_free (sm);
2397       n->skm = NULL;
2398       n->pitr = NULL;
2399       return;
2400     }
2401   if (n->public_key != NULL)
2402     return;                     /* multiple HELLOs match!? */
2403   n->public_key =
2404     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2405   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2406     {
2407       GNUNET_break_op (0);
2408       GNUNET_free (n->public_key);
2409       n->public_key = NULL;
2410       return;
2411     }
2412 #if DEBUG_CORE
2413   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2414               "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2415               "HELLO", GNUNET_i2s (peer), "SET_KEY");
2416 #endif
2417   handle_set_key (n, sm);
2418 }
2419
2420
2421 /**
2422  * We received a PING message.  Validate and transmit
2423  * PONG.
2424  *
2425  * @param n sender of the PING
2426  * @param m the encrypted PING message itself
2427  */
2428 static void
2429 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2430 {
2431   struct PingMessage t;
2432   struct PingMessage *tp;
2433   struct MessageEntry *me;
2434
2435 #if DEBUG_CORE
2436   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2437               "Core service receives `%s' request from `%4s'.\n",
2438               "PING", GNUNET_i2s (&n->peer));
2439 #endif
2440   if (GNUNET_OK !=
2441       do_decrypt (n,
2442                   &my_identity.hashPubKey,
2443                   &m->challenge,
2444                   &t.challenge,
2445                   sizeof (struct PingMessage) -
2446                   sizeof (struct GNUNET_MessageHeader)))
2447     return;
2448 #if DEBUG_CORE
2449   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2450               "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2451               "PING",
2452               GNUNET_i2s (&t.target),
2453               ntohl (t.challenge), n->decrypt_key.crc32);
2454   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2455               "Target of `%s' request is `%4s'.\n",
2456               "PING", GNUNET_i2s (&t.target));
2457 #endif
2458   if (0 != memcmp (&t.target,
2459                    &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2460     {
2461       GNUNET_break_op (0);
2462       return;
2463     }
2464   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2465                       sizeof (struct PingMessage));
2466   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2467                                      n->encrypted_tail,
2468                                      n->encrypted_tail,
2469                                      me);
2470   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2471   me->priority = PONG_PRIORITY;
2472   me->size = sizeof (struct PingMessage);
2473   tp = (struct PingMessage *) &me[1];
2474   tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2475   tp->header.size = htons (sizeof (struct PingMessage));
2476   do_encrypt (n,
2477               &my_identity.hashPubKey,
2478               &t.challenge,
2479               &tp->challenge,
2480               sizeof (struct PingMessage) -
2481               sizeof (struct GNUNET_MessageHeader));
2482 #if DEBUG_CORE
2483   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2484               "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2485               ntohl (t.challenge), n->encrypt_key.crc32);
2486 #endif
2487   /* trigger queue processing */
2488   process_encrypted_neighbour_queue (n);
2489 }
2490
2491
2492 /**
2493  * We received a PONG message.  Validate and update our status.
2494  *
2495  * @param n sender of the PONG
2496  * @param m the encrypted PONG message itself
2497  */
2498 static void
2499 handle_pong (struct Neighbour *n, const struct PingMessage *m)
2500 {
2501   struct PingMessage t;
2502   struct ConnectNotifyMessage cnm;
2503
2504 #if DEBUG_CORE
2505   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2506               "Core service receives `%s' request from `%4s'.\n",
2507               "PONG", GNUNET_i2s (&n->peer));
2508 #endif
2509   if (GNUNET_OK !=
2510       do_decrypt (n,
2511                   &n->peer.hashPubKey,
2512                   &m->challenge,
2513                   &t.challenge,
2514                   sizeof (struct PingMessage) -
2515                   sizeof (struct GNUNET_MessageHeader)))
2516     return;
2517 #if DEBUG_CORE
2518   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2519               "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2520               "PONG",
2521               GNUNET_i2s (&t.target),
2522               ntohl (t.challenge), n->decrypt_key.crc32);
2523 #endif
2524   if ((0 != memcmp (&t.target,
2525                     &n->peer,
2526                     sizeof (struct GNUNET_PeerIdentity))) ||
2527       (n->ping_challenge != ntohl (t.challenge)))
2528     {
2529       /* PONG malformed */
2530 #if DEBUG_CORE
2531       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2532                   "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2533                   "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2534       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2535                   "Received malformed `%s' received from `%4s' with challenge %u\n",
2536                   "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2537 #endif
2538       GNUNET_break_op (0);
2539       return;
2540     }
2541   switch (n->status)
2542     {
2543     case PEER_STATE_DOWN:
2544       GNUNET_break (0);         /* should be impossible */
2545       return;
2546     case PEER_STATE_KEY_SENT:
2547       GNUNET_break (0);         /* should be impossible, how did we decrypt? */
2548       return;
2549     case PEER_STATE_KEY_RECEIVED:
2550       n->status = PEER_STATE_KEY_CONFIRMED;
2551 #if DEBUG_CORE
2552       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2553                   "Confirmed key via `%s' message for peer `%4s'\n",
2554                   "PONG", GNUNET_i2s (&n->peer));
2555 #endif
2556       if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2557         {
2558           GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2559           n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2560         }      
2561       cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2562       cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2563       cnm.distance = htonl (n->last_distance);
2564       cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2565       cnm.peer = n->peer;
2566       send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2567       process_encrypted_neighbour_queue (n);
2568       break;
2569     case PEER_STATE_KEY_CONFIRMED:
2570       /* duplicate PONG? */
2571       break;
2572     default:
2573       GNUNET_break (0);
2574       break;
2575     }
2576 }
2577
2578
2579 /**
2580  * We received a SET_KEY message.  Validate and update
2581  * our key material and status.
2582  *
2583  * @param n the neighbour from which we received message m
2584  * @param m the set key message we received
2585  */
2586 static void
2587 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2588 {
2589   struct SetKeyMessage *m_cpy;
2590   struct GNUNET_TIME_Absolute t;
2591   struct GNUNET_CRYPTO_AesSessionKey k;
2592   struct PingMessage *ping;
2593   struct PingMessage *pong;
2594   enum PeerStateMachine sender_status;
2595
2596 #if DEBUG_CORE
2597   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2598               "Core service receives `%s' request from `%4s'.\n",
2599               "SET_KEY", GNUNET_i2s (&n->peer));
2600 #endif
2601   if (n->public_key == NULL)
2602     {
2603       if (n->pitr != NULL)
2604         {
2605 #if DEBUG_CORE
2606           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2607                       "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2608                       "SET_KEY");
2609 #endif
2610           return;
2611         }
2612 #if DEBUG_CORE
2613       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2614                   "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2615 #endif
2616       m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2617       memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2618       /* lookup n's public key, then try again */
2619       GNUNET_assert (n->skm == NULL);
2620       n->skm = m_cpy;
2621       n->pitr = GNUNET_PEERINFO_iterate (cfg,
2622                                          sched,
2623                                          &n->peer,
2624                                          0,
2625                                          GNUNET_TIME_UNIT_MINUTES,
2626                                          &process_hello_retry_handle_set_key, n);
2627       return;
2628     }
2629   if (0 != memcmp (&m->target,
2630                    &my_identity,
2631                    sizeof (struct GNUNET_PeerIdentity)))
2632     {
2633       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2634                   _("Received `%s' message that was not for me.  Ignoring.\n"),
2635                   "SET_KEY");
2636       return;
2637     }
2638   if ((ntohl (m->purpose.size) !=
2639        sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2640        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2641        sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2642        sizeof (struct GNUNET_PeerIdentity)) ||
2643       (GNUNET_OK !=
2644        GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2645                                  &m->purpose, &m->signature, n->public_key)))
2646     {
2647       /* invalid signature */
2648       GNUNET_break_op (0);
2649       return;
2650     }
2651   t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2652   if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2653        (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2654       (t.value < n->decrypt_key_created.value))
2655     {
2656       /* this could rarely happen due to massive re-ordering of
2657          messages on the network level, but is most likely either
2658          a bug or some adversary messing with us.  Report. */
2659       GNUNET_break_op (0);
2660       return;
2661     }
2662 #if DEBUG_CORE
2663   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
2664 #endif  
2665   if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2666                                   &m->encrypted_key,
2667                                   &k,
2668                                   sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2669        != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2670       (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2671     {
2672       /* failed to decrypt !? */
2673       GNUNET_break_op (0);
2674       return;
2675     }
2676
2677   n->decrypt_key = k;
2678   if (n->decrypt_key_created.value != t.value)
2679     {
2680       /* fresh key, reset sequence numbers */
2681       n->last_sequence_number_received = 0;
2682       n->last_packets_bitmap = 0;
2683       n->decrypt_key_created = t;
2684     }
2685   sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2686   switch (n->status)
2687     {
2688     case PEER_STATE_DOWN:
2689       n->status = PEER_STATE_KEY_RECEIVED;
2690 #if DEBUG_CORE
2691       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2692                   "Responding to `%s' with my own key.\n", "SET_KEY");
2693 #endif
2694       send_key (n);
2695       break;
2696     case PEER_STATE_KEY_SENT:
2697     case PEER_STATE_KEY_RECEIVED:
2698       n->status = PEER_STATE_KEY_RECEIVED;
2699       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2700           (sender_status != PEER_STATE_KEY_CONFIRMED))
2701         {
2702 #if DEBUG_CORE
2703           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2704                       "Responding to `%s' with my own key (other peer has status %u).\n",
2705                       "SET_KEY", sender_status);
2706 #endif
2707           send_key (n);
2708         }
2709       break;
2710     case PEER_STATE_KEY_CONFIRMED:
2711       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2712           (sender_status != PEER_STATE_KEY_CONFIRMED))
2713         {         
2714 #if DEBUG_CORE
2715           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2716                       "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2717                       "SET_KEY", sender_status);
2718 #endif
2719           send_key (n);
2720         }
2721       break;
2722     default:
2723       GNUNET_break (0);
2724       break;
2725     }
2726   if (n->pending_ping != NULL)
2727     {
2728       ping = n->pending_ping;
2729       n->pending_ping = NULL;
2730       handle_ping (n, ping);
2731       GNUNET_free (ping);
2732     }
2733   if (n->pending_pong != NULL)
2734     {
2735       pong = n->pending_pong;
2736       n->pending_pong = NULL;
2737       handle_pong (n, pong);
2738       GNUNET_free (pong);
2739     }
2740 }
2741
2742
2743 /**
2744  * Send a P2P message to a client.
2745  *
2746  * @param sender who sent us the message?
2747  * @param client who should we give the message to?
2748  * @param m contains the message to transmit
2749  * @param msize number of bytes in buf to transmit
2750  */
2751 static void
2752 send_p2p_message_to_client (struct Neighbour *sender,
2753                             struct Client *client,
2754                             const void *m, size_t msize)
2755 {
2756   char buf[msize + sizeof (struct NotifyTrafficMessage)];
2757   struct NotifyTrafficMessage *ntm;
2758
2759 #if DEBUG_CORE
2760   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2761               "Core service passes message from `%4s' of type %u to client.\n",
2762               GNUNET_i2s(&sender->peer),
2763               ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2764 #endif
2765   ntm = (struct NotifyTrafficMessage *) buf;
2766   ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2767   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2768   ntm->distance = htonl (sender->last_distance);
2769   ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
2770   ntm->peer = sender->peer;
2771   memcpy (&ntm[1], m, msize);
2772   send_to_client (client, &ntm->header, GNUNET_YES);
2773 }
2774
2775
2776 /**
2777  * Deliver P2P message to interested clients.
2778  *
2779  * @param sender who sent us the message?
2780  * @param m the message
2781  * @param msize size of the message (including header)
2782  */
2783 static void
2784 deliver_message (struct Neighbour *sender,
2785                  const struct GNUNET_MessageHeader *m, size_t msize)
2786 {
2787   struct Client *cpos;
2788   uint16_t type;
2789   unsigned int tpos;
2790   int deliver_full;
2791   int dropped;
2792
2793   type = ntohs (m->type);
2794 #if DEBUG_CORE
2795   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2796               "Received encapsulated message of type %u from `%4s'\n",
2797               type,
2798               GNUNET_i2s (&sender->peer));
2799 #endif
2800   dropped = GNUNET_YES;
2801   cpos = clients;
2802   while (cpos != NULL)
2803     {
2804       deliver_full = GNUNET_NO;
2805       if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
2806         deliver_full = GNUNET_YES;
2807       else
2808         {
2809           for (tpos = 0; tpos < cpos->tcnt; tpos++)
2810             {
2811               if (type != cpos->types[tpos])
2812                 continue;
2813               deliver_full = GNUNET_YES;
2814               break;
2815             }
2816         }
2817       if (GNUNET_YES == deliver_full)
2818         {
2819           send_p2p_message_to_client (sender, cpos, m, msize);
2820           dropped = GNUNET_NO;
2821         }
2822       else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2823         {
2824           send_p2p_message_to_client (sender, cpos, m,
2825                                       sizeof (struct GNUNET_MessageHeader));
2826         }
2827       cpos = cpos->next;
2828     }
2829   if (dropped == GNUNET_YES)
2830     {
2831 #if DEBUG_CORE
2832       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2833                   "Message of type %u from `%4s' not delivered to any client.\n",
2834                   type,
2835                   GNUNET_i2s (&sender->peer));
2836 #endif
2837       /* FIXME: stats... */
2838     }
2839 }
2840
2841
2842 /**
2843  * Align P2P message and then deliver to interested clients.
2844  *
2845  * @param sender who sent us the message?
2846  * @param buffer unaligned (!) buffer containing message
2847  * @param msize size of the message (including header)
2848  */
2849 static void
2850 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
2851 {
2852   char abuf[msize];
2853
2854   /* TODO: call to statistics? */
2855   memcpy (abuf, buffer, msize);
2856   deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
2857 }
2858
2859
2860 /**
2861  * Deliver P2P messages to interested clients.
2862  *
2863  * @param sender who sent us the message?
2864  * @param buffer buffer containing messages, can be modified
2865  * @param buffer_size size of the buffer (overall)
2866  * @param offset offset where messages in the buffer start
2867  */
2868 static void
2869 deliver_messages (struct Neighbour *sender,
2870                   const char *buffer, size_t buffer_size, size_t offset)
2871 {
2872   struct GNUNET_MessageHeader *mhp;
2873   struct GNUNET_MessageHeader mh;
2874   uint16_t msize;
2875   int need_align;
2876
2877   while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
2878     {
2879       if (0 != offset % sizeof (uint16_t))
2880         {
2881           /* outch, need to copy to access header */
2882           memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
2883           mhp = &mh;
2884         }
2885       else
2886         {
2887           /* can access header directly */
2888           mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
2889         }
2890       msize = ntohs (mhp->size);
2891       if (msize + offset > buffer_size)
2892         {
2893           /* malformed message, header says it is larger than what
2894              would fit into the overall buffer */
2895           GNUNET_break_op (0);
2896           break;
2897         }
2898 #if HAVE_UNALIGNED_64_ACCESS
2899       need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
2900 #else
2901       need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
2902 #endif
2903       if (GNUNET_YES == need_align)
2904         align_and_deliver (sender, &buffer[offset], msize);
2905       else
2906         deliver_message (sender,
2907                          (const struct GNUNET_MessageHeader *)
2908                          &buffer[offset], msize);
2909       offset += msize;
2910     }
2911 }
2912
2913
2914 /**
2915  * We received an encrypted message.  Decrypt, validate and
2916  * pass on to the appropriate clients.
2917  */
2918 static void
2919 handle_encrypted_message (struct Neighbour *n,
2920                           const struct EncryptedMessage *m)
2921 {
2922   size_t size = ntohs (m->header.size);
2923   char buf[size];
2924   struct EncryptedMessage *pt;  /* plaintext */
2925   GNUNET_HashCode ph;
2926   size_t off;
2927   uint32_t snum;
2928   struct GNUNET_TIME_Absolute t;
2929   GNUNET_HashCode iv;
2930
2931 #if DEBUG_CORE
2932   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2933               "Core service receives `%s' request from `%4s'.\n",
2934               "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
2935 #endif  
2936   GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
2937   /* decrypt */
2938   if (GNUNET_OK !=
2939       do_decrypt (n,
2940                   &iv,
2941                   &m->plaintext_hash,
2942                   &buf[ENCRYPTED_HEADER_SIZE], 
2943                   size - ENCRYPTED_HEADER_SIZE))
2944     return;
2945   pt = (struct EncryptedMessage *) buf;
2946
2947   /* validate hash */
2948   GNUNET_CRYPTO_hash (&pt->sequence_number,
2949                       size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
2950   if (0 != memcmp (&ph, 
2951                    &pt->plaintext_hash, 
2952                    sizeof (GNUNET_HashCode)))
2953     {
2954       /* checksum failed */
2955       GNUNET_break_op (0);
2956       return;
2957     }
2958
2959   /* validate sequence number */
2960   snum = ntohl (pt->sequence_number);
2961   if (n->last_sequence_number_received == snum)
2962     {
2963       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2964                   "Received duplicate message, ignoring.\n");
2965       /* duplicate, ignore */
2966       return;
2967     }
2968   if ((n->last_sequence_number_received > snum) &&
2969       (n->last_sequence_number_received - snum > 32))
2970     {
2971       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2972                   "Received ancient out of sequence message, ignoring.\n");
2973       /* ancient out of sequence, ignore */
2974       return;
2975     }
2976   if (n->last_sequence_number_received > snum)
2977     {
2978       unsigned int rotbit =
2979         1 << (n->last_sequence_number_received - snum - 1);
2980       if ((n->last_packets_bitmap & rotbit) != 0)
2981         {
2982           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2983                       "Received duplicate message, ignoring.\n");
2984           /* duplicate, ignore */
2985           return;
2986         }
2987       n->last_packets_bitmap |= rotbit;
2988     }
2989   if (n->last_sequence_number_received < snum)
2990     {
2991       n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
2992       n->last_sequence_number_received = snum;
2993     }
2994
2995   /* check timestamp */
2996   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
2997   if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
2998     {
2999       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3000                   _
3001                   ("Message received far too old (%llu ms). Content ignored.\n"),
3002                   GNUNET_TIME_absolute_get_duration (t).value);
3003       return;
3004     }
3005
3006   /* process decrypted message(s) */
3007   update_window (GNUNET_YES,
3008                  &n->available_send_window,
3009                  &n->last_asw_update,
3010                  n->bpm_out);
3011   n->bpm_out_external_limit = ntohl (pt->inbound_bpm_limit);
3012   n->bpm_out = GNUNET_MAX (n->bpm_out_external_limit,
3013                            n->bpm_out_internal_limit);
3014   n->last_activity = GNUNET_TIME_absolute_get ();
3015   off = sizeof (struct EncryptedMessage);
3016   deliver_messages (n, buf, size, off);
3017 }
3018
3019
3020 /**
3021  * Function called by the transport for each received message.
3022  *
3023  * @param cls closure
3024  * @param peer (claimed) identity of the other peer
3025  * @param message the message
3026  * @param latency estimated latency for communicating with the
3027  *             given peer (round-trip)
3028  * @param distance in overlay hops, as given by transport plugin
3029  */
3030 static void
3031 handle_transport_receive (void *cls,
3032                           const struct GNUNET_PeerIdentity *peer,
3033                           const struct GNUNET_MessageHeader *message,
3034                           struct GNUNET_TIME_Relative latency,
3035                           unsigned int distance)
3036 {
3037   struct Neighbour *n;
3038   struct GNUNET_TIME_Absolute now;
3039   int up;
3040   uint16_t type;
3041   uint16_t size;
3042
3043 #if DEBUG_CORE
3044   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3045               "Received message of type %u from `%4s', demultiplexing.\n",
3046               ntohs (message->type), GNUNET_i2s (peer));
3047 #endif
3048   n = find_neighbour (peer);
3049   if (n == NULL)
3050     n = create_neighbour (peer);
3051   if (n == NULL)
3052     return;   
3053   n->last_latency = latency;
3054   n->last_distance = distance;
3055   up = (n->status == PEER_STATE_KEY_CONFIRMED);
3056   type = ntohs (message->type);
3057   size = ntohs (message->size);
3058 #if DEBUG_HANDSHAKE
3059   fprintf (stderr,
3060            "Received message of type %u from `%4s'\n",
3061            type,
3062            GNUNET_i2s (peer));
3063 #endif
3064   switch (type)
3065     {
3066     case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3067       if (size != sizeof (struct SetKeyMessage))
3068         {
3069           GNUNET_break_op (0);
3070           return;
3071         }
3072       handle_set_key (n, (const struct SetKeyMessage *) message);
3073       break;
3074     case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3075       if (size < sizeof (struct EncryptedMessage) +
3076           sizeof (struct GNUNET_MessageHeader))
3077         {
3078           GNUNET_break_op (0);
3079           return;
3080         }
3081       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3082           (n->status != PEER_STATE_KEY_CONFIRMED))
3083         {
3084           GNUNET_break_op (0);
3085           return;
3086         }
3087       handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3088       break;
3089     case GNUNET_MESSAGE_TYPE_CORE_PING:
3090       if (size != sizeof (struct PingMessage))
3091         {
3092           GNUNET_break_op (0);
3093           return;
3094         }
3095       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3096           (n->status != PEER_STATE_KEY_CONFIRMED))
3097         {
3098 #if DEBUG_CORE
3099           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3100                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3101                       "PING", GNUNET_i2s (&n->peer));
3102 #endif
3103           GNUNET_free_non_null (n->pending_ping);
3104           n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3105           memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3106           return;
3107         }
3108       handle_ping (n, (const struct PingMessage *) message);
3109       break;
3110     case GNUNET_MESSAGE_TYPE_CORE_PONG:
3111       if (size != sizeof (struct PingMessage))
3112         {
3113           GNUNET_break_op (0);
3114           return;
3115         }
3116       if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3117            (n->status != PEER_STATE_KEY_CONFIRMED) )
3118         {
3119 #if DEBUG_CORE
3120           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3121                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3122                       "PONG", GNUNET_i2s (&n->peer));
3123 #endif
3124           GNUNET_free_non_null (n->pending_pong);
3125           n->pending_pong = GNUNET_malloc (sizeof (struct PingMessage));
3126           memcpy (n->pending_pong, message, sizeof (struct PingMessage));
3127           return;
3128         }
3129       handle_pong (n, (const struct PingMessage *) message);
3130       break;
3131     default:
3132       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3133                   _("Unsupported message of type %u received.\n"), type);
3134       return;
3135     }
3136   if (n->status == PEER_STATE_KEY_CONFIRMED)
3137     {
3138       now = GNUNET_TIME_absolute_get ();
3139       n->last_activity = now;
3140       if (!up)
3141         n->time_established = now;
3142     }
3143 }
3144
3145
3146 /**
3147  * Function that recalculates the bandwidth quota for the
3148  * given neighbour and transmits it to the transport service.
3149  * 
3150  * @param cls neighbour for the quota update
3151  * @param tc context
3152  */
3153 static void
3154 neighbour_quota_update (void *cls,
3155                         const struct GNUNET_SCHEDULER_TaskContext *tc)
3156 {
3157   struct Neighbour *n = cls;
3158   uint32_t q_in;
3159   double pref_rel;
3160   double share;
3161   unsigned long long distributable;
3162   
3163   n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3164   /* calculate relative preference among all neighbours;
3165      divides by a bit more to avoid division by zero AND to
3166      account for possibility of new neighbours joining any time 
3167      AND to convert to double... */
3168   pref_rel = n->current_preference / (1.0 + preference_sum);
3169   distributable = 0;
3170   if (bandwidth_target_out > neighbour_count * MIN_BPM_PER_PEER)
3171     distributable = bandwidth_target_out - neighbour_count * MIN_BPM_PER_PEER;
3172   share = distributable * pref_rel;
3173   q_in = MIN_BPM_PER_PEER + (unsigned long long) share;
3174   /* check if we want to disconnect for good due to inactivity */
3175   if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3176        (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3177     {
3178 #if DEBUG_CORE
3179   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3180               "Forcing disconnect of `%4s' due to inactivity (?).\n",
3181               GNUNET_i2s (&n->peer));
3182 #endif
3183       q_in = 0; /* force disconnect */
3184     }
3185   if ( (n->bpm_in + MIN_BPM_CHANGE < q_in) ||
3186        (n->bpm_in - MIN_BPM_CHANGE > q_in) ) 
3187     {
3188       n->bpm_in = q_in;
3189       GNUNET_TRANSPORT_set_quota (transport,
3190                                   &n->peer,
3191                                   n->bpm_in, 
3192                                   n->bpm_out,
3193                                   GNUNET_TIME_UNIT_FOREVER_REL,
3194                                   NULL, NULL);
3195     }
3196   schedule_quota_update (n);
3197 }
3198
3199
3200 /**
3201  * Function called by transport to notify us that
3202  * a peer connected to us (on the network level).
3203  *
3204  * @param cls closure
3205  * @param peer the peer that connected
3206  * @param latency current latency of the connection
3207  * @param distance in overlay hops, as given by transport plugin
3208  */
3209 static void
3210 handle_transport_notify_connect (void *cls,
3211                                  const struct GNUNET_PeerIdentity *peer,
3212                                  struct GNUNET_TIME_Relative latency,
3213                                  unsigned int distance)
3214 {
3215   struct Neighbour *n;
3216   struct GNUNET_TIME_Absolute now;
3217   struct ConnectNotifyMessage cnm;
3218
3219   n = find_neighbour (peer);
3220   if (n != NULL)
3221     {
3222       if (n->is_connected)
3223         {
3224           /* duplicate connect notification!? */
3225           GNUNET_break (0);
3226           return;
3227         }
3228     }
3229   else
3230     {
3231       n = create_neighbour (peer);
3232     }
3233   now = GNUNET_TIME_absolute_get ();
3234   n->is_connected = GNUNET_YES;      
3235   n->last_latency = latency;
3236   n->last_distance = distance;
3237   n->last_asw_update = now;
3238   n->last_arw_update = now;
3239 #if DEBUG_CORE
3240   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3241               "Received connection from `%4s'.\n",
3242               GNUNET_i2s (&n->peer));
3243 #endif
3244   cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3245   cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3246   cnm.distance = htonl (n->last_distance);
3247   cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3248   cnm.peer = *peer;
3249   send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3250   send_key (n);
3251 }
3252
3253
3254 /**
3255  * Function called by transport telling us that a peer
3256  * disconnected.
3257  *
3258  * @param cls closure
3259  * @param peer the peer that disconnected
3260  */
3261 static void
3262 handle_transport_notify_disconnect (void *cls,
3263                                     const struct GNUNET_PeerIdentity *peer)
3264 {
3265   struct DisconnectNotifyMessage cnm;
3266   struct Neighbour *n;
3267
3268 #if DEBUG_CORE
3269   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3270               "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3271 #endif
3272   n = find_neighbour (peer);
3273   if (n == NULL)
3274     {
3275       GNUNET_break (0);
3276       return;
3277     }
3278   GNUNET_break (n->is_connected);
3279   cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3280   cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3281   cnm.peer = *peer;
3282   send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3283   n->is_connected = GNUNET_NO;
3284 }
3285
3286
3287 /**
3288  * Last task run during shutdown.  Disconnects us from
3289  * the transport.
3290  */
3291 static void
3292 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3293 {
3294   struct Neighbour *n;
3295   struct Client *c;
3296
3297 #if DEBUG_CORE
3298   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3299               "Core service shutting down.\n");
3300 #endif
3301   GNUNET_assert (transport != NULL);
3302   GNUNET_TRANSPORT_disconnect (transport);
3303   transport = NULL;
3304   while (NULL != (n = neighbours))
3305     {
3306       neighbours = n->next;
3307       GNUNET_assert (neighbour_count > 0);
3308       neighbour_count--;
3309       free_neighbour (n);
3310     }
3311   GNUNET_SERVER_notification_context_destroy (notifier);
3312   notifier = NULL;
3313   while (NULL != (c = clients))
3314     handle_client_disconnect (NULL, c->client_handle);
3315   if (my_private_key != NULL)
3316     GNUNET_CRYPTO_rsa_key_free (my_private_key);
3317 }
3318
3319
3320 /**
3321  * Initiate core service.
3322  *
3323  * @param cls closure
3324  * @param s scheduler to use
3325  * @param serv the initialized server
3326  * @param c configuration to use
3327  */
3328 static void
3329 run (void *cls,
3330      struct GNUNET_SCHEDULER_Handle *s,
3331      struct GNUNET_SERVER_Handle *serv,
3332      const struct GNUNET_CONFIGURATION_Handle *c)
3333 {
3334 #if 0
3335   unsigned long long qin;
3336   unsigned long long qout;
3337   unsigned long long tneigh;
3338 #endif
3339   char *keyfile;
3340
3341   sched = s;
3342   cfg = c;  
3343   /* parse configuration */
3344   if (
3345        (GNUNET_OK !=
3346         GNUNET_CONFIGURATION_get_value_number (c,
3347                                                "CORE",
3348                                                "TOTAL_QUOTA_IN",
3349                                                &bandwidth_target_in)) ||
3350        (GNUNET_OK !=
3351         GNUNET_CONFIGURATION_get_value_number (c,
3352                                                "CORE",
3353                                                "TOTAL_QUOTA_OUT",
3354                                                &bandwidth_target_out)) ||
3355        (GNUNET_OK !=
3356         GNUNET_CONFIGURATION_get_value_filename (c,
3357                                                  "GNUNETD",
3358                                                  "HOSTKEY", &keyfile)))
3359     {
3360       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3361                   _
3362                   ("Core service is lacking key configuration settings.  Exiting.\n"));
3363       GNUNET_SCHEDULER_shutdown (s);
3364       return;
3365     }
3366   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3367   GNUNET_free (keyfile);
3368   if (my_private_key == NULL)
3369     {
3370       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3371                   _("Core service could not access hostkey.  Exiting.\n"));
3372       GNUNET_SCHEDULER_shutdown (s);
3373       return;
3374     }
3375   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3376   GNUNET_CRYPTO_hash (&my_public_key,
3377                       sizeof (my_public_key), &my_identity.hashPubKey);
3378   /* setup notification */
3379   server = serv;
3380   notifier = GNUNET_SERVER_notification_context_create (server, 
3381                                                         MAX_NOTIFY_QUEUE);
3382   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3383   /* setup transport connection */
3384   transport = GNUNET_TRANSPORT_connect (sched,
3385                                         cfg,
3386                                         NULL,
3387                                         &handle_transport_receive,
3388                                         &handle_transport_notify_connect,
3389                                         &handle_transport_notify_disconnect);
3390   GNUNET_assert (NULL != transport);
3391   GNUNET_SCHEDULER_add_delayed (sched,
3392                                 GNUNET_TIME_UNIT_FOREVER_REL,
3393                                 &cleaning_task, NULL);
3394   /* process client requests */
3395   GNUNET_SERVER_add_handlers (server, handlers);
3396   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3397               _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3398 }
3399
3400
3401
3402 /**
3403  * The main function for the transport service.
3404  *
3405  * @param argc number of arguments from the command line
3406  * @param argv command line arguments
3407  * @return 0 ok, 1 on error
3408  */
3409 int
3410 main (int argc, char *const *argv)
3411 {
3412   return (GNUNET_OK ==
3413           GNUNET_SERVICE_run (argc,
3414                               argv,
3415                               "core",
3416                               GNUNET_SERVICE_OPTION_NONE,
3417                               &run, NULL)) ? 0 : 1;
3418 }
3419
3420 /* end of gnunet-service-core.c */