support multi-message encapsulations
[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  * Handle CORE_SEND request.
2010  *
2011  * @param cls unused
2012  * @param client the client issuing the request
2013  * @param message the "struct SendMessage"
2014  */
2015 static void
2016 handle_client_send (void *cls,
2017                     struct GNUNET_SERVER_Client *client,
2018                     const struct GNUNET_MessageHeader *message)
2019 {
2020   const struct SendMessage *sm;
2021   struct Neighbour *n;
2022   struct MessageEntry *prev;
2023   struct MessageEntry *pos;
2024   struct MessageEntry *e; 
2025   struct MessageEntry *min_prio_entry;
2026   struct MessageEntry *min_prio_prev;
2027   unsigned int min_prio;
2028   unsigned int queue_size;
2029   uint16_t msize;
2030
2031   msize = ntohs (message->size);
2032   if (msize <
2033       sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2034     {
2035       GNUNET_break (0);
2036       if (client != NULL)
2037         GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2038       return;
2039     }
2040   sm = (const struct SendMessage *) message;
2041   msize -= sizeof (struct SendMessage);
2042   n = find_neighbour (&sm->peer);
2043   if (n == NULL)
2044     n = create_neighbour (&sm->peer);
2045 #if DEBUG_CORE
2046   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2047               "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2048               "SEND",
2049               msize, 
2050               GNUNET_i2s (&sm->peer));
2051 #endif
2052   /* bound queue size */
2053   discard_expired_messages (n);
2054   min_prio = (unsigned int) -1;
2055   min_prio_entry = NULL;
2056   min_prio_prev = NULL;
2057   queue_size = 0;
2058   prev = NULL;
2059   pos = n->messages;
2060   while (pos != NULL) 
2061     {
2062       if (pos->priority < min_prio)
2063         {
2064           min_prio_entry = pos;
2065           min_prio_prev = prev;
2066           min_prio = pos->priority;
2067         }
2068       queue_size++;
2069       prev = pos;
2070       pos = pos->next;
2071     }
2072   if (queue_size >= MAX_PEER_QUEUE_SIZE)
2073     {
2074       /* queue full */
2075       if (ntohl(sm->priority) <= min_prio)
2076         {
2077           /* discard new entry */
2078 #if DEBUG_CORE
2079           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2080                       "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2081                       queue_size,
2082                       MAX_PEER_QUEUE_SIZE,
2083                       msize,
2084                       ntohs (message->type));
2085 #endif
2086           if (client != NULL)
2087             GNUNET_SERVER_receive_done (client, GNUNET_OK);
2088           return;
2089         }
2090       /* discard "min_prio_entry" */
2091 #if DEBUG_CORE
2092       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2093                   "Queue full, discarding existing older request\n");
2094 #endif
2095       if (min_prio_prev == NULL)
2096         n->messages = min_prio_entry->next;
2097       else
2098         min_prio_prev->next = min_prio_entry->next;      
2099       GNUNET_free (min_prio_entry);     
2100     }
2101
2102 #if DEBUG_CORE
2103   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2104               "Adding transmission request for `%4s' to queue\n",
2105               GNUNET_i2s (&sm->peer));
2106 #endif  
2107   e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2108   e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2109   e->priority = ntohl (sm->priority);
2110   e->size = msize;
2111   memcpy (&e[1], &sm[1], msize);
2112
2113   /* insert, keep list sorted by deadline */
2114   prev = NULL;
2115   pos = n->messages;
2116   while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2117     {
2118       prev = pos;
2119       pos = pos->next;
2120     }
2121   if (prev == NULL)
2122     n->messages = e;
2123   else
2124     prev->next = e;
2125   e->next = pos;
2126
2127   /* consider scheduling now */
2128   process_plaintext_neighbour_queue (n);
2129   if (client != NULL)
2130     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2131 }
2132
2133
2134 /**
2135  * Function called when the transport service is ready to
2136  * receive a message.  Only resets 'n->th' to NULL.
2137  *
2138  * @param cls neighbour to use message from
2139  * @param size number of bytes we can transmit
2140  * @param buf where to copy the message
2141  * @return number of bytes transmitted
2142  */
2143 static size_t
2144 notify_transport_connect_done (void *cls, size_t size, void *buf)
2145 {
2146   struct Neighbour *n = cls;
2147   n->th = NULL;
2148   send_key (n);
2149   return 0;
2150 }
2151
2152
2153 /**
2154  * Handle CORE_REQUEST_CONNECT request.
2155  *
2156  * @param cls unused
2157  * @param client the client issuing the request
2158  * @param message the "struct ConnectMessage"
2159  */
2160 static void
2161 handle_client_request_connect (void *cls,
2162                                struct GNUNET_SERVER_Client *client,
2163                                const struct GNUNET_MessageHeader *message)
2164 {
2165   const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2166   struct Neighbour *n;
2167   struct GNUNET_TIME_Relative timeout;
2168
2169   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2170   n = find_neighbour (&cm->peer);
2171   if (n == NULL)
2172     n = create_neighbour (&cm->peer);
2173   if ( (n->is_connected) ||
2174        (n->th != NULL) )
2175     return; /* already connected, or at least trying */
2176 #if DEBUG_CORE
2177   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2178               "Core received `%s' request for `%4s', will try to establish connection\n",
2179               "REQUEST_CONNECT",
2180               GNUNET_i2s (&cm->peer));
2181 #endif
2182   timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2183   /* ask transport to connect to the peer */
2184   n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2185                                                   &cm->peer,
2186                                                   sizeof (struct GNUNET_MessageHeader), 0,
2187                                                   timeout,
2188                                                   &notify_transport_connect_done,
2189                                                   n);
2190   GNUNET_break (NULL != n->th);
2191 }
2192
2193
2194 /**
2195  * List of handlers for the messages understood by this
2196  * service.
2197  */
2198 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2199   {&handle_client_init, NULL,
2200    GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2201   {&handle_client_request_info, NULL,
2202    GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2203    sizeof (struct RequestInfoMessage)},
2204   {&handle_client_send, NULL,
2205    GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2206   {&handle_client_request_connect, NULL,
2207    GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2208    sizeof (struct ConnectMessage)},
2209   {NULL, NULL, 0, 0}
2210 };
2211
2212
2213 /**
2214  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
2215  * the neighbour's struct and retry send_key.  Or, if we did not get a
2216  * HELLO, just do nothing.
2217  *
2218  * @param cls the 'struct Neighbour' to retry sending the key for
2219  * @param peer the peer for which this is the HELLO
2220  * @param hello HELLO message of that peer
2221  * @param trust amount of trust we currently have in that peer
2222  */
2223 static void
2224 process_hello_retry_send_key (void *cls,
2225                               const struct GNUNET_PeerIdentity *peer,
2226                               const struct GNUNET_HELLO_Message *hello,
2227                               uint32_t trust)
2228 {
2229   struct Neighbour *n = cls;
2230
2231   if (peer == NULL)
2232     {
2233 #if DEBUG_CORE
2234       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2235                   "Entered `process_hello_retry_send_key' and `peer' is NULL!\n");
2236 #endif
2237       n->pitr = NULL;
2238       if (n->public_key != NULL)
2239         {
2240           send_key (n);
2241         }
2242       else
2243         {
2244           if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2245             n->retry_set_key_task
2246               = GNUNET_SCHEDULER_add_delayed (sched,
2247                                               n->set_key_retry_frequency,
2248                                               &set_key_retry_task, n);
2249         }
2250       return;
2251     }
2252
2253 #if DEBUG_CORE
2254   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2255               "Entered `process_hello_retry_send_key' for peer `%4s'\n",
2256               GNUNET_i2s (peer));
2257 #endif
2258   if (n->public_key != NULL)
2259     {
2260 #if DEBUG_CORE
2261       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2262               "already have public key for peer %s!! (so why are we here?)\n",
2263               GNUNET_i2s (peer));
2264 #endif
2265       return;
2266     }
2267
2268 #if DEBUG_CORE
2269   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2270               "Received new `%s' message for `%4s', initiating key exchange.\n",
2271               "HELLO",
2272               GNUNET_i2s (peer));
2273 #endif
2274   n->public_key =
2275     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2276   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2277     {
2278       GNUNET_free (n->public_key);
2279       n->public_key = NULL;
2280 #if DEBUG_CORE
2281   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2282               "GNUNET_HELLO_get_key returned awfully\n");
2283 #endif
2284       return;
2285     }
2286 }
2287
2288
2289 /**
2290  * Send our key (and encrypted PING) to the other peer.
2291  *
2292  * @param n the other peer
2293  */
2294 static void
2295 send_key (struct Neighbour *n)
2296 {
2297   struct SetKeyMessage *sm;
2298   struct MessageEntry *me;
2299   struct PingMessage pp;
2300   struct PingMessage *pm;
2301
2302   if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2303        (n->pitr != NULL) )
2304     {
2305 #if DEBUG_CORE
2306       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2307                   "Key exchange in progress with `%4s'.\n",
2308                   GNUNET_i2s (&n->peer));
2309 #endif
2310       return; /* already in progress */
2311     }
2312
2313 #if DEBUG_CORE
2314   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2315               "Asked to perform key exchange with `%4s'.\n",
2316               GNUNET_i2s (&n->peer));
2317 #endif
2318   if (n->public_key == NULL)
2319     {
2320       /* lookup n's public key, then try again */
2321 #if DEBUG_CORE
2322       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2323                   "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2324                   GNUNET_i2s (&n->peer));
2325 #endif
2326       GNUNET_assert (n->pitr == NULL);
2327       n->pitr = GNUNET_PEERINFO_iterate (cfg,
2328                                          sched,
2329                                          &n->peer,
2330                                          0,
2331                                          GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2332                                          &process_hello_retry_send_key, n);
2333       return;
2334     }
2335   /* first, set key message */
2336   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2337                       sizeof (struct SetKeyMessage));
2338   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2339   me->priority = SET_KEY_PRIORITY;
2340   me->size = sizeof (struct SetKeyMessage);
2341   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2342                                      n->encrypted_tail,
2343                                      n->encrypted_tail,
2344                                      me);
2345   sm = (struct SetKeyMessage *) &me[1];
2346   sm->header.size = htons (sizeof (struct SetKeyMessage));
2347   sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2348   sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2349                                         PEER_STATE_KEY_SENT : n->status));
2350   sm->purpose.size =
2351     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2352            sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2353            sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2354            sizeof (struct GNUNET_PeerIdentity));
2355   sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2356   sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2357   sm->target = n->peer;
2358   GNUNET_assert (GNUNET_OK ==
2359                  GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2360                                             sizeof (struct
2361                                                     GNUNET_CRYPTO_AesSessionKey),
2362                                             n->public_key,
2363                                             &sm->encrypted_key));
2364   GNUNET_assert (GNUNET_OK ==
2365                  GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2366                                          &sm->signature));
2367
2368   /* second, encrypted PING message */
2369   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2370                       sizeof (struct PingMessage));
2371   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2372   me->priority = PING_PRIORITY;
2373   me->size = sizeof (struct PingMessage);
2374   n->encrypted_tail->next = me;
2375   n->encrypted_tail = me;
2376   pm = (struct PingMessage *) &me[1];
2377   pm->header.size = htons (sizeof (struct PingMessage));
2378   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2379   pp.challenge = htonl (n->ping_challenge);
2380   pp.target = n->peer;
2381 #if DEBUG_CORE
2382   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2383               "Encrypting `%s' and `%s' messages for `%4s'.\n",
2384               "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2385   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2386               "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2387               "PING",
2388               GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2389 #endif
2390   do_encrypt (n,
2391               &n->peer.hashPubKey,
2392               &pp.challenge,
2393               &pm->challenge,
2394               sizeof (struct PingMessage) -
2395               sizeof (struct GNUNET_MessageHeader));
2396   /* update status */
2397   switch (n->status)
2398     {
2399     case PEER_STATE_DOWN:
2400       n->status = PEER_STATE_KEY_SENT;
2401       break;
2402     case PEER_STATE_KEY_SENT:
2403       break;
2404     case PEER_STATE_KEY_RECEIVED:
2405       break;
2406     case PEER_STATE_KEY_CONFIRMED:
2407       break;
2408     default:
2409       GNUNET_break (0);
2410       break;
2411     }
2412 #if DEBUG_CORE
2413   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2414               "Have %llu ms left for `%s' transmission.\n",
2415               (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2416               "SET_KEY");
2417 #endif
2418   /* trigger queue processing */
2419   process_encrypted_neighbour_queue (n);
2420   if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2421        (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2422     n->retry_set_key_task
2423       = GNUNET_SCHEDULER_add_delayed (sched,
2424                                       n->set_key_retry_frequency,
2425                                       &set_key_retry_task, n);    
2426 }
2427
2428
2429 /**
2430  * We received a SET_KEY message.  Validate and update
2431  * our key material and status.
2432  *
2433  * @param n the neighbour from which we received message m
2434  * @param m the set key message we received
2435  */
2436 static void
2437 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2438
2439
2440 /**
2441  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
2442  * the neighbour's struct and retry handling the set_key message.  Or,
2443  * if we did not get a HELLO, just free the set key message.
2444  *
2445  * @param cls pointer to the set key message
2446  * @param peer the peer for which this is the HELLO
2447  * @param hello HELLO message of that peer
2448  * @param trust amount of trust we currently have in that peer
2449  */
2450 static void
2451 process_hello_retry_handle_set_key (void *cls,
2452                                     const struct GNUNET_PeerIdentity *peer,
2453                                     const struct GNUNET_HELLO_Message *hello,
2454                                     uint32_t trust)
2455 {
2456   struct Neighbour *n = cls;
2457   struct SetKeyMessage *sm = n->skm;
2458
2459   if (peer == NULL)
2460     {
2461       GNUNET_free (sm);
2462       n->skm = NULL;
2463       n->pitr = NULL;
2464       return;
2465     }
2466   if (n->public_key != NULL)
2467     return;                     /* multiple HELLOs match!? */
2468   n->public_key =
2469     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2470   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2471     {
2472       GNUNET_break_op (0);
2473       GNUNET_free (n->public_key);
2474       n->public_key = NULL;
2475       return;
2476     }
2477 #if DEBUG_CORE
2478   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2479               "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2480               "HELLO", GNUNET_i2s (peer), "SET_KEY");
2481 #endif
2482   handle_set_key (n, sm);
2483 }
2484
2485
2486 /**
2487  * We received a PING message.  Validate and transmit
2488  * PONG.
2489  *
2490  * @param n sender of the PING
2491  * @param m the encrypted PING message itself
2492  */
2493 static void
2494 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2495 {
2496   struct PingMessage t;
2497   struct PongMessage tx;
2498   struct PongMessage *tp;
2499   struct MessageEntry *me;
2500
2501 #if DEBUG_CORE
2502   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2503               "Core service receives `%s' request from `%4s'.\n",
2504               "PING", GNUNET_i2s (&n->peer));
2505 #endif
2506   if (GNUNET_OK !=
2507       do_decrypt (n,
2508                   &my_identity.hashPubKey,
2509                   &m->challenge,
2510                   &t.challenge,
2511                   sizeof (struct PingMessage) -
2512                   sizeof (struct GNUNET_MessageHeader)))
2513     return;
2514 #if DEBUG_CORE
2515   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2516               "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2517               "PING",
2518               GNUNET_i2s (&t.target),
2519               ntohl (t.challenge), n->decrypt_key.crc32);
2520   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2521               "Target of `%s' request is `%4s'.\n",
2522               "PING", GNUNET_i2s (&t.target));
2523 #endif
2524   if (0 != memcmp (&t.target,
2525                    &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2526     {
2527       GNUNET_break_op (0);
2528       return;
2529     }
2530   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2531                       sizeof (struct PongMessage));
2532   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2533                                      n->encrypted_tail,
2534                                      n->encrypted_tail,
2535                                      me);
2536   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2537   me->priority = PONG_PRIORITY;
2538   me->size = sizeof (struct PongMessage);
2539   tx.reserved = htonl (0);
2540   tx.inbound_bpm_limit = htonl (n->bpm_in);
2541   tx.challenge = t.challenge;
2542   tx.target = t.target;
2543   tp = (struct PongMessage *) &me[1];
2544   tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2545   tp->header.size = htons (sizeof (struct PongMessage));
2546   do_encrypt (n,
2547               &my_identity.hashPubKey,
2548               &tx.challenge,
2549               &tp->challenge,
2550               sizeof (struct PongMessage) -
2551               sizeof (struct GNUNET_MessageHeader));
2552 #if DEBUG_CORE
2553   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2554               "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2555               ntohl (t.challenge), n->encrypt_key.crc32);
2556 #endif
2557   /* trigger queue processing */
2558   process_encrypted_neighbour_queue (n);
2559 }
2560
2561
2562 /**
2563  * We received a PONG message.  Validate and update our status.
2564  *
2565  * @param n sender of the PONG
2566  * @param m the encrypted PONG message itself
2567  */
2568 static void
2569 handle_pong (struct Neighbour *n, 
2570              const struct PongMessage *m)
2571 {
2572   struct PongMessage t;
2573   struct ConnectNotifyMessage cnm;
2574
2575 #if DEBUG_CORE
2576   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2577               "Core service receives `%s' request from `%4s'.\n",
2578               "PONG", GNUNET_i2s (&n->peer));
2579 #endif
2580   if (GNUNET_OK !=
2581       do_decrypt (n,
2582                   &n->peer.hashPubKey,
2583                   &m->challenge,
2584                   &t.challenge,
2585                   sizeof (struct PongMessage) -
2586                   sizeof (struct GNUNET_MessageHeader)))
2587     return;
2588   if (0 != ntohl (t.reserved))
2589     {
2590       GNUNET_break_op (0);
2591       return;
2592     }
2593 #if DEBUG_CORE
2594   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2595               "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2596               "PONG",
2597               GNUNET_i2s (&t.target),
2598               ntohl (t.challenge), n->decrypt_key.crc32);
2599 #endif
2600   if ((0 != memcmp (&t.target,
2601                     &n->peer,
2602                     sizeof (struct GNUNET_PeerIdentity))) ||
2603       (n->ping_challenge != ntohl (t.challenge)))
2604     {
2605       /* PONG malformed */
2606 #if DEBUG_CORE
2607       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2608                   "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2609                   "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2610       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2611                   "Received malformed `%s' received from `%4s' with challenge %u\n",
2612                   "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2613 #endif
2614       GNUNET_break_op (0);
2615       return;
2616     }
2617   switch (n->status)
2618     {
2619     case PEER_STATE_DOWN:
2620       GNUNET_break (0);         /* should be impossible */
2621       return;
2622     case PEER_STATE_KEY_SENT:
2623       GNUNET_break (0);         /* should be impossible, how did we decrypt? */
2624       return;
2625     case PEER_STATE_KEY_RECEIVED:
2626       n->status = PEER_STATE_KEY_CONFIRMED;
2627       n->bpm_out_external_limit = ntohl (t.inbound_bpm_limit);
2628       n->bpm_out = GNUNET_MIN (n->bpm_out_external_limit,
2629                                n->bpm_out_internal_limit);
2630 #if DEBUG_CORE
2631       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2632                   "Confirmed key via `%s' message for peer `%4s'\n",
2633                   "PONG", GNUNET_i2s (&n->peer));
2634 #endif
2635       if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2636         {
2637           GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2638           n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2639         }      
2640       cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2641       cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2642       cnm.distance = htonl (n->last_distance);
2643       cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2644       cnm.peer = n->peer;
2645       send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2646       process_encrypted_neighbour_queue (n);
2647       break;
2648     case PEER_STATE_KEY_CONFIRMED:
2649       /* duplicate PONG? */
2650       break;
2651     default:
2652       GNUNET_break (0);
2653       break;
2654     }
2655 }
2656
2657
2658 /**
2659  * We received a SET_KEY message.  Validate and update
2660  * our key material and status.
2661  *
2662  * @param n the neighbour from which we received message m
2663  * @param m the set key message we received
2664  */
2665 static void
2666 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2667 {
2668   struct SetKeyMessage *m_cpy;
2669   struct GNUNET_TIME_Absolute t;
2670   struct GNUNET_CRYPTO_AesSessionKey k;
2671   struct PingMessage *ping;
2672   struct PongMessage *pong;
2673   enum PeerStateMachine sender_status;
2674
2675 #if DEBUG_CORE
2676   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2677               "Core service receives `%s' request from `%4s'.\n",
2678               "SET_KEY", GNUNET_i2s (&n->peer));
2679 #endif
2680   if (n->public_key == NULL)
2681     {
2682       if (n->pitr != NULL)
2683         {
2684 #if DEBUG_CORE
2685           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2686                       "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2687                       "SET_KEY");
2688 #endif
2689           return;
2690         }
2691 #if DEBUG_CORE
2692       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2693                   "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2694 #endif
2695       m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2696       memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2697       /* lookup n's public key, then try again */
2698       GNUNET_assert (n->skm == NULL);
2699       n->skm = m_cpy;
2700       n->pitr = GNUNET_PEERINFO_iterate (cfg,
2701                                          sched,
2702                                          &n->peer,
2703                                          0,
2704                                          GNUNET_TIME_UNIT_MINUTES,
2705                                          &process_hello_retry_handle_set_key, n);
2706       return;
2707     }
2708   if (0 != memcmp (&m->target,
2709                    &my_identity,
2710                    sizeof (struct GNUNET_PeerIdentity)))
2711     {
2712       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2713                   _("Received `%s' message that was not for me.  Ignoring.\n"),
2714                   "SET_KEY");
2715       return;
2716     }
2717   if ((ntohl (m->purpose.size) !=
2718        sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2719        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2720        sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2721        sizeof (struct GNUNET_PeerIdentity)) ||
2722       (GNUNET_OK !=
2723        GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2724                                  &m->purpose, &m->signature, n->public_key)))
2725     {
2726       /* invalid signature */
2727       GNUNET_break_op (0);
2728       return;
2729     }
2730   t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2731   if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2732        (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2733       (t.value < n->decrypt_key_created.value))
2734     {
2735       /* this could rarely happen due to massive re-ordering of
2736          messages on the network level, but is most likely either
2737          a bug or some adversary messing with us.  Report. */
2738       GNUNET_break_op (0);
2739       return;
2740     }
2741 #if DEBUG_CORE
2742   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
2743 #endif  
2744   if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2745                                   &m->encrypted_key,
2746                                   &k,
2747                                   sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2748        != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2749       (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2750     {
2751       /* failed to decrypt !? */
2752       GNUNET_break_op (0);
2753       return;
2754     }
2755
2756   n->decrypt_key = k;
2757   if (n->decrypt_key_created.value != t.value)
2758     {
2759       /* fresh key, reset sequence numbers */
2760       n->last_sequence_number_received = 0;
2761       n->last_packets_bitmap = 0;
2762       n->decrypt_key_created = t;
2763     }
2764   sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2765   switch (n->status)
2766     {
2767     case PEER_STATE_DOWN:
2768       n->status = PEER_STATE_KEY_RECEIVED;
2769 #if DEBUG_CORE
2770       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2771                   "Responding to `%s' with my own key.\n", "SET_KEY");
2772 #endif
2773       send_key (n);
2774       break;
2775     case PEER_STATE_KEY_SENT:
2776     case PEER_STATE_KEY_RECEIVED:
2777       n->status = PEER_STATE_KEY_RECEIVED;
2778       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2779           (sender_status != PEER_STATE_KEY_CONFIRMED))
2780         {
2781 #if DEBUG_CORE
2782           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2783                       "Responding to `%s' with my own key (other peer has status %u).\n",
2784                       "SET_KEY", sender_status);
2785 #endif
2786           send_key (n);
2787         }
2788       break;
2789     case PEER_STATE_KEY_CONFIRMED:
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), I was already fully up.\n",
2796                       "SET_KEY", sender_status);
2797 #endif
2798           send_key (n);
2799         }
2800       break;
2801     default:
2802       GNUNET_break (0);
2803       break;
2804     }
2805   if (n->pending_ping != NULL)
2806     {
2807       ping = n->pending_ping;
2808       n->pending_ping = NULL;
2809       handle_ping (n, ping);
2810       GNUNET_free (ping);
2811     }
2812   if (n->pending_pong != NULL)
2813     {
2814       pong = n->pending_pong;
2815       n->pending_pong = NULL;
2816       handle_pong (n, pong);
2817       GNUNET_free (pong);
2818     }
2819 }
2820
2821
2822 /**
2823  * Send a P2P message to a client.
2824  *
2825  * @param sender who sent us the message?
2826  * @param client who should we give the message to?
2827  * @param m contains the message to transmit
2828  * @param msize number of bytes in buf to transmit
2829  */
2830 static void
2831 send_p2p_message_to_client (struct Neighbour *sender,
2832                             struct Client *client,
2833                             const void *m, size_t msize)
2834 {
2835   char buf[msize + sizeof (struct NotifyTrafficMessage)];
2836   struct NotifyTrafficMessage *ntm;
2837
2838 #if DEBUG_CORE
2839   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2840               "Core service passes message from `%4s' of type %u to client.\n",
2841               GNUNET_i2s(&sender->peer),
2842               ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2843 #endif
2844   ntm = (struct NotifyTrafficMessage *) buf;
2845   ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2846   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2847   ntm->distance = htonl (sender->last_distance);
2848   ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
2849   ntm->peer = sender->peer;
2850   memcpy (&ntm[1], m, msize);
2851   send_to_client (client, &ntm->header, GNUNET_YES);
2852 }
2853
2854
2855 /**
2856  * Deliver P2P message to interested clients.
2857  *
2858  * @param sender who sent us the message?
2859  * @param m the message
2860  * @param msize size of the message (including header)
2861  */
2862 static void
2863 deliver_message (struct Neighbour *sender,
2864                  const struct GNUNET_MessageHeader *m, size_t msize)
2865 {
2866   struct Client *cpos;
2867   uint16_t type;
2868   unsigned int tpos;
2869   int deliver_full;
2870   int dropped;
2871
2872   type = ntohs (m->type);
2873 #if DEBUG_CORE
2874   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2875               "Received encapsulated message of type %u from `%4s'\n",
2876               type,
2877               GNUNET_i2s (&sender->peer));
2878 #endif
2879   dropped = GNUNET_YES;
2880   cpos = clients;
2881   while (cpos != NULL)
2882     {
2883       deliver_full = GNUNET_NO;
2884       if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
2885         deliver_full = GNUNET_YES;
2886       else
2887         {
2888           for (tpos = 0; tpos < cpos->tcnt; tpos++)
2889             {
2890               if (type != cpos->types[tpos])
2891                 continue;
2892               deliver_full = GNUNET_YES;
2893               break;
2894             }
2895         }
2896       if (GNUNET_YES == deliver_full)
2897         {
2898           send_p2p_message_to_client (sender, cpos, m, msize);
2899           dropped = GNUNET_NO;
2900         }
2901       else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2902         {
2903           send_p2p_message_to_client (sender, cpos, m,
2904                                       sizeof (struct GNUNET_MessageHeader));
2905         }
2906       cpos = cpos->next;
2907     }
2908   if (dropped == GNUNET_YES)
2909     {
2910 #if DEBUG_CORE
2911       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2912                   "Message of type %u from `%4s' not delivered to any client.\n",
2913                   type,
2914                   GNUNET_i2s (&sender->peer));
2915 #endif
2916       /* FIXME: stats... */
2917     }
2918 }
2919
2920
2921 /**
2922  * Align P2P message and then deliver to interested clients.
2923  *
2924  * @param sender who sent us the message?
2925  * @param buffer unaligned (!) buffer containing message
2926  * @param msize size of the message (including header)
2927  */
2928 static void
2929 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
2930 {
2931   char abuf[msize];
2932
2933   /* TODO: call to statistics? */
2934   memcpy (abuf, buffer, msize);
2935   deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
2936 }
2937
2938
2939 /**
2940  * Deliver P2P messages to interested clients.
2941  *
2942  * @param sender who sent us the message?
2943  * @param buffer buffer containing messages, can be modified
2944  * @param buffer_size size of the buffer (overall)
2945  * @param offset offset where messages in the buffer start
2946  */
2947 static void
2948 deliver_messages (struct Neighbour *sender,
2949                   const char *buffer, size_t buffer_size, size_t offset)
2950 {
2951   struct GNUNET_MessageHeader *mhp;
2952   struct GNUNET_MessageHeader mh;
2953   uint16_t msize;
2954   int need_align;
2955
2956   while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
2957     {
2958       if (0 != offset % sizeof (uint16_t))
2959         {
2960           /* outch, need to copy to access header */
2961           memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
2962           mhp = &mh;
2963         }
2964       else
2965         {
2966           /* can access header directly */
2967           mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
2968         }
2969       msize = ntohs (mhp->size);
2970       if (msize + offset > buffer_size)
2971         {
2972           /* malformed message, header says it is larger than what
2973              would fit into the overall buffer */
2974           GNUNET_break_op (0);
2975           break;
2976         }
2977 #if HAVE_UNALIGNED_64_ACCESS
2978       need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
2979 #else
2980       need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
2981 #endif
2982       if (GNUNET_YES == need_align)
2983         align_and_deliver (sender, &buffer[offset], msize);
2984       else
2985         deliver_message (sender,
2986                          (const struct GNUNET_MessageHeader *)
2987                          &buffer[offset], msize);
2988       offset += msize;
2989     }
2990 }
2991
2992
2993 /**
2994  * We received an encrypted message.  Decrypt, validate and
2995  * pass on to the appropriate clients.
2996  */
2997 static void
2998 handle_encrypted_message (struct Neighbour *n,
2999                           const struct EncryptedMessage *m)
3000 {
3001   size_t size = ntohs (m->header.size);
3002   char buf[size];
3003   struct EncryptedMessage *pt;  /* plaintext */
3004   GNUNET_HashCode ph;
3005   size_t off;
3006   uint32_t snum;
3007   struct GNUNET_TIME_Absolute t;
3008   GNUNET_HashCode iv;
3009
3010 #if DEBUG_CORE
3011   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3012               "Core service receives `%s' request from `%4s'.\n",
3013               "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3014 #endif  
3015   GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3016   /* decrypt */
3017   if (GNUNET_OK !=
3018       do_decrypt (n,
3019                   &iv,
3020                   &m->plaintext_hash,
3021                   &buf[ENCRYPTED_HEADER_SIZE], 
3022                   size - ENCRYPTED_HEADER_SIZE))
3023     return;
3024   pt = (struct EncryptedMessage *) buf;
3025
3026   /* validate hash */
3027   GNUNET_CRYPTO_hash (&pt->sequence_number,
3028                       size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3029   if (0 != memcmp (&ph, 
3030                    &pt->plaintext_hash, 
3031                    sizeof (GNUNET_HashCode)))
3032     {
3033       /* checksum failed */
3034       GNUNET_break_op (0);
3035       return;
3036     }
3037
3038   /* validate sequence number */
3039   snum = ntohl (pt->sequence_number);
3040   if (n->last_sequence_number_received == snum)
3041     {
3042       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3043                   "Received duplicate message, ignoring.\n");
3044       /* duplicate, ignore */
3045       return;
3046     }
3047   if ((n->last_sequence_number_received > snum) &&
3048       (n->last_sequence_number_received - snum > 32))
3049     {
3050       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3051                   "Received ancient out of sequence message, ignoring.\n");
3052       /* ancient out of sequence, ignore */
3053       return;
3054     }
3055   if (n->last_sequence_number_received > snum)
3056     {
3057       unsigned int rotbit =
3058         1 << (n->last_sequence_number_received - snum - 1);
3059       if ((n->last_packets_bitmap & rotbit) != 0)
3060         {
3061           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3062                       "Received duplicate message, ignoring.\n");
3063           /* duplicate, ignore */
3064           return;
3065         }
3066       n->last_packets_bitmap |= rotbit;
3067     }
3068   if (n->last_sequence_number_received < snum)
3069     {
3070       n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3071       n->last_sequence_number_received = snum;
3072     }
3073
3074   /* check timestamp */
3075   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3076   if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3077     {
3078       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3079                   _
3080                   ("Message received far too old (%llu ms). Content ignored.\n"),
3081                   GNUNET_TIME_absolute_get_duration (t).value);
3082       return;
3083     }
3084
3085   /* process decrypted message(s) */
3086   if (n->bpm_out_external_limit != ntohl (pt->inbound_bpm_limit))
3087     {
3088       update_window (GNUNET_YES,
3089                      &n->available_send_window,
3090                      &n->last_asw_update,
3091                      n->bpm_out);
3092 #if DEBUG_CORE_QUOTA
3093       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3094                   "Received %llu as new inbound limit for peer `%4s'\n",
3095                   (unsigned long long) ntohl (pt->inbound_bpm_limit),
3096                   GNUNET_i2s (&n->peer));
3097 #endif
3098     }
3099   n->bpm_out_external_limit = ntohl (pt->inbound_bpm_limit);
3100   n->bpm_out = GNUNET_MIN (n->bpm_out_external_limit,
3101                            n->bpm_out_internal_limit);
3102   n->last_activity = GNUNET_TIME_absolute_get ();
3103   off = sizeof (struct EncryptedMessage);
3104   deliver_messages (n, buf, size, off);
3105 }
3106
3107
3108 /**
3109  * Function called by the transport for each received message.
3110  *
3111  * @param cls closure
3112  * @param peer (claimed) identity of the other peer
3113  * @param message the message
3114  * @param latency estimated latency for communicating with the
3115  *             given peer (round-trip)
3116  * @param distance in overlay hops, as given by transport plugin
3117  */
3118 static void
3119 handle_transport_receive (void *cls,
3120                           const struct GNUNET_PeerIdentity *peer,
3121                           const struct GNUNET_MessageHeader *message,
3122                           struct GNUNET_TIME_Relative latency,
3123                           unsigned int distance)
3124 {
3125   struct Neighbour *n;
3126   struct GNUNET_TIME_Absolute now;
3127   int up;
3128   uint16_t type;
3129   uint16_t size;
3130
3131 #if DEBUG_CORE
3132   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3133               "Received message of type %u from `%4s', demultiplexing.\n",
3134               ntohs (message->type), GNUNET_i2s (peer));
3135 #endif
3136   n = find_neighbour (peer);
3137   if (n == NULL)
3138     n = create_neighbour (peer);
3139   if (n == NULL)
3140     return;   
3141   n->last_latency = latency;
3142   n->last_distance = distance;
3143   up = (n->status == PEER_STATE_KEY_CONFIRMED);
3144   type = ntohs (message->type);
3145   size = ntohs (message->size);
3146 #if DEBUG_HANDSHAKE
3147   fprintf (stderr,
3148            "Received message of type %u from `%4s'\n",
3149            type,
3150            GNUNET_i2s (peer));
3151 #endif
3152   switch (type)
3153     {
3154     case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3155       if (size != sizeof (struct SetKeyMessage))
3156         {
3157           GNUNET_break_op (0);
3158           return;
3159         }
3160       handle_set_key (n, (const struct SetKeyMessage *) message);
3161       break;
3162     case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3163       if (size < sizeof (struct EncryptedMessage) +
3164           sizeof (struct GNUNET_MessageHeader))
3165         {
3166           GNUNET_break_op (0);
3167           return;
3168         }
3169       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3170           (n->status != PEER_STATE_KEY_CONFIRMED))
3171         {
3172           GNUNET_break_op (0);
3173           return;
3174         }
3175       handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3176       break;
3177     case GNUNET_MESSAGE_TYPE_CORE_PING:
3178       if (size != sizeof (struct PingMessage))
3179         {
3180           GNUNET_break_op (0);
3181           return;
3182         }
3183       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3184           (n->status != PEER_STATE_KEY_CONFIRMED))
3185         {
3186 #if DEBUG_CORE
3187           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3188                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3189                       "PING", GNUNET_i2s (&n->peer));
3190 #endif
3191           GNUNET_free_non_null (n->pending_ping);
3192           n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3193           memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3194           return;
3195         }
3196       handle_ping (n, (const struct PingMessage *) message);
3197       break;
3198     case GNUNET_MESSAGE_TYPE_CORE_PONG:
3199       if (size != sizeof (struct PongMessage))
3200         {
3201           GNUNET_break_op (0);
3202           return;
3203         }
3204       if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3205            (n->status != PEER_STATE_KEY_CONFIRMED) )
3206         {
3207 #if DEBUG_CORE
3208           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3209                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3210                       "PONG", GNUNET_i2s (&n->peer));
3211 #endif
3212           GNUNET_free_non_null (n->pending_pong);
3213           n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3214           memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3215           return;
3216         }
3217       handle_pong (n, (const struct PongMessage *) message);
3218       break;
3219     default:
3220       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3221                   _("Unsupported message of type %u received.\n"), type);
3222       return;
3223     }
3224   if (n->status == PEER_STATE_KEY_CONFIRMED)
3225     {
3226       now = GNUNET_TIME_absolute_get ();
3227       n->last_activity = now;
3228       if (!up)
3229         n->time_established = now;
3230     }
3231 }
3232
3233
3234 /**
3235  * Function that recalculates the bandwidth quota for the
3236  * given neighbour and transmits it to the transport service.
3237  * 
3238  * @param cls neighbour for the quota update
3239  * @param tc context
3240  */
3241 static void
3242 neighbour_quota_update (void *cls,
3243                         const struct GNUNET_SCHEDULER_TaskContext *tc)
3244 {
3245   struct Neighbour *n = cls;
3246   uint32_t q_in;
3247   double pref_rel;
3248   double share;
3249   unsigned long long distributable;
3250   uint32_t qin_ms;
3251   uint32_t qout_ms;
3252   
3253   n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3254   /* calculate relative preference among all neighbours;
3255      divides by a bit more to avoid division by zero AND to
3256      account for possibility of new neighbours joining any time 
3257      AND to convert to double... */
3258   if (preference_sum == 0)
3259     {
3260       pref_rel = 1.0 / (double) neighbour_count;
3261     }
3262   else
3263     {
3264       pref_rel = n->current_preference / preference_sum;
3265     }
3266   
3267   distributable = 0;
3268   if (bandwidth_target_out > neighbour_count * MIN_BPM_PER_PEER)
3269     distributable = bandwidth_target_out - neighbour_count * MIN_BPM_PER_PEER;
3270   share = distributable * pref_rel;
3271   q_in = MIN_BPM_PER_PEER + (unsigned long long) share;
3272   /* check if we want to disconnect for good due to inactivity */
3273   if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3274        (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3275     {
3276 #if DEBUG_CORE
3277   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3278               "Forcing disconnect of `%4s' due to inactivity (?).\n",
3279               GNUNET_i2s (&n->peer));
3280 #endif
3281       q_in = 0; /* force disconnect */
3282     }
3283 #if DEBUG_CORE_QUOTA
3284   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3285               "Current quota for `%4s' is %llu in (old: %llu) / %llu out (%llu internal)\n",
3286               GNUNET_i2s (&n->peer),
3287               (unsigned long long) q_in,
3288               (unsigned long long) n->bpm_in,
3289               (unsigned long long) n->bpm_out,
3290               (unsigned long long) n->bpm_out_internal_limit);
3291 #endif
3292   if ( (n->bpm_in + MIN_BPM_CHANGE < q_in) ||
3293        (n->bpm_in - MIN_BPM_CHANGE > q_in) ) 
3294     {
3295       n->bpm_in = q_in;
3296       /* need to convert to bytes / ms, rounding up! */
3297       qin_ms = (q_in == 0) ? 0 : 1 + q_in / 60000;
3298       qout_ms = (n->bpm_out == 0) ? 0 : 1 + n->bpm_out / 60000;
3299       GNUNET_TRANSPORT_set_quota (transport,
3300                                   &n->peer,
3301                                   n->bpm_in, 
3302                                   n->bpm_out,
3303                                   GNUNET_TIME_UNIT_FOREVER_REL,
3304                                   NULL, NULL);
3305     }
3306   schedule_quota_update (n);
3307 }
3308
3309
3310 /**
3311  * Function called by transport to notify us that
3312  * a peer connected to us (on the network level).
3313  *
3314  * @param cls closure
3315  * @param peer the peer that connected
3316  * @param latency current latency of the connection
3317  * @param distance in overlay hops, as given by transport plugin
3318  */
3319 static void
3320 handle_transport_notify_connect (void *cls,
3321                                  const struct GNUNET_PeerIdentity *peer,
3322                                  struct GNUNET_TIME_Relative latency,
3323                                  unsigned int distance)
3324 {
3325   struct Neighbour *n;
3326   struct GNUNET_TIME_Absolute now;
3327   struct ConnectNotifyMessage cnm;
3328
3329   n = find_neighbour (peer);
3330   if (n != NULL)
3331     {
3332       if (n->is_connected)
3333         {
3334           /* duplicate connect notification!? */
3335           GNUNET_break (0);
3336           return;
3337         }
3338     }
3339   else
3340     {
3341       n = create_neighbour (peer);
3342     }
3343   now = GNUNET_TIME_absolute_get ();
3344   n->is_connected = GNUNET_YES;      
3345   n->last_latency = latency;
3346   n->last_distance = distance;
3347   n->last_asw_update = now;
3348   n->last_arw_update = now;
3349 #if DEBUG_CORE
3350   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3351               "Received connection from `%4s'.\n",
3352               GNUNET_i2s (&n->peer));
3353 #endif
3354   cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3355   cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3356   cnm.distance = htonl (n->last_distance);
3357   cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3358   cnm.peer = *peer;
3359   send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3360   send_key (n);
3361 }
3362
3363
3364 /**
3365  * Function called by transport telling us that a peer
3366  * disconnected.
3367  *
3368  * @param cls closure
3369  * @param peer the peer that disconnected
3370  */
3371 static void
3372 handle_transport_notify_disconnect (void *cls,
3373                                     const struct GNUNET_PeerIdentity *peer)
3374 {
3375   struct DisconnectNotifyMessage cnm;
3376   struct Neighbour *n;
3377
3378 #if DEBUG_CORE
3379   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3380               "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3381 #endif
3382   n = find_neighbour (peer);
3383   if (n == NULL)
3384     {
3385       GNUNET_break (0);
3386       return;
3387     }
3388   GNUNET_break (n->is_connected);
3389   cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3390   cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3391   cnm.peer = *peer;
3392   send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3393   n->is_connected = GNUNET_NO;
3394 }
3395
3396
3397 /**
3398  * Last task run during shutdown.  Disconnects us from
3399  * the transport.
3400  */
3401 static void
3402 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3403 {
3404   struct Neighbour *n;
3405   struct Client *c;
3406
3407 #if DEBUG_CORE
3408   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3409               "Core service shutting down.\n");
3410 #endif
3411   GNUNET_assert (transport != NULL);
3412   GNUNET_TRANSPORT_disconnect (transport);
3413   transport = NULL;
3414   while (NULL != (n = neighbours))
3415     {
3416       neighbours = n->next;
3417       GNUNET_assert (neighbour_count > 0);
3418       neighbour_count--;
3419       free_neighbour (n);
3420     }
3421   GNUNET_SERVER_notification_context_destroy (notifier);
3422   notifier = NULL;
3423   while (NULL != (c = clients))
3424     handle_client_disconnect (NULL, c->client_handle);
3425   if (my_private_key != NULL)
3426     GNUNET_CRYPTO_rsa_key_free (my_private_key);
3427 }
3428
3429
3430 /**
3431  * Initiate core service.
3432  *
3433  * @param cls closure
3434  * @param s scheduler to use
3435  * @param serv the initialized server
3436  * @param c configuration to use
3437  */
3438 static void
3439 run (void *cls,
3440      struct GNUNET_SCHEDULER_Handle *s,
3441      struct GNUNET_SERVER_Handle *serv,
3442      const struct GNUNET_CONFIGURATION_Handle *c)
3443 {
3444 #if 0
3445   unsigned long long qin;
3446   unsigned long long qout;
3447   unsigned long long tneigh;
3448 #endif
3449   char *keyfile;
3450
3451   sched = s;
3452   cfg = c;  
3453   /* parse configuration */
3454   if (
3455        (GNUNET_OK !=
3456         GNUNET_CONFIGURATION_get_value_number (c,
3457                                                "CORE",
3458                                                "TOTAL_QUOTA_IN",
3459                                                &bandwidth_target_in)) ||
3460        (GNUNET_OK !=
3461         GNUNET_CONFIGURATION_get_value_number (c,
3462                                                "CORE",
3463                                                "TOTAL_QUOTA_OUT",
3464                                                &bandwidth_target_out)) ||
3465        (GNUNET_OK !=
3466         GNUNET_CONFIGURATION_get_value_filename (c,
3467                                                  "GNUNETD",
3468                                                  "HOSTKEY", &keyfile)))
3469     {
3470       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3471                   _
3472                   ("Core service is lacking key configuration settings.  Exiting.\n"));
3473       GNUNET_SCHEDULER_shutdown (s);
3474       return;
3475     }
3476   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3477   GNUNET_free (keyfile);
3478   if (my_private_key == NULL)
3479     {
3480       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3481                   _("Core service could not access hostkey.  Exiting.\n"));
3482       GNUNET_SCHEDULER_shutdown (s);
3483       return;
3484     }
3485   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3486   GNUNET_CRYPTO_hash (&my_public_key,
3487                       sizeof (my_public_key), &my_identity.hashPubKey);
3488   /* setup notification */
3489   server = serv;
3490   notifier = GNUNET_SERVER_notification_context_create (server, 
3491                                                         MAX_NOTIFY_QUEUE);
3492   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3493   /* setup transport connection */
3494   transport = GNUNET_TRANSPORT_connect (sched,
3495                                         cfg,
3496                                         NULL,
3497                                         &handle_transport_receive,
3498                                         &handle_transport_notify_connect,
3499                                         &handle_transport_notify_disconnect);
3500   GNUNET_assert (NULL != transport);
3501   GNUNET_SCHEDULER_add_delayed (sched,
3502                                 GNUNET_TIME_UNIT_FOREVER_REL,
3503                                 &cleaning_task, NULL);
3504   /* process client requests */
3505   GNUNET_SERVER_add_handlers (server, handlers);
3506   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3507               _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3508 }
3509
3510
3511
3512 /**
3513  * The main function for the transport service.
3514  *
3515  * @param argc number of arguments from the command line
3516  * @param argv command line arguments
3517  * @return 0 ok, 1 on error
3518  */
3519 int
3520 main (int argc, char *const *argv)
3521 {
3522   return (GNUNET_OK ==
3523           GNUNET_SERVICE_run (argc,
3524                               argv,
3525                               "core",
3526                               GNUNET_SERVICE_OPTION_NONE,
3527                               &run, NULL)) ? 0 : 1;
3528 }
3529
3530 /* end of gnunet-service-core.c */