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 * How long is the message? (number of bytes following
366 * the "struct MessageEntry", but not including the
367 * size of "struct MessageEntry" itself!)
372 * Was this message selected for transmission in the
373 * current round? GNUNET_YES or GNUNET_NO.
378 * Did we give this message some slack (delayed sending) previously
379 * (and hence should not give it any more slack)? GNUNET_YES or
385 * Is this a SETKEY message?
395 * We keep neighbours in a linked list (for now).
397 struct Neighbour *next;
400 * Unencrypted messages destined for this peer.
402 struct MessageEntry *messages;
405 * Head of the batched, encrypted message queue (already ordered,
406 * transmit starting with the head).
408 struct MessageEntry *encrypted_head;
411 * Tail of the batched, encrypted message queue (already ordered,
412 * append new messages to tail)
414 struct MessageEntry *encrypted_tail;
417 * Handle for pending requests for transmission to this peer
418 * with the transport service. NULL if no request is pending.
420 struct GNUNET_TRANSPORT_TransmitHandle *th;
423 * Public key of the neighbour, NULL if we don't have it yet.
425 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
428 * We received a PING message before we got the "public_key"
429 * (or the SET_KEY). We keep it here until we have a key
430 * to decrypt it. NULL if no PING is pending.
432 struct PingMessage *pending_ping;
435 * We received a PONG message before we got the "public_key"
436 * (or the SET_KEY). We keep it here until we have a key
437 * to decrypt it. NULL if no PONG is pending.
439 struct PongMessage *pending_pong;
442 * Non-NULL if we are currently looking up HELLOs for this peer.
445 struct GNUNET_PEERINFO_IteratorContext *pitr;
448 * SetKeyMessage to transmit, NULL if we are not currently trying
451 struct SetKeyMessage *skm;
454 * Identity of the neighbour.
456 struct GNUNET_PeerIdentity peer;
459 * Key we use to encrypt our messages for the other peer
460 * (initialized by us when we do the handshake).
462 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
465 * Key we use to decrypt messages from the other peer
466 * (given to us by the other peer during the handshake).
468 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
471 * ID of task used for re-trying plaintext scheduling.
473 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
476 * ID of task used for re-trying SET_KEY and PING message.
478 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
481 * ID of task used for updating bandwidth quota for this neighbour.
483 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
486 * ID of task used for sending keep-alive pings.
488 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
491 * ID of task used for cleaning up dead neighbour entries.
493 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
496 * At what time did we generate our encryption key?
498 struct GNUNET_TIME_Absolute encrypt_key_created;
501 * At what time did the other peer generate the decryption key?
503 struct GNUNET_TIME_Absolute decrypt_key_created;
506 * At what time did we initially establish (as in, complete session
507 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
509 struct GNUNET_TIME_Absolute time_established;
512 * At what time did we last receive an encrypted message from the
513 * other peer? Should be zero if status != KEY_CONFIRMED.
515 struct GNUNET_TIME_Absolute last_activity;
518 * Last latency observed from this peer.
520 struct GNUNET_TIME_Relative last_latency;
523 * At what frequency are we currently re-trying SET_KEY messages?
525 struct GNUNET_TIME_Relative set_key_retry_frequency;
528 * Tracking bandwidth for sending to this peer.
530 struct GNUNET_BANDWIDTH_Tracker available_send_window;
533 * Tracking bandwidth for receiving from this peer.
535 struct GNUNET_BANDWIDTH_Tracker available_recv_window;
538 * How valueable were the messages of this peer recently?
540 unsigned long long current_preference;
543 * Bit map indicating which of the 32 sequence numbers before the last
544 * were received (good for accepting out-of-order packets and
545 * estimating reliability of the connection)
547 unsigned int last_packets_bitmap;
550 * last sequence number received on this connection (highest)
552 uint32_t last_sequence_number_received;
555 * last sequence number transmitted
557 uint32_t last_sequence_number_sent;
560 * Available bandwidth in for this peer (current target).
562 struct GNUNET_BANDWIDTH_Value32NBO bw_in;
565 * Available bandwidth out for this peer (current target).
567 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
570 * Internal bandwidth limit set for this peer (initially typically
571 * set to "-1"). Actual "bw_out" is MIN of
572 * "bpm_out_internal_limit" and "bw_out_external_limit".
574 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
577 * External bandwidth limit set for this peer by the
578 * peer that we are communicating with. "bw_out" is MIN of
579 * "bw_out_internal_limit" and "bw_out_external_limit".
581 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
584 * What was our PING challenge number (for this peer)?
586 uint32_t ping_challenge;
589 * What was the last distance to this peer as reported by the transports?
591 uint32_t last_distance;
594 * What is our connection status?
596 enum PeerStateMachine status;
599 * Are we currently connected to this neighbour?
607 * Data structure for each client connected to the core service.
612 * Clients are kept in a linked list.
617 * Handle for the client with the server API.
619 struct GNUNET_SERVER_Client *client_handle;
622 * Array of the types of messages this peer cares
623 * about (with "tcnt" entries). Allocated as part
624 * of this client struct, do not free!
626 const uint16_t *types;
629 * Options for messages this client cares about,
630 * see GNUNET_CORE_OPTION_ values.
635 * Number of types of incoming messages this client
636 * specifically cares about. Size of the "types" array.
646 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
651 static struct GNUNET_PeerIdentity my_identity;
656 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
661 struct GNUNET_SCHEDULER_Handle *sched;
664 * Handle to peerinfo service.
666 static struct GNUNET_PEERINFO_Handle *peerinfo;
671 const struct GNUNET_CONFIGURATION_Handle *cfg;
676 static struct GNUNET_SERVER_Handle *server;
681 static struct GNUNET_TRANSPORT_Handle *transport;
684 * Linked list of our clients.
686 static struct Client *clients;
689 * Context for notifications we need to send to our clients.
691 static struct GNUNET_SERVER_NotificationContext *notifier;
694 * We keep neighbours in a linked list (for now).
696 static struct Neighbour *neighbours;
699 * For creating statistics.
701 static struct GNUNET_STATISTICS_Handle *stats;
704 * Sum of all preferences among all neighbours.
706 static unsigned long long preference_sum;
709 * Total number of neighbours we have.
711 static unsigned int neighbour_count;
714 * How much inbound bandwidth are we supposed to be using per second?
715 * FIXME: this value is not used!
717 static unsigned long long bandwidth_target_in_bps;
720 * How much outbound bandwidth are we supposed to be using per second?
722 static unsigned long long bandwidth_target_out_bps;
727 * A preference value for a neighbour was update. Update
728 * the preference sum accordingly.
730 * @param inc how much was a preference value increased?
733 update_preference_sum (unsigned long long inc)
736 unsigned long long os;
739 preference_sum += inc;
740 if (preference_sum >= os)
742 /* overflow! compensate by cutting all values in half! */
747 n->current_preference /= 2;
748 preference_sum += n->current_preference;
751 GNUNET_STATISTICS_set (stats, gettext_noop ("# total peer preference"), preference_sum, GNUNET_NO);
756 * Find the entry for the given neighbour.
758 * @param peer identity of the neighbour
759 * @return NULL if we are not connected, otherwise the
762 static struct Neighbour *
763 find_neighbour (const struct GNUNET_PeerIdentity *peer)
765 struct Neighbour *ret;
768 while ((ret != NULL) &&
769 (0 != memcmp (&ret->peer,
770 peer, sizeof (struct GNUNET_PeerIdentity))))
777 * Send a message to one of our clients.
779 * @param client target for the message
780 * @param msg message to transmit
781 * @param can_drop could this message be dropped if the
782 * client's queue is getting too large?
785 send_to_client (struct Client *client,
786 const struct GNUNET_MessageHeader *msg,
789 #if DEBUG_CORE_CLIENT
790 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
791 "Preparing to send message of type %u to client.\n",
792 (unsigned int) ntohs (msg->type));
794 GNUNET_SERVER_notification_context_unicast (notifier,
795 client->client_handle,
802 * Send a message to all of our current clients that have
803 * the right options set.
805 * @param msg message to multicast
806 * @param can_drop can this message be discarded if the queue is too long
807 * @param options mask to use
810 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
819 if (0 != (c->options & options))
821 #if DEBUG_CORE_CLIENT
822 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
823 "Sending message of type %u to client.\n",
824 (unsigned int) ntohs (msg->type));
826 send_to_client (c, msg, can_drop);
834 * Handle CORE_INIT request.
837 handle_client_init (void *cls,
838 struct GNUNET_SERVER_Client *client,
839 const struct GNUNET_MessageHeader *message)
841 const struct InitMessage *im;
842 struct InitReplyMessage irm;
845 const uint16_t *types;
848 struct ConnectNotifyMessage cnm;
851 #if DEBUG_CORE_CLIENT
852 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
853 "Client connecting to core service with `%s' message\n",
856 /* check that we don't have an entry already */
860 if (client == c->client_handle)
863 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
868 msize = ntohs (message->size);
869 if (msize < sizeof (struct InitMessage))
872 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
875 GNUNET_SERVER_notification_context_add (notifier, client);
876 im = (const struct InitMessage *) message;
877 types = (const uint16_t *) &im[1];
878 msize -= sizeof (struct InitMessage);
879 c = GNUNET_malloc (sizeof (struct Client) + msize);
880 c->client_handle = client;
883 c->tcnt = msize / sizeof (uint16_t);
884 c->types = (const uint16_t *) &c[1];
885 wtypes = (uint16_t *) &c[1];
886 for (i=0;i<c->tcnt;i++)
887 wtypes[i] = ntohs (types[i]);
888 c->options = ntohl (im->options);
889 #if DEBUG_CORE_CLIENT
890 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
891 "Client %p is interested in %u message types\n",
893 (unsigned int) c->tcnt);
895 /* send init reply message */
896 irm.header.size = htons (sizeof (struct InitReplyMessage));
897 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
898 irm.reserved = htonl (0);
899 memcpy (&irm.publicKey,
901 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
902 #if DEBUG_CORE_CLIENT
903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
904 "Sending `%s' message to client.\n", "INIT_REPLY");
906 send_to_client (c, &irm.header, GNUNET_NO);
907 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
909 /* notify new client about existing neighbours */
910 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
911 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
915 if (n->status == PEER_STATE_KEY_CONFIRMED)
917 #if DEBUG_CORE_CLIENT
918 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
919 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
921 cnm.distance = htonl (n->last_distance);
922 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
924 send_to_client (c, &cnm.header, GNUNET_NO);
929 GNUNET_SERVER_receive_done (client, GNUNET_OK);
934 * A client disconnected, clean up.
937 * @param client identification of the client
940 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
947 #if DEBUG_CORE_CLIENT
948 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
949 "Client %p has disconnected from core service.\n",
956 if (client == pos->client_handle)
961 prev->next = pos->next;
968 /* client never sent INIT */
973 * Handle REQUEST_INFO request.
976 handle_client_request_info (void *cls,
977 struct GNUNET_SERVER_Client *client,
978 const struct GNUNET_MessageHeader *message)
980 const struct RequestInfoMessage *rcm;
982 struct ConfigurationInfoMessage cim;
985 unsigned long long old_preference;
986 struct GNUNET_SERVER_TransmitContext *tc;
988 #if DEBUG_CORE_CLIENT
989 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
990 "Core service receives `%s' request.\n", "REQUEST_INFO");
992 rcm = (const struct RequestInfoMessage *) message;
993 n = find_neighbour (&rcm->peer);
994 memset (&cim, 0, sizeof (cim));
997 want_reserv = ntohl (rcm->reserve_inbound);
998 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1000 n->bw_out_internal_limit = rcm->limit_outbound;
1001 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1002 n->bw_out_external_limit);
1003 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1005 GNUNET_TRANSPORT_set_quota (transport,
1009 GNUNET_TIME_UNIT_FOREVER_REL,
1012 if (want_reserv < 0)
1014 got_reserv = want_reserv;
1016 else if (want_reserv > 0)
1018 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1019 want_reserv).value == 0)
1020 got_reserv = want_reserv;
1022 got_reserv = 0; /* all or nothing */
1026 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1028 old_preference = n->current_preference;
1029 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1030 if (old_preference > n->current_preference)
1032 /* overflow; cap at maximum value */
1033 n->current_preference = (unsigned long long) -1;
1035 update_preference_sum (n->current_preference - old_preference);
1036 #if DEBUG_CORE_QUOTA
1037 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1038 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1040 GNUNET_i2s (&rcm->peer),
1043 cim.reserved_amount = htonl (got_reserv);
1044 cim.bw_in = n->bw_in;
1045 cim.bw_out = n->bw_out;
1046 cim.preference = n->current_preference;
1048 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1049 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1050 cim.peer = rcm->peer;
1052 #if DEBUG_CORE_CLIENT
1053 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1054 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1056 tc = GNUNET_SERVER_transmit_context_create (client);
1057 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1058 GNUNET_SERVER_transmit_context_run (tc,
1059 GNUNET_TIME_UNIT_FOREVER_REL);
1064 * Free the given entry for the neighbour (it has
1065 * already been removed from the list at this point).
1067 * @param n neighbour to free
1070 free_neighbour (struct Neighbour *n)
1072 struct MessageEntry *m;
1074 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1075 "Destroying neighbour entry for peer `%4s'\n",
1076 GNUNET_i2s (&n->peer));
1077 if (n->pitr != NULL)
1079 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1084 GNUNET_free (n->skm);
1087 while (NULL != (m = n->messages))
1089 n->messages = m->next;
1092 while (NULL != (m = n->encrypted_head))
1094 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1101 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1104 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1105 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1106 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1107 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1108 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1109 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1110 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1111 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1112 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1113 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1114 if (n->status == PEER_STATE_KEY_CONFIRMED)
1115 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1116 GNUNET_free_non_null (n->public_key);
1117 GNUNET_free_non_null (n->pending_ping);
1118 GNUNET_free_non_null (n->pending_pong);
1124 * Check if we have encrypted messages for the specified neighbour
1125 * pending, and if so, check with the transport about sending them
1128 * @param n neighbour to check.
1130 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1134 * Encrypt size bytes from in and write the result to out. Use the
1135 * key for outbound traffic of the given neighbour.
1137 * @param n neighbour we are sending to
1138 * @param iv initialization vector to use
1139 * @param in ciphertext
1140 * @param out plaintext
1141 * @param size size of in/out
1142 * @return GNUNET_OK on success
1145 do_encrypt (struct Neighbour *n,
1146 const GNUNET_HashCode * iv,
1147 const void *in, void *out, size_t size)
1149 if (size != (uint16_t) size)
1154 GNUNET_assert (size ==
1155 GNUNET_CRYPTO_aes_encrypt (in,
1159 GNUNET_CRYPTO_AesInitializationVector
1161 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1163 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1164 "Encrypted %u bytes for `%4s' using key %u\n",
1165 (unsigned int) size,
1166 GNUNET_i2s (&n->peer),
1167 (unsigned int) n->encrypt_key.crc32);
1174 * Consider freeing the given neighbour since we may not need
1175 * to keep it around anymore.
1177 * @param n neighbour to consider discarding
1180 consider_free_neighbour (struct Neighbour *n);
1184 * Task triggered when a neighbour entry is about to time out
1185 * (and we should prevent this by sending a PING).
1187 * @param cls the 'struct Neighbour'
1188 * @param tc scheduler context (not used)
1191 send_keep_alive (void *cls,
1192 const struct GNUNET_SCHEDULER_TaskContext *tc)
1194 struct Neighbour *n = cls;
1195 struct GNUNET_TIME_Relative retry;
1196 struct GNUNET_TIME_Relative left;
1197 struct MessageEntry *me;
1198 struct PingMessage pp;
1199 struct PingMessage *pm;
1201 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1203 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1204 sizeof (struct PingMessage));
1205 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1206 me->priority = PING_PRIORITY;
1207 me->size = sizeof (struct PingMessage);
1208 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1212 pm = (struct PingMessage *) &me[1];
1213 pm->header.size = htons (sizeof (struct PingMessage));
1214 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1215 pp.challenge = htonl (n->ping_challenge);
1216 pp.target = n->peer;
1218 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1219 "Encrypting `%s' message with challenge %u for `%4s' using key %u.\n",
1221 (unsigned int) n->ping_challenge,
1222 GNUNET_i2s (&n->peer),
1223 (unsigned int) n->encrypt_key.crc32);
1226 &n->peer.hashPubKey,
1229 sizeof (struct PingMessage) -
1230 sizeof (struct GNUNET_MessageHeader));
1231 process_encrypted_neighbour_queue (n);
1232 /* reschedule PING job */
1233 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1234 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1235 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1236 MIN_PING_FREQUENCY);
1238 = GNUNET_SCHEDULER_add_delayed (sched,
1247 * Task triggered when a neighbour entry might have gotten stale.
1249 * @param cls the 'struct Neighbour'
1250 * @param tc scheduler context (not used)
1253 consider_free_task (void *cls,
1254 const struct GNUNET_SCHEDULER_TaskContext *tc)
1256 struct Neighbour *n = cls;
1258 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1259 consider_free_neighbour (n);
1264 * Consider freeing the given neighbour since we may not need
1265 * to keep it around anymore.
1267 * @param n neighbour to consider discarding
1270 consider_free_neighbour (struct Neighbour *n)
1272 struct Neighbour *pos;
1273 struct Neighbour *prev;
1274 struct GNUNET_TIME_Relative left;
1276 if ( (n->th != NULL) ||
1277 (n->pitr != NULL) ||
1278 (n->status == PEER_STATE_KEY_CONFIRMED) ||
1279 (GNUNET_YES == n->is_connected) )
1280 return; /* no chance */
1282 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1283 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1286 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1287 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1288 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1290 &consider_free_task,
1294 /* actually free the neighbour... */
1303 neighbours = n->next;
1305 prev->next = n->next;
1306 GNUNET_assert (neighbour_count > 0);
1308 GNUNET_STATISTICS_set (stats,
1309 gettext_noop ("# neighbour entries allocated"),
1317 * Function called when the transport service is ready to
1318 * receive an encrypted message for the respective peer
1320 * @param cls neighbour to use message from
1321 * @param size number of bytes we can transmit
1322 * @param buf where to copy the message
1323 * @return number of bytes transmitted
1326 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1328 struct Neighbour *n = cls;
1329 struct MessageEntry *m;
1334 m = n->encrypted_head;
1338 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1339 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1340 GNUNET_i2s (&n->peer));
1344 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1351 GNUNET_assert (size >= m->size);
1352 memcpy (cbuf, &m[1], m->size);
1354 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1357 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1358 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1359 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1361 GNUNET_i2s (&n->peer));
1363 process_encrypted_neighbour_queue (n);
1368 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1369 "Transmission of message of type %u and size %u failed\n",
1370 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1371 (unsigned int) m->size);
1375 consider_free_neighbour (n);
1381 * Check if we have plaintext messages for the specified neighbour
1382 * pending, and if so, consider batching and encrypting them (and
1383 * then trigger processing of the encrypted queue if needed).
1385 * @param n neighbour to check.
1387 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1391 * Check if we have encrypted messages for the specified neighbour
1392 * pending, and if so, check with the transport about sending them
1395 * @param n neighbour to check.
1398 process_encrypted_neighbour_queue (struct Neighbour *n)
1400 struct MessageEntry *m;
1403 return; /* request already pending */
1404 m = n->encrypted_head;
1407 /* encrypted queue empty, try plaintext instead */
1408 process_plaintext_neighbour_queue (n);
1412 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1413 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1414 (unsigned int) m->size,
1415 GNUNET_i2s (&n->peer),
1416 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).
1420 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1423 GNUNET_TIME_absolute_get_remaining
1425 ¬ify_encrypted_transmit_ready,
1429 /* message request too large or duplicate request */
1431 /* discard encrypted message */
1432 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1436 process_encrypted_neighbour_queue (n);
1442 * Decrypt size bytes from in and write the result to out. Use the
1443 * key for inbound traffic of the given neighbour. This function does
1444 * NOT do any integrity-checks on the result.
1446 * @param n neighbour we are receiving from
1447 * @param iv initialization vector to use
1448 * @param in ciphertext
1449 * @param out plaintext
1450 * @param size size of in/out
1451 * @return GNUNET_OK on success
1454 do_decrypt (struct Neighbour *n,
1455 const GNUNET_HashCode * iv,
1456 const void *in, void *out, size_t size)
1458 if (size != (uint16_t) size)
1463 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1464 (n->status != PEER_STATE_KEY_CONFIRMED))
1466 GNUNET_break_op (0);
1467 return GNUNET_SYSERR;
1470 GNUNET_CRYPTO_aes_decrypt (in,
1474 GNUNET_CRYPTO_AesInitializationVector *) iv,
1478 return GNUNET_SYSERR;
1480 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1482 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1483 "Decrypted %u bytes from `%4s' using key %u\n",
1484 (unsigned int) size,
1485 GNUNET_i2s (&n->peer),
1486 (unsigned int) n->decrypt_key.crc32);
1493 * Select messages for transmission. This heuristic uses a combination
1494 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1495 * and priority-based discard (in case no feasible schedule exist) and
1496 * speculative optimization (defer any kind of transmission until
1497 * we either create a batch of significant size, 25% of max, or until
1498 * we are close to a deadline). Furthermore, when scheduling the
1499 * heuristic also packs as many messages into the batch as possible,
1500 * starting with those with the earliest deadline. Yes, this is fun.
1502 * @param n neighbour to select messages from
1503 * @param size number of bytes to select for transmission
1504 * @param retry_time set to the time when we should try again
1505 * (only valid if this function returns zero)
1506 * @return number of bytes selected, or 0 if we decided to
1507 * defer scheduling overall; in that case, retry_time is set.
1510 select_messages (struct Neighbour *n,
1511 size_t size, struct GNUNET_TIME_Relative *retry_time)
1513 struct MessageEntry *pos;
1514 struct MessageEntry *min;
1515 struct MessageEntry *last;
1516 unsigned int min_prio;
1517 struct GNUNET_TIME_Absolute t;
1518 struct GNUNET_TIME_Absolute now;
1519 struct GNUNET_TIME_Relative delta;
1521 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1524 unsigned int queue_size;
1525 int discard_low_prio;
1527 GNUNET_assert (NULL != n->messages);
1528 now = GNUNET_TIME_absolute_get ();
1529 /* last entry in linked list of messages processed */
1531 /* should we remove the entry with the lowest
1532 priority from consideration for scheduling at the
1543 discard_low_prio = GNUNET_YES;
1544 while (GNUNET_YES == discard_low_prio)
1548 discard_low_prio = GNUNET_NO;
1549 /* calculate number of bytes available for transmission at time "t" */
1550 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1552 /* how many bytes have we (hypothetically) scheduled so far */
1554 /* maximum time we can wait before transmitting anything
1555 and still make all of our deadlines */
1556 slack = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1558 /* note that we use "*2" here because we want to look
1559 a bit further into the future; much more makes no
1560 sense since new message might be scheduled in the
1562 while ((pos != NULL) && (off < size * 2))
1564 if (pos->do_transmit == GNUNET_YES)
1566 /* already removed from consideration */
1570 if (discard_low_prio == GNUNET_NO)
1572 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1573 if (delta.value > 0)
1575 // FIXME: HUH? Check!
1577 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1580 if (avail < pos->size)
1582 // FIXME: HUH? Check!
1583 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1588 /* update slack, considering both its absolute deadline
1589 and relative deadlines caused by other messages
1590 with their respective load */
1591 slack = GNUNET_TIME_relative_min (slack,
1592 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1594 if (pos->deadline.value <= now.value)
1597 slack = GNUNET_TIME_UNIT_ZERO;
1599 else if (GNUNET_YES == pos->got_slack)
1601 /* should be soon now! */
1602 slack = GNUNET_TIME_relative_min (slack,
1603 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1608 GNUNET_TIME_relative_min (slack,
1609 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1610 pos->got_slack = GNUNET_YES;
1611 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1612 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
1617 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1618 if (pos->priority <= min_prio)
1620 /* update min for discard */
1621 min_prio = pos->priority;
1626 if (discard_low_prio)
1628 GNUNET_assert (min != NULL);
1629 /* remove lowest-priority entry from consideration */
1630 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1634 /* guard against sending "tiny" messages with large headers without
1636 if ( (slack.value > 0) &&
1638 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1640 /* less than 25% of message would be filled with deadlines still
1641 being met if we delay by one second or more; so just wait for
1642 more data; but do not wait longer than 1s (since we don't want
1643 to delay messages for a really long time either). */
1644 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1645 /* reset do_transmit values for next time */
1648 pos->do_transmit = GNUNET_NO;
1652 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1653 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1654 (unsigned long long) slack.value,
1656 (unsigned int) size);
1660 /* select marked messages (up to size) for transmission */
1665 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1667 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1672 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1676 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1677 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1678 (unsigned long long) off, (unsigned long long) tsize,
1679 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
1680 GNUNET_i2s (&n->peer));
1687 * Batch multiple messages into a larger buffer.
1689 * @param n neighbour to take messages from
1690 * @param buf target buffer
1691 * @param size size of buf
1692 * @param deadline set to transmission deadline for the result
1693 * @param retry_time set to the time when we should try again
1694 * (only valid if this function returns zero)
1695 * @param priority set to the priority of the batch
1696 * @return number of bytes written to buf (can be zero)
1699 batch_message (struct Neighbour *n,
1702 struct GNUNET_TIME_Absolute *deadline,
1703 struct GNUNET_TIME_Relative *retry_time,
1704 unsigned int *priority)
1706 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1707 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1708 struct MessageEntry *pos;
1709 struct MessageEntry *prev;
1710 struct MessageEntry *next;
1715 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1716 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1717 if (0 == select_messages (n, size, retry_time))
1720 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1721 "No messages selected, will try again in %llu ms\n",
1726 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1727 ntm->distance = htonl (n->last_distance);
1728 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1729 ntm->peer = n->peer;
1733 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1736 if (GNUNET_YES == pos->do_transmit)
1738 GNUNET_assert (pos->size <= size);
1739 /* do notifications */
1740 /* FIXME: track if we have *any* client that wants
1741 full notifications and only do this if that is
1743 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1745 memcpy (&ntm[1], &pos[1], pos->size);
1746 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1747 sizeof (struct GNUNET_MessageHeader));
1748 send_to_all_clients (&ntm->header,
1750 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1754 /* message too large for 'full' notifications, we do at
1755 least the 'hdr' type */
1758 sizeof (struct GNUNET_MessageHeader));
1760 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1762 send_to_all_clients (&ntm->header,
1764 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1766 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1767 "Encrypting message of type %u\n",
1768 (unsigned int) ntohs(((struct GNUNET_MessageHeader*)&pos[1])->type));
1770 /* copy for encrypted transmission */
1771 memcpy (&buf[ret], &pos[1], pos->size);
1774 *priority += pos->priority;
1776 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1777 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1778 (unsigned int) pos->size,
1779 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1781 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1795 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1796 "Deadline for message batch is %llu ms\n",
1797 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1804 * Remove messages with deadlines that have long expired from
1807 * @param n neighbour to inspect
1810 discard_expired_messages (struct Neighbour *n)
1812 struct MessageEntry *prev;
1813 struct MessageEntry *next;
1814 struct MessageEntry *pos;
1815 struct GNUNET_TIME_Absolute now;
1816 struct GNUNET_TIME_Relative delta;
1818 now = GNUNET_TIME_absolute_get ();
1824 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1825 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1828 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1829 "Message is %llu ms past due, discarding.\n",
1846 * Signature of the main function of a task.
1848 * @param cls closure
1849 * @param tc context information (why was this task triggered now)
1852 retry_plaintext_processing (void *cls,
1853 const struct GNUNET_SCHEDULER_TaskContext *tc)
1855 struct Neighbour *n = cls;
1857 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1858 process_plaintext_neighbour_queue (n);
1863 * Send our key (and encrypted PING) to the other peer.
1865 * @param n the other peer
1867 static void send_key (struct Neighbour *n);
1870 * Task that will retry "send_key" if our previous attempt failed
1874 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1876 struct Neighbour *n = cls;
1879 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1880 "Retrying key transmission to `%4s'\n",
1881 GNUNET_i2s (&n->peer));
1883 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1884 n->set_key_retry_frequency =
1885 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1891 * Check if we have plaintext messages for the specified neighbour
1892 * pending, and if so, consider batching and encrypting them (and
1893 * then trigger processing of the encrypted queue if needed).
1895 * @param n neighbour to check.
1898 process_plaintext_neighbour_queue (struct Neighbour *n)
1900 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1903 struct EncryptedMessage *em; /* encrypted message */
1904 struct EncryptedMessage *ph; /* plaintext header */
1905 struct MessageEntry *me;
1906 unsigned int priority;
1907 struct GNUNET_TIME_Absolute deadline;
1908 struct GNUNET_TIME_Relative retry_time;
1911 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1913 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1914 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1918 case PEER_STATE_DOWN:
1921 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1922 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1923 GNUNET_i2s(&n->peer));
1926 case PEER_STATE_KEY_SENT:
1927 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1928 n->retry_set_key_task
1929 = GNUNET_SCHEDULER_add_delayed (sched,
1930 n->set_key_retry_frequency,
1931 &set_key_retry_task, n);
1933 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1934 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1935 GNUNET_i2s(&n->peer));
1938 case PEER_STATE_KEY_RECEIVED:
1939 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1940 n->retry_set_key_task
1941 = GNUNET_SCHEDULER_add_delayed (sched,
1942 n->set_key_retry_frequency,
1943 &set_key_retry_task, n);
1945 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1946 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1947 GNUNET_i2s(&n->peer));
1950 case PEER_STATE_KEY_CONFIRMED:
1951 /* ready to continue */
1954 discard_expired_messages (n);
1955 if (n->messages == NULL)
1958 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1959 "Plaintext message queue for `%4s' is empty.\n",
1960 GNUNET_i2s(&n->peer));
1962 return; /* no pending messages */
1964 if (n->encrypted_head != NULL)
1967 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1968 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1969 GNUNET_i2s(&n->peer));
1971 return; /* wait for messages already encrypted to be
1974 ph = (struct EncryptedMessage *) pbuf;
1975 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1977 used = sizeof (struct EncryptedMessage);
1978 used += batch_message (n,
1980 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1981 &deadline, &retry_time, &priority);
1982 if (used == sizeof (struct EncryptedMessage))
1985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1986 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1987 GNUNET_i2s(&n->peer));
1989 /* no messages selected for sending, try again later... */
1990 n->retry_plaintext_task =
1991 GNUNET_SCHEDULER_add_delayed (sched,
1993 &retry_plaintext_processing, n);
1996 #if DEBUG_CORE_QUOTA
1997 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1998 "Sending %u b/s as new limit to peer `%4s'\n",
1999 (unsigned int) ntohl (n->bw_in.value__),
2000 GNUNET_i2s (&n->peer));
2002 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1));
2003 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2004 ph->inbound_bw_limit = n->bw_in;
2005 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2007 /* setup encryption message header */
2008 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2009 me->deadline = deadline;
2010 me->priority = priority;
2012 em = (struct EncryptedMessage *) &me[1];
2013 em->header.size = htons (used);
2014 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2015 em->iv_seed = ph->iv_seed;
2016 esize = used - ENCRYPTED_HEADER_SIZE;
2017 GNUNET_CRYPTO_hash (&ph->sequence_number,
2018 esize - sizeof (GNUNET_HashCode),
2019 &ph->plaintext_hash);
2020 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
2022 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2023 "Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
2024 (unsigned int) (esize - sizeof (GNUNET_HashCode)),
2025 GNUNET_h2s (&ph->plaintext_hash),
2030 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2031 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2032 (unsigned int) esize,
2033 GNUNET_i2s(&n->peer),
2034 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2036 GNUNET_assert (GNUNET_OK ==
2039 &ph->plaintext_hash,
2040 &em->plaintext_hash, esize));
2041 /* append to transmission list */
2042 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2046 process_encrypted_neighbour_queue (n);
2051 * Function that recalculates the bandwidth quota for the
2052 * given neighbour and transmits it to the transport service.
2054 * @param cls neighbour for the quota update
2058 neighbour_quota_update (void *cls,
2059 const struct GNUNET_SCHEDULER_TaskContext *tc);
2063 * Schedule the task that will recalculate the bandwidth
2064 * quota for this peer (and possibly force a disconnect of
2065 * idle peers by calculating a bandwidth of zero).
2068 schedule_quota_update (struct Neighbour *n)
2070 GNUNET_assert (n->quota_update_task ==
2071 GNUNET_SCHEDULER_NO_TASK);
2072 n->quota_update_task
2073 = GNUNET_SCHEDULER_add_delayed (sched,
2074 QUOTA_UPDATE_FREQUENCY,
2075 &neighbour_quota_update,
2081 * Initialize a new 'struct Neighbour'.
2083 * @param pid ID of the new neighbour
2084 * @return handle for the new neighbour
2086 static struct Neighbour *
2087 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2089 struct Neighbour *n;
2090 struct GNUNET_TIME_Absolute now;
2092 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2093 "Creating neighbour entry for peer `%4s'\n",
2095 n = GNUNET_malloc (sizeof (struct Neighbour));
2096 n->next = neighbours;
2099 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2101 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2102 now = GNUNET_TIME_absolute_get ();
2103 n->encrypt_key_created = now;
2104 n->last_activity = now;
2105 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2106 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2107 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2108 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init ((uint32_t) - 1);
2109 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2110 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2112 neighbour_quota_update (n, NULL);
2113 consider_free_neighbour (n);
2119 * Handle CORE_SEND request.
2122 * @param client the client issuing the request
2123 * @param message the "struct SendMessage"
2126 handle_client_send (void *cls,
2127 struct GNUNET_SERVER_Client *client,
2128 const struct GNUNET_MessageHeader *message)
2130 const struct SendMessage *sm;
2131 struct Neighbour *n;
2132 struct MessageEntry *prev;
2133 struct MessageEntry *pos;
2134 struct MessageEntry *e;
2135 struct MessageEntry *min_prio_entry;
2136 struct MessageEntry *min_prio_prev;
2137 unsigned int min_prio;
2138 unsigned int queue_size;
2141 msize = ntohs (message->size);
2143 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2147 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2150 sm = (const struct SendMessage *) message;
2151 msize -= sizeof (struct SendMessage);
2152 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2154 /* FIXME: should we not allow loopback-injection here? */
2157 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2160 n = find_neighbour (&sm->peer);
2162 n = create_neighbour (&sm->peer);
2164 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2165 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2167 (unsigned int) msize,
2168 GNUNET_i2s (&sm->peer));
2170 /* bound queue size */
2171 discard_expired_messages (n);
2172 min_prio = (unsigned int) -1;
2173 min_prio_entry = NULL;
2174 min_prio_prev = NULL;
2180 if (pos->priority < min_prio)
2182 min_prio_entry = pos;
2183 min_prio_prev = prev;
2184 min_prio = pos->priority;
2190 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2193 if (ntohl(sm->priority) <= min_prio)
2195 /* discard new entry */
2197 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2198 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2200 (unsigned int) MAX_PEER_QUEUE_SIZE,
2201 (unsigned int) msize,
2202 (unsigned int) ntohs (message->type));
2205 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2208 /* discard "min_prio_entry" */
2210 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2211 "Queue full, discarding existing older request\n");
2213 if (min_prio_prev == NULL)
2214 n->messages = min_prio_entry->next;
2216 min_prio_prev->next = min_prio_entry->next;
2217 GNUNET_free (min_prio_entry);
2221 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2222 "Adding transmission request for `%4s' of size %u to queue\n",
2223 GNUNET_i2s (&sm->peer),
2224 (unsigned int) msize);
2226 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2227 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2228 e->priority = ntohl (sm->priority);
2230 memcpy (&e[1], &sm[1], msize);
2232 /* insert, keep list sorted by deadline */
2235 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2246 /* consider scheduling now */
2247 process_plaintext_neighbour_queue (n);
2249 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2254 * Function called when the transport service is ready to
2255 * receive a message. Only resets 'n->th' to NULL.
2257 * @param cls neighbour to use message from
2258 * @param size number of bytes we can transmit
2259 * @param buf where to copy the message
2260 * @return number of bytes transmitted
2263 notify_transport_connect_done (void *cls, size_t size, void *buf)
2265 struct Neighbour *n = cls;
2270 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2271 _("Failed to connect to `%4s': transport failed to connect\n"),
2272 GNUNET_i2s (&n->peer));
2281 * Handle CORE_REQUEST_CONNECT request.
2284 * @param client the client issuing the request
2285 * @param message the "struct ConnectMessage"
2288 handle_client_request_connect (void *cls,
2289 struct GNUNET_SERVER_Client *client,
2290 const struct GNUNET_MessageHeader *message)
2292 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2293 struct Neighbour *n;
2294 struct GNUNET_TIME_Relative timeout;
2296 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2299 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2302 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2303 n = find_neighbour (&cm->peer);
2305 n = create_neighbour (&cm->peer);
2306 if ( (GNUNET_YES == n->is_connected) ||
2308 return; /* already connected, or at least trying */
2309 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2311 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2312 "Core received `%s' request for `%4s', will try to establish connection\n",
2314 GNUNET_i2s (&cm->peer));
2316 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2317 /* ask transport to connect to the peer */
2318 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2320 sizeof (struct GNUNET_MessageHeader), 0,
2322 ¬ify_transport_connect_done,
2324 GNUNET_break (NULL != n->th);
2329 * List of handlers for the messages understood by this
2332 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2333 {&handle_client_init, NULL,
2334 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2335 {&handle_client_request_info, NULL,
2336 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2337 sizeof (struct RequestInfoMessage)},
2338 {&handle_client_send, NULL,
2339 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2340 {&handle_client_request_connect, NULL,
2341 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2342 sizeof (struct ConnectMessage)},
2348 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2349 * the neighbour's struct and retry send_key. Or, if we did not get a
2350 * HELLO, just do nothing.
2352 * @param cls the 'struct Neighbour' to retry sending the key for
2353 * @param peer the peer for which this is the HELLO
2354 * @param hello HELLO message of that peer
2355 * @param trust amount of trust we currently have in that peer
2358 process_hello_retry_send_key (void *cls,
2359 const struct GNUNET_PeerIdentity *peer,
2360 const struct GNUNET_HELLO_Message *hello,
2363 struct Neighbour *n = cls;
2368 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2369 "Entered `%s' and `%s' is NULL!\n",
2370 "process_hello_retry_send_key",
2374 if (n->public_key != NULL)
2376 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2378 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2379 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2381 GNUNET_STATISTICS_update (stats,
2382 gettext_noop ("# SETKEY messages deferred (need public key)"),
2389 GNUNET_STATISTICS_update (stats,
2390 gettext_noop ("# Delayed connecting due to lack of public key"),
2393 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2394 n->retry_set_key_task
2395 = GNUNET_SCHEDULER_add_delayed (sched,
2396 n->set_key_retry_frequency,
2397 &set_key_retry_task, n);
2403 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2404 "Entered `%s' for peer `%4s'\n",
2405 "process_hello_retry_send_key",
2408 if (n->public_key != NULL)
2410 /* already have public key, why are we here? */
2416 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2417 "Received new `%s' message for `%4s', initiating key exchange.\n",
2422 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2423 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2425 GNUNET_STATISTICS_update (stats,
2426 gettext_noop ("# Error extracting public key from HELLO"),
2429 GNUNET_free (n->public_key);
2430 n->public_key = NULL;
2432 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2433 "GNUNET_HELLO_get_key returned awfully\n");
2441 * Send our key (and encrypted PING) to the other peer.
2443 * @param n the other peer
2446 send_key (struct Neighbour *n)
2448 struct MessageEntry *pos;
2449 struct SetKeyMessage *sm;
2450 struct MessageEntry *me;
2451 struct PingMessage pp;
2452 struct PingMessage *pm;
2454 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2456 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2457 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2459 if (n->pitr != NULL)
2462 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2463 "Key exchange in progress with `%4s'.\n",
2464 GNUNET_i2s (&n->peer));
2466 return; /* already in progress */
2468 if (GNUNET_YES != n->is_connected)
2471 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2472 "Not yet connected to peer `%4s'!\n",
2473 GNUNET_i2s (&n->peer));
2477 GNUNET_STATISTICS_update (stats,
2478 gettext_noop ("# Asking transport to connect (for SETKEY)"),
2481 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2483 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2485 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2486 ¬ify_encrypted_transmit_ready,
2492 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2493 "Asked to perform key exchange with `%4s'.\n",
2494 GNUNET_i2s (&n->peer));
2496 if (n->public_key == NULL)
2498 /* lookup n's public key, then try again */
2500 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2501 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2502 GNUNET_i2s (&n->peer));
2504 GNUNET_assert (n->pitr == NULL);
2505 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2508 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2509 &process_hello_retry_send_key, n);
2512 pos = n->encrypted_head;
2515 if (GNUNET_YES == pos->is_setkey)
2518 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2519 "%s message for `%s' already in the queue, not adding another one\n",
2521 GNUNET_i2s (&n->peer));
2528 /* first, set key message */
2529 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2530 sizeof (struct SetKeyMessage));
2531 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2532 me->priority = SET_KEY_PRIORITY;
2533 me->size = sizeof (struct SetKeyMessage);
2534 me->is_setkey = GNUNET_YES;
2535 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2539 sm = (struct SetKeyMessage *) &me[1];
2540 sm->header.size = htons (sizeof (struct SetKeyMessage));
2541 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2542 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2543 PEER_STATE_KEY_SENT : n->status));
2545 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2546 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2547 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2548 sizeof (struct GNUNET_PeerIdentity));
2549 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2550 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2551 sm->target = n->peer;
2552 GNUNET_assert (GNUNET_OK ==
2553 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2555 GNUNET_CRYPTO_AesSessionKey),
2557 &sm->encrypted_key));
2558 GNUNET_assert (GNUNET_OK ==
2559 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2562 /* second, encrypted PING message */
2563 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2564 sizeof (struct PingMessage));
2565 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2566 me->priority = PING_PRIORITY;
2567 me->size = sizeof (struct PingMessage);
2568 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2572 pm = (struct PingMessage *) &me[1];
2573 pm->header.size = htons (sizeof (struct PingMessage));
2574 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2575 pp.challenge = htonl (n->ping_challenge);
2576 pp.target = n->peer;
2578 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2579 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u.\n",
2581 (unsigned int) n->ping_challenge,
2582 GNUNET_i2s (&n->peer),
2583 (unsigned int) n->encrypt_key.crc32);
2586 &n->peer.hashPubKey,
2589 sizeof (struct PingMessage) -
2590 sizeof (struct GNUNET_MessageHeader));
2594 case PEER_STATE_DOWN:
2595 n->status = PEER_STATE_KEY_SENT;
2597 case PEER_STATE_KEY_SENT:
2599 case PEER_STATE_KEY_RECEIVED:
2601 case PEER_STATE_KEY_CONFIRMED:
2607 GNUNET_STATISTICS_update (stats,
2608 gettext_noop ("# SETKEY and PING messages created"),
2612 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2613 "Have %llu ms left for `%s' transmission.\n",
2614 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2617 /* trigger queue processing */
2618 process_encrypted_neighbour_queue (n);
2619 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2620 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2621 n->retry_set_key_task
2622 = GNUNET_SCHEDULER_add_delayed (sched,
2623 n->set_key_retry_frequency,
2624 &set_key_retry_task, n);
2629 * We received a SET_KEY message. Validate and update
2630 * our key material and status.
2632 * @param n the neighbour from which we received message m
2633 * @param m the set key message we received
2636 handle_set_key (struct Neighbour *n,
2637 const struct SetKeyMessage *m);
2641 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2642 * the neighbour's struct and retry handling the set_key message. Or,
2643 * if we did not get a HELLO, just free the set key message.
2645 * @param cls pointer to the set key message
2646 * @param peer the peer for which this is the HELLO
2647 * @param hello HELLO message of that peer
2648 * @param trust amount of trust we currently have in that peer
2651 process_hello_retry_handle_set_key (void *cls,
2652 const struct GNUNET_PeerIdentity *peer,
2653 const struct GNUNET_HELLO_Message *hello,
2656 struct Neighbour *n = cls;
2657 struct SetKeyMessage *sm = n->skm;
2663 if (n->public_key != NULL)
2666 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2667 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2669 GNUNET_i2s (&n->peer),
2672 handle_set_key (n, sm);
2677 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2678 "Ignoring `%s' message due to lack of public key for peer (failed to obtain one).\n",
2685 if (n->public_key != NULL)
2686 return; /* multiple HELLOs match!? */
2688 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2689 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2691 GNUNET_break_op (0);
2692 GNUNET_free (n->public_key);
2693 n->public_key = NULL;
2699 * We received a PING message. Validate and transmit
2702 * @param n sender of the PING
2703 * @param m the encrypted PING message itself
2706 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2708 struct PingMessage t;
2709 struct PongMessage tx;
2710 struct PongMessage *tp;
2711 struct MessageEntry *me;
2714 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2715 "Core service receives `%s' request from `%4s'.\n",
2716 "PING", GNUNET_i2s (&n->peer));
2720 &my_identity.hashPubKey,
2723 sizeof (struct PingMessage) -
2724 sizeof (struct GNUNET_MessageHeader)))
2727 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2728 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2730 GNUNET_i2s (&t.target),
2731 (unsigned int) ntohl (t.challenge),
2732 (unsigned int) n->decrypt_key.crc32);
2734 GNUNET_STATISTICS_update (stats,
2735 gettext_noop ("# PING messages decrypted"),
2738 if (0 != memcmp (&t.target,
2739 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2741 GNUNET_break_op (0);
2744 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2745 sizeof (struct PongMessage));
2746 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2750 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2751 me->priority = PONG_PRIORITY;
2752 me->size = sizeof (struct PongMessage);
2753 tx.reserved = htonl (0);
2754 tx.inbound_bw_limit = n->bw_in;
2755 tx.challenge = t.challenge;
2756 tx.target = t.target;
2757 tp = (struct PongMessage *) &me[1];
2758 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2759 tp->header.size = htons (sizeof (struct PongMessage));
2761 &my_identity.hashPubKey,
2764 sizeof (struct PongMessage) -
2765 sizeof (struct GNUNET_MessageHeader));
2766 GNUNET_STATISTICS_update (stats,
2767 gettext_noop ("# PONG messages created"),
2771 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2772 "Encrypting `%s' with challenge %u using key %u\n",
2774 (unsigned int) ntohl (t.challenge),
2775 (unsigned int) n->encrypt_key.crc32);
2777 /* trigger queue processing */
2778 process_encrypted_neighbour_queue (n);
2783 * We received a PONG message. Validate and update our status.
2785 * @param n sender of the PONG
2786 * @param m the encrypted PONG message itself
2789 handle_pong (struct Neighbour *n,
2790 const struct PongMessage *m)
2792 struct PongMessage t;
2793 struct ConnectNotifyMessage cnm;
2796 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2797 "Core service receives `%s' response from `%4s'.\n",
2798 "PONG", GNUNET_i2s (&n->peer));
2800 /* mark as garbage, just to be sure */
2801 memset (&t, 255, sizeof (t));
2804 &n->peer.hashPubKey,
2807 sizeof (struct PongMessage) -
2808 sizeof (struct GNUNET_MessageHeader)))
2810 GNUNET_break_op (0);
2813 GNUNET_STATISTICS_update (stats,
2814 gettext_noop ("# PONG messages decrypted"),
2817 if (0 != ntohl (t.reserved))
2819 GNUNET_break_op (0);
2823 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2824 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2826 GNUNET_i2s (&t.target),
2827 (unsigned int) ntohl (t.challenge),
2828 (unsigned int) n->decrypt_key.crc32);
2830 if ((0 != memcmp (&t.target,
2832 sizeof (struct GNUNET_PeerIdentity))) ||
2833 (n->ping_challenge != ntohl (t.challenge)))
2835 /* PONG malformed */
2837 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2838 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2840 GNUNET_i2s (&n->peer),
2841 (unsigned int) n->ping_challenge);
2842 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2843 "Received malformed `%s' received from `%4s' with challenge %u\n",
2844 "PONG", GNUNET_i2s (&t.target),
2845 (unsigned int) ntohl (t.challenge));
2847 GNUNET_break_op (0);
2852 case PEER_STATE_DOWN:
2853 GNUNET_break (0); /* should be impossible */
2855 case PEER_STATE_KEY_SENT:
2856 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2858 case PEER_STATE_KEY_RECEIVED:
2859 GNUNET_STATISTICS_update (stats,
2860 gettext_noop ("# Session keys confirmed via PONG"),
2863 n->status = PEER_STATE_KEY_CONFIRMED;
2864 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2866 n->bw_out_external_limit = t.inbound_bw_limit;
2867 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2868 n->bw_out_internal_limit);
2869 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2871 GNUNET_TRANSPORT_set_quota (transport,
2875 GNUNET_TIME_UNIT_FOREVER_REL,
2879 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2880 "Confirmed key via `%s' message for peer `%4s'\n",
2881 "PONG", GNUNET_i2s (&n->peer));
2883 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2885 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2886 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2888 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2889 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2890 cnm.distance = htonl (n->last_distance);
2891 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2893 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2894 process_encrypted_neighbour_queue (n);
2896 case PEER_STATE_KEY_CONFIRMED:
2897 n->last_activity = GNUNET_TIME_absolute_get ();
2898 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2899 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2901 = GNUNET_SCHEDULER_add_delayed (sched,
2902 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2914 * We received a SET_KEY message. Validate and update
2915 * our key material and status.
2917 * @param n the neighbour from which we received message m
2918 * @param m the set key message we received
2921 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2923 struct SetKeyMessage *m_cpy;
2924 struct GNUNET_TIME_Absolute t;
2925 struct GNUNET_CRYPTO_AesSessionKey k;
2926 struct PingMessage *ping;
2927 struct PongMessage *pong;
2928 enum PeerStateMachine sender_status;
2931 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2932 "Core service receives `%s' request from `%4s'.\n",
2933 "SET_KEY", GNUNET_i2s (&n->peer));
2935 if (n->public_key == NULL)
2937 if (n->pitr != NULL)
2940 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2941 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2947 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2948 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2950 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2951 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2952 /* lookup n's public key, then try again */
2953 GNUNET_assert (n->skm == NULL);
2955 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2958 GNUNET_TIME_UNIT_MINUTES,
2959 &process_hello_retry_handle_set_key, n);
2960 GNUNET_STATISTICS_update (stats,
2961 gettext_noop ("# SETKEY messages deferred (need public key)"),
2966 if (0 != memcmp (&m->target,
2968 sizeof (struct GNUNET_PeerIdentity)))
2970 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2971 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
2973 GNUNET_i2s (&m->target));
2976 if ((ntohl (m->purpose.size) !=
2977 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2978 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2979 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2980 sizeof (struct GNUNET_PeerIdentity)) ||
2982 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2983 &m->purpose, &m->signature, n->public_key)))
2985 /* invalid signature */
2986 GNUNET_break_op (0);
2989 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2990 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2991 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2992 (t.value < n->decrypt_key_created.value))
2994 /* this could rarely happen due to massive re-ordering of
2995 messages on the network level, but is most likely either
2996 a bug or some adversary messing with us. Report. */
2997 GNUNET_break_op (0);
3001 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3002 "Decrypting key material.\n");
3004 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3007 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3008 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3009 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3011 /* failed to decrypt !? */
3012 GNUNET_break_op (0);
3015 GNUNET_STATISTICS_update (stats,
3016 gettext_noop ("# SETKEY messages decrypted"),
3020 if (n->decrypt_key_created.value != t.value)
3022 /* fresh key, reset sequence numbers */
3023 n->last_sequence_number_received = 0;
3024 n->last_packets_bitmap = 0;
3025 n->decrypt_key_created = t;
3027 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3030 case PEER_STATE_DOWN:
3031 n->status = PEER_STATE_KEY_RECEIVED;
3033 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3034 "Responding to `%s' with my own key.\n", "SET_KEY");
3038 case PEER_STATE_KEY_SENT:
3039 case PEER_STATE_KEY_RECEIVED:
3040 n->status = PEER_STATE_KEY_RECEIVED;
3041 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3042 (sender_status != PEER_STATE_KEY_CONFIRMED))
3045 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3046 "Responding to `%s' with my own key (other peer has status %u).\n",
3048 (unsigned int) sender_status);
3053 case PEER_STATE_KEY_CONFIRMED:
3054 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3055 (sender_status != PEER_STATE_KEY_CONFIRMED))
3058 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3059 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3061 (unsigned int) sender_status);
3070 if (n->pending_ping != NULL)
3072 ping = n->pending_ping;
3073 n->pending_ping = NULL;
3074 handle_ping (n, ping);
3077 if (n->pending_pong != NULL)
3079 pong = n->pending_pong;
3080 n->pending_pong = NULL;
3081 handle_pong (n, pong);
3088 * Send a P2P message to a client.
3090 * @param sender who sent us the message?
3091 * @param client who should we give the message to?
3092 * @param m contains the message to transmit
3093 * @param msize number of bytes in buf to transmit
3096 send_p2p_message_to_client (struct Neighbour *sender,
3097 struct Client *client,
3098 const void *m, size_t msize)
3100 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3101 struct NotifyTrafficMessage *ntm;
3104 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3105 "Core service passes message from `%4s' of type %u to client.\n",
3106 GNUNET_i2s(&sender->peer),
3107 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3109 ntm = (struct NotifyTrafficMessage *) buf;
3110 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3111 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3112 ntm->distance = htonl (sender->last_distance);
3113 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3114 ntm->peer = sender->peer;
3115 memcpy (&ntm[1], m, msize);
3116 send_to_client (client, &ntm->header, GNUNET_YES);
3121 * Deliver P2P message to interested clients.
3123 * @param sender who sent us the message?
3124 * @param m the message
3125 * @param msize size of the message (including header)
3128 deliver_message (struct Neighbour *sender,
3129 const struct GNUNET_MessageHeader *m, size_t msize)
3132 struct Client *cpos;
3138 type = ntohs (m->type);
3140 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3141 "Received encapsulated message of type %u from `%4s'\n",
3142 (unsigned int) type,
3143 GNUNET_i2s (&sender->peer));
3145 GNUNET_snprintf (buf,
3147 gettext_noop ("# bytes of messages of type %u received"),
3148 (unsigned int) type);
3149 GNUNET_STATISTICS_set (stats,
3153 dropped = GNUNET_YES;
3155 while (cpos != NULL)
3157 deliver_full = GNUNET_NO;
3158 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3159 deliver_full = GNUNET_YES;
3162 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3164 if (type != cpos->types[tpos])
3166 deliver_full = GNUNET_YES;
3170 if (GNUNET_YES == deliver_full)
3172 send_p2p_message_to_client (sender, cpos, m, msize);
3173 dropped = GNUNET_NO;
3175 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3177 send_p2p_message_to_client (sender, cpos, m,
3178 sizeof (struct GNUNET_MessageHeader));
3182 if (dropped == GNUNET_YES)
3185 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3186 "Message of type %u from `%4s' not delivered to any client.\n",
3187 (unsigned int) type,
3188 GNUNET_i2s (&sender->peer));
3190 /* FIXME: stats... */
3196 * Align P2P message and then deliver to interested clients.
3198 * @param sender who sent us the message?
3199 * @param buffer unaligned (!) buffer containing message
3200 * @param msize size of the message (including header)
3203 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
3207 /* TODO: call to statistics? */
3208 memcpy (abuf, buffer, msize);
3209 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
3214 * Deliver P2P messages to interested clients.
3216 * @param sender who sent us the message?
3217 * @param buffer buffer containing messages, can be modified
3218 * @param buffer_size size of the buffer (overall)
3219 * @param offset offset where messages in the buffer start
3222 deliver_messages (struct Neighbour *sender,
3223 const char *buffer, size_t buffer_size, size_t offset)
3225 struct GNUNET_MessageHeader *mhp;
3226 struct GNUNET_MessageHeader mh;
3230 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
3232 if (0 != offset % sizeof (uint16_t))
3234 /* outch, need to copy to access header */
3235 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
3240 /* can access header directly */
3241 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
3243 msize = ntohs (mhp->size);
3244 if (msize + offset > buffer_size)
3246 /* malformed message, header says it is larger than what
3247 would fit into the overall buffer */
3248 GNUNET_break_op (0);
3251 #if HAVE_UNALIGNED_64_ACCESS
3252 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
3254 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
3256 if (GNUNET_YES == need_align)
3257 align_and_deliver (sender, &buffer[offset], msize);
3259 deliver_message (sender,
3260 (const struct GNUNET_MessageHeader *)
3261 &buffer[offset], msize);
3268 * We received an encrypted message. Decrypt, validate and
3269 * pass on to the appropriate clients.
3272 handle_encrypted_message (struct Neighbour *n,
3273 const struct EncryptedMessage *m)
3275 size_t size = ntohs (m->header.size);
3277 struct EncryptedMessage *pt; /* plaintext */
3280 struct GNUNET_TIME_Absolute t;
3284 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3285 "Core service receives `%s' request from `%4s'.\n",
3286 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3288 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3294 &buf[ENCRYPTED_HEADER_SIZE],
3295 size - ENCRYPTED_HEADER_SIZE))
3297 pt = (struct EncryptedMessage *) buf;
3299 GNUNET_CRYPTO_hash (&pt->sequence_number,
3300 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3302 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3303 "V-Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
3304 (unsigned int) (size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode)),
3308 if (0 != memcmp (&ph,
3309 &pt->plaintext_hash,
3310 sizeof (GNUNET_HashCode)))
3312 /* checksum failed */
3313 GNUNET_break_op (0);
3317 /* validate sequence number */
3318 snum = ntohl (pt->sequence_number);
3319 if (n->last_sequence_number_received == snum)
3321 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3322 "Received duplicate message, ignoring.\n");
3323 /* duplicate, ignore */
3324 GNUNET_STATISTICS_set (stats,
3325 gettext_noop ("# bytes dropped (duplicates)"),
3330 if ((n->last_sequence_number_received > snum) &&
3331 (n->last_sequence_number_received - snum > 32))
3333 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3334 "Received ancient out of sequence message, ignoring.\n");
3335 /* ancient out of sequence, ignore */
3336 GNUNET_STATISTICS_set (stats,
3337 gettext_noop ("# bytes dropped (out of sequence)"),
3342 if (n->last_sequence_number_received > snum)
3344 unsigned int rotbit =
3345 1 << (n->last_sequence_number_received - snum - 1);
3346 if ((n->last_packets_bitmap & rotbit) != 0)
3348 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3349 "Received duplicate message, ignoring.\n");
3350 GNUNET_STATISTICS_set (stats,
3351 gettext_noop ("# bytes dropped (duplicates)"),
3354 /* duplicate, ignore */
3357 n->last_packets_bitmap |= rotbit;
3359 if (n->last_sequence_number_received < snum)
3361 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3362 n->last_sequence_number_received = snum;
3365 /* check timestamp */
3366 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3367 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3369 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3371 ("Message received far too old (%llu ms). Content ignored.\n"),
3372 GNUNET_TIME_absolute_get_duration (t).value);
3373 GNUNET_STATISTICS_set (stats,
3374 gettext_noop ("# bytes dropped (ancient message)"),
3380 /* process decrypted message(s) */
3381 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3383 #if DEBUG_CORE_SET_QUOTA
3384 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3385 "Received %u b/s as new inbound limit for peer `%4s'\n",
3386 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3387 GNUNET_i2s (&n->peer));
3389 n->bw_out_external_limit = pt->inbound_bw_limit;
3390 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3391 n->bw_out_internal_limit);
3392 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3394 GNUNET_TRANSPORT_set_quota (transport,
3398 GNUNET_TIME_UNIT_FOREVER_REL,
3401 n->last_activity = GNUNET_TIME_absolute_get ();
3402 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3403 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3405 = GNUNET_SCHEDULER_add_delayed (sched,
3406 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3409 GNUNET_STATISTICS_set (stats,
3410 gettext_noop ("# bytes of payload decrypted"),
3411 size - sizeof (struct EncryptedMessage),
3413 deliver_messages (n, buf, size, sizeof (struct EncryptedMessage));
3418 * Function called by the transport for each received message.
3420 * @param cls closure
3421 * @param peer (claimed) identity of the other peer
3422 * @param message the message
3423 * @param latency estimated latency for communicating with the
3424 * given peer (round-trip)
3425 * @param distance in overlay hops, as given by transport plugin
3428 handle_transport_receive (void *cls,
3429 const struct GNUNET_PeerIdentity *peer,
3430 const struct GNUNET_MessageHeader *message,
3431 struct GNUNET_TIME_Relative latency,
3432 unsigned int distance)
3434 struct Neighbour *n;
3435 struct GNUNET_TIME_Absolute now;
3441 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3442 "Received message of type %u from `%4s', demultiplexing.\n",
3443 (unsigned int) ntohs (message->type),
3446 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3451 n = find_neighbour (peer);
3453 n = create_neighbour (peer);
3454 n->last_latency = latency;
3455 n->last_distance = distance;
3456 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3457 type = ntohs (message->type);
3458 size = ntohs (message->size);
3461 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3462 if (size != sizeof (struct SetKeyMessage))
3464 GNUNET_break_op (0);
3467 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3468 handle_set_key (n, (const struct SetKeyMessage *) message);
3470 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3471 if (size < sizeof (struct EncryptedMessage) +
3472 sizeof (struct GNUNET_MessageHeader))
3474 GNUNET_break_op (0);
3477 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3478 (n->status != PEER_STATE_KEY_CONFIRMED))
3480 GNUNET_break_op (0);
3483 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3485 case GNUNET_MESSAGE_TYPE_CORE_PING:
3486 if (size != sizeof (struct PingMessage))
3488 GNUNET_break_op (0);
3491 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3492 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3493 (n->status != PEER_STATE_KEY_CONFIRMED))
3496 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3497 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3498 "PING", GNUNET_i2s (&n->peer));
3500 GNUNET_free_non_null (n->pending_ping);
3501 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3502 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3505 handle_ping (n, (const struct PingMessage *) message);
3507 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3508 if (size != sizeof (struct PongMessage))
3510 GNUNET_break_op (0);
3513 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3514 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3515 (n->status != PEER_STATE_KEY_CONFIRMED) )
3518 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3519 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3520 "PONG", GNUNET_i2s (&n->peer));
3522 GNUNET_free_non_null (n->pending_pong);
3523 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3524 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3527 handle_pong (n, (const struct PongMessage *) message);
3530 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3531 _("Unsupported message of type %u received.\n"),
3532 (unsigned int) type);
3535 if (n->status == PEER_STATE_KEY_CONFIRMED)
3537 now = GNUNET_TIME_absolute_get ();
3538 n->last_activity = now;
3541 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3542 n->time_established = now;
3544 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3545 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3547 = GNUNET_SCHEDULER_add_delayed (sched,
3548 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3556 * Function that recalculates the bandwidth quota for the
3557 * given neighbour and transmits it to the transport service.
3559 * @param cls neighbour for the quota update
3563 neighbour_quota_update (void *cls,
3564 const struct GNUNET_SCHEDULER_TaskContext *tc)
3566 struct Neighbour *n = cls;
3567 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3570 unsigned long long distributable;
3571 uint64_t need_per_peer;
3572 uint64_t need_per_second;
3574 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3575 /* calculate relative preference among all neighbours;
3576 divides by a bit more to avoid division by zero AND to
3577 account for possibility of new neighbours joining any time
3578 AND to convert to double... */
3579 if (preference_sum == 0)
3581 pref_rel = 1.0 / (double) neighbour_count;
3585 pref_rel = n->current_preference / preference_sum;
3587 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3588 GNUNET_TIME_UNIT_SECONDS);
3589 need_per_second = need_per_peer * neighbour_count;
3591 if (bandwidth_target_out_bps > need_per_second)
3592 distributable = bandwidth_target_out_bps - need_per_second;
3593 share = distributable * pref_rel;
3594 if (share + need_per_peer > ( (uint32_t)-1))
3595 q_in = GNUNET_BANDWIDTH_value_init ((uint32_t) -1);
3597 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3598 /* check if we want to disconnect for good due to inactivity */
3599 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3600 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3603 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3604 "Forcing disconnect of `%4s' due to inactivity\n",
3605 GNUNET_i2s (&n->peer));
3607 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3609 #if DEBUG_CORE_QUOTA
3610 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3611 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3612 GNUNET_i2s (&n->peer),
3613 (unsigned int) ntohl (q_in.value__),
3614 bandwidth_target_out_bps,
3615 (unsigned int) ntohl (n->bw_in.value__),
3616 (unsigned int) ntohl (n->bw_out.value__),
3617 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3619 if (n->bw_in.value__ != q_in.value__)
3622 if (GNUNET_YES == n->is_connected)
3623 GNUNET_TRANSPORT_set_quota (transport,
3627 GNUNET_TIME_UNIT_FOREVER_REL,
3630 schedule_quota_update (n);
3635 * Function called by transport to notify us that
3636 * a peer connected to us (on the network level).
3638 * @param cls closure
3639 * @param peer the peer that connected
3640 * @param latency current latency of the connection
3641 * @param distance in overlay hops, as given by transport plugin
3644 handle_transport_notify_connect (void *cls,
3645 const struct GNUNET_PeerIdentity *peer,
3646 struct GNUNET_TIME_Relative latency,
3647 unsigned int distance)
3649 struct Neighbour *n;
3651 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3656 n = find_neighbour (peer);
3659 if (GNUNET_YES == n->is_connected)
3661 /* duplicate connect notification!? */
3668 n = create_neighbour (peer);
3670 GNUNET_STATISTICS_update (stats,
3671 gettext_noop ("# peers connected (transport)"),
3674 n->is_connected = GNUNET_YES;
3675 n->last_latency = latency;
3676 n->last_distance = distance;
3677 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3680 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3685 "Received connection from `%4s'.\n",
3686 GNUNET_i2s (&n->peer));
3688 GNUNET_TRANSPORT_set_quota (transport,
3692 GNUNET_TIME_UNIT_FOREVER_REL,
3699 * Function called by transport telling us that a peer
3702 * @param cls closure
3703 * @param peer the peer that disconnected
3706 handle_transport_notify_disconnect (void *cls,
3707 const struct GNUNET_PeerIdentity *peer)
3709 struct DisconnectNotifyMessage cnm;
3710 struct Neighbour *n;
3713 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3714 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3716 n = find_neighbour (peer);
3722 GNUNET_break (n->is_connected);
3723 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3724 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3726 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3727 n->is_connected = GNUNET_NO;
3728 GNUNET_STATISTICS_update (stats,
3729 gettext_noop ("# peers connected (transport)"),
3736 * Last task run during shutdown. Disconnects us from
3740 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3742 struct Neighbour *n;
3746 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3747 "Core service shutting down.\n");
3749 GNUNET_assert (transport != NULL);
3750 GNUNET_TRANSPORT_disconnect (transport);
3752 while (NULL != (n = neighbours))
3754 neighbours = n->next;
3755 GNUNET_assert (neighbour_count > 0);
3759 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
3760 GNUNET_SERVER_notification_context_destroy (notifier);
3762 while (NULL != (c = clients))
3763 handle_client_disconnect (NULL, c->client_handle);
3764 if (my_private_key != NULL)
3765 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3767 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3768 if (peerinfo != NULL)
3769 GNUNET_PEERINFO_disconnect (peerinfo);
3774 * Initiate core service.
3776 * @param cls closure
3777 * @param s scheduler to use
3778 * @param serv the initialized server
3779 * @param c configuration to use
3783 struct GNUNET_SCHEDULER_Handle *s,
3784 struct GNUNET_SERVER_Handle *serv,
3785 const struct GNUNET_CONFIGURATION_Handle *c)
3791 /* parse configuration */
3794 GNUNET_CONFIGURATION_get_value_number (c,
3797 &bandwidth_target_in_bps)) ||
3799 GNUNET_CONFIGURATION_get_value_number (c,
3802 &bandwidth_target_out_bps)) ||
3804 GNUNET_CONFIGURATION_get_value_filename (c,
3806 "HOSTKEY", &keyfile)))
3808 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3810 ("Core service is lacking key configuration settings. Exiting.\n"));
3811 GNUNET_SCHEDULER_shutdown (s);
3814 peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
3815 if (NULL == peerinfo)
3817 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3818 _("Could not access PEERINFO service. Exiting.\n"));
3819 GNUNET_SCHEDULER_shutdown (s);
3820 GNUNET_free (keyfile);
3823 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3824 GNUNET_free (keyfile);
3825 if (my_private_key == NULL)
3827 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3828 _("Core service could not access hostkey. Exiting.\n"));
3829 GNUNET_PEERINFO_disconnect (peerinfo);
3830 GNUNET_SCHEDULER_shutdown (s);
3833 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3834 GNUNET_CRYPTO_hash (&my_public_key,
3835 sizeof (my_public_key), &my_identity.hashPubKey);
3836 /* setup notification */
3838 notifier = GNUNET_SERVER_notification_context_create (server,
3840 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3841 /* setup transport connection */
3842 transport = GNUNET_TRANSPORT_connect (sched,
3845 &handle_transport_receive,
3846 &handle_transport_notify_connect,
3847 &handle_transport_notify_disconnect);
3848 GNUNET_assert (NULL != transport);
3849 stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3850 GNUNET_SCHEDULER_add_delayed (sched,
3851 GNUNET_TIME_UNIT_FOREVER_REL,
3852 &cleaning_task, NULL);
3853 /* process client requests */
3854 GNUNET_SERVER_add_handlers (server, handlers);
3855 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3856 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3862 * The main function for the transport service.
3864 * @param argc number of arguments from the command line
3865 * @param argv command line arguments
3866 * @return 0 ok, 1 on error
3869 main (int argc, char *const *argv)
3871 return (GNUNET_OK ==
3872 GNUNET_SERVICE_run (argc,
3875 GNUNET_SERVICE_OPTION_NONE,
3876 &run, NULL)) ? 0 : 1;
3879 /* end of gnunet-service-core.c */