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