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