2 This file is part of GNUnet.
3 (C) 2009 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file core/gnunet-service-core.c
23 * @brief high-level P2P messaging
24 * @author Christian Grothoff
26 * Considerations for later:
27 * - check that hostkey used by transport (for HELLOs) is the
28 * same as the hostkey that we are using!
29 * - add code to send PINGs if we are about to time-out otherwise
30 * - optimize lookup (many O(n) list traversals
31 * could ideally be changed to O(1) hash map lookups)
34 #include "gnunet_constants.h"
35 #include "gnunet_util_lib.h"
36 #include "gnunet_hello_lib.h"
37 #include "gnunet_peerinfo_service.h"
38 #include "gnunet_protocols.h"
39 #include "gnunet_signatures.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet_transport_service.h"
45 #define DEBUG_HANDSHAKE GNUNET_NO
47 #define DEBUG_CORE_QUOTA GNUNET_NO
50 * Receive and send buffer windows grow over time. For
51 * how long can 'unused' bandwidth accumulate before we
52 * need to cap it? (specified in seconds).
54 #define MAX_WINDOW_TIME_S (5 * 60)
57 * How many messages do we queue up at most for optional
58 * notifications to a client? (this can cause notifications
59 * about outgoing messages to be dropped).
61 #define MAX_NOTIFY_QUEUE 16
64 * Minimum bandwidth (out) to assign to any connected peer.
65 * Should be rather low; values larger than DEFAULT_BW_IN_OUT make no
68 #define MIN_BANDWIDTH_PER_PEER GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT
71 * After how much time past the "official" expiration time do
72 * we discard messages? Should not be zero since we may
73 * intentionally defer transmission until close to the deadline
74 * and then may be slightly past the deadline due to inaccuracy
75 * in sleep and our own CPU consumption.
77 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
80 * How long do we delay messages to get larger packet sizes (CORKing)?
82 #define MAX_CORK_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
85 * What is the maximum delay for a SET_KEY message?
87 #define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
90 * What how long do we wait for SET_KEY confirmation initially?
92 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 3)
95 * What is the maximum delay for a PING message?
97 #define MAX_PING_DELAY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 2)
100 * What is the maximum delay for a PONG message?
102 #define MAX_PONG_DELAY GNUNET_TIME_relative_multiply (MAX_PING_DELAY, 2)
105 * What is the minimum frequency for a PING message?
107 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
110 * How often do we recalculate bandwidth quotas?
112 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
115 * What is the priority for a SET_KEY message?
117 #define SET_KEY_PRIORITY 0xFFFFFF
120 * What is the priority for a PING message?
122 #define PING_PRIORITY 0xFFFFFF
125 * What is the priority for a PONG message?
127 #define PONG_PRIORITY 0xFFFFFF
130 * How many messages do we queue per peer at most? Must be at
133 #define MAX_PEER_QUEUE_SIZE 16
136 * How many non-mandatory messages do we queue per client at most?
138 #define MAX_CLIENT_QUEUE_SIZE 32
141 * What is the maximum age of a message for us to consider
142 * processing it? Note that this looks at the timestamp used
143 * by the other peer, so clock skew between machines does
144 * come into play here. So this should be picked high enough
145 * so that a little bit of clock skew does not prevent peers
146 * from connecting to us.
148 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
151 * What is the maximum size for encrypted messages? Note that this
152 * number imposes a clear limit on the maximum size of any message.
153 * Set to a value close to 64k but not so close that transports will
154 * have trouble with their headers.
156 #define MAX_ENCRYPTED_MESSAGE_SIZE (63 * 1024)
160 * State machine for our P2P encryption handshake. Everyone starts in
161 * "DOWN", if we receive the other peer's key (other peer initiated)
162 * we start in state RECEIVED (since we will immediately send our
163 * own); otherwise we start in SENT. If we get back a PONG from
164 * within either state, we move up to CONFIRMED (the PONG will always
165 * be sent back encrypted with the key we sent to the other peer).
167 enum PeerStateMachine
171 PEER_STATE_KEY_RECEIVED,
172 PEER_STATE_KEY_CONFIRMED
177 * Number of bytes (at the beginning) of "struct EncryptedMessage"
178 * that are NOT encrypted.
180 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t))
184 * Encapsulation for encrypted messages exchanged between
185 * peers. Followed by the actual encrypted data.
187 struct EncryptedMessage
190 * Message type is either CORE_ENCRYPTED_MESSAGE.
192 struct GNUNET_MessageHeader header;
195 * Random value used for IV generation. ENCRYPTED_HEADER_SIZE must
196 * be set to the offset of the *next* field.
198 uint32_t iv_seed GNUNET_PACKED;
201 * Hash of the plaintext (starting at 'sequence_number'), used to
202 * verify message integrity. Everything after this hash (including
203 * this hash itself) will be encrypted.
205 GNUNET_HashCode plaintext_hash;
208 * Sequence number, in network byte order. This field
209 * must be the first encrypted/decrypted field and the
210 * first byte that is hashed for the plaintext hash.
212 uint32_t sequence_number GNUNET_PACKED;
215 * Desired bandwidth (how much we should send to this peer / how
216 * much is the sender willing to receive)?
218 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
221 * Timestamp. Used to prevent reply of ancient messages
222 * (recent messages are caught with the sequence number).
224 struct GNUNET_TIME_AbsoluteNBO timestamp;
230 * We're sending an (encrypted) PING to the other peer to check if he
231 * can decrypt. The other peer should respond with a PONG with the
232 * same content, except this time encrypted with the receiver's key.
237 * Message type is CORE_PING.
239 struct GNUNET_MessageHeader header;
242 * Random number chosen to make reply harder.
244 uint32_t challenge GNUNET_PACKED;
247 * Intended target of the PING, used primarily to check
248 * that decryption actually worked.
250 struct GNUNET_PeerIdentity target;
256 * Response to a PING. Includes data from the original PING
257 * plus initial bandwidth quota information.
262 * Message type is CORE_PONG.
264 struct GNUNET_MessageHeader header;
267 * Random number proochosen to make reply harder. Must be
268 * first field after header (this is where we start to encrypt!).
270 uint32_t challenge GNUNET_PACKED;
275 uint32_t reserved GNUNET_PACKED;
278 * Desired bandwidth (how much we should send to this
279 * peer / how much is the sender willing to receive).
281 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
284 * Intended target of the PING, used primarily to check
285 * that decryption actually worked.
287 struct GNUNET_PeerIdentity target;
292 * Message transmitted to set (or update) a session key.
298 * Message type is either CORE_SET_KEY.
300 struct GNUNET_MessageHeader header;
303 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
305 int32_t sender_status GNUNET_PACKED;
308 * Purpose of the signature, will be
309 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
311 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
314 * At what time was this key created?
316 struct GNUNET_TIME_AbsoluteNBO creation_time;
319 * The encrypted session key.
321 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
324 * Who is the intended recipient?
326 struct GNUNET_PeerIdentity target;
329 * Signature of the stuff above (starting at purpose).
331 struct GNUNET_CRYPTO_RsaSignature signature;
337 * Message waiting for transmission. This struct
338 * is followed by the actual content of the message.
344 * We keep messages in a doubly linked list.
346 struct MessageEntry *next;
349 * We keep messages in a doubly linked list.
351 struct MessageEntry *prev;
354 * By when are we supposed to transmit this message?
356 struct GNUNET_TIME_Absolute deadline;
359 * By when are we supposed to transmit this message (after
362 struct GNUNET_TIME_Absolute slack_deadline;
365 * How important is this message to us?
367 unsigned int priority;
370 * How long is the message? (number of bytes following
371 * the "struct MessageEntry", but not including the
372 * size of "struct MessageEntry" itself!)
377 * Was this message selected for transmission in the
378 * current round? GNUNET_YES or GNUNET_NO.
383 * Did we give this message some slack (delayed sending) previously
384 * (and hence should not give it any more slack)? GNUNET_YES or
395 * We keep neighbours in a linked list (for now).
397 struct Neighbour *next;
400 * Unencrypted messages destined for this peer.
402 struct MessageEntry *messages;
405 * Head of the batched, encrypted message queue (already ordered,
406 * transmit starting with the head).
408 struct MessageEntry *encrypted_head;
411 * Tail of the batched, encrypted message queue (already ordered,
412 * append new messages to tail)
414 struct MessageEntry *encrypted_tail;
417 * Handle for pending requests for transmission to this peer
418 * with the transport service. NULL if no request is pending.
420 struct GNUNET_TRANSPORT_TransmitHandle *th;
423 * Public key of the neighbour, NULL if we don't have it yet.
425 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
428 * We received a PING message before we got the "public_key"
429 * (or the SET_KEY). We keep it here until we have a key
430 * to decrypt it. NULL if no PING is pending.
432 struct PingMessage *pending_ping;
435 * We received a PONG message before we got the "public_key"
436 * (or the SET_KEY). We keep it here until we have a key
437 * to decrypt it. NULL if no PONG is pending.
439 struct PongMessage *pending_pong;
442 * Non-NULL if we are currently looking up HELLOs for this peer.
445 struct GNUNET_PEERINFO_IteratorContext *pitr;
448 * SetKeyMessage to transmit, NULL if we are not currently trying
451 struct SetKeyMessage *skm;
454 * Identity of the neighbour.
456 struct GNUNET_PeerIdentity peer;
459 * Key we use to encrypt our messages for the other peer
460 * (initialized by us when we do the handshake).
462 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
465 * Key we use to decrypt messages from the other peer
466 * (given to us by the other peer during the handshake).
468 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
471 * ID of task used for re-trying plaintext scheduling.
473 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
476 * ID of task used for re-trying SET_KEY and PING message.
478 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
481 * ID of task used for updating bandwidth quota for this neighbour.
483 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
486 * ID of task used for sending keep-alive pings.
488 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
491 * ID of task used for cleaning up dead neighbour entries.
493 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
496 * At what time did we generate our encryption key?
498 struct GNUNET_TIME_Absolute encrypt_key_created;
501 * At what time did the other peer generate the decryption key?
503 struct GNUNET_TIME_Absolute decrypt_key_created;
506 * At what time did we initially establish (as in, complete session
507 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
509 struct GNUNET_TIME_Absolute time_established;
512 * At what time did we last receive an encrypted message from the
513 * other peer? Should be zero if status != KEY_CONFIRMED.
515 struct GNUNET_TIME_Absolute last_activity;
518 * Last latency observed from this peer.
520 struct GNUNET_TIME_Relative last_latency;
523 * At what frequency are we currently re-trying SET_KEY messages?
525 struct GNUNET_TIME_Relative set_key_retry_frequency;
528 * Tracking bandwidth for sending to this peer.
530 struct GNUNET_BANDWIDTH_Tracker available_send_window;
533 * Tracking bandwidth for receiving from this peer.
535 struct GNUNET_BANDWIDTH_Tracker available_recv_window;
538 * How valueable were the messages of this peer recently?
540 unsigned long long current_preference;
543 * Bit map indicating which of the 32 sequence numbers before the last
544 * were received (good for accepting out-of-order packets and
545 * estimating reliability of the connection)
547 unsigned int last_packets_bitmap;
550 * last sequence number received on this connection (highest)
552 uint32_t last_sequence_number_received;
555 * last sequence number transmitted
557 uint32_t last_sequence_number_sent;
560 * Available bandwidth in for this peer (current target).
562 struct GNUNET_BANDWIDTH_Value32NBO bw_in;
565 * Available bandwidth out for this peer (current target).
567 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
570 * Internal bandwidth limit set for this peer (initially typically
571 * set to "-1"). Actual "bw_out" is MIN of
572 * "bpm_out_internal_limit" and "bw_out_external_limit".
574 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
577 * External bandwidth limit set for this peer by the
578 * peer that we are communicating with. "bw_out" is MIN of
579 * "bw_out_internal_limit" and "bw_out_external_limit".
581 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
584 * What was our PING challenge number (for this peer)?
586 uint32_t ping_challenge;
589 * What was the last distance to this peer as reported by the transports?
591 uint32_t last_distance;
594 * What is our connection status?
596 enum PeerStateMachine status;
599 * Are we currently connected to this neighbour?
607 * Data structure for each client connected to the core service.
612 * Clients are kept in a linked list.
617 * Handle for the client with the server API.
619 struct GNUNET_SERVER_Client *client_handle;
622 * Array of the types of messages this peer cares
623 * about (with "tcnt" entries). Allocated as part
624 * of this client struct, do not free!
626 const uint16_t *types;
629 * Options for messages this client cares about,
630 * see GNUNET_CORE_OPTION_ values.
635 * Number of types of incoming messages this client
636 * specifically cares about. Size of the "types" array.
646 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
651 static struct GNUNET_PeerIdentity my_identity;
656 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
661 struct GNUNET_SCHEDULER_Handle *sched;
666 const struct GNUNET_CONFIGURATION_Handle *cfg;
671 static struct GNUNET_SERVER_Handle *server;
676 static struct GNUNET_TRANSPORT_Handle *transport;
679 * Linked list of our clients.
681 static struct Client *clients;
684 * Context for notifications we need to send to our clients.
686 static struct GNUNET_SERVER_NotificationContext *notifier;
689 * We keep neighbours in a linked list (for now).
691 static struct Neighbour *neighbours;
694 * For creating statistics.
696 static struct GNUNET_STATISTICS_Handle *stats;
699 * Sum of all preferences among all neighbours.
701 static unsigned long long preference_sum;
704 * Total number of neighbours we have.
706 static unsigned int neighbour_count;
709 * How much inbound bandwidth are we supposed to be using per second?
710 * FIXME: this value is not used!
712 static unsigned long long bandwidth_target_in_bps;
715 * How much outbound bandwidth are we supposed to be using per second?
717 static unsigned long long bandwidth_target_out_bps;
722 * A preference value for a neighbour was update. Update
723 * the preference sum accordingly.
725 * @param inc how much was a preference value increased?
728 update_preference_sum (unsigned long long inc)
731 unsigned long long os;
734 preference_sum += inc;
735 if (preference_sum >= os)
737 /* overflow! compensate by cutting all values in half! */
742 n->current_preference /= 2;
743 preference_sum += n->current_preference;
746 GNUNET_STATISTICS_set (stats, gettext_noop ("# total peer preference"), preference_sum, GNUNET_NO);
751 * Find the entry for the given neighbour.
753 * @param peer identity of the neighbour
754 * @return NULL if we are not connected, otherwise the
757 static struct Neighbour *
758 find_neighbour (const struct GNUNET_PeerIdentity *peer)
760 struct Neighbour *ret;
763 while ((ret != NULL) &&
764 (0 != memcmp (&ret->peer,
765 peer, sizeof (struct GNUNET_PeerIdentity))))
772 * Send a message to one of our clients.
774 * @param client target for the message
775 * @param msg message to transmit
776 * @param can_drop could this message be dropped if the
777 * client's queue is getting too large?
780 send_to_client (struct Client *client,
781 const struct GNUNET_MessageHeader *msg,
784 #if DEBUG_CORE_CLIENT
785 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
786 "Preparing to send message of type %u to client.\n",
789 GNUNET_SERVER_notification_context_unicast (notifier,
790 client->client_handle,
797 * Send a message to all of our current clients that have
798 * the right options set.
800 * @param msg message to multicast
801 * @param can_drop can this message be discarded if the queue is too long
802 * @param options mask to use
805 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
814 if (0 != (c->options & options))
816 #if DEBUG_CORE_CLIENT
817 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
818 "Sending message of type %u to client.\n",
821 send_to_client (c, msg, can_drop);
829 * Handle CORE_INIT request.
832 handle_client_init (void *cls,
833 struct GNUNET_SERVER_Client *client,
834 const struct GNUNET_MessageHeader *message)
836 const struct InitMessage *im;
837 struct InitReplyMessage irm;
840 const uint16_t *types;
843 struct ConnectNotifyMessage cnm;
846 #if DEBUG_CORE_CLIENT
847 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
848 "Client connecting to core service with `%s' message\n",
851 /* check that we don't have an entry already */
855 if (client == c->client_handle)
858 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
863 msize = ntohs (message->size);
864 if (msize < sizeof (struct InitMessage))
867 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
870 GNUNET_SERVER_notification_context_add (notifier, client);
871 im = (const struct InitMessage *) message;
872 types = (const uint16_t *) &im[1];
873 msize -= sizeof (struct InitMessage);
874 c = GNUNET_malloc (sizeof (struct Client) + msize);
875 c->client_handle = client;
878 c->tcnt = msize / sizeof (uint16_t);
879 c->types = (const uint16_t *) &c[1];
880 wtypes = (uint16_t *) &c[1];
881 for (i=0;i<c->tcnt;i++)
882 wtypes[i] = ntohs (types[i]);
883 c->options = ntohl (im->options);
884 #if DEBUG_CORE_CLIENT
885 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
886 "Client %p is interested in %u message types\n",
890 /* send init reply message */
891 irm.header.size = htons (sizeof (struct InitReplyMessage));
892 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
893 irm.reserved = htonl (0);
894 memcpy (&irm.publicKey,
896 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
897 #if DEBUG_CORE_CLIENT
898 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
899 "Sending `%s' message to client.\n", "INIT_REPLY");
901 send_to_client (c, &irm.header, GNUNET_NO);
902 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
904 /* notify new client about existing neighbours */
905 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
906 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
910 if (n->status == PEER_STATE_KEY_CONFIRMED)
912 #if DEBUG_CORE_CLIENT
913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
914 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
916 cnm.distance = htonl (n->last_distance);
917 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
919 send_to_client (c, &cnm.header, GNUNET_NO);
924 GNUNET_SERVER_receive_done (client, GNUNET_OK);
929 * A client disconnected, clean up.
932 * @param client identification of the client
935 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
942 #if DEBUG_CORE_CLIENT
943 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
944 "Client %p has disconnected from core service.\n",
951 if (client == pos->client_handle)
956 prev->next = pos->next;
963 /* client never sent INIT */
968 * Handle REQUEST_INFO request.
971 handle_client_request_info (void *cls,
972 struct GNUNET_SERVER_Client *client,
973 const struct GNUNET_MessageHeader *message)
975 const struct RequestInfoMessage *rcm;
977 struct ConfigurationInfoMessage cim;
980 unsigned long long old_preference;
981 struct GNUNET_SERVER_TransmitContext *tc;
983 #if DEBUG_CORE_CLIENT
984 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
985 "Core service receives `%s' request.\n", "REQUEST_INFO");
987 rcm = (const struct RequestInfoMessage *) message;
988 n = find_neighbour (&rcm->peer);
989 memset (&cim, 0, sizeof (cim));
992 want_reserv = ntohl (rcm->reserve_inbound);
993 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
995 n->bw_out_internal_limit = rcm->limit_outbound;
996 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
997 n->bw_out_external_limit);
998 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1000 GNUNET_TRANSPORT_set_quota (transport,
1004 GNUNET_TIME_UNIT_FOREVER_REL,
1007 if (want_reserv < 0)
1009 got_reserv = want_reserv;
1011 else if (want_reserv > 0)
1013 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1014 want_reserv).value == 0)
1015 got_reserv = want_reserv;
1017 got_reserv = 0; /* all or nothing */
1021 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1023 old_preference = n->current_preference;
1024 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1025 if (old_preference > n->current_preference)
1027 /* overflow; cap at maximum value */
1028 n->current_preference = (unsigned long long) -1;
1030 update_preference_sum (n->current_preference - old_preference);
1031 #if DEBUG_CORE_QUOTA
1032 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1033 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1035 GNUNET_i2s (&rcm->peer),
1038 cim.reserved_amount = htonl (got_reserv);
1039 cim.bw_in = n->bw_in;
1040 cim.bw_out = n->bw_out;
1041 cim.preference = n->current_preference;
1043 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1044 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1045 cim.peer = rcm->peer;
1047 #if DEBUG_CORE_CLIENT
1048 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1049 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1051 tc = GNUNET_SERVER_transmit_context_create (client);
1052 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1053 GNUNET_SERVER_transmit_context_run (tc,
1054 GNUNET_TIME_UNIT_FOREVER_REL);
1059 * Free the given entry for the neighbour (it has
1060 * already been removed from the list at this point).
1062 * @param n neighbour to free
1065 free_neighbour (struct Neighbour *n)
1067 struct MessageEntry *m;
1069 if (n->pitr != NULL)
1071 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1076 GNUNET_free (n->skm);
1079 while (NULL != (m = n->messages))
1081 n->messages = m->next;
1084 while (NULL != (m = n->encrypted_head))
1086 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1093 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1096 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1097 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1098 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1099 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1100 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1101 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1102 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1103 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1104 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1105 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1106 if (n->status == PEER_STATE_KEY_CONFIRMED)
1107 GNUNET_STATISTICS_update (stats, gettext_noop ("# peers connected"), -1, GNUNET_NO);
1108 GNUNET_free_non_null (n->public_key);
1109 GNUNET_free_non_null (n->pending_ping);
1110 GNUNET_free_non_null (n->pending_pong);
1116 * Check if we have encrypted messages for the specified neighbour
1117 * pending, and if so, check with the transport about sending them
1120 * @param n neighbour to check.
1122 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1126 * Encrypt size bytes from in and write the result to out. Use the
1127 * key for outbound traffic of the given neighbour.
1129 * @param n neighbour we are sending to
1130 * @param iv initialization vector to use
1131 * @param in ciphertext
1132 * @param out plaintext
1133 * @param size size of in/out
1134 * @return GNUNET_OK on success
1137 do_encrypt (struct Neighbour *n,
1138 const GNUNET_HashCode * iv,
1139 const void *in, void *out, size_t size)
1141 if (size != (uint16_t) size)
1146 GNUNET_assert (size ==
1147 GNUNET_CRYPTO_aes_encrypt (in,
1151 GNUNET_CRYPTO_AesInitializationVector
1153 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1155 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1156 "Encrypted %u bytes for `%4s' using key %u\n", size,
1157 GNUNET_i2s (&n->peer), 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' and `%s' messages for `%4s'.\n",
1210 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
1211 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1212 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
1214 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
1217 &n->peer.hashPubKey,
1220 sizeof (struct PingMessage) -
1221 sizeof (struct GNUNET_MessageHeader));
1222 process_encrypted_neighbour_queue (n);
1223 /* reschedule PING job */
1224 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1225 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1226 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1227 MIN_PING_FREQUENCY);
1229 = GNUNET_SCHEDULER_add_delayed (sched,
1238 * Task triggered when a neighbour entry might have gotten stale.
1240 * @param cls the 'struct Neighbour'
1241 * @param tc scheduler context (not used)
1244 consider_free_task (void *cls,
1245 const struct GNUNET_SCHEDULER_TaskContext *tc)
1247 struct Neighbour *n = cls;
1249 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1250 consider_free_neighbour (n);
1255 * Consider freeing the given neighbour since we may not need
1256 * to keep it around anymore.
1258 * @param n neighbour to consider discarding
1261 consider_free_neighbour (struct Neighbour *n)
1263 struct Neighbour *pos;
1264 struct Neighbour *prev;
1265 struct GNUNET_TIME_Relative left;
1267 if ( (n->th != NULL) ||
1268 (n->pitr != NULL) ||
1269 (n->status == PEER_STATE_KEY_CONFIRMED) ||
1270 (GNUNET_YES == n->is_connected) )
1271 return; /* no chance */
1273 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1274 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1277 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1278 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1279 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1281 &consider_free_task,
1285 /* actually free the neighbour... */
1294 neighbours = n->next;
1296 prev->next = n->next;
1297 GNUNET_assert (neighbour_count > 0);
1299 GNUNET_STATISTICS_set (stats, gettext_noop ("# active neighbours"), neighbour_count, GNUNET_NO);
1305 * Function called when the transport service is ready to
1306 * receive an encrypted message for the respective peer
1308 * @param cls neighbour to use message from
1309 * @param size number of bytes we can transmit
1310 * @param buf where to copy the message
1311 * @return number of bytes transmitted
1314 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1316 struct Neighbour *n = cls;
1317 struct MessageEntry *m;
1322 GNUNET_assert (NULL != (m = n->encrypted_head));
1323 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1330 GNUNET_assert (size >= m->size);
1331 memcpy (cbuf, &m[1], m->size);
1333 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1336 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1337 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1338 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1339 ret, GNUNET_i2s (&n->peer));
1341 process_encrypted_neighbour_queue (n);
1346 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1347 "Transmission of message of type %u and size %u failed\n",
1348 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1353 consider_free_neighbour (n);
1359 * Check if we have plaintext messages for the specified neighbour
1360 * pending, and if so, consider batching and encrypting them (and
1361 * then trigger processing of the encrypted queue if needed).
1363 * @param n neighbour to check.
1365 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1369 * Check if we have encrypted messages for the specified neighbour
1370 * pending, and if so, check with the transport about sending them
1373 * @param n neighbour to check.
1376 process_encrypted_neighbour_queue (struct Neighbour *n)
1378 struct MessageEntry *m;
1381 return; /* request already pending */
1382 m = n->encrypted_head;
1385 /* encrypted queue empty, try plaintext instead */
1386 process_plaintext_neighbour_queue (n);
1390 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1391 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1393 GNUNET_i2s (&n->peer),
1394 GNUNET_TIME_absolute_get_remaining (m->deadline).
1398 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1401 GNUNET_TIME_absolute_get_remaining
1403 ¬ify_encrypted_transmit_ready,
1407 /* message request too large or duplicate request */
1409 /* discard encrypted message */
1410 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1414 process_encrypted_neighbour_queue (n);
1420 * Decrypt size bytes from in and write the result to out. Use the
1421 * key for inbound traffic of the given neighbour. This function does
1422 * NOT do any integrity-checks on the result.
1424 * @param n neighbour we are receiving from
1425 * @param iv initialization vector to use
1426 * @param in ciphertext
1427 * @param out plaintext
1428 * @param size size of in/out
1429 * @return GNUNET_OK on success
1432 do_decrypt (struct Neighbour *n,
1433 const GNUNET_HashCode * iv,
1434 const void *in, void *out, size_t size)
1436 if (size != (uint16_t) size)
1441 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1442 (n->status != PEER_STATE_KEY_CONFIRMED))
1444 GNUNET_break_op (0);
1445 return GNUNET_SYSERR;
1448 GNUNET_CRYPTO_aes_decrypt (in,
1452 GNUNET_CRYPTO_AesInitializationVector *) iv,
1456 return GNUNET_SYSERR;
1458 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1460 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1461 "Decrypted %u bytes from `%4s' using key %u\n",
1462 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1469 * Select messages for transmission. This heuristic uses a combination
1470 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1471 * and priority-based discard (in case no feasible schedule exist) and
1472 * speculative optimization (defer any kind of transmission until
1473 * we either create a batch of significant size, 25% of max, or until
1474 * we are close to a deadline). Furthermore, when scheduling the
1475 * heuristic also packs as many messages into the batch as possible,
1476 * starting with those with the earliest deadline. Yes, this is fun.
1478 * @param n neighbour to select messages from
1479 * @param size number of bytes to select for transmission
1480 * @param retry_time set to the time when we should try again
1481 * (only valid if this function returns zero)
1482 * @return number of bytes selected, or 0 if we decided to
1483 * defer scheduling overall; in that case, retry_time is set.
1486 select_messages (struct Neighbour *n,
1487 size_t size, struct GNUNET_TIME_Relative *retry_time)
1489 struct MessageEntry *pos;
1490 struct MessageEntry *min;
1491 struct MessageEntry *last;
1492 unsigned int min_prio;
1493 struct GNUNET_TIME_Absolute t;
1494 struct GNUNET_TIME_Absolute now;
1495 struct GNUNET_TIME_Relative delta;
1497 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1500 unsigned int queue_size;
1501 int discard_low_prio;
1503 GNUNET_assert (NULL != n->messages);
1504 now = GNUNET_TIME_absolute_get ();
1505 /* last entry in linked list of messages processed */
1507 /* should we remove the entry with the lowest
1508 priority from consideration for scheduling at the
1519 discard_low_prio = GNUNET_YES;
1520 while (GNUNET_YES == discard_low_prio)
1524 discard_low_prio = GNUNET_NO;
1525 /* calculate number of bytes available for transmission at time "t" */
1526 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1528 /* how many bytes have we (hypothetically) scheduled so far */
1530 /* maximum time we can wait before transmitting anything
1531 and still make all of our deadlines */
1532 slack = MAX_CORK_DELAY;
1534 /* note that we use "*2" here because we want to look
1535 a bit further into the future; much more makes no
1536 sense since new message might be scheduled in the
1538 while ((pos != NULL) && (off < size * 2))
1540 if (pos->do_transmit == GNUNET_YES)
1542 /* already removed from consideration */
1546 if (discard_low_prio == GNUNET_NO)
1548 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1549 if (delta.value > 0)
1551 // FIXME: HUH? Check!
1553 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1556 if (avail < pos->size)
1558 // FIXME: HUH? Check!
1559 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1564 /* update slack, considering both its absolute deadline
1565 and relative deadlines caused by other messages
1566 with their respective load */
1567 slack = GNUNET_TIME_relative_min (slack,
1568 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1570 if (pos->deadline.value <= now.value)
1573 slack = GNUNET_TIME_UNIT_ZERO;
1575 else if (GNUNET_YES == pos->got_slack)
1577 /* should be soon now! */
1578 slack = GNUNET_TIME_relative_min (slack,
1579 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1584 GNUNET_TIME_relative_min (slack,
1585 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1586 pos->got_slack = GNUNET_YES;
1587 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1588 GNUNET_TIME_relative_to_absolute (MAX_CORK_DELAY));
1593 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1594 if (pos->priority <= min_prio)
1596 /* update min for discard */
1597 min_prio = pos->priority;
1602 if (discard_low_prio)
1604 GNUNET_assert (min != NULL);
1605 /* remove lowest-priority entry from consideration */
1606 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1610 /* guard against sending "tiny" messages with large headers without
1612 if ( (slack.value > 0) &&
1614 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1616 /* less than 25% of message would be filled with deadlines still
1617 being met if we delay by one second or more; so just wait for
1618 more data; but do not wait longer than 1s (since we don't want
1619 to delay messages for a really long time either). */
1620 *retry_time = MAX_CORK_DELAY;
1621 /* reset do_transmit values for next time */
1624 pos->do_transmit = GNUNET_NO;
1628 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1629 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1630 (unsigned long long) slack.value,
1632 (unsigned int) size);
1636 /* select marked messages (up to size) for transmission */
1641 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1643 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1648 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1652 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1653 "Selected %u/%u bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1655 queue_size, MAX_PEER_QUEUE_SIZE,
1656 GNUNET_i2s (&n->peer));
1663 * Batch multiple messages into a larger buffer.
1665 * @param n neighbour to take messages from
1666 * @param buf target buffer
1667 * @param size size of buf
1668 * @param deadline set to transmission deadline for the result
1669 * @param retry_time set to the time when we should try again
1670 * (only valid if this function returns zero)
1671 * @param priority set to the priority of the batch
1672 * @return number of bytes written to buf (can be zero)
1675 batch_message (struct Neighbour *n,
1678 struct GNUNET_TIME_Absolute *deadline,
1679 struct GNUNET_TIME_Relative *retry_time,
1680 unsigned int *priority)
1682 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1683 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1684 struct MessageEntry *pos;
1685 struct MessageEntry *prev;
1686 struct MessageEntry *next;
1691 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1692 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1693 if (0 == select_messages (n, size, retry_time))
1696 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1697 "No messages selected, will try again in %llu ms\n",
1702 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1703 ntm->distance = htonl (n->last_distance);
1704 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1705 ntm->peer = n->peer;
1709 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1712 if (GNUNET_YES == pos->do_transmit)
1714 GNUNET_assert (pos->size <= size);
1715 /* do notifications */
1716 /* FIXME: track if we have *any* client that wants
1717 full notifications and only do this if that is
1719 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1721 memcpy (&ntm[1], &pos[1], pos->size);
1722 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1723 sizeof (struct GNUNET_MessageHeader));
1724 send_to_all_clients (&ntm->header,
1726 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1730 /* message too large for 'full' notifications, we do at
1731 least the 'hdr' type */
1734 sizeof (struct GNUNET_MessageHeader));
1736 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1738 send_to_all_clients (&ntm->header,
1740 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1743 "Encrypting message of type %u\n",
1744 ntohs(((struct GNUNET_MessageHeader*)&pos[1])->type));
1746 /* copy for encrypted transmission */
1747 memcpy (&buf[ret], &pos[1], pos->size);
1750 *priority += pos->priority;
1752 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1753 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1755 GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1757 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1771 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1772 "Deadline for message batch is %llu ms\n",
1773 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1780 * Remove messages with deadlines that have long expired from
1783 * @param n neighbour to inspect
1786 discard_expired_messages (struct Neighbour *n)
1788 struct MessageEntry *prev;
1789 struct MessageEntry *next;
1790 struct MessageEntry *pos;
1791 struct GNUNET_TIME_Absolute now;
1792 struct GNUNET_TIME_Relative delta;
1794 now = GNUNET_TIME_absolute_get ();
1800 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1801 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1804 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1805 "Message is %llu ms past due, discarding.\n",
1822 * Signature of the main function of a task.
1824 * @param cls closure
1825 * @param tc context information (why was this task triggered now)
1828 retry_plaintext_processing (void *cls,
1829 const struct GNUNET_SCHEDULER_TaskContext *tc)
1831 struct Neighbour *n = cls;
1833 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1834 process_plaintext_neighbour_queue (n);
1839 * Send our key (and encrypted PING) to the other peer.
1841 * @param n the other peer
1843 static void send_key (struct Neighbour *n);
1846 * Task that will retry "send_key" if our previous attempt failed
1850 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1852 struct Neighbour *n = cls;
1855 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1856 "Retrying key transmission to `%4s'\n",
1857 GNUNET_i2s (&n->peer));
1859 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1860 n->set_key_retry_frequency =
1861 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1867 * Check if we have plaintext messages for the specified neighbour
1868 * pending, and if so, consider batching and encrypting them (and
1869 * then trigger processing of the encrypted queue if needed).
1871 * @param n neighbour to check.
1874 process_plaintext_neighbour_queue (struct Neighbour *n)
1876 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1879 struct EncryptedMessage *em; /* encrypted message */
1880 struct EncryptedMessage *ph; /* plaintext header */
1881 struct MessageEntry *me;
1882 unsigned int priority;
1883 struct GNUNET_TIME_Absolute deadline;
1884 struct GNUNET_TIME_Relative retry_time;
1887 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1889 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1890 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1894 case PEER_STATE_DOWN:
1897 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1898 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1899 GNUNET_i2s(&n->peer));
1902 case PEER_STATE_KEY_SENT:
1903 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1904 n->retry_set_key_task
1905 = GNUNET_SCHEDULER_add_delayed (sched,
1906 n->set_key_retry_frequency,
1907 &set_key_retry_task, n);
1909 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1910 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1911 GNUNET_i2s(&n->peer));
1914 case PEER_STATE_KEY_RECEIVED:
1915 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1916 n->retry_set_key_task
1917 = GNUNET_SCHEDULER_add_delayed (sched,
1918 n->set_key_retry_frequency,
1919 &set_key_retry_task, n);
1921 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1922 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1923 GNUNET_i2s(&n->peer));
1926 case PEER_STATE_KEY_CONFIRMED:
1927 /* ready to continue */
1930 discard_expired_messages (n);
1931 if (n->messages == NULL)
1934 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1935 "Plaintext message queue for `%4s' is empty.\n",
1936 GNUNET_i2s(&n->peer));
1938 return; /* no pending messages */
1940 if (n->encrypted_head != NULL)
1943 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1944 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1945 GNUNET_i2s(&n->peer));
1947 return; /* wait for messages already encrypted to be
1950 ph = (struct EncryptedMessage *) pbuf;
1951 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1953 used = sizeof (struct EncryptedMessage);
1954 used += batch_message (n,
1956 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1957 &deadline, &retry_time, &priority);
1958 if (used == sizeof (struct EncryptedMessage))
1961 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1962 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1963 GNUNET_i2s(&n->peer));
1965 /* no messages selected for sending, try again later... */
1966 n->retry_plaintext_task =
1967 GNUNET_SCHEDULER_add_delayed (sched,
1969 &retry_plaintext_processing, n);
1972 #if DEBUG_CORE_QUOTA
1973 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1974 "Sending %u b/s as new limit to peer `%4s'\n",
1975 (unsigned int) ntohl (n->bw_in.value__),
1976 GNUNET_i2s (&n->peer));
1978 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1));
1979 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1980 ph->inbound_bw_limit = n->bw_in;
1981 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1983 /* setup encryption message header */
1984 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1985 me->deadline = deadline;
1986 me->priority = priority;
1988 em = (struct EncryptedMessage *) &me[1];
1989 em->header.size = htons (used);
1990 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1991 em->iv_seed = ph->iv_seed;
1992 esize = used - ENCRYPTED_HEADER_SIZE;
1993 GNUNET_CRYPTO_hash (&ph->sequence_number,
1994 esize - sizeof (GNUNET_HashCode),
1995 &ph->plaintext_hash);
1996 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
1999 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2000 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2002 GNUNET_i2s(&n->peer),
2003 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2005 GNUNET_assert (GNUNET_OK ==
2008 &ph->plaintext_hash,
2009 &em->plaintext_hash, esize));
2010 /* append to transmission list */
2011 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2015 process_encrypted_neighbour_queue (n);
2020 * Function that recalculates the bandwidth quota for the
2021 * given neighbour and transmits it to the transport service.
2023 * @param cls neighbour for the quota update
2027 neighbour_quota_update (void *cls,
2028 const struct GNUNET_SCHEDULER_TaskContext *tc);
2032 * Schedule the task that will recalculate the bandwidth
2033 * quota for this peer (and possibly force a disconnect of
2034 * idle peers by calculating a bandwidth of zero).
2037 schedule_quota_update (struct Neighbour *n)
2039 GNUNET_assert (n->quota_update_task ==
2040 GNUNET_SCHEDULER_NO_TASK);
2041 n->quota_update_task
2042 = GNUNET_SCHEDULER_add_delayed (sched,
2043 QUOTA_UPDATE_FREQUENCY,
2044 &neighbour_quota_update,
2050 * Initialize a new 'struct Neighbour'.
2052 * @param pid ID of the new neighbour
2053 * @return handle for the new neighbour
2055 static struct Neighbour *
2056 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2058 struct Neighbour *n;
2059 struct GNUNET_TIME_Absolute now;
2061 n = GNUNET_malloc (sizeof (struct Neighbour));
2062 n->next = neighbours;
2065 GNUNET_STATISTICS_set (stats, gettext_noop ("# active neighbours"), neighbour_count, GNUNET_NO);
2067 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2068 now = GNUNET_TIME_absolute_get ();
2069 n->encrypt_key_created = now;
2070 n->last_activity = now;
2071 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2072 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2073 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2074 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init ((uint32_t) - 1);
2075 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2076 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2078 neighbour_quota_update (n, NULL);
2084 * Handle CORE_SEND request.
2087 * @param client the client issuing the request
2088 * @param message the "struct SendMessage"
2091 handle_client_send (void *cls,
2092 struct GNUNET_SERVER_Client *client,
2093 const struct GNUNET_MessageHeader *message)
2095 const struct SendMessage *sm;
2096 struct Neighbour *n;
2097 struct MessageEntry *prev;
2098 struct MessageEntry *pos;
2099 struct MessageEntry *e;
2100 struct MessageEntry *min_prio_entry;
2101 struct MessageEntry *min_prio_prev;
2102 unsigned int min_prio;
2103 unsigned int queue_size;
2106 msize = ntohs (message->size);
2108 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2112 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2115 sm = (const struct SendMessage *) message;
2116 msize -= sizeof (struct SendMessage);
2117 n = find_neighbour (&sm->peer);
2119 n = create_neighbour (&sm->peer);
2121 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2122 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2125 GNUNET_i2s (&sm->peer));
2127 /* bound queue size */
2128 discard_expired_messages (n);
2129 min_prio = (unsigned int) -1;
2130 min_prio_entry = NULL;
2131 min_prio_prev = NULL;
2137 if (pos->priority < min_prio)
2139 min_prio_entry = pos;
2140 min_prio_prev = prev;
2141 min_prio = pos->priority;
2147 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2150 if (ntohl(sm->priority) <= min_prio)
2152 /* discard new entry */
2154 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2155 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2157 MAX_PEER_QUEUE_SIZE,
2159 ntohs (message->type));
2162 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2165 /* discard "min_prio_entry" */
2167 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2168 "Queue full, discarding existing older request\n");
2170 if (min_prio_prev == NULL)
2171 n->messages = min_prio_entry->next;
2173 min_prio_prev->next = min_prio_entry->next;
2174 GNUNET_free (min_prio_entry);
2178 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2179 "Adding transmission request for `%4s' of size %u to queue\n",
2180 GNUNET_i2s (&sm->peer),
2183 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2184 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2185 e->priority = ntohl (sm->priority);
2187 memcpy (&e[1], &sm[1], msize);
2189 /* insert, keep list sorted by deadline */
2192 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2203 /* consider scheduling now */
2204 process_plaintext_neighbour_queue (n);
2206 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2211 * Function called when the transport service is ready to
2212 * receive a message. Only resets 'n->th' to NULL.
2214 * @param cls neighbour to use message from
2215 * @param size number of bytes we can transmit
2216 * @param buf where to copy the message
2217 * @return number of bytes transmitted
2220 notify_transport_connect_done (void *cls, size_t size, void *buf)
2222 struct Neighbour *n = cls;
2227 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2228 _("Failed to connect to `%4s': transport failed to connect\n"),
2229 GNUNET_i2s (&n->peer));
2238 * Handle CORE_REQUEST_CONNECT request.
2241 * @param client the client issuing the request
2242 * @param message the "struct ConnectMessage"
2245 handle_client_request_connect (void *cls,
2246 struct GNUNET_SERVER_Client *client,
2247 const struct GNUNET_MessageHeader *message)
2249 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2250 struct Neighbour *n;
2251 struct GNUNET_TIME_Relative timeout;
2253 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2256 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2259 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2260 n = find_neighbour (&cm->peer);
2262 n = create_neighbour (&cm->peer);
2263 if ( (n->is_connected) ||
2265 return; /* already connected, or at least trying */
2266 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2268 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2269 "Core received `%s' request for `%4s', will try to establish connection\n",
2271 GNUNET_i2s (&cm->peer));
2273 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2274 /* ask transport to connect to the peer */
2275 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2277 sizeof (struct GNUNET_MessageHeader), 0,
2279 ¬ify_transport_connect_done,
2281 GNUNET_break (NULL != n->th);
2286 * List of handlers for the messages understood by this
2289 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2290 {&handle_client_init, NULL,
2291 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2292 {&handle_client_request_info, NULL,
2293 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2294 sizeof (struct RequestInfoMessage)},
2295 {&handle_client_send, NULL,
2296 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2297 {&handle_client_request_connect, NULL,
2298 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2299 sizeof (struct ConnectMessage)},
2305 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2306 * the neighbour's struct and retry send_key. Or, if we did not get a
2307 * HELLO, just do nothing.
2309 * @param cls the 'struct Neighbour' to retry sending the key for
2310 * @param peer the peer for which this is the HELLO
2311 * @param hello HELLO message of that peer
2312 * @param trust amount of trust we currently have in that peer
2315 process_hello_retry_send_key (void *cls,
2316 const struct GNUNET_PeerIdentity *peer,
2317 const struct GNUNET_HELLO_Message *hello,
2320 struct Neighbour *n = cls;
2325 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2326 "Entered `process_hello_retry_send_key' and `peer' is NULL!\n");
2329 if (n->public_key != NULL)
2331 GNUNET_STATISTICS_update (stats,
2332 gettext_noop ("# SETKEY messages deferred (need public key)"),
2339 GNUNET_STATISTICS_update (stats,
2340 gettext_noop ("# Delayed connecting due to lack of public key"),
2343 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2344 n->retry_set_key_task
2345 = GNUNET_SCHEDULER_add_delayed (sched,
2346 n->set_key_retry_frequency,
2347 &set_key_retry_task, n);
2353 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2354 "Entered `process_hello_retry_send_key' for peer `%4s'\n",
2357 if (n->public_key != NULL)
2360 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2361 "already have public key for peer %s!! (so why are we here?)\n",
2368 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2369 "Received new `%s' message for `%4s', initiating key exchange.\n",
2374 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2375 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2377 GNUNET_STATISTICS_update (stats,
2378 gettext_noop ("# Error extracting public key from HELLO"),
2381 GNUNET_free (n->public_key);
2382 n->public_key = NULL;
2384 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2385 "GNUNET_HELLO_get_key returned awfully\n");
2393 * Send our key (and encrypted PING) to the other peer.
2395 * @param n the other peer
2398 send_key (struct Neighbour *n)
2400 struct SetKeyMessage *sm;
2401 struct MessageEntry *me;
2402 struct PingMessage pp;
2403 struct PingMessage *pm;
2405 if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2409 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2410 "Key exchange in progress with `%4s'.\n",
2411 GNUNET_i2s (&n->peer));
2413 return; /* already in progress */
2417 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2418 "Asked to perform key exchange with `%4s'.\n",
2419 GNUNET_i2s (&n->peer));
2421 if (n->public_key == NULL)
2423 /* lookup n's public key, then try again */
2425 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2426 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2427 GNUNET_i2s (&n->peer));
2429 GNUNET_assert (n->pitr == NULL);
2430 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2434 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2435 &process_hello_retry_send_key, n);
2438 /* first, set key message */
2439 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2440 sizeof (struct SetKeyMessage));
2441 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2442 me->priority = SET_KEY_PRIORITY;
2443 me->size = sizeof (struct SetKeyMessage);
2444 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2448 sm = (struct SetKeyMessage *) &me[1];
2449 sm->header.size = htons (sizeof (struct SetKeyMessage));
2450 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2451 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2452 PEER_STATE_KEY_SENT : n->status));
2454 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2455 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2456 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2457 sizeof (struct GNUNET_PeerIdentity));
2458 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2459 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2460 sm->target = n->peer;
2461 GNUNET_assert (GNUNET_OK ==
2462 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2464 GNUNET_CRYPTO_AesSessionKey),
2466 &sm->encrypted_key));
2467 GNUNET_assert (GNUNET_OK ==
2468 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2471 /* second, encrypted PING message */
2472 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2473 sizeof (struct PingMessage));
2474 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2475 me->priority = PING_PRIORITY;
2476 me->size = sizeof (struct PingMessage);
2477 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2481 pm = (struct PingMessage *) &me[1];
2482 pm->header.size = htons (sizeof (struct PingMessage));
2483 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2484 pp.challenge = htonl (n->ping_challenge);
2485 pp.target = n->peer;
2487 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2488 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2489 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2490 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2491 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2493 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2496 &n->peer.hashPubKey,
2499 sizeof (struct PingMessage) -
2500 sizeof (struct GNUNET_MessageHeader));
2504 case PEER_STATE_DOWN:
2505 n->status = PEER_STATE_KEY_SENT;
2507 case PEER_STATE_KEY_SENT:
2509 case PEER_STATE_KEY_RECEIVED:
2511 case PEER_STATE_KEY_CONFIRMED:
2518 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2519 "Have %llu ms left for `%s' transmission.\n",
2520 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2523 /* trigger queue processing */
2524 process_encrypted_neighbour_queue (n);
2525 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2526 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2527 n->retry_set_key_task
2528 = GNUNET_SCHEDULER_add_delayed (sched,
2529 n->set_key_retry_frequency,
2530 &set_key_retry_task, n);
2535 * We received a SET_KEY message. Validate and update
2536 * our key material and status.
2538 * @param n the neighbour from which we received message m
2539 * @param m the set key message we received
2542 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2546 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2547 * the neighbour's struct and retry handling the set_key message. Or,
2548 * if we did not get a HELLO, just free the set key message.
2550 * @param cls pointer to the set key message
2551 * @param peer the peer for which this is the HELLO
2552 * @param hello HELLO message of that peer
2553 * @param trust amount of trust we currently have in that peer
2556 process_hello_retry_handle_set_key (void *cls,
2557 const struct GNUNET_PeerIdentity *peer,
2558 const struct GNUNET_HELLO_Message *hello,
2561 struct Neighbour *n = cls;
2562 struct SetKeyMessage *sm = n->skm;
2571 if (n->public_key != NULL)
2572 return; /* multiple HELLOs match!? */
2574 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2575 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2577 GNUNET_break_op (0);
2578 GNUNET_free (n->public_key);
2579 n->public_key = NULL;
2583 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2584 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2585 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2587 handle_set_key (n, sm);
2592 * We received a PING message. Validate and transmit
2595 * @param n sender of the PING
2596 * @param m the encrypted PING message itself
2599 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2601 struct PingMessage t;
2602 struct PongMessage tx;
2603 struct PongMessage *tp;
2604 struct MessageEntry *me;
2607 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2608 "Core service receives `%s' request from `%4s'.\n",
2609 "PING", GNUNET_i2s (&n->peer));
2613 &my_identity.hashPubKey,
2616 sizeof (struct PingMessage) -
2617 sizeof (struct GNUNET_MessageHeader)))
2620 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2621 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2623 GNUNET_i2s (&t.target),
2624 ntohl (t.challenge), n->decrypt_key.crc32);
2625 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2626 "Target of `%s' request is `%4s'.\n",
2627 "PING", GNUNET_i2s (&t.target));
2629 GNUNET_STATISTICS_update (stats, gettext_noop ("# ping messages decrypted"), 1, GNUNET_NO);
2630 if (0 != memcmp (&t.target,
2631 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2633 GNUNET_break_op (0);
2636 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2637 sizeof (struct PongMessage));
2638 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2642 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2643 me->priority = PONG_PRIORITY;
2644 me->size = sizeof (struct PongMessage);
2645 tx.reserved = htonl (0);
2646 tx.inbound_bw_limit = n->bw_in;
2647 tx.challenge = t.challenge;
2648 tx.target = t.target;
2649 tp = (struct PongMessage *) &me[1];
2650 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2651 tp->header.size = htons (sizeof (struct PongMessage));
2653 &my_identity.hashPubKey,
2656 sizeof (struct PongMessage) -
2657 sizeof (struct GNUNET_MessageHeader));
2659 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2660 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2661 ntohl (t.challenge), n->encrypt_key.crc32);
2663 /* trigger queue processing */
2664 process_encrypted_neighbour_queue (n);
2669 * We received a PONG message. Validate and update our status.
2671 * @param n sender of the PONG
2672 * @param m the encrypted PONG message itself
2675 handle_pong (struct Neighbour *n,
2676 const struct PongMessage *m)
2678 struct PongMessage t;
2679 struct ConnectNotifyMessage cnm;
2682 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2683 "Core service receives `%s' request from `%4s'.\n",
2684 "PONG", GNUNET_i2s (&n->peer));
2688 &n->peer.hashPubKey,
2691 sizeof (struct PongMessage) -
2692 sizeof (struct GNUNET_MessageHeader)))
2694 if (0 != ntohl (t.reserved))
2696 GNUNET_break_op (0);
2700 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2701 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2703 GNUNET_i2s (&t.target),
2704 ntohl (t.challenge), n->decrypt_key.crc32);
2706 if ((0 != memcmp (&t.target,
2708 sizeof (struct GNUNET_PeerIdentity))) ||
2709 (n->ping_challenge != ntohl (t.challenge)))
2711 /* PONG malformed */
2713 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2714 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2715 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2716 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2717 "Received malformed `%s' received from `%4s' with challenge %u\n",
2718 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2720 GNUNET_break_op (0);
2725 case PEER_STATE_DOWN:
2726 GNUNET_break (0); /* should be impossible */
2728 case PEER_STATE_KEY_SENT:
2729 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2731 case PEER_STATE_KEY_RECEIVED:
2732 n->status = PEER_STATE_KEY_CONFIRMED;
2733 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2735 n->bw_out_external_limit = t.inbound_bw_limit;
2736 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2737 n->bw_out_internal_limit);
2738 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2740 GNUNET_TRANSPORT_set_quota (transport,
2744 GNUNET_TIME_UNIT_FOREVER_REL,
2748 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2749 "Confirmed key via `%s' message for peer `%4s'\n",
2750 "PONG", GNUNET_i2s (&n->peer));
2752 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2754 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2755 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2757 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2758 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2759 cnm.distance = htonl (n->last_distance);
2760 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2762 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2763 process_encrypted_neighbour_queue (n);
2765 case PEER_STATE_KEY_CONFIRMED:
2766 n->last_activity = GNUNET_TIME_absolute_get ();
2767 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2768 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2770 = GNUNET_SCHEDULER_add_delayed (sched,
2771 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2783 * We received a SET_KEY message. Validate and update
2784 * our key material and status.
2786 * @param n the neighbour from which we received message m
2787 * @param m the set key message we received
2790 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2792 struct SetKeyMessage *m_cpy;
2793 struct GNUNET_TIME_Absolute t;
2794 struct GNUNET_CRYPTO_AesSessionKey k;
2795 struct PingMessage *ping;
2796 struct PongMessage *pong;
2797 enum PeerStateMachine sender_status;
2800 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2801 "Core service receives `%s' request from `%4s'.\n",
2802 "SET_KEY", GNUNET_i2s (&n->peer));
2804 if (n->public_key == NULL)
2806 if (n->pitr != NULL)
2809 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2810 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2816 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2817 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2819 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2820 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2821 /* lookup n's public key, then try again */
2822 GNUNET_assert (n->skm == NULL);
2824 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2828 GNUNET_TIME_UNIT_MINUTES,
2829 &process_hello_retry_handle_set_key, n);
2830 GNUNET_STATISTICS_update (stats, gettext_noop ("# SETKEY messages deferred (need public key)"), 1, GNUNET_NO);
2833 if (0 != memcmp (&m->target,
2835 sizeof (struct GNUNET_PeerIdentity)))
2837 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2838 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
2840 GNUNET_i2s (&m->target));
2843 if ((ntohl (m->purpose.size) !=
2844 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2845 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2846 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2847 sizeof (struct GNUNET_PeerIdentity)) ||
2849 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2850 &m->purpose, &m->signature, n->public_key)))
2852 /* invalid signature */
2853 GNUNET_break_op (0);
2856 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2857 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2858 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2859 (t.value < n->decrypt_key_created.value))
2861 /* this could rarely happen due to massive re-ordering of
2862 messages on the network level, but is most likely either
2863 a bug or some adversary messing with us. Report. */
2864 GNUNET_break_op (0);
2868 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2869 "Decrypting key material.\n");
2871 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2874 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2875 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2876 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2878 /* failed to decrypt !? */
2879 GNUNET_break_op (0);
2884 if (n->decrypt_key_created.value != t.value)
2886 /* fresh key, reset sequence numbers */
2887 n->last_sequence_number_received = 0;
2888 n->last_packets_bitmap = 0;
2889 n->decrypt_key_created = t;
2891 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2894 case PEER_STATE_DOWN:
2895 n->status = PEER_STATE_KEY_RECEIVED;
2897 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2898 "Responding to `%s' with my own key.\n", "SET_KEY");
2902 case PEER_STATE_KEY_SENT:
2903 case PEER_STATE_KEY_RECEIVED:
2904 n->status = PEER_STATE_KEY_RECEIVED;
2905 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2906 (sender_status != PEER_STATE_KEY_CONFIRMED))
2909 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2910 "Responding to `%s' with my own key (other peer has status %u).\n",
2911 "SET_KEY", sender_status);
2916 case PEER_STATE_KEY_CONFIRMED:
2917 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2918 (sender_status != PEER_STATE_KEY_CONFIRMED))
2921 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2922 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2923 "SET_KEY", sender_status);
2932 if (n->pending_ping != NULL)
2934 ping = n->pending_ping;
2935 n->pending_ping = NULL;
2936 handle_ping (n, ping);
2939 if (n->pending_pong != NULL)
2941 pong = n->pending_pong;
2942 n->pending_pong = NULL;
2943 handle_pong (n, pong);
2950 * Send a P2P message to a client.
2952 * @param sender who sent us the message?
2953 * @param client who should we give the message to?
2954 * @param m contains the message to transmit
2955 * @param msize number of bytes in buf to transmit
2958 send_p2p_message_to_client (struct Neighbour *sender,
2959 struct Client *client,
2960 const void *m, size_t msize)
2962 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2963 struct NotifyTrafficMessage *ntm;
2966 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2967 "Core service passes message from `%4s' of type %u to client.\n",
2968 GNUNET_i2s(&sender->peer),
2969 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2971 ntm = (struct NotifyTrafficMessage *) buf;
2972 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2973 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2974 ntm->distance = htonl (sender->last_distance);
2975 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
2976 ntm->peer = sender->peer;
2977 memcpy (&ntm[1], m, msize);
2978 send_to_client (client, &ntm->header, GNUNET_YES);
2983 * Deliver P2P message to interested clients.
2985 * @param sender who sent us the message?
2986 * @param m the message
2987 * @param msize size of the message (including header)
2990 deliver_message (struct Neighbour *sender,
2991 const struct GNUNET_MessageHeader *m, size_t msize)
2993 struct Client *cpos;
2999 type = ntohs (m->type);
3001 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3002 "Received encapsulated message of type %u from `%4s'\n",
3004 GNUNET_i2s (&sender->peer));
3006 dropped = GNUNET_YES;
3008 while (cpos != NULL)
3010 deliver_full = GNUNET_NO;
3011 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3012 deliver_full = GNUNET_YES;
3015 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3017 if (type != cpos->types[tpos])
3019 deliver_full = GNUNET_YES;
3023 if (GNUNET_YES == deliver_full)
3025 send_p2p_message_to_client (sender, cpos, m, msize);
3026 dropped = GNUNET_NO;
3028 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3030 send_p2p_message_to_client (sender, cpos, m,
3031 sizeof (struct GNUNET_MessageHeader));
3035 if (dropped == GNUNET_YES)
3038 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3039 "Message of type %u from `%4s' not delivered to any client.\n",
3041 GNUNET_i2s (&sender->peer));
3043 /* FIXME: stats... */
3049 * Align P2P message and then deliver to interested clients.
3051 * @param sender who sent us the message?
3052 * @param buffer unaligned (!) buffer containing message
3053 * @param msize size of the message (including header)
3056 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
3060 /* TODO: call to statistics? */
3061 memcpy (abuf, buffer, msize);
3062 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
3067 * Deliver P2P messages to interested clients.
3069 * @param sender who sent us the message?
3070 * @param buffer buffer containing messages, can be modified
3071 * @param buffer_size size of the buffer (overall)
3072 * @param offset offset where messages in the buffer start
3075 deliver_messages (struct Neighbour *sender,
3076 const char *buffer, size_t buffer_size, size_t offset)
3078 struct GNUNET_MessageHeader *mhp;
3079 struct GNUNET_MessageHeader mh;
3083 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
3085 if (0 != offset % sizeof (uint16_t))
3087 /* outch, need to copy to access header */
3088 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
3093 /* can access header directly */
3094 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
3096 msize = ntohs (mhp->size);
3097 if (msize + offset > buffer_size)
3099 /* malformed message, header says it is larger than what
3100 would fit into the overall buffer */
3101 GNUNET_break_op (0);
3104 #if HAVE_UNALIGNED_64_ACCESS
3105 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
3107 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
3109 if (GNUNET_YES == need_align)
3110 align_and_deliver (sender, &buffer[offset], msize);
3112 deliver_message (sender,
3113 (const struct GNUNET_MessageHeader *)
3114 &buffer[offset], msize);
3121 * We received an encrypted message. Decrypt, validate and
3122 * pass on to the appropriate clients.
3125 handle_encrypted_message (struct Neighbour *n,
3126 const struct EncryptedMessage *m)
3128 size_t size = ntohs (m->header.size);
3130 struct EncryptedMessage *pt; /* plaintext */
3134 struct GNUNET_TIME_Absolute t;
3138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3139 "Core service receives `%s' request from `%4s'.\n",
3140 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3142 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3148 &buf[ENCRYPTED_HEADER_SIZE],
3149 size - ENCRYPTED_HEADER_SIZE))
3151 pt = (struct EncryptedMessage *) buf;
3154 GNUNET_CRYPTO_hash (&pt->sequence_number,
3155 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3156 if (0 != memcmp (&ph,
3157 &pt->plaintext_hash,
3158 sizeof (GNUNET_HashCode)))
3160 /* checksum failed */
3161 GNUNET_break_op (0);
3165 /* validate sequence number */
3166 snum = ntohl (pt->sequence_number);
3167 if (n->last_sequence_number_received == snum)
3169 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3170 "Received duplicate message, ignoring.\n");
3171 /* duplicate, ignore */
3174 if ((n->last_sequence_number_received > snum) &&
3175 (n->last_sequence_number_received - snum > 32))
3177 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3178 "Received ancient out of sequence message, ignoring.\n");
3179 /* ancient out of sequence, ignore */
3182 if (n->last_sequence_number_received > snum)
3184 unsigned int rotbit =
3185 1 << (n->last_sequence_number_received - snum - 1);
3186 if ((n->last_packets_bitmap & rotbit) != 0)
3188 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3189 "Received duplicate message, ignoring.\n");
3190 /* duplicate, ignore */
3193 n->last_packets_bitmap |= rotbit;
3195 if (n->last_sequence_number_received < snum)
3197 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3198 n->last_sequence_number_received = snum;
3201 /* check timestamp */
3202 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3203 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3205 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3207 ("Message received far too old (%llu ms). Content ignored.\n"),
3208 GNUNET_TIME_absolute_get_duration (t).value);
3212 /* process decrypted message(s) */
3213 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3215 #if DEBUG_CORE_SET_QUOTA
3216 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3217 "Received %u b/s as new inbound limit for peer `%4s'\n",
3218 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3219 GNUNET_i2s (&n->peer));
3221 n->bw_out_external_limit = pt->inbound_bw_limit;
3222 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3223 n->bw_out_internal_limit);
3224 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3226 GNUNET_TRANSPORT_set_quota (transport,
3230 GNUNET_TIME_UNIT_FOREVER_REL,
3233 n->last_activity = GNUNET_TIME_absolute_get ();
3234 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3235 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3237 = GNUNET_SCHEDULER_add_delayed (sched,
3238 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3241 off = sizeof (struct EncryptedMessage);
3242 deliver_messages (n, buf, size, off);
3247 * Function called by the transport for each received message.
3249 * @param cls closure
3250 * @param peer (claimed) identity of the other peer
3251 * @param message the message
3252 * @param latency estimated latency for communicating with the
3253 * given peer (round-trip)
3254 * @param distance in overlay hops, as given by transport plugin
3257 handle_transport_receive (void *cls,
3258 const struct GNUNET_PeerIdentity *peer,
3259 const struct GNUNET_MessageHeader *message,
3260 struct GNUNET_TIME_Relative latency,
3261 unsigned int distance)
3263 struct Neighbour *n;
3264 struct GNUNET_TIME_Absolute now;
3270 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3271 "Received message of type %u from `%4s', demultiplexing.\n",
3272 ntohs (message->type), GNUNET_i2s (peer));
3274 n = find_neighbour (peer);
3276 n = create_neighbour (peer);
3279 n->last_latency = latency;
3280 n->last_distance = distance;
3281 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3282 type = ntohs (message->type);
3283 size = ntohs (message->size);
3286 "Received message of type %u from `%4s'\n",
3292 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3293 if (size != sizeof (struct SetKeyMessage))
3295 GNUNET_break_op (0);
3298 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3299 handle_set_key (n, (const struct SetKeyMessage *) message);
3301 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3302 if (size < sizeof (struct EncryptedMessage) +
3303 sizeof (struct GNUNET_MessageHeader))
3305 GNUNET_break_op (0);
3308 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3309 (n->status != PEER_STATE_KEY_CONFIRMED))
3311 GNUNET_break_op (0);
3312 /* blacklist briefly (?); might help recover (?) */
3313 GNUNET_TRANSPORT_blacklist (sched, cfg,
3315 GNUNET_TIME_UNIT_SECONDS,
3316 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3321 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3323 case GNUNET_MESSAGE_TYPE_CORE_PING:
3324 if (size != sizeof (struct PingMessage))
3326 GNUNET_break_op (0);
3329 GNUNET_STATISTICS_update (stats, gettext_noop ("# ping messages received"), 1, GNUNET_NO);
3330 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3331 (n->status != PEER_STATE_KEY_CONFIRMED))
3334 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3335 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3336 "PING", GNUNET_i2s (&n->peer));
3338 GNUNET_free_non_null (n->pending_ping);
3339 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3340 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3343 handle_ping (n, (const struct PingMessage *) message);
3345 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3346 if (size != sizeof (struct PongMessage))
3348 GNUNET_break_op (0);
3351 GNUNET_STATISTICS_update (stats, gettext_noop ("# pong messages received"), 1, GNUNET_NO);
3352 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3353 (n->status != PEER_STATE_KEY_CONFIRMED) )
3356 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3357 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3358 "PONG", GNUNET_i2s (&n->peer));
3360 GNUNET_free_non_null (n->pending_pong);
3361 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3362 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3365 handle_pong (n, (const struct PongMessage *) message);
3368 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3369 _("Unsupported message of type %u received.\n"), type);
3372 if (n->status == PEER_STATE_KEY_CONFIRMED)
3374 now = GNUNET_TIME_absolute_get ();
3375 n->last_activity = now;
3378 GNUNET_STATISTICS_update (stats, gettext_noop ("# peers connected"), 1, GNUNET_NO);
3379 n->time_established = now;
3381 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3382 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3384 = GNUNET_SCHEDULER_add_delayed (sched,
3385 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3393 * Function that recalculates the bandwidth quota for the
3394 * given neighbour and transmits it to the transport service.
3396 * @param cls neighbour for the quota update
3400 neighbour_quota_update (void *cls,
3401 const struct GNUNET_SCHEDULER_TaskContext *tc)
3403 struct Neighbour *n = cls;
3404 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3407 unsigned long long distributable;
3408 uint64_t need_per_peer;
3409 uint64_t need_per_second;
3411 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3412 /* calculate relative preference among all neighbours;
3413 divides by a bit more to avoid division by zero AND to
3414 account for possibility of new neighbours joining any time
3415 AND to convert to double... */
3416 if (preference_sum == 0)
3418 pref_rel = 1.0 / (double) neighbour_count;
3422 pref_rel = n->current_preference / preference_sum;
3424 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3425 GNUNET_TIME_UNIT_SECONDS);
3426 need_per_second = need_per_peer * neighbour_count;
3428 if (bandwidth_target_out_bps > need_per_second)
3429 distributable = bandwidth_target_out_bps - need_per_second;
3430 share = distributable * pref_rel;
3431 if (share + need_per_peer > ( (uint32_t)-1))
3432 q_in = GNUNET_BANDWIDTH_value_init ((uint32_t) -1);
3434 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3435 /* check if we want to disconnect for good due to inactivity */
3436 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3437 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3440 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3441 "Forcing disconnect of `%4s' due to inactivity (?).\n",
3442 GNUNET_i2s (&n->peer));
3444 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3446 #if DEBUG_CORE_QUOTA
3447 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3448 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3449 GNUNET_i2s (&n->peer),
3450 (unsigned int) ntohl (q_in.value__),
3451 bandwidth_target_out_bps,
3452 (unsigned int) ntohl (n->bw_in.value__),
3453 (unsigned int) ntohl (n->bw_out.value__),
3454 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3456 if (n->bw_in.value__ != q_in.value__)
3459 GNUNET_TRANSPORT_set_quota (transport,
3463 GNUNET_TIME_UNIT_FOREVER_REL,
3466 schedule_quota_update (n);
3471 * Function called by transport to notify us that
3472 * a peer connected to us (on the network level).
3474 * @param cls closure
3475 * @param peer the peer that connected
3476 * @param latency current latency of the connection
3477 * @param distance in overlay hops, as given by transport plugin
3480 handle_transport_notify_connect (void *cls,
3481 const struct GNUNET_PeerIdentity *peer,
3482 struct GNUNET_TIME_Relative latency,
3483 unsigned int distance)
3485 struct Neighbour *n;
3486 struct ConnectNotifyMessage cnm;
3488 n = find_neighbour (peer);
3491 if (n->is_connected)
3493 /* duplicate connect notification!? */
3500 n = create_neighbour (peer);
3502 n->is_connected = GNUNET_YES;
3503 n->last_latency = latency;
3504 n->last_distance = distance;
3505 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3508 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3512 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3513 "Received connection from `%4s'.\n",
3514 GNUNET_i2s (&n->peer));
3516 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3517 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3518 cnm.distance = htonl (n->last_distance);
3519 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3521 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3522 GNUNET_TRANSPORT_set_quota (transport,
3526 GNUNET_TIME_UNIT_FOREVER_REL,
3533 * Function called by transport telling us that a peer
3536 * @param cls closure
3537 * @param peer the peer that disconnected
3540 handle_transport_notify_disconnect (void *cls,
3541 const struct GNUNET_PeerIdentity *peer)
3543 struct DisconnectNotifyMessage cnm;
3544 struct Neighbour *n;
3547 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3548 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3550 n = find_neighbour (peer);
3556 GNUNET_break (n->is_connected);
3557 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3558 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3560 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3561 n->is_connected = GNUNET_NO;
3566 * Last task run during shutdown. Disconnects us from
3570 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3572 struct Neighbour *n;
3576 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3577 "Core service shutting down.\n");
3579 GNUNET_assert (transport != NULL);
3580 GNUNET_TRANSPORT_disconnect (transport);
3582 while (NULL != (n = neighbours))
3584 neighbours = n->next;
3585 GNUNET_assert (neighbour_count > 0);
3589 GNUNET_STATISTICS_set (stats, gettext_noop ("# active neighbours"), neighbour_count, GNUNET_NO);
3590 GNUNET_SERVER_notification_context_destroy (notifier);
3592 while (NULL != (c = clients))
3593 handle_client_disconnect (NULL, c->client_handle);
3594 if (my_private_key != NULL)
3595 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3597 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3602 * Initiate core service.
3604 * @param cls closure
3605 * @param s scheduler to use
3606 * @param serv the initialized server
3607 * @param c configuration to use
3611 struct GNUNET_SCHEDULER_Handle *s,
3612 struct GNUNET_SERVER_Handle *serv,
3613 const struct GNUNET_CONFIGURATION_Handle *c)
3619 /* parse configuration */
3622 GNUNET_CONFIGURATION_get_value_number (c,
3625 &bandwidth_target_in_bps)) ||
3627 GNUNET_CONFIGURATION_get_value_number (c,
3630 &bandwidth_target_out_bps)) ||
3632 GNUNET_CONFIGURATION_get_value_filename (c,
3634 "HOSTKEY", &keyfile)))
3636 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3638 ("Core service is lacking key configuration settings. Exiting.\n"));
3639 GNUNET_SCHEDULER_shutdown (s);
3642 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3643 GNUNET_free (keyfile);
3644 if (my_private_key == NULL)
3646 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3647 _("Core service could not access hostkey. Exiting.\n"));
3648 GNUNET_SCHEDULER_shutdown (s);
3651 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3652 GNUNET_CRYPTO_hash (&my_public_key,
3653 sizeof (my_public_key), &my_identity.hashPubKey);
3654 /* setup notification */
3656 notifier = GNUNET_SERVER_notification_context_create (server,
3658 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3659 /* setup transport connection */
3660 transport = GNUNET_TRANSPORT_connect (sched,
3663 &handle_transport_receive,
3664 &handle_transport_notify_connect,
3665 &handle_transport_notify_disconnect);
3666 GNUNET_assert (NULL != transport);
3667 stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3668 GNUNET_SCHEDULER_add_delayed (sched,
3669 GNUNET_TIME_UNIT_FOREVER_REL,
3670 &cleaning_task, NULL);
3671 /* process client requests */
3672 GNUNET_SERVER_add_handlers (server, handlers);
3673 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3674 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3680 * The main function for the transport service.
3682 * @param argc number of arguments from the command line
3683 * @param argv command line arguments
3684 * @return 0 ok, 1 on error
3687 main (int argc, char *const *argv)
3689 return (GNUNET_OK ==
3690 GNUNET_SERVICE_run (argc,
3693 GNUNET_SERVICE_OPTION_NONE,
3694 &run, NULL)) ? 0 : 1;
3697 /* end of gnunet-service-core.c */