2 This file is part of GNUnet.
3 (C) 2009 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file core/gnunet-service-core.c
23 * @brief high-level P2P messaging
24 * @author Christian Grothoff
27 * - not all GNUNET_CORE_OPTION_SEND_* flags are fully supported yet
28 * (i.e. no SEND_XXX_OUTBOUND).
29 * - 'REQUEST_DISCONNECT' is not implemented (transport API is lacking!)
31 * Considerations for later:
32 * - check that hostkey used by transport (for HELLOs) is the
33 * same as the hostkey that we are using!
34 * - add code to send PINGs if we are about to time-out otherwise
35 * - optimize lookup (many O(n) list traversals
36 * could ideally be changed to O(1) hash map lookups)
39 #include "gnunet_constants.h"
40 #include "gnunet_util_lib.h"
41 #include "gnunet_hello_lib.h"
42 #include "gnunet_peerinfo_service.h"
43 #include "gnunet_protocols.h"
44 #include "gnunet_signatures.h"
45 #include "gnunet_transport_service.h"
50 * Receive and send buffer windows grow over time. For
51 * how long can 'unused' bandwidth accumulate before we
52 * need to cap it? (specified in ms).
54 #define MAX_WINDOW_TIME (5 * 60 * 1000)
57 * Minimum of bytes per minute (out) to assign to any connected peer.
58 * Should be rather low; values larger than DEFAULT_BPM_IN_OUT make no
61 #define MIN_BPM_PER_PEER GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT
64 * What is the smallest change (in number of bytes per minute)
65 * that we consider significant enough to bother triggering?
67 #define MIN_BPM_CHANGE 32
70 * After how much time past the "official" expiration time do
71 * we discard messages? Should not be zero since we may
72 * intentionally defer transmission until close to the deadline
73 * and then may be slightly past the deadline due to inaccuracy
74 * in sleep and our own CPU consumption.
76 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
79 * What is the maximum delay for a SET_KEY message?
81 #define MAX_SET_KEY_DELAY GNUNET_TIME_UNIT_SECONDS
84 * What how long do we wait for SET_KEY confirmation initially?
86 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3)
89 * What is the maximum delay for a PING message?
91 #define MAX_PING_DELAY GNUNET_TIME_UNIT_SECONDS
94 * What is the maximum delay for a PONG message?
96 #define MAX_PONG_DELAY GNUNET_TIME_UNIT_SECONDS
99 * How often do we recalculate bandwidth quotas?
101 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_UNIT_SECONDS
104 * What is the priority for a SET_KEY message?
106 #define SET_KEY_PRIORITY 0xFFFFFF
109 * What is the priority for a PING message?
111 #define PING_PRIORITY 0xFFFFFF
114 * What is the priority for a PONG message?
116 #define PONG_PRIORITY 0xFFFFFF
119 * How many messages do we queue per peer at most?
121 #define MAX_PEER_QUEUE_SIZE 16
124 * How many non-mandatory messages do we queue per client at most?
126 #define MAX_CLIENT_QUEUE_SIZE 32
129 * What is the maximum age of a message for us to consider
130 * processing it? Note that this looks at the timestamp used
131 * by the other peer, so clock skew between machines does
132 * come into play here. So this should be picked high enough
133 * so that a little bit of clock skew does not prevent peers
134 * from connecting to us.
136 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
139 * What is the maximum size for encrypted messages? Note that this
140 * number imposes a clear limit on the maximum size of any message.
141 * Set to a value close to 64k but not so close that transports will
142 * have trouble with their headers.
144 #define MAX_ENCRYPTED_MESSAGE_SIZE (63 * 1024)
148 * State machine for our P2P encryption handshake. Everyone starts in
149 * "DOWN", if we receive the other peer's key (other peer initiated)
150 * we start in state RECEIVED (since we will immediately send our
151 * own); otherwise we start in SENT. If we get back a PONG from
152 * within either state, we move up to CONFIRMED (the PONG will always
153 * be sent back encrypted with the key we sent to the other peer).
155 enum PeerStateMachine
159 PEER_STATE_KEY_RECEIVED,
160 PEER_STATE_KEY_CONFIRMED
165 * Number of bytes (at the beginning) of "struct EncryptedMessage"
166 * that are NOT encrypted.
168 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t) + sizeof(GNUNET_HashCode))
172 * Encapsulation for encrypted messages exchanged between
173 * peers. Followed by the actual encrypted data.
175 struct EncryptedMessage
178 * Message type is either CORE_ENCRYPTED_MESSAGE.
180 struct GNUNET_MessageHeader header;
185 uint32_t reserved GNUNET_PACKED;
188 * Hash of the plaintext, used to verify message integrity;
189 * ALSO used as the IV for the symmetric cipher! Everything
190 * after this hash will be encrypted. ENCRYPTED_HEADER_SIZE
191 * must be set to the offset of the next field.
193 GNUNET_HashCode plaintext_hash;
196 * Sequence number, in network byte order. This field
197 * must be the first encrypted/decrypted field and the
198 * first byte that is hashed for the plaintext hash.
200 uint32_t sequence_number GNUNET_PACKED;
203 * Desired bandwidth (how much we should send to this
204 * peer / how much is the sender willing to receive),
205 * in bytes per minute.
207 uint32_t inbound_bpm_limit GNUNET_PACKED;
210 * Timestamp. Used to prevent reply of ancient messages
211 * (recent messages are caught with the sequence number).
213 struct GNUNET_TIME_AbsoluteNBO timestamp;
218 * We're sending an (encrypted) PING to the other peer to check if he
219 * can decrypt. The other peer should respond with a PONG with the
220 * same content, except this time encrypted with the receiver's key.
225 * Message type is either CORE_PING or CORE_PONG.
227 struct GNUNET_MessageHeader header;
230 * Random number chosen to make reply harder.
232 uint32_t challenge GNUNET_PACKED;
235 * Intended target of the PING, used primarily to check
236 * that decryption actually worked.
238 struct GNUNET_PeerIdentity target;
243 * Message transmitted to set (or update) a session key.
249 * Message type is either CORE_SET_KEY.
251 struct GNUNET_MessageHeader header;
254 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
256 int32_t sender_status GNUNET_PACKED;
259 * Purpose of the signature, will be
260 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
262 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
265 * At what time was this key created?
267 struct GNUNET_TIME_AbsoluteNBO creation_time;
270 * The encrypted session key.
272 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
275 * Who is the intended recipient?
277 struct GNUNET_PeerIdentity target;
280 * Signature of the stuff above (starting at purpose).
282 struct GNUNET_CRYPTO_RsaSignature signature;
288 * Message waiting for transmission. This struct
289 * is followed by the actual content of the message.
295 * We keep messages in a linked list (for now).
297 struct MessageEntry *next;
300 * By when are we supposed to transmit this message?
302 struct GNUNET_TIME_Absolute deadline;
305 * How important is this message to us?
307 unsigned int priority;
310 * How long is the message? (number of bytes following
311 * the "struct MessageEntry", but not including the
312 * size of "struct MessageEntry" itself!)
317 * Was this message selected for transmission in the
318 * current round? GNUNET_YES or GNUNET_NO.
328 * We keep neighbours in a linked list (for now).
330 struct Neighbour *next;
333 * Unencrypted messages destined for this peer.
335 struct MessageEntry *messages;
338 * Head of the batched, encrypted message queue (already ordered,
339 * transmit starting with the head).
341 struct MessageEntry *encrypted_head;
344 * Tail of the batched, encrypted message queue (already ordered,
345 * append new messages to tail)
347 struct MessageEntry *encrypted_tail;
350 * Handle for pending requests for transmission to this peer
351 * with the transport service. NULL if no request is pending.
353 struct GNUNET_TRANSPORT_TransmitHandle *th;
356 * Public key of the neighbour, NULL if we don't have it yet.
358 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
361 * We received a PING message before we got the "public_key"
362 * (or the SET_KEY). We keep it here until we have a key
363 * to decrypt it. NULL if no PING is pending.
365 struct PingMessage *pending_ping;
368 * Non-NULL if we are currently looking up HELLOs for this peer.
371 struct GNUNET_PEERINFO_IteratorContext *pitr;
374 * SetKeyMessage to transmit, NULL if we are not currently trying
377 struct SetKeyMessage *skm;
380 * Identity of the neighbour.
382 struct GNUNET_PeerIdentity peer;
385 * Key we use to encrypt our messages for the other peer
386 * (initialized by us when we do the handshake).
388 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
391 * Key we use to decrypt messages from the other peer
392 * (given to us by the other peer during the handshake).
394 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
397 * ID of task used for re-trying plaintext scheduling.
399 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
402 * ID of task used for re-trying SET_KEY and PING message.
404 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
407 * ID of task used for updating bandwidth quota for this neighbour.
409 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
412 * At what time did we generate our encryption key?
414 struct GNUNET_TIME_Absolute encrypt_key_created;
417 * At what time did the other peer generate the decryption key?
419 struct GNUNET_TIME_Absolute decrypt_key_created;
422 * At what time did we initially establish (as in, complete session
423 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
425 struct GNUNET_TIME_Absolute time_established;
428 * At what time did we last receive an encrypted message from the
429 * other peer? Should be zero if status != KEY_CONFIRMED.
431 struct GNUNET_TIME_Absolute last_activity;
434 * Last latency observed from this peer.
436 struct GNUNET_TIME_Relative last_latency;
439 * At what frequency are we currently re-trying SET_KEY messages?
441 struct GNUNET_TIME_Relative set_key_retry_frequency;
444 * Time of our last update to the "available_send_window".
446 struct GNUNET_TIME_Absolute last_asw_update;
449 * Time of our last update to the "available_recv_window".
451 struct GNUNET_TIME_Absolute last_arw_update;
454 * Number of bytes that we are eligible to transmit to this
455 * peer at this point. Incremented every minute by max_out_bpm,
456 * bounded by max_bpm (no back-log larger than MAX_BUF_FACT minutes,
457 * bandwidth-hogs are sampled at a frequency of about 78s!);
458 * may get negative if we have VERY high priority content.
460 long long available_send_window;
463 * How much downstream capacity of this peer has been reserved for
464 * our traffic? (Our clients can request that a certain amount of
465 * bandwidth is available for replies to them; this value is used to
466 * make sure that this reserved amount of bandwidth is actually
469 long long available_recv_window;
472 * How valueable were the messages of this peer recently?
474 unsigned long long current_preference;
477 * Bit map indicating which of the 32 sequence numbers before the last
478 * were received (good for accepting out-of-order packets and
479 * estimating reliability of the connection)
481 unsigned int last_packets_bitmap;
484 * Number of messages in the message queue for this peer.
486 unsigned int message_queue_size;
489 * last sequence number received on this connection (highest)
491 uint32_t last_sequence_number_received;
494 * last sequence number transmitted
496 uint32_t last_sequence_number_sent;
499 * Available bandwidth in for this peer (current target).
504 * Available bandwidth out for this peer (current target).
509 * Internal bandwidth limit set for this peer (initially
510 * typically set to "-1"). "bpm_out" is MAX of
511 * "bpm_out_internal_limit" and "bpm_out_external_limit".
513 uint32_t bpm_out_internal_limit;
516 * External bandwidth limit set for this peer by the
517 * peer that we are communicating with. "bpm_out" is MAX of
518 * "bpm_out_internal_limit" and "bpm_out_external_limit".
520 uint32_t bpm_out_external_limit;
523 * What was our PING challenge number (for this peer)?
525 uint32_t ping_challenge;
528 * What is our connection status?
530 enum PeerStateMachine status;
536 * Events are messages for clients. The struct
537 * itself is followed by the actual message.
542 * This is a linked list.
547 * Size of the message.
552 * Could this event be dropped if this queue
553 * is getting too large? (NOT YET USED!)
561 * Data structure for each client connected to the core service.
566 * Clients are kept in a linked list.
571 * Handle for the client with the server API.
573 struct GNUNET_SERVER_Client *client_handle;
576 * Linked list of messages we still need to deliver to
579 struct Event *event_head;
582 * Tail of the linked list of events.
584 struct Event *event_tail;
587 * Current transmit handle, NULL if no transmission request
590 struct GNUNET_CONNECTION_TransmitHandle *th;
593 * Array of the types of messages this peer cares
594 * about (with "tcnt" entries). Allocated as part
595 * of this client struct, do not free!
600 * Options for messages this client cares about,
601 * see GNUNET_CORE_OPTION_ values.
606 * Number of types of incoming messages this client
607 * specifically cares about. Size of the "types" array.
617 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
622 static struct GNUNET_PeerIdentity my_identity;
627 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
632 struct GNUNET_SCHEDULER_Handle *sched;
637 const struct GNUNET_CONFIGURATION_Handle *cfg;
642 static struct GNUNET_SERVER_Handle *server;
647 static struct GNUNET_TRANSPORT_Handle *transport;
650 * Linked list of our clients.
652 static struct Client *clients;
655 * We keep neighbours in a linked list (for now).
657 static struct Neighbour *neighbours;
660 * Sum of all preferences among all neighbours.
662 static unsigned long long preference_sum;
665 * Total number of neighbours we have.
667 static unsigned int neighbour_count;
670 * How much inbound bandwidth are we supposed to be using?
672 static unsigned long long bandwidth_target_in;
675 * How much outbound bandwidth are we supposed to be using?
677 static unsigned long long bandwidth_target_out;
682 * A preference value for a neighbour was update. Update
683 * the preference sum accordingly.
685 * @param inc how much was a preference value increased?
688 update_preference_sum (unsigned long long inc)
691 unsigned long long os;
694 preference_sum += inc;
695 if (preference_sum >= os)
697 /* overflow! compensate by cutting all values in half! */
702 n->current_preference /= 2;
703 preference_sum += n->current_preference;
710 * Recalculate the number of bytes we expect to
711 * receive or transmit in a given window.
713 * @param force force an update now (even if not much time has passed)
714 * @param window pointer to the byte counter (updated)
715 * @param ts pointer to the timestamp (updated)
716 * @param bpm number of bytes per minute that should
717 * be added to the window.
720 update_window (int force,
722 struct GNUNET_TIME_Absolute *ts, unsigned int bpm)
724 struct GNUNET_TIME_Relative since;
726 since = GNUNET_TIME_absolute_get_duration (*ts);
727 if ( (force == GNUNET_NO) &&
728 (since.value < 60 * 1000) )
729 return; /* not even a minute has passed */
730 *ts = GNUNET_TIME_absolute_get ();
731 *window += (bpm * since.value) / 60 / 1000;
732 if (*window > MAX_WINDOW_TIME * bpm)
733 *window = MAX_WINDOW_TIME * bpm;
738 * Find the entry for the given neighbour.
740 * @param peer identity of the neighbour
741 * @return NULL if we are not connected, otherwise the
744 static struct Neighbour *
745 find_neighbour (const struct GNUNET_PeerIdentity *peer)
747 struct Neighbour *ret;
750 while ((ret != NULL) &&
751 (0 != memcmp (&ret->peer,
752 peer, sizeof (struct GNUNET_PeerIdentity))))
759 * Find the entry for the given client.
761 * @param client handle for the client
762 * @return NULL if we are not connected, otherwise the
765 static struct Client *
766 find_client (const struct GNUNET_SERVER_Client *client)
771 while ((ret != NULL) && (client != ret->client_handle))
778 * If necessary, initiate a request with the server to
779 * transmit messages from the queue of the given client.
780 * @param client who to transfer messages to
782 static void request_transmit (struct Client *client);
786 * Client is ready to receive data, provide it.
789 * @param size number of bytes available in buf
790 * @param buf where the callee should write the message
791 * @return number of bytes written to buf
794 do_client_transmit (void *cls, size_t size, void *buf)
796 struct Client *client = cls;
802 #if DEBUG_CORE_CLIENT
803 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
804 "Client ready to receive %u bytes.\n", size);
809 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
810 "Failed to transmit data to client (disconnect)?\n");
812 return 0; /* we'll surely get a disconnect soon... */
816 while ((NULL != (e = client->event_head)) && (e->size <= size))
818 memcpy (&tgt[ret], &e[1], e->size);
821 client->event_head = e->next;
824 GNUNET_assert (ret > 0);
825 if (client->event_head == NULL)
826 client->event_tail = NULL;
827 #if DEBUG_CORE_CLIENT
828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
829 "Transmitting %u bytes to client\n", ret);
831 request_transmit (client);
837 * If necessary, initiate a request with the server to
838 * transmit messages from the queue of the given client.
839 * @param client who to transfer messages to
842 request_transmit (struct Client *client)
845 if (NULL != client->th)
846 return; /* already pending */
847 if (NULL == client->event_head)
848 return; /* no more events pending */
849 #if DEBUG_CORE_CLIENT
850 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
851 "Asking server to transmit %u bytes to client\n",
852 client->event_head->size);
855 = GNUNET_SERVER_notify_transmit_ready (client->client_handle,
856 client->event_head->size,
857 GNUNET_TIME_UNIT_FOREVER_REL,
858 &do_client_transmit, client);
863 * Send a message to one of our clients.
865 * @param client target for the message
866 * @param msg message to transmit
867 * @param can_drop could this message be dropped if the
868 * client's queue is getting too large?
871 send_to_client (struct Client *client,
872 const struct GNUNET_MessageHeader *msg, int can_drop)
875 unsigned int queue_size;
878 #if DEBUG_CORE_CLIENT
879 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
880 "Preparing to send message of type %u to client.\n",
884 e = client->event_head;
890 if ( (queue_size >= MAX_CLIENT_QUEUE_SIZE) &&
891 (can_drop == GNUNET_YES) )
894 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
895 "Too many messages in queue for the client, dropping the new message.\n");
900 msize = ntohs (msg->size);
901 e = GNUNET_malloc (sizeof (struct Event) + msize);
903 if (client->event_tail != NULL)
904 client->event_tail->next = e;
906 client->event_head = e;
907 client->event_tail = e;
908 e->can_drop = can_drop;
910 memcpy (&e[1], msg, msize);
911 request_transmit (client);
916 * Send a message to all of our current clients.
919 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
928 if (0 != (c->options & options))
929 send_to_client (c, msg, can_drop);
936 * Handle CORE_INIT request.
939 handle_client_init (void *cls,
940 struct GNUNET_SERVER_Client *client,
941 const struct GNUNET_MessageHeader *message)
943 const struct InitMessage *im;
944 struct InitReplyMessage irm;
947 const uint16_t *types;
949 struct ConnectNotifyMessage cnm;
951 #if DEBUG_CORE_CLIENT
952 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
953 "Client connecting to core service with `%s' message\n",
956 /* check that we don't have an entry already */
960 if (client == c->client_handle)
963 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
968 msize = ntohs (message->size);
969 if (msize < sizeof (struct InitMessage))
972 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
975 im = (const struct InitMessage *) message;
976 types = (const uint16_t *) &im[1];
977 msize -= sizeof (struct InitMessage);
978 c = GNUNET_malloc (sizeof (struct Client) + msize);
979 c->client_handle = client;
982 memcpy (&c[1], types, msize);
983 c->types = (uint16_t *) & c[1];
984 c->options = ntohl (im->options);
985 c->tcnt = msize / sizeof (uint16_t);
986 /* send init reply message */
987 irm.header.size = htons (sizeof (struct InitReplyMessage));
988 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
989 irm.reserved = htonl (0);
990 memcpy (&irm.publicKey,
992 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
993 #if DEBUG_CORE_CLIENT
994 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
995 "Sending `%s' message to client.\n", "INIT_REPLY");
997 send_to_client (c, &irm.header, GNUNET_NO);
998 /* notify new client about existing neighbours */
999 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
1000 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1004 #if DEBUG_CORE_CLIENT
1005 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1006 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
1008 cnm.reserved = htonl (0);
1010 send_to_client (c, &cnm.header, GNUNET_NO);
1013 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1018 * A client disconnected, clean up.
1020 * @param cls closure
1021 * @param client identification of the client
1024 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1027 struct Client *prev;
1030 #if DEBUG_CORE_CLIENT
1031 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1032 "Client has disconnected from core service.\n");
1038 if (client == pos->client_handle)
1041 clients = pos->next;
1043 prev->next = pos->next;
1044 if (pos->th != NULL)
1045 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
1046 while (NULL != (e = pos->event_head))
1048 pos->event_head = e->next;
1057 /* client never sent INIT */
1062 * Handle REQUEST_INFO request.
1065 handle_client_request_info (void *cls,
1066 struct GNUNET_SERVER_Client *client,
1067 const struct GNUNET_MessageHeader *message)
1069 const struct RequestInfoMessage *rcm;
1070 struct Neighbour *n;
1071 struct ConfigurationInfoMessage cim;
1074 unsigned long long old_preference;
1076 #if DEBUG_CORE_CLIENT
1077 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1078 "Core service receives `%s' request.\n", "REQUEST_INFO");
1080 rcm = (const struct RequestInfoMessage *) message;
1081 n = find_neighbour (&rcm->peer);
1082 memset (&cim, 0, sizeof (cim));
1083 if ((n != NULL) && (n->status == PEER_STATE_KEY_CONFIRMED))
1085 update_window (GNUNET_YES,
1086 &n->available_send_window,
1087 &n->last_asw_update,
1089 n->bpm_out_internal_limit = ntohl (rcm->limit_outbound_bpm);
1090 n->bpm_out = GNUNET_MAX (n->bpm_out_internal_limit,
1091 n->bpm_out_external_limit);
1092 reserv = ntohl (rcm->reserve_inbound);
1095 n->available_recv_window += reserv;
1097 else if (reserv > 0)
1099 update_window (GNUNET_NO,
1100 &n->available_recv_window,
1101 &n->last_arw_update, n->bpm_in);
1102 if (n->available_recv_window < reserv)
1103 reserv = n->available_recv_window;
1104 n->available_recv_window -= reserv;
1106 old_preference = n->current_preference;
1107 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1108 if (old_preference > n->current_preference)
1110 /* overflow; cap at maximum value */
1111 n->current_preference = (unsigned long long) -1;
1113 update_preference_sum (n->current_preference - old_preference);
1114 cim.reserved_amount = htonl (reserv);
1115 cim.bpm_in = htonl (n->bpm_in);
1116 cim.bpm_out = htonl (n->bpm_out);
1117 cim.latency = GNUNET_TIME_relative_hton (n->last_latency);
1118 cim.preference = n->current_preference;
1120 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1121 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1122 cim.peer = rcm->peer;
1123 c = find_client (client);
1129 #if DEBUG_CORE_CLIENT
1130 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1131 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1133 send_to_client (c, &cim.header, GNUNET_NO);
1138 * Check if we have encrypted messages for the specified neighbour
1139 * pending, and if so, check with the transport about sending them
1142 * @param n neighbour to check.
1144 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1148 * Function called when the transport service is ready to
1149 * receive an encrypted message for the respective peer
1151 * @param cls neighbour to use message from
1152 * @param size number of bytes we can transmit
1153 * @param buf where to copy the message
1154 * @return number of bytes transmitted
1157 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1159 struct Neighbour *n = cls;
1160 struct MessageEntry *m;
1165 GNUNET_assert (NULL != (m = n->encrypted_head));
1166 n->encrypted_head = m->next;
1167 if (m->next == NULL)
1168 n->encrypted_tail = NULL;
1173 GNUNET_assert (size >= m->size);
1174 memcpy (cbuf, &m[1], m->size);
1176 n->available_send_window -= m->size;
1177 process_encrypted_neighbour_queue (n);
1179 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1180 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1181 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1182 ret, GNUNET_i2s (&n->peer));
1187 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1188 "Transmission for message of type %u and size %u failed\n",
1189 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1198 * Check if we have plaintext messages for the specified neighbour
1199 * pending, and if so, consider batching and encrypting them (and
1200 * then trigger processing of the encrypted queue if needed).
1202 * @param n neighbour to check.
1204 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1208 * Check if we have encrypted messages for the specified neighbour
1209 * pending, and if so, check with the transport about sending them
1212 * @param n neighbour to check.
1215 process_encrypted_neighbour_queue (struct Neighbour *n)
1217 struct MessageEntry *m;
1220 return; /* request already pending */
1221 if (n->encrypted_head == NULL)
1223 /* encrypted queue empty, try plaintext instead */
1224 process_plaintext_neighbour_queue (n);
1228 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1229 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1230 n->encrypted_head->size,
1231 GNUNET_i2s (&n->peer),
1232 GNUNET_TIME_absolute_get_remaining (n->
1233 encrypted_head->deadline).
1237 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1238 n->encrypted_head->size,
1239 n->encrypted_head->priority,
1240 GNUNET_TIME_absolute_get_remaining
1241 (n->encrypted_head->deadline),
1242 ¬ify_encrypted_transmit_ready,
1246 /* message request too large (oops) */
1248 /* discard encrypted message */
1249 GNUNET_assert (NULL != (m = n->encrypted_head));
1250 n->encrypted_head = m->next;
1251 if (m->next == NULL)
1252 n->encrypted_tail = NULL;
1254 process_encrypted_neighbour_queue (n);
1260 * Decrypt size bytes from in and write the result to out. Use the
1261 * key for inbound traffic of the given neighbour. This function does
1262 * NOT do any integrity-checks on the result.
1264 * @param n neighbour we are receiving from
1265 * @param iv initialization vector to use
1266 * @param in ciphertext
1267 * @param out plaintext
1268 * @param size size of in/out
1269 * @return GNUNET_OK on success
1272 do_decrypt (struct Neighbour *n,
1273 const GNUNET_HashCode * iv,
1274 const void *in, void *out, size_t size)
1276 if (size != (uint16_t) size)
1281 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1282 (n->status != PEER_STATE_KEY_CONFIRMED))
1284 GNUNET_break_op (0);
1285 return GNUNET_SYSERR;
1288 GNUNET_CRYPTO_aes_decrypt (in,
1292 GNUNET_CRYPTO_AesInitializationVector *) iv,
1296 return GNUNET_SYSERR;
1299 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1300 "Decrypted %u bytes from `%4s' using key %u\n",
1301 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1308 * Encrypt size bytes from in and write the result to out. Use the
1309 * key for outbound traffic of the given neighbour.
1311 * @param n neighbour we are sending to
1312 * @param iv initialization vector to use
1313 * @param in ciphertext
1314 * @param out plaintext
1315 * @param size size of in/out
1316 * @return GNUNET_OK on success
1319 do_encrypt (struct Neighbour *n,
1320 const GNUNET_HashCode * iv,
1321 const void *in, void *out, size_t size)
1323 if (size != (uint16_t) size)
1328 GNUNET_assert (size ==
1329 GNUNET_CRYPTO_aes_encrypt (in,
1333 GNUNET_CRYPTO_AesInitializationVector
1336 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1337 "Encrypted %u bytes for `%4s' using key %u\n", size,
1338 GNUNET_i2s (&n->peer), n->encrypt_key.crc32);
1345 * Select messages for transmission. This heuristic uses a combination
1346 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1347 * and priority-based discard (in case no feasible schedule exist) and
1348 * speculative optimization (defer any kind of transmission until
1349 * we either create a batch of significant size, 25% of max, or until
1350 * we are close to a deadline). Furthermore, when scheduling the
1351 * heuristic also packs as many messages into the batch as possible,
1352 * starting with those with the earliest deadline. Yes, this is fun.
1354 * @param n neighbour to select messages from
1355 * @param size number of bytes to select for transmission
1356 * @param retry_time set to the time when we should try again
1357 * (only valid if this function returns zero)
1358 * @return number of bytes selected, or 0 if we decided to
1359 * defer scheduling overall; in that case, retry_time is set.
1362 select_messages (struct Neighbour *n,
1363 size_t size, struct GNUNET_TIME_Relative *retry_time)
1365 struct MessageEntry *pos;
1366 struct MessageEntry *min;
1367 struct MessageEntry *last;
1368 unsigned int min_prio;
1369 struct GNUNET_TIME_Absolute t;
1370 struct GNUNET_TIME_Absolute now;
1373 unsigned long long slack; /* how long could we wait before missing deadlines? */
1375 int discard_low_prio;
1377 GNUNET_assert (NULL != n->messages);
1378 now = GNUNET_TIME_absolute_get ();
1379 /* last entry in linked list of messages processed */
1381 /* should we remove the entry with the lowest
1382 priority from consideration for scheduling at the
1384 discard_low_prio = GNUNET_YES;
1385 while (GNUNET_YES == discard_low_prio)
1389 discard_low_prio = GNUNET_NO;
1390 /* calculate number of bytes available for transmission at time "t" */
1391 update_window (GNUNET_NO,
1392 &n->available_send_window,
1393 &n->last_asw_update,
1395 avail = n->available_send_window;
1396 t = n->last_asw_update;
1397 /* how many bytes have we (hypothetically) scheduled so far */
1399 /* maximum time we can wait before transmitting anything
1400 and still make all of our deadlines */
1404 /* note that we use "*2" here because we want to look
1405 a bit further into the future; much more makes no
1406 sense since new message might be scheduled in the
1408 while ((pos != NULL) && (off < size * 2))
1410 if (pos->do_transmit == GNUNET_YES)
1412 /* already removed from consideration */
1416 if (discard_low_prio == GNUNET_NO)
1418 delta = pos->deadline.value;
1419 if (delta < t.value)
1422 delta = t.value - delta;
1423 avail += delta * n->bpm_out / 1000 / 60;
1424 if (avail < pos->size)
1426 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1431 /* update slack, considering both its absolute deadline
1432 and relative deadlines caused by other messages
1433 with their respective load */
1434 slack = GNUNET_MIN (slack, avail / n->bpm_out);
1435 if (pos->deadline.value < now.value)
1439 GNUNET_MIN (slack, pos->deadline.value - now.value);
1443 t.value = GNUNET_MAX (pos->deadline.value, t.value);
1444 if (pos->priority <= min_prio)
1446 /* update min for discard */
1447 min_prio = pos->priority;
1452 if (discard_low_prio)
1454 GNUNET_assert (min != NULL);
1455 /* remove lowest-priority entry from consideration */
1456 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1460 /* guard against sending "tiny" messages with large headers without
1462 if ( (slack > 1000) && (size > 4 * off) )
1464 /* less than 25% of message would be filled with
1465 deadlines still being met if we delay by one
1466 second or more; so just wait for more data */
1467 retry_time->value = slack / 2;
1468 /* reset do_transmit values for next time */
1471 pos->do_transmit = GNUNET_NO;
1476 /* select marked messages (up to size) for transmission */
1481 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1483 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1488 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1492 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1493 "Selected %u bytes of plaintext messages for transmission to `%4s'.\n",
1494 off, GNUNET_i2s (&n->peer));
1501 * Batch multiple messages into a larger buffer.
1503 * @param n neighbour to take messages from
1504 * @param buf target buffer
1505 * @param size size of buf
1506 * @param deadline set to transmission deadline for the result
1507 * @param retry_time set to the time when we should try again
1508 * (only valid if this function returns zero)
1509 * @param priority set to the priority of the batch
1510 * @return number of bytes written to buf (can be zero)
1513 batch_message (struct Neighbour *n,
1516 struct GNUNET_TIME_Absolute *deadline,
1517 struct GNUNET_TIME_Relative *retry_time,
1518 unsigned int *priority)
1520 struct MessageEntry *pos;
1521 struct MessageEntry *prev;
1522 struct MessageEntry *next;
1527 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1528 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1529 if (0 == select_messages (n, size, retry_time))
1531 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1532 "No messages selected, will try again in %llu ms\n",
1538 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1541 if (GNUNET_YES == pos->do_transmit)
1543 GNUNET_assert (pos->size <= size);
1544 memcpy (&buf[ret], &pos[1], pos->size);
1547 *priority += pos->priority;
1549 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1550 "Adding plaintext message with deadline %llu ms to batch\n",
1551 GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1553 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1567 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1568 "Deadline for message batch is %llu ms\n",
1569 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1576 * Remove messages with deadlines that have long expired from
1579 * @param n neighbour to inspect
1582 discard_expired_messages (struct Neighbour *n)
1584 struct MessageEntry *prev;
1585 struct MessageEntry *next;
1586 struct MessageEntry *pos;
1587 struct GNUNET_TIME_Absolute now;
1588 struct GNUNET_TIME_Relative delta;
1590 now = GNUNET_TIME_absolute_get ();
1596 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1597 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1600 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1601 "Message is %llu ms past due, discarding.\n",
1618 * Signature of the main function of a task.
1620 * @param cls closure
1621 * @param tc context information (why was this task triggered now)
1624 retry_plaintext_processing (void *cls,
1625 const struct GNUNET_SCHEDULER_TaskContext *tc)
1627 struct Neighbour *n = cls;
1629 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1630 process_plaintext_neighbour_queue (n);
1635 * Send our key (and encrypted PING) to the other peer.
1637 * @param n the other peer
1639 static void send_key (struct Neighbour *n);
1643 * Check if we have plaintext messages for the specified neighbour
1644 * pending, and if so, consider batching and encrypting them (and
1645 * then trigger processing of the encrypted queue if needed).
1647 * @param n neighbour to check.
1650 process_plaintext_neighbour_queue (struct Neighbour *n)
1652 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1655 struct EncryptedMessage *em; /* encrypted message */
1656 struct EncryptedMessage *ph; /* plaintext header */
1657 struct MessageEntry *me;
1658 unsigned int priority;
1659 struct GNUNET_TIME_Absolute deadline;
1660 struct GNUNET_TIME_Relative retry_time;
1662 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1664 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1665 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1669 case PEER_STATE_DOWN:
1672 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1673 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1674 GNUNET_i2s(&n->peer));
1677 case PEER_STATE_KEY_SENT:
1678 GNUNET_assert (n->retry_set_key_task !=
1679 GNUNET_SCHEDULER_NO_TASK);
1681 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1682 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1683 GNUNET_i2s(&n->peer));
1686 case PEER_STATE_KEY_RECEIVED:
1687 GNUNET_assert (n->retry_set_key_task !=
1688 GNUNET_SCHEDULER_NO_TASK);
1690 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1691 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1692 GNUNET_i2s(&n->peer));
1695 case PEER_STATE_KEY_CONFIRMED:
1696 /* ready to continue */
1699 discard_expired_messages (n);
1700 if (n->messages == NULL)
1703 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1704 "Plaintext message queue for `%4s' is empty.\n",
1705 GNUNET_i2s(&n->peer));
1707 return; /* no pending messages */
1709 if (n->encrypted_head != NULL)
1712 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1713 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1714 GNUNET_i2s(&n->peer));
1716 return; /* wait for messages already encrypted to be
1719 ph = (struct EncryptedMessage *) pbuf;
1720 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1722 used = sizeof (struct EncryptedMessage);
1723 used += batch_message (n,
1725 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1726 &deadline, &retry_time, &priority);
1727 if (used == sizeof (struct EncryptedMessage))
1730 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1731 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1732 GNUNET_i2s(&n->peer));
1734 /* no messages selected for sending, try again later... */
1735 n->retry_plaintext_task =
1736 GNUNET_SCHEDULER_add_delayed (sched,
1738 &retry_plaintext_processing, n);
1741 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1742 ph->inbound_bpm_limit = htonl (n->bpm_in);
1743 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1745 /* setup encryption message header */
1746 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1747 me->deadline = deadline;
1748 me->priority = priority;
1750 em = (struct EncryptedMessage *) &me[1];
1751 em->header.size = htons (used);
1752 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1753 em->reserved = htonl (0);
1754 esize = used - ENCRYPTED_HEADER_SIZE;
1755 GNUNET_CRYPTO_hash (&ph->sequence_number, esize, &em->plaintext_hash);
1758 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1759 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
1761 GNUNET_i2s(&n->peer),
1762 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
1764 GNUNET_assert (GNUNET_OK ==
1766 &em->plaintext_hash,
1767 &ph->sequence_number,
1768 &em->sequence_number, esize));
1769 /* append to transmission list */
1770 if (n->encrypted_tail == NULL)
1771 n->encrypted_head = me;
1773 n->encrypted_tail->next = me;
1774 n->encrypted_tail = me;
1775 process_encrypted_neighbour_queue (n);
1780 * Handle CORE_SEND request.
1783 * @param client the client issuing the request
1784 * @param message the "struct SendMessage"
1787 handle_client_send (void *cls,
1788 struct GNUNET_SERVER_Client *client,
1789 const struct GNUNET_MessageHeader *message);
1793 * Function called to notify us that we either succeeded
1794 * or failed to connect (at the transport level) to another
1795 * peer. We should either free the message we were asked
1796 * to transmit or re-try adding it to the queue.
1798 * @param cls closure
1799 * @param size number of bytes available in buf
1800 * @param buf where the callee should write the message
1801 * @return number of bytes written to buf
1804 send_connect_continuation (void *cls, size_t size, void *buf)
1806 struct SendMessage *sm = cls;
1811 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1812 "Asked to send message to disconnected peer `%4s' and connection failed. Discarding message.\n",
1813 GNUNET_i2s (&sm->peer));
1819 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1820 "Connection to peer `%4s' succeeded, retrying original transmission request\n",
1821 GNUNET_i2s (&sm->peer));
1823 handle_client_send (NULL, NULL, &sm->header);
1830 * Handle CORE_SEND request.
1833 * @param client the client issuing the request
1834 * @param message the "struct SendMessage"
1837 handle_client_send (void *cls,
1838 struct GNUNET_SERVER_Client *client,
1839 const struct GNUNET_MessageHeader *message)
1841 const struct SendMessage *sm;
1842 struct SendMessage *smc;
1843 const struct GNUNET_MessageHeader *mh;
1844 struct Neighbour *n;
1845 struct MessageEntry *prev;
1846 struct MessageEntry *pos;
1847 struct MessageEntry *e;
1848 struct MessageEntry *min_prio_entry;
1849 struct MessageEntry *min_prio_prev;
1850 unsigned int min_prio;
1851 unsigned int queue_size;
1854 msize = ntohs (message->size);
1856 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
1860 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1863 sm = (const struct SendMessage *) message;
1864 msize -= sizeof (struct SendMessage);
1865 mh = (const struct GNUNET_MessageHeader *) &sm[1];
1866 if (msize != ntohs (mh->size))
1870 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1873 n = find_neighbour (&sm->peer);
1877 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1878 "Core received `%s' request for `%4s', will try to establish connection within %llu ms\n",
1880 GNUNET_i2s (&sm->peer),
1881 GNUNET_TIME_absolute_get_remaining
1882 (GNUNET_TIME_absolute_ntoh(sm->deadline)).value);
1884 msize += sizeof (struct SendMessage);
1885 /* ask transport to connect to the peer */
1886 smc = GNUNET_malloc (msize);
1887 memcpy (smc, sm, msize);
1889 GNUNET_TRANSPORT_notify_transmit_ready (transport,
1892 GNUNET_TIME_absolute_get_remaining
1893 (GNUNET_TIME_absolute_ntoh
1895 &send_connect_continuation,
1898 /* transport has already a request pending for this peer! */
1900 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1901 "Dropped second message destined for `%4s' since connection is still down.\n",
1902 GNUNET_i2s(&sm->peer));
1907 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1911 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1912 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
1915 GNUNET_i2s (&sm->peer));
1917 /* bound queue size */
1918 discard_expired_messages (n);
1919 min_prio = (unsigned int) -1;
1920 min_prio_entry = NULL;
1921 min_prio_prev = NULL;
1927 if (pos->priority < min_prio)
1929 min_prio_entry = pos;
1930 min_prio_prev = prev;
1931 min_prio = pos->priority;
1937 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1940 if (ntohl(sm->priority) <= min_prio)
1942 /* discard new entry */
1944 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1945 "Queue full, discarding new request\n");
1948 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1951 /* discard "min_prio_entry" */
1953 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1954 "Queue full, discarding existing older request\n");
1956 if (min_prio_prev == NULL)
1957 n->messages = min_prio_entry->next;
1959 min_prio_prev->next = min_prio_entry->next;
1960 GNUNET_free (min_prio_entry);
1964 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1965 "Adding transmission request for `%4s' to queue\n",
1966 GNUNET_i2s (&sm->peer));
1968 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
1969 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
1970 e->priority = ntohl (sm->priority);
1972 memcpy (&e[1], mh, msize);
1974 /* insert, keep list sorted by deadline */
1977 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
1988 /* consider scheduling now */
1989 process_plaintext_neighbour_queue (n);
1991 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1996 * Handle CORE_REQUEST_CONNECT request.
1999 * @param client the client issuing the request
2000 * @param message the "struct ConnectMessage"
2003 handle_client_request_connect (void *cls,
2004 struct GNUNET_SERVER_Client *client,
2005 const struct GNUNET_MessageHeader *message)
2007 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2008 struct Neighbour *n;
2010 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2011 n = find_neighbour (&cm->peer);
2013 return; /* already connected, or at least trying */
2015 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2016 "Core received `%s' request for `%4s', will try to establish connection\n",
2018 GNUNET_i2s (&cm->peer));
2020 /* ask transport to connect to the peer */
2021 /* FIXME: timeout zero OK? need for cancellation? */
2022 GNUNET_TRANSPORT_notify_transmit_ready (transport,
2025 GNUNET_TIME_UNIT_ZERO,
2032 * Handle CORE_REQUEST_DISCONNECT request.
2035 * @param client the client issuing the request
2036 * @param message the "struct ConnectMessage"
2039 handle_client_request_disconnect (void *cls,
2040 struct GNUNET_SERVER_Client *client,
2041 const struct GNUNET_MessageHeader *message)
2043 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2044 struct Neighbour *n;
2046 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2047 n = find_neighbour (&cm->peer);
2050 /* FIXME: implement disconnect! */
2056 * List of handlers for the messages understood by this
2059 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2060 {&handle_client_init, NULL,
2061 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2062 {&handle_client_request_info, NULL,
2063 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2064 sizeof (struct RequestInfoMessage)},
2065 {&handle_client_send, NULL,
2066 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2067 {&handle_client_request_connect, NULL,
2068 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2069 sizeof (struct ConnectMessage)},
2070 {&handle_client_request_disconnect, NULL,
2071 GNUNET_MESSAGE_TYPE_CORE_REQUEST_DISCONNECT,
2072 sizeof (struct ConnectMessage)},
2078 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2079 * the neighbour's struct and retry send_key. Or, if we did not get a
2080 * HELLO, just do nothing.
2083 * @param peer the peer for which this is the HELLO
2084 * @param hello HELLO message of that peer
2085 * @param trust amount of trust we currently have in that peer
2088 process_hello_retry_send_key (void *cls,
2089 const struct GNUNET_PeerIdentity *peer,
2090 const struct GNUNET_HELLO_Message *hello,
2093 struct Neighbour *n = cls;
2100 if (n->public_key != NULL)
2103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2104 "Received new `%s' message for `%4s', initiating key exchange.\n",
2109 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2110 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2112 GNUNET_free (n->public_key);
2113 n->public_key = NULL;
2121 * Task that will retry "send_key" if our previous attempt failed
2125 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2127 struct Neighbour *n = cls;
2129 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2130 n->set_key_retry_frequency =
2131 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2137 * Send our key (and encrypted PING) to the other peer.
2139 * @param n the other peer
2142 send_key (struct Neighbour *n)
2144 struct SetKeyMessage *sm;
2145 struct MessageEntry *me;
2146 struct PingMessage pp;
2147 struct PingMessage *pm;
2149 if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2151 return; /* already in progress */
2153 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2154 "Asked to perform key exchange with `%4s'.\n",
2155 GNUNET_i2s (&n->peer));
2157 if (n->public_key == NULL)
2159 /* lookup n's public key, then try again */
2161 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2162 "Lacking public key for `%4s', trying to obtain one.\n",
2163 GNUNET_i2s (&n->peer));
2165 GNUNET_assert (n->pitr == NULL);
2166 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2170 GNUNET_TIME_UNIT_MINUTES,
2171 &process_hello_retry_send_key, n);
2174 /* first, set key message */
2175 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2176 sizeof (struct SetKeyMessage));
2177 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2178 me->priority = SET_KEY_PRIORITY;
2179 me->size = sizeof (struct SetKeyMessage);
2180 if (n->encrypted_head == NULL)
2181 n->encrypted_head = me;
2183 n->encrypted_tail->next = me;
2184 n->encrypted_tail = me;
2185 sm = (struct SetKeyMessage *) &me[1];
2186 sm->header.size = htons (sizeof (struct SetKeyMessage));
2187 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2188 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2189 PEER_STATE_KEY_SENT : n->status));
2191 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2192 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2193 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2194 sizeof (struct GNUNET_PeerIdentity));
2195 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2196 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2197 sm->target = n->peer;
2198 GNUNET_assert (GNUNET_OK ==
2199 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2201 GNUNET_CRYPTO_AesSessionKey),
2203 &sm->encrypted_key));
2204 GNUNET_assert (GNUNET_OK ==
2205 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2208 /* second, encrypted PING message */
2209 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2210 sizeof (struct PingMessage));
2211 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2212 me->priority = PING_PRIORITY;
2213 me->size = sizeof (struct PingMessage);
2214 n->encrypted_tail->next = me;
2215 n->encrypted_tail = me;
2216 pm = (struct PingMessage *) &me[1];
2217 pm->header.size = htons (sizeof (struct PingMessage));
2218 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2219 pp.challenge = htonl (n->ping_challenge);
2220 pp.target = n->peer;
2222 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2223 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2224 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2225 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2226 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2228 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2231 &n->peer.hashPubKey,
2234 sizeof (struct PingMessage) -
2235 sizeof (struct GNUNET_MessageHeader));
2239 case PEER_STATE_DOWN:
2240 n->status = PEER_STATE_KEY_SENT;
2242 case PEER_STATE_KEY_SENT:
2244 case PEER_STATE_KEY_RECEIVED:
2246 case PEER_STATE_KEY_CONFIRMED:
2253 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2254 "Have %llu ms left for `%s' transmission.\n",
2255 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2258 /* trigger queue processing */
2259 process_encrypted_neighbour_queue (n);
2260 if (n->status != PEER_STATE_KEY_CONFIRMED)
2262 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task);
2263 n->retry_set_key_task
2264 = GNUNET_SCHEDULER_add_delayed (sched,
2265 n->set_key_retry_frequency,
2266 &set_key_retry_task, n);
2272 * We received a SET_KEY message. Validate and update
2273 * our key material and status.
2275 * @param n the neighbour from which we received message m
2276 * @param m the set key message we received
2279 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2283 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2284 * the neighbour's struct and retry handling the set_key message. Or,
2285 * if we did not get a HELLO, just free the set key message.
2287 * @param cls pointer to the set key message
2288 * @param peer the peer for which this is the HELLO
2289 * @param hello HELLO message of that peer
2290 * @param trust amount of trust we currently have in that peer
2293 process_hello_retry_handle_set_key (void *cls,
2294 const struct GNUNET_PeerIdentity *peer,
2295 const struct GNUNET_HELLO_Message *hello,
2298 struct Neighbour *n = cls;
2299 struct SetKeyMessage *sm = n->skm;
2308 if (n->public_key != NULL)
2309 return; /* multiple HELLOs match!? */
2311 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2312 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2314 GNUNET_break_op (0);
2315 GNUNET_free (n->public_key);
2316 n->public_key = NULL;
2320 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2321 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2322 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2324 handle_set_key (n, sm);
2329 * We received a PING message. Validate and transmit
2332 * @param n sender of the PING
2333 * @param m the encrypted PING message itself
2336 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2338 struct PingMessage t;
2339 struct PingMessage *tp;
2340 struct MessageEntry *me;
2343 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2344 "Core service receives `%s' request from `%4s'.\n",
2345 "PING", GNUNET_i2s (&n->peer));
2349 &my_identity.hashPubKey,
2352 sizeof (struct PingMessage) -
2353 sizeof (struct GNUNET_MessageHeader)))
2356 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2357 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2359 GNUNET_i2s (&t.target),
2360 ntohl (t.challenge), n->decrypt_key.crc32);
2361 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2362 "Target of `%s' request is `%4s'.\n",
2363 "PING", GNUNET_i2s (&t.target));
2365 if (0 != memcmp (&t.target,
2366 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2368 GNUNET_break_op (0);
2371 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2372 sizeof (struct PingMessage));
2373 if (n->encrypted_tail != NULL)
2374 n->encrypted_tail->next = me;
2377 n->encrypted_tail = me;
2378 n->encrypted_head = me;
2380 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2381 me->priority = PONG_PRIORITY;
2382 me->size = sizeof (struct PingMessage);
2383 tp = (struct PingMessage *) &me[1];
2384 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2385 tp->header.size = htons (sizeof (struct PingMessage));
2387 &my_identity.hashPubKey,
2390 sizeof (struct PingMessage) -
2391 sizeof (struct GNUNET_MessageHeader));
2393 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2394 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2395 ntohl (t.challenge), n->encrypt_key.crc32);
2397 /* trigger queue processing */
2398 process_encrypted_neighbour_queue (n);
2403 * We received a SET_KEY message. Validate and update
2404 * our key material and status.
2406 * @param n the neighbour from which we received message m
2407 * @param m the set key message we received
2410 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2412 struct SetKeyMessage *m_cpy;
2413 struct GNUNET_TIME_Absolute t;
2414 struct GNUNET_CRYPTO_AesSessionKey k;
2415 struct PingMessage *ping;
2416 enum PeerStateMachine sender_status;
2419 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2420 "Core service receives `%s' request from `%4s'.\n",
2421 "SET_KEY", GNUNET_i2s (&n->peer));
2423 if (n->public_key == NULL)
2426 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2427 "Lacking public key for peer, trying to obtain one.\n");
2429 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2430 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2431 /* lookup n's public key, then try again */
2432 GNUNET_assert (n->pitr == NULL);
2433 GNUNET_assert (n->skm == NULL);
2435 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2439 GNUNET_TIME_UNIT_MINUTES,
2440 &process_hello_retry_handle_set_key, n);
2443 if (0 != memcmp (&m->target,
2445 sizeof (struct GNUNET_PeerIdentity)))
2447 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2448 _("Received `%s' message that was not for me. Ignoring.\n"));
2451 if ((ntohl (m->purpose.size) !=
2452 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2453 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2454 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2455 sizeof (struct GNUNET_PeerIdentity)) ||
2457 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2458 &m->purpose, &m->signature, n->public_key)))
2460 /* invalid signature */
2461 GNUNET_break_op (0);
2464 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2465 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2466 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2467 (t.value < n->decrypt_key_created.value))
2469 /* this could rarely happen due to massive re-ordering of
2470 messages on the network level, but is most likely either
2471 a bug or some adversary messing with us. Report. */
2472 GNUNET_break_op (0);
2476 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
2478 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2481 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2482 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2483 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2485 /* failed to decrypt !? */
2486 GNUNET_break_op (0);
2491 if (n->decrypt_key_created.value != t.value)
2493 /* fresh key, reset sequence numbers */
2494 n->last_sequence_number_received = 0;
2495 n->last_packets_bitmap = 0;
2496 n->decrypt_key_created = t;
2498 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2501 case PEER_STATE_DOWN:
2502 n->status = PEER_STATE_KEY_RECEIVED;
2504 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2505 "Responding to `%s' with my own key.\n", "SET_KEY");
2509 case PEER_STATE_KEY_SENT:
2510 case PEER_STATE_KEY_RECEIVED:
2511 n->status = PEER_STATE_KEY_RECEIVED;
2512 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2513 (sender_status != PEER_STATE_KEY_CONFIRMED))
2516 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2517 "Responding to `%s' with my own key (other peer has status %u).\n",
2518 "SET_KEY", sender_status);
2523 case PEER_STATE_KEY_CONFIRMED:
2524 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2525 (sender_status != PEER_STATE_KEY_CONFIRMED))
2528 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2529 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2530 "SET_KEY", sender_status);
2539 if (n->pending_ping != NULL)
2541 ping = n->pending_ping;
2542 n->pending_ping = NULL;
2543 handle_ping (n, ping);
2550 * We received a PONG message. Validate and update
2553 * @param n sender of the PONG
2554 * @param m the encrypted PONG message itself
2557 handle_pong (struct Neighbour *n, const struct PingMessage *m)
2559 struct PingMessage t;
2560 struct ConnectNotifyMessage cnm;
2563 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2564 "Core service receives `%s' request from `%4s'.\n",
2565 "PONG", GNUNET_i2s (&n->peer));
2569 &n->peer.hashPubKey,
2572 sizeof (struct PingMessage) -
2573 sizeof (struct GNUNET_MessageHeader)))
2576 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2577 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2579 GNUNET_i2s (&t.target),
2580 ntohl (t.challenge), n->decrypt_key.crc32);
2582 if ((0 != memcmp (&t.target,
2584 sizeof (struct GNUNET_PeerIdentity))) ||
2585 (n->ping_challenge != ntohl (t.challenge)))
2587 /* PONG malformed */
2589 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2590 "Received malfromed `%s' wanted sender `%4s' with challenge %u\n",
2591 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2592 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2593 "Received malfromed `%s' received from `%4s' with challenge %u\n",
2594 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2596 GNUNET_break_op (0);
2601 case PEER_STATE_DOWN:
2602 GNUNET_break (0); /* should be impossible */
2604 case PEER_STATE_KEY_SENT:
2605 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2607 case PEER_STATE_KEY_RECEIVED:
2608 n->status = PEER_STATE_KEY_CONFIRMED;
2609 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2611 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2612 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2614 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2615 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2616 cnm.reserved = htonl (0);
2618 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2619 process_encrypted_neighbour_queue (n);
2621 case PEER_STATE_KEY_CONFIRMED:
2622 /* duplicate PONG? */
2632 * Send a P2P message to a client.
2634 * @param sender who sent us the message?
2635 * @param client who should we give the message to?
2636 * @param m contains the message to transmit
2637 * @param msize number of bytes in buf to transmit
2640 send_p2p_message_to_client (struct Neighbour *sender,
2641 struct Client *client,
2642 const void *m, size_t msize)
2644 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2645 struct NotifyTrafficMessage *ntm;
2648 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2649 "Core service passes message from `%4s' of type %u to client.\n",
2650 GNUNET_i2s(&sender->peer),
2651 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2653 ntm = (struct NotifyTrafficMessage *) buf;
2654 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2655 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2656 ntm->reserved = htonl (0);
2657 ntm->peer = sender->peer;
2658 memcpy (&ntm[1], m, msize);
2659 send_to_client (client, &ntm->header, GNUNET_YES);
2664 * Deliver P2P message to interested clients.
2666 * @param sender who sent us the message?
2667 * @param m the message
2668 * @param msize size of the message (including header)
2671 deliver_message (struct Neighbour *sender,
2672 const struct GNUNET_MessageHeader *m, size_t msize)
2674 struct Client *cpos;
2679 type = ntohs (m->type);
2681 while (cpos != NULL)
2683 deliver_full = GNUNET_NO;
2684 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
2685 deliver_full = GNUNET_YES;
2688 for (tpos = 0; tpos < cpos->tcnt; tpos++)
2690 if (type != cpos->types[tpos])
2692 deliver_full = GNUNET_YES;
2696 if (GNUNET_YES == deliver_full)
2697 send_p2p_message_to_client (sender, cpos, m, msize);
2698 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2699 send_p2p_message_to_client (sender, cpos, m,
2700 sizeof (struct GNUNET_MessageHeader));
2707 * Align P2P message and then deliver to interested clients.
2709 * @param sender who sent us the message?
2710 * @param buffer unaligned (!) buffer containing message
2711 * @param msize size of the message (including header)
2714 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
2718 /* TODO: call to statistics? */
2719 memcpy (abuf, buffer, msize);
2720 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
2725 * Deliver P2P messages to interested clients.
2727 * @param sender who sent us the message?
2728 * @param buffer buffer containing messages, can be modified
2729 * @param buffer_size size of the buffer (overall)
2730 * @param offset offset where messages in the buffer start
2733 deliver_messages (struct Neighbour *sender,
2734 const char *buffer, size_t buffer_size, size_t offset)
2736 struct GNUNET_MessageHeader *mhp;
2737 struct GNUNET_MessageHeader mh;
2741 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
2743 if (0 != offset % sizeof (uint16_t))
2745 /* outch, need to copy to access header */
2746 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
2751 /* can access header directly */
2752 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
2754 msize = ntohs (mhp->size);
2755 if (msize + offset > buffer_size)
2757 /* malformed message, header says it is larger than what
2758 would fit into the overall buffer */
2759 GNUNET_break_op (0);
2762 #if HAVE_UNALIGNED_64_ACCESS
2763 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
2765 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
2767 if (GNUNET_YES == need_align)
2768 align_and_deliver (sender, &buffer[offset], msize);
2770 deliver_message (sender,
2771 (const struct GNUNET_MessageHeader *)
2772 &buffer[offset], msize);
2779 * We received an encrypted message. Decrypt, validate and
2780 * pass on to the appropriate clients.
2783 handle_encrypted_message (struct Neighbour *n,
2784 const struct EncryptedMessage *m)
2786 size_t size = ntohs (m->header.size);
2788 struct EncryptedMessage *pt; /* plaintext */
2792 struct GNUNET_TIME_Absolute t;
2795 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2796 "Core service receives `%s' request from `%4s'.\n",
2797 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
2803 &m->sequence_number,
2804 &buf[ENCRYPTED_HEADER_SIZE], size - ENCRYPTED_HEADER_SIZE))
2806 pt = (struct EncryptedMessage *) buf;
2809 GNUNET_CRYPTO_hash (&pt->sequence_number,
2810 size - ENCRYPTED_HEADER_SIZE, &ph);
2811 if (0 != memcmp (&ph, &m->plaintext_hash, sizeof (GNUNET_HashCode)))
2813 /* checksum failed */
2814 GNUNET_break_op (0);
2818 /* validate sequence number */
2819 snum = ntohl (pt->sequence_number);
2820 if (n->last_sequence_number_received == snum)
2822 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2823 "Received duplicate message, ignoring.\n");
2824 /* duplicate, ignore */
2827 if ((n->last_sequence_number_received > snum) &&
2828 (n->last_sequence_number_received - snum > 32))
2830 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2831 "Received ancient out of sequence message, ignoring.\n");
2832 /* ancient out of sequence, ignore */
2835 if (n->last_sequence_number_received > snum)
2837 unsigned int rotbit =
2838 1 << (n->last_sequence_number_received - snum - 1);
2839 if ((n->last_packets_bitmap & rotbit) != 0)
2841 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2842 "Received duplicate message, ignoring.\n");
2843 /* duplicate, ignore */
2846 n->last_packets_bitmap |= rotbit;
2848 if (n->last_sequence_number_received < snum)
2850 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
2851 n->last_sequence_number_received = snum;
2854 /* check timestamp */
2855 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
2856 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
2858 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2860 ("Message received far too old (%llu ms). Content ignored.\n"),
2861 GNUNET_TIME_absolute_get_duration (t).value);
2865 /* process decrypted message(s) */
2866 update_window (GNUNET_YES,
2867 &n->available_send_window,
2868 &n->last_asw_update,
2870 n->bpm_out_external_limit = ntohl (pt->inbound_bpm_limit);
2871 n->bpm_out = GNUNET_MAX (n->bpm_out_external_limit,
2872 n->bpm_out_internal_limit);
2873 n->last_activity = GNUNET_TIME_absolute_get ();
2874 off = sizeof (struct EncryptedMessage);
2875 deliver_messages (n, buf, size, off);
2880 * Function called by the transport for each received message.
2882 * @param cls closure
2883 * @param peer (claimed) identity of the other peer
2884 * @param message the message
2885 * @param latency estimated latency for communicating with the
2886 * given peer (round-trip)
2887 * @param distance in overlay hops, as given by transport plugin
2890 handle_transport_receive (void *cls,
2891 const struct GNUNET_PeerIdentity *peer,
2892 const struct GNUNET_MessageHeader *message,
2893 struct GNUNET_TIME_Relative latency,
2894 unsigned int distance)
2896 struct Neighbour *n;
2897 struct GNUNET_TIME_Absolute now;
2903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2904 "Received message of type %u from `%4s', demultiplexing.\n",
2905 ntohs (message->type), GNUNET_i2s (peer));
2907 n = find_neighbour (peer);
2913 n->last_latency = latency;
2914 up = (n->status == PEER_STATE_KEY_CONFIRMED);
2915 type = ntohs (message->type);
2916 size = ntohs (message->size);
2919 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
2920 if (size != sizeof (struct SetKeyMessage))
2922 GNUNET_break_op (0);
2925 handle_set_key (n, (const struct SetKeyMessage *) message);
2927 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
2928 if (size < sizeof (struct EncryptedMessage) +
2929 sizeof (struct GNUNET_MessageHeader))
2931 GNUNET_break_op (0);
2934 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2935 (n->status != PEER_STATE_KEY_CONFIRMED))
2937 GNUNET_break_op (0);
2940 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
2942 case GNUNET_MESSAGE_TYPE_CORE_PING:
2943 if (size != sizeof (struct PingMessage))
2945 GNUNET_break_op (0);
2948 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2949 (n->status != PEER_STATE_KEY_CONFIRMED))
2952 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2953 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
2954 "PING", GNUNET_i2s (&n->peer));
2956 GNUNET_free_non_null (n->pending_ping);
2957 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
2958 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
2961 handle_ping (n, (const struct PingMessage *) message);
2963 case GNUNET_MESSAGE_TYPE_CORE_PONG:
2964 if (size != sizeof (struct PingMessage))
2966 GNUNET_break_op (0);
2969 if ((n->status != PEER_STATE_KEY_SENT) &&
2970 (n->status != PEER_STATE_KEY_RECEIVED) &&
2971 (n->status != PEER_STATE_KEY_CONFIRMED))
2973 /* could not decrypt pong, oops! */
2974 GNUNET_break_op (0);
2977 handle_pong (n, (const struct PingMessage *) message);
2980 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2981 _("Unsupported message of type %u received.\n"), type);
2984 if (n->status == PEER_STATE_KEY_CONFIRMED)
2986 now = GNUNET_TIME_absolute_get ();
2987 n->last_activity = now;
2989 n->time_established = now;
2995 * Function that recalculates the bandwidth quota for the
2996 * given neighbour and transmits it to the transport service.
2998 * @param cls neighbour for the quota update
3002 neighbour_quota_update (void *cls,
3003 const struct GNUNET_SCHEDULER_TaskContext *tc);
3007 * Schedule the task that will recalculate the bandwidth
3008 * quota for this peer (and possibly force a disconnect of
3009 * idle peers by calculating a bandwidth of zero).
3012 schedule_quota_update (struct Neighbour *n)
3014 GNUNET_assert (n->quota_update_task ==
3015 GNUNET_SCHEDULER_NO_TASK);
3016 n->quota_update_task
3017 = GNUNET_SCHEDULER_add_delayed (sched,
3018 QUOTA_UPDATE_FREQUENCY,
3019 &neighbour_quota_update,
3025 * Function that recalculates the bandwidth quota for the
3026 * given neighbour and transmits it to the transport service.
3028 * @param cls neighbour for the quota update
3032 neighbour_quota_update (void *cls,
3033 const struct GNUNET_SCHEDULER_TaskContext *tc)
3035 struct Neighbour *n = cls;
3039 unsigned long long distributable;
3041 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3042 /* calculate relative preference among all neighbours;
3043 divides by a bit more to avoid division by zero AND to
3044 account for possibility of new neighbours joining any time
3045 AND to convert to double... */
3046 pref_rel = n->current_preference / (1.0 + preference_sum);
3048 if (bandwidth_target_out > neighbour_count * MIN_BPM_PER_PEER)
3049 distributable = bandwidth_target_out - neighbour_count * MIN_BPM_PER_PEER;
3050 share = distributable * pref_rel;
3051 q_in = MIN_BPM_PER_PEER + (unsigned long long) share;
3052 /* check if we want to disconnect for good due to inactivity */
3053 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3054 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3055 q_in = 0; /* force disconnect */
3056 if ( (n->bpm_in + MIN_BPM_CHANGE < q_in) ||
3057 (n->bpm_in - MIN_BPM_CHANGE > q_in) )
3060 GNUNET_TRANSPORT_set_quota (transport,
3064 GNUNET_TIME_UNIT_FOREVER_REL,
3067 schedule_quota_update (n);
3072 * Function called by transport to notify us that
3073 * a peer connected to us (on the network level).
3075 * @param cls closure
3076 * @param peer the peer that connected
3077 * @param latency current latency of the connection
3078 * @param distance in overlay hops, as given by transport plugin
3081 handle_transport_notify_connect (void *cls,
3082 const struct GNUNET_PeerIdentity *peer,
3083 struct GNUNET_TIME_Relative latency,
3084 unsigned int distance)
3086 struct Neighbour *n;
3087 struct GNUNET_TIME_Absolute now;
3088 struct ConnectNotifyMessage cnm;
3090 n = find_neighbour (peer);
3093 /* duplicate connect notification!? */
3097 now = GNUNET_TIME_absolute_get ();
3098 n = GNUNET_malloc (sizeof (struct Neighbour));
3099 n->next = neighbours;
3103 n->last_latency = latency;
3104 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
3105 n->encrypt_key_created = now;
3106 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
3107 n->last_asw_update = now;
3108 n->last_arw_update = now;
3109 n->bpm_in = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
3110 n->bpm_out = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
3111 n->bpm_out_internal_limit = (uint32_t) - 1;
3112 n->bpm_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
3113 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3116 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3117 "Received connection from `%4s'.\n",
3118 GNUNET_i2s (&n->peer));
3120 schedule_quota_update (n);
3121 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3122 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3123 cnm.reserved = htonl (0);
3125 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3131 * Free the given entry for the neighbour (it has
3132 * already been removed from the list at this point).
3134 * @param n neighbour to free
3137 free_neighbour (struct Neighbour *n)
3139 struct MessageEntry *m;
3141 if (n->pitr != NULL)
3143 GNUNET_PEERINFO_iterate_cancel (n->pitr);
3148 GNUNET_free (n->skm);
3151 while (NULL != (m = n->messages))
3153 n->messages = m->next;
3156 while (NULL != (m = n->encrypted_head))
3158 n->encrypted_head = m->next;
3162 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
3163 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
3164 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
3165 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3166 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
3167 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
3168 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
3169 GNUNET_free_non_null (n->public_key);
3170 GNUNET_free_non_null (n->pending_ping);
3176 * Function called by transport telling us that a peer
3179 * @param cls closure
3180 * @param peer the peer that disconnected
3183 handle_transport_notify_disconnect (void *cls,
3184 const struct GNUNET_PeerIdentity *peer)
3186 struct ConnectNotifyMessage cnm;
3187 struct Neighbour *n;
3188 struct Neighbour *p;
3191 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3192 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3196 while ((n != NULL) &&
3197 (0 != memcmp (&n->peer, peer, sizeof (struct GNUNET_PeerIdentity))))
3208 neighbours = n->next;
3211 GNUNET_assert (neighbour_count > 0);
3213 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3214 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3215 cnm.reserved = htonl (0);
3217 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3223 * Last task run during shutdown. Disconnects us from
3227 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3229 struct Neighbour *n;
3233 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3234 "Core service shutting down.\n");
3236 GNUNET_assert (transport != NULL);
3237 GNUNET_TRANSPORT_disconnect (transport);
3239 while (NULL != (n = neighbours))
3241 neighbours = n->next;
3242 GNUNET_assert (neighbour_count > 0);
3246 while (NULL != (c = clients))
3247 handle_client_disconnect (NULL, c->client_handle);
3248 if (my_private_key != NULL)
3249 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3254 * Initiate core service.
3256 * @param cls closure
3257 * @param s scheduler to use
3258 * @param serv the initialized server
3259 * @param c configuration to use
3263 struct GNUNET_SCHEDULER_Handle *s,
3264 struct GNUNET_SERVER_Handle *serv,
3265 const struct GNUNET_CONFIGURATION_Handle *c)
3268 unsigned long long qin;
3269 unsigned long long qout;
3270 unsigned long long tneigh;
3276 /* parse configuration */
3279 GNUNET_CONFIGURATION_get_value_number (c,
3282 &bandwidth_target_in)) ||
3284 GNUNET_CONFIGURATION_get_value_number (c,
3287 &bandwidth_target_out)) ||
3290 GNUNET_CONFIGURATION_get_value_number (c,
3295 GNUNET_CONFIGURATION_get_value_number (c,
3297 "ZZ_LIMIT", &tneigh)) ||
3300 GNUNET_CONFIGURATION_get_value_filename (c,
3302 "HOSTKEY", &keyfile)))
3304 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3306 ("Core service is lacking key configuration settings. Exiting.\n"));
3307 GNUNET_SCHEDULER_shutdown (s);
3310 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3311 GNUNET_free (keyfile);
3312 if (my_private_key == NULL)
3314 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3315 _("Core service could not access hostkey. Exiting.\n"));
3316 GNUNET_SCHEDULER_shutdown (s);
3319 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3320 GNUNET_CRYPTO_hash (&my_public_key,
3321 sizeof (my_public_key), &my_identity.hashPubKey);
3322 /* setup notification */
3324 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3325 /* setup transport connection */
3326 transport = GNUNET_TRANSPORT_connect (sched,
3329 &handle_transport_receive,
3330 &handle_transport_notify_connect,
3331 &handle_transport_notify_disconnect);
3332 GNUNET_assert (NULL != transport);
3333 GNUNET_SCHEDULER_add_delayed (sched,
3334 GNUNET_TIME_UNIT_FOREVER_REL,
3335 &cleaning_task, NULL);
3336 /* process client requests */
3337 GNUNET_SERVER_add_handlers (server, handlers);
3338 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3339 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3345 * The main function for the transport service.
3347 * @param argc number of arguments from the command line
3348 * @param argv command line arguments
3349 * @return 0 ok, 1 on error
3352 main (int argc, char *const *argv)
3354 return (GNUNET_OK ==
3355 GNUNET_SERVICE_run (argc,
3358 GNUNET_SERVICE_OPTION_NONE,
3359 &run, NULL)) ? 0 : 1;
3362 /* end of gnunet-service-core.c */