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 * ID of task used for cleaning up dead neighbour entries.
432 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
435 * At what time did we generate our encryption key?
437 struct GNUNET_TIME_Absolute encrypt_key_created;
440 * At what time did the other peer generate the decryption key?
442 struct GNUNET_TIME_Absolute decrypt_key_created;
445 * At what time did we initially establish (as in, complete session
446 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
448 struct GNUNET_TIME_Absolute time_established;
451 * At what time did we last receive an encrypted message from the
452 * other peer? Should be zero if status != KEY_CONFIRMED.
454 struct GNUNET_TIME_Absolute last_activity;
457 * Last latency observed from this peer.
459 struct GNUNET_TIME_Relative last_latency;
462 * At what frequency are we currently re-trying SET_KEY messages?
464 struct GNUNET_TIME_Relative set_key_retry_frequency;
467 * Time of our last update to the "available_send_window".
469 struct GNUNET_TIME_Absolute last_asw_update;
472 * Time of our last update to the "available_recv_window".
474 struct GNUNET_TIME_Absolute last_arw_update;
477 * Number of bytes that we are eligible to transmit to this
478 * peer at this point. Incremented every minute by max_out_bpm,
479 * bounded by max_bpm (no back-log larger than MAX_BUF_FACT minutes,
480 * bandwidth-hogs are sampled at a frequency of about 78s!);
481 * may get negative if we have VERY high priority content.
483 long long available_send_window;
486 * How much downstream capacity of this peer has been reserved for
487 * our traffic? (Our clients can request that a certain amount of
488 * bandwidth is available for replies to them; this value is used to
489 * make sure that this reserved amount of bandwidth is actually
492 long long available_recv_window;
495 * How valueable were the messages of this peer recently?
497 unsigned long long current_preference;
500 * Bit map indicating which of the 32 sequence numbers before the last
501 * were received (good for accepting out-of-order packets and
502 * estimating reliability of the connection)
504 unsigned int last_packets_bitmap;
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;
556 * Are we currently connected to this neighbour?
563 * Data structure for each client connected to the core service.
568 * Clients are kept in a linked list.
573 * Handle for the client with the server API.
575 struct GNUNET_SERVER_Client *client_handle;
578 * Array of the types of messages this peer cares
579 * about (with "tcnt" entries). Allocated as part
580 * of this client struct, do not free!
585 * Options for messages this client cares about,
586 * see GNUNET_CORE_OPTION_ values.
591 * Number of types of incoming messages this client
592 * specifically cares about. Size of the "types" array.
602 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
607 static struct GNUNET_PeerIdentity my_identity;
612 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
617 struct GNUNET_SCHEDULER_Handle *sched;
622 const struct GNUNET_CONFIGURATION_Handle *cfg;
627 static struct GNUNET_SERVER_Handle *server;
632 static struct GNUNET_TRANSPORT_Handle *transport;
635 * Linked list of our clients.
637 static struct Client *clients;
640 * Context for notifications we need to send to our clients.
642 static struct GNUNET_SERVER_NotificationContext *notifier;
645 * We keep neighbours in a linked list (for now).
647 static struct Neighbour *neighbours;
650 * Sum of all preferences among all neighbours.
652 static unsigned long long preference_sum;
655 * Total number of neighbours we have.
657 static unsigned int neighbour_count;
660 * How much inbound bandwidth are we supposed to be using?
662 static unsigned long long bandwidth_target_in;
665 * How much outbound bandwidth are we supposed to be using?
667 static unsigned long long bandwidth_target_out;
672 * A preference value for a neighbour was update. Update
673 * the preference sum accordingly.
675 * @param inc how much was a preference value increased?
678 update_preference_sum (unsigned long long inc)
681 unsigned long long os;
684 preference_sum += inc;
685 if (preference_sum >= os)
687 /* overflow! compensate by cutting all values in half! */
692 n->current_preference /= 2;
693 preference_sum += n->current_preference;
700 * Recalculate the number of bytes we expect to
701 * receive or transmit in a given window.
703 * @param force force an update now (even if not much time has passed)
704 * @param window pointer to the byte counter (updated)
705 * @param ts pointer to the timestamp (updated)
706 * @param bpm number of bytes per minute that should
707 * be added to the window.
710 update_window (int force,
712 struct GNUNET_TIME_Absolute *ts, unsigned int bpm)
714 struct GNUNET_TIME_Relative since;
716 since = GNUNET_TIME_absolute_get_duration (*ts);
717 if ( (force == GNUNET_NO) &&
718 (since.value < 60 * 1000) )
719 return; /* not even a minute has passed */
720 *ts = GNUNET_TIME_absolute_get ();
721 *window += (bpm * since.value) / 60 / 1000;
722 if (*window > MAX_WINDOW_TIME * bpm)
723 *window = MAX_WINDOW_TIME * bpm;
728 * Find the entry for the given neighbour.
730 * @param peer identity of the neighbour
731 * @return NULL if we are not connected, otherwise the
734 static struct Neighbour *
735 find_neighbour (const struct GNUNET_PeerIdentity *peer)
737 struct Neighbour *ret;
740 while ((ret != NULL) &&
741 (0 != memcmp (&ret->peer,
742 peer, sizeof (struct GNUNET_PeerIdentity))))
749 * Send a message to one of our clients.
751 * @param client target for the message
752 * @param msg message to transmit
753 * @param can_drop could this message be dropped if the
754 * client's queue is getting too large?
757 send_to_client (struct Client *client,
758 const struct GNUNET_MessageHeader *msg,
761 #if DEBUG_CORE_CLIENT
762 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
763 "Preparing to send message of type %u to client.\n",
766 GNUNET_SERVER_notification_context_unicast (notifier,
767 client->client_handle,
774 * Send a message to all of our current clients that have
775 * the right options set.
777 * @param msg message to multicast
778 * @param can_drop can this message be discarded if the queue is too long
779 * @param options mask to use
782 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
791 if (0 != (c->options & options))
792 send_to_client (c, msg, can_drop);
799 * Handle CORE_INIT request.
802 handle_client_init (void *cls,
803 struct GNUNET_SERVER_Client *client,
804 const struct GNUNET_MessageHeader *message)
806 const struct InitMessage *im;
807 struct InitReplyMessage irm;
810 const uint16_t *types;
812 struct ConnectNotifyMessage cnm;
814 #if DEBUG_CORE_CLIENT
815 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
816 "Client connecting to core service with `%s' message\n",
819 /* check that we don't have an entry already */
823 if (client == c->client_handle)
826 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
831 msize = ntohs (message->size);
832 if (msize < sizeof (struct InitMessage))
835 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
838 GNUNET_SERVER_notification_context_add (notifier, client);
839 im = (const struct InitMessage *) message;
840 types = (const uint16_t *) &im[1];
841 msize -= sizeof (struct InitMessage);
842 c = GNUNET_malloc (sizeof (struct Client) + msize);
843 c->client_handle = client;
846 memcpy (&c[1], types, msize);
847 c->types = (uint16_t *) & c[1];
848 c->options = ntohl (im->options);
849 c->tcnt = msize / sizeof (uint16_t);
850 /* send init reply message */
851 irm.header.size = htons (sizeof (struct InitReplyMessage));
852 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
853 irm.reserved = htonl (0);
854 memcpy (&irm.publicKey,
856 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
857 #if DEBUG_CORE_CLIENT
858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
859 "Sending `%s' message to client.\n", "INIT_REPLY");
861 send_to_client (c, &irm.header, GNUNET_NO);
862 /* notify new client about existing neighbours */
863 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
864 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
868 if (n->status == PEER_STATE_KEY_CONFIRMED)
870 #if DEBUG_CORE_CLIENT
871 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
872 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
874 cnm.distance = htonl (n->last_distance);
875 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
877 send_to_client (c, &cnm.header, GNUNET_NO);
881 GNUNET_SERVER_receive_done (client, GNUNET_OK);
886 * A client disconnected, clean up.
889 * @param client identification of the client
892 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
899 #if DEBUG_CORE_CLIENT
900 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
901 "Client has disconnected from core service.\n");
907 if (client == pos->client_handle)
912 prev->next = pos->next;
919 /* client never sent INIT */
924 * Handle REQUEST_INFO request.
927 handle_client_request_info (void *cls,
928 struct GNUNET_SERVER_Client *client,
929 const struct GNUNET_MessageHeader *message)
931 const struct RequestInfoMessage *rcm;
933 struct ConfigurationInfoMessage cim;
935 unsigned long long old_preference;
936 struct GNUNET_SERVER_TransmitContext *tc;
938 #if DEBUG_CORE_CLIENT
939 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
940 "Core service receives `%s' request.\n", "REQUEST_INFO");
942 rcm = (const struct RequestInfoMessage *) message;
943 n = find_neighbour (&rcm->peer);
944 memset (&cim, 0, sizeof (cim));
947 update_window (GNUNET_YES,
948 &n->available_send_window,
951 n->bpm_out_internal_limit = ntohl (rcm->limit_outbound_bpm);
952 n->bpm_out = GNUNET_MAX (n->bpm_out_internal_limit,
953 n->bpm_out_external_limit);
954 reserv = ntohl (rcm->reserve_inbound);
957 n->available_recv_window += reserv;
961 update_window (GNUNET_NO,
962 &n->available_recv_window,
963 &n->last_arw_update, n->bpm_in);
964 if (n->available_recv_window < reserv)
965 reserv = n->available_recv_window;
966 n->available_recv_window -= reserv;
968 old_preference = n->current_preference;
969 n->current_preference += GNUNET_ntohll(rcm->preference_change);
970 if (old_preference > n->current_preference)
972 /* overflow; cap at maximum value */
973 n->current_preference = (unsigned long long) -1;
975 update_preference_sum (n->current_preference - old_preference);
976 cim.reserved_amount = htonl (reserv);
977 cim.bpm_in = htonl (n->bpm_in);
978 cim.bpm_out = htonl (n->bpm_out);
979 cim.preference = n->current_preference;
981 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
982 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
983 cim.peer = rcm->peer;
985 #if DEBUG_CORE_CLIENT
986 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
987 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
989 tc = GNUNET_SERVER_transmit_context_create (client);
990 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
991 GNUNET_SERVER_transmit_context_run (tc,
992 GNUNET_TIME_UNIT_FOREVER_REL);
997 * Free the given entry for the neighbour (it has
998 * already been removed from the list at this point).
1000 * @param n neighbour to free
1003 free_neighbour (struct Neighbour *n)
1005 struct MessageEntry *m;
1007 if (n->pitr != NULL)
1009 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1014 GNUNET_free (n->skm);
1017 while (NULL != (m = n->messages))
1019 n->messages = m->next;
1022 while (NULL != (m = n->encrypted_head))
1024 n->encrypted_head = m->next;
1029 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1032 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1033 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1034 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1035 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1036 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1037 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1038 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1039 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1040 GNUNET_free_non_null (n->public_key);
1041 GNUNET_free_non_null (n->pending_ping);
1042 GNUNET_free_non_null (n->pending_pong);
1048 * Consider freeing the given neighbour since we may not need
1049 * to keep it around anymore.
1051 * @param n neighbour to consider discarding
1054 consider_free_neighbour (struct Neighbour *n);
1058 * Task triggered when a neighbour entry might have gotten stale.
1060 * @param cls the 'struct Neighbour'
1061 * @param tc scheduler context (not used)
1064 consider_free_task (void *cls,
1065 const struct GNUNET_SCHEDULER_TaskContext *tc)
1067 struct Neighbour *n = cls;
1068 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1069 consider_free_neighbour (n);
1074 * Consider freeing the given neighbour since we may not need
1075 * to keep it around anymore.
1077 * @param n neighbour to consider discarding
1080 consider_free_neighbour (struct Neighbour *n)
1082 struct Neighbour *pos;
1083 struct Neighbour *prev;
1084 struct GNUNET_TIME_Relative left;
1086 if ( (n->th != NULL) ||
1087 (n->pitr != NULL) ||
1088 (n->status == PEER_STATE_KEY_CONFIRMED) ||
1089 (GNUNET_YES == n->is_connected) )
1090 return; /* no chance */
1092 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1096 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1097 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1098 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1100 &consider_free_task,
1104 /* actually free the neighbour... */
1113 neighbours = n->next;
1115 prev->next = n->next;
1116 GNUNET_assert (neighbour_count > 0);
1123 * Check if we have encrypted messages for the specified neighbour
1124 * pending, and if so, check with the transport about sending them
1127 * @param n neighbour to check.
1129 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1133 * Function called when the transport service is ready to
1134 * receive an encrypted message for the respective peer
1136 * @param cls neighbour to use message from
1137 * @param size number of bytes we can transmit
1138 * @param buf where to copy the message
1139 * @return number of bytes transmitted
1142 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1144 struct Neighbour *n = cls;
1145 struct MessageEntry *m;
1150 GNUNET_assert (NULL != (m = n->encrypted_head));
1151 n->encrypted_head = m->next;
1152 if (m->next == NULL)
1153 n->encrypted_tail = NULL;
1158 GNUNET_assert (size >= m->size);
1159 memcpy (cbuf, &m[1], m->size);
1161 n->available_send_window -= m->size;
1162 process_encrypted_neighbour_queue (n);
1165 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1166 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1167 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1168 ret, GNUNET_i2s (&n->peer));
1173 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1174 "Transmission of message of type %u and size %u failed\n",
1175 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1179 consider_free_neighbour (n);
1185 * Check if we have plaintext messages for the specified neighbour
1186 * pending, and if so, consider batching and encrypting them (and
1187 * then trigger processing of the encrypted queue if needed).
1189 * @param n neighbour to check.
1191 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1195 * Check if we have encrypted messages for the specified neighbour
1196 * pending, and if so, check with the transport about sending them
1199 * @param n neighbour to check.
1202 process_encrypted_neighbour_queue (struct Neighbour *n)
1204 struct MessageEntry *m;
1207 return; /* request already pending */
1208 if (n->encrypted_head == NULL)
1210 /* encrypted queue empty, try plaintext instead */
1211 process_plaintext_neighbour_queue (n);
1215 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1216 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1217 n->encrypted_head->size,
1218 GNUNET_i2s (&n->peer),
1219 GNUNET_TIME_absolute_get_remaining (n->
1220 encrypted_head->deadline).
1224 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1225 n->encrypted_head->size,
1226 n->encrypted_head->priority,
1227 GNUNET_TIME_absolute_get_remaining
1228 (n->encrypted_head->deadline),
1229 ¬ify_encrypted_transmit_ready,
1233 /* message request too large or duplicate request */
1235 /* discard encrypted message */
1236 GNUNET_assert (NULL != (m = n->encrypted_head));
1237 n->encrypted_head = m->next;
1238 if (m->next == NULL)
1239 n->encrypted_tail = NULL;
1241 process_encrypted_neighbour_queue (n);
1247 * Decrypt size bytes from in and write the result to out. Use the
1248 * key for inbound traffic of the given neighbour. This function does
1249 * NOT do any integrity-checks on the result.
1251 * @param n neighbour we are receiving from
1252 * @param iv initialization vector to use
1253 * @param in ciphertext
1254 * @param out plaintext
1255 * @param size size of in/out
1256 * @return GNUNET_OK on success
1259 do_decrypt (struct Neighbour *n,
1260 const GNUNET_HashCode * iv,
1261 const void *in, void *out, size_t size)
1263 if (size != (uint16_t) size)
1268 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1269 (n->status != PEER_STATE_KEY_CONFIRMED))
1271 GNUNET_break_op (0);
1272 return GNUNET_SYSERR;
1275 GNUNET_CRYPTO_aes_decrypt (in,
1279 GNUNET_CRYPTO_AesInitializationVector *) iv,
1283 return GNUNET_SYSERR;
1286 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1287 "Decrypted %u bytes from `%4s' using key %u\n",
1288 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1295 * Encrypt size bytes from in and write the result to out. Use the
1296 * key for outbound traffic of the given neighbour.
1298 * @param n neighbour we are sending to
1299 * @param iv initialization vector to use
1300 * @param in ciphertext
1301 * @param out plaintext
1302 * @param size size of in/out
1303 * @return GNUNET_OK on success
1306 do_encrypt (struct Neighbour *n,
1307 const GNUNET_HashCode * iv,
1308 const void *in, void *out, size_t size)
1310 if (size != (uint16_t) size)
1315 GNUNET_assert (size ==
1316 GNUNET_CRYPTO_aes_encrypt (in,
1320 GNUNET_CRYPTO_AesInitializationVector
1323 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1324 "Encrypted %u bytes for `%4s' using key %u\n", size,
1325 GNUNET_i2s (&n->peer), n->encrypt_key.crc32);
1332 * Select messages for transmission. This heuristic uses a combination
1333 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1334 * and priority-based discard (in case no feasible schedule exist) and
1335 * speculative optimization (defer any kind of transmission until
1336 * we either create a batch of significant size, 25% of max, or until
1337 * we are close to a deadline). Furthermore, when scheduling the
1338 * heuristic also packs as many messages into the batch as possible,
1339 * starting with those with the earliest deadline. Yes, this is fun.
1341 * @param n neighbour to select messages from
1342 * @param size number of bytes to select for transmission
1343 * @param retry_time set to the time when we should try again
1344 * (only valid if this function returns zero)
1345 * @return number of bytes selected, or 0 if we decided to
1346 * defer scheduling overall; in that case, retry_time is set.
1349 select_messages (struct Neighbour *n,
1350 size_t size, struct GNUNET_TIME_Relative *retry_time)
1352 struct MessageEntry *pos;
1353 struct MessageEntry *min;
1354 struct MessageEntry *last;
1355 unsigned int min_prio;
1356 struct GNUNET_TIME_Absolute t;
1357 struct GNUNET_TIME_Absolute now;
1360 unsigned long long slack; /* how long could we wait before missing deadlines? */
1362 int discard_low_prio;
1364 GNUNET_assert (NULL != n->messages);
1365 now = GNUNET_TIME_absolute_get ();
1366 /* last entry in linked list of messages processed */
1368 /* should we remove the entry with the lowest
1369 priority from consideration for scheduling at the
1371 discard_low_prio = GNUNET_YES;
1372 while (GNUNET_YES == discard_low_prio)
1376 discard_low_prio = GNUNET_NO;
1377 /* calculate number of bytes available for transmission at time "t" */
1378 update_window (GNUNET_NO,
1379 &n->available_send_window,
1380 &n->last_asw_update,
1382 avail = n->available_send_window;
1383 t = n->last_asw_update;
1384 /* how many bytes have we (hypothetically) scheduled so far */
1386 /* maximum time we can wait before transmitting anything
1387 and still make all of our deadlines */
1391 /* note that we use "*2" here because we want to look
1392 a bit further into the future; much more makes no
1393 sense since new message might be scheduled in the
1395 while ((pos != NULL) && (off < size * 2))
1397 if (pos->do_transmit == GNUNET_YES)
1399 /* already removed from consideration */
1403 if (discard_low_prio == GNUNET_NO)
1405 delta = pos->deadline.value;
1406 if (delta < t.value)
1409 delta = t.value - delta;
1410 avail += delta * n->bpm_out / 1000 / 60;
1411 if (avail < pos->size)
1413 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1418 /* update slack, considering both its absolute deadline
1419 and relative deadlines caused by other messages
1420 with their respective load */
1421 slack = GNUNET_MIN (slack, avail / n->bpm_out);
1422 if ( (pos->deadline.value < now.value) ||
1423 (GNUNET_YES == pos->got_slack) )
1430 GNUNET_MIN (slack, pos->deadline.value - now.value);
1431 pos->got_slack = GNUNET_YES;
1437 t.value = GNUNET_MAX (pos->deadline.value, t.value);
1438 if (pos->priority <= min_prio)
1440 /* update min for discard */
1441 min_prio = pos->priority;
1446 if (discard_low_prio)
1448 GNUNET_assert (min != NULL);
1449 /* remove lowest-priority entry from consideration */
1450 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1454 /* guard against sending "tiny" messages with large headers without
1456 if ( (slack > 1000) && (size > 4 * off) )
1458 /* less than 25% of message would be filled with deadlines still
1459 being met if we delay by one second or more; so just wait for
1460 more data; but do not wait longer than 1s (since we don't want
1461 to delay messages for a really long time either). */
1462 retry_time->value = 1000;
1463 /* reset do_transmit values for next time */
1466 pos->do_transmit = GNUNET_NO;
1470 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1471 "Deferring transmission for 1s due to underfull message buffer size\n");
1475 /* select marked messages (up to size) for transmission */
1480 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1482 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1487 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1491 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1492 "Selected %u bytes of plaintext messages for transmission to `%4s'.\n",
1493 off, GNUNET_i2s (&n->peer));
1500 * Batch multiple messages into a larger buffer.
1502 * @param n neighbour to take messages from
1503 * @param buf target buffer
1504 * @param size size of buf
1505 * @param deadline set to transmission deadline for the result
1506 * @param retry_time set to the time when we should try again
1507 * (only valid if this function returns zero)
1508 * @param priority set to the priority of the batch
1509 * @return number of bytes written to buf (can be zero)
1512 batch_message (struct Neighbour *n,
1515 struct GNUNET_TIME_Absolute *deadline,
1516 struct GNUNET_TIME_Relative *retry_time,
1517 unsigned int *priority)
1519 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1520 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1521 struct MessageEntry *pos;
1522 struct MessageEntry *prev;
1523 struct MessageEntry *next;
1528 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1529 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1530 if (0 == select_messages (n, size, retry_time))
1532 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1533 "No messages selected, will try again in %llu ms\n",
1537 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1538 ntm->distance = htonl (n->last_distance);
1539 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1540 ntm->peer = n->peer;
1544 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1547 if (GNUNET_YES == pos->do_transmit)
1549 GNUNET_assert (pos->size <= size);
1550 /* do notifications */
1551 /* FIXME: track if we have *any* client that wants
1552 full notifications and only do this if that is
1554 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1556 memcpy (&ntm[1], &pos[1], pos->size);
1557 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1558 sizeof (struct GNUNET_MessageHeader));
1559 send_to_all_clients (&ntm->header,
1561 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1565 /* message too large for 'full' notifications, we do at
1566 least the 'hdr' type */
1569 sizeof (struct GNUNET_MessageHeader));
1571 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1573 send_to_all_clients (&ntm->header,
1575 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1578 "Encrypting message of type %u\n",
1579 ntohs(((struct GNUNET_MessageHeader*)&pos[1])->type));
1581 /* copy for encrypted transmission */
1582 memcpy (&buf[ret], &pos[1], pos->size);
1585 *priority += pos->priority;
1587 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1588 "Adding plaintext message with deadline %llu ms to batch\n",
1589 GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1591 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1605 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1606 "Deadline for message batch is %llu ms\n",
1607 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1614 * Remove messages with deadlines that have long expired from
1617 * @param n neighbour to inspect
1620 discard_expired_messages (struct Neighbour *n)
1622 struct MessageEntry *prev;
1623 struct MessageEntry *next;
1624 struct MessageEntry *pos;
1625 struct GNUNET_TIME_Absolute now;
1626 struct GNUNET_TIME_Relative delta;
1628 now = GNUNET_TIME_absolute_get ();
1634 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1635 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1638 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1639 "Message is %llu ms past due, discarding.\n",
1656 * Signature of the main function of a task.
1658 * @param cls closure
1659 * @param tc context information (why was this task triggered now)
1662 retry_plaintext_processing (void *cls,
1663 const struct GNUNET_SCHEDULER_TaskContext *tc)
1665 struct Neighbour *n = cls;
1667 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1668 process_plaintext_neighbour_queue (n);
1673 * Send our key (and encrypted PING) to the other peer.
1675 * @param n the other peer
1677 static void send_key (struct Neighbour *n);
1680 * Task that will retry "send_key" if our previous attempt failed
1684 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1686 struct Neighbour *n = cls;
1688 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1689 n->set_key_retry_frequency =
1690 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1696 * Check if we have plaintext messages for the specified neighbour
1697 * pending, and if so, consider batching and encrypting them (and
1698 * then trigger processing of the encrypted queue if needed).
1700 * @param n neighbour to check.
1703 process_plaintext_neighbour_queue (struct Neighbour *n)
1705 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1708 struct EncryptedMessage *em; /* encrypted message */
1709 struct EncryptedMessage *ph; /* plaintext header */
1710 struct MessageEntry *me;
1711 unsigned int priority;
1712 struct GNUNET_TIME_Absolute deadline;
1713 struct GNUNET_TIME_Relative retry_time;
1715 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1717 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1718 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1722 case PEER_STATE_DOWN:
1725 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1726 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1727 GNUNET_i2s(&n->peer));
1730 case PEER_STATE_KEY_SENT:
1731 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1732 n->retry_set_key_task
1733 = GNUNET_SCHEDULER_add_delayed (sched,
1734 n->set_key_retry_frequency,
1735 &set_key_retry_task, n);
1737 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1738 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1739 GNUNET_i2s(&n->peer));
1742 case PEER_STATE_KEY_RECEIVED:
1743 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1744 n->retry_set_key_task
1745 = GNUNET_SCHEDULER_add_delayed (sched,
1746 n->set_key_retry_frequency,
1747 &set_key_retry_task, n);
1749 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1750 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1751 GNUNET_i2s(&n->peer));
1754 case PEER_STATE_KEY_CONFIRMED:
1755 /* ready to continue */
1758 discard_expired_messages (n);
1759 if (n->messages == NULL)
1762 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1763 "Plaintext message queue for `%4s' is empty.\n",
1764 GNUNET_i2s(&n->peer));
1766 return; /* no pending messages */
1768 if (n->encrypted_head != NULL)
1771 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1772 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1773 GNUNET_i2s(&n->peer));
1775 return; /* wait for messages already encrypted to be
1778 ph = (struct EncryptedMessage *) pbuf;
1779 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1781 used = sizeof (struct EncryptedMessage);
1782 used += batch_message (n,
1784 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1785 &deadline, &retry_time, &priority);
1786 if (used == sizeof (struct EncryptedMessage))
1789 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1790 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1791 GNUNET_i2s(&n->peer));
1793 /* no messages selected for sending, try again later... */
1794 n->retry_plaintext_task =
1795 GNUNET_SCHEDULER_add_delayed (sched,
1797 &retry_plaintext_processing, n);
1800 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1801 ph->inbound_bpm_limit = htonl (n->bpm_in);
1802 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1804 /* setup encryption message header */
1805 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1806 me->deadline = deadline;
1807 me->priority = priority;
1809 em = (struct EncryptedMessage *) &me[1];
1810 em->header.size = htons (used);
1811 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1812 em->reserved = htonl (0);
1813 esize = used - ENCRYPTED_HEADER_SIZE;
1814 GNUNET_CRYPTO_hash (&ph->sequence_number, esize, &em->plaintext_hash);
1817 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1818 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
1820 GNUNET_i2s(&n->peer),
1821 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
1823 GNUNET_assert (GNUNET_OK ==
1825 &em->plaintext_hash,
1826 &ph->sequence_number,
1827 &em->sequence_number, esize));
1828 /* append to transmission list */
1829 if (n->encrypted_tail == NULL)
1830 n->encrypted_head = me;
1832 n->encrypted_tail->next = me;
1833 n->encrypted_tail = me;
1834 process_encrypted_neighbour_queue (n);
1839 * Function that recalculates the bandwidth quota for the
1840 * given neighbour and transmits it to the transport service.
1842 * @param cls neighbour for the quota update
1846 neighbour_quota_update (void *cls,
1847 const struct GNUNET_SCHEDULER_TaskContext *tc);
1851 * Schedule the task that will recalculate the bandwidth
1852 * quota for this peer (and possibly force a disconnect of
1853 * idle peers by calculating a bandwidth of zero).
1856 schedule_quota_update (struct Neighbour *n)
1858 GNUNET_assert (n->quota_update_task ==
1859 GNUNET_SCHEDULER_NO_TASK);
1860 n->quota_update_task
1861 = GNUNET_SCHEDULER_add_delayed (sched,
1862 QUOTA_UPDATE_FREQUENCY,
1863 &neighbour_quota_update,
1869 * Initialize a new 'struct Neighbour'.
1871 * @param pid ID of the new neighbour
1872 * @return handle for the new neighbour
1874 static struct Neighbour *
1875 create_neighbour (const struct GNUNET_PeerIdentity *pid)
1877 struct Neighbour *n;
1878 struct GNUNET_TIME_Absolute now;
1880 n = GNUNET_malloc (sizeof (struct Neighbour));
1881 n->next = neighbours;
1885 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
1886 now = GNUNET_TIME_absolute_get ();
1887 n->encrypt_key_created = now;
1888 n->last_activity = now;
1889 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
1890 n->bpm_in = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
1891 n->bpm_out = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
1892 n->bpm_out_internal_limit = (uint32_t) - 1;
1893 n->bpm_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
1894 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1896 schedule_quota_update (n);
1905 * Handle CORE_SEND request.
1908 * @param client the client issuing the request
1909 * @param message the "struct SendMessage"
1912 handle_client_send (void *cls,
1913 struct GNUNET_SERVER_Client *client,
1914 const struct GNUNET_MessageHeader *message)
1916 const struct SendMessage *sm;
1917 const struct GNUNET_MessageHeader *mh;
1918 struct Neighbour *n;
1919 struct MessageEntry *prev;
1920 struct MessageEntry *pos;
1921 struct MessageEntry *e;
1922 struct MessageEntry *min_prio_entry;
1923 struct MessageEntry *min_prio_prev;
1924 unsigned int min_prio;
1925 unsigned int queue_size;
1928 msize = ntohs (message->size);
1930 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
1934 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1937 sm = (const struct SendMessage *) message;
1938 msize -= sizeof (struct SendMessage);
1939 mh = (const struct GNUNET_MessageHeader *) &sm[1];
1940 if (msize != ntohs (mh->size))
1944 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1947 n = find_neighbour (&sm->peer);
1949 n = create_neighbour (&sm->peer);
1951 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1952 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
1955 GNUNET_i2s (&sm->peer));
1957 /* bound queue size */
1958 discard_expired_messages (n);
1959 min_prio = (unsigned int) -1;
1960 min_prio_entry = NULL;
1961 min_prio_prev = NULL;
1967 if (pos->priority < min_prio)
1969 min_prio_entry = pos;
1970 min_prio_prev = prev;
1971 min_prio = pos->priority;
1977 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1980 if (ntohl(sm->priority) <= min_prio)
1982 /* discard new entry */
1984 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1985 "Queue full, discarding new request\n");
1988 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1991 /* discard "min_prio_entry" */
1993 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1994 "Queue full, discarding existing older request\n");
1996 if (min_prio_prev == NULL)
1997 n->messages = min_prio_entry->next;
1999 min_prio_prev->next = min_prio_entry->next;
2000 GNUNET_free (min_prio_entry);
2004 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2005 "Adding transmission request for `%4s' to queue\n",
2006 GNUNET_i2s (&sm->peer));
2008 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2009 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2010 e->priority = ntohl (sm->priority);
2012 memcpy (&e[1], mh, msize);
2014 /* insert, keep list sorted by deadline */
2017 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2028 /* consider scheduling now */
2029 process_plaintext_neighbour_queue (n);
2031 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2036 * Function called when the transport service is ready to
2037 * receive a message. Only resets 'n->th' to NULL.
2039 * @param cls neighbour to use message from
2040 * @param size number of bytes we can transmit
2041 * @param buf where to copy the message
2042 * @return number of bytes transmitted
2045 notify_transport_connect_done (void *cls, size_t size, void *buf)
2047 struct Neighbour *n = cls;
2055 * Handle CORE_REQUEST_CONNECT request.
2058 * @param client the client issuing the request
2059 * @param message the "struct ConnectMessage"
2062 handle_client_request_connect (void *cls,
2063 struct GNUNET_SERVER_Client *client,
2064 const struct GNUNET_MessageHeader *message)
2066 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2067 struct Neighbour *n;
2068 struct GNUNET_TIME_Relative timeout;
2070 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2071 n = find_neighbour (&cm->peer);
2073 n = create_neighbour (&cm->peer);
2074 if ( (n->is_connected) ||
2076 return; /* already connected, or at least trying */
2078 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2079 "Core received `%s' request for `%4s', will try to establish connection\n",
2081 GNUNET_i2s (&cm->peer));
2083 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2084 /* ask transport to connect to the peer */
2085 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2087 sizeof (struct GNUNET_MessageHeader), 0,
2089 ¬ify_transport_connect_done,
2091 GNUNET_break (NULL != n->th);
2096 * List of handlers for the messages understood by this
2099 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2100 {&handle_client_init, NULL,
2101 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2102 {&handle_client_request_info, NULL,
2103 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2104 sizeof (struct RequestInfoMessage)},
2105 {&handle_client_send, NULL,
2106 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2107 {&handle_client_request_connect, NULL,
2108 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2109 sizeof (struct ConnectMessage)},
2115 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2116 * the neighbour's struct and retry send_key. Or, if we did not get a
2117 * HELLO, just do nothing.
2119 * @param cls the 'struct Neighbour' to retry sending the key for
2120 * @param peer the peer for which this is the HELLO
2121 * @param hello HELLO message of that peer
2122 * @param trust amount of trust we currently have in that peer
2125 process_hello_retry_send_key (void *cls,
2126 const struct GNUNET_PeerIdentity *peer,
2127 const struct GNUNET_HELLO_Message *hello,
2130 struct Neighbour *n = cls;
2135 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2136 "Entered `process_hello_retry_send_key' and `peer' is NULL!\n");
2139 if (n->public_key != NULL)
2145 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2146 n->retry_set_key_task
2147 = GNUNET_SCHEDULER_add_delayed (sched,
2148 n->set_key_retry_frequency,
2149 &set_key_retry_task, n);
2155 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2156 "Entered `process_hello_retry_send_key' for peer `%4s'\n",
2159 if (n->public_key != NULL)
2162 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2163 "already have public key for peer %s!! (so why are we here?)\n",
2170 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2171 "Received new `%s' message for `%4s', initiating key exchange.\n",
2176 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2177 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2179 GNUNET_free (n->public_key);
2180 n->public_key = NULL;
2182 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2183 "GNUNET_HELLO_get_key returned awfully\n");
2191 * Send our key (and encrypted PING) to the other peer.
2193 * @param n the other peer
2196 send_key (struct Neighbour *n)
2198 struct SetKeyMessage *sm;
2199 struct MessageEntry *me;
2200 struct PingMessage pp;
2201 struct PingMessage *pm;
2203 if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2207 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2208 "Key exchange in progress with `%4s'.\n",
2209 GNUNET_i2s (&n->peer));
2211 return; /* already in progress */
2215 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2216 "Asked to perform key exchange with `%4s'.\n",
2217 GNUNET_i2s (&n->peer));
2219 if (n->public_key == NULL)
2221 /* lookup n's public key, then try again */
2223 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2224 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2225 GNUNET_i2s (&n->peer));
2227 GNUNET_assert (n->pitr == NULL);
2228 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2232 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2233 &process_hello_retry_send_key, n);
2236 /* first, set key message */
2237 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2238 sizeof (struct SetKeyMessage));
2239 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2240 me->priority = SET_KEY_PRIORITY;
2241 me->size = sizeof (struct SetKeyMessage);
2242 if (n->encrypted_head == NULL)
2243 n->encrypted_head = me;
2245 n->encrypted_tail->next = me;
2246 n->encrypted_tail = me;
2247 sm = (struct SetKeyMessage *) &me[1];
2248 sm->header.size = htons (sizeof (struct SetKeyMessage));
2249 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2250 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2251 PEER_STATE_KEY_SENT : n->status));
2253 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2254 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2255 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2256 sizeof (struct GNUNET_PeerIdentity));
2257 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2258 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2259 sm->target = n->peer;
2260 GNUNET_assert (GNUNET_OK ==
2261 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2263 GNUNET_CRYPTO_AesSessionKey),
2265 &sm->encrypted_key));
2266 GNUNET_assert (GNUNET_OK ==
2267 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2270 /* second, encrypted PING message */
2271 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2272 sizeof (struct PingMessage));
2273 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2274 me->priority = PING_PRIORITY;
2275 me->size = sizeof (struct PingMessage);
2276 n->encrypted_tail->next = me;
2277 n->encrypted_tail = me;
2278 pm = (struct PingMessage *) &me[1];
2279 pm->header.size = htons (sizeof (struct PingMessage));
2280 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2281 pp.challenge = htonl (n->ping_challenge);
2282 pp.target = n->peer;
2284 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2285 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2286 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2287 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2288 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2290 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2293 &n->peer.hashPubKey,
2296 sizeof (struct PingMessage) -
2297 sizeof (struct GNUNET_MessageHeader));
2301 case PEER_STATE_DOWN:
2302 n->status = PEER_STATE_KEY_SENT;
2304 case PEER_STATE_KEY_SENT:
2306 case PEER_STATE_KEY_RECEIVED:
2308 case PEER_STATE_KEY_CONFIRMED:
2315 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2316 "Have %llu ms left for `%s' transmission.\n",
2317 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2320 /* trigger queue processing */
2321 process_encrypted_neighbour_queue (n);
2322 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2323 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2324 n->retry_set_key_task
2325 = GNUNET_SCHEDULER_add_delayed (sched,
2326 n->set_key_retry_frequency,
2327 &set_key_retry_task, n);
2332 * We received a SET_KEY message. Validate and update
2333 * our key material and status.
2335 * @param n the neighbour from which we received message m
2336 * @param m the set key message we received
2339 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2343 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2344 * the neighbour's struct and retry handling the set_key message. Or,
2345 * if we did not get a HELLO, just free the set key message.
2347 * @param cls pointer to the set key message
2348 * @param peer the peer for which this is the HELLO
2349 * @param hello HELLO message of that peer
2350 * @param trust amount of trust we currently have in that peer
2353 process_hello_retry_handle_set_key (void *cls,
2354 const struct GNUNET_PeerIdentity *peer,
2355 const struct GNUNET_HELLO_Message *hello,
2358 struct Neighbour *n = cls;
2359 struct SetKeyMessage *sm = n->skm;
2368 if (n->public_key != NULL)
2369 return; /* multiple HELLOs match!? */
2371 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2372 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2374 GNUNET_break_op (0);
2375 GNUNET_free (n->public_key);
2376 n->public_key = NULL;
2380 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2381 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2382 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2384 handle_set_key (n, sm);
2389 * We received a PING message. Validate and transmit
2392 * @param n sender of the PING
2393 * @param m the encrypted PING message itself
2396 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2398 struct PingMessage t;
2399 struct PingMessage *tp;
2400 struct MessageEntry *me;
2403 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2404 "Core service receives `%s' request from `%4s'.\n",
2405 "PING", GNUNET_i2s (&n->peer));
2409 &my_identity.hashPubKey,
2412 sizeof (struct PingMessage) -
2413 sizeof (struct GNUNET_MessageHeader)))
2416 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2417 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2419 GNUNET_i2s (&t.target),
2420 ntohl (t.challenge), n->decrypt_key.crc32);
2421 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2422 "Target of `%s' request is `%4s'.\n",
2423 "PING", GNUNET_i2s (&t.target));
2425 if (0 != memcmp (&t.target,
2426 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2428 GNUNET_break_op (0);
2431 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2432 sizeof (struct PingMessage));
2433 if (n->encrypted_tail != NULL)
2434 n->encrypted_tail->next = me;
2437 n->encrypted_tail = me;
2438 n->encrypted_head = me;
2440 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2441 me->priority = PONG_PRIORITY;
2442 me->size = sizeof (struct PingMessage);
2443 tp = (struct PingMessage *) &me[1];
2444 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2445 tp->header.size = htons (sizeof (struct PingMessage));
2447 &my_identity.hashPubKey,
2450 sizeof (struct PingMessage) -
2451 sizeof (struct GNUNET_MessageHeader));
2453 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2454 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2455 ntohl (t.challenge), n->encrypt_key.crc32);
2457 /* trigger queue processing */
2458 process_encrypted_neighbour_queue (n);
2463 * We received a PONG message. Validate and update our status.
2465 * @param n sender of the PONG
2466 * @param m the encrypted PONG message itself
2469 handle_pong (struct Neighbour *n, const struct PingMessage *m)
2471 struct PingMessage t;
2472 struct ConnectNotifyMessage cnm;
2475 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2476 "Core service receives `%s' request from `%4s'.\n",
2477 "PONG", GNUNET_i2s (&n->peer));
2481 &n->peer.hashPubKey,
2484 sizeof (struct PingMessage) -
2485 sizeof (struct GNUNET_MessageHeader)))
2488 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2489 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2491 GNUNET_i2s (&t.target),
2492 ntohl (t.challenge), n->decrypt_key.crc32);
2494 if ((0 != memcmp (&t.target,
2496 sizeof (struct GNUNET_PeerIdentity))) ||
2497 (n->ping_challenge != ntohl (t.challenge)))
2499 /* PONG malformed */
2501 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2502 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2503 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2504 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2505 "Received malformed `%s' received from `%4s' with challenge %u\n",
2506 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2508 GNUNET_break_op (0);
2513 case PEER_STATE_DOWN:
2514 GNUNET_break (0); /* should be impossible */
2516 case PEER_STATE_KEY_SENT:
2517 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2519 case PEER_STATE_KEY_RECEIVED:
2520 n->status = PEER_STATE_KEY_CONFIRMED;
2522 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2523 "Confirmed key via `%s' message for peer `%4s'\n",
2524 "PONG", GNUNET_i2s (&n->peer));
2526 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2528 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2529 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2531 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2532 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2533 cnm.distance = htonl (n->last_distance);
2534 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2536 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2537 process_encrypted_neighbour_queue (n);
2539 case PEER_STATE_KEY_CONFIRMED:
2540 /* duplicate PONG? */
2550 * We received a SET_KEY message. Validate and update
2551 * our key material and status.
2553 * @param n the neighbour from which we received message m
2554 * @param m the set key message we received
2557 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2559 struct SetKeyMessage *m_cpy;
2560 struct GNUNET_TIME_Absolute t;
2561 struct GNUNET_CRYPTO_AesSessionKey k;
2562 struct PingMessage *ping;
2563 struct PingMessage *pong;
2564 enum PeerStateMachine sender_status;
2567 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2568 "Core service receives `%s' request from `%4s'.\n",
2569 "SET_KEY", GNUNET_i2s (&n->peer));
2571 if (n->public_key == NULL)
2573 if (n->pitr != NULL)
2576 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2577 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2583 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2584 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2586 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2587 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2588 /* lookup n's public key, then try again */
2589 GNUNET_assert (n->skm == NULL);
2591 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2595 GNUNET_TIME_UNIT_MINUTES,
2596 &process_hello_retry_handle_set_key, n);
2599 if (0 != memcmp (&m->target,
2601 sizeof (struct GNUNET_PeerIdentity)))
2603 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2604 _("Received `%s' message that was not for me. Ignoring.\n"),
2608 if ((ntohl (m->purpose.size) !=
2609 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2610 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2611 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2612 sizeof (struct GNUNET_PeerIdentity)) ||
2614 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2615 &m->purpose, &m->signature, n->public_key)))
2617 /* invalid signature */
2618 GNUNET_break_op (0);
2621 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2622 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2623 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2624 (t.value < n->decrypt_key_created.value))
2626 /* this could rarely happen due to massive re-ordering of
2627 messages on the network level, but is most likely either
2628 a bug or some adversary messing with us. Report. */
2629 GNUNET_break_op (0);
2633 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
2635 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2638 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2639 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2640 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2642 /* failed to decrypt !? */
2643 GNUNET_break_op (0);
2648 if (n->decrypt_key_created.value != t.value)
2650 /* fresh key, reset sequence numbers */
2651 n->last_sequence_number_received = 0;
2652 n->last_packets_bitmap = 0;
2653 n->decrypt_key_created = t;
2655 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2658 case PEER_STATE_DOWN:
2659 n->status = PEER_STATE_KEY_RECEIVED;
2661 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2662 "Responding to `%s' with my own key.\n", "SET_KEY");
2666 case PEER_STATE_KEY_SENT:
2667 case PEER_STATE_KEY_RECEIVED:
2668 n->status = PEER_STATE_KEY_RECEIVED;
2669 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2670 (sender_status != PEER_STATE_KEY_CONFIRMED))
2673 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2674 "Responding to `%s' with my own key (other peer has status %u).\n",
2675 "SET_KEY", sender_status);
2680 case PEER_STATE_KEY_CONFIRMED:
2681 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2682 (sender_status != PEER_STATE_KEY_CONFIRMED))
2685 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2686 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2687 "SET_KEY", sender_status);
2696 if (n->pending_ping != NULL)
2698 ping = n->pending_ping;
2699 n->pending_ping = NULL;
2700 handle_ping (n, ping);
2703 if (n->pending_pong != NULL)
2705 pong = n->pending_pong;
2706 n->pending_pong = NULL;
2707 handle_pong (n, pong);
2714 * Send a P2P message to a client.
2716 * @param sender who sent us the message?
2717 * @param client who should we give the message to?
2718 * @param m contains the message to transmit
2719 * @param msize number of bytes in buf to transmit
2722 send_p2p_message_to_client (struct Neighbour *sender,
2723 struct Client *client,
2724 const void *m, size_t msize)
2726 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2727 struct NotifyTrafficMessage *ntm;
2730 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2731 "Core service passes message from `%4s' of type %u to client.\n",
2732 GNUNET_i2s(&sender->peer),
2733 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2735 ntm = (struct NotifyTrafficMessage *) buf;
2736 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2737 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2738 ntm->distance = htonl (sender->last_distance);
2739 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
2740 ntm->peer = sender->peer;
2741 memcpy (&ntm[1], m, msize);
2742 send_to_client (client, &ntm->header, GNUNET_YES);
2747 * Deliver P2P message to interested clients.
2749 * @param sender who sent us the message?
2750 * @param m the message
2751 * @param msize size of the message (including header)
2754 deliver_message (struct Neighbour *sender,
2755 const struct GNUNET_MessageHeader *m, size_t msize)
2757 struct Client *cpos;
2762 type = ntohs (m->type);
2765 "Received encapsulated message of type %u from `%4s'\n",
2767 GNUNET_i2s (&sender->peer));
2770 while (cpos != NULL)
2772 deliver_full = GNUNET_NO;
2773 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
2774 deliver_full = GNUNET_YES;
2777 for (tpos = 0; tpos < cpos->tcnt; tpos++)
2779 if (type != cpos->types[tpos])
2781 deliver_full = GNUNET_YES;
2785 if (GNUNET_YES == deliver_full)
2786 send_p2p_message_to_client (sender, cpos, m, msize);
2787 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2788 send_p2p_message_to_client (sender, cpos, m,
2789 sizeof (struct GNUNET_MessageHeader));
2796 * Align P2P message and then deliver to interested clients.
2798 * @param sender who sent us the message?
2799 * @param buffer unaligned (!) buffer containing message
2800 * @param msize size of the message (including header)
2803 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
2807 /* TODO: call to statistics? */
2808 memcpy (abuf, buffer, msize);
2809 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
2814 * Deliver P2P messages to interested clients.
2816 * @param sender who sent us the message?
2817 * @param buffer buffer containing messages, can be modified
2818 * @param buffer_size size of the buffer (overall)
2819 * @param offset offset where messages in the buffer start
2822 deliver_messages (struct Neighbour *sender,
2823 const char *buffer, size_t buffer_size, size_t offset)
2825 struct GNUNET_MessageHeader *mhp;
2826 struct GNUNET_MessageHeader mh;
2830 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
2832 if (0 != offset % sizeof (uint16_t))
2834 /* outch, need to copy to access header */
2835 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
2840 /* can access header directly */
2841 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
2843 msize = ntohs (mhp->size);
2844 if (msize + offset > buffer_size)
2846 /* malformed message, header says it is larger than what
2847 would fit into the overall buffer */
2848 GNUNET_break_op (0);
2851 #if HAVE_UNALIGNED_64_ACCESS
2852 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
2854 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
2856 if (GNUNET_YES == need_align)
2857 align_and_deliver (sender, &buffer[offset], msize);
2859 deliver_message (sender,
2860 (const struct GNUNET_MessageHeader *)
2861 &buffer[offset], msize);
2868 * We received an encrypted message. Decrypt, validate and
2869 * pass on to the appropriate clients.
2872 handle_encrypted_message (struct Neighbour *n,
2873 const struct EncryptedMessage *m)
2875 size_t size = ntohs (m->header.size);
2877 struct EncryptedMessage *pt; /* plaintext */
2881 struct GNUNET_TIME_Absolute t;
2884 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2885 "Core service receives `%s' request from `%4s'.\n",
2886 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
2892 &m->sequence_number,
2893 &buf[ENCRYPTED_HEADER_SIZE], size - ENCRYPTED_HEADER_SIZE))
2895 pt = (struct EncryptedMessage *) buf;
2898 GNUNET_CRYPTO_hash (&pt->sequence_number,
2899 size - ENCRYPTED_HEADER_SIZE, &ph);
2900 if (0 != memcmp (&ph, &m->plaintext_hash, sizeof (GNUNET_HashCode)))
2902 /* checksum failed */
2903 GNUNET_break_op (0);
2907 /* validate sequence number */
2908 snum = ntohl (pt->sequence_number);
2909 if (n->last_sequence_number_received == snum)
2911 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2912 "Received duplicate message, ignoring.\n");
2913 /* duplicate, ignore */
2916 if ((n->last_sequence_number_received > snum) &&
2917 (n->last_sequence_number_received - snum > 32))
2919 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2920 "Received ancient out of sequence message, ignoring.\n");
2921 /* ancient out of sequence, ignore */
2924 if (n->last_sequence_number_received > snum)
2926 unsigned int rotbit =
2927 1 << (n->last_sequence_number_received - snum - 1);
2928 if ((n->last_packets_bitmap & rotbit) != 0)
2930 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2931 "Received duplicate message, ignoring.\n");
2932 /* duplicate, ignore */
2935 n->last_packets_bitmap |= rotbit;
2937 if (n->last_sequence_number_received < snum)
2939 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
2940 n->last_sequence_number_received = snum;
2943 /* check timestamp */
2944 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
2945 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
2947 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2949 ("Message received far too old (%llu ms). Content ignored.\n"),
2950 GNUNET_TIME_absolute_get_duration (t).value);
2954 /* process decrypted message(s) */
2955 update_window (GNUNET_YES,
2956 &n->available_send_window,
2957 &n->last_asw_update,
2959 n->bpm_out_external_limit = ntohl (pt->inbound_bpm_limit);
2960 n->bpm_out = GNUNET_MAX (n->bpm_out_external_limit,
2961 n->bpm_out_internal_limit);
2962 n->last_activity = GNUNET_TIME_absolute_get ();
2963 off = sizeof (struct EncryptedMessage);
2964 deliver_messages (n, buf, size, off);
2969 * Function called by the transport for each received message.
2971 * @param cls closure
2972 * @param peer (claimed) identity of the other peer
2973 * @param message the message
2974 * @param latency estimated latency for communicating with the
2975 * given peer (round-trip)
2976 * @param distance in overlay hops, as given by transport plugin
2979 handle_transport_receive (void *cls,
2980 const struct GNUNET_PeerIdentity *peer,
2981 const struct GNUNET_MessageHeader *message,
2982 struct GNUNET_TIME_Relative latency,
2983 unsigned int distance)
2985 struct Neighbour *n;
2986 struct GNUNET_TIME_Absolute now;
2992 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2993 "Received message of type %u from `%4s', demultiplexing.\n",
2994 ntohs (message->type), GNUNET_i2s (peer));
2996 n = find_neighbour (peer);
2998 n = create_neighbour (peer);
3001 n->last_latency = latency;
3002 n->last_distance = distance;
3003 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3004 type = ntohs (message->type);
3005 size = ntohs (message->size);
3008 "Received message of type %u from `%4s'\n",
3014 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3015 if (size != sizeof (struct SetKeyMessage))
3017 GNUNET_break_op (0);
3020 handle_set_key (n, (const struct SetKeyMessage *) message);
3022 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3023 if (size < sizeof (struct EncryptedMessage) +
3024 sizeof (struct GNUNET_MessageHeader))
3026 GNUNET_break_op (0);
3029 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3030 (n->status != PEER_STATE_KEY_CONFIRMED))
3032 GNUNET_break_op (0);
3035 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3037 case GNUNET_MESSAGE_TYPE_CORE_PING:
3038 if (size != sizeof (struct PingMessage))
3040 GNUNET_break_op (0);
3043 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3044 (n->status != PEER_STATE_KEY_CONFIRMED))
3047 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3048 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3049 "PING", GNUNET_i2s (&n->peer));
3051 GNUNET_free_non_null (n->pending_ping);
3052 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3053 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3056 handle_ping (n, (const struct PingMessage *) message);
3058 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3059 if (size != sizeof (struct PingMessage))
3061 GNUNET_break_op (0);
3064 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3065 (n->status != PEER_STATE_KEY_CONFIRMED) )
3068 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3069 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3070 "PONG", GNUNET_i2s (&n->peer));
3072 GNUNET_free_non_null (n->pending_pong);
3073 n->pending_pong = GNUNET_malloc (sizeof (struct PingMessage));
3074 memcpy (n->pending_pong, message, sizeof (struct PingMessage));
3077 handle_pong (n, (const struct PingMessage *) message);
3080 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3081 _("Unsupported message of type %u received.\n"), type);
3084 if (n->status == PEER_STATE_KEY_CONFIRMED)
3086 now = GNUNET_TIME_absolute_get ();
3087 n->last_activity = now;
3089 n->time_established = now;
3095 * Function that recalculates the bandwidth quota for the
3096 * given neighbour and transmits it to the transport service.
3098 * @param cls neighbour for the quota update
3102 neighbour_quota_update (void *cls,
3103 const struct GNUNET_SCHEDULER_TaskContext *tc)
3105 struct Neighbour *n = cls;
3109 unsigned long long distributable;
3111 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3112 /* calculate relative preference among all neighbours;
3113 divides by a bit more to avoid division by zero AND to
3114 account for possibility of new neighbours joining any time
3115 AND to convert to double... */
3116 pref_rel = n->current_preference / (1.0 + preference_sum);
3118 if (bandwidth_target_out > neighbour_count * MIN_BPM_PER_PEER)
3119 distributable = bandwidth_target_out - neighbour_count * MIN_BPM_PER_PEER;
3120 share = distributable * pref_rel;
3121 q_in = MIN_BPM_PER_PEER + (unsigned long long) share;
3122 /* check if we want to disconnect for good due to inactivity */
3123 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3124 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3127 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3128 "Forcing disconnect of `%4s' due to inactivity (?).\n",
3129 GNUNET_i2s (&n->peer));
3131 q_in = 0; /* force disconnect */
3133 if ( (n->bpm_in + MIN_BPM_CHANGE < q_in) ||
3134 (n->bpm_in - MIN_BPM_CHANGE > q_in) )
3137 GNUNET_TRANSPORT_set_quota (transport,
3141 GNUNET_TIME_UNIT_FOREVER_REL,
3144 schedule_quota_update (n);
3149 * Function called by transport to notify us that
3150 * a peer connected to us (on the network level).
3152 * @param cls closure
3153 * @param peer the peer that connected
3154 * @param latency current latency of the connection
3155 * @param distance in overlay hops, as given by transport plugin
3158 handle_transport_notify_connect (void *cls,
3159 const struct GNUNET_PeerIdentity *peer,
3160 struct GNUNET_TIME_Relative latency,
3161 unsigned int distance)
3163 struct Neighbour *n;
3164 struct GNUNET_TIME_Absolute now;
3165 struct ConnectNotifyMessage cnm;
3167 n = find_neighbour (peer);
3170 if (n->is_connected)
3172 /* duplicate connect notification!? */
3179 n = create_neighbour (peer);
3181 now = GNUNET_TIME_absolute_get ();
3182 n->is_connected = GNUNET_YES;
3183 n->last_latency = latency;
3184 n->last_distance = distance;
3185 n->last_asw_update = now;
3186 n->last_arw_update = now;
3188 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3189 "Received connection from `%4s'.\n",
3190 GNUNET_i2s (&n->peer));
3192 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3193 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3194 cnm.distance = htonl (n->last_distance);
3195 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3197 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3203 * Function called by transport telling us that a peer
3206 * @param cls closure
3207 * @param peer the peer that disconnected
3210 handle_transport_notify_disconnect (void *cls,
3211 const struct GNUNET_PeerIdentity *peer)
3213 struct DisconnectNotifyMessage cnm;
3214 struct Neighbour *n;
3217 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3218 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3220 n = find_neighbour (peer);
3226 GNUNET_break (n->is_connected);
3227 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3228 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3230 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3231 n->is_connected = GNUNET_NO;
3236 * Last task run during shutdown. Disconnects us from
3240 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3242 struct Neighbour *n;
3246 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3247 "Core service shutting down.\n");
3249 GNUNET_assert (transport != NULL);
3250 GNUNET_TRANSPORT_disconnect (transport);
3252 while (NULL != (n = neighbours))
3254 neighbours = n->next;
3255 GNUNET_assert (neighbour_count > 0);
3259 GNUNET_SERVER_notification_context_destroy (notifier);
3261 while (NULL != (c = clients))
3262 handle_client_disconnect (NULL, c->client_handle);
3263 if (my_private_key != NULL)
3264 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3269 * Initiate core service.
3271 * @param cls closure
3272 * @param s scheduler to use
3273 * @param serv the initialized server
3274 * @param c configuration to use
3278 struct GNUNET_SCHEDULER_Handle *s,
3279 struct GNUNET_SERVER_Handle *serv,
3280 const struct GNUNET_CONFIGURATION_Handle *c)
3283 unsigned long long qin;
3284 unsigned long long qout;
3285 unsigned long long tneigh;
3291 /* parse configuration */
3294 GNUNET_CONFIGURATION_get_value_number (c,
3297 &bandwidth_target_in)) ||
3299 GNUNET_CONFIGURATION_get_value_number (c,
3302 &bandwidth_target_out)) ||
3304 GNUNET_CONFIGURATION_get_value_filename (c,
3306 "HOSTKEY", &keyfile)))
3308 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3310 ("Core service is lacking key configuration settings. Exiting.\n"));
3311 GNUNET_SCHEDULER_shutdown (s);
3314 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3315 GNUNET_free (keyfile);
3316 if (my_private_key == NULL)
3318 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3319 _("Core service could not access hostkey. Exiting.\n"));
3320 GNUNET_SCHEDULER_shutdown (s);
3323 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3324 GNUNET_CRYPTO_hash (&my_public_key,
3325 sizeof (my_public_key), &my_identity.hashPubKey);
3326 /* setup notification */
3328 notifier = GNUNET_SERVER_notification_context_create (server,
3330 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3331 /* setup transport connection */
3332 transport = GNUNET_TRANSPORT_connect (sched,
3335 &handle_transport_receive,
3336 &handle_transport_notify_connect,
3337 &handle_transport_notify_disconnect);
3338 GNUNET_assert (NULL != transport);
3339 GNUNET_SCHEDULER_add_delayed (sched,
3340 GNUNET_TIME_UNIT_FOREVER_REL,
3341 &cleaning_task, NULL);
3342 /* process client requests */
3343 GNUNET_SERVER_add_handlers (server, handlers);
3344 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3345 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3351 * The main function for the transport service.
3353 * @param argc number of arguments from the command line
3354 * @param argv command line arguments
3355 * @return 0 ok, 1 on error
3358 main (int argc, char *const *argv)
3360 return (GNUNET_OK ==
3361 GNUNET_SERVICE_run (argc,
3364 GNUNET_SERVICE_OPTION_NONE,
3365 &run, NULL)) ? 0 : 1;
3368 /* end of gnunet-service-core.c */