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 ("# established sessions"), -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 m = n->encrypted_head;
1325 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1332 GNUNET_assert (size >= m->size);
1333 memcpy (cbuf, &m[1], m->size);
1335 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1338 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1339 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1340 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1341 ret, GNUNET_i2s (&n->peer));
1343 process_encrypted_neighbour_queue (n);
1348 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1349 "Transmission of message of type %u and size %u failed\n",
1350 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1355 consider_free_neighbour (n);
1361 * Check if we have plaintext messages for the specified neighbour
1362 * pending, and if so, consider batching and encrypting them (and
1363 * then trigger processing of the encrypted queue if needed).
1365 * @param n neighbour to check.
1367 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1371 * Check if we have encrypted messages for the specified neighbour
1372 * pending, and if so, check with the transport about sending them
1375 * @param n neighbour to check.
1378 process_encrypted_neighbour_queue (struct Neighbour *n)
1380 struct MessageEntry *m;
1383 return; /* request already pending */
1384 m = n->encrypted_head;
1387 /* encrypted queue empty, try plaintext instead */
1388 process_plaintext_neighbour_queue (n);
1392 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1393 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1395 GNUNET_i2s (&n->peer),
1396 GNUNET_TIME_absolute_get_remaining (m->deadline).
1400 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1403 GNUNET_TIME_absolute_get_remaining
1405 ¬ify_encrypted_transmit_ready,
1409 /* message request too large or duplicate request */
1411 /* discard encrypted message */
1412 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1416 process_encrypted_neighbour_queue (n);
1422 * Decrypt size bytes from in and write the result to out. Use the
1423 * key for inbound traffic of the given neighbour. This function does
1424 * NOT do any integrity-checks on the result.
1426 * @param n neighbour we are receiving from
1427 * @param iv initialization vector to use
1428 * @param in ciphertext
1429 * @param out plaintext
1430 * @param size size of in/out
1431 * @return GNUNET_OK on success
1434 do_decrypt (struct Neighbour *n,
1435 const GNUNET_HashCode * iv,
1436 const void *in, void *out, size_t size)
1438 if (size != (uint16_t) size)
1443 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1444 (n->status != PEER_STATE_KEY_CONFIRMED))
1446 GNUNET_break_op (0);
1447 return GNUNET_SYSERR;
1450 GNUNET_CRYPTO_aes_decrypt (in,
1454 GNUNET_CRYPTO_AesInitializationVector *) iv,
1458 return GNUNET_SYSERR;
1460 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1462 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1463 "Decrypted %u bytes from `%4s' using key %u\n",
1464 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1471 * Select messages for transmission. This heuristic uses a combination
1472 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1473 * and priority-based discard (in case no feasible schedule exist) and
1474 * speculative optimization (defer any kind of transmission until
1475 * we either create a batch of significant size, 25% of max, or until
1476 * we are close to a deadline). Furthermore, when scheduling the
1477 * heuristic also packs as many messages into the batch as possible,
1478 * starting with those with the earliest deadline. Yes, this is fun.
1480 * @param n neighbour to select messages from
1481 * @param size number of bytes to select for transmission
1482 * @param retry_time set to the time when we should try again
1483 * (only valid if this function returns zero)
1484 * @return number of bytes selected, or 0 if we decided to
1485 * defer scheduling overall; in that case, retry_time is set.
1488 select_messages (struct Neighbour *n,
1489 size_t size, struct GNUNET_TIME_Relative *retry_time)
1491 struct MessageEntry *pos;
1492 struct MessageEntry *min;
1493 struct MessageEntry *last;
1494 unsigned int min_prio;
1495 struct GNUNET_TIME_Absolute t;
1496 struct GNUNET_TIME_Absolute now;
1497 struct GNUNET_TIME_Relative delta;
1499 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1502 unsigned int queue_size;
1503 int discard_low_prio;
1505 GNUNET_assert (NULL != n->messages);
1506 now = GNUNET_TIME_absolute_get ();
1507 /* last entry in linked list of messages processed */
1509 /* should we remove the entry with the lowest
1510 priority from consideration for scheduling at the
1521 discard_low_prio = GNUNET_YES;
1522 while (GNUNET_YES == discard_low_prio)
1526 discard_low_prio = GNUNET_NO;
1527 /* calculate number of bytes available for transmission at time "t" */
1528 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1530 /* how many bytes have we (hypothetically) scheduled so far */
1532 /* maximum time we can wait before transmitting anything
1533 and still make all of our deadlines */
1534 slack = MAX_CORK_DELAY;
1536 /* note that we use "*2" here because we want to look
1537 a bit further into the future; much more makes no
1538 sense since new message might be scheduled in the
1540 while ((pos != NULL) && (off < size * 2))
1542 if (pos->do_transmit == GNUNET_YES)
1544 /* already removed from consideration */
1548 if (discard_low_prio == GNUNET_NO)
1550 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1551 if (delta.value > 0)
1553 // FIXME: HUH? Check!
1555 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1558 if (avail < pos->size)
1560 // FIXME: HUH? Check!
1561 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1566 /* update slack, considering both its absolute deadline
1567 and relative deadlines caused by other messages
1568 with their respective load */
1569 slack = GNUNET_TIME_relative_min (slack,
1570 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1572 if (pos->deadline.value <= now.value)
1575 slack = GNUNET_TIME_UNIT_ZERO;
1577 else if (GNUNET_YES == pos->got_slack)
1579 /* should be soon now! */
1580 slack = GNUNET_TIME_relative_min (slack,
1581 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1586 GNUNET_TIME_relative_min (slack,
1587 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1588 pos->got_slack = GNUNET_YES;
1589 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1590 GNUNET_TIME_relative_to_absolute (MAX_CORK_DELAY));
1595 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1596 if (pos->priority <= min_prio)
1598 /* update min for discard */
1599 min_prio = pos->priority;
1604 if (discard_low_prio)
1606 GNUNET_assert (min != NULL);
1607 /* remove lowest-priority entry from consideration */
1608 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1612 /* guard against sending "tiny" messages with large headers without
1614 if ( (slack.value > 0) &&
1616 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1618 /* less than 25% of message would be filled with deadlines still
1619 being met if we delay by one second or more; so just wait for
1620 more data; but do not wait longer than 1s (since we don't want
1621 to delay messages for a really long time either). */
1622 *retry_time = MAX_CORK_DELAY;
1623 /* reset do_transmit values for next time */
1626 pos->do_transmit = GNUNET_NO;
1630 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1631 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1632 (unsigned long long) slack.value,
1634 (unsigned int) size);
1638 /* select marked messages (up to size) for transmission */
1643 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1645 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1650 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1654 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1655 "Selected %u/%u bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1657 queue_size, MAX_PEER_QUEUE_SIZE,
1658 GNUNET_i2s (&n->peer));
1665 * Batch multiple messages into a larger buffer.
1667 * @param n neighbour to take messages from
1668 * @param buf target buffer
1669 * @param size size of buf
1670 * @param deadline set to transmission deadline for the result
1671 * @param retry_time set to the time when we should try again
1672 * (only valid if this function returns zero)
1673 * @param priority set to the priority of the batch
1674 * @return number of bytes written to buf (can be zero)
1677 batch_message (struct Neighbour *n,
1680 struct GNUNET_TIME_Absolute *deadline,
1681 struct GNUNET_TIME_Relative *retry_time,
1682 unsigned int *priority)
1684 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1685 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1686 struct MessageEntry *pos;
1687 struct MessageEntry *prev;
1688 struct MessageEntry *next;
1693 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1694 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1695 if (0 == select_messages (n, size, retry_time))
1698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1699 "No messages selected, will try again in %llu ms\n",
1704 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1705 ntm->distance = htonl (n->last_distance);
1706 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1707 ntm->peer = n->peer;
1711 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1714 if (GNUNET_YES == pos->do_transmit)
1716 GNUNET_assert (pos->size <= size);
1717 /* do notifications */
1718 /* FIXME: track if we have *any* client that wants
1719 full notifications and only do this if that is
1721 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1723 memcpy (&ntm[1], &pos[1], pos->size);
1724 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1725 sizeof (struct GNUNET_MessageHeader));
1726 send_to_all_clients (&ntm->header,
1728 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1732 /* message too large for 'full' notifications, we do at
1733 least the 'hdr' type */
1736 sizeof (struct GNUNET_MessageHeader));
1738 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1740 send_to_all_clients (&ntm->header,
1742 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1745 "Encrypting message of type %u\n",
1746 ntohs(((struct GNUNET_MessageHeader*)&pos[1])->type));
1748 /* copy for encrypted transmission */
1749 memcpy (&buf[ret], &pos[1], pos->size);
1752 *priority += pos->priority;
1754 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1755 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1757 GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1759 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1773 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1774 "Deadline for message batch is %llu ms\n",
1775 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1782 * Remove messages with deadlines that have long expired from
1785 * @param n neighbour to inspect
1788 discard_expired_messages (struct Neighbour *n)
1790 struct MessageEntry *prev;
1791 struct MessageEntry *next;
1792 struct MessageEntry *pos;
1793 struct GNUNET_TIME_Absolute now;
1794 struct GNUNET_TIME_Relative delta;
1796 now = GNUNET_TIME_absolute_get ();
1802 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1803 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1806 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1807 "Message is %llu ms past due, discarding.\n",
1824 * Signature of the main function of a task.
1826 * @param cls closure
1827 * @param tc context information (why was this task triggered now)
1830 retry_plaintext_processing (void *cls,
1831 const struct GNUNET_SCHEDULER_TaskContext *tc)
1833 struct Neighbour *n = cls;
1835 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1836 process_plaintext_neighbour_queue (n);
1841 * Send our key (and encrypted PING) to the other peer.
1843 * @param n the other peer
1845 static void send_key (struct Neighbour *n);
1848 * Task that will retry "send_key" if our previous attempt failed
1852 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1854 struct Neighbour *n = cls;
1857 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1858 "Retrying key transmission to `%4s'\n",
1859 GNUNET_i2s (&n->peer));
1861 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1862 n->set_key_retry_frequency =
1863 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1869 * Check if we have plaintext messages for the specified neighbour
1870 * pending, and if so, consider batching and encrypting them (and
1871 * then trigger processing of the encrypted queue if needed).
1873 * @param n neighbour to check.
1876 process_plaintext_neighbour_queue (struct Neighbour *n)
1878 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1881 struct EncryptedMessage *em; /* encrypted message */
1882 struct EncryptedMessage *ph; /* plaintext header */
1883 struct MessageEntry *me;
1884 unsigned int priority;
1885 struct GNUNET_TIME_Absolute deadline;
1886 struct GNUNET_TIME_Relative retry_time;
1889 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1891 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1892 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1896 case PEER_STATE_DOWN:
1899 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1900 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1901 GNUNET_i2s(&n->peer));
1904 case PEER_STATE_KEY_SENT:
1905 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1906 n->retry_set_key_task
1907 = GNUNET_SCHEDULER_add_delayed (sched,
1908 n->set_key_retry_frequency,
1909 &set_key_retry_task, n);
1911 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1912 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1913 GNUNET_i2s(&n->peer));
1916 case PEER_STATE_KEY_RECEIVED:
1917 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1918 n->retry_set_key_task
1919 = GNUNET_SCHEDULER_add_delayed (sched,
1920 n->set_key_retry_frequency,
1921 &set_key_retry_task, n);
1923 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1924 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1925 GNUNET_i2s(&n->peer));
1928 case PEER_STATE_KEY_CONFIRMED:
1929 /* ready to continue */
1932 discard_expired_messages (n);
1933 if (n->messages == NULL)
1936 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1937 "Plaintext message queue for `%4s' is empty.\n",
1938 GNUNET_i2s(&n->peer));
1940 return; /* no pending messages */
1942 if (n->encrypted_head != NULL)
1945 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1946 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1947 GNUNET_i2s(&n->peer));
1949 return; /* wait for messages already encrypted to be
1952 ph = (struct EncryptedMessage *) pbuf;
1953 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1955 used = sizeof (struct EncryptedMessage);
1956 used += batch_message (n,
1958 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1959 &deadline, &retry_time, &priority);
1960 if (used == sizeof (struct EncryptedMessage))
1963 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1964 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1965 GNUNET_i2s(&n->peer));
1967 /* no messages selected for sending, try again later... */
1968 n->retry_plaintext_task =
1969 GNUNET_SCHEDULER_add_delayed (sched,
1971 &retry_plaintext_processing, n);
1974 #if DEBUG_CORE_QUOTA
1975 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1976 "Sending %u b/s as new limit to peer `%4s'\n",
1977 (unsigned int) ntohl (n->bw_in.value__),
1978 GNUNET_i2s (&n->peer));
1980 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1));
1981 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1982 ph->inbound_bw_limit = n->bw_in;
1983 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1985 /* setup encryption message header */
1986 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1987 me->deadline = deadline;
1988 me->priority = priority;
1990 em = (struct EncryptedMessage *) &me[1];
1991 em->header.size = htons (used);
1992 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1993 em->iv_seed = ph->iv_seed;
1994 esize = used - ENCRYPTED_HEADER_SIZE;
1995 GNUNET_CRYPTO_hash (&ph->sequence_number,
1996 esize - sizeof (GNUNET_HashCode),
1997 &ph->plaintext_hash);
1998 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
2001 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2002 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2004 GNUNET_i2s(&n->peer),
2005 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2007 GNUNET_assert (GNUNET_OK ==
2010 &ph->plaintext_hash,
2011 &em->plaintext_hash, esize));
2012 /* append to transmission list */
2013 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2017 process_encrypted_neighbour_queue (n);
2022 * Function that recalculates the bandwidth quota for the
2023 * given neighbour and transmits it to the transport service.
2025 * @param cls neighbour for the quota update
2029 neighbour_quota_update (void *cls,
2030 const struct GNUNET_SCHEDULER_TaskContext *tc);
2034 * Schedule the task that will recalculate the bandwidth
2035 * quota for this peer (and possibly force a disconnect of
2036 * idle peers by calculating a bandwidth of zero).
2039 schedule_quota_update (struct Neighbour *n)
2041 GNUNET_assert (n->quota_update_task ==
2042 GNUNET_SCHEDULER_NO_TASK);
2043 n->quota_update_task
2044 = GNUNET_SCHEDULER_add_delayed (sched,
2045 QUOTA_UPDATE_FREQUENCY,
2046 &neighbour_quota_update,
2052 * Initialize a new 'struct Neighbour'.
2054 * @param pid ID of the new neighbour
2055 * @return handle for the new neighbour
2057 static struct Neighbour *
2058 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2060 struct Neighbour *n;
2061 struct GNUNET_TIME_Absolute now;
2063 n = GNUNET_malloc (sizeof (struct Neighbour));
2064 n->next = neighbours;
2067 GNUNET_STATISTICS_set (stats, gettext_noop ("# active neighbours"), neighbour_count, GNUNET_NO);
2069 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2070 now = GNUNET_TIME_absolute_get ();
2071 n->encrypt_key_created = now;
2072 n->last_activity = now;
2073 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2074 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2075 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2076 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init ((uint32_t) - 1);
2077 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2078 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2080 neighbour_quota_update (n, NULL);
2086 * Handle CORE_SEND request.
2089 * @param client the client issuing the request
2090 * @param message the "struct SendMessage"
2093 handle_client_send (void *cls,
2094 struct GNUNET_SERVER_Client *client,
2095 const struct GNUNET_MessageHeader *message)
2097 const struct SendMessage *sm;
2098 struct Neighbour *n;
2099 struct MessageEntry *prev;
2100 struct MessageEntry *pos;
2101 struct MessageEntry *e;
2102 struct MessageEntry *min_prio_entry;
2103 struct MessageEntry *min_prio_prev;
2104 unsigned int min_prio;
2105 unsigned int queue_size;
2108 msize = ntohs (message->size);
2110 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2114 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2117 sm = (const struct SendMessage *) message;
2118 msize -= sizeof (struct SendMessage);
2119 n = find_neighbour (&sm->peer);
2121 n = create_neighbour (&sm->peer);
2123 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2124 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2127 GNUNET_i2s (&sm->peer));
2129 /* bound queue size */
2130 discard_expired_messages (n);
2131 min_prio = (unsigned int) -1;
2132 min_prio_entry = NULL;
2133 min_prio_prev = NULL;
2139 if (pos->priority < min_prio)
2141 min_prio_entry = pos;
2142 min_prio_prev = prev;
2143 min_prio = pos->priority;
2149 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2152 if (ntohl(sm->priority) <= min_prio)
2154 /* discard new entry */
2156 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2157 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2159 MAX_PEER_QUEUE_SIZE,
2161 ntohs (message->type));
2164 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2167 /* discard "min_prio_entry" */
2169 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2170 "Queue full, discarding existing older request\n");
2172 if (min_prio_prev == NULL)
2173 n->messages = min_prio_entry->next;
2175 min_prio_prev->next = min_prio_entry->next;
2176 GNUNET_free (min_prio_entry);
2180 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2181 "Adding transmission request for `%4s' of size %u to queue\n",
2182 GNUNET_i2s (&sm->peer),
2185 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2186 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2187 e->priority = ntohl (sm->priority);
2189 memcpy (&e[1], &sm[1], msize);
2191 /* insert, keep list sorted by deadline */
2194 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2205 /* consider scheduling now */
2206 process_plaintext_neighbour_queue (n);
2208 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2213 * Function called when the transport service is ready to
2214 * receive a message. Only resets 'n->th' to NULL.
2216 * @param cls neighbour to use message from
2217 * @param size number of bytes we can transmit
2218 * @param buf where to copy the message
2219 * @return number of bytes transmitted
2222 notify_transport_connect_done (void *cls, size_t size, void *buf)
2224 struct Neighbour *n = cls;
2229 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2230 _("Failed to connect to `%4s': transport failed to connect\n"),
2231 GNUNET_i2s (&n->peer));
2240 * Handle CORE_REQUEST_CONNECT request.
2243 * @param client the client issuing the request
2244 * @param message the "struct ConnectMessage"
2247 handle_client_request_connect (void *cls,
2248 struct GNUNET_SERVER_Client *client,
2249 const struct GNUNET_MessageHeader *message)
2251 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2252 struct Neighbour *n;
2253 struct GNUNET_TIME_Relative timeout;
2255 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2258 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2261 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2262 n = find_neighbour (&cm->peer);
2264 n = create_neighbour (&cm->peer);
2265 if ( (n->is_connected) ||
2267 return; /* already connected, or at least trying */
2268 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2270 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2271 "Core received `%s' request for `%4s', will try to establish connection\n",
2273 GNUNET_i2s (&cm->peer));
2275 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2276 /* ask transport to connect to the peer */
2277 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2279 sizeof (struct GNUNET_MessageHeader), 0,
2281 ¬ify_transport_connect_done,
2283 GNUNET_break (NULL != n->th);
2288 * List of handlers for the messages understood by this
2291 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2292 {&handle_client_init, NULL,
2293 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2294 {&handle_client_request_info, NULL,
2295 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2296 sizeof (struct RequestInfoMessage)},
2297 {&handle_client_send, NULL,
2298 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2299 {&handle_client_request_connect, NULL,
2300 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2301 sizeof (struct ConnectMessage)},
2307 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2308 * the neighbour's struct and retry send_key. Or, if we did not get a
2309 * HELLO, just do nothing.
2311 * @param cls the 'struct Neighbour' to retry sending the key for
2312 * @param peer the peer for which this is the HELLO
2313 * @param hello HELLO message of that peer
2314 * @param trust amount of trust we currently have in that peer
2317 process_hello_retry_send_key (void *cls,
2318 const struct GNUNET_PeerIdentity *peer,
2319 const struct GNUNET_HELLO_Message *hello,
2322 struct Neighbour *n = cls;
2327 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2328 "Entered `process_hello_retry_send_key' and `peer' is NULL!\n");
2331 if (n->public_key != NULL)
2333 GNUNET_STATISTICS_update (stats,
2334 gettext_noop ("# SETKEY messages deferred (need public key)"),
2341 GNUNET_STATISTICS_update (stats,
2342 gettext_noop ("# Delayed connecting due to lack of public key"),
2345 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2346 n->retry_set_key_task
2347 = GNUNET_SCHEDULER_add_delayed (sched,
2348 n->set_key_retry_frequency,
2349 &set_key_retry_task, n);
2355 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2356 "Entered `process_hello_retry_send_key' for peer `%4s'\n",
2359 if (n->public_key != NULL)
2362 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2363 "already have public key for peer %s!! (so why are we here?)\n",
2370 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2371 "Received new `%s' message for `%4s', initiating key exchange.\n",
2376 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2377 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2379 GNUNET_STATISTICS_update (stats,
2380 gettext_noop ("# Error extracting public key from HELLO"),
2383 GNUNET_free (n->public_key);
2384 n->public_key = NULL;
2386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2387 "GNUNET_HELLO_get_key returned awfully\n");
2395 * Send our key (and encrypted PING) to the other peer.
2397 * @param n the other peer
2400 send_key (struct Neighbour *n)
2402 struct SetKeyMessage *sm;
2403 struct MessageEntry *me;
2404 struct PingMessage pp;
2405 struct PingMessage *pm;
2407 if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2411 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2412 "Key exchange in progress with `%4s'.\n",
2413 GNUNET_i2s (&n->peer));
2415 return; /* already in progress */
2417 if (! n->is_connected)
2421 GNUNET_STATISTICS_update (stats,
2422 gettext_noop ("# Asking transport to connect (for SETKEY)"),
2425 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2427 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2428 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2429 ¬ify_encrypted_transmit_ready,
2435 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2436 "Asked to perform key exchange with `%4s'.\n",
2437 GNUNET_i2s (&n->peer));
2439 if (n->public_key == NULL)
2441 /* lookup n's public key, then try again */
2443 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2444 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2445 GNUNET_i2s (&n->peer));
2447 GNUNET_assert (n->pitr == NULL);
2448 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2452 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2453 &process_hello_retry_send_key, n);
2456 /* first, set key message */
2457 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2458 sizeof (struct SetKeyMessage));
2459 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2460 me->priority = SET_KEY_PRIORITY;
2461 me->size = sizeof (struct SetKeyMessage);
2462 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2466 sm = (struct SetKeyMessage *) &me[1];
2467 sm->header.size = htons (sizeof (struct SetKeyMessage));
2468 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2469 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2470 PEER_STATE_KEY_SENT : n->status));
2472 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2473 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2474 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2475 sizeof (struct GNUNET_PeerIdentity));
2476 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2477 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2478 sm->target = n->peer;
2479 GNUNET_assert (GNUNET_OK ==
2480 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2482 GNUNET_CRYPTO_AesSessionKey),
2484 &sm->encrypted_key));
2485 GNUNET_assert (GNUNET_OK ==
2486 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2489 /* second, encrypted PING message */
2490 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2491 sizeof (struct PingMessage));
2492 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2493 me->priority = PING_PRIORITY;
2494 me->size = sizeof (struct PingMessage);
2495 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2499 pm = (struct PingMessage *) &me[1];
2500 pm->header.size = htons (sizeof (struct PingMessage));
2501 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2502 pp.challenge = htonl (n->ping_challenge);
2503 pp.target = n->peer;
2505 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2506 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2507 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2508 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2509 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2511 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2514 &n->peer.hashPubKey,
2517 sizeof (struct PingMessage) -
2518 sizeof (struct GNUNET_MessageHeader));
2522 case PEER_STATE_DOWN:
2523 n->status = PEER_STATE_KEY_SENT;
2525 case PEER_STATE_KEY_SENT:
2527 case PEER_STATE_KEY_RECEIVED:
2529 case PEER_STATE_KEY_CONFIRMED:
2535 GNUNET_STATISTICS_update (stats,
2536 gettext_noop ("# SETKEY and PING messages created"),
2540 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2541 "Have %llu ms left for `%s' transmission.\n",
2542 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2545 /* trigger queue processing */
2546 process_encrypted_neighbour_queue (n);
2547 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2548 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2549 n->retry_set_key_task
2550 = GNUNET_SCHEDULER_add_delayed (sched,
2551 n->set_key_retry_frequency,
2552 &set_key_retry_task, n);
2557 * We received a SET_KEY message. Validate and update
2558 * our key material and status.
2560 * @param n the neighbour from which we received message m
2561 * @param m the set key message we received
2564 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2568 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2569 * the neighbour's struct and retry handling the set_key message. Or,
2570 * if we did not get a HELLO, just free the set key message.
2572 * @param cls pointer to the set key message
2573 * @param peer the peer for which this is the HELLO
2574 * @param hello HELLO message of that peer
2575 * @param trust amount of trust we currently have in that peer
2578 process_hello_retry_handle_set_key (void *cls,
2579 const struct GNUNET_PeerIdentity *peer,
2580 const struct GNUNET_HELLO_Message *hello,
2583 struct Neighbour *n = cls;
2584 struct SetKeyMessage *sm = n->skm;
2593 if (n->public_key != NULL)
2594 return; /* multiple HELLOs match!? */
2596 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2597 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2599 GNUNET_break_op (0);
2600 GNUNET_free (n->public_key);
2601 n->public_key = NULL;
2605 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2606 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2607 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2609 handle_set_key (n, sm);
2614 * We received a PING message. Validate and transmit
2617 * @param n sender of the PING
2618 * @param m the encrypted PING message itself
2621 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2623 struct PingMessage t;
2624 struct PongMessage tx;
2625 struct PongMessage *tp;
2626 struct MessageEntry *me;
2629 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2630 "Core service receives `%s' request from `%4s'.\n",
2631 "PING", GNUNET_i2s (&n->peer));
2635 &my_identity.hashPubKey,
2638 sizeof (struct PingMessage) -
2639 sizeof (struct GNUNET_MessageHeader)))
2642 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2643 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2645 GNUNET_i2s (&t.target),
2646 ntohl (t.challenge), n->decrypt_key.crc32);
2647 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2648 "Target of `%s' request is `%4s'.\n",
2649 "PING", GNUNET_i2s (&t.target));
2651 GNUNET_STATISTICS_update (stats,
2652 gettext_noop ("# PING messages decrypted"),
2655 if (0 != memcmp (&t.target,
2656 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2658 GNUNET_break_op (0);
2661 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2662 sizeof (struct PongMessage));
2663 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2667 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2668 me->priority = PONG_PRIORITY;
2669 me->size = sizeof (struct PongMessage);
2670 tx.reserved = htonl (0);
2671 tx.inbound_bw_limit = n->bw_in;
2672 tx.challenge = t.challenge;
2673 tx.target = t.target;
2674 tp = (struct PongMessage *) &me[1];
2675 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2676 tp->header.size = htons (sizeof (struct PongMessage));
2678 &my_identity.hashPubKey,
2681 sizeof (struct PongMessage) -
2682 sizeof (struct GNUNET_MessageHeader));
2683 GNUNET_STATISTICS_update (stats,
2684 gettext_noop ("# PONG messages created"),
2688 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2689 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2690 ntohl (t.challenge), n->encrypt_key.crc32);
2692 /* trigger queue processing */
2693 process_encrypted_neighbour_queue (n);
2698 * We received a PONG message. Validate and update our status.
2700 * @param n sender of the PONG
2701 * @param m the encrypted PONG message itself
2704 handle_pong (struct Neighbour *n,
2705 const struct PongMessage *m)
2707 struct PongMessage t;
2708 struct ConnectNotifyMessage cnm;
2711 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2712 "Core service receives `%s' request from `%4s'.\n",
2713 "PONG", GNUNET_i2s (&n->peer));
2717 &n->peer.hashPubKey,
2720 sizeof (struct PongMessage) -
2721 sizeof (struct GNUNET_MessageHeader)))
2723 GNUNET_break_op (0);
2726 GNUNET_STATISTICS_update (stats,
2727 gettext_noop ("# PONG messages decrypted"),
2730 if (0 != ntohl (t.reserved))
2732 GNUNET_break_op (0);
2736 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2737 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2739 GNUNET_i2s (&t.target),
2740 ntohl (t.challenge), n->decrypt_key.crc32);
2742 if ((0 != memcmp (&t.target,
2744 sizeof (struct GNUNET_PeerIdentity))) ||
2745 (n->ping_challenge != ntohl (t.challenge)))
2747 /* PONG malformed */
2749 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2750 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2751 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2752 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2753 "Received malformed `%s' received from `%4s' with challenge %u\n",
2754 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2756 GNUNET_break_op (0);
2761 case PEER_STATE_DOWN:
2762 GNUNET_break (0); /* should be impossible */
2764 case PEER_STATE_KEY_SENT:
2765 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2767 case PEER_STATE_KEY_RECEIVED:
2768 GNUNET_STATISTICS_update (stats,
2769 gettext_noop ("# Session keys confirmed via PONG"),
2772 n->status = PEER_STATE_KEY_CONFIRMED;
2773 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2775 n->bw_out_external_limit = t.inbound_bw_limit;
2776 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2777 n->bw_out_internal_limit);
2778 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2780 GNUNET_TRANSPORT_set_quota (transport,
2784 GNUNET_TIME_UNIT_FOREVER_REL,
2788 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2789 "Confirmed key via `%s' message for peer `%4s'\n",
2790 "PONG", GNUNET_i2s (&n->peer));
2792 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2794 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2795 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2797 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2798 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2799 cnm.distance = htonl (n->last_distance);
2800 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2802 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2803 process_encrypted_neighbour_queue (n);
2805 case PEER_STATE_KEY_CONFIRMED:
2806 n->last_activity = GNUNET_TIME_absolute_get ();
2807 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2808 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2810 = GNUNET_SCHEDULER_add_delayed (sched,
2811 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2823 * We received a SET_KEY message. Validate and update
2824 * our key material and status.
2826 * @param n the neighbour from which we received message m
2827 * @param m the set key message we received
2830 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2832 struct SetKeyMessage *m_cpy;
2833 struct GNUNET_TIME_Absolute t;
2834 struct GNUNET_CRYPTO_AesSessionKey k;
2835 struct PingMessage *ping;
2836 struct PongMessage *pong;
2837 enum PeerStateMachine sender_status;
2840 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2841 "Core service receives `%s' request from `%4s'.\n",
2842 "SET_KEY", GNUNET_i2s (&n->peer));
2844 if (n->public_key == NULL)
2846 if (n->pitr != NULL)
2849 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2850 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2856 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2857 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2859 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2860 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2861 /* lookup n's public key, then try again */
2862 GNUNET_assert (n->skm == NULL);
2864 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2868 GNUNET_TIME_UNIT_MINUTES,
2869 &process_hello_retry_handle_set_key, n);
2870 GNUNET_STATISTICS_update (stats,
2871 gettext_noop ("# SETKEY messages deferred (need public key)"),
2876 if (0 != memcmp (&m->target,
2878 sizeof (struct GNUNET_PeerIdentity)))
2880 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2881 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
2883 GNUNET_i2s (&m->target));
2886 if ((ntohl (m->purpose.size) !=
2887 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2888 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2889 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2890 sizeof (struct GNUNET_PeerIdentity)) ||
2892 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2893 &m->purpose, &m->signature, n->public_key)))
2895 /* invalid signature */
2896 GNUNET_break_op (0);
2899 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2900 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2901 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2902 (t.value < n->decrypt_key_created.value))
2904 /* this could rarely happen due to massive re-ordering of
2905 messages on the network level, but is most likely either
2906 a bug or some adversary messing with us. Report. */
2907 GNUNET_break_op (0);
2911 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2912 "Decrypting key material.\n");
2914 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2917 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2918 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2919 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2921 /* failed to decrypt !? */
2922 GNUNET_break_op (0);
2925 GNUNET_STATISTICS_update (stats,
2926 gettext_noop ("# SETKEY messages decrypted"),
2930 if (n->decrypt_key_created.value != t.value)
2932 /* fresh key, reset sequence numbers */
2933 n->last_sequence_number_received = 0;
2934 n->last_packets_bitmap = 0;
2935 n->decrypt_key_created = t;
2937 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2940 case PEER_STATE_DOWN:
2941 n->status = PEER_STATE_KEY_RECEIVED;
2943 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2944 "Responding to `%s' with my own key.\n", "SET_KEY");
2948 case PEER_STATE_KEY_SENT:
2949 case PEER_STATE_KEY_RECEIVED:
2950 n->status = PEER_STATE_KEY_RECEIVED;
2951 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2952 (sender_status != PEER_STATE_KEY_CONFIRMED))
2955 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2956 "Responding to `%s' with my own key (other peer has status %u).\n",
2957 "SET_KEY", sender_status);
2962 case PEER_STATE_KEY_CONFIRMED:
2963 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2964 (sender_status != PEER_STATE_KEY_CONFIRMED))
2967 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2968 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2969 "SET_KEY", sender_status);
2978 if (n->pending_ping != NULL)
2980 ping = n->pending_ping;
2981 n->pending_ping = NULL;
2982 handle_ping (n, ping);
2985 if (n->pending_pong != NULL)
2987 pong = n->pending_pong;
2988 n->pending_pong = NULL;
2989 handle_pong (n, pong);
2996 * Send a P2P message to a client.
2998 * @param sender who sent us the message?
2999 * @param client who should we give the message to?
3000 * @param m contains the message to transmit
3001 * @param msize number of bytes in buf to transmit
3004 send_p2p_message_to_client (struct Neighbour *sender,
3005 struct Client *client,
3006 const void *m, size_t msize)
3008 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3009 struct NotifyTrafficMessage *ntm;
3012 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3013 "Core service passes message from `%4s' of type %u to client.\n",
3014 GNUNET_i2s(&sender->peer),
3015 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3017 ntm = (struct NotifyTrafficMessage *) buf;
3018 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3019 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3020 ntm->distance = htonl (sender->last_distance);
3021 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3022 ntm->peer = sender->peer;
3023 memcpy (&ntm[1], m, msize);
3024 send_to_client (client, &ntm->header, GNUNET_YES);
3029 * Deliver P2P message to interested clients.
3031 * @param sender who sent us the message?
3032 * @param m the message
3033 * @param msize size of the message (including header)
3036 deliver_message (struct Neighbour *sender,
3037 const struct GNUNET_MessageHeader *m, size_t msize)
3039 struct Client *cpos;
3045 type = ntohs (m->type);
3047 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3048 "Received encapsulated message of type %u from `%4s'\n",
3050 GNUNET_i2s (&sender->peer));
3052 dropped = GNUNET_YES;
3054 while (cpos != NULL)
3056 deliver_full = GNUNET_NO;
3057 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3058 deliver_full = GNUNET_YES;
3061 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3063 if (type != cpos->types[tpos])
3065 deliver_full = GNUNET_YES;
3069 if (GNUNET_YES == deliver_full)
3071 send_p2p_message_to_client (sender, cpos, m, msize);
3072 dropped = GNUNET_NO;
3074 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3076 send_p2p_message_to_client (sender, cpos, m,
3077 sizeof (struct GNUNET_MessageHeader));
3081 if (dropped == GNUNET_YES)
3084 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3085 "Message of type %u from `%4s' not delivered to any client.\n",
3087 GNUNET_i2s (&sender->peer));
3089 /* FIXME: stats... */
3095 * Align P2P message and then deliver to interested clients.
3097 * @param sender who sent us the message?
3098 * @param buffer unaligned (!) buffer containing message
3099 * @param msize size of the message (including header)
3102 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
3106 /* TODO: call to statistics? */
3107 memcpy (abuf, buffer, msize);
3108 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
3113 * Deliver P2P messages to interested clients.
3115 * @param sender who sent us the message?
3116 * @param buffer buffer containing messages, can be modified
3117 * @param buffer_size size of the buffer (overall)
3118 * @param offset offset where messages in the buffer start
3121 deliver_messages (struct Neighbour *sender,
3122 const char *buffer, size_t buffer_size, size_t offset)
3124 struct GNUNET_MessageHeader *mhp;
3125 struct GNUNET_MessageHeader mh;
3129 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
3131 if (0 != offset % sizeof (uint16_t))
3133 /* outch, need to copy to access header */
3134 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
3139 /* can access header directly */
3140 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
3142 msize = ntohs (mhp->size);
3143 if (msize + offset > buffer_size)
3145 /* malformed message, header says it is larger than what
3146 would fit into the overall buffer */
3147 GNUNET_break_op (0);
3150 #if HAVE_UNALIGNED_64_ACCESS
3151 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
3153 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
3155 if (GNUNET_YES == need_align)
3156 align_and_deliver (sender, &buffer[offset], msize);
3158 deliver_message (sender,
3159 (const struct GNUNET_MessageHeader *)
3160 &buffer[offset], msize);
3167 * We received an encrypted message. Decrypt, validate and
3168 * pass on to the appropriate clients.
3171 handle_encrypted_message (struct Neighbour *n,
3172 const struct EncryptedMessage *m)
3174 size_t size = ntohs (m->header.size);
3176 struct EncryptedMessage *pt; /* plaintext */
3180 struct GNUNET_TIME_Absolute t;
3184 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3185 "Core service receives `%s' request from `%4s'.\n",
3186 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3188 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3194 &buf[ENCRYPTED_HEADER_SIZE],
3195 size - ENCRYPTED_HEADER_SIZE))
3197 pt = (struct EncryptedMessage *) buf;
3200 GNUNET_CRYPTO_hash (&pt->sequence_number,
3201 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3202 if (0 != memcmp (&ph,
3203 &pt->plaintext_hash,
3204 sizeof (GNUNET_HashCode)))
3206 /* checksum failed */
3207 GNUNET_break_op (0);
3211 /* validate sequence number */
3212 snum = ntohl (pt->sequence_number);
3213 if (n->last_sequence_number_received == snum)
3215 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3216 "Received duplicate message, ignoring.\n");
3217 /* duplicate, ignore */
3220 if ((n->last_sequence_number_received > snum) &&
3221 (n->last_sequence_number_received - snum > 32))
3223 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3224 "Received ancient out of sequence message, ignoring.\n");
3225 /* ancient out of sequence, ignore */
3228 if (n->last_sequence_number_received > snum)
3230 unsigned int rotbit =
3231 1 << (n->last_sequence_number_received - snum - 1);
3232 if ((n->last_packets_bitmap & rotbit) != 0)
3234 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3235 "Received duplicate message, ignoring.\n");
3236 /* duplicate, ignore */
3239 n->last_packets_bitmap |= rotbit;
3241 if (n->last_sequence_number_received < snum)
3243 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3244 n->last_sequence_number_received = snum;
3247 /* check timestamp */
3248 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3249 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3251 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3253 ("Message received far too old (%llu ms). Content ignored.\n"),
3254 GNUNET_TIME_absolute_get_duration (t).value);
3258 /* process decrypted message(s) */
3259 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3261 #if DEBUG_CORE_SET_QUOTA
3262 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3263 "Received %u b/s as new inbound limit for peer `%4s'\n",
3264 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3265 GNUNET_i2s (&n->peer));
3267 n->bw_out_external_limit = pt->inbound_bw_limit;
3268 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3269 n->bw_out_internal_limit);
3270 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3272 GNUNET_TRANSPORT_set_quota (transport,
3276 GNUNET_TIME_UNIT_FOREVER_REL,
3279 n->last_activity = GNUNET_TIME_absolute_get ();
3280 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3281 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3283 = GNUNET_SCHEDULER_add_delayed (sched,
3284 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3287 off = sizeof (struct EncryptedMessage);
3288 deliver_messages (n, buf, size, off);
3293 * Function called by the transport for each received message.
3295 * @param cls closure
3296 * @param peer (claimed) identity of the other peer
3297 * @param message the message
3298 * @param latency estimated latency for communicating with the
3299 * given peer (round-trip)
3300 * @param distance in overlay hops, as given by transport plugin
3303 handle_transport_receive (void *cls,
3304 const struct GNUNET_PeerIdentity *peer,
3305 const struct GNUNET_MessageHeader *message,
3306 struct GNUNET_TIME_Relative latency,
3307 unsigned int distance)
3309 struct Neighbour *n;
3310 struct GNUNET_TIME_Absolute now;
3316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3317 "Received message of type %u from `%4s', demultiplexing.\n",
3318 ntohs (message->type), GNUNET_i2s (peer));
3320 n = find_neighbour (peer);
3322 n = create_neighbour (peer);
3325 n->last_latency = latency;
3326 n->last_distance = distance;
3327 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3328 type = ntohs (message->type);
3329 size = ntohs (message->size);
3332 "Received message of type %u from `%4s'\n",
3338 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3339 if (size != sizeof (struct SetKeyMessage))
3341 GNUNET_break_op (0);
3344 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3345 handle_set_key (n, (const struct SetKeyMessage *) message);
3347 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3348 if (size < sizeof (struct EncryptedMessage) +
3349 sizeof (struct GNUNET_MessageHeader))
3351 GNUNET_break_op (0);
3354 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3355 (n->status != PEER_STATE_KEY_CONFIRMED))
3357 GNUNET_break_op (0);
3358 /* blacklist briefly (?); might help recover (?) */
3359 GNUNET_TRANSPORT_blacklist (sched, cfg,
3361 GNUNET_TIME_UNIT_SECONDS,
3362 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3367 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3369 case GNUNET_MESSAGE_TYPE_CORE_PING:
3370 if (size != sizeof (struct PingMessage))
3372 GNUNET_break_op (0);
3375 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3376 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3377 (n->status != PEER_STATE_KEY_CONFIRMED))
3380 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3381 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3382 "PING", GNUNET_i2s (&n->peer));
3384 GNUNET_free_non_null (n->pending_ping);
3385 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3386 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3389 handle_ping (n, (const struct PingMessage *) message);
3391 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3392 if (size != sizeof (struct PongMessage))
3394 GNUNET_break_op (0);
3397 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3398 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3399 (n->status != PEER_STATE_KEY_CONFIRMED) )
3402 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3403 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3404 "PONG", GNUNET_i2s (&n->peer));
3406 GNUNET_free_non_null (n->pending_pong);
3407 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3408 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3411 handle_pong (n, (const struct PongMessage *) message);
3414 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3415 _("Unsupported message of type %u received.\n"), type);
3418 if (n->status == PEER_STATE_KEY_CONFIRMED)
3420 now = GNUNET_TIME_absolute_get ();
3421 n->last_activity = now;
3424 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3425 n->time_established = now;
3427 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3428 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3430 = GNUNET_SCHEDULER_add_delayed (sched,
3431 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3439 * Function that recalculates the bandwidth quota for the
3440 * given neighbour and transmits it to the transport service.
3442 * @param cls neighbour for the quota update
3446 neighbour_quota_update (void *cls,
3447 const struct GNUNET_SCHEDULER_TaskContext *tc)
3449 struct Neighbour *n = cls;
3450 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3453 unsigned long long distributable;
3454 uint64_t need_per_peer;
3455 uint64_t need_per_second;
3457 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3458 /* calculate relative preference among all neighbours;
3459 divides by a bit more to avoid division by zero AND to
3460 account for possibility of new neighbours joining any time
3461 AND to convert to double... */
3462 if (preference_sum == 0)
3464 pref_rel = 1.0 / (double) neighbour_count;
3468 pref_rel = n->current_preference / preference_sum;
3470 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3471 GNUNET_TIME_UNIT_SECONDS);
3472 need_per_second = need_per_peer * neighbour_count;
3474 if (bandwidth_target_out_bps > need_per_second)
3475 distributable = bandwidth_target_out_bps - need_per_second;
3476 share = distributable * pref_rel;
3477 if (share + need_per_peer > ( (uint32_t)-1))
3478 q_in = GNUNET_BANDWIDTH_value_init ((uint32_t) -1);
3480 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3481 /* check if we want to disconnect for good due to inactivity */
3482 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3483 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3486 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3487 "Forcing disconnect of `%4s' due to inactivity (?).\n",
3488 GNUNET_i2s (&n->peer));
3490 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3492 #if DEBUG_CORE_QUOTA
3493 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3494 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3495 GNUNET_i2s (&n->peer),
3496 (unsigned int) ntohl (q_in.value__),
3497 bandwidth_target_out_bps,
3498 (unsigned int) ntohl (n->bw_in.value__),
3499 (unsigned int) ntohl (n->bw_out.value__),
3500 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3502 if (n->bw_in.value__ != q_in.value__)
3505 GNUNET_TRANSPORT_set_quota (transport,
3509 GNUNET_TIME_UNIT_FOREVER_REL,
3512 schedule_quota_update (n);
3517 * Function called by transport to notify us that
3518 * a peer connected to us (on the network level).
3520 * @param cls closure
3521 * @param peer the peer that connected
3522 * @param latency current latency of the connection
3523 * @param distance in overlay hops, as given by transport plugin
3526 handle_transport_notify_connect (void *cls,
3527 const struct GNUNET_PeerIdentity *peer,
3528 struct GNUNET_TIME_Relative latency,
3529 unsigned int distance)
3531 struct Neighbour *n;
3532 struct ConnectNotifyMessage cnm;
3534 n = find_neighbour (peer);
3537 if (n->is_connected)
3539 /* duplicate connect notification!? */
3546 n = create_neighbour (peer);
3548 GNUNET_STATISTICS_update (stats,
3549 gettext_noop ("# peers connected"),
3552 n->is_connected = GNUNET_YES;
3553 n->last_latency = latency;
3554 n->last_distance = distance;
3555 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3558 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3562 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3563 "Received connection from `%4s'.\n",
3564 GNUNET_i2s (&n->peer));
3566 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3567 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3568 cnm.distance = htonl (n->last_distance);
3569 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3571 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3572 GNUNET_TRANSPORT_set_quota (transport,
3576 GNUNET_TIME_UNIT_FOREVER_REL,
3583 * Function called by transport telling us that a peer
3586 * @param cls closure
3587 * @param peer the peer that disconnected
3590 handle_transport_notify_disconnect (void *cls,
3591 const struct GNUNET_PeerIdentity *peer)
3593 struct DisconnectNotifyMessage cnm;
3594 struct Neighbour *n;
3597 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3598 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3600 n = find_neighbour (peer);
3606 GNUNET_break (n->is_connected);
3607 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3608 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3610 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3611 n->is_connected = GNUNET_NO;
3612 GNUNET_STATISTICS_update (stats,
3613 gettext_noop ("# peers connected"),
3620 * Last task run during shutdown. Disconnects us from
3624 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3626 struct Neighbour *n;
3630 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3631 "Core service shutting down.\n");
3633 GNUNET_assert (transport != NULL);
3634 GNUNET_TRANSPORT_disconnect (transport);
3636 while (NULL != (n = neighbours))
3638 neighbours = n->next;
3639 GNUNET_assert (neighbour_count > 0);
3643 GNUNET_STATISTICS_set (stats, gettext_noop ("# active neighbours"), neighbour_count, GNUNET_NO);
3644 GNUNET_SERVER_notification_context_destroy (notifier);
3646 while (NULL != (c = clients))
3647 handle_client_disconnect (NULL, c->client_handle);
3648 if (my_private_key != NULL)
3649 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3651 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3656 * Initiate core service.
3658 * @param cls closure
3659 * @param s scheduler to use
3660 * @param serv the initialized server
3661 * @param c configuration to use
3665 struct GNUNET_SCHEDULER_Handle *s,
3666 struct GNUNET_SERVER_Handle *serv,
3667 const struct GNUNET_CONFIGURATION_Handle *c)
3673 /* parse configuration */
3676 GNUNET_CONFIGURATION_get_value_number (c,
3679 &bandwidth_target_in_bps)) ||
3681 GNUNET_CONFIGURATION_get_value_number (c,
3684 &bandwidth_target_out_bps)) ||
3686 GNUNET_CONFIGURATION_get_value_filename (c,
3688 "HOSTKEY", &keyfile)))
3690 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3692 ("Core service is lacking key configuration settings. Exiting.\n"));
3693 GNUNET_SCHEDULER_shutdown (s);
3696 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3697 GNUNET_free (keyfile);
3698 if (my_private_key == NULL)
3700 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3701 _("Core service could not access hostkey. Exiting.\n"));
3702 GNUNET_SCHEDULER_shutdown (s);
3705 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3706 GNUNET_CRYPTO_hash (&my_public_key,
3707 sizeof (my_public_key), &my_identity.hashPubKey);
3708 /* setup notification */
3710 notifier = GNUNET_SERVER_notification_context_create (server,
3712 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3713 /* setup transport connection */
3714 transport = GNUNET_TRANSPORT_connect (sched,
3717 &handle_transport_receive,
3718 &handle_transport_notify_connect,
3719 &handle_transport_notify_disconnect);
3720 GNUNET_assert (NULL != transport);
3721 stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3722 GNUNET_SCHEDULER_add_delayed (sched,
3723 GNUNET_TIME_UNIT_FOREVER_REL,
3724 &cleaning_task, NULL);
3725 /* process client requests */
3726 GNUNET_SERVER_add_handlers (server, handlers);
3727 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3728 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3734 * The main function for the transport service.
3736 * @param argc number of arguments from the command line
3737 * @param argv command line arguments
3738 * @return 0 ok, 1 on error
3741 main (int argc, char *const *argv)
3743 return (GNUNET_OK ==
3744 GNUNET_SERVICE_run (argc,
3747 GNUNET_SERVICE_OPTION_NONE,
3748 &run, NULL)) ? 0 : 1;
3751 /* end of gnunet-service-core.c */