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