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 1024
64 * Minimum bandwidth (out) to assign to any connected peer.
65 * Should be rather low; values larger than DEFAULT_BW_IN_OUT make no
68 #define MIN_BANDWIDTH_PER_PEER GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT
71 * After how much time past the "official" expiration time do
72 * we discard messages? Should not be zero since we may
73 * intentionally defer transmission until close to the deadline
74 * and then may be slightly past the deadline due to inaccuracy
75 * in sleep and our own CPU consumption.
77 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
80 * What is the maximum delay for a SET_KEY message?
82 #define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
85 * How long do we wait for SET_KEY confirmation initially?
87 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 1)
90 * What is the maximum delay for a PING message?
92 #define MAX_PING_DELAY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 2)
95 * What is the maximum delay for a PONG message?
97 #define MAX_PONG_DELAY GNUNET_TIME_relative_multiply (MAX_PING_DELAY, 2)
100 * What is the minimum frequency for a PING message?
102 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
105 * How often do we recalculate bandwidth quotas?
107 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
110 * What is the priority for a SET_KEY message?
112 #define SET_KEY_PRIORITY 0xFFFFFF
115 * What is the priority for a PING message?
117 #define PING_PRIORITY 0xFFFFFF
120 * What is the priority for a PONG message?
122 #define PONG_PRIORITY 0xFFFFFF
125 * How many messages do we queue per peer at most? Must be at
128 #define MAX_PEER_QUEUE_SIZE 16
131 * How many non-mandatory messages do we queue per client at most?
133 #define MAX_CLIENT_QUEUE_SIZE 32
136 * What is the maximum age of a message for us to consider
137 * processing it? Note that this looks at the timestamp used
138 * by the other peer, so clock skew between machines does
139 * come into play here. So this should be picked high enough
140 * so that a little bit of clock skew does not prevent peers
141 * from connecting to us.
143 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
147 * State machine for our P2P encryption handshake. Everyone starts in
148 * "DOWN", if we receive the other peer's key (other peer initiated)
149 * we start in state RECEIVED (since we will immediately send our
150 * own); otherwise we start in SENT. If we get back a PONG from
151 * within either state, we move up to CONFIRMED (the PONG will always
152 * be sent back encrypted with the key we sent to the other peer).
154 enum PeerStateMachine
158 PEER_STATE_KEY_RECEIVED,
159 PEER_STATE_KEY_CONFIRMED
164 * Number of bytes (at the beginning) of "struct EncryptedMessage"
165 * that are NOT encrypted.
167 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t))
171 * Encapsulation for encrypted messages exchanged between
172 * peers. Followed by the actual encrypted data.
174 struct EncryptedMessage
177 * Message type is either CORE_ENCRYPTED_MESSAGE.
179 struct GNUNET_MessageHeader header;
182 * Random value used for IV generation. ENCRYPTED_HEADER_SIZE must
183 * be set to the offset of the *next* field.
185 uint32_t iv_seed GNUNET_PACKED;
188 * Hash of the plaintext (starting at 'sequence_number'), used to
189 * verify message integrity. Everything after this hash (including
190 * this hash itself) will be encrypted.
192 GNUNET_HashCode hmac;
195 * Sequence number, in network byte order. This field
196 * must be the first encrypted/decrypted field and the
197 * first byte that is hashed for the plaintext hash.
199 uint32_t sequence_number GNUNET_PACKED;
202 * Desired bandwidth (how much we should send to this peer / how
203 * much is the sender willing to receive)?
205 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
208 * Timestamp. Used to prevent reply of ancient messages
209 * (recent messages are caught with the sequence number).
211 struct GNUNET_TIME_AbsoluteNBO timestamp;
217 * We're sending an (encrypted) PING to the other peer to check if he
218 * can decrypt. The other peer should respond with a PONG with the
219 * same content, except this time encrypted with the receiver's key.
224 * Message type is CORE_PING.
226 struct GNUNET_MessageHeader header;
229 * Random number chosen to make reply harder.
231 uint32_t challenge GNUNET_PACKED;
234 * Intended target of the PING, used primarily to check
235 * that decryption actually worked.
237 struct GNUNET_PeerIdentity target;
243 * Response to a PING. Includes data from the original PING
244 * plus initial bandwidth quota information.
249 * Message type is CORE_PONG.
251 struct GNUNET_MessageHeader header;
254 * Random number proochosen to make reply harder. Must be
255 * first field after header (this is where we start to encrypt!).
257 uint32_t challenge GNUNET_PACKED;
262 uint32_t reserved GNUNET_PACKED;
265 * Desired bandwidth (how much we should send to this
266 * peer / how much is the sender willing to receive).
268 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
271 * Intended target of the PING, used primarily to check
272 * that decryption actually worked.
274 struct GNUNET_PeerIdentity target;
279 * Message transmitted to set (or update) a session key.
285 * Message type is either CORE_SET_KEY.
287 struct GNUNET_MessageHeader header;
290 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
292 int32_t sender_status GNUNET_PACKED;
295 * Purpose of the signature, will be
296 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
298 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
301 * At what time was this key created?
303 struct GNUNET_TIME_AbsoluteNBO creation_time;
306 * The encrypted session key.
308 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
311 * Who is the intended recipient?
313 struct GNUNET_PeerIdentity target;
316 * Signature of the stuff above (starting at purpose).
318 struct GNUNET_CRYPTO_RsaSignature signature;
324 * Message waiting for transmission. This struct
325 * is followed by the actual content of the message.
331 * We keep messages in a doubly linked list.
333 struct MessageEntry *next;
336 * We keep messages in a doubly linked list.
338 struct MessageEntry *prev;
341 * By when are we supposed to transmit this message?
343 struct GNUNET_TIME_Absolute deadline;
346 * By when are we supposed to transmit this message (after
349 struct GNUNET_TIME_Absolute slack_deadline;
352 * How important is this message to us?
354 unsigned int priority;
357 * If this is a SET_KEY message, what was our connection status when this
358 * message was queued?
360 enum PeerStateMachine sender_status;
363 * Is this a SET_KEY message?
368 * How long is the message? (number of bytes following
369 * the "struct MessageEntry", but not including the
370 * size of "struct MessageEntry" itself!)
375 * Was this message selected for transmission in the
376 * current round? GNUNET_YES or GNUNET_NO.
381 * Did we give this message some slack (delayed sending) previously
382 * (and hence should not give it any more slack)? GNUNET_YES or
393 * We keep neighbours in a linked list (for now).
395 struct Neighbour *next;
398 * Unencrypted messages destined for this peer.
400 struct MessageEntry *messages;
403 * Head of the batched, encrypted message queue (already ordered,
404 * transmit starting with the head).
406 struct MessageEntry *encrypted_head;
409 * Tail of the batched, encrypted message queue (already ordered,
410 * append new messages to tail)
412 struct MessageEntry *encrypted_tail;
415 * Handle for pending requests for transmission to this peer
416 * with the transport service. NULL if no request is pending.
418 struct GNUNET_TRANSPORT_TransmitHandle *th;
421 * Public key of the neighbour, NULL if we don't have it yet.
423 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
426 * We received a PING message before we got the "public_key"
427 * (or the SET_KEY). We keep it here until we have a key
428 * to decrypt it. NULL if no PING is pending.
430 struct PingMessage *pending_ping;
433 * We received a PONG message before we got the "public_key"
434 * (or the SET_KEY). We keep it here until we have a key
435 * to decrypt it. NULL if no PONG is pending.
437 struct PongMessage *pending_pong;
440 * Non-NULL if we are currently looking up HELLOs for this peer.
443 struct GNUNET_PEERINFO_IteratorContext *pitr;
446 * SetKeyMessage to transmit, NULL if we are not currently trying
449 struct SetKeyMessage *skm;
452 * Identity of the neighbour.
454 struct GNUNET_PeerIdentity peer;
457 * Key we use to encrypt our messages for the other peer
458 * (initialized by us when we do the handshake).
460 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
463 * Key we use to decrypt messages from the other peer
464 * (given to us by the other peer during the handshake).
466 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
469 * ID of task used for re-trying plaintext scheduling.
471 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
474 * ID of task used for re-trying SET_KEY and PING message.
476 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
479 * ID of task used for updating bandwidth quota for this neighbour.
481 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
484 * ID of task used for sending keep-alive pings.
486 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
489 * ID of task used for cleaning up dead neighbour entries.
491 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
494 * At what time did we generate our encryption key?
496 struct GNUNET_TIME_Absolute encrypt_key_created;
499 * At what time did the other peer generate the decryption key?
501 struct GNUNET_TIME_Absolute decrypt_key_created;
504 * At what time did we initially establish (as in, complete session
505 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
507 struct GNUNET_TIME_Absolute time_established;
510 * At what time did we last receive an encrypted message from the
511 * other peer? Should be zero if status != KEY_CONFIRMED.
513 struct GNUNET_TIME_Absolute last_activity;
516 * Last latency observed from this peer.
518 struct GNUNET_TIME_Relative last_latency;
521 * At what frequency are we currently re-trying SET_KEY messages?
523 struct GNUNET_TIME_Relative set_key_retry_frequency;
526 * Tracking bandwidth for sending to this peer.
528 struct GNUNET_BANDWIDTH_Tracker available_send_window;
531 * Tracking bandwidth for receiving from this peer.
533 struct GNUNET_BANDWIDTH_Tracker available_recv_window;
536 * How valueable were the messages of this peer recently?
538 unsigned long long current_preference;
541 * Bit map indicating which of the 32 sequence numbers before the last
542 * were received (good for accepting out-of-order packets and
543 * estimating reliability of the connection)
545 unsigned int last_packets_bitmap;
548 * last sequence number received on this connection (highest)
550 uint32_t last_sequence_number_received;
553 * last sequence number transmitted
555 uint32_t last_sequence_number_sent;
558 * Available bandwidth in for this peer (current target).
560 struct GNUNET_BANDWIDTH_Value32NBO bw_in;
563 * Available bandwidth out for this peer (current target).
565 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
568 * Internal bandwidth limit set for this peer (initially typically
569 * set to "-1"). Actual "bw_out" is MIN of
570 * "bpm_out_internal_limit" and "bw_out_external_limit".
572 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
575 * External bandwidth limit set for this peer by the
576 * peer that we are communicating with. "bw_out" is MIN of
577 * "bw_out_internal_limit" and "bw_out_external_limit".
579 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
582 * What was our PING challenge number (for this peer)?
584 uint32_t ping_challenge;
587 * What was the last distance to this peer as reported by the transports?
589 uint32_t last_distance;
592 * What is our connection status?
594 enum PeerStateMachine status;
597 * Are we currently connected to this neighbour?
605 * Data structure for each client connected to the core service.
610 * Clients are kept in a linked list.
615 * Handle for the client with the server API.
617 struct GNUNET_SERVER_Client *client_handle;
620 * Array of the types of messages this peer cares
621 * about (with "tcnt" entries). Allocated as part
622 * of this client struct, do not free!
624 const uint16_t *types;
627 * Options for messages this client cares about,
628 * see GNUNET_CORE_OPTION_ values.
633 * Number of types of incoming messages this client
634 * specifically cares about. Size of the "types" array.
644 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
649 static struct GNUNET_PeerIdentity my_identity;
654 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
659 struct GNUNET_SCHEDULER_Handle *sched;
662 * Handle to peerinfo service.
664 static struct GNUNET_PEERINFO_Handle *peerinfo;
669 const struct GNUNET_CONFIGURATION_Handle *cfg;
674 static struct GNUNET_TRANSPORT_Handle *transport;
677 * Linked list of our clients.
679 static struct Client *clients;
682 * Context for notifications we need to send to our clients.
684 static struct GNUNET_SERVER_NotificationContext *notifier;
687 * We keep neighbours in a linked list (for now).
689 static struct Neighbour *neighbours;
692 * For creating statistics.
694 static struct GNUNET_STATISTICS_Handle *stats;
697 * Sum of all preferences among all neighbours.
699 static unsigned long long preference_sum;
702 * Total number of neighbours we have.
704 static unsigned int neighbour_count;
707 * How much inbound bandwidth are we supposed to be using per second?
708 * FIXME: this value is not used!
710 static unsigned long long bandwidth_target_in_bps;
713 * How much outbound bandwidth are we supposed to be using per second?
715 static unsigned long long bandwidth_target_out_bps;
720 * A preference value for a neighbour was update. Update
721 * the preference sum accordingly.
723 * @param inc how much was a preference value increased?
726 update_preference_sum (unsigned long long inc)
729 unsigned long long os;
732 preference_sum += inc;
733 if (preference_sum >= os)
735 /* overflow! compensate by cutting all values in half! */
740 n->current_preference /= 2;
741 preference_sum += n->current_preference;
744 GNUNET_STATISTICS_set (stats, gettext_noop ("# total peer preference"), preference_sum, GNUNET_NO);
749 * Find the entry for the given neighbour.
751 * @param peer identity of the neighbour
752 * @return NULL if we are not connected, otherwise the
755 static struct Neighbour *
756 find_neighbour (const struct GNUNET_PeerIdentity *peer)
758 struct Neighbour *ret;
761 while ((ret != NULL) &&
762 (0 != memcmp (&ret->peer,
763 peer, sizeof (struct GNUNET_PeerIdentity))))
770 * Send a message to one of our clients.
772 * @param client target for the message
773 * @param msg message to transmit
774 * @param can_drop could this message be dropped if the
775 * client's queue is getting too large?
778 send_to_client (struct Client *client,
779 const struct GNUNET_MessageHeader *msg,
782 #if DEBUG_CORE_CLIENT
783 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
784 "Preparing to send %u bytes of message of type %u to client.\n",
785 (unsigned int) ntohs (msg->size),
786 (unsigned int) ntohs (msg->type));
788 GNUNET_SERVER_notification_context_unicast (notifier,
789 client->client_handle,
796 * Send a message to all of our current clients that have
797 * the right options set.
799 * @param msg message to multicast
800 * @param can_drop can this message be discarded if the queue is too long
801 * @param options mask to use
804 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
813 if (0 != (c->options & options))
815 #if DEBUG_CORE_CLIENT
816 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
817 "Sending message of type %u to client.\n",
818 (unsigned int) ntohs (msg->type));
820 send_to_client (c, msg, can_drop);
828 * Handle CORE_INIT request.
831 handle_client_init (void *cls,
832 struct GNUNET_SERVER_Client *client,
833 const struct GNUNET_MessageHeader *message)
835 const struct InitMessage *im;
836 struct InitReplyMessage irm;
839 const uint16_t *types;
842 struct ConnectNotifyMessage cnm;
845 #if DEBUG_CORE_CLIENT
846 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
847 "Client connecting to core service with `%s' message\n",
850 /* check that we don't have an entry already */
854 if (client == c->client_handle)
857 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
862 msize = ntohs (message->size);
863 if (msize < sizeof (struct InitMessage))
866 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
869 GNUNET_SERVER_notification_context_add (notifier, client);
870 im = (const struct InitMessage *) message;
871 types = (const uint16_t *) &im[1];
872 msize -= sizeof (struct InitMessage);
873 c = GNUNET_malloc (sizeof (struct Client) + msize);
874 c->client_handle = client;
877 c->tcnt = msize / sizeof (uint16_t);
878 c->types = (const uint16_t *) &c[1];
879 wtypes = (uint16_t *) &c[1];
880 for (i=0;i<c->tcnt;i++)
881 wtypes[i] = ntohs (types[i]);
882 c->options = ntohl (im->options);
883 #if DEBUG_CORE_CLIENT
884 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
885 "Client %p is interested in %u message types\n",
887 (unsigned int) c->tcnt);
889 /* send init reply message */
890 irm.header.size = htons (sizeof (struct InitReplyMessage));
891 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
892 irm.reserved = htonl (0);
893 memcpy (&irm.publicKey,
895 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
896 #if DEBUG_CORE_CLIENT
897 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
898 "Sending `%s' message to client.\n", "INIT_REPLY");
900 send_to_client (c, &irm.header, GNUNET_NO);
901 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
903 /* notify new client about existing neighbours */
904 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
905 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
909 if (n->status == PEER_STATE_KEY_CONFIRMED)
911 #if DEBUG_CORE_CLIENT
912 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
913 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
915 cnm.distance = htonl (n->last_distance);
916 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
918 send_to_client (c, &cnm.header, GNUNET_NO);
923 GNUNET_SERVER_receive_done (client, GNUNET_OK);
928 * A client disconnected, clean up.
931 * @param client identification of the client
934 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
941 #if DEBUG_CORE_CLIENT
942 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
943 "Client %p has disconnected from core service.\n",
950 if (client == pos->client_handle)
955 prev->next = pos->next;
962 /* client never sent INIT */
967 * Handle REQUEST_INFO request.
970 handle_client_request_info (void *cls,
971 struct GNUNET_SERVER_Client *client,
972 const struct GNUNET_MessageHeader *message)
974 const struct RequestInfoMessage *rcm;
976 struct ConfigurationInfoMessage cim;
979 unsigned long long old_preference;
980 struct GNUNET_SERVER_TransmitContext *tc;
982 #if DEBUG_CORE_CLIENT
983 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
984 "Core service receives `%s' request.\n", "REQUEST_INFO");
986 rcm = (const struct RequestInfoMessage *) message;
987 n = find_neighbour (&rcm->peer);
988 memset (&cim, 0, sizeof (cim));
991 want_reserv = ntohl (rcm->reserve_inbound);
992 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
994 n->bw_out_internal_limit = rcm->limit_outbound;
995 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
996 n->bw_out_external_limit);
997 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
999 GNUNET_TRANSPORT_set_quota (transport,
1003 GNUNET_TIME_UNIT_FOREVER_REL,
1006 if (want_reserv < 0)
1008 got_reserv = want_reserv;
1010 else if (want_reserv > 0)
1012 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1013 want_reserv).value == 0)
1014 got_reserv = want_reserv;
1016 got_reserv = 0; /* all or nothing */
1020 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1022 old_preference = n->current_preference;
1023 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1024 if (old_preference > n->current_preference)
1026 /* overflow; cap at maximum value */
1027 n->current_preference = ULLONG_MAX;
1029 update_preference_sum (n->current_preference - old_preference);
1030 #if DEBUG_CORE_QUOTA
1031 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1032 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1034 GNUNET_i2s (&rcm->peer),
1037 cim.reserved_amount = htonl (got_reserv);
1038 cim.bw_in = n->bw_in;
1039 cim.bw_out = n->bw_out;
1040 cim.preference = n->current_preference;
1042 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1043 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1044 cim.peer = rcm->peer;
1046 #if DEBUG_CORE_CLIENT
1047 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1048 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1050 tc = GNUNET_SERVER_transmit_context_create (client);
1051 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1052 GNUNET_SERVER_transmit_context_run (tc,
1053 GNUNET_TIME_UNIT_FOREVER_REL);
1058 * Free the given entry for the neighbour (it has
1059 * already been removed from the list at this point).
1061 * @param n neighbour to free
1064 free_neighbour (struct Neighbour *n)
1066 struct MessageEntry *m;
1069 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1070 "Destroying neighbour entry for peer `%4s'\n",
1071 GNUNET_i2s (&n->peer));
1073 if (n->pitr != NULL)
1075 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1080 GNUNET_free (n->skm);
1083 while (NULL != (m = n->messages))
1085 n->messages = m->next;
1088 while (NULL != (m = n->encrypted_head))
1090 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1097 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1100 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1101 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1102 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1103 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1104 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1105 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1106 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1107 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1108 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1109 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1110 if (n->status == PEER_STATE_KEY_CONFIRMED)
1111 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1112 GNUNET_free_non_null (n->public_key);
1113 GNUNET_free_non_null (n->pending_ping);
1114 GNUNET_free_non_null (n->pending_pong);
1120 * Check if we have encrypted messages for the specified neighbour
1121 * pending, and if so, check with the transport about sending them
1124 * @param n neighbour to check.
1126 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1130 * Encrypt size bytes from in and write the result to out. Use the
1131 * key for outbound traffic of the given neighbour.
1133 * @param n neighbour we are sending to
1134 * @param iv initialization vector to use
1135 * @param in ciphertext
1136 * @param out plaintext
1137 * @param size size of in/out
1138 * @return GNUNET_OK on success
1141 do_encrypt (struct Neighbour *n,
1142 const GNUNET_HashCode * iv,
1143 const void *in, void *out, size_t size)
1145 if (size != (uint16_t) size)
1150 GNUNET_assert (size ==
1151 GNUNET_CRYPTO_aes_encrypt (in,
1155 GNUNET_CRYPTO_AesInitializationVector
1157 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1159 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1160 "Encrypted %u bytes for `%4s' using key %u\n",
1161 (unsigned int) size,
1162 GNUNET_i2s (&n->peer),
1163 (unsigned int) n->encrypt_key.crc32);
1170 * Consider freeing the given neighbour since we may not need
1171 * to keep it around anymore.
1173 * @param n neighbour to consider discarding
1176 consider_free_neighbour (struct Neighbour *n);
1180 * Task triggered when a neighbour entry is about to time out
1181 * (and we should prevent this by sending a PING).
1183 * @param cls the 'struct Neighbour'
1184 * @param tc scheduler context (not used)
1187 send_keep_alive (void *cls,
1188 const struct GNUNET_SCHEDULER_TaskContext *tc)
1190 struct Neighbour *n = cls;
1191 struct GNUNET_TIME_Relative retry;
1192 struct GNUNET_TIME_Relative left;
1193 struct MessageEntry *me;
1194 struct PingMessage pp;
1195 struct PingMessage *pm;
1197 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1199 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1200 sizeof (struct PingMessage));
1201 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1202 me->priority = PING_PRIORITY;
1203 me->size = sizeof (struct PingMessage);
1204 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1208 pm = (struct PingMessage *) &me[1];
1209 pm->header.size = htons (sizeof (struct PingMessage));
1210 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1211 pp.challenge = htonl (n->ping_challenge);
1212 pp.target = n->peer;
1214 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1215 "Encrypting `%s' message with challenge %u for `%4s' using key %u.\n",
1217 (unsigned int) n->ping_challenge,
1218 GNUNET_i2s (&n->peer),
1219 (unsigned int) n->encrypt_key.crc32);
1222 &n->peer.hashPubKey,
1225 sizeof (struct PingMessage) -
1226 sizeof (struct GNUNET_MessageHeader));
1227 process_encrypted_neighbour_queue (n);
1228 /* reschedule PING job */
1229 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1230 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1231 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1232 MIN_PING_FREQUENCY);
1234 = GNUNET_SCHEDULER_add_delayed (sched,
1243 * Task triggered when a neighbour entry might have gotten stale.
1245 * @param cls the 'struct Neighbour'
1246 * @param tc scheduler context (not used)
1249 consider_free_task (void *cls,
1250 const struct GNUNET_SCHEDULER_TaskContext *tc)
1252 struct Neighbour *n = cls;
1254 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1255 consider_free_neighbour (n);
1260 * Consider freeing the given neighbour since we may not need
1261 * to keep it around anymore.
1263 * @param n neighbour to consider discarding
1266 consider_free_neighbour (struct Neighbour *n)
1268 struct Neighbour *pos;
1269 struct Neighbour *prev;
1270 struct GNUNET_TIME_Relative left;
1272 if ( (n->th != NULL) ||
1273 (n->pitr != NULL) ||
1274 (n->status == PEER_STATE_KEY_CONFIRMED) ||
1275 (GNUNET_YES == n->is_connected) )
1276 return; /* no chance */
1278 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1279 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1282 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1283 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1284 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1286 &consider_free_task,
1290 /* actually free the neighbour... */
1299 neighbours = n->next;
1301 prev->next = n->next;
1302 GNUNET_assert (neighbour_count > 0);
1304 GNUNET_STATISTICS_set (stats,
1305 gettext_noop ("# neighbour entries allocated"),
1313 * Function called when the transport service is ready to
1314 * receive an encrypted message for the respective peer
1316 * @param cls neighbour to use message from
1317 * @param size number of bytes we can transmit
1318 * @param buf where to copy the message
1319 * @return number of bytes transmitted
1322 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1324 struct Neighbour *n = cls;
1325 struct MessageEntry *m;
1330 m = n->encrypted_head;
1334 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1335 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1336 GNUNET_i2s (&n->peer));
1340 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1347 GNUNET_assert (size >= m->size);
1348 memcpy (cbuf, &m[1], m->size);
1350 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1353 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1354 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1355 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1357 GNUNET_i2s (&n->peer));
1359 process_encrypted_neighbour_queue (n);
1364 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1365 "Transmission of message of type %u and size %u failed\n",
1366 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1367 (unsigned int) m->size);
1371 consider_free_neighbour (n);
1377 * Check if we have plaintext messages for the specified neighbour
1378 * pending, and if so, consider batching and encrypting them (and
1379 * then trigger processing of the encrypted queue if needed).
1381 * @param n neighbour to check.
1383 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1387 * Check if we have encrypted messages for the specified neighbour
1388 * pending, and if so, check with the transport about sending them
1391 * @param n neighbour to check.
1394 process_encrypted_neighbour_queue (struct Neighbour *n)
1396 struct MessageEntry *m;
1399 return; /* request already pending */
1400 m = n->encrypted_head;
1403 /* encrypted queue empty, try plaintext instead */
1404 process_plaintext_neighbour_queue (n);
1408 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1409 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1410 (unsigned int) m->size,
1411 GNUNET_i2s (&n->peer),
1412 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).
1416 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1419 GNUNET_TIME_absolute_get_remaining
1421 ¬ify_encrypted_transmit_ready,
1425 /* message request too large or duplicate request */
1427 /* discard encrypted message */
1428 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1432 process_encrypted_neighbour_queue (n);
1438 * Decrypt size bytes from in and write the result to out. Use the
1439 * key for inbound traffic of the given neighbour. This function does
1440 * NOT do any integrity-checks on the result.
1442 * @param n neighbour we are receiving from
1443 * @param iv initialization vector to use
1444 * @param in ciphertext
1445 * @param out plaintext
1446 * @param size size of in/out
1447 * @return GNUNET_OK on success
1450 do_decrypt (struct Neighbour *n,
1451 const GNUNET_HashCode * iv,
1452 const void *in, void *out, size_t size)
1454 if (size != (uint16_t) size)
1459 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1460 (n->status != PEER_STATE_KEY_CONFIRMED))
1462 GNUNET_break_op (0);
1463 return GNUNET_SYSERR;
1466 GNUNET_CRYPTO_aes_decrypt (in,
1470 GNUNET_CRYPTO_AesInitializationVector *) iv,
1474 return GNUNET_SYSERR;
1476 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1478 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1479 "Decrypted %u bytes from `%4s' using key %u\n",
1480 (unsigned int) size,
1481 GNUNET_i2s (&n->peer),
1482 (unsigned int) n->decrypt_key.crc32);
1489 * Select messages for transmission. This heuristic uses a combination
1490 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1491 * and priority-based discard (in case no feasible schedule exist) and
1492 * speculative optimization (defer any kind of transmission until
1493 * we either create a batch of significant size, 25% of max, or until
1494 * we are close to a deadline). Furthermore, when scheduling the
1495 * heuristic also packs as many messages into the batch as possible,
1496 * starting with those with the earliest deadline. Yes, this is fun.
1498 * @param n neighbour to select messages from
1499 * @param size number of bytes to select for transmission
1500 * @param retry_time set to the time when we should try again
1501 * (only valid if this function returns zero)
1502 * @return number of bytes selected, or 0 if we decided to
1503 * defer scheduling overall; in that case, retry_time is set.
1506 select_messages (struct Neighbour *n,
1507 size_t size, struct GNUNET_TIME_Relative *retry_time)
1509 struct MessageEntry *pos;
1510 struct MessageEntry *min;
1511 struct MessageEntry *last;
1512 unsigned int min_prio;
1513 struct GNUNET_TIME_Absolute t;
1514 struct GNUNET_TIME_Absolute now;
1515 struct GNUNET_TIME_Relative delta;
1517 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1520 unsigned int queue_size;
1521 int discard_low_prio;
1523 GNUNET_assert (NULL != n->messages);
1524 now = GNUNET_TIME_absolute_get ();
1525 /* last entry in linked list of messages processed */
1527 /* should we remove the entry with the lowest
1528 priority from consideration for scheduling at the
1539 discard_low_prio = GNUNET_YES;
1540 while (GNUNET_YES == discard_low_prio)
1543 min_prio = UINT_MAX;
1544 discard_low_prio = GNUNET_NO;
1545 /* calculate number of bytes available for transmission at time "t" */
1546 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1548 /* how many bytes have we (hypothetically) scheduled so far */
1550 /* maximum time we can wait before transmitting anything
1551 and still make all of our deadlines */
1552 slack = GNUNET_TIME_UNIT_FOREVER_REL;
1554 /* note that we use "*2" here because we want to look
1555 a bit further into the future; much more makes no
1556 sense since new message might be scheduled in the
1558 while ((pos != NULL) && (off < size * 2))
1560 if (pos->do_transmit == GNUNET_YES)
1562 /* already removed from consideration */
1566 if (discard_low_prio == GNUNET_NO)
1568 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1569 if (delta.value > 0)
1571 // FIXME: HUH? Check!
1573 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1576 if (avail < pos->size)
1578 // FIXME: HUH? Check!
1579 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1584 /* update slack, considering both its absolute deadline
1585 and relative deadlines caused by other messages
1586 with their respective load */
1587 slack = GNUNET_TIME_relative_min (slack,
1588 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1590 if (pos->deadline.value <= now.value)
1593 slack = GNUNET_TIME_UNIT_ZERO;
1595 else if (GNUNET_YES == pos->got_slack)
1597 /* should be soon now! */
1598 slack = GNUNET_TIME_relative_min (slack,
1599 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1604 GNUNET_TIME_relative_min (slack,
1605 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1606 pos->got_slack = GNUNET_YES;
1607 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1608 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
1613 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1614 if (pos->priority <= min_prio)
1616 /* update min for discard */
1617 min_prio = pos->priority;
1622 if (discard_low_prio)
1624 GNUNET_assert (min != NULL);
1625 /* remove lowest-priority entry from consideration */
1626 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1630 /* guard against sending "tiny" messages with large headers without
1632 if ( (slack.value > GNUNET_CONSTANTS_MAX_CORK_DELAY.value) &&
1634 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1636 /* less than 25% of message would be filled with deadlines still
1637 being met if we delay by one second or more; so just wait for
1638 more data; but do not wait longer than 1s (since we don't want
1639 to delay messages for a really long time either). */
1640 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1641 /* reset do_transmit values for next time */
1644 pos->do_transmit = GNUNET_NO;
1648 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1649 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1650 (unsigned long long) retry_time->value,
1652 (unsigned int) size);
1656 /* select marked messages (up to size) for transmission */
1661 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1663 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1667 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1668 "Selecting message of size %u for transmission\n",
1669 (unsigned int) pos->size);
1675 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1676 "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
1677 (unsigned int) pos->size,
1680 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1685 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1686 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1687 (unsigned long long) off, (unsigned long long) tsize,
1688 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
1689 GNUNET_i2s (&n->peer));
1696 * Batch multiple messages into a larger buffer.
1698 * @param n neighbour to take messages from
1699 * @param buf target buffer
1700 * @param size size of buf
1701 * @param deadline set to transmission deadline for the result
1702 * @param retry_time set to the time when we should try again
1703 * (only valid if this function returns zero)
1704 * @param priority set to the priority of the batch
1705 * @return number of bytes written to buf (can be zero)
1708 batch_message (struct Neighbour *n,
1711 struct GNUNET_TIME_Absolute *deadline,
1712 struct GNUNET_TIME_Relative *retry_time,
1713 unsigned int *priority)
1715 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1716 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1717 struct MessageEntry *pos;
1718 struct MessageEntry *prev;
1719 struct MessageEntry *next;
1724 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1725 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1726 if (0 == select_messages (n, size, retry_time))
1729 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1730 "No messages selected, will try again in %llu ms\n",
1735 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1736 ntm->distance = htonl (n->last_distance);
1737 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1738 ntm->peer = n->peer;
1741 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1744 if (GNUNET_YES == pos->do_transmit)
1746 GNUNET_assert (pos->size <= size);
1747 /* do notifications */
1748 /* FIXME: track if we have *any* client that wants
1749 full notifications and only do this if that is
1751 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1753 memcpy (&ntm[1], &pos[1], pos->size);
1754 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1755 sizeof (struct GNUNET_MessageHeader));
1756 send_to_all_clients (&ntm->header,
1758 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1762 /* message too large for 'full' notifications, we do at
1763 least the 'hdr' type */
1766 sizeof (struct GNUNET_MessageHeader));
1768 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1770 send_to_all_clients (&ntm->header,
1772 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1774 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1775 "Encrypting %u bytes with message of type %u and size %u\n",
1777 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
1778 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
1780 /* copy for encrypted transmission */
1781 memcpy (&buf[ret], &pos[1], pos->size);
1784 *priority += pos->priority;
1786 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1787 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1788 (unsigned int) pos->size,
1789 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1791 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1805 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1806 "Deadline for message batch is %llu ms\n",
1807 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1814 * Remove messages with deadlines that have long expired from
1817 * @param n neighbour to inspect
1820 discard_expired_messages (struct Neighbour *n)
1822 struct MessageEntry *prev;
1823 struct MessageEntry *next;
1824 struct MessageEntry *pos;
1825 struct GNUNET_TIME_Absolute now;
1826 struct GNUNET_TIME_Relative delta;
1828 now = GNUNET_TIME_absolute_get ();
1834 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1835 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1838 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1839 "Message is %llu ms past due, discarding.\n",
1856 * Signature of the main function of a task.
1858 * @param cls closure
1859 * @param tc context information (why was this task triggered now)
1862 retry_plaintext_processing (void *cls,
1863 const struct GNUNET_SCHEDULER_TaskContext *tc)
1865 struct Neighbour *n = cls;
1867 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1868 process_plaintext_neighbour_queue (n);
1873 * Send our key (and encrypted PING) to the other peer.
1875 * @param n the other peer
1877 static void send_key (struct Neighbour *n);
1880 * Task that will retry "send_key" if our previous attempt failed
1884 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1886 struct Neighbour *n = cls;
1889 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1890 "Retrying key transmission to `%4s'\n",
1891 GNUNET_i2s (&n->peer));
1893 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1894 n->set_key_retry_frequency =
1895 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1901 * Check if we have plaintext messages for the specified neighbour
1902 * pending, and if so, consider batching and encrypting them (and
1903 * then trigger processing of the encrypted queue if needed).
1905 * @param n neighbour to check.
1908 process_plaintext_neighbour_queue (struct Neighbour *n)
1910 char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)]; /* plaintext */
1913 struct EncryptedMessage *em; /* encrypted message */
1914 struct EncryptedMessage *ph; /* plaintext header */
1915 struct MessageEntry *me;
1916 unsigned int priority;
1917 struct GNUNET_TIME_Absolute deadline;
1918 struct GNUNET_TIME_Relative retry_time;
1921 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1923 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1924 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1928 case PEER_STATE_DOWN:
1931 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1932 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1933 GNUNET_i2s(&n->peer));
1936 case PEER_STATE_KEY_SENT:
1937 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1938 n->retry_set_key_task
1939 = GNUNET_SCHEDULER_add_delayed (sched,
1940 n->set_key_retry_frequency,
1941 &set_key_retry_task, n);
1943 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1944 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1945 GNUNET_i2s(&n->peer));
1948 case PEER_STATE_KEY_RECEIVED:
1949 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1950 n->retry_set_key_task
1951 = GNUNET_SCHEDULER_add_delayed (sched,
1952 n->set_key_retry_frequency,
1953 &set_key_retry_task, n);
1955 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1956 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1957 GNUNET_i2s(&n->peer));
1960 case PEER_STATE_KEY_CONFIRMED:
1961 /* ready to continue */
1964 discard_expired_messages (n);
1965 if (n->messages == NULL)
1968 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1969 "Plaintext message queue for `%4s' is empty.\n",
1970 GNUNET_i2s(&n->peer));
1972 return; /* no pending messages */
1974 if (n->encrypted_head != NULL)
1977 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1978 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1979 GNUNET_i2s(&n->peer));
1981 return; /* wait for messages already encrypted to be
1984 ph = (struct EncryptedMessage *) pbuf;
1985 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1987 used = sizeof (struct EncryptedMessage);
1988 used += batch_message (n,
1990 GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
1991 &deadline, &retry_time, &priority);
1992 if (used == sizeof (struct EncryptedMessage))
1995 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1996 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1997 GNUNET_i2s(&n->peer));
1999 /* no messages selected for sending, try again later... */
2000 n->retry_plaintext_task =
2001 GNUNET_SCHEDULER_add_delayed (sched,
2003 &retry_plaintext_processing, n);
2006 #if DEBUG_CORE_QUOTA
2007 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2008 "Sending %u b/s as new limit to peer `%4s'\n",
2009 (unsigned int) ntohl (n->bw_in.value__),
2010 GNUNET_i2s (&n->peer));
2012 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX));
2013 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2014 ph->inbound_bw_limit = n->bw_in;
2015 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2017 /* setup encryption message header */
2018 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2019 me->deadline = deadline;
2020 me->priority = priority;
2022 em = (struct EncryptedMessage *) &me[1];
2023 em->header.size = htons (used);
2024 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2025 em->iv_seed = ph->iv_seed;
2026 esize = used - ENCRYPTED_HEADER_SIZE;
2027 GNUNET_CRYPTO_hmac (&n->encrypt_key,
2028 &ph->sequence_number,
2029 esize - sizeof (GNUNET_HashCode),
2031 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
2033 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2034 "Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
2035 (unsigned int) (esize - sizeof (GNUNET_HashCode)),
2036 GNUNET_h2s (&ph->hmac),
2041 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2042 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2043 (unsigned int) esize,
2044 GNUNET_i2s(&n->peer),
2045 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2047 GNUNET_assert (GNUNET_OK ==
2052 /* append to transmission list */
2053 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2057 process_encrypted_neighbour_queue (n);
2062 * Function that recalculates the bandwidth quota for the
2063 * given neighbour and transmits it to the transport service.
2065 * @param cls neighbour for the quota update
2069 neighbour_quota_update (void *cls,
2070 const struct GNUNET_SCHEDULER_TaskContext *tc);
2074 * Schedule the task that will recalculate the bandwidth
2075 * quota for this peer (and possibly force a disconnect of
2076 * idle peers by calculating a bandwidth of zero).
2079 schedule_quota_update (struct Neighbour *n)
2081 GNUNET_assert (n->quota_update_task ==
2082 GNUNET_SCHEDULER_NO_TASK);
2083 n->quota_update_task
2084 = GNUNET_SCHEDULER_add_delayed (sched,
2085 QUOTA_UPDATE_FREQUENCY,
2086 &neighbour_quota_update,
2092 * Initialize a new 'struct Neighbour'.
2094 * @param pid ID of the new neighbour
2095 * @return handle for the new neighbour
2097 static struct Neighbour *
2098 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2100 struct Neighbour *n;
2101 struct GNUNET_TIME_Absolute now;
2104 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2105 "Creating neighbour entry for peer `%4s'\n",
2108 n = GNUNET_malloc (sizeof (struct Neighbour));
2109 n->next = neighbours;
2112 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2114 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2115 now = GNUNET_TIME_absolute_get ();
2116 n->encrypt_key_created = now;
2117 n->last_activity = now;
2118 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2119 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2120 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2121 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2122 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2123 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2125 neighbour_quota_update (n, NULL);
2126 consider_free_neighbour (n);
2132 * Handle CORE_SEND request.
2135 * @param client the client issuing the request
2136 * @param message the "struct SendMessage"
2139 handle_client_send (void *cls,
2140 struct GNUNET_SERVER_Client *client,
2141 const struct GNUNET_MessageHeader *message)
2143 const struct SendMessage *sm;
2144 struct Neighbour *n;
2145 struct MessageEntry *prev;
2146 struct MessageEntry *pos;
2147 struct MessageEntry *e;
2148 struct MessageEntry *min_prio_entry;
2149 struct MessageEntry *min_prio_prev;
2150 unsigned int min_prio;
2151 unsigned int queue_size;
2154 msize = ntohs (message->size);
2156 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2160 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2163 sm = (const struct SendMessage *) message;
2164 msize -= sizeof (struct SendMessage);
2165 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2167 /* FIXME: should we not allow loopback-injection here? */
2170 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2173 n = find_neighbour (&sm->peer);
2175 n = create_neighbour (&sm->peer);
2177 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2178 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2180 (unsigned int) msize,
2181 GNUNET_i2s (&sm->peer));
2183 /* bound queue size */
2184 discard_expired_messages (n);
2185 min_prio = UINT32_MAX;
2186 min_prio_entry = NULL;
2187 min_prio_prev = NULL;
2193 if (pos->priority < min_prio)
2195 min_prio_entry = pos;
2196 min_prio_prev = prev;
2197 min_prio = pos->priority;
2203 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2206 if (ntohl(sm->priority) <= min_prio)
2208 /* discard new entry */
2210 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2211 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2213 (unsigned int) MAX_PEER_QUEUE_SIZE,
2214 (unsigned int) msize,
2215 (unsigned int) ntohs (message->type));
2218 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2221 /* discard "min_prio_entry" */
2223 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2224 "Queue full, discarding existing older request\n");
2226 if (min_prio_prev == NULL)
2227 n->messages = min_prio_entry->next;
2229 min_prio_prev->next = min_prio_entry->next;
2230 GNUNET_free (min_prio_entry);
2234 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2235 "Adding transmission request for `%4s' of size %u to queue\n",
2236 GNUNET_i2s (&sm->peer),
2237 (unsigned int) msize);
2239 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2240 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2241 e->priority = ntohl (sm->priority);
2243 memcpy (&e[1], &sm[1], msize);
2245 /* insert, keep list sorted by deadline */
2248 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2259 /* consider scheduling now */
2260 process_plaintext_neighbour_queue (n);
2262 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2267 * Function called when the transport service is ready to
2268 * receive a message. Only resets 'n->th' to NULL.
2270 * @param cls neighbour to use message from
2271 * @param size number of bytes we can transmit
2272 * @param buf where to copy the message
2273 * @return number of bytes transmitted
2276 notify_transport_connect_done (void *cls, size_t size, void *buf)
2278 struct Neighbour *n = cls;
2283 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2284 _("Failed to connect to `%4s': transport failed to connect\n"),
2285 GNUNET_i2s (&n->peer));
2288 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2289 _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2290 GNUNET_i2s (&n->peer));
2291 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2292 GNUNET_SCHEDULER_cancel (sched,
2293 n->retry_set_key_task);
2294 n->retry_set_key_task = GNUNET_SCHEDULER_add_now (sched,
2295 &set_key_retry_task,
2302 * Handle CORE_REQUEST_CONNECT request.
2305 * @param client the client issuing the request
2306 * @param message the "struct ConnectMessage"
2309 handle_client_request_connect (void *cls,
2310 struct GNUNET_SERVER_Client *client,
2311 const struct GNUNET_MessageHeader *message)
2313 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2314 struct Neighbour *n;
2315 struct GNUNET_TIME_Relative timeout;
2317 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2320 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2323 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2324 n = find_neighbour (&cm->peer);
2326 n = create_neighbour (&cm->peer);
2327 if ( (GNUNET_YES == n->is_connected) ||
2329 return; /* already connected, or at least trying */
2330 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2332 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2333 "Core received `%s' request for `%4s', will try to establish connection\n",
2335 GNUNET_i2s (&cm->peer));
2337 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2338 /* ask transport to connect to the peer */
2339 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2341 sizeof (struct GNUNET_MessageHeader), 0,
2343 ¬ify_transport_connect_done,
2345 GNUNET_break (NULL != n->th);
2350 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2351 * the neighbour's struct and retry send_key. Or, if we did not get a
2352 * HELLO, just do nothing.
2354 * @param cls the 'struct Neighbour' to retry sending the key for
2355 * @param peer the peer for which this is the HELLO
2356 * @param hello HELLO message of that peer
2357 * @param trust amount of trust we currently have in that peer
2360 process_hello_retry_send_key (void *cls,
2361 const struct GNUNET_PeerIdentity *peer,
2362 const struct GNUNET_HELLO_Message *hello,
2365 struct Neighbour *n = cls;
2370 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2371 "Entered `%s' and `%s' is NULL!\n",
2372 "process_hello_retry_send_key",
2376 if (n->public_key != NULL)
2378 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2380 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2381 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2383 GNUNET_STATISTICS_update (stats,
2384 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2391 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2392 _("Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n"),
2393 GNUNET_i2s (&n->peer));
2394 GNUNET_STATISTICS_update (stats,
2395 gettext_noop ("# Delayed connecting due to lack of public key"),
2398 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2399 n->retry_set_key_task
2400 = GNUNET_SCHEDULER_add_delayed (sched,
2401 n->set_key_retry_frequency,
2402 &set_key_retry_task, n);
2408 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2409 "Entered `%s' for peer `%4s'\n",
2410 "process_hello_retry_send_key",
2413 if (n->public_key != NULL)
2415 /* already have public key, why are we here? */
2421 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2422 "Received new `%s' message for `%4s', initiating key exchange.\n",
2427 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2428 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2430 GNUNET_STATISTICS_update (stats,
2431 gettext_noop ("# Error extracting public key from HELLO"),
2434 GNUNET_free (n->public_key);
2435 n->public_key = NULL;
2437 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2438 "GNUNET_HELLO_get_key returned awfully\n");
2446 * Send our key (and encrypted PING) to the other peer.
2448 * @param n the other peer
2451 send_key (struct Neighbour *n)
2453 struct MessageEntry *pos;
2454 struct SetKeyMessage *sm;
2455 struct MessageEntry *me;
2456 struct PingMessage pp;
2457 struct PingMessage *pm;
2459 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2461 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2462 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2464 if (n->pitr != NULL)
2467 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2468 "Key exchange in progress with `%4s'.\n",
2469 GNUNET_i2s (&n->peer));
2471 return; /* already in progress */
2473 if (GNUNET_YES != n->is_connected)
2476 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2477 "Not yet connected to peer `%4s'!\n",
2478 GNUNET_i2s (&n->peer));
2482 GNUNET_STATISTICS_update (stats,
2483 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
2486 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2488 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2490 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2491 ¬ify_encrypted_transmit_ready,
2497 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2498 "Asked to perform key exchange with `%4s'.\n",
2499 GNUNET_i2s (&n->peer));
2501 if (n->public_key == NULL)
2503 /* lookup n's public key, then try again */
2505 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2506 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2507 GNUNET_i2s (&n->peer));
2509 GNUNET_assert (n->pitr == NULL);
2510 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2513 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2514 &process_hello_retry_send_key, n);
2517 pos = n->encrypted_head;
2520 if (GNUNET_YES == pos->is_setkey)
2522 if (pos->sender_status == n->status)
2525 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2526 "`%s' message for `%4s' queued already\n",
2528 GNUNET_i2s (&n->peer));
2530 goto trigger_processing;
2532 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2537 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2538 "Removing queued `%s' message for `%4s', will create a new one\n",
2540 GNUNET_i2s (&n->peer));
2550 case PEER_STATE_DOWN:
2551 n->status = PEER_STATE_KEY_SENT;
2553 case PEER_STATE_KEY_SENT:
2555 case PEER_STATE_KEY_RECEIVED:
2557 case PEER_STATE_KEY_CONFIRMED:
2565 /* first, set key message */
2566 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2567 sizeof (struct SetKeyMessage) +
2568 sizeof (struct PingMessage));
2569 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2570 me->priority = SET_KEY_PRIORITY;
2571 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
2572 me->is_setkey = GNUNET_YES;
2573 me->got_slack = GNUNET_YES; /* do not defer this one! */
2574 me->sender_status = n->status;
2575 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2579 sm = (struct SetKeyMessage *) &me[1];
2580 sm->header.size = htons (sizeof (struct SetKeyMessage));
2581 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2582 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2583 PEER_STATE_KEY_SENT : n->status));
2585 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2586 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2587 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2588 sizeof (struct GNUNET_PeerIdentity));
2589 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2590 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2591 sm->target = n->peer;
2592 GNUNET_assert (GNUNET_OK ==
2593 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2595 GNUNET_CRYPTO_AesSessionKey),
2597 &sm->encrypted_key));
2598 GNUNET_assert (GNUNET_OK ==
2599 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2601 pm = (struct PingMessage *) &sm[1];
2602 pm->header.size = htons (sizeof (struct PingMessage));
2603 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2604 pp.challenge = htonl (n->ping_challenge);
2605 pp.target = n->peer;
2607 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2608 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u.\n",
2610 (unsigned int) n->ping_challenge,
2611 GNUNET_i2s (&n->peer),
2612 (unsigned int) n->encrypt_key.crc32);
2615 &n->peer.hashPubKey,
2618 sizeof (struct PingMessage) -
2619 sizeof (struct GNUNET_MessageHeader));
2620 GNUNET_STATISTICS_update (stats,
2621 gettext_noop ("# SET_KEY and PING messages created"),
2625 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2626 "Have %llu ms left for `%s' transmission.\n",
2627 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2631 /* trigger queue processing */
2632 process_encrypted_neighbour_queue (n);
2633 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2634 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2635 n->retry_set_key_task
2636 = GNUNET_SCHEDULER_add_delayed (sched,
2637 n->set_key_retry_frequency,
2638 &set_key_retry_task, n);
2643 * We received a SET_KEY message. Validate and update
2644 * our key material and status.
2646 * @param n the neighbour from which we received message m
2647 * @param m the set key message we received
2650 handle_set_key (struct Neighbour *n,
2651 const struct SetKeyMessage *m);
2655 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2656 * the neighbour's struct and retry handling the set_key message. Or,
2657 * if we did not get a HELLO, just free the set key message.
2659 * @param cls pointer to the set key message
2660 * @param peer the peer for which this is the HELLO
2661 * @param hello HELLO message of that peer
2662 * @param trust amount of trust we currently have in that peer
2665 process_hello_retry_handle_set_key (void *cls,
2666 const struct GNUNET_PeerIdentity *peer,
2667 const struct GNUNET_HELLO_Message *hello,
2670 struct Neighbour *n = cls;
2671 struct SetKeyMessage *sm = n->skm;
2677 if (n->public_key != NULL)
2680 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2681 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2683 GNUNET_i2s (&n->peer),
2686 handle_set_key (n, sm);
2690 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2691 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
2693 GNUNET_i2s (&n->peer));
2698 if (n->public_key != NULL)
2699 return; /* multiple HELLOs match!? */
2701 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2702 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2704 GNUNET_break_op (0);
2705 GNUNET_free (n->public_key);
2706 n->public_key = NULL;
2712 * We received a PING message. Validate and transmit
2715 * @param n sender of the PING
2716 * @param m the encrypted PING message itself
2719 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2721 struct PingMessage t;
2722 struct PongMessage tx;
2723 struct PongMessage *tp;
2724 struct MessageEntry *me;
2727 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2728 "Core service receives `%s' request from `%4s'.\n",
2729 "PING", GNUNET_i2s (&n->peer));
2733 &my_identity.hashPubKey,
2736 sizeof (struct PingMessage) -
2737 sizeof (struct GNUNET_MessageHeader)))
2740 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2741 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2743 GNUNET_i2s (&t.target),
2744 (unsigned int) ntohl (t.challenge),
2745 (unsigned int) n->decrypt_key.crc32);
2747 GNUNET_STATISTICS_update (stats,
2748 gettext_noop ("# PING messages decrypted"),
2751 if (0 != memcmp (&t.target,
2752 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2754 GNUNET_break_op (0);
2757 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2758 sizeof (struct PongMessage));
2759 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2763 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2764 me->priority = PONG_PRIORITY;
2765 me->size = sizeof (struct PongMessage);
2766 tx.reserved = htonl (0);
2767 tx.inbound_bw_limit = n->bw_in;
2768 tx.challenge = t.challenge;
2769 tx.target = t.target;
2770 tp = (struct PongMessage *) &me[1];
2771 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2772 tp->header.size = htons (sizeof (struct PongMessage));
2774 &my_identity.hashPubKey,
2777 sizeof (struct PongMessage) -
2778 sizeof (struct GNUNET_MessageHeader));
2779 GNUNET_STATISTICS_update (stats,
2780 gettext_noop ("# PONG messages created"),
2784 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2785 "Encrypting `%s' with challenge %u using key %u\n",
2787 (unsigned int) ntohl (t.challenge),
2788 (unsigned int) n->encrypt_key.crc32);
2790 /* trigger queue processing */
2791 process_encrypted_neighbour_queue (n);
2796 * We received a PONG message. Validate and update our status.
2798 * @param n sender of the PONG
2799 * @param m the encrypted PONG message itself
2802 handle_pong (struct Neighbour *n,
2803 const struct PongMessage *m)
2805 struct PongMessage t;
2806 struct ConnectNotifyMessage cnm;
2809 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2810 "Core service receives `%s' response from `%4s'.\n",
2811 "PONG", GNUNET_i2s (&n->peer));
2813 /* mark as garbage, just to be sure */
2814 memset (&t, 255, sizeof (t));
2817 &n->peer.hashPubKey,
2820 sizeof (struct PongMessage) -
2821 sizeof (struct GNUNET_MessageHeader)))
2823 GNUNET_break_op (0);
2826 GNUNET_STATISTICS_update (stats,
2827 gettext_noop ("# PONG messages decrypted"),
2830 if (0 != ntohl (t.reserved))
2832 GNUNET_break_op (0);
2836 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2837 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2839 GNUNET_i2s (&t.target),
2840 (unsigned int) ntohl (t.challenge),
2841 (unsigned int) n->decrypt_key.crc32);
2843 if ((0 != memcmp (&t.target,
2845 sizeof (struct GNUNET_PeerIdentity))) ||
2846 (n->ping_challenge != ntohl (t.challenge)))
2848 /* PONG malformed */
2850 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2851 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2853 GNUNET_i2s (&n->peer),
2854 (unsigned int) n->ping_challenge);
2855 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2856 "Received malformed `%s' received from `%4s' with challenge %u\n",
2857 "PONG", GNUNET_i2s (&t.target),
2858 (unsigned int) ntohl (t.challenge));
2860 GNUNET_break_op (0);
2865 case PEER_STATE_DOWN:
2866 GNUNET_break (0); /* should be impossible */
2868 case PEER_STATE_KEY_SENT:
2869 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2871 case PEER_STATE_KEY_RECEIVED:
2872 GNUNET_STATISTICS_update (stats,
2873 gettext_noop ("# Session keys confirmed via PONG"),
2876 n->status = PEER_STATE_KEY_CONFIRMED;
2877 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2879 n->bw_out_external_limit = t.inbound_bw_limit;
2880 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2881 n->bw_out_internal_limit);
2882 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2884 GNUNET_TRANSPORT_set_quota (transport,
2888 GNUNET_TIME_UNIT_FOREVER_REL,
2892 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2893 "Confirmed key via `%s' message for peer `%4s'\n",
2894 "PONG", GNUNET_i2s (&n->peer));
2896 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2898 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2899 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2901 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2902 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2903 cnm.distance = htonl (n->last_distance);
2904 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2906 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2907 process_encrypted_neighbour_queue (n);
2909 case PEER_STATE_KEY_CONFIRMED:
2910 n->last_activity = GNUNET_TIME_absolute_get ();
2911 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2912 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2914 = GNUNET_SCHEDULER_add_delayed (sched,
2915 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2927 * We received a SET_KEY message. Validate and update
2928 * our key material and status.
2930 * @param n the neighbour from which we received message m
2931 * @param m the set key message we received
2934 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2936 struct SetKeyMessage *m_cpy;
2937 struct GNUNET_TIME_Absolute t;
2938 struct GNUNET_CRYPTO_AesSessionKey k;
2939 struct PingMessage *ping;
2940 struct PongMessage *pong;
2941 enum PeerStateMachine sender_status;
2944 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2945 "Core service receives `%s' request from `%4s'.\n",
2946 "SET_KEY", GNUNET_i2s (&n->peer));
2948 if (n->public_key == NULL)
2950 if (n->pitr != NULL)
2953 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2954 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2960 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2961 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2963 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2964 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2965 /* lookup n's public key, then try again */
2966 GNUNET_assert (n->skm == NULL);
2968 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2971 GNUNET_TIME_UNIT_MINUTES,
2972 &process_hello_retry_handle_set_key, n);
2973 GNUNET_STATISTICS_update (stats,
2974 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2979 if (0 != memcmp (&m->target,
2981 sizeof (struct GNUNET_PeerIdentity)))
2983 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2984 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
2986 GNUNET_i2s (&m->target));
2989 if ((ntohl (m->purpose.size) !=
2990 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2991 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2992 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2993 sizeof (struct GNUNET_PeerIdentity)) ||
2995 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2996 &m->purpose, &m->signature, n->public_key)))
2998 /* invalid signature */
2999 GNUNET_break_op (0);
3002 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3003 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3004 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3005 (t.value < n->decrypt_key_created.value))
3007 /* this could rarely happen due to massive re-ordering of
3008 messages on the network level, but is most likely either
3009 a bug or some adversary messing with us. Report. */
3010 GNUNET_break_op (0);
3014 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3015 "Decrypting key material.\n");
3017 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3020 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3021 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3022 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3024 /* failed to decrypt !? */
3025 GNUNET_break_op (0);
3028 GNUNET_STATISTICS_update (stats,
3029 gettext_noop ("# SET_KEY messages decrypted"),
3033 if (n->decrypt_key_created.value != t.value)
3035 /* fresh key, reset sequence numbers */
3036 n->last_sequence_number_received = 0;
3037 n->last_packets_bitmap = 0;
3038 n->decrypt_key_created = t;
3040 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3043 case PEER_STATE_DOWN:
3044 n->status = PEER_STATE_KEY_RECEIVED;
3046 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3047 "Responding to `%s' with my own key.\n", "SET_KEY");
3051 case PEER_STATE_KEY_SENT:
3052 case PEER_STATE_KEY_RECEIVED:
3053 n->status = PEER_STATE_KEY_RECEIVED;
3054 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3055 (sender_status != PEER_STATE_KEY_CONFIRMED))
3058 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3059 "Responding to `%s' with my own key (other peer has status %u).\n",
3061 (unsigned int) sender_status);
3066 case PEER_STATE_KEY_CONFIRMED:
3067 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3068 (sender_status != PEER_STATE_KEY_CONFIRMED))
3071 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3072 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3074 (unsigned int) sender_status);
3083 if (n->pending_ping != NULL)
3085 ping = n->pending_ping;
3086 n->pending_ping = NULL;
3087 handle_ping (n, ping);
3090 if (n->pending_pong != NULL)
3092 pong = n->pending_pong;
3093 n->pending_pong = NULL;
3094 handle_pong (n, pong);
3101 * Send a P2P message to a client.
3103 * @param sender who sent us the message?
3104 * @param client who should we give the message to?
3105 * @param m contains the message to transmit
3106 * @param msize number of bytes in buf to transmit
3109 send_p2p_message_to_client (struct Neighbour *sender,
3110 struct Client *client,
3111 const void *m, size_t msize)
3113 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3114 struct NotifyTrafficMessage *ntm;
3117 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3118 "Core service passes message from `%4s' of type %u to client.\n",
3119 GNUNET_i2s(&sender->peer),
3120 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3122 ntm = (struct NotifyTrafficMessage *) buf;
3123 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3124 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3125 ntm->distance = htonl (sender->last_distance);
3126 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3127 ntm->peer = sender->peer;
3128 memcpy (&ntm[1], m, msize);
3129 send_to_client (client, &ntm->header, GNUNET_YES);
3134 * Deliver P2P message to interested clients.
3136 * @param sender who sent us the message?
3137 * @param m the message
3138 * @param msize size of the message (including header)
3141 deliver_message (struct Neighbour *sender,
3142 const struct GNUNET_MessageHeader *m, size_t msize)
3145 struct Client *cpos;
3151 type = ntohs (m->type);
3153 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3154 "Received encapsulated message of type %u and size %u from `%4s'\n",
3155 (unsigned int) type,
3157 GNUNET_i2s (&sender->peer));
3159 GNUNET_snprintf (buf,
3161 gettext_noop ("# bytes of messages of type %u received"),
3162 (unsigned int) type);
3163 GNUNET_STATISTICS_set (stats,
3167 dropped = GNUNET_YES;
3169 while (cpos != NULL)
3171 deliver_full = GNUNET_NO;
3172 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3173 deliver_full = GNUNET_YES;
3176 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3178 if (type != cpos->types[tpos])
3180 deliver_full = GNUNET_YES;
3184 if (GNUNET_YES == deliver_full)
3186 send_p2p_message_to_client (sender, cpos, m, msize);
3187 dropped = GNUNET_NO;
3189 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3191 send_p2p_message_to_client (sender, cpos, m,
3192 sizeof (struct GNUNET_MessageHeader));
3196 if (dropped == GNUNET_YES)
3199 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3200 "Message of type %u from `%4s' not delivered to any client.\n",
3201 (unsigned int) type,
3202 GNUNET_i2s (&sender->peer));
3204 GNUNET_STATISTICS_update (stats,
3205 gettext_noop ("# messages not delivered to any client"),
3212 * Align P2P message and then deliver to interested clients.
3214 * @param sender who sent us the message?
3215 * @param buffer unaligned (!) buffer containing message
3216 * @param msize size of the message (including header)
3219 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
3223 /* TODO: call to statistics? */
3224 memcpy (abuf, buffer, msize);
3225 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
3230 * Deliver P2P messages to interested clients.
3232 * @param sender who sent us the message?
3233 * @param buffer buffer containing messages, can be modified
3234 * @param buffer_size size of the buffer (overall)
3235 * @param offset offset where messages in the buffer start
3238 deliver_messages (struct Neighbour *sender,
3239 const char *buffer, size_t buffer_size, size_t offset)
3241 struct GNUNET_MessageHeader *mhp;
3242 struct GNUNET_MessageHeader mh;
3246 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
3248 if (0 != offset % sizeof (uint16_t))
3250 /* outch, need to copy to access header */
3251 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
3256 /* can access header directly */
3257 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
3259 msize = ntohs (mhp->size);
3260 if (msize + offset > buffer_size)
3262 /* malformed message, header says it is larger than what
3263 would fit into the overall buffer */
3264 GNUNET_break_op (0);
3267 #if HAVE_UNALIGNED_64_ACCESS
3268 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
3270 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
3273 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3274 "Delivering %u bytes of message at offset %u/%u to clients.\n",
3275 (unsigned int) msize,
3276 (unsigned int) offset,
3277 (unsigned int) buffer_size);
3280 if (GNUNET_YES == need_align)
3281 align_and_deliver (sender, &buffer[offset], msize);
3283 deliver_message (sender,
3284 (const struct GNUNET_MessageHeader *)
3285 &buffer[offset], msize);
3292 * We received an encrypted message. Decrypt, validate and
3293 * pass on to the appropriate clients.
3296 handle_encrypted_message (struct Neighbour *n,
3297 const struct EncryptedMessage *m)
3299 size_t size = ntohs (m->header.size);
3301 struct EncryptedMessage *pt; /* plaintext */
3304 struct GNUNET_TIME_Absolute t;
3308 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3309 "Core service receives `%s' request from `%4s'.\n",
3310 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3312 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3318 &buf[ENCRYPTED_HEADER_SIZE],
3319 size - ENCRYPTED_HEADER_SIZE))
3321 pt = (struct EncryptedMessage *) buf;
3323 GNUNET_CRYPTO_hmac (&n->decrypt_key,
3324 &pt->sequence_number,
3325 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3327 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3328 "V-Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
3329 (unsigned int) (size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode)),
3333 if (0 != memcmp (&ph,
3335 sizeof (GNUNET_HashCode)))
3337 /* checksum failed */
3338 GNUNET_break_op (0);
3342 /* validate sequence number */
3343 snum = ntohl (pt->sequence_number);
3344 if (n->last_sequence_number_received == snum)
3346 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3347 "Received duplicate message, ignoring.\n");
3348 /* duplicate, ignore */
3349 GNUNET_STATISTICS_set (stats,
3350 gettext_noop ("# bytes dropped (duplicates)"),
3355 if ((n->last_sequence_number_received > snum) &&
3356 (n->last_sequence_number_received - snum > 32))
3358 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3359 "Received ancient out of sequence message, ignoring.\n");
3360 /* ancient out of sequence, ignore */
3361 GNUNET_STATISTICS_set (stats,
3362 gettext_noop ("# bytes dropped (out of sequence)"),
3367 if (n->last_sequence_number_received > snum)
3369 unsigned int rotbit =
3370 1 << (n->last_sequence_number_received - snum - 1);
3371 if ((n->last_packets_bitmap & rotbit) != 0)
3373 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3374 "Received duplicate message, ignoring.\n");
3375 GNUNET_STATISTICS_set (stats,
3376 gettext_noop ("# bytes dropped (duplicates)"),
3379 /* duplicate, ignore */
3382 n->last_packets_bitmap |= rotbit;
3384 if (n->last_sequence_number_received < snum)
3386 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3387 n->last_sequence_number_received = snum;
3390 /* check timestamp */
3391 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3392 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3394 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3396 ("Message received far too old (%llu ms). Content ignored.\n"),
3397 GNUNET_TIME_absolute_get_duration (t).value);
3398 GNUNET_STATISTICS_set (stats,
3399 gettext_noop ("# bytes dropped (ancient message)"),
3405 /* process decrypted message(s) */
3406 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3408 #if DEBUG_CORE_SET_QUOTA
3409 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3410 "Received %u b/s as new inbound limit for peer `%4s'\n",
3411 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3412 GNUNET_i2s (&n->peer));
3414 n->bw_out_external_limit = pt->inbound_bw_limit;
3415 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3416 n->bw_out_internal_limit);
3417 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3419 GNUNET_TRANSPORT_set_quota (transport,
3423 GNUNET_TIME_UNIT_FOREVER_REL,
3426 n->last_activity = GNUNET_TIME_absolute_get ();
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),
3434 GNUNET_STATISTICS_set (stats,
3435 gettext_noop ("# bytes of payload decrypted"),
3436 size - sizeof (struct EncryptedMessage),
3438 deliver_messages (n, buf, size, sizeof (struct EncryptedMessage));
3443 * Function called by the transport for each received message.
3445 * @param cls closure
3446 * @param peer (claimed) identity of the other peer
3447 * @param message the message
3448 * @param latency estimated latency for communicating with the
3449 * given peer (round-trip)
3450 * @param distance in overlay hops, as given by transport plugin
3453 handle_transport_receive (void *cls,
3454 const struct GNUNET_PeerIdentity *peer,
3455 const struct GNUNET_MessageHeader *message,
3456 struct GNUNET_TIME_Relative latency,
3457 unsigned int distance)
3459 struct Neighbour *n;
3460 struct GNUNET_TIME_Absolute now;
3466 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3467 "Received message of type %u from `%4s', demultiplexing.\n",
3468 (unsigned int) ntohs (message->type),
3471 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3476 n = find_neighbour (peer);
3478 n = create_neighbour (peer);
3479 n->last_latency = latency;
3480 n->last_distance = distance;
3481 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3482 type = ntohs (message->type);
3483 size = ntohs (message->size);
3486 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3487 if (size != sizeof (struct SetKeyMessage))
3489 GNUNET_break_op (0);
3492 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3493 handle_set_key (n, (const struct SetKeyMessage *) message);
3495 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3496 if (size < sizeof (struct EncryptedMessage) +
3497 sizeof (struct GNUNET_MessageHeader))
3499 GNUNET_break_op (0);
3502 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3503 (n->status != PEER_STATE_KEY_CONFIRMED))
3505 GNUNET_break_op (0);
3508 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3510 case GNUNET_MESSAGE_TYPE_CORE_PING:
3511 if (size != sizeof (struct PingMessage))
3513 GNUNET_break_op (0);
3516 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3517 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3518 (n->status != PEER_STATE_KEY_CONFIRMED))
3521 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3522 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3523 "PING", GNUNET_i2s (&n->peer));
3525 GNUNET_free_non_null (n->pending_ping);
3526 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3527 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3530 handle_ping (n, (const struct PingMessage *) message);
3532 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3533 if (size != sizeof (struct PongMessage))
3535 GNUNET_break_op (0);
3538 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3539 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3540 (n->status != PEER_STATE_KEY_CONFIRMED) )
3543 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3544 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3545 "PONG", GNUNET_i2s (&n->peer));
3547 GNUNET_free_non_null (n->pending_pong);
3548 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3549 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3552 handle_pong (n, (const struct PongMessage *) message);
3555 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3556 _("Unsupported message of type %u received.\n"),
3557 (unsigned int) type);
3560 if (n->status == PEER_STATE_KEY_CONFIRMED)
3562 now = GNUNET_TIME_absolute_get ();
3563 n->last_activity = now;
3566 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3567 n->time_established = now;
3569 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3570 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3572 = GNUNET_SCHEDULER_add_delayed (sched,
3573 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3581 * Function that recalculates the bandwidth quota for the
3582 * given neighbour and transmits it to the transport service.
3584 * @param cls neighbour for the quota update
3588 neighbour_quota_update (void *cls,
3589 const struct GNUNET_SCHEDULER_TaskContext *tc)
3591 struct Neighbour *n = cls;
3592 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3595 unsigned long long distributable;
3596 uint64_t need_per_peer;
3597 uint64_t need_per_second;
3600 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3601 "Neighbour quota update calculation running for peer `%4s'\n",
3602 GNUNET_i2s (&n->peer));
3604 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3605 /* calculate relative preference among all neighbours;
3606 divides by a bit more to avoid division by zero AND to
3607 account for possibility of new neighbours joining any time
3608 AND to convert to double... */
3609 if (preference_sum == 0)
3611 pref_rel = 1.0 / (double) neighbour_count;
3615 pref_rel = n->current_preference / preference_sum;
3617 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3618 GNUNET_TIME_UNIT_SECONDS);
3619 need_per_second = need_per_peer * neighbour_count;
3621 if (bandwidth_target_out_bps > need_per_second)
3622 distributable = bandwidth_target_out_bps - need_per_second;
3623 share = distributable * pref_rel;
3624 if (share + need_per_peer > UINT32_MAX)
3625 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
3627 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3628 /* check if we want to disconnect for good due to inactivity */
3629 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3630 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3633 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3634 "Forcing disconnect of `%4s' due to inactivity\n",
3635 GNUNET_i2s (&n->peer));
3637 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3639 #if DEBUG_CORE_QUOTA
3640 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3641 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3642 GNUNET_i2s (&n->peer),
3643 (unsigned int) ntohl (q_in.value__),
3644 bandwidth_target_out_bps,
3645 (unsigned int) ntohl (n->bw_in.value__),
3646 (unsigned int) ntohl (n->bw_out.value__),
3647 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3649 if (n->bw_in.value__ != q_in.value__)
3652 if (GNUNET_YES == n->is_connected)
3653 GNUNET_TRANSPORT_set_quota (transport,
3657 GNUNET_TIME_UNIT_FOREVER_REL,
3660 schedule_quota_update (n);
3665 * Function called by transport to notify us that
3666 * a peer connected to us (on the network level).
3668 * @param cls closure
3669 * @param peer the peer that connected
3670 * @param latency current latency of the connection
3671 * @param distance in overlay hops, as given by transport plugin
3674 handle_transport_notify_connect (void *cls,
3675 const struct GNUNET_PeerIdentity *peer,
3676 struct GNUNET_TIME_Relative latency,
3677 unsigned int distance)
3679 struct Neighbour *n;
3681 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3686 n = find_neighbour (peer);
3689 if (GNUNET_YES == n->is_connected)
3691 /* duplicate connect notification!? */
3698 n = create_neighbour (peer);
3700 GNUNET_STATISTICS_update (stats,
3701 gettext_noop ("# peers connected (transport)"),
3704 n->is_connected = GNUNET_YES;
3705 n->last_latency = latency;
3706 n->last_distance = distance;
3707 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3710 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3714 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3715 "Received connection from `%4s'.\n",
3716 GNUNET_i2s (&n->peer));
3718 GNUNET_TRANSPORT_set_quota (transport,
3722 GNUNET_TIME_UNIT_FOREVER_REL,
3729 * Function called by transport telling us that a peer
3732 * @param cls closure
3733 * @param peer the peer that disconnected
3736 handle_transport_notify_disconnect (void *cls,
3737 const struct GNUNET_PeerIdentity *peer)
3739 struct DisconnectNotifyMessage cnm;
3740 struct Neighbour *n;
3743 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3744 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3746 n = find_neighbour (peer);
3752 GNUNET_break (n->is_connected);
3753 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3754 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3756 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3757 n->is_connected = GNUNET_NO;
3758 GNUNET_STATISTICS_update (stats,
3759 gettext_noop ("# peers connected (transport)"),
3766 * Last task run during shutdown. Disconnects us from
3770 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3772 struct Neighbour *n;
3776 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3777 "Core service shutting down.\n");
3779 GNUNET_assert (transport != NULL);
3780 GNUNET_TRANSPORT_disconnect (transport);
3782 while (NULL != (n = neighbours))
3784 neighbours = n->next;
3785 GNUNET_assert (neighbour_count > 0);
3789 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
3790 GNUNET_SERVER_notification_context_destroy (notifier);
3792 while (NULL != (c = clients))
3793 handle_client_disconnect (NULL, c->client_handle);
3794 if (my_private_key != NULL)
3795 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3797 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3798 if (peerinfo != NULL)
3799 GNUNET_PEERINFO_disconnect (peerinfo);
3804 * Initiate core service.
3806 * @param cls closure
3807 * @param s scheduler to use
3808 * @param server the initialized server
3809 * @param c configuration to use
3813 struct GNUNET_SCHEDULER_Handle *s,
3814 struct GNUNET_SERVER_Handle *server,
3815 const struct GNUNET_CONFIGURATION_Handle *c)
3817 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3818 {&handle_client_init, NULL,
3819 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
3820 {&handle_client_request_info, NULL,
3821 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
3822 sizeof (struct RequestInfoMessage)},
3823 {&handle_client_send, NULL,
3824 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
3825 {&handle_client_request_connect, NULL,
3826 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
3827 sizeof (struct ConnectMessage)},
3834 /* parse configuration */
3837 GNUNET_CONFIGURATION_get_value_number (c,
3840 &bandwidth_target_in_bps)) ||
3842 GNUNET_CONFIGURATION_get_value_number (c,
3845 &bandwidth_target_out_bps)) ||
3847 GNUNET_CONFIGURATION_get_value_filename (c,
3849 "HOSTKEY", &keyfile)))
3851 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3853 ("Core service is lacking key configuration settings. Exiting.\n"));
3854 GNUNET_SCHEDULER_shutdown (s);
3857 peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
3858 if (NULL == peerinfo)
3860 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3861 _("Could not access PEERINFO service. Exiting.\n"));
3862 GNUNET_SCHEDULER_shutdown (s);
3863 GNUNET_free (keyfile);
3866 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3867 GNUNET_free (keyfile);
3868 if (my_private_key == NULL)
3870 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3871 _("Core service could not access hostkey. Exiting.\n"));
3872 GNUNET_PEERINFO_disconnect (peerinfo);
3873 GNUNET_SCHEDULER_shutdown (s);
3876 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3877 GNUNET_CRYPTO_hash (&my_public_key,
3878 sizeof (my_public_key), &my_identity.hashPubKey);
3879 /* setup notification */
3880 notifier = GNUNET_SERVER_notification_context_create (server,
3882 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3883 /* setup transport connection */
3884 transport = GNUNET_TRANSPORT_connect (sched,
3887 &handle_transport_receive,
3888 &handle_transport_notify_connect,
3889 &handle_transport_notify_disconnect);
3890 GNUNET_assert (NULL != transport);
3891 stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3892 GNUNET_SCHEDULER_add_delayed (sched,
3893 GNUNET_TIME_UNIT_FOREVER_REL,
3894 &cleaning_task, NULL);
3895 /* process client requests */
3896 GNUNET_SERVER_add_handlers (server, handlers);
3897 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3898 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3904 * The main function for the transport service.
3906 * @param argc number of arguments from the command line
3907 * @param argv command line arguments
3908 * @return 0 ok, 1 on error
3911 main (int argc, char *const *argv)
3913 return (GNUNET_OK ==
3914 GNUNET_SERVICE_run (argc,
3917 GNUNET_SERVICE_OPTION_NONE,
3918 &run, NULL)) ? 0 : 1;
3921 /* end of gnunet-service-core.c */