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_statistics_service.h"
41 #include "gnunet_transport_service.h"
45 #define DEBUG_HANDSHAKE GNUNET_NO
47 #define DEBUG_CORE_QUOTA GNUNET_NO
50 * Receive and send buffer windows grow over time. For
51 * how long can 'unused' bandwidth accumulate before we
52 * need to cap it? (specified in seconds).
54 #define MAX_WINDOW_TIME_S (5 * 60)
57 * How many messages do we queue up at most for optional
58 * notifications to a client? (this can cause notifications
59 * about outgoing messages to be dropped).
61 #define MAX_NOTIFY_QUEUE 16
64 * Minimum bandwidth (out) to assign to any connected peer.
65 * Should be rather low; values larger than DEFAULT_BW_IN_OUT make no
68 #define MIN_BANDWIDTH_PER_PEER GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT
71 * After how much time past the "official" expiration time do
72 * we discard messages? Should not be zero since we may
73 * intentionally defer transmission until close to the deadline
74 * and then may be slightly past the deadline due to inaccuracy
75 * in sleep and our own CPU consumption.
77 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
80 * What is the maximum delay for a SET_KEY message?
82 #define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
85 * How long do we wait for SET_KEY confirmation initially?
87 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 1)
90 * What is the maximum delay for a PING message?
92 #define MAX_PING_DELAY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 2)
95 * What is the maximum delay for a PONG message?
97 #define MAX_PONG_DELAY GNUNET_TIME_relative_multiply (MAX_PING_DELAY, 2)
100 * What is the minimum frequency for a PING message?
102 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
105 * How often do we recalculate bandwidth quotas?
107 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
110 * What is the priority for a SET_KEY message?
112 #define SET_KEY_PRIORITY 0xFFFFFF
115 * What is the priority for a PING message?
117 #define PING_PRIORITY 0xFFFFFF
120 * What is the priority for a PONG message?
122 #define PONG_PRIORITY 0xFFFFFF
125 * How many messages do we queue per peer at most? Must be at
128 #define MAX_PEER_QUEUE_SIZE 16
131 * How many non-mandatory messages do we queue per client at most?
133 #define MAX_CLIENT_QUEUE_SIZE 32
136 * What is the maximum age of a message for us to consider
137 * processing it? Note that this looks at the timestamp used
138 * by the other peer, so clock skew between machines does
139 * come into play here. So this should be picked high enough
140 * so that a little bit of clock skew does not prevent peers
141 * from connecting to us.
143 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
146 * What is the maximum size for encrypted messages? Note that this
147 * number imposes a clear limit on the maximum size of any message.
148 * Set to a value close to 64k but not so close that transports will
149 * have trouble with their headers.
151 #define MAX_ENCRYPTED_MESSAGE_SIZE (63 * 1024)
155 * State machine for our P2P encryption handshake. Everyone starts in
156 * "DOWN", if we receive the other peer's key (other peer initiated)
157 * we start in state RECEIVED (since we will immediately send our
158 * own); otherwise we start in SENT. If we get back a PONG from
159 * within either state, we move up to CONFIRMED (the PONG will always
160 * be sent back encrypted with the key we sent to the other peer).
162 enum PeerStateMachine
166 PEER_STATE_KEY_RECEIVED,
167 PEER_STATE_KEY_CONFIRMED
172 * Number of bytes (at the beginning) of "struct EncryptedMessage"
173 * that are NOT encrypted.
175 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t))
179 * Encapsulation for encrypted messages exchanged between
180 * peers. Followed by the actual encrypted data.
182 struct EncryptedMessage
185 * Message type is either CORE_ENCRYPTED_MESSAGE.
187 struct GNUNET_MessageHeader header;
190 * Random value used for IV generation. ENCRYPTED_HEADER_SIZE must
191 * be set to the offset of the *next* field.
193 uint32_t iv_seed GNUNET_PACKED;
196 * Hash of the plaintext (starting at 'sequence_number'), used to
197 * verify message integrity. Everything after this hash (including
198 * this hash itself) will be encrypted.
200 GNUNET_HashCode plaintext_hash;
203 * Sequence number, in network byte order. This field
204 * must be the first encrypted/decrypted field and the
205 * first byte that is hashed for the plaintext hash.
207 uint32_t sequence_number GNUNET_PACKED;
210 * Desired bandwidth (how much we should send to this peer / how
211 * much is the sender willing to receive)?
213 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
216 * Timestamp. Used to prevent reply of ancient messages
217 * (recent messages are caught with the sequence number).
219 struct GNUNET_TIME_AbsoluteNBO timestamp;
225 * We're sending an (encrypted) PING to the other peer to check if he
226 * can decrypt. The other peer should respond with a PONG with the
227 * same content, except this time encrypted with the receiver's key.
232 * Message type is CORE_PING.
234 struct GNUNET_MessageHeader header;
237 * Random number chosen to make reply harder.
239 uint32_t challenge GNUNET_PACKED;
242 * Intended target of the PING, used primarily to check
243 * that decryption actually worked.
245 struct GNUNET_PeerIdentity target;
251 * Response to a PING. Includes data from the original PING
252 * plus initial bandwidth quota information.
257 * Message type is CORE_PONG.
259 struct GNUNET_MessageHeader header;
262 * Random number proochosen to make reply harder. Must be
263 * first field after header (this is where we start to encrypt!).
265 uint32_t challenge GNUNET_PACKED;
270 uint32_t reserved GNUNET_PACKED;
273 * Desired bandwidth (how much we should send to this
274 * peer / how much is the sender willing to receive).
276 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
279 * Intended target of the PING, used primarily to check
280 * that decryption actually worked.
282 struct GNUNET_PeerIdentity target;
287 * Message transmitted to set (or update) a session key.
293 * Message type is either CORE_SET_KEY.
295 struct GNUNET_MessageHeader header;
298 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
300 int32_t sender_status GNUNET_PACKED;
303 * Purpose of the signature, will be
304 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
306 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
309 * At what time was this key created?
311 struct GNUNET_TIME_AbsoluteNBO creation_time;
314 * The encrypted session key.
316 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
319 * Who is the intended recipient?
321 struct GNUNET_PeerIdentity target;
324 * Signature of the stuff above (starting at purpose).
326 struct GNUNET_CRYPTO_RsaSignature signature;
332 * Message waiting for transmission. This struct
333 * is followed by the actual content of the message.
339 * We keep messages in a doubly linked list.
341 struct MessageEntry *next;
344 * We keep messages in a doubly linked list.
346 struct MessageEntry *prev;
349 * By when are we supposed to transmit this message?
351 struct GNUNET_TIME_Absolute deadline;
354 * By when are we supposed to transmit this message (after
357 struct GNUNET_TIME_Absolute slack_deadline;
360 * How important is this message to us?
362 unsigned int priority;
365 * If this is a SET_KEY message, what was our connection status when this
366 * message was queued?
368 enum PeerStateMachine sender_status;
371 * Is this a SET_KEY message?
376 * How long is the message? (number of bytes following
377 * the "struct MessageEntry", but not including the
378 * size of "struct MessageEntry" itself!)
383 * Was this message selected for transmission in the
384 * current round? GNUNET_YES or GNUNET_NO.
389 * Did we give this message some slack (delayed sending) previously
390 * (and hence should not give it any more slack)? GNUNET_YES or
401 * We keep neighbours in a linked list (for now).
403 struct Neighbour *next;
406 * Unencrypted messages destined for this peer.
408 struct MessageEntry *messages;
411 * Head of the batched, encrypted message queue (already ordered,
412 * transmit starting with the head).
414 struct MessageEntry *encrypted_head;
417 * Tail of the batched, encrypted message queue (already ordered,
418 * append new messages to tail)
420 struct MessageEntry *encrypted_tail;
423 * Handle for pending requests for transmission to this peer
424 * with the transport service. NULL if no request is pending.
426 struct GNUNET_TRANSPORT_TransmitHandle *th;
429 * Public key of the neighbour, NULL if we don't have it yet.
431 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
434 * We received a PING message before we got the "public_key"
435 * (or the SET_KEY). We keep it here until we have a key
436 * to decrypt it. NULL if no PING is pending.
438 struct PingMessage *pending_ping;
441 * We received a PONG message before we got the "public_key"
442 * (or the SET_KEY). We keep it here until we have a key
443 * to decrypt it. NULL if no PONG is pending.
445 struct PongMessage *pending_pong;
448 * Non-NULL if we are currently looking up HELLOs for this peer.
451 struct GNUNET_PEERINFO_IteratorContext *pitr;
454 * SetKeyMessage to transmit, NULL if we are not currently trying
457 struct SetKeyMessage *skm;
460 * Identity of the neighbour.
462 struct GNUNET_PeerIdentity peer;
465 * Key we use to encrypt our messages for the other peer
466 * (initialized by us when we do the handshake).
468 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
471 * Key we use to decrypt messages from the other peer
472 * (given to us by the other peer during the handshake).
474 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
477 * ID of task used for re-trying plaintext scheduling.
479 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
482 * ID of task used for re-trying SET_KEY and PING message.
484 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
487 * ID of task used for updating bandwidth quota for this neighbour.
489 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
492 * ID of task used for sending keep-alive pings.
494 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
497 * ID of task used for cleaning up dead neighbour entries.
499 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
502 * At what time did we generate our encryption key?
504 struct GNUNET_TIME_Absolute encrypt_key_created;
507 * At what time did the other peer generate the decryption key?
509 struct GNUNET_TIME_Absolute decrypt_key_created;
512 * At what time did we initially establish (as in, complete session
513 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
515 struct GNUNET_TIME_Absolute time_established;
518 * At what time did we last receive an encrypted message from the
519 * other peer? Should be zero if status != KEY_CONFIRMED.
521 struct GNUNET_TIME_Absolute last_activity;
524 * Last latency observed from this peer.
526 struct GNUNET_TIME_Relative last_latency;
529 * At what frequency are we currently re-trying SET_KEY messages?
531 struct GNUNET_TIME_Relative set_key_retry_frequency;
534 * Tracking bandwidth for sending to this peer.
536 struct GNUNET_BANDWIDTH_Tracker available_send_window;
539 * Tracking bandwidth for receiving from this peer.
541 struct GNUNET_BANDWIDTH_Tracker available_recv_window;
544 * How valueable were the messages of this peer recently?
546 unsigned long long current_preference;
549 * Bit map indicating which of the 32 sequence numbers before the last
550 * were received (good for accepting out-of-order packets and
551 * estimating reliability of the connection)
553 unsigned int last_packets_bitmap;
556 * last sequence number received on this connection (highest)
558 uint32_t last_sequence_number_received;
561 * last sequence number transmitted
563 uint32_t last_sequence_number_sent;
566 * Available bandwidth in for this peer (current target).
568 struct GNUNET_BANDWIDTH_Value32NBO bw_in;
571 * Available bandwidth out for this peer (current target).
573 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
576 * Internal bandwidth limit set for this peer (initially typically
577 * set to "-1"). Actual "bw_out" is MIN of
578 * "bpm_out_internal_limit" and "bw_out_external_limit".
580 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
583 * External bandwidth limit set for this peer by the
584 * peer that we are communicating with. "bw_out" is MIN of
585 * "bw_out_internal_limit" and "bw_out_external_limit".
587 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
590 * What was our PING challenge number (for this peer)?
592 uint32_t ping_challenge;
595 * What was the last distance to this peer as reported by the transports?
597 uint32_t last_distance;
600 * What is our connection status?
602 enum PeerStateMachine status;
605 * Are we currently connected to this neighbour?
613 * Data structure for each client connected to the core service.
618 * Clients are kept in a linked list.
623 * Handle for the client with the server API.
625 struct GNUNET_SERVER_Client *client_handle;
628 * Array of the types of messages this peer cares
629 * about (with "tcnt" entries). Allocated as part
630 * of this client struct, do not free!
632 const uint16_t *types;
635 * Options for messages this client cares about,
636 * see GNUNET_CORE_OPTION_ values.
641 * Number of types of incoming messages this client
642 * specifically cares about. Size of the "types" array.
652 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
657 static struct GNUNET_PeerIdentity my_identity;
662 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
667 struct GNUNET_SCHEDULER_Handle *sched;
670 * Handle to peerinfo service.
672 static struct GNUNET_PEERINFO_Handle *peerinfo;
677 const struct GNUNET_CONFIGURATION_Handle *cfg;
682 static struct GNUNET_SERVER_Handle *server;
687 static struct GNUNET_TRANSPORT_Handle *transport;
690 * Linked list of our clients.
692 static struct Client *clients;
695 * Context for notifications we need to send to our clients.
697 static struct GNUNET_SERVER_NotificationContext *notifier;
700 * We keep neighbours in a linked list (for now).
702 static struct Neighbour *neighbours;
705 * For creating statistics.
707 static struct GNUNET_STATISTICS_Handle *stats;
710 * Sum of all preferences among all neighbours.
712 static unsigned long long preference_sum;
715 * Total number of neighbours we have.
717 static unsigned int neighbour_count;
720 * How much inbound bandwidth are we supposed to be using per second?
721 * FIXME: this value is not used!
723 static unsigned long long bandwidth_target_in_bps;
726 * How much outbound bandwidth are we supposed to be using per second?
728 static unsigned long long bandwidth_target_out_bps;
733 * A preference value for a neighbour was update. Update
734 * the preference sum accordingly.
736 * @param inc how much was a preference value increased?
739 update_preference_sum (unsigned long long inc)
742 unsigned long long os;
745 preference_sum += inc;
746 if (preference_sum >= os)
748 /* overflow! compensate by cutting all values in half! */
753 n->current_preference /= 2;
754 preference_sum += n->current_preference;
757 GNUNET_STATISTICS_set (stats, gettext_noop ("# total peer preference"), preference_sum, GNUNET_NO);
762 * Find the entry for the given neighbour.
764 * @param peer identity of the neighbour
765 * @return NULL if we are not connected, otherwise the
768 static struct Neighbour *
769 find_neighbour (const struct GNUNET_PeerIdentity *peer)
771 struct Neighbour *ret;
774 while ((ret != NULL) &&
775 (0 != memcmp (&ret->peer,
776 peer, sizeof (struct GNUNET_PeerIdentity))))
783 * Send a message to one of our clients.
785 * @param client target for the message
786 * @param msg message to transmit
787 * @param can_drop could this message be dropped if the
788 * client's queue is getting too large?
791 send_to_client (struct Client *client,
792 const struct GNUNET_MessageHeader *msg,
795 #if DEBUG_CORE_CLIENT
796 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
797 "Preparing to send message of type %u to client.\n",
798 (unsigned int) ntohs (msg->type));
800 GNUNET_SERVER_notification_context_unicast (notifier,
801 client->client_handle,
808 * Send a message to all of our current clients that have
809 * the right options set.
811 * @param msg message to multicast
812 * @param can_drop can this message be discarded if the queue is too long
813 * @param options mask to use
816 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
825 if (0 != (c->options & options))
827 #if DEBUG_CORE_CLIENT
828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
829 "Sending message of type %u to client.\n",
830 (unsigned int) ntohs (msg->type));
832 send_to_client (c, msg, can_drop);
840 * Handle CORE_INIT request.
843 handle_client_init (void *cls,
844 struct GNUNET_SERVER_Client *client,
845 const struct GNUNET_MessageHeader *message)
847 const struct InitMessage *im;
848 struct InitReplyMessage irm;
851 const uint16_t *types;
854 struct ConnectNotifyMessage cnm;
857 #if DEBUG_CORE_CLIENT
858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
859 "Client connecting to core service with `%s' message\n",
862 /* check that we don't have an entry already */
866 if (client == c->client_handle)
869 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
874 msize = ntohs (message->size);
875 if (msize < sizeof (struct InitMessage))
878 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
881 GNUNET_SERVER_notification_context_add (notifier, client);
882 im = (const struct InitMessage *) message;
883 types = (const uint16_t *) &im[1];
884 msize -= sizeof (struct InitMessage);
885 c = GNUNET_malloc (sizeof (struct Client) + msize);
886 c->client_handle = client;
889 c->tcnt = msize / sizeof (uint16_t);
890 c->types = (const uint16_t *) &c[1];
891 wtypes = (uint16_t *) &c[1];
892 for (i=0;i<c->tcnt;i++)
893 wtypes[i] = ntohs (types[i]);
894 c->options = ntohl (im->options);
895 #if DEBUG_CORE_CLIENT
896 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
897 "Client %p is interested in %u message types\n",
899 (unsigned int) c->tcnt);
901 /* send init reply message */
902 irm.header.size = htons (sizeof (struct InitReplyMessage));
903 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
904 irm.reserved = htonl (0);
905 memcpy (&irm.publicKey,
907 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
908 #if DEBUG_CORE_CLIENT
909 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
910 "Sending `%s' message to client.\n", "INIT_REPLY");
912 send_to_client (c, &irm.header, GNUNET_NO);
913 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
915 /* notify new client about existing neighbours */
916 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
917 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
921 if (n->status == PEER_STATE_KEY_CONFIRMED)
923 #if DEBUG_CORE_CLIENT
924 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
925 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
927 cnm.distance = htonl (n->last_distance);
928 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
930 send_to_client (c, &cnm.header, GNUNET_NO);
935 GNUNET_SERVER_receive_done (client, GNUNET_OK);
940 * A client disconnected, clean up.
943 * @param client identification of the client
946 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
953 #if DEBUG_CORE_CLIENT
954 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
955 "Client %p has disconnected from core service.\n",
962 if (client == pos->client_handle)
967 prev->next = pos->next;
974 /* client never sent INIT */
979 * Handle REQUEST_INFO request.
982 handle_client_request_info (void *cls,
983 struct GNUNET_SERVER_Client *client,
984 const struct GNUNET_MessageHeader *message)
986 const struct RequestInfoMessage *rcm;
988 struct ConfigurationInfoMessage cim;
991 unsigned long long old_preference;
992 struct GNUNET_SERVER_TransmitContext *tc;
994 #if DEBUG_CORE_CLIENT
995 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
996 "Core service receives `%s' request.\n", "REQUEST_INFO");
998 rcm = (const struct RequestInfoMessage *) message;
999 n = find_neighbour (&rcm->peer);
1000 memset (&cim, 0, sizeof (cim));
1003 want_reserv = ntohl (rcm->reserve_inbound);
1004 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1006 n->bw_out_internal_limit = rcm->limit_outbound;
1007 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1008 n->bw_out_external_limit);
1009 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1011 GNUNET_TRANSPORT_set_quota (transport,
1015 GNUNET_TIME_UNIT_FOREVER_REL,
1018 if (want_reserv < 0)
1020 got_reserv = want_reserv;
1022 else if (want_reserv > 0)
1024 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1025 want_reserv).value == 0)
1026 got_reserv = want_reserv;
1028 got_reserv = 0; /* all or nothing */
1032 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1034 old_preference = n->current_preference;
1035 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1036 if (old_preference > n->current_preference)
1038 /* overflow; cap at maximum value */
1039 n->current_preference = (unsigned long long) -1;
1041 update_preference_sum (n->current_preference - old_preference);
1042 #if DEBUG_CORE_QUOTA
1043 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1044 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1046 GNUNET_i2s (&rcm->peer),
1049 cim.reserved_amount = htonl (got_reserv);
1050 cim.bw_in = n->bw_in;
1051 cim.bw_out = n->bw_out;
1052 cim.preference = n->current_preference;
1054 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1055 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1056 cim.peer = rcm->peer;
1058 #if DEBUG_CORE_CLIENT
1059 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1060 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1062 tc = GNUNET_SERVER_transmit_context_create (client);
1063 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1064 GNUNET_SERVER_transmit_context_run (tc,
1065 GNUNET_TIME_UNIT_FOREVER_REL);
1070 * Free the given entry for the neighbour (it has
1071 * already been removed from the list at this point).
1073 * @param n neighbour to free
1076 free_neighbour (struct Neighbour *n)
1078 struct MessageEntry *m;
1081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1082 "Destroying neighbour entry for peer `%4s'\n",
1083 GNUNET_i2s (&n->peer));
1085 if (n->pitr != NULL)
1087 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1092 GNUNET_free (n->skm);
1095 while (NULL != (m = n->messages))
1097 n->messages = m->next;
1100 while (NULL != (m = n->encrypted_head))
1102 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1109 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1112 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1113 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1114 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1115 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1116 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1117 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1118 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1119 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1120 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1121 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1122 if (n->status == PEER_STATE_KEY_CONFIRMED)
1123 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1124 GNUNET_free_non_null (n->public_key);
1125 GNUNET_free_non_null (n->pending_ping);
1126 GNUNET_free_non_null (n->pending_pong);
1132 * Check if we have encrypted messages for the specified neighbour
1133 * pending, and if so, check with the transport about sending them
1136 * @param n neighbour to check.
1138 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1142 * Encrypt size bytes from in and write the result to out. Use the
1143 * key for outbound traffic of the given neighbour.
1145 * @param n neighbour we are sending to
1146 * @param iv initialization vector to use
1147 * @param in ciphertext
1148 * @param out plaintext
1149 * @param size size of in/out
1150 * @return GNUNET_OK on success
1153 do_encrypt (struct Neighbour *n,
1154 const GNUNET_HashCode * iv,
1155 const void *in, void *out, size_t size)
1157 if (size != (uint16_t) size)
1162 GNUNET_assert (size ==
1163 GNUNET_CRYPTO_aes_encrypt (in,
1167 GNUNET_CRYPTO_AesInitializationVector
1169 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1171 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1172 "Encrypted %u bytes for `%4s' using key %u\n",
1173 (unsigned int) size,
1174 GNUNET_i2s (&n->peer),
1175 (unsigned int) n->encrypt_key.crc32);
1182 * Consider freeing the given neighbour since we may not need
1183 * to keep it around anymore.
1185 * @param n neighbour to consider discarding
1188 consider_free_neighbour (struct Neighbour *n);
1192 * Task triggered when a neighbour entry is about to time out
1193 * (and we should prevent this by sending a PING).
1195 * @param cls the 'struct Neighbour'
1196 * @param tc scheduler context (not used)
1199 send_keep_alive (void *cls,
1200 const struct GNUNET_SCHEDULER_TaskContext *tc)
1202 struct Neighbour *n = cls;
1203 struct GNUNET_TIME_Relative retry;
1204 struct GNUNET_TIME_Relative left;
1205 struct MessageEntry *me;
1206 struct PingMessage pp;
1207 struct PingMessage *pm;
1209 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1211 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1212 sizeof (struct PingMessage));
1213 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1214 me->priority = PING_PRIORITY;
1215 me->size = sizeof (struct PingMessage);
1216 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1220 pm = (struct PingMessage *) &me[1];
1221 pm->header.size = htons (sizeof (struct PingMessage));
1222 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1223 pp.challenge = htonl (n->ping_challenge);
1224 pp.target = n->peer;
1226 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1227 "Encrypting `%s' message with challenge %u for `%4s' using key %u.\n",
1229 (unsigned int) n->ping_challenge,
1230 GNUNET_i2s (&n->peer),
1231 (unsigned int) n->encrypt_key.crc32);
1234 &n->peer.hashPubKey,
1237 sizeof (struct PingMessage) -
1238 sizeof (struct GNUNET_MessageHeader));
1239 process_encrypted_neighbour_queue (n);
1240 /* reschedule PING job */
1241 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1242 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1243 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1244 MIN_PING_FREQUENCY);
1246 = GNUNET_SCHEDULER_add_delayed (sched,
1255 * Task triggered when a neighbour entry might have gotten stale.
1257 * @param cls the 'struct Neighbour'
1258 * @param tc scheduler context (not used)
1261 consider_free_task (void *cls,
1262 const struct GNUNET_SCHEDULER_TaskContext *tc)
1264 struct Neighbour *n = cls;
1266 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1267 consider_free_neighbour (n);
1272 * Consider freeing the given neighbour since we may not need
1273 * to keep it around anymore.
1275 * @param n neighbour to consider discarding
1278 consider_free_neighbour (struct Neighbour *n)
1280 struct Neighbour *pos;
1281 struct Neighbour *prev;
1282 struct GNUNET_TIME_Relative left;
1284 if ( (n->th != NULL) ||
1285 (n->pitr != NULL) ||
1286 (n->status == PEER_STATE_KEY_CONFIRMED) ||
1287 (GNUNET_YES == n->is_connected) )
1288 return; /* no chance */
1290 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1291 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1294 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1295 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1296 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1298 &consider_free_task,
1302 /* actually free the neighbour... */
1311 neighbours = n->next;
1313 prev->next = n->next;
1314 GNUNET_assert (neighbour_count > 0);
1316 GNUNET_STATISTICS_set (stats,
1317 gettext_noop ("# neighbour entries allocated"),
1325 * Function called when the transport service is ready to
1326 * receive an encrypted message for the respective peer
1328 * @param cls neighbour to use message from
1329 * @param size number of bytes we can transmit
1330 * @param buf where to copy the message
1331 * @return number of bytes transmitted
1334 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1336 struct Neighbour *n = cls;
1337 struct MessageEntry *m;
1342 m = n->encrypted_head;
1346 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1347 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1348 GNUNET_i2s (&n->peer));
1352 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1359 GNUNET_assert (size >= m->size);
1360 memcpy (cbuf, &m[1], m->size);
1362 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1365 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1366 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1367 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1369 GNUNET_i2s (&n->peer));
1371 process_encrypted_neighbour_queue (n);
1376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1377 "Transmission of message of type %u and size %u failed\n",
1378 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1379 (unsigned int) m->size);
1383 consider_free_neighbour (n);
1389 * Check if we have plaintext messages for the specified neighbour
1390 * pending, and if so, consider batching and encrypting them (and
1391 * then trigger processing of the encrypted queue if needed).
1393 * @param n neighbour to check.
1395 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1399 * Check if we have encrypted messages for the specified neighbour
1400 * pending, and if so, check with the transport about sending them
1403 * @param n neighbour to check.
1406 process_encrypted_neighbour_queue (struct Neighbour *n)
1408 struct MessageEntry *m;
1411 return; /* request already pending */
1412 m = n->encrypted_head;
1415 /* encrypted queue empty, try plaintext instead */
1416 process_plaintext_neighbour_queue (n);
1420 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1421 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1422 (unsigned int) m->size,
1423 GNUNET_i2s (&n->peer),
1424 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).
1428 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1431 GNUNET_TIME_absolute_get_remaining
1433 ¬ify_encrypted_transmit_ready,
1437 /* message request too large or duplicate request */
1439 /* discard encrypted message */
1440 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1444 process_encrypted_neighbour_queue (n);
1450 * Decrypt size bytes from in and write the result to out. Use the
1451 * key for inbound traffic of the given neighbour. This function does
1452 * NOT do any integrity-checks on the result.
1454 * @param n neighbour we are receiving from
1455 * @param iv initialization vector to use
1456 * @param in ciphertext
1457 * @param out plaintext
1458 * @param size size of in/out
1459 * @return GNUNET_OK on success
1462 do_decrypt (struct Neighbour *n,
1463 const GNUNET_HashCode * iv,
1464 const void *in, void *out, size_t size)
1466 if (size != (uint16_t) size)
1471 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1472 (n->status != PEER_STATE_KEY_CONFIRMED))
1474 GNUNET_break_op (0);
1475 return GNUNET_SYSERR;
1478 GNUNET_CRYPTO_aes_decrypt (in,
1482 GNUNET_CRYPTO_AesInitializationVector *) iv,
1486 return GNUNET_SYSERR;
1488 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1490 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1491 "Decrypted %u bytes from `%4s' using key %u\n",
1492 (unsigned int) size,
1493 GNUNET_i2s (&n->peer),
1494 (unsigned int) n->decrypt_key.crc32);
1501 * Select messages for transmission. This heuristic uses a combination
1502 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1503 * and priority-based discard (in case no feasible schedule exist) and
1504 * speculative optimization (defer any kind of transmission until
1505 * we either create a batch of significant size, 25% of max, or until
1506 * we are close to a deadline). Furthermore, when scheduling the
1507 * heuristic also packs as many messages into the batch as possible,
1508 * starting with those with the earliest deadline. Yes, this is fun.
1510 * @param n neighbour to select messages from
1511 * @param size number of bytes to select for transmission
1512 * @param retry_time set to the time when we should try again
1513 * (only valid if this function returns zero)
1514 * @return number of bytes selected, or 0 if we decided to
1515 * defer scheduling overall; in that case, retry_time is set.
1518 select_messages (struct Neighbour *n,
1519 size_t size, struct GNUNET_TIME_Relative *retry_time)
1521 struct MessageEntry *pos;
1522 struct MessageEntry *min;
1523 struct MessageEntry *last;
1524 unsigned int min_prio;
1525 struct GNUNET_TIME_Absolute t;
1526 struct GNUNET_TIME_Absolute now;
1527 struct GNUNET_TIME_Relative delta;
1529 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1532 unsigned int queue_size;
1533 int discard_low_prio;
1535 GNUNET_assert (NULL != n->messages);
1536 now = GNUNET_TIME_absolute_get ();
1537 /* last entry in linked list of messages processed */
1539 /* should we remove the entry with the lowest
1540 priority from consideration for scheduling at the
1551 discard_low_prio = GNUNET_YES;
1552 while (GNUNET_YES == discard_low_prio)
1556 discard_low_prio = GNUNET_NO;
1557 /* calculate number of bytes available for transmission at time "t" */
1558 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1560 /* how many bytes have we (hypothetically) scheduled so far */
1562 /* maximum time we can wait before transmitting anything
1563 and still make all of our deadlines */
1564 slack = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1566 /* note that we use "*2" here because we want to look
1567 a bit further into the future; much more makes no
1568 sense since new message might be scheduled in the
1570 while ((pos != NULL) && (off < size * 2))
1572 if (pos->do_transmit == GNUNET_YES)
1574 /* already removed from consideration */
1578 if (discard_low_prio == GNUNET_NO)
1580 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1581 if (delta.value > 0)
1583 // FIXME: HUH? Check!
1585 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1588 if (avail < pos->size)
1590 // FIXME: HUH? Check!
1591 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1596 /* update slack, considering both its absolute deadline
1597 and relative deadlines caused by other messages
1598 with their respective load */
1599 slack = GNUNET_TIME_relative_min (slack,
1600 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1602 if (pos->deadline.value <= now.value)
1605 slack = GNUNET_TIME_UNIT_ZERO;
1607 else if (GNUNET_YES == pos->got_slack)
1609 /* should be soon now! */
1610 slack = GNUNET_TIME_relative_min (slack,
1611 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1616 GNUNET_TIME_relative_min (slack,
1617 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1618 pos->got_slack = GNUNET_YES;
1619 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1620 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
1625 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1626 if (pos->priority <= min_prio)
1628 /* update min for discard */
1629 min_prio = pos->priority;
1634 if (discard_low_prio)
1636 GNUNET_assert (min != NULL);
1637 /* remove lowest-priority entry from consideration */
1638 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1642 /* guard against sending "tiny" messages with large headers without
1644 if ( (slack.value > 0) &&
1646 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1648 /* less than 25% of message would be filled with deadlines still
1649 being met if we delay by one second or more; so just wait for
1650 more data; but do not wait longer than 1s (since we don't want
1651 to delay messages for a really long time either). */
1652 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1653 /* reset do_transmit values for next time */
1656 pos->do_transmit = GNUNET_NO;
1660 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1661 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1662 (unsigned long long) slack.value,
1664 (unsigned int) size);
1668 /* select marked messages (up to size) for transmission */
1673 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1675 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1680 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1685 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1686 (unsigned long long) off, (unsigned long long) tsize,
1687 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
1688 GNUNET_i2s (&n->peer));
1695 * Batch multiple messages into a larger buffer.
1697 * @param n neighbour to take messages from
1698 * @param buf target buffer
1699 * @param size size of buf
1700 * @param deadline set to transmission deadline for the result
1701 * @param retry_time set to the time when we should try again
1702 * (only valid if this function returns zero)
1703 * @param priority set to the priority of the batch
1704 * @return number of bytes written to buf (can be zero)
1707 batch_message (struct Neighbour *n,
1710 struct GNUNET_TIME_Absolute *deadline,
1711 struct GNUNET_TIME_Relative *retry_time,
1712 unsigned int *priority)
1714 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1715 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1716 struct MessageEntry *pos;
1717 struct MessageEntry *prev;
1718 struct MessageEntry *next;
1723 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1724 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1725 if (0 == select_messages (n, size, retry_time))
1728 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1729 "No messages selected, will try again in %llu ms\n",
1734 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1735 ntm->distance = htonl (n->last_distance);
1736 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1737 ntm->peer = n->peer;
1741 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1744 if (GNUNET_YES == pos->do_transmit)
1746 GNUNET_assert (pos->size <= size);
1747 /* do notifications */
1748 /* FIXME: track if we have *any* client that wants
1749 full notifications and only do this if that is
1751 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1753 memcpy (&ntm[1], &pos[1], pos->size);
1754 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1755 sizeof (struct GNUNET_MessageHeader));
1756 send_to_all_clients (&ntm->header,
1758 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1762 /* message too large for 'full' notifications, we do at
1763 least the 'hdr' type */
1766 sizeof (struct GNUNET_MessageHeader));
1768 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1770 send_to_all_clients (&ntm->header,
1772 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1774 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1775 "Encrypting message of type %u\n",
1776 (unsigned int) ntohs(((struct GNUNET_MessageHeader*)&pos[1])->type));
1778 /* copy for encrypted transmission */
1779 memcpy (&buf[ret], &pos[1], pos->size);
1782 *priority += pos->priority;
1784 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1785 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1786 (unsigned int) pos->size,
1787 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1789 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1803 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1804 "Deadline for message batch is %llu ms\n",
1805 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1812 * Remove messages with deadlines that have long expired from
1815 * @param n neighbour to inspect
1818 discard_expired_messages (struct Neighbour *n)
1820 struct MessageEntry *prev;
1821 struct MessageEntry *next;
1822 struct MessageEntry *pos;
1823 struct GNUNET_TIME_Absolute now;
1824 struct GNUNET_TIME_Relative delta;
1826 now = GNUNET_TIME_absolute_get ();
1832 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1833 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1836 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1837 "Message is %llu ms past due, discarding.\n",
1854 * Signature of the main function of a task.
1856 * @param cls closure
1857 * @param tc context information (why was this task triggered now)
1860 retry_plaintext_processing (void *cls,
1861 const struct GNUNET_SCHEDULER_TaskContext *tc)
1863 struct Neighbour *n = cls;
1865 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1866 process_plaintext_neighbour_queue (n);
1871 * Send our key (and encrypted PING) to the other peer.
1873 * @param n the other peer
1875 static void send_key (struct Neighbour *n);
1878 * Task that will retry "send_key" if our previous attempt failed
1882 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1884 struct Neighbour *n = cls;
1887 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1888 "Retrying key transmission to `%4s'\n",
1889 GNUNET_i2s (&n->peer));
1891 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1892 n->set_key_retry_frequency =
1893 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1899 * Check if we have plaintext messages for the specified neighbour
1900 * pending, and if so, consider batching and encrypting them (and
1901 * then trigger processing of the encrypted queue if needed).
1903 * @param n neighbour to check.
1906 process_plaintext_neighbour_queue (struct Neighbour *n)
1908 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1911 struct EncryptedMessage *em; /* encrypted message */
1912 struct EncryptedMessage *ph; /* plaintext header */
1913 struct MessageEntry *me;
1914 unsigned int priority;
1915 struct GNUNET_TIME_Absolute deadline;
1916 struct GNUNET_TIME_Relative retry_time;
1919 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1921 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1922 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1926 case PEER_STATE_DOWN:
1929 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1930 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1931 GNUNET_i2s(&n->peer));
1934 case PEER_STATE_KEY_SENT:
1935 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1936 n->retry_set_key_task
1937 = GNUNET_SCHEDULER_add_delayed (sched,
1938 n->set_key_retry_frequency,
1939 &set_key_retry_task, n);
1941 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1942 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1943 GNUNET_i2s(&n->peer));
1946 case PEER_STATE_KEY_RECEIVED:
1947 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1948 n->retry_set_key_task
1949 = GNUNET_SCHEDULER_add_delayed (sched,
1950 n->set_key_retry_frequency,
1951 &set_key_retry_task, n);
1953 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1954 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1955 GNUNET_i2s(&n->peer));
1958 case PEER_STATE_KEY_CONFIRMED:
1959 /* ready to continue */
1962 discard_expired_messages (n);
1963 if (n->messages == NULL)
1966 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1967 "Plaintext message queue for `%4s' is empty.\n",
1968 GNUNET_i2s(&n->peer));
1970 return; /* no pending messages */
1972 if (n->encrypted_head != NULL)
1975 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1976 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1977 GNUNET_i2s(&n->peer));
1979 return; /* wait for messages already encrypted to be
1982 ph = (struct EncryptedMessage *) pbuf;
1983 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1985 used = sizeof (struct EncryptedMessage);
1986 used += batch_message (n,
1988 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1989 &deadline, &retry_time, &priority);
1990 if (used == sizeof (struct EncryptedMessage))
1993 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1994 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1995 GNUNET_i2s(&n->peer));
1997 /* no messages selected for sending, try again later... */
1998 n->retry_plaintext_task =
1999 GNUNET_SCHEDULER_add_delayed (sched,
2001 &retry_plaintext_processing, n);
2004 #if DEBUG_CORE_QUOTA
2005 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2006 "Sending %u b/s as new limit to peer `%4s'\n",
2007 (unsigned int) ntohl (n->bw_in.value__),
2008 GNUNET_i2s (&n->peer));
2010 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1));
2011 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2012 ph->inbound_bw_limit = n->bw_in;
2013 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2015 /* setup encryption message header */
2016 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2017 me->deadline = deadline;
2018 me->priority = priority;
2020 em = (struct EncryptedMessage *) &me[1];
2021 em->header.size = htons (used);
2022 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2023 em->iv_seed = ph->iv_seed;
2024 esize = used - ENCRYPTED_HEADER_SIZE;
2025 GNUNET_CRYPTO_hash (&ph->sequence_number,
2026 esize - sizeof (GNUNET_HashCode),
2027 &ph->plaintext_hash);
2028 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
2030 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2031 "Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
2032 (unsigned int) (esize - sizeof (GNUNET_HashCode)),
2033 GNUNET_h2s (&ph->plaintext_hash),
2038 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2039 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2040 (unsigned int) esize,
2041 GNUNET_i2s(&n->peer),
2042 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2044 GNUNET_assert (GNUNET_OK ==
2047 &ph->plaintext_hash,
2048 &em->plaintext_hash, esize));
2049 /* append to transmission list */
2050 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2054 process_encrypted_neighbour_queue (n);
2059 * Function that recalculates the bandwidth quota for the
2060 * given neighbour and transmits it to the transport service.
2062 * @param cls neighbour for the quota update
2066 neighbour_quota_update (void *cls,
2067 const struct GNUNET_SCHEDULER_TaskContext *tc);
2071 * Schedule the task that will recalculate the bandwidth
2072 * quota for this peer (and possibly force a disconnect of
2073 * idle peers by calculating a bandwidth of zero).
2076 schedule_quota_update (struct Neighbour *n)
2078 GNUNET_assert (n->quota_update_task ==
2079 GNUNET_SCHEDULER_NO_TASK);
2080 n->quota_update_task
2081 = GNUNET_SCHEDULER_add_delayed (sched,
2082 QUOTA_UPDATE_FREQUENCY,
2083 &neighbour_quota_update,
2089 * Initialize a new 'struct Neighbour'.
2091 * @param pid ID of the new neighbour
2092 * @return handle for the new neighbour
2094 static struct Neighbour *
2095 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2097 struct Neighbour *n;
2098 struct GNUNET_TIME_Absolute now;
2101 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2102 "Creating neighbour entry for peer `%4s'\n",
2105 n = GNUNET_malloc (sizeof (struct Neighbour));
2106 n->next = neighbours;
2109 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2111 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2112 now = GNUNET_TIME_absolute_get ();
2113 n->encrypt_key_created = now;
2114 n->last_activity = now;
2115 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2116 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2117 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2118 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init ((uint32_t) - 1);
2119 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2120 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2122 neighbour_quota_update (n, NULL);
2123 consider_free_neighbour (n);
2129 * Handle CORE_SEND request.
2132 * @param client the client issuing the request
2133 * @param message the "struct SendMessage"
2136 handle_client_send (void *cls,
2137 struct GNUNET_SERVER_Client *client,
2138 const struct GNUNET_MessageHeader *message)
2140 const struct SendMessage *sm;
2141 struct Neighbour *n;
2142 struct MessageEntry *prev;
2143 struct MessageEntry *pos;
2144 struct MessageEntry *e;
2145 struct MessageEntry *min_prio_entry;
2146 struct MessageEntry *min_prio_prev;
2147 unsigned int min_prio;
2148 unsigned int queue_size;
2151 msize = ntohs (message->size);
2153 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2157 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2160 sm = (const struct SendMessage *) message;
2161 msize -= sizeof (struct SendMessage);
2162 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2164 /* FIXME: should we not allow loopback-injection here? */
2167 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2170 n = find_neighbour (&sm->peer);
2172 n = create_neighbour (&sm->peer);
2174 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2175 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2177 (unsigned int) msize,
2178 GNUNET_i2s (&sm->peer));
2180 /* bound queue size */
2181 discard_expired_messages (n);
2182 min_prio = (unsigned int) -1;
2183 min_prio_entry = NULL;
2184 min_prio_prev = NULL;
2190 if (pos->priority < min_prio)
2192 min_prio_entry = pos;
2193 min_prio_prev = prev;
2194 min_prio = pos->priority;
2200 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2203 if (ntohl(sm->priority) <= min_prio)
2205 /* discard new entry */
2207 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2208 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2210 (unsigned int) MAX_PEER_QUEUE_SIZE,
2211 (unsigned int) msize,
2212 (unsigned int) ntohs (message->type));
2215 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2218 /* discard "min_prio_entry" */
2220 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2221 "Queue full, discarding existing older request\n");
2223 if (min_prio_prev == NULL)
2224 n->messages = min_prio_entry->next;
2226 min_prio_prev->next = min_prio_entry->next;
2227 GNUNET_free (min_prio_entry);
2231 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2232 "Adding transmission request for `%4s' of size %u to queue\n",
2233 GNUNET_i2s (&sm->peer),
2234 (unsigned int) msize);
2236 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2237 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2238 e->priority = ntohl (sm->priority);
2240 memcpy (&e[1], &sm[1], msize);
2242 /* insert, keep list sorted by deadline */
2245 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2256 /* consider scheduling now */
2257 process_plaintext_neighbour_queue (n);
2259 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2264 * Function called when the transport service is ready to
2265 * receive a message. Only resets 'n->th' to NULL.
2267 * @param cls neighbour to use message from
2268 * @param size number of bytes we can transmit
2269 * @param buf where to copy the message
2270 * @return number of bytes transmitted
2273 notify_transport_connect_done (void *cls, size_t size, void *buf)
2275 struct Neighbour *n = cls;
2280 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2281 _("Failed to connect to `%4s': transport failed to connect\n"),
2282 GNUNET_i2s (&n->peer));
2285 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2286 _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2287 GNUNET_i2s (&n->peer));
2288 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2289 GNUNET_SCHEDULER_cancel (sched,
2290 n->retry_set_key_task);
2291 n->retry_set_key_task = GNUNET_SCHEDULER_add_now (sched,
2292 &set_key_retry_task,
2299 * Handle CORE_REQUEST_CONNECT request.
2302 * @param client the client issuing the request
2303 * @param message the "struct ConnectMessage"
2306 handle_client_request_connect (void *cls,
2307 struct GNUNET_SERVER_Client *client,
2308 const struct GNUNET_MessageHeader *message)
2310 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2311 struct Neighbour *n;
2312 struct GNUNET_TIME_Relative timeout;
2314 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2317 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2320 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2321 n = find_neighbour (&cm->peer);
2323 n = create_neighbour (&cm->peer);
2324 if ( (GNUNET_YES == n->is_connected) ||
2326 return; /* already connected, or at least trying */
2327 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2329 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2330 "Core received `%s' request for `%4s', will try to establish connection\n",
2332 GNUNET_i2s (&cm->peer));
2334 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2335 /* ask transport to connect to the peer */
2336 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2338 sizeof (struct GNUNET_MessageHeader), 0,
2340 ¬ify_transport_connect_done,
2342 GNUNET_break (NULL != n->th);
2347 * List of handlers for the messages understood by this
2350 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2351 {&handle_client_init, NULL,
2352 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2353 {&handle_client_request_info, NULL,
2354 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2355 sizeof (struct RequestInfoMessage)},
2356 {&handle_client_send, NULL,
2357 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2358 {&handle_client_request_connect, NULL,
2359 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2360 sizeof (struct ConnectMessage)},
2366 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2367 * the neighbour's struct and retry send_key. Or, if we did not get a
2368 * HELLO, just do nothing.
2370 * @param cls the 'struct Neighbour' to retry sending the key for
2371 * @param peer the peer for which this is the HELLO
2372 * @param hello HELLO message of that peer
2373 * @param trust amount of trust we currently have in that peer
2376 process_hello_retry_send_key (void *cls,
2377 const struct GNUNET_PeerIdentity *peer,
2378 const struct GNUNET_HELLO_Message *hello,
2381 struct Neighbour *n = cls;
2386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2387 "Entered `%s' and `%s' is NULL!\n",
2388 "process_hello_retry_send_key",
2392 if (n->public_key != NULL)
2394 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2396 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2397 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2399 GNUNET_STATISTICS_update (stats,
2400 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2407 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2408 _("Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n"),
2409 GNUNET_i2s (&n->peer));
2410 GNUNET_STATISTICS_update (stats,
2411 gettext_noop ("# Delayed connecting due to lack of public key"),
2414 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2415 n->retry_set_key_task
2416 = GNUNET_SCHEDULER_add_delayed (sched,
2417 n->set_key_retry_frequency,
2418 &set_key_retry_task, n);
2424 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2425 "Entered `%s' for peer `%4s'\n",
2426 "process_hello_retry_send_key",
2429 if (n->public_key != NULL)
2431 /* already have public key, why are we here? */
2437 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2438 "Received new `%s' message for `%4s', initiating key exchange.\n",
2443 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2444 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2446 GNUNET_STATISTICS_update (stats,
2447 gettext_noop ("# Error extracting public key from HELLO"),
2450 GNUNET_free (n->public_key);
2451 n->public_key = NULL;
2453 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2454 "GNUNET_HELLO_get_key returned awfully\n");
2462 * Send our key (and encrypted PING) to the other peer.
2464 * @param n the other peer
2467 send_key (struct Neighbour *n)
2469 struct MessageEntry *pos;
2470 struct SetKeyMessage *sm;
2471 struct MessageEntry *me;
2472 struct PingMessage pp;
2473 struct PingMessage *pm;
2475 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2477 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2478 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2480 if (n->pitr != NULL)
2483 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2484 "Key exchange in progress with `%4s'.\n",
2485 GNUNET_i2s (&n->peer));
2487 return; /* already in progress */
2489 if (GNUNET_YES != n->is_connected)
2492 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2493 "Not yet connected to peer `%4s'!\n",
2494 GNUNET_i2s (&n->peer));
2498 GNUNET_STATISTICS_update (stats,
2499 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
2502 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2504 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2506 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2507 ¬ify_encrypted_transmit_ready,
2513 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2514 "Asked to perform key exchange with `%4s'.\n",
2515 GNUNET_i2s (&n->peer));
2517 if (n->public_key == NULL)
2519 /* lookup n's public key, then try again */
2521 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2522 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2523 GNUNET_i2s (&n->peer));
2525 GNUNET_assert (n->pitr == NULL);
2526 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2529 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2530 &process_hello_retry_send_key, n);
2533 pos = n->encrypted_head;
2536 if (GNUNET_YES == pos->is_setkey)
2538 if (pos->sender_status == n->status)
2541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2542 "`%s' message for `%4s' queued already\n",
2544 GNUNET_i2s (&n->peer));
2546 goto trigger_processing;
2548 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2553 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2554 "Removing queued `%s' message for `%4s', will create a new one\n",
2556 GNUNET_i2s (&n->peer));
2566 case PEER_STATE_DOWN:
2567 n->status = PEER_STATE_KEY_SENT;
2569 case PEER_STATE_KEY_SENT:
2571 case PEER_STATE_KEY_RECEIVED:
2573 case PEER_STATE_KEY_CONFIRMED:
2581 /* first, set key message */
2582 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2583 sizeof (struct SetKeyMessage) +
2584 sizeof (struct PingMessage));
2585 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2586 me->priority = SET_KEY_PRIORITY;
2587 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
2588 me->is_setkey = GNUNET_YES;
2589 me->got_slack = GNUNET_YES; /* do not defer this one! */
2590 me->sender_status = n->status;
2591 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2595 sm = (struct SetKeyMessage *) &me[1];
2596 sm->header.size = htons (sizeof (struct SetKeyMessage));
2597 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2598 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2599 PEER_STATE_KEY_SENT : n->status));
2601 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2602 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2603 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2604 sizeof (struct GNUNET_PeerIdentity));
2605 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2606 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2607 sm->target = n->peer;
2608 GNUNET_assert (GNUNET_OK ==
2609 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2611 GNUNET_CRYPTO_AesSessionKey),
2613 &sm->encrypted_key));
2614 GNUNET_assert (GNUNET_OK ==
2615 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2617 pm = (struct PingMessage *) &sm[1];
2618 pm->header.size = htons (sizeof (struct PingMessage));
2619 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2620 pp.challenge = htonl (n->ping_challenge);
2621 pp.target = n->peer;
2623 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2624 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u.\n",
2626 (unsigned int) n->ping_challenge,
2627 GNUNET_i2s (&n->peer),
2628 (unsigned int) n->encrypt_key.crc32);
2631 &n->peer.hashPubKey,
2634 sizeof (struct PingMessage) -
2635 sizeof (struct GNUNET_MessageHeader));
2636 GNUNET_STATISTICS_update (stats,
2637 gettext_noop ("# SET_KEY and PING messages created"),
2641 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2642 "Have %llu ms left for `%s' transmission.\n",
2643 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2647 /* trigger queue processing */
2648 process_encrypted_neighbour_queue (n);
2649 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2650 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2651 n->retry_set_key_task
2652 = GNUNET_SCHEDULER_add_delayed (sched,
2653 n->set_key_retry_frequency,
2654 &set_key_retry_task, n);
2659 * We received a SET_KEY message. Validate and update
2660 * our key material and status.
2662 * @param n the neighbour from which we received message m
2663 * @param m the set key message we received
2666 handle_set_key (struct Neighbour *n,
2667 const struct SetKeyMessage *m);
2671 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2672 * the neighbour's struct and retry handling the set_key message. Or,
2673 * if we did not get a HELLO, just free the set key message.
2675 * @param cls pointer to the set key message
2676 * @param peer the peer for which this is the HELLO
2677 * @param hello HELLO message of that peer
2678 * @param trust amount of trust we currently have in that peer
2681 process_hello_retry_handle_set_key (void *cls,
2682 const struct GNUNET_PeerIdentity *peer,
2683 const struct GNUNET_HELLO_Message *hello,
2686 struct Neighbour *n = cls;
2687 struct SetKeyMessage *sm = n->skm;
2693 if (n->public_key != NULL)
2696 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2697 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2699 GNUNET_i2s (&n->peer),
2702 handle_set_key (n, sm);
2706 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2707 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
2709 GNUNET_i2s (&n->peer));
2714 if (n->public_key != NULL)
2715 return; /* multiple HELLOs match!? */
2717 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2718 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2720 GNUNET_break_op (0);
2721 GNUNET_free (n->public_key);
2722 n->public_key = NULL;
2728 * We received a PING message. Validate and transmit
2731 * @param n sender of the PING
2732 * @param m the encrypted PING message itself
2735 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2737 struct PingMessage t;
2738 struct PongMessage tx;
2739 struct PongMessage *tp;
2740 struct MessageEntry *me;
2743 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2744 "Core service receives `%s' request from `%4s'.\n",
2745 "PING", GNUNET_i2s (&n->peer));
2749 &my_identity.hashPubKey,
2752 sizeof (struct PingMessage) -
2753 sizeof (struct GNUNET_MessageHeader)))
2756 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2757 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2759 GNUNET_i2s (&t.target),
2760 (unsigned int) ntohl (t.challenge),
2761 (unsigned int) n->decrypt_key.crc32);
2763 GNUNET_STATISTICS_update (stats,
2764 gettext_noop ("# PING messages decrypted"),
2767 if (0 != memcmp (&t.target,
2768 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2770 GNUNET_break_op (0);
2773 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2774 sizeof (struct PongMessage));
2775 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2779 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2780 me->priority = PONG_PRIORITY;
2781 me->size = sizeof (struct PongMessage);
2782 tx.reserved = htonl (0);
2783 tx.inbound_bw_limit = n->bw_in;
2784 tx.challenge = t.challenge;
2785 tx.target = t.target;
2786 tp = (struct PongMessage *) &me[1];
2787 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2788 tp->header.size = htons (sizeof (struct PongMessage));
2790 &my_identity.hashPubKey,
2793 sizeof (struct PongMessage) -
2794 sizeof (struct GNUNET_MessageHeader));
2795 GNUNET_STATISTICS_update (stats,
2796 gettext_noop ("# PONG messages created"),
2800 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2801 "Encrypting `%s' with challenge %u using key %u\n",
2803 (unsigned int) ntohl (t.challenge),
2804 (unsigned int) n->encrypt_key.crc32);
2806 /* trigger queue processing */
2807 process_encrypted_neighbour_queue (n);
2812 * We received a PONG message. Validate and update our status.
2814 * @param n sender of the PONG
2815 * @param m the encrypted PONG message itself
2818 handle_pong (struct Neighbour *n,
2819 const struct PongMessage *m)
2821 struct PongMessage t;
2822 struct ConnectNotifyMessage cnm;
2825 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2826 "Core service receives `%s' response from `%4s'.\n",
2827 "PONG", GNUNET_i2s (&n->peer));
2829 /* mark as garbage, just to be sure */
2830 memset (&t, 255, sizeof (t));
2833 &n->peer.hashPubKey,
2836 sizeof (struct PongMessage) -
2837 sizeof (struct GNUNET_MessageHeader)))
2839 GNUNET_break_op (0);
2842 GNUNET_STATISTICS_update (stats,
2843 gettext_noop ("# PONG messages decrypted"),
2846 if (0 != ntohl (t.reserved))
2848 GNUNET_break_op (0);
2852 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2853 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2855 GNUNET_i2s (&t.target),
2856 (unsigned int) ntohl (t.challenge),
2857 (unsigned int) n->decrypt_key.crc32);
2859 if ((0 != memcmp (&t.target,
2861 sizeof (struct GNUNET_PeerIdentity))) ||
2862 (n->ping_challenge != ntohl (t.challenge)))
2864 /* PONG malformed */
2866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2867 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2869 GNUNET_i2s (&n->peer),
2870 (unsigned int) n->ping_challenge);
2871 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2872 "Received malformed `%s' received from `%4s' with challenge %u\n",
2873 "PONG", GNUNET_i2s (&t.target),
2874 (unsigned int) ntohl (t.challenge));
2876 GNUNET_break_op (0);
2881 case PEER_STATE_DOWN:
2882 GNUNET_break (0); /* should be impossible */
2884 case PEER_STATE_KEY_SENT:
2885 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2887 case PEER_STATE_KEY_RECEIVED:
2888 GNUNET_STATISTICS_update (stats,
2889 gettext_noop ("# Session keys confirmed via PONG"),
2892 n->status = PEER_STATE_KEY_CONFIRMED;
2893 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2895 n->bw_out_external_limit = t.inbound_bw_limit;
2896 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2897 n->bw_out_internal_limit);
2898 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2900 GNUNET_TRANSPORT_set_quota (transport,
2904 GNUNET_TIME_UNIT_FOREVER_REL,
2908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2909 "Confirmed key via `%s' message for peer `%4s'\n",
2910 "PONG", GNUNET_i2s (&n->peer));
2912 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2914 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2915 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2917 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2918 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2919 cnm.distance = htonl (n->last_distance);
2920 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2922 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2923 process_encrypted_neighbour_queue (n);
2925 case PEER_STATE_KEY_CONFIRMED:
2926 n->last_activity = GNUNET_TIME_absolute_get ();
2927 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2928 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2930 = GNUNET_SCHEDULER_add_delayed (sched,
2931 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2943 * We received a SET_KEY message. Validate and update
2944 * our key material and status.
2946 * @param n the neighbour from which we received message m
2947 * @param m the set key message we received
2950 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2952 struct SetKeyMessage *m_cpy;
2953 struct GNUNET_TIME_Absolute t;
2954 struct GNUNET_CRYPTO_AesSessionKey k;
2955 struct PingMessage *ping;
2956 struct PongMessage *pong;
2957 enum PeerStateMachine sender_status;
2960 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2961 "Core service receives `%s' request from `%4s'.\n",
2962 "SET_KEY", GNUNET_i2s (&n->peer));
2964 if (n->public_key == NULL)
2966 if (n->pitr != NULL)
2969 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2970 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2976 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2977 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2979 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2980 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2981 /* lookup n's public key, then try again */
2982 GNUNET_assert (n->skm == NULL);
2984 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2987 GNUNET_TIME_UNIT_MINUTES,
2988 &process_hello_retry_handle_set_key, n);
2989 GNUNET_STATISTICS_update (stats,
2990 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2995 if (0 != memcmp (&m->target,
2997 sizeof (struct GNUNET_PeerIdentity)))
2999 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3000 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3002 GNUNET_i2s (&m->target));
3005 if ((ntohl (m->purpose.size) !=
3006 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3007 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3008 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3009 sizeof (struct GNUNET_PeerIdentity)) ||
3011 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3012 &m->purpose, &m->signature, n->public_key)))
3014 /* invalid signature */
3015 GNUNET_break_op (0);
3018 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3019 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3020 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3021 (t.value < n->decrypt_key_created.value))
3023 /* this could rarely happen due to massive re-ordering of
3024 messages on the network level, but is most likely either
3025 a bug or some adversary messing with us. Report. */
3026 GNUNET_break_op (0);
3030 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3031 "Decrypting key material.\n");
3033 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3036 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3037 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3038 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3040 /* failed to decrypt !? */
3041 GNUNET_break_op (0);
3044 GNUNET_STATISTICS_update (stats,
3045 gettext_noop ("# SET_KEY messages decrypted"),
3049 if (n->decrypt_key_created.value != t.value)
3051 /* fresh key, reset sequence numbers */
3052 n->last_sequence_number_received = 0;
3053 n->last_packets_bitmap = 0;
3054 n->decrypt_key_created = t;
3056 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3059 case PEER_STATE_DOWN:
3060 n->status = PEER_STATE_KEY_RECEIVED;
3062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3063 "Responding to `%s' with my own key.\n", "SET_KEY");
3067 case PEER_STATE_KEY_SENT:
3068 case PEER_STATE_KEY_RECEIVED:
3069 n->status = PEER_STATE_KEY_RECEIVED;
3070 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3071 (sender_status != PEER_STATE_KEY_CONFIRMED))
3074 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3075 "Responding to `%s' with my own key (other peer has status %u).\n",
3077 (unsigned int) sender_status);
3082 case PEER_STATE_KEY_CONFIRMED:
3083 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3084 (sender_status != PEER_STATE_KEY_CONFIRMED))
3087 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3088 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3090 (unsigned int) sender_status);
3099 if (n->pending_ping != NULL)
3101 ping = n->pending_ping;
3102 n->pending_ping = NULL;
3103 handle_ping (n, ping);
3106 if (n->pending_pong != NULL)
3108 pong = n->pending_pong;
3109 n->pending_pong = NULL;
3110 handle_pong (n, pong);
3117 * Send a P2P message to a client.
3119 * @param sender who sent us the message?
3120 * @param client who should we give the message to?
3121 * @param m contains the message to transmit
3122 * @param msize number of bytes in buf to transmit
3125 send_p2p_message_to_client (struct Neighbour *sender,
3126 struct Client *client,
3127 const void *m, size_t msize)
3129 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3130 struct NotifyTrafficMessage *ntm;
3133 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3134 "Core service passes message from `%4s' of type %u to client.\n",
3135 GNUNET_i2s(&sender->peer),
3136 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3138 ntm = (struct NotifyTrafficMessage *) buf;
3139 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3140 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3141 ntm->distance = htonl (sender->last_distance);
3142 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3143 ntm->peer = sender->peer;
3144 memcpy (&ntm[1], m, msize);
3145 send_to_client (client, &ntm->header, GNUNET_YES);
3150 * Deliver P2P message to interested clients.
3152 * @param sender who sent us the message?
3153 * @param m the message
3154 * @param msize size of the message (including header)
3157 deliver_message (struct Neighbour *sender,
3158 const struct GNUNET_MessageHeader *m, size_t msize)
3161 struct Client *cpos;
3167 type = ntohs (m->type);
3169 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3170 "Received encapsulated message of type %u from `%4s'\n",
3171 (unsigned int) type,
3172 GNUNET_i2s (&sender->peer));
3174 GNUNET_snprintf (buf,
3176 gettext_noop ("# bytes of messages of type %u received"),
3177 (unsigned int) type);
3178 GNUNET_STATISTICS_set (stats,
3182 dropped = GNUNET_YES;
3184 while (cpos != NULL)
3186 deliver_full = GNUNET_NO;
3187 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3188 deliver_full = GNUNET_YES;
3191 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3193 if (type != cpos->types[tpos])
3195 deliver_full = GNUNET_YES;
3199 if (GNUNET_YES == deliver_full)
3201 send_p2p_message_to_client (sender, cpos, m, msize);
3202 dropped = GNUNET_NO;
3204 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3206 send_p2p_message_to_client (sender, cpos, m,
3207 sizeof (struct GNUNET_MessageHeader));
3211 if (dropped == GNUNET_YES)
3214 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3215 "Message of type %u from `%4s' not delivered to any client.\n",
3216 (unsigned int) type,
3217 GNUNET_i2s (&sender->peer));
3219 /* FIXME: stats... */
3225 * Align P2P message and then deliver to interested clients.
3227 * @param sender who sent us the message?
3228 * @param buffer unaligned (!) buffer containing message
3229 * @param msize size of the message (including header)
3232 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
3236 /* TODO: call to statistics? */
3237 memcpy (abuf, buffer, msize);
3238 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
3243 * Deliver P2P messages to interested clients.
3245 * @param sender who sent us the message?
3246 * @param buffer buffer containing messages, can be modified
3247 * @param buffer_size size of the buffer (overall)
3248 * @param offset offset where messages in the buffer start
3251 deliver_messages (struct Neighbour *sender,
3252 const char *buffer, size_t buffer_size, size_t offset)
3254 struct GNUNET_MessageHeader *mhp;
3255 struct GNUNET_MessageHeader mh;
3259 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
3261 if (0 != offset % sizeof (uint16_t))
3263 /* outch, need to copy to access header */
3264 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
3269 /* can access header directly */
3270 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
3272 msize = ntohs (mhp->size);
3273 if (msize + offset > buffer_size)
3275 /* malformed message, header says it is larger than what
3276 would fit into the overall buffer */
3277 GNUNET_break_op (0);
3280 #if HAVE_UNALIGNED_64_ACCESS
3281 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
3283 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
3285 if (GNUNET_YES == need_align)
3286 align_and_deliver (sender, &buffer[offset], msize);
3288 deliver_message (sender,
3289 (const struct GNUNET_MessageHeader *)
3290 &buffer[offset], msize);
3297 * We received an encrypted message. Decrypt, validate and
3298 * pass on to the appropriate clients.
3301 handle_encrypted_message (struct Neighbour *n,
3302 const struct EncryptedMessage *m)
3304 size_t size = ntohs (m->header.size);
3306 struct EncryptedMessage *pt; /* plaintext */
3309 struct GNUNET_TIME_Absolute t;
3313 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3314 "Core service receives `%s' request from `%4s'.\n",
3315 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3317 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3323 &buf[ENCRYPTED_HEADER_SIZE],
3324 size - ENCRYPTED_HEADER_SIZE))
3326 pt = (struct EncryptedMessage *) buf;
3328 GNUNET_CRYPTO_hash (&pt->sequence_number,
3329 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3332 "V-Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
3333 (unsigned int) (size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode)),
3337 if (0 != memcmp (&ph,
3338 &pt->plaintext_hash,
3339 sizeof (GNUNET_HashCode)))
3341 /* checksum failed */
3342 GNUNET_break_op (0);
3346 /* validate sequence number */
3347 snum = ntohl (pt->sequence_number);
3348 if (n->last_sequence_number_received == snum)
3350 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3351 "Received duplicate message, ignoring.\n");
3352 /* duplicate, ignore */
3353 GNUNET_STATISTICS_set (stats,
3354 gettext_noop ("# bytes dropped (duplicates)"),
3359 if ((n->last_sequence_number_received > snum) &&
3360 (n->last_sequence_number_received - snum > 32))
3362 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3363 "Received ancient out of sequence message, ignoring.\n");
3364 /* ancient out of sequence, ignore */
3365 GNUNET_STATISTICS_set (stats,
3366 gettext_noop ("# bytes dropped (out of sequence)"),
3371 if (n->last_sequence_number_received > snum)
3373 unsigned int rotbit =
3374 1 << (n->last_sequence_number_received - snum - 1);
3375 if ((n->last_packets_bitmap & rotbit) != 0)
3377 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3378 "Received duplicate message, ignoring.\n");
3379 GNUNET_STATISTICS_set (stats,
3380 gettext_noop ("# bytes dropped (duplicates)"),
3383 /* duplicate, ignore */
3386 n->last_packets_bitmap |= rotbit;
3388 if (n->last_sequence_number_received < snum)
3390 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3391 n->last_sequence_number_received = snum;
3394 /* check timestamp */
3395 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3396 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3398 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3400 ("Message received far too old (%llu ms). Content ignored.\n"),
3401 GNUNET_TIME_absolute_get_duration (t).value);
3402 GNUNET_STATISTICS_set (stats,
3403 gettext_noop ("# bytes dropped (ancient message)"),
3409 /* process decrypted message(s) */
3410 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3412 #if DEBUG_CORE_SET_QUOTA
3413 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3414 "Received %u b/s as new inbound limit for peer `%4s'\n",
3415 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3416 GNUNET_i2s (&n->peer));
3418 n->bw_out_external_limit = pt->inbound_bw_limit;
3419 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3420 n->bw_out_internal_limit);
3421 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3423 GNUNET_TRANSPORT_set_quota (transport,
3427 GNUNET_TIME_UNIT_FOREVER_REL,
3430 n->last_activity = GNUNET_TIME_absolute_get ();
3431 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3432 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3434 = GNUNET_SCHEDULER_add_delayed (sched,
3435 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3438 GNUNET_STATISTICS_set (stats,
3439 gettext_noop ("# bytes of payload decrypted"),
3440 size - sizeof (struct EncryptedMessage),
3442 deliver_messages (n, buf, size, sizeof (struct EncryptedMessage));
3447 * Function called by the transport for each received message.
3449 * @param cls closure
3450 * @param peer (claimed) identity of the other peer
3451 * @param message the message
3452 * @param latency estimated latency for communicating with the
3453 * given peer (round-trip)
3454 * @param distance in overlay hops, as given by transport plugin
3457 handle_transport_receive (void *cls,
3458 const struct GNUNET_PeerIdentity *peer,
3459 const struct GNUNET_MessageHeader *message,
3460 struct GNUNET_TIME_Relative latency,
3461 unsigned int distance)
3463 struct Neighbour *n;
3464 struct GNUNET_TIME_Absolute now;
3470 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3471 "Received message of type %u from `%4s', demultiplexing.\n",
3472 (unsigned int) ntohs (message->type),
3475 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3480 n = find_neighbour (peer);
3482 n = create_neighbour (peer);
3483 n->last_latency = latency;
3484 n->last_distance = distance;
3485 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3486 type = ntohs (message->type);
3487 size = ntohs (message->size);
3490 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3491 if (size != sizeof (struct SetKeyMessage))
3493 GNUNET_break_op (0);
3496 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3497 handle_set_key (n, (const struct SetKeyMessage *) message);
3499 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3500 if (size < sizeof (struct EncryptedMessage) +
3501 sizeof (struct GNUNET_MessageHeader))
3503 GNUNET_break_op (0);
3506 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3507 (n->status != PEER_STATE_KEY_CONFIRMED))
3509 GNUNET_break_op (0);
3512 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3514 case GNUNET_MESSAGE_TYPE_CORE_PING:
3515 if (size != sizeof (struct PingMessage))
3517 GNUNET_break_op (0);
3520 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3521 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3522 (n->status != PEER_STATE_KEY_CONFIRMED))
3525 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3526 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3527 "PING", GNUNET_i2s (&n->peer));
3529 GNUNET_free_non_null (n->pending_ping);
3530 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3531 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3534 handle_ping (n, (const struct PingMessage *) message);
3536 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3537 if (size != sizeof (struct PongMessage))
3539 GNUNET_break_op (0);
3542 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3543 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3544 (n->status != PEER_STATE_KEY_CONFIRMED) )
3547 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3548 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3549 "PONG", GNUNET_i2s (&n->peer));
3551 GNUNET_free_non_null (n->pending_pong);
3552 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3553 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3556 handle_pong (n, (const struct PongMessage *) message);
3559 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3560 _("Unsupported message of type %u received.\n"),
3561 (unsigned int) type);
3564 if (n->status == PEER_STATE_KEY_CONFIRMED)
3566 now = GNUNET_TIME_absolute_get ();
3567 n->last_activity = now;
3570 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3571 n->time_established = now;
3573 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3574 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3576 = GNUNET_SCHEDULER_add_delayed (sched,
3577 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3585 * Function that recalculates the bandwidth quota for the
3586 * given neighbour and transmits it to the transport service.
3588 * @param cls neighbour for the quota update
3592 neighbour_quota_update (void *cls,
3593 const struct GNUNET_SCHEDULER_TaskContext *tc)
3595 struct Neighbour *n = cls;
3596 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3599 unsigned long long distributable;
3600 uint64_t need_per_peer;
3601 uint64_t need_per_second;
3604 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3605 "Neighbour quota update calculation running for peer `%4s'\n"
3606 GNUNET_i2s (&n->peer));
3608 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3609 /* calculate relative preference among all neighbours;
3610 divides by a bit more to avoid division by zero AND to
3611 account for possibility of new neighbours joining any time
3612 AND to convert to double... */
3613 if (preference_sum == 0)
3615 pref_rel = 1.0 / (double) neighbour_count;
3619 pref_rel = n->current_preference / preference_sum;
3621 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3622 GNUNET_TIME_UNIT_SECONDS);
3623 need_per_second = need_per_peer * neighbour_count;
3625 if (bandwidth_target_out_bps > need_per_second)
3626 distributable = bandwidth_target_out_bps - need_per_second;
3627 share = distributable * pref_rel;
3628 if (share + need_per_peer > ( (uint32_t)-1))
3629 q_in = GNUNET_BANDWIDTH_value_init ((uint32_t) -1);
3631 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3632 /* check if we want to disconnect for good due to inactivity */
3633 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3634 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3637 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3638 "Forcing disconnect of `%4s' due to inactivity\n",
3639 GNUNET_i2s (&n->peer));
3641 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3643 #if DEBUG_CORE_QUOTA
3644 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3645 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3646 GNUNET_i2s (&n->peer),
3647 (unsigned int) ntohl (q_in.value__),
3648 bandwidth_target_out_bps,
3649 (unsigned int) ntohl (n->bw_in.value__),
3650 (unsigned int) ntohl (n->bw_out.value__),
3651 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3653 if (n->bw_in.value__ != q_in.value__)
3656 if (GNUNET_YES == n->is_connected)
3657 GNUNET_TRANSPORT_set_quota (transport,
3661 GNUNET_TIME_UNIT_FOREVER_REL,
3664 schedule_quota_update (n);
3669 * Function called by transport to notify us that
3670 * a peer connected to us (on the network level).
3672 * @param cls closure
3673 * @param peer the peer that connected
3674 * @param latency current latency of the connection
3675 * @param distance in overlay hops, as given by transport plugin
3678 handle_transport_notify_connect (void *cls,
3679 const struct GNUNET_PeerIdentity *peer,
3680 struct GNUNET_TIME_Relative latency,
3681 unsigned int distance)
3683 struct Neighbour *n;
3685 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3690 n = find_neighbour (peer);
3693 if (GNUNET_YES == n->is_connected)
3695 /* duplicate connect notification!? */
3702 n = create_neighbour (peer);
3704 GNUNET_STATISTICS_update (stats,
3705 gettext_noop ("# peers connected (transport)"),
3708 n->is_connected = GNUNET_YES;
3709 n->last_latency = latency;
3710 n->last_distance = distance;
3711 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3714 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3718 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3719 "Received connection from `%4s'.\n",
3720 GNUNET_i2s (&n->peer));
3722 GNUNET_TRANSPORT_set_quota (transport,
3726 GNUNET_TIME_UNIT_FOREVER_REL,
3733 * Function called by transport telling us that a peer
3736 * @param cls closure
3737 * @param peer the peer that disconnected
3740 handle_transport_notify_disconnect (void *cls,
3741 const struct GNUNET_PeerIdentity *peer)
3743 struct DisconnectNotifyMessage cnm;
3744 struct Neighbour *n;
3747 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3748 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3750 n = find_neighbour (peer);
3756 GNUNET_break (n->is_connected);
3757 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3758 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3760 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3761 n->is_connected = GNUNET_NO;
3762 GNUNET_STATISTICS_update (stats,
3763 gettext_noop ("# peers connected (transport)"),
3770 * Last task run during shutdown. Disconnects us from
3774 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3776 struct Neighbour *n;
3780 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3781 "Core service shutting down.\n");
3783 GNUNET_assert (transport != NULL);
3784 GNUNET_TRANSPORT_disconnect (transport);
3786 while (NULL != (n = neighbours))
3788 neighbours = n->next;
3789 GNUNET_assert (neighbour_count > 0);
3793 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
3794 GNUNET_SERVER_notification_context_destroy (notifier);
3796 while (NULL != (c = clients))
3797 handle_client_disconnect (NULL, c->client_handle);
3798 if (my_private_key != NULL)
3799 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3801 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3802 if (peerinfo != NULL)
3803 GNUNET_PEERINFO_disconnect (peerinfo);
3808 * Initiate core service.
3810 * @param cls closure
3811 * @param s scheduler to use
3812 * @param serv the initialized server
3813 * @param c configuration to use
3817 struct GNUNET_SCHEDULER_Handle *s,
3818 struct GNUNET_SERVER_Handle *serv,
3819 const struct GNUNET_CONFIGURATION_Handle *c)
3825 /* parse configuration */
3828 GNUNET_CONFIGURATION_get_value_number (c,
3831 &bandwidth_target_in_bps)) ||
3833 GNUNET_CONFIGURATION_get_value_number (c,
3836 &bandwidth_target_out_bps)) ||
3838 GNUNET_CONFIGURATION_get_value_filename (c,
3840 "HOSTKEY", &keyfile)))
3842 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3844 ("Core service is lacking key configuration settings. Exiting.\n"));
3845 GNUNET_SCHEDULER_shutdown (s);
3848 peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
3849 if (NULL == peerinfo)
3851 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3852 _("Could not access PEERINFO service. Exiting.\n"));
3853 GNUNET_SCHEDULER_shutdown (s);
3854 GNUNET_free (keyfile);
3857 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3858 GNUNET_free (keyfile);
3859 if (my_private_key == NULL)
3861 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3862 _("Core service could not access hostkey. Exiting.\n"));
3863 GNUNET_PEERINFO_disconnect (peerinfo);
3864 GNUNET_SCHEDULER_shutdown (s);
3867 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3868 GNUNET_CRYPTO_hash (&my_public_key,
3869 sizeof (my_public_key), &my_identity.hashPubKey);
3870 /* setup notification */
3872 notifier = GNUNET_SERVER_notification_context_create (server,
3874 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3875 /* setup transport connection */
3876 transport = GNUNET_TRANSPORT_connect (sched,
3879 &handle_transport_receive,
3880 &handle_transport_notify_connect,
3881 &handle_transport_notify_disconnect);
3882 GNUNET_assert (NULL != transport);
3883 stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3884 GNUNET_SCHEDULER_add_delayed (sched,
3885 GNUNET_TIME_UNIT_FOREVER_REL,
3886 &cleaning_task, NULL);
3887 /* process client requests */
3888 GNUNET_SERVER_add_handlers (server, handlers);
3889 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3890 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3896 * The main function for the transport service.
3898 * @param argc number of arguments from the command line
3899 * @param argv command line arguments
3900 * @return 0 ok, 1 on error
3903 main (int argc, char *const *argv)
3905 return (GNUNET_OK ==
3906 GNUNET_SERVICE_run (argc,
3909 GNUNET_SERVICE_OPTION_NONE,
3910 &run, NULL)) ? 0 : 1;
3913 /* end of gnunet-service-core.c */