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