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);
862 * A client disconnected, clean up.
865 * @param client identification of the client
868 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
875 #if DEBUG_CORE_CLIENT
876 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
877 "Client has disconnected from core service.\n");
883 if (client == pos->client_handle)
888 prev->next = pos->next;
895 /* client never sent INIT */
900 * Handle REQUEST_INFO request.
903 handle_client_request_info (void *cls,
904 struct GNUNET_SERVER_Client *client,
905 const struct GNUNET_MessageHeader *message)
907 const struct RequestInfoMessage *rcm;
909 struct ConfigurationInfoMessage cim;
911 unsigned long long old_preference;
912 struct GNUNET_SERVER_TransmitContext *tc;
914 #if DEBUG_CORE_CLIENT
915 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
916 "Core service receives `%s' request.\n", "REQUEST_INFO");
918 rcm = (const struct RequestInfoMessage *) message;
919 n = find_neighbour (&rcm->peer);
920 memset (&cim, 0, sizeof (cim));
921 if ((n != NULL) && (n->status == PEER_STATE_KEY_CONFIRMED))
923 update_window (GNUNET_YES,
924 &n->available_send_window,
927 n->bpm_out_internal_limit = ntohl (rcm->limit_outbound_bpm);
928 n->bpm_out = GNUNET_MAX (n->bpm_out_internal_limit,
929 n->bpm_out_external_limit);
930 reserv = ntohl (rcm->reserve_inbound);
933 n->available_recv_window += reserv;
937 update_window (GNUNET_NO,
938 &n->available_recv_window,
939 &n->last_arw_update, n->bpm_in);
940 if (n->available_recv_window < reserv)
941 reserv = n->available_recv_window;
942 n->available_recv_window -= reserv;
944 old_preference = n->current_preference;
945 n->current_preference += GNUNET_ntohll(rcm->preference_change);
946 if (old_preference > n->current_preference)
948 /* overflow; cap at maximum value */
949 n->current_preference = (unsigned long long) -1;
951 update_preference_sum (n->current_preference - old_preference);
952 cim.reserved_amount = htonl (reserv);
953 cim.bpm_in = htonl (n->bpm_in);
954 cim.bpm_out = htonl (n->bpm_out);
955 cim.preference = n->current_preference;
957 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
958 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
959 cim.peer = rcm->peer;
961 #if DEBUG_CORE_CLIENT
962 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
963 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
965 tc = GNUNET_SERVER_transmit_context_create (client);
966 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
967 GNUNET_SERVER_transmit_context_run (tc,
968 GNUNET_TIME_UNIT_FOREVER_REL);
973 * Check if we have encrypted messages for the specified neighbour
974 * pending, and if so, check with the transport about sending them
977 * @param n neighbour to check.
979 static void process_encrypted_neighbour_queue (struct Neighbour *n);
983 * Function called when the transport service is ready to
984 * receive an encrypted message for the respective peer
986 * @param cls neighbour to use message from
987 * @param size number of bytes we can transmit
988 * @param buf where to copy the message
989 * @return number of bytes transmitted
992 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
994 struct Neighbour *n = cls;
995 struct MessageEntry *m;
1000 GNUNET_assert (NULL != (m = n->encrypted_head));
1001 n->encrypted_head = m->next;
1002 if (m->next == NULL)
1003 n->encrypted_tail = NULL;
1008 GNUNET_assert (size >= m->size);
1009 memcpy (cbuf, &m[1], m->size);
1011 n->available_send_window -= m->size;
1012 process_encrypted_neighbour_queue (n);
1014 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1015 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1016 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1017 ret, GNUNET_i2s (&n->peer));
1022 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1023 "Transmission for message of type %u and size %u failed\n",
1024 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1033 * Check if we have plaintext messages for the specified neighbour
1034 * pending, and if so, consider batching and encrypting them (and
1035 * then trigger processing of the encrypted queue if needed).
1037 * @param n neighbour to check.
1039 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1043 * Check if we have encrypted messages for the specified neighbour
1044 * pending, and if so, check with the transport about sending them
1047 * @param n neighbour to check.
1050 process_encrypted_neighbour_queue (struct Neighbour *n)
1052 struct MessageEntry *m;
1055 return; /* request already pending */
1056 if (n->encrypted_head == NULL)
1058 /* encrypted queue empty, try plaintext instead */
1059 process_plaintext_neighbour_queue (n);
1063 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1064 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1065 n->encrypted_head->size,
1066 GNUNET_i2s (&n->peer),
1067 GNUNET_TIME_absolute_get_remaining (n->
1068 encrypted_head->deadline).
1072 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1073 n->encrypted_head->size,
1074 n->encrypted_head->priority,
1075 GNUNET_TIME_absolute_get_remaining
1076 (n->encrypted_head->deadline),
1077 ¬ify_encrypted_transmit_ready,
1081 /* message request too large (oops) */
1083 /* discard encrypted message */
1084 GNUNET_assert (NULL != (m = n->encrypted_head));
1085 n->encrypted_head = m->next;
1086 if (m->next == NULL)
1087 n->encrypted_tail = NULL;
1089 process_encrypted_neighbour_queue (n);
1095 * Decrypt size bytes from in and write the result to out. Use the
1096 * key for inbound traffic of the given neighbour. This function does
1097 * NOT do any integrity-checks on the result.
1099 * @param n neighbour we are receiving from
1100 * @param iv initialization vector to use
1101 * @param in ciphertext
1102 * @param out plaintext
1103 * @param size size of in/out
1104 * @return GNUNET_OK on success
1107 do_decrypt (struct Neighbour *n,
1108 const GNUNET_HashCode * iv,
1109 const void *in, void *out, size_t size)
1111 if (size != (uint16_t) size)
1116 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1117 (n->status != PEER_STATE_KEY_CONFIRMED))
1119 GNUNET_break_op (0);
1120 return GNUNET_SYSERR;
1123 GNUNET_CRYPTO_aes_decrypt (in,
1127 GNUNET_CRYPTO_AesInitializationVector *) iv,
1131 return GNUNET_SYSERR;
1134 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1135 "Decrypted %u bytes from `%4s' using key %u\n",
1136 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1143 * Encrypt size bytes from in and write the result to out. Use the
1144 * key for outbound traffic of the given neighbour.
1146 * @param n neighbour we are sending to
1147 * @param iv initialization vector to use
1148 * @param in ciphertext
1149 * @param out plaintext
1150 * @param size size of in/out
1151 * @return GNUNET_OK on success
1154 do_encrypt (struct Neighbour *n,
1155 const GNUNET_HashCode * iv,
1156 const void *in, void *out, size_t size)
1158 if (size != (uint16_t) size)
1163 GNUNET_assert (size ==
1164 GNUNET_CRYPTO_aes_encrypt (in,
1168 GNUNET_CRYPTO_AesInitializationVector
1171 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1172 "Encrypted %u bytes for `%4s' using key %u\n", size,
1173 GNUNET_i2s (&n->peer), n->encrypt_key.crc32);
1180 * Select messages for transmission. This heuristic uses a combination
1181 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1182 * and priority-based discard (in case no feasible schedule exist) and
1183 * speculative optimization (defer any kind of transmission until
1184 * we either create a batch of significant size, 25% of max, or until
1185 * we are close to a deadline). Furthermore, when scheduling the
1186 * heuristic also packs as many messages into the batch as possible,
1187 * starting with those with the earliest deadline. Yes, this is fun.
1189 * @param n neighbour to select messages from
1190 * @param size number of bytes to select for transmission
1191 * @param retry_time set to the time when we should try again
1192 * (only valid if this function returns zero)
1193 * @return number of bytes selected, or 0 if we decided to
1194 * defer scheduling overall; in that case, retry_time is set.
1197 select_messages (struct Neighbour *n,
1198 size_t size, struct GNUNET_TIME_Relative *retry_time)
1200 struct MessageEntry *pos;
1201 struct MessageEntry *min;
1202 struct MessageEntry *last;
1203 unsigned int min_prio;
1204 struct GNUNET_TIME_Absolute t;
1205 struct GNUNET_TIME_Absolute now;
1208 unsigned long long slack; /* how long could we wait before missing deadlines? */
1210 int discard_low_prio;
1212 GNUNET_assert (NULL != n->messages);
1213 now = GNUNET_TIME_absolute_get ();
1214 /* last entry in linked list of messages processed */
1216 /* should we remove the entry with the lowest
1217 priority from consideration for scheduling at the
1219 discard_low_prio = GNUNET_YES;
1220 while (GNUNET_YES == discard_low_prio)
1224 discard_low_prio = GNUNET_NO;
1225 /* calculate number of bytes available for transmission at time "t" */
1226 update_window (GNUNET_NO,
1227 &n->available_send_window,
1228 &n->last_asw_update,
1230 avail = n->available_send_window;
1231 t = n->last_asw_update;
1232 /* how many bytes have we (hypothetically) scheduled so far */
1234 /* maximum time we can wait before transmitting anything
1235 and still make all of our deadlines */
1239 /* note that we use "*2" here because we want to look
1240 a bit further into the future; much more makes no
1241 sense since new message might be scheduled in the
1243 while ((pos != NULL) && (off < size * 2))
1245 if (pos->do_transmit == GNUNET_YES)
1247 /* already removed from consideration */
1251 if (discard_low_prio == GNUNET_NO)
1253 delta = pos->deadline.value;
1254 if (delta < t.value)
1257 delta = t.value - delta;
1258 avail += delta * n->bpm_out / 1000 / 60;
1259 if (avail < pos->size)
1261 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1266 /* update slack, considering both its absolute deadline
1267 and relative deadlines caused by other messages
1268 with their respective load */
1269 slack = GNUNET_MIN (slack, avail / n->bpm_out);
1270 if (pos->deadline.value < now.value)
1274 GNUNET_MIN (slack, pos->deadline.value - now.value);
1278 t.value = GNUNET_MAX (pos->deadline.value, t.value);
1279 if (pos->priority <= min_prio)
1281 /* update min for discard */
1282 min_prio = pos->priority;
1287 if (discard_low_prio)
1289 GNUNET_assert (min != NULL);
1290 /* remove lowest-priority entry from consideration */
1291 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1295 /* guard against sending "tiny" messages with large headers without
1297 if ( (slack > 1000) && (size > 4 * off) )
1299 /* less than 25% of message would be filled with
1300 deadlines still being met if we delay by one
1301 second or more; so just wait for more data */
1302 retry_time->value = slack / 2;
1303 /* reset do_transmit values for next time */
1306 pos->do_transmit = GNUNET_NO;
1311 /* select marked messages (up to size) for transmission */
1316 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1318 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1323 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1327 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1328 "Selected %u bytes of plaintext messages for transmission to `%4s'.\n",
1329 off, GNUNET_i2s (&n->peer));
1336 * Batch multiple messages into a larger buffer.
1338 * @param n neighbour to take messages from
1339 * @param buf target buffer
1340 * @param size size of buf
1341 * @param deadline set to transmission deadline for the result
1342 * @param retry_time set to the time when we should try again
1343 * (only valid if this function returns zero)
1344 * @param priority set to the priority of the batch
1345 * @return number of bytes written to buf (can be zero)
1348 batch_message (struct Neighbour *n,
1351 struct GNUNET_TIME_Absolute *deadline,
1352 struct GNUNET_TIME_Relative *retry_time,
1353 unsigned int *priority)
1355 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1356 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1357 struct MessageEntry *pos;
1358 struct MessageEntry *prev;
1359 struct MessageEntry *next;
1364 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1365 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1366 if (0 == select_messages (n, size, retry_time))
1368 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1369 "No messages selected, will try again in %llu ms\n",
1373 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1374 ntm->distance = htonl (n->last_distance);
1375 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1376 ntm->peer = n->peer;
1380 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1383 if (GNUNET_YES == pos->do_transmit)
1385 GNUNET_assert (pos->size <= size);
1386 /* do notifications */
1387 /* FIXME: track if we have *any* client that wants
1388 full notifications and only do this if that is
1390 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1392 memcpy (&ntm[1], &pos[1], pos->size);
1393 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1394 sizeof (struct GNUNET_MessageHeader));
1395 send_to_all_clients (&ntm->header,
1397 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1401 /* message too large for 'full' notifications, we do at
1402 least the 'hdr' type */
1405 sizeof (struct GNUNET_MessageHeader));
1407 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1409 send_to_all_clients (&ntm->header,
1411 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1412 /* copy for encrypted transmission */
1413 memcpy (&buf[ret], &pos[1], pos->size);
1416 *priority += pos->priority;
1418 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1419 "Adding plaintext message with deadline %llu ms to batch\n",
1420 GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1422 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1436 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1437 "Deadline for message batch is %llu ms\n",
1438 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1445 * Remove messages with deadlines that have long expired from
1448 * @param n neighbour to inspect
1451 discard_expired_messages (struct Neighbour *n)
1453 struct MessageEntry *prev;
1454 struct MessageEntry *next;
1455 struct MessageEntry *pos;
1456 struct GNUNET_TIME_Absolute now;
1457 struct GNUNET_TIME_Relative delta;
1459 now = GNUNET_TIME_absolute_get ();
1465 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1466 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1469 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1470 "Message is %llu ms past due, discarding.\n",
1487 * Signature of the main function of a task.
1489 * @param cls closure
1490 * @param tc context information (why was this task triggered now)
1493 retry_plaintext_processing (void *cls,
1494 const struct GNUNET_SCHEDULER_TaskContext *tc)
1496 struct Neighbour *n = cls;
1498 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1499 process_plaintext_neighbour_queue (n);
1504 * Send our key (and encrypted PING) to the other peer.
1506 * @param n the other peer
1508 static void send_key (struct Neighbour *n);
1512 * Check if we have plaintext messages for the specified neighbour
1513 * pending, and if so, consider batching and encrypting them (and
1514 * then trigger processing of the encrypted queue if needed).
1516 * @param n neighbour to check.
1519 process_plaintext_neighbour_queue (struct Neighbour *n)
1521 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1524 struct EncryptedMessage *em; /* encrypted message */
1525 struct EncryptedMessage *ph; /* plaintext header */
1526 struct MessageEntry *me;
1527 unsigned int priority;
1528 struct GNUNET_TIME_Absolute deadline;
1529 struct GNUNET_TIME_Relative retry_time;
1531 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1533 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1534 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1538 case PEER_STATE_DOWN:
1541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1542 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1543 GNUNET_i2s(&n->peer));
1546 case PEER_STATE_KEY_SENT:
1547 GNUNET_assert (n->retry_set_key_task !=
1548 GNUNET_SCHEDULER_NO_TASK);
1550 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1551 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1552 GNUNET_i2s(&n->peer));
1555 case PEER_STATE_KEY_RECEIVED:
1556 GNUNET_assert (n->retry_set_key_task !=
1557 GNUNET_SCHEDULER_NO_TASK);
1559 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1560 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1561 GNUNET_i2s(&n->peer));
1564 case PEER_STATE_KEY_CONFIRMED:
1565 /* ready to continue */
1568 discard_expired_messages (n);
1569 if (n->messages == NULL)
1572 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1573 "Plaintext message queue for `%4s' is empty.\n",
1574 GNUNET_i2s(&n->peer));
1576 return; /* no pending messages */
1578 if (n->encrypted_head != NULL)
1581 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1582 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1583 GNUNET_i2s(&n->peer));
1585 return; /* wait for messages already encrypted to be
1588 ph = (struct EncryptedMessage *) pbuf;
1589 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1591 used = sizeof (struct EncryptedMessage);
1592 used += batch_message (n,
1594 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1595 &deadline, &retry_time, &priority);
1596 if (used == sizeof (struct EncryptedMessage))
1599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1600 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1601 GNUNET_i2s(&n->peer));
1603 /* no messages selected for sending, try again later... */
1604 n->retry_plaintext_task =
1605 GNUNET_SCHEDULER_add_delayed (sched,
1607 &retry_plaintext_processing, n);
1610 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1611 ph->inbound_bpm_limit = htonl (n->bpm_in);
1612 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1614 /* setup encryption message header */
1615 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1616 me->deadline = deadline;
1617 me->priority = priority;
1619 em = (struct EncryptedMessage *) &me[1];
1620 em->header.size = htons (used);
1621 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1622 em->reserved = htonl (0);
1623 esize = used - ENCRYPTED_HEADER_SIZE;
1624 GNUNET_CRYPTO_hash (&ph->sequence_number, esize, &em->plaintext_hash);
1627 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1628 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
1630 GNUNET_i2s(&n->peer),
1631 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
1633 GNUNET_assert (GNUNET_OK ==
1635 &em->plaintext_hash,
1636 &ph->sequence_number,
1637 &em->sequence_number, esize));
1638 /* append to transmission list */
1639 if (n->encrypted_tail == NULL)
1640 n->encrypted_head = me;
1642 n->encrypted_tail->next = me;
1643 n->encrypted_tail = me;
1644 process_encrypted_neighbour_queue (n);
1649 * Handle CORE_SEND request.
1652 * @param client the client issuing the request
1653 * @param message the "struct SendMessage"
1656 handle_client_send (void *cls,
1657 struct GNUNET_SERVER_Client *client,
1658 const struct GNUNET_MessageHeader *message);
1662 * Function called to notify us that we either succeeded
1663 * or failed to connect (at the transport level) to another
1664 * peer. We should either free the message we were asked
1665 * to transmit or re-try adding it to the queue.
1667 * @param cls closure
1668 * @param size number of bytes available in buf
1669 * @param buf where the callee should write the message
1670 * @return number of bytes written to buf
1673 send_connect_continuation (void *cls, size_t size, void *buf)
1675 struct SendMessage *sm = cls;
1680 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1681 "Asked to send message to disconnected peer `%4s' and connection failed. Discarding message.\n",
1682 GNUNET_i2s (&sm->peer));
1688 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1689 "Connection to peer `%4s' succeeded, retrying original transmission request\n",
1690 GNUNET_i2s (&sm->peer));
1692 handle_client_send (NULL, NULL, &sm->header);
1699 * Handle CORE_SEND request.
1702 * @param client the client issuing the request
1703 * @param message the "struct SendMessage"
1706 handle_client_send (void *cls,
1707 struct GNUNET_SERVER_Client *client,
1708 const struct GNUNET_MessageHeader *message)
1710 const struct SendMessage *sm;
1711 struct SendMessage *smc;
1712 const struct GNUNET_MessageHeader *mh;
1713 struct Neighbour *n;
1714 struct MessageEntry *prev;
1715 struct MessageEntry *pos;
1716 struct MessageEntry *e;
1717 struct MessageEntry *min_prio_entry;
1718 struct MessageEntry *min_prio_prev;
1719 unsigned int min_prio;
1720 unsigned int queue_size;
1723 msize = ntohs (message->size);
1725 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
1729 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1732 sm = (const struct SendMessage *) message;
1733 msize -= sizeof (struct SendMessage);
1734 mh = (const struct GNUNET_MessageHeader *) &sm[1];
1735 if (msize != ntohs (mh->size))
1739 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1742 n = find_neighbour (&sm->peer);
1746 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1747 "\n\n\nCore received `%s' request for `%4s', will try to establish connection within %llu ms\n\n\n",
1749 GNUNET_i2s (&sm->peer),
1750 GNUNET_TIME_absolute_get_remaining
1751 (GNUNET_TIME_absolute_ntoh(sm->deadline)).value);
1753 msize += sizeof (struct SendMessage);
1754 /* ask transport to connect to the peer */
1755 smc = GNUNET_malloc (msize);
1756 memcpy (smc, sm, msize);
1758 GNUNET_TRANSPORT_notify_transmit_ready (transport,
1761 GNUNET_TIME_absolute_get_remaining
1762 (GNUNET_TIME_absolute_ntoh
1764 &send_connect_continuation,
1767 /* transport has already a request pending for this peer! */
1769 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1770 "Dropped second message destined for `%4s' since connection is still down.\n",
1771 GNUNET_i2s(&sm->peer));
1776 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1780 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1781 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
1784 GNUNET_i2s (&sm->peer));
1786 /* bound queue size */
1787 discard_expired_messages (n);
1788 min_prio = (unsigned int) -1;
1789 min_prio_entry = NULL;
1790 min_prio_prev = NULL;
1796 if (pos->priority < min_prio)
1798 min_prio_entry = pos;
1799 min_prio_prev = prev;
1800 min_prio = pos->priority;
1806 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1809 if (ntohl(sm->priority) <= min_prio)
1811 /* discard new entry */
1813 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1814 "Queue full, discarding new request\n");
1817 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1820 /* discard "min_prio_entry" */
1822 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1823 "Queue full, discarding existing older request\n");
1825 if (min_prio_prev == NULL)
1826 n->messages = min_prio_entry->next;
1828 min_prio_prev->next = min_prio_entry->next;
1829 GNUNET_free (min_prio_entry);
1833 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1834 "Adding transmission request for `%4s' to queue\n",
1835 GNUNET_i2s (&sm->peer));
1837 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
1838 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
1839 e->priority = ntohl (sm->priority);
1841 memcpy (&e[1], mh, msize);
1843 /* insert, keep list sorted by deadline */
1846 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
1857 /* consider scheduling now */
1858 process_plaintext_neighbour_queue (n);
1860 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1865 * Handle CORE_REQUEST_CONNECT request.
1868 * @param client the client issuing the request
1869 * @param message the "struct ConnectMessage"
1872 handle_client_request_connect (void *cls,
1873 struct GNUNET_SERVER_Client *client,
1874 const struct GNUNET_MessageHeader *message)
1876 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
1877 struct Neighbour *n;
1879 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1880 n = find_neighbour (&cm->peer);
1882 return; /* already connected, or at least trying */
1884 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1885 "Core received `%s' request for `%4s', will try to establish connection\n",
1887 GNUNET_i2s (&cm->peer));
1889 /* ask transport to connect to the peer */
1890 /* FIXME: timeout zero OK? need for cancellation? */
1891 GNUNET_TRANSPORT_notify_transmit_ready (transport,
1894 GNUNET_TIME_UNIT_ZERO,
1901 * List of handlers for the messages understood by this
1904 static struct GNUNET_SERVER_MessageHandler handlers[] = {
1905 {&handle_client_init, NULL,
1906 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
1907 {&handle_client_request_info, NULL,
1908 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
1909 sizeof (struct RequestInfoMessage)},
1910 {&handle_client_send, NULL,
1911 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
1912 {&handle_client_request_connect, NULL,
1913 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
1914 sizeof (struct ConnectMessage)},
1920 * Task that will retry "send_key" if our previous attempt failed
1924 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1926 struct Neighbour *n = cls;
1928 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1929 n->set_key_retry_frequency =
1930 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1936 * PEERINFO is giving us a HELLO for a peer. Add the public key to
1937 * the neighbour's struct and retry send_key. Or, if we did not get a
1938 * HELLO, just do nothing.
1941 * @param peer the peer for which this is the HELLO
1942 * @param hello HELLO message of that peer
1943 * @param trust amount of trust we currently have in that peer
1946 process_hello_retry_send_key (void *cls,
1947 const struct GNUNET_PeerIdentity *peer,
1948 const struct GNUNET_HELLO_Message *hello,
1951 struct Neighbour *n = cls;
1956 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1957 "Entered process_hello_retry_send_key Peer is null!\n");
1960 if (n->public_key != NULL)
1963 n->retry_set_key_task
1964 = GNUNET_SCHEDULER_add_delayed (sched,
1965 n->set_key_retry_frequency,
1966 &set_key_retry_task, n);
1971 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1972 "process_hello_retry_send_key for peer %s\n",
1975 if (n->public_key != NULL)
1978 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1979 "already have public key for peer %s!! (so why are we here?)\n",
1986 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1987 "Received new `%s' message for `%4s', initiating key exchange.\n",
1992 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1993 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
1995 GNUNET_free (n->public_key);
1996 n->public_key = NULL;
1998 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1999 "GNUNET_HELLO_get_key returned awfully\n");
2007 * Send our key (and encrypted PING) to the other peer.
2009 * @param n the other peer
2012 send_key (struct Neighbour *n)
2014 struct SetKeyMessage *sm;
2015 struct MessageEntry *me;
2016 struct PingMessage pp;
2017 struct PingMessage *pm;
2019 if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2023 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2024 "Key exchange in progress with `%4s'.\n",
2025 GNUNET_i2s (&n->peer));
2027 return; /* already in progress */
2031 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2032 "Asked to perform key exchange with `%4s'.\n",
2033 GNUNET_i2s (&n->peer));
2035 if (n->public_key == NULL)
2037 /* lookup n's public key, then try again */
2039 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2040 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2041 GNUNET_i2s (&n->peer));
2043 GNUNET_assert (n->pitr == NULL);
2045 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2049 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2050 &process_hello_retry_send_key, n);
2053 /* first, set key message */
2054 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2055 sizeof (struct SetKeyMessage));
2056 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2057 me->priority = SET_KEY_PRIORITY;
2058 me->size = sizeof (struct SetKeyMessage);
2059 if (n->encrypted_head == NULL)
2060 n->encrypted_head = me;
2062 n->encrypted_tail->next = me;
2063 n->encrypted_tail = me;
2064 sm = (struct SetKeyMessage *) &me[1];
2065 sm->header.size = htons (sizeof (struct SetKeyMessage));
2066 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2067 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2068 PEER_STATE_KEY_SENT : n->status));
2070 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2071 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2072 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2073 sizeof (struct GNUNET_PeerIdentity));
2074 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2075 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2076 sm->target = n->peer;
2077 GNUNET_assert (GNUNET_OK ==
2078 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2080 GNUNET_CRYPTO_AesSessionKey),
2082 &sm->encrypted_key));
2083 GNUNET_assert (GNUNET_OK ==
2084 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2087 /* second, encrypted PING message */
2088 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2089 sizeof (struct PingMessage));
2090 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2091 me->priority = PING_PRIORITY;
2092 me->size = sizeof (struct PingMessage);
2093 n->encrypted_tail->next = me;
2094 n->encrypted_tail = me;
2095 pm = (struct PingMessage *) &me[1];
2096 pm->header.size = htons (sizeof (struct PingMessage));
2097 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2098 pp.challenge = htonl (n->ping_challenge);
2099 pp.target = n->peer;
2101 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2102 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2103 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2104 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2105 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2107 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2110 &n->peer.hashPubKey,
2113 sizeof (struct PingMessage) -
2114 sizeof (struct GNUNET_MessageHeader));
2118 case PEER_STATE_DOWN:
2119 n->status = PEER_STATE_KEY_SENT;
2121 case PEER_STATE_KEY_SENT:
2123 case PEER_STATE_KEY_RECEIVED:
2125 case PEER_STATE_KEY_CONFIRMED:
2132 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2133 "Have %llu ms left for `%s' transmission.\n",
2134 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2137 /* trigger queue processing */
2138 process_encrypted_neighbour_queue (n);
2139 if (n->status != PEER_STATE_KEY_CONFIRMED)
2141 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task);
2142 n->retry_set_key_task
2143 = GNUNET_SCHEDULER_add_delayed (sched,
2144 n->set_key_retry_frequency,
2145 &set_key_retry_task, n);
2151 * We received a SET_KEY message. Validate and update
2152 * our key material and status.
2154 * @param n the neighbour from which we received message m
2155 * @param m the set key message we received
2158 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2162 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2163 * the neighbour's struct and retry handling the set_key message. Or,
2164 * if we did not get a HELLO, just free the set key message.
2166 * @param cls pointer to the set key message
2167 * @param peer the peer for which this is the HELLO
2168 * @param hello HELLO message of that peer
2169 * @param trust amount of trust we currently have in that peer
2172 process_hello_retry_handle_set_key (void *cls,
2173 const struct GNUNET_PeerIdentity *peer,
2174 const struct GNUNET_HELLO_Message *hello,
2177 struct Neighbour *n = cls;
2178 struct SetKeyMessage *sm = n->skm;
2187 if (n->public_key != NULL)
2188 return; /* multiple HELLOs match!? */
2190 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2191 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2193 GNUNET_break_op (0);
2194 GNUNET_free (n->public_key);
2195 n->public_key = NULL;
2199 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2200 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2201 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2203 handle_set_key (n, sm);
2208 * We received a PING message. Validate and transmit
2211 * @param n sender of the PING
2212 * @param m the encrypted PING message itself
2215 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2217 struct PingMessage t;
2218 struct PingMessage *tp;
2219 struct MessageEntry *me;
2222 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2223 "Core service receives `%s' request from `%4s'.\n",
2224 "PING", GNUNET_i2s (&n->peer));
2228 &my_identity.hashPubKey,
2231 sizeof (struct PingMessage) -
2232 sizeof (struct GNUNET_MessageHeader)))
2235 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2236 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2238 GNUNET_i2s (&t.target),
2239 ntohl (t.challenge), n->decrypt_key.crc32);
2240 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2241 "Target of `%s' request is `%4s'.\n",
2242 "PING", GNUNET_i2s (&t.target));
2244 if (0 != memcmp (&t.target,
2245 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2247 GNUNET_break_op (0);
2250 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2251 sizeof (struct PingMessage));
2252 if (n->encrypted_tail != NULL)
2253 n->encrypted_tail->next = me;
2256 n->encrypted_tail = me;
2257 n->encrypted_head = me;
2259 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2260 me->priority = PONG_PRIORITY;
2261 me->size = sizeof (struct PingMessage);
2262 tp = (struct PingMessage *) &me[1];
2263 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2264 tp->header.size = htons (sizeof (struct PingMessage));
2266 &my_identity.hashPubKey,
2269 sizeof (struct PingMessage) -
2270 sizeof (struct GNUNET_MessageHeader));
2272 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2273 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2274 ntohl (t.challenge), n->encrypt_key.crc32);
2276 /* trigger queue processing */
2277 process_encrypted_neighbour_queue (n);
2282 * We received a SET_KEY message. Validate and update
2283 * our key material and status.
2285 * @param n the neighbour from which we received message m
2286 * @param m the set key message we received
2289 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2291 struct SetKeyMessage *m_cpy;
2292 struct GNUNET_TIME_Absolute t;
2293 struct GNUNET_CRYPTO_AesSessionKey k;
2294 struct PingMessage *ping;
2295 enum PeerStateMachine sender_status;
2298 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2299 "Core service receives `%s' request from `%4s'.\n",
2300 "SET_KEY", GNUNET_i2s (&n->peer));
2302 if (n->public_key == NULL)
2305 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2306 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2308 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2309 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2310 /* lookup n's public key, then try again */
2311 GNUNET_assert (n->pitr == NULL);
2312 GNUNET_assert (n->skm == NULL);
2314 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2318 GNUNET_TIME_UNIT_MINUTES,
2319 &process_hello_retry_handle_set_key, n);
2322 if (0 != memcmp (&m->target,
2324 sizeof (struct GNUNET_PeerIdentity)))
2326 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2327 _("Received `%s' message that was not for me. Ignoring.\n"));
2330 if ((ntohl (m->purpose.size) !=
2331 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2332 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2333 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2334 sizeof (struct GNUNET_PeerIdentity)) ||
2336 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2337 &m->purpose, &m->signature, n->public_key)))
2339 /* invalid signature */
2340 GNUNET_break_op (0);
2343 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2344 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2345 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2346 (t.value < n->decrypt_key_created.value))
2348 /* this could rarely happen due to massive re-ordering of
2349 messages on the network level, but is most likely either
2350 a bug or some adversary messing with us. Report. */
2351 GNUNET_break_op (0);
2355 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
2357 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2360 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2361 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2362 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2364 /* failed to decrypt !? */
2365 GNUNET_break_op (0);
2370 if (n->decrypt_key_created.value != t.value)
2372 /* fresh key, reset sequence numbers */
2373 n->last_sequence_number_received = 0;
2374 n->last_packets_bitmap = 0;
2375 n->decrypt_key_created = t;
2377 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2380 case PEER_STATE_DOWN:
2381 n->status = PEER_STATE_KEY_RECEIVED;
2383 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2384 "Responding to `%s' with my own key.\n", "SET_KEY");
2388 case PEER_STATE_KEY_SENT:
2389 case PEER_STATE_KEY_RECEIVED:
2390 n->status = PEER_STATE_KEY_RECEIVED;
2391 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2392 (sender_status != PEER_STATE_KEY_CONFIRMED))
2395 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2396 "Responding to `%s' with my own key (other peer has status %u).\n",
2397 "SET_KEY", sender_status);
2402 case PEER_STATE_KEY_CONFIRMED:
2403 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2404 (sender_status != PEER_STATE_KEY_CONFIRMED))
2407 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2408 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2409 "SET_KEY", sender_status);
2418 if (n->pending_ping != NULL)
2420 ping = n->pending_ping;
2421 n->pending_ping = NULL;
2422 handle_ping (n, ping);
2429 * We received a PONG message. Validate and update our status.
2431 * @param n sender of the PONG
2432 * @param m the encrypted PONG message itself
2435 handle_pong (struct Neighbour *n, const struct PingMessage *m)
2437 struct PingMessage t;
2438 struct ConnectNotifyMessage cnm;
2441 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2442 "Core service receives `%s' request from `%4s'.\n",
2443 "PONG", GNUNET_i2s (&n->peer));
2447 &n->peer.hashPubKey,
2450 sizeof (struct PingMessage) -
2451 sizeof (struct GNUNET_MessageHeader)))
2454 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2455 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2457 GNUNET_i2s (&t.target),
2458 ntohl (t.challenge), n->decrypt_key.crc32);
2460 if ((0 != memcmp (&t.target,
2462 sizeof (struct GNUNET_PeerIdentity))) ||
2463 (n->ping_challenge != ntohl (t.challenge)))
2465 /* PONG malformed */
2467 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2468 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2469 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2470 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2471 "Received malformed `%s' received from `%4s' with challenge %u\n",
2472 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2474 GNUNET_break_op (0);
2479 case PEER_STATE_DOWN:
2480 GNUNET_break (0); /* should be impossible */
2482 case PEER_STATE_KEY_SENT:
2483 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2485 case PEER_STATE_KEY_RECEIVED:
2486 n->status = PEER_STATE_KEY_CONFIRMED;
2488 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2489 "Confirmed key via %s for peer %s\n",
2490 "PONG", GNUNET_i2s (&n->peer));
2492 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2494 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2495 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2497 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2498 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2499 cnm.distance = htonl (n->last_distance);
2500 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2502 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2503 process_encrypted_neighbour_queue (n);
2505 case PEER_STATE_KEY_CONFIRMED:
2506 /* duplicate PONG? */
2516 * Send a P2P message to a client.
2518 * @param sender who sent us the message?
2519 * @param client who should we give the message to?
2520 * @param m contains the message to transmit
2521 * @param msize number of bytes in buf to transmit
2524 send_p2p_message_to_client (struct Neighbour *sender,
2525 struct Client *client,
2526 const void *m, size_t msize)
2528 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2529 struct NotifyTrafficMessage *ntm;
2532 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2533 "Core service passes message from `%4s' of type %u to client.\n",
2534 GNUNET_i2s(&sender->peer),
2535 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2537 ntm = (struct NotifyTrafficMessage *) buf;
2538 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2539 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2540 ntm->distance = htonl (sender->last_distance);
2541 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
2542 ntm->peer = sender->peer;
2543 memcpy (&ntm[1], m, msize);
2544 send_to_client (client, &ntm->header, GNUNET_YES);
2549 * Deliver P2P message to interested clients.
2551 * @param sender who sent us the message?
2552 * @param m the message
2553 * @param msize size of the message (including header)
2556 deliver_message (struct Neighbour *sender,
2557 const struct GNUNET_MessageHeader *m, size_t msize)
2559 struct Client *cpos;
2564 type = ntohs (m->type);
2566 while (cpos != NULL)
2568 deliver_full = GNUNET_NO;
2569 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
2570 deliver_full = GNUNET_YES;
2573 for (tpos = 0; tpos < cpos->tcnt; tpos++)
2575 if (type != cpos->types[tpos])
2577 deliver_full = GNUNET_YES;
2581 if (GNUNET_YES == deliver_full)
2582 send_p2p_message_to_client (sender, cpos, m, msize);
2583 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2584 send_p2p_message_to_client (sender, cpos, m,
2585 sizeof (struct GNUNET_MessageHeader));
2592 * Align P2P message and then deliver to interested clients.
2594 * @param sender who sent us the message?
2595 * @param buffer unaligned (!) buffer containing message
2596 * @param msize size of the message (including header)
2599 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
2603 /* TODO: call to statistics? */
2604 memcpy (abuf, buffer, msize);
2605 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
2610 * Deliver P2P messages to interested clients.
2612 * @param sender who sent us the message?
2613 * @param buffer buffer containing messages, can be modified
2614 * @param buffer_size size of the buffer (overall)
2615 * @param offset offset where messages in the buffer start
2618 deliver_messages (struct Neighbour *sender,
2619 const char *buffer, size_t buffer_size, size_t offset)
2621 struct GNUNET_MessageHeader *mhp;
2622 struct GNUNET_MessageHeader mh;
2626 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
2628 if (0 != offset % sizeof (uint16_t))
2630 /* outch, need to copy to access header */
2631 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
2636 /* can access header directly */
2637 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
2639 msize = ntohs (mhp->size);
2640 if (msize + offset > buffer_size)
2642 /* malformed message, header says it is larger than what
2643 would fit into the overall buffer */
2644 GNUNET_break_op (0);
2647 #if HAVE_UNALIGNED_64_ACCESS
2648 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
2650 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
2652 if (GNUNET_YES == need_align)
2653 align_and_deliver (sender, &buffer[offset], msize);
2655 deliver_message (sender,
2656 (const struct GNUNET_MessageHeader *)
2657 &buffer[offset], msize);
2664 * We received an encrypted message. Decrypt, validate and
2665 * pass on to the appropriate clients.
2668 handle_encrypted_message (struct Neighbour *n,
2669 const struct EncryptedMessage *m)
2671 size_t size = ntohs (m->header.size);
2673 struct EncryptedMessage *pt; /* plaintext */
2677 struct GNUNET_TIME_Absolute t;
2680 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2681 "Core service receives `%s' request from `%4s'.\n",
2682 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
2688 &m->sequence_number,
2689 &buf[ENCRYPTED_HEADER_SIZE], size - ENCRYPTED_HEADER_SIZE))
2691 pt = (struct EncryptedMessage *) buf;
2694 GNUNET_CRYPTO_hash (&pt->sequence_number,
2695 size - ENCRYPTED_HEADER_SIZE, &ph);
2696 if (0 != memcmp (&ph, &m->plaintext_hash, sizeof (GNUNET_HashCode)))
2698 /* checksum failed */
2699 GNUNET_break_op (0);
2703 /* validate sequence number */
2704 snum = ntohl (pt->sequence_number);
2705 if (n->last_sequence_number_received == snum)
2707 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2708 "Received duplicate message, ignoring.\n");
2709 /* duplicate, ignore */
2712 if ((n->last_sequence_number_received > snum) &&
2713 (n->last_sequence_number_received - snum > 32))
2715 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2716 "Received ancient out of sequence message, ignoring.\n");
2717 /* ancient out of sequence, ignore */
2720 if (n->last_sequence_number_received > snum)
2722 unsigned int rotbit =
2723 1 << (n->last_sequence_number_received - snum - 1);
2724 if ((n->last_packets_bitmap & rotbit) != 0)
2726 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2727 "Received duplicate message, ignoring.\n");
2728 /* duplicate, ignore */
2731 n->last_packets_bitmap |= rotbit;
2733 if (n->last_sequence_number_received < snum)
2735 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
2736 n->last_sequence_number_received = snum;
2739 /* check timestamp */
2740 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
2741 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
2743 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2745 ("Message received far too old (%llu ms). Content ignored.\n"),
2746 GNUNET_TIME_absolute_get_duration (t).value);
2750 /* process decrypted message(s) */
2751 update_window (GNUNET_YES,
2752 &n->available_send_window,
2753 &n->last_asw_update,
2755 n->bpm_out_external_limit = ntohl (pt->inbound_bpm_limit);
2756 n->bpm_out = GNUNET_MAX (n->bpm_out_external_limit,
2757 n->bpm_out_internal_limit);
2758 n->last_activity = GNUNET_TIME_absolute_get ();
2759 off = sizeof (struct EncryptedMessage);
2760 deliver_messages (n, buf, size, off);
2765 * Function called by the transport for each received message.
2767 * @param cls closure
2768 * @param peer (claimed) identity of the other peer
2769 * @param message the message
2770 * @param latency estimated latency for communicating with the
2771 * given peer (round-trip)
2772 * @param distance in overlay hops, as given by transport plugin
2775 handle_transport_receive (void *cls,
2776 const struct GNUNET_PeerIdentity *peer,
2777 const struct GNUNET_MessageHeader *message,
2778 struct GNUNET_TIME_Relative latency,
2779 unsigned int distance)
2781 struct Neighbour *n;
2782 struct GNUNET_TIME_Absolute now;
2788 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2789 "Received message of type %u from `%4s', demultiplexing.\n",
2790 ntohs (message->type), GNUNET_i2s (peer));
2792 n = find_neighbour (peer);
2798 n->last_latency = latency;
2799 n->last_distance = distance;
2800 up = (n->status == PEER_STATE_KEY_CONFIRMED);
2801 type = ntohs (message->type);
2802 size = ntohs (message->size);
2805 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
2806 if (size != sizeof (struct SetKeyMessage))
2808 GNUNET_break_op (0);
2811 handle_set_key (n, (const struct SetKeyMessage *) message);
2813 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
2814 if (size < sizeof (struct EncryptedMessage) +
2815 sizeof (struct GNUNET_MessageHeader))
2817 GNUNET_break_op (0);
2820 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2821 (n->status != PEER_STATE_KEY_CONFIRMED))
2823 GNUNET_break_op (0);
2826 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
2828 case GNUNET_MESSAGE_TYPE_CORE_PING:
2829 if (size != sizeof (struct PingMessage))
2831 GNUNET_break_op (0);
2834 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2835 (n->status != PEER_STATE_KEY_CONFIRMED))
2838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2839 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
2840 "PING", GNUNET_i2s (&n->peer));
2842 GNUNET_free_non_null (n->pending_ping);
2843 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
2844 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
2847 handle_ping (n, (const struct PingMessage *) message);
2849 case GNUNET_MESSAGE_TYPE_CORE_PONG:
2850 if (size != sizeof (struct PingMessage))
2852 GNUNET_break_op (0);
2855 if ((n->status != PEER_STATE_KEY_SENT) &&
2856 (n->status != PEER_STATE_KEY_RECEIVED) &&
2857 (n->status != PEER_STATE_KEY_CONFIRMED))
2859 /* could not decrypt pong, oops! */
2860 GNUNET_break_op (0);
2863 handle_pong (n, (const struct PingMessage *) message);
2866 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2867 _("Unsupported message of type %u received.\n"), type);
2870 if (n->status == PEER_STATE_KEY_CONFIRMED)
2872 now = GNUNET_TIME_absolute_get ();
2873 n->last_activity = now;
2875 n->time_established = now;
2881 * Function that recalculates the bandwidth quota for the
2882 * given neighbour and transmits it to the transport service.
2884 * @param cls neighbour for the quota update
2888 neighbour_quota_update (void *cls,
2889 const struct GNUNET_SCHEDULER_TaskContext *tc);
2893 * Schedule the task that will recalculate the bandwidth
2894 * quota for this peer (and possibly force a disconnect of
2895 * idle peers by calculating a bandwidth of zero).
2898 schedule_quota_update (struct Neighbour *n)
2900 GNUNET_assert (n->quota_update_task ==
2901 GNUNET_SCHEDULER_NO_TASK);
2902 n->quota_update_task
2903 = GNUNET_SCHEDULER_add_delayed (sched,
2904 QUOTA_UPDATE_FREQUENCY,
2905 &neighbour_quota_update,
2911 * Function that recalculates the bandwidth quota for the
2912 * given neighbour and transmits it to the transport service.
2914 * @param cls neighbour for the quota update
2918 neighbour_quota_update (void *cls,
2919 const struct GNUNET_SCHEDULER_TaskContext *tc)
2921 struct Neighbour *n = cls;
2925 unsigned long long distributable;
2927 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
2928 /* calculate relative preference among all neighbours;
2929 divides by a bit more to avoid division by zero AND to
2930 account for possibility of new neighbours joining any time
2931 AND to convert to double... */
2932 pref_rel = n->current_preference / (1.0 + preference_sum);
2934 if (bandwidth_target_out > neighbour_count * MIN_BPM_PER_PEER)
2935 distributable = bandwidth_target_out - neighbour_count * MIN_BPM_PER_PEER;
2936 share = distributable * pref_rel;
2937 q_in = MIN_BPM_PER_PEER + (unsigned long long) share;
2938 /* check if we want to disconnect for good due to inactivity */
2939 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
2940 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
2941 q_in = 0; /* force disconnect */
2942 if ( (n->bpm_in + MIN_BPM_CHANGE < q_in) ||
2943 (n->bpm_in - MIN_BPM_CHANGE > q_in) )
2946 GNUNET_TRANSPORT_set_quota (transport,
2950 GNUNET_TIME_UNIT_FOREVER_REL,
2953 schedule_quota_update (n);
2958 * Function called by transport to notify us that
2959 * a peer connected to us (on the network level).
2961 * @param cls closure
2962 * @param peer the peer that connected
2963 * @param latency current latency of the connection
2964 * @param distance in overlay hops, as given by transport plugin
2967 handle_transport_notify_connect (void *cls,
2968 const struct GNUNET_PeerIdentity *peer,
2969 struct GNUNET_TIME_Relative latency,
2970 unsigned int distance)
2972 struct Neighbour *n;
2973 struct GNUNET_TIME_Absolute now;
2974 struct ConnectNotifyMessage cnm;
2976 n = find_neighbour (peer);
2979 /* duplicate connect notification!? */
2983 now = GNUNET_TIME_absolute_get ();
2984 n = GNUNET_malloc (sizeof (struct Neighbour));
2985 n->next = neighbours;
2989 n->last_latency = latency;
2990 n->last_distance = distance;
2991 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2992 n->encrypt_key_created = now;
2993 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2994 n->last_asw_update = now;
2995 n->last_arw_update = now;
2996 n->bpm_in = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
2997 n->bpm_out = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
2998 n->bpm_out_internal_limit = (uint32_t) - 1;
2999 n->bpm_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
3000 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3003 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3004 "Received connection from `%4s'.\n",
3005 GNUNET_i2s (&n->peer));
3007 schedule_quota_update (n);
3008 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3009 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3010 cnm.distance = htonl (n->last_distance);
3011 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3013 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3019 * Free the given entry for the neighbour (it has
3020 * already been removed from the list at this point).
3022 * @param n neighbour to free
3025 free_neighbour (struct Neighbour *n)
3027 struct MessageEntry *m;
3029 if (n->pitr != NULL)
3031 GNUNET_PEERINFO_iterate_cancel (n->pitr);
3036 GNUNET_free (n->skm);
3039 while (NULL != (m = n->messages))
3041 n->messages = m->next;
3044 while (NULL != (m = n->encrypted_head))
3046 n->encrypted_head = m->next;
3050 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
3051 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
3052 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
3053 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3054 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
3055 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
3056 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
3057 GNUNET_free_non_null (n->public_key);
3058 GNUNET_free_non_null (n->pending_ping);
3064 * Function called by transport telling us that a peer
3067 * @param cls closure
3068 * @param peer the peer that disconnected
3071 handle_transport_notify_disconnect (void *cls,
3072 const struct GNUNET_PeerIdentity *peer)
3074 struct DisconnectNotifyMessage cnm;
3075 struct Neighbour *n;
3076 struct Neighbour *p;
3079 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3080 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3084 while ((n != NULL) &&
3085 (0 != memcmp (&n->peer, peer, sizeof (struct GNUNET_PeerIdentity))))
3096 neighbours = n->next;
3099 GNUNET_assert (neighbour_count > 0);
3101 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3102 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3104 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3110 * Last task run during shutdown. Disconnects us from
3114 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3116 struct Neighbour *n;
3120 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3121 "Core service shutting down.\n");
3123 GNUNET_assert (transport != NULL);
3124 GNUNET_TRANSPORT_disconnect (transport);
3126 while (NULL != (n = neighbours))
3128 neighbours = n->next;
3129 GNUNET_assert (neighbour_count > 0);
3133 GNUNET_SERVER_notification_context_destroy (notifier);
3135 while (NULL != (c = clients))
3136 handle_client_disconnect (NULL, c->client_handle);
3137 if (my_private_key != NULL)
3138 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3143 * Initiate core service.
3145 * @param cls closure
3146 * @param s scheduler to use
3147 * @param serv the initialized server
3148 * @param c configuration to use
3152 struct GNUNET_SCHEDULER_Handle *s,
3153 struct GNUNET_SERVER_Handle *serv,
3154 const struct GNUNET_CONFIGURATION_Handle *c)
3157 unsigned long long qin;
3158 unsigned long long qout;
3159 unsigned long long tneigh;
3165 /* parse configuration */
3168 GNUNET_CONFIGURATION_get_value_number (c,
3171 &bandwidth_target_in)) ||
3173 GNUNET_CONFIGURATION_get_value_number (c,
3176 &bandwidth_target_out)) ||
3178 GNUNET_CONFIGURATION_get_value_filename (c,
3180 "HOSTKEY", &keyfile)))
3182 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3184 ("Core service is lacking key configuration settings. Exiting.\n"));
3185 GNUNET_SCHEDULER_shutdown (s);
3188 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3189 GNUNET_free (keyfile);
3190 if (my_private_key == NULL)
3192 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3193 _("Core service could not access hostkey. Exiting.\n"));
3194 GNUNET_SCHEDULER_shutdown (s);
3197 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3198 GNUNET_CRYPTO_hash (&my_public_key,
3199 sizeof (my_public_key), &my_identity.hashPubKey);
3200 /* setup notification */
3202 notifier = GNUNET_SERVER_notification_context_create (server,
3204 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3205 /* setup transport connection */
3206 transport = GNUNET_TRANSPORT_connect (sched,
3209 &handle_transport_receive,
3210 &handle_transport_notify_connect,
3211 &handle_transport_notify_disconnect);
3212 GNUNET_assert (NULL != transport);
3213 GNUNET_SCHEDULER_add_delayed (sched,
3214 GNUNET_TIME_UNIT_FOREVER_REL,
3215 &cleaning_task, NULL);
3216 /* process client requests */
3217 GNUNET_SERVER_add_handlers (server, handlers);
3218 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3219 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3225 * The main function for the transport service.
3227 * @param argc number of arguments from the command line
3228 * @param argv command line arguments
3229 * @return 0 ok, 1 on error
3232 main (int argc, char *const *argv)
3234 return (GNUNET_OK ==
3235 GNUNET_SERVICE_run (argc,
3238 GNUNET_SERVICE_OPTION_NONE,
3239 &run, NULL)) ? 0 : 1;
3242 /* end of gnunet-service-core.c */