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