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;
2048 struct GNUNET_MessageHeader hdr;
2051 hdr.type = htons (GNUNET_MESSAGE_TYPE_TOPOLOGY_DUMMY);
2052 hdr.size = htons (sizeof(hdr));
2053 memcpy (buf, &hdr, sizeof (hdr));
2054 return sizeof (hdr);
2059 * Handle CORE_REQUEST_CONNECT request.
2062 * @param client the client issuing the request
2063 * @param message the "struct ConnectMessage"
2066 handle_client_request_connect (void *cls,
2067 struct GNUNET_SERVER_Client *client,
2068 const struct GNUNET_MessageHeader *message)
2070 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2071 struct Neighbour *n;
2072 struct GNUNET_TIME_Relative timeout;
2074 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2075 n = find_neighbour (&cm->peer);
2077 n = create_neighbour (&cm->peer);
2078 if ( (n->is_connected) ||
2080 return; /* already connected, or at least trying */
2082 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2083 "Core received `%s' request for `%4s', will try to establish connection\n",
2085 GNUNET_i2s (&cm->peer));
2087 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2088 /* ask transport to connect to the peer */
2089 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2091 sizeof (struct GNUNET_MessageHeader), 0,
2093 ¬ify_transport_connect_done,
2095 GNUNET_break (NULL != n->th);
2100 * List of handlers for the messages understood by this
2103 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2104 {&handle_client_init, NULL,
2105 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2106 {&handle_client_request_info, NULL,
2107 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2108 sizeof (struct RequestInfoMessage)},
2109 {&handle_client_send, NULL,
2110 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2111 {&handle_client_request_connect, NULL,
2112 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2113 sizeof (struct ConnectMessage)},
2119 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2120 * the neighbour's struct and retry send_key. Or, if we did not get a
2121 * HELLO, just do nothing.
2123 * @param cls the 'struct Neighbour' to retry sending the key for
2124 * @param peer the peer for which this is the HELLO
2125 * @param hello HELLO message of that peer
2126 * @param trust amount of trust we currently have in that peer
2129 process_hello_retry_send_key (void *cls,
2130 const struct GNUNET_PeerIdentity *peer,
2131 const struct GNUNET_HELLO_Message *hello,
2134 struct Neighbour *n = cls;
2139 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2140 "Entered `process_hello_retry_send_key' and `peer' is NULL!\n");
2143 if (n->public_key != NULL)
2149 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2150 n->retry_set_key_task
2151 = GNUNET_SCHEDULER_add_delayed (sched,
2152 n->set_key_retry_frequency,
2153 &set_key_retry_task, n);
2159 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2160 "Entered `process_hello_retry_send_key' for peer `%4s'\n",
2163 if (n->public_key != NULL)
2166 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2167 "already have public key for peer %s!! (so why are we here?)\n",
2174 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2175 "Received new `%s' message for `%4s', initiating key exchange.\n",
2180 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2181 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2183 GNUNET_free (n->public_key);
2184 n->public_key = NULL;
2186 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2187 "GNUNET_HELLO_get_key returned awfully\n");
2195 * Send our key (and encrypted PING) to the other peer.
2197 * @param n the other peer
2200 send_key (struct Neighbour *n)
2202 struct SetKeyMessage *sm;
2203 struct MessageEntry *me;
2204 struct PingMessage pp;
2205 struct PingMessage *pm;
2207 if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2211 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2212 "Key exchange in progress with `%4s'.\n",
2213 GNUNET_i2s (&n->peer));
2215 return; /* already in progress */
2219 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2220 "Asked to perform key exchange with `%4s'.\n",
2221 GNUNET_i2s (&n->peer));
2223 if (n->public_key == NULL)
2225 /* lookup n's public key, then try again */
2227 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2228 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2229 GNUNET_i2s (&n->peer));
2231 GNUNET_assert (n->pitr == NULL);
2232 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2236 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2237 &process_hello_retry_send_key, n);
2240 /* first, set key message */
2241 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2242 sizeof (struct SetKeyMessage));
2243 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2244 me->priority = SET_KEY_PRIORITY;
2245 me->size = sizeof (struct SetKeyMessage);
2246 if (n->encrypted_head == NULL)
2247 n->encrypted_head = me;
2249 n->encrypted_tail->next = me;
2250 n->encrypted_tail = me;
2251 sm = (struct SetKeyMessage *) &me[1];
2252 sm->header.size = htons (sizeof (struct SetKeyMessage));
2253 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2254 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2255 PEER_STATE_KEY_SENT : n->status));
2257 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2258 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2259 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2260 sizeof (struct GNUNET_PeerIdentity));
2261 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2262 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2263 sm->target = n->peer;
2264 GNUNET_assert (GNUNET_OK ==
2265 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2267 GNUNET_CRYPTO_AesSessionKey),
2269 &sm->encrypted_key));
2270 GNUNET_assert (GNUNET_OK ==
2271 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2274 /* second, encrypted PING message */
2275 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2276 sizeof (struct PingMessage));
2277 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2278 me->priority = PING_PRIORITY;
2279 me->size = sizeof (struct PingMessage);
2280 n->encrypted_tail->next = me;
2281 n->encrypted_tail = me;
2282 pm = (struct PingMessage *) &me[1];
2283 pm->header.size = htons (sizeof (struct PingMessage));
2284 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2285 pp.challenge = htonl (n->ping_challenge);
2286 pp.target = n->peer;
2288 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2289 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2290 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2291 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2292 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2294 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2297 &n->peer.hashPubKey,
2300 sizeof (struct PingMessage) -
2301 sizeof (struct GNUNET_MessageHeader));
2305 case PEER_STATE_DOWN:
2306 n->status = PEER_STATE_KEY_SENT;
2308 case PEER_STATE_KEY_SENT:
2310 case PEER_STATE_KEY_RECEIVED:
2312 case PEER_STATE_KEY_CONFIRMED:
2319 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2320 "Have %llu ms left for `%s' transmission.\n",
2321 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2324 /* trigger queue processing */
2325 process_encrypted_neighbour_queue (n);
2326 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2327 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2328 n->retry_set_key_task
2329 = GNUNET_SCHEDULER_add_delayed (sched,
2330 n->set_key_retry_frequency,
2331 &set_key_retry_task, n);
2336 * We received a SET_KEY message. Validate and update
2337 * our key material and status.
2339 * @param n the neighbour from which we received message m
2340 * @param m the set key message we received
2343 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2347 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2348 * the neighbour's struct and retry handling the set_key message. Or,
2349 * if we did not get a HELLO, just free the set key message.
2351 * @param cls pointer to the set key message
2352 * @param peer the peer for which this is the HELLO
2353 * @param hello HELLO message of that peer
2354 * @param trust amount of trust we currently have in that peer
2357 process_hello_retry_handle_set_key (void *cls,
2358 const struct GNUNET_PeerIdentity *peer,
2359 const struct GNUNET_HELLO_Message *hello,
2362 struct Neighbour *n = cls;
2363 struct SetKeyMessage *sm = n->skm;
2372 if (n->public_key != NULL)
2373 return; /* multiple HELLOs match!? */
2375 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2376 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2378 GNUNET_break_op (0);
2379 GNUNET_free (n->public_key);
2380 n->public_key = NULL;
2384 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2385 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2386 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2388 handle_set_key (n, sm);
2393 * We received a PING message. Validate and transmit
2396 * @param n sender of the PING
2397 * @param m the encrypted PING message itself
2400 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2402 struct PingMessage t;
2403 struct PingMessage *tp;
2404 struct MessageEntry *me;
2407 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2408 "Core service receives `%s' request from `%4s'.\n",
2409 "PING", GNUNET_i2s (&n->peer));
2413 &my_identity.hashPubKey,
2416 sizeof (struct PingMessage) -
2417 sizeof (struct GNUNET_MessageHeader)))
2420 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2421 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2423 GNUNET_i2s (&t.target),
2424 ntohl (t.challenge), n->decrypt_key.crc32);
2425 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2426 "Target of `%s' request is `%4s'.\n",
2427 "PING", GNUNET_i2s (&t.target));
2429 if (0 != memcmp (&t.target,
2430 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2432 GNUNET_break_op (0);
2435 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2436 sizeof (struct PingMessage));
2437 if (n->encrypted_tail != NULL)
2438 n->encrypted_tail->next = me;
2441 n->encrypted_tail = me;
2442 n->encrypted_head = me;
2444 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2445 me->priority = PONG_PRIORITY;
2446 me->size = sizeof (struct PingMessage);
2447 tp = (struct PingMessage *) &me[1];
2448 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2449 tp->header.size = htons (sizeof (struct PingMessage));
2451 &my_identity.hashPubKey,
2454 sizeof (struct PingMessage) -
2455 sizeof (struct GNUNET_MessageHeader));
2457 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2458 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2459 ntohl (t.challenge), n->encrypt_key.crc32);
2461 /* trigger queue processing */
2462 process_encrypted_neighbour_queue (n);
2467 * We received a PONG message. Validate and update our status.
2469 * @param n sender of the PONG
2470 * @param m the encrypted PONG message itself
2473 handle_pong (struct Neighbour *n, const struct PingMessage *m)
2475 struct PingMessage t;
2476 struct ConnectNotifyMessage cnm;
2479 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2480 "Core service receives `%s' request from `%4s'.\n",
2481 "PONG", GNUNET_i2s (&n->peer));
2485 &n->peer.hashPubKey,
2488 sizeof (struct PingMessage) -
2489 sizeof (struct GNUNET_MessageHeader)))
2492 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2493 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2495 GNUNET_i2s (&t.target),
2496 ntohl (t.challenge), n->decrypt_key.crc32);
2498 if ((0 != memcmp (&t.target,
2500 sizeof (struct GNUNET_PeerIdentity))) ||
2501 (n->ping_challenge != ntohl (t.challenge)))
2503 /* PONG malformed */
2505 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2506 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2507 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2508 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2509 "Received malformed `%s' received from `%4s' with challenge %u\n",
2510 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2512 GNUNET_break_op (0);
2517 case PEER_STATE_DOWN:
2518 GNUNET_break (0); /* should be impossible */
2520 case PEER_STATE_KEY_SENT:
2521 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2523 case PEER_STATE_KEY_RECEIVED:
2524 n->status = PEER_STATE_KEY_CONFIRMED;
2526 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2527 "Confirmed key via `%s' message for peer `%4s'\n",
2528 "PONG", GNUNET_i2s (&n->peer));
2530 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2532 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2533 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2535 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2536 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2537 cnm.distance = htonl (n->last_distance);
2538 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2540 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2541 process_encrypted_neighbour_queue (n);
2543 case PEER_STATE_KEY_CONFIRMED:
2544 /* duplicate PONG? */
2554 * We received a SET_KEY message. Validate and update
2555 * our key material and status.
2557 * @param n the neighbour from which we received message m
2558 * @param m the set key message we received
2561 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2563 struct SetKeyMessage *m_cpy;
2564 struct GNUNET_TIME_Absolute t;
2565 struct GNUNET_CRYPTO_AesSessionKey k;
2566 struct PingMessage *ping;
2567 struct PingMessage *pong;
2568 enum PeerStateMachine sender_status;
2571 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2572 "Core service receives `%s' request from `%4s'.\n",
2573 "SET_KEY", GNUNET_i2s (&n->peer));
2575 if (n->public_key == NULL)
2577 if (n->pitr != NULL)
2580 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2581 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2587 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2588 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2590 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2591 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2592 /* lookup n's public key, then try again */
2593 GNUNET_assert (n->skm == NULL);
2595 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2599 GNUNET_TIME_UNIT_MINUTES,
2600 &process_hello_retry_handle_set_key, n);
2603 if (0 != memcmp (&m->target,
2605 sizeof (struct GNUNET_PeerIdentity)))
2607 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2608 _("Received `%s' message that was not for me. Ignoring.\n"),
2612 if ((ntohl (m->purpose.size) !=
2613 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2614 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2615 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2616 sizeof (struct GNUNET_PeerIdentity)) ||
2618 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2619 &m->purpose, &m->signature, n->public_key)))
2621 /* invalid signature */
2622 GNUNET_break_op (0);
2625 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2626 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2627 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2628 (t.value < n->decrypt_key_created.value))
2630 /* this could rarely happen due to massive re-ordering of
2631 messages on the network level, but is most likely either
2632 a bug or some adversary messing with us. Report. */
2633 GNUNET_break_op (0);
2637 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
2639 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2642 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2643 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2644 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2646 /* failed to decrypt !? */
2647 GNUNET_break_op (0);
2652 if (n->decrypt_key_created.value != t.value)
2654 /* fresh key, reset sequence numbers */
2655 n->last_sequence_number_received = 0;
2656 n->last_packets_bitmap = 0;
2657 n->decrypt_key_created = t;
2659 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2662 case PEER_STATE_DOWN:
2663 n->status = PEER_STATE_KEY_RECEIVED;
2665 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2666 "Responding to `%s' with my own key.\n", "SET_KEY");
2670 case PEER_STATE_KEY_SENT:
2671 case PEER_STATE_KEY_RECEIVED:
2672 n->status = PEER_STATE_KEY_RECEIVED;
2673 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2674 (sender_status != PEER_STATE_KEY_CONFIRMED))
2677 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2678 "Responding to `%s' with my own key (other peer has status %u).\n",
2679 "SET_KEY", sender_status);
2684 case PEER_STATE_KEY_CONFIRMED:
2685 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2686 (sender_status != PEER_STATE_KEY_CONFIRMED))
2689 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2690 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2691 "SET_KEY", sender_status);
2700 if (n->pending_ping != NULL)
2702 ping = n->pending_ping;
2703 n->pending_ping = NULL;
2704 handle_ping (n, ping);
2707 if (n->pending_pong != NULL)
2709 pong = n->pending_pong;
2710 n->pending_pong = NULL;
2711 handle_pong (n, pong);
2718 * Send a P2P message to a client.
2720 * @param sender who sent us the message?
2721 * @param client who should we give the message to?
2722 * @param m contains the message to transmit
2723 * @param msize number of bytes in buf to transmit
2726 send_p2p_message_to_client (struct Neighbour *sender,
2727 struct Client *client,
2728 const void *m, size_t msize)
2730 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2731 struct NotifyTrafficMessage *ntm;
2734 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2735 "Core service passes message from `%4s' of type %u to client.\n",
2736 GNUNET_i2s(&sender->peer),
2737 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2739 ntm = (struct NotifyTrafficMessage *) buf;
2740 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2741 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2742 ntm->distance = htonl (sender->last_distance);
2743 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
2744 ntm->peer = sender->peer;
2745 memcpy (&ntm[1], m, msize);
2746 send_to_client (client, &ntm->header, GNUNET_YES);
2751 * Deliver P2P message to interested clients.
2753 * @param sender who sent us the message?
2754 * @param m the message
2755 * @param msize size of the message (including header)
2758 deliver_message (struct Neighbour *sender,
2759 const struct GNUNET_MessageHeader *m, size_t msize)
2761 struct Client *cpos;
2766 type = ntohs (m->type);
2769 "Received encapsulated message of type %u from `%4s'\n",
2771 GNUNET_i2s (&sender->peer));
2774 while (cpos != NULL)
2776 deliver_full = GNUNET_NO;
2777 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
2778 deliver_full = GNUNET_YES;
2781 for (tpos = 0; tpos < cpos->tcnt; tpos++)
2783 if (type != cpos->types[tpos])
2785 deliver_full = GNUNET_YES;
2789 if (GNUNET_YES == deliver_full)
2790 send_p2p_message_to_client (sender, cpos, m, msize);
2791 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2792 send_p2p_message_to_client (sender, cpos, m,
2793 sizeof (struct GNUNET_MessageHeader));
2800 * Align P2P message and then deliver to interested clients.
2802 * @param sender who sent us the message?
2803 * @param buffer unaligned (!) buffer containing message
2804 * @param msize size of the message (including header)
2807 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
2811 /* TODO: call to statistics? */
2812 memcpy (abuf, buffer, msize);
2813 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
2818 * Deliver P2P messages to interested clients.
2820 * @param sender who sent us the message?
2821 * @param buffer buffer containing messages, can be modified
2822 * @param buffer_size size of the buffer (overall)
2823 * @param offset offset where messages in the buffer start
2826 deliver_messages (struct Neighbour *sender,
2827 const char *buffer, size_t buffer_size, size_t offset)
2829 struct GNUNET_MessageHeader *mhp;
2830 struct GNUNET_MessageHeader mh;
2834 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
2836 if (0 != offset % sizeof (uint16_t))
2838 /* outch, need to copy to access header */
2839 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
2844 /* can access header directly */
2845 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
2847 msize = ntohs (mhp->size);
2848 if (msize + offset > buffer_size)
2850 /* malformed message, header says it is larger than what
2851 would fit into the overall buffer */
2852 GNUNET_break_op (0);
2855 #if HAVE_UNALIGNED_64_ACCESS
2856 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
2858 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
2860 if (GNUNET_YES == need_align)
2861 align_and_deliver (sender, &buffer[offset], msize);
2863 deliver_message (sender,
2864 (const struct GNUNET_MessageHeader *)
2865 &buffer[offset], msize);
2872 * We received an encrypted message. Decrypt, validate and
2873 * pass on to the appropriate clients.
2876 handle_encrypted_message (struct Neighbour *n,
2877 const struct EncryptedMessage *m)
2879 size_t size = ntohs (m->header.size);
2881 struct EncryptedMessage *pt; /* plaintext */
2885 struct GNUNET_TIME_Absolute t;
2888 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2889 "Core service receives `%s' request from `%4s'.\n",
2890 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
2896 &m->sequence_number,
2897 &buf[ENCRYPTED_HEADER_SIZE], size - ENCRYPTED_HEADER_SIZE))
2899 pt = (struct EncryptedMessage *) buf;
2902 GNUNET_CRYPTO_hash (&pt->sequence_number,
2903 size - ENCRYPTED_HEADER_SIZE, &ph);
2904 if (0 != memcmp (&ph, &m->plaintext_hash, sizeof (GNUNET_HashCode)))
2906 /* checksum failed */
2907 GNUNET_break_op (0);
2911 /* validate sequence number */
2912 snum = ntohl (pt->sequence_number);
2913 if (n->last_sequence_number_received == snum)
2915 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2916 "Received duplicate message, ignoring.\n");
2917 /* duplicate, ignore */
2920 if ((n->last_sequence_number_received > snum) &&
2921 (n->last_sequence_number_received - snum > 32))
2923 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2924 "Received ancient out of sequence message, ignoring.\n");
2925 /* ancient out of sequence, ignore */
2928 if (n->last_sequence_number_received > snum)
2930 unsigned int rotbit =
2931 1 << (n->last_sequence_number_received - snum - 1);
2932 if ((n->last_packets_bitmap & rotbit) != 0)
2934 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2935 "Received duplicate message, ignoring.\n");
2936 /* duplicate, ignore */
2939 n->last_packets_bitmap |= rotbit;
2941 if (n->last_sequence_number_received < snum)
2943 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
2944 n->last_sequence_number_received = snum;
2947 /* check timestamp */
2948 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
2949 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
2951 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2953 ("Message received far too old (%llu ms). Content ignored.\n"),
2954 GNUNET_TIME_absolute_get_duration (t).value);
2958 /* process decrypted message(s) */
2959 update_window (GNUNET_YES,
2960 &n->available_send_window,
2961 &n->last_asw_update,
2963 n->bpm_out_external_limit = ntohl (pt->inbound_bpm_limit);
2964 n->bpm_out = GNUNET_MAX (n->bpm_out_external_limit,
2965 n->bpm_out_internal_limit);
2966 n->last_activity = GNUNET_TIME_absolute_get ();
2967 off = sizeof (struct EncryptedMessage);
2968 deliver_messages (n, buf, size, off);
2973 * Function called by the transport for each received message.
2975 * @param cls closure
2976 * @param peer (claimed) identity of the other peer
2977 * @param message the message
2978 * @param latency estimated latency for communicating with the
2979 * given peer (round-trip)
2980 * @param distance in overlay hops, as given by transport plugin
2983 handle_transport_receive (void *cls,
2984 const struct GNUNET_PeerIdentity *peer,
2985 const struct GNUNET_MessageHeader *message,
2986 struct GNUNET_TIME_Relative latency,
2987 unsigned int distance)
2989 struct Neighbour *n;
2990 struct GNUNET_TIME_Absolute now;
2996 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2997 "Received message of type %u from `%4s', demultiplexing.\n",
2998 ntohs (message->type), GNUNET_i2s (peer));
3000 n = find_neighbour (peer);
3002 n = create_neighbour (peer);
3005 n->last_latency = latency;
3006 n->last_distance = distance;
3007 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3008 type = ntohs (message->type);
3009 size = ntohs (message->size);
3012 "Received message of type %u from `%4s'\n",
3018 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3019 if (size != sizeof (struct SetKeyMessage))
3021 GNUNET_break_op (0);
3024 handle_set_key (n, (const struct SetKeyMessage *) message);
3026 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3027 if (size < sizeof (struct EncryptedMessage) +
3028 sizeof (struct GNUNET_MessageHeader))
3030 GNUNET_break_op (0);
3033 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3034 (n->status != PEER_STATE_KEY_CONFIRMED))
3036 GNUNET_break_op (0);
3039 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3041 case GNUNET_MESSAGE_TYPE_CORE_PING:
3042 if (size != sizeof (struct PingMessage))
3044 GNUNET_break_op (0);
3047 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3048 (n->status != PEER_STATE_KEY_CONFIRMED))
3051 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3052 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3053 "PING", GNUNET_i2s (&n->peer));
3055 GNUNET_free_non_null (n->pending_ping);
3056 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3057 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3060 handle_ping (n, (const struct PingMessage *) message);
3062 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3063 if (size != sizeof (struct PingMessage))
3065 GNUNET_break_op (0);
3068 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3069 (n->status != PEER_STATE_KEY_CONFIRMED) )
3072 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3073 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3074 "PONG", GNUNET_i2s (&n->peer));
3076 GNUNET_free_non_null (n->pending_pong);
3077 n->pending_pong = GNUNET_malloc (sizeof (struct PingMessage));
3078 memcpy (n->pending_pong, message, sizeof (struct PingMessage));
3081 handle_pong (n, (const struct PingMessage *) message);
3084 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3085 _("Unsupported message of type %u received.\n"), type);
3088 if (n->status == PEER_STATE_KEY_CONFIRMED)
3090 now = GNUNET_TIME_absolute_get ();
3091 n->last_activity = now;
3093 n->time_established = now;
3099 * Function that recalculates the bandwidth quota for the
3100 * given neighbour and transmits it to the transport service.
3102 * @param cls neighbour for the quota update
3106 neighbour_quota_update (void *cls,
3107 const struct GNUNET_SCHEDULER_TaskContext *tc)
3109 struct Neighbour *n = cls;
3113 unsigned long long distributable;
3115 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3116 /* calculate relative preference among all neighbours;
3117 divides by a bit more to avoid division by zero AND to
3118 account for possibility of new neighbours joining any time
3119 AND to convert to double... */
3120 pref_rel = n->current_preference / (1.0 + preference_sum);
3122 if (bandwidth_target_out > neighbour_count * MIN_BPM_PER_PEER)
3123 distributable = bandwidth_target_out - neighbour_count * MIN_BPM_PER_PEER;
3124 share = distributable * pref_rel;
3125 q_in = MIN_BPM_PER_PEER + (unsigned long long) share;
3126 /* check if we want to disconnect for good due to inactivity */
3127 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3128 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3131 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3132 "Forcing disconnect of `%4s' due to inactivity (?).\n",
3133 GNUNET_i2s (&n->peer));
3135 q_in = 0; /* force disconnect */
3137 if ( (n->bpm_in + MIN_BPM_CHANGE < q_in) ||
3138 (n->bpm_in - MIN_BPM_CHANGE > q_in) )
3141 GNUNET_TRANSPORT_set_quota (transport,
3145 GNUNET_TIME_UNIT_FOREVER_REL,
3148 schedule_quota_update (n);
3153 * Function called by transport to notify us that
3154 * a peer connected to us (on the network level).
3156 * @param cls closure
3157 * @param peer the peer that connected
3158 * @param latency current latency of the connection
3159 * @param distance in overlay hops, as given by transport plugin
3162 handle_transport_notify_connect (void *cls,
3163 const struct GNUNET_PeerIdentity *peer,
3164 struct GNUNET_TIME_Relative latency,
3165 unsigned int distance)
3167 struct Neighbour *n;
3168 struct GNUNET_TIME_Absolute now;
3169 struct ConnectNotifyMessage cnm;
3171 n = find_neighbour (peer);
3174 if (n->is_connected)
3176 /* duplicate connect notification!? */
3183 n = create_neighbour (peer);
3185 now = GNUNET_TIME_absolute_get ();
3186 n->is_connected = GNUNET_YES;
3187 n->last_latency = latency;
3188 n->last_distance = distance;
3189 n->last_asw_update = now;
3190 n->last_arw_update = now;
3192 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3193 "Received connection from `%4s'.\n",
3194 GNUNET_i2s (&n->peer));
3196 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3197 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3198 cnm.distance = htonl (n->last_distance);
3199 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3201 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3207 * Function called by transport telling us that a peer
3210 * @param cls closure
3211 * @param peer the peer that disconnected
3214 handle_transport_notify_disconnect (void *cls,
3215 const struct GNUNET_PeerIdentity *peer)
3217 struct DisconnectNotifyMessage cnm;
3218 struct Neighbour *n;
3221 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3222 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3224 n = find_neighbour (peer);
3230 GNUNET_break (n->is_connected);
3231 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3232 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3234 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3235 n->is_connected = GNUNET_NO;
3240 * Last task run during shutdown. Disconnects us from
3244 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3246 struct Neighbour *n;
3250 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3251 "Core service shutting down.\n");
3253 GNUNET_assert (transport != NULL);
3254 GNUNET_TRANSPORT_disconnect (transport);
3256 while (NULL != (n = neighbours))
3258 neighbours = n->next;
3259 GNUNET_assert (neighbour_count > 0);
3263 GNUNET_SERVER_notification_context_destroy (notifier);
3265 while (NULL != (c = clients))
3266 handle_client_disconnect (NULL, c->client_handle);
3267 if (my_private_key != NULL)
3268 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3273 * Initiate core service.
3275 * @param cls closure
3276 * @param s scheduler to use
3277 * @param serv the initialized server
3278 * @param c configuration to use
3282 struct GNUNET_SCHEDULER_Handle *s,
3283 struct GNUNET_SERVER_Handle *serv,
3284 const struct GNUNET_CONFIGURATION_Handle *c)
3287 unsigned long long qin;
3288 unsigned long long qout;
3289 unsigned long long tneigh;
3295 /* parse configuration */
3298 GNUNET_CONFIGURATION_get_value_number (c,
3301 &bandwidth_target_in)) ||
3303 GNUNET_CONFIGURATION_get_value_number (c,
3306 &bandwidth_target_out)) ||
3308 GNUNET_CONFIGURATION_get_value_filename (c,
3310 "HOSTKEY", &keyfile)))
3312 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3314 ("Core service is lacking key configuration settings. Exiting.\n"));
3315 GNUNET_SCHEDULER_shutdown (s);
3318 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3319 GNUNET_free (keyfile);
3320 if (my_private_key == NULL)
3322 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3323 _("Core service could not access hostkey. Exiting.\n"));
3324 GNUNET_SCHEDULER_shutdown (s);
3327 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3328 GNUNET_CRYPTO_hash (&my_public_key,
3329 sizeof (my_public_key), &my_identity.hashPubKey);
3330 /* setup notification */
3332 notifier = GNUNET_SERVER_notification_context_create (server,
3334 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3335 /* setup transport connection */
3336 transport = GNUNET_TRANSPORT_connect (sched,
3339 &handle_transport_receive,
3340 &handle_transport_notify_connect,
3341 &handle_transport_notify_disconnect);
3342 GNUNET_assert (NULL != transport);
3343 GNUNET_SCHEDULER_add_delayed (sched,
3344 GNUNET_TIME_UNIT_FOREVER_REL,
3345 &cleaning_task, NULL);
3346 /* process client requests */
3347 GNUNET_SERVER_add_handlers (server, handlers);
3348 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3349 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3355 * The main function for the transport service.
3357 * @param argc number of arguments from the command line
3358 * @param argv command line arguments
3359 * @return 0 ok, 1 on error
3362 main (int argc, char *const *argv)
3364 return (GNUNET_OK ==
3365 GNUNET_SERVICE_run (argc,
3368 GNUNET_SERVICE_OPTION_NONE,
3369 &run, NULL)) ? 0 : 1;
3372 /* end of gnunet-service-core.c */