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