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