(no commit message)
[oweals/gnunet.git] / src / core / gnunet-service-core.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010 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 3, 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  * Function called by transport telling us that a peer
834  * changed status.
835  *
836  * @param peer the peer that changed status
837  */
838 static void
839 handle_peer_status_change (struct Neighbour *n)
840 {
841   struct PeerStatusNotifyMessage psnm;
842
843   if (! n->is_connected)
844     return;
845 #if DEBUG_CORE
846   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
847               "Peer `%4s' changed status\n",
848               GNUNET_i2s (&n->peer));
849 #endif
850   psnm.header.size = htons (sizeof (struct PeerStatusNotifyMessage));
851   psnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_STATUS_CHANGE);
852   psnm.distance = htonl (n->last_distance);
853   psnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
854   psnm.timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_add (n->last_activity,
855                                                                       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
856   psnm.bandwidth_in = n->bw_in;
857   psnm.bandwidth_out = n->bw_out;
858   psnm.peer = n->peer;
859   send_to_all_clients (&psnm.header, 
860                        GNUNET_YES, 
861                        GNUNET_CORE_OPTION_SEND_STATUS_CHANGE);
862   GNUNET_STATISTICS_update (stats, 
863                             gettext_noop ("# peer status changes"), 
864                             1, 
865                             GNUNET_NO);
866 }
867
868
869 /**
870  * Handle CORE_INIT request.
871  */
872 static void
873 handle_client_init (void *cls,
874                     struct GNUNET_SERVER_Client *client,
875                     const struct GNUNET_MessageHeader *message)
876 {
877   const struct InitMessage *im;
878   struct InitReplyMessage irm;
879   struct Client *c;
880   uint16_t msize;
881   const uint16_t *types;
882   uint16_t *wtypes;
883   struct Neighbour *n;
884   struct ConnectNotifyMessage cnm;
885   unsigned int i;
886
887 #if DEBUG_CORE_CLIENT
888   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
889               "Client connecting to core service with `%s' message\n",
890               "INIT");
891 #endif
892   /* check that we don't have an entry already */
893   c = clients;
894   while (c != NULL)
895     {
896       if (client == c->client_handle)
897         {
898           GNUNET_break (0);
899           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
900           return;
901         }
902       c = c->next;
903     }
904   msize = ntohs (message->size);
905   if (msize < sizeof (struct InitMessage))
906     {
907       GNUNET_break (0);
908       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
909       return;
910     }
911   GNUNET_SERVER_notification_context_add (notifier, client);
912   im = (const struct InitMessage *) message;
913   types = (const uint16_t *) &im[1];
914   msize -= sizeof (struct InitMessage);
915   c = GNUNET_malloc (sizeof (struct Client) + msize);
916   c->client_handle = client;
917   c->next = clients;
918   clients = c;
919   c->tcnt = msize / sizeof (uint16_t);
920   c->types = (const uint16_t *) &c[1];
921   wtypes = (uint16_t *) &c[1];
922   for (i=0;i<c->tcnt;i++)
923     wtypes[i] = ntohs (types[i]);
924   c->options = ntohl (im->options);
925 #if DEBUG_CORE_CLIENT
926   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
927               "Client %p is interested in %u message types\n",
928               c,
929               (unsigned int) c->tcnt);
930 #endif
931   /* send init reply message */
932   irm.header.size = htons (sizeof (struct InitReplyMessage));
933   irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
934   irm.reserved = htonl (0);
935   memcpy (&irm.publicKey,
936           &my_public_key,
937           sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
938 #if DEBUG_CORE_CLIENT
939   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
940               "Sending `%s' message to client.\n", "INIT_REPLY");
941 #endif
942   send_to_client (c, &irm.header, GNUNET_NO);
943   if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
944     {
945       /* notify new client about existing neighbours */
946       cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
947       cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
948       n = neighbours;
949       while (n != NULL)
950         {
951           if (n->status == PEER_STATE_KEY_CONFIRMED)
952             {
953 #if DEBUG_CORE_CLIENT
954               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
955                           "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
956 #endif
957               cnm.distance = htonl (n->last_distance);
958               cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
959               cnm.peer = n->peer;
960               send_to_client (c, &cnm.header, GNUNET_NO);
961             }
962           n = n->next;
963         }
964     }
965   GNUNET_SERVER_receive_done (client, GNUNET_OK);
966 }
967
968
969 /**
970  * A client disconnected, clean up.
971  *
972  * @param cls closure
973  * @param client identification of the client
974  */
975 static void
976 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
977 {
978   struct Client *pos;
979   struct Client *prev;
980
981   if (client == NULL)
982     return;
983 #if DEBUG_CORE_CLIENT
984   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
985               "Client %p has disconnected from core service.\n",
986               client);
987 #endif
988   prev = NULL;
989   pos = clients;
990   while (pos != NULL)
991     {
992       if (client == pos->client_handle)
993         {
994           if (prev == NULL)
995             clients = pos->next;
996           else
997             prev->next = pos->next;
998           GNUNET_free (pos);
999           return;
1000         }
1001       prev = pos;
1002       pos = pos->next;
1003     }
1004   /* client never sent INIT */
1005 }
1006
1007
1008 /**
1009  * Handle REQUEST_INFO request.
1010  */
1011 static void
1012 handle_client_request_info (void *cls,
1013                             struct GNUNET_SERVER_Client *client,
1014                             const struct GNUNET_MessageHeader *message)
1015 {
1016   const struct RequestInfoMessage *rcm;
1017   struct Neighbour *n;
1018   struct ConfigurationInfoMessage cim;
1019   int32_t want_reserv;
1020   int32_t got_reserv;
1021   unsigned long long old_preference;
1022   struct GNUNET_SERVER_TransmitContext *tc;
1023
1024 #if DEBUG_CORE_CLIENT
1025   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1026               "Core service receives `%s' request.\n", "REQUEST_INFO");
1027 #endif
1028   rcm = (const struct RequestInfoMessage *) message;
1029   n = find_neighbour (&rcm->peer);
1030   memset (&cim, 0, sizeof (cim));
1031   if (n != NULL) 
1032     {
1033       want_reserv = ntohl (rcm->reserve_inbound);
1034       if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1035         {
1036           n->bw_out_internal_limit = rcm->limit_outbound;
1037           if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1038                                                                n->bw_out_external_limit).value__)
1039             {
1040               n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1041                                                       n->bw_out_external_limit);
1042               GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1043                                                      n->bw_out);
1044               GNUNET_TRANSPORT_set_quota (transport,
1045                                           &n->peer,
1046                                           n->bw_in,
1047                                           n->bw_out,
1048                                           GNUNET_TIME_UNIT_FOREVER_REL,
1049                                           NULL, NULL); 
1050               handle_peer_status_change (n);
1051             }
1052         }
1053       if (want_reserv < 0)
1054         {
1055           got_reserv = want_reserv;
1056         }
1057       else if (want_reserv > 0)
1058         {
1059           if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1060                                                   want_reserv).value == 0)
1061             got_reserv = want_reserv;
1062           else
1063             got_reserv = 0; /* all or nothing */
1064         }
1065       else
1066         got_reserv = 0;
1067       GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1068                                         got_reserv);
1069       old_preference = n->current_preference;
1070       n->current_preference += GNUNET_ntohll(rcm->preference_change);
1071       if (old_preference > n->current_preference) 
1072         {
1073           /* overflow; cap at maximum value */
1074           n->current_preference = ULLONG_MAX;
1075         }
1076       update_preference_sum (n->current_preference - old_preference);
1077 #if DEBUG_CORE_QUOTA
1078       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1079                   "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1080                   (int) want_reserv,
1081                   GNUNET_i2s (&rcm->peer),
1082                   (int) got_reserv);
1083 #endif
1084       cim.reserved_amount = htonl (got_reserv);
1085       cim.bw_in = n->bw_in;
1086       cim.bw_out = n->bw_out;
1087       cim.preference = n->current_preference;
1088     }
1089   cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1090   cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1091   cim.peer = rcm->peer;
1092
1093 #if DEBUG_CORE_CLIENT
1094   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1095               "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1096 #endif
1097   tc = GNUNET_SERVER_transmit_context_create (client);
1098   GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1099   GNUNET_SERVER_transmit_context_run (tc,
1100                                       GNUNET_TIME_UNIT_FOREVER_REL);
1101 }
1102
1103
1104 /**
1105  * Free the given entry for the neighbour (it has
1106  * already been removed from the list at this point).
1107  *
1108  * @param n neighbour to free
1109  */
1110 static void
1111 free_neighbour (struct Neighbour *n)
1112 {
1113   struct MessageEntry *m;
1114
1115 #if DEBUG_CORE
1116   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1117               "Destroying neighbour entry for peer `%4s'\n",
1118               GNUNET_i2s (&n->peer));
1119 #endif
1120   if (n->pitr != NULL)
1121     {
1122       GNUNET_PEERINFO_iterate_cancel (n->pitr);
1123       n->pitr = NULL;
1124     }
1125   if (n->skm != NULL)
1126     {
1127       GNUNET_free (n->skm);
1128       n->skm = NULL;
1129     }
1130   while (NULL != (m = n->messages))
1131     {
1132       n->messages = m->next;
1133       GNUNET_free (m);
1134     }
1135   while (NULL != (m = n->encrypted_head))
1136     {
1137       GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1138                                    n->encrypted_tail,
1139                                    m);
1140       GNUNET_free (m);
1141     }
1142   if (NULL != n->th)
1143     {
1144       GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1145       n->th = NULL;
1146     }
1147   if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1148     GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1149   if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1150     GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1151   if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1152     GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1153   if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1154     GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1155   if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)    
1156       GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1157   if (n->status == PEER_STATE_KEY_CONFIRMED)
1158     GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1159   GNUNET_free_non_null (n->public_key);
1160   GNUNET_free_non_null (n->pending_ping);
1161   GNUNET_free_non_null (n->pending_pong);
1162   GNUNET_free (n);
1163 }
1164
1165
1166 /**
1167  * Check if we have encrypted messages for the specified neighbour
1168  * pending, and if so, check with the transport about sending them
1169  * out.
1170  *
1171  * @param n neighbour to check.
1172  */
1173 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1174
1175
1176 /**
1177  * Encrypt size bytes from in and write the result to out.  Use the
1178  * key for outbound traffic of the given neighbour.
1179  *
1180  * @param n neighbour we are sending to
1181  * @param iv initialization vector to use
1182  * @param in ciphertext
1183  * @param out plaintext
1184  * @param size size of in/out
1185  * @return GNUNET_OK on success
1186  */
1187 static int
1188 do_encrypt (struct Neighbour *n,
1189             const GNUNET_HashCode * iv,
1190             const void *in, void *out, size_t size)
1191 {
1192   if (size != (uint16_t) size)
1193     {
1194       GNUNET_break (0);
1195       return GNUNET_NO;
1196     }
1197   GNUNET_assert (size ==
1198                  GNUNET_CRYPTO_aes_encrypt (in,
1199                                             (uint16_t) size,
1200                                             &n->encrypt_key,
1201                                             (const struct
1202                                              GNUNET_CRYPTO_AesInitializationVector
1203                                              *) iv, out));
1204   GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1205 #if DEBUG_CORE
1206   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1207               "Encrypted %u bytes for `%4s' using key %u\n", 
1208               (unsigned int) size,
1209               GNUNET_i2s (&n->peer),
1210               (unsigned int) n->encrypt_key.crc32);
1211 #endif
1212   return GNUNET_OK;
1213 }
1214
1215
1216 /**
1217  * Consider freeing the given neighbour since we may not need
1218  * to keep it around anymore.
1219  *
1220  * @param n neighbour to consider discarding
1221  */
1222 static void
1223 consider_free_neighbour (struct Neighbour *n);
1224
1225
1226 /**
1227  * Task triggered when a neighbour entry is about to time out 
1228  * (and we should prevent this by sending a PING).
1229  *
1230  * @param cls the 'struct Neighbour'
1231  * @param tc scheduler context (not used)
1232  */
1233 static void
1234 send_keep_alive (void *cls,
1235                  const struct GNUNET_SCHEDULER_TaskContext *tc)
1236 {
1237   struct Neighbour *n = cls;
1238   struct GNUNET_TIME_Relative retry;
1239   struct GNUNET_TIME_Relative left;
1240   struct MessageEntry *me;
1241   struct PingMessage pp;
1242   struct PingMessage *pm;
1243
1244   n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1245   /* send PING */
1246   me = GNUNET_malloc (sizeof (struct MessageEntry) +
1247                       sizeof (struct PingMessage));
1248   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1249   me->priority = PING_PRIORITY;
1250   me->size = sizeof (struct PingMessage);
1251   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1252                                      n->encrypted_tail,
1253                                      n->encrypted_tail,
1254                                      me);
1255   pm = (struct PingMessage *) &me[1];
1256   pm->header.size = htons (sizeof (struct PingMessage));
1257   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1258   pp.challenge = htonl (n->ping_challenge);
1259   pp.target = n->peer;
1260 #if DEBUG_HANDSHAKE
1261   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1262               "Encrypting `%s' message with challenge %u for `%4s' using key %u.\n",
1263               "PING", 
1264               (unsigned int) n->ping_challenge,
1265               GNUNET_i2s (&n->peer),
1266               (unsigned int) n->encrypt_key.crc32);
1267 #endif
1268   do_encrypt (n,
1269               &n->peer.hashPubKey,
1270               &pp.challenge,
1271               &pm->challenge,
1272               sizeof (struct PingMessage) -
1273               sizeof (struct GNUNET_MessageHeader));
1274   process_encrypted_neighbour_queue (n);
1275   /* reschedule PING job */
1276   left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1277                                                                        GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1278   retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1279                                     MIN_PING_FREQUENCY);
1280   n->keep_alive_task 
1281     = GNUNET_SCHEDULER_add_delayed (sched, 
1282                                     retry,
1283                                     &send_keep_alive,
1284                                     n);
1285
1286 }
1287
1288
1289 /**
1290  * Task triggered when a neighbour entry might have gotten stale.
1291  *
1292  * @param cls the 'struct Neighbour'
1293  * @param tc scheduler context (not used)
1294  */
1295 static void
1296 consider_free_task (void *cls,
1297                     const struct GNUNET_SCHEDULER_TaskContext *tc)
1298 {
1299   struct Neighbour *n = cls;
1300
1301   n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1302   consider_free_neighbour (n);
1303 }
1304
1305
1306 /**
1307  * Consider freeing the given neighbour since we may not need
1308  * to keep it around anymore.
1309  *
1310  * @param n neighbour to consider discarding
1311  */
1312 static void
1313 consider_free_neighbour (struct Neighbour *n)
1314
1315   struct Neighbour *pos;
1316   struct Neighbour *prev;
1317   struct GNUNET_TIME_Relative left;
1318
1319   if ( (n->th != NULL) ||
1320        (n->pitr != NULL) ||
1321        (GNUNET_YES == n->is_connected) )
1322     return; /* no chance */
1323     
1324   left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1325                                                                        GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1326   if (left.value > 0)
1327     {
1328       if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1329         GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1330       n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1331                                                          left,
1332                                                          &consider_free_task,
1333                                                          n);
1334       return;
1335     }
1336   /* actually free the neighbour... */
1337   prev = NULL;
1338   pos = neighbours;
1339   while (pos != n)
1340     {
1341       prev = pos;
1342       pos = pos->next;
1343     }
1344   if (prev == NULL)
1345     neighbours = n->next;
1346   else
1347     prev->next = n->next;
1348   GNUNET_assert (neighbour_count > 0);
1349   neighbour_count--;
1350   GNUNET_STATISTICS_set (stats,
1351                          gettext_noop ("# neighbour entries allocated"), 
1352                          neighbour_count,
1353                          GNUNET_NO);
1354   free_neighbour (n);
1355 }
1356
1357
1358 /**
1359  * Function called when the transport service is ready to
1360  * receive an encrypted message for the respective peer
1361  *
1362  * @param cls neighbour to use message from
1363  * @param size number of bytes we can transmit
1364  * @param buf where to copy the message
1365  * @return number of bytes transmitted
1366  */
1367 static size_t
1368 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1369 {
1370   struct Neighbour *n = cls;
1371   struct MessageEntry *m;
1372   size_t ret;
1373   char *cbuf;
1374
1375   n->th = NULL;
1376   m = n->encrypted_head;
1377   if (m == NULL)
1378     {
1379 #if DEBUG_CORE
1380       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1381                   "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1382                   GNUNET_i2s (&n->peer));
1383 #endif
1384       return 0;
1385     }
1386   GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1387                                n->encrypted_tail,
1388                                m);
1389   ret = 0;
1390   cbuf = buf;
1391   if (buf != NULL)
1392     {
1393       GNUNET_assert (size >= m->size);
1394       memcpy (cbuf, &m[1], m->size);
1395       ret = m->size;
1396       GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1397                                         m->size);
1398 #if DEBUG_CORE
1399       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1400                   "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1401                   (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1402                   (unsigned int) ret, 
1403                   GNUNET_i2s (&n->peer));
1404 #endif
1405       process_encrypted_neighbour_queue (n);
1406     }
1407   else
1408     {
1409 #if DEBUG_CORE
1410       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1411                   "Transmission of message of type %u and size %u failed\n",
1412                   (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1413                   (unsigned int) m->size);
1414 #endif
1415     }
1416   GNUNET_free (m);
1417   consider_free_neighbour (n);
1418   return ret;
1419 }
1420
1421
1422 /**
1423  * Check if we have plaintext messages for the specified neighbour
1424  * pending, and if so, consider batching and encrypting them (and
1425  * then trigger processing of the encrypted queue if needed).
1426  *
1427  * @param n neighbour to check.
1428  */
1429 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1430
1431
1432 /**
1433  * Check if we have encrypted messages for the specified neighbour
1434  * pending, and if so, check with the transport about sending them
1435  * out.
1436  *
1437  * @param n neighbour to check.
1438  */
1439 static void
1440 process_encrypted_neighbour_queue (struct Neighbour *n)
1441 {
1442   struct MessageEntry *m;
1443  
1444   if (n->th != NULL)
1445     return;  /* request already pending */
1446   m = n->encrypted_head;
1447   if (m == NULL)
1448     {
1449       /* encrypted queue empty, try plaintext instead */
1450       process_plaintext_neighbour_queue (n);
1451       return;
1452     }
1453 #if DEBUG_CORE
1454   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1455               "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1456               (unsigned int) m->size,
1457               GNUNET_i2s (&n->peer),
1458               (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).
1459               value);
1460 #endif
1461   n->th =
1462     GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1463                                             m->size,
1464                                             m->priority,
1465                                             GNUNET_TIME_absolute_get_remaining
1466                                             (m->deadline),
1467                                             &notify_encrypted_transmit_ready,
1468                                             n);
1469   if (n->th == NULL)
1470     {
1471       /* message request too large or duplicate request */
1472       GNUNET_break (0);
1473       /* discard encrypted message */
1474       GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1475                                    n->encrypted_tail,
1476                                    m);
1477       GNUNET_free (m);
1478       process_encrypted_neighbour_queue (n);
1479     }
1480 }
1481
1482
1483 /**
1484  * Decrypt size bytes from in and write the result to out.  Use the
1485  * key for inbound traffic of the given neighbour.  This function does
1486  * NOT do any integrity-checks on the result.
1487  *
1488  * @param n neighbour we are receiving from
1489  * @param iv initialization vector to use
1490  * @param in ciphertext
1491  * @param out plaintext
1492  * @param size size of in/out
1493  * @return GNUNET_OK on success
1494  */
1495 static int
1496 do_decrypt (struct Neighbour *n,
1497             const GNUNET_HashCode * iv,
1498             const void *in, void *out, size_t size)
1499 {
1500   if (size != (uint16_t) size)
1501     {
1502       GNUNET_break (0);
1503       return GNUNET_NO;
1504     }
1505   if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1506       (n->status != PEER_STATE_KEY_CONFIRMED))
1507     {
1508       GNUNET_break_op (0);
1509       return GNUNET_SYSERR;
1510     }
1511   if (size !=
1512       GNUNET_CRYPTO_aes_decrypt (in,
1513                                  (uint16_t) size,
1514                                  &n->decrypt_key,
1515                                  (const struct
1516                                   GNUNET_CRYPTO_AesInitializationVector *) iv,
1517                                  out))
1518     {
1519       GNUNET_break (0);
1520       return GNUNET_SYSERR;
1521     }
1522   GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1523 #if DEBUG_CORE
1524   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1525               "Decrypted %u bytes from `%4s' using key %u\n",
1526               (unsigned int) size, 
1527               GNUNET_i2s (&n->peer),
1528               (unsigned int) n->decrypt_key.crc32);
1529 #endif
1530   return GNUNET_OK;
1531 }
1532
1533
1534 /**
1535  * Select messages for transmission.  This heuristic uses a combination
1536  * of earliest deadline first (EDF) scheduling (with bounded horizon)
1537  * and priority-based discard (in case no feasible schedule exist) and
1538  * speculative optimization (defer any kind of transmission until
1539  * we either create a batch of significant size, 25% of max, or until
1540  * we are close to a deadline).  Furthermore, when scheduling the
1541  * heuristic also packs as many messages into the batch as possible,
1542  * starting with those with the earliest deadline.  Yes, this is fun.
1543  *
1544  * @param n neighbour to select messages from
1545  * @param size number of bytes to select for transmission
1546  * @param retry_time set to the time when we should try again
1547  *        (only valid if this function returns zero)
1548  * @return number of bytes selected, or 0 if we decided to
1549  *         defer scheduling overall; in that case, retry_time is set.
1550  */
1551 static size_t
1552 select_messages (struct Neighbour *n,
1553                  size_t size, struct GNUNET_TIME_Relative *retry_time)
1554 {
1555   struct MessageEntry *pos;
1556   struct MessageEntry *min;
1557   struct MessageEntry *last;
1558   unsigned int min_prio;
1559   struct GNUNET_TIME_Absolute t;
1560   struct GNUNET_TIME_Absolute now;
1561   struct GNUNET_TIME_Relative delta;
1562   uint64_t avail;
1563   struct GNUNET_TIME_Relative slack;     /* how long could we wait before missing deadlines? */
1564   size_t off;
1565   uint64_t tsize;
1566   unsigned int queue_size;
1567   int discard_low_prio;
1568
1569   GNUNET_assert (NULL != n->messages);
1570   now = GNUNET_TIME_absolute_get ();
1571   /* last entry in linked list of messages processed */
1572   last = NULL;
1573   /* should we remove the entry with the lowest
1574      priority from consideration for scheduling at the
1575      end of the loop? */
1576   queue_size = 0;
1577   tsize = 0;
1578   pos = n->messages;
1579   while (pos != NULL)
1580     {
1581       queue_size++;
1582       tsize += pos->size;
1583       pos = pos->next;
1584     }
1585   discard_low_prio = GNUNET_YES;
1586   while (GNUNET_YES == discard_low_prio)
1587     {
1588       min = NULL;
1589       min_prio = UINT_MAX;
1590       discard_low_prio = GNUNET_NO;
1591       /* calculate number of bytes available for transmission at time "t" */
1592       avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1593       t = now;
1594       /* how many bytes have we (hypothetically) scheduled so far */
1595       off = 0;
1596       /* maximum time we can wait before transmitting anything
1597          and still make all of our deadlines */
1598       slack = GNUNET_TIME_UNIT_FOREVER_REL;
1599       pos = n->messages;
1600       /* note that we use "*2" here because we want to look
1601          a bit further into the future; much more makes no
1602          sense since new message might be scheduled in the
1603          meantime... */
1604       while ((pos != NULL) && (off < size * 2))
1605         {         
1606           if (pos->do_transmit == GNUNET_YES)
1607             {
1608               /* already removed from consideration */
1609               pos = pos->next;
1610               continue;
1611             }
1612           if (discard_low_prio == GNUNET_NO)
1613             {
1614               delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1615               if (delta.value > 0)
1616                 {
1617                   // FIXME: HUH? Check!
1618                   t = pos->deadline;
1619                   avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1620                                                                        delta);
1621                 }
1622               if (avail < pos->size)
1623                 {
1624                   // FIXME: HUH? Check!
1625                   discard_low_prio = GNUNET_YES;        /* we could not schedule this one! */
1626                 }
1627               else
1628                 {
1629                   avail -= pos->size;
1630                   /* update slack, considering both its absolute deadline
1631                      and relative deadlines caused by other messages
1632                      with their respective load */
1633                   slack = GNUNET_TIME_relative_min (slack,
1634                                                     GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1635                                                                                           avail));
1636                   if (pos->deadline.value <= now.value) 
1637                     {
1638                       /* now or never */
1639                       slack = GNUNET_TIME_UNIT_ZERO;
1640                     }
1641                   else if (GNUNET_YES == pos->got_slack)
1642                     {
1643                       /* should be soon now! */
1644                       slack = GNUNET_TIME_relative_min (slack,
1645                                                         GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1646                     }
1647                   else
1648                     {
1649                       slack =
1650                         GNUNET_TIME_relative_min (slack, 
1651                                                   GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1652                       pos->got_slack = GNUNET_YES;
1653                       pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1654                                                                       GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
1655                     }
1656                 }
1657             }
1658           off += pos->size;
1659           t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1660           if (pos->priority <= min_prio)
1661             {
1662               /* update min for discard */
1663               min_prio = pos->priority;
1664               min = pos;
1665             }
1666           pos = pos->next;
1667         }
1668       if (discard_low_prio)
1669         {
1670           GNUNET_assert (min != NULL);
1671           /* remove lowest-priority entry from consideration */
1672           min->do_transmit = GNUNET_YES;        /* means: discard (for now) */
1673         }
1674       last = pos;
1675     }
1676   /* guard against sending "tiny" messages with large headers without
1677      urgent deadlines */
1678   if ( (slack.value > GNUNET_CONSTANTS_MAX_CORK_DELAY.value) && 
1679        (size > 4 * off) &&
1680        (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1681     {
1682       /* less than 25% of message would be filled with deadlines still
1683          being met if we delay by one second or more; so just wait for
1684          more data; but do not wait longer than 1s (since we don't want
1685          to delay messages for a really long time either). */
1686       *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1687       /* reset do_transmit values for next time */
1688       while (pos != last)
1689         {
1690           pos->do_transmit = GNUNET_NO;   
1691           pos = pos->next;
1692         }
1693 #if DEBUG_CORE
1694       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1695                   "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1696                   (unsigned long long) retry_time->value,
1697                   (unsigned int) off,
1698                   (unsigned int) size);
1699 #endif
1700       return 0;
1701     }
1702   /* select marked messages (up to size) for transmission */
1703   off = 0;
1704   pos = n->messages;
1705   while (pos != last)
1706     {
1707       if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1708         {
1709           pos->do_transmit = GNUNET_YES;        /* mark for transmission */
1710           off += pos->size;
1711           size -= pos->size;
1712 #if DEBUG_CORE
1713           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1714                       "Selecting message of size %u for transmission\n",
1715                       (unsigned int) pos->size);
1716 #endif
1717         }
1718       else
1719         {
1720 #if DEBUG_CORE
1721           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1722                       "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
1723                       (unsigned int) pos->size,
1724                       size);
1725 #endif
1726           pos->do_transmit = GNUNET_NO;   /* mark for not transmitting! */
1727         }
1728       pos = pos->next;
1729     }
1730 #if DEBUG_CORE
1731   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1732               "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1733               (unsigned long long) off, (unsigned long long) tsize,
1734               queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
1735               GNUNET_i2s (&n->peer));
1736 #endif
1737   return off;
1738 }
1739
1740
1741 /**
1742  * Batch multiple messages into a larger buffer.
1743  *
1744  * @param n neighbour to take messages from
1745  * @param buf target buffer
1746  * @param size size of buf
1747  * @param deadline set to transmission deadline for the result
1748  * @param retry_time set to the time when we should try again
1749  *        (only valid if this function returns zero)
1750  * @param priority set to the priority of the batch
1751  * @return number of bytes written to buf (can be zero)
1752  */
1753 static size_t
1754 batch_message (struct Neighbour *n,
1755                char *buf,
1756                size_t size,
1757                struct GNUNET_TIME_Absolute *deadline,
1758                struct GNUNET_TIME_Relative *retry_time,
1759                unsigned int *priority)
1760 {
1761   char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1762   struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1763   struct MessageEntry *pos;
1764   struct MessageEntry *prev;
1765   struct MessageEntry *next;
1766   size_t ret;
1767   
1768   ret = 0;
1769   *priority = 0;
1770   *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1771   *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1772   if (0 == select_messages (n, size, retry_time))
1773     {
1774 #if DEBUG_CORE
1775       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1776                   "No messages selected, will try again in %llu ms\n",
1777                   retry_time->value);
1778 #endif
1779       return 0;
1780     }
1781   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1782   ntm->distance = htonl (n->last_distance);
1783   ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1784   ntm->peer = n->peer;
1785   pos = n->messages;
1786   prev = NULL;
1787   while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1788     {
1789       next = pos->next;
1790       if (GNUNET_YES == pos->do_transmit)
1791         {
1792           GNUNET_assert (pos->size <= size);
1793           /* do notifications */
1794           /* FIXME: track if we have *any* client that wants
1795              full notifications and only do this if that is
1796              actually true */
1797           if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1798             {
1799               memcpy (&ntm[1], &pos[1], pos->size);
1800               ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) + 
1801                                         sizeof (struct GNUNET_MessageHeader));
1802               send_to_all_clients (&ntm->header,
1803                                    GNUNET_YES,
1804                                    GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1805             }
1806           else
1807             {
1808               /* message too large for 'full' notifications, we do at
1809                  least the 'hdr' type */
1810               memcpy (&ntm[1],
1811                       &pos[1],
1812                       sizeof (struct GNUNET_MessageHeader));
1813             }
1814           ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) + 
1815                                     pos->size);
1816           send_to_all_clients (&ntm->header,
1817                                GNUNET_YES,
1818                                GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);   
1819 #if DEBUG_HANDSHAKE
1820           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1821                       "Encrypting %u bytes with message of type %u and size %u\n",
1822                       pos->size,
1823                       (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
1824                       (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
1825 #endif
1826           /* copy for encrypted transmission */
1827           memcpy (&buf[ret], &pos[1], pos->size);
1828           ret += pos->size;
1829           size -= pos->size;
1830           *priority += pos->priority;
1831 #if DEBUG_CORE
1832           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1833                       "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1834                       (unsigned int) pos->size,
1835                       (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1836 #endif
1837           deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1838           GNUNET_free (pos);
1839           if (prev == NULL)
1840             n->messages = next;
1841           else
1842             prev->next = next;
1843         }
1844       else
1845         {
1846           prev = pos;
1847         }
1848       pos = next;
1849     }
1850 #if DEBUG_CORE
1851   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1852               "Deadline for message batch is %llu ms\n",
1853               GNUNET_TIME_absolute_get_remaining (*deadline).value);
1854 #endif
1855   return ret;
1856 }
1857
1858
1859 /**
1860  * Remove messages with deadlines that have long expired from
1861  * the queue.
1862  *
1863  * @param n neighbour to inspect
1864  */
1865 static void
1866 discard_expired_messages (struct Neighbour *n)
1867 {
1868   struct MessageEntry *prev;
1869   struct MessageEntry *next;
1870   struct MessageEntry *pos;
1871   struct GNUNET_TIME_Absolute now;
1872   struct GNUNET_TIME_Relative delta;
1873
1874   now = GNUNET_TIME_absolute_get ();
1875   prev = NULL;
1876   pos = n->messages;
1877   while (pos != NULL) 
1878     {
1879       next = pos->next;
1880       delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1881       if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1882         {
1883 #if DEBUG_CORE
1884           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1885                       "Message is %llu ms past due, discarding.\n",
1886                       delta.value);
1887 #endif
1888           if (prev == NULL)
1889             n->messages = next;
1890           else
1891             prev->next = next;
1892           GNUNET_free (pos);
1893         }
1894       else
1895         prev = pos;
1896       pos = next;
1897     }
1898 }
1899
1900
1901 /**
1902  * Signature of the main function of a task.
1903  *
1904  * @param cls closure
1905  * @param tc context information (why was this task triggered now)
1906  */
1907 static void
1908 retry_plaintext_processing (void *cls,
1909                             const struct GNUNET_SCHEDULER_TaskContext *tc)
1910 {
1911   struct Neighbour *n = cls;
1912
1913   n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1914   process_plaintext_neighbour_queue (n);
1915 }
1916
1917
1918 /**
1919  * Send our key (and encrypted PING) to the other peer.
1920  *
1921  * @param n the other peer
1922  */
1923 static void send_key (struct Neighbour *n);
1924
1925 /**
1926  * Task that will retry "send_key" if our previous attempt failed
1927  * to yield a PONG.
1928  */
1929 static void
1930 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1931 {
1932   struct Neighbour *n = cls;
1933
1934 #if DEBUG_CORE
1935   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1936               "Retrying key transmission to `%4s'\n",
1937               GNUNET_i2s (&n->peer));
1938 #endif
1939   n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1940   n->set_key_retry_frequency =
1941     GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1942   send_key (n);
1943 }
1944
1945
1946 /**
1947  * Check if we have plaintext messages for the specified neighbour
1948  * pending, and if so, consider batching and encrypting them (and
1949  * then trigger processing of the encrypted queue if needed).
1950  *
1951  * @param n neighbour to check.
1952  */
1953 static void
1954 process_plaintext_neighbour_queue (struct Neighbour *n)
1955 {
1956   char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)];        /* plaintext */
1957   size_t used;
1958   size_t esize;
1959   struct EncryptedMessage *em;  /* encrypted message */
1960   struct EncryptedMessage *ph;  /* plaintext header */
1961   struct MessageEntry *me;
1962   unsigned int priority;
1963   struct GNUNET_TIME_Absolute deadline;
1964   struct GNUNET_TIME_Relative retry_time;
1965   GNUNET_HashCode iv;
1966
1967   if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1968     {
1969       GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1970       n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1971     }
1972   switch (n->status)
1973     {
1974     case PEER_STATE_DOWN:
1975       send_key (n);
1976 #if DEBUG_CORE
1977       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1978                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1979                   GNUNET_i2s(&n->peer));
1980 #endif
1981       return;
1982     case PEER_STATE_KEY_SENT:
1983       if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1984         n->retry_set_key_task
1985           = GNUNET_SCHEDULER_add_delayed (sched,
1986                                           n->set_key_retry_frequency,
1987                                           &set_key_retry_task, n);    
1988 #if DEBUG_CORE
1989       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1990                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1991                   GNUNET_i2s(&n->peer));
1992 #endif
1993       return;
1994     case PEER_STATE_KEY_RECEIVED:
1995       if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)        
1996         n->retry_set_key_task
1997           = GNUNET_SCHEDULER_add_delayed (sched,
1998                                           n->set_key_retry_frequency,
1999                                           &set_key_retry_task, n);        
2000 #if DEBUG_CORE
2001       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2002                   "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2003                   GNUNET_i2s(&n->peer));
2004 #endif
2005       return;
2006     case PEER_STATE_KEY_CONFIRMED:
2007       /* ready to continue */
2008       break;
2009     }
2010   discard_expired_messages (n);
2011   if (n->messages == NULL)
2012     {
2013 #if DEBUG_CORE
2014       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2015                   "Plaintext message queue for `%4s' is empty.\n",
2016                   GNUNET_i2s(&n->peer));
2017 #endif
2018       return;                   /* no pending messages */
2019     }
2020   if (n->encrypted_head != NULL)
2021     {
2022 #if DEBUG_CORE
2023       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2024                   "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2025                   GNUNET_i2s(&n->peer));
2026 #endif
2027       return;                   /* wait for messages already encrypted to be
2028                                    processed first! */
2029     }
2030   ph = (struct EncryptedMessage *) pbuf;
2031   deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2032   priority = 0;
2033   used = sizeof (struct EncryptedMessage);
2034   used += batch_message (n,
2035                          &pbuf[used],
2036                          GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2037                          &deadline, &retry_time, &priority);
2038   if (used == sizeof (struct EncryptedMessage))
2039     {
2040 #if DEBUG_CORE
2041       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2042                   "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2043                   GNUNET_i2s(&n->peer));
2044 #endif
2045       /* no messages selected for sending, try again later... */
2046       n->retry_plaintext_task =
2047         GNUNET_SCHEDULER_add_delayed (sched,
2048                                       retry_time,
2049                                       &retry_plaintext_processing, n);
2050       return;
2051     }
2052 #if DEBUG_CORE_QUOTA
2053   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2054               "Sending %u b/s as new limit to peer `%4s'\n",
2055               (unsigned int) ntohl (n->bw_in.value__),
2056               GNUNET_i2s (&n->peer));
2057 #endif
2058   ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX));
2059   ph->sequence_number = htonl (++n->last_sequence_number_sent);
2060   ph->inbound_bw_limit = n->bw_in;
2061   ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2062
2063   /* setup encryption message header */
2064   me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2065   me->deadline = deadline;
2066   me->priority = priority;
2067   me->size = used;
2068   em = (struct EncryptedMessage *) &me[1];
2069   em->header.size = htons (used);
2070   em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2071   em->iv_seed = ph->iv_seed;
2072   esize = used - ENCRYPTED_HEADER_SIZE;
2073   GNUNET_CRYPTO_hmac (&n->encrypt_key,
2074                       &ph->sequence_number,
2075                       esize - sizeof (GNUNET_HashCode), 
2076                       &ph->hmac);
2077   GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
2078 #if DEBUG_HANDSHAKE
2079   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2080               "Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
2081               (unsigned int) (esize - sizeof (GNUNET_HashCode)),
2082               GNUNET_h2s (&ph->hmac),
2083               (int) ph->iv_seed);
2084 #endif
2085   /* encrypt */
2086 #if DEBUG_HANDSHAKE
2087   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2088               "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2089               (unsigned int) esize,
2090               GNUNET_i2s(&n->peer),
2091               (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2092 #endif
2093   GNUNET_assert (GNUNET_OK ==
2094                  do_encrypt (n,
2095                              &iv,
2096                              &ph->hmac,
2097                              &em->hmac, esize));
2098   /* append to transmission list */
2099   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2100                                      n->encrypted_tail,
2101                                      n->encrypted_tail,
2102                                      me);
2103   process_encrypted_neighbour_queue (n);
2104 }
2105
2106
2107 /**
2108  * Function that recalculates the bandwidth quota for the
2109  * given neighbour and transmits it to the transport service.
2110  * 
2111  * @param cls neighbour for the quota update
2112  * @param tc context
2113  */
2114 static void
2115 neighbour_quota_update (void *cls,
2116                         const struct GNUNET_SCHEDULER_TaskContext *tc);
2117
2118
2119 /**
2120  * Schedule the task that will recalculate the bandwidth
2121  * quota for this peer (and possibly force a disconnect of
2122  * idle peers by calculating a bandwidth of zero).
2123  */
2124 static void
2125 schedule_quota_update (struct Neighbour *n)
2126 {
2127   GNUNET_assert (n->quota_update_task ==
2128                  GNUNET_SCHEDULER_NO_TASK);
2129   n->quota_update_task
2130     = GNUNET_SCHEDULER_add_delayed (sched,
2131                                     QUOTA_UPDATE_FREQUENCY,
2132                                     &neighbour_quota_update,
2133                                     n);
2134 }
2135
2136
2137 /**
2138  * Initialize a new 'struct Neighbour'.
2139  *
2140  * @param pid ID of the new neighbour
2141  * @return handle for the new neighbour
2142  */
2143 static struct Neighbour *
2144 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2145 {
2146   struct Neighbour *n;
2147   struct GNUNET_TIME_Absolute now;
2148
2149 #if DEBUG_CORE
2150   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2151               "Creating neighbour entry for peer `%4s'\n",
2152               GNUNET_i2s (pid));
2153 #endif
2154   n = GNUNET_malloc (sizeof (struct Neighbour));
2155   n->next = neighbours;
2156   neighbours = n;
2157   neighbour_count++;
2158   GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2159   n->peer = *pid;
2160   GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2161   now = GNUNET_TIME_absolute_get ();
2162   n->encrypt_key_created = now;
2163   n->last_activity = now;
2164   n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2165   n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2166   n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2167   n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2168   n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2169   n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2170                                                 UINT32_MAX);
2171   neighbour_quota_update (n, NULL);
2172   consider_free_neighbour (n);
2173   return n;
2174 }
2175
2176
2177 /**
2178  * Handle CORE_SEND request.
2179  *
2180  * @param cls unused
2181  * @param client the client issuing the request
2182  * @param message the "struct SendMessage"
2183  */
2184 static void
2185 handle_client_send (void *cls,
2186                     struct GNUNET_SERVER_Client *client,
2187                     const struct GNUNET_MessageHeader *message)
2188 {
2189   const struct SendMessage *sm;
2190   struct Neighbour *n;
2191   struct MessageEntry *prev;
2192   struct MessageEntry *pos;
2193   struct MessageEntry *e; 
2194   struct MessageEntry *min_prio_entry;
2195   struct MessageEntry *min_prio_prev;
2196   unsigned int min_prio;
2197   unsigned int queue_size;
2198   uint16_t msize;
2199
2200   msize = ntohs (message->size);
2201   if (msize <
2202       sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2203     {
2204       GNUNET_break (0);
2205       if (client != NULL)
2206         GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2207       return;
2208     }
2209   sm = (const struct SendMessage *) message;
2210   msize -= sizeof (struct SendMessage);
2211   if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2212     {
2213       /* FIXME: should we not allow loopback-injection here? */
2214       GNUNET_break (0);
2215       if (client != NULL)
2216         GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2217       return;
2218     }
2219   n = find_neighbour (&sm->peer);
2220   if (n == NULL)
2221     n = create_neighbour (&sm->peer);
2222 #if DEBUG_CORE
2223   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2224               "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2225               "SEND",
2226               (unsigned int) msize, 
2227               GNUNET_i2s (&sm->peer));
2228 #endif
2229   /* bound queue size */
2230   discard_expired_messages (n);
2231   min_prio = UINT32_MAX;
2232   min_prio_entry = NULL;
2233   min_prio_prev = NULL;
2234   queue_size = 0;
2235   prev = NULL;
2236   pos = n->messages;
2237   while (pos != NULL) 
2238     {
2239       if (pos->priority < min_prio)
2240         {
2241           min_prio_entry = pos;
2242           min_prio_prev = prev;
2243           min_prio = pos->priority;
2244         }
2245       queue_size++;
2246       prev = pos;
2247       pos = pos->next;
2248     }
2249   if (queue_size >= MAX_PEER_QUEUE_SIZE)
2250     {
2251       /* queue full */
2252       if (ntohl(sm->priority) <= min_prio)
2253         {
2254           /* discard new entry */
2255 #if DEBUG_CORE
2256           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2257                       "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2258                       queue_size,
2259                       (unsigned int) MAX_PEER_QUEUE_SIZE,
2260                       (unsigned int) msize,
2261                       (unsigned int) ntohs (message->type));
2262 #endif
2263           if (client != NULL)
2264             GNUNET_SERVER_receive_done (client, GNUNET_OK);
2265           return;
2266         }
2267       /* discard "min_prio_entry" */
2268 #if DEBUG_CORE
2269       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2270                   "Queue full, discarding existing older request\n");
2271 #endif
2272       if (min_prio_prev == NULL)
2273         n->messages = min_prio_entry->next;
2274       else
2275         min_prio_prev->next = min_prio_entry->next;      
2276       GNUNET_free (min_prio_entry);     
2277     }
2278
2279 #if DEBUG_CORE
2280   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2281               "Adding transmission request for `%4s' of size %u to queue\n",
2282               GNUNET_i2s (&sm->peer),
2283               (unsigned int) msize);
2284 #endif  
2285   e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2286   e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2287   e->priority = ntohl (sm->priority);
2288   e->size = msize;
2289   memcpy (&e[1], &sm[1], msize);
2290
2291   /* insert, keep list sorted by deadline */
2292   prev = NULL;
2293   pos = n->messages;
2294   while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2295     {
2296       prev = pos;
2297       pos = pos->next;
2298     }
2299   if (prev == NULL)
2300     n->messages = e;
2301   else
2302     prev->next = e;
2303   e->next = pos;
2304
2305   /* consider scheduling now */
2306   process_plaintext_neighbour_queue (n);
2307   if (client != NULL)
2308     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2309 }
2310
2311
2312 /**
2313  * Function called when the transport service is ready to
2314  * receive a message.  Only resets 'n->th' to NULL.
2315  *
2316  * @param cls neighbour to use message from
2317  * @param size number of bytes we can transmit
2318  * @param buf where to copy the message
2319  * @return number of bytes transmitted
2320  */
2321 static size_t
2322 notify_transport_connect_done (void *cls, size_t size, void *buf)
2323 {
2324   struct Neighbour *n = cls;
2325
2326   n->th = NULL;
2327   if (buf == NULL)
2328     {
2329       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2330                   _("Failed to connect to `%4s': transport failed to connect\n"),
2331                   GNUNET_i2s (&n->peer));
2332       return 0;
2333     }
2334   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2335               _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2336               GNUNET_i2s (&n->peer));
2337   if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2338     GNUNET_SCHEDULER_cancel (sched,
2339                              n->retry_set_key_task);
2340   n->retry_set_key_task = GNUNET_SCHEDULER_add_now (sched, 
2341                                                     &set_key_retry_task,
2342                                                     n);
2343   return 0;
2344 }
2345
2346
2347 /**
2348  * Handle CORE_REQUEST_CONNECT request.
2349  *
2350  * @param cls unused
2351  * @param client the client issuing the request
2352  * @param message the "struct ConnectMessage"
2353  */
2354 static void
2355 handle_client_request_connect (void *cls,
2356                                struct GNUNET_SERVER_Client *client,
2357                                const struct GNUNET_MessageHeader *message)
2358 {
2359   const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2360   struct Neighbour *n;
2361   struct GNUNET_TIME_Relative timeout;
2362
2363   if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2364     {
2365       GNUNET_break (0);
2366       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2367       return;
2368     }
2369   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2370   n = find_neighbour (&cm->peer);
2371   if (n == NULL)
2372     n = create_neighbour (&cm->peer);
2373   if ( (GNUNET_YES == n->is_connected) ||
2374        (n->th != NULL) )
2375     return; /* already connected, or at least trying */
2376   GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2377 #if DEBUG_CORE
2378   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2379               "Core received `%s' request for `%4s', will try to establish connection\n",
2380               "REQUEST_CONNECT",
2381               GNUNET_i2s (&cm->peer));
2382 #endif
2383   timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2384   /* ask transport to connect to the peer */
2385   n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2386                                                   &cm->peer,
2387                                                   sizeof (struct GNUNET_MessageHeader), 0,
2388                                                   timeout,
2389                                                   &notify_transport_connect_done,
2390                                                   n);
2391   GNUNET_break (NULL != n->th);
2392 }
2393
2394
2395 /**
2396  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
2397  * the neighbour's struct and retry send_key.  Or, if we did not get a
2398  * HELLO, just do nothing.
2399  *
2400  * @param cls the 'struct Neighbour' to retry sending the key for
2401  * @param peer the peer for which this is the HELLO
2402  * @param hello HELLO message of that peer
2403  */
2404 static void
2405 process_hello_retry_send_key (void *cls,
2406                               const struct GNUNET_PeerIdentity *peer,
2407                               const struct GNUNET_HELLO_Message *hello)
2408 {
2409   struct Neighbour *n = cls;
2410
2411   if (peer == NULL)
2412     {
2413 #if DEBUG_CORE
2414       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2415                   "Entered `%s' and `%s' is NULL!\n",
2416                   "process_hello_retry_send_key",
2417                   "peer");
2418 #endif
2419       n->pitr = NULL;
2420       if (n->public_key != NULL)
2421         {
2422           if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2423             {
2424               GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2425               n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2426             }      
2427           GNUNET_STATISTICS_update (stats,
2428                                     gettext_noop ("# SET_KEY messages deferred (need public key)"), 
2429                                     -1, 
2430                                     GNUNET_NO);
2431           send_key (n);
2432         }
2433       else
2434         {
2435 #if DEBUG_CORE
2436           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2437                       "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
2438                       GNUNET_i2s (&n->peer));
2439 #endif
2440           GNUNET_STATISTICS_update (stats,
2441                                     gettext_noop ("# Delayed connecting due to lack of public key"),
2442                                     1,
2443                                     GNUNET_NO);      
2444           if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2445             n->retry_set_key_task
2446               = GNUNET_SCHEDULER_add_delayed (sched,
2447                                               n->set_key_retry_frequency,
2448                                               &set_key_retry_task, n);
2449         }
2450       return;
2451     }
2452
2453 #if DEBUG_CORE
2454   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2455               "Entered `%s' for peer `%4s'\n",
2456               "process_hello_retry_send_key",
2457               GNUNET_i2s (peer));
2458 #endif
2459   if (n->public_key != NULL)
2460     {
2461       /* already have public key, why are we here? */
2462       GNUNET_break (0);
2463       return;
2464     }
2465
2466 #if DEBUG_CORE
2467   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2468               "Received new `%s' message for `%4s', initiating key exchange.\n",
2469               "HELLO",
2470               GNUNET_i2s (peer));
2471 #endif
2472   n->public_key =
2473     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2474   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2475     {
2476       GNUNET_STATISTICS_update (stats,
2477                                 gettext_noop ("# Error extracting public key from HELLO"),
2478                                 1,
2479                                 GNUNET_NO);      
2480       GNUNET_free (n->public_key);
2481       n->public_key = NULL;
2482 #if DEBUG_CORE
2483   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2484               "GNUNET_HELLO_get_key returned awfully\n");
2485 #endif
2486       return;
2487     }
2488 }
2489
2490
2491 /**
2492  * Send our key (and encrypted PING) to the other peer.
2493  *
2494  * @param n the other peer
2495  */
2496 static void
2497 send_key (struct Neighbour *n)
2498 {
2499   struct MessageEntry *pos;
2500   struct SetKeyMessage *sm;
2501   struct MessageEntry *me;
2502   struct PingMessage pp;
2503   struct PingMessage *pm;
2504
2505   if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2506     {
2507       GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2508       n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2509     }        
2510   if (n->pitr != NULL)
2511     {
2512 #if DEBUG_CORE
2513       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2514                   "Key exchange in progress with `%4s'.\n",
2515                   GNUNET_i2s (&n->peer));
2516 #endif
2517       return; /* already in progress */
2518     }
2519   if (GNUNET_YES != n->is_connected)
2520     {
2521 #if DEBUG_CORE
2522       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2523                   "Not yet connected to peer `%4s'!\n",
2524                   GNUNET_i2s (&n->peer));
2525 #endif
2526       if (NULL == n->th)
2527         {
2528           GNUNET_STATISTICS_update (stats, 
2529                                     gettext_noop ("# Asking transport to connect (for SET_KEY)"), 
2530                                     1, 
2531                                     GNUNET_NO);
2532           n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2533                                                           &n->peer,
2534                                                           sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2535                                                           0,
2536                                                           GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2537                                                           &notify_encrypted_transmit_ready,
2538                                                           n);
2539         }
2540       return; 
2541     }
2542 #if DEBUG_CORE
2543   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2544               "Asked to perform key exchange with `%4s'.\n",
2545               GNUNET_i2s (&n->peer));
2546 #endif
2547   if (n->public_key == NULL)
2548     {
2549       /* lookup n's public key, then try again */
2550 #if DEBUG_CORE
2551       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2552                   "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2553                   GNUNET_i2s (&n->peer));
2554 #endif
2555       GNUNET_assert (n->pitr == NULL);
2556       n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2557                                          &n->peer,
2558                                          GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2559                                          &process_hello_retry_send_key, n);
2560       return;
2561     }
2562   pos = n->encrypted_head;
2563   while (pos != NULL)
2564     {
2565       if (GNUNET_YES == pos->is_setkey)
2566         {
2567           if (pos->sender_status == n->status)
2568             {
2569 #if DEBUG_CORE
2570               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2571                           "`%s' message for `%4s' queued already\n",
2572                           "SET_KEY",
2573                           GNUNET_i2s (&n->peer));
2574 #endif
2575               goto trigger_processing;
2576             }
2577           GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2578                                        n->encrypted_tail,
2579                                        pos);
2580           GNUNET_free (pos);
2581 #if DEBUG_CORE
2582           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2583                       "Removing queued `%s' message for `%4s', will create a new one\n",
2584                       "SET_KEY",
2585                       GNUNET_i2s (&n->peer));
2586 #endif
2587           break;
2588         }
2589       pos = pos->next;
2590     }
2591
2592   /* update status */
2593   switch (n->status)
2594     {
2595     case PEER_STATE_DOWN:
2596       n->status = PEER_STATE_KEY_SENT;
2597       break;
2598     case PEER_STATE_KEY_SENT:
2599       break;
2600     case PEER_STATE_KEY_RECEIVED:
2601       break;
2602     case PEER_STATE_KEY_CONFIRMED:
2603       break;
2604     default:
2605       GNUNET_break (0);
2606       break;
2607     }
2608   
2609
2610   /* first, set key message */
2611   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2612                       sizeof (struct SetKeyMessage) +
2613                       sizeof (struct PingMessage));
2614   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2615   me->priority = SET_KEY_PRIORITY;
2616   me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
2617   me->is_setkey = GNUNET_YES;
2618   me->got_slack = GNUNET_YES; /* do not defer this one! */
2619   me->sender_status = n->status;
2620   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2621                                      n->encrypted_tail,
2622                                      n->encrypted_tail,
2623                                      me);
2624   sm = (struct SetKeyMessage *) &me[1];
2625   sm->header.size = htons (sizeof (struct SetKeyMessage));
2626   sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2627   sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2628                                         PEER_STATE_KEY_SENT : n->status));
2629   sm->purpose.size =
2630     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2631            sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2632            sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2633            sizeof (struct GNUNET_PeerIdentity));
2634   sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2635   sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2636   sm->target = n->peer;
2637   GNUNET_assert (GNUNET_OK ==
2638                  GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2639                                             sizeof (struct
2640                                                     GNUNET_CRYPTO_AesSessionKey),
2641                                             n->public_key,
2642                                             &sm->encrypted_key));
2643   GNUNET_assert (GNUNET_OK ==
2644                  GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2645                                          &sm->signature));  
2646   pm = (struct PingMessage *) &sm[1];
2647   pm->header.size = htons (sizeof (struct PingMessage));
2648   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2649   pp.challenge = htonl (n->ping_challenge);
2650   pp.target = n->peer;
2651 #if DEBUG_HANDSHAKE
2652   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2653               "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u.\n",
2654               "SET_KEY", "PING",
2655               (unsigned int) n->ping_challenge,
2656               GNUNET_i2s (&n->peer),
2657               (unsigned int) n->encrypt_key.crc32);
2658 #endif
2659   do_encrypt (n,
2660               &n->peer.hashPubKey,
2661               &pp.challenge,
2662               &pm->challenge,
2663               sizeof (struct PingMessage) -
2664               sizeof (struct GNUNET_MessageHeader));
2665   GNUNET_STATISTICS_update (stats, 
2666                             gettext_noop ("# SET_KEY and PING messages created"), 
2667                             1, 
2668                             GNUNET_NO);
2669 #if DEBUG_CORE
2670   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2671               "Have %llu ms left for `%s' transmission.\n",
2672               (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2673               "SET_KEY");
2674 #endif
2675  trigger_processing:
2676   /* trigger queue processing */
2677   process_encrypted_neighbour_queue (n);
2678   if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2679        (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2680     n->retry_set_key_task
2681       = GNUNET_SCHEDULER_add_delayed (sched,
2682                                       n->set_key_retry_frequency,
2683                                       &set_key_retry_task, n);    
2684 }
2685
2686
2687 /**
2688  * We received a SET_KEY message.  Validate and update
2689  * our key material and status.
2690  *
2691  * @param n the neighbour from which we received message m
2692  * @param m the set key message we received
2693  */
2694 static void
2695 handle_set_key (struct Neighbour *n,
2696                 const struct SetKeyMessage *m);
2697
2698
2699 /**
2700  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
2701  * the neighbour's struct and retry handling the set_key message.  Or,
2702  * if we did not get a HELLO, just free the set key message.
2703  *
2704  * @param cls pointer to the set key message
2705  * @param peer the peer for which this is the HELLO
2706  * @param hello HELLO message of that peer
2707  */
2708 static void
2709 process_hello_retry_handle_set_key (void *cls,
2710                                     const struct GNUNET_PeerIdentity *peer,
2711                                     const struct GNUNET_HELLO_Message *hello)
2712 {
2713   struct Neighbour *n = cls;
2714   struct SetKeyMessage *sm = n->skm;
2715
2716   if (peer == NULL)
2717     {
2718       n->skm = NULL;
2719       n->pitr = NULL;
2720       if (n->public_key != NULL)
2721         {
2722 #if DEBUG_CORE
2723           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2724                       "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2725                       "HELLO",
2726                       GNUNET_i2s (&n->peer),
2727                       "SET_KEY");
2728 #endif
2729           handle_set_key (n, sm);
2730         }
2731       else
2732         {
2733           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2734                       _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
2735                       "SET_KEY",
2736                       GNUNET_i2s (&n->peer));
2737         }
2738       GNUNET_free (sm);
2739       return;
2740     }
2741   if (n->public_key != NULL)
2742     return;                     /* multiple HELLOs match!? */
2743   n->public_key =
2744     GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2745   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2746     {
2747       GNUNET_break_op (0);
2748       GNUNET_free (n->public_key);
2749       n->public_key = NULL;
2750     }
2751 }
2752
2753
2754 /**
2755  * We received a PING message.  Validate and transmit
2756  * PONG.
2757  *
2758  * @param n sender of the PING
2759  * @param m the encrypted PING message itself
2760  */
2761 static void
2762 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2763 {
2764   struct PingMessage t;
2765   struct PongMessage tx;
2766   struct PongMessage *tp;
2767   struct MessageEntry *me;
2768
2769 #if DEBUG_CORE
2770   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2771               "Core service receives `%s' request from `%4s'.\n",
2772               "PING", GNUNET_i2s (&n->peer));
2773 #endif
2774   if (GNUNET_OK !=
2775       do_decrypt (n,
2776                   &my_identity.hashPubKey,
2777                   &m->challenge,
2778                   &t.challenge,
2779                   sizeof (struct PingMessage) -
2780                   sizeof (struct GNUNET_MessageHeader)))
2781     return;
2782 #if DEBUG_HANDSHAKE
2783   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2784               "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2785               "PING",
2786               GNUNET_i2s (&t.target),
2787               (unsigned int) ntohl (t.challenge), 
2788               (unsigned int) n->decrypt_key.crc32);
2789 #endif
2790   GNUNET_STATISTICS_update (stats,
2791                             gettext_noop ("# PING messages decrypted"), 
2792                             1,
2793                             GNUNET_NO);
2794   if (0 != memcmp (&t.target,
2795                    &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2796     {
2797       GNUNET_break_op (0);
2798       return;
2799     }
2800   me = GNUNET_malloc (sizeof (struct MessageEntry) +
2801                       sizeof (struct PongMessage));
2802   GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2803                                      n->encrypted_tail,
2804                                      n->encrypted_tail,
2805                                      me);
2806   me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2807   me->priority = PONG_PRIORITY;
2808   me->size = sizeof (struct PongMessage);
2809   tx.reserved = htonl (0);
2810   tx.inbound_bw_limit = n->bw_in;
2811   tx.challenge = t.challenge;
2812   tx.target = t.target;
2813   tp = (struct PongMessage *) &me[1];
2814   tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2815   tp->header.size = htons (sizeof (struct PongMessage));
2816   do_encrypt (n,
2817               &my_identity.hashPubKey,
2818               &tx.challenge,
2819               &tp->challenge,
2820               sizeof (struct PongMessage) -
2821               sizeof (struct GNUNET_MessageHeader));
2822   GNUNET_STATISTICS_update (stats, 
2823                             gettext_noop ("# PONG messages created"), 
2824                             1, 
2825                             GNUNET_NO);
2826 #if DEBUG_HANDSHAKE
2827   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2828               "Encrypting `%s' with challenge %u using key %u\n",
2829               "PONG",
2830               (unsigned int) ntohl (t.challenge),
2831               (unsigned int) n->encrypt_key.crc32);
2832 #endif
2833   /* trigger queue processing */
2834   process_encrypted_neighbour_queue (n);
2835 }
2836
2837
2838 /**
2839  * We received a PONG message.  Validate and update our status.
2840  *
2841  * @param n sender of the PONG
2842  * @param m the encrypted PONG message itself
2843  */
2844 static void
2845 handle_pong (struct Neighbour *n, 
2846              const struct PongMessage *m)
2847 {
2848   struct PongMessage t;
2849   struct ConnectNotifyMessage cnm;
2850
2851 #if DEBUG_CORE
2852   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2853               "Core service receives `%s' response from `%4s'.\n",
2854               "PONG", GNUNET_i2s (&n->peer));
2855 #endif
2856   /* mark as garbage, just to be sure */
2857   memset (&t, 255, sizeof (t));
2858   if (GNUNET_OK !=
2859       do_decrypt (n,
2860                   &n->peer.hashPubKey,
2861                   &m->challenge,
2862                   &t.challenge,
2863                   sizeof (struct PongMessage) -
2864                   sizeof (struct GNUNET_MessageHeader)))
2865     {
2866       GNUNET_break_op (0);
2867       return;
2868     }
2869   GNUNET_STATISTICS_update (stats, 
2870                             gettext_noop ("# PONG messages decrypted"), 
2871                             1, 
2872                             GNUNET_NO);
2873   if (0 != ntohl (t.reserved))
2874     {
2875       GNUNET_break_op (0);
2876       return;
2877     }
2878 #if DEBUG_HANDSHAKE
2879   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2880               "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2881               "PONG",
2882               GNUNET_i2s (&t.target),
2883               (unsigned int) ntohl (t.challenge),
2884               (unsigned int) n->decrypt_key.crc32);
2885 #endif
2886   if ((0 != memcmp (&t.target,
2887                     &n->peer,
2888                     sizeof (struct GNUNET_PeerIdentity))) ||
2889       (n->ping_challenge != ntohl (t.challenge)))
2890     {
2891       /* PONG malformed */
2892 #if DEBUG_CORE
2893       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2894                   "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2895                   "PONG", 
2896                   GNUNET_i2s (&n->peer),
2897                   (unsigned int) n->ping_challenge);
2898       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2899                   "Received malformed `%s' received from `%4s' with challenge %u\n",
2900                   "PONG", GNUNET_i2s (&t.target), 
2901                   (unsigned int) ntohl (t.challenge));
2902 #endif
2903       GNUNET_break_op (0);
2904       return;
2905     }
2906   switch (n->status)
2907     {
2908     case PEER_STATE_DOWN:
2909       GNUNET_break (0);         /* should be impossible */
2910       return;
2911     case PEER_STATE_KEY_SENT:
2912       GNUNET_break (0);         /* should be impossible, how did we decrypt? */
2913       return;
2914     case PEER_STATE_KEY_RECEIVED:
2915       GNUNET_STATISTICS_update (stats, 
2916                                 gettext_noop ("# Session keys confirmed via PONG"), 
2917                                 1, 
2918                                 GNUNET_NO);
2919       n->status = PEER_STATE_KEY_CONFIRMED;
2920       if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2921         {
2922           n->bw_out_external_limit = t.inbound_bw_limit;
2923           n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2924                                                   n->bw_out_internal_limit);
2925           GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2926                                                  n->bw_out);       
2927           GNUNET_TRANSPORT_set_quota (transport,
2928                                       &n->peer,
2929                                       n->bw_in,
2930                                       n->bw_out,
2931                                       GNUNET_TIME_UNIT_FOREVER_REL,
2932                                       NULL, NULL); 
2933         }
2934 #if DEBUG_CORE
2935       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2936                   "Confirmed key via `%s' message for peer `%4s'\n",
2937                   "PONG", GNUNET_i2s (&n->peer));
2938 #endif      
2939       if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2940         {
2941           GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2942           n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2943         }      
2944       cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2945       cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2946       cnm.distance = htonl (n->last_distance);
2947       cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2948       cnm.peer = n->peer;
2949       send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2950       process_encrypted_neighbour_queue (n);
2951       /* fall-through! */
2952     case PEER_STATE_KEY_CONFIRMED:
2953       n->last_activity = GNUNET_TIME_absolute_get ();
2954       if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2955         GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2956       n->keep_alive_task 
2957         = GNUNET_SCHEDULER_add_delayed (sched, 
2958                                         GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2959                                         &send_keep_alive,
2960                                         n);
2961       handle_peer_status_change (n);
2962       break;
2963     default:
2964       GNUNET_break (0);
2965       break;
2966     }
2967 }
2968
2969
2970 /**
2971  * We received a SET_KEY message.  Validate and update
2972  * our key material and status.
2973  *
2974  * @param n the neighbour from which we received message m
2975  * @param m the set key message we received
2976  */
2977 static void
2978 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2979 {
2980   struct SetKeyMessage *m_cpy;
2981   struct GNUNET_TIME_Absolute t;
2982   struct GNUNET_CRYPTO_AesSessionKey k;
2983   struct PingMessage *ping;
2984   struct PongMessage *pong;
2985   enum PeerStateMachine sender_status;
2986
2987 #if DEBUG_CORE
2988   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2989               "Core service receives `%s' request from `%4s'.\n",
2990               "SET_KEY", GNUNET_i2s (&n->peer));
2991 #endif
2992   if (n->public_key == NULL)
2993     {
2994       if (n->pitr != NULL)
2995         {
2996 #if DEBUG_CORE
2997           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2998                       "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2999                       "SET_KEY");
3000 #endif
3001           return;
3002         }
3003 #if DEBUG_CORE
3004       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3005                   "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3006 #endif
3007       m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3008       memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3009       /* lookup n's public key, then try again */
3010       GNUNET_assert (n->skm == NULL);
3011       n->skm = m_cpy;
3012       n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3013                                          &n->peer,
3014                                          GNUNET_TIME_UNIT_MINUTES,
3015                                          &process_hello_retry_handle_set_key, n);
3016       GNUNET_STATISTICS_update (stats, 
3017                                 gettext_noop ("# SET_KEY messages deferred (need public key)"), 
3018                                 1, 
3019                                 GNUNET_NO);
3020       return;
3021     }
3022   if (0 != memcmp (&m->target,
3023                    &my_identity,
3024                    sizeof (struct GNUNET_PeerIdentity)))
3025     {
3026       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3027                   _("Received `%s' message that was for `%s', not for me.  Ignoring.\n"),
3028                   "SET_KEY",
3029                   GNUNET_i2s (&m->target));
3030       return;
3031     }
3032   if ((ntohl (m->purpose.size) !=
3033        sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3034        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3035        sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3036        sizeof (struct GNUNET_PeerIdentity)) ||
3037       (GNUNET_OK !=
3038        GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3039                                  &m->purpose, &m->signature, n->public_key)))
3040     {
3041       /* invalid signature */
3042       GNUNET_break_op (0);
3043       return;
3044     }
3045   t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3046   if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3047        (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3048       (t.value < n->decrypt_key_created.value))
3049     {
3050       /* this could rarely happen due to massive re-ordering of
3051          messages on the network level, but is most likely either
3052          a bug or some adversary messing with us.  Report. */
3053       GNUNET_break_op (0);
3054       return;
3055     }
3056 #if DEBUG_CORE
3057   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
3058               "Decrypting key material.\n");
3059 #endif  
3060   if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3061                                   &m->encrypted_key,
3062                                   &k,
3063                                   sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3064        != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3065       (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3066     {
3067       /* failed to decrypt !? */
3068       GNUNET_break_op (0);
3069       return;
3070     }
3071   GNUNET_STATISTICS_update (stats, 
3072                             gettext_noop ("# SET_KEY messages decrypted"), 
3073                             1, 
3074                             GNUNET_NO);
3075   n->decrypt_key = k;
3076   if (n->decrypt_key_created.value != t.value)
3077     {
3078       /* fresh key, reset sequence numbers */
3079       n->last_sequence_number_received = 0;
3080       n->last_packets_bitmap = 0;
3081       n->decrypt_key_created = t;
3082     }
3083   sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3084   switch (n->status)
3085     {
3086     case PEER_STATE_DOWN:
3087       n->status = PEER_STATE_KEY_RECEIVED;
3088 #if DEBUG_CORE
3089       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3090                   "Responding to `%s' with my own key.\n", "SET_KEY");
3091 #endif
3092       send_key (n);
3093       break;
3094     case PEER_STATE_KEY_SENT:
3095     case PEER_STATE_KEY_RECEIVED:
3096       n->status = PEER_STATE_KEY_RECEIVED;
3097       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3098           (sender_status != PEER_STATE_KEY_CONFIRMED))
3099         {
3100 #if DEBUG_CORE
3101           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3102                       "Responding to `%s' with my own key (other peer has status %u).\n",
3103                       "SET_KEY",
3104                       (unsigned int) sender_status);
3105 #endif
3106           send_key (n);
3107         }
3108       break;
3109     case PEER_STATE_KEY_CONFIRMED:
3110       if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3111           (sender_status != PEER_STATE_KEY_CONFIRMED))
3112         {         
3113 #if DEBUG_CORE
3114           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3115                       "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3116                       "SET_KEY", 
3117                       (unsigned int) sender_status);
3118 #endif
3119           send_key (n);
3120         }
3121       break;
3122     default:
3123       GNUNET_break (0);
3124       break;
3125     }
3126   if (n->pending_ping != NULL)
3127     {
3128       ping = n->pending_ping;
3129       n->pending_ping = NULL;
3130       handle_ping (n, ping);
3131       GNUNET_free (ping);
3132     }
3133   if (n->pending_pong != NULL)
3134     {
3135       pong = n->pending_pong;
3136       n->pending_pong = NULL;
3137       handle_pong (n, pong);
3138       GNUNET_free (pong);
3139     }
3140 }
3141
3142
3143 /**
3144  * Send a P2P message to a client.
3145  *
3146  * @param sender who sent us the message?
3147  * @param client who should we give the message to?
3148  * @param m contains the message to transmit
3149  * @param msize number of bytes in buf to transmit
3150  */
3151 static void
3152 send_p2p_message_to_client (struct Neighbour *sender,
3153                             struct Client *client,
3154                             const void *m, size_t msize)
3155 {
3156   char buf[msize + sizeof (struct NotifyTrafficMessage)];
3157   struct NotifyTrafficMessage *ntm;
3158
3159 #if DEBUG_CORE
3160   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3161               "Core service passes message from `%4s' of type %u to client.\n",
3162               GNUNET_i2s(&sender->peer),
3163               (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3164 #endif
3165   ntm = (struct NotifyTrafficMessage *) buf;
3166   ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3167   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3168   ntm->distance = htonl (sender->last_distance);
3169   ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3170   ntm->peer = sender->peer;
3171   memcpy (&ntm[1], m, msize);
3172   send_to_client (client, &ntm->header, GNUNET_YES);
3173 }
3174
3175
3176 /**
3177  * Deliver P2P message to interested clients.
3178  *
3179  * @param cls always NULL
3180  * @param client who sent us the message (struct Neighbour)
3181  * @param m the message
3182  */
3183 static void
3184 deliver_message (void *cls,
3185                  void *client,
3186                  const struct GNUNET_MessageHeader *m)
3187 {
3188   struct Neighbour *sender = client;
3189   size_t msize = ntohs (m->size);
3190   char buf[256];
3191   struct Client *cpos;
3192   uint16_t type;
3193   unsigned int tpos;
3194   int deliver_full;
3195   int dropped;
3196
3197   type = ntohs (m->type);
3198 #if DEBUG_CORE
3199   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3200               "Received encapsulated message of type %u and size %u from `%4s'\n",
3201               (unsigned int) type,
3202               ntohs (m->size),
3203               GNUNET_i2s (&sender->peer));
3204 #endif
3205   GNUNET_snprintf (buf,
3206                    sizeof(buf),
3207                    gettext_noop ("# bytes of messages of type %u received"),
3208                    (unsigned int) type);
3209   GNUNET_STATISTICS_set (stats,
3210                          buf,
3211                          msize,
3212                          GNUNET_NO);     
3213   dropped = GNUNET_YES;
3214   cpos = clients;
3215   while (cpos != NULL)
3216     {
3217       deliver_full = GNUNET_NO;
3218       if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3219         deliver_full = GNUNET_YES;
3220       else
3221         {
3222           for (tpos = 0; tpos < cpos->tcnt; tpos++)
3223             {
3224               if (type != cpos->types[tpos])
3225                 continue;
3226               deliver_full = GNUNET_YES;
3227               break;
3228             }
3229         }
3230       if (GNUNET_YES == deliver_full)
3231         {
3232           send_p2p_message_to_client (sender, cpos, m, msize);
3233           dropped = GNUNET_NO;
3234         }
3235       else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3236         {
3237           send_p2p_message_to_client (sender, cpos, m,
3238                                       sizeof (struct GNUNET_MessageHeader));
3239         }
3240       cpos = cpos->next;
3241     }
3242   if (dropped == GNUNET_YES)
3243     {
3244 #if DEBUG_CORE
3245       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3246                   "Message of type %u from `%4s' not delivered to any client.\n",
3247                   (unsigned int) type,
3248                   GNUNET_i2s (&sender->peer));
3249 #endif
3250       GNUNET_STATISTICS_update (stats,
3251                                 gettext_noop ("# messages not delivered to any client"), 
3252                                 1, GNUNET_NO);
3253     }
3254 }
3255
3256
3257 /**
3258  * We received an encrypted message.  Decrypt, validate and
3259  * pass on to the appropriate clients.
3260  */
3261 static void
3262 handle_encrypted_message (struct Neighbour *n,
3263                           const struct EncryptedMessage *m)
3264 {
3265   size_t size = ntohs (m->header.size);
3266   char buf[size];
3267   struct EncryptedMessage *pt;  /* plaintext */
3268   GNUNET_HashCode ph;
3269   uint32_t snum;
3270   struct GNUNET_TIME_Absolute t;
3271   GNUNET_HashCode iv;
3272
3273 #if DEBUG_CORE
3274   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3275               "Core service receives `%s' request from `%4s'.\n",
3276               "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3277 #endif  
3278   GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3279   /* decrypt */
3280   if (GNUNET_OK !=
3281       do_decrypt (n,
3282                   &iv,
3283                   &m->hmac,
3284                   &buf[ENCRYPTED_HEADER_SIZE], 
3285                   size - ENCRYPTED_HEADER_SIZE))
3286     return;
3287   pt = (struct EncryptedMessage *) buf;
3288   /* validate hash */
3289   GNUNET_CRYPTO_hmac (&n->decrypt_key,
3290                       &pt->sequence_number,
3291                       size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3292 #if DEBUG_HANDSHAKE 
3293   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3294               "V-Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
3295               (unsigned int) (size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode)),
3296               GNUNET_h2s (&ph),
3297               (int) m->iv_seed);
3298 #endif
3299   if (0 != memcmp (&ph, 
3300                    &pt->hmac, 
3301                    sizeof (GNUNET_HashCode)))
3302     {
3303       /* checksum failed */
3304       GNUNET_break_op (0);
3305       return;
3306     }
3307
3308   /* validate sequence number */
3309   snum = ntohl (pt->sequence_number);
3310   if (n->last_sequence_number_received == snum)
3311     {
3312       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3313                   "Received duplicate message, ignoring.\n");
3314       /* duplicate, ignore */
3315       GNUNET_STATISTICS_set (stats,
3316                              gettext_noop ("# bytes dropped (duplicates)"),
3317                              size,
3318                              GNUNET_NO);      
3319       return;
3320     }
3321   if ((n->last_sequence_number_received > snum) &&
3322       (n->last_sequence_number_received - snum > 32))
3323     {
3324       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3325                   "Received ancient out of sequence message, ignoring.\n");
3326       /* ancient out of sequence, ignore */
3327       GNUNET_STATISTICS_set (stats,
3328                              gettext_noop ("# bytes dropped (out of sequence)"),
3329                              size,
3330                              GNUNET_NO);      
3331       return;
3332     }
3333   if (n->last_sequence_number_received > snum)
3334     {
3335       unsigned int rotbit =
3336         1 << (n->last_sequence_number_received - snum - 1);
3337       if ((n->last_packets_bitmap & rotbit) != 0)
3338         {
3339           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3340                       "Received duplicate message, ignoring.\n");
3341           GNUNET_STATISTICS_set (stats,
3342                                  gettext_noop ("# bytes dropped (duplicates)"),
3343                                  size,
3344                                  GNUNET_NO);      
3345           /* duplicate, ignore */
3346           return;
3347         }
3348       n->last_packets_bitmap |= rotbit;
3349     }
3350   if (n->last_sequence_number_received < snum)
3351     {
3352       n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3353       n->last_sequence_number_received = snum;
3354     }
3355
3356   /* check timestamp */
3357   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3358   if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3359     {
3360       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3361                   _
3362                   ("Message received far too old (%llu ms). Content ignored.\n"),
3363                   GNUNET_TIME_absolute_get_duration (t).value);
3364       GNUNET_STATISTICS_set (stats,
3365                              gettext_noop ("# bytes dropped (ancient message)"),
3366                              size,
3367                              GNUNET_NO);      
3368       return;
3369     }
3370
3371   /* process decrypted message(s) */
3372   if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3373     {
3374 #if DEBUG_CORE_SET_QUOTA
3375       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3376                   "Received %u b/s as new inbound limit for peer `%4s'\n",
3377                   (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3378                   GNUNET_i2s (&n->peer));
3379 #endif
3380       n->bw_out_external_limit = pt->inbound_bw_limit;
3381       n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3382                                               n->bw_out_internal_limit);
3383       GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3384                                              n->bw_out);
3385       GNUNET_TRANSPORT_set_quota (transport,
3386                                   &n->peer,
3387                                   n->bw_in,
3388                                   n->bw_out,
3389                                   GNUNET_TIME_UNIT_FOREVER_REL,
3390                                   NULL, NULL); 
3391     }
3392   n->last_activity = GNUNET_TIME_absolute_get ();
3393   if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3394     GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3395   n->keep_alive_task 
3396     = GNUNET_SCHEDULER_add_delayed (sched, 
3397                                     GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3398                                     &send_keep_alive,
3399                                     n);
3400   GNUNET_STATISTICS_set (stats,
3401                          gettext_noop ("# bytes of payload decrypted"),
3402                          size - sizeof (struct EncryptedMessage),
3403                          GNUNET_NO);
3404   handle_peer_status_change (n);
3405   if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst, 
3406                                               n,
3407                                               &buf[sizeof (struct EncryptedMessage)], 
3408                                               size - sizeof (struct EncryptedMessage),
3409                                               GNUNET_YES, GNUNET_NO))
3410     GNUNET_break_op (0);
3411 }
3412
3413
3414 /**
3415  * Function called by the transport for each received message.
3416  *
3417  * @param cls closure
3418  * @param peer (claimed) identity of the other peer
3419  * @param message the message
3420  * @param latency estimated latency for communicating with the
3421  *             given peer (round-trip)
3422  * @param distance in overlay hops, as given by transport plugin
3423  */
3424 static void
3425 handle_transport_receive (void *cls,
3426                           const struct GNUNET_PeerIdentity *peer,
3427                           const struct GNUNET_MessageHeader *message,
3428                           struct GNUNET_TIME_Relative latency,
3429                           unsigned int distance)
3430 {
3431   struct Neighbour *n;
3432   struct GNUNET_TIME_Absolute now;
3433   int up;
3434   uint16_t type;
3435   uint16_t size;
3436   int changed;
3437
3438 #if DEBUG_CORE
3439   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3440               "Received message of type %u from `%4s', demultiplexing.\n",
3441               (unsigned int) ntohs (message->type), 
3442               GNUNET_i2s (peer));
3443 #endif
3444   if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3445     {
3446       GNUNET_break (0);
3447       return;
3448     }
3449   n = find_neighbour (peer);
3450   if (n == NULL)
3451     n = create_neighbour (peer);
3452   changed = (latency.value != n->last_latency.value) || (distance != n->last_distance);
3453   n->last_latency = latency;
3454   n->last_distance = distance;
3455   up = (n->status == PEER_STATE_KEY_CONFIRMED);
3456   type = ntohs (message->type);
3457   size = ntohs (message->size);
3458   switch (type)
3459     {
3460     case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3461       if (size != sizeof (struct SetKeyMessage))
3462         {
3463           GNUNET_break_op (0);
3464           return;
3465         }
3466       GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3467       handle_set_key (n, (const struct SetKeyMessage *) message);
3468       break;
3469     case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3470       if (size < sizeof (struct EncryptedMessage) +
3471           sizeof (struct GNUNET_MessageHeader))
3472         {
3473           GNUNET_break_op (0);
3474           return;
3475         }
3476       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3477           (n->status != PEER_STATE_KEY_CONFIRMED))
3478         {
3479           GNUNET_break_op (0);
3480           return;
3481         }
3482       handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3483       break;
3484     case GNUNET_MESSAGE_TYPE_CORE_PING:
3485       if (size != sizeof (struct PingMessage))
3486         {
3487           GNUNET_break_op (0);
3488           return;
3489         }
3490       GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3491       if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3492           (n->status != PEER_STATE_KEY_CONFIRMED))
3493         {
3494 #if DEBUG_CORE
3495           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3496                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3497                       "PING", GNUNET_i2s (&n->peer));
3498 #endif
3499           GNUNET_free_non_null (n->pending_ping);
3500           n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3501           memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3502           return;
3503         }
3504       handle_ping (n, (const struct PingMessage *) message);
3505       break;
3506     case GNUNET_MESSAGE_TYPE_CORE_PONG:
3507       if (size != sizeof (struct PongMessage))
3508         {
3509           GNUNET_break_op (0);
3510           return;
3511         }
3512       GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3513       if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3514            (n->status != PEER_STATE_KEY_CONFIRMED) )
3515         {
3516 #if DEBUG_CORE
3517           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3518                       "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3519                       "PONG", GNUNET_i2s (&n->peer));
3520 #endif
3521           GNUNET_free_non_null (n->pending_pong);
3522           n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3523           memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3524           return;
3525         }
3526       handle_pong (n, (const struct PongMessage *) message);
3527       break;
3528     default:
3529       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3530                   _("Unsupported message of type %u received.\n"),
3531                   (unsigned int) type);
3532       return;
3533     }
3534   if (n->status == PEER_STATE_KEY_CONFIRMED)
3535     {
3536       now = GNUNET_TIME_absolute_get ();
3537       n->last_activity = now;
3538       changed = GNUNET_YES;
3539       if (!up)
3540         {
3541           GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3542           n->time_established = now;
3543         }
3544       if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3545         GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3546       n->keep_alive_task 
3547         = GNUNET_SCHEDULER_add_delayed (sched, 
3548                                         GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3549                                         &send_keep_alive,
3550                                         n);
3551     }
3552   if (changed)
3553     handle_peer_status_change (n);
3554 }
3555
3556
3557 /**
3558  * Function that recalculates the bandwidth quota for the
3559  * given neighbour and transmits it to the transport service.
3560  * 
3561  * @param cls neighbour for the quota update
3562  * @param tc context
3563  */
3564 static void
3565 neighbour_quota_update (void *cls,
3566                         const struct GNUNET_SCHEDULER_TaskContext *tc)
3567 {
3568   struct Neighbour *n = cls;
3569   struct GNUNET_BANDWIDTH_Value32NBO q_in;
3570   double pref_rel;
3571   double share;
3572   unsigned long long distributable;
3573   uint64_t need_per_peer;
3574   uint64_t need_per_second;
3575
3576 #if DEBUG_CORE
3577   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3578               "Neighbour quota update calculation running for peer `%4s'\n",
3579               GNUNET_i2s (&n->peer));  
3580 #endif
3581   n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3582   /* calculate relative preference among all neighbours;
3583      divides by a bit more to avoid division by zero AND to
3584      account for possibility of new neighbours joining any time 
3585      AND to convert to double... */
3586   if (preference_sum == 0)
3587     {
3588       pref_rel = 1.0 / (double) neighbour_count;
3589     }
3590   else
3591     {
3592       pref_rel = n->current_preference / preference_sum;
3593     }
3594   need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3595                                                               GNUNET_TIME_UNIT_SECONDS);  
3596   need_per_second = need_per_peer * neighbour_count;
3597   distributable = 0;
3598   if (bandwidth_target_out_bps > need_per_second)
3599     distributable = bandwidth_target_out_bps - need_per_second;
3600   share = distributable * pref_rel;
3601   if (share + need_per_peer > UINT32_MAX)
3602     q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
3603   else
3604     q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3605   /* check if we want to disconnect for good due to inactivity */
3606   if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3607        (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3608     {
3609 #if DEBUG_CORE
3610       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3611                   "Forcing disconnect of `%4s' due to inactivity\n",
3612                   GNUNET_i2s (&n->peer));
3613 #endif
3614       q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3615     }
3616 #if DEBUG_CORE_QUOTA
3617   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3618               "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3619               GNUNET_i2s (&n->peer),
3620               (unsigned int) ntohl (q_in.value__),
3621               bandwidth_target_out_bps,
3622               (unsigned int) ntohl (n->bw_in.value__),
3623               (unsigned int) ntohl (n->bw_out.value__),
3624               (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3625 #endif
3626   if (n->bw_in.value__ != q_in.value__) 
3627     {
3628       n->bw_in = q_in;
3629       if (GNUNET_YES == n->is_connected)
3630         GNUNET_TRANSPORT_set_quota (transport,
3631                                     &n->peer,
3632                                     n->bw_in,
3633                                     n->bw_out,
3634                                     GNUNET_TIME_UNIT_FOREVER_REL,
3635                                     NULL, NULL);
3636       handle_peer_status_change (n);
3637     }
3638   schedule_quota_update (n);
3639 }
3640
3641
3642 /**
3643  * Function called by transport to notify us that
3644  * a peer connected to us (on the network level).
3645  *
3646  * @param cls closure
3647  * @param peer the peer that connected
3648  * @param latency current latency of the connection
3649  * @param distance in overlay hops, as given by transport plugin
3650  */
3651 static void
3652 handle_transport_notify_connect (void *cls,
3653                                  const struct GNUNET_PeerIdentity *peer,
3654                                  struct GNUNET_TIME_Relative latency,
3655                                  unsigned int distance)
3656 {
3657   struct Neighbour *n;
3658
3659   if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3660     {
3661       GNUNET_break (0);
3662       return;
3663     }
3664   n = find_neighbour (peer);
3665   if (n != NULL)
3666     {
3667       if (GNUNET_YES == n->is_connected)
3668         {
3669           /* duplicate connect notification!? */
3670           GNUNET_break (0);
3671           return;
3672         }
3673     }
3674   else
3675     {
3676       n = create_neighbour (peer);
3677     }
3678   GNUNET_STATISTICS_update (stats, 
3679                             gettext_noop ("# peers connected (transport)"), 
3680                             1, 
3681                             GNUNET_NO);
3682   n->is_connected = GNUNET_YES;      
3683   n->last_latency = latency;
3684   n->last_distance = distance;
3685   GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3686                                  n->bw_out,
3687                                  MAX_WINDOW_TIME_S);
3688   GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3689                                  n->bw_in,
3690                                  MAX_WINDOW_TIME_S);  
3691 #if DEBUG_CORE
3692   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3693               "Received connection from `%4s'.\n",
3694               GNUNET_i2s (&n->peer));
3695 #endif
3696   GNUNET_TRANSPORT_set_quota (transport,
3697                               &n->peer,
3698                               n->bw_in,
3699                               n->bw_out,
3700                               GNUNET_TIME_UNIT_FOREVER_REL,
3701                               NULL, NULL);
3702   send_key (n); 
3703 }
3704
3705
3706 /**
3707  * Function called by transport telling us that a peer
3708  * disconnected.
3709  *
3710  * @param cls closure
3711  * @param peer the peer that disconnected
3712  */
3713 static void
3714 handle_transport_notify_disconnect (void *cls,
3715                                     const struct GNUNET_PeerIdentity *peer)
3716 {
3717   struct DisconnectNotifyMessage cnm;
3718   struct Neighbour *n;
3719   struct GNUNET_TIME_Relative left;
3720
3721 #if DEBUG_CORE
3722   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3723               "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3724 #endif
3725   n = find_neighbour (peer);
3726   if (n == NULL)
3727     {
3728       GNUNET_break (0);
3729       return;
3730     }
3731   GNUNET_break (n->is_connected);
3732   if (n->status == PEER_STATE_KEY_CONFIRMED)
3733     {
3734       cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3735       cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3736       cnm.peer = *peer;
3737       send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3738     }
3739   n->is_connected = GNUNET_NO;
3740   GNUNET_STATISTICS_update (stats, 
3741                             gettext_noop ("# peers connected (transport)"), 
3742                             -1, 
3743                             GNUNET_NO);
3744   if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
3745     GNUNET_SCHEDULER_cancel (sched,
3746                              n->dead_clean_task);
3747   left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3748                                         GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
3749   n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (), 
3750                                                     left);
3751   n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
3752                                                      GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
3753                                                      &consider_free_task,
3754                                                      n);
3755 }
3756
3757
3758 /**
3759  * Last task run during shutdown.  Disconnects us from
3760  * the transport.
3761  */
3762 static void
3763 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3764 {
3765   struct Neighbour *n;
3766   struct Client *c;
3767
3768 #if DEBUG_CORE
3769   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3770               "Core service shutting down.\n");
3771 #endif
3772   GNUNET_assert (transport != NULL);
3773   GNUNET_TRANSPORT_disconnect (transport);
3774   transport = NULL;
3775   while (NULL != (n = neighbours))
3776     {
3777       neighbours = n->next;
3778       GNUNET_assert (neighbour_count > 0);
3779       neighbour_count--;
3780       free_neighbour (n);
3781     }
3782   GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
3783   GNUNET_SERVER_notification_context_destroy (notifier);
3784   notifier = NULL;
3785   while (NULL != (c = clients))
3786     handle_client_disconnect (NULL, c->client_handle);
3787   if (my_private_key != NULL)
3788     GNUNET_CRYPTO_rsa_key_free (my_private_key);
3789   if (stats != NULL)
3790     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3791   if (peerinfo != NULL)
3792     GNUNET_PEERINFO_disconnect (peerinfo);
3793   if (mst != NULL)
3794     GNUNET_SERVER_mst_destroy (mst);
3795 }
3796
3797
3798 /**
3799  * Initiate core service.
3800  *
3801  * @param cls closure
3802  * @param s scheduler to use
3803  * @param server the initialized server
3804  * @param c configuration to use
3805  */
3806 static void
3807 run (void *cls,
3808      struct GNUNET_SCHEDULER_Handle *s,
3809      struct GNUNET_SERVER_Handle *server,
3810      const struct GNUNET_CONFIGURATION_Handle *c)
3811 {
3812   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3813     {&handle_client_init, NULL,
3814      GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
3815     {&handle_client_request_info, NULL,
3816      GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
3817      sizeof (struct RequestInfoMessage)},
3818     {&handle_client_send, NULL,
3819      GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
3820     {&handle_client_request_connect, NULL,
3821      GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
3822      sizeof (struct ConnectMessage)},
3823     {NULL, NULL, 0, 0}
3824   };
3825   char *keyfile;
3826
3827   sched = s;
3828   cfg = c;  
3829   /* parse configuration */
3830   if (
3831        (GNUNET_OK !=
3832         GNUNET_CONFIGURATION_get_value_number (c,
3833                                                "CORE",
3834                                                "TOTAL_QUOTA_IN",
3835                                                &bandwidth_target_in_bps)) ||
3836        (GNUNET_OK !=
3837         GNUNET_CONFIGURATION_get_value_number (c,
3838                                                "CORE",
3839                                                "TOTAL_QUOTA_OUT",
3840                                                &bandwidth_target_out_bps)) ||
3841        (GNUNET_OK !=
3842         GNUNET_CONFIGURATION_get_value_filename (c,
3843                                                  "GNUNETD",
3844                                                  "HOSTKEY", &keyfile)))
3845     {
3846       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3847                   _
3848                   ("Core service is lacking key configuration settings.  Exiting.\n"));
3849       GNUNET_SCHEDULER_shutdown (s);
3850       return;
3851     }
3852   peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
3853   if (NULL == peerinfo)
3854     {
3855       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3856                   _("Could not access PEERINFO service.  Exiting.\n"));
3857       GNUNET_SCHEDULER_shutdown (s);
3858       GNUNET_free (keyfile);
3859       return;
3860     }
3861   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3862   GNUNET_free (keyfile);
3863   if (my_private_key == NULL)
3864     {
3865       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3866                   _("Core service could not access hostkey.  Exiting.\n"));
3867       GNUNET_PEERINFO_disconnect (peerinfo);
3868       GNUNET_SCHEDULER_shutdown (s);
3869       return;
3870     }
3871   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3872   GNUNET_CRYPTO_hash (&my_public_key,
3873                       sizeof (my_public_key), &my_identity.hashPubKey);
3874   /* setup notification */
3875   notifier = GNUNET_SERVER_notification_context_create (server, 
3876                                                         MAX_NOTIFY_QUEUE);
3877   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3878   /* setup transport connection */
3879   transport = GNUNET_TRANSPORT_connect (sched,
3880                                         cfg,
3881                                         &my_identity,
3882                                         NULL,
3883                                         &handle_transport_receive,
3884                                         &handle_transport_notify_connect,
3885                                         &handle_transport_notify_disconnect);
3886   GNUNET_assert (NULL != transport);
3887   stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3888   mst = GNUNET_SERVER_mst_create (&deliver_message,
3889                                   NULL);
3890   GNUNET_SCHEDULER_add_delayed (sched,
3891                                 GNUNET_TIME_UNIT_FOREVER_REL,
3892                                 &cleaning_task, NULL);
3893   /* process client requests */
3894   GNUNET_SERVER_add_handlers (server, handlers);
3895   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3896               _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3897 }
3898
3899
3900
3901 /**
3902  * The main function for the transport service.
3903  *
3904  * @param argc number of arguments from the command line
3905  * @param argv command line arguments
3906  * @return 0 ok, 1 on error
3907  */
3908 int
3909 main (int argc, char *const *argv)
3910 {
3911   return (GNUNET_OK ==
3912           GNUNET_SERVICE_run (argc,
3913                               argv,
3914                               "core",
3915                               GNUNET_SERVICE_OPTION_NONE,
3916                               &run, NULL)) ? 0 : 1;
3917 }
3918
3919 /* end of gnunet-service-core.c */