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