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