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_YES
50 * Receive and send buffer windows grow over time. For
51 * how long can 'unused' bandwidth accumulate before we
52 * need to cap it? (specified in seconds).
54 #define MAX_WINDOW_TIME_S (5 * 60)
57 * How many messages do we queue up at most for optional
58 * notifications to a client? (this can cause notifications
59 * about outgoing messages to be dropped).
61 #define MAX_NOTIFY_QUEUE 16
64 * Minimum bandwidth (out) to assign to any connected peer.
65 * Should be rather low; values larger than DEFAULT_BW_IN_OUT make no
68 #define MIN_BANDWIDTH_PER_PEER GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT
71 * After how much time past the "official" expiration time do
72 * we discard messages? Should not be zero since we may
73 * intentionally defer transmission until close to the deadline
74 * and then may be slightly past the deadline due to inaccuracy
75 * in sleep and our own CPU consumption.
77 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
80 * 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 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1070 "Destroying neighbour entry for peer `%4s'\n",
1071 GNUNET_i2s (&n->peer));
1072 if (n->pitr != NULL)
1074 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1079 GNUNET_free (n->skm);
1082 while (NULL != (m = n->messages))
1084 n->messages = m->next;
1087 while (NULL != (m = n->encrypted_head))
1089 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1096 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1099 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1100 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1101 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1102 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1103 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1104 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1105 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1106 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1107 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1108 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1109 if (n->status == PEER_STATE_KEY_CONFIRMED)
1110 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1111 GNUNET_free_non_null (n->public_key);
1112 GNUNET_free_non_null (n->pending_ping);
1113 GNUNET_free_non_null (n->pending_pong);
1119 * Check if we have encrypted messages for the specified neighbour
1120 * pending, and if so, check with the transport about sending them
1123 * @param n neighbour to check.
1125 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1129 * Encrypt size bytes from in and write the result to out. Use the
1130 * key for outbound traffic of the given neighbour.
1132 * @param n neighbour we are sending to
1133 * @param iv initialization vector to use
1134 * @param in ciphertext
1135 * @param out plaintext
1136 * @param size size of in/out
1137 * @return GNUNET_OK on success
1140 do_encrypt (struct Neighbour *n,
1141 const GNUNET_HashCode * iv,
1142 const void *in, void *out, size_t size)
1144 if (size != (uint16_t) size)
1149 GNUNET_assert (size ==
1150 GNUNET_CRYPTO_aes_encrypt (in,
1154 GNUNET_CRYPTO_AesInitializationVector
1156 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1159 "Encrypted %u bytes for `%4s' using key %u\n", size,
1160 GNUNET_i2s (&n->peer), n->encrypt_key.crc32);
1167 * Consider freeing the given neighbour since we may not need
1168 * to keep it around anymore.
1170 * @param n neighbour to consider discarding
1173 consider_free_neighbour (struct Neighbour *n);
1177 * Task triggered when a neighbour entry is about to time out
1178 * (and we should prevent this by sending a PING).
1180 * @param cls the 'struct Neighbour'
1181 * @param tc scheduler context (not used)
1184 send_keep_alive (void *cls,
1185 const struct GNUNET_SCHEDULER_TaskContext *tc)
1187 struct Neighbour *n = cls;
1188 struct GNUNET_TIME_Relative retry;
1189 struct GNUNET_TIME_Relative left;
1190 struct MessageEntry *me;
1191 struct PingMessage pp;
1192 struct PingMessage *pm;
1194 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1196 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1197 sizeof (struct PingMessage));
1198 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1199 me->priority = PING_PRIORITY;
1200 me->size = sizeof (struct PingMessage);
1201 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1205 pm = (struct PingMessage *) &me[1];
1206 pm->header.size = htons (sizeof (struct PingMessage));
1207 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1208 pp.challenge = htonl (n->ping_challenge);
1209 pp.target = n->peer;
1211 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1212 "Encrypting `%s' and `%s' messages for `%4s'.\n",
1213 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
1214 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1215 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
1217 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
1220 &n->peer.hashPubKey,
1223 sizeof (struct PingMessage) -
1224 sizeof (struct GNUNET_MessageHeader));
1225 process_encrypted_neighbour_queue (n);
1226 /* reschedule PING job */
1227 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1228 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1229 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1230 MIN_PING_FREQUENCY);
1232 = GNUNET_SCHEDULER_add_delayed (sched,
1241 * Task triggered when a neighbour entry might have gotten stale.
1243 * @param cls the 'struct Neighbour'
1244 * @param tc scheduler context (not used)
1247 consider_free_task (void *cls,
1248 const struct GNUNET_SCHEDULER_TaskContext *tc)
1250 struct Neighbour *n = cls;
1252 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1253 consider_free_neighbour (n);
1258 * Consider freeing the given neighbour since we may not need
1259 * to keep it around anymore.
1261 * @param n neighbour to consider discarding
1264 consider_free_neighbour (struct Neighbour *n)
1266 struct Neighbour *pos;
1267 struct Neighbour *prev;
1268 struct GNUNET_TIME_Relative left;
1270 if ( (n->th != NULL) ||
1271 (n->pitr != NULL) ||
1272 (n->status == PEER_STATE_KEY_CONFIRMED) ||
1273 (GNUNET_YES == n->is_connected) )
1274 return; /* no chance */
1276 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1277 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1280 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1281 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1282 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1284 &consider_free_task,
1288 /* actually free the neighbour... */
1297 neighbours = n->next;
1299 prev->next = n->next;
1300 GNUNET_assert (neighbour_count > 0);
1302 GNUNET_STATISTICS_set (stats,
1303 gettext_noop ("# active neighbours"),
1311 * Function called when the transport service is ready to
1312 * receive an encrypted message for the respective peer
1314 * @param cls neighbour to use message from
1315 * @param size number of bytes we can transmit
1316 * @param buf where to copy the message
1317 * @return number of bytes transmitted
1320 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1322 struct Neighbour *n = cls;
1323 struct MessageEntry *m;
1328 m = n->encrypted_head;
1331 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1338 GNUNET_assert (size >= m->size);
1339 memcpy (cbuf, &m[1], m->size);
1341 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1344 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1345 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1346 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1347 ret, GNUNET_i2s (&n->peer));
1349 process_encrypted_neighbour_queue (n);
1354 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1355 "Transmission of message of type %u and size %u failed\n",
1356 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1361 consider_free_neighbour (n);
1367 * Check if we have plaintext messages for the specified neighbour
1368 * pending, and if so, consider batching and encrypting them (and
1369 * then trigger processing of the encrypted queue if needed).
1371 * @param n neighbour to check.
1373 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1377 * Check if we have encrypted messages for the specified neighbour
1378 * pending, and if so, check with the transport about sending them
1381 * @param n neighbour to check.
1384 process_encrypted_neighbour_queue (struct Neighbour *n)
1386 struct MessageEntry *m;
1389 return; /* request already pending */
1390 m = n->encrypted_head;
1393 /* encrypted queue empty, try plaintext instead */
1394 process_plaintext_neighbour_queue (n);
1398 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1399 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1401 GNUNET_i2s (&n->peer),
1402 GNUNET_TIME_absolute_get_remaining (m->deadline).
1406 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1409 GNUNET_TIME_absolute_get_remaining
1411 ¬ify_encrypted_transmit_ready,
1415 /* message request too large or duplicate request */
1417 /* discard encrypted message */
1418 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1422 process_encrypted_neighbour_queue (n);
1428 * Decrypt size bytes from in and write the result to out. Use the
1429 * key for inbound traffic of the given neighbour. This function does
1430 * NOT do any integrity-checks on the result.
1432 * @param n neighbour we are receiving from
1433 * @param iv initialization vector to use
1434 * @param in ciphertext
1435 * @param out plaintext
1436 * @param size size of in/out
1437 * @return GNUNET_OK on success
1440 do_decrypt (struct Neighbour *n,
1441 const GNUNET_HashCode * iv,
1442 const void *in, void *out, size_t size)
1444 if (size != (uint16_t) size)
1449 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1450 (n->status != PEER_STATE_KEY_CONFIRMED))
1452 GNUNET_break_op (0);
1453 return GNUNET_SYSERR;
1456 GNUNET_CRYPTO_aes_decrypt (in,
1460 GNUNET_CRYPTO_AesInitializationVector *) iv,
1464 return GNUNET_SYSERR;
1466 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1468 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1469 "Decrypted %u bytes from `%4s' using key %u\n",
1470 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1477 * Select messages for transmission. This heuristic uses a combination
1478 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1479 * and priority-based discard (in case no feasible schedule exist) and
1480 * speculative optimization (defer any kind of transmission until
1481 * we either create a batch of significant size, 25% of max, or until
1482 * we are close to a deadline). Furthermore, when scheduling the
1483 * heuristic also packs as many messages into the batch as possible,
1484 * starting with those with the earliest deadline. Yes, this is fun.
1486 * @param n neighbour to select messages from
1487 * @param size number of bytes to select for transmission
1488 * @param retry_time set to the time when we should try again
1489 * (only valid if this function returns zero)
1490 * @return number of bytes selected, or 0 if we decided to
1491 * defer scheduling overall; in that case, retry_time is set.
1494 select_messages (struct Neighbour *n,
1495 size_t size, struct GNUNET_TIME_Relative *retry_time)
1497 struct MessageEntry *pos;
1498 struct MessageEntry *min;
1499 struct MessageEntry *last;
1500 unsigned int min_prio;
1501 struct GNUNET_TIME_Absolute t;
1502 struct GNUNET_TIME_Absolute now;
1503 struct GNUNET_TIME_Relative delta;
1505 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1508 unsigned int queue_size;
1509 int discard_low_prio;
1511 GNUNET_assert (NULL != n->messages);
1512 now = GNUNET_TIME_absolute_get ();
1513 /* last entry in linked list of messages processed */
1515 /* should we remove the entry with the lowest
1516 priority from consideration for scheduling at the
1527 discard_low_prio = GNUNET_YES;
1528 while (GNUNET_YES == discard_low_prio)
1532 discard_low_prio = GNUNET_NO;
1533 /* calculate number of bytes available for transmission at time "t" */
1534 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1536 /* how many bytes have we (hypothetically) scheduled so far */
1538 /* maximum time we can wait before transmitting anything
1539 and still make all of our deadlines */
1540 slack = MAX_CORK_DELAY;
1542 /* note that we use "*2" here because we want to look
1543 a bit further into the future; much more makes no
1544 sense since new message might be scheduled in the
1546 while ((pos != NULL) && (off < size * 2))
1548 if (pos->do_transmit == GNUNET_YES)
1550 /* already removed from consideration */
1554 if (discard_low_prio == GNUNET_NO)
1556 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1557 if (delta.value > 0)
1559 // FIXME: HUH? Check!
1561 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1564 if (avail < pos->size)
1566 // FIXME: HUH? Check!
1567 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1572 /* update slack, considering both its absolute deadline
1573 and relative deadlines caused by other messages
1574 with their respective load */
1575 slack = GNUNET_TIME_relative_min (slack,
1576 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1578 if (pos->deadline.value <= now.value)
1581 slack = GNUNET_TIME_UNIT_ZERO;
1583 else if (GNUNET_YES == pos->got_slack)
1585 /* should be soon now! */
1586 slack = GNUNET_TIME_relative_min (slack,
1587 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1592 GNUNET_TIME_relative_min (slack,
1593 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1594 pos->got_slack = GNUNET_YES;
1595 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1596 GNUNET_TIME_relative_to_absolute (MAX_CORK_DELAY));
1601 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1602 if (pos->priority <= min_prio)
1604 /* update min for discard */
1605 min_prio = pos->priority;
1610 if (discard_low_prio)
1612 GNUNET_assert (min != NULL);
1613 /* remove lowest-priority entry from consideration */
1614 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1618 /* guard against sending "tiny" messages with large headers without
1620 if ( (slack.value > 0) &&
1622 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1624 /* less than 25% of message would be filled with deadlines still
1625 being met if we delay by one second or more; so just wait for
1626 more data; but do not wait longer than 1s (since we don't want
1627 to delay messages for a really long time either). */
1628 *retry_time = MAX_CORK_DELAY;
1629 /* reset do_transmit values for next time */
1632 pos->do_transmit = GNUNET_NO;
1636 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1637 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1638 (unsigned long long) slack.value,
1640 (unsigned int) size);
1644 /* select marked messages (up to size) for transmission */
1649 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1651 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1656 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1660 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1661 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1662 (unsigned long long) off, (unsigned long long) tsize,
1663 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
1664 GNUNET_i2s (&n->peer));
1671 * Batch multiple messages into a larger buffer.
1673 * @param n neighbour to take messages from
1674 * @param buf target buffer
1675 * @param size size of buf
1676 * @param deadline set to transmission deadline for the result
1677 * @param retry_time set to the time when we should try again
1678 * (only valid if this function returns zero)
1679 * @param priority set to the priority of the batch
1680 * @return number of bytes written to buf (can be zero)
1683 batch_message (struct Neighbour *n,
1686 struct GNUNET_TIME_Absolute *deadline,
1687 struct GNUNET_TIME_Relative *retry_time,
1688 unsigned int *priority)
1690 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1691 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1692 struct MessageEntry *pos;
1693 struct MessageEntry *prev;
1694 struct MessageEntry *next;
1699 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1700 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1701 if (0 == select_messages (n, size, retry_time))
1704 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1705 "No messages selected, will try again in %llu ms\n",
1710 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1711 ntm->distance = htonl (n->last_distance);
1712 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1713 ntm->peer = n->peer;
1717 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1720 if (GNUNET_YES == pos->do_transmit)
1722 GNUNET_assert (pos->size <= size);
1723 /* do notifications */
1724 /* FIXME: track if we have *any* client that wants
1725 full notifications and only do this if that is
1727 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1729 memcpy (&ntm[1], &pos[1], pos->size);
1730 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1731 sizeof (struct GNUNET_MessageHeader));
1732 send_to_all_clients (&ntm->header,
1734 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1738 /* message too large for 'full' notifications, we do at
1739 least the 'hdr' type */
1742 sizeof (struct GNUNET_MessageHeader));
1744 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1746 send_to_all_clients (&ntm->header,
1748 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1750 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1751 "Encrypting message of type %u\n",
1752 ntohs(((struct GNUNET_MessageHeader*)&pos[1])->type));
1754 /* copy for encrypted transmission */
1755 memcpy (&buf[ret], &pos[1], pos->size);
1758 *priority += pos->priority;
1760 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1761 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1763 GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1765 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1779 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1780 "Deadline for message batch is %llu ms\n",
1781 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1788 * Remove messages with deadlines that have long expired from
1791 * @param n neighbour to inspect
1794 discard_expired_messages (struct Neighbour *n)
1796 struct MessageEntry *prev;
1797 struct MessageEntry *next;
1798 struct MessageEntry *pos;
1799 struct GNUNET_TIME_Absolute now;
1800 struct GNUNET_TIME_Relative delta;
1802 now = GNUNET_TIME_absolute_get ();
1808 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1809 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1812 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1813 "Message is %llu ms past due, discarding.\n",
1830 * Signature of the main function of a task.
1832 * @param cls closure
1833 * @param tc context information (why was this task triggered now)
1836 retry_plaintext_processing (void *cls,
1837 const struct GNUNET_SCHEDULER_TaskContext *tc)
1839 struct Neighbour *n = cls;
1841 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1842 process_plaintext_neighbour_queue (n);
1847 * Send our key (and encrypted PING) to the other peer.
1849 * @param n the other peer
1851 static void send_key (struct Neighbour *n);
1854 * Task that will retry "send_key" if our previous attempt failed
1858 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1860 struct Neighbour *n = cls;
1863 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1864 "Retrying key transmission to `%4s'\n",
1865 GNUNET_i2s (&n->peer));
1867 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1868 n->set_key_retry_frequency =
1869 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1875 * Check if we have plaintext messages for the specified neighbour
1876 * pending, and if so, consider batching and encrypting them (and
1877 * then trigger processing of the encrypted queue if needed).
1879 * @param n neighbour to check.
1882 process_plaintext_neighbour_queue (struct Neighbour *n)
1884 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1887 struct EncryptedMessage *em; /* encrypted message */
1888 struct EncryptedMessage *ph; /* plaintext header */
1889 struct MessageEntry *me;
1890 unsigned int priority;
1891 struct GNUNET_TIME_Absolute deadline;
1892 struct GNUNET_TIME_Relative retry_time;
1895 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1897 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1898 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1902 case PEER_STATE_DOWN:
1905 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1906 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1907 GNUNET_i2s(&n->peer));
1910 case PEER_STATE_KEY_SENT:
1911 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1912 n->retry_set_key_task
1913 = GNUNET_SCHEDULER_add_delayed (sched,
1914 n->set_key_retry_frequency,
1915 &set_key_retry_task, n);
1917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1918 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1919 GNUNET_i2s(&n->peer));
1922 case PEER_STATE_KEY_RECEIVED:
1923 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1924 n->retry_set_key_task
1925 = GNUNET_SCHEDULER_add_delayed (sched,
1926 n->set_key_retry_frequency,
1927 &set_key_retry_task, n);
1929 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1930 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1931 GNUNET_i2s(&n->peer));
1934 case PEER_STATE_KEY_CONFIRMED:
1935 /* ready to continue */
1938 discard_expired_messages (n);
1939 if (n->messages == NULL)
1942 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1943 "Plaintext message queue for `%4s' is empty.\n",
1944 GNUNET_i2s(&n->peer));
1946 return; /* no pending messages */
1948 if (n->encrypted_head != NULL)
1951 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1952 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1953 GNUNET_i2s(&n->peer));
1955 return; /* wait for messages already encrypted to be
1958 ph = (struct EncryptedMessage *) pbuf;
1959 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1961 used = sizeof (struct EncryptedMessage);
1962 used += batch_message (n,
1964 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1965 &deadline, &retry_time, &priority);
1966 if (used == sizeof (struct EncryptedMessage))
1969 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1970 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1971 GNUNET_i2s(&n->peer));
1973 /* no messages selected for sending, try again later... */
1974 n->retry_plaintext_task =
1975 GNUNET_SCHEDULER_add_delayed (sched,
1977 &retry_plaintext_processing, n);
1980 #if DEBUG_CORE_QUOTA
1981 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1982 "Sending %u b/s as new limit to peer `%4s'\n",
1983 (unsigned int) ntohl (n->bw_in.value__),
1984 GNUNET_i2s (&n->peer));
1986 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1));
1987 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1988 ph->inbound_bw_limit = n->bw_in;
1989 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1991 /* setup encryption message header */
1992 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1993 me->deadline = deadline;
1994 me->priority = priority;
1996 em = (struct EncryptedMessage *) &me[1];
1997 em->header.size = htons (used);
1998 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1999 em->iv_seed = ph->iv_seed;
2000 esize = used - ENCRYPTED_HEADER_SIZE;
2001 GNUNET_CRYPTO_hash (&ph->sequence_number,
2002 esize - sizeof (GNUNET_HashCode),
2003 &ph->plaintext_hash);
2004 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
2006 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2007 "Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
2008 esize - sizeof (GNUNET_HashCode),
2009 GNUNET_h2s (&ph->plaintext_hash),
2014 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2015 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2017 GNUNET_i2s(&n->peer),
2018 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2020 GNUNET_assert (GNUNET_OK ==
2023 &ph->plaintext_hash,
2024 &em->plaintext_hash, esize));
2025 /* append to transmission list */
2026 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2030 process_encrypted_neighbour_queue (n);
2035 * Function that recalculates the bandwidth quota for the
2036 * given neighbour and transmits it to the transport service.
2038 * @param cls neighbour for the quota update
2042 neighbour_quota_update (void *cls,
2043 const struct GNUNET_SCHEDULER_TaskContext *tc);
2047 * Schedule the task that will recalculate the bandwidth
2048 * quota for this peer (and possibly force a disconnect of
2049 * idle peers by calculating a bandwidth of zero).
2052 schedule_quota_update (struct Neighbour *n)
2054 GNUNET_assert (n->quota_update_task ==
2055 GNUNET_SCHEDULER_NO_TASK);
2056 n->quota_update_task
2057 = GNUNET_SCHEDULER_add_delayed (sched,
2058 QUOTA_UPDATE_FREQUENCY,
2059 &neighbour_quota_update,
2065 * Initialize a new 'struct Neighbour'.
2067 * @param pid ID of the new neighbour
2068 * @return handle for the new neighbour
2070 static struct Neighbour *
2071 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2073 struct Neighbour *n;
2074 struct GNUNET_TIME_Absolute now;
2076 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2077 "Creating neighbour entry for peer `%4s'\n",
2079 n = GNUNET_malloc (sizeof (struct Neighbour));
2080 n->next = neighbours;
2083 GNUNET_STATISTICS_set (stats, gettext_noop ("# active neighbours"), neighbour_count, GNUNET_NO);
2085 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2086 now = GNUNET_TIME_absolute_get ();
2087 n->encrypt_key_created = now;
2088 n->last_activity = now;
2089 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2090 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2091 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2092 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init ((uint32_t) - 1);
2093 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2094 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2096 neighbour_quota_update (n, NULL);
2102 * Handle CORE_SEND request.
2105 * @param client the client issuing the request
2106 * @param message the "struct SendMessage"
2109 handle_client_send (void *cls,
2110 struct GNUNET_SERVER_Client *client,
2111 const struct GNUNET_MessageHeader *message)
2113 const struct SendMessage *sm;
2114 struct Neighbour *n;
2115 struct MessageEntry *prev;
2116 struct MessageEntry *pos;
2117 struct MessageEntry *e;
2118 struct MessageEntry *min_prio_entry;
2119 struct MessageEntry *min_prio_prev;
2120 unsigned int min_prio;
2121 unsigned int queue_size;
2124 msize = ntohs (message->size);
2126 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2130 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2133 sm = (const struct SendMessage *) message;
2134 msize -= sizeof (struct SendMessage);
2135 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2137 /* FIXME: should we not allow loopback-injection here? */
2140 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2143 n = find_neighbour (&sm->peer);
2145 n = create_neighbour (&sm->peer);
2147 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2148 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2151 GNUNET_i2s (&sm->peer));
2153 /* bound queue size */
2154 discard_expired_messages (n);
2155 min_prio = (unsigned int) -1;
2156 min_prio_entry = NULL;
2157 min_prio_prev = NULL;
2163 if (pos->priority < min_prio)
2165 min_prio_entry = pos;
2166 min_prio_prev = prev;
2167 min_prio = pos->priority;
2173 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2176 if (ntohl(sm->priority) <= min_prio)
2178 /* discard new entry */
2180 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2181 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2183 MAX_PEER_QUEUE_SIZE,
2185 ntohs (message->type));
2188 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2191 /* discard "min_prio_entry" */
2193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2194 "Queue full, discarding existing older request\n");
2196 if (min_prio_prev == NULL)
2197 n->messages = min_prio_entry->next;
2199 min_prio_prev->next = min_prio_entry->next;
2200 GNUNET_free (min_prio_entry);
2204 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2205 "Adding transmission request for `%4s' of size %u to queue\n",
2206 GNUNET_i2s (&sm->peer),
2209 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2210 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2211 e->priority = ntohl (sm->priority);
2213 memcpy (&e[1], &sm[1], msize);
2215 /* insert, keep list sorted by deadline */
2218 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2229 /* consider scheduling now */
2230 process_plaintext_neighbour_queue (n);
2232 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2237 * Function called when the transport service is ready to
2238 * receive a message. Only resets 'n->th' to NULL.
2240 * @param cls neighbour to use message from
2241 * @param size number of bytes we can transmit
2242 * @param buf where to copy the message
2243 * @return number of bytes transmitted
2246 notify_transport_connect_done (void *cls, size_t size, void *buf)
2248 struct Neighbour *n = cls;
2253 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2254 _("Failed to connect to `%4s': transport failed to connect\n"),
2255 GNUNET_i2s (&n->peer));
2264 * Handle CORE_REQUEST_CONNECT request.
2267 * @param client the client issuing the request
2268 * @param message the "struct ConnectMessage"
2271 handle_client_request_connect (void *cls,
2272 struct GNUNET_SERVER_Client *client,
2273 const struct GNUNET_MessageHeader *message)
2275 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2276 struct Neighbour *n;
2277 struct GNUNET_TIME_Relative timeout;
2279 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2282 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2285 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2286 n = find_neighbour (&cm->peer);
2288 n = create_neighbour (&cm->peer);
2289 if ( (n->is_connected) ||
2291 return; /* already connected, or at least trying */
2292 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2294 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2295 "Core received `%s' request for `%4s', will try to establish connection\n",
2297 GNUNET_i2s (&cm->peer));
2299 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2300 /* ask transport to connect to the peer */
2301 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2303 sizeof (struct GNUNET_MessageHeader), 0,
2305 ¬ify_transport_connect_done,
2307 GNUNET_break (NULL != n->th);
2312 * List of handlers for the messages understood by this
2315 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2316 {&handle_client_init, NULL,
2317 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2318 {&handle_client_request_info, NULL,
2319 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2320 sizeof (struct RequestInfoMessage)},
2321 {&handle_client_send, NULL,
2322 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2323 {&handle_client_request_connect, NULL,
2324 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2325 sizeof (struct ConnectMessage)},
2331 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2332 * the neighbour's struct and retry send_key. Or, if we did not get a
2333 * HELLO, just do nothing.
2335 * @param cls the 'struct Neighbour' to retry sending the key for
2336 * @param peer the peer for which this is the HELLO
2337 * @param hello HELLO message of that peer
2338 * @param trust amount of trust we currently have in that peer
2341 process_hello_retry_send_key (void *cls,
2342 const struct GNUNET_PeerIdentity *peer,
2343 const struct GNUNET_HELLO_Message *hello,
2346 struct Neighbour *n = cls;
2351 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2352 "Entered `process_hello_retry_send_key' and `peer' is NULL!\n");
2355 if (n->public_key != NULL)
2357 GNUNET_STATISTICS_update (stats,
2358 gettext_noop ("# SETKEY messages deferred (need public key)"),
2365 GNUNET_STATISTICS_update (stats,
2366 gettext_noop ("# Delayed connecting due to lack of public key"),
2369 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2370 n->retry_set_key_task
2371 = GNUNET_SCHEDULER_add_delayed (sched,
2372 n->set_key_retry_frequency,
2373 &set_key_retry_task, n);
2379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2380 "Entered `process_hello_retry_send_key' for peer `%4s'\n",
2383 if (n->public_key != NULL)
2386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2387 "already have public key for peer %s!! (so why are we here?)\n",
2394 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2395 "Received new `%s' message for `%4s', initiating key exchange.\n",
2400 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2401 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2403 GNUNET_STATISTICS_update (stats,
2404 gettext_noop ("# Error extracting public key from HELLO"),
2407 GNUNET_free (n->public_key);
2408 n->public_key = NULL;
2410 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2411 "GNUNET_HELLO_get_key returned awfully\n");
2419 * Send our key (and encrypted PING) to the other peer.
2421 * @param n the other peer
2424 send_key (struct Neighbour *n)
2426 struct SetKeyMessage *sm;
2427 struct MessageEntry *me;
2428 struct PingMessage pp;
2429 struct PingMessage *pm;
2431 if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2435 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2436 "Key exchange in progress with `%4s'.\n",
2437 GNUNET_i2s (&n->peer));
2439 return; /* already in progress */
2441 if (! n->is_connected)
2445 GNUNET_STATISTICS_update (stats,
2446 gettext_noop ("# Asking transport to connect (for SETKEY)"),
2449 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2451 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2453 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2454 ¬ify_encrypted_transmit_ready,
2460 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2461 "Asked to perform key exchange with `%4s'.\n",
2462 GNUNET_i2s (&n->peer));
2464 if (n->public_key == NULL)
2466 /* lookup n's public key, then try again */
2468 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2469 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2470 GNUNET_i2s (&n->peer));
2472 GNUNET_assert (n->pitr == NULL);
2473 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2477 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2478 &process_hello_retry_send_key, n);
2481 /* first, set key message */
2482 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2483 sizeof (struct SetKeyMessage));
2484 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2485 me->priority = SET_KEY_PRIORITY;
2486 me->size = sizeof (struct SetKeyMessage);
2487 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2491 sm = (struct SetKeyMessage *) &me[1];
2492 sm->header.size = htons (sizeof (struct SetKeyMessage));
2493 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2494 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2495 PEER_STATE_KEY_SENT : n->status));
2497 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2498 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2499 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2500 sizeof (struct GNUNET_PeerIdentity));
2501 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2502 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2503 sm->target = n->peer;
2504 GNUNET_assert (GNUNET_OK ==
2505 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2507 GNUNET_CRYPTO_AesSessionKey),
2509 &sm->encrypted_key));
2510 GNUNET_assert (GNUNET_OK ==
2511 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2514 /* second, encrypted PING message */
2515 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2516 sizeof (struct PingMessage));
2517 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2518 me->priority = PING_PRIORITY;
2519 me->size = sizeof (struct PingMessage);
2520 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2524 pm = (struct PingMessage *) &me[1];
2525 pm->header.size = htons (sizeof (struct PingMessage));
2526 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2527 pp.challenge = htonl (n->ping_challenge);
2528 pp.target = n->peer;
2530 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2531 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2532 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2533 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2534 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2536 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2539 &n->peer.hashPubKey,
2542 sizeof (struct PingMessage) -
2543 sizeof (struct GNUNET_MessageHeader));
2547 case PEER_STATE_DOWN:
2548 n->status = PEER_STATE_KEY_SENT;
2550 case PEER_STATE_KEY_SENT:
2552 case PEER_STATE_KEY_RECEIVED:
2554 case PEER_STATE_KEY_CONFIRMED:
2560 GNUNET_STATISTICS_update (stats,
2561 gettext_noop ("# SETKEY and PING messages created"),
2565 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2566 "Have %llu ms left for `%s' transmission.\n",
2567 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2570 /* trigger queue processing */
2571 process_encrypted_neighbour_queue (n);
2572 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2573 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2574 n->retry_set_key_task
2575 = GNUNET_SCHEDULER_add_delayed (sched,
2576 n->set_key_retry_frequency,
2577 &set_key_retry_task, n);
2582 * We received a SET_KEY message. Validate and update
2583 * our key material and status.
2585 * @param n the neighbour from which we received message m
2586 * @param m the set key message we received
2589 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2593 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2594 * the neighbour's struct and retry handling the set_key message. Or,
2595 * if we did not get a HELLO, just free the set key message.
2597 * @param cls pointer to the set key message
2598 * @param peer the peer for which this is the HELLO
2599 * @param hello HELLO message of that peer
2600 * @param trust amount of trust we currently have in that peer
2603 process_hello_retry_handle_set_key (void *cls,
2604 const struct GNUNET_PeerIdentity *peer,
2605 const struct GNUNET_HELLO_Message *hello,
2608 struct Neighbour *n = cls;
2609 struct SetKeyMessage *sm = n->skm;
2618 if (n->public_key != NULL)
2619 return; /* multiple HELLOs match!? */
2621 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2622 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2624 GNUNET_break_op (0);
2625 GNUNET_free (n->public_key);
2626 n->public_key = NULL;
2630 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2631 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2632 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2634 handle_set_key (n, sm);
2639 * We received a PING message. Validate and transmit
2642 * @param n sender of the PING
2643 * @param m the encrypted PING message itself
2646 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2648 struct PingMessage t;
2649 struct PongMessage tx;
2650 struct PongMessage *tp;
2651 struct MessageEntry *me;
2654 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2655 "Core service receives `%s' request from `%4s'.\n",
2656 "PING", GNUNET_i2s (&n->peer));
2660 &my_identity.hashPubKey,
2663 sizeof (struct PingMessage) -
2664 sizeof (struct GNUNET_MessageHeader)))
2667 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2668 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2670 GNUNET_i2s (&t.target),
2671 ntohl (t.challenge), n->decrypt_key.crc32);
2672 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2673 "Target of `%s' request is `%4s'.\n",
2674 "PING", GNUNET_i2s (&t.target));
2676 GNUNET_STATISTICS_update (stats,
2677 gettext_noop ("# PING messages decrypted"),
2680 if (0 != memcmp (&t.target,
2681 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2683 GNUNET_break_op (0);
2686 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2687 sizeof (struct PongMessage));
2688 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2692 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2693 me->priority = PONG_PRIORITY;
2694 me->size = sizeof (struct PongMessage);
2695 tx.reserved = htonl (0);
2696 tx.inbound_bw_limit = n->bw_in;
2697 tx.challenge = t.challenge;
2698 tx.target = t.target;
2699 tp = (struct PongMessage *) &me[1];
2700 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2701 tp->header.size = htons (sizeof (struct PongMessage));
2703 &my_identity.hashPubKey,
2706 sizeof (struct PongMessage) -
2707 sizeof (struct GNUNET_MessageHeader));
2708 GNUNET_STATISTICS_update (stats,
2709 gettext_noop ("# PONG messages created"),
2713 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2714 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2715 ntohl (t.challenge), n->encrypt_key.crc32);
2717 /* trigger queue processing */
2718 process_encrypted_neighbour_queue (n);
2723 * We received a PONG message. Validate and update our status.
2725 * @param n sender of the PONG
2726 * @param m the encrypted PONG message itself
2729 handle_pong (struct Neighbour *n,
2730 const struct PongMessage *m)
2732 struct PongMessage t;
2733 struct ConnectNotifyMessage cnm;
2736 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2737 "Core service receives `%s' request from `%4s'.\n",
2738 "PONG", GNUNET_i2s (&n->peer));
2742 &n->peer.hashPubKey,
2745 sizeof (struct PongMessage) -
2746 sizeof (struct GNUNET_MessageHeader)))
2748 GNUNET_break_op (0);
2751 GNUNET_STATISTICS_update (stats,
2752 gettext_noop ("# PONG messages decrypted"),
2755 if (0 != ntohl (t.reserved))
2757 GNUNET_break_op (0);
2761 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2762 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2764 GNUNET_i2s (&t.target),
2765 ntohl (t.challenge), n->decrypt_key.crc32);
2767 if ((0 != memcmp (&t.target,
2769 sizeof (struct GNUNET_PeerIdentity))) ||
2770 (n->ping_challenge != ntohl (t.challenge)))
2772 /* PONG malformed */
2774 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2775 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2776 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2777 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2778 "Received malformed `%s' received from `%4s' with challenge %u\n",
2779 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2781 GNUNET_break_op (0);
2786 case PEER_STATE_DOWN:
2787 GNUNET_break (0); /* should be impossible */
2789 case PEER_STATE_KEY_SENT:
2790 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2792 case PEER_STATE_KEY_RECEIVED:
2793 GNUNET_STATISTICS_update (stats,
2794 gettext_noop ("# Session keys confirmed via PONG"),
2797 n->status = PEER_STATE_KEY_CONFIRMED;
2798 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2800 n->bw_out_external_limit = t.inbound_bw_limit;
2801 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2802 n->bw_out_internal_limit);
2803 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2805 GNUNET_TRANSPORT_set_quota (transport,
2809 GNUNET_TIME_UNIT_FOREVER_REL,
2813 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2814 "Confirmed key via `%s' message for peer `%4s'\n",
2815 "PONG", GNUNET_i2s (&n->peer));
2817 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2819 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2820 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2822 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2823 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2824 cnm.distance = htonl (n->last_distance);
2825 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2827 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2828 process_encrypted_neighbour_queue (n);
2830 case PEER_STATE_KEY_CONFIRMED:
2831 n->last_activity = GNUNET_TIME_absolute_get ();
2832 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2833 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2835 = GNUNET_SCHEDULER_add_delayed (sched,
2836 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2848 * We received a SET_KEY message. Validate and update
2849 * our key material and status.
2851 * @param n the neighbour from which we received message m
2852 * @param m the set key message we received
2855 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2857 struct SetKeyMessage *m_cpy;
2858 struct GNUNET_TIME_Absolute t;
2859 struct GNUNET_CRYPTO_AesSessionKey k;
2860 struct PingMessage *ping;
2861 struct PongMessage *pong;
2862 enum PeerStateMachine sender_status;
2865 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2866 "Core service receives `%s' request from `%4s'.\n",
2867 "SET_KEY", GNUNET_i2s (&n->peer));
2869 if (n->public_key == NULL)
2871 if (n->pitr != NULL)
2874 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2875 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2881 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2882 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2884 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2885 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2886 /* lookup n's public key, then try again */
2887 GNUNET_assert (n->skm == NULL);
2889 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2893 GNUNET_TIME_UNIT_MINUTES,
2894 &process_hello_retry_handle_set_key, n);
2895 GNUNET_STATISTICS_update (stats,
2896 gettext_noop ("# SETKEY messages deferred (need public key)"),
2901 if (0 != memcmp (&m->target,
2903 sizeof (struct GNUNET_PeerIdentity)))
2905 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2906 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
2908 GNUNET_i2s (&m->target));
2911 if ((ntohl (m->purpose.size) !=
2912 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2913 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2914 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2915 sizeof (struct GNUNET_PeerIdentity)) ||
2917 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2918 &m->purpose, &m->signature, n->public_key)))
2920 /* invalid signature */
2921 GNUNET_break_op (0);
2924 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2925 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2926 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2927 (t.value < n->decrypt_key_created.value))
2929 /* this could rarely happen due to massive re-ordering of
2930 messages on the network level, but is most likely either
2931 a bug or some adversary messing with us. Report. */
2932 GNUNET_break_op (0);
2936 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2937 "Decrypting key material.\n");
2939 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2942 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2943 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2944 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2946 /* failed to decrypt !? */
2947 GNUNET_break_op (0);
2950 GNUNET_STATISTICS_update (stats,
2951 gettext_noop ("# SETKEY messages decrypted"),
2955 if (n->decrypt_key_created.value != t.value)
2957 /* fresh key, reset sequence numbers */
2958 n->last_sequence_number_received = 0;
2959 n->last_packets_bitmap = 0;
2960 n->decrypt_key_created = t;
2962 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2965 case PEER_STATE_DOWN:
2966 n->status = PEER_STATE_KEY_RECEIVED;
2968 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2969 "Responding to `%s' with my own key.\n", "SET_KEY");
2973 case PEER_STATE_KEY_SENT:
2974 case PEER_STATE_KEY_RECEIVED:
2975 n->status = PEER_STATE_KEY_RECEIVED;
2976 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2977 (sender_status != PEER_STATE_KEY_CONFIRMED))
2980 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2981 "Responding to `%s' with my own key (other peer has status %u).\n",
2982 "SET_KEY", sender_status);
2987 case PEER_STATE_KEY_CONFIRMED:
2988 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2989 (sender_status != PEER_STATE_KEY_CONFIRMED))
2992 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2993 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2994 "SET_KEY", sender_status);
3003 if (n->pending_ping != NULL)
3005 ping = n->pending_ping;
3006 n->pending_ping = NULL;
3007 handle_ping (n, ping);
3010 if (n->pending_pong != NULL)
3012 pong = n->pending_pong;
3013 n->pending_pong = NULL;
3014 handle_pong (n, pong);
3021 * Send a P2P message to a client.
3023 * @param sender who sent us the message?
3024 * @param client who should we give the message to?
3025 * @param m contains the message to transmit
3026 * @param msize number of bytes in buf to transmit
3029 send_p2p_message_to_client (struct Neighbour *sender,
3030 struct Client *client,
3031 const void *m, size_t msize)
3033 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3034 struct NotifyTrafficMessage *ntm;
3037 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3038 "Core service passes message from `%4s' of type %u to client.\n",
3039 GNUNET_i2s(&sender->peer),
3040 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3042 ntm = (struct NotifyTrafficMessage *) buf;
3043 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3044 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3045 ntm->distance = htonl (sender->last_distance);
3046 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3047 ntm->peer = sender->peer;
3048 memcpy (&ntm[1], m, msize);
3049 send_to_client (client, &ntm->header, GNUNET_YES);
3054 * Deliver P2P message to interested clients.
3056 * @param sender who sent us the message?
3057 * @param m the message
3058 * @param msize size of the message (including header)
3061 deliver_message (struct Neighbour *sender,
3062 const struct GNUNET_MessageHeader *m, size_t msize)
3065 struct Client *cpos;
3071 type = ntohs (m->type);
3073 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3074 "Received encapsulated message of type %u from `%4s'\n",
3076 GNUNET_i2s (&sender->peer));
3078 GNUNET_snprintf (buf,
3080 gettext_noop ("# bytes of messages of type %u received"),
3082 GNUNET_STATISTICS_set (stats,
3086 dropped = GNUNET_YES;
3088 while (cpos != NULL)
3090 deliver_full = GNUNET_NO;
3091 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3092 deliver_full = GNUNET_YES;
3095 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3097 if (type != cpos->types[tpos])
3099 deliver_full = GNUNET_YES;
3103 if (GNUNET_YES == deliver_full)
3105 send_p2p_message_to_client (sender, cpos, m, msize);
3106 dropped = GNUNET_NO;
3108 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3110 send_p2p_message_to_client (sender, cpos, m,
3111 sizeof (struct GNUNET_MessageHeader));
3115 if (dropped == GNUNET_YES)
3118 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3119 "Message of type %u from `%4s' not delivered to any client.\n",
3121 GNUNET_i2s (&sender->peer));
3123 /* FIXME: stats... */
3129 * Align P2P message and then deliver to interested clients.
3131 * @param sender who sent us the message?
3132 * @param buffer unaligned (!) buffer containing message
3133 * @param msize size of the message (including header)
3136 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
3140 /* TODO: call to statistics? */
3141 memcpy (abuf, buffer, msize);
3142 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
3147 * Deliver P2P messages to interested clients.
3149 * @param sender who sent us the message?
3150 * @param buffer buffer containing messages, can be modified
3151 * @param buffer_size size of the buffer (overall)
3152 * @param offset offset where messages in the buffer start
3155 deliver_messages (struct Neighbour *sender,
3156 const char *buffer, size_t buffer_size, size_t offset)
3158 struct GNUNET_MessageHeader *mhp;
3159 struct GNUNET_MessageHeader mh;
3163 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
3165 if (0 != offset % sizeof (uint16_t))
3167 /* outch, need to copy to access header */
3168 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
3173 /* can access header directly */
3174 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
3176 msize = ntohs (mhp->size);
3177 if (msize + offset > buffer_size)
3179 /* malformed message, header says it is larger than what
3180 would fit into the overall buffer */
3181 GNUNET_break_op (0);
3184 #if HAVE_UNALIGNED_64_ACCESS
3185 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
3187 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
3189 if (GNUNET_YES == need_align)
3190 align_and_deliver (sender, &buffer[offset], msize);
3192 deliver_message (sender,
3193 (const struct GNUNET_MessageHeader *)
3194 &buffer[offset], msize);
3201 * We received an encrypted message. Decrypt, validate and
3202 * pass on to the appropriate clients.
3205 handle_encrypted_message (struct Neighbour *n,
3206 const struct EncryptedMessage *m)
3208 size_t size = ntohs (m->header.size);
3210 struct EncryptedMessage *pt; /* plaintext */
3213 struct GNUNET_TIME_Absolute t;
3217 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3218 "Core service receives `%s' request from `%4s'.\n",
3219 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3221 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3227 &buf[ENCRYPTED_HEADER_SIZE],
3228 size - ENCRYPTED_HEADER_SIZE))
3230 pt = (struct EncryptedMessage *) buf;
3232 GNUNET_CRYPTO_hash (&pt->sequence_number,
3233 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3235 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3236 "V-Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
3237 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode),
3241 if (0 != memcmp (&ph,
3242 &pt->plaintext_hash,
3243 sizeof (GNUNET_HashCode)))
3245 /* checksum failed */
3246 GNUNET_break_op (0);
3250 /* validate sequence number */
3251 snum = ntohl (pt->sequence_number);
3252 if (n->last_sequence_number_received == snum)
3254 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3255 "Received duplicate message, ignoring.\n");
3256 /* duplicate, ignore */
3257 GNUNET_STATISTICS_set (stats,
3258 gettext_noop ("# bytes dropped (duplicates)"),
3263 if ((n->last_sequence_number_received > snum) &&
3264 (n->last_sequence_number_received - snum > 32))
3266 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3267 "Received ancient out of sequence message, ignoring.\n");
3268 /* ancient out of sequence, ignore */
3269 GNUNET_STATISTICS_set (stats,
3270 gettext_noop ("# bytes dropped (out of sequence)"),
3275 if (n->last_sequence_number_received > snum)
3277 unsigned int rotbit =
3278 1 << (n->last_sequence_number_received - snum - 1);
3279 if ((n->last_packets_bitmap & rotbit) != 0)
3281 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3282 "Received duplicate message, ignoring.\n");
3283 GNUNET_STATISTICS_set (stats,
3284 gettext_noop ("# bytes dropped (duplicates)"),
3287 /* duplicate, ignore */
3290 n->last_packets_bitmap |= rotbit;
3292 if (n->last_sequence_number_received < snum)
3294 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3295 n->last_sequence_number_received = snum;
3298 /* check timestamp */
3299 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3300 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3302 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3304 ("Message received far too old (%llu ms). Content ignored.\n"),
3305 GNUNET_TIME_absolute_get_duration (t).value);
3306 GNUNET_STATISTICS_set (stats,
3307 gettext_noop ("# bytes dropped (ancient message)"),
3313 /* process decrypted message(s) */
3314 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3316 #if DEBUG_CORE_SET_QUOTA
3317 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3318 "Received %u b/s as new inbound limit for peer `%4s'\n",
3319 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3320 GNUNET_i2s (&n->peer));
3322 n->bw_out_external_limit = pt->inbound_bw_limit;
3323 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3324 n->bw_out_internal_limit);
3325 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3327 GNUNET_TRANSPORT_set_quota (transport,
3331 GNUNET_TIME_UNIT_FOREVER_REL,
3334 n->last_activity = GNUNET_TIME_absolute_get ();
3335 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3336 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3338 = GNUNET_SCHEDULER_add_delayed (sched,
3339 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3342 GNUNET_STATISTICS_set (stats,
3343 gettext_noop ("# bytes of payload decrypted"),
3344 size - sizeof (struct EncryptedMessage),
3346 deliver_messages (n, buf, size, sizeof (struct EncryptedMessage));
3351 * Function called by the transport for each received message.
3353 * @param cls closure
3354 * @param peer (claimed) identity of the other peer
3355 * @param message the message
3356 * @param latency estimated latency for communicating with the
3357 * given peer (round-trip)
3358 * @param distance in overlay hops, as given by transport plugin
3361 handle_transport_receive (void *cls,
3362 const struct GNUNET_PeerIdentity *peer,
3363 const struct GNUNET_MessageHeader *message,
3364 struct GNUNET_TIME_Relative latency,
3365 unsigned int distance)
3367 struct Neighbour *n;
3368 struct GNUNET_TIME_Absolute now;
3374 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3375 "Received message of type %u from `%4s', demultiplexing.\n",
3376 ntohs (message->type), GNUNET_i2s (peer));
3378 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3383 n = find_neighbour (peer);
3385 n = create_neighbour (peer);
3386 n->last_latency = latency;
3387 n->last_distance = distance;
3388 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3389 type = ntohs (message->type);
3390 size = ntohs (message->size);
3393 "Received message of type %u from `%4s'\n",
3399 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3400 if (size != sizeof (struct SetKeyMessage))
3402 GNUNET_break_op (0);
3405 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3406 handle_set_key (n, (const struct SetKeyMessage *) message);
3408 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3409 if (size < sizeof (struct EncryptedMessage) +
3410 sizeof (struct GNUNET_MessageHeader))
3412 GNUNET_break_op (0);
3415 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3416 (n->status != PEER_STATE_KEY_CONFIRMED))
3418 GNUNET_break_op (0);
3419 /* blacklist briefly (?); might help recover (?) */
3420 GNUNET_TRANSPORT_blacklist (sched, cfg,
3422 GNUNET_TIME_UNIT_SECONDS,
3423 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3428 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3430 case GNUNET_MESSAGE_TYPE_CORE_PING:
3431 if (size != sizeof (struct PingMessage))
3433 GNUNET_break_op (0);
3436 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3437 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3438 (n->status != PEER_STATE_KEY_CONFIRMED))
3441 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3442 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3443 "PING", GNUNET_i2s (&n->peer));
3445 GNUNET_free_non_null (n->pending_ping);
3446 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3447 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3450 handle_ping (n, (const struct PingMessage *) message);
3452 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3453 if (size != sizeof (struct PongMessage))
3455 GNUNET_break_op (0);
3458 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3459 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3460 (n->status != PEER_STATE_KEY_CONFIRMED) )
3463 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3464 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3465 "PONG", GNUNET_i2s (&n->peer));
3467 GNUNET_free_non_null (n->pending_pong);
3468 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3469 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3472 handle_pong (n, (const struct PongMessage *) message);
3475 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3476 _("Unsupported message of type %u received.\n"), type);
3479 if (n->status == PEER_STATE_KEY_CONFIRMED)
3481 now = GNUNET_TIME_absolute_get ();
3482 n->last_activity = now;
3485 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3486 n->time_established = now;
3488 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3489 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3491 = GNUNET_SCHEDULER_add_delayed (sched,
3492 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3500 * Function that recalculates the bandwidth quota for the
3501 * given neighbour and transmits it to the transport service.
3503 * @param cls neighbour for the quota update
3507 neighbour_quota_update (void *cls,
3508 const struct GNUNET_SCHEDULER_TaskContext *tc)
3510 struct Neighbour *n = cls;
3511 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3514 unsigned long long distributable;
3515 uint64_t need_per_peer;
3516 uint64_t need_per_second;
3518 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3519 /* calculate relative preference among all neighbours;
3520 divides by a bit more to avoid division by zero AND to
3521 account for possibility of new neighbours joining any time
3522 AND to convert to double... */
3523 if (preference_sum == 0)
3525 pref_rel = 1.0 / (double) neighbour_count;
3529 pref_rel = n->current_preference / preference_sum;
3531 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3532 GNUNET_TIME_UNIT_SECONDS);
3533 need_per_second = need_per_peer * neighbour_count;
3535 if (bandwidth_target_out_bps > need_per_second)
3536 distributable = bandwidth_target_out_bps - need_per_second;
3537 share = distributable * pref_rel;
3538 if (share + need_per_peer > ( (uint32_t)-1))
3539 q_in = GNUNET_BANDWIDTH_value_init ((uint32_t) -1);
3541 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3542 /* check if we want to disconnect for good due to inactivity */
3543 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3544 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3547 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3548 "Forcing disconnect of `%4s' due to inactivity (?).\n",
3549 GNUNET_i2s (&n->peer));
3551 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3553 #if DEBUG_CORE_QUOTA
3554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3555 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3556 GNUNET_i2s (&n->peer),
3557 (unsigned int) ntohl (q_in.value__),
3558 bandwidth_target_out_bps,
3559 (unsigned int) ntohl (n->bw_in.value__),
3560 (unsigned int) ntohl (n->bw_out.value__),
3561 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3563 if (n->bw_in.value__ != q_in.value__)
3566 GNUNET_TRANSPORT_set_quota (transport,
3570 GNUNET_TIME_UNIT_FOREVER_REL,
3573 schedule_quota_update (n);
3578 * Function called by transport to notify us that
3579 * a peer connected to us (on the network level).
3581 * @param cls closure
3582 * @param peer the peer that connected
3583 * @param latency current latency of the connection
3584 * @param distance in overlay hops, as given by transport plugin
3587 handle_transport_notify_connect (void *cls,
3588 const struct GNUNET_PeerIdentity *peer,
3589 struct GNUNET_TIME_Relative latency,
3590 unsigned int distance)
3592 struct Neighbour *n;
3593 struct ConnectNotifyMessage cnm;
3595 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3600 n = find_neighbour (peer);
3603 if (n->is_connected)
3605 /* duplicate connect notification!? */
3612 n = create_neighbour (peer);
3614 GNUNET_STATISTICS_update (stats,
3615 gettext_noop ("# peers connected"),
3618 n->is_connected = GNUNET_YES;
3619 n->last_latency = latency;
3620 n->last_distance = distance;
3621 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3624 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3628 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3629 "Received connection from `%4s'.\n",
3630 GNUNET_i2s (&n->peer));
3632 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3633 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3634 cnm.distance = htonl (n->last_distance);
3635 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3637 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3638 GNUNET_TRANSPORT_set_quota (transport,
3642 GNUNET_TIME_UNIT_FOREVER_REL,
3649 * Function called by transport telling us that a peer
3652 * @param cls closure
3653 * @param peer the peer that disconnected
3656 handle_transport_notify_disconnect (void *cls,
3657 const struct GNUNET_PeerIdentity *peer)
3659 struct DisconnectNotifyMessage cnm;
3660 struct Neighbour *n;
3663 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3664 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3666 n = find_neighbour (peer);
3672 GNUNET_break (n->is_connected);
3673 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3674 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3676 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3677 n->is_connected = GNUNET_NO;
3678 GNUNET_STATISTICS_update (stats,
3679 gettext_noop ("# peers connected"),
3686 * Last task run during shutdown. Disconnects us from
3690 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3692 struct Neighbour *n;
3696 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3697 "Core service shutting down.\n");
3699 GNUNET_assert (transport != NULL);
3700 GNUNET_TRANSPORT_disconnect (transport);
3702 while (NULL != (n = neighbours))
3704 neighbours = n->next;
3705 GNUNET_assert (neighbour_count > 0);
3709 GNUNET_STATISTICS_set (stats, gettext_noop ("# active neighbours"), neighbour_count, GNUNET_NO);
3710 GNUNET_SERVER_notification_context_destroy (notifier);
3712 while (NULL != (c = clients))
3713 handle_client_disconnect (NULL, c->client_handle);
3714 if (my_private_key != NULL)
3715 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3717 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3722 * Initiate core service.
3724 * @param cls closure
3725 * @param s scheduler to use
3726 * @param serv the initialized server
3727 * @param c configuration to use
3731 struct GNUNET_SCHEDULER_Handle *s,
3732 struct GNUNET_SERVER_Handle *serv,
3733 const struct GNUNET_CONFIGURATION_Handle *c)
3739 /* parse configuration */
3742 GNUNET_CONFIGURATION_get_value_number (c,
3745 &bandwidth_target_in_bps)) ||
3747 GNUNET_CONFIGURATION_get_value_number (c,
3750 &bandwidth_target_out_bps)) ||
3752 GNUNET_CONFIGURATION_get_value_filename (c,
3754 "HOSTKEY", &keyfile)))
3756 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3758 ("Core service is lacking key configuration settings. Exiting.\n"));
3759 GNUNET_SCHEDULER_shutdown (s);
3762 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3763 GNUNET_free (keyfile);
3764 if (my_private_key == NULL)
3766 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3767 _("Core service could not access hostkey. Exiting.\n"));
3768 GNUNET_SCHEDULER_shutdown (s);
3771 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3772 GNUNET_CRYPTO_hash (&my_public_key,
3773 sizeof (my_public_key), &my_identity.hashPubKey);
3774 /* setup notification */
3776 notifier = GNUNET_SERVER_notification_context_create (server,
3778 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3779 /* setup transport connection */
3780 transport = GNUNET_TRANSPORT_connect (sched,
3783 &handle_transport_receive,
3784 &handle_transport_notify_connect,
3785 &handle_transport_notify_disconnect);
3786 GNUNET_assert (NULL != transport);
3787 stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3788 GNUNET_SCHEDULER_add_delayed (sched,
3789 GNUNET_TIME_UNIT_FOREVER_REL,
3790 &cleaning_task, NULL);
3791 /* process client requests */
3792 GNUNET_SERVER_add_handlers (server, handlers);
3793 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3794 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3800 * The main function for the transport service.
3802 * @param argc number of arguments from the command line
3803 * @param argv command line arguments
3804 * @return 0 ok, 1 on error
3807 main (int argc, char *const *argv)
3809 return (GNUNET_OK ==
3810 GNUNET_SERVICE_run (argc,
3813 GNUNET_SERVICE_OPTION_NONE,
3814 &run, NULL)) ? 0 : 1;
3817 /* end of gnunet-service-core.c */