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_YES
47 #define DEBUG_CORE_QUOTA GNUNET_YES
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, 5)
85 * What 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, 3)
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
390 * We keep neighbours in a linked list (for now).
392 struct Neighbour *next;
395 * Unencrypted messages destined for this peer.
397 struct MessageEntry *messages;
400 * Head of the batched, encrypted message queue (already ordered,
401 * transmit starting with the head).
403 struct MessageEntry *encrypted_head;
406 * Tail of the batched, encrypted message queue (already ordered,
407 * append new messages to tail)
409 struct MessageEntry *encrypted_tail;
412 * Handle for pending requests for transmission to this peer
413 * with the transport service. NULL if no request is pending.
415 struct GNUNET_TRANSPORT_TransmitHandle *th;
418 * Public key of the neighbour, NULL if we don't have it yet.
420 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
423 * We received a PING message before we got the "public_key"
424 * (or the SET_KEY). We keep it here until we have a key
425 * to decrypt it. NULL if no PING is pending.
427 struct PingMessage *pending_ping;
430 * We received a PONG message before we got the "public_key"
431 * (or the SET_KEY). We keep it here until we have a key
432 * to decrypt it. NULL if no PONG is pending.
434 struct PongMessage *pending_pong;
437 * Non-NULL if we are currently looking up HELLOs for this peer.
440 struct GNUNET_PEERINFO_IteratorContext *pitr;
443 * SetKeyMessage to transmit, NULL if we are not currently trying
446 struct SetKeyMessage *skm;
449 * Identity of the neighbour.
451 struct GNUNET_PeerIdentity peer;
454 * Key we use to encrypt our messages for the other peer
455 * (initialized by us when we do the handshake).
457 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
460 * Key we use to decrypt messages from the other peer
461 * (given to us by the other peer during the handshake).
463 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
466 * ID of task used for re-trying plaintext scheduling.
468 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
471 * ID of task used for re-trying SET_KEY and PING message.
473 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
476 * ID of task used for updating bandwidth quota for this neighbour.
478 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
481 * ID of task used for sending keep-alive pings.
483 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
486 * ID of task used for cleaning up dead neighbour entries.
488 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
491 * At what time did we generate our encryption key?
493 struct GNUNET_TIME_Absolute encrypt_key_created;
496 * At what time did the other peer generate the decryption key?
498 struct GNUNET_TIME_Absolute decrypt_key_created;
501 * At what time did we initially establish (as in, complete session
502 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
504 struct GNUNET_TIME_Absolute time_established;
507 * At what time did we last receive an encrypted message from the
508 * other peer? Should be zero if status != KEY_CONFIRMED.
510 struct GNUNET_TIME_Absolute last_activity;
513 * Last latency observed from this peer.
515 struct GNUNET_TIME_Relative last_latency;
518 * At what frequency are we currently re-trying SET_KEY messages?
520 struct GNUNET_TIME_Relative set_key_retry_frequency;
523 * Tracking bandwidth for sending to this peer.
525 struct GNUNET_BANDWIDTH_Tracker available_send_window;
528 * Tracking bandwidth for receiving from this peer.
530 struct GNUNET_BANDWIDTH_Tracker available_recv_window;
533 * How valueable were the messages of this peer recently?
535 unsigned long long current_preference;
538 * Bit map indicating which of the 32 sequence numbers before the last
539 * were received (good for accepting out-of-order packets and
540 * estimating reliability of the connection)
542 unsigned int last_packets_bitmap;
545 * last sequence number received on this connection (highest)
547 uint32_t last_sequence_number_received;
550 * last sequence number transmitted
552 uint32_t last_sequence_number_sent;
555 * Available bandwidth in for this peer (current target).
557 struct GNUNET_BANDWIDTH_Value32NBO bw_in;
560 * Available bandwidth out for this peer (current target).
562 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
565 * Internal bandwidth limit set for this peer (initially typically
566 * set to "-1"). Actual "bw_out" is MIN of
567 * "bpm_out_internal_limit" and "bw_out_external_limit".
569 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
572 * External bandwidth limit set for this peer by the
573 * peer that we are communicating with. "bw_out" is MIN of
574 * "bw_out_internal_limit" and "bw_out_external_limit".
576 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
579 * What was our PING challenge number (for this peer)?
581 uint32_t ping_challenge;
584 * What was the last distance to this peer as reported by the transports?
586 uint32_t last_distance;
589 * What is our connection status?
591 enum PeerStateMachine status;
594 * Are we currently connected to this neighbour?
602 * Data structure for each client connected to the core service.
607 * Clients are kept in a linked list.
612 * Handle for the client with the server API.
614 struct GNUNET_SERVER_Client *client_handle;
617 * Array of the types of messages this peer cares
618 * about (with "tcnt" entries). Allocated as part
619 * of this client struct, do not free!
621 const uint16_t *types;
624 * Options for messages this client cares about,
625 * see GNUNET_CORE_OPTION_ values.
630 * Number of types of incoming messages this client
631 * specifically cares about. Size of the "types" array.
641 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
646 static struct GNUNET_PeerIdentity my_identity;
651 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
656 struct GNUNET_SCHEDULER_Handle *sched;
661 const struct GNUNET_CONFIGURATION_Handle *cfg;
666 static struct GNUNET_SERVER_Handle *server;
671 static struct GNUNET_TRANSPORT_Handle *transport;
674 * Linked list of our clients.
676 static struct Client *clients;
679 * Context for notifications we need to send to our clients.
681 static struct GNUNET_SERVER_NotificationContext *notifier;
684 * We keep neighbours in a linked list (for now).
686 static struct Neighbour *neighbours;
689 * For creating statistics.
691 static struct GNUNET_STATISTICS_Handle *stats;
694 * Sum of all preferences among all neighbours.
696 static unsigned long long preference_sum;
699 * Total number of neighbours we have.
701 static unsigned int neighbour_count;
704 * How much inbound bandwidth are we supposed to be using per second?
705 * FIXME: this value is not used!
707 static unsigned long long bandwidth_target_in_bps;
710 * How much outbound bandwidth are we supposed to be using per second?
712 static unsigned long long bandwidth_target_out_bps;
717 * A preference value for a neighbour was update. Update
718 * the preference sum accordingly.
720 * @param inc how much was a preference value increased?
723 update_preference_sum (unsigned long long inc)
726 unsigned long long os;
729 preference_sum += inc;
730 if (preference_sum >= os)
732 /* overflow! compensate by cutting all values in half! */
737 n->current_preference /= 2;
738 preference_sum += n->current_preference;
741 GNUNET_STATISTICS_set (stats, gettext_noop ("# total peer preference"), preference_sum, GNUNET_NO);
746 * Find the entry for the given neighbour.
748 * @param peer identity of the neighbour
749 * @return NULL if we are not connected, otherwise the
752 static struct Neighbour *
753 find_neighbour (const struct GNUNET_PeerIdentity *peer)
755 struct Neighbour *ret;
758 while ((ret != NULL) &&
759 (0 != memcmp (&ret->peer,
760 peer, sizeof (struct GNUNET_PeerIdentity))))
767 * Send a message to one of our clients.
769 * @param client target for the message
770 * @param msg message to transmit
771 * @param can_drop could this message be dropped if the
772 * client's queue is getting too large?
775 send_to_client (struct Client *client,
776 const struct GNUNET_MessageHeader *msg,
779 #if DEBUG_CORE_CLIENT
780 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
781 "Preparing to send message of type %u to client.\n",
782 (unsigned int) ntohs (msg->type));
784 GNUNET_SERVER_notification_context_unicast (notifier,
785 client->client_handle,
792 * Send a message to all of our current clients that have
793 * the right options set.
795 * @param msg message to multicast
796 * @param can_drop can this message be discarded if the queue is too long
797 * @param options mask to use
800 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
809 if (0 != (c->options & options))
811 #if DEBUG_CORE_CLIENT
812 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
813 "Sending message of type %u to client.\n",
814 (unsigned int) ntohs (msg->type));
816 send_to_client (c, msg, can_drop);
824 * Handle CORE_INIT request.
827 handle_client_init (void *cls,
828 struct GNUNET_SERVER_Client *client,
829 const struct GNUNET_MessageHeader *message)
831 const struct InitMessage *im;
832 struct InitReplyMessage irm;
835 const uint16_t *types;
838 struct ConnectNotifyMessage cnm;
841 #if DEBUG_CORE_CLIENT
842 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
843 "Client connecting to core service with `%s' message\n",
846 /* check that we don't have an entry already */
850 if (client == c->client_handle)
853 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
858 msize = ntohs (message->size);
859 if (msize < sizeof (struct InitMessage))
862 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
865 GNUNET_SERVER_notification_context_add (notifier, client);
866 im = (const struct InitMessage *) message;
867 types = (const uint16_t *) &im[1];
868 msize -= sizeof (struct InitMessage);
869 c = GNUNET_malloc (sizeof (struct Client) + msize);
870 c->client_handle = client;
873 c->tcnt = msize / sizeof (uint16_t);
874 c->types = (const uint16_t *) &c[1];
875 wtypes = (uint16_t *) &c[1];
876 for (i=0;i<c->tcnt;i++)
877 wtypes[i] = ntohs (types[i]);
878 c->options = ntohl (im->options);
879 #if DEBUG_CORE_CLIENT
880 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
881 "Client %p is interested in %u message types\n",
883 (unsigned int) c->tcnt);
885 /* send init reply message */
886 irm.header.size = htons (sizeof (struct InitReplyMessage));
887 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
888 irm.reserved = htonl (0);
889 memcpy (&irm.publicKey,
891 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
892 #if DEBUG_CORE_CLIENT
893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
894 "Sending `%s' message to client.\n", "INIT_REPLY");
896 send_to_client (c, &irm.header, GNUNET_NO);
897 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
899 /* notify new client about existing neighbours */
900 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
901 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
905 if (n->status == PEER_STATE_KEY_CONFIRMED)
907 #if DEBUG_CORE_CLIENT
908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
909 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
911 cnm.distance = htonl (n->last_distance);
912 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
914 send_to_client (c, &cnm.header, GNUNET_NO);
919 GNUNET_SERVER_receive_done (client, GNUNET_OK);
924 * A client disconnected, clean up.
927 * @param client identification of the client
930 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
937 #if DEBUG_CORE_CLIENT
938 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
939 "Client %p has disconnected from core service.\n",
946 if (client == pos->client_handle)
951 prev->next = pos->next;
958 /* client never sent INIT */
963 * Handle REQUEST_INFO request.
966 handle_client_request_info (void *cls,
967 struct GNUNET_SERVER_Client *client,
968 const struct GNUNET_MessageHeader *message)
970 const struct RequestInfoMessage *rcm;
972 struct ConfigurationInfoMessage cim;
975 unsigned long long old_preference;
976 struct GNUNET_SERVER_TransmitContext *tc;
978 #if DEBUG_CORE_CLIENT
979 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
980 "Core service receives `%s' request.\n", "REQUEST_INFO");
982 rcm = (const struct RequestInfoMessage *) message;
983 n = find_neighbour (&rcm->peer);
984 memset (&cim, 0, sizeof (cim));
987 want_reserv = ntohl (rcm->reserve_inbound);
988 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
990 n->bw_out_internal_limit = rcm->limit_outbound;
991 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
992 n->bw_out_external_limit);
993 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
995 GNUNET_TRANSPORT_set_quota (transport,
999 GNUNET_TIME_UNIT_FOREVER_REL,
1002 if (want_reserv < 0)
1004 got_reserv = want_reserv;
1006 else if (want_reserv > 0)
1008 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1009 want_reserv).value == 0)
1010 got_reserv = want_reserv;
1012 got_reserv = 0; /* all or nothing */
1016 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1018 old_preference = n->current_preference;
1019 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1020 if (old_preference > n->current_preference)
1022 /* overflow; cap at maximum value */
1023 n->current_preference = (unsigned long long) -1;
1025 update_preference_sum (n->current_preference - old_preference);
1026 #if DEBUG_CORE_QUOTA
1027 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1028 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1030 GNUNET_i2s (&rcm->peer),
1033 cim.reserved_amount = htonl (got_reserv);
1034 cim.bw_in = n->bw_in;
1035 cim.bw_out = n->bw_out;
1036 cim.preference = n->current_preference;
1038 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1039 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1040 cim.peer = rcm->peer;
1042 #if DEBUG_CORE_CLIENT
1043 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1044 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1046 tc = GNUNET_SERVER_transmit_context_create (client);
1047 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1048 GNUNET_SERVER_transmit_context_run (tc,
1049 GNUNET_TIME_UNIT_FOREVER_REL);
1054 * Free the given entry for the neighbour (it has
1055 * already been removed from the list at this point).
1057 * @param n neighbour to free
1060 free_neighbour (struct Neighbour *n)
1062 struct MessageEntry *m;
1064 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1065 "Destroying neighbour entry for peer `%4s'\n",
1066 GNUNET_i2s (&n->peer));
1067 if (n->pitr != NULL)
1069 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1074 GNUNET_free (n->skm);
1077 while (NULL != (m = n->messages))
1079 n->messages = m->next;
1082 while (NULL != (m = n->encrypted_head))
1084 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1091 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1094 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1095 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1096 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1097 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1098 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1099 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1100 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1101 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1102 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1103 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1104 if (n->status == PEER_STATE_KEY_CONFIRMED)
1105 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1106 GNUNET_free_non_null (n->public_key);
1107 GNUNET_free_non_null (n->pending_ping);
1108 GNUNET_free_non_null (n->pending_pong);
1114 * Check if we have encrypted messages for the specified neighbour
1115 * pending, and if so, check with the transport about sending them
1118 * @param n neighbour to check.
1120 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1124 * Encrypt size bytes from in and write the result to out. Use the
1125 * key for outbound traffic of the given neighbour.
1127 * @param n neighbour we are sending to
1128 * @param iv initialization vector to use
1129 * @param in ciphertext
1130 * @param out plaintext
1131 * @param size size of in/out
1132 * @return GNUNET_OK on success
1135 do_encrypt (struct Neighbour *n,
1136 const GNUNET_HashCode * iv,
1137 const void *in, void *out, size_t size)
1139 if (size != (uint16_t) size)
1144 GNUNET_assert (size ==
1145 GNUNET_CRYPTO_aes_encrypt (in,
1149 GNUNET_CRYPTO_AesInitializationVector
1151 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1153 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1154 "Encrypted %u bytes for `%4s' using key %u\n",
1155 (unsigned int) size,
1156 GNUNET_i2s (&n->peer),
1157 (unsigned int) n->encrypt_key.crc32);
1164 * Consider freeing the given neighbour since we may not need
1165 * to keep it around anymore.
1167 * @param n neighbour to consider discarding
1170 consider_free_neighbour (struct Neighbour *n);
1174 * Task triggered when a neighbour entry is about to time out
1175 * (and we should prevent this by sending a PING).
1177 * @param cls the 'struct Neighbour'
1178 * @param tc scheduler context (not used)
1181 send_keep_alive (void *cls,
1182 const struct GNUNET_SCHEDULER_TaskContext *tc)
1184 struct Neighbour *n = cls;
1185 struct GNUNET_TIME_Relative retry;
1186 struct GNUNET_TIME_Relative left;
1187 struct MessageEntry *me;
1188 struct PingMessage pp;
1189 struct PingMessage *pm;
1191 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1193 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1194 sizeof (struct PingMessage));
1195 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1196 me->priority = PING_PRIORITY;
1197 me->size = sizeof (struct PingMessage);
1198 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1202 pm = (struct PingMessage *) &me[1];
1203 pm->header.size = htons (sizeof (struct PingMessage));
1204 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1205 pp.challenge = htonl (n->ping_challenge);
1206 pp.target = n->peer;
1208 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1209 "Encrypting `%s' message with challenge %u for `%4s' using key %u.\n",
1211 (unsigned int) n->ping_challenge,
1212 GNUNET_i2s (&n->peer),
1213 (unsigned int) n->encrypt_key.crc32);
1216 &n->peer.hashPubKey,
1219 sizeof (struct PingMessage) -
1220 sizeof (struct GNUNET_MessageHeader));
1221 process_encrypted_neighbour_queue (n);
1222 /* reschedule PING job */
1223 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1224 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1225 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1226 MIN_PING_FREQUENCY);
1228 = GNUNET_SCHEDULER_add_delayed (sched,
1237 * Task triggered when a neighbour entry might have gotten stale.
1239 * @param cls the 'struct Neighbour'
1240 * @param tc scheduler context (not used)
1243 consider_free_task (void *cls,
1244 const struct GNUNET_SCHEDULER_TaskContext *tc)
1246 struct Neighbour *n = cls;
1248 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1249 consider_free_neighbour (n);
1254 * Consider freeing the given neighbour since we may not need
1255 * to keep it around anymore.
1257 * @param n neighbour to consider discarding
1260 consider_free_neighbour (struct Neighbour *n)
1262 struct Neighbour *pos;
1263 struct Neighbour *prev;
1264 struct GNUNET_TIME_Relative left;
1266 if ( (n->th != NULL) ||
1267 (n->pitr != NULL) ||
1268 (n->status == PEER_STATE_KEY_CONFIRMED) ||
1269 (GNUNET_YES == n->is_connected) )
1270 return; /* no chance */
1272 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1273 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1276 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1277 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1278 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1280 &consider_free_task,
1284 /* actually free the neighbour... */
1293 neighbours = n->next;
1295 prev->next = n->next;
1296 GNUNET_assert (neighbour_count > 0);
1298 GNUNET_STATISTICS_set (stats,
1299 gettext_noop ("# active neighbours"),
1307 * Function called when the transport service is ready to
1308 * receive an encrypted message for the respective peer
1310 * @param cls neighbour to use message from
1311 * @param size number of bytes we can transmit
1312 * @param buf where to copy the message
1313 * @return number of bytes transmitted
1316 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1318 struct Neighbour *n = cls;
1319 struct MessageEntry *m;
1324 m = n->encrypted_head;
1327 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1334 GNUNET_assert (size >= m->size);
1335 memcpy (cbuf, &m[1], m->size);
1337 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1340 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1341 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1342 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1344 GNUNET_i2s (&n->peer));
1346 process_encrypted_neighbour_queue (n);
1351 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1352 "Transmission of message of type %u and size %u failed\n",
1353 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1354 (unsigned int) m->size);
1358 consider_free_neighbour (n);
1364 * Check if we have plaintext messages for the specified neighbour
1365 * pending, and if so, consider batching and encrypting them (and
1366 * then trigger processing of the encrypted queue if needed).
1368 * @param n neighbour to check.
1370 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1374 * Check if we have encrypted messages for the specified neighbour
1375 * pending, and if so, check with the transport about sending them
1378 * @param n neighbour to check.
1381 process_encrypted_neighbour_queue (struct Neighbour *n)
1383 struct MessageEntry *m;
1386 return; /* request already pending */
1387 m = n->encrypted_head;
1390 /* encrypted queue empty, try plaintext instead */
1391 process_plaintext_neighbour_queue (n);
1395 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1396 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1397 (unsigned int) m->size,
1398 GNUNET_i2s (&n->peer),
1399 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).
1403 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1406 GNUNET_TIME_absolute_get_remaining
1408 ¬ify_encrypted_transmit_ready,
1412 /* message request too large or duplicate request */
1414 /* discard encrypted message */
1415 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1419 process_encrypted_neighbour_queue (n);
1425 * Decrypt size bytes from in and write the result to out. Use the
1426 * key for inbound traffic of the given neighbour. This function does
1427 * NOT do any integrity-checks on the result.
1429 * @param n neighbour we are receiving from
1430 * @param iv initialization vector to use
1431 * @param in ciphertext
1432 * @param out plaintext
1433 * @param size size of in/out
1434 * @return GNUNET_OK on success
1437 do_decrypt (struct Neighbour *n,
1438 const GNUNET_HashCode * iv,
1439 const void *in, void *out, size_t size)
1441 if (size != (uint16_t) size)
1446 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1447 (n->status != PEER_STATE_KEY_CONFIRMED))
1449 GNUNET_break_op (0);
1450 return GNUNET_SYSERR;
1453 GNUNET_CRYPTO_aes_decrypt (in,
1457 GNUNET_CRYPTO_AesInitializationVector *) iv,
1461 return GNUNET_SYSERR;
1463 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1465 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1466 "Decrypted %u bytes from `%4s' using key %u\n",
1467 (unsigned int) size,
1468 GNUNET_i2s (&n->peer),
1469 (unsigned int) n->decrypt_key.crc32);
1476 * Select messages for transmission. This heuristic uses a combination
1477 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1478 * and priority-based discard (in case no feasible schedule exist) and
1479 * speculative optimization (defer any kind of transmission until
1480 * we either create a batch of significant size, 25% of max, or until
1481 * we are close to a deadline). Furthermore, when scheduling the
1482 * heuristic also packs as many messages into the batch as possible,
1483 * starting with those with the earliest deadline. Yes, this is fun.
1485 * @param n neighbour to select messages from
1486 * @param size number of bytes to select for transmission
1487 * @param retry_time set to the time when we should try again
1488 * (only valid if this function returns zero)
1489 * @return number of bytes selected, or 0 if we decided to
1490 * defer scheduling overall; in that case, retry_time is set.
1493 select_messages (struct Neighbour *n,
1494 size_t size, struct GNUNET_TIME_Relative *retry_time)
1496 struct MessageEntry *pos;
1497 struct MessageEntry *min;
1498 struct MessageEntry *last;
1499 unsigned int min_prio;
1500 struct GNUNET_TIME_Absolute t;
1501 struct GNUNET_TIME_Absolute now;
1502 struct GNUNET_TIME_Relative delta;
1504 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1507 unsigned int queue_size;
1508 int discard_low_prio;
1510 GNUNET_assert (NULL != n->messages);
1511 now = GNUNET_TIME_absolute_get ();
1512 /* last entry in linked list of messages processed */
1514 /* should we remove the entry with the lowest
1515 priority from consideration for scheduling at the
1526 discard_low_prio = GNUNET_YES;
1527 while (GNUNET_YES == discard_low_prio)
1531 discard_low_prio = GNUNET_NO;
1532 /* calculate number of bytes available for transmission at time "t" */
1533 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1535 /* how many bytes have we (hypothetically) scheduled so far */
1537 /* maximum time we can wait before transmitting anything
1538 and still make all of our deadlines */
1539 slack = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1541 /* note that we use "*2" here because we want to look
1542 a bit further into the future; much more makes no
1543 sense since new message might be scheduled in the
1545 while ((pos != NULL) && (off < size * 2))
1547 if (pos->do_transmit == GNUNET_YES)
1549 /* already removed from consideration */
1553 if (discard_low_prio == GNUNET_NO)
1555 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1556 if (delta.value > 0)
1558 // FIXME: HUH? Check!
1560 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1563 if (avail < pos->size)
1565 // FIXME: HUH? Check!
1566 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1571 /* update slack, considering both its absolute deadline
1572 and relative deadlines caused by other messages
1573 with their respective load */
1574 slack = GNUNET_TIME_relative_min (slack,
1575 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1577 if (pos->deadline.value <= now.value)
1580 slack = GNUNET_TIME_UNIT_ZERO;
1582 else if (GNUNET_YES == pos->got_slack)
1584 /* should be soon now! */
1585 slack = GNUNET_TIME_relative_min (slack,
1586 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1591 GNUNET_TIME_relative_min (slack,
1592 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1593 pos->got_slack = GNUNET_YES;
1594 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1595 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
1600 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1601 if (pos->priority <= min_prio)
1603 /* update min for discard */
1604 min_prio = pos->priority;
1609 if (discard_low_prio)
1611 GNUNET_assert (min != NULL);
1612 /* remove lowest-priority entry from consideration */
1613 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1617 /* guard against sending "tiny" messages with large headers without
1619 if ( (slack.value > 0) &&
1621 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1623 /* less than 25% of message would be filled with deadlines still
1624 being met if we delay by one second or more; so just wait for
1625 more data; but do not wait longer than 1s (since we don't want
1626 to delay messages for a really long time either). */
1627 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1628 /* reset do_transmit values for next time */
1631 pos->do_transmit = GNUNET_NO;
1635 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1636 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1637 (unsigned long long) slack.value,
1639 (unsigned int) size);
1643 /* select marked messages (up to size) for transmission */
1648 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1650 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1655 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1659 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1660 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1661 (unsigned long long) off, (unsigned long long) tsize,
1662 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
1663 GNUNET_i2s (&n->peer));
1670 * Batch multiple messages into a larger buffer.
1672 * @param n neighbour to take messages from
1673 * @param buf target buffer
1674 * @param size size of buf
1675 * @param deadline set to transmission deadline for the result
1676 * @param retry_time set to the time when we should try again
1677 * (only valid if this function returns zero)
1678 * @param priority set to the priority of the batch
1679 * @return number of bytes written to buf (can be zero)
1682 batch_message (struct Neighbour *n,
1685 struct GNUNET_TIME_Absolute *deadline,
1686 struct GNUNET_TIME_Relative *retry_time,
1687 unsigned int *priority)
1689 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1690 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1691 struct MessageEntry *pos;
1692 struct MessageEntry *prev;
1693 struct MessageEntry *next;
1698 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1699 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1700 if (0 == select_messages (n, size, retry_time))
1703 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1704 "No messages selected, will try again in %llu ms\n",
1709 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1710 ntm->distance = htonl (n->last_distance);
1711 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1712 ntm->peer = n->peer;
1716 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1719 if (GNUNET_YES == pos->do_transmit)
1721 GNUNET_assert (pos->size <= size);
1722 /* do notifications */
1723 /* FIXME: track if we have *any* client that wants
1724 full notifications and only do this if that is
1726 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1728 memcpy (&ntm[1], &pos[1], pos->size);
1729 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1730 sizeof (struct GNUNET_MessageHeader));
1731 send_to_all_clients (&ntm->header,
1733 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1737 /* message too large for 'full' notifications, we do at
1738 least the 'hdr' type */
1741 sizeof (struct GNUNET_MessageHeader));
1743 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1745 send_to_all_clients (&ntm->header,
1747 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1749 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1750 "Encrypting message of type %u\n",
1751 (unsigned int) ntohs(((struct GNUNET_MessageHeader*)&pos[1])->type));
1753 /* copy for encrypted transmission */
1754 memcpy (&buf[ret], &pos[1], pos->size);
1757 *priority += pos->priority;
1759 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1760 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1761 (unsigned int) pos->size,
1762 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1764 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1778 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1779 "Deadline for message batch is %llu ms\n",
1780 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1787 * Remove messages with deadlines that have long expired from
1790 * @param n neighbour to inspect
1793 discard_expired_messages (struct Neighbour *n)
1795 struct MessageEntry *prev;
1796 struct MessageEntry *next;
1797 struct MessageEntry *pos;
1798 struct GNUNET_TIME_Absolute now;
1799 struct GNUNET_TIME_Relative delta;
1801 now = GNUNET_TIME_absolute_get ();
1807 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1808 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1811 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1812 "Message is %llu ms past due, discarding.\n",
1829 * Signature of the main function of a task.
1831 * @param cls closure
1832 * @param tc context information (why was this task triggered now)
1835 retry_plaintext_processing (void *cls,
1836 const struct GNUNET_SCHEDULER_TaskContext *tc)
1838 struct Neighbour *n = cls;
1840 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1841 process_plaintext_neighbour_queue (n);
1846 * Send our key (and encrypted PING) to the other peer.
1848 * @param n the other peer
1850 static void send_key (struct Neighbour *n);
1853 * Task that will retry "send_key" if our previous attempt failed
1857 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1859 struct Neighbour *n = cls;
1862 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1863 "Retrying key transmission to `%4s'\n",
1864 GNUNET_i2s (&n->peer));
1866 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1867 n->set_key_retry_frequency =
1868 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1874 * Check if we have plaintext messages for the specified neighbour
1875 * pending, and if so, consider batching and encrypting them (and
1876 * then trigger processing of the encrypted queue if needed).
1878 * @param n neighbour to check.
1881 process_plaintext_neighbour_queue (struct Neighbour *n)
1883 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1886 struct EncryptedMessage *em; /* encrypted message */
1887 struct EncryptedMessage *ph; /* plaintext header */
1888 struct MessageEntry *me;
1889 unsigned int priority;
1890 struct GNUNET_TIME_Absolute deadline;
1891 struct GNUNET_TIME_Relative retry_time;
1894 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1896 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1897 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1901 case PEER_STATE_DOWN:
1904 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1905 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1906 GNUNET_i2s(&n->peer));
1909 case PEER_STATE_KEY_SENT:
1910 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1911 n->retry_set_key_task
1912 = GNUNET_SCHEDULER_add_delayed (sched,
1913 n->set_key_retry_frequency,
1914 &set_key_retry_task, n);
1916 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1917 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1918 GNUNET_i2s(&n->peer));
1921 case PEER_STATE_KEY_RECEIVED:
1922 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1923 n->retry_set_key_task
1924 = GNUNET_SCHEDULER_add_delayed (sched,
1925 n->set_key_retry_frequency,
1926 &set_key_retry_task, n);
1928 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1929 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1930 GNUNET_i2s(&n->peer));
1933 case PEER_STATE_KEY_CONFIRMED:
1934 /* ready to continue */
1937 discard_expired_messages (n);
1938 if (n->messages == NULL)
1941 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1942 "Plaintext message queue for `%4s' is empty.\n",
1943 GNUNET_i2s(&n->peer));
1945 return; /* no pending messages */
1947 if (n->encrypted_head != NULL)
1950 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1951 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1952 GNUNET_i2s(&n->peer));
1954 return; /* wait for messages already encrypted to be
1957 ph = (struct EncryptedMessage *) pbuf;
1958 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1960 used = sizeof (struct EncryptedMessage);
1961 used += batch_message (n,
1963 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1964 &deadline, &retry_time, &priority);
1965 if (used == sizeof (struct EncryptedMessage))
1968 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1969 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1970 GNUNET_i2s(&n->peer));
1972 /* no messages selected for sending, try again later... */
1973 n->retry_plaintext_task =
1974 GNUNET_SCHEDULER_add_delayed (sched,
1976 &retry_plaintext_processing, n);
1979 #if DEBUG_CORE_QUOTA
1980 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1981 "Sending %u b/s as new limit to peer `%4s'\n",
1982 (unsigned int) ntohl (n->bw_in.value__),
1983 GNUNET_i2s (&n->peer));
1985 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1));
1986 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1987 ph->inbound_bw_limit = n->bw_in;
1988 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1990 /* setup encryption message header */
1991 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1992 me->deadline = deadline;
1993 me->priority = priority;
1995 em = (struct EncryptedMessage *) &me[1];
1996 em->header.size = htons (used);
1997 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1998 em->iv_seed = ph->iv_seed;
1999 esize = used - ENCRYPTED_HEADER_SIZE;
2000 GNUNET_CRYPTO_hash (&ph->sequence_number,
2001 esize - sizeof (GNUNET_HashCode),
2002 &ph->plaintext_hash);
2003 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
2005 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2006 "Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
2007 (unsigned int) (esize - sizeof (GNUNET_HashCode)),
2008 GNUNET_h2s (&ph->plaintext_hash),
2013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2014 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2015 (unsigned int) esize,
2016 GNUNET_i2s(&n->peer),
2017 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2019 GNUNET_assert (GNUNET_OK ==
2022 &ph->plaintext_hash,
2023 &em->plaintext_hash, esize));
2024 /* append to transmission list */
2025 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2029 process_encrypted_neighbour_queue (n);
2034 * Function that recalculates the bandwidth quota for the
2035 * given neighbour and transmits it to the transport service.
2037 * @param cls neighbour for the quota update
2041 neighbour_quota_update (void *cls,
2042 const struct GNUNET_SCHEDULER_TaskContext *tc);
2046 * Schedule the task that will recalculate the bandwidth
2047 * quota for this peer (and possibly force a disconnect of
2048 * idle peers by calculating a bandwidth of zero).
2051 schedule_quota_update (struct Neighbour *n)
2053 GNUNET_assert (n->quota_update_task ==
2054 GNUNET_SCHEDULER_NO_TASK);
2055 n->quota_update_task
2056 = GNUNET_SCHEDULER_add_delayed (sched,
2057 QUOTA_UPDATE_FREQUENCY,
2058 &neighbour_quota_update,
2064 * Initialize a new 'struct Neighbour'.
2066 * @param pid ID of the new neighbour
2067 * @return handle for the new neighbour
2069 static struct Neighbour *
2070 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2072 struct Neighbour *n;
2073 struct GNUNET_TIME_Absolute now;
2075 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2076 "Creating neighbour entry for peer `%4s'\n",
2078 n = GNUNET_malloc (sizeof (struct Neighbour));
2079 n->next = neighbours;
2082 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbours entries allocated"), neighbour_count, GNUNET_NO);
2084 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2085 now = GNUNET_TIME_absolute_get ();
2086 n->encrypt_key_created = now;
2087 n->last_activity = now;
2088 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2089 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2090 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2091 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init ((uint32_t) - 1);
2092 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2093 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2095 neighbour_quota_update (n, NULL);
2096 consider_free_neighbour (n);
2102 * Handle CORE_SEND request.
2105 * @param client the client issuing the request
2106 * @param message the "struct SendMessage"
2109 handle_client_send (void *cls,
2110 struct GNUNET_SERVER_Client *client,
2111 const struct GNUNET_MessageHeader *message)
2113 const struct SendMessage *sm;
2114 struct Neighbour *n;
2115 struct MessageEntry *prev;
2116 struct MessageEntry *pos;
2117 struct MessageEntry *e;
2118 struct MessageEntry *min_prio_entry;
2119 struct MessageEntry *min_prio_prev;
2120 unsigned int min_prio;
2121 unsigned int queue_size;
2124 msize = ntohs (message->size);
2126 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2130 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2133 sm = (const struct SendMessage *) message;
2134 msize -= sizeof (struct SendMessage);
2135 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2137 /* FIXME: should we not allow loopback-injection here? */
2140 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2143 n = find_neighbour (&sm->peer);
2145 n = create_neighbour (&sm->peer);
2147 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2148 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2150 (unsigned int) msize,
2151 GNUNET_i2s (&sm->peer));
2153 /* bound queue size */
2154 discard_expired_messages (n);
2155 min_prio = (unsigned int) -1;
2156 min_prio_entry = NULL;
2157 min_prio_prev = NULL;
2163 if (pos->priority < min_prio)
2165 min_prio_entry = pos;
2166 min_prio_prev = prev;
2167 min_prio = pos->priority;
2173 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2176 if (ntohl(sm->priority) <= min_prio)
2178 /* discard new entry */
2180 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2181 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2183 (unsigned int) MAX_PEER_QUEUE_SIZE,
2184 (unsigned int) msize,
2185 (unsigned int) ntohs (message->type));
2188 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2191 /* discard "min_prio_entry" */
2193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2194 "Queue full, discarding existing older request\n");
2196 if (min_prio_prev == NULL)
2197 n->messages = min_prio_entry->next;
2199 min_prio_prev->next = min_prio_entry->next;
2200 GNUNET_free (min_prio_entry);
2204 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2205 "Adding transmission request for `%4s' of size %u to queue\n",
2206 GNUNET_i2s (&sm->peer),
2207 (unsigned int) msize);
2209 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2210 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2211 e->priority = ntohl (sm->priority);
2213 memcpy (&e[1], &sm[1], msize);
2215 /* insert, keep list sorted by deadline */
2218 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2229 /* consider scheduling now */
2230 process_plaintext_neighbour_queue (n);
2232 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2237 * Function called when the transport service is ready to
2238 * receive a message. Only resets 'n->th' to NULL.
2240 * @param cls neighbour to use message from
2241 * @param size number of bytes we can transmit
2242 * @param buf where to copy the message
2243 * @return number of bytes transmitted
2246 notify_transport_connect_done (void *cls, size_t size, void *buf)
2248 struct Neighbour *n = cls;
2253 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2254 _("Failed to connect to `%4s': transport failed to connect\n"),
2255 GNUNET_i2s (&n->peer));
2264 * Handle CORE_REQUEST_CONNECT request.
2267 * @param client the client issuing the request
2268 * @param message the "struct ConnectMessage"
2271 handle_client_request_connect (void *cls,
2272 struct GNUNET_SERVER_Client *client,
2273 const struct GNUNET_MessageHeader *message)
2275 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2276 struct Neighbour *n;
2277 struct GNUNET_TIME_Relative timeout;
2279 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2282 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2285 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2286 n = find_neighbour (&cm->peer);
2288 n = create_neighbour (&cm->peer);
2289 if ( (GNUNET_YES == n->is_connected) ||
2291 return; /* already connected, or at least trying */
2292 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2294 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2295 "Core received `%s' request for `%4s', will try to establish connection\n",
2297 GNUNET_i2s (&cm->peer));
2299 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2300 /* ask transport to connect to the peer */
2301 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2303 sizeof (struct GNUNET_MessageHeader), 0,
2305 ¬ify_transport_connect_done,
2307 GNUNET_break (NULL != n->th);
2312 * List of handlers for the messages understood by this
2315 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2316 {&handle_client_init, NULL,
2317 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2318 {&handle_client_request_info, NULL,
2319 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2320 sizeof (struct RequestInfoMessage)},
2321 {&handle_client_send, NULL,
2322 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2323 {&handle_client_request_connect, NULL,
2324 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2325 sizeof (struct ConnectMessage)},
2331 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2332 * the neighbour's struct and retry send_key. Or, if we did not get a
2333 * HELLO, just do nothing.
2335 * @param cls the 'struct Neighbour' to retry sending the key for
2336 * @param peer the peer for which this is the HELLO
2337 * @param hello HELLO message of that peer
2338 * @param trust amount of trust we currently have in that peer
2341 process_hello_retry_send_key (void *cls,
2342 const struct GNUNET_PeerIdentity *peer,
2343 const struct GNUNET_HELLO_Message *hello,
2346 struct Neighbour *n = cls;
2351 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2352 "Entered `process_hello_retry_send_key' and `peer' is NULL!\n");
2355 if (n->public_key != NULL)
2357 GNUNET_STATISTICS_update (stats,
2358 gettext_noop ("# SETKEY messages deferred (need public key)"),
2365 GNUNET_STATISTICS_update (stats,
2366 gettext_noop ("# Delayed connecting due to lack of public key"),
2369 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2370 n->retry_set_key_task
2371 = GNUNET_SCHEDULER_add_delayed (sched,
2372 n->set_key_retry_frequency,
2373 &set_key_retry_task, n);
2379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2380 "Entered `process_hello_retry_send_key' for peer `%4s'\n",
2383 if (n->public_key != NULL)
2386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2387 "already have public key for peer %s!! (so why are we here?)\n",
2394 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2395 "Received new `%s' message for `%4s', initiating key exchange.\n",
2400 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2401 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2403 GNUNET_STATISTICS_update (stats,
2404 gettext_noop ("# Error extracting public key from HELLO"),
2407 GNUNET_free (n->public_key);
2408 n->public_key = NULL;
2410 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2411 "GNUNET_HELLO_get_key returned awfully\n");
2419 * Send our key (and encrypted PING) to the other peer.
2421 * @param n the other peer
2424 send_key (struct Neighbour *n)
2426 struct SetKeyMessage *sm;
2427 struct MessageEntry *me;
2428 struct PingMessage pp;
2429 struct PingMessage *pm;
2431 if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2435 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2436 "Key exchange in progress with `%4s'.\n",
2437 GNUNET_i2s (&n->peer));
2439 return; /* already in progress */
2441 if (! n->is_connected)
2445 GNUNET_STATISTICS_update (stats,
2446 gettext_noop ("# Asking transport to connect (for SETKEY)"),
2449 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2451 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2453 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2454 ¬ify_encrypted_transmit_ready,
2460 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2461 "Asked to perform key exchange with `%4s'.\n",
2462 GNUNET_i2s (&n->peer));
2464 if (n->public_key == NULL)
2466 /* lookup n's public key, then try again */
2468 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2469 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2470 GNUNET_i2s (&n->peer));
2472 GNUNET_assert (n->pitr == NULL);
2473 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2477 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2478 &process_hello_retry_send_key, n);
2481 /* first, set key message */
2482 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2483 sizeof (struct SetKeyMessage));
2484 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2485 me->priority = SET_KEY_PRIORITY;
2486 me->size = sizeof (struct SetKeyMessage);
2487 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2491 sm = (struct SetKeyMessage *) &me[1];
2492 sm->header.size = htons (sizeof (struct SetKeyMessage));
2493 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2494 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2495 PEER_STATE_KEY_SENT : n->status));
2497 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2498 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2499 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2500 sizeof (struct GNUNET_PeerIdentity));
2501 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2502 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2503 sm->target = n->peer;
2504 GNUNET_assert (GNUNET_OK ==
2505 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2507 GNUNET_CRYPTO_AesSessionKey),
2509 &sm->encrypted_key));
2510 GNUNET_assert (GNUNET_OK ==
2511 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2514 /* second, encrypted PING message */
2515 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2516 sizeof (struct PingMessage));
2517 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2518 me->priority = PING_PRIORITY;
2519 me->size = sizeof (struct PingMessage);
2520 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2524 pm = (struct PingMessage *) &me[1];
2525 pm->header.size = htons (sizeof (struct PingMessage));
2526 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2527 pp.challenge = htonl (n->ping_challenge);
2528 pp.target = n->peer;
2530 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2531 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u.\n",
2533 (unsigned int) n->ping_challenge,
2534 GNUNET_i2s (&n->peer),
2535 (unsigned int) n->encrypt_key.crc32);
2538 &n->peer.hashPubKey,
2541 sizeof (struct PingMessage) -
2542 sizeof (struct GNUNET_MessageHeader));
2546 case PEER_STATE_DOWN:
2547 n->status = PEER_STATE_KEY_SENT;
2549 case PEER_STATE_KEY_SENT:
2551 case PEER_STATE_KEY_RECEIVED:
2553 case PEER_STATE_KEY_CONFIRMED:
2559 GNUNET_STATISTICS_update (stats,
2560 gettext_noop ("# SETKEY and PING messages created"),
2564 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2565 "Have %llu ms left for `%s' transmission.\n",
2566 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2569 /* trigger queue processing */
2570 process_encrypted_neighbour_queue (n);
2571 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2572 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2573 n->retry_set_key_task
2574 = GNUNET_SCHEDULER_add_delayed (sched,
2575 n->set_key_retry_frequency,
2576 &set_key_retry_task, n);
2581 * We received a SET_KEY message. Validate and update
2582 * our key material and status.
2584 * @param n the neighbour from which we received message m
2585 * @param m the set key message we received
2588 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2592 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2593 * the neighbour's struct and retry handling the set_key message. Or,
2594 * if we did not get a HELLO, just free the set key message.
2596 * @param cls pointer to the set key message
2597 * @param peer the peer for which this is the HELLO
2598 * @param hello HELLO message of that peer
2599 * @param trust amount of trust we currently have in that peer
2602 process_hello_retry_handle_set_key (void *cls,
2603 const struct GNUNET_PeerIdentity *peer,
2604 const struct GNUNET_HELLO_Message *hello,
2607 struct Neighbour *n = cls;
2608 struct SetKeyMessage *sm = n->skm;
2617 if (n->public_key != NULL)
2618 return; /* multiple HELLOs match!? */
2620 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2621 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2623 GNUNET_break_op (0);
2624 GNUNET_free (n->public_key);
2625 n->public_key = NULL;
2629 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2630 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2631 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2633 handle_set_key (n, sm);
2638 * We received a PING message. Validate and transmit
2641 * @param n sender of the PING
2642 * @param m the encrypted PING message itself
2645 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2647 struct PingMessage t;
2648 struct PongMessage tx;
2649 struct PongMessage *tp;
2650 struct MessageEntry *me;
2653 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2654 "Core service receives `%s' request from `%4s'.\n",
2655 "PING", GNUNET_i2s (&n->peer));
2659 &my_identity.hashPubKey,
2662 sizeof (struct PingMessage) -
2663 sizeof (struct GNUNET_MessageHeader)))
2666 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2667 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2669 GNUNET_i2s (&t.target),
2670 (unsigned int) ntohl (t.challenge),
2671 (unsigned int) n->decrypt_key.crc32);
2673 GNUNET_STATISTICS_update (stats,
2674 gettext_noop ("# PING messages decrypted"),
2677 if (0 != memcmp (&t.target,
2678 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2680 GNUNET_break_op (0);
2683 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2684 sizeof (struct PongMessage));
2685 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2689 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2690 me->priority = PONG_PRIORITY;
2691 me->size = sizeof (struct PongMessage);
2692 tx.reserved = htonl (0);
2693 tx.inbound_bw_limit = n->bw_in;
2694 tx.challenge = t.challenge;
2695 tx.target = t.target;
2696 tp = (struct PongMessage *) &me[1];
2697 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2698 tp->header.size = htons (sizeof (struct PongMessage));
2700 &my_identity.hashPubKey,
2703 sizeof (struct PongMessage) -
2704 sizeof (struct GNUNET_MessageHeader));
2705 GNUNET_STATISTICS_update (stats,
2706 gettext_noop ("# PONG messages created"),
2710 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2711 "Encrypting `%s' with challenge %u using key %u\n",
2713 (unsigned int) ntohl (t.challenge),
2714 (unsigned int) n->encrypt_key.crc32);
2716 /* trigger queue processing */
2717 process_encrypted_neighbour_queue (n);
2722 * We received a PONG message. Validate and update our status.
2724 * @param n sender of the PONG
2725 * @param m the encrypted PONG message itself
2728 handle_pong (struct Neighbour *n,
2729 const struct PongMessage *m)
2731 struct PongMessage t;
2732 struct ConnectNotifyMessage cnm;
2735 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2736 "Core service receives `%s' request from `%4s'.\n",
2737 "PONG", GNUNET_i2s (&n->peer));
2741 &n->peer.hashPubKey,
2744 sizeof (struct PongMessage) -
2745 sizeof (struct GNUNET_MessageHeader)))
2747 GNUNET_break_op (0);
2750 GNUNET_STATISTICS_update (stats,
2751 gettext_noop ("# PONG messages decrypted"),
2754 if (0 != ntohl (t.reserved))
2756 GNUNET_break_op (0);
2760 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2761 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2763 GNUNET_i2s (&t.target),
2764 (unsigned int) ntohl (t.challenge),
2765 (unsigned int) n->decrypt_key.crc32);
2767 if ((0 != memcmp (&t.target,
2769 sizeof (struct GNUNET_PeerIdentity))) ||
2770 (n->ping_challenge != ntohl (t.challenge)))
2772 /* PONG malformed */
2774 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2775 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2777 GNUNET_i2s (&n->peer),
2778 (unsigned int) n->ping_challenge);
2779 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2780 "Received malformed `%s' received from `%4s' with challenge %u\n",
2781 "PONG", GNUNET_i2s (&t.target),
2782 (unsigned int) ntohl (t.challenge));
2784 GNUNET_break_op (0);
2789 case PEER_STATE_DOWN:
2790 GNUNET_break (0); /* should be impossible */
2792 case PEER_STATE_KEY_SENT:
2793 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2795 case PEER_STATE_KEY_RECEIVED:
2796 GNUNET_STATISTICS_update (stats,
2797 gettext_noop ("# Session keys confirmed via PONG"),
2800 n->status = PEER_STATE_KEY_CONFIRMED;
2801 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2803 n->bw_out_external_limit = t.inbound_bw_limit;
2804 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2805 n->bw_out_internal_limit);
2806 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2808 GNUNET_TRANSPORT_set_quota (transport,
2812 GNUNET_TIME_UNIT_FOREVER_REL,
2816 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2817 "Confirmed key via `%s' message for peer `%4s'\n",
2818 "PONG", GNUNET_i2s (&n->peer));
2820 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2822 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2823 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2825 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2826 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2827 cnm.distance = htonl (n->last_distance);
2828 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2830 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2831 process_encrypted_neighbour_queue (n);
2833 case PEER_STATE_KEY_CONFIRMED:
2834 n->last_activity = GNUNET_TIME_absolute_get ();
2835 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2836 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2838 = GNUNET_SCHEDULER_add_delayed (sched,
2839 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2851 * We received a SET_KEY message. Validate and update
2852 * our key material and status.
2854 * @param n the neighbour from which we received message m
2855 * @param m the set key message we received
2858 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2860 struct SetKeyMessage *m_cpy;
2861 struct GNUNET_TIME_Absolute t;
2862 struct GNUNET_CRYPTO_AesSessionKey k;
2863 struct PingMessage *ping;
2864 struct PongMessage *pong;
2865 enum PeerStateMachine sender_status;
2868 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2869 "Core service receives `%s' request from `%4s'.\n",
2870 "SET_KEY", GNUNET_i2s (&n->peer));
2872 if (n->public_key == NULL)
2874 if (n->pitr != NULL)
2877 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2878 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2884 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2885 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2887 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2888 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2889 /* lookup n's public key, then try again */
2890 GNUNET_assert (n->skm == NULL);
2892 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2896 GNUNET_TIME_UNIT_MINUTES,
2897 &process_hello_retry_handle_set_key, n);
2898 GNUNET_STATISTICS_update (stats,
2899 gettext_noop ("# SETKEY messages deferred (need public key)"),
2904 if (0 != memcmp (&m->target,
2906 sizeof (struct GNUNET_PeerIdentity)))
2908 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2909 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
2911 GNUNET_i2s (&m->target));
2914 if ((ntohl (m->purpose.size) !=
2915 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2916 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2917 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2918 sizeof (struct GNUNET_PeerIdentity)) ||
2920 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2921 &m->purpose, &m->signature, n->public_key)))
2923 /* invalid signature */
2924 GNUNET_break_op (0);
2927 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2928 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2929 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2930 (t.value < n->decrypt_key_created.value))
2932 /* this could rarely happen due to massive re-ordering of
2933 messages on the network level, but is most likely either
2934 a bug or some adversary messing with us. Report. */
2935 GNUNET_break_op (0);
2939 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2940 "Decrypting key material.\n");
2942 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2945 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2946 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2947 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2949 /* failed to decrypt !? */
2950 GNUNET_break_op (0);
2953 GNUNET_STATISTICS_update (stats,
2954 gettext_noop ("# SETKEY messages decrypted"),
2958 if (n->decrypt_key_created.value != t.value)
2960 /* fresh key, reset sequence numbers */
2961 n->last_sequence_number_received = 0;
2962 n->last_packets_bitmap = 0;
2963 n->decrypt_key_created = t;
2965 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2968 case PEER_STATE_DOWN:
2969 n->status = PEER_STATE_KEY_RECEIVED;
2971 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2972 "Responding to `%s' with my own key.\n", "SET_KEY");
2976 case PEER_STATE_KEY_SENT:
2977 case PEER_STATE_KEY_RECEIVED:
2978 n->status = PEER_STATE_KEY_RECEIVED;
2979 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2980 (sender_status != PEER_STATE_KEY_CONFIRMED))
2983 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2984 "Responding to `%s' with my own key (other peer has status %u).\n",
2986 (unsigned int) sender_status);
2991 case PEER_STATE_KEY_CONFIRMED:
2992 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2993 (sender_status != PEER_STATE_KEY_CONFIRMED))
2996 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2997 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2999 (unsigned int) sender_status);
3008 if (n->pending_ping != NULL)
3010 ping = n->pending_ping;
3011 n->pending_ping = NULL;
3012 handle_ping (n, ping);
3015 if (n->pending_pong != NULL)
3017 pong = n->pending_pong;
3018 n->pending_pong = NULL;
3019 handle_pong (n, pong);
3026 * Send a P2P message to a client.
3028 * @param sender who sent us the message?
3029 * @param client who should we give the message to?
3030 * @param m contains the message to transmit
3031 * @param msize number of bytes in buf to transmit
3034 send_p2p_message_to_client (struct Neighbour *sender,
3035 struct Client *client,
3036 const void *m, size_t msize)
3038 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3039 struct NotifyTrafficMessage *ntm;
3042 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3043 "Core service passes message from `%4s' of type %u to client.\n",
3044 GNUNET_i2s(&sender->peer),
3045 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3047 ntm = (struct NotifyTrafficMessage *) buf;
3048 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3049 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3050 ntm->distance = htonl (sender->last_distance);
3051 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3052 ntm->peer = sender->peer;
3053 memcpy (&ntm[1], m, msize);
3054 send_to_client (client, &ntm->header, GNUNET_YES);
3059 * Deliver P2P message to interested clients.
3061 * @param sender who sent us the message?
3062 * @param m the message
3063 * @param msize size of the message (including header)
3066 deliver_message (struct Neighbour *sender,
3067 const struct GNUNET_MessageHeader *m, size_t msize)
3070 struct Client *cpos;
3076 type = ntohs (m->type);
3078 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3079 "Received encapsulated message of type %u from `%4s'\n",
3080 (unsigned int) type,
3081 GNUNET_i2s (&sender->peer));
3083 GNUNET_snprintf (buf,
3085 gettext_noop ("# bytes of messages of type %u received"),
3086 (unsigned int) type);
3087 GNUNET_STATISTICS_set (stats,
3091 dropped = GNUNET_YES;
3093 while (cpos != NULL)
3095 deliver_full = GNUNET_NO;
3096 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3097 deliver_full = GNUNET_YES;
3100 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3102 if (type != cpos->types[tpos])
3104 deliver_full = GNUNET_YES;
3108 if (GNUNET_YES == deliver_full)
3110 send_p2p_message_to_client (sender, cpos, m, msize);
3111 dropped = GNUNET_NO;
3113 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3115 send_p2p_message_to_client (sender, cpos, m,
3116 sizeof (struct GNUNET_MessageHeader));
3120 if (dropped == GNUNET_YES)
3123 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3124 "Message of type %u from `%4s' not delivered to any client.\n",
3125 (unsigned int) type,
3126 GNUNET_i2s (&sender->peer));
3128 /* FIXME: stats... */
3134 * Align P2P message and then deliver to interested clients.
3136 * @param sender who sent us the message?
3137 * @param buffer unaligned (!) buffer containing message
3138 * @param msize size of the message (including header)
3141 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
3145 /* TODO: call to statistics? */
3146 memcpy (abuf, buffer, msize);
3147 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
3152 * Deliver P2P messages to interested clients.
3154 * @param sender who sent us the message?
3155 * @param buffer buffer containing messages, can be modified
3156 * @param buffer_size size of the buffer (overall)
3157 * @param offset offset where messages in the buffer start
3160 deliver_messages (struct Neighbour *sender,
3161 const char *buffer, size_t buffer_size, size_t offset)
3163 struct GNUNET_MessageHeader *mhp;
3164 struct GNUNET_MessageHeader mh;
3168 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
3170 if (0 != offset % sizeof (uint16_t))
3172 /* outch, need to copy to access header */
3173 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
3178 /* can access header directly */
3179 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
3181 msize = ntohs (mhp->size);
3182 if (msize + offset > buffer_size)
3184 /* malformed message, header says it is larger than what
3185 would fit into the overall buffer */
3186 GNUNET_break_op (0);
3189 #if HAVE_UNALIGNED_64_ACCESS
3190 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
3192 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
3194 if (GNUNET_YES == need_align)
3195 align_and_deliver (sender, &buffer[offset], msize);
3197 deliver_message (sender,
3198 (const struct GNUNET_MessageHeader *)
3199 &buffer[offset], msize);
3206 * We received an encrypted message. Decrypt, validate and
3207 * pass on to the appropriate clients.
3210 handle_encrypted_message (struct Neighbour *n,
3211 const struct EncryptedMessage *m)
3213 size_t size = ntohs (m->header.size);
3215 struct EncryptedMessage *pt; /* plaintext */
3218 struct GNUNET_TIME_Absolute t;
3222 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3223 "Core service receives `%s' request from `%4s'.\n",
3224 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3226 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3232 &buf[ENCRYPTED_HEADER_SIZE],
3233 size - ENCRYPTED_HEADER_SIZE))
3235 pt = (struct EncryptedMessage *) buf;
3237 GNUNET_CRYPTO_hash (&pt->sequence_number,
3238 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3240 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3241 "V-Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
3242 (unsigned int) (size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode)),
3246 if (0 != memcmp (&ph,
3247 &pt->plaintext_hash,
3248 sizeof (GNUNET_HashCode)))
3250 /* checksum failed */
3251 GNUNET_break_op (0);
3255 /* validate sequence number */
3256 snum = ntohl (pt->sequence_number);
3257 if (n->last_sequence_number_received == snum)
3259 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3260 "Received duplicate message, ignoring.\n");
3261 /* duplicate, ignore */
3262 GNUNET_STATISTICS_set (stats,
3263 gettext_noop ("# bytes dropped (duplicates)"),
3268 if ((n->last_sequence_number_received > snum) &&
3269 (n->last_sequence_number_received - snum > 32))
3271 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3272 "Received ancient out of sequence message, ignoring.\n");
3273 /* ancient out of sequence, ignore */
3274 GNUNET_STATISTICS_set (stats,
3275 gettext_noop ("# bytes dropped (out of sequence)"),
3280 if (n->last_sequence_number_received > snum)
3282 unsigned int rotbit =
3283 1 << (n->last_sequence_number_received - snum - 1);
3284 if ((n->last_packets_bitmap & rotbit) != 0)
3286 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3287 "Received duplicate message, ignoring.\n");
3288 GNUNET_STATISTICS_set (stats,
3289 gettext_noop ("# bytes dropped (duplicates)"),
3292 /* duplicate, ignore */
3295 n->last_packets_bitmap |= rotbit;
3297 if (n->last_sequence_number_received < snum)
3299 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3300 n->last_sequence_number_received = snum;
3303 /* check timestamp */
3304 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3305 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3307 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3309 ("Message received far too old (%llu ms). Content ignored.\n"),
3310 GNUNET_TIME_absolute_get_duration (t).value);
3311 GNUNET_STATISTICS_set (stats,
3312 gettext_noop ("# bytes dropped (ancient message)"),
3318 /* process decrypted message(s) */
3319 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3321 #if DEBUG_CORE_SET_QUOTA
3322 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3323 "Received %u b/s as new inbound limit for peer `%4s'\n",
3324 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3325 GNUNET_i2s (&n->peer));
3327 n->bw_out_external_limit = pt->inbound_bw_limit;
3328 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3329 n->bw_out_internal_limit);
3330 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3332 GNUNET_TRANSPORT_set_quota (transport,
3336 GNUNET_TIME_UNIT_FOREVER_REL,
3339 n->last_activity = GNUNET_TIME_absolute_get ();
3340 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3341 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3343 = GNUNET_SCHEDULER_add_delayed (sched,
3344 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3347 GNUNET_STATISTICS_set (stats,
3348 gettext_noop ("# bytes of payload decrypted"),
3349 size - sizeof (struct EncryptedMessage),
3351 deliver_messages (n, buf, size, sizeof (struct EncryptedMessage));
3356 * Function called by the transport for each received message.
3358 * @param cls closure
3359 * @param peer (claimed) identity of the other peer
3360 * @param message the message
3361 * @param latency estimated latency for communicating with the
3362 * given peer (round-trip)
3363 * @param distance in overlay hops, as given by transport plugin
3366 handle_transport_receive (void *cls,
3367 const struct GNUNET_PeerIdentity *peer,
3368 const struct GNUNET_MessageHeader *message,
3369 struct GNUNET_TIME_Relative latency,
3370 unsigned int distance)
3372 struct Neighbour *n;
3373 struct GNUNET_TIME_Absolute now;
3379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3380 "Received message of type %u from `%4s', demultiplexing.\n",
3381 (unsigned int) ntohs (message->type),
3384 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3389 n = find_neighbour (peer);
3391 n = create_neighbour (peer);
3392 n->last_latency = latency;
3393 n->last_distance = distance;
3394 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3395 type = ntohs (message->type);
3396 size = ntohs (message->size);
3398 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3399 "Received message of type %u from `%4s'\n",
3400 (unsigned int) type,
3405 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3406 if (size != sizeof (struct SetKeyMessage))
3408 GNUNET_break_op (0);
3411 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3412 handle_set_key (n, (const struct SetKeyMessage *) message);
3414 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3415 if (size < sizeof (struct EncryptedMessage) +
3416 sizeof (struct GNUNET_MessageHeader))
3418 GNUNET_break_op (0);
3421 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3422 (n->status != PEER_STATE_KEY_CONFIRMED))
3424 GNUNET_break_op (0);
3425 /* blacklist briefly (?); might help recover (?) */
3426 GNUNET_TRANSPORT_blacklist (sched, cfg,
3428 GNUNET_TIME_UNIT_SECONDS,
3429 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3434 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3436 case GNUNET_MESSAGE_TYPE_CORE_PING:
3437 if (size != sizeof (struct PingMessage))
3439 GNUNET_break_op (0);
3442 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3443 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3444 (n->status != PEER_STATE_KEY_CONFIRMED))
3447 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3448 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3449 "PING", GNUNET_i2s (&n->peer));
3451 GNUNET_free_non_null (n->pending_ping);
3452 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3453 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3456 handle_ping (n, (const struct PingMessage *) message);
3458 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3459 if (size != sizeof (struct PongMessage))
3461 GNUNET_break_op (0);
3464 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3465 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3466 (n->status != PEER_STATE_KEY_CONFIRMED) )
3469 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3470 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3471 "PONG", GNUNET_i2s (&n->peer));
3473 GNUNET_free_non_null (n->pending_pong);
3474 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3475 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3478 handle_pong (n, (const struct PongMessage *) message);
3481 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3482 _("Unsupported message of type %u received.\n"),
3483 (unsigned int) type);
3486 if (n->status == PEER_STATE_KEY_CONFIRMED)
3488 now = GNUNET_TIME_absolute_get ();
3489 n->last_activity = now;
3492 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3493 n->time_established = now;
3495 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3496 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3498 = GNUNET_SCHEDULER_add_delayed (sched,
3499 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3507 * Function that recalculates the bandwidth quota for the
3508 * given neighbour and transmits it to the transport service.
3510 * @param cls neighbour for the quota update
3514 neighbour_quota_update (void *cls,
3515 const struct GNUNET_SCHEDULER_TaskContext *tc)
3517 struct Neighbour *n = cls;
3518 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3521 unsigned long long distributable;
3522 uint64_t need_per_peer;
3523 uint64_t need_per_second;
3525 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3526 /* calculate relative preference among all neighbours;
3527 divides by a bit more to avoid division by zero AND to
3528 account for possibility of new neighbours joining any time
3529 AND to convert to double... */
3530 if (preference_sum == 0)
3532 pref_rel = 1.0 / (double) neighbour_count;
3536 pref_rel = n->current_preference / preference_sum;
3538 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3539 GNUNET_TIME_UNIT_SECONDS);
3540 need_per_second = need_per_peer * neighbour_count;
3542 if (bandwidth_target_out_bps > need_per_second)
3543 distributable = bandwidth_target_out_bps - need_per_second;
3544 share = distributable * pref_rel;
3545 if (share + need_per_peer > ( (uint32_t)-1))
3546 q_in = GNUNET_BANDWIDTH_value_init ((uint32_t) -1);
3548 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3549 /* check if we want to disconnect for good due to inactivity */
3550 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3551 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3555 "Forcing disconnect of `%4s' due to inactivity\n",
3556 GNUNET_i2s (&n->peer));
3558 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3560 #if DEBUG_CORE_QUOTA
3561 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3562 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3563 GNUNET_i2s (&n->peer),
3564 (unsigned int) ntohl (q_in.value__),
3565 bandwidth_target_out_bps,
3566 (unsigned int) ntohl (n->bw_in.value__),
3567 (unsigned int) ntohl (n->bw_out.value__),
3568 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3570 if (n->bw_in.value__ != q_in.value__)
3573 if (GNUNET_YES == n->is_connected)
3574 GNUNET_TRANSPORT_set_quota (transport,
3578 GNUNET_TIME_UNIT_FOREVER_REL,
3581 schedule_quota_update (n);
3586 * Function called by transport to notify us that
3587 * a peer connected to us (on the network level).
3589 * @param cls closure
3590 * @param peer the peer that connected
3591 * @param latency current latency of the connection
3592 * @param distance in overlay hops, as given by transport plugin
3595 handle_transport_notify_connect (void *cls,
3596 const struct GNUNET_PeerIdentity *peer,
3597 struct GNUNET_TIME_Relative latency,
3598 unsigned int distance)
3600 struct Neighbour *n;
3601 struct ConnectNotifyMessage cnm;
3603 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3608 n = find_neighbour (peer);
3611 if (GNUNET_YES == n->is_connected)
3613 /* duplicate connect notification!? */
3620 n = create_neighbour (peer);
3622 GNUNET_STATISTICS_update (stats,
3623 gettext_noop ("# peers connected"),
3626 n->is_connected = GNUNET_YES;
3627 n->last_latency = latency;
3628 n->last_distance = distance;
3629 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3632 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3636 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3637 "Received connection from `%4s'.\n",
3638 GNUNET_i2s (&n->peer));
3640 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3641 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3642 cnm.distance = htonl (n->last_distance);
3643 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3645 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3646 GNUNET_TRANSPORT_set_quota (transport,
3650 GNUNET_TIME_UNIT_FOREVER_REL,
3657 * Function called by transport telling us that a peer
3660 * @param cls closure
3661 * @param peer the peer that disconnected
3664 handle_transport_notify_disconnect (void *cls,
3665 const struct GNUNET_PeerIdentity *peer)
3667 struct DisconnectNotifyMessage cnm;
3668 struct Neighbour *n;
3671 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3672 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3674 n = find_neighbour (peer);
3680 GNUNET_break (n->is_connected);
3681 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3682 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3684 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3685 n->is_connected = GNUNET_NO;
3686 GNUNET_STATISTICS_update (stats,
3687 gettext_noop ("# peers connected"),
3694 * Last task run during shutdown. Disconnects us from
3698 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3700 struct Neighbour *n;
3704 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3705 "Core service shutting down.\n");
3707 GNUNET_assert (transport != NULL);
3708 GNUNET_TRANSPORT_disconnect (transport);
3710 while (NULL != (n = neighbours))
3712 neighbours = n->next;
3713 GNUNET_assert (neighbour_count > 0);
3717 GNUNET_STATISTICS_set (stats, gettext_noop ("# active neighbours"), neighbour_count, GNUNET_NO);
3718 GNUNET_SERVER_notification_context_destroy (notifier);
3720 while (NULL != (c = clients))
3721 handle_client_disconnect (NULL, c->client_handle);
3722 if (my_private_key != NULL)
3723 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3725 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3730 * Initiate core service.
3732 * @param cls closure
3733 * @param s scheduler to use
3734 * @param serv the initialized server
3735 * @param c configuration to use
3739 struct GNUNET_SCHEDULER_Handle *s,
3740 struct GNUNET_SERVER_Handle *serv,
3741 const struct GNUNET_CONFIGURATION_Handle *c)
3747 /* parse configuration */
3750 GNUNET_CONFIGURATION_get_value_number (c,
3753 &bandwidth_target_in_bps)) ||
3755 GNUNET_CONFIGURATION_get_value_number (c,
3758 &bandwidth_target_out_bps)) ||
3760 GNUNET_CONFIGURATION_get_value_filename (c,
3762 "HOSTKEY", &keyfile)))
3764 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3766 ("Core service is lacking key configuration settings. Exiting.\n"));
3767 GNUNET_SCHEDULER_shutdown (s);
3770 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3771 GNUNET_free (keyfile);
3772 if (my_private_key == NULL)
3774 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3775 _("Core service could not access hostkey. Exiting.\n"));
3776 GNUNET_SCHEDULER_shutdown (s);
3779 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3780 GNUNET_CRYPTO_hash (&my_public_key,
3781 sizeof (my_public_key), &my_identity.hashPubKey);
3782 /* setup notification */
3784 notifier = GNUNET_SERVER_notification_context_create (server,
3786 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3787 /* setup transport connection */
3788 transport = GNUNET_TRANSPORT_connect (sched,
3791 &handle_transport_receive,
3792 &handle_transport_notify_connect,
3793 &handle_transport_notify_disconnect);
3794 GNUNET_assert (NULL != transport);
3795 stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3796 GNUNET_SCHEDULER_add_delayed (sched,
3797 GNUNET_TIME_UNIT_FOREVER_REL,
3798 &cleaning_task, NULL);
3799 /* process client requests */
3800 GNUNET_SERVER_add_handlers (server, handlers);
3801 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3802 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3808 * The main function for the transport service.
3810 * @param argc number of arguments from the command line
3811 * @param argv command line arguments
3812 * @return 0 ok, 1 on error
3815 main (int argc, char *const *argv)
3817 return (GNUNET_OK ==
3818 GNUNET_SERVICE_run (argc,
3821 GNUNET_SERVICE_OPTION_NONE,
3822 &run, NULL)) ? 0 : 1;
3825 /* end of gnunet-service-core.c */