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