stuff
[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 ("# established sessions"), -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   m = n->encrypted_head;
1323   if (m == NULL)
1324     return 0;
1325   GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1326                                n->encrypted_tail,
1327                                m);
1328   ret = 0;
1329   cbuf = buf;
1330   if (buf != NULL)
1331     {
1332       GNUNET_assert (size >= m->size);
1333       memcpy (cbuf, &m[1], m->size);
1334       ret = m->size;
1335       GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1336                                         m->size);
1337 #if DEBUG_CORE
1338       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1339                   "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1340                   ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1341                   ret, GNUNET_i2s (&n->peer));
1342 #endif
1343       process_encrypted_neighbour_queue (n);
1344     }
1345   else
1346     {
1347 #if DEBUG_CORE
1348       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1349                   "Transmission of message of type %u and size %u failed\n",
1350                   ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1351                   m->size);
1352 #endif
1353     }
1354   GNUNET_free (m);
1355   consider_free_neighbour (n);
1356   return ret;
1357 }
1358
1359
1360 /**
1361  * Check if we have plaintext messages for the specified neighbour
1362  * pending, and if so, consider batching and encrypting them (and
1363  * then trigger processing of the encrypted queue if needed).
1364  *
1365  * @param n neighbour to check.
1366  */
1367 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1368
1369
1370 /**
1371  * Check if we have encrypted messages for the specified neighbour
1372  * pending, and if so, check with the transport about sending them
1373  * out.
1374  *
1375  * @param n neighbour to check.
1376  */
1377 static void
1378 process_encrypted_neighbour_queue (struct Neighbour *n)
1379 {
1380   struct MessageEntry *m;
1381  
1382   if (n->th != NULL)
1383     return;  /* request already pending */
1384   m = n->encrypted_head;
1385   if (m == NULL)
1386     {
1387       /* encrypted queue empty, try plaintext instead */
1388       process_plaintext_neighbour_queue (n);
1389       return;
1390     }
1391 #if DEBUG_CORE
1392   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1393               "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1394               m->size,
1395               GNUNET_i2s (&n->peer),
1396               GNUNET_TIME_absolute_get_remaining (m->deadline).
1397               value);
1398 #endif
1399   n->th =
1400     GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1401                                             m->size,
1402                                             m->priority,
1403                                             GNUNET_TIME_absolute_get_remaining
1404                                             (m->deadline),
1405                                             &notify_encrypted_transmit_ready,
1406                                             n);
1407   if (n->th == NULL)
1408     {
1409       /* message request too large or duplicate request */
1410       GNUNET_break (0);
1411       /* discard encrypted message */
1412       GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1413                                    n->encrypted_tail,
1414                                    m);
1415       GNUNET_free (m);
1416       process_encrypted_neighbour_queue (n);
1417     }
1418 }
1419
1420
1421 /**
1422  * Decrypt size bytes from in and write the result to out.  Use the
1423  * key for inbound traffic of the given neighbour.  This function does
1424  * NOT do any integrity-checks on the result.
1425  *
1426  * @param n neighbour we are receiving from
1427  * @param iv initialization vector to use
1428  * @param in ciphertext
1429  * @param out plaintext
1430  * @param size size of in/out
1431  * @return GNUNET_OK on success
1432  */
1433 static int
1434 do_decrypt (struct Neighbour *n,
1435             const GNUNET_HashCode * iv,
1436             const void *in, void *out, size_t size)
1437 {
1438   if (size != (uint16_t) size)
1439     {
1440       GNUNET_break (0);
1441       return GNUNET_NO;
1442     }
1443   if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1444       (n->status != PEER_STATE_KEY_CONFIRMED))
1445     {
1446       GNUNET_break_op (0);
1447       return GNUNET_SYSERR;
1448     }
1449   if (size !=
1450       GNUNET_CRYPTO_aes_decrypt (in,
1451                                  (uint16_t) size,
1452                                  &n->decrypt_key,
1453                                  (const struct
1454                                   GNUNET_CRYPTO_AesInitializationVector *) iv,
1455                                  out))
1456     {
1457       GNUNET_break (0);
1458       return GNUNET_SYSERR;
1459     }
1460   GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1461 #if DEBUG_CORE
1462   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1463               "Decrypted %u bytes from `%4s' using key %u\n",
1464               size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1465 #endif
1466   return GNUNET_OK;
1467 }
1468
1469
1470 /**
1471  * Select messages for transmission.  This heuristic uses a combination
1472  * of earliest deadline first (EDF) scheduling (with bounded horizon)
1473  * and priority-based discard (in case no feasible schedule exist) and
1474  * speculative optimization (defer any kind of transmission until
1475  * we either create a batch of significant size, 25% of max, or until
1476  * we are close to a deadline).  Furthermore, when scheduling the
1477  * heuristic also packs as many messages into the batch as possible,
1478  * starting with those with the earliest deadline.  Yes, this is fun.
1479  *
1480  * @param n neighbour to select messages from
1481  * @param size number of bytes to select for transmission
1482  * @param retry_time set to the time when we should try again
1483  *        (only valid if this function returns zero)
1484  * @return number of bytes selected, or 0 if we decided to
1485  *         defer scheduling overall; in that case, retry_time is set.
1486  */
1487 static size_t
1488 select_messages (struct Neighbour *n,
1489                  size_t size, struct GNUNET_TIME_Relative *retry_time)
1490 {
1491   struct MessageEntry *pos;
1492   struct MessageEntry *min;
1493   struct MessageEntry *last;
1494   unsigned int min_prio;
1495   struct GNUNET_TIME_Absolute t;
1496   struct GNUNET_TIME_Absolute now;
1497   struct GNUNET_TIME_Relative delta;
1498   uint64_t avail;
1499   struct GNUNET_TIME_Relative slack;     /* how long could we wait before missing deadlines? */
1500   size_t off;
1501   uint64_t tsize;
1502   unsigned int queue_size;
1503   int discard_low_prio;
1504
1505   GNUNET_assert (NULL != n->messages);
1506   now = GNUNET_TIME_absolute_get ();
1507   /* last entry in linked list of messages processed */
1508   last = NULL;
1509   /* should we remove the entry with the lowest
1510      priority from consideration for scheduling at the
1511      end of the loop? */
1512   queue_size = 0;
1513   tsize = 0;
1514   pos = n->messages;
1515   while (pos != NULL)
1516     {
1517       queue_size++;
1518       tsize += pos->size;
1519       pos = pos->next;
1520     }
1521   discard_low_prio = GNUNET_YES;
1522   while (GNUNET_YES == discard_low_prio)
1523     {
1524       min = NULL;
1525       min_prio = -1;
1526       discard_low_prio = GNUNET_NO;
1527       /* calculate number of bytes available for transmission at time "t" */
1528       avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1529       t = now;
1530       /* how many bytes have we (hypothetically) scheduled so far */
1531       off = 0;
1532       /* maximum time we can wait before transmitting anything
1533          and still make all of our deadlines */
1534       slack = MAX_CORK_DELAY;
1535       pos = n->messages;
1536       /* note that we use "*2" here because we want to look
1537          a bit further into the future; much more makes no
1538          sense since new message might be scheduled in the
1539          meantime... */
1540       while ((pos != NULL) && (off < size * 2))
1541         {         
1542           if (pos->do_transmit == GNUNET_YES)
1543             {
1544               /* already removed from consideration */
1545               pos = pos->next;
1546               continue;
1547             }
1548           if (discard_low_prio == GNUNET_NO)
1549             {
1550               delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1551               if (delta.value > 0)
1552                 {
1553                   // FIXME: HUH? Check!
1554                   t = pos->deadline;
1555                   avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1556                                                                        delta);
1557                 }
1558               if (avail < pos->size)
1559                 {
1560                   // FIXME: HUH? Check!
1561                   discard_low_prio = GNUNET_YES;        /* we could not schedule this one! */
1562                 }
1563               else
1564                 {
1565                   avail -= pos->size;
1566                   /* update slack, considering both its absolute deadline
1567                      and relative deadlines caused by other messages
1568                      with their respective load */
1569                   slack = GNUNET_TIME_relative_min (slack,
1570                                                     GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1571                                                                                           avail));
1572                   if (pos->deadline.value <= now.value) 
1573                     {
1574                       /* now or never */
1575                       slack = GNUNET_TIME_UNIT_ZERO;
1576                     }
1577                   else if (GNUNET_YES == pos->got_slack)
1578                     {
1579                       /* should be soon now! */
1580                       slack = GNUNET_TIME_relative_min (slack,
1581                                                         GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1582                     }
1583                   else
1584                     {
1585                       slack =
1586                         GNUNET_TIME_relative_min (slack, 
1587                                                   GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1588                       pos->got_slack = GNUNET_YES;
1589                       pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1590                                                                       GNUNET_TIME_relative_to_absolute (MAX_CORK_DELAY));
1591                     }
1592                 }
1593             }
1594           off += pos->size;
1595           t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1596           if (pos->priority <= min_prio)
1597             {
1598               /* update min for discard */
1599               min_prio = pos->priority;
1600               min = pos;
1601             }
1602           pos = pos->next;
1603         }
1604       if (discard_low_prio)
1605         {
1606           GNUNET_assert (min != NULL);
1607           /* remove lowest-priority entry from consideration */
1608           min->do_transmit = GNUNET_YES;        /* means: discard (for now) */
1609         }
1610       last = pos;
1611     }
1612   /* guard against sending "tiny" messages with large headers without
1613      urgent deadlines */
1614   if ( (slack.value > 0) && 
1615        (size > 4 * off) &&
1616        (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1617     {
1618       /* less than 25% of message would be filled with deadlines still
1619          being met if we delay by one second or more; so just wait for
1620          more data; but do not wait longer than 1s (since we don't want
1621          to delay messages for a really long time either). */
1622       *retry_time = MAX_CORK_DELAY;
1623       /* reset do_transmit values for next time */
1624       while (pos != last)
1625         {
1626           pos->do_transmit = GNUNET_NO;   
1627           pos = pos->next;
1628         }
1629 #if DEBUG_CORE
1630       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1631                   "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1632                   (unsigned long long) slack.value,
1633                   (unsigned int) off,
1634                   (unsigned int) size);
1635 #endif
1636       return 0;
1637     }
1638   /* select marked messages (up to size) for transmission */
1639   off = 0;
1640   pos = n->messages;
1641   while (pos != last)
1642     {
1643       if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1644         {
1645           pos->do_transmit = GNUNET_YES;        /* mark for transmission */
1646           off += pos->size;
1647           size -= pos->size;
1648         }
1649       else
1650         pos->do_transmit = GNUNET_NO;   /* mark for not transmitting! */
1651       pos = pos->next;
1652     }
1653 #if DEBUG_CORE
1654   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1655               "Selected %u/%u bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1656               off, tsize,
1657               queue_size, MAX_PEER_QUEUE_SIZE,
1658               GNUNET_i2s (&n->peer));
1659 #endif
1660   return off;
1661 }
1662
1663
1664 /**
1665  * Batch multiple messages into a larger buffer.
1666  *
1667  * @param n neighbour to take messages from
1668  * @param buf target buffer
1669  * @param size size of buf
1670  * @param deadline set to transmission deadline for the result
1671  * @param retry_time set to the time when we should try again
1672  *        (only valid if this function returns zero)
1673  * @param priority set to the priority of the batch
1674  * @return number of bytes written to buf (can be zero)
1675  */
1676 static size_t
1677 batch_message (struct Neighbour *n,
1678                char *buf,
1679                size_t size,
1680                struct GNUNET_TIME_Absolute *deadline,
1681                struct GNUNET_TIME_Relative *retry_time,
1682                unsigned int *priority)
1683 {
1684   char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1685   struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1686   struct MessageEntry *pos;
1687   struct MessageEntry *prev;
1688   struct MessageEntry *next;
1689   size_t ret;
1690   
1691   ret = 0;
1692   *priority = 0;
1693   *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1694   *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1695   if (0 == select_messages (n, size, retry_time))
1696     {
1697 #if DEBUG_CORE
1698       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1699                   "No messages selected, will try again in %llu ms\n",
1700                   retry_time->value);
1701 #endif
1702       return 0;
1703     }
1704   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1705   ntm->distance = htonl (n->last_distance);
1706   ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1707   ntm->peer = n->peer;
1708   
1709   pos = n->messages;
1710   prev = NULL;
1711   while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1712     {
1713       next = pos->next;
1714       if (GNUNET_YES == pos->do_transmit)
1715         {
1716           GNUNET_assert (pos->size <= size);
1717           /* do notifications */
1718           /* FIXME: track if we have *any* client that wants
1719              full notifications and only do this if that is
1720              actually true */
1721           if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1722             {
1723               memcpy (&ntm[1], &pos[1], pos->size);
1724               ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) + 
1725                                         sizeof (struct GNUNET_MessageHeader));
1726               send_to_all_clients (&ntm->header,
1727                                    GNUNET_YES,
1728                                    GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1729             }
1730           else
1731             {
1732               /* message too large for 'full' notifications, we do at
1733                  least the 'hdr' type */
1734               memcpy (&ntm[1],
1735                       &pos[1],
1736                       sizeof (struct GNUNET_MessageHeader));
1737             }
1738           ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) + 
1739                                     pos->size);
1740           send_to_all_clients (&ntm->header,
1741                                GNUNET_YES,
1742                                GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);   
1743 #if DEBUG_HANDSHAKE
1744           fprintf (stderr,
1745                    "Encrypting message of type %u\n",
1746                    ntohs(((struct GNUNET_MessageHeader*)&pos[1])->type));
1747 #endif
1748           /* copy for encrypted transmission */
1749           memcpy (&buf[ret], &pos[1], pos->size);
1750           ret += pos->size;
1751           size -= pos->size;
1752           *priority += pos->priority;
1753 #if DEBUG_CORE
1754           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1755                       "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1756                       pos->size,
1757                       GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1758 #endif
1759           deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1760           GNUNET_free (pos);
1761           if (prev == NULL)
1762             n->messages = next;
1763           else
1764             prev->next = next;
1765         }
1766       else
1767         {
1768           prev = pos;
1769         }
1770       pos = next;
1771     }
1772 #if DEBUG_CORE
1773   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1774               "Deadline for message batch is %llu ms\n",
1775               GNUNET_TIME_absolute_get_remaining (*deadline).value);
1776 #endif
1777   return ret;
1778 }
1779
1780
1781 /**
1782  * Remove messages with deadlines that have long expired from
1783  * the queue.
1784  *
1785  * @param n neighbour to inspect
1786  */
1787 static void
1788 discard_expired_messages (struct Neighbour *n)
1789 {
1790   struct MessageEntry *prev;
1791   struct MessageEntry *next;
1792   struct MessageEntry *pos;
1793   struct GNUNET_TIME_Absolute now;
1794   struct GNUNET_TIME_Relative delta;
1795
1796   now = GNUNET_TIME_absolute_get ();
1797   prev = NULL;
1798   pos = n->messages;
1799   while (pos != NULL) 
1800     {
1801       next = pos->next;
1802       delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1803       if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1804         {
1805 #if DEBUG_CORE
1806           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1807                       "Message is %llu ms past due, discarding.\n",
1808                       delta.value);
1809 #endif
1810           if (prev == NULL)
1811             n->messages = next;
1812           else
1813             prev->next = next;
1814           GNUNET_free (pos);
1815         }
1816       else
1817         prev = pos;
1818       pos = next;
1819     }
1820 }
1821
1822
1823 /**
1824  * Signature of the main function of a task.
1825  *
1826  * @param cls closure
1827  * @param tc context information (why was this task triggered now)
1828  */
1829 static void
1830 retry_plaintext_processing (void *cls,
1831                             const struct GNUNET_SCHEDULER_TaskContext *tc)
1832 {
1833   struct Neighbour *n = cls;
1834
1835   n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1836   process_plaintext_neighbour_queue (n);
1837 }
1838
1839
1840 /**
1841  * Send our key (and encrypted PING) to the other peer.
1842  *
1843  * @param n the other peer
1844  */
1845 static void send_key (struct Neighbour *n);
1846
1847 /**
1848  * Task that will retry "send_key" if our previous attempt failed
1849  * to yield a PONG.
1850  */
1851 static void
1852 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1853 {
1854   struct Neighbour *n = cls;
1855
1856 #if DEBUG_CORE
1857   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1858               "Retrying key transmission to `%4s'\n",
1859               GNUNET_i2s (&n->peer));
1860 #endif
1861   n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1862   n->set_key_retry_frequency =
1863     GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1864   send_key (n);
1865 }
1866
1867
1868 /**
1869  * Check if we have plaintext messages for the specified neighbour
1870  * pending, and if so, consider batching and encrypting them (and
1871  * then trigger processing of the encrypted queue if needed).
1872  *
1873  * @param n neighbour to check.
1874  */
1875 static void
1876 process_plaintext_neighbour_queue (struct Neighbour *n)
1877 {
1878   char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE];        /* plaintext */
1879   size_t used;
1880   size_t esize;
1881   struct EncryptedMessage *em;  /* encrypted message */
1882   struct EncryptedMessage *ph;  /* plaintext header */
1883   struct MessageEntry *me;
1884   unsigned int priority;
1885   struct GNUNET_TIME_Absolute deadline;
1886   struct GNUNET_TIME_Relative retry_time;
1887   GNUNET_HashCode iv;
1888
1889   if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1890     {
1891       GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1892       n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1893     }
1894   switch (n->status)
1895     {
1896     case PEER_STATE_DOWN:
1897       send_key (n);
1898 #if DEBUG_CORE
1899       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1900                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1901                   GNUNET_i2s(&n->peer));
1902 #endif
1903       return;
1904     case PEER_STATE_KEY_SENT:
1905       if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1906         n->retry_set_key_task
1907           = GNUNET_SCHEDULER_add_delayed (sched,
1908                                           n->set_key_retry_frequency,
1909                                           &set_key_retry_task, n);    
1910 #if DEBUG_CORE
1911       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1912                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1913                   GNUNET_i2s(&n->peer));
1914 #endif
1915       return;
1916     case PEER_STATE_KEY_RECEIVED:
1917       if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)        
1918         n->retry_set_key_task
1919           = GNUNET_SCHEDULER_add_delayed (sched,
1920                                           n->set_key_retry_frequency,
1921                                           &set_key_retry_task, n);        
1922 #if DEBUG_CORE
1923       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1924                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1925                   GNUNET_i2s(&n->peer));
1926 #endif
1927       return;
1928     case PEER_STATE_KEY_CONFIRMED:
1929       /* ready to continue */
1930       break;
1931     }
1932   discard_expired_messages (n);
1933   if (n->messages == NULL)
1934     {
1935 #if DEBUG_CORE
1936       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1937                   "Plaintext message queue for `%4s' is empty.\n",
1938                   GNUNET_i2s(&n->peer));
1939 #endif
1940       return;                   /* no pending messages */
1941     }
1942   if (n->encrypted_head != NULL)
1943     {
1944 #if DEBUG_CORE
1945       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1946                   "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1947                   GNUNET_i2s(&n->peer));
1948 #endif
1949       return;                   /* wait for messages already encrypted to be
1950                                    processed first! */
1951     }
1952   ph = (struct EncryptedMessage *) pbuf;
1953   deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1954   priority = 0;
1955   used = sizeof (struct EncryptedMessage);
1956   used += batch_message (n,
1957                          &pbuf[used],
1958                          MAX_ENCRYPTED_MESSAGE_SIZE - used,
1959                          &deadline, &retry_time, &priority);
1960   if (used == sizeof (struct EncryptedMessage))
1961     {
1962 #if DEBUG_CORE
1963       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1964                   "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1965                   GNUNET_i2s(&n->peer));
1966 #endif
1967       /* no messages selected for sending, try again later... */
1968       n->retry_plaintext_task =
1969         GNUNET_SCHEDULER_add_delayed (sched,
1970                                       retry_time,
1971                                       &retry_plaintext_processing, n);
1972       return;
1973     }
1974 #if DEBUG_CORE_QUOTA
1975   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1976               "Sending %u b/s as new limit to peer `%4s'\n",
1977               (unsigned int) ntohl (n->bw_in.value__),
1978               GNUNET_i2s (&n->peer));
1979 #endif
1980   ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1));
1981   ph->sequence_number = htonl (++n->last_sequence_number_sent);
1982   ph->inbound_bw_limit = n->bw_in;
1983   ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1984
1985   /* setup encryption message header */
1986   me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1987   me->deadline = deadline;
1988   me->priority = priority;
1989   me->size = used;
1990   em = (struct EncryptedMessage *) &me[1];
1991   em->header.size = htons (used);
1992   em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1993   em->iv_seed = ph->iv_seed;
1994   esize = used - ENCRYPTED_HEADER_SIZE;
1995   GNUNET_CRYPTO_hash (&ph->sequence_number,
1996                       esize - sizeof (GNUNET_HashCode), 
1997                       &ph->plaintext_hash);
1998   GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
1999   /* encrypt */
2000 #if DEBUG_CORE
2001   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2002               "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2003               esize,
2004               GNUNET_i2s(&n->peer),
2005               (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2006 #endif
2007   GNUNET_assert (GNUNET_OK ==
2008                  do_encrypt (n,
2009                              &iv,
2010                              &ph->plaintext_hash,
2011                              &em->plaintext_hash, esize));
2012   /* append to transmission list */
2013   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2014                                      n->encrypted_tail,
2015                                      n->encrypted_tail,
2016                                      me);
2017   process_encrypted_neighbour_queue (n);
2018 }
2019
2020
2021 /**
2022  * Function that recalculates the bandwidth quota for the
2023  * given neighbour and transmits it to the transport service.
2024  * 
2025  * @param cls neighbour for the quota update
2026  * @param tc context
2027  */
2028 static void
2029 neighbour_quota_update (void *cls,
2030                         const struct GNUNET_SCHEDULER_TaskContext *tc);
2031
2032
2033 /**
2034  * Schedule the task that will recalculate the bandwidth
2035  * quota for this peer (and possibly force a disconnect of
2036  * idle peers by calculating a bandwidth of zero).
2037  */
2038 static void
2039 schedule_quota_update (struct Neighbour *n)
2040 {
2041   GNUNET_assert (n->quota_update_task ==
2042                  GNUNET_SCHEDULER_NO_TASK);
2043   n->quota_update_task
2044     = GNUNET_SCHEDULER_add_delayed (sched,
2045                                     QUOTA_UPDATE_FREQUENCY,
2046                                     &neighbour_quota_update,
2047                                     n);
2048 }
2049
2050
2051 /**
2052  * Initialize a new 'struct Neighbour'.
2053  *
2054  * @param pid ID of the new neighbour
2055  * @return handle for the new neighbour
2056  */
2057 static struct Neighbour *
2058 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2059 {
2060   struct Neighbour *n;
2061   struct GNUNET_TIME_Absolute now;
2062
2063   n = GNUNET_malloc (sizeof (struct Neighbour));
2064   n->next = neighbours;
2065   neighbours = n;
2066   neighbour_count++;
2067   GNUNET_STATISTICS_set (stats, gettext_noop ("# active neighbours"), neighbour_count, GNUNET_NO);
2068   n->peer = *pid;
2069   GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2070   now = GNUNET_TIME_absolute_get ();
2071   n->encrypt_key_created = now;
2072   n->last_activity = now;
2073   n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2074   n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2075   n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2076   n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init ((uint32_t) - 1);
2077   n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2078   n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2079                                                 (uint32_t) - 1);
2080   neighbour_quota_update (n, NULL);
2081   return n;
2082 }
2083
2084
2085 /**
2086  * Handle CORE_SEND request.
2087  *
2088  * @param cls unused
2089  * @param client the client issuing the request
2090  * @param message the "struct SendMessage"
2091  */
2092 static void
2093 handle_client_send (void *cls,
2094                     struct GNUNET_SERVER_Client *client,
2095                     const struct GNUNET_MessageHeader *message)
2096 {
2097   const struct SendMessage *sm;
2098   struct Neighbour *n;
2099   struct MessageEntry *prev;
2100   struct MessageEntry *pos;
2101   struct MessageEntry *e; 
2102   struct MessageEntry *min_prio_entry;
2103   struct MessageEntry *min_prio_prev;
2104   unsigned int min_prio;
2105   unsigned int queue_size;
2106   uint16_t msize;
2107
2108   msize = ntohs (message->size);
2109   if (msize <
2110       sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2111     {
2112       GNUNET_break (0);
2113       if (client != NULL)
2114         GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2115       return;
2116     }
2117   sm = (const struct SendMessage *) message;
2118   msize -= sizeof (struct SendMessage);
2119   n = find_neighbour (&sm->peer);
2120   if (n == NULL)
2121     n = create_neighbour (&sm->peer);
2122 #if DEBUG_CORE
2123   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2124               "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2125               "SEND",
2126               msize, 
2127               GNUNET_i2s (&sm->peer));
2128 #endif
2129   /* bound queue size */
2130   discard_expired_messages (n);
2131   min_prio = (unsigned int) -1;
2132   min_prio_entry = NULL;
2133   min_prio_prev = NULL;
2134   queue_size = 0;
2135   prev = NULL;
2136   pos = n->messages;
2137   while (pos != NULL) 
2138     {
2139       if (pos->priority < min_prio)
2140         {
2141           min_prio_entry = pos;
2142           min_prio_prev = prev;
2143           min_prio = pos->priority;
2144         }
2145       queue_size++;
2146       prev = pos;
2147       pos = pos->next;
2148     }
2149   if (queue_size >= MAX_PEER_QUEUE_SIZE)
2150     {
2151       /* queue full */
2152       if (ntohl(sm->priority) <= min_prio)
2153         {
2154           /* discard new entry */
2155 #if DEBUG_CORE
2156           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2157                       "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2158                       queue_size,
2159                       MAX_PEER_QUEUE_SIZE,
2160                       msize,
2161                       ntohs (message->type));
2162 #endif
2163           if (client != NULL)
2164             GNUNET_SERVER_receive_done (client, GNUNET_OK);
2165           return;
2166         }
2167       /* discard "min_prio_entry" */
2168 #if DEBUG_CORE
2169       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2170                   "Queue full, discarding existing older request\n");
2171 #endif
2172       if (min_prio_prev == NULL)
2173         n->messages = min_prio_entry->next;
2174       else
2175         min_prio_prev->next = min_prio_entry->next;      
2176       GNUNET_free (min_prio_entry);     
2177     }
2178
2179 #if DEBUG_CORE
2180   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2181               "Adding transmission request for `%4s' of size %u to queue\n",
2182               GNUNET_i2s (&sm->peer),
2183               msize);
2184 #endif  
2185   e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2186   e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2187   e->priority = ntohl (sm->priority);
2188   e->size = msize;
2189   memcpy (&e[1], &sm[1], msize);
2190
2191   /* insert, keep list sorted by deadline */
2192   prev = NULL;
2193   pos = n->messages;
2194   while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2195     {
2196       prev = pos;
2197       pos = pos->next;
2198     }
2199   if (prev == NULL)
2200     n->messages = e;
2201   else
2202     prev->next = e;
2203   e->next = pos;
2204
2205   /* consider scheduling now */
2206   process_plaintext_neighbour_queue (n);
2207   if (client != NULL)
2208     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2209 }
2210
2211
2212 /**
2213  * Function called when the transport service is ready to
2214  * receive a message.  Only resets 'n->th' to NULL.
2215  *
2216  * @param cls neighbour to use message from
2217  * @param size number of bytes we can transmit
2218  * @param buf where to copy the message
2219  * @return number of bytes transmitted
2220  */
2221 static size_t
2222 notify_transport_connect_done (void *cls, size_t size, void *buf)
2223 {
2224   struct Neighbour *n = cls;
2225
2226   n->th = NULL;
2227   if (buf == NULL)
2228     {
2229       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2230                   _("Failed to connect to `%4s': transport failed to connect\n"),
2231                   GNUNET_i2s (&n->peer));
2232       return 0;
2233     }
2234   send_key (n);
2235   return 0;
2236 }
2237
2238
2239 /**
2240  * Handle CORE_REQUEST_CONNECT request.
2241  *
2242  * @param cls unused
2243  * @param client the client issuing the request
2244  * @param message the "struct ConnectMessage"
2245  */
2246 static void
2247 handle_client_request_connect (void *cls,
2248                                struct GNUNET_SERVER_Client *client,
2249                                const struct GNUNET_MessageHeader *message)
2250 {
2251   const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2252   struct Neighbour *n;
2253   struct GNUNET_TIME_Relative timeout;
2254
2255   if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2256     {
2257       GNUNET_break (0);
2258       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2259       return;
2260     }
2261   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2262   n = find_neighbour (&cm->peer);
2263   if (n == NULL)
2264     n = create_neighbour (&cm->peer);
2265   if ( (n->is_connected) ||
2266        (n->th != NULL) )
2267     return; /* already connected, or at least trying */
2268   GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2269 #if DEBUG_CORE
2270   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2271               "Core received `%s' request for `%4s', will try to establish connection\n",
2272               "REQUEST_CONNECT",
2273               GNUNET_i2s (&cm->peer));
2274 #endif
2275   timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2276   /* ask transport to connect to the peer */
2277   n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2278                                                   &cm->peer,
2279                                                   sizeof (struct GNUNET_MessageHeader), 0,
2280                                                   timeout,
2281                                                   &notify_transport_connect_done,
2282                                                   n);
2283   GNUNET_break (NULL != n->th);
2284 }
2285
2286
2287 /**
2288  * List of handlers for the messages understood by this
2289  * service.
2290  */
2291 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2292   {&handle_client_init, NULL,
2293    GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2294   {&handle_client_request_info, NULL,
2295    GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2296    sizeof (struct RequestInfoMessage)},
2297   {&handle_client_send, NULL,
2298    GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2299   {&handle_client_request_connect, NULL,
2300    GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2301    sizeof (struct ConnectMessage)},
2302   {NULL, NULL, 0, 0}
2303 };
2304
2305
2306 /**
2307  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
2308  * the neighbour's struct and retry send_key.  Or, if we did not get a
2309  * HELLO, just do nothing.
2310  *
2311  * @param cls the 'struct Neighbour' to retry sending the key for
2312  * @param peer the peer for which this is the HELLO
2313  * @param hello HELLO message of that peer
2314  * @param trust amount of trust we currently have in that peer
2315  */
2316 static void
2317 process_hello_retry_send_key (void *cls,
2318                               const struct GNUNET_PeerIdentity *peer,
2319                               const struct GNUNET_HELLO_Message *hello,
2320                               uint32_t trust)
2321 {
2322   struct Neighbour *n = cls;
2323
2324   if (peer == NULL)
2325     {
2326 #if DEBUG_CORE
2327       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2328                   "Entered `process_hello_retry_send_key' and `peer' is NULL!\n");
2329 #endif
2330       n->pitr = NULL;
2331       if (n->public_key != NULL)
2332         {
2333           GNUNET_STATISTICS_update (stats,
2334                                     gettext_noop ("# SETKEY messages deferred (need public key)"), 
2335                                     -1, 
2336                                     GNUNET_NO);
2337           send_key (n);
2338         }
2339       else
2340         {
2341           GNUNET_STATISTICS_update (stats,
2342                                     gettext_noop ("# Delayed connecting due to lack of public key"),
2343                                     1,
2344                                     GNUNET_NO);      
2345           if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2346             n->retry_set_key_task
2347               = GNUNET_SCHEDULER_add_delayed (sched,
2348                                               n->set_key_retry_frequency,
2349                                               &set_key_retry_task, n);
2350         }
2351       return;
2352     }
2353
2354 #if DEBUG_CORE
2355   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2356               "Entered `process_hello_retry_send_key' for peer `%4s'\n",
2357               GNUNET_i2s (peer));
2358 #endif
2359   if (n->public_key != NULL)
2360     {
2361 #if DEBUG_CORE
2362       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2363               "already have public key for peer %s!! (so why are we here?)\n",
2364               GNUNET_i2s (peer));
2365 #endif
2366       return;
2367     }
2368
2369 #if DEBUG_CORE
2370   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2371               "Received new `%s' message for `%4s', initiating key exchange.\n",
2372               "HELLO",
2373               GNUNET_i2s (peer));
2374 #endif
2375   n->public_key =
2376     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2377   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2378     {
2379       GNUNET_STATISTICS_update (stats,
2380                                 gettext_noop ("# Error extracting public key from HELLO"),
2381                                 1,
2382                                 GNUNET_NO);      
2383       GNUNET_free (n->public_key);
2384       n->public_key = NULL;
2385 #if DEBUG_CORE
2386   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2387               "GNUNET_HELLO_get_key returned awfully\n");
2388 #endif
2389       return;
2390     }
2391 }
2392
2393
2394 /**
2395  * Send our key (and encrypted PING) to the other peer.
2396  *
2397  * @param n the other peer
2398  */
2399 static void
2400 send_key (struct Neighbour *n)
2401 {
2402   struct SetKeyMessage *sm;
2403   struct MessageEntry *me;
2404   struct PingMessage pp;
2405   struct PingMessage *pm;
2406
2407   if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2408        (n->pitr != NULL) )
2409     {
2410 #if DEBUG_CORE
2411       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2412                   "Key exchange in progress with `%4s'.\n",
2413                   GNUNET_i2s (&n->peer));
2414 #endif
2415       return; /* already in progress */
2416     }
2417   if (! n->is_connected)
2418     {
2419       if (NULL == n->th)
2420         {
2421           GNUNET_STATISTICS_update (stats, 
2422                                     gettext_noop ("# Asking transport to connect (for SETKEY)"), 
2423                                     1, 
2424                                     GNUNET_NO);
2425           n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2426                                                           &n->peer,
2427                                                           sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2428                                                           GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2429                                                           &notify_encrypted_transmit_ready,
2430                                                           n);
2431         }
2432       return; 
2433     }
2434 #if DEBUG_CORE
2435   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2436               "Asked to perform key exchange with `%4s'.\n",
2437               GNUNET_i2s (&n->peer));
2438 #endif
2439   if (n->public_key == NULL)
2440     {
2441       /* lookup n's public key, then try again */
2442 #if DEBUG_CORE
2443       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2444                   "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2445                   GNUNET_i2s (&n->peer));
2446 #endif
2447       GNUNET_assert (n->pitr == NULL);
2448       n->pitr = GNUNET_PEERINFO_iterate (cfg,
2449                                          sched,
2450                                          &n->peer,
2451                                          0,
2452                                          GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2453                                          &process_hello_retry_send_key, n);
2454       return;
2455     }
2456   /* first, set key message */
2457   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2458                       sizeof (struct SetKeyMessage));
2459   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2460   me->priority = SET_KEY_PRIORITY;
2461   me->size = sizeof (struct SetKeyMessage);
2462   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2463                                      n->encrypted_tail,
2464                                      n->encrypted_tail,
2465                                      me);
2466   sm = (struct SetKeyMessage *) &me[1];
2467   sm->header.size = htons (sizeof (struct SetKeyMessage));
2468   sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2469   sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2470                                         PEER_STATE_KEY_SENT : n->status));
2471   sm->purpose.size =
2472     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2473            sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2474            sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2475            sizeof (struct GNUNET_PeerIdentity));
2476   sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2477   sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2478   sm->target = n->peer;
2479   GNUNET_assert (GNUNET_OK ==
2480                  GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2481                                             sizeof (struct
2482                                                     GNUNET_CRYPTO_AesSessionKey),
2483                                             n->public_key,
2484                                             &sm->encrypted_key));
2485   GNUNET_assert (GNUNET_OK ==
2486                  GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2487                                          &sm->signature));
2488
2489   /* second, encrypted PING message */
2490   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2491                       sizeof (struct PingMessage));
2492   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2493   me->priority = PING_PRIORITY;
2494   me->size = sizeof (struct PingMessage);
2495   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2496                                      n->encrypted_tail,
2497                                      n->encrypted_tail,
2498                                      me);
2499   pm = (struct PingMessage *) &me[1];
2500   pm->header.size = htons (sizeof (struct PingMessage));
2501   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2502   pp.challenge = htonl (n->ping_challenge);
2503   pp.target = n->peer;
2504 #if DEBUG_CORE
2505   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2506               "Encrypting `%s' and `%s' messages for `%4s'.\n",
2507               "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2508   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2509               "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2510               "PING",
2511               GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2512 #endif
2513   do_encrypt (n,
2514               &n->peer.hashPubKey,
2515               &pp.challenge,
2516               &pm->challenge,
2517               sizeof (struct PingMessage) -
2518               sizeof (struct GNUNET_MessageHeader));
2519   /* update status */
2520   switch (n->status)
2521     {
2522     case PEER_STATE_DOWN:
2523       n->status = PEER_STATE_KEY_SENT;
2524       break;
2525     case PEER_STATE_KEY_SENT:
2526       break;
2527     case PEER_STATE_KEY_RECEIVED:
2528       break;
2529     case PEER_STATE_KEY_CONFIRMED:
2530       break;
2531     default:
2532       GNUNET_break (0);
2533       break;
2534     }
2535   GNUNET_STATISTICS_update (stats, 
2536                             gettext_noop ("# SETKEY and PING messages created"), 
2537                             1, 
2538                             GNUNET_NO);
2539 #if DEBUG_CORE
2540   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2541               "Have %llu ms left for `%s' transmission.\n",
2542               (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2543               "SET_KEY");
2544 #endif
2545   /* trigger queue processing */
2546   process_encrypted_neighbour_queue (n);
2547   if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2548        (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2549     n->retry_set_key_task
2550       = GNUNET_SCHEDULER_add_delayed (sched,
2551                                       n->set_key_retry_frequency,
2552                                       &set_key_retry_task, n);    
2553 }
2554
2555
2556 /**
2557  * We received a SET_KEY message.  Validate and update
2558  * our key material and status.
2559  *
2560  * @param n the neighbour from which we received message m
2561  * @param m the set key message we received
2562  */
2563 static void
2564 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2565
2566
2567 /**
2568  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
2569  * the neighbour's struct and retry handling the set_key message.  Or,
2570  * if we did not get a HELLO, just free the set key message.
2571  *
2572  * @param cls pointer to the set key message
2573  * @param peer the peer for which this is the HELLO
2574  * @param hello HELLO message of that peer
2575  * @param trust amount of trust we currently have in that peer
2576  */
2577 static void
2578 process_hello_retry_handle_set_key (void *cls,
2579                                     const struct GNUNET_PeerIdentity *peer,
2580                                     const struct GNUNET_HELLO_Message *hello,
2581                                     uint32_t trust)
2582 {
2583   struct Neighbour *n = cls;
2584   struct SetKeyMessage *sm = n->skm;
2585
2586   if (peer == NULL)
2587     {
2588       GNUNET_free (sm);
2589       n->skm = NULL;
2590       n->pitr = NULL;
2591       return;
2592     }
2593   if (n->public_key != NULL)
2594     return;                     /* multiple HELLOs match!? */
2595   n->public_key =
2596     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2597   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2598     {
2599       GNUNET_break_op (0);
2600       GNUNET_free (n->public_key);
2601       n->public_key = NULL;
2602       return;
2603     }
2604 #if DEBUG_CORE
2605   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2606               "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2607               "HELLO", GNUNET_i2s (peer), "SET_KEY");
2608 #endif
2609   handle_set_key (n, sm);
2610 }
2611
2612
2613 /**
2614  * We received a PING message.  Validate and transmit
2615  * PONG.
2616  *
2617  * @param n sender of the PING
2618  * @param m the encrypted PING message itself
2619  */
2620 static void
2621 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2622 {
2623   struct PingMessage t;
2624   struct PongMessage tx;
2625   struct PongMessage *tp;
2626   struct MessageEntry *me;
2627
2628 #if DEBUG_CORE
2629   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2630               "Core service receives `%s' request from `%4s'.\n",
2631               "PING", GNUNET_i2s (&n->peer));
2632 #endif
2633   if (GNUNET_OK !=
2634       do_decrypt (n,
2635                   &my_identity.hashPubKey,
2636                   &m->challenge,
2637                   &t.challenge,
2638                   sizeof (struct PingMessage) -
2639                   sizeof (struct GNUNET_MessageHeader)))
2640     return;
2641 #if DEBUG_CORE
2642   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2643               "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2644               "PING",
2645               GNUNET_i2s (&t.target),
2646               ntohl (t.challenge), n->decrypt_key.crc32);
2647   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2648               "Target of `%s' request is `%4s'.\n",
2649               "PING", GNUNET_i2s (&t.target));
2650 #endif
2651   GNUNET_STATISTICS_update (stats,
2652                             gettext_noop ("# PING messages decrypted"), 
2653                             1,
2654                             GNUNET_NO);
2655   if (0 != memcmp (&t.target,
2656                    &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2657     {
2658       GNUNET_break_op (0);
2659       return;
2660     }
2661   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2662                       sizeof (struct PongMessage));
2663   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2664                                      n->encrypted_tail,
2665                                      n->encrypted_tail,
2666                                      me);
2667   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2668   me->priority = PONG_PRIORITY;
2669   me->size = sizeof (struct PongMessage);
2670   tx.reserved = htonl (0);
2671   tx.inbound_bw_limit = n->bw_in;
2672   tx.challenge = t.challenge;
2673   tx.target = t.target;
2674   tp = (struct PongMessage *) &me[1];
2675   tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2676   tp->header.size = htons (sizeof (struct PongMessage));
2677   do_encrypt (n,
2678               &my_identity.hashPubKey,
2679               &tx.challenge,
2680               &tp->challenge,
2681               sizeof (struct PongMessage) -
2682               sizeof (struct GNUNET_MessageHeader));
2683   GNUNET_STATISTICS_update (stats, 
2684                             gettext_noop ("# PONG messages created"), 
2685                             1, 
2686                             GNUNET_NO);
2687 #if DEBUG_CORE
2688   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2689               "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2690               ntohl (t.challenge), n->encrypt_key.crc32);
2691 #endif
2692   /* trigger queue processing */
2693   process_encrypted_neighbour_queue (n);
2694 }
2695
2696
2697 /**
2698  * We received a PONG message.  Validate and update our status.
2699  *
2700  * @param n sender of the PONG
2701  * @param m the encrypted PONG message itself
2702  */
2703 static void
2704 handle_pong (struct Neighbour *n, 
2705              const struct PongMessage *m)
2706 {
2707   struct PongMessage t;
2708   struct ConnectNotifyMessage cnm;
2709
2710 #if DEBUG_CORE
2711   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2712               "Core service receives `%s' request from `%4s'.\n",
2713               "PONG", GNUNET_i2s (&n->peer));
2714 #endif
2715   if (GNUNET_OK !=
2716       do_decrypt (n,
2717                   &n->peer.hashPubKey,
2718                   &m->challenge,
2719                   &t.challenge,
2720                   sizeof (struct PongMessage) -
2721                   sizeof (struct GNUNET_MessageHeader)))
2722     {
2723       GNUNET_break_op (0);
2724       return;
2725     }
2726   GNUNET_STATISTICS_update (stats, 
2727                             gettext_noop ("# PONG messages decrypted"), 
2728                             1, 
2729                             GNUNET_NO);
2730   if (0 != ntohl (t.reserved))
2731     {
2732       GNUNET_break_op (0);
2733       return;
2734     }
2735 #if DEBUG_CORE
2736   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2737               "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2738               "PONG",
2739               GNUNET_i2s (&t.target),
2740               ntohl (t.challenge), n->decrypt_key.crc32);
2741 #endif
2742   if ((0 != memcmp (&t.target,
2743                     &n->peer,
2744                     sizeof (struct GNUNET_PeerIdentity))) ||
2745       (n->ping_challenge != ntohl (t.challenge)))
2746     {
2747       /* PONG malformed */
2748 #if DEBUG_CORE
2749       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2750                   "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2751                   "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2752       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2753                   "Received malformed `%s' received from `%4s' with challenge %u\n",
2754                   "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2755 #endif
2756       GNUNET_break_op (0);
2757       return;
2758     }
2759   switch (n->status)
2760     {
2761     case PEER_STATE_DOWN:
2762       GNUNET_break (0);         /* should be impossible */
2763       return;
2764     case PEER_STATE_KEY_SENT:
2765       GNUNET_break (0);         /* should be impossible, how did we decrypt? */
2766       return;
2767     case PEER_STATE_KEY_RECEIVED:
2768       GNUNET_STATISTICS_update (stats, 
2769                                 gettext_noop ("# Session keys confirmed via PONG"), 
2770                                 1, 
2771                                 GNUNET_NO);
2772       n->status = PEER_STATE_KEY_CONFIRMED;
2773       if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2774         {
2775           n->bw_out_external_limit = t.inbound_bw_limit;
2776           n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2777                                                   n->bw_out_internal_limit);
2778           GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2779                                                  n->bw_out);       
2780           GNUNET_TRANSPORT_set_quota (transport,
2781                                       &n->peer,
2782                                       n->bw_in,
2783                                       n->bw_out,
2784                                       GNUNET_TIME_UNIT_FOREVER_REL,
2785                                       NULL, NULL); 
2786         }
2787 #if DEBUG_CORE
2788       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2789                   "Confirmed key via `%s' message for peer `%4s'\n",
2790                   "PONG", GNUNET_i2s (&n->peer));
2791 #endif      
2792       if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2793         {
2794           GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2795           n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2796         }      
2797       cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2798       cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2799       cnm.distance = htonl (n->last_distance);
2800       cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2801       cnm.peer = n->peer;
2802       send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2803       process_encrypted_neighbour_queue (n);
2804       /* fall-through! */
2805     case PEER_STATE_KEY_CONFIRMED:
2806       n->last_activity = GNUNET_TIME_absolute_get ();
2807       if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2808         GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2809       n->keep_alive_task 
2810         = GNUNET_SCHEDULER_add_delayed (sched, 
2811                                         GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2812                                         &send_keep_alive,
2813                                         n);
2814       break;
2815     default:
2816       GNUNET_break (0);
2817       break;
2818     }
2819 }
2820
2821
2822 /**
2823  * We received a SET_KEY message.  Validate and update
2824  * our key material and status.
2825  *
2826  * @param n the neighbour from which we received message m
2827  * @param m the set key message we received
2828  */
2829 static void
2830 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2831 {
2832   struct SetKeyMessage *m_cpy;
2833   struct GNUNET_TIME_Absolute t;
2834   struct GNUNET_CRYPTO_AesSessionKey k;
2835   struct PingMessage *ping;
2836   struct PongMessage *pong;
2837   enum PeerStateMachine sender_status;
2838
2839 #if DEBUG_CORE
2840   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2841               "Core service receives `%s' request from `%4s'.\n",
2842               "SET_KEY", GNUNET_i2s (&n->peer));
2843 #endif
2844   if (n->public_key == NULL)
2845     {
2846       if (n->pitr != NULL)
2847         {
2848 #if DEBUG_CORE
2849           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2850                       "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2851                       "SET_KEY");
2852 #endif
2853           return;
2854         }
2855 #if DEBUG_CORE
2856       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2857                   "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2858 #endif
2859       m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2860       memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2861       /* lookup n's public key, then try again */
2862       GNUNET_assert (n->skm == NULL);
2863       n->skm = m_cpy;
2864       n->pitr = GNUNET_PEERINFO_iterate (cfg,
2865                                          sched,
2866                                          &n->peer,
2867                                          0,
2868                                          GNUNET_TIME_UNIT_MINUTES,
2869                                          &process_hello_retry_handle_set_key, n);
2870       GNUNET_STATISTICS_update (stats, 
2871                                 gettext_noop ("# SETKEY messages deferred (need public key)"), 
2872                                 1, 
2873                                 GNUNET_NO);
2874       return;
2875     }
2876   if (0 != memcmp (&m->target,
2877                    &my_identity,
2878                    sizeof (struct GNUNET_PeerIdentity)))
2879     {
2880       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2881                   _("Received `%s' message that was for `%s', not for me.  Ignoring.\n"),
2882                   "SET_KEY",
2883                   GNUNET_i2s (&m->target));
2884       return;
2885     }
2886   if ((ntohl (m->purpose.size) !=
2887        sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2888        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2889        sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2890        sizeof (struct GNUNET_PeerIdentity)) ||
2891       (GNUNET_OK !=
2892        GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2893                                  &m->purpose, &m->signature, n->public_key)))
2894     {
2895       /* invalid signature */
2896       GNUNET_break_op (0);
2897       return;
2898     }
2899   t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2900   if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2901        (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2902       (t.value < n->decrypt_key_created.value))
2903     {
2904       /* this could rarely happen due to massive re-ordering of
2905          messages on the network level, but is most likely either
2906          a bug or some adversary messing with us.  Report. */
2907       GNUNET_break_op (0);
2908       return;
2909     }
2910 #if DEBUG_CORE
2911   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
2912               "Decrypting key material.\n");
2913 #endif  
2914   if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2915                                   &m->encrypted_key,
2916                                   &k,
2917                                   sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2918        != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2919       (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2920     {
2921       /* failed to decrypt !? */
2922       GNUNET_break_op (0);
2923       return;
2924     }
2925   GNUNET_STATISTICS_update (stats, 
2926                             gettext_noop ("# SETKEY messages decrypted"), 
2927                             1, 
2928                             GNUNET_NO);
2929   n->decrypt_key = k;
2930   if (n->decrypt_key_created.value != t.value)
2931     {
2932       /* fresh key, reset sequence numbers */
2933       n->last_sequence_number_received = 0;
2934       n->last_packets_bitmap = 0;
2935       n->decrypt_key_created = t;
2936     }
2937   sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2938   switch (n->status)
2939     {
2940     case PEER_STATE_DOWN:
2941       n->status = PEER_STATE_KEY_RECEIVED;
2942 #if DEBUG_CORE
2943       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2944                   "Responding to `%s' with my own key.\n", "SET_KEY");
2945 #endif
2946       send_key (n);
2947       break;
2948     case PEER_STATE_KEY_SENT:
2949     case PEER_STATE_KEY_RECEIVED:
2950       n->status = PEER_STATE_KEY_RECEIVED;
2951       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2952           (sender_status != PEER_STATE_KEY_CONFIRMED))
2953         {
2954 #if DEBUG_CORE
2955           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2956                       "Responding to `%s' with my own key (other peer has status %u).\n",
2957                       "SET_KEY", sender_status);
2958 #endif
2959           send_key (n);
2960         }
2961       break;
2962     case PEER_STATE_KEY_CONFIRMED:
2963       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2964           (sender_status != PEER_STATE_KEY_CONFIRMED))
2965         {         
2966 #if DEBUG_CORE
2967           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2968                       "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2969                       "SET_KEY", sender_status);
2970 #endif
2971           send_key (n);
2972         }
2973       break;
2974     default:
2975       GNUNET_break (0);
2976       break;
2977     }
2978   if (n->pending_ping != NULL)
2979     {
2980       ping = n->pending_ping;
2981       n->pending_ping = NULL;
2982       handle_ping (n, ping);
2983       GNUNET_free (ping);
2984     }
2985   if (n->pending_pong != NULL)
2986     {
2987       pong = n->pending_pong;
2988       n->pending_pong = NULL;
2989       handle_pong (n, pong);
2990       GNUNET_free (pong);
2991     }
2992 }
2993
2994
2995 /**
2996  * Send a P2P message to a client.
2997  *
2998  * @param sender who sent us the message?
2999  * @param client who should we give the message to?
3000  * @param m contains the message to transmit
3001  * @param msize number of bytes in buf to transmit
3002  */
3003 static void
3004 send_p2p_message_to_client (struct Neighbour *sender,
3005                             struct Client *client,
3006                             const void *m, size_t msize)
3007 {
3008   char buf[msize + sizeof (struct NotifyTrafficMessage)];
3009   struct NotifyTrafficMessage *ntm;
3010
3011 #if DEBUG_CORE
3012   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3013               "Core service passes message from `%4s' of type %u to client.\n",
3014               GNUNET_i2s(&sender->peer),
3015               ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3016 #endif
3017   ntm = (struct NotifyTrafficMessage *) buf;
3018   ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3019   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3020   ntm->distance = htonl (sender->last_distance);
3021   ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3022   ntm->peer = sender->peer;
3023   memcpy (&ntm[1], m, msize);
3024   send_to_client (client, &ntm->header, GNUNET_YES);
3025 }
3026
3027
3028 /**
3029  * Deliver P2P message to interested clients.
3030  *
3031  * @param sender who sent us the message?
3032  * @param m the message
3033  * @param msize size of the message (including header)
3034  */
3035 static void
3036 deliver_message (struct Neighbour *sender,
3037                  const struct GNUNET_MessageHeader *m, size_t msize)
3038 {
3039   struct Client *cpos;
3040   uint16_t type;
3041   unsigned int tpos;
3042   int deliver_full;
3043   int dropped;
3044
3045   type = ntohs (m->type);
3046 #if DEBUG_CORE
3047   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3048               "Received encapsulated message of type %u from `%4s'\n",
3049               type,
3050               GNUNET_i2s (&sender->peer));
3051 #endif
3052   dropped = GNUNET_YES;
3053   cpos = clients;
3054   while (cpos != NULL)
3055     {
3056       deliver_full = GNUNET_NO;
3057       if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3058         deliver_full = GNUNET_YES;
3059       else
3060         {
3061           for (tpos = 0; tpos < cpos->tcnt; tpos++)
3062             {
3063               if (type != cpos->types[tpos])
3064                 continue;
3065               deliver_full = GNUNET_YES;
3066               break;
3067             }
3068         }
3069       if (GNUNET_YES == deliver_full)
3070         {
3071           send_p2p_message_to_client (sender, cpos, m, msize);
3072           dropped = GNUNET_NO;
3073         }
3074       else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3075         {
3076           send_p2p_message_to_client (sender, cpos, m,
3077                                       sizeof (struct GNUNET_MessageHeader));
3078         }
3079       cpos = cpos->next;
3080     }
3081   if (dropped == GNUNET_YES)
3082     {
3083 #if DEBUG_CORE
3084       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3085                   "Message of type %u from `%4s' not delivered to any client.\n",
3086                   type,
3087                   GNUNET_i2s (&sender->peer));
3088 #endif
3089       /* FIXME: stats... */
3090     }
3091 }
3092
3093
3094 /**
3095  * Align P2P message and then deliver to interested clients.
3096  *
3097  * @param sender who sent us the message?
3098  * @param buffer unaligned (!) buffer containing message
3099  * @param msize size of the message (including header)
3100  */
3101 static void
3102 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
3103 {
3104   char abuf[msize];
3105
3106   /* TODO: call to statistics? */
3107   memcpy (abuf, buffer, msize);
3108   deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
3109 }
3110
3111
3112 /**
3113  * Deliver P2P messages to interested clients.
3114  *
3115  * @param sender who sent us the message?
3116  * @param buffer buffer containing messages, can be modified
3117  * @param buffer_size size of the buffer (overall)
3118  * @param offset offset where messages in the buffer start
3119  */
3120 static void
3121 deliver_messages (struct Neighbour *sender,
3122                   const char *buffer, size_t buffer_size, size_t offset)
3123 {
3124   struct GNUNET_MessageHeader *mhp;
3125   struct GNUNET_MessageHeader mh;
3126   uint16_t msize;
3127   int need_align;
3128
3129   while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
3130     {
3131       if (0 != offset % sizeof (uint16_t))
3132         {
3133           /* outch, need to copy to access header */
3134           memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
3135           mhp = &mh;
3136         }
3137       else
3138         {
3139           /* can access header directly */
3140           mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
3141         }
3142       msize = ntohs (mhp->size);
3143       if (msize + offset > buffer_size)
3144         {
3145           /* malformed message, header says it is larger than what
3146              would fit into the overall buffer */
3147           GNUNET_break_op (0);
3148           break;
3149         }
3150 #if HAVE_UNALIGNED_64_ACCESS
3151       need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
3152 #else
3153       need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
3154 #endif
3155       if (GNUNET_YES == need_align)
3156         align_and_deliver (sender, &buffer[offset], msize);
3157       else
3158         deliver_message (sender,
3159                          (const struct GNUNET_MessageHeader *)
3160                          &buffer[offset], msize);
3161       offset += msize;
3162     }
3163 }
3164
3165
3166 /**
3167  * We received an encrypted message.  Decrypt, validate and
3168  * pass on to the appropriate clients.
3169  */
3170 static void
3171 handle_encrypted_message (struct Neighbour *n,
3172                           const struct EncryptedMessage *m)
3173 {
3174   size_t size = ntohs (m->header.size);
3175   char buf[size];
3176   struct EncryptedMessage *pt;  /* plaintext */
3177   GNUNET_HashCode ph;
3178   size_t off;
3179   uint32_t snum;
3180   struct GNUNET_TIME_Absolute t;
3181   GNUNET_HashCode iv;
3182
3183 #if DEBUG_CORE
3184   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3185               "Core service receives `%s' request from `%4s'.\n",
3186               "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3187 #endif  
3188   GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3189   /* decrypt */
3190   if (GNUNET_OK !=
3191       do_decrypt (n,
3192                   &iv,
3193                   &m->plaintext_hash,
3194                   &buf[ENCRYPTED_HEADER_SIZE], 
3195                   size - ENCRYPTED_HEADER_SIZE))
3196     return;
3197   pt = (struct EncryptedMessage *) buf;
3198
3199   /* validate hash */
3200   GNUNET_CRYPTO_hash (&pt->sequence_number,
3201                       size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3202   if (0 != memcmp (&ph, 
3203                    &pt->plaintext_hash, 
3204                    sizeof (GNUNET_HashCode)))
3205     {
3206       /* checksum failed */
3207       GNUNET_break_op (0);
3208       return;
3209     }
3210
3211   /* validate sequence number */
3212   snum = ntohl (pt->sequence_number);
3213   if (n->last_sequence_number_received == snum)
3214     {
3215       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3216                   "Received duplicate message, ignoring.\n");
3217       /* duplicate, ignore */
3218       return;
3219     }
3220   if ((n->last_sequence_number_received > snum) &&
3221       (n->last_sequence_number_received - snum > 32))
3222     {
3223       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3224                   "Received ancient out of sequence message, ignoring.\n");
3225       /* ancient out of sequence, ignore */
3226       return;
3227     }
3228   if (n->last_sequence_number_received > snum)
3229     {
3230       unsigned int rotbit =
3231         1 << (n->last_sequence_number_received - snum - 1);
3232       if ((n->last_packets_bitmap & rotbit) != 0)
3233         {
3234           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3235                       "Received duplicate message, ignoring.\n");
3236           /* duplicate, ignore */
3237           return;
3238         }
3239       n->last_packets_bitmap |= rotbit;
3240     }
3241   if (n->last_sequence_number_received < snum)
3242     {
3243       n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3244       n->last_sequence_number_received = snum;
3245     }
3246
3247   /* check timestamp */
3248   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3249   if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3250     {
3251       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3252                   _
3253                   ("Message received far too old (%llu ms). Content ignored.\n"),
3254                   GNUNET_TIME_absolute_get_duration (t).value);
3255       return;
3256     }
3257
3258   /* process decrypted message(s) */
3259   if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3260     {
3261 #if DEBUG_CORE_SET_QUOTA
3262       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3263                   "Received %u b/s as new inbound limit for peer `%4s'\n",
3264                   (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3265                   GNUNET_i2s (&n->peer));
3266 #endif
3267       n->bw_out_external_limit = pt->inbound_bw_limit;
3268       n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3269                                               n->bw_out_internal_limit);
3270       GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3271                                              n->bw_out);
3272       GNUNET_TRANSPORT_set_quota (transport,
3273                                   &n->peer,
3274                                   n->bw_in,
3275                                   n->bw_out,
3276                                   GNUNET_TIME_UNIT_FOREVER_REL,
3277                                   NULL, NULL); 
3278     }
3279   n->last_activity = GNUNET_TIME_absolute_get ();
3280   if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3281     GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3282   n->keep_alive_task 
3283     = GNUNET_SCHEDULER_add_delayed (sched, 
3284                                     GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3285                                     &send_keep_alive,
3286                                     n);
3287   off = sizeof (struct EncryptedMessage);
3288   deliver_messages (n, buf, size, off);
3289 }
3290
3291
3292 /**
3293  * Function called by the transport for each received message.
3294  *
3295  * @param cls closure
3296  * @param peer (claimed) identity of the other peer
3297  * @param message the message
3298  * @param latency estimated latency for communicating with the
3299  *             given peer (round-trip)
3300  * @param distance in overlay hops, as given by transport plugin
3301  */
3302 static void
3303 handle_transport_receive (void *cls,
3304                           const struct GNUNET_PeerIdentity *peer,
3305                           const struct GNUNET_MessageHeader *message,
3306                           struct GNUNET_TIME_Relative latency,
3307                           unsigned int distance)
3308 {
3309   struct Neighbour *n;
3310   struct GNUNET_TIME_Absolute now;
3311   int up;
3312   uint16_t type;
3313   uint16_t size;
3314
3315 #if DEBUG_CORE
3316   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3317               "Received message of type %u from `%4s', demultiplexing.\n",
3318               ntohs (message->type), GNUNET_i2s (peer));
3319 #endif
3320   n = find_neighbour (peer);
3321   if (n == NULL)
3322     n = create_neighbour (peer);
3323   if (n == NULL)
3324     return;   
3325   n->last_latency = latency;
3326   n->last_distance = distance;
3327   up = (n->status == PEER_STATE_KEY_CONFIRMED);
3328   type = ntohs (message->type);
3329   size = ntohs (message->size);
3330 #if DEBUG_HANDSHAKE
3331   fprintf (stderr,
3332            "Received message of type %u from `%4s'\n",
3333            type,
3334            GNUNET_i2s (peer));
3335 #endif
3336   switch (type)
3337     {
3338     case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3339       if (size != sizeof (struct SetKeyMessage))
3340         {
3341           GNUNET_break_op (0);
3342           return;
3343         }
3344       GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3345       handle_set_key (n, (const struct SetKeyMessage *) message);
3346       break;
3347     case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3348       if (size < sizeof (struct EncryptedMessage) +
3349           sizeof (struct GNUNET_MessageHeader))
3350         {
3351           GNUNET_break_op (0);
3352           return;
3353         }
3354       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3355           (n->status != PEER_STATE_KEY_CONFIRMED))
3356         {
3357           GNUNET_break_op (0);
3358           /* blacklist briefly (?); might help recover (?) */
3359           GNUNET_TRANSPORT_blacklist (sched, cfg,
3360                                       &n->peer, 
3361                                       GNUNET_TIME_UNIT_SECONDS,
3362                                       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3363                                                                      5),
3364                                       NULL, NULL);
3365           return;
3366         }
3367       handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3368       break;
3369     case GNUNET_MESSAGE_TYPE_CORE_PING:
3370       if (size != sizeof (struct PingMessage))
3371         {
3372           GNUNET_break_op (0);
3373           return;
3374         }
3375       GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3376       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3377           (n->status != PEER_STATE_KEY_CONFIRMED))
3378         {
3379 #if DEBUG_CORE
3380           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3381                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3382                       "PING", GNUNET_i2s (&n->peer));
3383 #endif
3384           GNUNET_free_non_null (n->pending_ping);
3385           n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3386           memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3387           return;
3388         }
3389       handle_ping (n, (const struct PingMessage *) message);
3390       break;
3391     case GNUNET_MESSAGE_TYPE_CORE_PONG:
3392       if (size != sizeof (struct PongMessage))
3393         {
3394           GNUNET_break_op (0);
3395           return;
3396         }
3397       GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3398       if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3399            (n->status != PEER_STATE_KEY_CONFIRMED) )
3400         {
3401 #if DEBUG_CORE
3402           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3403                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3404                       "PONG", GNUNET_i2s (&n->peer));
3405 #endif
3406           GNUNET_free_non_null (n->pending_pong);
3407           n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3408           memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3409           return;
3410         }
3411       handle_pong (n, (const struct PongMessage *) message);
3412       break;
3413     default:
3414       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3415                   _("Unsupported message of type %u received.\n"), type);
3416       return;
3417     }
3418   if (n->status == PEER_STATE_KEY_CONFIRMED)
3419     {
3420       now = GNUNET_TIME_absolute_get ();
3421       n->last_activity = now;
3422       if (!up)
3423         {
3424           GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3425           n->time_established = now;
3426         }
3427       if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3428         GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3429       n->keep_alive_task 
3430         = GNUNET_SCHEDULER_add_delayed (sched, 
3431                                         GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3432                                         &send_keep_alive,
3433                                         n);
3434     }
3435 }
3436
3437
3438 /**
3439  * Function that recalculates the bandwidth quota for the
3440  * given neighbour and transmits it to the transport service.
3441  * 
3442  * @param cls neighbour for the quota update
3443  * @param tc context
3444  */
3445 static void
3446 neighbour_quota_update (void *cls,
3447                         const struct GNUNET_SCHEDULER_TaskContext *tc)
3448 {
3449   struct Neighbour *n = cls;
3450   struct GNUNET_BANDWIDTH_Value32NBO q_in;
3451   double pref_rel;
3452   double share;
3453   unsigned long long distributable;
3454   uint64_t need_per_peer;
3455   uint64_t need_per_second;
3456   
3457   n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3458   /* calculate relative preference among all neighbours;
3459      divides by a bit more to avoid division by zero AND to
3460      account for possibility of new neighbours joining any time 
3461      AND to convert to double... */
3462   if (preference_sum == 0)
3463     {
3464       pref_rel = 1.0 / (double) neighbour_count;
3465     }
3466   else
3467     {
3468       pref_rel = n->current_preference / preference_sum;
3469     }
3470   need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3471                                                               GNUNET_TIME_UNIT_SECONDS);  
3472   need_per_second = need_per_peer * neighbour_count;
3473   distributable = 0;
3474   if (bandwidth_target_out_bps > need_per_second)
3475     distributable = bandwidth_target_out_bps - need_per_second;
3476   share = distributable * pref_rel;
3477   if (share + need_per_peer > ( (uint32_t)-1))
3478     q_in = GNUNET_BANDWIDTH_value_init ((uint32_t) -1);
3479   else
3480     q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3481   /* check if we want to disconnect for good due to inactivity */
3482   if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3483        (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3484     {
3485 #if DEBUG_CORE
3486       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3487                   "Forcing disconnect of `%4s' due to inactivity (?).\n",
3488                   GNUNET_i2s (&n->peer));
3489 #endif
3490       q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3491     }
3492 #if DEBUG_CORE_QUOTA
3493   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3494               "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3495               GNUNET_i2s (&n->peer),
3496               (unsigned int) ntohl (q_in.value__),
3497               bandwidth_target_out_bps,
3498               (unsigned int) ntohl (n->bw_in.value__),
3499               (unsigned int) ntohl (n->bw_out.value__),
3500               (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3501 #endif
3502   if (n->bw_in.value__ != q_in.value__) 
3503     {
3504       n->bw_in = q_in;
3505       GNUNET_TRANSPORT_set_quota (transport,
3506                                   &n->peer,
3507                                   n->bw_in,
3508                                   n->bw_out,
3509                                   GNUNET_TIME_UNIT_FOREVER_REL,
3510                                   NULL, NULL);
3511     }
3512   schedule_quota_update (n);
3513 }
3514
3515
3516 /**
3517  * Function called by transport to notify us that
3518  * a peer connected to us (on the network level).
3519  *
3520  * @param cls closure
3521  * @param peer the peer that connected
3522  * @param latency current latency of the connection
3523  * @param distance in overlay hops, as given by transport plugin
3524  */
3525 static void
3526 handle_transport_notify_connect (void *cls,
3527                                  const struct GNUNET_PeerIdentity *peer,
3528                                  struct GNUNET_TIME_Relative latency,
3529                                  unsigned int distance)
3530 {
3531   struct Neighbour *n;
3532   struct ConnectNotifyMessage cnm;
3533
3534   n = find_neighbour (peer);
3535   if (n != NULL)
3536     {
3537       if (n->is_connected)
3538         {
3539           /* duplicate connect notification!? */
3540           GNUNET_break (0);
3541           return;
3542         }
3543     }
3544   else
3545     {
3546       n = create_neighbour (peer);
3547     }
3548   GNUNET_STATISTICS_update (stats, 
3549                             gettext_noop ("# peers connected"), 
3550                             1, 
3551                             GNUNET_NO);
3552   n->is_connected = GNUNET_YES;      
3553   n->last_latency = latency;
3554   n->last_distance = distance;
3555   GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3556                                  n->bw_out,
3557                                  MAX_WINDOW_TIME_S);
3558   GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3559                                  n->bw_in,
3560                                  MAX_WINDOW_TIME_S);  
3561 #if DEBUG_CORE
3562   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3563               "Received connection from `%4s'.\n",
3564               GNUNET_i2s (&n->peer));
3565 #endif
3566   cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3567   cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3568   cnm.distance = htonl (n->last_distance);
3569   cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3570   cnm.peer = *peer;
3571   send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3572   GNUNET_TRANSPORT_set_quota (transport,
3573                               &n->peer,
3574                               n->bw_in,
3575                               n->bw_out,
3576                               GNUNET_TIME_UNIT_FOREVER_REL,
3577                               NULL, NULL);
3578   send_key (n); 
3579 }
3580
3581
3582 /**
3583  * Function called by transport telling us that a peer
3584  * disconnected.
3585  *
3586  * @param cls closure
3587  * @param peer the peer that disconnected
3588  */
3589 static void
3590 handle_transport_notify_disconnect (void *cls,
3591                                     const struct GNUNET_PeerIdentity *peer)
3592 {
3593   struct DisconnectNotifyMessage cnm;
3594   struct Neighbour *n;
3595
3596 #if DEBUG_CORE
3597   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3598               "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3599 #endif
3600   n = find_neighbour (peer);
3601   if (n == NULL)
3602     {
3603       GNUNET_break (0);
3604       return;
3605     }
3606   GNUNET_break (n->is_connected);
3607   cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3608   cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3609   cnm.peer = *peer;
3610   send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3611   n->is_connected = GNUNET_NO;
3612   GNUNET_STATISTICS_update (stats, 
3613                             gettext_noop ("# peers connected"), 
3614                             -1, 
3615                             GNUNET_NO);
3616 }
3617
3618
3619 /**
3620  * Last task run during shutdown.  Disconnects us from
3621  * the transport.
3622  */
3623 static void
3624 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3625 {
3626   struct Neighbour *n;
3627   struct Client *c;
3628
3629 #if DEBUG_CORE
3630   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3631               "Core service shutting down.\n");
3632 #endif
3633   GNUNET_assert (transport != NULL);
3634   GNUNET_TRANSPORT_disconnect (transport);
3635   transport = NULL;
3636   while (NULL != (n = neighbours))
3637     {
3638       neighbours = n->next;
3639       GNUNET_assert (neighbour_count > 0);
3640       neighbour_count--;
3641       free_neighbour (n);
3642     }
3643   GNUNET_STATISTICS_set (stats, gettext_noop ("# active neighbours"), neighbour_count, GNUNET_NO);
3644   GNUNET_SERVER_notification_context_destroy (notifier);
3645   notifier = NULL;
3646   while (NULL != (c = clients))
3647     handle_client_disconnect (NULL, c->client_handle);
3648   if (my_private_key != NULL)
3649     GNUNET_CRYPTO_rsa_key_free (my_private_key);
3650   if (stats != NULL)
3651     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3652 }
3653
3654
3655 /**
3656  * Initiate core service.
3657  *
3658  * @param cls closure
3659  * @param s scheduler to use
3660  * @param serv the initialized server
3661  * @param c configuration to use
3662  */
3663 static void
3664 run (void *cls,
3665      struct GNUNET_SCHEDULER_Handle *s,
3666      struct GNUNET_SERVER_Handle *serv,
3667      const struct GNUNET_CONFIGURATION_Handle *c)
3668 {
3669   char *keyfile;
3670
3671   sched = s;
3672   cfg = c;  
3673   /* parse configuration */
3674   if (
3675        (GNUNET_OK !=
3676         GNUNET_CONFIGURATION_get_value_number (c,
3677                                                "CORE",
3678                                                "TOTAL_QUOTA_IN",
3679                                                &bandwidth_target_in_bps)) ||
3680        (GNUNET_OK !=
3681         GNUNET_CONFIGURATION_get_value_number (c,
3682                                                "CORE",
3683                                                "TOTAL_QUOTA_OUT",
3684                                                &bandwidth_target_out_bps)) ||
3685        (GNUNET_OK !=
3686         GNUNET_CONFIGURATION_get_value_filename (c,
3687                                                  "GNUNETD",
3688                                                  "HOSTKEY", &keyfile)))
3689     {
3690       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3691                   _
3692                   ("Core service is lacking key configuration settings.  Exiting.\n"));
3693       GNUNET_SCHEDULER_shutdown (s);
3694       return;
3695     }
3696   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3697   GNUNET_free (keyfile);
3698   if (my_private_key == NULL)
3699     {
3700       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3701                   _("Core service could not access hostkey.  Exiting.\n"));
3702       GNUNET_SCHEDULER_shutdown (s);
3703       return;
3704     }
3705   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3706   GNUNET_CRYPTO_hash (&my_public_key,
3707                       sizeof (my_public_key), &my_identity.hashPubKey);
3708   /* setup notification */
3709   server = serv;
3710   notifier = GNUNET_SERVER_notification_context_create (server, 
3711                                                         MAX_NOTIFY_QUEUE);
3712   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3713   /* setup transport connection */
3714   transport = GNUNET_TRANSPORT_connect (sched,
3715                                         cfg,
3716                                         NULL,
3717                                         &handle_transport_receive,
3718                                         &handle_transport_notify_connect,
3719                                         &handle_transport_notify_disconnect);
3720   GNUNET_assert (NULL != transport);
3721   stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3722   GNUNET_SCHEDULER_add_delayed (sched,
3723                                 GNUNET_TIME_UNIT_FOREVER_REL,
3724                                 &cleaning_task, NULL);
3725   /* process client requests */
3726   GNUNET_SERVER_add_handlers (server, handlers);
3727   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3728               _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3729 }
3730
3731
3732
3733 /**
3734  * The main function for the transport service.
3735  *
3736  * @param argc number of arguments from the command line
3737  * @param argv command line arguments
3738  * @return 0 ok, 1 on error
3739  */
3740 int
3741 main (int argc, char *const *argv)
3742 {
3743   return (GNUNET_OK ==
3744           GNUNET_SERVICE_run (argc,
3745                               argv,
3746                               "core",
3747                               GNUNET_SERVICE_OPTION_NONE,
3748                               &run, NULL)) ? 0 : 1;
3749 }
3750
3751 /* end of gnunet-service-core.c */