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