bound client queue size
[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           if (prev == NULL)
1504             n->messages = next;
1505           else
1506             prev->next = next;
1507           GNUNET_free (pos);
1508         }
1509       else
1510         prev = pos;
1511       pos = next;
1512     }
1513 }
1514
1515
1516 /**
1517  * Signature of the main function of a task.
1518  *
1519  * @param cls closure
1520  * @param tc context information (why was this task triggered now)
1521  */
1522 static void
1523 retry_plaintext_processing (void *cls,
1524                             const struct GNUNET_SCHEDULER_TaskContext *tc)
1525 {
1526   struct Neighbour *n = cls;
1527
1528   n->retry_plaintext_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1529   process_plaintext_neighbour_queue (n);
1530 }
1531
1532
1533 /**
1534  * Send our key (and encrypted PING) to the other peer.
1535  *
1536  * @param n the other peer
1537  */
1538 static void send_key (struct Neighbour *n);
1539
1540
1541 /**
1542  * Check if we have plaintext messages for the specified neighbour
1543  * pending, and if so, consider batching and encrypting them (and
1544  * then trigger processing of the encrypted queue if needed).
1545  *
1546  * @param n neighbour to check.
1547  */
1548 static void
1549 process_plaintext_neighbour_queue (struct Neighbour *n)
1550 {
1551   char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE];        /* plaintext */
1552   size_t used;
1553   size_t esize;
1554   struct EncryptedMessage *em;  /* encrypted message */
1555   struct EncryptedMessage *ph;  /* plaintext header */
1556   struct MessageEntry *me;
1557   unsigned int priority;
1558   struct GNUNET_TIME_Absolute deadline;
1559   struct GNUNET_TIME_Relative retry_time;
1560
1561   if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1562     {
1563       GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1564       n->retry_plaintext_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1565     }
1566   switch (n->status)
1567     {
1568     case PEER_STATE_DOWN:
1569       send_key (n);
1570 #if DEBUG_CORE
1571       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1572                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1573                   GNUNET_i2s(&n->peer));
1574 #endif
1575       return;
1576     case PEER_STATE_KEY_SENT:
1577       GNUNET_assert (n->retry_set_key_task !=
1578                      GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
1579 #if DEBUG_CORE
1580       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1581                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1582                   GNUNET_i2s(&n->peer));
1583 #endif
1584       return;
1585     case PEER_STATE_KEY_RECEIVED:
1586       GNUNET_assert (n->retry_set_key_task !=
1587                      GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
1588 #if DEBUG_CORE
1589       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1590                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1591                   GNUNET_i2s(&n->peer));
1592 #endif
1593       return;
1594     case PEER_STATE_KEY_CONFIRMED:
1595       /* ready to continue */
1596       break;
1597     }
1598   if (n->messages == NULL)
1599     {
1600 #if DEBUG_CORE
1601       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1602                   "Plaintext message queue for `%4s' is empty.\n",
1603                   GNUNET_i2s(&n->peer));
1604 #endif
1605       return;                   /* no pending messages */
1606     }
1607   discard_expired_messages (n);
1608   if (n->encrypted_head != NULL)
1609     {
1610 #if DEBUG_CORE
1611       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1612                   "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1613                   GNUNET_i2s(&n->peer));
1614 #endif
1615       return;                   /* wait for messages already encrypted to be
1616                                    processed first! */
1617     }
1618   ph = (struct EncryptedMessage *) pbuf;
1619   deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1620   priority = 0;
1621   used = sizeof (struct EncryptedMessage);
1622
1623   used += batch_message (n,
1624                          &pbuf[used],
1625                          MAX_ENCRYPTED_MESSAGE_SIZE - used,
1626                          &deadline, &retry_time, &priority);
1627   if (used == sizeof (struct EncryptedMessage))
1628     {
1629 #if DEBUG_CORE
1630       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1631                   "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1632                   GNUNET_i2s(&n->peer));
1633 #endif
1634       /* no messages selected for sending, try again later... */
1635       n->retry_plaintext_task =
1636         GNUNET_SCHEDULER_add_delayed (sched,
1637                                       GNUNET_NO,
1638                                       GNUNET_SCHEDULER_PRIORITY_IDLE,
1639                                       GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1640                                       retry_time,
1641                                       &retry_plaintext_processing, n);
1642       return;
1643     }
1644
1645   ph->sequence_number = htonl (++n->last_sequence_number_sent);
1646   ph->inbound_bpm_limit = htonl (n->bpm_in);
1647   ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1648
1649   /* setup encryption message header */
1650   me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1651   me->deadline = deadline;
1652   me->priority = priority;
1653   me->size = used;
1654   em = (struct EncryptedMessage *) &me[1];
1655   em->header.size = htons (used);
1656   em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1657   em->reserved = htonl (0);
1658   esize = used - ENCRYPTED_HEADER_SIZE;
1659   GNUNET_CRYPTO_hash (&ph->sequence_number, esize, &em->plaintext_hash);
1660   /* encrypt */
1661 #if DEBUG_CORE
1662   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1663               "Encrypting %u bytes of plaintext messages for `%4s' for transmission.\n",
1664               esize,
1665               GNUNET_i2s(&n->peer));
1666 #endif
1667   GNUNET_assert (GNUNET_OK ==
1668                  do_encrypt (n,
1669                              &em->plaintext_hash,
1670                              &ph->sequence_number,
1671                              &em->sequence_number, esize));
1672   /* append to transmission list */
1673   if (n->encrypted_tail == NULL)
1674     n->encrypted_head = me;
1675   else
1676     n->encrypted_tail->next = me;
1677   n->encrypted_tail = me;
1678   process_encrypted_neighbour_queue (n);
1679 }
1680
1681
1682 /**
1683  * Handle CORE_SEND request.
1684  */
1685 static void
1686 handle_client_send (void *cls,
1687                     struct GNUNET_SERVER_Client *client,
1688                     const struct GNUNET_MessageHeader *message);
1689
1690
1691 /**
1692  * Function called to notify us that we either succeeded
1693  * or failed to connect (at the transport level) to another
1694  * peer.  We should either free the message we were asked
1695  * to transmit or re-try adding it to the queue.
1696  *
1697  * @param cls closure
1698  * @param size number of bytes available in buf
1699  * @param buf where the callee should write the message
1700  * @return number of bytes written to buf
1701  */
1702 static size_t
1703 send_connect_continuation (void *cls, size_t size, void *buf)
1704 {
1705   struct SendMessage *sm = cls;
1706
1707   if (buf == NULL)
1708     {
1709 #if DEBUG_CORE
1710       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1711                   "Asked to send message to disconnected peer `%4s' and connection failed.  Discarding message.\n",
1712                   GNUNET_i2s (&sm->peer));
1713 #endif
1714       GNUNET_free (sm);
1715       return 0;
1716     }
1717 #if DEBUG_CORE
1718   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1719               "Connection to peer `%4s' succeeded, retrying original transmission request\n",
1720               GNUNET_i2s (&sm->peer));
1721 #endif
1722   handle_client_send (NULL, NULL, &sm->header);
1723   GNUNET_free (sm);
1724   return 0;
1725 }
1726
1727
1728 /**
1729  * Handle CORE_SEND request.
1730  */
1731 static void
1732 handle_client_send (void *cls,
1733                     struct GNUNET_SERVER_Client *client,
1734                     const struct GNUNET_MessageHeader *message)
1735 {
1736   const struct SendMessage *sm;
1737   struct SendMessage *smc;
1738   const struct GNUNET_MessageHeader *mh;
1739   struct Neighbour *n;
1740   struct MessageEntry *prev;
1741   struct MessageEntry *pos;
1742   struct MessageEntry *e; 
1743   struct MessageEntry *min_prio_entry;
1744   struct MessageEntry *min_prio_prev;
1745   unsigned int min_prio;
1746   unsigned int queue_size;
1747   uint16_t msize;
1748
1749   msize = ntohs (message->size);
1750   if (msize <
1751       sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
1752     {
1753       GNUNET_break (0);
1754       if (client != NULL)
1755         GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1756       return;
1757     }
1758   sm = (const struct SendMessage *) message;
1759   msize -= sizeof (struct SendMessage);
1760   mh = (const struct GNUNET_MessageHeader *) &sm[1];
1761   if (msize != ntohs (mh->size))
1762     {
1763       GNUNET_break (0);
1764       if (client != NULL)
1765         GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1766       return;
1767     }
1768   n = find_neighbour (&sm->peer);
1769   if (n == NULL)
1770     {
1771 #if DEBUG_CORE
1772       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1773                   "Core received `%s' request for `%4s', will try to establish connection within %llu ms\n",
1774                   "SEND",
1775                   GNUNET_i2s (&sm->peer),
1776                   sm->deadline.value);
1777 #endif
1778       msize += sizeof (struct SendMessage);
1779       /* ask transport to connect to the peer */
1780       smc = GNUNET_malloc (msize);
1781       memcpy (smc, sm, msize);
1782       if (NULL ==
1783           GNUNET_TRANSPORT_notify_transmit_ready (transport,
1784                                                   &sm->peer,
1785                                                   0,
1786                                                   GNUNET_TIME_absolute_get_remaining
1787                                                   (GNUNET_TIME_absolute_ntoh
1788                                                    (sm->deadline)),
1789                                                   &send_connect_continuation,
1790                                                   smc))
1791         {
1792           /* transport has already a request pending for this peer! */
1793 #if DEBUG_CORE
1794           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1795                       "Dropped second message destined for `%4s' since connection is still down.\n",
1796                       GNUNET_i2s(&sm->peer));
1797 #endif
1798           GNUNET_free (smc);
1799         }
1800       if (client != NULL)
1801         GNUNET_SERVER_receive_done (client, GNUNET_OK);
1802       return;
1803     }
1804 #if DEBUG_CORE
1805   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1806               "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
1807               "SEND",
1808               msize, 
1809               GNUNET_i2s (&sm->peer));
1810 #endif
1811   /* bound queue size */
1812   discard_expired_messages (n);
1813   min_prio = (unsigned int) -1;
1814   queue_size = 0;
1815   prev = NULL;
1816   pos = n->messages;
1817   while (pos != NULL) 
1818     {
1819       if (pos->priority < min_prio)
1820         {
1821           min_prio_entry = pos;
1822           min_prio_prev = prev;
1823           min_prio = pos->priority;
1824         }
1825       queue_size++;
1826       prev = pos;
1827       pos = pos->next;
1828     }
1829   if (queue_size >= MAX_PEER_QUEUE_SIZE)
1830     {
1831       /* queue full */
1832       if (ntohl(sm->priority) <= min_prio)
1833         {
1834           /* discard new entry */
1835 #if DEBUG_CORE
1836           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1837                       "Queue full, discarding new request\n");
1838 #endif
1839           if (client != NULL)
1840             GNUNET_SERVER_receive_done (client, GNUNET_OK);
1841           return;
1842         }
1843       /* discard "min_prio_entry" */
1844 #if DEBUG_CORE
1845       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1846                   "Queue full, discarding existing older request\n");
1847 #endif
1848       if (min_prio_prev == NULL)
1849         n->messages = min_prio_entry->next;
1850       else
1851         min_prio_prev->next = min_prio_entry->next;      
1852       GNUNET_free (min_prio_entry);     
1853     }
1854   
1855   e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
1856   e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
1857   e->priority = ntohl (sm->priority);
1858   e->size = msize;
1859   memcpy (&e[1], mh, msize);
1860
1861   /* insert, keep list sorted by deadline */
1862   prev = NULL;
1863   pos = n->messages;
1864   while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
1865     {
1866       prev = pos;
1867       pos = pos->next;
1868     }
1869   if (prev == NULL)
1870     n->messages = e;
1871   else
1872     prev->next = e;
1873   e->next = pos;
1874
1875   /* consider scheduling now */
1876   process_plaintext_neighbour_queue (n);
1877   if (client != NULL)
1878     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1879 }
1880
1881
1882 /**
1883  * List of handlers for the messages understood by this
1884  * service.
1885  */
1886 static struct GNUNET_SERVER_MessageHandler handlers[] = {
1887   {&handle_client_init, NULL,
1888    GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
1889   {&handle_client_request_configure, NULL,
1890    GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONFIGURE,
1891    sizeof (struct RequestConfigureMessage)},
1892   {&handle_client_send, NULL,
1893    GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
1894   {NULL, NULL, 0, 0}
1895 };
1896
1897
1898 /**
1899  * PEERINFO is giving us a HELLO for a peer.  Add the
1900  * public key to the neighbour's struct and retry
1901  * send_key.  Or, if we did not get a HELLO, just do
1902  * nothing.
1903  *
1904  * @param cls NULL
1905  * @param peer the peer for which this is the HELLO
1906  * @param hello HELLO message of that peer
1907  * @param trust amount of trust we currently have in that peer
1908  */
1909 static void
1910 process_hello_retry_send_key (void *cls,
1911                               const struct GNUNET_PeerIdentity *peer,
1912                               const struct GNUNET_HELLO_Message *hello,
1913                               uint32_t trust)
1914 {
1915   struct Neighbour *n;
1916
1917   if (peer == NULL)
1918     return;
1919   n = find_neighbour (peer);
1920   if (n == NULL)
1921     return;
1922   if (n->public_key != NULL)
1923     return;
1924 #if DEBUG_CORE
1925   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1926               "Received new `%s' message for `%4s', initiating key exchange.\n",
1927               "HELLO",
1928               GNUNET_i2s (peer));
1929 #endif
1930   n->public_key =
1931     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1932   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
1933     {
1934       GNUNET_free (n->public_key);
1935       n->public_key = NULL;
1936       return;
1937     }
1938   send_key (n);
1939 }
1940
1941
1942 /**
1943  * Task that will retry "send_key" if our previous attempt failed
1944  * to yield a PONG.
1945  */
1946 static void
1947 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1948 {
1949   struct Neighbour *n = cls;
1950
1951   GNUNET_assert (n->status != PEER_STATE_KEY_CONFIRMED);
1952   n->retry_set_key_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1953   n->set_key_retry_frequency =
1954     GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1955   send_key (n);
1956 }
1957
1958
1959 /**
1960  * Send our key (and encrypted PING) to the other peer.
1961  *
1962  * @param n the other peer
1963  */
1964 static void
1965 send_key (struct Neighbour *n)
1966 {
1967   struct SetKeyMessage *sm;
1968   struct MessageEntry *me;
1969   struct PingMessage pp;
1970   struct PingMessage *pm;
1971
1972 #if DEBUG_CORE
1973   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1974               "Asked to perform key exchange with `%4s'.\n",
1975               GNUNET_i2s (&n->peer));
1976 #endif
1977   if (n->public_key == NULL)
1978     {
1979       /* lookup n's public key, then try again */
1980 #if DEBUG_CORE
1981       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1982                   "Lacking public key for `%4s', trying to obtain one.\n",
1983                   GNUNET_i2s (&n->peer));
1984 #endif
1985       GNUNET_PEERINFO_for_all (cfg,
1986                                sched,
1987                                &n->peer,
1988                                0,
1989                                GNUNET_TIME_UNIT_MINUTES,
1990                                &process_hello_retry_send_key, NULL);
1991       return;
1992     }
1993   /* first, set key message */
1994   me = GNUNET_malloc (sizeof (struct MessageEntry) +
1995                       sizeof (struct SetKeyMessage));
1996   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
1997   me->priority = SET_KEY_PRIORITY;
1998   me->size = sizeof (struct SetKeyMessage);
1999   if (n->encrypted_head == NULL)
2000     n->encrypted_head = me;
2001   else
2002     n->encrypted_tail->next = me;
2003   n->encrypted_tail = me;
2004   sm = (struct SetKeyMessage *) &me[1];
2005   sm->header.size = htons (sizeof (struct SetKeyMessage));
2006   sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2007   sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2008                                         PEER_STATE_KEY_SENT : n->status));
2009   sm->purpose.size =
2010     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2011            sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2012            sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2013            sizeof (struct GNUNET_PeerIdentity));
2014   sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2015   sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2016   sm->target = n->peer;
2017   GNUNET_assert (GNUNET_OK ==
2018                  GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2019                                             sizeof (struct
2020                                                     GNUNET_CRYPTO_AesSessionKey),
2021                                             n->public_key,
2022                                             &sm->encrypted_key));
2023   GNUNET_assert (GNUNET_OK ==
2024                  GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2025                                          &sm->signature));
2026
2027   /* second, encrypted PING message */
2028   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2029                       sizeof (struct PingMessage));
2030   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2031   me->priority = PING_PRIORITY;
2032   me->size = sizeof (struct PingMessage);
2033   n->encrypted_tail->next = me;
2034   n->encrypted_tail = me;
2035   pm = (struct PingMessage *) &me[1];
2036   pm->header.size = htons (sizeof (struct PingMessage));
2037   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2038   pp.challenge = htonl (n->ping_challenge);
2039   pp.target = n->peer;
2040 #if DEBUG_CORE
2041   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2042               "Encrypting `%s' and `%s' messages for `%4s'.\n",
2043               "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2044   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2045               "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2046               "PING",
2047               GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2048 #endif
2049   do_encrypt (n,
2050               &n->peer.hashPubKey,
2051               &pp.challenge,
2052               &pm->challenge,
2053               sizeof (struct PingMessage) -
2054               sizeof (struct GNUNET_MessageHeader));
2055   /* update status */
2056   switch (n->status)
2057     {
2058     case PEER_STATE_DOWN:
2059       n->status = PEER_STATE_KEY_SENT;
2060       break;
2061     case PEER_STATE_KEY_SENT:
2062       break;
2063     case PEER_STATE_KEY_RECEIVED:
2064       break;
2065     case PEER_STATE_KEY_CONFIRMED:
2066       GNUNET_break (0);
2067       break;
2068     default:
2069       GNUNET_break (0);
2070       break;
2071     }
2072   /* trigger queue processing */
2073   process_encrypted_neighbour_queue (n);
2074   if (n->status != PEER_STATE_KEY_CONFIRMED)
2075     n->retry_set_key_task
2076       = GNUNET_SCHEDULER_add_delayed (sched,
2077                                       GNUNET_NO,
2078                                       GNUNET_SCHEDULER_PRIORITY_KEEP,
2079                                       GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
2080                                       n->set_key_retry_frequency,
2081                                       &set_key_retry_task, n);
2082 }
2083
2084
2085 /**
2086  * We received a SET_KEY message.  Validate and update
2087  * our key material and status.
2088  *
2089  * @param n the neighbour from which we received message m
2090  * @param m the set key message we received
2091  */
2092 static void
2093 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2094
2095
2096 /**
2097  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
2098  * the neighbour's struct and retry handling the set_key message.  Or,
2099  * if we did not get a HELLO, just free the set key message.
2100  *
2101  * @param cls pointer to the set key message
2102  * @param peer the peer for which this is the HELLO
2103  * @param hello HELLO message of that peer
2104  * @param trust amount of trust we currently have in that peer
2105  */
2106 static void
2107 process_hello_retry_handle_set_key (void *cls,
2108                                     const struct GNUNET_PeerIdentity *peer,
2109                                     const struct GNUNET_HELLO_Message *hello,
2110                                     uint32_t trust)
2111 {
2112   struct SetKeyMessage *sm = cls;
2113   struct Neighbour *n;
2114
2115   if (peer == NULL)
2116     {
2117       GNUNET_free (sm);
2118       return;
2119     }
2120   n = find_neighbour (peer);
2121   if (n == NULL)
2122     {
2123       GNUNET_break (0);
2124       return;
2125     }
2126   if (n->public_key != NULL)
2127     return;                     /* multiple HELLOs match!? */
2128   n->public_key =
2129     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2130   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2131     {
2132       GNUNET_break_op (0);
2133       GNUNET_free (n->public_key);
2134       n->public_key = NULL;
2135       return;
2136     }
2137 #if DEBUG_CORE
2138   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2139               "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2140               "HELLO", GNUNET_i2s (peer), "SET_KEY");
2141 #endif
2142   handle_set_key (n, sm);
2143 }
2144
2145
2146 /**
2147  * We received a PING message.  Validate and transmit
2148  * PONG.
2149  *
2150  * @param n sender of the PING
2151  * @param m the encrypted PING message itself
2152  */
2153 static void
2154 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2155 {
2156   struct PingMessage t;
2157   struct PingMessage *tp;
2158   struct MessageEntry *me;
2159
2160 #if DEBUG_CORE
2161   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2162               "Core service receives `%s' request from `%4s'.\n",
2163               "PING", GNUNET_i2s (&n->peer));
2164 #endif
2165   if (GNUNET_OK !=
2166       do_decrypt (n,
2167                   &my_identity.hashPubKey,
2168                   &m->challenge,
2169                   &t.challenge,
2170                   sizeof (struct PingMessage) -
2171                   sizeof (struct GNUNET_MessageHeader)))
2172     return;
2173 #if DEBUG_CORE
2174   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2175               "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2176               "PING",
2177               GNUNET_i2s (&t.target),
2178               ntohl (t.challenge), n->decrypt_key.crc32);
2179   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2180               "Target of `%s' request is `%4s'.\n",
2181               "PING", GNUNET_i2s (&t.target));
2182 #endif
2183   if (0 != memcmp (&t.target,
2184                    &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2185     {
2186       GNUNET_break_op (0);
2187       return;
2188     }
2189   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2190                       sizeof (struct PingMessage));
2191   if (n->encrypted_tail != NULL)
2192     n->encrypted_tail->next = me;
2193   else
2194     {
2195       n->encrypted_tail = me;
2196       n->encrypted_head = me;
2197     }
2198   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2199   me->priority = PONG_PRIORITY;
2200   me->size = sizeof (struct PingMessage);
2201   tp = (struct PingMessage *) &me[1];
2202   tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2203   tp->header.size = htons (sizeof (struct PingMessage));
2204   do_encrypt (n,
2205               &my_identity.hashPubKey,
2206               &t.challenge,
2207               &tp->challenge,
2208               sizeof (struct PingMessage) -
2209               sizeof (struct GNUNET_MessageHeader));
2210 #if DEBUG_CORE
2211   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2212               "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2213               ntohl (t.challenge), n->encrypt_key.crc32);
2214 #endif
2215   /* trigger queue processing */
2216   process_encrypted_neighbour_queue (n);
2217 }
2218
2219
2220 /**
2221  * We received a SET_KEY message.  Validate and update
2222  * our key material and status.
2223  *
2224  * @param n the neighbour from which we received message m
2225  * @param m the set key message we received
2226  */
2227 static void
2228 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2229 {
2230   struct SetKeyMessage *m_cpy;
2231   struct GNUNET_TIME_Absolute t;
2232   struct GNUNET_CRYPTO_AesSessionKey k;
2233   struct PingMessage *ping;
2234   enum PeerStateMachine sender_status;
2235
2236 #if DEBUG_CORE
2237   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2238               "Core service receives `%s' request from `%4s'.\n",
2239               "SET_KEY", GNUNET_i2s (&n->peer));
2240 #endif
2241   if (n->public_key == NULL)
2242     {
2243       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2244                   "Lacking public key for peer, trying to obtain one.\n");
2245       m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2246       memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2247       /* lookup n's public key, then try again */
2248       GNUNET_PEERINFO_for_all (cfg,
2249                                sched,
2250                                &n->peer,
2251                                0,
2252                                GNUNET_TIME_UNIT_MINUTES,
2253                                &process_hello_retry_handle_set_key, m_cpy);
2254       return;
2255     }
2256   if ((ntohl (m->purpose.size) !=
2257        sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2258        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2259        sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2260        sizeof (struct GNUNET_PeerIdentity)) ||
2261       (GNUNET_OK !=
2262        GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2263                                  &m->purpose, &m->signature, n->public_key)))
2264     {
2265       /* invalid signature */
2266       GNUNET_break_op (0);
2267       return;
2268     }
2269   t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2270   if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2271        (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2272       (t.value < n->decrypt_key_created.value))
2273     {
2274       /* this could rarely happen due to massive re-ordering of
2275          messages on the network level, but is most likely either
2276          a bug or some adversary messing with us.  Report. */
2277       GNUNET_break_op (0);
2278       return;
2279     }
2280 #if DEBUG_CORE
2281   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
2282 #endif
2283   if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2284                                   &m->encrypted_key,
2285                                   &k,
2286                                   sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2287        != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2288       (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2289     {
2290       /* failed to decrypt !? */
2291       GNUNET_break_op (0);
2292       return;
2293     }
2294
2295   n->decrypt_key = k;
2296   if (n->decrypt_key_created.value != t.value)
2297     {
2298       /* fresh key, reset sequence numbers */
2299       n->last_sequence_number_received = 0;
2300       n->last_packets_bitmap = 0;
2301       n->decrypt_key_created = t;
2302     }
2303   sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2304   switch (n->status)
2305     {
2306     case PEER_STATE_DOWN:
2307       n->status = PEER_STATE_KEY_RECEIVED;
2308 #if DEBUG_CORE
2309       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2310                   "Responding to `%s' with my own key.\n", "SET_KEY");
2311 #endif
2312       send_key (n);
2313       break;
2314     case PEER_STATE_KEY_SENT:
2315     case PEER_STATE_KEY_RECEIVED:
2316       n->status = PEER_STATE_KEY_RECEIVED;
2317       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2318           (sender_status != PEER_STATE_KEY_CONFIRMED))
2319         {
2320 #if DEBUG_CORE
2321           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2322                       "Responding to `%s' with my own key (other peer has status %u).\n",
2323                       "SET_KEY", sender_status);
2324 #endif
2325           send_key (n);
2326         }
2327       break;
2328     case PEER_STATE_KEY_CONFIRMED:
2329       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2330           (sender_status != PEER_STATE_KEY_CONFIRMED))
2331         {
2332 #if DEBUG_CORE
2333           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2334                       "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2335                       "SET_KEY", sender_status);
2336 #endif
2337           send_key (n);
2338         }
2339       break;
2340     default:
2341       GNUNET_break (0);
2342       break;
2343     }
2344   if (n->pending_ping != NULL)
2345     {
2346       ping = n->pending_ping;
2347       n->pending_ping = NULL;
2348       handle_ping (n, ping);
2349       GNUNET_free (ping);
2350     }
2351 }
2352
2353
2354 /**
2355  * We received a PONG message.  Validate and update
2356  * our status.
2357  *
2358  * @param n sender of the PONG
2359  * @param m the encrypted PONG message itself
2360  */
2361 static void
2362 handle_pong (struct Neighbour *n, const struct PingMessage *m)
2363 {
2364   struct PingMessage t;
2365
2366 #if DEBUG_CORE
2367   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2368               "Core service receives `%s' request from `%4s'.\n",
2369               "PONG", GNUNET_i2s (&n->peer));
2370 #endif
2371   if (GNUNET_OK !=
2372       do_decrypt (n,
2373                   &n->peer.hashPubKey,
2374                   &m->challenge,
2375                   &t.challenge,
2376                   sizeof (struct PingMessage) -
2377                   sizeof (struct GNUNET_MessageHeader)))
2378     return;
2379 #if DEBUG_CORE
2380   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2381               "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2382               "PONG",
2383               GNUNET_i2s (&t.target),
2384               ntohl (t.challenge), n->decrypt_key.crc32);
2385 #endif
2386   if ((0 != memcmp (&t.target,
2387                     &n->peer,
2388                     sizeof (struct GNUNET_PeerIdentity))) ||
2389       (n->ping_challenge != ntohl (t.challenge)))
2390     {
2391       /* PONG malformed */
2392 #if DEBUG_CORE
2393       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2394                   "Received malfromed `%s' wanted sender `%4s' with challenge %u\n",
2395                   "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2396       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2397                   "Received malfromed `%s' received from `%4s' with challenge %u\n",
2398                   "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2399 #endif
2400       GNUNET_break_op (0);
2401       return;
2402     }
2403   switch (n->status)
2404     {
2405     case PEER_STATE_DOWN:
2406       GNUNET_break (0);         /* should be impossible */
2407       return;
2408     case PEER_STATE_KEY_SENT:
2409       GNUNET_break (0);         /* should be impossible, how did we decrypt? */
2410       return;
2411     case PEER_STATE_KEY_RECEIVED:
2412       n->status = PEER_STATE_KEY_CONFIRMED;
2413       if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
2414         {
2415           GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2416           n->retry_set_key_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
2417         }
2418       process_encrypted_neighbour_queue (n);
2419       break;
2420     case PEER_STATE_KEY_CONFIRMED:
2421       /* duplicate PONG? */
2422       break;
2423     default:
2424       GNUNET_break (0);
2425       break;
2426     }
2427 }
2428
2429
2430 /**
2431  * Send a P2P message to a client.
2432  *
2433  * @param sender who sent us the message?
2434  * @param client who should we give the message to?
2435  * @param m contains the message to transmit
2436  * @param msize number of bytes in buf to transmit
2437  */
2438 static void
2439 send_p2p_message_to_client (struct Neighbour *sender,
2440                             struct Client *client,
2441                             const void *m, size_t msize)
2442 {
2443   char buf[msize + sizeof (struct NotifyTrafficMessage)];
2444   struct NotifyTrafficMessage *ntm;
2445
2446 #if DEBUG_CORE
2447   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2448               "Core service passes message from `%4s' of type %u to client.\n",
2449               GNUNET_i2s(&sender->peer),
2450               ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2451 #endif
2452   ntm = (struct NotifyTrafficMessage *) buf;
2453   ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2454   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2455   ntm->reserved = htonl (0);
2456   ntm->peer = sender->peer;
2457   memcpy (&ntm[1], m, msize);
2458   send_to_client (client, &ntm->header, GNUNET_YES);
2459 }
2460
2461
2462 /**
2463  * Deliver P2P message to interested clients.
2464  *
2465  * @param sender who sent us the message?
2466  * @param m the message
2467  * @param msize size of the message (including header)
2468  */
2469 static void
2470 deliver_message (struct Neighbour *sender,
2471                  const struct GNUNET_MessageHeader *m, size_t msize)
2472 {
2473   struct Client *cpos;
2474   uint16_t type;
2475   unsigned int tpos;
2476   int deliver_full;
2477
2478   type = ntohs (m->type);
2479   cpos = clients;
2480   while (cpos != NULL)
2481     {
2482       deliver_full = GNUNET_NO;
2483       if (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND)
2484         deliver_full = GNUNET_YES;
2485       else
2486         {
2487           for (tpos = 0; tpos < cpos->tcnt; tpos++)
2488             {
2489               if (type != cpos->types[tpos])
2490                 continue;
2491               deliver_full = GNUNET_YES;
2492               break;
2493             }
2494         }
2495       if (GNUNET_YES == deliver_full)
2496         send_p2p_message_to_client (sender, cpos, m, msize);
2497       else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2498         send_p2p_message_to_client (sender, cpos, m,
2499                                     sizeof (struct GNUNET_MessageHeader));
2500       cpos = cpos->next;
2501     }
2502 }
2503
2504
2505 /**
2506  * Align P2P message and then deliver to interested clients.
2507  *
2508  * @param sender who sent us the message?
2509  * @param buffer unaligned (!) buffer containing message
2510  * @param msize size of the message (including header)
2511  */
2512 static void
2513 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
2514 {
2515   char abuf[msize];
2516
2517   /* TODO: call to statistics? */
2518   memcpy (abuf, buffer, msize);
2519   deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
2520 }
2521
2522
2523 /**
2524  * Deliver P2P messages to interested clients.
2525  *
2526  * @param sender who sent us the message?
2527  * @param buffer buffer containing messages, can be modified
2528  * @param buffer_size size of the buffer (overall)
2529  * @param offset offset where messages in the buffer start
2530  */
2531 static void
2532 deliver_messages (struct Neighbour *sender,
2533                   const char *buffer, size_t buffer_size, size_t offset)
2534 {
2535   struct GNUNET_MessageHeader *mhp;
2536   struct GNUNET_MessageHeader mh;
2537   uint16_t msize;
2538   int need_align;
2539
2540   while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
2541     {
2542       if (0 != offset % sizeof (uint16_t))
2543         {
2544           /* outch, need to copy to access header */
2545           memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
2546           mhp = &mh;
2547         }
2548       else
2549         {
2550           /* can access header directly */
2551           mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
2552         }
2553       msize = ntohs (mhp->size);
2554       if (msize + offset > buffer_size)
2555         {
2556           /* malformed message, header says it is larger than what
2557              would fit into the overall buffer */
2558           GNUNET_break_op (0);
2559           break;
2560         }
2561 #if HAVE_UNALIGNED_64_ACCESS
2562       need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
2563 #else
2564       need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
2565 #endif
2566       if (GNUNET_YES == need_align)
2567         align_and_deliver (sender, &buffer[offset], msize);
2568       else
2569         deliver_message (sender,
2570                          (const struct GNUNET_MessageHeader *)
2571                          &buffer[offset], msize);
2572       offset += msize;
2573     }
2574 }
2575
2576
2577 /**
2578  * We received an encrypted message.  Decrypt, validate and
2579  * pass on to the appropriate clients.
2580  */
2581 static void
2582 handle_encrypted_message (struct Neighbour *n,
2583                           const struct EncryptedMessage *m)
2584 {
2585   size_t size = ntohs (m->header.size);
2586   char buf[size];
2587   struct EncryptedMessage *pt;  /* plaintext */
2588   GNUNET_HashCode ph;
2589   size_t off;
2590   uint32_t snum;
2591   struct GNUNET_TIME_Absolute t;
2592
2593 #if DEBUG_CORE
2594   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2595               "Core service receives `%s' request from `%4s'.\n",
2596               "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
2597 #endif
2598   /* decrypt */
2599   if (GNUNET_OK !=
2600       do_decrypt (n,
2601                   &m->plaintext_hash,
2602                   &m->sequence_number,
2603                   &buf[ENCRYPTED_HEADER_SIZE], size - ENCRYPTED_HEADER_SIZE))
2604     return;
2605   pt = (struct EncryptedMessage *) buf;
2606
2607   /* validate hash */
2608   GNUNET_CRYPTO_hash (&pt->sequence_number,
2609                       size - ENCRYPTED_HEADER_SIZE, &ph);
2610   if (0 != memcmp (&ph, &m->plaintext_hash, sizeof (GNUNET_HashCode)))
2611     {
2612       /* checksum failed */
2613       GNUNET_break_op (0);
2614       return;
2615     }
2616
2617   /* validate sequence number */
2618   snum = ntohl (pt->sequence_number);
2619   if (n->last_sequence_number_received == snum)
2620     {
2621       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2622                   "Received duplicate message, ignoring.\n");
2623       /* duplicate, ignore */
2624       return;
2625     }
2626   if ((n->last_sequence_number_received > snum) &&
2627       (n->last_sequence_number_received - snum > 32))
2628     {
2629       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2630                   "Received ancient out of sequence message, ignoring.\n");
2631       /* ancient out of sequence, ignore */
2632       return;
2633     }
2634   if (n->last_sequence_number_received > snum)
2635     {
2636       unsigned int rotbit =
2637         1 << (n->last_sequence_number_received - snum - 1);
2638       if ((n->last_packets_bitmap & rotbit) != 0)
2639         {
2640           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2641                       "Received duplicate message, ignoring.\n");
2642           /* duplicate, ignore */
2643           return;
2644         }
2645       n->last_packets_bitmap |= rotbit;
2646     }
2647   if (n->last_sequence_number_received < snum)
2648     {
2649       n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
2650       n->last_sequence_number_received = snum;
2651     }
2652
2653   /* check timestamp */
2654   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
2655   if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
2656     {
2657       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2658                   _
2659                   ("Message received far too old (%llu ms). Content ignored.\n"),
2660                   GNUNET_TIME_absolute_get_duration (t).value);
2661       return;
2662     }
2663
2664   /* process decrypted message(s) */
2665   n->bpm_out_external_limit = ntohl (pt->inbound_bpm_limit);
2666   n->bpm_out = GNUNET_MAX (n->bpm_out_external_limit,
2667                            n->bpm_out_internal_limit);
2668   n->last_activity = GNUNET_TIME_absolute_get ();
2669   off = sizeof (struct EncryptedMessage);
2670   deliver_messages (n, buf, size, off);
2671 }
2672
2673
2674 /**
2675  * Function called by the transport for each received message.
2676  *
2677  * @param cls closure
2678  * @param latency estimated latency for communicating with the
2679  *             given peer
2680  * @param peer (claimed) identity of the other peer
2681  * @param message the message
2682  */
2683 static void
2684 handle_transport_receive (void *cls,
2685                           struct GNUNET_TIME_Relative latency,
2686                           const struct GNUNET_PeerIdentity *peer,
2687                           const struct GNUNET_MessageHeader *message)
2688 {
2689   struct Neighbour *n;
2690   struct GNUNET_TIME_Absolute now;
2691   int up;
2692   uint16_t type;
2693   uint16_t size;
2694
2695 #if DEBUG_CORE
2696   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2697               "Received message of type %u from `%4s', demultiplexing.\n",
2698               ntohs (message->type), GNUNET_i2s (peer));
2699 #endif
2700   n = find_neighbour (peer);
2701   if (n == NULL)
2702     {
2703       GNUNET_break (0);
2704       return;
2705     }
2706   n->last_latency = latency;
2707   up = n->status == PEER_STATE_KEY_CONFIRMED;
2708   type = ntohs (message->type);
2709   size = ntohs (message->size);
2710   switch (type)
2711     {
2712     case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
2713       if (size != sizeof (struct SetKeyMessage))
2714         {
2715           GNUNET_break_op (0);
2716           return;
2717         }
2718       handle_set_key (n, (const struct SetKeyMessage *) message);
2719       break;
2720     case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
2721       if (size < sizeof (struct EncryptedMessage) +
2722           sizeof (struct GNUNET_MessageHeader))
2723         {
2724           GNUNET_break_op (0);
2725           return;
2726         }
2727       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2728           (n->status != PEER_STATE_KEY_CONFIRMED))
2729         {
2730           GNUNET_break_op (0);
2731           return;
2732         }
2733       handle_encrypted_message (n, (const struct EncryptedMessage *) message);
2734       break;
2735     case GNUNET_MESSAGE_TYPE_CORE_PING:
2736       if (size != sizeof (struct PingMessage))
2737         {
2738           GNUNET_break_op (0);
2739           return;
2740         }
2741       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2742           (n->status != PEER_STATE_KEY_CONFIRMED))
2743         {
2744 #if DEBUG_CORE
2745           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2746                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
2747                       "PING", GNUNET_i2s (&n->peer));
2748 #endif
2749           GNUNET_free_non_null (n->pending_ping);
2750           n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
2751           memcpy (n->pending_ping, message, sizeof (struct PingMessage));
2752           return;
2753         }
2754       handle_ping (n, (const struct PingMessage *) message);
2755       break;
2756     case GNUNET_MESSAGE_TYPE_CORE_PONG:
2757       if (size != sizeof (struct PingMessage))
2758         {
2759           GNUNET_break_op (0);
2760           return;
2761         }
2762       if ((n->status != PEER_STATE_KEY_SENT) &&
2763           (n->status != PEER_STATE_KEY_RECEIVED) &&
2764           (n->status != PEER_STATE_KEY_CONFIRMED))
2765         {
2766           /* could not decrypt pong, oops! */
2767           GNUNET_break_op (0);
2768           return;
2769         }
2770       handle_pong (n, (const struct PingMessage *) message);
2771       break;
2772     default:
2773       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2774                   _("Unsupported message of type %u received.\n"), type);
2775       return;
2776     }
2777   if (n->status == PEER_STATE_KEY_CONFIRMED)
2778     {
2779       now = GNUNET_TIME_absolute_get ();
2780       n->last_activity = now;
2781       if (!up)
2782         n->time_established = now;
2783     }
2784 }
2785
2786
2787 /**
2788  * Function called by transport to notify us that
2789  * a peer connected to us (on the network level).
2790  *
2791  * @param cls closure
2792  * @param peer the peer that connected
2793  * @param latency current latency of the connection
2794  */
2795 static void
2796 handle_transport_notify_connect (void *cls,
2797                                  const struct GNUNET_PeerIdentity *peer,
2798                                  struct GNUNET_TIME_Relative latency)
2799 {
2800   struct Neighbour *n;
2801   struct GNUNET_TIME_Absolute now;
2802   struct ConnectNotifyMessage cnm;
2803
2804   n = find_neighbour (peer);
2805   if (n != NULL)
2806     {
2807       /* duplicate connect notification!? */
2808       GNUNET_break (0);
2809       return;
2810     }
2811   now = GNUNET_TIME_absolute_get ();
2812   n = GNUNET_malloc (sizeof (struct Neighbour));
2813   n->next = neighbours;
2814   neighbours = n;
2815   n->peer = *peer;
2816   n->last_latency = latency;
2817   GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2818   n->encrypt_key_created = now;
2819   n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2820   n->last_asw_update = now;
2821   n->last_arw_update = now;
2822   n->bpm_in = DEFAULT_BPM_IN_OUT;
2823   n->bpm_out = DEFAULT_BPM_IN_OUT;
2824   n->bpm_out_internal_limit = (uint32_t) - 1;
2825   n->bpm_out_external_limit = DEFAULT_BPM_IN_OUT;
2826   n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2827                                                 (uint32_t) - 1);
2828 #if DEBUG_CORE
2829   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2830               "Received connection from `%4s'.\n",
2831               GNUNET_i2s (&n->peer));
2832 #endif
2833   cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2834   cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2835   cnm.bpm_available = htonl (DEFAULT_BPM_IN_OUT);
2836   cnm.peer = *peer;
2837   cnm.last_activity = GNUNET_TIME_absolute_hton (now);
2838   send_to_all_clients (&cnm.header, GNUNET_YES);
2839 }
2840
2841
2842 /**
2843  * Free the given entry for the neighbour (it has
2844  * already been removed from the list at this point).
2845  * @param n neighbour to free
2846  */
2847 static void
2848 free_neighbour (struct Neighbour *n)
2849 {
2850   struct MessageEntry *m;
2851
2852   while (NULL != (m = n->messages))
2853     {
2854       n->messages = m->next;
2855       GNUNET_free (m);
2856     }
2857   while (NULL != (m = n->encrypted_head))
2858     {
2859       n->encrypted_head = m->next;
2860       GNUNET_free (m);
2861     }
2862   if (NULL != n->th)
2863     GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
2864   if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
2865     GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
2866   if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
2867     GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2868   GNUNET_free_non_null (n->public_key);
2869   GNUNET_free_non_null (n->pending_ping);
2870   GNUNET_free (n);
2871 }
2872
2873
2874 /**
2875  * Function called by transport telling us that a peer
2876  * disconnected.
2877  *
2878  * @param cls closure
2879  * @param peer the peer that disconnected
2880  */
2881 static void
2882 handle_transport_notify_disconnect (void *cls,
2883                                     const struct GNUNET_PeerIdentity *peer)
2884 {
2885   struct ConnectNotifyMessage cnm;
2886   struct Neighbour *n;
2887   struct Neighbour *p;
2888
2889 #if DEBUG_CORE
2890   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2891               "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
2892 #endif
2893   p = NULL;
2894   n = neighbours;
2895   while ((n != NULL) &&
2896          (0 != memcmp (&n->peer, peer, sizeof (struct GNUNET_PeerIdentity))))
2897     {
2898       p = n;
2899       n = n->next;
2900     }
2901   if (n == NULL)
2902     {
2903       GNUNET_break (0);
2904       return;
2905     }
2906   if (p == NULL)
2907     neighbours = n->next;
2908   else
2909     p->next = n->next;
2910   cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2911   cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
2912   cnm.bpm_available = htonl (0);
2913   cnm.peer = *peer;
2914   cnm.last_activity = GNUNET_TIME_absolute_hton (n->last_activity);
2915   send_to_all_clients (&cnm.header, GNUNET_YES);
2916   free_neighbour (n);
2917 }
2918
2919
2920 /**
2921  * Last task run during shutdown.  Disconnects us from
2922  * the transport.
2923  */
2924 static void
2925 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2926 {
2927   struct Neighbour *n;
2928   struct Client *c;
2929
2930 #if DEBUG_CORE
2931   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2932               "Core service shutting down.\n");
2933 #endif
2934   GNUNET_assert (transport != NULL);
2935   GNUNET_TRANSPORT_disconnect (transport);
2936   transport = NULL;
2937   while (NULL != (n = neighbours))
2938     {
2939       neighbours = n->next;
2940       free_neighbour (n);
2941     }
2942   while (NULL != (c = clients))
2943     handle_client_disconnect (NULL, c->client_handle);
2944 }
2945
2946
2947 /**
2948  * Initiate core service.
2949  *
2950  * @param cls closure
2951  * @param s scheduler to use
2952  * @param serv the initialized server
2953  * @param c configuration to use
2954  */
2955 static void
2956 run (void *cls,
2957      struct GNUNET_SCHEDULER_Handle *s,
2958      struct GNUNET_SERVER_Handle *serv, struct GNUNET_CONFIGURATION_Handle *c)
2959 {
2960 #if 0
2961   unsigned long long qin;
2962   unsigned long long qout;
2963   unsigned long long tneigh;
2964 #endif
2965   char *keyfile;
2966
2967   sched = s;
2968   cfg = c;
2969   /* parse configuration */
2970   if (
2971 #if 0
2972        (GNUNET_OK !=
2973         GNUNET_CONFIGURATION_get_value_number (c,
2974                                                "CORE",
2975                                                "XX",
2976                                                &qin)) ||
2977        (GNUNET_OK !=
2978         GNUNET_CONFIGURATION_get_value_number (c,
2979                                                "CORE",
2980                                                "YY",
2981                                                &qout)) ||
2982        (GNUNET_OK !=
2983         GNUNET_CONFIGURATION_get_value_number (c,
2984                                                "CORE",
2985                                                "ZZ_LIMIT", &tneigh)) ||
2986 #endif
2987        (GNUNET_OK !=
2988         GNUNET_CONFIGURATION_get_value_filename (c,
2989                                                  "GNUNETD",
2990                                                  "HOSTKEY", &keyfile)))
2991     {
2992       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2993                   _
2994                   ("Core service is lacking key configuration settings.  Exiting.\n"));
2995       GNUNET_SCHEDULER_shutdown (s);
2996       return;
2997     }
2998   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2999   GNUNET_free (keyfile);
3000   if (my_private_key == NULL)
3001     {
3002       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3003                   _("Core service could not access hostkey.  Exiting.\n"));
3004       GNUNET_SCHEDULER_shutdown (s);
3005       return;
3006     }
3007   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3008   GNUNET_CRYPTO_hash (&my_public_key,
3009                       sizeof (my_public_key), &my_identity.hashPubKey);
3010   /* setup notification */
3011   server = serv;
3012   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3013   /* setup transport connection */
3014   transport = GNUNET_TRANSPORT_connect (sched,
3015                                         cfg,
3016                                         NULL,
3017                                         &handle_transport_receive,
3018                                         &handle_transport_notify_connect,
3019                                         &handle_transport_notify_disconnect);
3020   GNUNET_assert (NULL != transport);
3021   GNUNET_SCHEDULER_add_delayed (sched,
3022                                 GNUNET_YES,
3023                                 GNUNET_SCHEDULER_PRIORITY_IDLE,
3024                                 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
3025                                 GNUNET_TIME_UNIT_FOREVER_REL,
3026                                 &cleaning_task, NULL);
3027   /* process client requests */
3028   GNUNET_SERVER_add_handlers (server, handlers);
3029   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3030               _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3031 }
3032
3033
3034 /**
3035  * Function called during shutdown.  Clean up our state.
3036  */
3037 static void
3038 cleanup (void *cls, struct GNUNET_CONFIGURATION_Handle *cfg)
3039 {
3040
3041
3042   if (my_private_key != NULL)
3043     GNUNET_CRYPTO_rsa_key_free (my_private_key);
3044 }
3045
3046
3047 /**
3048  * The main function for the transport service.
3049  *
3050  * @param argc number of arguments from the command line
3051  * @param argv command line arguments
3052  * @return 0 ok, 1 on error
3053  */
3054 int
3055 main (int argc, char *const *argv)
3056 {
3057   return (GNUNET_OK ==
3058           GNUNET_SERVICE_run (argc,
3059                               argv,
3060                               "core", &run, NULL, &cleanup, NULL)) ? 0 : 1;
3061 }
3062
3063 /* end of gnunet-service-core.c */