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"
44 #define DEBUG_HANDSHAKE GNUNET_NO
47 * Receive and send buffer windows grow over time. For
48 * how long can 'unused' bandwidth accumulate before we
49 * need to cap it? (specified in ms).
51 #define MAX_WINDOW_TIME (5 * 60 * 1000)
54 * How many messages do we queue up at most for optional
55 * notifications to a client? (this can cause notifications
56 * about outgoing messages to be dropped).
58 #define MAX_NOTIFY_QUEUE 16
61 * Minimum of bytes per minute (out) to assign to any connected peer.
62 * Should be rather low; values larger than DEFAULT_BPM_IN_OUT make no
65 #define MIN_BPM_PER_PEER GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT
68 * What is the smallest change (in number of bytes per minute)
69 * that we consider significant enough to bother triggering?
71 #define MIN_BPM_CHANGE 32
74 * After how much time past the "official" expiration time do
75 * we discard messages? Should not be zero since we may
76 * intentionally defer transmission until close to the deadline
77 * and then may be slightly past the deadline due to inaccuracy
78 * in sleep and our own CPU consumption.
80 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
83 * What is the maximum delay for a SET_KEY message?
85 #define MAX_SET_KEY_DELAY GNUNET_TIME_UNIT_SECONDS
88 * What how long do we wait for SET_KEY confirmation initially?
90 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3)
93 * What is the maximum delay for a PING message?
95 #define MAX_PING_DELAY GNUNET_TIME_UNIT_SECONDS
98 * What is the maximum delay for a PONG message?
100 #define MAX_PONG_DELAY GNUNET_TIME_UNIT_SECONDS
103 * How often do we recalculate bandwidth quotas?
105 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_UNIT_SECONDS
108 * What is the priority for a SET_KEY message?
110 #define SET_KEY_PRIORITY 0xFFFFFF
113 * What is the priority for a PING message?
115 #define PING_PRIORITY 0xFFFFFF
118 * What is the priority for a PONG message?
120 #define PONG_PRIORITY 0xFFFFFF
123 * How many messages do we queue per peer at most?
125 #define MAX_PEER_QUEUE_SIZE 16
128 * How many non-mandatory messages do we queue per client at most?
130 #define MAX_CLIENT_QUEUE_SIZE 32
133 * What is the maximum age of a message for us to consider
134 * processing it? Note that this looks at the timestamp used
135 * by the other peer, so clock skew between machines does
136 * come into play here. So this should be picked high enough
137 * so that a little bit of clock skew does not prevent peers
138 * from connecting to us.
140 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
143 * What is the maximum size for encrypted messages? Note that this
144 * number imposes a clear limit on the maximum size of any message.
145 * Set to a value close to 64k but not so close that transports will
146 * have trouble with their headers.
148 #define MAX_ENCRYPTED_MESSAGE_SIZE (63 * 1024)
152 * State machine for our P2P encryption handshake. Everyone starts in
153 * "DOWN", if we receive the other peer's key (other peer initiated)
154 * we start in state RECEIVED (since we will immediately send our
155 * own); otherwise we start in SENT. If we get back a PONG from
156 * within either state, we move up to CONFIRMED (the PONG will always
157 * be sent back encrypted with the key we sent to the other peer).
159 enum PeerStateMachine
163 PEER_STATE_KEY_RECEIVED,
164 PEER_STATE_KEY_CONFIRMED
169 * Number of bytes (at the beginning) of "struct EncryptedMessage"
170 * that are NOT encrypted.
172 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t) + sizeof(GNUNET_HashCode))
176 * Encapsulation for encrypted messages exchanged between
177 * peers. Followed by the actual encrypted data.
179 struct EncryptedMessage
182 * Message type is either CORE_ENCRYPTED_MESSAGE.
184 struct GNUNET_MessageHeader header;
189 uint32_t reserved GNUNET_PACKED;
192 * Hash of the plaintext, used to verify message integrity;
193 * ALSO used as the IV for the symmetric cipher! Everything
194 * after this hash will be encrypted. ENCRYPTED_HEADER_SIZE
195 * must be set to the offset of the next field.
197 GNUNET_HashCode plaintext_hash;
200 * Sequence number, in network byte order. This field
201 * must be the first encrypted/decrypted field and the
202 * first byte that is hashed for the plaintext hash.
204 uint32_t sequence_number GNUNET_PACKED;
207 * Desired bandwidth (how much we should send to this
208 * peer / how much is the sender willing to receive),
209 * in bytes per minute.
211 uint32_t inbound_bpm_limit GNUNET_PACKED;
214 * Timestamp. Used to prevent reply of ancient messages
215 * (recent messages are caught with the sequence number).
217 struct GNUNET_TIME_AbsoluteNBO timestamp;
222 * We're sending an (encrypted) PING to the other peer to check if he
223 * can decrypt. The other peer should respond with a PONG with the
224 * same content, except this time encrypted with the receiver's key.
229 * Message type is either CORE_PING or CORE_PONG.
231 struct GNUNET_MessageHeader header;
234 * Random number chosen to make reply harder.
236 uint32_t challenge GNUNET_PACKED;
239 * Intended target of the PING, used primarily to check
240 * that decryption actually worked.
242 struct GNUNET_PeerIdentity target;
247 * Message transmitted to set (or update) a session key.
253 * Message type is either CORE_SET_KEY.
255 struct GNUNET_MessageHeader header;
258 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
260 int32_t sender_status GNUNET_PACKED;
263 * Purpose of the signature, will be
264 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
266 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
269 * At what time was this key created?
271 struct GNUNET_TIME_AbsoluteNBO creation_time;
274 * The encrypted session key.
276 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
279 * Who is the intended recipient?
281 struct GNUNET_PeerIdentity target;
284 * Signature of the stuff above (starting at purpose).
286 struct GNUNET_CRYPTO_RsaSignature signature;
292 * Message waiting for transmission. This struct
293 * is followed by the actual content of the message.
299 * We keep messages in a linked list (for now).
301 struct MessageEntry *next;
304 * By when are we supposed to transmit this message?
306 struct GNUNET_TIME_Absolute deadline;
309 * How important is this message to us?
311 unsigned int priority;
314 * How long is the message? (number of bytes following
315 * the "struct MessageEntry", but not including the
316 * size of "struct MessageEntry" itself!)
321 * Was this message selected for transmission in the
322 * current round? GNUNET_YES or GNUNET_NO.
327 * Did we give this message some slack (delayed sending) previously
328 * (and hence should not give it any more slack)? GNUNET_YES or
339 * We keep neighbours in a linked list (for now).
341 struct Neighbour *next;
344 * Unencrypted messages destined for this peer.
346 struct MessageEntry *messages;
349 * Head of the batched, encrypted message queue (already ordered,
350 * transmit starting with the head).
352 struct MessageEntry *encrypted_head;
355 * Tail of the batched, encrypted message queue (already ordered,
356 * append new messages to tail)
358 struct MessageEntry *encrypted_tail;
361 * Handle for pending requests for transmission to this peer
362 * with the transport service. NULL if no request is pending.
364 struct GNUNET_TRANSPORT_TransmitHandle *th;
367 * Public key of the neighbour, NULL if we don't have it yet.
369 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
372 * We received a PING message before we got the "public_key"
373 * (or the SET_KEY). We keep it here until we have a key
374 * to decrypt it. NULL if no PING is pending.
376 struct PingMessage *pending_ping;
379 * We received a PONG message before we got the "public_key"
380 * (or the SET_KEY). We keep it here until we have a key
381 * to decrypt it. NULL if no PONG is pending.
383 struct PingMessage *pending_pong;
386 * Non-NULL if we are currently looking up HELLOs for this peer.
389 struct GNUNET_PEERINFO_IteratorContext *pitr;
392 * SetKeyMessage to transmit, NULL if we are not currently trying
395 struct SetKeyMessage *skm;
398 * Identity of the neighbour.
400 struct GNUNET_PeerIdentity peer;
403 * Key we use to encrypt our messages for the other peer
404 * (initialized by us when we do the handshake).
406 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
409 * Key we use to decrypt messages from the other peer
410 * (given to us by the other peer during the handshake).
412 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
415 * ID of task used for re-trying plaintext scheduling.
417 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
420 * ID of task used for re-trying SET_KEY and PING message.
422 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
425 * ID of task used for updating bandwidth quota for this neighbour.
427 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
430 * At what time did we generate our encryption key?
432 struct GNUNET_TIME_Absolute encrypt_key_created;
435 * At what time did the other peer generate the decryption key?
437 struct GNUNET_TIME_Absolute decrypt_key_created;
440 * At what time did we initially establish (as in, complete session
441 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
443 struct GNUNET_TIME_Absolute time_established;
446 * At what time did we last receive an encrypted message from the
447 * other peer? Should be zero if status != KEY_CONFIRMED.
449 struct GNUNET_TIME_Absolute last_activity;
452 * Last latency observed from this peer.
454 struct GNUNET_TIME_Relative last_latency;
457 * At what frequency are we currently re-trying SET_KEY messages?
459 struct GNUNET_TIME_Relative set_key_retry_frequency;
462 * Time of our last update to the "available_send_window".
464 struct GNUNET_TIME_Absolute last_asw_update;
467 * Time of our last update to the "available_recv_window".
469 struct GNUNET_TIME_Absolute last_arw_update;
472 * Number of bytes that we are eligible to transmit to this
473 * peer at this point. Incremented every minute by max_out_bpm,
474 * bounded by max_bpm (no back-log larger than MAX_BUF_FACT minutes,
475 * bandwidth-hogs are sampled at a frequency of about 78s!);
476 * may get negative if we have VERY high priority content.
478 long long available_send_window;
481 * How much downstream capacity of this peer has been reserved for
482 * our traffic? (Our clients can request that a certain amount of
483 * bandwidth is available for replies to them; this value is used to
484 * make sure that this reserved amount of bandwidth is actually
487 long long available_recv_window;
490 * How valueable were the messages of this peer recently?
492 unsigned long long current_preference;
495 * Bit map indicating which of the 32 sequence numbers before the last
496 * were received (good for accepting out-of-order packets and
497 * estimating reliability of the connection)
499 unsigned int last_packets_bitmap;
502 * Number of messages in the message queue for this peer.
504 unsigned int message_queue_size;
507 * last sequence number received on this connection (highest)
509 uint32_t last_sequence_number_received;
512 * last sequence number transmitted
514 uint32_t last_sequence_number_sent;
517 * Available bandwidth in for this peer (current target).
522 * Available bandwidth out for this peer (current target).
527 * Internal bandwidth limit set for this peer (initially
528 * typically set to "-1"). "bpm_out" is MAX of
529 * "bpm_out_internal_limit" and "bpm_out_external_limit".
531 uint32_t bpm_out_internal_limit;
534 * External bandwidth limit set for this peer by the
535 * peer that we are communicating with. "bpm_out" is MAX of
536 * "bpm_out_internal_limit" and "bpm_out_external_limit".
538 uint32_t bpm_out_external_limit;
541 * What was our PING challenge number (for this peer)?
543 uint32_t ping_challenge;
546 * What was the last distance to this peer as reported by the transports?
548 uint32_t last_distance;
551 * What is our connection status?
553 enum PeerStateMachine status;
559 * Data structure for each client connected to the core service.
564 * Clients are kept in a linked list.
569 * Handle for the client with the server API.
571 struct GNUNET_SERVER_Client *client_handle;
574 * Array of the types of messages this peer cares
575 * about (with "tcnt" entries). Allocated as part
576 * of this client struct, do not free!
581 * Options for messages this client cares about,
582 * see GNUNET_CORE_OPTION_ values.
587 * Number of types of incoming messages this client
588 * specifically cares about. Size of the "types" array.
598 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
603 static struct GNUNET_PeerIdentity my_identity;
608 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
613 struct GNUNET_SCHEDULER_Handle *sched;
618 const struct GNUNET_CONFIGURATION_Handle *cfg;
623 static struct GNUNET_SERVER_Handle *server;
628 static struct GNUNET_TRANSPORT_Handle *transport;
631 * Linked list of our clients.
633 static struct Client *clients;
636 * Context for notifications we need to send to our clients.
638 static struct GNUNET_SERVER_NotificationContext *notifier;
641 * We keep neighbours in a linked list (for now).
643 static struct Neighbour *neighbours;
646 * Sum of all preferences among all neighbours.
648 static unsigned long long preference_sum;
651 * Total number of neighbours we have.
653 static unsigned int neighbour_count;
656 * How much inbound bandwidth are we supposed to be using?
658 static unsigned long long bandwidth_target_in;
661 * How much outbound bandwidth are we supposed to be using?
663 static unsigned long long bandwidth_target_out;
668 * A preference value for a neighbour was update. Update
669 * the preference sum accordingly.
671 * @param inc how much was a preference value increased?
674 update_preference_sum (unsigned long long inc)
677 unsigned long long os;
680 preference_sum += inc;
681 if (preference_sum >= os)
683 /* overflow! compensate by cutting all values in half! */
688 n->current_preference /= 2;
689 preference_sum += n->current_preference;
696 * Recalculate the number of bytes we expect to
697 * receive or transmit in a given window.
699 * @param force force an update now (even if not much time has passed)
700 * @param window pointer to the byte counter (updated)
701 * @param ts pointer to the timestamp (updated)
702 * @param bpm number of bytes per minute that should
703 * be added to the window.
706 update_window (int force,
708 struct GNUNET_TIME_Absolute *ts, unsigned int bpm)
710 struct GNUNET_TIME_Relative since;
712 since = GNUNET_TIME_absolute_get_duration (*ts);
713 if ( (force == GNUNET_NO) &&
714 (since.value < 60 * 1000) )
715 return; /* not even a minute has passed */
716 *ts = GNUNET_TIME_absolute_get ();
717 *window += (bpm * since.value) / 60 / 1000;
718 if (*window > MAX_WINDOW_TIME * bpm)
719 *window = MAX_WINDOW_TIME * bpm;
724 * Find the entry for the given neighbour.
726 * @param peer identity of the neighbour
727 * @return NULL if we are not connected, otherwise the
730 static struct Neighbour *
731 find_neighbour (const struct GNUNET_PeerIdentity *peer)
733 struct Neighbour *ret;
736 while ((ret != NULL) &&
737 (0 != memcmp (&ret->peer,
738 peer, sizeof (struct GNUNET_PeerIdentity))))
745 * Send a message to one of our clients.
747 * @param client target for the message
748 * @param msg message to transmit
749 * @param can_drop could this message be dropped if the
750 * client's queue is getting too large?
753 send_to_client (struct Client *client,
754 const struct GNUNET_MessageHeader *msg,
757 #if DEBUG_CORE_CLIENT
758 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
759 "Preparing to send message of type %u to client.\n",
762 GNUNET_SERVER_notification_context_unicast (notifier,
763 client->client_handle,
770 * Send a message to all of our current clients that have
771 * the right options set.
773 * @param msg message to multicast
774 * @param can_drop can this message be discarded if the queue is too long
775 * @param options mask to use
778 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
787 if (0 != (c->options & options))
788 send_to_client (c, msg, can_drop);
795 * Handle CORE_INIT request.
798 handle_client_init (void *cls,
799 struct GNUNET_SERVER_Client *client,
800 const struct GNUNET_MessageHeader *message)
802 const struct InitMessage *im;
803 struct InitReplyMessage irm;
806 const uint16_t *types;
808 struct ConnectNotifyMessage cnm;
810 #if DEBUG_CORE_CLIENT
811 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
812 "Client connecting to core service with `%s' message\n",
815 /* check that we don't have an entry already */
819 if (client == c->client_handle)
822 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
827 msize = ntohs (message->size);
828 if (msize < sizeof (struct InitMessage))
831 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
834 GNUNET_SERVER_notification_context_add (notifier, client);
835 im = (const struct InitMessage *) message;
836 types = (const uint16_t *) &im[1];
837 msize -= sizeof (struct InitMessage);
838 c = GNUNET_malloc (sizeof (struct Client) + msize);
839 c->client_handle = client;
842 memcpy (&c[1], types, msize);
843 c->types = (uint16_t *) & c[1];
844 c->options = ntohl (im->options);
845 c->tcnt = msize / sizeof (uint16_t);
846 /* send init reply message */
847 irm.header.size = htons (sizeof (struct InitReplyMessage));
848 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
849 irm.reserved = htonl (0);
850 memcpy (&irm.publicKey,
852 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
853 #if DEBUG_CORE_CLIENT
854 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
855 "Sending `%s' message to client.\n", "INIT_REPLY");
857 send_to_client (c, &irm.header, GNUNET_NO);
858 /* notify new client about existing neighbours */
859 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
860 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
864 #if DEBUG_CORE_CLIENT
865 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
866 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
868 cnm.distance = htonl (n->last_distance);
869 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
871 send_to_client (c, &cnm.header, GNUNET_NO);
874 GNUNET_SERVER_receive_done (client, GNUNET_OK);
879 * A client disconnected, clean up.
882 * @param client identification of the client
885 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
892 #if DEBUG_CORE_CLIENT
893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
894 "Client has disconnected from core service.\n");
900 if (client == pos->client_handle)
905 prev->next = pos->next;
912 /* client never sent INIT */
917 * Handle REQUEST_INFO request.
920 handle_client_request_info (void *cls,
921 struct GNUNET_SERVER_Client *client,
922 const struct GNUNET_MessageHeader *message)
924 const struct RequestInfoMessage *rcm;
926 struct ConfigurationInfoMessage cim;
928 unsigned long long old_preference;
929 struct GNUNET_SERVER_TransmitContext *tc;
931 #if DEBUG_CORE_CLIENT
932 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
933 "Core service receives `%s' request.\n", "REQUEST_INFO");
935 rcm = (const struct RequestInfoMessage *) message;
936 n = find_neighbour (&rcm->peer);
937 memset (&cim, 0, sizeof (cim));
938 if ((n != NULL) && (n->status == PEER_STATE_KEY_CONFIRMED))
940 update_window (GNUNET_YES,
941 &n->available_send_window,
944 n->bpm_out_internal_limit = ntohl (rcm->limit_outbound_bpm);
945 n->bpm_out = GNUNET_MAX (n->bpm_out_internal_limit,
946 n->bpm_out_external_limit);
947 reserv = ntohl (rcm->reserve_inbound);
950 n->available_recv_window += reserv;
954 update_window (GNUNET_NO,
955 &n->available_recv_window,
956 &n->last_arw_update, n->bpm_in);
957 if (n->available_recv_window < reserv)
958 reserv = n->available_recv_window;
959 n->available_recv_window -= reserv;
961 old_preference = n->current_preference;
962 n->current_preference += GNUNET_ntohll(rcm->preference_change);
963 if (old_preference > n->current_preference)
965 /* overflow; cap at maximum value */
966 n->current_preference = (unsigned long long) -1;
968 update_preference_sum (n->current_preference - old_preference);
969 cim.reserved_amount = htonl (reserv);
970 cim.bpm_in = htonl (n->bpm_in);
971 cim.bpm_out = htonl (n->bpm_out);
972 cim.preference = n->current_preference;
974 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
975 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
976 cim.peer = rcm->peer;
978 #if DEBUG_CORE_CLIENT
979 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
980 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
982 tc = GNUNET_SERVER_transmit_context_create (client);
983 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
984 GNUNET_SERVER_transmit_context_run (tc,
985 GNUNET_TIME_UNIT_FOREVER_REL);
990 * Check if we have encrypted messages for the specified neighbour
991 * pending, and if so, check with the transport about sending them
994 * @param n neighbour to check.
996 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1000 * Function called when the transport service is ready to
1001 * receive an encrypted message for the respective peer
1003 * @param cls neighbour to use message from
1004 * @param size number of bytes we can transmit
1005 * @param buf where to copy the message
1006 * @return number of bytes transmitted
1009 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1011 struct Neighbour *n = cls;
1012 struct MessageEntry *m;
1017 GNUNET_assert (NULL != (m = n->encrypted_head));
1018 n->encrypted_head = m->next;
1019 if (m->next == NULL)
1020 n->encrypted_tail = NULL;
1025 GNUNET_assert (size >= m->size);
1026 memcpy (cbuf, &m[1], m->size);
1028 n->available_send_window -= m->size;
1029 process_encrypted_neighbour_queue (n);
1032 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1033 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1034 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1035 ret, GNUNET_i2s (&n->peer));
1040 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1041 "Transmission for message of type %u and size %u failed\n",
1042 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1051 * Check if we have plaintext messages for the specified neighbour
1052 * pending, and if so, consider batching and encrypting them (and
1053 * then trigger processing of the encrypted queue if needed).
1055 * @param n neighbour to check.
1057 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1061 * Check if we have encrypted messages for the specified neighbour
1062 * pending, and if so, check with the transport about sending them
1065 * @param n neighbour to check.
1068 process_encrypted_neighbour_queue (struct Neighbour *n)
1070 struct MessageEntry *m;
1073 return; /* request already pending */
1074 if (n->encrypted_head == NULL)
1076 /* encrypted queue empty, try plaintext instead */
1077 process_plaintext_neighbour_queue (n);
1081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1082 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1083 n->encrypted_head->size,
1084 GNUNET_i2s (&n->peer),
1085 GNUNET_TIME_absolute_get_remaining (n->
1086 encrypted_head->deadline).
1090 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1091 n->encrypted_head->size,
1092 n->encrypted_head->priority,
1093 GNUNET_TIME_absolute_get_remaining
1094 (n->encrypted_head->deadline),
1095 ¬ify_encrypted_transmit_ready,
1099 /* message request too large (oops) */
1101 /* discard encrypted message */
1102 GNUNET_assert (NULL != (m = n->encrypted_head));
1103 n->encrypted_head = m->next;
1104 if (m->next == NULL)
1105 n->encrypted_tail = NULL;
1107 process_encrypted_neighbour_queue (n);
1113 * Decrypt size bytes from in and write the result to out. Use the
1114 * key for inbound traffic of the given neighbour. This function does
1115 * NOT do any integrity-checks on the result.
1117 * @param n neighbour we are receiving from
1118 * @param iv initialization vector to use
1119 * @param in ciphertext
1120 * @param out plaintext
1121 * @param size size of in/out
1122 * @return GNUNET_OK on success
1125 do_decrypt (struct Neighbour *n,
1126 const GNUNET_HashCode * iv,
1127 const void *in, void *out, size_t size)
1129 if (size != (uint16_t) size)
1134 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1135 (n->status != PEER_STATE_KEY_CONFIRMED))
1137 GNUNET_break_op (0);
1138 return GNUNET_SYSERR;
1141 GNUNET_CRYPTO_aes_decrypt (in,
1145 GNUNET_CRYPTO_AesInitializationVector *) iv,
1149 return GNUNET_SYSERR;
1152 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1153 "Decrypted %u bytes from `%4s' using key %u\n",
1154 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1161 * Encrypt size bytes from in and write the result to out. Use the
1162 * key for outbound traffic of the given neighbour.
1164 * @param n neighbour we are sending to
1165 * @param iv initialization vector to use
1166 * @param in ciphertext
1167 * @param out plaintext
1168 * @param size size of in/out
1169 * @return GNUNET_OK on success
1172 do_encrypt (struct Neighbour *n,
1173 const GNUNET_HashCode * iv,
1174 const void *in, void *out, size_t size)
1176 if (size != (uint16_t) size)
1181 GNUNET_assert (size ==
1182 GNUNET_CRYPTO_aes_encrypt (in,
1186 GNUNET_CRYPTO_AesInitializationVector
1189 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1190 "Encrypted %u bytes for `%4s' using key %u\n", size,
1191 GNUNET_i2s (&n->peer), n->encrypt_key.crc32);
1198 * Select messages for transmission. This heuristic uses a combination
1199 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1200 * and priority-based discard (in case no feasible schedule exist) and
1201 * speculative optimization (defer any kind of transmission until
1202 * we either create a batch of significant size, 25% of max, or until
1203 * we are close to a deadline). Furthermore, when scheduling the
1204 * heuristic also packs as many messages into the batch as possible,
1205 * starting with those with the earliest deadline. Yes, this is fun.
1207 * @param n neighbour to select messages from
1208 * @param size number of bytes to select for transmission
1209 * @param retry_time set to the time when we should try again
1210 * (only valid if this function returns zero)
1211 * @return number of bytes selected, or 0 if we decided to
1212 * defer scheduling overall; in that case, retry_time is set.
1215 select_messages (struct Neighbour *n,
1216 size_t size, struct GNUNET_TIME_Relative *retry_time)
1218 struct MessageEntry *pos;
1219 struct MessageEntry *min;
1220 struct MessageEntry *last;
1221 unsigned int min_prio;
1222 struct GNUNET_TIME_Absolute t;
1223 struct GNUNET_TIME_Absolute now;
1226 unsigned long long slack; /* how long could we wait before missing deadlines? */
1228 int discard_low_prio;
1230 GNUNET_assert (NULL != n->messages);
1231 now = GNUNET_TIME_absolute_get ();
1232 /* last entry in linked list of messages processed */
1234 /* should we remove the entry with the lowest
1235 priority from consideration for scheduling at the
1237 discard_low_prio = GNUNET_YES;
1238 while (GNUNET_YES == discard_low_prio)
1242 discard_low_prio = GNUNET_NO;
1243 /* calculate number of bytes available for transmission at time "t" */
1244 update_window (GNUNET_NO,
1245 &n->available_send_window,
1246 &n->last_asw_update,
1248 avail = n->available_send_window;
1249 t = n->last_asw_update;
1250 /* how many bytes have we (hypothetically) scheduled so far */
1252 /* maximum time we can wait before transmitting anything
1253 and still make all of our deadlines */
1257 /* note that we use "*2" here because we want to look
1258 a bit further into the future; much more makes no
1259 sense since new message might be scheduled in the
1261 while ((pos != NULL) && (off < size * 2))
1263 if (pos->do_transmit == GNUNET_YES)
1265 /* already removed from consideration */
1269 if (discard_low_prio == GNUNET_NO)
1271 delta = pos->deadline.value;
1272 if (delta < t.value)
1275 delta = t.value - delta;
1276 avail += delta * n->bpm_out / 1000 / 60;
1277 if (avail < pos->size)
1279 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1284 /* update slack, considering both its absolute deadline
1285 and relative deadlines caused by other messages
1286 with their respective load */
1287 slack = GNUNET_MIN (slack, avail / n->bpm_out);
1288 if ( (pos->deadline.value < now.value) ||
1289 (GNUNET_YES == pos->got_slack) )
1296 GNUNET_MIN (slack, pos->deadline.value - now.value);
1297 pos->got_slack = GNUNET_YES;
1303 t.value = GNUNET_MAX (pos->deadline.value, t.value);
1304 if (pos->priority <= min_prio)
1306 /* update min for discard */
1307 min_prio = pos->priority;
1312 if (discard_low_prio)
1314 GNUNET_assert (min != NULL);
1315 /* remove lowest-priority entry from consideration */
1316 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1320 /* guard against sending "tiny" messages with large headers without
1322 if ( (slack > 1000) && (size > 4 * off) )
1324 /* less than 25% of message would be filled with deadlines still
1325 being met if we delay by one second or more; so just wait for
1326 more data; but do not wait longer than 1s (since we don't want
1327 to delay messages for a really long time either). */
1328 retry_time->value = 1000;
1329 /* reset do_transmit values for next time */
1332 pos->do_transmit = GNUNET_NO;
1336 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1337 "Deferring transmission for 1s due to underfull message buffer size\n");
1341 /* select marked messages (up to size) for transmission */
1346 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1348 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1353 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1357 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1358 "Selected %u bytes of plaintext messages for transmission to `%4s'.\n",
1359 off, GNUNET_i2s (&n->peer));
1366 * Batch multiple messages into a larger buffer.
1368 * @param n neighbour to take messages from
1369 * @param buf target buffer
1370 * @param size size of buf
1371 * @param deadline set to transmission deadline for the result
1372 * @param retry_time set to the time when we should try again
1373 * (only valid if this function returns zero)
1374 * @param priority set to the priority of the batch
1375 * @return number of bytes written to buf (can be zero)
1378 batch_message (struct Neighbour *n,
1381 struct GNUNET_TIME_Absolute *deadline,
1382 struct GNUNET_TIME_Relative *retry_time,
1383 unsigned int *priority)
1385 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1386 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1387 struct MessageEntry *pos;
1388 struct MessageEntry *prev;
1389 struct MessageEntry *next;
1394 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1395 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1396 if (0 == select_messages (n, size, retry_time))
1398 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1399 "No messages selected, will try again in %llu ms\n",
1403 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1404 ntm->distance = htonl (n->last_distance);
1405 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1406 ntm->peer = n->peer;
1410 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1413 if (GNUNET_YES == pos->do_transmit)
1415 GNUNET_assert (pos->size <= size);
1416 /* do notifications */
1417 /* FIXME: track if we have *any* client that wants
1418 full notifications and only do this if that is
1420 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1422 memcpy (&ntm[1], &pos[1], pos->size);
1423 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1424 sizeof (struct GNUNET_MessageHeader));
1425 send_to_all_clients (&ntm->header,
1427 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1431 /* message too large for 'full' notifications, we do at
1432 least the 'hdr' type */
1435 sizeof (struct GNUNET_MessageHeader));
1437 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1439 send_to_all_clients (&ntm->header,
1441 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1444 "Encrypting message of type %u\n",
1445 ntohs(((struct GNUNET_MessageHeader*)&pos[1])->type));
1447 /* copy for encrypted transmission */
1448 memcpy (&buf[ret], &pos[1], pos->size);
1451 *priority += pos->priority;
1453 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1454 "Adding plaintext message with deadline %llu ms to batch\n",
1455 GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1457 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1471 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1472 "Deadline for message batch is %llu ms\n",
1473 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1480 * Remove messages with deadlines that have long expired from
1483 * @param n neighbour to inspect
1486 discard_expired_messages (struct Neighbour *n)
1488 struct MessageEntry *prev;
1489 struct MessageEntry *next;
1490 struct MessageEntry *pos;
1491 struct GNUNET_TIME_Absolute now;
1492 struct GNUNET_TIME_Relative delta;
1494 now = GNUNET_TIME_absolute_get ();
1500 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1501 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1504 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1505 "Message is %llu ms past due, discarding.\n",
1522 * Signature of the main function of a task.
1524 * @param cls closure
1525 * @param tc context information (why was this task triggered now)
1528 retry_plaintext_processing (void *cls,
1529 const struct GNUNET_SCHEDULER_TaskContext *tc)
1531 struct Neighbour *n = cls;
1533 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1534 process_plaintext_neighbour_queue (n);
1539 * Send our key (and encrypted PING) to the other peer.
1541 * @param n the other peer
1543 static void send_key (struct Neighbour *n);
1546 * Task that will retry "send_key" if our previous attempt failed
1550 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1552 struct Neighbour *n = cls;
1554 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1555 n->set_key_retry_frequency =
1556 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1562 * Check if we have plaintext messages for the specified neighbour
1563 * pending, and if so, consider batching and encrypting them (and
1564 * then trigger processing of the encrypted queue if needed).
1566 * @param n neighbour to check.
1569 process_plaintext_neighbour_queue (struct Neighbour *n)
1571 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1574 struct EncryptedMessage *em; /* encrypted message */
1575 struct EncryptedMessage *ph; /* plaintext header */
1576 struct MessageEntry *me;
1577 unsigned int priority;
1578 struct GNUNET_TIME_Absolute deadline;
1579 struct GNUNET_TIME_Relative retry_time;
1581 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1583 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1584 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1588 case PEER_STATE_DOWN:
1591 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1592 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1593 GNUNET_i2s(&n->peer));
1596 case PEER_STATE_KEY_SENT:
1597 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1598 n->retry_set_key_task
1599 = GNUNET_SCHEDULER_add_delayed (sched,
1600 n->set_key_retry_frequency,
1601 &set_key_retry_task, n);
1603 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1604 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1605 GNUNET_i2s(&n->peer));
1608 case PEER_STATE_KEY_RECEIVED:
1609 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1610 n->retry_set_key_task
1611 = GNUNET_SCHEDULER_add_delayed (sched,
1612 n->set_key_retry_frequency,
1613 &set_key_retry_task, n);
1615 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1616 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1617 GNUNET_i2s(&n->peer));
1620 case PEER_STATE_KEY_CONFIRMED:
1621 /* ready to continue */
1624 discard_expired_messages (n);
1625 if (n->messages == NULL)
1628 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1629 "Plaintext message queue for `%4s' is empty.\n",
1630 GNUNET_i2s(&n->peer));
1632 return; /* no pending messages */
1634 if (n->encrypted_head != NULL)
1637 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1638 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1639 GNUNET_i2s(&n->peer));
1641 return; /* wait for messages already encrypted to be
1644 ph = (struct EncryptedMessage *) pbuf;
1645 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1647 used = sizeof (struct EncryptedMessage);
1648 used += batch_message (n,
1650 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1651 &deadline, &retry_time, &priority);
1652 if (used == sizeof (struct EncryptedMessage))
1655 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1656 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1657 GNUNET_i2s(&n->peer));
1659 /* no messages selected for sending, try again later... */
1660 n->retry_plaintext_task =
1661 GNUNET_SCHEDULER_add_delayed (sched,
1663 &retry_plaintext_processing, n);
1666 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1667 ph->inbound_bpm_limit = htonl (n->bpm_in);
1668 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1670 /* setup encryption message header */
1671 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1672 me->deadline = deadline;
1673 me->priority = priority;
1675 em = (struct EncryptedMessage *) &me[1];
1676 em->header.size = htons (used);
1677 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1678 em->reserved = htonl (0);
1679 esize = used - ENCRYPTED_HEADER_SIZE;
1680 GNUNET_CRYPTO_hash (&ph->sequence_number, esize, &em->plaintext_hash);
1683 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1684 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
1686 GNUNET_i2s(&n->peer),
1687 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
1689 GNUNET_assert (GNUNET_OK ==
1691 &em->plaintext_hash,
1692 &ph->sequence_number,
1693 &em->sequence_number, esize));
1694 /* append to transmission list */
1695 if (n->encrypted_tail == NULL)
1696 n->encrypted_head = me;
1698 n->encrypted_tail->next = me;
1699 n->encrypted_tail = me;
1700 process_encrypted_neighbour_queue (n);
1705 * Handle CORE_SEND request.
1708 * @param client the client issuing the request
1709 * @param message the "struct SendMessage"
1712 handle_client_send (void *cls,
1713 struct GNUNET_SERVER_Client *client,
1714 const struct GNUNET_MessageHeader *message);
1718 * Function called to notify us that we either succeeded
1719 * or failed to connect (at the transport level) to another
1720 * peer. We should either free the message we were asked
1721 * to transmit or re-try adding it to the queue.
1723 * @param cls closure
1724 * @param size number of bytes available in buf
1725 * @param buf where the callee should write the message
1726 * @return number of bytes written to buf
1729 send_connect_continuation (void *cls, size_t size, void *buf)
1731 struct SendMessage *sm = cls;
1736 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1737 "Asked to send message to disconnected peer `%4s' and connection failed. Discarding message.\n",
1738 GNUNET_i2s (&sm->peer));
1744 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1745 "Connection to peer `%4s' succeeded, retrying original transmission request\n",
1746 GNUNET_i2s (&sm->peer));
1748 handle_client_send (NULL, NULL, &sm->header);
1755 * Handle CORE_SEND request.
1758 * @param client the client issuing the request
1759 * @param message the "struct SendMessage"
1762 handle_client_send (void *cls,
1763 struct GNUNET_SERVER_Client *client,
1764 const struct GNUNET_MessageHeader *message)
1766 const struct SendMessage *sm;
1767 struct SendMessage *smc;
1768 const struct GNUNET_MessageHeader *mh;
1769 struct Neighbour *n;
1770 struct MessageEntry *prev;
1771 struct MessageEntry *pos;
1772 struct MessageEntry *e;
1773 struct MessageEntry *min_prio_entry;
1774 struct MessageEntry *min_prio_prev;
1775 unsigned int min_prio;
1776 unsigned int queue_size;
1779 msize = ntohs (message->size);
1781 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
1785 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1788 sm = (const struct SendMessage *) message;
1789 msize -= sizeof (struct SendMessage);
1790 mh = (const struct GNUNET_MessageHeader *) &sm[1];
1791 if (msize != ntohs (mh->size))
1795 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1798 n = find_neighbour (&sm->peer);
1802 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1803 "Core received `%s' request for `%4s', will try to establish connection within %llu ms\n",
1805 GNUNET_i2s (&sm->peer),
1806 GNUNET_TIME_absolute_get_remaining
1807 (GNUNET_TIME_absolute_ntoh(sm->deadline)).value);
1809 msize += sizeof (struct SendMessage);
1810 /* ask transport to connect to the peer */
1811 smc = GNUNET_malloc (msize);
1812 memcpy (smc, sm, msize);
1814 GNUNET_TRANSPORT_notify_transmit_ready (transport,
1817 GNUNET_TIME_absolute_get_remaining
1818 (GNUNET_TIME_absolute_ntoh
1820 &send_connect_continuation,
1823 /* transport has already a request pending for this peer! */
1825 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1826 "Dropped second message destined for `%4s' since connection is still down.\n",
1827 GNUNET_i2s(&sm->peer));
1832 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1836 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1837 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
1840 GNUNET_i2s (&sm->peer));
1842 /* bound queue size */
1843 discard_expired_messages (n);
1844 min_prio = (unsigned int) -1;
1845 min_prio_entry = NULL;
1846 min_prio_prev = NULL;
1852 if (pos->priority < min_prio)
1854 min_prio_entry = pos;
1855 min_prio_prev = prev;
1856 min_prio = pos->priority;
1862 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1865 if (ntohl(sm->priority) <= min_prio)
1867 /* discard new entry */
1869 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1870 "Queue full, discarding new request\n");
1873 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1876 /* discard "min_prio_entry" */
1878 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1879 "Queue full, discarding existing older request\n");
1881 if (min_prio_prev == NULL)
1882 n->messages = min_prio_entry->next;
1884 min_prio_prev->next = min_prio_entry->next;
1885 GNUNET_free (min_prio_entry);
1889 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1890 "Adding transmission request for `%4s' to queue\n",
1891 GNUNET_i2s (&sm->peer));
1893 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
1894 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
1895 e->priority = ntohl (sm->priority);
1897 memcpy (&e[1], mh, msize);
1899 /* insert, keep list sorted by deadline */
1902 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
1913 /* consider scheduling now */
1914 process_plaintext_neighbour_queue (n);
1916 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1921 * Handle CORE_REQUEST_CONNECT request.
1924 * @param client the client issuing the request
1925 * @param message the "struct ConnectMessage"
1928 handle_client_request_connect (void *cls,
1929 struct GNUNET_SERVER_Client *client,
1930 const struct GNUNET_MessageHeader *message)
1932 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
1933 struct Neighbour *n;
1935 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1936 n = find_neighbour (&cm->peer);
1938 return; /* already connected, or at least trying */
1940 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1941 "Core received `%s' request for `%4s', will try to establish connection\n",
1943 GNUNET_i2s (&cm->peer));
1945 /* ask transport to connect to the peer */
1946 /* FIXME: timeout zero OK? need for cancellation? */
1947 GNUNET_TRANSPORT_notify_transmit_ready (transport,
1950 GNUNET_TIME_UNIT_ZERO,
1957 * List of handlers for the messages understood by this
1960 static struct GNUNET_SERVER_MessageHandler handlers[] = {
1961 {&handle_client_init, NULL,
1962 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
1963 {&handle_client_request_info, NULL,
1964 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
1965 sizeof (struct RequestInfoMessage)},
1966 {&handle_client_send, NULL,
1967 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
1968 {&handle_client_request_connect, NULL,
1969 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
1970 sizeof (struct ConnectMessage)},
1976 * PEERINFO is giving us a HELLO for a peer. Add the public key to
1977 * the neighbour's struct and retry send_key. Or, if we did not get a
1978 * HELLO, just do nothing.
1981 * @param peer the peer for which this is the HELLO
1982 * @param hello HELLO message of that peer
1983 * @param trust amount of trust we currently have in that peer
1986 process_hello_retry_send_key (void *cls,
1987 const struct GNUNET_PeerIdentity *peer,
1988 const struct GNUNET_HELLO_Message *hello,
1991 struct Neighbour *n = cls;
1996 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1997 "Entered `process_hello_retry_send_key' and `peer' is NULL!\n");
2000 if (n->public_key != NULL)
2006 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2007 n->retry_set_key_task
2008 = GNUNET_SCHEDULER_add_delayed (sched,
2009 n->set_key_retry_frequency,
2010 &set_key_retry_task, n);
2016 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2017 "Entered `process_hello_retry_send_key' for peer `%4s'\n",
2020 if (n->public_key != NULL)
2023 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2024 "already have public key for peer %s!! (so why are we here?)\n",
2031 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2032 "Received new `%s' message for `%4s', initiating key exchange.\n",
2037 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2038 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2040 GNUNET_free (n->public_key);
2041 n->public_key = NULL;
2043 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2044 "GNUNET_HELLO_get_key returned awfully\n");
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;
2064 if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2068 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2069 "Key exchange in progress with `%4s'.\n",
2070 GNUNET_i2s (&n->peer));
2072 return; /* already in progress */
2076 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2077 "Asked to perform key exchange with `%4s'.\n",
2078 GNUNET_i2s (&n->peer));
2080 if (n->public_key == NULL)
2082 /* lookup n's public key, then try again */
2084 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2085 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2086 GNUNET_i2s (&n->peer));
2088 GNUNET_assert (n->pitr == NULL);
2090 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2094 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2095 &process_hello_retry_send_key, n);
2098 /* first, set key message */
2099 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2100 sizeof (struct SetKeyMessage));
2101 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2102 me->priority = SET_KEY_PRIORITY;
2103 me->size = sizeof (struct SetKeyMessage);
2104 if (n->encrypted_head == NULL)
2105 n->encrypted_head = me;
2107 n->encrypted_tail->next = me;
2108 n->encrypted_tail = me;
2109 sm = (struct SetKeyMessage *) &me[1];
2110 sm->header.size = htons (sizeof (struct SetKeyMessage));
2111 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2112 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2113 PEER_STATE_KEY_SENT : n->status));
2115 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2116 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2117 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2118 sizeof (struct GNUNET_PeerIdentity));
2119 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2120 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2121 sm->target = n->peer;
2122 GNUNET_assert (GNUNET_OK ==
2123 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2125 GNUNET_CRYPTO_AesSessionKey),
2127 &sm->encrypted_key));
2128 GNUNET_assert (GNUNET_OK ==
2129 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2132 /* second, encrypted PING message */
2133 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2134 sizeof (struct PingMessage));
2135 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2136 me->priority = PING_PRIORITY;
2137 me->size = sizeof (struct PingMessage);
2138 n->encrypted_tail->next = me;
2139 n->encrypted_tail = me;
2140 pm = (struct PingMessage *) &me[1];
2141 pm->header.size = htons (sizeof (struct PingMessage));
2142 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2143 pp.challenge = htonl (n->ping_challenge);
2144 pp.target = n->peer;
2146 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2147 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2148 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2149 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2150 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2152 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2155 &n->peer.hashPubKey,
2158 sizeof (struct PingMessage) -
2159 sizeof (struct GNUNET_MessageHeader));
2163 case PEER_STATE_DOWN:
2164 n->status = PEER_STATE_KEY_SENT;
2166 case PEER_STATE_KEY_SENT:
2168 case PEER_STATE_KEY_RECEIVED:
2170 case PEER_STATE_KEY_CONFIRMED:
2177 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2178 "Have %llu ms left for `%s' transmission.\n",
2179 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2182 /* trigger queue processing */
2183 process_encrypted_neighbour_queue (n);
2184 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2185 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2186 n->retry_set_key_task
2187 = GNUNET_SCHEDULER_add_delayed (sched,
2188 n->set_key_retry_frequency,
2189 &set_key_retry_task, n);
2194 * We received a SET_KEY message. Validate and update
2195 * our key material and status.
2197 * @param n the neighbour from which we received message m
2198 * @param m the set key message we received
2201 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2205 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2206 * the neighbour's struct and retry handling the set_key message. Or,
2207 * if we did not get a HELLO, just free the set key message.
2209 * @param cls pointer to the set key message
2210 * @param peer the peer for which this is the HELLO
2211 * @param hello HELLO message of that peer
2212 * @param trust amount of trust we currently have in that peer
2215 process_hello_retry_handle_set_key (void *cls,
2216 const struct GNUNET_PeerIdentity *peer,
2217 const struct GNUNET_HELLO_Message *hello,
2220 struct Neighbour *n = cls;
2221 struct SetKeyMessage *sm = n->skm;
2230 if (n->public_key != NULL)
2231 return; /* multiple HELLOs match!? */
2233 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2234 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2236 GNUNET_break_op (0);
2237 GNUNET_free (n->public_key);
2238 n->public_key = NULL;
2242 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2243 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2244 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2246 handle_set_key (n, sm);
2251 * We received a PING message. Validate and transmit
2254 * @param n sender of the PING
2255 * @param m the encrypted PING message itself
2258 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2260 struct PingMessage t;
2261 struct PingMessage *tp;
2262 struct MessageEntry *me;
2265 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2266 "Core service receives `%s' request from `%4s'.\n",
2267 "PING", GNUNET_i2s (&n->peer));
2271 &my_identity.hashPubKey,
2274 sizeof (struct PingMessage) -
2275 sizeof (struct GNUNET_MessageHeader)))
2278 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2279 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2281 GNUNET_i2s (&t.target),
2282 ntohl (t.challenge), n->decrypt_key.crc32);
2283 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2284 "Target of `%s' request is `%4s'.\n",
2285 "PING", GNUNET_i2s (&t.target));
2287 if (0 != memcmp (&t.target,
2288 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2290 GNUNET_break_op (0);
2293 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2294 sizeof (struct PingMessage));
2295 if (n->encrypted_tail != NULL)
2296 n->encrypted_tail->next = me;
2299 n->encrypted_tail = me;
2300 n->encrypted_head = me;
2302 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2303 me->priority = PONG_PRIORITY;
2304 me->size = sizeof (struct PingMessage);
2305 tp = (struct PingMessage *) &me[1];
2306 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2307 tp->header.size = htons (sizeof (struct PingMessage));
2309 &my_identity.hashPubKey,
2312 sizeof (struct PingMessage) -
2313 sizeof (struct GNUNET_MessageHeader));
2315 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2316 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2317 ntohl (t.challenge), n->encrypt_key.crc32);
2319 /* trigger queue processing */
2320 process_encrypted_neighbour_queue (n);
2325 * We received a PONG message. Validate and update our status.
2327 * @param n sender of the PONG
2328 * @param m the encrypted PONG message itself
2331 handle_pong (struct Neighbour *n, const struct PingMessage *m)
2333 struct PingMessage t;
2334 struct ConnectNotifyMessage cnm;
2337 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2338 "Core service receives `%s' request from `%4s'.\n",
2339 "PONG", GNUNET_i2s (&n->peer));
2343 &n->peer.hashPubKey,
2346 sizeof (struct PingMessage) -
2347 sizeof (struct GNUNET_MessageHeader)))
2350 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2351 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2353 GNUNET_i2s (&t.target),
2354 ntohl (t.challenge), n->decrypt_key.crc32);
2356 if ((0 != memcmp (&t.target,
2358 sizeof (struct GNUNET_PeerIdentity))) ||
2359 (n->ping_challenge != ntohl (t.challenge)))
2361 /* PONG malformed */
2363 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2364 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2365 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2366 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2367 "Received malformed `%s' received from `%4s' with challenge %u\n",
2368 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2370 GNUNET_break_op (0);
2375 case PEER_STATE_DOWN:
2376 GNUNET_break (0); /* should be impossible */
2378 case PEER_STATE_KEY_SENT:
2379 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2381 case PEER_STATE_KEY_RECEIVED:
2382 n->status = PEER_STATE_KEY_CONFIRMED;
2384 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2385 "Confirmed key via `%s' message for peer `%4s'\n",
2386 "PONG", GNUNET_i2s (&n->peer));
2388 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2390 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2391 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2393 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2394 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2395 cnm.distance = htonl (n->last_distance);
2396 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2398 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2399 process_encrypted_neighbour_queue (n);
2401 case PEER_STATE_KEY_CONFIRMED:
2402 /* duplicate PONG? */
2412 * We received a SET_KEY message. Validate and update
2413 * our key material and status.
2415 * @param n the neighbour from which we received message m
2416 * @param m the set key message we received
2419 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2421 struct SetKeyMessage *m_cpy;
2422 struct GNUNET_TIME_Absolute t;
2423 struct GNUNET_CRYPTO_AesSessionKey k;
2424 struct PingMessage *ping;
2425 struct PingMessage *pong;
2426 enum PeerStateMachine sender_status;
2429 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2430 "Core service receives `%s' request from `%4s'.\n",
2431 "SET_KEY", GNUNET_i2s (&n->peer));
2433 if (n->public_key == NULL)
2435 if (n->pitr != NULL)
2438 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2439 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2445 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2446 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2448 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2449 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2450 /* lookup n's public key, then try again */
2451 GNUNET_assert (n->skm == NULL);
2453 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2457 GNUNET_TIME_UNIT_MINUTES,
2458 &process_hello_retry_handle_set_key, n);
2461 if (0 != memcmp (&m->target,
2463 sizeof (struct GNUNET_PeerIdentity)))
2465 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2466 _("Received `%s' message that was not for me. Ignoring.\n"),
2470 if ((ntohl (m->purpose.size) !=
2471 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2472 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2473 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2474 sizeof (struct GNUNET_PeerIdentity)) ||
2476 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2477 &m->purpose, &m->signature, n->public_key)))
2479 /* invalid signature */
2480 GNUNET_break_op (0);
2483 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2484 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2485 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2486 (t.value < n->decrypt_key_created.value))
2488 /* this could rarely happen due to massive re-ordering of
2489 messages on the network level, but is most likely either
2490 a bug or some adversary messing with us. Report. */
2491 GNUNET_break_op (0);
2495 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
2497 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2500 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2501 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2502 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2504 /* failed to decrypt !? */
2505 GNUNET_break_op (0);
2510 if (n->decrypt_key_created.value != t.value)
2512 /* fresh key, reset sequence numbers */
2513 n->last_sequence_number_received = 0;
2514 n->last_packets_bitmap = 0;
2515 n->decrypt_key_created = t;
2517 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2520 case PEER_STATE_DOWN:
2521 n->status = PEER_STATE_KEY_RECEIVED;
2523 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2524 "Responding to `%s' with my own key.\n", "SET_KEY");
2528 case PEER_STATE_KEY_SENT:
2529 case PEER_STATE_KEY_RECEIVED:
2530 n->status = PEER_STATE_KEY_RECEIVED;
2531 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2532 (sender_status != PEER_STATE_KEY_CONFIRMED))
2535 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2536 "Responding to `%s' with my own key (other peer has status %u).\n",
2537 "SET_KEY", sender_status);
2542 case PEER_STATE_KEY_CONFIRMED:
2543 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2544 (sender_status != PEER_STATE_KEY_CONFIRMED))
2547 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2548 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2549 "SET_KEY", sender_status);
2558 if (n->pending_ping != NULL)
2560 ping = n->pending_ping;
2561 n->pending_ping = NULL;
2562 handle_ping (n, ping);
2565 if (n->pending_pong != NULL)
2567 pong = n->pending_pong;
2568 n->pending_pong = NULL;
2569 handle_pong (n, pong);
2576 * Send a P2P message to a client.
2578 * @param sender who sent us the message?
2579 * @param client who should we give the message to?
2580 * @param m contains the message to transmit
2581 * @param msize number of bytes in buf to transmit
2584 send_p2p_message_to_client (struct Neighbour *sender,
2585 struct Client *client,
2586 const void *m, size_t msize)
2588 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2589 struct NotifyTrafficMessage *ntm;
2592 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2593 "Core service passes message from `%4s' of type %u to client.\n",
2594 GNUNET_i2s(&sender->peer),
2595 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2597 ntm = (struct NotifyTrafficMessage *) buf;
2598 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2599 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2600 ntm->distance = htonl (sender->last_distance);
2601 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
2602 ntm->peer = sender->peer;
2603 memcpy (&ntm[1], m, msize);
2604 send_to_client (client, &ntm->header, GNUNET_YES);
2609 * Deliver P2P message to interested clients.
2611 * @param sender who sent us the message?
2612 * @param m the message
2613 * @param msize size of the message (including header)
2616 deliver_message (struct Neighbour *sender,
2617 const struct GNUNET_MessageHeader *m, size_t msize)
2619 struct Client *cpos;
2624 type = ntohs (m->type);
2627 "Received encapsulated message of type %u from `%4s'\n",
2629 GNUNET_i2s (&sender->peer));
2632 while (cpos != NULL)
2634 deliver_full = GNUNET_NO;
2635 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
2636 deliver_full = GNUNET_YES;
2639 for (tpos = 0; tpos < cpos->tcnt; tpos++)
2641 if (type != cpos->types[tpos])
2643 deliver_full = GNUNET_YES;
2647 if (GNUNET_YES == deliver_full)
2648 send_p2p_message_to_client (sender, cpos, m, msize);
2649 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2650 send_p2p_message_to_client (sender, cpos, m,
2651 sizeof (struct GNUNET_MessageHeader));
2658 * Align P2P message and then deliver to interested clients.
2660 * @param sender who sent us the message?
2661 * @param buffer unaligned (!) buffer containing message
2662 * @param msize size of the message (including header)
2665 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
2669 /* TODO: call to statistics? */
2670 memcpy (abuf, buffer, msize);
2671 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
2676 * Deliver P2P messages to interested clients.
2678 * @param sender who sent us the message?
2679 * @param buffer buffer containing messages, can be modified
2680 * @param buffer_size size of the buffer (overall)
2681 * @param offset offset where messages in the buffer start
2684 deliver_messages (struct Neighbour *sender,
2685 const char *buffer, size_t buffer_size, size_t offset)
2687 struct GNUNET_MessageHeader *mhp;
2688 struct GNUNET_MessageHeader mh;
2692 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
2694 if (0 != offset % sizeof (uint16_t))
2696 /* outch, need to copy to access header */
2697 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
2702 /* can access header directly */
2703 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
2705 msize = ntohs (mhp->size);
2706 if (msize + offset > buffer_size)
2708 /* malformed message, header says it is larger than what
2709 would fit into the overall buffer */
2710 GNUNET_break_op (0);
2713 #if HAVE_UNALIGNED_64_ACCESS
2714 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
2716 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
2718 if (GNUNET_YES == need_align)
2719 align_and_deliver (sender, &buffer[offset], msize);
2721 deliver_message (sender,
2722 (const struct GNUNET_MessageHeader *)
2723 &buffer[offset], msize);
2730 * We received an encrypted message. Decrypt, validate and
2731 * pass on to the appropriate clients.
2734 handle_encrypted_message (struct Neighbour *n,
2735 const struct EncryptedMessage *m)
2737 size_t size = ntohs (m->header.size);
2739 struct EncryptedMessage *pt; /* plaintext */
2743 struct GNUNET_TIME_Absolute t;
2746 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2747 "Core service receives `%s' request from `%4s'.\n",
2748 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
2754 &m->sequence_number,
2755 &buf[ENCRYPTED_HEADER_SIZE], size - ENCRYPTED_HEADER_SIZE))
2757 pt = (struct EncryptedMessage *) buf;
2760 GNUNET_CRYPTO_hash (&pt->sequence_number,
2761 size - ENCRYPTED_HEADER_SIZE, &ph);
2762 if (0 != memcmp (&ph, &m->plaintext_hash, sizeof (GNUNET_HashCode)))
2764 /* checksum failed */
2765 GNUNET_break_op (0);
2769 /* validate sequence number */
2770 snum = ntohl (pt->sequence_number);
2771 if (n->last_sequence_number_received == snum)
2773 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2774 "Received duplicate message, ignoring.\n");
2775 /* duplicate, ignore */
2778 if ((n->last_sequence_number_received > snum) &&
2779 (n->last_sequence_number_received - snum > 32))
2781 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2782 "Received ancient out of sequence message, ignoring.\n");
2783 /* ancient out of sequence, ignore */
2786 if (n->last_sequence_number_received > snum)
2788 unsigned int rotbit =
2789 1 << (n->last_sequence_number_received - snum - 1);
2790 if ((n->last_packets_bitmap & rotbit) != 0)
2792 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2793 "Received duplicate message, ignoring.\n");
2794 /* duplicate, ignore */
2797 n->last_packets_bitmap |= rotbit;
2799 if (n->last_sequence_number_received < snum)
2801 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
2802 n->last_sequence_number_received = snum;
2805 /* check timestamp */
2806 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
2807 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
2809 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2811 ("Message received far too old (%llu ms). Content ignored.\n"),
2812 GNUNET_TIME_absolute_get_duration (t).value);
2816 /* process decrypted message(s) */
2817 update_window (GNUNET_YES,
2818 &n->available_send_window,
2819 &n->last_asw_update,
2821 n->bpm_out_external_limit = ntohl (pt->inbound_bpm_limit);
2822 n->bpm_out = GNUNET_MAX (n->bpm_out_external_limit,
2823 n->bpm_out_internal_limit);
2824 n->last_activity = GNUNET_TIME_absolute_get ();
2825 off = sizeof (struct EncryptedMessage);
2826 deliver_messages (n, buf, size, off);
2831 * Function called by the transport for each received message.
2833 * @param cls closure
2834 * @param peer (claimed) identity of the other peer
2835 * @param message the message
2836 * @param latency estimated latency for communicating with the
2837 * given peer (round-trip)
2838 * @param distance in overlay hops, as given by transport plugin
2841 handle_transport_receive (void *cls,
2842 const struct GNUNET_PeerIdentity *peer,
2843 const struct GNUNET_MessageHeader *message,
2844 struct GNUNET_TIME_Relative latency,
2845 unsigned int distance)
2847 struct Neighbour *n;
2848 struct GNUNET_TIME_Absolute now;
2854 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2855 "Received message of type %u from `%4s', demultiplexing.\n",
2856 ntohs (message->type), GNUNET_i2s (peer));
2858 n = find_neighbour (peer);
2864 n->last_latency = latency;
2865 n->last_distance = distance;
2866 up = (n->status == PEER_STATE_KEY_CONFIRMED);
2867 type = ntohs (message->type);
2868 size = ntohs (message->size);
2871 "Received message of type %u from `%4s'\n",
2877 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
2878 if (size != sizeof (struct SetKeyMessage))
2880 GNUNET_break_op (0);
2883 handle_set_key (n, (const struct SetKeyMessage *) message);
2885 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
2886 if (size < sizeof (struct EncryptedMessage) +
2887 sizeof (struct GNUNET_MessageHeader))
2889 GNUNET_break_op (0);
2892 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2893 (n->status != PEER_STATE_KEY_CONFIRMED))
2895 GNUNET_break_op (0);
2898 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
2900 case GNUNET_MESSAGE_TYPE_CORE_PING:
2901 if (size != sizeof (struct PingMessage))
2903 GNUNET_break_op (0);
2906 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2907 (n->status != PEER_STATE_KEY_CONFIRMED))
2910 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2911 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
2912 "PING", GNUNET_i2s (&n->peer));
2914 GNUNET_free_non_null (n->pending_ping);
2915 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
2916 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
2919 handle_ping (n, (const struct PingMessage *) message);
2921 case GNUNET_MESSAGE_TYPE_CORE_PONG:
2922 if (size != sizeof (struct PingMessage))
2924 GNUNET_break_op (0);
2927 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
2928 (n->status != PEER_STATE_KEY_CONFIRMED) )
2931 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2932 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
2933 "PONG", GNUNET_i2s (&n->peer));
2935 GNUNET_free_non_null (n->pending_pong);
2936 n->pending_pong = GNUNET_malloc (sizeof (struct PingMessage));
2937 memcpy (n->pending_pong, message, sizeof (struct PingMessage));
2940 handle_pong (n, (const struct PingMessage *) message);
2943 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2944 _("Unsupported message of type %u received.\n"), type);
2947 if (n->status == PEER_STATE_KEY_CONFIRMED)
2949 now = GNUNET_TIME_absolute_get ();
2950 n->last_activity = now;
2952 n->time_established = now;
2958 * Function that recalculates the bandwidth quota for the
2959 * given neighbour and transmits it to the transport service.
2961 * @param cls neighbour for the quota update
2965 neighbour_quota_update (void *cls,
2966 const struct GNUNET_SCHEDULER_TaskContext *tc);
2970 * Schedule the task that will recalculate the bandwidth
2971 * quota for this peer (and possibly force a disconnect of
2972 * idle peers by calculating a bandwidth of zero).
2975 schedule_quota_update (struct Neighbour *n)
2977 GNUNET_assert (n->quota_update_task ==
2978 GNUNET_SCHEDULER_NO_TASK);
2979 n->quota_update_task
2980 = GNUNET_SCHEDULER_add_delayed (sched,
2981 QUOTA_UPDATE_FREQUENCY,
2982 &neighbour_quota_update,
2988 * Function that recalculates the bandwidth quota for the
2989 * given neighbour and transmits it to the transport service.
2991 * @param cls neighbour for the quota update
2995 neighbour_quota_update (void *cls,
2996 const struct GNUNET_SCHEDULER_TaskContext *tc)
2998 struct Neighbour *n = cls;
3002 unsigned long long distributable;
3004 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3005 /* calculate relative preference among all neighbours;
3006 divides by a bit more to avoid division by zero AND to
3007 account for possibility of new neighbours joining any time
3008 AND to convert to double... */
3009 pref_rel = n->current_preference / (1.0 + preference_sum);
3011 if (bandwidth_target_out > neighbour_count * MIN_BPM_PER_PEER)
3012 distributable = bandwidth_target_out - neighbour_count * MIN_BPM_PER_PEER;
3013 share = distributable * pref_rel;
3014 q_in = MIN_BPM_PER_PEER + (unsigned long long) share;
3015 /* check if we want to disconnect for good due to inactivity */
3016 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3017 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3020 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3021 "Forcing disconnect of `%4s' due to inactivity (?).\n",
3022 GNUNET_i2s (&n->peer));
3024 q_in = 0; /* force disconnect */
3026 if ( (n->bpm_in + MIN_BPM_CHANGE < q_in) ||
3027 (n->bpm_in - MIN_BPM_CHANGE > q_in) )
3030 GNUNET_TRANSPORT_set_quota (transport,
3034 GNUNET_TIME_UNIT_FOREVER_REL,
3037 schedule_quota_update (n);
3042 * Function called by transport to notify us that
3043 * a peer connected to us (on the network level).
3045 * @param cls closure
3046 * @param peer the peer that connected
3047 * @param latency current latency of the connection
3048 * @param distance in overlay hops, as given by transport plugin
3051 handle_transport_notify_connect (void *cls,
3052 const struct GNUNET_PeerIdentity *peer,
3053 struct GNUNET_TIME_Relative latency,
3054 unsigned int distance)
3056 struct Neighbour *n;
3057 struct GNUNET_TIME_Absolute now;
3058 struct ConnectNotifyMessage cnm;
3060 n = find_neighbour (peer);
3063 /* duplicate connect notification!? */
3067 now = GNUNET_TIME_absolute_get ();
3068 n = GNUNET_malloc (sizeof (struct Neighbour));
3069 n->next = neighbours;
3073 n->last_latency = latency;
3074 n->last_distance = distance;
3075 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
3076 n->encrypt_key_created = now;
3077 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
3078 n->last_activity = now;
3079 n->last_asw_update = now;
3080 n->last_arw_update = now;
3081 n->bpm_in = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
3082 n->bpm_out = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
3083 n->bpm_out_internal_limit = (uint32_t) - 1;
3084 n->bpm_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
3085 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3088 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3089 "Received connection from `%4s'.\n",
3090 GNUNET_i2s (&n->peer));
3092 schedule_quota_update (n);
3093 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3094 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3095 cnm.distance = htonl (n->last_distance);
3096 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3098 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3104 * Free the given entry for the neighbour (it has
3105 * already been removed from the list at this point).
3107 * @param n neighbour to free
3110 free_neighbour (struct Neighbour *n)
3112 struct MessageEntry *m;
3114 if (n->pitr != NULL)
3116 GNUNET_PEERINFO_iterate_cancel (n->pitr);
3121 GNUNET_free (n->skm);
3124 while (NULL != (m = n->messages))
3126 n->messages = m->next;
3129 while (NULL != (m = n->encrypted_head))
3131 n->encrypted_head = m->next;
3135 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
3136 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
3137 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
3138 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3139 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
3140 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
3141 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
3142 GNUNET_free_non_null (n->public_key);
3143 GNUNET_free_non_null (n->pending_ping);
3144 GNUNET_free_non_null (n->pending_pong);
3150 * Function called by transport telling us that a peer
3153 * @param cls closure
3154 * @param peer the peer that disconnected
3157 handle_transport_notify_disconnect (void *cls,
3158 const struct GNUNET_PeerIdentity *peer)
3160 struct DisconnectNotifyMessage cnm;
3161 struct Neighbour *n;
3162 struct Neighbour *p;
3165 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3166 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3170 while ((n != NULL) &&
3171 (0 != memcmp (&n->peer, peer, sizeof (struct GNUNET_PeerIdentity))))
3182 neighbours = n->next;
3185 GNUNET_assert (neighbour_count > 0);
3187 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3188 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3190 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3196 * Last task run during shutdown. Disconnects us from
3200 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3202 struct Neighbour *n;
3206 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3207 "Core service shutting down.\n");
3209 GNUNET_assert (transport != NULL);
3210 GNUNET_TRANSPORT_disconnect (transport);
3212 while (NULL != (n = neighbours))
3214 neighbours = n->next;
3215 GNUNET_assert (neighbour_count > 0);
3219 GNUNET_SERVER_notification_context_destroy (notifier);
3221 while (NULL != (c = clients))
3222 handle_client_disconnect (NULL, c->client_handle);
3223 if (my_private_key != NULL)
3224 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3229 * Initiate core service.
3231 * @param cls closure
3232 * @param s scheduler to use
3233 * @param serv the initialized server
3234 * @param c configuration to use
3238 struct GNUNET_SCHEDULER_Handle *s,
3239 struct GNUNET_SERVER_Handle *serv,
3240 const struct GNUNET_CONFIGURATION_Handle *c)
3243 unsigned long long qin;
3244 unsigned long long qout;
3245 unsigned long long tneigh;
3251 /* parse configuration */
3254 GNUNET_CONFIGURATION_get_value_number (c,
3257 &bandwidth_target_in)) ||
3259 GNUNET_CONFIGURATION_get_value_number (c,
3262 &bandwidth_target_out)) ||
3264 GNUNET_CONFIGURATION_get_value_filename (c,
3266 "HOSTKEY", &keyfile)))
3268 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3270 ("Core service is lacking key configuration settings. Exiting.\n"));
3271 GNUNET_SCHEDULER_shutdown (s);
3274 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3275 GNUNET_free (keyfile);
3276 if (my_private_key == NULL)
3278 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3279 _("Core service could not access hostkey. Exiting.\n"));
3280 GNUNET_SCHEDULER_shutdown (s);
3283 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3284 GNUNET_CRYPTO_hash (&my_public_key,
3285 sizeof (my_public_key), &my_identity.hashPubKey);
3286 /* setup notification */
3288 notifier = GNUNET_SERVER_notification_context_create (server,
3290 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3291 /* setup transport connection */
3292 transport = GNUNET_TRANSPORT_connect (sched,
3295 &handle_transport_receive,
3296 &handle_transport_notify_connect,
3297 &handle_transport_notify_disconnect);
3298 GNUNET_assert (NULL != transport);
3299 GNUNET_SCHEDULER_add_delayed (sched,
3300 GNUNET_TIME_UNIT_FOREVER_REL,
3301 &cleaning_task, NULL);
3302 /* process client requests */
3303 GNUNET_SERVER_add_handlers (server, handlers);
3304 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3305 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3311 * The main function for the transport service.
3313 * @param argc number of arguments from the command line
3314 * @param argv command line arguments
3315 * @return 0 ok, 1 on error
3318 main (int argc, char *const *argv)
3320 return (GNUNET_OK ==
3321 GNUNET_SERVICE_run (argc,
3324 GNUNET_SERVICE_OPTION_NONE,
3325 &run, NULL)) ? 0 : 1;
3328 /* end of gnunet-service-core.c */