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"
45 * Receive and send buffer windows grow over time. For
46 * how long can 'unused' bandwidth accumulate before we
47 * need to cap it? (specified in ms).
49 #define MAX_WINDOW_TIME (5 * 60 * 1000)
52 * How many messages do we queue up at most for optional
53 * notifications to a client? (this can cause notifications
54 * about outgoing messages to be dropped).
56 #define MAX_NOTIFY_QUEUE 16
59 * Minimum of bytes per minute (out) to assign to any connected peer.
60 * Should be rather low; values larger than DEFAULT_BPM_IN_OUT make no
63 #define MIN_BPM_PER_PEER GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT
66 * What is the smallest change (in number of bytes per minute)
67 * that we consider significant enough to bother triggering?
69 #define MIN_BPM_CHANGE 32
72 * After how much time past the "official" expiration time do
73 * we discard messages? Should not be zero since we may
74 * intentionally defer transmission until close to the deadline
75 * and then may be slightly past the deadline due to inaccuracy
76 * in sleep and our own CPU consumption.
78 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
81 * What is the maximum delay for a SET_KEY message?
83 #define MAX_SET_KEY_DELAY GNUNET_TIME_UNIT_SECONDS
86 * What how long do we wait for SET_KEY confirmation initially?
88 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3)
91 * What is the maximum delay for a PING message?
93 #define MAX_PING_DELAY GNUNET_TIME_UNIT_SECONDS
96 * What is the maximum delay for a PONG message?
98 #define MAX_PONG_DELAY GNUNET_TIME_UNIT_SECONDS
101 * How often do we recalculate bandwidth quotas?
103 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_UNIT_SECONDS
106 * What is the priority for a SET_KEY message?
108 #define SET_KEY_PRIORITY 0xFFFFFF
111 * What is the priority for a PING message?
113 #define PING_PRIORITY 0xFFFFFF
116 * What is the priority for a PONG message?
118 #define PONG_PRIORITY 0xFFFFFF
121 * How many messages do we queue per peer at most?
123 #define MAX_PEER_QUEUE_SIZE 16
126 * How many non-mandatory messages do we queue per client at most?
128 #define MAX_CLIENT_QUEUE_SIZE 32
131 * What is the maximum age of a message for us to consider
132 * processing it? Note that this looks at the timestamp used
133 * by the other peer, so clock skew between machines does
134 * come into play here. So this should be picked high enough
135 * so that a little bit of clock skew does not prevent peers
136 * from connecting to us.
138 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
141 * What is the maximum size for encrypted messages? Note that this
142 * number imposes a clear limit on the maximum size of any message.
143 * Set to a value close to 64k but not so close that transports will
144 * have trouble with their headers.
146 #define MAX_ENCRYPTED_MESSAGE_SIZE (63 * 1024)
150 * State machine for our P2P encryption handshake. Everyone starts in
151 * "DOWN", if we receive the other peer's key (other peer initiated)
152 * we start in state RECEIVED (since we will immediately send our
153 * own); otherwise we start in SENT. If we get back a PONG from
154 * within either state, we move up to CONFIRMED (the PONG will always
155 * be sent back encrypted with the key we sent to the other peer).
157 enum PeerStateMachine
161 PEER_STATE_KEY_RECEIVED,
162 PEER_STATE_KEY_CONFIRMED
167 * Number of bytes (at the beginning) of "struct EncryptedMessage"
168 * that are NOT encrypted.
170 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t) + sizeof(GNUNET_HashCode))
174 * Encapsulation for encrypted messages exchanged between
175 * peers. Followed by the actual encrypted data.
177 struct EncryptedMessage
180 * Message type is either CORE_ENCRYPTED_MESSAGE.
182 struct GNUNET_MessageHeader header;
187 uint32_t reserved GNUNET_PACKED;
190 * Hash of the plaintext, used to verify message integrity;
191 * ALSO used as the IV for the symmetric cipher! Everything
192 * after this hash will be encrypted. ENCRYPTED_HEADER_SIZE
193 * must be set to the offset of the next field.
195 GNUNET_HashCode plaintext_hash;
198 * Sequence number, in network byte order. This field
199 * must be the first encrypted/decrypted field and the
200 * first byte that is hashed for the plaintext hash.
202 uint32_t sequence_number GNUNET_PACKED;
205 * Desired bandwidth (how much we should send to this
206 * peer / how much is the sender willing to receive),
207 * in bytes per minute.
209 uint32_t inbound_bpm_limit GNUNET_PACKED;
212 * Timestamp. Used to prevent reply of ancient messages
213 * (recent messages are caught with the sequence number).
215 struct GNUNET_TIME_AbsoluteNBO timestamp;
220 * We're sending an (encrypted) PING to the other peer to check if he
221 * can decrypt. The other peer should respond with a PONG with the
222 * same content, except this time encrypted with the receiver's key.
227 * Message type is either CORE_PING or CORE_PONG.
229 struct GNUNET_MessageHeader header;
232 * Random number chosen to make reply harder.
234 uint32_t challenge GNUNET_PACKED;
237 * Intended target of the PING, used primarily to check
238 * that decryption actually worked.
240 struct GNUNET_PeerIdentity target;
245 * Message transmitted to set (or update) a session key.
251 * Message type is either CORE_SET_KEY.
253 struct GNUNET_MessageHeader header;
256 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
258 int32_t sender_status GNUNET_PACKED;
261 * Purpose of the signature, will be
262 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
264 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
267 * At what time was this key created?
269 struct GNUNET_TIME_AbsoluteNBO creation_time;
272 * The encrypted session key.
274 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
277 * Who is the intended recipient?
279 struct GNUNET_PeerIdentity target;
282 * Signature of the stuff above (starting at purpose).
284 struct GNUNET_CRYPTO_RsaSignature signature;
290 * Message waiting for transmission. This struct
291 * is followed by the actual content of the message.
297 * We keep messages in a linked list (for now).
299 struct MessageEntry *next;
302 * By when are we supposed to transmit this message?
304 struct GNUNET_TIME_Absolute deadline;
307 * How important is this message to us?
309 unsigned int priority;
312 * How long is the message? (number of bytes following
313 * the "struct MessageEntry", but not including the
314 * size of "struct MessageEntry" itself!)
319 * Was this message selected for transmission in the
320 * current round? GNUNET_YES or GNUNET_NO.
330 * We keep neighbours in a linked list (for now).
332 struct Neighbour *next;
335 * Unencrypted messages destined for this peer.
337 struct MessageEntry *messages;
340 * Head of the batched, encrypted message queue (already ordered,
341 * transmit starting with the head).
343 struct MessageEntry *encrypted_head;
346 * Tail of the batched, encrypted message queue (already ordered,
347 * append new messages to tail)
349 struct MessageEntry *encrypted_tail;
352 * Handle for pending requests for transmission to this peer
353 * with the transport service. NULL if no request is pending.
355 struct GNUNET_TRANSPORT_TransmitHandle *th;
358 * Public key of the neighbour, NULL if we don't have it yet.
360 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
363 * We received a PING message before we got the "public_key"
364 * (or the SET_KEY). We keep it here until we have a key
365 * to decrypt it. NULL if no PING is pending.
367 struct PingMessage *pending_ping;
370 * Non-NULL if we are currently looking up HELLOs for this peer.
373 struct GNUNET_PEERINFO_IteratorContext *pitr;
376 * SetKeyMessage to transmit, NULL if we are not currently trying
379 struct SetKeyMessage *skm;
382 * Identity of the neighbour.
384 struct GNUNET_PeerIdentity peer;
387 * Key we use to encrypt our messages for the other peer
388 * (initialized by us when we do the handshake).
390 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
393 * Key we use to decrypt messages from the other peer
394 * (given to us by the other peer during the handshake).
396 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
399 * ID of task used for re-trying plaintext scheduling.
401 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
404 * ID of task used for re-trying SET_KEY and PING message.
406 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
409 * ID of task used for updating bandwidth quota for this neighbour.
411 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
414 * At what time did we generate our encryption key?
416 struct GNUNET_TIME_Absolute encrypt_key_created;
419 * At what time did the other peer generate the decryption key?
421 struct GNUNET_TIME_Absolute decrypt_key_created;
424 * At what time did we initially establish (as in, complete session
425 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
427 struct GNUNET_TIME_Absolute time_established;
430 * At what time did we last receive an encrypted message from the
431 * other peer? Should be zero if status != KEY_CONFIRMED.
433 struct GNUNET_TIME_Absolute last_activity;
436 * Last latency observed from this peer.
438 struct GNUNET_TIME_Relative last_latency;
441 * At what frequency are we currently re-trying SET_KEY messages?
443 struct GNUNET_TIME_Relative set_key_retry_frequency;
446 * Time of our last update to the "available_send_window".
448 struct GNUNET_TIME_Absolute last_asw_update;
451 * Time of our last update to the "available_recv_window".
453 struct GNUNET_TIME_Absolute last_arw_update;
456 * Number of bytes that we are eligible to transmit to this
457 * peer at this point. Incremented every minute by max_out_bpm,
458 * bounded by max_bpm (no back-log larger than MAX_BUF_FACT minutes,
459 * bandwidth-hogs are sampled at a frequency of about 78s!);
460 * may get negative if we have VERY high priority content.
462 long long available_send_window;
465 * How much downstream capacity of this peer has been reserved for
466 * our traffic? (Our clients can request that a certain amount of
467 * bandwidth is available for replies to them; this value is used to
468 * make sure that this reserved amount of bandwidth is actually
471 long long available_recv_window;
474 * How valueable were the messages of this peer recently?
476 unsigned long long current_preference;
479 * Bit map indicating which of the 32 sequence numbers before the last
480 * were received (good for accepting out-of-order packets and
481 * estimating reliability of the connection)
483 unsigned int last_packets_bitmap;
486 * Number of messages in the message queue for this peer.
488 unsigned int message_queue_size;
491 * last sequence number received on this connection (highest)
493 uint32_t last_sequence_number_received;
496 * last sequence number transmitted
498 uint32_t last_sequence_number_sent;
501 * Available bandwidth in for this peer (current target).
506 * Available bandwidth out for this peer (current target).
511 * Internal bandwidth limit set for this peer (initially
512 * typically set to "-1"). "bpm_out" is MAX of
513 * "bpm_out_internal_limit" and "bpm_out_external_limit".
515 uint32_t bpm_out_internal_limit;
518 * External bandwidth limit set for this peer by the
519 * peer that we are communicating with. "bpm_out" is MAX of
520 * "bpm_out_internal_limit" and "bpm_out_external_limit".
522 uint32_t bpm_out_external_limit;
525 * What was our PING challenge number (for this peer)?
527 uint32_t ping_challenge;
530 * What was the last distance to this peer as reported by the transports?
532 uint32_t last_distance;
535 * What is our connection status?
537 enum PeerStateMachine status;
543 * Data structure for each client connected to the core service.
548 * Clients are kept in a linked list.
553 * Handle for the client with the server API.
555 struct GNUNET_SERVER_Client *client_handle;
558 * Array of the types of messages this peer cares
559 * about (with "tcnt" entries). Allocated as part
560 * of this client struct, do not free!
565 * Options for messages this client cares about,
566 * see GNUNET_CORE_OPTION_ values.
571 * Number of types of incoming messages this client
572 * specifically cares about. Size of the "types" array.
582 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
587 static struct GNUNET_PeerIdentity my_identity;
592 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
597 struct GNUNET_SCHEDULER_Handle *sched;
602 const struct GNUNET_CONFIGURATION_Handle *cfg;
607 static struct GNUNET_SERVER_Handle *server;
612 static struct GNUNET_TRANSPORT_Handle *transport;
615 * Linked list of our clients.
617 static struct Client *clients;
620 * Context for notifications we need to send to our clients.
622 static struct GNUNET_SERVER_NotificationContext *notifier;
625 * We keep neighbours in a linked list (for now).
627 static struct Neighbour *neighbours;
630 * Sum of all preferences among all neighbours.
632 static unsigned long long preference_sum;
635 * Total number of neighbours we have.
637 static unsigned int neighbour_count;
640 * How much inbound bandwidth are we supposed to be using?
642 static unsigned long long bandwidth_target_in;
645 * How much outbound bandwidth are we supposed to be using?
647 static unsigned long long bandwidth_target_out;
652 * A preference value for a neighbour was update. Update
653 * the preference sum accordingly.
655 * @param inc how much was a preference value increased?
658 update_preference_sum (unsigned long long inc)
661 unsigned long long os;
664 preference_sum += inc;
665 if (preference_sum >= os)
667 /* overflow! compensate by cutting all values in half! */
672 n->current_preference /= 2;
673 preference_sum += n->current_preference;
680 * Recalculate the number of bytes we expect to
681 * receive or transmit in a given window.
683 * @param force force an update now (even if not much time has passed)
684 * @param window pointer to the byte counter (updated)
685 * @param ts pointer to the timestamp (updated)
686 * @param bpm number of bytes per minute that should
687 * be added to the window.
690 update_window (int force,
692 struct GNUNET_TIME_Absolute *ts, unsigned int bpm)
694 struct GNUNET_TIME_Relative since;
696 since = GNUNET_TIME_absolute_get_duration (*ts);
697 if ( (force == GNUNET_NO) &&
698 (since.value < 60 * 1000) )
699 return; /* not even a minute has passed */
700 *ts = GNUNET_TIME_absolute_get ();
701 *window += (bpm * since.value) / 60 / 1000;
702 if (*window > MAX_WINDOW_TIME * bpm)
703 *window = MAX_WINDOW_TIME * bpm;
708 * Find the entry for the given neighbour.
710 * @param peer identity of the neighbour
711 * @return NULL if we are not connected, otherwise the
714 static struct Neighbour *
715 find_neighbour (const struct GNUNET_PeerIdentity *peer)
717 struct Neighbour *ret;
720 while ((ret != NULL) &&
721 (0 != memcmp (&ret->peer,
722 peer, sizeof (struct GNUNET_PeerIdentity))))
729 * Send a message to one of our clients.
731 * @param client target for the message
732 * @param msg message to transmit
733 * @param can_drop could this message be dropped if the
734 * client's queue is getting too large?
737 send_to_client (struct Client *client,
738 const struct GNUNET_MessageHeader *msg,
741 #if DEBUG_CORE_CLIENT
742 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
743 "Preparing to send message of type %u to client.\n",
746 GNUNET_SERVER_notification_context_unicast (notifier,
747 client->client_handle,
754 * Send a message to all of our current clients that have
755 * the right options set.
757 * @param msg message to multicast
758 * @param can_drop can this message be discarded if the queue is too long
759 * @param options mask to use
762 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
771 if (0 != (c->options & options))
772 send_to_client (c, msg, can_drop);
779 * Handle CORE_INIT request.
782 handle_client_init (void *cls,
783 struct GNUNET_SERVER_Client *client,
784 const struct GNUNET_MessageHeader *message)
786 const struct InitMessage *im;
787 struct InitReplyMessage irm;
790 const uint16_t *types;
792 struct ConnectNotifyMessage cnm;
794 #if DEBUG_CORE_CLIENT
795 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
796 "Client connecting to core service with `%s' message\n",
799 /* check that we don't have an entry already */
803 if (client == c->client_handle)
806 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
811 msize = ntohs (message->size);
812 if (msize < sizeof (struct InitMessage))
815 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
818 GNUNET_SERVER_notification_context_add (notifier, client);
819 im = (const struct InitMessage *) message;
820 types = (const uint16_t *) &im[1];
821 msize -= sizeof (struct InitMessage);
822 c = GNUNET_malloc (sizeof (struct Client) + msize);
823 c->client_handle = client;
826 memcpy (&c[1], types, msize);
827 c->types = (uint16_t *) & c[1];
828 c->options = ntohl (im->options);
829 c->tcnt = msize / sizeof (uint16_t);
830 /* send init reply message */
831 irm.header.size = htons (sizeof (struct InitReplyMessage));
832 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
833 irm.reserved = htonl (0);
834 memcpy (&irm.publicKey,
836 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
837 #if DEBUG_CORE_CLIENT
838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
839 "Sending `%s' message to client.\n", "INIT_REPLY");
841 send_to_client (c, &irm.header, GNUNET_NO);
842 /* notify new client about existing neighbours */
843 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
844 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
848 #if DEBUG_CORE_CLIENT
849 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
850 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
852 cnm.distance = htonl (n->last_distance);
853 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
855 send_to_client (c, &cnm.header, GNUNET_NO);
858 GNUNET_SERVER_receive_done (client, GNUNET_OK);
863 * A client disconnected, clean up.
866 * @param client identification of the client
869 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
876 #if DEBUG_CORE_CLIENT
877 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
878 "Client has disconnected from core service.\n");
884 if (client == pos->client_handle)
889 prev->next = pos->next;
896 /* client never sent INIT */
901 * Handle REQUEST_INFO request.
904 handle_client_request_info (void *cls,
905 struct GNUNET_SERVER_Client *client,
906 const struct GNUNET_MessageHeader *message)
908 const struct RequestInfoMessage *rcm;
910 struct ConfigurationInfoMessage cim;
912 unsigned long long old_preference;
913 struct GNUNET_SERVER_TransmitContext *tc;
915 #if DEBUG_CORE_CLIENT
916 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
917 "Core service receives `%s' request.\n", "REQUEST_INFO");
919 rcm = (const struct RequestInfoMessage *) message;
920 n = find_neighbour (&rcm->peer);
921 memset (&cim, 0, sizeof (cim));
922 if ((n != NULL) && (n->status == PEER_STATE_KEY_CONFIRMED))
924 update_window (GNUNET_YES,
925 &n->available_send_window,
928 n->bpm_out_internal_limit = ntohl (rcm->limit_outbound_bpm);
929 n->bpm_out = GNUNET_MAX (n->bpm_out_internal_limit,
930 n->bpm_out_external_limit);
931 reserv = ntohl (rcm->reserve_inbound);
934 n->available_recv_window += reserv;
938 update_window (GNUNET_NO,
939 &n->available_recv_window,
940 &n->last_arw_update, n->bpm_in);
941 if (n->available_recv_window < reserv)
942 reserv = n->available_recv_window;
943 n->available_recv_window -= reserv;
945 old_preference = n->current_preference;
946 n->current_preference += GNUNET_ntohll(rcm->preference_change);
947 if (old_preference > n->current_preference)
949 /* overflow; cap at maximum value */
950 n->current_preference = (unsigned long long) -1;
952 update_preference_sum (n->current_preference - old_preference);
953 cim.reserved_amount = htonl (reserv);
954 cim.bpm_in = htonl (n->bpm_in);
955 cim.bpm_out = htonl (n->bpm_out);
956 cim.preference = n->current_preference;
958 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
959 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
960 cim.peer = rcm->peer;
962 #if DEBUG_CORE_CLIENT
963 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
964 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
966 tc = GNUNET_SERVER_transmit_context_create (client);
967 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
968 GNUNET_SERVER_transmit_context_run (tc,
969 GNUNET_TIME_UNIT_FOREVER_REL);
974 * Check if we have encrypted messages for the specified neighbour
975 * pending, and if so, check with the transport about sending them
978 * @param n neighbour to check.
980 static void process_encrypted_neighbour_queue (struct Neighbour *n);
984 * Function called when the transport service is ready to
985 * receive an encrypted message for the respective peer
987 * @param cls neighbour to use message from
988 * @param size number of bytes we can transmit
989 * @param buf where to copy the message
990 * @return number of bytes transmitted
993 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
995 struct Neighbour *n = cls;
996 struct MessageEntry *m;
1001 GNUNET_assert (NULL != (m = n->encrypted_head));
1002 n->encrypted_head = m->next;
1003 if (m->next == NULL)
1004 n->encrypted_tail = NULL;
1009 GNUNET_assert (size >= m->size);
1010 memcpy (cbuf, &m[1], m->size);
1012 n->available_send_window -= m->size;
1013 process_encrypted_neighbour_queue (n);
1015 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1016 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1017 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1018 ret, GNUNET_i2s (&n->peer));
1023 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1024 "Transmission for message of type %u and size %u failed\n",
1025 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1034 * Check if we have plaintext messages for the specified neighbour
1035 * pending, and if so, consider batching and encrypting them (and
1036 * then trigger processing of the encrypted queue if needed).
1038 * @param n neighbour to check.
1040 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1044 * Check if we have encrypted messages for the specified neighbour
1045 * pending, and if so, check with the transport about sending them
1048 * @param n neighbour to check.
1051 process_encrypted_neighbour_queue (struct Neighbour *n)
1053 struct MessageEntry *m;
1056 return; /* request already pending */
1057 if (n->encrypted_head == NULL)
1059 /* encrypted queue empty, try plaintext instead */
1060 process_plaintext_neighbour_queue (n);
1064 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1065 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1066 n->encrypted_head->size,
1067 GNUNET_i2s (&n->peer),
1068 GNUNET_TIME_absolute_get_remaining (n->
1069 encrypted_head->deadline).
1073 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1074 n->encrypted_head->size,
1075 n->encrypted_head->priority,
1076 GNUNET_TIME_absolute_get_remaining
1077 (n->encrypted_head->deadline),
1078 ¬ify_encrypted_transmit_ready,
1082 /* message request too large (oops) */
1084 /* discard encrypted message */
1085 GNUNET_assert (NULL != (m = n->encrypted_head));
1086 n->encrypted_head = m->next;
1087 if (m->next == NULL)
1088 n->encrypted_tail = NULL;
1090 process_encrypted_neighbour_queue (n);
1096 * Decrypt size bytes from in and write the result to out. Use the
1097 * key for inbound traffic of the given neighbour. This function does
1098 * NOT do any integrity-checks on the result.
1100 * @param n neighbour we are receiving from
1101 * @param iv initialization vector to use
1102 * @param in ciphertext
1103 * @param out plaintext
1104 * @param size size of in/out
1105 * @return GNUNET_OK on success
1108 do_decrypt (struct Neighbour *n,
1109 const GNUNET_HashCode * iv,
1110 const void *in, void *out, size_t size)
1112 if (size != (uint16_t) size)
1117 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1118 (n->status != PEER_STATE_KEY_CONFIRMED))
1120 GNUNET_break_op (0);
1121 return GNUNET_SYSERR;
1124 GNUNET_CRYPTO_aes_decrypt (in,
1128 GNUNET_CRYPTO_AesInitializationVector *) iv,
1132 return GNUNET_SYSERR;
1135 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1136 "Decrypted %u bytes from `%4s' using key %u\n",
1137 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1144 * Encrypt size bytes from in and write the result to out. Use the
1145 * key for outbound traffic of the given neighbour.
1147 * @param n neighbour we are sending to
1148 * @param iv initialization vector to use
1149 * @param in ciphertext
1150 * @param out plaintext
1151 * @param size size of in/out
1152 * @return GNUNET_OK on success
1155 do_encrypt (struct Neighbour *n,
1156 const GNUNET_HashCode * iv,
1157 const void *in, void *out, size_t size)
1159 if (size != (uint16_t) size)
1164 GNUNET_assert (size ==
1165 GNUNET_CRYPTO_aes_encrypt (in,
1169 GNUNET_CRYPTO_AesInitializationVector
1172 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1173 "Encrypted %u bytes for `%4s' using key %u\n", size,
1174 GNUNET_i2s (&n->peer), n->encrypt_key.crc32);
1181 * Select messages for transmission. This heuristic uses a combination
1182 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1183 * and priority-based discard (in case no feasible schedule exist) and
1184 * speculative optimization (defer any kind of transmission until
1185 * we either create a batch of significant size, 25% of max, or until
1186 * we are close to a deadline). Furthermore, when scheduling the
1187 * heuristic also packs as many messages into the batch as possible,
1188 * starting with those with the earliest deadline. Yes, this is fun.
1190 * @param n neighbour to select messages from
1191 * @param size number of bytes to select for transmission
1192 * @param retry_time set to the time when we should try again
1193 * (only valid if this function returns zero)
1194 * @return number of bytes selected, or 0 if we decided to
1195 * defer scheduling overall; in that case, retry_time is set.
1198 select_messages (struct Neighbour *n,
1199 size_t size, struct GNUNET_TIME_Relative *retry_time)
1201 struct MessageEntry *pos;
1202 struct MessageEntry *min;
1203 struct MessageEntry *last;
1204 unsigned int min_prio;
1205 struct GNUNET_TIME_Absolute t;
1206 struct GNUNET_TIME_Absolute now;
1209 unsigned long long slack; /* how long could we wait before missing deadlines? */
1211 int discard_low_prio;
1213 GNUNET_assert (NULL != n->messages);
1214 now = GNUNET_TIME_absolute_get ();
1215 /* last entry in linked list of messages processed */
1217 /* should we remove the entry with the lowest
1218 priority from consideration for scheduling at the
1220 discard_low_prio = GNUNET_YES;
1221 while (GNUNET_YES == discard_low_prio)
1225 discard_low_prio = GNUNET_NO;
1226 /* calculate number of bytes available for transmission at time "t" */
1227 update_window (GNUNET_NO,
1228 &n->available_send_window,
1229 &n->last_asw_update,
1231 avail = n->available_send_window;
1232 t = n->last_asw_update;
1233 /* how many bytes have we (hypothetically) scheduled so far */
1235 /* maximum time we can wait before transmitting anything
1236 and still make all of our deadlines */
1240 /* note that we use "*2" here because we want to look
1241 a bit further into the future; much more makes no
1242 sense since new message might be scheduled in the
1244 while ((pos != NULL) && (off < size * 2))
1246 if (pos->do_transmit == GNUNET_YES)
1248 /* already removed from consideration */
1252 if (discard_low_prio == GNUNET_NO)
1254 delta = pos->deadline.value;
1255 if (delta < t.value)
1258 delta = t.value - delta;
1259 avail += delta * n->bpm_out / 1000 / 60;
1260 if (avail < pos->size)
1262 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1267 /* update slack, considering both its absolute deadline
1268 and relative deadlines caused by other messages
1269 with their respective load */
1270 slack = GNUNET_MIN (slack, avail / n->bpm_out);
1271 if (pos->deadline.value < now.value)
1275 GNUNET_MIN (slack, pos->deadline.value - now.value);
1279 t.value = GNUNET_MAX (pos->deadline.value, t.value);
1280 if (pos->priority <= min_prio)
1282 /* update min for discard */
1283 min_prio = pos->priority;
1288 if (discard_low_prio)
1290 GNUNET_assert (min != NULL);
1291 /* remove lowest-priority entry from consideration */
1292 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1296 /* guard against sending "tiny" messages with large headers without
1298 if ( (slack > 1000) && (size > 4 * off) )
1300 /* less than 25% of message would be filled with
1301 deadlines still being met if we delay by one
1302 second or more; so just wait for more data */
1303 retry_time->value = slack / 2;
1304 /* reset do_transmit values for next time */
1307 pos->do_transmit = GNUNET_NO;
1312 /* select marked messages (up to size) for transmission */
1317 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1319 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1324 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1328 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1329 "Selected %u bytes of plaintext messages for transmission to `%4s'.\n",
1330 off, GNUNET_i2s (&n->peer));
1337 * Batch multiple messages into a larger buffer.
1339 * @param n neighbour to take messages from
1340 * @param buf target buffer
1341 * @param size size of buf
1342 * @param deadline set to transmission deadline for the result
1343 * @param retry_time set to the time when we should try again
1344 * (only valid if this function returns zero)
1345 * @param priority set to the priority of the batch
1346 * @return number of bytes written to buf (can be zero)
1349 batch_message (struct Neighbour *n,
1352 struct GNUNET_TIME_Absolute *deadline,
1353 struct GNUNET_TIME_Relative *retry_time,
1354 unsigned int *priority)
1356 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1357 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1358 struct MessageEntry *pos;
1359 struct MessageEntry *prev;
1360 struct MessageEntry *next;
1365 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1366 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1367 if (0 == select_messages (n, size, retry_time))
1369 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1370 "No messages selected, will try again in %llu ms\n",
1374 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1375 ntm->distance = htonl (n->last_distance);
1376 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1377 ntm->peer = n->peer;
1381 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1384 if (GNUNET_YES == pos->do_transmit)
1386 GNUNET_assert (pos->size <= size);
1387 /* do notifications */
1388 /* FIXME: track if we have *any* client that wants
1389 full notifications and only do this if that is
1391 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1393 memcpy (&ntm[1], &pos[1], pos->size);
1394 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1395 sizeof (struct GNUNET_MessageHeader));
1396 send_to_all_clients (&ntm->header,
1398 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1402 /* message too large for 'full' notifications, we do at
1403 least the 'hdr' type */
1406 sizeof (struct GNUNET_MessageHeader));
1408 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1410 send_to_all_clients (&ntm->header,
1412 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1413 /* copy for encrypted transmission */
1414 memcpy (&buf[ret], &pos[1], pos->size);
1417 *priority += pos->priority;
1419 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1420 "Adding plaintext message with deadline %llu ms to batch\n",
1421 GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1423 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1437 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1438 "Deadline for message batch is %llu ms\n",
1439 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1446 * Remove messages with deadlines that have long expired from
1449 * @param n neighbour to inspect
1452 discard_expired_messages (struct Neighbour *n)
1454 struct MessageEntry *prev;
1455 struct MessageEntry *next;
1456 struct MessageEntry *pos;
1457 struct GNUNET_TIME_Absolute now;
1458 struct GNUNET_TIME_Relative delta;
1460 now = GNUNET_TIME_absolute_get ();
1466 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1467 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1470 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1471 "Message is %llu ms past due, discarding.\n",
1488 * Signature of the main function of a task.
1490 * @param cls closure
1491 * @param tc context information (why was this task triggered now)
1494 retry_plaintext_processing (void *cls,
1495 const struct GNUNET_SCHEDULER_TaskContext *tc)
1497 struct Neighbour *n = cls;
1499 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1500 process_plaintext_neighbour_queue (n);
1505 * Send our key (and encrypted PING) to the other peer.
1507 * @param n the other peer
1509 static void send_key (struct Neighbour *n);
1513 * Check if we have plaintext messages for the specified neighbour
1514 * pending, and if so, consider batching and encrypting them (and
1515 * then trigger processing of the encrypted queue if needed).
1517 * @param n neighbour to check.
1520 process_plaintext_neighbour_queue (struct Neighbour *n)
1522 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1525 struct EncryptedMessage *em; /* encrypted message */
1526 struct EncryptedMessage *ph; /* plaintext header */
1527 struct MessageEntry *me;
1528 unsigned int priority;
1529 struct GNUNET_TIME_Absolute deadline;
1530 struct GNUNET_TIME_Relative retry_time;
1532 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1534 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1535 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1539 case PEER_STATE_DOWN:
1542 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1543 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1544 GNUNET_i2s(&n->peer));
1547 case PEER_STATE_KEY_SENT:
1548 GNUNET_assert (n->retry_set_key_task !=
1549 GNUNET_SCHEDULER_NO_TASK);
1551 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1552 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1553 GNUNET_i2s(&n->peer));
1556 case PEER_STATE_KEY_RECEIVED:
1557 GNUNET_assert (n->retry_set_key_task !=
1558 GNUNET_SCHEDULER_NO_TASK);
1560 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1561 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1562 GNUNET_i2s(&n->peer));
1565 case PEER_STATE_KEY_CONFIRMED:
1566 /* ready to continue */
1569 discard_expired_messages (n);
1570 if (n->messages == NULL)
1573 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1574 "Plaintext message queue for `%4s' is empty.\n",
1575 GNUNET_i2s(&n->peer));
1577 return; /* no pending messages */
1579 if (n->encrypted_head != NULL)
1582 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1583 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1584 GNUNET_i2s(&n->peer));
1586 return; /* wait for messages already encrypted to be
1589 ph = (struct EncryptedMessage *) pbuf;
1590 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1592 used = sizeof (struct EncryptedMessage);
1593 used += batch_message (n,
1595 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1596 &deadline, &retry_time, &priority);
1597 if (used == sizeof (struct EncryptedMessage))
1600 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1601 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1602 GNUNET_i2s(&n->peer));
1604 /* no messages selected for sending, try again later... */
1605 n->retry_plaintext_task =
1606 GNUNET_SCHEDULER_add_delayed (sched,
1608 &retry_plaintext_processing, n);
1611 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1612 ph->inbound_bpm_limit = htonl (n->bpm_in);
1613 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1615 /* setup encryption message header */
1616 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1617 me->deadline = deadline;
1618 me->priority = priority;
1620 em = (struct EncryptedMessage *) &me[1];
1621 em->header.size = htons (used);
1622 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1623 em->reserved = htonl (0);
1624 esize = used - ENCRYPTED_HEADER_SIZE;
1625 GNUNET_CRYPTO_hash (&ph->sequence_number, esize, &em->plaintext_hash);
1628 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1629 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
1631 GNUNET_i2s(&n->peer),
1632 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
1634 GNUNET_assert (GNUNET_OK ==
1636 &em->plaintext_hash,
1637 &ph->sequence_number,
1638 &em->sequence_number, esize));
1639 /* append to transmission list */
1640 if (n->encrypted_tail == NULL)
1641 n->encrypted_head = me;
1643 n->encrypted_tail->next = me;
1644 n->encrypted_tail = me;
1645 process_encrypted_neighbour_queue (n);
1650 * Handle CORE_SEND request.
1653 * @param client the client issuing the request
1654 * @param message the "struct SendMessage"
1657 handle_client_send (void *cls,
1658 struct GNUNET_SERVER_Client *client,
1659 const struct GNUNET_MessageHeader *message);
1663 * Function called to notify us that we either succeeded
1664 * or failed to connect (at the transport level) to another
1665 * peer. We should either free the message we were asked
1666 * to transmit or re-try adding it to the queue.
1668 * @param cls closure
1669 * @param size number of bytes available in buf
1670 * @param buf where the callee should write the message
1671 * @return number of bytes written to buf
1674 send_connect_continuation (void *cls, size_t size, void *buf)
1676 struct SendMessage *sm = cls;
1681 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1682 "Asked to send message to disconnected peer `%4s' and connection failed. Discarding message.\n",
1683 GNUNET_i2s (&sm->peer));
1689 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1690 "Connection to peer `%4s' succeeded, retrying original transmission request\n",
1691 GNUNET_i2s (&sm->peer));
1693 handle_client_send (NULL, NULL, &sm->header);
1700 * Handle CORE_SEND request.
1703 * @param client the client issuing the request
1704 * @param message the "struct SendMessage"
1707 handle_client_send (void *cls,
1708 struct GNUNET_SERVER_Client *client,
1709 const struct GNUNET_MessageHeader *message)
1711 const struct SendMessage *sm;
1712 struct SendMessage *smc;
1713 const struct GNUNET_MessageHeader *mh;
1714 struct Neighbour *n;
1715 struct MessageEntry *prev;
1716 struct MessageEntry *pos;
1717 struct MessageEntry *e;
1718 struct MessageEntry *min_prio_entry;
1719 struct MessageEntry *min_prio_prev;
1720 unsigned int min_prio;
1721 unsigned int queue_size;
1724 msize = ntohs (message->size);
1726 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
1730 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1733 sm = (const struct SendMessage *) message;
1734 msize -= sizeof (struct SendMessage);
1735 mh = (const struct GNUNET_MessageHeader *) &sm[1];
1736 if (msize != ntohs (mh->size))
1740 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1743 n = find_neighbour (&sm->peer);
1747 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1748 "Core received `%s' request for `%4s', will try to establish connection within %llu ms\n",
1750 GNUNET_i2s (&sm->peer),
1751 GNUNET_TIME_absolute_get_remaining
1752 (GNUNET_TIME_absolute_ntoh(sm->deadline)).value);
1754 msize += sizeof (struct SendMessage);
1755 /* ask transport to connect to the peer */
1756 smc = GNUNET_malloc (msize);
1757 memcpy (smc, sm, msize);
1759 GNUNET_TRANSPORT_notify_transmit_ready (transport,
1762 GNUNET_TIME_absolute_get_remaining
1763 (GNUNET_TIME_absolute_ntoh
1765 &send_connect_continuation,
1768 /* transport has already a request pending for this peer! */
1770 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1771 "Dropped second message destined for `%4s' since connection is still down.\n",
1772 GNUNET_i2s(&sm->peer));
1777 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1781 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1782 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
1785 GNUNET_i2s (&sm->peer));
1787 /* bound queue size */
1788 discard_expired_messages (n);
1789 min_prio = (unsigned int) -1;
1790 min_prio_entry = NULL;
1791 min_prio_prev = NULL;
1797 if (pos->priority < min_prio)
1799 min_prio_entry = pos;
1800 min_prio_prev = prev;
1801 min_prio = pos->priority;
1807 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1810 if (ntohl(sm->priority) <= min_prio)
1812 /* discard new entry */
1814 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1815 "Queue full, discarding new request\n");
1818 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1821 /* discard "min_prio_entry" */
1823 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1824 "Queue full, discarding existing older request\n");
1826 if (min_prio_prev == NULL)
1827 n->messages = min_prio_entry->next;
1829 min_prio_prev->next = min_prio_entry->next;
1830 GNUNET_free (min_prio_entry);
1834 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1835 "Adding transmission request for `%4s' to queue\n",
1836 GNUNET_i2s (&sm->peer));
1838 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
1839 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
1840 e->priority = ntohl (sm->priority);
1842 memcpy (&e[1], mh, msize);
1844 /* insert, keep list sorted by deadline */
1847 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
1858 /* consider scheduling now */
1859 process_plaintext_neighbour_queue (n);
1861 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1866 * Handle CORE_REQUEST_CONNECT request.
1869 * @param client the client issuing the request
1870 * @param message the "struct ConnectMessage"
1873 handle_client_request_connect (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);
1883 return; /* already connected, or at least trying */
1885 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1886 "Core received `%s' request for `%4s', will try to establish connection\n",
1888 GNUNET_i2s (&cm->peer));
1890 /* ask transport to connect to the peer */
1891 /* FIXME: timeout zero OK? need for cancellation? */
1892 GNUNET_TRANSPORT_notify_transmit_ready (transport,
1895 GNUNET_TIME_UNIT_ZERO,
1902 * List of handlers for the messages understood by this
1905 static struct GNUNET_SERVER_MessageHandler handlers[] = {
1906 {&handle_client_init, NULL,
1907 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
1908 {&handle_client_request_info, NULL,
1909 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
1910 sizeof (struct RequestInfoMessage)},
1911 {&handle_client_send, NULL,
1912 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
1913 {&handle_client_request_connect, NULL,
1914 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
1915 sizeof (struct ConnectMessage)},
1921 * Task that will retry "send_key" if our previous attempt failed
1925 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1927 struct Neighbour *n = cls;
1929 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1930 n->set_key_retry_frequency =
1931 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1937 * PEERINFO is giving us a HELLO for a peer. Add the public key to
1938 * the neighbour's struct and retry send_key. Or, if we did not get a
1939 * HELLO, just do nothing.
1942 * @param peer the peer for which this is the HELLO
1943 * @param hello HELLO message of that peer
1944 * @param trust amount of trust we currently have in that peer
1947 process_hello_retry_send_key (void *cls,
1948 const struct GNUNET_PeerIdentity *peer,
1949 const struct GNUNET_HELLO_Message *hello,
1952 struct Neighbour *n = cls;
1957 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1958 "Entered process_hello_retry_send_key Peer is null!\n");
1961 if (n->public_key != NULL)
1964 n->retry_set_key_task
1965 = GNUNET_SCHEDULER_add_delayed (sched,
1966 n->set_key_retry_frequency,
1967 &set_key_retry_task, n);
1972 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1973 "process_hello_retry_send_key for peer %s\n",
1976 if (n->public_key != NULL)
1979 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1980 "already have public key for peer %s!! (so why are we here?)\n",
1987 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1988 "Received new `%s' message for `%4s', initiating key exchange.\n",
1993 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1994 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
1996 GNUNET_free (n->public_key);
1997 n->public_key = NULL;
1999 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2000 "GNUNET_HELLO_get_key returned awfully\n");
2008 * Send our key (and encrypted PING) to the other peer.
2010 * @param n the other peer
2013 send_key (struct Neighbour *n)
2015 struct SetKeyMessage *sm;
2016 struct MessageEntry *me;
2017 struct PingMessage pp;
2018 struct PingMessage *pm;
2020 if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2024 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2025 "Key exchange in progress with `%4s'.\n",
2026 GNUNET_i2s (&n->peer));
2028 return; /* already in progress */
2032 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2033 "Asked to perform key exchange with `%4s'.\n",
2034 GNUNET_i2s (&n->peer));
2036 if (n->public_key == NULL)
2038 /* lookup n's public key, then try again */
2040 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2041 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2042 GNUNET_i2s (&n->peer));
2044 GNUNET_assert (n->pitr == NULL);
2046 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2050 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2051 &process_hello_retry_send_key, n);
2054 /* first, set key message */
2055 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2056 sizeof (struct SetKeyMessage));
2057 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2058 me->priority = SET_KEY_PRIORITY;
2059 me->size = sizeof (struct SetKeyMessage);
2060 if (n->encrypted_head == NULL)
2061 n->encrypted_head = me;
2063 n->encrypted_tail->next = me;
2064 n->encrypted_tail = me;
2065 sm = (struct SetKeyMessage *) &me[1];
2066 sm->header.size = htons (sizeof (struct SetKeyMessage));
2067 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2068 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2069 PEER_STATE_KEY_SENT : n->status));
2071 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2072 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2073 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2074 sizeof (struct GNUNET_PeerIdentity));
2075 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2076 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2077 sm->target = n->peer;
2078 GNUNET_assert (GNUNET_OK ==
2079 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2081 GNUNET_CRYPTO_AesSessionKey),
2083 &sm->encrypted_key));
2084 GNUNET_assert (GNUNET_OK ==
2085 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2088 /* second, encrypted PING message */
2089 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2090 sizeof (struct PingMessage));
2091 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2092 me->priority = PING_PRIORITY;
2093 me->size = sizeof (struct PingMessage);
2094 n->encrypted_tail->next = me;
2095 n->encrypted_tail = me;
2096 pm = (struct PingMessage *) &me[1];
2097 pm->header.size = htons (sizeof (struct PingMessage));
2098 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2099 pp.challenge = htonl (n->ping_challenge);
2100 pp.target = n->peer;
2102 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2103 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2104 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2105 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2106 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2108 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2111 &n->peer.hashPubKey,
2114 sizeof (struct PingMessage) -
2115 sizeof (struct GNUNET_MessageHeader));
2119 case PEER_STATE_DOWN:
2120 n->status = PEER_STATE_KEY_SENT;
2122 case PEER_STATE_KEY_SENT:
2124 case PEER_STATE_KEY_RECEIVED:
2126 case PEER_STATE_KEY_CONFIRMED:
2133 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2134 "Have %llu ms left for `%s' transmission.\n",
2135 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2138 /* trigger queue processing */
2139 process_encrypted_neighbour_queue (n);
2140 if (n->status != PEER_STATE_KEY_CONFIRMED)
2142 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task);
2143 n->retry_set_key_task
2144 = GNUNET_SCHEDULER_add_delayed (sched,
2145 n->set_key_retry_frequency,
2146 &set_key_retry_task, n);
2152 * We received a SET_KEY message. Validate and update
2153 * our key material and status.
2155 * @param n the neighbour from which we received message m
2156 * @param m the set key message we received
2159 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2163 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2164 * the neighbour's struct and retry handling the set_key message. Or,
2165 * if we did not get a HELLO, just free the set key message.
2167 * @param cls pointer to the set key message
2168 * @param peer the peer for which this is the HELLO
2169 * @param hello HELLO message of that peer
2170 * @param trust amount of trust we currently have in that peer
2173 process_hello_retry_handle_set_key (void *cls,
2174 const struct GNUNET_PeerIdentity *peer,
2175 const struct GNUNET_HELLO_Message *hello,
2178 struct Neighbour *n = cls;
2179 struct SetKeyMessage *sm = n->skm;
2188 if (n->public_key != NULL)
2189 return; /* multiple HELLOs match!? */
2191 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2192 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2194 GNUNET_break_op (0);
2195 GNUNET_free (n->public_key);
2196 n->public_key = NULL;
2200 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2201 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2202 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2204 handle_set_key (n, sm);
2209 * We received a PING message. Validate and transmit
2212 * @param n sender of the PING
2213 * @param m the encrypted PING message itself
2216 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2218 struct PingMessage t;
2219 struct PingMessage *tp;
2220 struct MessageEntry *me;
2223 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2224 "Core service receives `%s' request from `%4s'.\n",
2225 "PING", GNUNET_i2s (&n->peer));
2229 &my_identity.hashPubKey,
2232 sizeof (struct PingMessage) -
2233 sizeof (struct GNUNET_MessageHeader)))
2236 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2237 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2239 GNUNET_i2s (&t.target),
2240 ntohl (t.challenge), n->decrypt_key.crc32);
2241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2242 "Target of `%s' request is `%4s'.\n",
2243 "PING", GNUNET_i2s (&t.target));
2245 if (0 != memcmp (&t.target,
2246 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2248 GNUNET_break_op (0);
2251 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2252 sizeof (struct PingMessage));
2253 if (n->encrypted_tail != NULL)
2254 n->encrypted_tail->next = me;
2257 n->encrypted_tail = me;
2258 n->encrypted_head = me;
2260 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2261 me->priority = PONG_PRIORITY;
2262 me->size = sizeof (struct PingMessage);
2263 tp = (struct PingMessage *) &me[1];
2264 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2265 tp->header.size = htons (sizeof (struct PingMessage));
2267 &my_identity.hashPubKey,
2270 sizeof (struct PingMessage) -
2271 sizeof (struct GNUNET_MessageHeader));
2273 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2274 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2275 ntohl (t.challenge), n->encrypt_key.crc32);
2277 /* trigger queue processing */
2278 process_encrypted_neighbour_queue (n);
2283 * We received a SET_KEY message. Validate and update
2284 * our key material and status.
2286 * @param n the neighbour from which we received message m
2287 * @param m the set key message we received
2290 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2292 struct SetKeyMessage *m_cpy;
2293 struct GNUNET_TIME_Absolute t;
2294 struct GNUNET_CRYPTO_AesSessionKey k;
2295 struct PingMessage *ping;
2296 enum PeerStateMachine sender_status;
2299 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2300 "Core service receives `%s' request from `%4s'.\n",
2301 "SET_KEY", GNUNET_i2s (&n->peer));
2303 if (n->public_key == NULL)
2306 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2307 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2309 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2310 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2311 /* lookup n's public key, then try again */
2312 GNUNET_assert (n->pitr == NULL);
2313 GNUNET_assert (n->skm == NULL);
2315 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2319 GNUNET_TIME_UNIT_MINUTES,
2320 &process_hello_retry_handle_set_key, n);
2323 if (0 != memcmp (&m->target,
2325 sizeof (struct GNUNET_PeerIdentity)))
2327 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2328 _("Received `%s' message that was not for me. Ignoring.\n"));
2331 if ((ntohl (m->purpose.size) !=
2332 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2333 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2334 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2335 sizeof (struct GNUNET_PeerIdentity)) ||
2337 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2338 &m->purpose, &m->signature, n->public_key)))
2340 /* invalid signature */
2341 GNUNET_break_op (0);
2344 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2345 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2346 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2347 (t.value < n->decrypt_key_created.value))
2349 /* this could rarely happen due to massive re-ordering of
2350 messages on the network level, but is most likely either
2351 a bug or some adversary messing with us. Report. */
2352 GNUNET_break_op (0);
2356 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
2358 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2361 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2362 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2363 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2365 /* failed to decrypt !? */
2366 GNUNET_break_op (0);
2371 if (n->decrypt_key_created.value != t.value)
2373 /* fresh key, reset sequence numbers */
2374 n->last_sequence_number_received = 0;
2375 n->last_packets_bitmap = 0;
2376 n->decrypt_key_created = t;
2378 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2381 case PEER_STATE_DOWN:
2382 n->status = PEER_STATE_KEY_RECEIVED;
2384 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2385 "Responding to `%s' with my own key.\n", "SET_KEY");
2389 case PEER_STATE_KEY_SENT:
2390 case PEER_STATE_KEY_RECEIVED:
2391 n->status = PEER_STATE_KEY_RECEIVED;
2392 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2393 (sender_status != PEER_STATE_KEY_CONFIRMED))
2396 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2397 "Responding to `%s' with my own key (other peer has status %u).\n",
2398 "SET_KEY", sender_status);
2403 case PEER_STATE_KEY_CONFIRMED:
2404 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2405 (sender_status != PEER_STATE_KEY_CONFIRMED))
2408 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2409 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2410 "SET_KEY", sender_status);
2419 if (n->pending_ping != NULL)
2421 ping = n->pending_ping;
2422 n->pending_ping = NULL;
2423 handle_ping (n, ping);
2430 * We received a PONG message. Validate and update our status.
2432 * @param n sender of the PONG
2433 * @param m the encrypted PONG message itself
2436 handle_pong (struct Neighbour *n, const struct PingMessage *m)
2438 struct PingMessage t;
2439 struct ConnectNotifyMessage cnm;
2442 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2443 "Core service receives `%s' request from `%4s'.\n",
2444 "PONG", GNUNET_i2s (&n->peer));
2448 &n->peer.hashPubKey,
2451 sizeof (struct PingMessage) -
2452 sizeof (struct GNUNET_MessageHeader)))
2455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2456 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2458 GNUNET_i2s (&t.target),
2459 ntohl (t.challenge), n->decrypt_key.crc32);
2461 if ((0 != memcmp (&t.target,
2463 sizeof (struct GNUNET_PeerIdentity))) ||
2464 (n->ping_challenge != ntohl (t.challenge)))
2466 /* PONG malformed */
2468 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2469 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2470 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2471 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2472 "Received malformed `%s' received from `%4s' with challenge %u\n",
2473 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2475 GNUNET_break_op (0);
2480 case PEER_STATE_DOWN:
2481 GNUNET_break (0); /* should be impossible */
2483 case PEER_STATE_KEY_SENT:
2484 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2486 case PEER_STATE_KEY_RECEIVED:
2487 n->status = PEER_STATE_KEY_CONFIRMED;
2489 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2490 "Confirmed key via %s for peer %s\n",
2491 "PONG", GNUNET_i2s (&n->peer));
2493 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2495 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2496 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2498 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2499 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2500 cnm.distance = htonl (n->last_distance);
2501 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2503 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2504 process_encrypted_neighbour_queue (n);
2506 case PEER_STATE_KEY_CONFIRMED:
2507 /* duplicate PONG? */
2517 * Send a P2P message to a client.
2519 * @param sender who sent us the message?
2520 * @param client who should we give the message to?
2521 * @param m contains the message to transmit
2522 * @param msize number of bytes in buf to transmit
2525 send_p2p_message_to_client (struct Neighbour *sender,
2526 struct Client *client,
2527 const void *m, size_t msize)
2529 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2530 struct NotifyTrafficMessage *ntm;
2533 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2534 "Core service passes message from `%4s' of type %u to client.\n",
2535 GNUNET_i2s(&sender->peer),
2536 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2538 ntm = (struct NotifyTrafficMessage *) buf;
2539 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2540 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2541 ntm->distance = htonl (sender->last_distance);
2542 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
2543 ntm->peer = sender->peer;
2544 memcpy (&ntm[1], m, msize);
2545 send_to_client (client, &ntm->header, GNUNET_YES);
2550 * Deliver P2P message to interested clients.
2552 * @param sender who sent us the message?
2553 * @param m the message
2554 * @param msize size of the message (including header)
2557 deliver_message (struct Neighbour *sender,
2558 const struct GNUNET_MessageHeader *m, size_t msize)
2560 struct Client *cpos;
2565 type = ntohs (m->type);
2567 while (cpos != NULL)
2569 deliver_full = GNUNET_NO;
2570 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
2571 deliver_full = GNUNET_YES;
2574 for (tpos = 0; tpos < cpos->tcnt; tpos++)
2576 if (type != cpos->types[tpos])
2578 deliver_full = GNUNET_YES;
2582 if (GNUNET_YES == deliver_full)
2583 send_p2p_message_to_client (sender, cpos, m, msize);
2584 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2585 send_p2p_message_to_client (sender, cpos, m,
2586 sizeof (struct GNUNET_MessageHeader));
2593 * Align P2P message and then deliver to interested clients.
2595 * @param sender who sent us the message?
2596 * @param buffer unaligned (!) buffer containing message
2597 * @param msize size of the message (including header)
2600 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
2604 /* TODO: call to statistics? */
2605 memcpy (abuf, buffer, msize);
2606 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
2611 * Deliver P2P messages to interested clients.
2613 * @param sender who sent us the message?
2614 * @param buffer buffer containing messages, can be modified
2615 * @param buffer_size size of the buffer (overall)
2616 * @param offset offset where messages in the buffer start
2619 deliver_messages (struct Neighbour *sender,
2620 const char *buffer, size_t buffer_size, size_t offset)
2622 struct GNUNET_MessageHeader *mhp;
2623 struct GNUNET_MessageHeader mh;
2627 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
2629 if (0 != offset % sizeof (uint16_t))
2631 /* outch, need to copy to access header */
2632 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
2637 /* can access header directly */
2638 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
2640 msize = ntohs (mhp->size);
2641 if (msize + offset > buffer_size)
2643 /* malformed message, header says it is larger than what
2644 would fit into the overall buffer */
2645 GNUNET_break_op (0);
2648 #if HAVE_UNALIGNED_64_ACCESS
2649 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
2651 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
2653 if (GNUNET_YES == need_align)
2654 align_and_deliver (sender, &buffer[offset], msize);
2656 deliver_message (sender,
2657 (const struct GNUNET_MessageHeader *)
2658 &buffer[offset], msize);
2665 * We received an encrypted message. Decrypt, validate and
2666 * pass on to the appropriate clients.
2669 handle_encrypted_message (struct Neighbour *n,
2670 const struct EncryptedMessage *m)
2672 size_t size = ntohs (m->header.size);
2674 struct EncryptedMessage *pt; /* plaintext */
2678 struct GNUNET_TIME_Absolute t;
2681 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2682 "Core service receives `%s' request from `%4s'.\n",
2683 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
2689 &m->sequence_number,
2690 &buf[ENCRYPTED_HEADER_SIZE], size - ENCRYPTED_HEADER_SIZE))
2692 pt = (struct EncryptedMessage *) buf;
2695 GNUNET_CRYPTO_hash (&pt->sequence_number,
2696 size - ENCRYPTED_HEADER_SIZE, &ph);
2697 if (0 != memcmp (&ph, &m->plaintext_hash, sizeof (GNUNET_HashCode)))
2699 /* checksum failed */
2700 GNUNET_break_op (0);
2704 /* validate sequence number */
2705 snum = ntohl (pt->sequence_number);
2706 if (n->last_sequence_number_received == snum)
2708 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2709 "Received duplicate message, ignoring.\n");
2710 /* duplicate, ignore */
2713 if ((n->last_sequence_number_received > snum) &&
2714 (n->last_sequence_number_received - snum > 32))
2716 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2717 "Received ancient out of sequence message, ignoring.\n");
2718 /* ancient out of sequence, ignore */
2721 if (n->last_sequence_number_received > snum)
2723 unsigned int rotbit =
2724 1 << (n->last_sequence_number_received - snum - 1);
2725 if ((n->last_packets_bitmap & rotbit) != 0)
2727 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2728 "Received duplicate message, ignoring.\n");
2729 /* duplicate, ignore */
2732 n->last_packets_bitmap |= rotbit;
2734 if (n->last_sequence_number_received < snum)
2736 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
2737 n->last_sequence_number_received = snum;
2740 /* check timestamp */
2741 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
2742 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
2744 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2746 ("Message received far too old (%llu ms). Content ignored.\n"),
2747 GNUNET_TIME_absolute_get_duration (t).value);
2751 /* process decrypted message(s) */
2752 update_window (GNUNET_YES,
2753 &n->available_send_window,
2754 &n->last_asw_update,
2756 n->bpm_out_external_limit = ntohl (pt->inbound_bpm_limit);
2757 n->bpm_out = GNUNET_MAX (n->bpm_out_external_limit,
2758 n->bpm_out_internal_limit);
2759 n->last_activity = GNUNET_TIME_absolute_get ();
2760 off = sizeof (struct EncryptedMessage);
2761 deliver_messages (n, buf, size, off);
2766 * Function called by the transport for each received message.
2768 * @param cls closure
2769 * @param peer (claimed) identity of the other peer
2770 * @param message the message
2771 * @param latency estimated latency for communicating with the
2772 * given peer (round-trip)
2773 * @param distance in overlay hops, as given by transport plugin
2776 handle_transport_receive (void *cls,
2777 const struct GNUNET_PeerIdentity *peer,
2778 const struct GNUNET_MessageHeader *message,
2779 struct GNUNET_TIME_Relative latency,
2780 unsigned int distance)
2782 struct Neighbour *n;
2783 struct GNUNET_TIME_Absolute now;
2789 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2790 "Received message of type %u from `%4s', demultiplexing.\n",
2791 ntohs (message->type), GNUNET_i2s (peer));
2793 n = find_neighbour (peer);
2799 n->last_latency = latency;
2800 n->last_distance = distance;
2801 up = (n->status == PEER_STATE_KEY_CONFIRMED);
2802 type = ntohs (message->type);
2803 size = ntohs (message->size);
2806 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
2807 if (size != sizeof (struct SetKeyMessage))
2809 GNUNET_break_op (0);
2812 handle_set_key (n, (const struct SetKeyMessage *) message);
2814 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
2815 if (size < sizeof (struct EncryptedMessage) +
2816 sizeof (struct GNUNET_MessageHeader))
2818 GNUNET_break_op (0);
2821 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2822 (n->status != PEER_STATE_KEY_CONFIRMED))
2824 GNUNET_break_op (0);
2827 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
2829 case GNUNET_MESSAGE_TYPE_CORE_PING:
2830 if (size != sizeof (struct PingMessage))
2832 GNUNET_break_op (0);
2835 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2836 (n->status != PEER_STATE_KEY_CONFIRMED))
2839 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2840 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
2841 "PING", GNUNET_i2s (&n->peer));
2843 GNUNET_free_non_null (n->pending_ping);
2844 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
2845 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
2848 handle_ping (n, (const struct PingMessage *) message);
2850 case GNUNET_MESSAGE_TYPE_CORE_PONG:
2851 if (size != sizeof (struct PingMessage))
2853 GNUNET_break_op (0);
2856 if ((n->status != PEER_STATE_KEY_SENT) &&
2857 (n->status != PEER_STATE_KEY_RECEIVED) &&
2858 (n->status != PEER_STATE_KEY_CONFIRMED))
2860 /* could not decrypt pong, oops! */
2861 GNUNET_break_op (0);
2864 handle_pong (n, (const struct PingMessage *) message);
2867 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2868 _("Unsupported message of type %u received.\n"), type);
2871 if (n->status == PEER_STATE_KEY_CONFIRMED)
2873 now = GNUNET_TIME_absolute_get ();
2874 n->last_activity = now;
2876 n->time_established = now;
2882 * Function that recalculates the bandwidth quota for the
2883 * given neighbour and transmits it to the transport service.
2885 * @param cls neighbour for the quota update
2889 neighbour_quota_update (void *cls,
2890 const struct GNUNET_SCHEDULER_TaskContext *tc);
2894 * Schedule the task that will recalculate the bandwidth
2895 * quota for this peer (and possibly force a disconnect of
2896 * idle peers by calculating a bandwidth of zero).
2899 schedule_quota_update (struct Neighbour *n)
2901 GNUNET_assert (n->quota_update_task ==
2902 GNUNET_SCHEDULER_NO_TASK);
2903 n->quota_update_task
2904 = GNUNET_SCHEDULER_add_delayed (sched,
2905 QUOTA_UPDATE_FREQUENCY,
2906 &neighbour_quota_update,
2912 * Function that recalculates the bandwidth quota for the
2913 * given neighbour and transmits it to the transport service.
2915 * @param cls neighbour for the quota update
2919 neighbour_quota_update (void *cls,
2920 const struct GNUNET_SCHEDULER_TaskContext *tc)
2922 struct Neighbour *n = cls;
2926 unsigned long long distributable;
2928 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
2929 /* calculate relative preference among all neighbours;
2930 divides by a bit more to avoid division by zero AND to
2931 account for possibility of new neighbours joining any time
2932 AND to convert to double... */
2933 pref_rel = n->current_preference / (1.0 + preference_sum);
2935 if (bandwidth_target_out > neighbour_count * MIN_BPM_PER_PEER)
2936 distributable = bandwidth_target_out - neighbour_count * MIN_BPM_PER_PEER;
2937 share = distributable * pref_rel;
2938 q_in = MIN_BPM_PER_PEER + (unsigned long long) share;
2939 /* check if we want to disconnect for good due to inactivity */
2940 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
2941 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
2944 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2945 "Forcing disconnect of `%4s' due to inactivity (?).\n",
2946 GNUNET_i2s (&n->peer));
2948 q_in = 0; /* force disconnect */
2950 if ( (n->bpm_in + MIN_BPM_CHANGE < q_in) ||
2951 (n->bpm_in - MIN_BPM_CHANGE > q_in) )
2954 GNUNET_TRANSPORT_set_quota (transport,
2958 GNUNET_TIME_UNIT_FOREVER_REL,
2961 schedule_quota_update (n);
2966 * Function called by transport to notify us that
2967 * a peer connected to us (on the network level).
2969 * @param cls closure
2970 * @param peer the peer that connected
2971 * @param latency current latency of the connection
2972 * @param distance in overlay hops, as given by transport plugin
2975 handle_transport_notify_connect (void *cls,
2976 const struct GNUNET_PeerIdentity *peer,
2977 struct GNUNET_TIME_Relative latency,
2978 unsigned int distance)
2980 struct Neighbour *n;
2981 struct GNUNET_TIME_Absolute now;
2982 struct ConnectNotifyMessage cnm;
2984 n = find_neighbour (peer);
2987 /* duplicate connect notification!? */
2991 now = GNUNET_TIME_absolute_get ();
2992 n = GNUNET_malloc (sizeof (struct Neighbour));
2993 n->next = neighbours;
2997 n->last_latency = latency;
2998 n->last_distance = distance;
2999 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
3000 n->encrypt_key_created = now;
3001 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
3002 n->last_activity = now;
3003 n->last_asw_update = now;
3004 n->last_arw_update = now;
3005 n->bpm_in = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
3006 n->bpm_out = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
3007 n->bpm_out_internal_limit = (uint32_t) - 1;
3008 n->bpm_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
3009 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3012 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3013 "Received connection from `%4s'.\n",
3014 GNUNET_i2s (&n->peer));
3016 schedule_quota_update (n);
3017 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3018 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3019 cnm.distance = htonl (n->last_distance);
3020 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3022 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3028 * Free the given entry for the neighbour (it has
3029 * already been removed from the list at this point).
3031 * @param n neighbour to free
3034 free_neighbour (struct Neighbour *n)
3036 struct MessageEntry *m;
3038 if (n->pitr != NULL)
3040 GNUNET_PEERINFO_iterate_cancel (n->pitr);
3045 GNUNET_free (n->skm);
3048 while (NULL != (m = n->messages))
3050 n->messages = m->next;
3053 while (NULL != (m = n->encrypted_head))
3055 n->encrypted_head = m->next;
3059 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
3060 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
3061 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
3062 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3063 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
3064 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
3065 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
3066 GNUNET_free_non_null (n->public_key);
3067 GNUNET_free_non_null (n->pending_ping);
3073 * Function called by transport telling us that a peer
3076 * @param cls closure
3077 * @param peer the peer that disconnected
3080 handle_transport_notify_disconnect (void *cls,
3081 const struct GNUNET_PeerIdentity *peer)
3083 struct DisconnectNotifyMessage cnm;
3084 struct Neighbour *n;
3085 struct Neighbour *p;
3088 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3089 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3093 while ((n != NULL) &&
3094 (0 != memcmp (&n->peer, peer, sizeof (struct GNUNET_PeerIdentity))))
3105 neighbours = n->next;
3108 GNUNET_assert (neighbour_count > 0);
3110 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3111 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3113 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3119 * Last task run during shutdown. Disconnects us from
3123 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3125 struct Neighbour *n;
3129 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3130 "Core service shutting down.\n");
3132 GNUNET_assert (transport != NULL);
3133 GNUNET_TRANSPORT_disconnect (transport);
3135 while (NULL != (n = neighbours))
3137 neighbours = n->next;
3138 GNUNET_assert (neighbour_count > 0);
3142 GNUNET_SERVER_notification_context_destroy (notifier);
3144 while (NULL != (c = clients))
3145 handle_client_disconnect (NULL, c->client_handle);
3146 if (my_private_key != NULL)
3147 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3152 * Initiate core service.
3154 * @param cls closure
3155 * @param s scheduler to use
3156 * @param serv the initialized server
3157 * @param c configuration to use
3161 struct GNUNET_SCHEDULER_Handle *s,
3162 struct GNUNET_SERVER_Handle *serv,
3163 const struct GNUNET_CONFIGURATION_Handle *c)
3166 unsigned long long qin;
3167 unsigned long long qout;
3168 unsigned long long tneigh;
3174 /* parse configuration */
3177 GNUNET_CONFIGURATION_get_value_number (c,
3180 &bandwidth_target_in)) ||
3182 GNUNET_CONFIGURATION_get_value_number (c,
3185 &bandwidth_target_out)) ||
3187 GNUNET_CONFIGURATION_get_value_filename (c,
3189 "HOSTKEY", &keyfile)))
3191 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3193 ("Core service is lacking key configuration settings. Exiting.\n"));
3194 GNUNET_SCHEDULER_shutdown (s);
3197 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3198 GNUNET_free (keyfile);
3199 if (my_private_key == NULL)
3201 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3202 _("Core service could not access hostkey. Exiting.\n"));
3203 GNUNET_SCHEDULER_shutdown (s);
3206 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3207 GNUNET_CRYPTO_hash (&my_public_key,
3208 sizeof (my_public_key), &my_identity.hashPubKey);
3209 /* setup notification */
3211 notifier = GNUNET_SERVER_notification_context_create (server,
3213 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3214 /* setup transport connection */
3215 transport = GNUNET_TRANSPORT_connect (sched,
3218 &handle_transport_receive,
3219 &handle_transport_notify_connect,
3220 &handle_transport_notify_disconnect);
3221 GNUNET_assert (NULL != transport);
3222 GNUNET_SCHEDULER_add_delayed (sched,
3223 GNUNET_TIME_UNIT_FOREVER_REL,
3224 &cleaning_task, NULL);
3225 /* process client requests */
3226 GNUNET_SERVER_add_handlers (server, handlers);
3227 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3228 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3234 * The main function for the transport service.
3236 * @param argc number of arguments from the command line
3237 * @param argv command line arguments
3238 * @return 0 ok, 1 on error
3241 main (int argc, char *const *argv)
3243 return (GNUNET_OK ==
3244 GNUNET_SERVICE_run (argc,
3247 GNUNET_SERVICE_OPTION_NONE,
3248 &run, NULL)) ? 0 : 1;
3251 /* end of gnunet-service-core.c */