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