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;
1028 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1029 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1030 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1031 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1032 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1033 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1034 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1035 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1036 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1037 GNUNET_free_non_null (n->public_key);
1038 GNUNET_free_non_null (n->pending_ping);
1039 GNUNET_free_non_null (n->pending_pong);
1045 * Consider freeing the given neighbour since we may not need
1046 * to keep it around anymore.
1048 * @param n neighbour to consider discarding
1051 consider_free_neighbour (struct Neighbour *n);
1055 * Task triggered when a neighbour entry might have gotten stale.
1057 * @param cls the 'struct Neighbour'
1058 * @param tc scheduler context (not used)
1061 consider_free_task (void *cls,
1062 const struct GNUNET_SCHEDULER_TaskContext *tc)
1064 struct Neighbour *n = cls;
1065 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1066 consider_free_neighbour (n);
1071 * Consider freeing the given neighbour since we may not need
1072 * to keep it around anymore.
1074 * @param n neighbour to consider discarding
1077 consider_free_neighbour (struct Neighbour *n)
1079 struct Neighbour *pos;
1080 struct Neighbour *prev;
1081 struct GNUNET_TIME_Relative left;
1083 if ( (n->th != NULL) ||
1084 (n->pitr != NULL) ||
1085 (n->status == PEER_STATE_KEY_CONFIRMED) ||
1086 (GNUNET_YES == n->is_connected) )
1087 return; /* no chance */
1089 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1093 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1094 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1095 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1097 &consider_free_task,
1101 /* actually free the neighbour... */
1110 neighbours = n->next;
1112 prev->next = n->next;
1113 GNUNET_assert (neighbour_count > 0);
1120 * Check if we have encrypted messages for the specified neighbour
1121 * pending, and if so, check with the transport about sending them
1124 * @param n neighbour to check.
1126 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1130 * Function called when the transport service is ready to
1131 * receive an encrypted message for the respective peer
1133 * @param cls neighbour to use message from
1134 * @param size number of bytes we can transmit
1135 * @param buf where to copy the message
1136 * @return number of bytes transmitted
1139 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1141 struct Neighbour *n = cls;
1142 struct MessageEntry *m;
1147 GNUNET_assert (NULL != (m = n->encrypted_head));
1148 n->encrypted_head = m->next;
1149 if (m->next == NULL)
1150 n->encrypted_tail = NULL;
1155 GNUNET_assert (size >= m->size);
1156 memcpy (cbuf, &m[1], m->size);
1158 n->available_send_window -= m->size;
1159 process_encrypted_neighbour_queue (n);
1162 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1163 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1164 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1165 ret, GNUNET_i2s (&n->peer));
1170 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1171 "Transmission of message of type %u and size %u failed\n",
1172 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1176 consider_free_neighbour (n);
1182 * Check if we have plaintext messages for the specified neighbour
1183 * pending, and if so, consider batching and encrypting them (and
1184 * then trigger processing of the encrypted queue if needed).
1186 * @param n neighbour to check.
1188 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1192 * Check if we have encrypted messages for the specified neighbour
1193 * pending, and if so, check with the transport about sending them
1196 * @param n neighbour to check.
1199 process_encrypted_neighbour_queue (struct Neighbour *n)
1201 struct MessageEntry *m;
1204 return; /* request already pending */
1205 if (n->encrypted_head == NULL)
1207 /* encrypted queue empty, try plaintext instead */
1208 process_plaintext_neighbour_queue (n);
1212 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1213 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1214 n->encrypted_head->size,
1215 GNUNET_i2s (&n->peer),
1216 GNUNET_TIME_absolute_get_remaining (n->
1217 encrypted_head->deadline).
1221 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1222 n->encrypted_head->size,
1223 n->encrypted_head->priority,
1224 GNUNET_TIME_absolute_get_remaining
1225 (n->encrypted_head->deadline),
1226 ¬ify_encrypted_transmit_ready,
1230 /* message request too large or duplicate request */
1232 /* discard encrypted message */
1233 GNUNET_assert (NULL != (m = n->encrypted_head));
1234 n->encrypted_head = m->next;
1235 if (m->next == NULL)
1236 n->encrypted_tail = NULL;
1238 process_encrypted_neighbour_queue (n);
1244 * Decrypt size bytes from in and write the result to out. Use the
1245 * key for inbound traffic of the given neighbour. This function does
1246 * NOT do any integrity-checks on the result.
1248 * @param n neighbour we are receiving from
1249 * @param iv initialization vector to use
1250 * @param in ciphertext
1251 * @param out plaintext
1252 * @param size size of in/out
1253 * @return GNUNET_OK on success
1256 do_decrypt (struct Neighbour *n,
1257 const GNUNET_HashCode * iv,
1258 const void *in, void *out, size_t size)
1260 if (size != (uint16_t) size)
1265 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1266 (n->status != PEER_STATE_KEY_CONFIRMED))
1268 GNUNET_break_op (0);
1269 return GNUNET_SYSERR;
1272 GNUNET_CRYPTO_aes_decrypt (in,
1276 GNUNET_CRYPTO_AesInitializationVector *) iv,
1280 return GNUNET_SYSERR;
1283 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1284 "Decrypted %u bytes from `%4s' using key %u\n",
1285 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1292 * Encrypt size bytes from in and write the result to out. Use the
1293 * key for outbound traffic of the given neighbour.
1295 * @param n neighbour we are sending to
1296 * @param iv initialization vector to use
1297 * @param in ciphertext
1298 * @param out plaintext
1299 * @param size size of in/out
1300 * @return GNUNET_OK on success
1303 do_encrypt (struct Neighbour *n,
1304 const GNUNET_HashCode * iv,
1305 const void *in, void *out, size_t size)
1307 if (size != (uint16_t) size)
1312 GNUNET_assert (size ==
1313 GNUNET_CRYPTO_aes_encrypt (in,
1317 GNUNET_CRYPTO_AesInitializationVector
1320 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1321 "Encrypted %u bytes for `%4s' using key %u\n", size,
1322 GNUNET_i2s (&n->peer), n->encrypt_key.crc32);
1329 * Select messages for transmission. This heuristic uses a combination
1330 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1331 * and priority-based discard (in case no feasible schedule exist) and
1332 * speculative optimization (defer any kind of transmission until
1333 * we either create a batch of significant size, 25% of max, or until
1334 * we are close to a deadline). Furthermore, when scheduling the
1335 * heuristic also packs as many messages into the batch as possible,
1336 * starting with those with the earliest deadline. Yes, this is fun.
1338 * @param n neighbour to select messages from
1339 * @param size number of bytes to select for transmission
1340 * @param retry_time set to the time when we should try again
1341 * (only valid if this function returns zero)
1342 * @return number of bytes selected, or 0 if we decided to
1343 * defer scheduling overall; in that case, retry_time is set.
1346 select_messages (struct Neighbour *n,
1347 size_t size, struct GNUNET_TIME_Relative *retry_time)
1349 struct MessageEntry *pos;
1350 struct MessageEntry *min;
1351 struct MessageEntry *last;
1352 unsigned int min_prio;
1353 struct GNUNET_TIME_Absolute t;
1354 struct GNUNET_TIME_Absolute now;
1357 unsigned long long slack; /* how long could we wait before missing deadlines? */
1359 int discard_low_prio;
1361 GNUNET_assert (NULL != n->messages);
1362 now = GNUNET_TIME_absolute_get ();
1363 /* last entry in linked list of messages processed */
1365 /* should we remove the entry with the lowest
1366 priority from consideration for scheduling at the
1368 discard_low_prio = GNUNET_YES;
1369 while (GNUNET_YES == discard_low_prio)
1373 discard_low_prio = GNUNET_NO;
1374 /* calculate number of bytes available for transmission at time "t" */
1375 update_window (GNUNET_NO,
1376 &n->available_send_window,
1377 &n->last_asw_update,
1379 avail = n->available_send_window;
1380 t = n->last_asw_update;
1381 /* how many bytes have we (hypothetically) scheduled so far */
1383 /* maximum time we can wait before transmitting anything
1384 and still make all of our deadlines */
1388 /* note that we use "*2" here because we want to look
1389 a bit further into the future; much more makes no
1390 sense since new message might be scheduled in the
1392 while ((pos != NULL) && (off < size * 2))
1394 if (pos->do_transmit == GNUNET_YES)
1396 /* already removed from consideration */
1400 if (discard_low_prio == GNUNET_NO)
1402 delta = pos->deadline.value;
1403 if (delta < t.value)
1406 delta = t.value - delta;
1407 avail += delta * n->bpm_out / 1000 / 60;
1408 if (avail < pos->size)
1410 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1415 /* update slack, considering both its absolute deadline
1416 and relative deadlines caused by other messages
1417 with their respective load */
1418 slack = GNUNET_MIN (slack, avail / n->bpm_out);
1419 if ( (pos->deadline.value < now.value) ||
1420 (GNUNET_YES == pos->got_slack) )
1427 GNUNET_MIN (slack, pos->deadline.value - now.value);
1428 pos->got_slack = GNUNET_YES;
1434 t.value = GNUNET_MAX (pos->deadline.value, t.value);
1435 if (pos->priority <= min_prio)
1437 /* update min for discard */
1438 min_prio = pos->priority;
1443 if (discard_low_prio)
1445 GNUNET_assert (min != NULL);
1446 /* remove lowest-priority entry from consideration */
1447 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1451 /* guard against sending "tiny" messages with large headers without
1453 if ( (slack > 1000) && (size > 4 * off) )
1455 /* less than 25% of message would be filled with deadlines still
1456 being met if we delay by one second or more; so just wait for
1457 more data; but do not wait longer than 1s (since we don't want
1458 to delay messages for a really long time either). */
1459 retry_time->value = 1000;
1460 /* reset do_transmit values for next time */
1463 pos->do_transmit = GNUNET_NO;
1467 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1468 "Deferring transmission for 1s due to underfull message buffer size\n");
1472 /* select marked messages (up to size) for transmission */
1477 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1479 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1484 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1488 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1489 "Selected %u bytes of plaintext messages for transmission to `%4s'.\n",
1490 off, GNUNET_i2s (&n->peer));
1497 * Batch multiple messages into a larger buffer.
1499 * @param n neighbour to take messages from
1500 * @param buf target buffer
1501 * @param size size of buf
1502 * @param deadline set to transmission deadline for the result
1503 * @param retry_time set to the time when we should try again
1504 * (only valid if this function returns zero)
1505 * @param priority set to the priority of the batch
1506 * @return number of bytes written to buf (can be zero)
1509 batch_message (struct Neighbour *n,
1512 struct GNUNET_TIME_Absolute *deadline,
1513 struct GNUNET_TIME_Relative *retry_time,
1514 unsigned int *priority)
1516 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1517 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1518 struct MessageEntry *pos;
1519 struct MessageEntry *prev;
1520 struct MessageEntry *next;
1525 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1526 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1527 if (0 == select_messages (n, size, retry_time))
1529 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1530 "No messages selected, will try again in %llu ms\n",
1534 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1535 ntm->distance = htonl (n->last_distance);
1536 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1537 ntm->peer = n->peer;
1541 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1544 if (GNUNET_YES == pos->do_transmit)
1546 GNUNET_assert (pos->size <= size);
1547 /* do notifications */
1548 /* FIXME: track if we have *any* client that wants
1549 full notifications and only do this if that is
1551 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1553 memcpy (&ntm[1], &pos[1], pos->size);
1554 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1555 sizeof (struct GNUNET_MessageHeader));
1556 send_to_all_clients (&ntm->header,
1558 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1562 /* message too large for 'full' notifications, we do at
1563 least the 'hdr' type */
1566 sizeof (struct GNUNET_MessageHeader));
1568 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1570 send_to_all_clients (&ntm->header,
1572 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1575 "Encrypting message of type %u\n",
1576 ntohs(((struct GNUNET_MessageHeader*)&pos[1])->type));
1578 /* copy for encrypted transmission */
1579 memcpy (&buf[ret], &pos[1], pos->size);
1582 *priority += pos->priority;
1584 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1585 "Adding plaintext message with deadline %llu ms to batch\n",
1586 GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1588 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1602 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1603 "Deadline for message batch is %llu ms\n",
1604 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1611 * Remove messages with deadlines that have long expired from
1614 * @param n neighbour to inspect
1617 discard_expired_messages (struct Neighbour *n)
1619 struct MessageEntry *prev;
1620 struct MessageEntry *next;
1621 struct MessageEntry *pos;
1622 struct GNUNET_TIME_Absolute now;
1623 struct GNUNET_TIME_Relative delta;
1625 now = GNUNET_TIME_absolute_get ();
1631 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1632 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1635 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1636 "Message is %llu ms past due, discarding.\n",
1653 * Signature of the main function of a task.
1655 * @param cls closure
1656 * @param tc context information (why was this task triggered now)
1659 retry_plaintext_processing (void *cls,
1660 const struct GNUNET_SCHEDULER_TaskContext *tc)
1662 struct Neighbour *n = cls;
1664 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1665 process_plaintext_neighbour_queue (n);
1670 * Send our key (and encrypted PING) to the other peer.
1672 * @param n the other peer
1674 static void send_key (struct Neighbour *n);
1677 * Task that will retry "send_key" if our previous attempt failed
1681 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1683 struct Neighbour *n = cls;
1685 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1686 n->set_key_retry_frequency =
1687 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1693 * Check if we have plaintext messages for the specified neighbour
1694 * pending, and if so, consider batching and encrypting them (and
1695 * then trigger processing of the encrypted queue if needed).
1697 * @param n neighbour to check.
1700 process_plaintext_neighbour_queue (struct Neighbour *n)
1702 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1705 struct EncryptedMessage *em; /* encrypted message */
1706 struct EncryptedMessage *ph; /* plaintext header */
1707 struct MessageEntry *me;
1708 unsigned int priority;
1709 struct GNUNET_TIME_Absolute deadline;
1710 struct GNUNET_TIME_Relative retry_time;
1712 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1714 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1715 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1719 case PEER_STATE_DOWN:
1722 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1723 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1724 GNUNET_i2s(&n->peer));
1727 case PEER_STATE_KEY_SENT:
1728 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1729 n->retry_set_key_task
1730 = GNUNET_SCHEDULER_add_delayed (sched,
1731 n->set_key_retry_frequency,
1732 &set_key_retry_task, n);
1734 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1735 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1736 GNUNET_i2s(&n->peer));
1739 case PEER_STATE_KEY_RECEIVED:
1740 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1741 n->retry_set_key_task
1742 = GNUNET_SCHEDULER_add_delayed (sched,
1743 n->set_key_retry_frequency,
1744 &set_key_retry_task, n);
1746 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1747 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1748 GNUNET_i2s(&n->peer));
1751 case PEER_STATE_KEY_CONFIRMED:
1752 /* ready to continue */
1755 discard_expired_messages (n);
1756 if (n->messages == NULL)
1759 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1760 "Plaintext message queue for `%4s' is empty.\n",
1761 GNUNET_i2s(&n->peer));
1763 return; /* no pending messages */
1765 if (n->encrypted_head != NULL)
1768 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1769 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1770 GNUNET_i2s(&n->peer));
1772 return; /* wait for messages already encrypted to be
1775 ph = (struct EncryptedMessage *) pbuf;
1776 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1778 used = sizeof (struct EncryptedMessage);
1779 used += batch_message (n,
1781 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1782 &deadline, &retry_time, &priority);
1783 if (used == sizeof (struct EncryptedMessage))
1786 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1787 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1788 GNUNET_i2s(&n->peer));
1790 /* no messages selected for sending, try again later... */
1791 n->retry_plaintext_task =
1792 GNUNET_SCHEDULER_add_delayed (sched,
1794 &retry_plaintext_processing, n);
1797 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1798 ph->inbound_bpm_limit = htonl (n->bpm_in);
1799 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1801 /* setup encryption message header */
1802 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1803 me->deadline = deadline;
1804 me->priority = priority;
1806 em = (struct EncryptedMessage *) &me[1];
1807 em->header.size = htons (used);
1808 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1809 em->reserved = htonl (0);
1810 esize = used - ENCRYPTED_HEADER_SIZE;
1811 GNUNET_CRYPTO_hash (&ph->sequence_number, esize, &em->plaintext_hash);
1814 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1815 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
1817 GNUNET_i2s(&n->peer),
1818 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
1820 GNUNET_assert (GNUNET_OK ==
1822 &em->plaintext_hash,
1823 &ph->sequence_number,
1824 &em->sequence_number, esize));
1825 /* append to transmission list */
1826 if (n->encrypted_tail == NULL)
1827 n->encrypted_head = me;
1829 n->encrypted_tail->next = me;
1830 n->encrypted_tail = me;
1831 process_encrypted_neighbour_queue (n);
1836 * Function that recalculates the bandwidth quota for the
1837 * given neighbour and transmits it to the transport service.
1839 * @param cls neighbour for the quota update
1843 neighbour_quota_update (void *cls,
1844 const struct GNUNET_SCHEDULER_TaskContext *tc);
1848 * Schedule the task that will recalculate the bandwidth
1849 * quota for this peer (and possibly force a disconnect of
1850 * idle peers by calculating a bandwidth of zero).
1853 schedule_quota_update (struct Neighbour *n)
1855 GNUNET_assert (n->quota_update_task ==
1856 GNUNET_SCHEDULER_NO_TASK);
1857 n->quota_update_task
1858 = GNUNET_SCHEDULER_add_delayed (sched,
1859 QUOTA_UPDATE_FREQUENCY,
1860 &neighbour_quota_update,
1866 * Initialize a new 'struct Neighbour'.
1868 * @param pid ID of the new neighbour
1869 * @return handle for the new neighbour
1871 static struct Neighbour *
1872 create_neighbour (const struct GNUNET_PeerIdentity *pid)
1874 struct Neighbour *n;
1875 struct GNUNET_TIME_Absolute now;
1877 n = GNUNET_malloc (sizeof (struct Neighbour));
1878 n->next = neighbours;
1882 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
1883 now = GNUNET_TIME_absolute_get ();
1884 n->encrypt_key_created = now;
1885 n->last_activity = now;
1886 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
1887 n->bpm_in = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
1888 n->bpm_out = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
1889 n->bpm_out_internal_limit = (uint32_t) - 1;
1890 n->bpm_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT;
1891 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1893 schedule_quota_update (n);
1902 * Handle CORE_SEND request.
1905 * @param client the client issuing the request
1906 * @param message the "struct SendMessage"
1909 handle_client_send (void *cls,
1910 struct GNUNET_SERVER_Client *client,
1911 const struct GNUNET_MessageHeader *message)
1913 const struct SendMessage *sm;
1914 const struct GNUNET_MessageHeader *mh;
1915 struct Neighbour *n;
1916 struct MessageEntry *prev;
1917 struct MessageEntry *pos;
1918 struct MessageEntry *e;
1919 struct MessageEntry *min_prio_entry;
1920 struct MessageEntry *min_prio_prev;
1921 unsigned int min_prio;
1922 unsigned int queue_size;
1925 msize = ntohs (message->size);
1927 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
1931 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1934 sm = (const struct SendMessage *) message;
1935 msize -= sizeof (struct SendMessage);
1936 mh = (const struct GNUNET_MessageHeader *) &sm[1];
1937 if (msize != ntohs (mh->size))
1941 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1944 n = find_neighbour (&sm->peer);
1946 n = create_neighbour (&sm->peer);
1948 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1949 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
1952 GNUNET_i2s (&sm->peer));
1954 /* bound queue size */
1955 discard_expired_messages (n);
1956 min_prio = (unsigned int) -1;
1957 min_prio_entry = NULL;
1958 min_prio_prev = NULL;
1964 if (pos->priority < min_prio)
1966 min_prio_entry = pos;
1967 min_prio_prev = prev;
1968 min_prio = pos->priority;
1974 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1977 if (ntohl(sm->priority) <= min_prio)
1979 /* discard new entry */
1981 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1982 "Queue full, discarding new request\n");
1985 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1988 /* discard "min_prio_entry" */
1990 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1991 "Queue full, discarding existing older request\n");
1993 if (min_prio_prev == NULL)
1994 n->messages = min_prio_entry->next;
1996 min_prio_prev->next = min_prio_entry->next;
1997 GNUNET_free (min_prio_entry);
2001 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2002 "Adding transmission request for `%4s' to queue\n",
2003 GNUNET_i2s (&sm->peer));
2005 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2006 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2007 e->priority = ntohl (sm->priority);
2009 memcpy (&e[1], mh, msize);
2011 /* insert, keep list sorted by deadline */
2014 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2025 /* consider scheduling now */
2026 process_plaintext_neighbour_queue (n);
2028 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2033 * Handle CORE_REQUEST_CONNECT request.
2036 * @param client the client issuing the request
2037 * @param message the "struct ConnectMessage"
2040 handle_client_request_connect (void *cls,
2041 struct GNUNET_SERVER_Client *client,
2042 const struct GNUNET_MessageHeader *message)
2044 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2045 struct Neighbour *n;
2047 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2048 n = find_neighbour (&cm->peer);
2050 n = create_neighbour (&cm->peer);
2051 if ( (n->is_connected) ||
2053 return; /* already connected, or at least trying */
2055 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2056 "Core received `%s' request for `%4s', will try to establish connection\n",
2058 GNUNET_i2s (&cm->peer));
2060 /* ask transport to connect to the peer */
2061 /* FIXME: timeout zero OK? */
2062 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2065 GNUNET_TIME_UNIT_ZERO,
2072 * List of handlers for the messages understood by this
2075 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2076 {&handle_client_init, NULL,
2077 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2078 {&handle_client_request_info, NULL,
2079 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2080 sizeof (struct RequestInfoMessage)},
2081 {&handle_client_send, NULL,
2082 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2083 {&handle_client_request_connect, NULL,
2084 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2085 sizeof (struct ConnectMessage)},
2091 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2092 * the neighbour's struct and retry send_key. Or, if we did not get a
2093 * HELLO, just do nothing.
2095 * @param cls the 'struct Neighbour' to retry sending the key for
2096 * @param peer the peer for which this is the HELLO
2097 * @param hello HELLO message of that peer
2098 * @param trust amount of trust we currently have in that peer
2101 process_hello_retry_send_key (void *cls,
2102 const struct GNUNET_PeerIdentity *peer,
2103 const struct GNUNET_HELLO_Message *hello,
2106 struct Neighbour *n = cls;
2111 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2112 "Entered `process_hello_retry_send_key' and `peer' is NULL!\n");
2115 if (n->public_key != NULL)
2121 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2122 n->retry_set_key_task
2123 = GNUNET_SCHEDULER_add_delayed (sched,
2124 n->set_key_retry_frequency,
2125 &set_key_retry_task, n);
2131 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2132 "Entered `process_hello_retry_send_key' for peer `%4s'\n",
2135 if (n->public_key != NULL)
2138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2139 "already have public key for peer %s!! (so why are we here?)\n",
2146 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2147 "Received new `%s' message for `%4s', initiating key exchange.\n",
2152 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2153 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2155 GNUNET_free (n->public_key);
2156 n->public_key = NULL;
2158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2159 "GNUNET_HELLO_get_key returned awfully\n");
2167 * Send our key (and encrypted PING) to the other peer.
2169 * @param n the other peer
2172 send_key (struct Neighbour *n)
2174 struct SetKeyMessage *sm;
2175 struct MessageEntry *me;
2176 struct PingMessage pp;
2177 struct PingMessage *pm;
2179 if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2183 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2184 "Key exchange in progress with `%4s'.\n",
2185 GNUNET_i2s (&n->peer));
2187 return; /* already in progress */
2191 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2192 "Asked to perform key exchange with `%4s'.\n",
2193 GNUNET_i2s (&n->peer));
2195 if (n->public_key == NULL)
2197 /* lookup n's public key, then try again */
2199 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2200 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2201 GNUNET_i2s (&n->peer));
2203 GNUNET_assert (n->pitr == NULL);
2204 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2208 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2209 &process_hello_retry_send_key, n);
2212 /* first, set key message */
2213 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2214 sizeof (struct SetKeyMessage));
2215 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2216 me->priority = SET_KEY_PRIORITY;
2217 me->size = sizeof (struct SetKeyMessage);
2218 if (n->encrypted_head == NULL)
2219 n->encrypted_head = me;
2221 n->encrypted_tail->next = me;
2222 n->encrypted_tail = me;
2223 sm = (struct SetKeyMessage *) &me[1];
2224 sm->header.size = htons (sizeof (struct SetKeyMessage));
2225 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2226 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2227 PEER_STATE_KEY_SENT : n->status));
2229 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2230 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2231 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2232 sizeof (struct GNUNET_PeerIdentity));
2233 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2234 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2235 sm->target = n->peer;
2236 GNUNET_assert (GNUNET_OK ==
2237 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2239 GNUNET_CRYPTO_AesSessionKey),
2241 &sm->encrypted_key));
2242 GNUNET_assert (GNUNET_OK ==
2243 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2246 /* second, encrypted PING message */
2247 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2248 sizeof (struct PingMessage));
2249 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2250 me->priority = PING_PRIORITY;
2251 me->size = sizeof (struct PingMessage);
2252 n->encrypted_tail->next = me;
2253 n->encrypted_tail = me;
2254 pm = (struct PingMessage *) &me[1];
2255 pm->header.size = htons (sizeof (struct PingMessage));
2256 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2257 pp.challenge = htonl (n->ping_challenge);
2258 pp.target = n->peer;
2260 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2261 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2262 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2264 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2266 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2269 &n->peer.hashPubKey,
2272 sizeof (struct PingMessage) -
2273 sizeof (struct GNUNET_MessageHeader));
2277 case PEER_STATE_DOWN:
2278 n->status = PEER_STATE_KEY_SENT;
2280 case PEER_STATE_KEY_SENT:
2282 case PEER_STATE_KEY_RECEIVED:
2284 case PEER_STATE_KEY_CONFIRMED:
2291 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2292 "Have %llu ms left for `%s' transmission.\n",
2293 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2296 /* trigger queue processing */
2297 process_encrypted_neighbour_queue (n);
2298 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2299 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2300 n->retry_set_key_task
2301 = GNUNET_SCHEDULER_add_delayed (sched,
2302 n->set_key_retry_frequency,
2303 &set_key_retry_task, n);
2308 * We received a SET_KEY message. Validate and update
2309 * our key material and status.
2311 * @param n the neighbour from which we received message m
2312 * @param m the set key message we received
2315 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2319 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2320 * the neighbour's struct and retry handling the set_key message. Or,
2321 * if we did not get a HELLO, just free the set key message.
2323 * @param cls pointer to the set key message
2324 * @param peer the peer for which this is the HELLO
2325 * @param hello HELLO message of that peer
2326 * @param trust amount of trust we currently have in that peer
2329 process_hello_retry_handle_set_key (void *cls,
2330 const struct GNUNET_PeerIdentity *peer,
2331 const struct GNUNET_HELLO_Message *hello,
2334 struct Neighbour *n = cls;
2335 struct SetKeyMessage *sm = n->skm;
2344 if (n->public_key != NULL)
2345 return; /* multiple HELLOs match!? */
2347 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2348 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2350 GNUNET_break_op (0);
2351 GNUNET_free (n->public_key);
2352 n->public_key = NULL;
2356 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2357 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2358 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2360 handle_set_key (n, sm);
2365 * We received a PING message. Validate and transmit
2368 * @param n sender of the PING
2369 * @param m the encrypted PING message itself
2372 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2374 struct PingMessage t;
2375 struct PingMessage *tp;
2376 struct MessageEntry *me;
2379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2380 "Core service receives `%s' request from `%4s'.\n",
2381 "PING", GNUNET_i2s (&n->peer));
2385 &my_identity.hashPubKey,
2388 sizeof (struct PingMessage) -
2389 sizeof (struct GNUNET_MessageHeader)))
2392 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2393 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2395 GNUNET_i2s (&t.target),
2396 ntohl (t.challenge), n->decrypt_key.crc32);
2397 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2398 "Target of `%s' request is `%4s'.\n",
2399 "PING", GNUNET_i2s (&t.target));
2401 if (0 != memcmp (&t.target,
2402 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2404 GNUNET_break_op (0);
2407 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2408 sizeof (struct PingMessage));
2409 if (n->encrypted_tail != NULL)
2410 n->encrypted_tail->next = me;
2413 n->encrypted_tail = me;
2414 n->encrypted_head = me;
2416 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2417 me->priority = PONG_PRIORITY;
2418 me->size = sizeof (struct PingMessage);
2419 tp = (struct PingMessage *) &me[1];
2420 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2421 tp->header.size = htons (sizeof (struct PingMessage));
2423 &my_identity.hashPubKey,
2426 sizeof (struct PingMessage) -
2427 sizeof (struct GNUNET_MessageHeader));
2429 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2430 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2431 ntohl (t.challenge), n->encrypt_key.crc32);
2433 /* trigger queue processing */
2434 process_encrypted_neighbour_queue (n);
2439 * We received a PONG message. Validate and update our status.
2441 * @param n sender of the PONG
2442 * @param m the encrypted PONG message itself
2445 handle_pong (struct Neighbour *n, const struct PingMessage *m)
2447 struct PingMessage t;
2448 struct ConnectNotifyMessage cnm;
2451 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2452 "Core service receives `%s' request from `%4s'.\n",
2453 "PONG", GNUNET_i2s (&n->peer));
2457 &n->peer.hashPubKey,
2460 sizeof (struct PingMessage) -
2461 sizeof (struct GNUNET_MessageHeader)))
2464 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2465 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2467 GNUNET_i2s (&t.target),
2468 ntohl (t.challenge), n->decrypt_key.crc32);
2470 if ((0 != memcmp (&t.target,
2472 sizeof (struct GNUNET_PeerIdentity))) ||
2473 (n->ping_challenge != ntohl (t.challenge)))
2475 /* PONG malformed */
2477 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2478 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2479 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2480 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2481 "Received malformed `%s' received from `%4s' with challenge %u\n",
2482 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2484 GNUNET_break_op (0);
2489 case PEER_STATE_DOWN:
2490 GNUNET_break (0); /* should be impossible */
2492 case PEER_STATE_KEY_SENT:
2493 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2495 case PEER_STATE_KEY_RECEIVED:
2496 n->status = PEER_STATE_KEY_CONFIRMED;
2498 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2499 "Confirmed key via `%s' message for peer `%4s'\n",
2500 "PONG", GNUNET_i2s (&n->peer));
2502 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2504 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2505 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2507 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2508 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2509 cnm.distance = htonl (n->last_distance);
2510 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2512 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2513 process_encrypted_neighbour_queue (n);
2515 case PEER_STATE_KEY_CONFIRMED:
2516 /* duplicate PONG? */
2526 * We received a SET_KEY message. Validate and update
2527 * our key material and status.
2529 * @param n the neighbour from which we received message m
2530 * @param m the set key message we received
2533 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2535 struct SetKeyMessage *m_cpy;
2536 struct GNUNET_TIME_Absolute t;
2537 struct GNUNET_CRYPTO_AesSessionKey k;
2538 struct PingMessage *ping;
2539 struct PingMessage *pong;
2540 enum PeerStateMachine sender_status;
2543 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2544 "Core service receives `%s' request from `%4s'.\n",
2545 "SET_KEY", GNUNET_i2s (&n->peer));
2547 if (n->public_key == NULL)
2549 if (n->pitr != NULL)
2552 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2553 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2559 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2560 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2562 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2563 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2564 /* lookup n's public key, then try again */
2565 GNUNET_assert (n->skm == NULL);
2567 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2571 GNUNET_TIME_UNIT_MINUTES,
2572 &process_hello_retry_handle_set_key, n);
2575 if (0 != memcmp (&m->target,
2577 sizeof (struct GNUNET_PeerIdentity)))
2579 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2580 _("Received `%s' message that was not for me. Ignoring.\n"),
2584 if ((ntohl (m->purpose.size) !=
2585 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2586 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2587 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2588 sizeof (struct GNUNET_PeerIdentity)) ||
2590 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2591 &m->purpose, &m->signature, n->public_key)))
2593 /* invalid signature */
2594 GNUNET_break_op (0);
2597 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2598 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2599 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2600 (t.value < n->decrypt_key_created.value))
2602 /* this could rarely happen due to massive re-ordering of
2603 messages on the network level, but is most likely either
2604 a bug or some adversary messing with us. Report. */
2605 GNUNET_break_op (0);
2609 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
2611 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2614 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2615 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2616 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2618 /* failed to decrypt !? */
2619 GNUNET_break_op (0);
2624 if (n->decrypt_key_created.value != t.value)
2626 /* fresh key, reset sequence numbers */
2627 n->last_sequence_number_received = 0;
2628 n->last_packets_bitmap = 0;
2629 n->decrypt_key_created = t;
2631 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2634 case PEER_STATE_DOWN:
2635 n->status = PEER_STATE_KEY_RECEIVED;
2637 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2638 "Responding to `%s' with my own key.\n", "SET_KEY");
2642 case PEER_STATE_KEY_SENT:
2643 case PEER_STATE_KEY_RECEIVED:
2644 n->status = PEER_STATE_KEY_RECEIVED;
2645 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2646 (sender_status != PEER_STATE_KEY_CONFIRMED))
2649 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2650 "Responding to `%s' with my own key (other peer has status %u).\n",
2651 "SET_KEY", sender_status);
2656 case PEER_STATE_KEY_CONFIRMED:
2657 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2658 (sender_status != PEER_STATE_KEY_CONFIRMED))
2661 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2662 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2663 "SET_KEY", sender_status);
2672 if (n->pending_ping != NULL)
2674 ping = n->pending_ping;
2675 n->pending_ping = NULL;
2676 handle_ping (n, ping);
2679 if (n->pending_pong != NULL)
2681 pong = n->pending_pong;
2682 n->pending_pong = NULL;
2683 handle_pong (n, pong);
2690 * Send a P2P message to a client.
2692 * @param sender who sent us the message?
2693 * @param client who should we give the message to?
2694 * @param m contains the message to transmit
2695 * @param msize number of bytes in buf to transmit
2698 send_p2p_message_to_client (struct Neighbour *sender,
2699 struct Client *client,
2700 const void *m, size_t msize)
2702 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2703 struct NotifyTrafficMessage *ntm;
2706 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2707 "Core service passes message from `%4s' of type %u to client.\n",
2708 GNUNET_i2s(&sender->peer),
2709 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2711 ntm = (struct NotifyTrafficMessage *) buf;
2712 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2713 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2714 ntm->distance = htonl (sender->last_distance);
2715 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
2716 ntm->peer = sender->peer;
2717 memcpy (&ntm[1], m, msize);
2718 send_to_client (client, &ntm->header, GNUNET_YES);
2723 * Deliver P2P message to interested clients.
2725 * @param sender who sent us the message?
2726 * @param m the message
2727 * @param msize size of the message (including header)
2730 deliver_message (struct Neighbour *sender,
2731 const struct GNUNET_MessageHeader *m, size_t msize)
2733 struct Client *cpos;
2738 type = ntohs (m->type);
2741 "Received encapsulated message of type %u from `%4s'\n",
2743 GNUNET_i2s (&sender->peer));
2746 while (cpos != NULL)
2748 deliver_full = GNUNET_NO;
2749 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
2750 deliver_full = GNUNET_YES;
2753 for (tpos = 0; tpos < cpos->tcnt; tpos++)
2755 if (type != cpos->types[tpos])
2757 deliver_full = GNUNET_YES;
2761 if (GNUNET_YES == deliver_full)
2762 send_p2p_message_to_client (sender, cpos, m, msize);
2763 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2764 send_p2p_message_to_client (sender, cpos, m,
2765 sizeof (struct GNUNET_MessageHeader));
2772 * Align P2P message and then deliver to interested clients.
2774 * @param sender who sent us the message?
2775 * @param buffer unaligned (!) buffer containing message
2776 * @param msize size of the message (including header)
2779 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
2783 /* TODO: call to statistics? */
2784 memcpy (abuf, buffer, msize);
2785 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
2790 * Deliver P2P messages to interested clients.
2792 * @param sender who sent us the message?
2793 * @param buffer buffer containing messages, can be modified
2794 * @param buffer_size size of the buffer (overall)
2795 * @param offset offset where messages in the buffer start
2798 deliver_messages (struct Neighbour *sender,
2799 const char *buffer, size_t buffer_size, size_t offset)
2801 struct GNUNET_MessageHeader *mhp;
2802 struct GNUNET_MessageHeader mh;
2806 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
2808 if (0 != offset % sizeof (uint16_t))
2810 /* outch, need to copy to access header */
2811 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
2816 /* can access header directly */
2817 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
2819 msize = ntohs (mhp->size);
2820 if (msize + offset > buffer_size)
2822 /* malformed message, header says it is larger than what
2823 would fit into the overall buffer */
2824 GNUNET_break_op (0);
2827 #if HAVE_UNALIGNED_64_ACCESS
2828 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
2830 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
2832 if (GNUNET_YES == need_align)
2833 align_and_deliver (sender, &buffer[offset], msize);
2835 deliver_message (sender,
2836 (const struct GNUNET_MessageHeader *)
2837 &buffer[offset], msize);
2844 * We received an encrypted message. Decrypt, validate and
2845 * pass on to the appropriate clients.
2848 handle_encrypted_message (struct Neighbour *n,
2849 const struct EncryptedMessage *m)
2851 size_t size = ntohs (m->header.size);
2853 struct EncryptedMessage *pt; /* plaintext */
2857 struct GNUNET_TIME_Absolute t;
2860 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2861 "Core service receives `%s' request from `%4s'.\n",
2862 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
2868 &m->sequence_number,
2869 &buf[ENCRYPTED_HEADER_SIZE], size - ENCRYPTED_HEADER_SIZE))
2871 pt = (struct EncryptedMessage *) buf;
2874 GNUNET_CRYPTO_hash (&pt->sequence_number,
2875 size - ENCRYPTED_HEADER_SIZE, &ph);
2876 if (0 != memcmp (&ph, &m->plaintext_hash, sizeof (GNUNET_HashCode)))
2878 /* checksum failed */
2879 GNUNET_break_op (0);
2883 /* validate sequence number */
2884 snum = ntohl (pt->sequence_number);
2885 if (n->last_sequence_number_received == snum)
2887 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2888 "Received duplicate message, ignoring.\n");
2889 /* duplicate, ignore */
2892 if ((n->last_sequence_number_received > snum) &&
2893 (n->last_sequence_number_received - snum > 32))
2895 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2896 "Received ancient out of sequence message, ignoring.\n");
2897 /* ancient out of sequence, ignore */
2900 if (n->last_sequence_number_received > snum)
2902 unsigned int rotbit =
2903 1 << (n->last_sequence_number_received - snum - 1);
2904 if ((n->last_packets_bitmap & rotbit) != 0)
2906 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2907 "Received duplicate message, ignoring.\n");
2908 /* duplicate, ignore */
2911 n->last_packets_bitmap |= rotbit;
2913 if (n->last_sequence_number_received < snum)
2915 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
2916 n->last_sequence_number_received = snum;
2919 /* check timestamp */
2920 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
2921 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
2923 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2925 ("Message received far too old (%llu ms). Content ignored.\n"),
2926 GNUNET_TIME_absolute_get_duration (t).value);
2930 /* process decrypted message(s) */
2931 update_window (GNUNET_YES,
2932 &n->available_send_window,
2933 &n->last_asw_update,
2935 n->bpm_out_external_limit = ntohl (pt->inbound_bpm_limit);
2936 n->bpm_out = GNUNET_MAX (n->bpm_out_external_limit,
2937 n->bpm_out_internal_limit);
2938 n->last_activity = GNUNET_TIME_absolute_get ();
2939 off = sizeof (struct EncryptedMessage);
2940 deliver_messages (n, buf, size, off);
2945 * Function called by the transport for each received message.
2947 * @param cls closure
2948 * @param peer (claimed) identity of the other peer
2949 * @param message the message
2950 * @param latency estimated latency for communicating with the
2951 * given peer (round-trip)
2952 * @param distance in overlay hops, as given by transport plugin
2955 handle_transport_receive (void *cls,
2956 const struct GNUNET_PeerIdentity *peer,
2957 const struct GNUNET_MessageHeader *message,
2958 struct GNUNET_TIME_Relative latency,
2959 unsigned int distance)
2961 struct Neighbour *n;
2962 struct GNUNET_TIME_Absolute now;
2968 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2969 "Received message of type %u from `%4s', demultiplexing.\n",
2970 ntohs (message->type), GNUNET_i2s (peer));
2972 n = find_neighbour (peer);
2974 n = create_neighbour (peer);
2977 n->last_latency = latency;
2978 n->last_distance = distance;
2979 up = (n->status == PEER_STATE_KEY_CONFIRMED);
2980 type = ntohs (message->type);
2981 size = ntohs (message->size);
2984 "Received message of type %u from `%4s'\n",
2990 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
2991 if (size != sizeof (struct SetKeyMessage))
2993 GNUNET_break_op (0);
2996 handle_set_key (n, (const struct SetKeyMessage *) message);
2998 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
2999 if (size < sizeof (struct EncryptedMessage) +
3000 sizeof (struct GNUNET_MessageHeader))
3002 GNUNET_break_op (0);
3005 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3006 (n->status != PEER_STATE_KEY_CONFIRMED))
3008 GNUNET_break_op (0);
3011 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3013 case GNUNET_MESSAGE_TYPE_CORE_PING:
3014 if (size != sizeof (struct PingMessage))
3016 GNUNET_break_op (0);
3019 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3020 (n->status != PEER_STATE_KEY_CONFIRMED))
3023 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3024 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3025 "PING", GNUNET_i2s (&n->peer));
3027 GNUNET_free_non_null (n->pending_ping);
3028 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3029 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3032 handle_ping (n, (const struct PingMessage *) message);
3034 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3035 if (size != sizeof (struct PingMessage))
3037 GNUNET_break_op (0);
3040 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3041 (n->status != PEER_STATE_KEY_CONFIRMED) )
3044 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3045 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3046 "PONG", GNUNET_i2s (&n->peer));
3048 GNUNET_free_non_null (n->pending_pong);
3049 n->pending_pong = GNUNET_malloc (sizeof (struct PingMessage));
3050 memcpy (n->pending_pong, message, sizeof (struct PingMessage));
3053 handle_pong (n, (const struct PingMessage *) message);
3056 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3057 _("Unsupported message of type %u received.\n"), type);
3060 if (n->status == PEER_STATE_KEY_CONFIRMED)
3062 now = GNUNET_TIME_absolute_get ();
3063 n->last_activity = now;
3065 n->time_established = now;
3071 * Function that recalculates the bandwidth quota for the
3072 * given neighbour and transmits it to the transport service.
3074 * @param cls neighbour for the quota update
3078 neighbour_quota_update (void *cls,
3079 const struct GNUNET_SCHEDULER_TaskContext *tc)
3081 struct Neighbour *n = cls;
3085 unsigned long long distributable;
3087 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3088 /* calculate relative preference among all neighbours;
3089 divides by a bit more to avoid division by zero AND to
3090 account for possibility of new neighbours joining any time
3091 AND to convert to double... */
3092 pref_rel = n->current_preference / (1.0 + preference_sum);
3094 if (bandwidth_target_out > neighbour_count * MIN_BPM_PER_PEER)
3095 distributable = bandwidth_target_out - neighbour_count * MIN_BPM_PER_PEER;
3096 share = distributable * pref_rel;
3097 q_in = MIN_BPM_PER_PEER + (unsigned long long) share;
3098 /* check if we want to disconnect for good due to inactivity */
3099 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3100 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3104 "Forcing disconnect of `%4s' due to inactivity (?).\n",
3105 GNUNET_i2s (&n->peer));
3107 q_in = 0; /* force disconnect */
3109 if ( (n->bpm_in + MIN_BPM_CHANGE < q_in) ||
3110 (n->bpm_in - MIN_BPM_CHANGE > q_in) )
3113 GNUNET_TRANSPORT_set_quota (transport,
3117 GNUNET_TIME_UNIT_FOREVER_REL,
3120 schedule_quota_update (n);
3125 * Function called by transport to notify us that
3126 * a peer connected to us (on the network level).
3128 * @param cls closure
3129 * @param peer the peer that connected
3130 * @param latency current latency of the connection
3131 * @param distance in overlay hops, as given by transport plugin
3134 handle_transport_notify_connect (void *cls,
3135 const struct GNUNET_PeerIdentity *peer,
3136 struct GNUNET_TIME_Relative latency,
3137 unsigned int distance)
3139 struct Neighbour *n;
3140 struct GNUNET_TIME_Absolute now;
3141 struct ConnectNotifyMessage cnm;
3143 n = find_neighbour (peer);
3146 if (n->is_connected)
3148 /* duplicate connect notification!? */
3155 n = create_neighbour (peer);
3157 now = GNUNET_TIME_absolute_get ();
3158 n->is_connected = GNUNET_YES;
3159 n->last_latency = latency;
3160 n->last_distance = distance;
3161 n->last_asw_update = now;
3162 n->last_arw_update = now;
3164 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3165 "Received connection from `%4s'.\n",
3166 GNUNET_i2s (&n->peer));
3168 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3169 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3170 cnm.distance = htonl (n->last_distance);
3171 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3173 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3179 * Function called by transport telling us that a peer
3182 * @param cls closure
3183 * @param peer the peer that disconnected
3186 handle_transport_notify_disconnect (void *cls,
3187 const struct GNUNET_PeerIdentity *peer)
3189 struct DisconnectNotifyMessage cnm;
3190 struct Neighbour *n;
3193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3194 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3196 n = find_neighbour (peer);
3197 GNUNET_break (n->is_connected);
3198 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3199 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3201 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3202 n->is_connected = GNUNET_NO;
3207 * Last task run during shutdown. Disconnects us from
3211 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3213 struct Neighbour *n;
3217 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3218 "Core service shutting down.\n");
3220 GNUNET_assert (transport != NULL);
3221 GNUNET_TRANSPORT_disconnect (transport);
3223 while (NULL != (n = neighbours))
3225 neighbours = n->next;
3226 GNUNET_assert (neighbour_count > 0);
3230 GNUNET_SERVER_notification_context_destroy (notifier);
3232 while (NULL != (c = clients))
3233 handle_client_disconnect (NULL, c->client_handle);
3234 if (my_private_key != NULL)
3235 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3240 * Initiate core service.
3242 * @param cls closure
3243 * @param s scheduler to use
3244 * @param serv the initialized server
3245 * @param c configuration to use
3249 struct GNUNET_SCHEDULER_Handle *s,
3250 struct GNUNET_SERVER_Handle *serv,
3251 const struct GNUNET_CONFIGURATION_Handle *c)
3254 unsigned long long qin;
3255 unsigned long long qout;
3256 unsigned long long tneigh;
3262 /* parse configuration */
3265 GNUNET_CONFIGURATION_get_value_number (c,
3268 &bandwidth_target_in)) ||
3270 GNUNET_CONFIGURATION_get_value_number (c,
3273 &bandwidth_target_out)) ||
3275 GNUNET_CONFIGURATION_get_value_filename (c,
3277 "HOSTKEY", &keyfile)))
3279 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3281 ("Core service is lacking key configuration settings. Exiting.\n"));
3282 GNUNET_SCHEDULER_shutdown (s);
3285 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3286 GNUNET_free (keyfile);
3287 if (my_private_key == NULL)
3289 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3290 _("Core service could not access hostkey. Exiting.\n"));
3291 GNUNET_SCHEDULER_shutdown (s);
3294 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3295 GNUNET_CRYPTO_hash (&my_public_key,
3296 sizeof (my_public_key), &my_identity.hashPubKey);
3297 /* setup notification */
3299 notifier = GNUNET_SERVER_notification_context_create (server,
3301 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3302 /* setup transport connection */
3303 transport = GNUNET_TRANSPORT_connect (sched,
3306 &handle_transport_receive,
3307 &handle_transport_notify_connect,
3308 &handle_transport_notify_disconnect);
3309 GNUNET_assert (NULL != transport);
3310 GNUNET_SCHEDULER_add_delayed (sched,
3311 GNUNET_TIME_UNIT_FOREVER_REL,
3312 &cleaning_task, NULL);
3313 /* process client requests */
3314 GNUNET_SERVER_add_handlers (server, handlers);
3315 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3316 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3322 * The main function for the transport service.
3324 * @param argc number of arguments from the command line
3325 * @param argv command line arguments
3326 * @return 0 ok, 1 on error
3329 main (int argc, char *const *argv)
3331 return (GNUNET_OK ==
3332 GNUNET_SERVICE_run (argc,
3335 GNUNET_SERVICE_OPTION_NONE,
3336 &run, NULL)) ? 0 : 1;
3339 /* end of gnunet-service-core.c */