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