2 This file is part of GNUnet.
3 (C) 2009 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
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.
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.
22 * @file core/gnunet-service-core.c
23 * @brief high-level P2P messaging
24 * @author Christian Grothoff
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)
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_transport_service.h"
44 #define DEBUG_HANDSHAKE GNUNET_NO
47 * Receive and send buffer windows grow over time. For
48 * how long can 'unused' bandwidth accumulate before we
49 * need to cap it? (specified in ms).
51 #define MAX_WINDOW_TIME (5 * 60 * 1000)
54 * How many messages do we queue up at most for optional
55 * notifications to a client? (this can cause notifications
56 * about outgoing messages to be dropped).
58 #define MAX_NOTIFY_QUEUE 16
61 * Minimum of bytes per minute (out) to assign to any connected peer.
62 * Should be rather low; values larger than DEFAULT_BPM_IN_OUT make no
65 #define MIN_BPM_PER_PEER GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT
68 * What is the smallest change (in number of bytes per minute)
69 * that we consider significant enough to bother triggering?
71 #define MIN_BPM_CHANGE 32
74 * After how much time past the "official" expiration time do
75 * we discard messages? Should not be zero since we may
76 * intentionally defer transmission until close to the deadline
77 * and then may be slightly past the deadline due to inaccuracy
78 * in sleep and our own CPU consumption.
80 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
83 * What is the maximum delay for a SET_KEY message?
85 #define MAX_SET_KEY_DELAY GNUNET_TIME_UNIT_SECONDS
88 * What how long do we wait for SET_KEY confirmation initially?
90 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3)
93 * What is the maximum delay for a PING message?
95 #define MAX_PING_DELAY GNUNET_TIME_UNIT_SECONDS
98 * What is the maximum delay for a PONG message?
100 #define MAX_PONG_DELAY GNUNET_TIME_UNIT_SECONDS
103 * How often do we recalculate bandwidth quotas?
105 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_UNIT_SECONDS
108 * What is the priority for a SET_KEY message?
110 #define SET_KEY_PRIORITY 0xFFFFFF
113 * What is the priority for a PING message?
115 #define PING_PRIORITY 0xFFFFFF
118 * What is the priority for a PONG message?
120 #define PONG_PRIORITY 0xFFFFFF
123 * How many messages do we queue per peer at most?
125 #define MAX_PEER_QUEUE_SIZE 16
128 * How many non-mandatory messages do we queue per client at most?
130 #define MAX_CLIENT_QUEUE_SIZE 32
133 * What is the maximum age of a message for us to consider
134 * processing it? Note that this looks at the timestamp used
135 * by the other peer, so clock skew between machines does
136 * come into play here. So this should be picked high enough
137 * so that a little bit of clock skew does not prevent peers
138 * from connecting to us.
140 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
143 * What is the maximum size for encrypted messages? Note that this
144 * number imposes a clear limit on the maximum size of any message.
145 * Set to a value close to 64k but not so close that transports will
146 * have trouble with their headers.
148 #define MAX_ENCRYPTED_MESSAGE_SIZE (63 * 1024)
152 * State machine for our P2P encryption handshake. Everyone starts in
153 * "DOWN", if we receive the other peer's key (other peer initiated)
154 * we start in state RECEIVED (since we will immediately send our
155 * own); otherwise we start in SENT. If we get back a PONG from
156 * within either state, we move up to CONFIRMED (the PONG will always
157 * be sent back encrypted with the key we sent to the other peer).
159 enum PeerStateMachine
163 PEER_STATE_KEY_RECEIVED,
164 PEER_STATE_KEY_CONFIRMED
169 * Number of bytes (at the beginning) of "struct EncryptedMessage"
170 * that are NOT encrypted.
172 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t) + sizeof(GNUNET_HashCode))
176 * Encapsulation for encrypted messages exchanged between
177 * peers. Followed by the actual encrypted data.
179 struct EncryptedMessage
182 * Message type is either CORE_ENCRYPTED_MESSAGE.
184 struct GNUNET_MessageHeader header;
189 uint32_t reserved GNUNET_PACKED;
192 * Hash of the plaintext, used to verify message integrity;
193 * ALSO used as the IV for the symmetric cipher! Everything
194 * after this hash will be encrypted. ENCRYPTED_HEADER_SIZE
195 * must be set to the offset of the next field.
197 GNUNET_HashCode plaintext_hash;
200 * Sequence number, in network byte order. This field
201 * must be the first encrypted/decrypted field and the
202 * first byte that is hashed for the plaintext hash.
204 uint32_t sequence_number GNUNET_PACKED;
207 * Desired bandwidth (how much we should send to this
208 * peer / how much is the sender willing to receive),
209 * in bytes per minute.
211 uint32_t inbound_bpm_limit GNUNET_PACKED;
214 * Timestamp. Used to prevent reply of ancient messages
215 * (recent messages are caught with the sequence number).
217 struct GNUNET_TIME_AbsoluteNBO timestamp;
222 * We're sending an (encrypted) PING to the other peer to check if he
223 * can decrypt. The other peer should respond with a PONG with the
224 * same content, except this time encrypted with the receiver's key.
229 * Message type is either CORE_PING or CORE_PONG.
231 struct GNUNET_MessageHeader header;
234 * Random number chosen to make reply harder.
236 uint32_t challenge GNUNET_PACKED;
239 * Intended target of the PING, used primarily to check
240 * that decryption actually worked.
242 struct GNUNET_PeerIdentity target;
247 * Message transmitted to set (or update) a session key.
253 * Message type is either CORE_SET_KEY.
255 struct GNUNET_MessageHeader header;
258 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
260 int32_t sender_status GNUNET_PACKED;
263 * Purpose of the signature, will be
264 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
266 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
269 * At what time was this key created?
271 struct GNUNET_TIME_AbsoluteNBO creation_time;
274 * The encrypted session key.
276 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
279 * Who is the intended recipient?
281 struct GNUNET_PeerIdentity target;
284 * Signature of the stuff above (starting at purpose).
286 struct GNUNET_CRYPTO_RsaSignature signature;
292 * Message waiting for transmission. This struct
293 * is followed by the actual content of the message.
299 * We keep messages in a doubly linked list.
301 struct MessageEntry *next;
304 * We keep messages in a doubly linked list.
306 struct MessageEntry *prev;
309 * By when are we supposed to transmit this message?
311 struct GNUNET_TIME_Absolute deadline;
314 * How important is this message to us?
316 unsigned int priority;
319 * How long is the message? (number of bytes following
320 * the "struct MessageEntry", but not including the
321 * size of "struct MessageEntry" itself!)
326 * Was this message selected for transmission in the
327 * current round? GNUNET_YES or GNUNET_NO.
332 * Did we give this message some slack (delayed sending) previously
333 * (and hence should not give it any more slack)? GNUNET_YES or
344 * We keep neighbours in a linked list (for now).
346 struct Neighbour *next;
349 * Unencrypted messages destined for this peer.
351 struct MessageEntry *messages;
354 * Head of the batched, encrypted message queue (already ordered,
355 * transmit starting with the head).
357 struct MessageEntry *encrypted_head;
360 * Tail of the batched, encrypted message queue (already ordered,
361 * append new messages to tail)
363 struct MessageEntry *encrypted_tail;
366 * Handle for pending requests for transmission to this peer
367 * with the transport service. NULL if no request is pending.
369 struct GNUNET_TRANSPORT_TransmitHandle *th;
372 * Public key of the neighbour, NULL if we don't have it yet.
374 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
377 * We received a PING message before we got the "public_key"
378 * (or the SET_KEY). We keep it here until we have a key
379 * to decrypt it. NULL if no PING is pending.
381 struct PingMessage *pending_ping;
384 * We received a PONG message before we got the "public_key"
385 * (or the SET_KEY). We keep it here until we have a key
386 * to decrypt it. NULL if no PONG is pending.
388 struct PingMessage *pending_pong;
391 * Non-NULL if we are currently looking up HELLOs for this peer.
394 struct GNUNET_PEERINFO_IteratorContext *pitr;
397 * SetKeyMessage to transmit, NULL if we are not currently trying
400 struct SetKeyMessage *skm;
403 * Identity of the neighbour.
405 struct GNUNET_PeerIdentity peer;
408 * Key we use to encrypt our messages for the other peer
409 * (initialized by us when we do the handshake).
411 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
414 * Key we use to decrypt messages from the other peer
415 * (given to us by the other peer during the handshake).
417 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
420 * ID of task used for re-trying plaintext scheduling.
422 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
425 * ID of task used for re-trying SET_KEY and PING message.
427 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
430 * ID of task used for updating bandwidth quota for this neighbour.
432 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
435 * ID of task used for cleaning up dead neighbour entries.
437 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
440 * At what time did we generate our encryption key?
442 struct GNUNET_TIME_Absolute encrypt_key_created;
445 * At what time did the other peer generate the decryption key?
447 struct GNUNET_TIME_Absolute decrypt_key_created;
450 * At what time did we initially establish (as in, complete session
451 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
453 struct GNUNET_TIME_Absolute time_established;
456 * At what time did we last receive an encrypted message from the
457 * other peer? Should be zero if status != KEY_CONFIRMED.
459 struct GNUNET_TIME_Absolute last_activity;
462 * Last latency observed from this peer.
464 struct GNUNET_TIME_Relative last_latency;
467 * At what frequency are we currently re-trying SET_KEY messages?
469 struct GNUNET_TIME_Relative set_key_retry_frequency;
472 * Time of our last update to the "available_send_window".
474 struct GNUNET_TIME_Absolute last_asw_update;
477 * Time of our last update to the "available_recv_window".
479 struct GNUNET_TIME_Absolute last_arw_update;
482 * Number of bytes that we are eligible to transmit to this
483 * peer at this point. Incremented every minute by max_out_bpm,
484 * bounded by max_bpm (no back-log larger than MAX_BUF_FACT minutes,
485 * bandwidth-hogs are sampled at a frequency of about 78s!);
486 * may get negative if we have VERY high priority content.
488 long long available_send_window;
491 * How much downstream capacity of this peer has been reserved for
492 * our traffic? (Our clients can request that a certain amount of
493 * bandwidth is available for replies to them; this value is used to
494 * make sure that this reserved amount of bandwidth is actually
497 long long available_recv_window;
500 * How valueable were the messages of this peer recently?
502 unsigned long long current_preference;
505 * Bit map indicating which of the 32 sequence numbers before the last
506 * were received (good for accepting out-of-order packets and
507 * estimating reliability of the connection)
509 unsigned int last_packets_bitmap;
512 * last sequence number received on this connection (highest)
514 uint32_t last_sequence_number_received;
517 * last sequence number transmitted
519 uint32_t last_sequence_number_sent;
522 * Available bandwidth in for this peer (current target).
527 * Available bandwidth out for this peer (current target).
532 * Internal bandwidth limit set for this peer (initially
533 * typically set to "-1"). "bpm_out" is MAX of
534 * "bpm_out_internal_limit" and "bpm_out_external_limit".
536 uint32_t bpm_out_internal_limit;
539 * External bandwidth limit set for this peer by the
540 * peer that we are communicating with. "bpm_out" is MAX of
541 * "bpm_out_internal_limit" and "bpm_out_external_limit".
543 uint32_t bpm_out_external_limit;
546 * What was our PING challenge number (for this peer)?
548 uint32_t ping_challenge;
551 * What was the last distance to this peer as reported by the transports?
553 uint32_t last_distance;
556 * What is our connection status?
558 enum PeerStateMachine status;
561 * Are we currently connected to this neighbour?
568 * Data structure for each client connected to the core service.
573 * Clients are kept in a linked list.
578 * Handle for the client with the server API.
580 struct GNUNET_SERVER_Client *client_handle;
583 * Array of the types of messages this peer cares
584 * about (with "tcnt" entries). Allocated as part
585 * of this client struct, do not free!
590 * Options for messages this client cares about,
591 * see GNUNET_CORE_OPTION_ values.
596 * Number of types of incoming messages this client
597 * specifically cares about. Size of the "types" array.
607 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
612 static struct GNUNET_PeerIdentity my_identity;
617 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
622 struct GNUNET_SCHEDULER_Handle *sched;
627 const struct GNUNET_CONFIGURATION_Handle *cfg;
632 static struct GNUNET_SERVER_Handle *server;
637 static struct GNUNET_TRANSPORT_Handle *transport;
640 * Linked list of our clients.
642 static struct Client *clients;
645 * Context for notifications we need to send to our clients.
647 static struct GNUNET_SERVER_NotificationContext *notifier;
650 * We keep neighbours in a linked list (for now).
652 static struct Neighbour *neighbours;
655 * Sum of all preferences among all neighbours.
657 static unsigned long long preference_sum;
660 * Total number of neighbours we have.
662 static unsigned int neighbour_count;
665 * How much inbound bandwidth are we supposed to be using?
667 static unsigned long long bandwidth_target_in;
670 * How much outbound bandwidth are we supposed to be using?
672 static unsigned long long bandwidth_target_out;
677 * A preference value for a neighbour was update. Update
678 * the preference sum accordingly.
680 * @param inc how much was a preference value increased?
683 update_preference_sum (unsigned long long inc)
686 unsigned long long os;
689 preference_sum += inc;
690 if (preference_sum >= os)
692 /* overflow! compensate by cutting all values in half! */
697 n->current_preference /= 2;
698 preference_sum += n->current_preference;
705 * Recalculate the number of bytes we expect to
706 * receive or transmit in a given window.
708 * @param force force an update now (even if not much time has passed)
709 * @param window pointer to the byte counter (updated)
710 * @param ts pointer to the timestamp (updated)
711 * @param bpm number of bytes per minute that should
712 * be added to the window.
715 update_window (int force,
717 struct GNUNET_TIME_Absolute *ts, unsigned int bpm)
719 struct GNUNET_TIME_Relative since;
720 unsigned long long increment;
722 since = GNUNET_TIME_absolute_get_duration (*ts);
723 increment = (bpm * since.value) / 60 / 1000;
724 if ( (force == GNUNET_NO) &&
725 (since.value < 60 * 1000) &&
726 (increment < 32 * 1024) )
727 return; /* not even a minute has passed */
728 *ts = GNUNET_TIME_absolute_get ();
729 *window += increment;
730 if (*window > MAX_WINDOW_TIME * bpm)
731 *window = MAX_WINDOW_TIME * bpm;
736 * Find the entry for the given neighbour.
738 * @param peer identity of the neighbour
739 * @return NULL if we are not connected, otherwise the
742 static struct Neighbour *
743 find_neighbour (const struct GNUNET_PeerIdentity *peer)
745 struct Neighbour *ret;
748 while ((ret != NULL) &&
749 (0 != memcmp (&ret->peer,
750 peer, sizeof (struct GNUNET_PeerIdentity))))
757 * Send a message to one of our clients.
759 * @param client target for the message
760 * @param msg message to transmit
761 * @param can_drop could this message be dropped if the
762 * client's queue is getting too large?
765 send_to_client (struct Client *client,
766 const struct GNUNET_MessageHeader *msg,
769 #if DEBUG_CORE_CLIENT
770 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
771 "Preparing to send message of type %u to client.\n",
774 GNUNET_SERVER_notification_context_unicast (notifier,
775 client->client_handle,
782 * Send a message to all of our current clients that have
783 * the right options set.
785 * @param msg message to multicast
786 * @param can_drop can this message be discarded if the queue is too long
787 * @param options mask to use
790 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
799 if (0 != (c->options & options))
800 send_to_client (c, msg, can_drop);
807 * Handle CORE_INIT request.
810 handle_client_init (void *cls,
811 struct GNUNET_SERVER_Client *client,
812 const struct GNUNET_MessageHeader *message)
814 const struct InitMessage *im;
815 struct InitReplyMessage irm;
818 const uint16_t *types;
820 struct ConnectNotifyMessage cnm;
822 #if DEBUG_CORE_CLIENT
823 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
824 "Client connecting to core service with `%s' message\n",
827 /* check that we don't have an entry already */
831 if (client == c->client_handle)
834 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
839 msize = ntohs (message->size);
840 if (msize < sizeof (struct InitMessage))
843 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
846 GNUNET_SERVER_notification_context_add (notifier, client);
847 im = (const struct InitMessage *) message;
848 types = (const uint16_t *) &im[1];
849 msize -= sizeof (struct InitMessage);
850 c = GNUNET_malloc (sizeof (struct Client) + msize);
851 c->client_handle = client;
854 memcpy (&c[1], types, msize);
855 c->types = (uint16_t *) & c[1];
856 c->options = ntohl (im->options);
857 c->tcnt = msize / sizeof (uint16_t);
858 /* send init reply message */
859 irm.header.size = htons (sizeof (struct InitReplyMessage));
860 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
861 irm.reserved = htonl (0);
862 memcpy (&irm.publicKey,
864 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
865 #if DEBUG_CORE_CLIENT
866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
867 "Sending `%s' message to client.\n", "INIT_REPLY");
869 send_to_client (c, &irm.header, GNUNET_NO);
870 /* notify new client about existing neighbours */
871 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
872 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
876 if (n->status == PEER_STATE_KEY_CONFIRMED)
878 #if DEBUG_CORE_CLIENT
879 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
880 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
882 cnm.distance = htonl (n->last_distance);
883 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
885 send_to_client (c, &cnm.header, GNUNET_NO);
889 GNUNET_SERVER_receive_done (client, GNUNET_OK);
894 * A client disconnected, clean up.
897 * @param client identification of the client
900 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
907 #if DEBUG_CORE_CLIENT
908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
909 "Client has disconnected from core service.\n");
915 if (client == pos->client_handle)
920 prev->next = pos->next;
927 /* client never sent INIT */
932 * Handle REQUEST_INFO request.
935 handle_client_request_info (void *cls,
936 struct GNUNET_SERVER_Client *client,
937 const struct GNUNET_MessageHeader *message)
939 const struct RequestInfoMessage *rcm;
941 struct ConfigurationInfoMessage cim;
944 unsigned long long old_preference;
945 struct GNUNET_SERVER_TransmitContext *tc;
947 #if DEBUG_CORE_CLIENT
948 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
949 "Core service receives `%s' request.\n", "REQUEST_INFO");
951 rcm = (const struct RequestInfoMessage *) message;
952 n = find_neighbour (&rcm->peer);
953 memset (&cim, 0, sizeof (cim));
956 update_window (GNUNET_YES,
957 &n->available_send_window,
960 n->bpm_out_internal_limit = ntohl (rcm->limit_outbound_bpm);
961 n->bpm_out = GNUNET_MAX (n->bpm_out_internal_limit,
962 n->bpm_out_external_limit);
963 want_reserv = ntohl (rcm->reserve_inbound);
966 n->available_recv_window += want_reserv;
968 else if (want_reserv > 0)
970 update_window (GNUNET_NO,
971 &n->available_recv_window,
972 &n->last_arw_update, n->bpm_in);
973 if (n->available_recv_window < want_reserv)
974 got_reserv = n->available_recv_window;
976 got_reserv = want_reserv;
977 n->available_recv_window -= got_reserv;
979 old_preference = n->current_preference;
980 n->current_preference += GNUNET_ntohll(rcm->preference_change);
981 if (old_preference > n->current_preference)
983 /* overflow; cap at maximum value */
984 n->current_preference = (unsigned long long) -1;
986 update_preference_sum (n->current_preference - old_preference);
987 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
988 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
990 GNUNET_i2s (&rcm->peer),
992 cim.reserved_amount = htonl (got_reserv);
993 cim.bpm_in = htonl (n->bpm_in);
994 cim.bpm_out = htonl (n->bpm_out);
995 cim.preference = n->current_preference;
997 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
998 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
999 cim.peer = rcm->peer;
1001 #if DEBUG_CORE_CLIENT
1002 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1003 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1005 tc = GNUNET_SERVER_transmit_context_create (client);
1006 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1007 GNUNET_SERVER_transmit_context_run (tc,
1008 GNUNET_TIME_UNIT_FOREVER_REL);
1013 * Free the given entry for the neighbour (it has
1014 * already been removed from the list at this point).
1016 * @param n neighbour to free
1019 free_neighbour (struct Neighbour *n)
1021 struct MessageEntry *m;
1023 if (n->pitr != NULL)
1025 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1030 GNUNET_free (n->skm);
1033 while (NULL != (m = n->messages))
1035 n->messages = m->next;
1038 while (NULL != (m = n->encrypted_head))
1040 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1047 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1050 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1051 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1052 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1053 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1054 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1055 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1056 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1057 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1058 GNUNET_free_non_null (n->public_key);
1059 GNUNET_free_non_null (n->pending_ping);
1060 GNUNET_free_non_null (n->pending_pong);
1066 * Consider freeing the given neighbour since we may not need
1067 * to keep it around anymore.
1069 * @param n neighbour to consider discarding
1072 consider_free_neighbour (struct Neighbour *n);
1076 * Task triggered when a neighbour entry might have gotten stale.
1078 * @param cls the 'struct Neighbour'
1079 * @param tc scheduler context (not used)
1082 consider_free_task (void *cls,
1083 const struct GNUNET_SCHEDULER_TaskContext *tc)
1085 struct Neighbour *n = cls;
1086 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1087 consider_free_neighbour (n);
1092 * Consider freeing the given neighbour since we may not need
1093 * to keep it around anymore.
1095 * @param n neighbour to consider discarding
1098 consider_free_neighbour (struct Neighbour *n)
1100 struct Neighbour *pos;
1101 struct Neighbour *prev;
1102 struct GNUNET_TIME_Relative left;
1104 if ( (n->th != NULL) ||
1105 (n->pitr != NULL) ||
1106 (n->status == PEER_STATE_KEY_CONFIRMED) ||
1107 (GNUNET_YES == n->is_connected) )
1108 return; /* no chance */
1110 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1114 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1115 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1116 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1118 &consider_free_task,
1122 /* actually free the neighbour... */
1131 neighbours = n->next;
1133 prev->next = n->next;
1134 GNUNET_assert (neighbour_count > 0);
1141 * Check if we have encrypted messages for the specified neighbour
1142 * pending, and if so, check with the transport about sending them
1145 * @param n neighbour to check.
1147 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1151 * Function called when the transport service is ready to
1152 * receive an encrypted message for the respective peer
1154 * @param cls neighbour to use message from
1155 * @param size number of bytes we can transmit
1156 * @param buf where to copy the message
1157 * @return number of bytes transmitted
1160 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1162 struct Neighbour *n = cls;
1163 struct MessageEntry *m;
1168 GNUNET_assert (NULL != (m = n->encrypted_head));
1169 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1176 GNUNET_assert (size >= m->size);
1177 memcpy (cbuf, &m[1], m->size);
1179 n->available_send_window -= m->size;
1180 process_encrypted_neighbour_queue (n);
1183 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1184 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1185 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1186 ret, GNUNET_i2s (&n->peer));
1192 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1193 "Transmission of message of type %u and size %u failed\n",
1194 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1199 consider_free_neighbour (n);
1205 * Check if we have plaintext messages for the specified neighbour
1206 * pending, and if so, consider batching and encrypting them (and
1207 * then trigger processing of the encrypted queue if needed).
1209 * @param n neighbour to check.
1211 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1215 * Check if we have encrypted messages for the specified neighbour
1216 * pending, and if so, check with the transport about sending them
1219 * @param n neighbour to check.
1222 process_encrypted_neighbour_queue (struct Neighbour *n)
1224 struct MessageEntry *m;
1227 return; /* request already pending */
1228 m = n->encrypted_head;
1231 /* encrypted queue empty, try plaintext instead */
1232 process_plaintext_neighbour_queue (n);
1236 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1237 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1239 GNUNET_i2s (&n->peer),
1240 GNUNET_TIME_absolute_get_remaining (m->deadline).
1244 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1247 GNUNET_TIME_absolute_get_remaining
1249 ¬ify_encrypted_transmit_ready,
1253 /* message request too large or duplicate request */
1255 /* discard encrypted message */
1256 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1260 process_encrypted_neighbour_queue (n);
1266 * Decrypt size bytes from in and write the result to out. Use the
1267 * key for inbound traffic of the given neighbour. This function does
1268 * NOT do any integrity-checks on the result.
1270 * @param n neighbour we are receiving from
1271 * @param iv initialization vector to use
1272 * @param in ciphertext
1273 * @param out plaintext
1274 * @param size size of in/out
1275 * @return GNUNET_OK on success
1278 do_decrypt (struct Neighbour *n,
1279 const GNUNET_HashCode * iv,
1280 const void *in, void *out, size_t size)
1282 if (size != (uint16_t) size)
1287 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1288 (n->status != PEER_STATE_KEY_CONFIRMED))
1290 GNUNET_break_op (0);
1291 return GNUNET_SYSERR;
1294 GNUNET_CRYPTO_aes_decrypt (in,
1298 GNUNET_CRYPTO_AesInitializationVector *) iv,
1302 return GNUNET_SYSERR;
1305 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1306 "Decrypted %u bytes from `%4s' using key %u\n",
1307 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1314 * Encrypt size bytes from in and write the result to out. Use the
1315 * key for outbound traffic of the given neighbour.
1317 * @param n neighbour we are sending to
1318 * @param iv initialization vector to use
1319 * @param in ciphertext
1320 * @param out plaintext
1321 * @param size size of in/out
1322 * @return GNUNET_OK on success
1325 do_encrypt (struct Neighbour *n,
1326 const GNUNET_HashCode * iv,
1327 const void *in, void *out, size_t size)
1329 if (size != (uint16_t) size)
1334 GNUNET_assert (size ==
1335 GNUNET_CRYPTO_aes_encrypt (in,
1339 GNUNET_CRYPTO_AesInitializationVector
1342 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1343 "Encrypted %u bytes for `%4s' using key %u\n", size,
1344 GNUNET_i2s (&n->peer), n->encrypt_key.crc32);
1351 * Select messages for transmission. This heuristic uses a combination
1352 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1353 * and priority-based discard (in case no feasible schedule exist) and
1354 * speculative optimization (defer any kind of transmission until
1355 * we either create a batch of significant size, 25% of max, or until
1356 * we are close to a deadline). Furthermore, when scheduling the
1357 * heuristic also packs as many messages into the batch as possible,
1358 * starting with those with the earliest deadline. Yes, this is fun.
1360 * @param n neighbour to select messages from
1361 * @param size number of bytes to select for transmission
1362 * @param retry_time set to the time when we should try again
1363 * (only valid if this function returns zero)
1364 * @return number of bytes selected, or 0 if we decided to
1365 * defer scheduling overall; in that case, retry_time is set.
1368 select_messages (struct Neighbour *n,
1369 size_t size, struct GNUNET_TIME_Relative *retry_time)
1371 struct MessageEntry *pos;
1372 struct MessageEntry *min;
1373 struct MessageEntry *last;
1374 unsigned int min_prio;
1375 struct GNUNET_TIME_Absolute t;
1376 struct GNUNET_TIME_Absolute now;
1379 unsigned long long slack; /* how long could we wait before missing deadlines? */
1381 int discard_low_prio;
1383 GNUNET_assert (NULL != n->messages);
1384 now = GNUNET_TIME_absolute_get ();
1385 /* last entry in linked list of messages processed */
1387 /* should we remove the entry with the lowest
1388 priority from consideration for scheduling at the
1390 discard_low_prio = GNUNET_YES;
1391 while (GNUNET_YES == discard_low_prio)
1395 discard_low_prio = GNUNET_NO;
1396 /* calculate number of bytes available for transmission at time "t" */
1397 update_window (GNUNET_NO,
1398 &n->available_send_window,
1399 &n->last_asw_update,
1401 avail = n->available_send_window;
1402 t = n->last_asw_update;
1403 /* how many bytes have we (hypothetically) scheduled so far */
1405 /* maximum time we can wait before transmitting anything
1406 and still make all of our deadlines */
1410 /* note that we use "*2" here because we want to look
1411 a bit further into the future; much more makes no
1412 sense since new message might be scheduled in the
1414 while ((pos != NULL) && (off < size * 2))
1416 if (pos->do_transmit == GNUNET_YES)
1418 /* already removed from consideration */
1422 if (discard_low_prio == GNUNET_NO)
1424 delta = pos->deadline.value;
1425 if (delta < t.value)
1428 delta = t.value - delta;
1429 avail += delta * n->bpm_out / 1000 / 60;
1430 if (avail < pos->size)
1432 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1437 /* update slack, considering both its absolute deadline
1438 and relative deadlines caused by other messages
1439 with their respective load */
1440 slack = GNUNET_MIN (slack, avail / n->bpm_out);
1441 if ( (pos->deadline.value < now.value) ||
1442 (GNUNET_YES == pos->got_slack) )
1449 GNUNET_MIN (slack, pos->deadline.value - now.value);
1450 pos->got_slack = GNUNET_YES;
1456 t.value = GNUNET_MAX (pos->deadline.value, t.value);
1457 if (pos->priority <= min_prio)
1459 /* update min for discard */
1460 min_prio = pos->priority;
1465 if (discard_low_prio)
1467 GNUNET_assert (min != NULL);
1468 /* remove lowest-priority entry from consideration */
1469 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1473 /* guard against sending "tiny" messages with large headers without
1475 if ( (slack > 1000) && (size > 4 * off) )
1477 /* less than 25% of message would be filled with deadlines still
1478 being met if we delay by one second or more; so just wait for
1479 more data; but do not wait longer than 1s (since we don't want
1480 to delay messages for a really long time either). */
1481 retry_time->value = 1000;
1482 /* reset do_transmit values for next time */
1485 pos->do_transmit = GNUNET_NO;
1489 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1490 "Deferring transmission for 1s due to underfull message buffer size\n");
1494 /* select marked messages (up to size) for transmission */
1499 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1501 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1506 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1510 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1511 "Selected %u bytes of plaintext messages for transmission to `%4s'.\n",
1512 off, GNUNET_i2s (&n->peer));
1519 * Batch multiple messages into a larger buffer.
1521 * @param n neighbour to take messages from
1522 * @param buf target buffer
1523 * @param size size of buf
1524 * @param deadline set to transmission deadline for the result
1525 * @param retry_time set to the time when we should try again
1526 * (only valid if this function returns zero)
1527 * @param priority set to the priority of the batch
1528 * @return number of bytes written to buf (can be zero)
1531 batch_message (struct Neighbour *n,
1534 struct GNUNET_TIME_Absolute *deadline,
1535 struct GNUNET_TIME_Relative *retry_time,
1536 unsigned int *priority)
1538 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1539 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1540 struct MessageEntry *pos;
1541 struct MessageEntry *prev;
1542 struct MessageEntry *next;
1547 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1548 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1549 if (0 == select_messages (n, size, retry_time))
1551 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1552 "No messages selected, will try again in %llu ms\n",
1556 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1557 ntm->distance = htonl (n->last_distance);
1558 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1559 ntm->peer = n->peer;
1563 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1566 if (GNUNET_YES == pos->do_transmit)
1568 GNUNET_assert (pos->size <= size);
1569 /* do notifications */
1570 /* FIXME: track if we have *any* client that wants
1571 full notifications and only do this if that is
1573 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1575 memcpy (&ntm[1], &pos[1], pos->size);
1576 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1577 sizeof (struct GNUNET_MessageHeader));
1578 send_to_all_clients (&ntm->header,
1580 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1584 /* message too large for 'full' notifications, we do at
1585 least the 'hdr' type */
1588 sizeof (struct GNUNET_MessageHeader));
1590 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1592 send_to_all_clients (&ntm->header,
1594 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1597 "Encrypting message of type %u\n",
1598 ntohs(((struct GNUNET_MessageHeader*)&pos[1])->type));
1600 /* copy for encrypted transmission */
1601 memcpy (&buf[ret], &pos[1], pos->size);
1604 *priority += pos->priority;
1606 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1607 "Adding plaintext message with deadline %llu ms to batch\n",
1608 GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1610 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1624 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1625 "Deadline for message batch is %llu ms\n",
1626 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1633 * Remove messages with deadlines that have long expired from
1636 * @param n neighbour to inspect
1639 discard_expired_messages (struct Neighbour *n)
1641 struct MessageEntry *prev;
1642 struct MessageEntry *next;
1643 struct MessageEntry *pos;
1644 struct GNUNET_TIME_Absolute now;
1645 struct GNUNET_TIME_Relative delta;
1647 now = GNUNET_TIME_absolute_get ();
1653 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1654 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1657 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1658 "Message is %llu ms past due, discarding.\n",
1675 * Signature of the main function of a task.
1677 * @param cls closure
1678 * @param tc context information (why was this task triggered now)
1681 retry_plaintext_processing (void *cls,
1682 const struct GNUNET_SCHEDULER_TaskContext *tc)
1684 struct Neighbour *n = cls;
1686 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1687 process_plaintext_neighbour_queue (n);
1692 * Send our key (and encrypted PING) to the other peer.
1694 * @param n the other peer
1696 static void send_key (struct Neighbour *n);
1699 * Task that will retry "send_key" if our previous attempt failed
1703 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1705 struct Neighbour *n = cls;
1707 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1708 n->set_key_retry_frequency =
1709 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1715 * Check if we have plaintext messages for the specified neighbour
1716 * pending, and if so, consider batching and encrypting them (and
1717 * then trigger processing of the encrypted queue if needed).
1719 * @param n neighbour to check.
1722 process_plaintext_neighbour_queue (struct Neighbour *n)
1724 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1727 struct EncryptedMessage *em; /* encrypted message */
1728 struct EncryptedMessage *ph; /* plaintext header */
1729 struct MessageEntry *me;
1730 unsigned int priority;
1731 struct GNUNET_TIME_Absolute deadline;
1732 struct GNUNET_TIME_Relative retry_time;
1734 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1736 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1737 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1741 case PEER_STATE_DOWN:
1744 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1745 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1746 GNUNET_i2s(&n->peer));
1749 case PEER_STATE_KEY_SENT:
1750 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1751 n->retry_set_key_task
1752 = GNUNET_SCHEDULER_add_delayed (sched,
1753 n->set_key_retry_frequency,
1754 &set_key_retry_task, n);
1756 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1757 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1758 GNUNET_i2s(&n->peer));
1761 case PEER_STATE_KEY_RECEIVED:
1762 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1763 n->retry_set_key_task
1764 = GNUNET_SCHEDULER_add_delayed (sched,
1765 n->set_key_retry_frequency,
1766 &set_key_retry_task, n);
1768 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1769 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1770 GNUNET_i2s(&n->peer));
1773 case PEER_STATE_KEY_CONFIRMED:
1774 /* ready to continue */
1777 discard_expired_messages (n);
1778 if (n->messages == NULL)
1781 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1782 "Plaintext message queue for `%4s' is empty.\n",
1783 GNUNET_i2s(&n->peer));
1785 return; /* no pending messages */
1787 if (n->encrypted_head != NULL)
1790 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1791 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1792 GNUNET_i2s(&n->peer));
1794 return; /* wait for messages already encrypted to be
1797 ph = (struct EncryptedMessage *) pbuf;
1798 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1800 used = sizeof (struct EncryptedMessage);
1801 used += batch_message (n,
1803 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1804 &deadline, &retry_time, &priority);
1805 if (used == sizeof (struct EncryptedMessage))
1808 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1809 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1810 GNUNET_i2s(&n->peer));
1812 /* no messages selected for sending, try again later... */
1813 n->retry_plaintext_task =
1814 GNUNET_SCHEDULER_add_delayed (sched,
1816 &retry_plaintext_processing, n);
1819 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1820 ph->inbound_bpm_limit = htonl (n->bpm_in);
1821 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1823 /* setup encryption message header */
1824 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1825 me->deadline = deadline;
1826 me->priority = priority;
1828 em = (struct EncryptedMessage *) &me[1];
1829 em->header.size = htons (used);
1830 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1831 em->reserved = htonl (0);
1832 esize = used - ENCRYPTED_HEADER_SIZE;
1833 GNUNET_CRYPTO_hash (&ph->sequence_number, esize, &em->plaintext_hash);
1836 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1837 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
1839 GNUNET_i2s(&n->peer),
1840 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
1842 GNUNET_assert (GNUNET_OK ==
1844 &em->plaintext_hash,
1845 &ph->sequence_number,
1846 &em->sequence_number, esize));
1847 /* append to transmission list */
1848 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1852 process_encrypted_neighbour_queue (n);
1857 * Function that recalculates the bandwidth quota for the
1858 * given neighbour and transmits it to the transport service.
1860 * @param cls neighbour for the quota update
1864 neighbour_quota_update (void *cls,
1865 const struct GNUNET_SCHEDULER_TaskContext *tc);
1869 * Schedule the task that will recalculate the bandwidth
1870 * quota for this peer (and possibly force a disconnect of
1871 * idle peers by calculating a bandwidth of zero).
1874 schedule_quota_update (struct Neighbour *n)
1876 GNUNET_assert (n->quota_update_task ==
1877 GNUNET_SCHEDULER_NO_TASK);
1878 n->quota_update_task
1879 = GNUNET_SCHEDULER_add_delayed (sched,
1880 QUOTA_UPDATE_FREQUENCY,
1881 &neighbour_quota_update,
1887 * Initialize a new 'struct Neighbour'.
1889 * @param pid ID of the new neighbour
1890 * @return handle for the new neighbour
1892 static struct Neighbour *
1893 create_neighbour (const struct GNUNET_PeerIdentity *pid)
1895 struct Neighbour *n;
1896 struct GNUNET_TIME_Absolute now;
1898 n = GNUNET_malloc (sizeof (struct Neighbour));
1899 n->next = neighbours;
1903 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
1904 now = GNUNET_TIME_absolute_get ();
1905 n->encrypt_key_created = now;
1906 n->last_activity = now;
1907 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
1908 n->bpm_in = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
1909 n->bpm_out = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
1910 n->bpm_out_internal_limit = (uint32_t) - 1;
1911 n->bpm_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
1912 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1914 schedule_quota_update (n);
1923 * Handle CORE_SEND request.
1926 * @param client the client issuing the request
1927 * @param message the "struct SendMessage"
1930 handle_client_send (void *cls,
1931 struct GNUNET_SERVER_Client *client,
1932 const struct GNUNET_MessageHeader *message)
1934 const struct SendMessage *sm;
1935 const struct GNUNET_MessageHeader *mh;
1936 struct Neighbour *n;
1937 struct MessageEntry *prev;
1938 struct MessageEntry *pos;
1939 struct MessageEntry *e;
1940 struct MessageEntry *min_prio_entry;
1941 struct MessageEntry *min_prio_prev;
1942 unsigned int min_prio;
1943 unsigned int queue_size;
1946 msize = ntohs (message->size);
1948 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
1952 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1955 sm = (const struct SendMessage *) message;
1956 msize -= sizeof (struct SendMessage);
1957 mh = (const struct GNUNET_MessageHeader *) &sm[1];
1958 if (msize != ntohs (mh->size))
1962 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1965 n = find_neighbour (&sm->peer);
1967 n = create_neighbour (&sm->peer);
1969 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1970 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
1973 GNUNET_i2s (&sm->peer));
1975 /* bound queue size */
1976 discard_expired_messages (n);
1977 min_prio = (unsigned int) -1;
1978 min_prio_entry = NULL;
1979 min_prio_prev = NULL;
1985 if (pos->priority < min_prio)
1987 min_prio_entry = pos;
1988 min_prio_prev = prev;
1989 min_prio = pos->priority;
1995 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1998 if (ntohl(sm->priority) <= min_prio)
2000 /* discard new entry */
2002 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2003 "Queue full, discarding new request\n");
2006 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2009 /* discard "min_prio_entry" */
2011 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2012 "Queue full, discarding existing older request\n");
2014 if (min_prio_prev == NULL)
2015 n->messages = min_prio_entry->next;
2017 min_prio_prev->next = min_prio_entry->next;
2018 GNUNET_free (min_prio_entry);
2022 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2023 "Adding transmission request for `%4s' to queue\n",
2024 GNUNET_i2s (&sm->peer));
2026 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2027 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2028 e->priority = ntohl (sm->priority);
2030 memcpy (&e[1], mh, msize);
2032 /* insert, keep list sorted by deadline */
2035 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2046 /* consider scheduling now */
2047 process_plaintext_neighbour_queue (n);
2049 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2054 * Function called when the transport service is ready to
2055 * receive a message. Only resets 'n->th' to NULL.
2057 * @param cls neighbour to use message from
2058 * @param size number of bytes we can transmit
2059 * @param buf where to copy the message
2060 * @return number of bytes transmitted
2063 notify_transport_connect_done (void *cls, size_t size, void *buf)
2065 struct Neighbour *n = cls;
2073 * Handle CORE_REQUEST_CONNECT request.
2076 * @param client the client issuing the request
2077 * @param message the "struct ConnectMessage"
2080 handle_client_request_connect (void *cls,
2081 struct GNUNET_SERVER_Client *client,
2082 const struct GNUNET_MessageHeader *message)
2084 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2085 struct Neighbour *n;
2086 struct GNUNET_TIME_Relative timeout;
2088 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2089 n = find_neighbour (&cm->peer);
2091 n = create_neighbour (&cm->peer);
2092 if ( (n->is_connected) ||
2094 return; /* already connected, or at least trying */
2096 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2097 "Core received `%s' request for `%4s', will try to establish connection\n",
2099 GNUNET_i2s (&cm->peer));
2101 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2102 /* ask transport to connect to the peer */
2103 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2105 sizeof (struct GNUNET_MessageHeader), 0,
2107 ¬ify_transport_connect_done,
2109 GNUNET_break (NULL != n->th);
2114 * List of handlers for the messages understood by this
2117 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2118 {&handle_client_init, NULL,
2119 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2120 {&handle_client_request_info, NULL,
2121 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2122 sizeof (struct RequestInfoMessage)},
2123 {&handle_client_send, NULL,
2124 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2125 {&handle_client_request_connect, NULL,
2126 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2127 sizeof (struct ConnectMessage)},
2133 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2134 * the neighbour's struct and retry send_key. Or, if we did not get a
2135 * HELLO, just do nothing.
2137 * @param cls the 'struct Neighbour' to retry sending the key for
2138 * @param peer the peer for which this is the HELLO
2139 * @param hello HELLO message of that peer
2140 * @param trust amount of trust we currently have in that peer
2143 process_hello_retry_send_key (void *cls,
2144 const struct GNUNET_PeerIdentity *peer,
2145 const struct GNUNET_HELLO_Message *hello,
2148 struct Neighbour *n = cls;
2153 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2154 "Entered `process_hello_retry_send_key' and `peer' is NULL!\n");
2157 if (n->public_key != NULL)
2163 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2164 n->retry_set_key_task
2165 = GNUNET_SCHEDULER_add_delayed (sched,
2166 n->set_key_retry_frequency,
2167 &set_key_retry_task, n);
2173 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2174 "Entered `process_hello_retry_send_key' for peer `%4s'\n",
2177 if (n->public_key != NULL)
2180 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2181 "already have public key for peer %s!! (so why are we here?)\n",
2188 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2189 "Received new `%s' message for `%4s', initiating key exchange.\n",
2194 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2195 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2197 GNUNET_free (n->public_key);
2198 n->public_key = NULL;
2200 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2201 "GNUNET_HELLO_get_key returned awfully\n");
2209 * Send our key (and encrypted PING) to the other peer.
2211 * @param n the other peer
2214 send_key (struct Neighbour *n)
2216 struct SetKeyMessage *sm;
2217 struct MessageEntry *me;
2218 struct PingMessage pp;
2219 struct PingMessage *pm;
2221 if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2225 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2226 "Key exchange in progress with `%4s'.\n",
2227 GNUNET_i2s (&n->peer));
2229 return; /* already in progress */
2233 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2234 "Asked to perform key exchange with `%4s'.\n",
2235 GNUNET_i2s (&n->peer));
2237 if (n->public_key == NULL)
2239 /* lookup n's public key, then try again */
2241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2242 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2243 GNUNET_i2s (&n->peer));
2245 GNUNET_assert (n->pitr == NULL);
2246 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2250 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2251 &process_hello_retry_send_key, n);
2254 /* first, set key message */
2255 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2256 sizeof (struct SetKeyMessage));
2257 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2258 me->priority = SET_KEY_PRIORITY;
2259 me->size = sizeof (struct SetKeyMessage);
2260 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2264 sm = (struct SetKeyMessage *) &me[1];
2265 sm->header.size = htons (sizeof (struct SetKeyMessage));
2266 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2267 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2268 PEER_STATE_KEY_SENT : n->status));
2270 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2271 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2272 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2273 sizeof (struct GNUNET_PeerIdentity));
2274 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2275 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2276 sm->target = n->peer;
2277 GNUNET_assert (GNUNET_OK ==
2278 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2280 GNUNET_CRYPTO_AesSessionKey),
2282 &sm->encrypted_key));
2283 GNUNET_assert (GNUNET_OK ==
2284 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2287 /* second, encrypted PING message */
2288 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2289 sizeof (struct PingMessage));
2290 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2291 me->priority = PING_PRIORITY;
2292 me->size = sizeof (struct PingMessage);
2293 n->encrypted_tail->next = me;
2294 n->encrypted_tail = me;
2295 pm = (struct PingMessage *) &me[1];
2296 pm->header.size = htons (sizeof (struct PingMessage));
2297 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2298 pp.challenge = htonl (n->ping_challenge);
2299 pp.target = n->peer;
2301 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2302 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2303 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2304 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2305 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2307 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2310 &n->peer.hashPubKey,
2313 sizeof (struct PingMessage) -
2314 sizeof (struct GNUNET_MessageHeader));
2318 case PEER_STATE_DOWN:
2319 n->status = PEER_STATE_KEY_SENT;
2321 case PEER_STATE_KEY_SENT:
2323 case PEER_STATE_KEY_RECEIVED:
2325 case PEER_STATE_KEY_CONFIRMED:
2332 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2333 "Have %llu ms left for `%s' transmission.\n",
2334 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2337 /* trigger queue processing */
2338 process_encrypted_neighbour_queue (n);
2339 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2340 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2341 n->retry_set_key_task
2342 = GNUNET_SCHEDULER_add_delayed (sched,
2343 n->set_key_retry_frequency,
2344 &set_key_retry_task, n);
2349 * We received a SET_KEY message. Validate and update
2350 * our key material and status.
2352 * @param n the neighbour from which we received message m
2353 * @param m the set key message we received
2356 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2360 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2361 * the neighbour's struct and retry handling the set_key message. Or,
2362 * if we did not get a HELLO, just free the set key message.
2364 * @param cls pointer to the set key message
2365 * @param peer the peer for which this is the HELLO
2366 * @param hello HELLO message of that peer
2367 * @param trust amount of trust we currently have in that peer
2370 process_hello_retry_handle_set_key (void *cls,
2371 const struct GNUNET_PeerIdentity *peer,
2372 const struct GNUNET_HELLO_Message *hello,
2375 struct Neighbour *n = cls;
2376 struct SetKeyMessage *sm = n->skm;
2385 if (n->public_key != NULL)
2386 return; /* multiple HELLOs match!? */
2388 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2389 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2391 GNUNET_break_op (0);
2392 GNUNET_free (n->public_key);
2393 n->public_key = NULL;
2397 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2398 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2399 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2401 handle_set_key (n, sm);
2406 * We received a PING message. Validate and transmit
2409 * @param n sender of the PING
2410 * @param m the encrypted PING message itself
2413 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2415 struct PingMessage t;
2416 struct PingMessage *tp;
2417 struct MessageEntry *me;
2420 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2421 "Core service receives `%s' request from `%4s'.\n",
2422 "PING", GNUNET_i2s (&n->peer));
2426 &my_identity.hashPubKey,
2429 sizeof (struct PingMessage) -
2430 sizeof (struct GNUNET_MessageHeader)))
2433 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2434 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2436 GNUNET_i2s (&t.target),
2437 ntohl (t.challenge), n->decrypt_key.crc32);
2438 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2439 "Target of `%s' request is `%4s'.\n",
2440 "PING", GNUNET_i2s (&t.target));
2442 if (0 != memcmp (&t.target,
2443 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2445 GNUNET_break_op (0);
2448 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2449 sizeof (struct PingMessage));
2450 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2454 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2455 me->priority = PONG_PRIORITY;
2456 me->size = sizeof (struct PingMessage);
2457 tp = (struct PingMessage *) &me[1];
2458 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2459 tp->header.size = htons (sizeof (struct PingMessage));
2461 &my_identity.hashPubKey,
2464 sizeof (struct PingMessage) -
2465 sizeof (struct GNUNET_MessageHeader));
2467 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2468 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2469 ntohl (t.challenge), n->encrypt_key.crc32);
2471 /* trigger queue processing */
2472 process_encrypted_neighbour_queue (n);
2477 * We received a PONG message. Validate and update our status.
2479 * @param n sender of the PONG
2480 * @param m the encrypted PONG message itself
2483 handle_pong (struct Neighbour *n, const struct PingMessage *m)
2485 struct PingMessage t;
2486 struct ConnectNotifyMessage cnm;
2489 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2490 "Core service receives `%s' request from `%4s'.\n",
2491 "PONG", GNUNET_i2s (&n->peer));
2495 &n->peer.hashPubKey,
2498 sizeof (struct PingMessage) -
2499 sizeof (struct GNUNET_MessageHeader)))
2502 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2503 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2505 GNUNET_i2s (&t.target),
2506 ntohl (t.challenge), n->decrypt_key.crc32);
2508 if ((0 != memcmp (&t.target,
2510 sizeof (struct GNUNET_PeerIdentity))) ||
2511 (n->ping_challenge != ntohl (t.challenge)))
2513 /* PONG malformed */
2515 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2516 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2517 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2518 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2519 "Received malformed `%s' received from `%4s' with challenge %u\n",
2520 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2522 GNUNET_break_op (0);
2527 case PEER_STATE_DOWN:
2528 GNUNET_break (0); /* should be impossible */
2530 case PEER_STATE_KEY_SENT:
2531 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2533 case PEER_STATE_KEY_RECEIVED:
2534 n->status = PEER_STATE_KEY_CONFIRMED;
2536 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2537 "Confirmed key via `%s' message for peer `%4s'\n",
2538 "PONG", GNUNET_i2s (&n->peer));
2540 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2542 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2543 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2545 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2546 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2547 cnm.distance = htonl (n->last_distance);
2548 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2550 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2551 process_encrypted_neighbour_queue (n);
2553 case PEER_STATE_KEY_CONFIRMED:
2554 /* duplicate PONG? */
2564 * We received a SET_KEY message. Validate and update
2565 * our key material and status.
2567 * @param n the neighbour from which we received message m
2568 * @param m the set key message we received
2571 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2573 struct SetKeyMessage *m_cpy;
2574 struct GNUNET_TIME_Absolute t;
2575 struct GNUNET_CRYPTO_AesSessionKey k;
2576 struct PingMessage *ping;
2577 struct PingMessage *pong;
2578 enum PeerStateMachine sender_status;
2581 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2582 "Core service receives `%s' request from `%4s'.\n",
2583 "SET_KEY", GNUNET_i2s (&n->peer));
2585 if (n->public_key == NULL)
2587 if (n->pitr != NULL)
2590 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2591 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2597 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2598 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2600 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2601 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2602 /* lookup n's public key, then try again */
2603 GNUNET_assert (n->skm == NULL);
2605 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2609 GNUNET_TIME_UNIT_MINUTES,
2610 &process_hello_retry_handle_set_key, n);
2613 if (0 != memcmp (&m->target,
2615 sizeof (struct GNUNET_PeerIdentity)))
2617 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2618 _("Received `%s' message that was not for me. Ignoring.\n"),
2622 if ((ntohl (m->purpose.size) !=
2623 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2624 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2625 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2626 sizeof (struct GNUNET_PeerIdentity)) ||
2628 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2629 &m->purpose, &m->signature, n->public_key)))
2631 /* invalid signature */
2632 GNUNET_break_op (0);
2635 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2636 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2637 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2638 (t.value < n->decrypt_key_created.value))
2640 /* this could rarely happen due to massive re-ordering of
2641 messages on the network level, but is most likely either
2642 a bug or some adversary messing with us. Report. */
2643 GNUNET_break_op (0);
2647 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
2649 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2652 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2653 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2654 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2656 /* failed to decrypt !? */
2657 GNUNET_break_op (0);
2662 if (n->decrypt_key_created.value != t.value)
2664 /* fresh key, reset sequence numbers */
2665 n->last_sequence_number_received = 0;
2666 n->last_packets_bitmap = 0;
2667 n->decrypt_key_created = t;
2669 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2672 case PEER_STATE_DOWN:
2673 n->status = PEER_STATE_KEY_RECEIVED;
2675 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2676 "Responding to `%s' with my own key.\n", "SET_KEY");
2680 case PEER_STATE_KEY_SENT:
2681 case PEER_STATE_KEY_RECEIVED:
2682 n->status = PEER_STATE_KEY_RECEIVED;
2683 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2684 (sender_status != PEER_STATE_KEY_CONFIRMED))
2687 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2688 "Responding to `%s' with my own key (other peer has status %u).\n",
2689 "SET_KEY", sender_status);
2694 case PEER_STATE_KEY_CONFIRMED:
2695 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2696 (sender_status != PEER_STATE_KEY_CONFIRMED))
2699 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2700 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2701 "SET_KEY", sender_status);
2710 if (n->pending_ping != NULL)
2712 ping = n->pending_ping;
2713 n->pending_ping = NULL;
2714 handle_ping (n, ping);
2717 if (n->pending_pong != NULL)
2719 pong = n->pending_pong;
2720 n->pending_pong = NULL;
2721 handle_pong (n, pong);
2728 * Send a P2P message to a client.
2730 * @param sender who sent us the message?
2731 * @param client who should we give the message to?
2732 * @param m contains the message to transmit
2733 * @param msize number of bytes in buf to transmit
2736 send_p2p_message_to_client (struct Neighbour *sender,
2737 struct Client *client,
2738 const void *m, size_t msize)
2740 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2741 struct NotifyTrafficMessage *ntm;
2744 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2745 "Core service passes message from `%4s' of type %u to client.\n",
2746 GNUNET_i2s(&sender->peer),
2747 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2749 ntm = (struct NotifyTrafficMessage *) buf;
2750 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2751 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2752 ntm->distance = htonl (sender->last_distance);
2753 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
2754 ntm->peer = sender->peer;
2755 memcpy (&ntm[1], m, msize);
2756 send_to_client (client, &ntm->header, GNUNET_YES);
2761 * Deliver P2P message to interested clients.
2763 * @param sender who sent us the message?
2764 * @param m the message
2765 * @param msize size of the message (including header)
2768 deliver_message (struct Neighbour *sender,
2769 const struct GNUNET_MessageHeader *m, size_t msize)
2771 struct Client *cpos;
2776 type = ntohs (m->type);
2779 "Received encapsulated message of type %u from `%4s'\n",
2781 GNUNET_i2s (&sender->peer));
2784 while (cpos != NULL)
2786 deliver_full = GNUNET_NO;
2787 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
2788 deliver_full = GNUNET_YES;
2791 for (tpos = 0; tpos < cpos->tcnt; tpos++)
2793 if (type != cpos->types[tpos])
2795 deliver_full = GNUNET_YES;
2799 if (GNUNET_YES == deliver_full)
2800 send_p2p_message_to_client (sender, cpos, m, msize);
2801 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2802 send_p2p_message_to_client (sender, cpos, m,
2803 sizeof (struct GNUNET_MessageHeader));
2810 * Align P2P message and then deliver to interested clients.
2812 * @param sender who sent us the message?
2813 * @param buffer unaligned (!) buffer containing message
2814 * @param msize size of the message (including header)
2817 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
2821 /* TODO: call to statistics? */
2822 memcpy (abuf, buffer, msize);
2823 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
2828 * Deliver P2P messages to interested clients.
2830 * @param sender who sent us the message?
2831 * @param buffer buffer containing messages, can be modified
2832 * @param buffer_size size of the buffer (overall)
2833 * @param offset offset where messages in the buffer start
2836 deliver_messages (struct Neighbour *sender,
2837 const char *buffer, size_t buffer_size, size_t offset)
2839 struct GNUNET_MessageHeader *mhp;
2840 struct GNUNET_MessageHeader mh;
2844 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
2846 if (0 != offset % sizeof (uint16_t))
2848 /* outch, need to copy to access header */
2849 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
2854 /* can access header directly */
2855 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
2857 msize = ntohs (mhp->size);
2858 if (msize + offset > buffer_size)
2860 /* malformed message, header says it is larger than what
2861 would fit into the overall buffer */
2862 GNUNET_break_op (0);
2865 #if HAVE_UNALIGNED_64_ACCESS
2866 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
2868 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
2870 if (GNUNET_YES == need_align)
2871 align_and_deliver (sender, &buffer[offset], msize);
2873 deliver_message (sender,
2874 (const struct GNUNET_MessageHeader *)
2875 &buffer[offset], msize);
2882 * We received an encrypted message. Decrypt, validate and
2883 * pass on to the appropriate clients.
2886 handle_encrypted_message (struct Neighbour *n,
2887 const struct EncryptedMessage *m)
2889 size_t size = ntohs (m->header.size);
2891 struct EncryptedMessage *pt; /* plaintext */
2895 struct GNUNET_TIME_Absolute t;
2898 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2899 "Core service receives `%s' request from `%4s'.\n",
2900 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
2906 &m->sequence_number,
2907 &buf[ENCRYPTED_HEADER_SIZE], size - ENCRYPTED_HEADER_SIZE))
2909 pt = (struct EncryptedMessage *) buf;
2912 GNUNET_CRYPTO_hash (&pt->sequence_number,
2913 size - ENCRYPTED_HEADER_SIZE, &ph);
2914 if (0 != memcmp (&ph, &m->plaintext_hash, sizeof (GNUNET_HashCode)))
2916 /* checksum failed */
2917 GNUNET_break_op (0);
2921 /* validate sequence number */
2922 snum = ntohl (pt->sequence_number);
2923 if (n->last_sequence_number_received == snum)
2925 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2926 "Received duplicate message, ignoring.\n");
2927 /* duplicate, ignore */
2930 if ((n->last_sequence_number_received > snum) &&
2931 (n->last_sequence_number_received - snum > 32))
2933 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2934 "Received ancient out of sequence message, ignoring.\n");
2935 /* ancient out of sequence, ignore */
2938 if (n->last_sequence_number_received > snum)
2940 unsigned int rotbit =
2941 1 << (n->last_sequence_number_received - snum - 1);
2942 if ((n->last_packets_bitmap & rotbit) != 0)
2944 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2945 "Received duplicate message, ignoring.\n");
2946 /* duplicate, ignore */
2949 n->last_packets_bitmap |= rotbit;
2951 if (n->last_sequence_number_received < snum)
2953 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
2954 n->last_sequence_number_received = snum;
2957 /* check timestamp */
2958 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
2959 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
2961 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2963 ("Message received far too old (%llu ms). Content ignored.\n"),
2964 GNUNET_TIME_absolute_get_duration (t).value);
2968 /* process decrypted message(s) */
2969 update_window (GNUNET_YES,
2970 &n->available_send_window,
2971 &n->last_asw_update,
2973 n->bpm_out_external_limit = ntohl (pt->inbound_bpm_limit);
2974 n->bpm_out = GNUNET_MAX (n->bpm_out_external_limit,
2975 n->bpm_out_internal_limit);
2976 n->last_activity = GNUNET_TIME_absolute_get ();
2977 off = sizeof (struct EncryptedMessage);
2978 deliver_messages (n, buf, size, off);
2983 * Function called by the transport for each received message.
2985 * @param cls closure
2986 * @param peer (claimed) identity of the other peer
2987 * @param message the message
2988 * @param latency estimated latency for communicating with the
2989 * given peer (round-trip)
2990 * @param distance in overlay hops, as given by transport plugin
2993 handle_transport_receive (void *cls,
2994 const struct GNUNET_PeerIdentity *peer,
2995 const struct GNUNET_MessageHeader *message,
2996 struct GNUNET_TIME_Relative latency,
2997 unsigned int distance)
2999 struct Neighbour *n;
3000 struct GNUNET_TIME_Absolute now;
3006 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3007 "Received message of type %u from `%4s', demultiplexing.\n",
3008 ntohs (message->type), GNUNET_i2s (peer));
3010 n = find_neighbour (peer);
3012 n = create_neighbour (peer);
3015 n->last_latency = latency;
3016 n->last_distance = distance;
3017 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3018 type = ntohs (message->type);
3019 size = ntohs (message->size);
3022 "Received message of type %u from `%4s'\n",
3028 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3029 if (size != sizeof (struct SetKeyMessage))
3031 GNUNET_break_op (0);
3034 handle_set_key (n, (const struct SetKeyMessage *) message);
3036 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3037 if (size < sizeof (struct EncryptedMessage) +
3038 sizeof (struct GNUNET_MessageHeader))
3040 GNUNET_break_op (0);
3043 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3044 (n->status != PEER_STATE_KEY_CONFIRMED))
3046 GNUNET_break_op (0);
3049 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3051 case GNUNET_MESSAGE_TYPE_CORE_PING:
3052 if (size != sizeof (struct PingMessage))
3054 GNUNET_break_op (0);
3057 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3058 (n->status != PEER_STATE_KEY_CONFIRMED))
3061 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3062 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3063 "PING", GNUNET_i2s (&n->peer));
3065 GNUNET_free_non_null (n->pending_ping);
3066 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3067 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3070 handle_ping (n, (const struct PingMessage *) message);
3072 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3073 if (size != sizeof (struct PingMessage))
3075 GNUNET_break_op (0);
3078 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3079 (n->status != PEER_STATE_KEY_CONFIRMED) )
3082 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3083 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3084 "PONG", GNUNET_i2s (&n->peer));
3086 GNUNET_free_non_null (n->pending_pong);
3087 n->pending_pong = GNUNET_malloc (sizeof (struct PingMessage));
3088 memcpy (n->pending_pong, message, sizeof (struct PingMessage));
3091 handle_pong (n, (const struct PingMessage *) message);
3094 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3095 _("Unsupported message of type %u received.\n"), type);
3098 if (n->status == PEER_STATE_KEY_CONFIRMED)
3100 now = GNUNET_TIME_absolute_get ();
3101 n->last_activity = now;
3103 n->time_established = now;
3109 * Function that recalculates the bandwidth quota for the
3110 * given neighbour and transmits it to the transport service.
3112 * @param cls neighbour for the quota update
3116 neighbour_quota_update (void *cls,
3117 const struct GNUNET_SCHEDULER_TaskContext *tc)
3119 struct Neighbour *n = cls;
3123 unsigned long long distributable;
3125 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3126 /* calculate relative preference among all neighbours;
3127 divides by a bit more to avoid division by zero AND to
3128 account for possibility of new neighbours joining any time
3129 AND to convert to double... */
3130 pref_rel = n->current_preference / (1.0 + preference_sum);
3132 if (bandwidth_target_out > neighbour_count * MIN_BPM_PER_PEER)
3133 distributable = bandwidth_target_out - neighbour_count * MIN_BPM_PER_PEER;
3134 share = distributable * pref_rel;
3135 q_in = MIN_BPM_PER_PEER + (unsigned long long) share;
3136 /* check if we want to disconnect for good due to inactivity */
3137 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3138 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3141 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3142 "Forcing disconnect of `%4s' due to inactivity (?).\n",
3143 GNUNET_i2s (&n->peer));
3145 q_in = 0; /* force disconnect */
3147 if ( (n->bpm_in + MIN_BPM_CHANGE < q_in) ||
3148 (n->bpm_in - MIN_BPM_CHANGE > q_in) )
3151 GNUNET_TRANSPORT_set_quota (transport,
3155 GNUNET_TIME_UNIT_FOREVER_REL,
3158 schedule_quota_update (n);
3163 * Function called by transport to notify us that
3164 * a peer connected to us (on the network level).
3166 * @param cls closure
3167 * @param peer the peer that connected
3168 * @param latency current latency of the connection
3169 * @param distance in overlay hops, as given by transport plugin
3172 handle_transport_notify_connect (void *cls,
3173 const struct GNUNET_PeerIdentity *peer,
3174 struct GNUNET_TIME_Relative latency,
3175 unsigned int distance)
3177 struct Neighbour *n;
3178 struct GNUNET_TIME_Absolute now;
3179 struct ConnectNotifyMessage cnm;
3181 n = find_neighbour (peer);
3184 if (n->is_connected)
3186 /* duplicate connect notification!? */
3193 n = create_neighbour (peer);
3195 now = GNUNET_TIME_absolute_get ();
3196 n->is_connected = GNUNET_YES;
3197 n->last_latency = latency;
3198 n->last_distance = distance;
3199 n->last_asw_update = now;
3200 n->last_arw_update = now;
3202 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3203 "Received connection from `%4s'.\n",
3204 GNUNET_i2s (&n->peer));
3206 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3207 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3208 cnm.distance = htonl (n->last_distance);
3209 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3211 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3217 * Function called by transport telling us that a peer
3220 * @param cls closure
3221 * @param peer the peer that disconnected
3224 handle_transport_notify_disconnect (void *cls,
3225 const struct GNUNET_PeerIdentity *peer)
3227 struct DisconnectNotifyMessage cnm;
3228 struct Neighbour *n;
3231 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3232 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3234 n = find_neighbour (peer);
3240 GNUNET_break (n->is_connected);
3241 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3242 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3244 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3245 n->is_connected = GNUNET_NO;
3250 * Last task run during shutdown. Disconnects us from
3254 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3256 struct Neighbour *n;
3260 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3261 "Core service shutting down.\n");
3263 GNUNET_assert (transport != NULL);
3264 GNUNET_TRANSPORT_disconnect (transport);
3266 while (NULL != (n = neighbours))
3268 neighbours = n->next;
3269 GNUNET_assert (neighbour_count > 0);
3273 GNUNET_SERVER_notification_context_destroy (notifier);
3275 while (NULL != (c = clients))
3276 handle_client_disconnect (NULL, c->client_handle);
3277 if (my_private_key != NULL)
3278 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3283 * Initiate core service.
3285 * @param cls closure
3286 * @param s scheduler to use
3287 * @param serv the initialized server
3288 * @param c configuration to use
3292 struct GNUNET_SCHEDULER_Handle *s,
3293 struct GNUNET_SERVER_Handle *serv,
3294 const struct GNUNET_CONFIGURATION_Handle *c)
3297 unsigned long long qin;
3298 unsigned long long qout;
3299 unsigned long long tneigh;
3305 /* parse configuration */
3308 GNUNET_CONFIGURATION_get_value_number (c,
3311 &bandwidth_target_in)) ||
3313 GNUNET_CONFIGURATION_get_value_number (c,
3316 &bandwidth_target_out)) ||
3318 GNUNET_CONFIGURATION_get_value_filename (c,
3320 "HOSTKEY", &keyfile)))
3322 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3324 ("Core service is lacking key configuration settings. Exiting.\n"));
3325 GNUNET_SCHEDULER_shutdown (s);
3328 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3329 GNUNET_free (keyfile);
3330 if (my_private_key == NULL)
3332 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3333 _("Core service could not access hostkey. Exiting.\n"));
3334 GNUNET_SCHEDULER_shutdown (s);
3337 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3338 GNUNET_CRYPTO_hash (&my_public_key,
3339 sizeof (my_public_key), &my_identity.hashPubKey);
3340 /* setup notification */
3342 notifier = GNUNET_SERVER_notification_context_create (server,
3344 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3345 /* setup transport connection */
3346 transport = GNUNET_TRANSPORT_connect (sched,
3349 &handle_transport_receive,
3350 &handle_transport_notify_connect,
3351 &handle_transport_notify_disconnect);
3352 GNUNET_assert (NULL != transport);
3353 GNUNET_SCHEDULER_add_delayed (sched,
3354 GNUNET_TIME_UNIT_FOREVER_REL,
3355 &cleaning_task, NULL);
3356 /* process client requests */
3357 GNUNET_SERVER_add_handlers (server, handlers);
3358 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3359 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3365 * The main function for the transport service.
3367 * @param argc number of arguments from the command line
3368 * @param argv command line arguments
3369 * @return 0 ok, 1 on error
3372 main (int argc, char *const *argv)
3374 return (GNUNET_OK ==
3375 GNUNET_SERVICE_run (argc,
3378 GNUNET_SERVICE_OPTION_NONE,
3379 &run, NULL)) ? 0 : 1;
3382 /* end of gnunet-service-core.c */