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