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