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