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