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 * Minimum of bytes per minute (out) to assign to any connected peer.
53 * Should be rather low; values larger than DEFAULT_BPM_IN_OUT make no
56 #define MIN_BPM_PER_PEER GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT
59 * What is the smallest change (in number of bytes per minute)
60 * that we consider significant enough to bother triggering?
62 #define MIN_BPM_CHANGE 32
65 * After how much time past the "official" expiration time do
66 * we discard messages? Should not be zero since we may
67 * intentionally defer transmission until close to the deadline
68 * and then may be slightly past the deadline due to inaccuracy
69 * in sleep and our own CPU consumption.
71 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
74 * What is the maximum delay for a SET_KEY message?
76 #define MAX_SET_KEY_DELAY GNUNET_TIME_UNIT_SECONDS
79 * What how long do we wait for SET_KEY confirmation initially?
81 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3)
84 * What is the maximum delay for a PING message?
86 #define MAX_PING_DELAY GNUNET_TIME_UNIT_SECONDS
89 * What is the maximum delay for a PONG message?
91 #define MAX_PONG_DELAY GNUNET_TIME_UNIT_SECONDS
94 * How often do we recalculate bandwidth quotas?
96 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_UNIT_SECONDS
99 * What is the priority for a SET_KEY message?
101 #define SET_KEY_PRIORITY 0xFFFFFF
104 * What is the priority for a PING message?
106 #define PING_PRIORITY 0xFFFFFF
109 * What is the priority for a PONG message?
111 #define PONG_PRIORITY 0xFFFFFF
114 * How many messages do we queue per peer at most?
116 #define MAX_PEER_QUEUE_SIZE 16
119 * How many non-mandatory messages do we queue per client at most?
121 #define MAX_CLIENT_QUEUE_SIZE 32
124 * What is the maximum age of a message for us to consider
125 * processing it? Note that this looks at the timestamp used
126 * by the other peer, so clock skew between machines does
127 * come into play here. So this should be picked high enough
128 * so that a little bit of clock skew does not prevent peers
129 * from connecting to us.
131 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
134 * What is the maximum size for encrypted messages? Note that this
135 * number imposes a clear limit on the maximum size of any message.
136 * Set to a value close to 64k but not so close that transports will
137 * have trouble with their headers.
139 #define MAX_ENCRYPTED_MESSAGE_SIZE (63 * 1024)
143 * State machine for our P2P encryption handshake. Everyone starts in
144 * "DOWN", if we receive the other peer's key (other peer initiated)
145 * we start in state RECEIVED (since we will immediately send our
146 * own); otherwise we start in SENT. If we get back a PONG from
147 * within either state, we move up to CONFIRMED (the PONG will always
148 * be sent back encrypted with the key we sent to the other peer).
150 enum PeerStateMachine
154 PEER_STATE_KEY_RECEIVED,
155 PEER_STATE_KEY_CONFIRMED
160 * Number of bytes (at the beginning) of "struct EncryptedMessage"
161 * that are NOT encrypted.
163 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t) + sizeof(GNUNET_HashCode))
167 * Encapsulation for encrypted messages exchanged between
168 * peers. Followed by the actual encrypted data.
170 struct EncryptedMessage
173 * Message type is either CORE_ENCRYPTED_MESSAGE.
175 struct GNUNET_MessageHeader header;
180 uint32_t reserved GNUNET_PACKED;
183 * Hash of the plaintext, used to verify message integrity;
184 * ALSO used as the IV for the symmetric cipher! Everything
185 * after this hash will be encrypted. ENCRYPTED_HEADER_SIZE
186 * must be set to the offset of the next field.
188 GNUNET_HashCode plaintext_hash;
191 * Sequence number, in network byte order. This field
192 * must be the first encrypted/decrypted field and the
193 * first byte that is hashed for the plaintext hash.
195 uint32_t sequence_number GNUNET_PACKED;
198 * Desired bandwidth (how much we should send to this
199 * peer / how much is the sender willing to receive),
200 * in bytes per minute.
202 uint32_t inbound_bpm_limit GNUNET_PACKED;
205 * Timestamp. Used to prevent reply of ancient messages
206 * (recent messages are caught with the sequence number).
208 struct GNUNET_TIME_AbsoluteNBO timestamp;
213 * We're sending an (encrypted) PING to the other peer to check if he
214 * can decrypt. The other peer should respond with a PONG with the
215 * same content, except this time encrypted with the receiver's key.
220 * Message type is either CORE_PING or CORE_PONG.
222 struct GNUNET_MessageHeader header;
225 * Random number chosen to make reply harder.
227 uint32_t challenge GNUNET_PACKED;
230 * Intended target of the PING, used primarily to check
231 * that decryption actually worked.
233 struct GNUNET_PeerIdentity target;
238 * Message transmitted to set (or update) a session key.
244 * Message type is either CORE_SET_KEY.
246 struct GNUNET_MessageHeader header;
249 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
251 int32_t sender_status GNUNET_PACKED;
254 * Purpose of the signature, will be
255 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
257 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
260 * At what time was this key created?
262 struct GNUNET_TIME_AbsoluteNBO creation_time;
265 * The encrypted session key.
267 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
270 * Who is the intended recipient?
272 struct GNUNET_PeerIdentity target;
275 * Signature of the stuff above (starting at purpose).
277 struct GNUNET_CRYPTO_RsaSignature signature;
283 * Message waiting for transmission. This struct
284 * is followed by the actual content of the message.
290 * We keep messages in a linked list (for now).
292 struct MessageEntry *next;
295 * By when are we supposed to transmit this message?
297 struct GNUNET_TIME_Absolute deadline;
300 * How important is this message to us?
302 unsigned int priority;
305 * How long is the message? (number of bytes following
306 * the "struct MessageEntry", but not including the
307 * size of "struct MessageEntry" itself!)
312 * Was this message selected for transmission in the
313 * current round? GNUNET_YES or GNUNET_NO.
323 * We keep neighbours in a linked list (for now).
325 struct Neighbour *next;
328 * Unencrypted messages destined for this peer.
330 struct MessageEntry *messages;
333 * Head of the batched, encrypted message queue (already ordered,
334 * transmit starting with the head).
336 struct MessageEntry *encrypted_head;
339 * Tail of the batched, encrypted message queue (already ordered,
340 * append new messages to tail)
342 struct MessageEntry *encrypted_tail;
345 * Handle for pending requests for transmission to this peer
346 * with the transport service. NULL if no request is pending.
348 struct GNUNET_TRANSPORT_TransmitHandle *th;
351 * Public key of the neighbour, NULL if we don't have it yet.
353 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
356 * We received a PING message before we got the "public_key"
357 * (or the SET_KEY). We keep it here until we have a key
358 * to decrypt it. NULL if no PING is pending.
360 struct PingMessage *pending_ping;
363 * Identity of the neighbour.
365 struct GNUNET_PeerIdentity peer;
368 * Key we use to encrypt our messages for the other peer
369 * (initialized by us when we do the handshake).
371 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
374 * Key we use to decrypt messages from the other peer
375 * (given to us by the other peer during the handshake).
377 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
380 * ID of task used for re-trying plaintext scheduling.
382 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
385 * ID of task used for re-trying SET_KEY and PING message.
387 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
390 * ID of task used for updating bandwidth quota for this neighbour.
392 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
395 * At what time did we generate our encryption key?
397 struct GNUNET_TIME_Absolute encrypt_key_created;
400 * At what time did the other peer generate the decryption key?
402 struct GNUNET_TIME_Absolute decrypt_key_created;
405 * At what time did we initially establish (as in, complete session
406 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
408 struct GNUNET_TIME_Absolute time_established;
411 * At what time did we last receive an encrypted message from the
412 * other peer? Should be zero if status != KEY_CONFIRMED.
414 struct GNUNET_TIME_Absolute last_activity;
417 * Last latency observed from this peer.
419 struct GNUNET_TIME_Relative last_latency;
422 * At what frequency are we currently re-trying SET_KEY messages?
424 struct GNUNET_TIME_Relative set_key_retry_frequency;
427 * Time of our last update to the "available_send_window".
429 struct GNUNET_TIME_Absolute last_asw_update;
432 * Time of our last update to the "available_recv_window".
434 struct GNUNET_TIME_Absolute last_arw_update;
437 * Number of bytes that we are eligible to transmit to this
438 * peer at this point. Incremented every minute by max_out_bpm,
439 * bounded by max_bpm (no back-log larger than MAX_BUF_FACT minutes,
440 * bandwidth-hogs are sampled at a frequency of about 78s!);
441 * may get negative if we have VERY high priority content.
443 long long available_send_window;
446 * How much downstream capacity of this peer has been reserved for
447 * our traffic? (Our clients can request that a certain amount of
448 * bandwidth is available for replies to them; this value is used to
449 * make sure that this reserved amount of bandwidth is actually
452 long long available_recv_window;
455 * How valueable were the messages of this peer recently?
457 unsigned long long current_preference;
460 * Bit map indicating which of the 32 sequence numbers before the last
461 * were received (good for accepting out-of-order packets and
462 * estimating reliability of the connection)
464 unsigned int last_packets_bitmap;
467 * Number of messages in the message queue for this peer.
469 unsigned int message_queue_size;
472 * last sequence number received on this connection (highest)
474 uint32_t last_sequence_number_received;
477 * last sequence number transmitted
479 uint32_t last_sequence_number_sent;
482 * Available bandwidth in for this peer (current target).
487 * Available bandwidth out for this peer (current target).
492 * Internal bandwidth limit set for this peer (initially
493 * typically set to "-1"). "bpm_out" is MAX of
494 * "bpm_out_internal_limit" and "bpm_out_external_limit".
496 uint32_t bpm_out_internal_limit;
499 * External bandwidth limit set for this peer by the
500 * peer that we are communicating with. "bpm_out" is MAX of
501 * "bpm_out_internal_limit" and "bpm_out_external_limit".
503 uint32_t bpm_out_external_limit;
506 * What was our PING challenge number (for this peer)?
508 uint32_t ping_challenge;
511 * What is our connection status?
513 enum PeerStateMachine status;
519 * Events are messages for clients. The struct
520 * itself is followed by the actual message.
525 * This is a linked list.
530 * Size of the message.
535 * Could this event be dropped if this queue
536 * is getting too large? (NOT YET USED!)
544 * Data structure for each client connected to the core service.
549 * Clients are kept in a linked list.
554 * Handle for the client with the server API.
556 struct GNUNET_SERVER_Client *client_handle;
559 * Linked list of messages we still need to deliver to
562 struct Event *event_head;
565 * Tail of the linked list of events.
567 struct Event *event_tail;
570 * Current transmit handle, NULL if no transmission request
573 struct GNUNET_CONNECTION_TransmitHandle *th;
576 * Array of the types of messages this peer cares
577 * about (with "tcnt" entries). Allocated as part
578 * of this client struct, do not free!
583 * Options for messages this client cares about,
584 * see GNUNET_CORE_OPTION_ values.
589 * Number of types of incoming messages this client
590 * specifically cares about. Size of the "types" array.
600 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
605 static struct GNUNET_PeerIdentity my_identity;
610 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
615 struct GNUNET_SCHEDULER_Handle *sched;
620 const struct GNUNET_CONFIGURATION_Handle *cfg;
625 static struct GNUNET_SERVER_Handle *server;
630 static struct GNUNET_TRANSPORT_Handle *transport;
633 * Linked list of our clients.
635 static struct Client *clients;
638 * We keep neighbours in a linked list (for now).
640 static struct Neighbour *neighbours;
643 * Sum of all preferences among all neighbours.
645 static unsigned long long preference_sum;
648 * Total number of neighbours we have.
650 static unsigned int neighbour_count;
653 * How much inbound bandwidth are we supposed to be using?
655 static unsigned long long bandwidth_target_in;
658 * How much outbound bandwidth are we supposed to be using?
660 static unsigned long long bandwidth_target_out;
665 * A preference value for a neighbour was update. Update
666 * the preference sum accordingly.
668 * @param inc how much was a preference value increased?
671 update_preference_sum (unsigned long long inc)
674 unsigned long long os;
677 preference_sum += inc;
678 if (preference_sum >= os)
680 /* overflow! compensate by cutting all values in half! */
685 n->current_preference /= 2;
686 preference_sum += n->current_preference;
693 * Recalculate the number of bytes we expect to
694 * receive or transmit in a given window.
696 * @param force force an update now (even if not much time has passed)
697 * @param window pointer to the byte counter (updated)
698 * @param ts pointer to the timestamp (updated)
699 * @param bpm number of bytes per minute that should
700 * be added to the window.
703 update_window (int force,
705 struct GNUNET_TIME_Absolute *ts, unsigned int bpm)
707 struct GNUNET_TIME_Relative since;
709 since = GNUNET_TIME_absolute_get_duration (*ts);
710 if ( (force == GNUNET_NO) &&
711 (since.value < 60 * 1000) )
712 return; /* not even a minute has passed */
713 *ts = GNUNET_TIME_absolute_get ();
714 *window += (bpm * since.value) / 60 / 1000;
715 if (*window > MAX_WINDOW_TIME * bpm)
716 *window = MAX_WINDOW_TIME * bpm;
721 * Find the entry for the given neighbour.
723 * @param peer identity of the neighbour
724 * @return NULL if we are not connected, otherwise the
727 static struct Neighbour *
728 find_neighbour (const struct GNUNET_PeerIdentity *peer)
730 struct Neighbour *ret;
733 while ((ret != NULL) &&
734 (0 != memcmp (&ret->peer,
735 peer, sizeof (struct GNUNET_PeerIdentity))))
742 * Find the entry for the given client.
744 * @param client handle for the client
745 * @return NULL if we are not connected, otherwise the
748 static struct Client *
749 find_client (const struct GNUNET_SERVER_Client *client)
754 while ((ret != NULL) && (client != ret->client_handle))
761 * If necessary, initiate a request with the server to
762 * transmit messages from the queue of the given client.
763 * @param client who to transfer messages to
765 static void request_transmit (struct Client *client);
769 * Client is ready to receive data, provide it.
772 * @param size number of bytes available in buf
773 * @param buf where the callee should write the message
774 * @return number of bytes written to buf
777 do_client_transmit (void *cls, size_t size, void *buf)
779 struct Client *client = cls;
785 #if DEBUG_CORE_CLIENT
786 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
787 "Client ready to receive %u bytes.\n", size);
792 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
793 "Failed to transmit data to client (disconnect)?\n");
795 return 0; /* we'll surely get a disconnect soon... */
799 while ((NULL != (e = client->event_head)) && (e->size <= size))
801 memcpy (&tgt[ret], &e[1], e->size);
804 client->event_head = e->next;
807 GNUNET_assert (ret > 0);
808 if (client->event_head == NULL)
809 client->event_tail = NULL;
810 #if DEBUG_CORE_CLIENT
811 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
812 "Transmitting %u bytes to client\n", ret);
814 request_transmit (client);
820 * If necessary, initiate a request with the server to
821 * transmit messages from the queue of the given client.
822 * @param client who to transfer messages to
825 request_transmit (struct Client *client)
828 if (NULL != client->th)
829 return; /* already pending */
830 if (NULL == client->event_head)
831 return; /* no more events pending */
832 #if DEBUG_CORE_CLIENT
833 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
834 "Asking server to transmit %u bytes to client\n",
835 client->event_head->size);
838 = GNUNET_SERVER_notify_transmit_ready (client->client_handle,
839 client->event_head->size,
840 GNUNET_TIME_UNIT_FOREVER_REL,
841 &do_client_transmit, client);
846 * Send a message to one of our clients.
848 * @param client target for the message
849 * @param msg message to transmit
850 * @param can_drop could this message be dropped if the
851 * client's queue is getting too large?
854 send_to_client (struct Client *client,
855 const struct GNUNET_MessageHeader *msg, int can_drop)
858 unsigned int queue_size;
861 #if DEBUG_CORE_CLIENT
862 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
863 "Preparing to send message of type %u to client.\n",
867 e = client->event_head;
873 if ( (queue_size >= MAX_CLIENT_QUEUE_SIZE) &&
874 (can_drop == GNUNET_YES) )
877 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
878 "Too many messages in queue for the client, dropping the new message.\n");
883 msize = ntohs (msg->size);
884 e = GNUNET_malloc (sizeof (struct Event) + msize);
886 if (client->event_tail != NULL)
887 client->event_tail->next = e;
889 client->event_head = e;
890 client->event_tail = e;
891 e->can_drop = can_drop;
893 memcpy (&e[1], msg, msize);
894 request_transmit (client);
899 * Send a message to all of our current clients.
902 send_to_all_clients (const struct GNUNET_MessageHeader *msg, int can_drop)
909 send_to_client (c, msg, can_drop);
916 * Handle CORE_INIT request.
919 handle_client_init (void *cls,
920 struct GNUNET_SERVER_Client *client,
921 const struct GNUNET_MessageHeader *message)
923 const struct InitMessage *im;
924 struct InitReplyMessage irm;
927 const uint16_t *types;
929 struct ConnectNotifyMessage cnm;
931 #if DEBUG_CORE_CLIENT
932 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
933 "Client connecting to core service with `%s' message\n",
936 /* check that we don't have an entry already */
940 if (client == c->client_handle)
943 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
948 msize = ntohs (message->size);
949 if (msize < sizeof (struct InitMessage))
952 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
955 im = (const struct InitMessage *) message;
956 types = (const uint16_t *) &im[1];
957 msize -= sizeof (struct InitMessage);
958 c = GNUNET_malloc (sizeof (struct Client) + msize);
959 c->client_handle = client;
962 memcpy (&c[1], types, msize);
963 c->types = (uint16_t *) & c[1];
964 c->options = ntohl (im->options);
965 c->tcnt = msize / sizeof (uint16_t);
966 /* send init reply message */
967 irm.header.size = htons (sizeof (struct InitReplyMessage));
968 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
969 irm.reserved = htonl (0);
970 memcpy (&irm.publicKey,
972 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
973 #if DEBUG_CORE_CLIENT
974 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
975 "Sending `%s' message to client.\n", "INIT_REPLY");
977 send_to_client (c, &irm.header, GNUNET_NO);
978 /* notify new client about existing neighbours */
979 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
980 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
984 #if DEBUG_CORE_CLIENT
985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
986 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
988 cnm.reserved = htonl (0);
990 send_to_client (c, &cnm.header, GNUNET_NO);
993 GNUNET_SERVER_receive_done (client, GNUNET_OK);
998 * A client disconnected, clean up.
1000 * @param cls closure
1001 * @param client identification of the client
1004 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1007 struct Client *prev;
1010 #if DEBUG_CORE_CLIENT
1011 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1012 "Client has disconnected from core service.\n");
1018 if (client == pos->client_handle)
1021 clients = pos->next;
1023 prev->next = pos->next;
1024 if (pos->th != NULL)
1025 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
1026 while (NULL != (e = pos->event_head))
1028 pos->event_head = e->next;
1037 /* client never sent INIT */
1042 * Handle REQUEST_CONFIGURE request.
1045 handle_client_request_configure (void *cls,
1046 struct GNUNET_SERVER_Client *client,
1047 const struct GNUNET_MessageHeader *message)
1049 const struct RequestConfigureMessage *rcm;
1050 struct Neighbour *n;
1051 struct ConfigurationInfoMessage cim;
1054 unsigned long long old_preference;
1056 #if DEBUG_CORE_CLIENT
1057 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1058 "Core service receives `%s' request.\n", "CONFIGURE");
1060 rcm = (const struct RequestConfigureMessage *) message;
1061 n = find_neighbour (&rcm->peer);
1062 memset (&cim, 0, sizeof (cim));
1063 if ((n != NULL) && (n->status == PEER_STATE_KEY_CONFIRMED))
1065 update_window (GNUNET_YES,
1066 &n->available_send_window,
1067 &n->last_asw_update,
1069 n->bpm_out_internal_limit = ntohl (rcm->limit_outbound_bpm);
1070 n->bpm_out = GNUNET_MAX (n->bpm_out_internal_limit,
1071 n->bpm_out_external_limit);
1072 reserv = ntohl (rcm->reserve_inbound);
1075 n->available_recv_window += reserv;
1077 else if (reserv > 0)
1079 update_window (GNUNET_NO,
1080 &n->available_recv_window,
1081 &n->last_arw_update, n->bpm_in);
1082 if (n->available_recv_window < reserv)
1083 reserv = n->available_recv_window;
1084 n->available_recv_window -= reserv;
1086 old_preference = n->current_preference;
1087 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1088 if (old_preference > n->current_preference)
1090 /* overflow; cap at maximum value */
1091 n->current_preference = (unsigned long long) -1;
1093 update_preference_sum (n->current_preference - old_preference);
1094 cim.reserved_amount = htonl (reserv);
1095 cim.bpm_in = htonl (n->bpm_in);
1096 cim.bpm_out = htonl (n->bpm_out);
1097 cim.latency = GNUNET_TIME_relative_hton (n->last_latency);
1098 cim.preference = n->current_preference;
1100 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1101 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1102 cim.peer = rcm->peer;
1103 c = find_client (client);
1109 #if DEBUG_CORE_CLIENT
1110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1111 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1113 send_to_client (c, &cim.header, GNUNET_NO);
1118 * Check if we have encrypted messages for the specified neighbour
1119 * pending, and if so, check with the transport about sending them
1122 * @param n neighbour to check.
1124 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1128 * Function called when the transport service is ready to
1129 * receive an encrypted message for the respective peer
1131 * @param cls neighbour to use message from
1132 * @param size number of bytes we can transmit
1133 * @param buf where to copy the message
1134 * @return number of bytes transmitted
1137 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1139 struct Neighbour *n = cls;
1140 struct MessageEntry *m;
1145 GNUNET_assert (NULL != (m = n->encrypted_head));
1146 n->encrypted_head = m->next;
1147 if (m->next == NULL)
1148 n->encrypted_tail = NULL;
1153 GNUNET_assert (size >= m->size);
1154 memcpy (cbuf, &m[1], m->size);
1156 n->available_send_window -= m->size;
1157 process_encrypted_neighbour_queue (n);
1159 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1160 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1161 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1162 ret, GNUNET_i2s (&n->peer));
1167 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1168 "Transmission for message of type %u and size %u failed\n",
1169 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1178 * Check if we have plaintext messages for the specified neighbour
1179 * pending, and if so, consider batching and encrypting them (and
1180 * then trigger processing of the encrypted queue if needed).
1182 * @param n neighbour to check.
1184 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1188 * Check if we have encrypted messages for the specified neighbour
1189 * pending, and if so, check with the transport about sending them
1192 * @param n neighbour to check.
1195 process_encrypted_neighbour_queue (struct Neighbour *n)
1197 struct MessageEntry *m;
1200 return; /* request already pending */
1201 if (n->encrypted_head == NULL)
1203 /* encrypted queue empty, try plaintext instead */
1204 process_plaintext_neighbour_queue (n);
1208 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1209 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1210 n->encrypted_head->size,
1211 GNUNET_i2s (&n->peer),
1212 GNUNET_TIME_absolute_get_remaining (n->
1213 encrypted_head->deadline).
1217 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1218 n->encrypted_head->size,
1219 n->encrypted_head->priority,
1220 GNUNET_TIME_absolute_get_remaining
1221 (n->encrypted_head->deadline),
1222 ¬ify_encrypted_transmit_ready,
1226 /* message request too large (oops) */
1228 /* discard encrypted message */
1229 GNUNET_assert (NULL != (m = n->encrypted_head));
1230 n->encrypted_head = m->next;
1231 if (m->next == NULL)
1232 n->encrypted_tail = NULL;
1234 process_encrypted_neighbour_queue (n);
1240 * Decrypt size bytes from in and write the result to out. Use the
1241 * key for inbound traffic of the given neighbour. This function does
1242 * NOT do any integrity-checks on the result.
1244 * @param n neighbour we are receiving from
1245 * @param iv initialization vector to use
1246 * @param in ciphertext
1247 * @param out plaintext
1248 * @param size size of in/out
1249 * @return GNUNET_OK on success
1252 do_decrypt (struct Neighbour *n,
1253 const GNUNET_HashCode * iv,
1254 const void *in, void *out, size_t size)
1256 if (size != (uint16_t) size)
1261 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1262 (n->status != PEER_STATE_KEY_CONFIRMED))
1264 GNUNET_break_op (0);
1265 return GNUNET_SYSERR;
1268 GNUNET_CRYPTO_aes_decrypt (in,
1272 GNUNET_CRYPTO_AesInitializationVector *) iv,
1276 return GNUNET_SYSERR;
1279 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1280 "Decrypted %u bytes from `%4s' using key %u\n",
1281 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1288 * Encrypt size bytes from in and write the result to out. Use the
1289 * key for outbound traffic of the given neighbour.
1291 * @param n neighbour we are sending to
1292 * @param iv initialization vector to use
1293 * @param in ciphertext
1294 * @param out plaintext
1295 * @param size size of in/out
1296 * @return GNUNET_OK on success
1299 do_encrypt (struct Neighbour *n,
1300 const GNUNET_HashCode * iv,
1301 const void *in, void *out, size_t size)
1303 if (size != (uint16_t) size)
1308 GNUNET_assert (size ==
1309 GNUNET_CRYPTO_aes_encrypt (in,
1313 GNUNET_CRYPTO_AesInitializationVector
1316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1317 "Encrypted %u bytes for `%4s' using key %u\n", size,
1318 GNUNET_i2s (&n->peer), n->encrypt_key.crc32);
1325 * Select messages for transmission. This heuristic uses a combination
1326 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1327 * and priority-based discard (in case no feasible schedule exist) and
1328 * speculative optimization (defer any kind of transmission until
1329 * we either create a batch of significant size, 25% of max, or until
1330 * we are close to a deadline). Furthermore, when scheduling the
1331 * heuristic also packs as many messages into the batch as possible,
1332 * starting with those with the earliest deadline. Yes, this is fun.
1334 * @param n neighbour to select messages from
1335 * @param size number of bytes to select for transmission
1336 * @param retry_time set to the time when we should try again
1337 * (only valid if this function returns zero)
1338 * @return number of bytes selected, or 0 if we decided to
1339 * defer scheduling overall; in that case, retry_time is set.
1342 select_messages (struct Neighbour *n,
1343 size_t size, struct GNUNET_TIME_Relative *retry_time)
1345 struct MessageEntry *pos;
1346 struct MessageEntry *min;
1347 struct MessageEntry *last;
1348 unsigned int min_prio;
1349 struct GNUNET_TIME_Absolute t;
1350 struct GNUNET_TIME_Absolute now;
1353 unsigned long long slack; /* how long could we wait before missing deadlines? */
1355 int discard_low_prio;
1357 GNUNET_assert (NULL != n->messages);
1358 now = GNUNET_TIME_absolute_get ();
1359 /* last entry in linked list of messages processed */
1361 /* should we remove the entry with the lowest
1362 priority from consideration for scheduling at the
1364 discard_low_prio = GNUNET_YES;
1365 while (GNUNET_YES == discard_low_prio)
1369 discard_low_prio = GNUNET_NO;
1370 /* calculate number of bytes available for transmission at time "t" */
1371 update_window (GNUNET_NO,
1372 &n->available_send_window,
1373 &n->last_asw_update,
1375 avail = n->available_send_window;
1376 t = n->last_asw_update;
1377 /* how many bytes have we (hypothetically) scheduled so far */
1379 /* maximum time we can wait before transmitting anything
1380 and still make all of our deadlines */
1384 /* note that we use "*2" here because we want to look
1385 a bit further into the future; much more makes no
1386 sense since new message might be scheduled in the
1388 while ((pos != NULL) && (off < size * 2))
1390 if (pos->do_transmit == GNUNET_YES)
1392 /* already removed from consideration */
1396 if (discard_low_prio == GNUNET_NO)
1398 delta = pos->deadline.value;
1399 if (delta < t.value)
1402 delta = t.value - delta;
1403 avail += delta * n->bpm_out / 1000 / 60;
1404 if (avail < pos->size)
1406 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1411 /* update slack, considering both its absolute deadline
1412 and relative deadlines caused by other messages
1413 with their respective load */
1414 slack = GNUNET_MIN (slack, avail / n->bpm_out);
1415 if (pos->deadline.value < now.value)
1419 GNUNET_MIN (slack, pos->deadline.value - now.value);
1423 t.value = GNUNET_MAX (pos->deadline.value, t.value);
1424 if (pos->priority <= min_prio)
1426 /* update min for discard */
1427 min_prio = pos->priority;
1432 if (discard_low_prio)
1434 GNUNET_assert (min != NULL);
1435 /* remove lowest-priority entry from consideration */
1436 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1440 /* guard against sending "tiny" messages with large headers without
1442 if ( (slack > 1000) && (size > 4 * off) )
1444 /* less than 25% of message would be filled with
1445 deadlines still being met if we delay by one
1446 second or more; so just wait for more data */
1447 retry_time->value = slack / 2;
1448 /* reset do_transmit values for next time */
1451 pos->do_transmit = GNUNET_NO;
1456 /* select marked messages (up to size) for transmission */
1461 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1463 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1468 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1472 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1473 "Selected %u bytes of plaintext messages for transmission to `%4s'.\n",
1474 off, GNUNET_i2s (&n->peer));
1481 * Batch multiple messages into a larger buffer.
1483 * @param n neighbour to take messages from
1484 * @param buf target buffer
1485 * @param size size of buf
1486 * @param deadline set to transmission deadline for the result
1487 * @param retry_time set to the time when we should try again
1488 * (only valid if this function returns zero)
1489 * @param priority set to the priority of the batch
1490 * @return number of bytes written to buf (can be zero)
1493 batch_message (struct Neighbour *n,
1496 struct GNUNET_TIME_Absolute *deadline,
1497 struct GNUNET_TIME_Relative *retry_time,
1498 unsigned int *priority)
1500 struct MessageEntry *pos;
1501 struct MessageEntry *prev;
1502 struct MessageEntry *next;
1507 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1508 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1509 if (0 == select_messages (n, size, retry_time))
1511 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1512 "No messages selected, will try again in %llu ms\n",
1518 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1521 if (GNUNET_YES == pos->do_transmit)
1523 GNUNET_assert (pos->size <= size);
1524 memcpy (&buf[ret], &pos[1], pos->size);
1527 *priority += pos->priority;
1529 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1530 "Adding plaintext message with deadline %llu ms to batch\n",
1531 GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1533 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1547 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1548 "Deadline for message batch is %llu ms\n",
1549 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1556 * Remove messages with deadlines that have long expired from
1559 * @param n neighbour to inspect
1562 discard_expired_messages (struct Neighbour *n)
1564 struct MessageEntry *prev;
1565 struct MessageEntry *next;
1566 struct MessageEntry *pos;
1567 struct GNUNET_TIME_Absolute now;
1568 struct GNUNET_TIME_Relative delta;
1570 now = GNUNET_TIME_absolute_get ();
1576 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1577 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1580 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1581 "Message is %llu ms past due, discarding.\n",
1598 * Signature of the main function of a task.
1600 * @param cls closure
1601 * @param tc context information (why was this task triggered now)
1604 retry_plaintext_processing (void *cls,
1605 const struct GNUNET_SCHEDULER_TaskContext *tc)
1607 struct Neighbour *n = cls;
1609 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1610 process_plaintext_neighbour_queue (n);
1615 * Send our key (and encrypted PING) to the other peer.
1617 * @param n the other peer
1619 static void send_key (struct Neighbour *n);
1623 * Check if we have plaintext messages for the specified neighbour
1624 * pending, and if so, consider batching and encrypting them (and
1625 * then trigger processing of the encrypted queue if needed).
1627 * @param n neighbour to check.
1630 process_plaintext_neighbour_queue (struct Neighbour *n)
1632 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1635 struct EncryptedMessage *em; /* encrypted message */
1636 struct EncryptedMessage *ph; /* plaintext header */
1637 struct MessageEntry *me;
1638 unsigned int priority;
1639 struct GNUNET_TIME_Absolute deadline;
1640 struct GNUNET_TIME_Relative retry_time;
1642 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1644 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1645 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1649 case PEER_STATE_DOWN:
1652 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1653 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1654 GNUNET_i2s(&n->peer));
1657 case PEER_STATE_KEY_SENT:
1658 GNUNET_assert (n->retry_set_key_task !=
1659 GNUNET_SCHEDULER_NO_TASK);
1661 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1662 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1663 GNUNET_i2s(&n->peer));
1666 case PEER_STATE_KEY_RECEIVED:
1667 GNUNET_assert (n->retry_set_key_task !=
1668 GNUNET_SCHEDULER_NO_TASK);
1670 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1671 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1672 GNUNET_i2s(&n->peer));
1675 case PEER_STATE_KEY_CONFIRMED:
1676 /* ready to continue */
1679 discard_expired_messages (n);
1680 if (n->messages == NULL)
1683 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1684 "Plaintext message queue for `%4s' is empty.\n",
1685 GNUNET_i2s(&n->peer));
1687 return; /* no pending messages */
1689 if (n->encrypted_head != NULL)
1692 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1693 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1694 GNUNET_i2s(&n->peer));
1696 return; /* wait for messages already encrypted to be
1699 ph = (struct EncryptedMessage *) pbuf;
1700 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1702 used = sizeof (struct EncryptedMessage);
1703 used += batch_message (n,
1705 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1706 &deadline, &retry_time, &priority);
1707 if (used == sizeof (struct EncryptedMessage))
1710 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1711 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1712 GNUNET_i2s(&n->peer));
1714 /* no messages selected for sending, try again later... */
1715 n->retry_plaintext_task =
1716 GNUNET_SCHEDULER_add_delayed (sched,
1718 &retry_plaintext_processing, n);
1721 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1722 ph->inbound_bpm_limit = htonl (n->bpm_in);
1723 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1725 /* setup encryption message header */
1726 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1727 me->deadline = deadline;
1728 me->priority = priority;
1730 em = (struct EncryptedMessage *) &me[1];
1731 em->header.size = htons (used);
1732 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1733 em->reserved = htonl (0);
1734 esize = used - ENCRYPTED_HEADER_SIZE;
1735 GNUNET_CRYPTO_hash (&ph->sequence_number, esize, &em->plaintext_hash);
1738 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1739 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
1741 GNUNET_i2s(&n->peer),
1742 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
1744 GNUNET_assert (GNUNET_OK ==
1746 &em->plaintext_hash,
1747 &ph->sequence_number,
1748 &em->sequence_number, esize));
1749 /* append to transmission list */
1750 if (n->encrypted_tail == NULL)
1751 n->encrypted_head = me;
1753 n->encrypted_tail->next = me;
1754 n->encrypted_tail = me;
1755 process_encrypted_neighbour_queue (n);
1760 * Handle CORE_SEND request.
1763 * @param client the client issuing the request
1764 * @param message the "struct SendMessage"
1767 handle_client_send (void *cls,
1768 struct GNUNET_SERVER_Client *client,
1769 const struct GNUNET_MessageHeader *message);
1773 * Function called to notify us that we either succeeded
1774 * or failed to connect (at the transport level) to another
1775 * peer. We should either free the message we were asked
1776 * to transmit or re-try adding it to the queue.
1778 * @param cls closure
1779 * @param size number of bytes available in buf
1780 * @param buf where the callee should write the message
1781 * @return number of bytes written to buf
1784 send_connect_continuation (void *cls, size_t size, void *buf)
1786 struct SendMessage *sm = cls;
1791 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1792 "Asked to send message to disconnected peer `%4s' and connection failed. Discarding message.\n",
1793 GNUNET_i2s (&sm->peer));
1799 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1800 "Connection to peer `%4s' succeeded, retrying original transmission request\n",
1801 GNUNET_i2s (&sm->peer));
1803 handle_client_send (NULL, NULL, &sm->header);
1810 * Handle CORE_SEND request.
1813 * @param client the client issuing the request
1814 * @param message the "struct SendMessage"
1817 handle_client_send (void *cls,
1818 struct GNUNET_SERVER_Client *client,
1819 const struct GNUNET_MessageHeader *message)
1821 const struct SendMessage *sm;
1822 struct SendMessage *smc;
1823 const struct GNUNET_MessageHeader *mh;
1824 struct Neighbour *n;
1825 struct MessageEntry *prev;
1826 struct MessageEntry *pos;
1827 struct MessageEntry *e;
1828 struct MessageEntry *min_prio_entry;
1829 struct MessageEntry *min_prio_prev;
1830 unsigned int min_prio;
1831 unsigned int queue_size;
1834 msize = ntohs (message->size);
1836 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
1840 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1843 sm = (const struct SendMessage *) message;
1844 msize -= sizeof (struct SendMessage);
1845 mh = (const struct GNUNET_MessageHeader *) &sm[1];
1846 if (msize != ntohs (mh->size))
1850 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1853 n = find_neighbour (&sm->peer);
1857 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1858 "Core received `%s' request for `%4s', will try to establish connection within %llu ms\n",
1860 GNUNET_i2s (&sm->peer),
1861 GNUNET_TIME_absolute_get_remaining
1862 (GNUNET_TIME_absolute_ntoh(sm->deadline)).value);
1864 msize += sizeof (struct SendMessage);
1865 /* ask transport to connect to the peer */
1866 smc = GNUNET_malloc (msize);
1867 memcpy (smc, sm, msize);
1869 GNUNET_TRANSPORT_notify_transmit_ready (transport,
1872 GNUNET_TIME_absolute_get_remaining
1873 (GNUNET_TIME_absolute_ntoh
1875 &send_connect_continuation,
1878 /* transport has already a request pending for this peer! */
1880 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1881 "Dropped second message destined for `%4s' since connection is still down.\n",
1882 GNUNET_i2s(&sm->peer));
1887 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1891 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1892 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
1895 GNUNET_i2s (&sm->peer));
1897 /* bound queue size */
1898 discard_expired_messages (n);
1899 min_prio = (unsigned int) -1;
1900 min_prio_entry = NULL;
1901 min_prio_prev = NULL;
1907 if (pos->priority < min_prio)
1909 min_prio_entry = pos;
1910 min_prio_prev = prev;
1911 min_prio = pos->priority;
1917 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1920 if (ntohl(sm->priority) <= min_prio)
1922 /* discard new entry */
1924 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1925 "Queue full, discarding new request\n");
1928 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1931 /* discard "min_prio_entry" */
1933 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1934 "Queue full, discarding existing older request\n");
1936 if (min_prio_prev == NULL)
1937 n->messages = min_prio_entry->next;
1939 min_prio_prev->next = min_prio_entry->next;
1940 GNUNET_free (min_prio_entry);
1944 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1945 "Adding transmission request for `%4s' to queue\n",
1946 GNUNET_i2s (&sm->peer));
1948 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
1949 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
1950 e->priority = ntohl (sm->priority);
1952 memcpy (&e[1], mh, msize);
1954 /* insert, keep list sorted by deadline */
1957 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
1968 /* consider scheduling now */
1969 process_plaintext_neighbour_queue (n);
1971 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1976 * List of handlers for the messages understood by this
1979 static struct GNUNET_SERVER_MessageHandler handlers[] = {
1980 {&handle_client_init, NULL,
1981 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
1982 {&handle_client_request_configure, NULL,
1983 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONFIGURE,
1984 sizeof (struct RequestConfigureMessage)},
1985 {&handle_client_send, NULL,
1986 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
1992 * PEERINFO is giving us a HELLO for a peer. Add the
1993 * public key to the neighbour's struct and retry
1994 * send_key. Or, if we did not get a HELLO, just do
1998 * @param peer the peer for which this is the HELLO
1999 * @param hello HELLO message of that peer
2000 * @param trust amount of trust we currently have in that peer
2003 process_hello_retry_send_key (void *cls,
2004 const struct GNUNET_PeerIdentity *peer,
2005 const struct GNUNET_HELLO_Message *hello,
2008 struct Neighbour *n;
2012 n = find_neighbour (peer);
2015 if (n->public_key != NULL)
2018 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2019 "Received new `%s' message for `%4s', initiating key exchange.\n",
2024 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2025 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2027 GNUNET_free (n->public_key);
2028 n->public_key = NULL;
2036 * Task that will retry "send_key" if our previous attempt failed
2040 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2042 struct Neighbour *n = cls;
2044 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2045 n->set_key_retry_frequency =
2046 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2052 * Send our key (and encrypted PING) to the other peer.
2054 * @param n the other peer
2057 send_key (struct Neighbour *n)
2059 struct SetKeyMessage *sm;
2060 struct MessageEntry *me;
2061 struct PingMessage pp;
2062 struct PingMessage *pm;
2065 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2066 "Asked to perform key exchange with `%4s'.\n",
2067 GNUNET_i2s (&n->peer));
2069 if (n->public_key == NULL)
2071 /* lookup n's public key, then try again */
2073 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2074 "Lacking public key for `%4s', trying to obtain one.\n",
2075 GNUNET_i2s (&n->peer));
2077 GNUNET_PEERINFO_for_all (cfg,
2081 GNUNET_TIME_UNIT_MINUTES,
2082 &process_hello_retry_send_key, NULL);
2085 /* first, set key message */
2086 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2087 sizeof (struct SetKeyMessage));
2088 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2089 me->priority = SET_KEY_PRIORITY;
2090 me->size = sizeof (struct SetKeyMessage);
2091 if (n->encrypted_head == NULL)
2092 n->encrypted_head = me;
2094 n->encrypted_tail->next = me;
2095 n->encrypted_tail = me;
2096 sm = (struct SetKeyMessage *) &me[1];
2097 sm->header.size = htons (sizeof (struct SetKeyMessage));
2098 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2099 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2100 PEER_STATE_KEY_SENT : n->status));
2102 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2103 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2104 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2105 sizeof (struct GNUNET_PeerIdentity));
2106 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2107 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2108 sm->target = n->peer;
2109 GNUNET_assert (GNUNET_OK ==
2110 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2112 GNUNET_CRYPTO_AesSessionKey),
2114 &sm->encrypted_key));
2115 GNUNET_assert (GNUNET_OK ==
2116 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2119 /* second, encrypted PING message */
2120 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2121 sizeof (struct PingMessage));
2122 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2123 me->priority = PING_PRIORITY;
2124 me->size = sizeof (struct PingMessage);
2125 n->encrypted_tail->next = me;
2126 n->encrypted_tail = me;
2127 pm = (struct PingMessage *) &me[1];
2128 pm->header.size = htons (sizeof (struct PingMessage));
2129 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2130 pp.challenge = htonl (n->ping_challenge);
2131 pp.target = n->peer;
2133 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2134 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2135 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2136 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2137 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2139 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2142 &n->peer.hashPubKey,
2145 sizeof (struct PingMessage) -
2146 sizeof (struct GNUNET_MessageHeader));
2150 case PEER_STATE_DOWN:
2151 n->status = PEER_STATE_KEY_SENT;
2153 case PEER_STATE_KEY_SENT:
2155 case PEER_STATE_KEY_RECEIVED:
2157 case PEER_STATE_KEY_CONFIRMED:
2164 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2165 "Have %llu ms left for `%s' transmission.\n",
2166 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2169 /* trigger queue processing */
2170 process_encrypted_neighbour_queue (n);
2171 if (n->status != PEER_STATE_KEY_CONFIRMED)
2172 n->retry_set_key_task
2173 = GNUNET_SCHEDULER_add_delayed (sched,
2174 n->set_key_retry_frequency,
2175 &set_key_retry_task, n);
2180 * We received a SET_KEY message. Validate and update
2181 * our key material and status.
2183 * @param n the neighbour from which we received message m
2184 * @param m the set key message we received
2187 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2191 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2192 * the neighbour's struct and retry handling the set_key message. Or,
2193 * if we did not get a HELLO, just free the set key message.
2195 * @param cls pointer to the set key message
2196 * @param peer the peer for which this is the HELLO
2197 * @param hello HELLO message of that peer
2198 * @param trust amount of trust we currently have in that peer
2201 process_hello_retry_handle_set_key (void *cls,
2202 const struct GNUNET_PeerIdentity *peer,
2203 const struct GNUNET_HELLO_Message *hello,
2206 struct SetKeyMessage *sm = cls;
2207 struct Neighbour *n;
2214 n = find_neighbour (peer);
2220 if (n->public_key != NULL)
2221 return; /* multiple HELLOs match!? */
2223 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2224 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2226 GNUNET_break_op (0);
2227 GNUNET_free (n->public_key);
2228 n->public_key = NULL;
2232 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2233 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2234 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2236 handle_set_key (n, sm);
2241 * We received a PING message. Validate and transmit
2244 * @param n sender of the PING
2245 * @param m the encrypted PING message itself
2248 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2250 struct PingMessage t;
2251 struct PingMessage *tp;
2252 struct MessageEntry *me;
2255 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2256 "Core service receives `%s' request from `%4s'.\n",
2257 "PING", GNUNET_i2s (&n->peer));
2261 &my_identity.hashPubKey,
2264 sizeof (struct PingMessage) -
2265 sizeof (struct GNUNET_MessageHeader)))
2268 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2269 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2271 GNUNET_i2s (&t.target),
2272 ntohl (t.challenge), n->decrypt_key.crc32);
2273 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2274 "Target of `%s' request is `%4s'.\n",
2275 "PING", GNUNET_i2s (&t.target));
2277 if (0 != memcmp (&t.target,
2278 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2280 GNUNET_break_op (0);
2283 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2284 sizeof (struct PingMessage));
2285 if (n->encrypted_tail != NULL)
2286 n->encrypted_tail->next = me;
2289 n->encrypted_tail = me;
2290 n->encrypted_head = me;
2292 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2293 me->priority = PONG_PRIORITY;
2294 me->size = sizeof (struct PingMessage);
2295 tp = (struct PingMessage *) &me[1];
2296 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2297 tp->header.size = htons (sizeof (struct PingMessage));
2299 &my_identity.hashPubKey,
2302 sizeof (struct PingMessage) -
2303 sizeof (struct GNUNET_MessageHeader));
2305 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2306 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2307 ntohl (t.challenge), n->encrypt_key.crc32);
2309 /* trigger queue processing */
2310 process_encrypted_neighbour_queue (n);
2315 * We received a SET_KEY message. Validate and update
2316 * our key material and status.
2318 * @param n the neighbour from which we received message m
2319 * @param m the set key message we received
2322 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2324 struct SetKeyMessage *m_cpy;
2325 struct GNUNET_TIME_Absolute t;
2326 struct GNUNET_CRYPTO_AesSessionKey k;
2327 struct PingMessage *ping;
2328 enum PeerStateMachine sender_status;
2331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2332 "Core service receives `%s' request from `%4s'.\n",
2333 "SET_KEY", GNUNET_i2s (&n->peer));
2335 if (n->public_key == NULL)
2338 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2339 "Lacking public key for peer, trying to obtain one.\n");
2341 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2342 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2343 /* lookup n's public key, then try again */
2344 GNUNET_PEERINFO_for_all (cfg,
2348 GNUNET_TIME_UNIT_MINUTES,
2349 &process_hello_retry_handle_set_key, m_cpy);
2352 if (0 != memcmp (&m->target,
2354 sizeof (struct GNUNET_PeerIdentity)))
2356 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2357 _("Received `%s' message that was not for me. Ignoring.\n"));
2360 if ((ntohl (m->purpose.size) !=
2361 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2362 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2363 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2364 sizeof (struct GNUNET_PeerIdentity)) ||
2366 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2367 &m->purpose, &m->signature, n->public_key)))
2369 /* invalid signature */
2370 GNUNET_break_op (0);
2373 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2374 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2375 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2376 (t.value < n->decrypt_key_created.value))
2378 /* this could rarely happen due to massive re-ordering of
2379 messages on the network level, but is most likely either
2380 a bug or some adversary messing with us. Report. */
2381 GNUNET_break_op (0);
2385 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
2387 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2390 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2391 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2392 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2394 /* failed to decrypt !? */
2395 GNUNET_break_op (0);
2400 if (n->decrypt_key_created.value != t.value)
2402 /* fresh key, reset sequence numbers */
2403 n->last_sequence_number_received = 0;
2404 n->last_packets_bitmap = 0;
2405 n->decrypt_key_created = t;
2407 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2410 case PEER_STATE_DOWN:
2411 n->status = PEER_STATE_KEY_RECEIVED;
2413 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2414 "Responding to `%s' with my own key.\n", "SET_KEY");
2418 case PEER_STATE_KEY_SENT:
2419 case PEER_STATE_KEY_RECEIVED:
2420 n->status = PEER_STATE_KEY_RECEIVED;
2421 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2422 (sender_status != PEER_STATE_KEY_CONFIRMED))
2425 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2426 "Responding to `%s' with my own key (other peer has status %u).\n",
2427 "SET_KEY", sender_status);
2432 case PEER_STATE_KEY_CONFIRMED:
2433 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2434 (sender_status != PEER_STATE_KEY_CONFIRMED))
2437 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2438 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2439 "SET_KEY", sender_status);
2448 if (n->pending_ping != NULL)
2450 ping = n->pending_ping;
2451 n->pending_ping = NULL;
2452 handle_ping (n, ping);
2459 * We received a PONG message. Validate and update
2462 * @param n sender of the PONG
2463 * @param m the encrypted PONG message itself
2466 handle_pong (struct Neighbour *n, const struct PingMessage *m)
2468 struct PingMessage t;
2471 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2472 "Core service receives `%s' request from `%4s'.\n",
2473 "PONG", GNUNET_i2s (&n->peer));
2477 &n->peer.hashPubKey,
2480 sizeof (struct PingMessage) -
2481 sizeof (struct GNUNET_MessageHeader)))
2484 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2485 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2487 GNUNET_i2s (&t.target),
2488 ntohl (t.challenge), n->decrypt_key.crc32);
2490 if ((0 != memcmp (&t.target,
2492 sizeof (struct GNUNET_PeerIdentity))) ||
2493 (n->ping_challenge != ntohl (t.challenge)))
2495 /* PONG malformed */
2497 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2498 "Received malfromed `%s' wanted sender `%4s' with challenge %u\n",
2499 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2500 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2501 "Received malfromed `%s' received from `%4s' with challenge %u\n",
2502 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2504 GNUNET_break_op (0);
2509 case PEER_STATE_DOWN:
2510 GNUNET_break (0); /* should be impossible */
2512 case PEER_STATE_KEY_SENT:
2513 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2515 case PEER_STATE_KEY_RECEIVED:
2516 n->status = PEER_STATE_KEY_CONFIRMED;
2517 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2519 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2520 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2522 process_encrypted_neighbour_queue (n);
2524 case PEER_STATE_KEY_CONFIRMED:
2525 /* duplicate PONG? */
2535 * Send a P2P message to a client.
2537 * @param sender who sent us the message?
2538 * @param client who should we give the message to?
2539 * @param m contains the message to transmit
2540 * @param msize number of bytes in buf to transmit
2543 send_p2p_message_to_client (struct Neighbour *sender,
2544 struct Client *client,
2545 const void *m, size_t msize)
2547 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2548 struct NotifyTrafficMessage *ntm;
2551 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2552 "Core service passes message from `%4s' of type %u to client.\n",
2553 GNUNET_i2s(&sender->peer),
2554 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2556 ntm = (struct NotifyTrafficMessage *) buf;
2557 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2558 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2559 ntm->reserved = htonl (0);
2560 ntm->peer = sender->peer;
2561 memcpy (&ntm[1], m, msize);
2562 send_to_client (client, &ntm->header, GNUNET_YES);
2567 * Deliver P2P message to interested clients.
2569 * @param sender who sent us the message?
2570 * @param m the message
2571 * @param msize size of the message (including header)
2574 deliver_message (struct Neighbour *sender,
2575 const struct GNUNET_MessageHeader *m, size_t msize)
2577 struct Client *cpos;
2582 type = ntohs (m->type);
2584 while (cpos != NULL)
2586 deliver_full = GNUNET_NO;
2587 if (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND)
2588 deliver_full = GNUNET_YES;
2591 for (tpos = 0; tpos < cpos->tcnt; tpos++)
2593 if (type != cpos->types[tpos])
2595 deliver_full = GNUNET_YES;
2599 if (GNUNET_YES == deliver_full)
2600 send_p2p_message_to_client (sender, cpos, m, msize);
2601 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2602 send_p2p_message_to_client (sender, cpos, m,
2603 sizeof (struct GNUNET_MessageHeader));
2610 * Align P2P message and then deliver to interested clients.
2612 * @param sender who sent us the message?
2613 * @param buffer unaligned (!) buffer containing message
2614 * @param msize size of the message (including header)
2617 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
2621 /* TODO: call to statistics? */
2622 memcpy (abuf, buffer, msize);
2623 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
2628 * Deliver P2P messages to interested clients.
2630 * @param sender who sent us the message?
2631 * @param buffer buffer containing messages, can be modified
2632 * @param buffer_size size of the buffer (overall)
2633 * @param offset offset where messages in the buffer start
2636 deliver_messages (struct Neighbour *sender,
2637 const char *buffer, size_t buffer_size, size_t offset)
2639 struct GNUNET_MessageHeader *mhp;
2640 struct GNUNET_MessageHeader mh;
2644 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
2646 if (0 != offset % sizeof (uint16_t))
2648 /* outch, need to copy to access header */
2649 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
2654 /* can access header directly */
2655 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
2657 msize = ntohs (mhp->size);
2658 if (msize + offset > buffer_size)
2660 /* malformed message, header says it is larger than what
2661 would fit into the overall buffer */
2662 GNUNET_break_op (0);
2665 #if HAVE_UNALIGNED_64_ACCESS
2666 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
2668 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
2670 if (GNUNET_YES == need_align)
2671 align_and_deliver (sender, &buffer[offset], msize);
2673 deliver_message (sender,
2674 (const struct GNUNET_MessageHeader *)
2675 &buffer[offset], msize);
2682 * We received an encrypted message. Decrypt, validate and
2683 * pass on to the appropriate clients.
2686 handle_encrypted_message (struct Neighbour *n,
2687 const struct EncryptedMessage *m)
2689 size_t size = ntohs (m->header.size);
2691 struct EncryptedMessage *pt; /* plaintext */
2695 struct GNUNET_TIME_Absolute t;
2698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2699 "Core service receives `%s' request from `%4s'.\n",
2700 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
2706 &m->sequence_number,
2707 &buf[ENCRYPTED_HEADER_SIZE], size - ENCRYPTED_HEADER_SIZE))
2709 pt = (struct EncryptedMessage *) buf;
2712 GNUNET_CRYPTO_hash (&pt->sequence_number,
2713 size - ENCRYPTED_HEADER_SIZE, &ph);
2714 if (0 != memcmp (&ph, &m->plaintext_hash, sizeof (GNUNET_HashCode)))
2716 /* checksum failed */
2717 GNUNET_break_op (0);
2721 /* validate sequence number */
2722 snum = ntohl (pt->sequence_number);
2723 if (n->last_sequence_number_received == snum)
2725 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2726 "Received duplicate message, ignoring.\n");
2727 /* duplicate, ignore */
2730 if ((n->last_sequence_number_received > snum) &&
2731 (n->last_sequence_number_received - snum > 32))
2733 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2734 "Received ancient out of sequence message, ignoring.\n");
2735 /* ancient out of sequence, ignore */
2738 if (n->last_sequence_number_received > snum)
2740 unsigned int rotbit =
2741 1 << (n->last_sequence_number_received - snum - 1);
2742 if ((n->last_packets_bitmap & rotbit) != 0)
2744 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2745 "Received duplicate message, ignoring.\n");
2746 /* duplicate, ignore */
2749 n->last_packets_bitmap |= rotbit;
2751 if (n->last_sequence_number_received < snum)
2753 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
2754 n->last_sequence_number_received = snum;
2757 /* check timestamp */
2758 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
2759 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
2761 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2763 ("Message received far too old (%llu ms). Content ignored.\n"),
2764 GNUNET_TIME_absolute_get_duration (t).value);
2768 /* process decrypted message(s) */
2769 update_window (GNUNET_YES,
2770 &n->available_send_window,
2771 &n->last_asw_update,
2773 n->bpm_out_external_limit = ntohl (pt->inbound_bpm_limit);
2774 n->bpm_out = GNUNET_MAX (n->bpm_out_external_limit,
2775 n->bpm_out_internal_limit);
2776 n->last_activity = GNUNET_TIME_absolute_get ();
2777 off = sizeof (struct EncryptedMessage);
2778 deliver_messages (n, buf, size, off);
2783 * Function called by the transport for each received message.
2785 * @param cls closure
2786 * @param latency estimated latency for communicating with the
2788 * @param peer (claimed) identity of the other peer
2789 * @param message the message
2792 handle_transport_receive (void *cls,
2793 struct GNUNET_TIME_Relative latency,
2794 const struct GNUNET_PeerIdentity *peer,
2795 const struct GNUNET_MessageHeader *message)
2797 struct Neighbour *n;
2798 struct GNUNET_TIME_Absolute now;
2804 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2805 "Received message of type %u from `%4s', demultiplexing.\n",
2806 ntohs (message->type), GNUNET_i2s (peer));
2808 n = find_neighbour (peer);
2814 n->last_latency = latency;
2815 up = (n->status == PEER_STATE_KEY_CONFIRMED);
2816 type = ntohs (message->type);
2817 size = ntohs (message->size);
2820 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
2821 if (size != sizeof (struct SetKeyMessage))
2823 GNUNET_break_op (0);
2826 handle_set_key (n, (const struct SetKeyMessage *) message);
2828 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
2829 if (size < sizeof (struct EncryptedMessage) +
2830 sizeof (struct GNUNET_MessageHeader))
2832 GNUNET_break_op (0);
2835 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2836 (n->status != PEER_STATE_KEY_CONFIRMED))
2838 GNUNET_break_op (0);
2841 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
2843 case GNUNET_MESSAGE_TYPE_CORE_PING:
2844 if (size != sizeof (struct PingMessage))
2846 GNUNET_break_op (0);
2849 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2850 (n->status != PEER_STATE_KEY_CONFIRMED))
2853 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2854 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
2855 "PING", GNUNET_i2s (&n->peer));
2857 GNUNET_free_non_null (n->pending_ping);
2858 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
2859 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
2862 handle_ping (n, (const struct PingMessage *) message);
2864 case GNUNET_MESSAGE_TYPE_CORE_PONG:
2865 if (size != sizeof (struct PingMessage))
2867 GNUNET_break_op (0);
2870 if ((n->status != PEER_STATE_KEY_SENT) &&
2871 (n->status != PEER_STATE_KEY_RECEIVED) &&
2872 (n->status != PEER_STATE_KEY_CONFIRMED))
2874 /* could not decrypt pong, oops! */
2875 GNUNET_break_op (0);
2878 handle_pong (n, (const struct PingMessage *) message);
2881 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2882 _("Unsupported message of type %u received.\n"), type);
2885 if (n->status == PEER_STATE_KEY_CONFIRMED)
2887 now = GNUNET_TIME_absolute_get ();
2888 n->last_activity = now;
2890 n->time_established = now;
2896 * Function that recalculates the bandwidth quota for the
2897 * given neighbour and transmits it to the transport service.
2899 * @param cls neighbour for the quota update
2903 neighbour_quota_update (void *cls,
2904 const struct GNUNET_SCHEDULER_TaskContext *tc);
2908 * Schedule the task that will recalculate the bandwidth
2909 * quota for this peer (and possibly force a disconnect of
2910 * idle peers by calculating a bandwidth of zero).
2913 schedule_quota_update (struct Neighbour *n)
2915 GNUNET_assert (n->quota_update_task ==
2916 GNUNET_SCHEDULER_NO_TASK);
2917 n->quota_update_task
2918 = GNUNET_SCHEDULER_add_delayed (sched,
2919 QUOTA_UPDATE_FREQUENCY,
2920 &neighbour_quota_update,
2926 * Function that recalculates the bandwidth quota for the
2927 * given neighbour and transmits it to the transport service.
2929 * @param cls neighbour for the quota update
2933 neighbour_quota_update (void *cls,
2934 const struct GNUNET_SCHEDULER_TaskContext *tc)
2936 struct Neighbour *n = cls;
2940 unsigned long long distributable;
2942 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
2943 /* calculate relative preference among all neighbours;
2944 divides by a bit more to avoid division by zero AND to
2945 account for possibility of new neighbours joining any time
2946 AND to convert to double... */
2947 pref_rel = n->current_preference / (1.0 + preference_sum);
2949 if (bandwidth_target_out > neighbour_count * MIN_BPM_PER_PEER)
2950 distributable = bandwidth_target_out - neighbour_count * MIN_BPM_PER_PEER;
2951 share = distributable * pref_rel;
2952 q_in = MIN_BPM_PER_PEER + (unsigned long long) share;
2953 /* check if we want to disconnect for good due to inactivity */
2954 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
2955 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
2956 q_in = 0; /* force disconnect */
2957 if ( (n->bpm_in + MIN_BPM_CHANGE < q_in) ||
2958 (n->bpm_in - MIN_BPM_CHANGE > q_in) )
2961 GNUNET_TRANSPORT_set_quota (transport,
2965 GNUNET_TIME_UNIT_FOREVER_REL,
2968 schedule_quota_update (n);
2973 * Function called by transport to notify us that
2974 * a peer connected to us (on the network level).
2976 * @param cls closure
2977 * @param peer the peer that connected
2978 * @param latency current latency of the connection
2981 handle_transport_notify_connect (void *cls,
2982 const struct GNUNET_PeerIdentity *peer,
2983 struct GNUNET_TIME_Relative latency)
2985 struct Neighbour *n;
2986 struct GNUNET_TIME_Absolute now;
2987 struct ConnectNotifyMessage cnm;
2989 n = find_neighbour (peer);
2992 /* duplicate connect notification!? */
2996 now = GNUNET_TIME_absolute_get ();
2997 n = GNUNET_malloc (sizeof (struct Neighbour));
2998 n->next = neighbours;
3002 n->last_latency = latency;
3003 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
3004 n->encrypt_key_created = now;
3005 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
3006 n->last_asw_update = now;
3007 n->last_arw_update = now;
3008 n->bpm_in = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
3009 n->bpm_out = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
3010 n->bpm_out_internal_limit = (uint32_t) - 1;
3011 n->bpm_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
3012 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3015 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3016 "Received connection from `%4s'.\n",
3017 GNUNET_i2s (&n->peer));
3019 schedule_quota_update (n);
3020 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3021 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3022 cnm.reserved = htonl (0);
3024 send_to_all_clients (&cnm.header, GNUNET_YES);
3029 * Free the given entry for the neighbour (it has
3030 * already been removed from the list at this point).
3032 * @param n neighbour to free
3035 free_neighbour (struct Neighbour *n)
3037 struct MessageEntry *m;
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 ConnectNotifyMessage 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 ConnectNotifyMessage));
3102 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3103 cnm.reserved = htonl (0);
3105 send_to_all_clients (&cnm.header, GNUNET_YES);
3111 * Last task run during shutdown. Disconnects us from
3115 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3117 struct Neighbour *n;
3121 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3122 "Core service shutting down.\n");
3124 GNUNET_assert (transport != NULL);
3125 GNUNET_TRANSPORT_disconnect (transport);
3127 while (NULL != (n = neighbours))
3129 neighbours = n->next;
3130 GNUNET_assert (neighbour_count > 0);
3134 while (NULL != (c = clients))
3135 handle_client_disconnect (NULL, c->client_handle);
3136 if (my_private_key != NULL)
3137 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3142 * Initiate core service.
3144 * @param cls closure
3145 * @param s scheduler to use
3146 * @param serv the initialized server
3147 * @param c configuration to use
3151 struct GNUNET_SCHEDULER_Handle *s,
3152 struct GNUNET_SERVER_Handle *serv,
3153 const struct GNUNET_CONFIGURATION_Handle *c)
3156 unsigned long long qin;
3157 unsigned long long qout;
3158 unsigned long long tneigh;
3164 /* parse configuration */
3167 GNUNET_CONFIGURATION_get_value_number (c,
3170 &bandwidth_target_in)) ||
3172 GNUNET_CONFIGURATION_get_value_number (c,
3175 &bandwidth_target_out)) ||
3178 GNUNET_CONFIGURATION_get_value_number (c,
3183 GNUNET_CONFIGURATION_get_value_number (c,
3185 "ZZ_LIMIT", &tneigh)) ||
3188 GNUNET_CONFIGURATION_get_value_filename (c,
3190 "HOSTKEY", &keyfile)))
3192 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3194 ("Core service is lacking key configuration settings. Exiting.\n"));
3195 GNUNET_SCHEDULER_shutdown (s);
3198 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3199 GNUNET_free (keyfile);
3200 if (my_private_key == NULL)
3202 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3203 _("Core service could not access hostkey. Exiting.\n"));
3204 GNUNET_SCHEDULER_shutdown (s);
3207 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3208 GNUNET_CRYPTO_hash (&my_public_key,
3209 sizeof (my_public_key), &my_identity.hashPubKey);
3210 /* setup notification */
3212 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3213 /* setup transport connection */
3214 transport = GNUNET_TRANSPORT_connect (sched,
3217 &handle_transport_receive,
3218 &handle_transport_notify_connect,
3219 &handle_transport_notify_disconnect);
3220 GNUNET_assert (NULL != transport);
3221 GNUNET_SCHEDULER_add_delayed (sched,
3222 GNUNET_TIME_UNIT_FOREVER_REL,
3223 &cleaning_task, NULL);
3224 /* process client requests */
3225 GNUNET_SERVER_add_handlers (server, handlers);
3226 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3227 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3233 * The main function for the transport service.
3235 * @param argc number of arguments from the command line
3236 * @param argv command line arguments
3237 * @return 0 ok, 1 on error
3240 main (int argc, char *const *argv)
3242 return (GNUNET_OK ==
3243 GNUNET_SERVICE_run (argc,
3246 GNUNET_SERVICE_OPTION_NONE,
3247 &run, NULL)) ? 0 : 1;
3250 /* end of gnunet-service-core.c */