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