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
27 * - not all GNUNET_CORE_OPTION_SEND_* flags are fully supported yet
28 * (i.e. no SEND_XXX_OUTBOUND).
29 * - 'REQUEST_DISCONNECT' is not implemented (transport API is lacking!)
31 * Considerations for later:
32 * - check that hostkey used by transport (for HELLOs) is the
33 * same as the hostkey that we are using!
34 * - add code to send PINGs if we are about to time-out otherwise
35 * - optimize lookup (many O(n) list traversals
36 * could ideally be changed to O(1) hash map lookups)
39 #include "gnunet_constants.h"
40 #include "gnunet_util_lib.h"
41 #include "gnunet_hello_lib.h"
42 #include "gnunet_peerinfo_service.h"
43 #include "gnunet_protocols.h"
44 #include "gnunet_signatures.h"
45 #include "gnunet_transport_service.h"
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 ms).
54 #define MAX_WINDOW_TIME (5 * 60 * 1000)
57 * Minimum of bytes per minute (out) to assign to any connected peer.
58 * Should be rather low; values larger than DEFAULT_BPM_IN_OUT make no
61 #define MIN_BPM_PER_PEER GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT
64 * What is the smallest change (in number of bytes per minute)
65 * that we consider significant enough to bother triggering?
67 #define MIN_BPM_CHANGE 32
70 * After how much time past the "official" expiration time do
71 * we discard messages? Should not be zero since we may
72 * intentionally defer transmission until close to the deadline
73 * and then may be slightly past the deadline due to inaccuracy
74 * in sleep and our own CPU consumption.
76 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
79 * What is the maximum delay for a SET_KEY message?
81 #define MAX_SET_KEY_DELAY GNUNET_TIME_UNIT_SECONDS
84 * What how long do we wait for SET_KEY confirmation initially?
86 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3)
89 * What is the maximum delay for a PING message?
91 #define MAX_PING_DELAY GNUNET_TIME_UNIT_SECONDS
94 * What is the maximum delay for a PONG message?
96 #define MAX_PONG_DELAY GNUNET_TIME_UNIT_SECONDS
99 * How often do we recalculate bandwidth quotas?
101 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_UNIT_SECONDS
104 * What is the priority for a SET_KEY message?
106 #define SET_KEY_PRIORITY 0xFFFFFF
109 * What is the priority for a PING message?
111 #define PING_PRIORITY 0xFFFFFF
114 * What is the priority for a PONG message?
116 #define PONG_PRIORITY 0xFFFFFF
119 * How many messages do we queue per peer at most?
121 #define MAX_PEER_QUEUE_SIZE 16
124 * How many non-mandatory messages do we queue per client at most?
126 #define MAX_CLIENT_QUEUE_SIZE 32
129 * What is the maximum age of a message for us to consider
130 * processing it? Note that this looks at the timestamp used
131 * by the other peer, so clock skew between machines does
132 * come into play here. So this should be picked high enough
133 * so that a little bit of clock skew does not prevent peers
134 * from connecting to us.
136 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
139 * What is the maximum size for encrypted messages? Note that this
140 * number imposes a clear limit on the maximum size of any message.
141 * Set to a value close to 64k but not so close that transports will
142 * have trouble with their headers.
144 #define MAX_ENCRYPTED_MESSAGE_SIZE (63 * 1024)
148 * State machine for our P2P encryption handshake. Everyone starts in
149 * "DOWN", if we receive the other peer's key (other peer initiated)
150 * we start in state RECEIVED (since we will immediately send our
151 * own); otherwise we start in SENT. If we get back a PONG from
152 * within either state, we move up to CONFIRMED (the PONG will always
153 * be sent back encrypted with the key we sent to the other peer).
155 enum PeerStateMachine
159 PEER_STATE_KEY_RECEIVED,
160 PEER_STATE_KEY_CONFIRMED
165 * Number of bytes (at the beginning) of "struct EncryptedMessage"
166 * that are NOT encrypted.
168 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t) + sizeof(GNUNET_HashCode))
172 * Encapsulation for encrypted messages exchanged between
173 * peers. Followed by the actual encrypted data.
175 struct EncryptedMessage
178 * Message type is either CORE_ENCRYPTED_MESSAGE.
180 struct GNUNET_MessageHeader header;
185 uint32_t reserved GNUNET_PACKED;
188 * Hash of the plaintext, used to verify message integrity;
189 * ALSO used as the IV for the symmetric cipher! Everything
190 * after this hash will be encrypted. ENCRYPTED_HEADER_SIZE
191 * must be set to the offset of the next field.
193 GNUNET_HashCode plaintext_hash;
196 * Sequence number, in network byte order. This field
197 * must be the first encrypted/decrypted field and the
198 * first byte that is hashed for the plaintext hash.
200 uint32_t sequence_number GNUNET_PACKED;
203 * Desired bandwidth (how much we should send to this
204 * peer / how much is the sender willing to receive),
205 * in bytes per minute.
207 uint32_t inbound_bpm_limit GNUNET_PACKED;
210 * Timestamp. Used to prevent reply of ancient messages
211 * (recent messages are caught with the sequence number).
213 struct GNUNET_TIME_AbsoluteNBO timestamp;
218 * We're sending an (encrypted) PING to the other peer to check if he
219 * can decrypt. The other peer should respond with a PONG with the
220 * same content, except this time encrypted with the receiver's key.
225 * Message type is either CORE_PING or CORE_PONG.
227 struct GNUNET_MessageHeader header;
230 * Random number chosen to make reply harder.
232 uint32_t challenge GNUNET_PACKED;
235 * Intended target of the PING, used primarily to check
236 * that decryption actually worked.
238 struct GNUNET_PeerIdentity target;
243 * Message transmitted to set (or update) a session key.
249 * Message type is either CORE_SET_KEY.
251 struct GNUNET_MessageHeader header;
254 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
256 int32_t sender_status GNUNET_PACKED;
259 * Purpose of the signature, will be
260 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
262 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
265 * At what time was this key created?
267 struct GNUNET_TIME_AbsoluteNBO creation_time;
270 * The encrypted session key.
272 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
275 * Who is the intended recipient?
277 struct GNUNET_PeerIdentity target;
280 * Signature of the stuff above (starting at purpose).
282 struct GNUNET_CRYPTO_RsaSignature signature;
288 * Message waiting for transmission. This struct
289 * is followed by the actual content of the message.
295 * We keep messages in a linked list (for now).
297 struct MessageEntry *next;
300 * By when are we supposed to transmit this message?
302 struct GNUNET_TIME_Absolute deadline;
305 * How important is this message to us?
307 unsigned int priority;
310 * How long is the message? (number of bytes following
311 * the "struct MessageEntry", but not including the
312 * size of "struct MessageEntry" itself!)
317 * Was this message selected for transmission in the
318 * current round? GNUNET_YES or GNUNET_NO.
328 * We keep neighbours in a linked list (for now).
330 struct Neighbour *next;
333 * Unencrypted messages destined for this peer.
335 struct MessageEntry *messages;
338 * Head of the batched, encrypted message queue (already ordered,
339 * transmit starting with the head).
341 struct MessageEntry *encrypted_head;
344 * Tail of the batched, encrypted message queue (already ordered,
345 * append new messages to tail)
347 struct MessageEntry *encrypted_tail;
350 * Handle for pending requests for transmission to this peer
351 * with the transport service. NULL if no request is pending.
353 struct GNUNET_TRANSPORT_TransmitHandle *th;
356 * Public key of the neighbour, NULL if we don't have it yet.
358 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
361 * We received a PING message before we got the "public_key"
362 * (or the SET_KEY). We keep it here until we have a key
363 * to decrypt it. NULL if no PING is pending.
365 struct PingMessage *pending_ping;
368 * Non-NULL if we are currently looking up HELLOs for this peer.
371 struct GNUNET_PEERINFO_IteratorContext *pitr;
374 * SetKeyMessage to transmit, NULL if we are not currently trying
377 struct SetKeyMessage *skm;
380 * Identity of the neighbour.
382 struct GNUNET_PeerIdentity peer;
385 * Key we use to encrypt our messages for the other peer
386 * (initialized by us when we do the handshake).
388 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
391 * Key we use to decrypt messages from the other peer
392 * (given to us by the other peer during the handshake).
394 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
397 * ID of task used for re-trying plaintext scheduling.
399 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
402 * ID of task used for re-trying SET_KEY and PING message.
404 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
407 * ID of task used for updating bandwidth quota for this neighbour.
409 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
412 * At what time did we generate our encryption key?
414 struct GNUNET_TIME_Absolute encrypt_key_created;
417 * At what time did the other peer generate the decryption key?
419 struct GNUNET_TIME_Absolute decrypt_key_created;
422 * At what time did we initially establish (as in, complete session
423 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
425 struct GNUNET_TIME_Absolute time_established;
428 * At what time did we last receive an encrypted message from the
429 * other peer? Should be zero if status != KEY_CONFIRMED.
431 struct GNUNET_TIME_Absolute last_activity;
434 * Last latency observed from this peer.
436 struct GNUNET_TIME_Relative last_latency;
439 * At what frequency are we currently re-trying SET_KEY messages?
441 struct GNUNET_TIME_Relative set_key_retry_frequency;
444 * Time of our last update to the "available_send_window".
446 struct GNUNET_TIME_Absolute last_asw_update;
449 * Time of our last update to the "available_recv_window".
451 struct GNUNET_TIME_Absolute last_arw_update;
454 * Number of bytes that we are eligible to transmit to this
455 * peer at this point. Incremented every minute by max_out_bpm,
456 * bounded by max_bpm (no back-log larger than MAX_BUF_FACT minutes,
457 * bandwidth-hogs are sampled at a frequency of about 78s!);
458 * may get negative if we have VERY high priority content.
460 long long available_send_window;
463 * How much downstream capacity of this peer has been reserved for
464 * our traffic? (Our clients can request that a certain amount of
465 * bandwidth is available for replies to them; this value is used to
466 * make sure that this reserved amount of bandwidth is actually
469 long long available_recv_window;
472 * How valueable were the messages of this peer recently?
474 unsigned long long current_preference;
477 * Bit map indicating which of the 32 sequence numbers before the last
478 * were received (good for accepting out-of-order packets and
479 * estimating reliability of the connection)
481 unsigned int last_packets_bitmap;
484 * Number of messages in the message queue for this peer.
486 unsigned int message_queue_size;
489 * last sequence number received on this connection (highest)
491 uint32_t last_sequence_number_received;
494 * last sequence number transmitted
496 uint32_t last_sequence_number_sent;
499 * Available bandwidth in for this peer (current target).
504 * Available bandwidth out for this peer (current target).
509 * Internal bandwidth limit set for this peer (initially
510 * typically set to "-1"). "bpm_out" is MAX of
511 * "bpm_out_internal_limit" and "bpm_out_external_limit".
513 uint32_t bpm_out_internal_limit;
516 * External bandwidth limit set for this peer by the
517 * peer that we are communicating with. "bpm_out" is MAX of
518 * "bpm_out_internal_limit" and "bpm_out_external_limit".
520 uint32_t bpm_out_external_limit;
523 * What was our PING challenge number (for this peer)?
525 uint32_t ping_challenge;
528 * What was the last distance to this peer as reported by the transports?
529 * (FIXME: actually set this!)
531 uint32_t last_distance;
534 * What is our connection status?
536 enum PeerStateMachine status;
542 * Data structure for each client connected to the core service.
547 * Clients are kept in a linked list.
552 * Handle for the client with the server API.
554 struct GNUNET_SERVER_Client *client_handle;
557 * Array of the types of messages this peer cares
558 * about (with "tcnt" entries). Allocated as part
559 * of this client struct, do not free!
564 * Options for messages this client cares about,
565 * see GNUNET_CORE_OPTION_ values.
570 * Number of types of incoming messages this client
571 * specifically cares about. Size of the "types" array.
581 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
586 static struct GNUNET_PeerIdentity my_identity;
591 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
596 struct GNUNET_SCHEDULER_Handle *sched;
601 const struct GNUNET_CONFIGURATION_Handle *cfg;
606 static struct GNUNET_SERVER_Handle *server;
611 static struct GNUNET_TRANSPORT_Handle *transport;
614 * Linked list of our clients.
616 static struct Client *clients;
619 * Context for notifications we need to send to our clients.
621 static struct GNUNET_SERVER_NotificationContext *notifier;
624 * We keep neighbours in a linked list (for now).
626 static struct Neighbour *neighbours;
629 * Sum of all preferences among all neighbours.
631 static unsigned long long preference_sum;
634 * Total number of neighbours we have.
636 static unsigned int neighbour_count;
639 * How much inbound bandwidth are we supposed to be using?
641 static unsigned long long bandwidth_target_in;
644 * How much outbound bandwidth are we supposed to be using?
646 static unsigned long long bandwidth_target_out;
651 * A preference value for a neighbour was update. Update
652 * the preference sum accordingly.
654 * @param inc how much was a preference value increased?
657 update_preference_sum (unsigned long long inc)
660 unsigned long long os;
663 preference_sum += inc;
664 if (preference_sum >= os)
666 /* overflow! compensate by cutting all values in half! */
671 n->current_preference /= 2;
672 preference_sum += n->current_preference;
679 * Recalculate the number of bytes we expect to
680 * receive or transmit in a given window.
682 * @param force force an update now (even if not much time has passed)
683 * @param window pointer to the byte counter (updated)
684 * @param ts pointer to the timestamp (updated)
685 * @param bpm number of bytes per minute that should
686 * be added to the window.
689 update_window (int force,
691 struct GNUNET_TIME_Absolute *ts, unsigned int bpm)
693 struct GNUNET_TIME_Relative since;
695 since = GNUNET_TIME_absolute_get_duration (*ts);
696 if ( (force == GNUNET_NO) &&
697 (since.value < 60 * 1000) )
698 return; /* not even a minute has passed */
699 *ts = GNUNET_TIME_absolute_get ();
700 *window += (bpm * since.value) / 60 / 1000;
701 if (*window > MAX_WINDOW_TIME * bpm)
702 *window = MAX_WINDOW_TIME * bpm;
707 * Find the entry for the given neighbour.
709 * @param peer identity of the neighbour
710 * @return NULL if we are not connected, otherwise the
713 static struct Neighbour *
714 find_neighbour (const struct GNUNET_PeerIdentity *peer)
716 struct Neighbour *ret;
719 while ((ret != NULL) &&
720 (0 != memcmp (&ret->peer,
721 peer, sizeof (struct GNUNET_PeerIdentity))))
728 * Send a message to one of our clients.
730 * @param client target for the message
731 * @param msg message to transmit
732 * @param can_drop could this message be dropped if the
733 * client's queue is getting too large?
736 send_to_client (struct Client *client,
737 const struct GNUNET_MessageHeader *msg,
740 #if DEBUG_CORE_CLIENT
741 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
742 "Preparing to send message of type %u to client.\n",
745 GNUNET_SERVER_notification_context_unicast (notifier,
746 client->client_handle,
753 * Send a message to all of our current clients that have
754 * the right options set.
756 * @param msg message to multicast
757 * @param can_drop can this message be discarded if the queue is too long
758 * @param options mask to use
761 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
770 if (0 != (c->options & options))
771 send_to_client (c, msg, can_drop);
778 * Handle CORE_INIT request.
781 handle_client_init (void *cls,
782 struct GNUNET_SERVER_Client *client,
783 const struct GNUNET_MessageHeader *message)
785 const struct InitMessage *im;
786 struct InitReplyMessage irm;
789 const uint16_t *types;
791 struct ConnectNotifyMessage cnm;
793 #if DEBUG_CORE_CLIENT
794 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
795 "Client connecting to core service with `%s' message\n",
798 /* check that we don't have an entry already */
802 if (client == c->client_handle)
805 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
810 msize = ntohs (message->size);
811 if (msize < sizeof (struct InitMessage))
814 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
817 GNUNET_SERVER_notification_context_add (notifier, client);
818 im = (const struct InitMessage *) message;
819 types = (const uint16_t *) &im[1];
820 msize -= sizeof (struct InitMessage);
821 c = GNUNET_malloc (sizeof (struct Client) + msize);
822 c->client_handle = client;
825 memcpy (&c[1], types, msize);
826 c->types = (uint16_t *) & c[1];
827 c->options = ntohl (im->options);
828 c->tcnt = msize / sizeof (uint16_t);
829 /* send init reply message */
830 irm.header.size = htons (sizeof (struct InitReplyMessage));
831 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
832 irm.reserved = htonl (0);
833 memcpy (&irm.publicKey,
835 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
836 #if DEBUG_CORE_CLIENT
837 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
838 "Sending `%s' message to client.\n", "INIT_REPLY");
840 send_to_client (c, &irm.header, GNUNET_NO);
841 /* notify new client about existing neighbours */
842 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
843 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
847 #if DEBUG_CORE_CLIENT
848 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
849 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
851 cnm.distance = htonl (n->last_distance);
852 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
854 send_to_client (c, &cnm.header, GNUNET_NO);
861 * A client disconnected, clean up.
864 * @param client identification of the client
867 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
874 #if DEBUG_CORE_CLIENT
875 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
876 "Client has disconnected from core service.\n");
882 if (client == pos->client_handle)
887 prev->next = pos->next;
894 /* client never sent INIT */
899 * Handle REQUEST_INFO request.
902 handle_client_request_info (void *cls,
903 struct GNUNET_SERVER_Client *client,
904 const struct GNUNET_MessageHeader *message)
906 const struct RequestInfoMessage *rcm;
908 struct ConfigurationInfoMessage cim;
910 unsigned long long old_preference;
911 struct GNUNET_SERVER_TransmitContext *tc;
913 #if DEBUG_CORE_CLIENT
914 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
915 "Core service receives `%s' request.\n", "REQUEST_INFO");
917 rcm = (const struct RequestInfoMessage *) message;
918 n = find_neighbour (&rcm->peer);
919 memset (&cim, 0, sizeof (cim));
920 if ((n != NULL) && (n->status == PEER_STATE_KEY_CONFIRMED))
922 update_window (GNUNET_YES,
923 &n->available_send_window,
926 n->bpm_out_internal_limit = ntohl (rcm->limit_outbound_bpm);
927 n->bpm_out = GNUNET_MAX (n->bpm_out_internal_limit,
928 n->bpm_out_external_limit);
929 reserv = ntohl (rcm->reserve_inbound);
932 n->available_recv_window += reserv;
936 update_window (GNUNET_NO,
937 &n->available_recv_window,
938 &n->last_arw_update, n->bpm_in);
939 if (n->available_recv_window < reserv)
940 reserv = n->available_recv_window;
941 n->available_recv_window -= reserv;
943 old_preference = n->current_preference;
944 n->current_preference += GNUNET_ntohll(rcm->preference_change);
945 if (old_preference > n->current_preference)
947 /* overflow; cap at maximum value */
948 n->current_preference = (unsigned long long) -1;
950 update_preference_sum (n->current_preference - old_preference);
951 cim.reserved_amount = htonl (reserv);
952 cim.bpm_in = htonl (n->bpm_in);
953 cim.bpm_out = htonl (n->bpm_out);
954 cim.preference = n->current_preference;
956 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
957 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
958 cim.peer = rcm->peer;
960 #if DEBUG_CORE_CLIENT
961 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
962 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
964 tc = GNUNET_SERVER_transmit_context_create (client);
965 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
966 GNUNET_SERVER_transmit_context_run (tc,
967 GNUNET_TIME_UNIT_FOREVER_REL);
972 * Check if we have encrypted messages for the specified neighbour
973 * pending, and if so, check with the transport about sending them
976 * @param n neighbour to check.
978 static void process_encrypted_neighbour_queue (struct Neighbour *n);
982 * Function called when the transport service is ready to
983 * receive an encrypted message for the respective peer
985 * @param cls neighbour to use message from
986 * @param size number of bytes we can transmit
987 * @param buf where to copy the message
988 * @return number of bytes transmitted
991 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
993 struct Neighbour *n = cls;
994 struct MessageEntry *m;
999 GNUNET_assert (NULL != (m = n->encrypted_head));
1000 n->encrypted_head = m->next;
1001 if (m->next == NULL)
1002 n->encrypted_tail = NULL;
1007 GNUNET_assert (size >= m->size);
1008 memcpy (cbuf, &m[1], m->size);
1010 n->available_send_window -= m->size;
1011 process_encrypted_neighbour_queue (n);
1013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1014 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1015 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1016 ret, GNUNET_i2s (&n->peer));
1021 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1022 "Transmission for message of type %u and size %u failed\n",
1023 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1032 * Check if we have plaintext messages for the specified neighbour
1033 * pending, and if so, consider batching and encrypting them (and
1034 * then trigger processing of the encrypted queue if needed).
1036 * @param n neighbour to check.
1038 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1042 * Check if we have encrypted messages for the specified neighbour
1043 * pending, and if so, check with the transport about sending them
1046 * @param n neighbour to check.
1049 process_encrypted_neighbour_queue (struct Neighbour *n)
1051 struct MessageEntry *m;
1054 return; /* request already pending */
1055 if (n->encrypted_head == NULL)
1057 /* encrypted queue empty, try plaintext instead */
1058 process_plaintext_neighbour_queue (n);
1062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1063 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1064 n->encrypted_head->size,
1065 GNUNET_i2s (&n->peer),
1066 GNUNET_TIME_absolute_get_remaining (n->
1067 encrypted_head->deadline).
1071 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1072 n->encrypted_head->size,
1073 n->encrypted_head->priority,
1074 GNUNET_TIME_absolute_get_remaining
1075 (n->encrypted_head->deadline),
1076 ¬ify_encrypted_transmit_ready,
1080 /* message request too large (oops) */
1082 /* discard encrypted message */
1083 GNUNET_assert (NULL != (m = n->encrypted_head));
1084 n->encrypted_head = m->next;
1085 if (m->next == NULL)
1086 n->encrypted_tail = NULL;
1088 process_encrypted_neighbour_queue (n);
1094 * Decrypt size bytes from in and write the result to out. Use the
1095 * key for inbound traffic of the given neighbour. This function does
1096 * NOT do any integrity-checks on the result.
1098 * @param n neighbour we are receiving from
1099 * @param iv initialization vector to use
1100 * @param in ciphertext
1101 * @param out plaintext
1102 * @param size size of in/out
1103 * @return GNUNET_OK on success
1106 do_decrypt (struct Neighbour *n,
1107 const GNUNET_HashCode * iv,
1108 const void *in, void *out, size_t size)
1110 if (size != (uint16_t) size)
1115 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1116 (n->status != PEER_STATE_KEY_CONFIRMED))
1118 GNUNET_break_op (0);
1119 return GNUNET_SYSERR;
1122 GNUNET_CRYPTO_aes_decrypt (in,
1126 GNUNET_CRYPTO_AesInitializationVector *) iv,
1130 return GNUNET_SYSERR;
1133 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1134 "Decrypted %u bytes from `%4s' using key %u\n",
1135 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1142 * Encrypt size bytes from in and write the result to out. Use the
1143 * key for outbound traffic of the given neighbour.
1145 * @param n neighbour we are sending to
1146 * @param iv initialization vector to use
1147 * @param in ciphertext
1148 * @param out plaintext
1149 * @param size size of in/out
1150 * @return GNUNET_OK on success
1153 do_encrypt (struct Neighbour *n,
1154 const GNUNET_HashCode * iv,
1155 const void *in, void *out, size_t size)
1157 if (size != (uint16_t) size)
1162 GNUNET_assert (size ==
1163 GNUNET_CRYPTO_aes_encrypt (in,
1167 GNUNET_CRYPTO_AesInitializationVector
1170 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1171 "Encrypted %u bytes for `%4s' using key %u\n", size,
1172 GNUNET_i2s (&n->peer), n->encrypt_key.crc32);
1179 * Select messages for transmission. This heuristic uses a combination
1180 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1181 * and priority-based discard (in case no feasible schedule exist) and
1182 * speculative optimization (defer any kind of transmission until
1183 * we either create a batch of significant size, 25% of max, or until
1184 * we are close to a deadline). Furthermore, when scheduling the
1185 * heuristic also packs as many messages into the batch as possible,
1186 * starting with those with the earliest deadline. Yes, this is fun.
1188 * @param n neighbour to select messages from
1189 * @param size number of bytes to select for transmission
1190 * @param retry_time set to the time when we should try again
1191 * (only valid if this function returns zero)
1192 * @return number of bytes selected, or 0 if we decided to
1193 * defer scheduling overall; in that case, retry_time is set.
1196 select_messages (struct Neighbour *n,
1197 size_t size, struct GNUNET_TIME_Relative *retry_time)
1199 struct MessageEntry *pos;
1200 struct MessageEntry *min;
1201 struct MessageEntry *last;
1202 unsigned int min_prio;
1203 struct GNUNET_TIME_Absolute t;
1204 struct GNUNET_TIME_Absolute now;
1207 unsigned long long slack; /* how long could we wait before missing deadlines? */
1209 int discard_low_prio;
1211 GNUNET_assert (NULL != n->messages);
1212 now = GNUNET_TIME_absolute_get ();
1213 /* last entry in linked list of messages processed */
1215 /* should we remove the entry with the lowest
1216 priority from consideration for scheduling at the
1218 discard_low_prio = GNUNET_YES;
1219 while (GNUNET_YES == discard_low_prio)
1223 discard_low_prio = GNUNET_NO;
1224 /* calculate number of bytes available for transmission at time "t" */
1225 update_window (GNUNET_NO,
1226 &n->available_send_window,
1227 &n->last_asw_update,
1229 avail = n->available_send_window;
1230 t = n->last_asw_update;
1231 /* how many bytes have we (hypothetically) scheduled so far */
1233 /* maximum time we can wait before transmitting anything
1234 and still make all of our deadlines */
1238 /* note that we use "*2" here because we want to look
1239 a bit further into the future; much more makes no
1240 sense since new message might be scheduled in the
1242 while ((pos != NULL) && (off < size * 2))
1244 if (pos->do_transmit == GNUNET_YES)
1246 /* already removed from consideration */
1250 if (discard_low_prio == GNUNET_NO)
1252 delta = pos->deadline.value;
1253 if (delta < t.value)
1256 delta = t.value - delta;
1257 avail += delta * n->bpm_out / 1000 / 60;
1258 if (avail < pos->size)
1260 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1265 /* update slack, considering both its absolute deadline
1266 and relative deadlines caused by other messages
1267 with their respective load */
1268 slack = GNUNET_MIN (slack, avail / n->bpm_out);
1269 if (pos->deadline.value < now.value)
1273 GNUNET_MIN (slack, pos->deadline.value - now.value);
1277 t.value = GNUNET_MAX (pos->deadline.value, t.value);
1278 if (pos->priority <= min_prio)
1280 /* update min for discard */
1281 min_prio = pos->priority;
1286 if (discard_low_prio)
1288 GNUNET_assert (min != NULL);
1289 /* remove lowest-priority entry from consideration */
1290 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1294 /* guard against sending "tiny" messages with large headers without
1296 if ( (slack > 1000) && (size > 4 * off) )
1298 /* less than 25% of message would be filled with
1299 deadlines still being met if we delay by one
1300 second or more; so just wait for more data */
1301 retry_time->value = slack / 2;
1302 /* reset do_transmit values for next time */
1305 pos->do_transmit = GNUNET_NO;
1310 /* select marked messages (up to size) for transmission */
1315 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1317 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1322 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1326 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1327 "Selected %u bytes of plaintext messages for transmission to `%4s'.\n",
1328 off, GNUNET_i2s (&n->peer));
1335 * Batch multiple messages into a larger buffer.
1337 * @param n neighbour to take messages from
1338 * @param buf target buffer
1339 * @param size size of buf
1340 * @param deadline set to transmission deadline for the result
1341 * @param retry_time set to the time when we should try again
1342 * (only valid if this function returns zero)
1343 * @param priority set to the priority of the batch
1344 * @return number of bytes written to buf (can be zero)
1347 batch_message (struct Neighbour *n,
1350 struct GNUNET_TIME_Absolute *deadline,
1351 struct GNUNET_TIME_Relative *retry_time,
1352 unsigned int *priority)
1354 struct MessageEntry *pos;
1355 struct MessageEntry *prev;
1356 struct MessageEntry *next;
1361 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1362 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1363 if (0 == select_messages (n, size, retry_time))
1365 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1366 "No messages selected, will try again in %llu ms\n",
1372 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1375 if (GNUNET_YES == pos->do_transmit)
1377 GNUNET_assert (pos->size <= size);
1378 memcpy (&buf[ret], &pos[1], pos->size);
1381 *priority += pos->priority;
1383 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1384 "Adding plaintext message with deadline %llu ms to batch\n",
1385 GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1387 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1401 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1402 "Deadline for message batch is %llu ms\n",
1403 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1410 * Remove messages with deadlines that have long expired from
1413 * @param n neighbour to inspect
1416 discard_expired_messages (struct Neighbour *n)
1418 struct MessageEntry *prev;
1419 struct MessageEntry *next;
1420 struct MessageEntry *pos;
1421 struct GNUNET_TIME_Absolute now;
1422 struct GNUNET_TIME_Relative delta;
1424 now = GNUNET_TIME_absolute_get ();
1430 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1431 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1434 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1435 "Message is %llu ms past due, discarding.\n",
1452 * Signature of the main function of a task.
1454 * @param cls closure
1455 * @param tc context information (why was this task triggered now)
1458 retry_plaintext_processing (void *cls,
1459 const struct GNUNET_SCHEDULER_TaskContext *tc)
1461 struct Neighbour *n = cls;
1463 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1464 process_plaintext_neighbour_queue (n);
1469 * Send our key (and encrypted PING) to the other peer.
1471 * @param n the other peer
1473 static void send_key (struct Neighbour *n);
1477 * Check if we have plaintext messages for the specified neighbour
1478 * pending, and if so, consider batching and encrypting them (and
1479 * then trigger processing of the encrypted queue if needed).
1481 * @param n neighbour to check.
1484 process_plaintext_neighbour_queue (struct Neighbour *n)
1486 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1489 struct EncryptedMessage *em; /* encrypted message */
1490 struct EncryptedMessage *ph; /* plaintext header */
1491 struct MessageEntry *me;
1492 unsigned int priority;
1493 struct GNUNET_TIME_Absolute deadline;
1494 struct GNUNET_TIME_Relative retry_time;
1496 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1498 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1499 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1503 case PEER_STATE_DOWN:
1506 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1507 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1508 GNUNET_i2s(&n->peer));
1511 case PEER_STATE_KEY_SENT:
1512 GNUNET_assert (n->retry_set_key_task !=
1513 GNUNET_SCHEDULER_NO_TASK);
1515 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1516 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1517 GNUNET_i2s(&n->peer));
1520 case PEER_STATE_KEY_RECEIVED:
1521 GNUNET_assert (n->retry_set_key_task !=
1522 GNUNET_SCHEDULER_NO_TASK);
1524 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1525 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1526 GNUNET_i2s(&n->peer));
1529 case PEER_STATE_KEY_CONFIRMED:
1530 /* ready to continue */
1533 discard_expired_messages (n);
1534 if (n->messages == NULL)
1537 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1538 "Plaintext message queue for `%4s' is empty.\n",
1539 GNUNET_i2s(&n->peer));
1541 return; /* no pending messages */
1543 if (n->encrypted_head != NULL)
1546 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1547 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1548 GNUNET_i2s(&n->peer));
1550 return; /* wait for messages already encrypted to be
1553 ph = (struct EncryptedMessage *) pbuf;
1554 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1556 used = sizeof (struct EncryptedMessage);
1557 used += batch_message (n,
1559 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1560 &deadline, &retry_time, &priority);
1561 if (used == sizeof (struct EncryptedMessage))
1564 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1565 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1566 GNUNET_i2s(&n->peer));
1568 /* no messages selected for sending, try again later... */
1569 n->retry_plaintext_task =
1570 GNUNET_SCHEDULER_add_delayed (sched,
1572 &retry_plaintext_processing, n);
1575 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1576 ph->inbound_bpm_limit = htonl (n->bpm_in);
1577 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1579 /* setup encryption message header */
1580 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1581 me->deadline = deadline;
1582 me->priority = priority;
1584 em = (struct EncryptedMessage *) &me[1];
1585 em->header.size = htons (used);
1586 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1587 em->reserved = htonl (0);
1588 esize = used - ENCRYPTED_HEADER_SIZE;
1589 GNUNET_CRYPTO_hash (&ph->sequence_number, esize, &em->plaintext_hash);
1592 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1593 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
1595 GNUNET_i2s(&n->peer),
1596 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
1598 GNUNET_assert (GNUNET_OK ==
1600 &em->plaintext_hash,
1601 &ph->sequence_number,
1602 &em->sequence_number, esize));
1603 /* append to transmission list */
1604 if (n->encrypted_tail == NULL)
1605 n->encrypted_head = me;
1607 n->encrypted_tail->next = me;
1608 n->encrypted_tail = me;
1609 process_encrypted_neighbour_queue (n);
1614 * Handle CORE_SEND request.
1617 * @param client the client issuing the request
1618 * @param message the "struct SendMessage"
1621 handle_client_send (void *cls,
1622 struct GNUNET_SERVER_Client *client,
1623 const struct GNUNET_MessageHeader *message);
1627 * Function called to notify us that we either succeeded
1628 * or failed to connect (at the transport level) to another
1629 * peer. We should either free the message we were asked
1630 * to transmit or re-try adding it to the queue.
1632 * @param cls closure
1633 * @param size number of bytes available in buf
1634 * @param buf where the callee should write the message
1635 * @return number of bytes written to buf
1638 send_connect_continuation (void *cls, size_t size, void *buf)
1640 struct SendMessage *sm = cls;
1645 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1646 "Asked to send message to disconnected peer `%4s' and connection failed. Discarding message.\n",
1647 GNUNET_i2s (&sm->peer));
1653 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1654 "Connection to peer `%4s' succeeded, retrying original transmission request\n",
1655 GNUNET_i2s (&sm->peer));
1657 handle_client_send (NULL, NULL, &sm->header);
1664 * Handle CORE_SEND request.
1667 * @param client the client issuing the request
1668 * @param message the "struct SendMessage"
1671 handle_client_send (void *cls,
1672 struct GNUNET_SERVER_Client *client,
1673 const struct GNUNET_MessageHeader *message)
1675 const struct SendMessage *sm;
1676 struct SendMessage *smc;
1677 const struct GNUNET_MessageHeader *mh;
1678 struct Neighbour *n;
1679 struct MessageEntry *prev;
1680 struct MessageEntry *pos;
1681 struct MessageEntry *e;
1682 struct MessageEntry *min_prio_entry;
1683 struct MessageEntry *min_prio_prev;
1684 unsigned int min_prio;
1685 unsigned int queue_size;
1688 msize = ntohs (message->size);
1690 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
1694 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1697 sm = (const struct SendMessage *) message;
1698 msize -= sizeof (struct SendMessage);
1699 mh = (const struct GNUNET_MessageHeader *) &sm[1];
1700 if (msize != ntohs (mh->size))
1704 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1707 n = find_neighbour (&sm->peer);
1711 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1712 "Core received `%s' request for `%4s', will try to establish connection within %llu ms\n",
1714 GNUNET_i2s (&sm->peer),
1715 GNUNET_TIME_absolute_get_remaining
1716 (GNUNET_TIME_absolute_ntoh(sm->deadline)).value);
1718 msize += sizeof (struct SendMessage);
1719 /* ask transport to connect to the peer */
1720 smc = GNUNET_malloc (msize);
1721 memcpy (smc, sm, msize);
1723 GNUNET_TRANSPORT_notify_transmit_ready (transport,
1726 GNUNET_TIME_absolute_get_remaining
1727 (GNUNET_TIME_absolute_ntoh
1729 &send_connect_continuation,
1732 /* transport has already a request pending for this peer! */
1734 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1735 "Dropped second message destined for `%4s' since connection is still down.\n",
1736 GNUNET_i2s(&sm->peer));
1741 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1745 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1746 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
1749 GNUNET_i2s (&sm->peer));
1751 /* bound queue size */
1752 discard_expired_messages (n);
1753 min_prio = (unsigned int) -1;
1754 min_prio_entry = NULL;
1755 min_prio_prev = NULL;
1761 if (pos->priority < min_prio)
1763 min_prio_entry = pos;
1764 min_prio_prev = prev;
1765 min_prio = pos->priority;
1771 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1774 if (ntohl(sm->priority) <= min_prio)
1776 /* discard new entry */
1778 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1779 "Queue full, discarding new request\n");
1782 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1785 /* discard "min_prio_entry" */
1787 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1788 "Queue full, discarding existing older request\n");
1790 if (min_prio_prev == NULL)
1791 n->messages = min_prio_entry->next;
1793 min_prio_prev->next = min_prio_entry->next;
1794 GNUNET_free (min_prio_entry);
1798 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1799 "Adding transmission request for `%4s' to queue\n",
1800 GNUNET_i2s (&sm->peer));
1802 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
1803 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
1804 e->priority = ntohl (sm->priority);
1806 memcpy (&e[1], mh, msize);
1808 /* insert, keep list sorted by deadline */
1811 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
1822 /* consider scheduling now */
1823 process_plaintext_neighbour_queue (n);
1825 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1830 * Handle CORE_REQUEST_CONNECT request.
1833 * @param client the client issuing the request
1834 * @param message the "struct ConnectMessage"
1837 handle_client_request_connect (void *cls,
1838 struct GNUNET_SERVER_Client *client,
1839 const struct GNUNET_MessageHeader *message)
1841 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
1842 struct Neighbour *n;
1844 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1845 n = find_neighbour (&cm->peer);
1847 return; /* already connected, or at least trying */
1849 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1850 "Core received `%s' request for `%4s', will try to establish connection\n",
1852 GNUNET_i2s (&cm->peer));
1854 /* ask transport to connect to the peer */
1855 /* FIXME: timeout zero OK? need for cancellation? */
1856 GNUNET_TRANSPORT_notify_transmit_ready (transport,
1859 GNUNET_TIME_UNIT_ZERO,
1866 * Handle CORE_REQUEST_DISCONNECT request.
1869 * @param client the client issuing the request
1870 * @param message the "struct ConnectMessage"
1873 handle_client_request_disconnect (void *cls,
1874 struct GNUNET_SERVER_Client *client,
1875 const struct GNUNET_MessageHeader *message)
1877 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
1878 struct Neighbour *n;
1880 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1881 n = find_neighbour (&cm->peer);
1884 /* FIXME: implement disconnect! */
1890 * List of handlers for the messages understood by this
1893 static struct GNUNET_SERVER_MessageHandler handlers[] = {
1894 {&handle_client_init, NULL,
1895 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
1896 {&handle_client_request_info, NULL,
1897 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
1898 sizeof (struct RequestInfoMessage)},
1899 {&handle_client_send, NULL,
1900 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
1901 {&handle_client_request_connect, NULL,
1902 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
1903 sizeof (struct ConnectMessage)},
1904 {&handle_client_request_disconnect, NULL,
1905 GNUNET_MESSAGE_TYPE_CORE_REQUEST_DISCONNECT,
1906 sizeof (struct ConnectMessage)},
1912 * PEERINFO is giving us a HELLO for a peer. Add the public key to
1913 * the neighbour's struct and retry send_key. Or, if we did not get a
1914 * HELLO, just do nothing.
1917 * @param peer the peer for which this is the HELLO
1918 * @param hello HELLO message of that peer
1919 * @param trust amount of trust we currently have in that peer
1922 process_hello_retry_send_key (void *cls,
1923 const struct GNUNET_PeerIdentity *peer,
1924 const struct GNUNET_HELLO_Message *hello,
1927 struct Neighbour *n = cls;
1934 if (n->public_key != NULL)
1937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1938 "Received new `%s' message for `%4s', initiating key exchange.\n",
1943 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1944 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
1946 GNUNET_free (n->public_key);
1947 n->public_key = NULL;
1955 * Task that will retry "send_key" if our previous attempt failed
1959 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1961 struct Neighbour *n = cls;
1963 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1964 n->set_key_retry_frequency =
1965 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1971 * Send our key (and encrypted PING) to the other peer.
1973 * @param n the other peer
1976 send_key (struct Neighbour *n)
1978 struct SetKeyMessage *sm;
1979 struct MessageEntry *me;
1980 struct PingMessage pp;
1981 struct PingMessage *pm;
1983 if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
1985 return; /* already in progress */
1987 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1988 "Asked to perform key exchange with `%4s'.\n",
1989 GNUNET_i2s (&n->peer));
1991 if (n->public_key == NULL)
1993 /* lookup n's public key, then try again */
1995 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1996 "Lacking public key for `%4s', trying to obtain one.\n",
1997 GNUNET_i2s (&n->peer));
1999 GNUNET_assert (n->pitr == NULL);
2000 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2004 GNUNET_TIME_UNIT_MINUTES,
2005 &process_hello_retry_send_key, n);
2008 /* first, set key message */
2009 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2010 sizeof (struct SetKeyMessage));
2011 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2012 me->priority = SET_KEY_PRIORITY;
2013 me->size = sizeof (struct SetKeyMessage);
2014 if (n->encrypted_head == NULL)
2015 n->encrypted_head = me;
2017 n->encrypted_tail->next = me;
2018 n->encrypted_tail = me;
2019 sm = (struct SetKeyMessage *) &me[1];
2020 sm->header.size = htons (sizeof (struct SetKeyMessage));
2021 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2022 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2023 PEER_STATE_KEY_SENT : n->status));
2025 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2026 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2027 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2028 sizeof (struct GNUNET_PeerIdentity));
2029 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2030 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2031 sm->target = n->peer;
2032 GNUNET_assert (GNUNET_OK ==
2033 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2035 GNUNET_CRYPTO_AesSessionKey),
2037 &sm->encrypted_key));
2038 GNUNET_assert (GNUNET_OK ==
2039 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2042 /* second, encrypted PING message */
2043 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2044 sizeof (struct PingMessage));
2045 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2046 me->priority = PING_PRIORITY;
2047 me->size = sizeof (struct PingMessage);
2048 n->encrypted_tail->next = me;
2049 n->encrypted_tail = me;
2050 pm = (struct PingMessage *) &me[1];
2051 pm->header.size = htons (sizeof (struct PingMessage));
2052 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2053 pp.challenge = htonl (n->ping_challenge);
2054 pp.target = n->peer;
2056 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2057 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2058 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2059 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2060 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2062 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2065 &n->peer.hashPubKey,
2068 sizeof (struct PingMessage) -
2069 sizeof (struct GNUNET_MessageHeader));
2073 case PEER_STATE_DOWN:
2074 n->status = PEER_STATE_KEY_SENT;
2076 case PEER_STATE_KEY_SENT:
2078 case PEER_STATE_KEY_RECEIVED:
2080 case PEER_STATE_KEY_CONFIRMED:
2087 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2088 "Have %llu ms left for `%s' transmission.\n",
2089 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2092 /* trigger queue processing */
2093 process_encrypted_neighbour_queue (n);
2094 if (n->status != PEER_STATE_KEY_CONFIRMED)
2096 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task);
2097 n->retry_set_key_task
2098 = GNUNET_SCHEDULER_add_delayed (sched,
2099 n->set_key_retry_frequency,
2100 &set_key_retry_task, n);
2106 * We received a SET_KEY message. Validate and update
2107 * our key material and status.
2109 * @param n the neighbour from which we received message m
2110 * @param m the set key message we received
2113 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2117 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2118 * the neighbour's struct and retry handling the set_key message. Or,
2119 * if we did not get a HELLO, just free the set key message.
2121 * @param cls pointer to the set key message
2122 * @param peer the peer for which this is the HELLO
2123 * @param hello HELLO message of that peer
2124 * @param trust amount of trust we currently have in that peer
2127 process_hello_retry_handle_set_key (void *cls,
2128 const struct GNUNET_PeerIdentity *peer,
2129 const struct GNUNET_HELLO_Message *hello,
2132 struct Neighbour *n = cls;
2133 struct SetKeyMessage *sm = n->skm;
2142 if (n->public_key != NULL)
2143 return; /* multiple HELLOs match!? */
2145 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2146 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2148 GNUNET_break_op (0);
2149 GNUNET_free (n->public_key);
2150 n->public_key = NULL;
2154 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2155 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2156 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2158 handle_set_key (n, sm);
2163 * We received a PING message. Validate and transmit
2166 * @param n sender of the PING
2167 * @param m the encrypted PING message itself
2170 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2172 struct PingMessage t;
2173 struct PingMessage *tp;
2174 struct MessageEntry *me;
2177 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2178 "Core service receives `%s' request from `%4s'.\n",
2179 "PING", GNUNET_i2s (&n->peer));
2183 &my_identity.hashPubKey,
2186 sizeof (struct PingMessage) -
2187 sizeof (struct GNUNET_MessageHeader)))
2190 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2191 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2193 GNUNET_i2s (&t.target),
2194 ntohl (t.challenge), n->decrypt_key.crc32);
2195 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2196 "Target of `%s' request is `%4s'.\n",
2197 "PING", GNUNET_i2s (&t.target));
2199 if (0 != memcmp (&t.target,
2200 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2202 GNUNET_break_op (0);
2205 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2206 sizeof (struct PingMessage));
2207 if (n->encrypted_tail != NULL)
2208 n->encrypted_tail->next = me;
2211 n->encrypted_tail = me;
2212 n->encrypted_head = me;
2214 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2215 me->priority = PONG_PRIORITY;
2216 me->size = sizeof (struct PingMessage);
2217 tp = (struct PingMessage *) &me[1];
2218 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2219 tp->header.size = htons (sizeof (struct PingMessage));
2221 &my_identity.hashPubKey,
2224 sizeof (struct PingMessage) -
2225 sizeof (struct GNUNET_MessageHeader));
2227 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2228 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2229 ntohl (t.challenge), n->encrypt_key.crc32);
2231 /* trigger queue processing */
2232 process_encrypted_neighbour_queue (n);
2237 * We received a SET_KEY message. Validate and update
2238 * our key material and status.
2240 * @param n the neighbour from which we received message m
2241 * @param m the set key message we received
2244 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2246 struct SetKeyMessage *m_cpy;
2247 struct GNUNET_TIME_Absolute t;
2248 struct GNUNET_CRYPTO_AesSessionKey k;
2249 struct PingMessage *ping;
2250 enum PeerStateMachine sender_status;
2253 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2254 "Core service receives `%s' request from `%4s'.\n",
2255 "SET_KEY", GNUNET_i2s (&n->peer));
2257 if (n->public_key == NULL)
2260 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2261 "Lacking public key for peer, trying to obtain one.\n");
2263 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2264 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2265 /* lookup n's public key, then try again */
2266 GNUNET_assert (n->pitr == NULL);
2267 GNUNET_assert (n->skm == NULL);
2269 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2273 GNUNET_TIME_UNIT_MINUTES,
2274 &process_hello_retry_handle_set_key, n);
2277 if (0 != memcmp (&m->target,
2279 sizeof (struct GNUNET_PeerIdentity)))
2281 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2282 _("Received `%s' message that was not for me. Ignoring.\n"));
2285 if ((ntohl (m->purpose.size) !=
2286 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2287 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2288 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2289 sizeof (struct GNUNET_PeerIdentity)) ||
2291 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2292 &m->purpose, &m->signature, n->public_key)))
2294 /* invalid signature */
2295 GNUNET_break_op (0);
2298 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2299 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2300 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2301 (t.value < n->decrypt_key_created.value))
2303 /* this could rarely happen due to massive re-ordering of
2304 messages on the network level, but is most likely either
2305 a bug or some adversary messing with us. Report. */
2306 GNUNET_break_op (0);
2310 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
2312 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2315 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2316 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2317 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2319 /* failed to decrypt !? */
2320 GNUNET_break_op (0);
2325 if (n->decrypt_key_created.value != t.value)
2327 /* fresh key, reset sequence numbers */
2328 n->last_sequence_number_received = 0;
2329 n->last_packets_bitmap = 0;
2330 n->decrypt_key_created = t;
2332 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2335 case PEER_STATE_DOWN:
2336 n->status = PEER_STATE_KEY_RECEIVED;
2338 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2339 "Responding to `%s' with my own key.\n", "SET_KEY");
2343 case PEER_STATE_KEY_SENT:
2344 case PEER_STATE_KEY_RECEIVED:
2345 n->status = PEER_STATE_KEY_RECEIVED;
2346 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2347 (sender_status != PEER_STATE_KEY_CONFIRMED))
2350 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2351 "Responding to `%s' with my own key (other peer has status %u).\n",
2352 "SET_KEY", sender_status);
2357 case PEER_STATE_KEY_CONFIRMED:
2358 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2359 (sender_status != PEER_STATE_KEY_CONFIRMED))
2362 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2363 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2364 "SET_KEY", sender_status);
2373 if (n->pending_ping != NULL)
2375 ping = n->pending_ping;
2376 n->pending_ping = NULL;
2377 handle_ping (n, ping);
2384 * We received a PONG message. Validate and update our status.
2386 * @param n sender of the PONG
2387 * @param m the encrypted PONG message itself
2390 handle_pong (struct Neighbour *n, const struct PingMessage *m)
2392 struct PingMessage t;
2393 struct ConnectNotifyMessage cnm;
2396 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2397 "Core service receives `%s' request from `%4s'.\n",
2398 "PONG", GNUNET_i2s (&n->peer));
2402 &n->peer.hashPubKey,
2405 sizeof (struct PingMessage) -
2406 sizeof (struct GNUNET_MessageHeader)))
2409 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2410 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2412 GNUNET_i2s (&t.target),
2413 ntohl (t.challenge), n->decrypt_key.crc32);
2415 if ((0 != memcmp (&t.target,
2417 sizeof (struct GNUNET_PeerIdentity))) ||
2418 (n->ping_challenge != ntohl (t.challenge)))
2420 /* PONG malformed */
2422 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2423 "Received malfromed `%s' wanted sender `%4s' with challenge %u\n",
2424 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2425 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2426 "Received malfromed `%s' received from `%4s' with challenge %u\n",
2427 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2429 GNUNET_break_op (0);
2434 case PEER_STATE_DOWN:
2435 GNUNET_break (0); /* should be impossible */
2437 case PEER_STATE_KEY_SENT:
2438 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2440 case PEER_STATE_KEY_RECEIVED:
2441 n->status = PEER_STATE_KEY_CONFIRMED;
2442 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2444 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2445 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2447 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2448 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2449 cnm.distance = htonl (n->last_distance);
2450 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2452 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2453 process_encrypted_neighbour_queue (n);
2455 case PEER_STATE_KEY_CONFIRMED:
2456 /* duplicate PONG? */
2466 * Send a P2P message to a client.
2468 * @param sender who sent us the message?
2469 * @param client who should we give the message to?
2470 * @param m contains the message to transmit
2471 * @param msize number of bytes in buf to transmit
2474 send_p2p_message_to_client (struct Neighbour *sender,
2475 struct Client *client,
2476 const void *m, size_t msize)
2478 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2479 struct NotifyTrafficMessage *ntm;
2482 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2483 "Core service passes message from `%4s' of type %u to client.\n",
2484 GNUNET_i2s(&sender->peer),
2485 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2487 ntm = (struct NotifyTrafficMessage *) buf;
2488 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2489 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2490 ntm->distance = htonl (sender->last_distance);
2491 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
2492 ntm->peer = sender->peer;
2493 memcpy (&ntm[1], m, msize);
2494 send_to_client (client, &ntm->header, GNUNET_YES);
2499 * Deliver P2P message to interested clients.
2501 * @param sender who sent us the message?
2502 * @param m the message
2503 * @param msize size of the message (including header)
2506 deliver_message (struct Neighbour *sender,
2507 const struct GNUNET_MessageHeader *m, size_t msize)
2509 struct Client *cpos;
2514 type = ntohs (m->type);
2516 while (cpos != NULL)
2518 deliver_full = GNUNET_NO;
2519 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
2520 deliver_full = GNUNET_YES;
2523 for (tpos = 0; tpos < cpos->tcnt; tpos++)
2525 if (type != cpos->types[tpos])
2527 deliver_full = GNUNET_YES;
2531 if (GNUNET_YES == deliver_full)
2532 send_p2p_message_to_client (sender, cpos, m, msize);
2533 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2534 send_p2p_message_to_client (sender, cpos, m,
2535 sizeof (struct GNUNET_MessageHeader));
2542 * Align P2P message and then deliver to interested clients.
2544 * @param sender who sent us the message?
2545 * @param buffer unaligned (!) buffer containing message
2546 * @param msize size of the message (including header)
2549 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
2553 /* TODO: call to statistics? */
2554 memcpy (abuf, buffer, msize);
2555 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
2560 * Deliver P2P messages to interested clients.
2562 * @param sender who sent us the message?
2563 * @param buffer buffer containing messages, can be modified
2564 * @param buffer_size size of the buffer (overall)
2565 * @param offset offset where messages in the buffer start
2568 deliver_messages (struct Neighbour *sender,
2569 const char *buffer, size_t buffer_size, size_t offset)
2571 struct GNUNET_MessageHeader *mhp;
2572 struct GNUNET_MessageHeader mh;
2576 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
2578 if (0 != offset % sizeof (uint16_t))
2580 /* outch, need to copy to access header */
2581 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
2586 /* can access header directly */
2587 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
2589 msize = ntohs (mhp->size);
2590 if (msize + offset > buffer_size)
2592 /* malformed message, header says it is larger than what
2593 would fit into the overall buffer */
2594 GNUNET_break_op (0);
2597 #if HAVE_UNALIGNED_64_ACCESS
2598 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
2600 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
2602 if (GNUNET_YES == need_align)
2603 align_and_deliver (sender, &buffer[offset], msize);
2605 deliver_message (sender,
2606 (const struct GNUNET_MessageHeader *)
2607 &buffer[offset], msize);
2614 * We received an encrypted message. Decrypt, validate and
2615 * pass on to the appropriate clients.
2618 handle_encrypted_message (struct Neighbour *n,
2619 const struct EncryptedMessage *m)
2621 size_t size = ntohs (m->header.size);
2623 struct EncryptedMessage *pt; /* plaintext */
2627 struct GNUNET_TIME_Absolute t;
2630 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2631 "Core service receives `%s' request from `%4s'.\n",
2632 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
2638 &m->sequence_number,
2639 &buf[ENCRYPTED_HEADER_SIZE], size - ENCRYPTED_HEADER_SIZE))
2641 pt = (struct EncryptedMessage *) buf;
2644 GNUNET_CRYPTO_hash (&pt->sequence_number,
2645 size - ENCRYPTED_HEADER_SIZE, &ph);
2646 if (0 != memcmp (&ph, &m->plaintext_hash, sizeof (GNUNET_HashCode)))
2648 /* checksum failed */
2649 GNUNET_break_op (0);
2653 /* validate sequence number */
2654 snum = ntohl (pt->sequence_number);
2655 if (n->last_sequence_number_received == snum)
2657 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2658 "Received duplicate message, ignoring.\n");
2659 /* duplicate, ignore */
2662 if ((n->last_sequence_number_received > snum) &&
2663 (n->last_sequence_number_received - snum > 32))
2665 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2666 "Received ancient out of sequence message, ignoring.\n");
2667 /* ancient out of sequence, ignore */
2670 if (n->last_sequence_number_received > snum)
2672 unsigned int rotbit =
2673 1 << (n->last_sequence_number_received - snum - 1);
2674 if ((n->last_packets_bitmap & rotbit) != 0)
2676 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2677 "Received duplicate message, ignoring.\n");
2678 /* duplicate, ignore */
2681 n->last_packets_bitmap |= rotbit;
2683 if (n->last_sequence_number_received < snum)
2685 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
2686 n->last_sequence_number_received = snum;
2689 /* check timestamp */
2690 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
2691 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
2693 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2695 ("Message received far too old (%llu ms). Content ignored.\n"),
2696 GNUNET_TIME_absolute_get_duration (t).value);
2700 /* process decrypted message(s) */
2701 update_window (GNUNET_YES,
2702 &n->available_send_window,
2703 &n->last_asw_update,
2705 n->bpm_out_external_limit = ntohl (pt->inbound_bpm_limit);
2706 n->bpm_out = GNUNET_MAX (n->bpm_out_external_limit,
2707 n->bpm_out_internal_limit);
2708 n->last_activity = GNUNET_TIME_absolute_get ();
2709 off = sizeof (struct EncryptedMessage);
2710 deliver_messages (n, buf, size, off);
2715 * Function called by the transport for each received message.
2717 * @param cls closure
2718 * @param peer (claimed) identity of the other peer
2719 * @param message the message
2720 * @param latency estimated latency for communicating with the
2721 * given peer (round-trip)
2722 * @param distance in overlay hops, as given by transport plugin
2725 handle_transport_receive (void *cls,
2726 const struct GNUNET_PeerIdentity *peer,
2727 const struct GNUNET_MessageHeader *message,
2728 struct GNUNET_TIME_Relative latency,
2729 unsigned int distance)
2731 struct Neighbour *n;
2732 struct GNUNET_TIME_Absolute now;
2738 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2739 "Received message of type %u from `%4s', demultiplexing.\n",
2740 ntohs (message->type), GNUNET_i2s (peer));
2742 n = find_neighbour (peer);
2748 n->last_latency = latency;
2749 up = (n->status == PEER_STATE_KEY_CONFIRMED);
2750 type = ntohs (message->type);
2751 size = ntohs (message->size);
2754 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
2755 if (size != sizeof (struct SetKeyMessage))
2757 GNUNET_break_op (0);
2760 handle_set_key (n, (const struct SetKeyMessage *) message);
2762 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
2763 if (size < sizeof (struct EncryptedMessage) +
2764 sizeof (struct GNUNET_MessageHeader))
2766 GNUNET_break_op (0);
2769 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2770 (n->status != PEER_STATE_KEY_CONFIRMED))
2772 GNUNET_break_op (0);
2775 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
2777 case GNUNET_MESSAGE_TYPE_CORE_PING:
2778 if (size != sizeof (struct PingMessage))
2780 GNUNET_break_op (0);
2783 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2784 (n->status != PEER_STATE_KEY_CONFIRMED))
2787 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2788 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
2789 "PING", GNUNET_i2s (&n->peer));
2791 GNUNET_free_non_null (n->pending_ping);
2792 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
2793 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
2796 handle_ping (n, (const struct PingMessage *) message);
2798 case GNUNET_MESSAGE_TYPE_CORE_PONG:
2799 if (size != sizeof (struct PingMessage))
2801 GNUNET_break_op (0);
2804 if ((n->status != PEER_STATE_KEY_SENT) &&
2805 (n->status != PEER_STATE_KEY_RECEIVED) &&
2806 (n->status != PEER_STATE_KEY_CONFIRMED))
2808 /* could not decrypt pong, oops! */
2809 GNUNET_break_op (0);
2812 handle_pong (n, (const struct PingMessage *) message);
2815 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2816 _("Unsupported message of type %u received.\n"), type);
2819 if (n->status == PEER_STATE_KEY_CONFIRMED)
2821 now = GNUNET_TIME_absolute_get ();
2822 n->last_activity = now;
2824 n->time_established = now;
2830 * Function that recalculates the bandwidth quota for the
2831 * given neighbour and transmits it to the transport service.
2833 * @param cls neighbour for the quota update
2837 neighbour_quota_update (void *cls,
2838 const struct GNUNET_SCHEDULER_TaskContext *tc);
2842 * Schedule the task that will recalculate the bandwidth
2843 * quota for this peer (and possibly force a disconnect of
2844 * idle peers by calculating a bandwidth of zero).
2847 schedule_quota_update (struct Neighbour *n)
2849 GNUNET_assert (n->quota_update_task ==
2850 GNUNET_SCHEDULER_NO_TASK);
2851 n->quota_update_task
2852 = GNUNET_SCHEDULER_add_delayed (sched,
2853 QUOTA_UPDATE_FREQUENCY,
2854 &neighbour_quota_update,
2860 * Function that recalculates the bandwidth quota for the
2861 * given neighbour and transmits it to the transport service.
2863 * @param cls neighbour for the quota update
2867 neighbour_quota_update (void *cls,
2868 const struct GNUNET_SCHEDULER_TaskContext *tc)
2870 struct Neighbour *n = cls;
2874 unsigned long long distributable;
2876 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
2877 /* calculate relative preference among all neighbours;
2878 divides by a bit more to avoid division by zero AND to
2879 account for possibility of new neighbours joining any time
2880 AND to convert to double... */
2881 pref_rel = n->current_preference / (1.0 + preference_sum);
2883 if (bandwidth_target_out > neighbour_count * MIN_BPM_PER_PEER)
2884 distributable = bandwidth_target_out - neighbour_count * MIN_BPM_PER_PEER;
2885 share = distributable * pref_rel;
2886 q_in = MIN_BPM_PER_PEER + (unsigned long long) share;
2887 /* check if we want to disconnect for good due to inactivity */
2888 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
2889 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
2890 q_in = 0; /* force disconnect */
2891 if ( (n->bpm_in + MIN_BPM_CHANGE < q_in) ||
2892 (n->bpm_in - MIN_BPM_CHANGE > q_in) )
2895 GNUNET_TRANSPORT_set_quota (transport,
2899 GNUNET_TIME_UNIT_FOREVER_REL,
2902 schedule_quota_update (n);
2907 * Function called by transport to notify us that
2908 * a peer connected to us (on the network level).
2910 * @param cls closure
2911 * @param peer the peer that connected
2912 * @param latency current latency of the connection
2913 * @param distance in overlay hops, as given by transport plugin
2916 handle_transport_notify_connect (void *cls,
2917 const struct GNUNET_PeerIdentity *peer,
2918 struct GNUNET_TIME_Relative latency,
2919 unsigned int distance)
2921 struct Neighbour *n;
2922 struct GNUNET_TIME_Absolute now;
2923 struct ConnectNotifyMessage cnm;
2925 n = find_neighbour (peer);
2928 /* duplicate connect notification!? */
2932 now = GNUNET_TIME_absolute_get ();
2933 n = GNUNET_malloc (sizeof (struct Neighbour));
2934 n->next = neighbours;
2938 n->last_latency = latency;
2939 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2940 n->encrypt_key_created = now;
2941 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2942 n->last_asw_update = now;
2943 n->last_arw_update = now;
2944 n->bpm_in = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
2945 n->bpm_out = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
2946 n->bpm_out_internal_limit = (uint32_t) - 1;
2947 n->bpm_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
2948 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2951 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2952 "Received connection from `%4s'.\n",
2953 GNUNET_i2s (&n->peer));
2955 schedule_quota_update (n);
2956 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2957 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
2958 cnm.distance = htonl (n->last_distance);
2959 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2961 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
2967 * Free the given entry for the neighbour (it has
2968 * already been removed from the list at this point).
2970 * @param n neighbour to free
2973 free_neighbour (struct Neighbour *n)
2975 struct MessageEntry *m;
2977 if (n->pitr != NULL)
2979 GNUNET_PEERINFO_iterate_cancel (n->pitr);
2984 GNUNET_free (n->skm);
2987 while (NULL != (m = n->messages))
2989 n->messages = m->next;
2992 while (NULL != (m = n->encrypted_head))
2994 n->encrypted_head = m->next;
2998 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
2999 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
3000 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
3001 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3002 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
3003 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
3004 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
3005 GNUNET_free_non_null (n->public_key);
3006 GNUNET_free_non_null (n->pending_ping);
3012 * Function called by transport telling us that a peer
3015 * @param cls closure
3016 * @param peer the peer that disconnected
3019 handle_transport_notify_disconnect (void *cls,
3020 const struct GNUNET_PeerIdentity *peer)
3022 struct DisconnectNotifyMessage cnm;
3023 struct Neighbour *n;
3024 struct Neighbour *p;
3027 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3028 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3032 while ((n != NULL) &&
3033 (0 != memcmp (&n->peer, peer, sizeof (struct GNUNET_PeerIdentity))))
3044 neighbours = n->next;
3047 GNUNET_assert (neighbour_count > 0);
3049 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3050 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3052 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3058 * Last task run during shutdown. Disconnects us from
3062 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3064 struct Neighbour *n;
3068 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3069 "Core service shutting down.\n");
3071 GNUNET_assert (transport != NULL);
3072 GNUNET_TRANSPORT_disconnect (transport);
3074 while (NULL != (n = neighbours))
3076 neighbours = n->next;
3077 GNUNET_assert (neighbour_count > 0);
3081 GNUNET_SERVER_notification_context_destroy (notifier);
3083 while (NULL != (c = clients))
3084 handle_client_disconnect (NULL, c->client_handle);
3085 if (my_private_key != NULL)
3086 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3091 * Initiate core service.
3093 * @param cls closure
3094 * @param s scheduler to use
3095 * @param serv the initialized server
3096 * @param c configuration to use
3100 struct GNUNET_SCHEDULER_Handle *s,
3101 struct GNUNET_SERVER_Handle *serv,
3102 const struct GNUNET_CONFIGURATION_Handle *c)
3105 unsigned long long qin;
3106 unsigned long long qout;
3107 unsigned long long tneigh;
3113 /* parse configuration */
3116 GNUNET_CONFIGURATION_get_value_number (c,
3119 &bandwidth_target_in)) ||
3121 GNUNET_CONFIGURATION_get_value_number (c,
3124 &bandwidth_target_out)) ||
3127 GNUNET_CONFIGURATION_get_value_number (c,
3132 GNUNET_CONFIGURATION_get_value_number (c,
3134 "ZZ_LIMIT", &tneigh)) ||
3137 GNUNET_CONFIGURATION_get_value_filename (c,
3139 "HOSTKEY", &keyfile)))
3141 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3143 ("Core service is lacking key configuration settings. Exiting.\n"));
3144 GNUNET_SCHEDULER_shutdown (s);
3147 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3148 GNUNET_free (keyfile);
3149 if (my_private_key == NULL)
3151 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3152 _("Core service could not access hostkey. Exiting.\n"));
3153 GNUNET_SCHEDULER_shutdown (s);
3156 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3157 GNUNET_CRYPTO_hash (&my_public_key,
3158 sizeof (my_public_key), &my_identity.hashPubKey);
3159 /* setup notification */
3161 notifier = GNUNET_SERVER_notification_context_create (server, 0);
3162 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3163 /* setup transport connection */
3164 transport = GNUNET_TRANSPORT_connect (sched,
3167 &handle_transport_receive,
3168 &handle_transport_notify_connect,
3169 &handle_transport_notify_disconnect);
3170 GNUNET_assert (NULL != transport);
3171 GNUNET_SCHEDULER_add_delayed (sched,
3172 GNUNET_TIME_UNIT_FOREVER_REL,
3173 &cleaning_task, NULL);
3174 /* process client requests */
3175 GNUNET_SERVER_add_handlers (server, handlers);
3176 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3177 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3183 * The main function for the transport service.
3185 * @param argc number of arguments from the command line
3186 * @param argv command line arguments
3187 * @return 0 ok, 1 on error
3190 main (int argc, char *const *argv)
3192 return (GNUNET_OK ==
3193 GNUNET_SERVICE_run (argc,
3196 GNUNET_SERVICE_OPTION_NONE,
3197 &run, NULL)) ? 0 : 1;
3200 /* end of gnunet-service-core.c */