more stats
[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           GNUNET_STATISTICS_update (stats,
2332                                     gettext_noop ("# SETKEY messages deferred (need public key)"), 
2333                                     -1, 
2334                                     GNUNET_NO);
2335           send_key (n);
2336         }
2337       else
2338         {
2339           GNUNET_STATISTICS_update (stats,
2340                                     gettext_noop ("# Delayed connecting due to lack of public key"),
2341                                     1,
2342                                     GNUNET_NO);      
2343           if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2344             n->retry_set_key_task
2345               = GNUNET_SCHEDULER_add_delayed (sched,
2346                                               n->set_key_retry_frequency,
2347                                               &set_key_retry_task, n);
2348         }
2349       return;
2350     }
2351
2352 #if DEBUG_CORE
2353   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2354               "Entered `process_hello_retry_send_key' for peer `%4s'\n",
2355               GNUNET_i2s (peer));
2356 #endif
2357   if (n->public_key != NULL)
2358     {
2359 #if DEBUG_CORE
2360       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2361               "already have public key for peer %s!! (so why are we here?)\n",
2362               GNUNET_i2s (peer));
2363 #endif
2364       return;
2365     }
2366
2367 #if DEBUG_CORE
2368   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2369               "Received new `%s' message for `%4s', initiating key exchange.\n",
2370               "HELLO",
2371               GNUNET_i2s (peer));
2372 #endif
2373   n->public_key =
2374     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2375   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2376     {
2377       GNUNET_STATISTICS_update (stats,
2378                                 gettext_noop ("# Error extracting public key from HELLO"),
2379                                 1,
2380                                 GNUNET_NO);      
2381       GNUNET_free (n->public_key);
2382       n->public_key = NULL;
2383 #if DEBUG_CORE
2384   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2385               "GNUNET_HELLO_get_key returned awfully\n");
2386 #endif
2387       return;
2388     }
2389 }
2390
2391
2392 /**
2393  * Send our key (and encrypted PING) to the other peer.
2394  *
2395  * @param n the other peer
2396  */
2397 static void
2398 send_key (struct Neighbour *n)
2399 {
2400   struct SetKeyMessage *sm;
2401   struct MessageEntry *me;
2402   struct PingMessage pp;
2403   struct PingMessage *pm;
2404
2405   if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2406        (n->pitr != NULL) )
2407     {
2408 #if DEBUG_CORE
2409       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2410                   "Key exchange in progress with `%4s'.\n",
2411                   GNUNET_i2s (&n->peer));
2412 #endif
2413       return; /* already in progress */
2414     }
2415
2416 #if DEBUG_CORE
2417   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2418               "Asked to perform key exchange with `%4s'.\n",
2419               GNUNET_i2s (&n->peer));
2420 #endif
2421   if (n->public_key == NULL)
2422     {
2423       /* lookup n's public key, then try again */
2424 #if DEBUG_CORE
2425       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2426                   "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2427                   GNUNET_i2s (&n->peer));
2428 #endif
2429       GNUNET_assert (n->pitr == NULL);
2430       n->pitr = GNUNET_PEERINFO_iterate (cfg,
2431                                          sched,
2432                                          &n->peer,
2433                                          0,
2434                                          GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2435                                          &process_hello_retry_send_key, n);
2436       return;
2437     }
2438   /* first, set key message */
2439   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2440                       sizeof (struct SetKeyMessage));
2441   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2442   me->priority = SET_KEY_PRIORITY;
2443   me->size = sizeof (struct SetKeyMessage);
2444   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2445                                      n->encrypted_tail,
2446                                      n->encrypted_tail,
2447                                      me);
2448   sm = (struct SetKeyMessage *) &me[1];
2449   sm->header.size = htons (sizeof (struct SetKeyMessage));
2450   sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2451   sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2452                                         PEER_STATE_KEY_SENT : n->status));
2453   sm->purpose.size =
2454     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2455            sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2456            sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2457            sizeof (struct GNUNET_PeerIdentity));
2458   sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2459   sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2460   sm->target = n->peer;
2461   GNUNET_assert (GNUNET_OK ==
2462                  GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2463                                             sizeof (struct
2464                                                     GNUNET_CRYPTO_AesSessionKey),
2465                                             n->public_key,
2466                                             &sm->encrypted_key));
2467   GNUNET_assert (GNUNET_OK ==
2468                  GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2469                                          &sm->signature));
2470
2471   /* second, encrypted PING message */
2472   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2473                       sizeof (struct PingMessage));
2474   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2475   me->priority = PING_PRIORITY;
2476   me->size = sizeof (struct PingMessage);
2477   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2478                                      n->encrypted_tail,
2479                                      n->encrypted_tail,
2480                                      me);
2481   pm = (struct PingMessage *) &me[1];
2482   pm->header.size = htons (sizeof (struct PingMessage));
2483   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2484   pp.challenge = htonl (n->ping_challenge);
2485   pp.target = n->peer;
2486 #if DEBUG_CORE
2487   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2488               "Encrypting `%s' and `%s' messages for `%4s'.\n",
2489               "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2490   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2491               "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2492               "PING",
2493               GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2494 #endif
2495   do_encrypt (n,
2496               &n->peer.hashPubKey,
2497               &pp.challenge,
2498               &pm->challenge,
2499               sizeof (struct PingMessage) -
2500               sizeof (struct GNUNET_MessageHeader));
2501   /* update status */
2502   switch (n->status)
2503     {
2504     case PEER_STATE_DOWN:
2505       n->status = PEER_STATE_KEY_SENT;
2506       break;
2507     case PEER_STATE_KEY_SENT:
2508       break;
2509     case PEER_STATE_KEY_RECEIVED:
2510       break;
2511     case PEER_STATE_KEY_CONFIRMED:
2512       break;
2513     default:
2514       GNUNET_break (0);
2515       break;
2516     }
2517 #if DEBUG_CORE
2518   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2519               "Have %llu ms left for `%s' transmission.\n",
2520               (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2521               "SET_KEY");
2522 #endif
2523   /* trigger queue processing */
2524   process_encrypted_neighbour_queue (n);
2525   if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2526        (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2527     n->retry_set_key_task
2528       = GNUNET_SCHEDULER_add_delayed (sched,
2529                                       n->set_key_retry_frequency,
2530                                       &set_key_retry_task, n);    
2531 }
2532
2533
2534 /**
2535  * We received a SET_KEY message.  Validate and update
2536  * our key material and status.
2537  *
2538  * @param n the neighbour from which we received message m
2539  * @param m the set key message we received
2540  */
2541 static void
2542 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2543
2544
2545 /**
2546  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
2547  * the neighbour's struct and retry handling the set_key message.  Or,
2548  * if we did not get a HELLO, just free the set key message.
2549  *
2550  * @param cls pointer to the set key message
2551  * @param peer the peer for which this is the HELLO
2552  * @param hello HELLO message of that peer
2553  * @param trust amount of trust we currently have in that peer
2554  */
2555 static void
2556 process_hello_retry_handle_set_key (void *cls,
2557                                     const struct GNUNET_PeerIdentity *peer,
2558                                     const struct GNUNET_HELLO_Message *hello,
2559                                     uint32_t trust)
2560 {
2561   struct Neighbour *n = cls;
2562   struct SetKeyMessage *sm = n->skm;
2563
2564   if (peer == NULL)
2565     {
2566       GNUNET_free (sm);
2567       n->skm = NULL;
2568       n->pitr = NULL;
2569       return;
2570     }
2571   if (n->public_key != NULL)
2572     return;                     /* multiple HELLOs match!? */
2573   n->public_key =
2574     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2575   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2576     {
2577       GNUNET_break_op (0);
2578       GNUNET_free (n->public_key);
2579       n->public_key = NULL;
2580       return;
2581     }
2582 #if DEBUG_CORE
2583   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2584               "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2585               "HELLO", GNUNET_i2s (peer), "SET_KEY");
2586 #endif
2587   handle_set_key (n, sm);
2588 }
2589
2590
2591 /**
2592  * We received a PING message.  Validate and transmit
2593  * PONG.
2594  *
2595  * @param n sender of the PING
2596  * @param m the encrypted PING message itself
2597  */
2598 static void
2599 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2600 {
2601   struct PingMessage t;
2602   struct PongMessage tx;
2603   struct PongMessage *tp;
2604   struct MessageEntry *me;
2605
2606 #if DEBUG_CORE
2607   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2608               "Core service receives `%s' request from `%4s'.\n",
2609               "PING", GNUNET_i2s (&n->peer));
2610 #endif
2611   if (GNUNET_OK !=
2612       do_decrypt (n,
2613                   &my_identity.hashPubKey,
2614                   &m->challenge,
2615                   &t.challenge,
2616                   sizeof (struct PingMessage) -
2617                   sizeof (struct GNUNET_MessageHeader)))
2618     return;
2619 #if DEBUG_CORE
2620   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2621               "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2622               "PING",
2623               GNUNET_i2s (&t.target),
2624               ntohl (t.challenge), n->decrypt_key.crc32);
2625   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2626               "Target of `%s' request is `%4s'.\n",
2627               "PING", GNUNET_i2s (&t.target));
2628 #endif
2629   GNUNET_STATISTICS_update (stats, gettext_noop ("# ping messages decrypted"), 1, GNUNET_NO);
2630   if (0 != memcmp (&t.target,
2631                    &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2632     {
2633       GNUNET_break_op (0);
2634       return;
2635     }
2636   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2637                       sizeof (struct PongMessage));
2638   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2639                                      n->encrypted_tail,
2640                                      n->encrypted_tail,
2641                                      me);
2642   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2643   me->priority = PONG_PRIORITY;
2644   me->size = sizeof (struct PongMessage);
2645   tx.reserved = htonl (0);
2646   tx.inbound_bw_limit = n->bw_in;
2647   tx.challenge = t.challenge;
2648   tx.target = t.target;
2649   tp = (struct PongMessage *) &me[1];
2650   tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2651   tp->header.size = htons (sizeof (struct PongMessage));
2652   do_encrypt (n,
2653               &my_identity.hashPubKey,
2654               &tx.challenge,
2655               &tp->challenge,
2656               sizeof (struct PongMessage) -
2657               sizeof (struct GNUNET_MessageHeader));
2658 #if DEBUG_CORE
2659   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2660               "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2661               ntohl (t.challenge), n->encrypt_key.crc32);
2662 #endif
2663   /* trigger queue processing */
2664   process_encrypted_neighbour_queue (n);
2665 }
2666
2667
2668 /**
2669  * We received a PONG message.  Validate and update our status.
2670  *
2671  * @param n sender of the PONG
2672  * @param m the encrypted PONG message itself
2673  */
2674 static void
2675 handle_pong (struct Neighbour *n, 
2676              const struct PongMessage *m)
2677 {
2678   struct PongMessage t;
2679   struct ConnectNotifyMessage cnm;
2680
2681 #if DEBUG_CORE
2682   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2683               "Core service receives `%s' request from `%4s'.\n",
2684               "PONG", GNUNET_i2s (&n->peer));
2685 #endif
2686   if (GNUNET_OK !=
2687       do_decrypt (n,
2688                   &n->peer.hashPubKey,
2689                   &m->challenge,
2690                   &t.challenge,
2691                   sizeof (struct PongMessage) -
2692                   sizeof (struct GNUNET_MessageHeader)))
2693     return;
2694   if (0 != ntohl (t.reserved))
2695     {
2696       GNUNET_break_op (0);
2697       return;
2698     }
2699 #if DEBUG_CORE
2700   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2701               "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2702               "PONG",
2703               GNUNET_i2s (&t.target),
2704               ntohl (t.challenge), n->decrypt_key.crc32);
2705 #endif
2706   if ((0 != memcmp (&t.target,
2707                     &n->peer,
2708                     sizeof (struct GNUNET_PeerIdentity))) ||
2709       (n->ping_challenge != ntohl (t.challenge)))
2710     {
2711       /* PONG malformed */
2712 #if DEBUG_CORE
2713       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2714                   "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2715                   "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2716       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2717                   "Received malformed `%s' received from `%4s' with challenge %u\n",
2718                   "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2719 #endif
2720       GNUNET_break_op (0);
2721       return;
2722     }
2723   switch (n->status)
2724     {
2725     case PEER_STATE_DOWN:
2726       GNUNET_break (0);         /* should be impossible */
2727       return;
2728     case PEER_STATE_KEY_SENT:
2729       GNUNET_break (0);         /* should be impossible, how did we decrypt? */
2730       return;
2731     case PEER_STATE_KEY_RECEIVED:
2732       n->status = PEER_STATE_KEY_CONFIRMED;
2733       if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2734         {
2735           n->bw_out_external_limit = t.inbound_bw_limit;
2736           n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2737                                                   n->bw_out_internal_limit);
2738           GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2739                                                  n->bw_out);       
2740           GNUNET_TRANSPORT_set_quota (transport,
2741                                       &n->peer,
2742                                       n->bw_in,
2743                                       n->bw_out,
2744                                       GNUNET_TIME_UNIT_FOREVER_REL,
2745                                       NULL, NULL); 
2746         }
2747 #if DEBUG_CORE
2748       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2749                   "Confirmed key via `%s' message for peer `%4s'\n",
2750                   "PONG", GNUNET_i2s (&n->peer));
2751 #endif      
2752       if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2753         {
2754           GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2755           n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2756         }      
2757       cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2758       cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2759       cnm.distance = htonl (n->last_distance);
2760       cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2761       cnm.peer = n->peer;
2762       send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2763       process_encrypted_neighbour_queue (n);
2764       /* fall-through! */
2765     case PEER_STATE_KEY_CONFIRMED:
2766       n->last_activity = GNUNET_TIME_absolute_get ();
2767       if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2768         GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2769       n->keep_alive_task 
2770         = GNUNET_SCHEDULER_add_delayed (sched, 
2771                                         GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2772                                         &send_keep_alive,
2773                                         n);
2774       break;
2775     default:
2776       GNUNET_break (0);
2777       break;
2778     }
2779 }
2780
2781
2782 /**
2783  * We received a SET_KEY message.  Validate and update
2784  * our key material and status.
2785  *
2786  * @param n the neighbour from which we received message m
2787  * @param m the set key message we received
2788  */
2789 static void
2790 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2791 {
2792   struct SetKeyMessage *m_cpy;
2793   struct GNUNET_TIME_Absolute t;
2794   struct GNUNET_CRYPTO_AesSessionKey k;
2795   struct PingMessage *ping;
2796   struct PongMessage *pong;
2797   enum PeerStateMachine sender_status;
2798
2799 #if DEBUG_CORE
2800   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2801               "Core service receives `%s' request from `%4s'.\n",
2802               "SET_KEY", GNUNET_i2s (&n->peer));
2803 #endif
2804   if (n->public_key == NULL)
2805     {
2806       if (n->pitr != NULL)
2807         {
2808 #if DEBUG_CORE
2809           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2810                       "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2811                       "SET_KEY");
2812 #endif
2813           return;
2814         }
2815 #if DEBUG_CORE
2816       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2817                   "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2818 #endif
2819       m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2820       memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2821       /* lookup n's public key, then try again */
2822       GNUNET_assert (n->skm == NULL);
2823       n->skm = m_cpy;
2824       n->pitr = GNUNET_PEERINFO_iterate (cfg,
2825                                          sched,
2826                                          &n->peer,
2827                                          0,
2828                                          GNUNET_TIME_UNIT_MINUTES,
2829                                          &process_hello_retry_handle_set_key, n);
2830       GNUNET_STATISTICS_update (stats, gettext_noop ("# SETKEY messages deferred (need public key)"), 1, GNUNET_NO);
2831       return;
2832     }
2833   if (0 != memcmp (&m->target,
2834                    &my_identity,
2835                    sizeof (struct GNUNET_PeerIdentity)))
2836     {
2837       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2838                   _("Received `%s' message that was for `%s', not for me.  Ignoring.\n"),
2839                   "SET_KEY",
2840                   GNUNET_i2s (&m->target));
2841       return;
2842     }
2843   if ((ntohl (m->purpose.size) !=
2844        sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2845        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2846        sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2847        sizeof (struct GNUNET_PeerIdentity)) ||
2848       (GNUNET_OK !=
2849        GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2850                                  &m->purpose, &m->signature, n->public_key)))
2851     {
2852       /* invalid signature */
2853       GNUNET_break_op (0);
2854       return;
2855     }
2856   t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2857   if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2858        (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2859       (t.value < n->decrypt_key_created.value))
2860     {
2861       /* this could rarely happen due to massive re-ordering of
2862          messages on the network level, but is most likely either
2863          a bug or some adversary messing with us.  Report. */
2864       GNUNET_break_op (0);
2865       return;
2866     }
2867 #if DEBUG_CORE
2868   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
2869               "Decrypting key material.\n");
2870 #endif  
2871   if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2872                                   &m->encrypted_key,
2873                                   &k,
2874                                   sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2875        != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2876       (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2877     {
2878       /* failed to decrypt !? */
2879       GNUNET_break_op (0);
2880       return;
2881     }
2882
2883   n->decrypt_key = k;
2884   if (n->decrypt_key_created.value != t.value)
2885     {
2886       /* fresh key, reset sequence numbers */
2887       n->last_sequence_number_received = 0;
2888       n->last_packets_bitmap = 0;
2889       n->decrypt_key_created = t;
2890     }
2891   sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2892   switch (n->status)
2893     {
2894     case PEER_STATE_DOWN:
2895       n->status = PEER_STATE_KEY_RECEIVED;
2896 #if DEBUG_CORE
2897       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2898                   "Responding to `%s' with my own key.\n", "SET_KEY");
2899 #endif
2900       send_key (n);
2901       break;
2902     case PEER_STATE_KEY_SENT:
2903     case PEER_STATE_KEY_RECEIVED:
2904       n->status = PEER_STATE_KEY_RECEIVED;
2905       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2906           (sender_status != PEER_STATE_KEY_CONFIRMED))
2907         {
2908 #if DEBUG_CORE
2909           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2910                       "Responding to `%s' with my own key (other peer has status %u).\n",
2911                       "SET_KEY", sender_status);
2912 #endif
2913           send_key (n);
2914         }
2915       break;
2916     case PEER_STATE_KEY_CONFIRMED:
2917       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2918           (sender_status != PEER_STATE_KEY_CONFIRMED))
2919         {         
2920 #if DEBUG_CORE
2921           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2922                       "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2923                       "SET_KEY", sender_status);
2924 #endif
2925           send_key (n);
2926         }
2927       break;
2928     default:
2929       GNUNET_break (0);
2930       break;
2931     }
2932   if (n->pending_ping != NULL)
2933     {
2934       ping = n->pending_ping;
2935       n->pending_ping = NULL;
2936       handle_ping (n, ping);
2937       GNUNET_free (ping);
2938     }
2939   if (n->pending_pong != NULL)
2940     {
2941       pong = n->pending_pong;
2942       n->pending_pong = NULL;
2943       handle_pong (n, pong);
2944       GNUNET_free (pong);
2945     }
2946 }
2947
2948
2949 /**
2950  * Send a P2P message to a client.
2951  *
2952  * @param sender who sent us the message?
2953  * @param client who should we give the message to?
2954  * @param m contains the message to transmit
2955  * @param msize number of bytes in buf to transmit
2956  */
2957 static void
2958 send_p2p_message_to_client (struct Neighbour *sender,
2959                             struct Client *client,
2960                             const void *m, size_t msize)
2961 {
2962   char buf[msize + sizeof (struct NotifyTrafficMessage)];
2963   struct NotifyTrafficMessage *ntm;
2964
2965 #if DEBUG_CORE
2966   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2967               "Core service passes message from `%4s' of type %u to client.\n",
2968               GNUNET_i2s(&sender->peer),
2969               ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2970 #endif
2971   ntm = (struct NotifyTrafficMessage *) buf;
2972   ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2973   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2974   ntm->distance = htonl (sender->last_distance);
2975   ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
2976   ntm->peer = sender->peer;
2977   memcpy (&ntm[1], m, msize);
2978   send_to_client (client, &ntm->header, GNUNET_YES);
2979 }
2980
2981
2982 /**
2983  * Deliver P2P message to interested clients.
2984  *
2985  * @param sender who sent us the message?
2986  * @param m the message
2987  * @param msize size of the message (including header)
2988  */
2989 static void
2990 deliver_message (struct Neighbour *sender,
2991                  const struct GNUNET_MessageHeader *m, size_t msize)
2992 {
2993   struct Client *cpos;
2994   uint16_t type;
2995   unsigned int tpos;
2996   int deliver_full;
2997   int dropped;
2998
2999   type = ntohs (m->type);
3000 #if DEBUG_CORE
3001   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3002               "Received encapsulated message of type %u from `%4s'\n",
3003               type,
3004               GNUNET_i2s (&sender->peer));
3005 #endif
3006   dropped = GNUNET_YES;
3007   cpos = clients;
3008   while (cpos != NULL)
3009     {
3010       deliver_full = GNUNET_NO;
3011       if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3012         deliver_full = GNUNET_YES;
3013       else
3014         {
3015           for (tpos = 0; tpos < cpos->tcnt; tpos++)
3016             {
3017               if (type != cpos->types[tpos])
3018                 continue;
3019               deliver_full = GNUNET_YES;
3020               break;
3021             }
3022         }
3023       if (GNUNET_YES == deliver_full)
3024         {
3025           send_p2p_message_to_client (sender, cpos, m, msize);
3026           dropped = GNUNET_NO;
3027         }
3028       else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3029         {
3030           send_p2p_message_to_client (sender, cpos, m,
3031                                       sizeof (struct GNUNET_MessageHeader));
3032         }
3033       cpos = cpos->next;
3034     }
3035   if (dropped == GNUNET_YES)
3036     {
3037 #if DEBUG_CORE
3038       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3039                   "Message of type %u from `%4s' not delivered to any client.\n",
3040                   type,
3041                   GNUNET_i2s (&sender->peer));
3042 #endif
3043       /* FIXME: stats... */
3044     }
3045 }
3046
3047
3048 /**
3049  * Align P2P message and then deliver to interested clients.
3050  *
3051  * @param sender who sent us the message?
3052  * @param buffer unaligned (!) buffer containing message
3053  * @param msize size of the message (including header)
3054  */
3055 static void
3056 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
3057 {
3058   char abuf[msize];
3059
3060   /* TODO: call to statistics? */
3061   memcpy (abuf, buffer, msize);
3062   deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
3063 }
3064
3065
3066 /**
3067  * Deliver P2P messages to interested clients.
3068  *
3069  * @param sender who sent us the message?
3070  * @param buffer buffer containing messages, can be modified
3071  * @param buffer_size size of the buffer (overall)
3072  * @param offset offset where messages in the buffer start
3073  */
3074 static void
3075 deliver_messages (struct Neighbour *sender,
3076                   const char *buffer, size_t buffer_size, size_t offset)
3077 {
3078   struct GNUNET_MessageHeader *mhp;
3079   struct GNUNET_MessageHeader mh;
3080   uint16_t msize;
3081   int need_align;
3082
3083   while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
3084     {
3085       if (0 != offset % sizeof (uint16_t))
3086         {
3087           /* outch, need to copy to access header */
3088           memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
3089           mhp = &mh;
3090         }
3091       else
3092         {
3093           /* can access header directly */
3094           mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
3095         }
3096       msize = ntohs (mhp->size);
3097       if (msize + offset > buffer_size)
3098         {
3099           /* malformed message, header says it is larger than what
3100              would fit into the overall buffer */
3101           GNUNET_break_op (0);
3102           break;
3103         }
3104 #if HAVE_UNALIGNED_64_ACCESS
3105       need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
3106 #else
3107       need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
3108 #endif
3109       if (GNUNET_YES == need_align)
3110         align_and_deliver (sender, &buffer[offset], msize);
3111       else
3112         deliver_message (sender,
3113                          (const struct GNUNET_MessageHeader *)
3114                          &buffer[offset], msize);
3115       offset += msize;
3116     }
3117 }
3118
3119
3120 /**
3121  * We received an encrypted message.  Decrypt, validate and
3122  * pass on to the appropriate clients.
3123  */
3124 static void
3125 handle_encrypted_message (struct Neighbour *n,
3126                           const struct EncryptedMessage *m)
3127 {
3128   size_t size = ntohs (m->header.size);
3129   char buf[size];
3130   struct EncryptedMessage *pt;  /* plaintext */
3131   GNUNET_HashCode ph;
3132   size_t off;
3133   uint32_t snum;
3134   struct GNUNET_TIME_Absolute t;
3135   GNUNET_HashCode iv;
3136
3137 #if DEBUG_CORE
3138   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3139               "Core service receives `%s' request from `%4s'.\n",
3140               "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3141 #endif  
3142   GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3143   /* decrypt */
3144   if (GNUNET_OK !=
3145       do_decrypt (n,
3146                   &iv,
3147                   &m->plaintext_hash,
3148                   &buf[ENCRYPTED_HEADER_SIZE], 
3149                   size - ENCRYPTED_HEADER_SIZE))
3150     return;
3151   pt = (struct EncryptedMessage *) buf;
3152
3153   /* validate hash */
3154   GNUNET_CRYPTO_hash (&pt->sequence_number,
3155                       size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3156   if (0 != memcmp (&ph, 
3157                    &pt->plaintext_hash, 
3158                    sizeof (GNUNET_HashCode)))
3159     {
3160       /* checksum failed */
3161       GNUNET_break_op (0);
3162       return;
3163     }
3164
3165   /* validate sequence number */
3166   snum = ntohl (pt->sequence_number);
3167   if (n->last_sequence_number_received == snum)
3168     {
3169       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3170                   "Received duplicate message, ignoring.\n");
3171       /* duplicate, ignore */
3172       return;
3173     }
3174   if ((n->last_sequence_number_received > snum) &&
3175       (n->last_sequence_number_received - snum > 32))
3176     {
3177       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3178                   "Received ancient out of sequence message, ignoring.\n");
3179       /* ancient out of sequence, ignore */
3180       return;
3181     }
3182   if (n->last_sequence_number_received > snum)
3183     {
3184       unsigned int rotbit =
3185         1 << (n->last_sequence_number_received - snum - 1);
3186       if ((n->last_packets_bitmap & rotbit) != 0)
3187         {
3188           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3189                       "Received duplicate message, ignoring.\n");
3190           /* duplicate, ignore */
3191           return;
3192         }
3193       n->last_packets_bitmap |= rotbit;
3194     }
3195   if (n->last_sequence_number_received < snum)
3196     {
3197       n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3198       n->last_sequence_number_received = snum;
3199     }
3200
3201   /* check timestamp */
3202   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3203   if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3204     {
3205       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3206                   _
3207                   ("Message received far too old (%llu ms). Content ignored.\n"),
3208                   GNUNET_TIME_absolute_get_duration (t).value);
3209       return;
3210     }
3211
3212   /* process decrypted message(s) */
3213   if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3214     {
3215 #if DEBUG_CORE_SET_QUOTA
3216       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3217                   "Received %u b/s as new inbound limit for peer `%4s'\n",
3218                   (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3219                   GNUNET_i2s (&n->peer));
3220 #endif
3221       n->bw_out_external_limit = pt->inbound_bw_limit;
3222       n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3223                                               n->bw_out_internal_limit);
3224       GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3225                                              n->bw_out);
3226       GNUNET_TRANSPORT_set_quota (transport,
3227                                   &n->peer,
3228                                   n->bw_in,
3229                                   n->bw_out,
3230                                   GNUNET_TIME_UNIT_FOREVER_REL,
3231                                   NULL, NULL); 
3232     }
3233   n->last_activity = GNUNET_TIME_absolute_get ();
3234   if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3235     GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3236   n->keep_alive_task 
3237     = GNUNET_SCHEDULER_add_delayed (sched, 
3238                                     GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3239                                     &send_keep_alive,
3240                                     n);
3241   off = sizeof (struct EncryptedMessage);
3242   deliver_messages (n, buf, size, off);
3243 }
3244
3245
3246 /**
3247  * Function called by the transport for each received message.
3248  *
3249  * @param cls closure
3250  * @param peer (claimed) identity of the other peer
3251  * @param message the message
3252  * @param latency estimated latency for communicating with the
3253  *             given peer (round-trip)
3254  * @param distance in overlay hops, as given by transport plugin
3255  */
3256 static void
3257 handle_transport_receive (void *cls,
3258                           const struct GNUNET_PeerIdentity *peer,
3259                           const struct GNUNET_MessageHeader *message,
3260                           struct GNUNET_TIME_Relative latency,
3261                           unsigned int distance)
3262 {
3263   struct Neighbour *n;
3264   struct GNUNET_TIME_Absolute now;
3265   int up;
3266   uint16_t type;
3267   uint16_t size;
3268
3269 #if DEBUG_CORE
3270   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3271               "Received message of type %u from `%4s', demultiplexing.\n",
3272               ntohs (message->type), GNUNET_i2s (peer));
3273 #endif
3274   n = find_neighbour (peer);
3275   if (n == NULL)
3276     n = create_neighbour (peer);
3277   if (n == NULL)
3278     return;   
3279   n->last_latency = latency;
3280   n->last_distance = distance;
3281   up = (n->status == PEER_STATE_KEY_CONFIRMED);
3282   type = ntohs (message->type);
3283   size = ntohs (message->size);
3284 #if DEBUG_HANDSHAKE
3285   fprintf (stderr,
3286            "Received message of type %u from `%4s'\n",
3287            type,
3288            GNUNET_i2s (peer));
3289 #endif
3290   switch (type)
3291     {
3292     case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3293       if (size != sizeof (struct SetKeyMessage))
3294         {
3295           GNUNET_break_op (0);
3296           return;
3297         }
3298       GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3299       handle_set_key (n, (const struct SetKeyMessage *) message);
3300       break;
3301     case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3302       if (size < sizeof (struct EncryptedMessage) +
3303           sizeof (struct GNUNET_MessageHeader))
3304         {
3305           GNUNET_break_op (0);
3306           return;
3307         }
3308       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3309           (n->status != PEER_STATE_KEY_CONFIRMED))
3310         {
3311           GNUNET_break_op (0);
3312           /* blacklist briefly (?); might help recover (?) */
3313           GNUNET_TRANSPORT_blacklist (sched, cfg,
3314                                       &n->peer, 
3315                                       GNUNET_TIME_UNIT_SECONDS,
3316                                       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3317                                                                      5),
3318                                       NULL, NULL);
3319           return;
3320         }
3321       handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3322       break;
3323     case GNUNET_MESSAGE_TYPE_CORE_PING:
3324       if (size != sizeof (struct PingMessage))
3325         {
3326           GNUNET_break_op (0);
3327           return;
3328         }
3329       GNUNET_STATISTICS_update (stats, gettext_noop ("# ping messages received"), 1, GNUNET_NO);
3330       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3331           (n->status != PEER_STATE_KEY_CONFIRMED))
3332         {
3333 #if DEBUG_CORE
3334           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3335                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3336                       "PING", GNUNET_i2s (&n->peer));
3337 #endif
3338           GNUNET_free_non_null (n->pending_ping);
3339           n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3340           memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3341           return;
3342         }
3343       handle_ping (n, (const struct PingMessage *) message);
3344       break;
3345     case GNUNET_MESSAGE_TYPE_CORE_PONG:
3346       if (size != sizeof (struct PongMessage))
3347         {
3348           GNUNET_break_op (0);
3349           return;
3350         }
3351       GNUNET_STATISTICS_update (stats, gettext_noop ("# pong messages received"), 1, GNUNET_NO);
3352       if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3353            (n->status != PEER_STATE_KEY_CONFIRMED) )
3354         {
3355 #if DEBUG_CORE
3356           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3357                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3358                       "PONG", GNUNET_i2s (&n->peer));
3359 #endif
3360           GNUNET_free_non_null (n->pending_pong);
3361           n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3362           memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3363           return;
3364         }
3365       handle_pong (n, (const struct PongMessage *) message);
3366       break;
3367     default:
3368       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3369                   _("Unsupported message of type %u received.\n"), type);
3370       return;
3371     }
3372   if (n->status == PEER_STATE_KEY_CONFIRMED)
3373     {
3374       now = GNUNET_TIME_absolute_get ();
3375       n->last_activity = now;
3376       if (!up)
3377         {
3378           GNUNET_STATISTICS_update (stats, gettext_noop ("# peers connected"), 1, GNUNET_NO);
3379           n->time_established = now;
3380         }
3381       if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3382         GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3383       n->keep_alive_task 
3384         = GNUNET_SCHEDULER_add_delayed (sched, 
3385                                         GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3386                                         &send_keep_alive,
3387                                         n);
3388     }
3389 }
3390
3391
3392 /**
3393  * Function that recalculates the bandwidth quota for the
3394  * given neighbour and transmits it to the transport service.
3395  * 
3396  * @param cls neighbour for the quota update
3397  * @param tc context
3398  */
3399 static void
3400 neighbour_quota_update (void *cls,
3401                         const struct GNUNET_SCHEDULER_TaskContext *tc)
3402 {
3403   struct Neighbour *n = cls;
3404   struct GNUNET_BANDWIDTH_Value32NBO q_in;
3405   double pref_rel;
3406   double share;
3407   unsigned long long distributable;
3408   uint64_t need_per_peer;
3409   uint64_t need_per_second;
3410   
3411   n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3412   /* calculate relative preference among all neighbours;
3413      divides by a bit more to avoid division by zero AND to
3414      account for possibility of new neighbours joining any time 
3415      AND to convert to double... */
3416   if (preference_sum == 0)
3417     {
3418       pref_rel = 1.0 / (double) neighbour_count;
3419     }
3420   else
3421     {
3422       pref_rel = n->current_preference / preference_sum;
3423     }
3424   need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3425                                                               GNUNET_TIME_UNIT_SECONDS);  
3426   need_per_second = need_per_peer * neighbour_count;
3427   distributable = 0;
3428   if (bandwidth_target_out_bps > need_per_second)
3429     distributable = bandwidth_target_out_bps - need_per_second;
3430   share = distributable * pref_rel;
3431   if (share + need_per_peer > ( (uint32_t)-1))
3432     q_in = GNUNET_BANDWIDTH_value_init ((uint32_t) -1);
3433   else
3434     q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3435   /* check if we want to disconnect for good due to inactivity */
3436   if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3437        (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3438     {
3439 #if DEBUG_CORE
3440       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3441                   "Forcing disconnect of `%4s' due to inactivity (?).\n",
3442                   GNUNET_i2s (&n->peer));
3443 #endif
3444       q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3445     }
3446 #if DEBUG_CORE_QUOTA
3447   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3448               "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3449               GNUNET_i2s (&n->peer),
3450               (unsigned int) ntohl (q_in.value__),
3451               bandwidth_target_out_bps,
3452               (unsigned int) ntohl (n->bw_in.value__),
3453               (unsigned int) ntohl (n->bw_out.value__),
3454               (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3455 #endif
3456   if (n->bw_in.value__ != q_in.value__) 
3457     {
3458       n->bw_in = q_in;
3459       GNUNET_TRANSPORT_set_quota (transport,
3460                                   &n->peer,
3461                                   n->bw_in,
3462                                   n->bw_out,
3463                                   GNUNET_TIME_UNIT_FOREVER_REL,
3464                                   NULL, NULL);
3465     }
3466   schedule_quota_update (n);
3467 }
3468
3469
3470 /**
3471  * Function called by transport to notify us that
3472  * a peer connected to us (on the network level).
3473  *
3474  * @param cls closure
3475  * @param peer the peer that connected
3476  * @param latency current latency of the connection
3477  * @param distance in overlay hops, as given by transport plugin
3478  */
3479 static void
3480 handle_transport_notify_connect (void *cls,
3481                                  const struct GNUNET_PeerIdentity *peer,
3482                                  struct GNUNET_TIME_Relative latency,
3483                                  unsigned int distance)
3484 {
3485   struct Neighbour *n;
3486   struct ConnectNotifyMessage cnm;
3487
3488   n = find_neighbour (peer);
3489   if (n != NULL)
3490     {
3491       if (n->is_connected)
3492         {
3493           /* duplicate connect notification!? */
3494           GNUNET_break (0);
3495           return;
3496         }
3497     }
3498   else
3499     {
3500       n = create_neighbour (peer);
3501     }
3502   n->is_connected = GNUNET_YES;      
3503   n->last_latency = latency;
3504   n->last_distance = distance;
3505   GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3506                                  n->bw_out,
3507                                  MAX_WINDOW_TIME_S);
3508   GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3509                                  n->bw_in,
3510                                  MAX_WINDOW_TIME_S);  
3511 #if DEBUG_CORE
3512   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3513               "Received connection from `%4s'.\n",
3514               GNUNET_i2s (&n->peer));
3515 #endif
3516   cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3517   cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3518   cnm.distance = htonl (n->last_distance);
3519   cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3520   cnm.peer = *peer;
3521   send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3522   GNUNET_TRANSPORT_set_quota (transport,
3523                               &n->peer,
3524                               n->bw_in,
3525                               n->bw_out,
3526                               GNUNET_TIME_UNIT_FOREVER_REL,
3527                               NULL, NULL);
3528   send_key (n); 
3529 }
3530
3531
3532 /**
3533  * Function called by transport telling us that a peer
3534  * disconnected.
3535  *
3536  * @param cls closure
3537  * @param peer the peer that disconnected
3538  */
3539 static void
3540 handle_transport_notify_disconnect (void *cls,
3541                                     const struct GNUNET_PeerIdentity *peer)
3542 {
3543   struct DisconnectNotifyMessage cnm;
3544   struct Neighbour *n;
3545
3546 #if DEBUG_CORE
3547   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3548               "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3549 #endif
3550   n = find_neighbour (peer);
3551   if (n == NULL)
3552     {
3553       GNUNET_break (0);
3554       return;
3555     }
3556   GNUNET_break (n->is_connected);
3557   cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3558   cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3559   cnm.peer = *peer;
3560   send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3561   n->is_connected = GNUNET_NO;
3562 }
3563
3564
3565 /**
3566  * Last task run during shutdown.  Disconnects us from
3567  * the transport.
3568  */
3569 static void
3570 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3571 {
3572   struct Neighbour *n;
3573   struct Client *c;
3574
3575 #if DEBUG_CORE
3576   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3577               "Core service shutting down.\n");
3578 #endif
3579   GNUNET_assert (transport != NULL);
3580   GNUNET_TRANSPORT_disconnect (transport);
3581   transport = NULL;
3582   while (NULL != (n = neighbours))
3583     {
3584       neighbours = n->next;
3585       GNUNET_assert (neighbour_count > 0);
3586       neighbour_count--;
3587       free_neighbour (n);
3588     }
3589   GNUNET_STATISTICS_set (stats, gettext_noop ("# active neighbours"), neighbour_count, GNUNET_NO);
3590   GNUNET_SERVER_notification_context_destroy (notifier);
3591   notifier = NULL;
3592   while (NULL != (c = clients))
3593     handle_client_disconnect (NULL, c->client_handle);
3594   if (my_private_key != NULL)
3595     GNUNET_CRYPTO_rsa_key_free (my_private_key);
3596   if (stats != NULL)
3597     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3598 }
3599
3600
3601 /**
3602  * Initiate core service.
3603  *
3604  * @param cls closure
3605  * @param s scheduler to use
3606  * @param serv the initialized server
3607  * @param c configuration to use
3608  */
3609 static void
3610 run (void *cls,
3611      struct GNUNET_SCHEDULER_Handle *s,
3612      struct GNUNET_SERVER_Handle *serv,
3613      const struct GNUNET_CONFIGURATION_Handle *c)
3614 {
3615   char *keyfile;
3616
3617   sched = s;
3618   cfg = c;  
3619   /* parse configuration */
3620   if (
3621        (GNUNET_OK !=
3622         GNUNET_CONFIGURATION_get_value_number (c,
3623                                                "CORE",
3624                                                "TOTAL_QUOTA_IN",
3625                                                &bandwidth_target_in_bps)) ||
3626        (GNUNET_OK !=
3627         GNUNET_CONFIGURATION_get_value_number (c,
3628                                                "CORE",
3629                                                "TOTAL_QUOTA_OUT",
3630                                                &bandwidth_target_out_bps)) ||
3631        (GNUNET_OK !=
3632         GNUNET_CONFIGURATION_get_value_filename (c,
3633                                                  "GNUNETD",
3634                                                  "HOSTKEY", &keyfile)))
3635     {
3636       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3637                   _
3638                   ("Core service is lacking key configuration settings.  Exiting.\n"));
3639       GNUNET_SCHEDULER_shutdown (s);
3640       return;
3641     }
3642   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3643   GNUNET_free (keyfile);
3644   if (my_private_key == NULL)
3645     {
3646       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3647                   _("Core service could not access hostkey.  Exiting.\n"));
3648       GNUNET_SCHEDULER_shutdown (s);
3649       return;
3650     }
3651   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3652   GNUNET_CRYPTO_hash (&my_public_key,
3653                       sizeof (my_public_key), &my_identity.hashPubKey);
3654   /* setup notification */
3655   server = serv;
3656   notifier = GNUNET_SERVER_notification_context_create (server, 
3657                                                         MAX_NOTIFY_QUEUE);
3658   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3659   /* setup transport connection */
3660   transport = GNUNET_TRANSPORT_connect (sched,
3661                                         cfg,
3662                                         NULL,
3663                                         &handle_transport_receive,
3664                                         &handle_transport_notify_connect,
3665                                         &handle_transport_notify_disconnect);
3666   GNUNET_assert (NULL != transport);
3667   stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3668   GNUNET_SCHEDULER_add_delayed (sched,
3669                                 GNUNET_TIME_UNIT_FOREVER_REL,
3670                                 &cleaning_task, NULL);
3671   /* process client requests */
3672   GNUNET_SERVER_add_handlers (server, handlers);
3673   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3674               _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3675 }
3676
3677
3678
3679 /**
3680  * The main function for the transport service.
3681  *
3682  * @param argc number of arguments from the command line
3683  * @param argv command line arguments
3684  * @return 0 ok, 1 on error
3685  */
3686 int
3687 main (int argc, char *const *argv)
3688 {
3689   return (GNUNET_OK ==
3690           GNUNET_SERVICE_run (argc,
3691                               argv,
3692                               "core",
3693                               GNUNET_SERVICE_OPTION_NONE,
3694                               &run, NULL)) ? 0 : 1;
3695 }
3696
3697 /* end of gnunet-service-core.c */