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