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 plaintext_hash;
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_SERVER_Handle *server;
679 static struct GNUNET_TRANSPORT_Handle *transport;
682 * Linked list of our clients.
684 static struct Client *clients;
687 * Context for notifications we need to send to our clients.
689 static struct GNUNET_SERVER_NotificationContext *notifier;
692 * We keep neighbours in a linked list (for now).
694 static struct Neighbour *neighbours;
697 * For creating statistics.
699 static struct GNUNET_STATISTICS_Handle *stats;
702 * Sum of all preferences among all neighbours.
704 static unsigned long long preference_sum;
707 * Total number of neighbours we have.
709 static unsigned int neighbour_count;
712 * How much inbound bandwidth are we supposed to be using per second?
713 * FIXME: this value is not used!
715 static unsigned long long bandwidth_target_in_bps;
718 * How much outbound bandwidth are we supposed to be using per second?
720 static unsigned long long bandwidth_target_out_bps;
725 * A preference value for a neighbour was update. Update
726 * the preference sum accordingly.
728 * @param inc how much was a preference value increased?
731 update_preference_sum (unsigned long long inc)
734 unsigned long long os;
737 preference_sum += inc;
738 if (preference_sum >= os)
740 /* overflow! compensate by cutting all values in half! */
745 n->current_preference /= 2;
746 preference_sum += n->current_preference;
749 GNUNET_STATISTICS_set (stats, gettext_noop ("# total peer preference"), preference_sum, GNUNET_NO);
754 * Find the entry for the given neighbour.
756 * @param peer identity of the neighbour
757 * @return NULL if we are not connected, otherwise the
760 static struct Neighbour *
761 find_neighbour (const struct GNUNET_PeerIdentity *peer)
763 struct Neighbour *ret;
766 while ((ret != NULL) &&
767 (0 != memcmp (&ret->peer,
768 peer, sizeof (struct GNUNET_PeerIdentity))))
775 * Send a message to one of our clients.
777 * @param client target for the message
778 * @param msg message to transmit
779 * @param can_drop could this message be dropped if the
780 * client's queue is getting too large?
783 send_to_client (struct Client *client,
784 const struct GNUNET_MessageHeader *msg,
787 #if DEBUG_CORE_CLIENT
788 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
789 "Preparing to send %u bytes of message of type %u to client.\n",
790 (unsigned int) ntohs (msg->size),
791 (unsigned int) ntohs (msg->type));
793 GNUNET_SERVER_notification_context_unicast (notifier,
794 client->client_handle,
801 * Send a message to all of our current clients that have
802 * the right options set.
804 * @param msg message to multicast
805 * @param can_drop can this message be discarded if the queue is too long
806 * @param options mask to use
809 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
818 if (0 != (c->options & options))
820 #if DEBUG_CORE_CLIENT
821 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
822 "Sending message of type %u to client.\n",
823 (unsigned int) ntohs (msg->type));
825 send_to_client (c, msg, can_drop);
833 * Handle CORE_INIT request.
836 handle_client_init (void *cls,
837 struct GNUNET_SERVER_Client *client,
838 const struct GNUNET_MessageHeader *message)
840 const struct InitMessage *im;
841 struct InitReplyMessage irm;
844 const uint16_t *types;
847 struct ConnectNotifyMessage cnm;
850 #if DEBUG_CORE_CLIENT
851 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
852 "Client connecting to core service with `%s' message\n",
855 /* check that we don't have an entry already */
859 if (client == c->client_handle)
862 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
867 msize = ntohs (message->size);
868 if (msize < sizeof (struct InitMessage))
871 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
874 GNUNET_SERVER_notification_context_add (notifier, client);
875 im = (const struct InitMessage *) message;
876 types = (const uint16_t *) &im[1];
877 msize -= sizeof (struct InitMessage);
878 c = GNUNET_malloc (sizeof (struct Client) + msize);
879 c->client_handle = client;
882 c->tcnt = msize / sizeof (uint16_t);
883 c->types = (const uint16_t *) &c[1];
884 wtypes = (uint16_t *) &c[1];
885 for (i=0;i<c->tcnt;i++)
886 wtypes[i] = ntohs (types[i]);
887 c->options = ntohl (im->options);
888 #if DEBUG_CORE_CLIENT
889 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
890 "Client %p is interested in %u message types\n",
892 (unsigned int) c->tcnt);
894 /* send init reply message */
895 irm.header.size = htons (sizeof (struct InitReplyMessage));
896 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
897 irm.reserved = htonl (0);
898 memcpy (&irm.publicKey,
900 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
901 #if DEBUG_CORE_CLIENT
902 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
903 "Sending `%s' message to client.\n", "INIT_REPLY");
905 send_to_client (c, &irm.header, GNUNET_NO);
906 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
908 /* notify new client about existing neighbours */
909 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
910 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
914 if (n->status == PEER_STATE_KEY_CONFIRMED)
916 #if DEBUG_CORE_CLIENT
917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
918 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
920 cnm.distance = htonl (n->last_distance);
921 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
923 send_to_client (c, &cnm.header, GNUNET_NO);
928 GNUNET_SERVER_receive_done (client, GNUNET_OK);
933 * A client disconnected, clean up.
936 * @param client identification of the client
939 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
946 #if DEBUG_CORE_CLIENT
947 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
948 "Client %p has disconnected from core service.\n",
955 if (client == pos->client_handle)
960 prev->next = pos->next;
967 /* client never sent INIT */
972 * Handle REQUEST_INFO request.
975 handle_client_request_info (void *cls,
976 struct GNUNET_SERVER_Client *client,
977 const struct GNUNET_MessageHeader *message)
979 const struct RequestInfoMessage *rcm;
981 struct ConfigurationInfoMessage cim;
984 unsigned long long old_preference;
985 struct GNUNET_SERVER_TransmitContext *tc;
987 #if DEBUG_CORE_CLIENT
988 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
989 "Core service receives `%s' request.\n", "REQUEST_INFO");
991 rcm = (const struct RequestInfoMessage *) message;
992 n = find_neighbour (&rcm->peer);
993 memset (&cim, 0, sizeof (cim));
996 want_reserv = ntohl (rcm->reserve_inbound);
997 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
999 n->bw_out_internal_limit = rcm->limit_outbound;
1000 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1001 n->bw_out_external_limit);
1002 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1004 GNUNET_TRANSPORT_set_quota (transport,
1008 GNUNET_TIME_UNIT_FOREVER_REL,
1011 if (want_reserv < 0)
1013 got_reserv = want_reserv;
1015 else if (want_reserv > 0)
1017 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1018 want_reserv).value == 0)
1019 got_reserv = want_reserv;
1021 got_reserv = 0; /* all or nothing */
1025 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1027 old_preference = n->current_preference;
1028 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1029 if (old_preference > n->current_preference)
1031 /* overflow; cap at maximum value */
1032 n->current_preference = ULLONG_MAX;
1034 update_preference_sum (n->current_preference - old_preference);
1035 #if DEBUG_CORE_QUOTA
1036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1037 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1039 GNUNET_i2s (&rcm->peer),
1042 cim.reserved_amount = htonl (got_reserv);
1043 cim.bw_in = n->bw_in;
1044 cim.bw_out = n->bw_out;
1045 cim.preference = n->current_preference;
1047 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1048 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1049 cim.peer = rcm->peer;
1051 #if DEBUG_CORE_CLIENT
1052 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1053 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1055 tc = GNUNET_SERVER_transmit_context_create (client);
1056 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1057 GNUNET_SERVER_transmit_context_run (tc,
1058 GNUNET_TIME_UNIT_FOREVER_REL);
1063 * Free the given entry for the neighbour (it has
1064 * already been removed from the list at this point).
1066 * @param n neighbour to free
1069 free_neighbour (struct Neighbour *n)
1071 struct MessageEntry *m;
1074 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1075 "Destroying neighbour entry for peer `%4s'\n",
1076 GNUNET_i2s (&n->peer));
1078 if (n->pitr != NULL)
1080 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1085 GNUNET_free (n->skm);
1088 while (NULL != (m = n->messages))
1090 n->messages = m->next;
1093 while (NULL != (m = n->encrypted_head))
1095 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1102 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1105 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1106 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1107 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1108 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1109 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1110 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1111 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1112 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1113 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1114 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1115 if (n->status == PEER_STATE_KEY_CONFIRMED)
1116 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1117 GNUNET_free_non_null (n->public_key);
1118 GNUNET_free_non_null (n->pending_ping);
1119 GNUNET_free_non_null (n->pending_pong);
1125 * Check if we have encrypted messages for the specified neighbour
1126 * pending, and if so, check with the transport about sending them
1129 * @param n neighbour to check.
1131 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1135 * Encrypt size bytes from in and write the result to out. Use the
1136 * key for outbound traffic of the given neighbour.
1138 * @param n neighbour we are sending to
1139 * @param iv initialization vector to use
1140 * @param in ciphertext
1141 * @param out plaintext
1142 * @param size size of in/out
1143 * @return GNUNET_OK on success
1146 do_encrypt (struct Neighbour *n,
1147 const GNUNET_HashCode * iv,
1148 const void *in, void *out, size_t size)
1150 if (size != (uint16_t) size)
1155 GNUNET_assert (size ==
1156 GNUNET_CRYPTO_aes_encrypt (in,
1160 GNUNET_CRYPTO_AesInitializationVector
1162 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1164 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1165 "Encrypted %u bytes for `%4s' using key %u\n",
1166 (unsigned int) size,
1167 GNUNET_i2s (&n->peer),
1168 (unsigned int) n->encrypt_key.crc32);
1175 * Consider freeing the given neighbour since we may not need
1176 * to keep it around anymore.
1178 * @param n neighbour to consider discarding
1181 consider_free_neighbour (struct Neighbour *n);
1185 * Task triggered when a neighbour entry is about to time out
1186 * (and we should prevent this by sending a PING).
1188 * @param cls the 'struct Neighbour'
1189 * @param tc scheduler context (not used)
1192 send_keep_alive (void *cls,
1193 const struct GNUNET_SCHEDULER_TaskContext *tc)
1195 struct Neighbour *n = cls;
1196 struct GNUNET_TIME_Relative retry;
1197 struct GNUNET_TIME_Relative left;
1198 struct MessageEntry *me;
1199 struct PingMessage pp;
1200 struct PingMessage *pm;
1202 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1204 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1205 sizeof (struct PingMessage));
1206 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1207 me->priority = PING_PRIORITY;
1208 me->size = sizeof (struct PingMessage);
1209 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1213 pm = (struct PingMessage *) &me[1];
1214 pm->header.size = htons (sizeof (struct PingMessage));
1215 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1216 pp.challenge = htonl (n->ping_challenge);
1217 pp.target = n->peer;
1219 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1220 "Encrypting `%s' message with challenge %u for `%4s' using key %u.\n",
1222 (unsigned int) n->ping_challenge,
1223 GNUNET_i2s (&n->peer),
1224 (unsigned int) n->encrypt_key.crc32);
1227 &n->peer.hashPubKey,
1230 sizeof (struct PingMessage) -
1231 sizeof (struct GNUNET_MessageHeader));
1232 process_encrypted_neighbour_queue (n);
1233 /* reschedule PING job */
1234 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1235 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1236 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1237 MIN_PING_FREQUENCY);
1239 = GNUNET_SCHEDULER_add_delayed (sched,
1248 * Task triggered when a neighbour entry might have gotten stale.
1250 * @param cls the 'struct Neighbour'
1251 * @param tc scheduler context (not used)
1254 consider_free_task (void *cls,
1255 const struct GNUNET_SCHEDULER_TaskContext *tc)
1257 struct Neighbour *n = cls;
1259 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1260 consider_free_neighbour (n);
1265 * Consider freeing the given neighbour since we may not need
1266 * to keep it around anymore.
1268 * @param n neighbour to consider discarding
1271 consider_free_neighbour (struct Neighbour *n)
1273 struct Neighbour *pos;
1274 struct Neighbour *prev;
1275 struct GNUNET_TIME_Relative left;
1277 if ( (n->th != NULL) ||
1278 (n->pitr != NULL) ||
1279 (n->status == PEER_STATE_KEY_CONFIRMED) ||
1280 (GNUNET_YES == n->is_connected) )
1281 return; /* no chance */
1283 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1284 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1287 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1288 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1289 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1291 &consider_free_task,
1295 /* actually free the neighbour... */
1304 neighbours = n->next;
1306 prev->next = n->next;
1307 GNUNET_assert (neighbour_count > 0);
1309 GNUNET_STATISTICS_set (stats,
1310 gettext_noop ("# neighbour entries allocated"),
1318 * Function called when the transport service is ready to
1319 * receive an encrypted message for the respective peer
1321 * @param cls neighbour to use message from
1322 * @param size number of bytes we can transmit
1323 * @param buf where to copy the message
1324 * @return number of bytes transmitted
1327 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1329 struct Neighbour *n = cls;
1330 struct MessageEntry *m;
1335 m = n->encrypted_head;
1339 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1340 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1341 GNUNET_i2s (&n->peer));
1345 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1352 GNUNET_assert (size >= m->size);
1353 memcpy (cbuf, &m[1], m->size);
1355 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1358 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1359 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1360 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1362 GNUNET_i2s (&n->peer));
1364 process_encrypted_neighbour_queue (n);
1369 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1370 "Transmission of message of type %u and size %u failed\n",
1371 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1372 (unsigned int) m->size);
1376 consider_free_neighbour (n);
1382 * Check if we have plaintext messages for the specified neighbour
1383 * pending, and if so, consider batching and encrypting them (and
1384 * then trigger processing of the encrypted queue if needed).
1386 * @param n neighbour to check.
1388 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1392 * Check if we have encrypted messages for the specified neighbour
1393 * pending, and if so, check with the transport about sending them
1396 * @param n neighbour to check.
1399 process_encrypted_neighbour_queue (struct Neighbour *n)
1401 struct MessageEntry *m;
1404 return; /* request already pending */
1405 m = n->encrypted_head;
1408 /* encrypted queue empty, try plaintext instead */
1409 process_plaintext_neighbour_queue (n);
1413 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1414 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1415 (unsigned int) m->size,
1416 GNUNET_i2s (&n->peer),
1417 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).
1421 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1424 GNUNET_TIME_absolute_get_remaining
1426 ¬ify_encrypted_transmit_ready,
1430 /* message request too large or duplicate request */
1432 /* discard encrypted message */
1433 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1437 process_encrypted_neighbour_queue (n);
1443 * Decrypt size bytes from in and write the result to out. Use the
1444 * key for inbound traffic of the given neighbour. This function does
1445 * NOT do any integrity-checks on the result.
1447 * @param n neighbour we are receiving from
1448 * @param iv initialization vector to use
1449 * @param in ciphertext
1450 * @param out plaintext
1451 * @param size size of in/out
1452 * @return GNUNET_OK on success
1455 do_decrypt (struct Neighbour *n,
1456 const GNUNET_HashCode * iv,
1457 const void *in, void *out, size_t size)
1459 if (size != (uint16_t) size)
1464 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1465 (n->status != PEER_STATE_KEY_CONFIRMED))
1467 GNUNET_break_op (0);
1468 return GNUNET_SYSERR;
1471 GNUNET_CRYPTO_aes_decrypt (in,
1475 GNUNET_CRYPTO_AesInitializationVector *) iv,
1479 return GNUNET_SYSERR;
1481 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1483 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1484 "Decrypted %u bytes from `%4s' using key %u\n",
1485 (unsigned int) size,
1486 GNUNET_i2s (&n->peer),
1487 (unsigned int) n->decrypt_key.crc32);
1494 * Select messages for transmission. This heuristic uses a combination
1495 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1496 * and priority-based discard (in case no feasible schedule exist) and
1497 * speculative optimization (defer any kind of transmission until
1498 * we either create a batch of significant size, 25% of max, or until
1499 * we are close to a deadline). Furthermore, when scheduling the
1500 * heuristic also packs as many messages into the batch as possible,
1501 * starting with those with the earliest deadline. Yes, this is fun.
1503 * @param n neighbour to select messages from
1504 * @param size number of bytes to select for transmission
1505 * @param retry_time set to the time when we should try again
1506 * (only valid if this function returns zero)
1507 * @return number of bytes selected, or 0 if we decided to
1508 * defer scheduling overall; in that case, retry_time is set.
1511 select_messages (struct Neighbour *n,
1512 size_t size, struct GNUNET_TIME_Relative *retry_time)
1514 struct MessageEntry *pos;
1515 struct MessageEntry *min;
1516 struct MessageEntry *last;
1517 unsigned int min_prio;
1518 struct GNUNET_TIME_Absolute t;
1519 struct GNUNET_TIME_Absolute now;
1520 struct GNUNET_TIME_Relative delta;
1522 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1525 unsigned int queue_size;
1526 int discard_low_prio;
1528 GNUNET_assert (NULL != n->messages);
1529 now = GNUNET_TIME_absolute_get ();
1530 /* last entry in linked list of messages processed */
1532 /* should we remove the entry with the lowest
1533 priority from consideration for scheduling at the
1544 discard_low_prio = GNUNET_YES;
1545 while (GNUNET_YES == discard_low_prio)
1548 min_prio = UINT_MAX;
1549 discard_low_prio = GNUNET_NO;
1550 /* calculate number of bytes available for transmission at time "t" */
1551 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1553 /* how many bytes have we (hypothetically) scheduled so far */
1555 /* maximum time we can wait before transmitting anything
1556 and still make all of our deadlines */
1557 slack = GNUNET_TIME_UNIT_FOREVER_REL;
1559 /* note that we use "*2" here because we want to look
1560 a bit further into the future; much more makes no
1561 sense since new message might be scheduled in the
1563 while ((pos != NULL) && (off < size * 2))
1565 if (pos->do_transmit == GNUNET_YES)
1567 /* already removed from consideration */
1571 if (discard_low_prio == GNUNET_NO)
1573 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1574 if (delta.value > 0)
1576 // FIXME: HUH? Check!
1578 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1581 if (avail < pos->size)
1583 // FIXME: HUH? Check!
1584 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1589 /* update slack, considering both its absolute deadline
1590 and relative deadlines caused by other messages
1591 with their respective load */
1592 slack = GNUNET_TIME_relative_min (slack,
1593 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1595 if (pos->deadline.value <= now.value)
1598 slack = GNUNET_TIME_UNIT_ZERO;
1600 else if (GNUNET_YES == pos->got_slack)
1602 /* should be soon now! */
1603 slack = GNUNET_TIME_relative_min (slack,
1604 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1609 GNUNET_TIME_relative_min (slack,
1610 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1611 pos->got_slack = GNUNET_YES;
1612 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1613 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
1618 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1619 if (pos->priority <= min_prio)
1621 /* update min for discard */
1622 min_prio = pos->priority;
1627 if (discard_low_prio)
1629 GNUNET_assert (min != NULL);
1630 /* remove lowest-priority entry from consideration */
1631 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1635 /* guard against sending "tiny" messages with large headers without
1637 if ( (slack.value > GNUNET_CONSTANTS_MAX_CORK_DELAY.value) &&
1639 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1641 /* less than 25% of message would be filled with deadlines still
1642 being met if we delay by one second or more; so just wait for
1643 more data; but do not wait longer than 1s (since we don't want
1644 to delay messages for a really long time either). */
1645 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1646 /* reset do_transmit values for next time */
1649 pos->do_transmit = GNUNET_NO;
1653 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1654 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1655 (unsigned long long) retry_time->value,
1657 (unsigned int) size);
1661 /* select marked messages (up to size) for transmission */
1666 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1668 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1672 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1673 "Selecting message of size %u for transmission\n",
1674 (unsigned int) pos->size);
1680 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1681 "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
1682 (unsigned int) pos->size,
1685 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1690 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1691 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1692 (unsigned long long) off, (unsigned long long) tsize,
1693 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
1694 GNUNET_i2s (&n->peer));
1701 * Batch multiple messages into a larger buffer.
1703 * @param n neighbour to take messages from
1704 * @param buf target buffer
1705 * @param size size of buf
1706 * @param deadline set to transmission deadline for the result
1707 * @param retry_time set to the time when we should try again
1708 * (only valid if this function returns zero)
1709 * @param priority set to the priority of the batch
1710 * @return number of bytes written to buf (can be zero)
1713 batch_message (struct Neighbour *n,
1716 struct GNUNET_TIME_Absolute *deadline,
1717 struct GNUNET_TIME_Relative *retry_time,
1718 unsigned int *priority)
1720 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1721 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1722 struct MessageEntry *pos;
1723 struct MessageEntry *prev;
1724 struct MessageEntry *next;
1729 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1730 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1731 if (0 == select_messages (n, size, retry_time))
1734 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1735 "No messages selected, will try again in %llu ms\n",
1740 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1741 ntm->distance = htonl (n->last_distance);
1742 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1743 ntm->peer = n->peer;
1746 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1749 if (GNUNET_YES == pos->do_transmit)
1751 GNUNET_assert (pos->size <= size);
1752 /* do notifications */
1753 /* FIXME: track if we have *any* client that wants
1754 full notifications and only do this if that is
1756 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1758 memcpy (&ntm[1], &pos[1], pos->size);
1759 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1760 sizeof (struct GNUNET_MessageHeader));
1761 send_to_all_clients (&ntm->header,
1763 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1767 /* message too large for 'full' notifications, we do at
1768 least the 'hdr' type */
1771 sizeof (struct GNUNET_MessageHeader));
1773 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1775 send_to_all_clients (&ntm->header,
1777 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1779 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1780 "Encrypting %u bytes with message of type %u and size %u\n",
1782 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
1783 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
1785 /* copy for encrypted transmission */
1786 memcpy (&buf[ret], &pos[1], pos->size);
1789 *priority += pos->priority;
1791 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1792 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1793 (unsigned int) pos->size,
1794 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1796 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1810 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1811 "Deadline for message batch is %llu ms\n",
1812 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1819 * Remove messages with deadlines that have long expired from
1822 * @param n neighbour to inspect
1825 discard_expired_messages (struct Neighbour *n)
1827 struct MessageEntry *prev;
1828 struct MessageEntry *next;
1829 struct MessageEntry *pos;
1830 struct GNUNET_TIME_Absolute now;
1831 struct GNUNET_TIME_Relative delta;
1833 now = GNUNET_TIME_absolute_get ();
1839 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1840 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1843 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1844 "Message is %llu ms past due, discarding.\n",
1861 * Signature of the main function of a task.
1863 * @param cls closure
1864 * @param tc context information (why was this task triggered now)
1867 retry_plaintext_processing (void *cls,
1868 const struct GNUNET_SCHEDULER_TaskContext *tc)
1870 struct Neighbour *n = cls;
1872 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1873 process_plaintext_neighbour_queue (n);
1878 * Send our key (and encrypted PING) to the other peer.
1880 * @param n the other peer
1882 static void send_key (struct Neighbour *n);
1885 * Task that will retry "send_key" if our previous attempt failed
1889 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1891 struct Neighbour *n = cls;
1894 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1895 "Retrying key transmission to `%4s'\n",
1896 GNUNET_i2s (&n->peer));
1898 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1899 n->set_key_retry_frequency =
1900 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1906 * Check if we have plaintext messages for the specified neighbour
1907 * pending, and if so, consider batching and encrypting them (and
1908 * then trigger processing of the encrypted queue if needed).
1910 * @param n neighbour to check.
1913 process_plaintext_neighbour_queue (struct Neighbour *n)
1915 char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)]; /* plaintext */
1918 struct EncryptedMessage *em; /* encrypted message */
1919 struct EncryptedMessage *ph; /* plaintext header */
1920 struct MessageEntry *me;
1921 unsigned int priority;
1922 struct GNUNET_TIME_Absolute deadline;
1923 struct GNUNET_TIME_Relative retry_time;
1926 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1928 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1929 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1933 case PEER_STATE_DOWN:
1936 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1937 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1938 GNUNET_i2s(&n->peer));
1941 case PEER_STATE_KEY_SENT:
1942 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1943 n->retry_set_key_task
1944 = GNUNET_SCHEDULER_add_delayed (sched,
1945 n->set_key_retry_frequency,
1946 &set_key_retry_task, n);
1948 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1949 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1950 GNUNET_i2s(&n->peer));
1953 case PEER_STATE_KEY_RECEIVED:
1954 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1955 n->retry_set_key_task
1956 = GNUNET_SCHEDULER_add_delayed (sched,
1957 n->set_key_retry_frequency,
1958 &set_key_retry_task, n);
1960 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1961 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1962 GNUNET_i2s(&n->peer));
1965 case PEER_STATE_KEY_CONFIRMED:
1966 /* ready to continue */
1969 discard_expired_messages (n);
1970 if (n->messages == NULL)
1973 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1974 "Plaintext message queue for `%4s' is empty.\n",
1975 GNUNET_i2s(&n->peer));
1977 return; /* no pending messages */
1979 if (n->encrypted_head != NULL)
1982 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1983 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1984 GNUNET_i2s(&n->peer));
1986 return; /* wait for messages already encrypted to be
1989 ph = (struct EncryptedMessage *) pbuf;
1990 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1992 used = sizeof (struct EncryptedMessage);
1993 used += batch_message (n,
1995 GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
1996 &deadline, &retry_time, &priority);
1997 if (used == sizeof (struct EncryptedMessage))
2000 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2001 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2002 GNUNET_i2s(&n->peer));
2004 /* no messages selected for sending, try again later... */
2005 n->retry_plaintext_task =
2006 GNUNET_SCHEDULER_add_delayed (sched,
2008 &retry_plaintext_processing, n);
2011 #if DEBUG_CORE_QUOTA
2012 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2013 "Sending %u b/s as new limit to peer `%4s'\n",
2014 (unsigned int) ntohl (n->bw_in.value__),
2015 GNUNET_i2s (&n->peer));
2017 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX));
2018 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2019 ph->inbound_bw_limit = n->bw_in;
2020 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2022 /* setup encryption message header */
2023 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2024 me->deadline = deadline;
2025 me->priority = priority;
2027 em = (struct EncryptedMessage *) &me[1];
2028 em->header.size = htons (used);
2029 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2030 em->iv_seed = ph->iv_seed;
2031 esize = used - ENCRYPTED_HEADER_SIZE;
2032 GNUNET_CRYPTO_hash (&ph->sequence_number,
2033 esize - sizeof (GNUNET_HashCode),
2034 &ph->plaintext_hash);
2035 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
2037 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2038 "Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
2039 (unsigned int) (esize - sizeof (GNUNET_HashCode)),
2040 GNUNET_h2s (&ph->plaintext_hash),
2045 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2046 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2047 (unsigned int) esize,
2048 GNUNET_i2s(&n->peer),
2049 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2051 GNUNET_assert (GNUNET_OK ==
2054 &ph->plaintext_hash,
2055 &em->plaintext_hash, esize));
2056 /* append to transmission list */
2057 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2061 process_encrypted_neighbour_queue (n);
2066 * Function that recalculates the bandwidth quota for the
2067 * given neighbour and transmits it to the transport service.
2069 * @param cls neighbour for the quota update
2073 neighbour_quota_update (void *cls,
2074 const struct GNUNET_SCHEDULER_TaskContext *tc);
2078 * Schedule the task that will recalculate the bandwidth
2079 * quota for this peer (and possibly force a disconnect of
2080 * idle peers by calculating a bandwidth of zero).
2083 schedule_quota_update (struct Neighbour *n)
2085 GNUNET_assert (n->quota_update_task ==
2086 GNUNET_SCHEDULER_NO_TASK);
2087 n->quota_update_task
2088 = GNUNET_SCHEDULER_add_delayed (sched,
2089 QUOTA_UPDATE_FREQUENCY,
2090 &neighbour_quota_update,
2096 * Initialize a new 'struct Neighbour'.
2098 * @param pid ID of the new neighbour
2099 * @return handle for the new neighbour
2101 static struct Neighbour *
2102 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2104 struct Neighbour *n;
2105 struct GNUNET_TIME_Absolute now;
2108 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2109 "Creating neighbour entry for peer `%4s'\n",
2112 n = GNUNET_malloc (sizeof (struct Neighbour));
2113 n->next = neighbours;
2116 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2118 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2119 now = GNUNET_TIME_absolute_get ();
2120 n->encrypt_key_created = now;
2121 n->last_activity = now;
2122 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2123 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2124 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2125 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2126 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2127 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2129 neighbour_quota_update (n, NULL);
2130 consider_free_neighbour (n);
2136 * Handle CORE_SEND request.
2139 * @param client the client issuing the request
2140 * @param message the "struct SendMessage"
2143 handle_client_send (void *cls,
2144 struct GNUNET_SERVER_Client *client,
2145 const struct GNUNET_MessageHeader *message)
2147 const struct SendMessage *sm;
2148 struct Neighbour *n;
2149 struct MessageEntry *prev;
2150 struct MessageEntry *pos;
2151 struct MessageEntry *e;
2152 struct MessageEntry *min_prio_entry;
2153 struct MessageEntry *min_prio_prev;
2154 unsigned int min_prio;
2155 unsigned int queue_size;
2158 msize = ntohs (message->size);
2160 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2164 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2167 sm = (const struct SendMessage *) message;
2168 msize -= sizeof (struct SendMessage);
2169 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2171 /* FIXME: should we not allow loopback-injection here? */
2174 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2177 n = find_neighbour (&sm->peer);
2179 n = create_neighbour (&sm->peer);
2181 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2182 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2184 (unsigned int) msize,
2185 GNUNET_i2s (&sm->peer));
2187 /* bound queue size */
2188 discard_expired_messages (n);
2189 min_prio = UINT32_MAX;
2190 min_prio_entry = NULL;
2191 min_prio_prev = NULL;
2197 if (pos->priority < min_prio)
2199 min_prio_entry = pos;
2200 min_prio_prev = prev;
2201 min_prio = pos->priority;
2207 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2210 if (ntohl(sm->priority) <= min_prio)
2212 /* discard new entry */
2214 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2215 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2217 (unsigned int) MAX_PEER_QUEUE_SIZE,
2218 (unsigned int) msize,
2219 (unsigned int) ntohs (message->type));
2222 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2225 /* discard "min_prio_entry" */
2227 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2228 "Queue full, discarding existing older request\n");
2230 if (min_prio_prev == NULL)
2231 n->messages = min_prio_entry->next;
2233 min_prio_prev->next = min_prio_entry->next;
2234 GNUNET_free (min_prio_entry);
2238 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2239 "Adding transmission request for `%4s' of size %u to queue\n",
2240 GNUNET_i2s (&sm->peer),
2241 (unsigned int) msize);
2243 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2244 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2245 e->priority = ntohl (sm->priority);
2247 memcpy (&e[1], &sm[1], msize);
2249 /* insert, keep list sorted by deadline */
2252 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2263 /* consider scheduling now */
2264 process_plaintext_neighbour_queue (n);
2266 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2271 * Function called when the transport service is ready to
2272 * receive a message. Only resets 'n->th' to NULL.
2274 * @param cls neighbour to use message from
2275 * @param size number of bytes we can transmit
2276 * @param buf where to copy the message
2277 * @return number of bytes transmitted
2280 notify_transport_connect_done (void *cls, size_t size, void *buf)
2282 struct Neighbour *n = cls;
2287 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2288 _("Failed to connect to `%4s': transport failed to connect\n"),
2289 GNUNET_i2s (&n->peer));
2292 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2293 _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2294 GNUNET_i2s (&n->peer));
2295 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2296 GNUNET_SCHEDULER_cancel (sched,
2297 n->retry_set_key_task);
2298 n->retry_set_key_task = GNUNET_SCHEDULER_add_now (sched,
2299 &set_key_retry_task,
2306 * Handle CORE_REQUEST_CONNECT request.
2309 * @param client the client issuing the request
2310 * @param message the "struct ConnectMessage"
2313 handle_client_request_connect (void *cls,
2314 struct GNUNET_SERVER_Client *client,
2315 const struct GNUNET_MessageHeader *message)
2317 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2318 struct Neighbour *n;
2319 struct GNUNET_TIME_Relative timeout;
2321 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2324 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2327 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2328 n = find_neighbour (&cm->peer);
2330 n = create_neighbour (&cm->peer);
2331 if ( (GNUNET_YES == n->is_connected) ||
2333 return; /* already connected, or at least trying */
2334 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2336 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2337 "Core received `%s' request for `%4s', will try to establish connection\n",
2339 GNUNET_i2s (&cm->peer));
2341 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2342 /* ask transport to connect to the peer */
2343 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2345 sizeof (struct GNUNET_MessageHeader), 0,
2347 ¬ify_transport_connect_done,
2349 GNUNET_break (NULL != n->th);
2354 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2355 * the neighbour's struct and retry send_key. Or, if we did not get a
2356 * HELLO, just do nothing.
2358 * @param cls the 'struct Neighbour' to retry sending the key for
2359 * @param peer the peer for which this is the HELLO
2360 * @param hello HELLO message of that peer
2361 * @param trust amount of trust we currently have in that peer
2364 process_hello_retry_send_key (void *cls,
2365 const struct GNUNET_PeerIdentity *peer,
2366 const struct GNUNET_HELLO_Message *hello,
2369 struct Neighbour *n = cls;
2374 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2375 "Entered `%s' and `%s' is NULL!\n",
2376 "process_hello_retry_send_key",
2380 if (n->public_key != NULL)
2382 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2384 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2385 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2387 GNUNET_STATISTICS_update (stats,
2388 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2395 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2396 _("Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n"),
2397 GNUNET_i2s (&n->peer));
2398 GNUNET_STATISTICS_update (stats,
2399 gettext_noop ("# Delayed connecting due to lack of public key"),
2402 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2403 n->retry_set_key_task
2404 = GNUNET_SCHEDULER_add_delayed (sched,
2405 n->set_key_retry_frequency,
2406 &set_key_retry_task, n);
2412 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2413 "Entered `%s' for peer `%4s'\n",
2414 "process_hello_retry_send_key",
2417 if (n->public_key != NULL)
2419 /* already have public key, why are we here? */
2425 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2426 "Received new `%s' message for `%4s', initiating key exchange.\n",
2431 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2432 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2434 GNUNET_STATISTICS_update (stats,
2435 gettext_noop ("# Error extracting public key from HELLO"),
2438 GNUNET_free (n->public_key);
2439 n->public_key = NULL;
2441 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2442 "GNUNET_HELLO_get_key returned awfully\n");
2450 * Send our key (and encrypted PING) to the other peer.
2452 * @param n the other peer
2455 send_key (struct Neighbour *n)
2457 struct MessageEntry *pos;
2458 struct SetKeyMessage *sm;
2459 struct MessageEntry *me;
2460 struct PingMessage pp;
2461 struct PingMessage *pm;
2463 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2465 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2466 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2468 if (n->pitr != NULL)
2471 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2472 "Key exchange in progress with `%4s'.\n",
2473 GNUNET_i2s (&n->peer));
2475 return; /* already in progress */
2477 if (GNUNET_YES != n->is_connected)
2480 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2481 "Not yet connected to peer `%4s'!\n",
2482 GNUNET_i2s (&n->peer));
2486 GNUNET_STATISTICS_update (stats,
2487 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
2490 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2492 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2494 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2495 ¬ify_encrypted_transmit_ready,
2501 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2502 "Asked to perform key exchange with `%4s'.\n",
2503 GNUNET_i2s (&n->peer));
2505 if (n->public_key == NULL)
2507 /* lookup n's public key, then try again */
2509 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2510 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2511 GNUNET_i2s (&n->peer));
2513 GNUNET_assert (n->pitr == NULL);
2514 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2517 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2518 &process_hello_retry_send_key, n);
2521 pos = n->encrypted_head;
2524 if (GNUNET_YES == pos->is_setkey)
2526 if (pos->sender_status == n->status)
2529 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2530 "`%s' message for `%4s' queued already\n",
2532 GNUNET_i2s (&n->peer));
2534 goto trigger_processing;
2536 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2542 "Removing queued `%s' message for `%4s', will create a new one\n",
2544 GNUNET_i2s (&n->peer));
2554 case PEER_STATE_DOWN:
2555 n->status = PEER_STATE_KEY_SENT;
2557 case PEER_STATE_KEY_SENT:
2559 case PEER_STATE_KEY_RECEIVED:
2561 case PEER_STATE_KEY_CONFIRMED:
2569 /* first, set key message */
2570 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2571 sizeof (struct SetKeyMessage) +
2572 sizeof (struct PingMessage));
2573 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2574 me->priority = SET_KEY_PRIORITY;
2575 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
2576 me->is_setkey = GNUNET_YES;
2577 me->got_slack = GNUNET_YES; /* do not defer this one! */
2578 me->sender_status = n->status;
2579 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2583 sm = (struct SetKeyMessage *) &me[1];
2584 sm->header.size = htons (sizeof (struct SetKeyMessage));
2585 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2586 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2587 PEER_STATE_KEY_SENT : n->status));
2589 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2590 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2591 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2592 sizeof (struct GNUNET_PeerIdentity));
2593 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2594 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2595 sm->target = n->peer;
2596 GNUNET_assert (GNUNET_OK ==
2597 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2599 GNUNET_CRYPTO_AesSessionKey),
2601 &sm->encrypted_key));
2602 GNUNET_assert (GNUNET_OK ==
2603 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2605 pm = (struct PingMessage *) &sm[1];
2606 pm->header.size = htons (sizeof (struct PingMessage));
2607 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2608 pp.challenge = htonl (n->ping_challenge);
2609 pp.target = n->peer;
2611 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2612 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u.\n",
2614 (unsigned int) n->ping_challenge,
2615 GNUNET_i2s (&n->peer),
2616 (unsigned int) n->encrypt_key.crc32);
2619 &n->peer.hashPubKey,
2622 sizeof (struct PingMessage) -
2623 sizeof (struct GNUNET_MessageHeader));
2624 GNUNET_STATISTICS_update (stats,
2625 gettext_noop ("# SET_KEY and PING messages created"),
2629 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2630 "Have %llu ms left for `%s' transmission.\n",
2631 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2635 /* trigger queue processing */
2636 process_encrypted_neighbour_queue (n);
2637 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2638 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2639 n->retry_set_key_task
2640 = GNUNET_SCHEDULER_add_delayed (sched,
2641 n->set_key_retry_frequency,
2642 &set_key_retry_task, n);
2647 * We received a SET_KEY message. Validate and update
2648 * our key material and status.
2650 * @param n the neighbour from which we received message m
2651 * @param m the set key message we received
2654 handle_set_key (struct Neighbour *n,
2655 const struct SetKeyMessage *m);
2659 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2660 * the neighbour's struct and retry handling the set_key message. Or,
2661 * if we did not get a HELLO, just free the set key message.
2663 * @param cls pointer to the set key message
2664 * @param peer the peer for which this is the HELLO
2665 * @param hello HELLO message of that peer
2666 * @param trust amount of trust we currently have in that peer
2669 process_hello_retry_handle_set_key (void *cls,
2670 const struct GNUNET_PeerIdentity *peer,
2671 const struct GNUNET_HELLO_Message *hello,
2674 struct Neighbour *n = cls;
2675 struct SetKeyMessage *sm = n->skm;
2681 if (n->public_key != NULL)
2684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2685 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2687 GNUNET_i2s (&n->peer),
2690 handle_set_key (n, sm);
2694 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2695 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
2697 GNUNET_i2s (&n->peer));
2702 if (n->public_key != NULL)
2703 return; /* multiple HELLOs match!? */
2705 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2706 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2708 GNUNET_break_op (0);
2709 GNUNET_free (n->public_key);
2710 n->public_key = NULL;
2716 * We received a PING message. Validate and transmit
2719 * @param n sender of the PING
2720 * @param m the encrypted PING message itself
2723 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2725 struct PingMessage t;
2726 struct PongMessage tx;
2727 struct PongMessage *tp;
2728 struct MessageEntry *me;
2731 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2732 "Core service receives `%s' request from `%4s'.\n",
2733 "PING", GNUNET_i2s (&n->peer));
2737 &my_identity.hashPubKey,
2740 sizeof (struct PingMessage) -
2741 sizeof (struct GNUNET_MessageHeader)))
2744 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2745 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2747 GNUNET_i2s (&t.target),
2748 (unsigned int) ntohl (t.challenge),
2749 (unsigned int) n->decrypt_key.crc32);
2751 GNUNET_STATISTICS_update (stats,
2752 gettext_noop ("# PING messages decrypted"),
2755 if (0 != memcmp (&t.target,
2756 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2758 GNUNET_break_op (0);
2761 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2762 sizeof (struct PongMessage));
2763 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2767 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2768 me->priority = PONG_PRIORITY;
2769 me->size = sizeof (struct PongMessage);
2770 tx.reserved = htonl (0);
2771 tx.inbound_bw_limit = n->bw_in;
2772 tx.challenge = t.challenge;
2773 tx.target = t.target;
2774 tp = (struct PongMessage *) &me[1];
2775 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2776 tp->header.size = htons (sizeof (struct PongMessage));
2778 &my_identity.hashPubKey,
2781 sizeof (struct PongMessage) -
2782 sizeof (struct GNUNET_MessageHeader));
2783 GNUNET_STATISTICS_update (stats,
2784 gettext_noop ("# PONG messages created"),
2788 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2789 "Encrypting `%s' with challenge %u using key %u\n",
2791 (unsigned int) ntohl (t.challenge),
2792 (unsigned int) n->encrypt_key.crc32);
2794 /* trigger queue processing */
2795 process_encrypted_neighbour_queue (n);
2800 * We received a PONG message. Validate and update our status.
2802 * @param n sender of the PONG
2803 * @param m the encrypted PONG message itself
2806 handle_pong (struct Neighbour *n,
2807 const struct PongMessage *m)
2809 struct PongMessage t;
2810 struct ConnectNotifyMessage cnm;
2813 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2814 "Core service receives `%s' response from `%4s'.\n",
2815 "PONG", GNUNET_i2s (&n->peer));
2817 /* mark as garbage, just to be sure */
2818 memset (&t, 255, sizeof (t));
2821 &n->peer.hashPubKey,
2824 sizeof (struct PongMessage) -
2825 sizeof (struct GNUNET_MessageHeader)))
2827 GNUNET_break_op (0);
2830 GNUNET_STATISTICS_update (stats,
2831 gettext_noop ("# PONG messages decrypted"),
2834 if (0 != ntohl (t.reserved))
2836 GNUNET_break_op (0);
2840 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2841 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2843 GNUNET_i2s (&t.target),
2844 (unsigned int) ntohl (t.challenge),
2845 (unsigned int) n->decrypt_key.crc32);
2847 if ((0 != memcmp (&t.target,
2849 sizeof (struct GNUNET_PeerIdentity))) ||
2850 (n->ping_challenge != ntohl (t.challenge)))
2852 /* PONG malformed */
2854 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2855 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2857 GNUNET_i2s (&n->peer),
2858 (unsigned int) n->ping_challenge);
2859 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2860 "Received malformed `%s' received from `%4s' with challenge %u\n",
2861 "PONG", GNUNET_i2s (&t.target),
2862 (unsigned int) ntohl (t.challenge));
2864 GNUNET_break_op (0);
2869 case PEER_STATE_DOWN:
2870 GNUNET_break (0); /* should be impossible */
2872 case PEER_STATE_KEY_SENT:
2873 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2875 case PEER_STATE_KEY_RECEIVED:
2876 GNUNET_STATISTICS_update (stats,
2877 gettext_noop ("# Session keys confirmed via PONG"),
2880 n->status = PEER_STATE_KEY_CONFIRMED;
2881 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2883 n->bw_out_external_limit = t.inbound_bw_limit;
2884 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2885 n->bw_out_internal_limit);
2886 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2888 GNUNET_TRANSPORT_set_quota (transport,
2892 GNUNET_TIME_UNIT_FOREVER_REL,
2896 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2897 "Confirmed key via `%s' message for peer `%4s'\n",
2898 "PONG", GNUNET_i2s (&n->peer));
2900 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2902 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2903 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2905 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2906 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2907 cnm.distance = htonl (n->last_distance);
2908 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2910 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2911 process_encrypted_neighbour_queue (n);
2913 case PEER_STATE_KEY_CONFIRMED:
2914 n->last_activity = GNUNET_TIME_absolute_get ();
2915 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2916 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2918 = GNUNET_SCHEDULER_add_delayed (sched,
2919 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2931 * We received a SET_KEY message. Validate and update
2932 * our key material and status.
2934 * @param n the neighbour from which we received message m
2935 * @param m the set key message we received
2938 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2940 struct SetKeyMessage *m_cpy;
2941 struct GNUNET_TIME_Absolute t;
2942 struct GNUNET_CRYPTO_AesSessionKey k;
2943 struct PingMessage *ping;
2944 struct PongMessage *pong;
2945 enum PeerStateMachine sender_status;
2948 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2949 "Core service receives `%s' request from `%4s'.\n",
2950 "SET_KEY", GNUNET_i2s (&n->peer));
2952 if (n->public_key == NULL)
2954 if (n->pitr != NULL)
2957 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2958 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2964 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2965 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2967 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2968 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2969 /* lookup n's public key, then try again */
2970 GNUNET_assert (n->skm == NULL);
2972 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2975 GNUNET_TIME_UNIT_MINUTES,
2976 &process_hello_retry_handle_set_key, n);
2977 GNUNET_STATISTICS_update (stats,
2978 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2983 if (0 != memcmp (&m->target,
2985 sizeof (struct GNUNET_PeerIdentity)))
2987 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2988 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
2990 GNUNET_i2s (&m->target));
2993 if ((ntohl (m->purpose.size) !=
2994 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2995 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2996 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2997 sizeof (struct GNUNET_PeerIdentity)) ||
2999 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3000 &m->purpose, &m->signature, n->public_key)))
3002 /* invalid signature */
3003 GNUNET_break_op (0);
3006 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3007 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3008 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3009 (t.value < n->decrypt_key_created.value))
3011 /* this could rarely happen due to massive re-ordering of
3012 messages on the network level, but is most likely either
3013 a bug or some adversary messing with us. Report. */
3014 GNUNET_break_op (0);
3018 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3019 "Decrypting key material.\n");
3021 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3024 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3025 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3026 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3028 /* failed to decrypt !? */
3029 GNUNET_break_op (0);
3032 GNUNET_STATISTICS_update (stats,
3033 gettext_noop ("# SET_KEY messages decrypted"),
3037 if (n->decrypt_key_created.value != t.value)
3039 /* fresh key, reset sequence numbers */
3040 n->last_sequence_number_received = 0;
3041 n->last_packets_bitmap = 0;
3042 n->decrypt_key_created = t;
3044 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3047 case PEER_STATE_DOWN:
3048 n->status = PEER_STATE_KEY_RECEIVED;
3050 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3051 "Responding to `%s' with my own key.\n", "SET_KEY");
3055 case PEER_STATE_KEY_SENT:
3056 case PEER_STATE_KEY_RECEIVED:
3057 n->status = PEER_STATE_KEY_RECEIVED;
3058 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3059 (sender_status != PEER_STATE_KEY_CONFIRMED))
3062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3063 "Responding to `%s' with my own key (other peer has status %u).\n",
3065 (unsigned int) sender_status);
3070 case PEER_STATE_KEY_CONFIRMED:
3071 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3072 (sender_status != PEER_STATE_KEY_CONFIRMED))
3075 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3076 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3078 (unsigned int) sender_status);
3087 if (n->pending_ping != NULL)
3089 ping = n->pending_ping;
3090 n->pending_ping = NULL;
3091 handle_ping (n, ping);
3094 if (n->pending_pong != NULL)
3096 pong = n->pending_pong;
3097 n->pending_pong = NULL;
3098 handle_pong (n, pong);
3105 * Send a P2P message to a client.
3107 * @param sender who sent us the message?
3108 * @param client who should we give the message to?
3109 * @param m contains the message to transmit
3110 * @param msize number of bytes in buf to transmit
3113 send_p2p_message_to_client (struct Neighbour *sender,
3114 struct Client *client,
3115 const void *m, size_t msize)
3117 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3118 struct NotifyTrafficMessage *ntm;
3121 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3122 "Core service passes message from `%4s' of type %u to client.\n",
3123 GNUNET_i2s(&sender->peer),
3124 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3126 ntm = (struct NotifyTrafficMessage *) buf;
3127 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3128 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3129 ntm->distance = htonl (sender->last_distance);
3130 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3131 ntm->peer = sender->peer;
3132 memcpy (&ntm[1], m, msize);
3133 send_to_client (client, &ntm->header, GNUNET_YES);
3138 * Deliver P2P message to interested clients.
3140 * @param sender who sent us the message?
3141 * @param m the message
3142 * @param msize size of the message (including header)
3145 deliver_message (struct Neighbour *sender,
3146 const struct GNUNET_MessageHeader *m, size_t msize)
3149 struct Client *cpos;
3155 type = ntohs (m->type);
3157 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3158 "Received encapsulated message of type %u and size %u from `%4s'\n",
3159 (unsigned int) type,
3161 GNUNET_i2s (&sender->peer));
3163 GNUNET_snprintf (buf,
3165 gettext_noop ("# bytes of messages of type %u received"),
3166 (unsigned int) type);
3167 GNUNET_STATISTICS_set (stats,
3171 dropped = GNUNET_YES;
3173 while (cpos != NULL)
3175 deliver_full = GNUNET_NO;
3176 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3177 deliver_full = GNUNET_YES;
3180 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3182 if (type != cpos->types[tpos])
3184 deliver_full = GNUNET_YES;
3188 if (GNUNET_YES == deliver_full)
3190 send_p2p_message_to_client (sender, cpos, m, msize);
3191 dropped = GNUNET_NO;
3193 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3195 send_p2p_message_to_client (sender, cpos, m,
3196 sizeof (struct GNUNET_MessageHeader));
3200 if (dropped == GNUNET_YES)
3203 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3204 "Message of type %u from `%4s' not delivered to any client.\n",
3205 (unsigned int) type,
3206 GNUNET_i2s (&sender->peer));
3208 /* FIXME: stats... */
3214 * Align P2P message and then deliver to interested clients.
3216 * @param sender who sent us the message?
3217 * @param buffer unaligned (!) buffer containing message
3218 * @param msize size of the message (including header)
3221 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
3225 /* TODO: call to statistics? */
3226 memcpy (abuf, buffer, msize);
3227 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
3232 * Deliver P2P messages to interested clients.
3234 * @param sender who sent us the message?
3235 * @param buffer buffer containing messages, can be modified
3236 * @param buffer_size size of the buffer (overall)
3237 * @param offset offset where messages in the buffer start
3240 deliver_messages (struct Neighbour *sender,
3241 const char *buffer, size_t buffer_size, size_t offset)
3243 struct GNUNET_MessageHeader *mhp;
3244 struct GNUNET_MessageHeader mh;
3248 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
3250 if (0 != offset % sizeof (uint16_t))
3252 /* outch, need to copy to access header */
3253 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
3258 /* can access header directly */
3259 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
3261 msize = ntohs (mhp->size);
3262 if (msize + offset > buffer_size)
3264 /* malformed message, header says it is larger than what
3265 would fit into the overall buffer */
3266 GNUNET_break_op (0);
3269 #if HAVE_UNALIGNED_64_ACCESS
3270 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
3272 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
3275 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3276 "Delivering %u bytes of message at offset %u/%u to clients.\n",
3277 (unsigned int) msize,
3278 (unsigned int) offset,
3279 (unsigned int) buffer_size);
3282 if (GNUNET_YES == need_align)
3283 align_and_deliver (sender, &buffer[offset], msize);
3285 deliver_message (sender,
3286 (const struct GNUNET_MessageHeader *)
3287 &buffer[offset], msize);
3294 * We received an encrypted message. Decrypt, validate and
3295 * pass on to the appropriate clients.
3298 handle_encrypted_message (struct Neighbour *n,
3299 const struct EncryptedMessage *m)
3301 size_t size = ntohs (m->header.size);
3303 struct EncryptedMessage *pt; /* plaintext */
3306 struct GNUNET_TIME_Absolute t;
3310 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3311 "Core service receives `%s' request from `%4s'.\n",
3312 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3314 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3320 &buf[ENCRYPTED_HEADER_SIZE],
3321 size - ENCRYPTED_HEADER_SIZE))
3323 pt = (struct EncryptedMessage *) buf;
3325 GNUNET_CRYPTO_hash (&pt->sequence_number,
3326 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3328 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3329 "V-Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
3330 (unsigned int) (size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode)),
3334 if (0 != memcmp (&ph,
3335 &pt->plaintext_hash,
3336 sizeof (GNUNET_HashCode)))
3338 /* checksum failed */
3339 GNUNET_break_op (0);
3343 /* validate sequence number */
3344 snum = ntohl (pt->sequence_number);
3345 if (n->last_sequence_number_received == snum)
3347 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3348 "Received duplicate message, ignoring.\n");
3349 /* duplicate, ignore */
3350 GNUNET_STATISTICS_set (stats,
3351 gettext_noop ("# bytes dropped (duplicates)"),
3356 if ((n->last_sequence_number_received > snum) &&
3357 (n->last_sequence_number_received - snum > 32))
3359 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3360 "Received ancient out of sequence message, ignoring.\n");
3361 /* ancient out of sequence, ignore */
3362 GNUNET_STATISTICS_set (stats,
3363 gettext_noop ("# bytes dropped (out of sequence)"),
3368 if (n->last_sequence_number_received > snum)
3370 unsigned int rotbit =
3371 1 << (n->last_sequence_number_received - snum - 1);
3372 if ((n->last_packets_bitmap & rotbit) != 0)
3374 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3375 "Received duplicate message, ignoring.\n");
3376 GNUNET_STATISTICS_set (stats,
3377 gettext_noop ("# bytes dropped (duplicates)"),
3380 /* duplicate, ignore */
3383 n->last_packets_bitmap |= rotbit;
3385 if (n->last_sequence_number_received < snum)
3387 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3388 n->last_sequence_number_received = snum;
3391 /* check timestamp */
3392 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3393 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3395 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3397 ("Message received far too old (%llu ms). Content ignored.\n"),
3398 GNUNET_TIME_absolute_get_duration (t).value);
3399 GNUNET_STATISTICS_set (stats,
3400 gettext_noop ("# bytes dropped (ancient message)"),
3406 /* process decrypted message(s) */
3407 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3409 #if DEBUG_CORE_SET_QUOTA
3410 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3411 "Received %u b/s as new inbound limit for peer `%4s'\n",
3412 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3413 GNUNET_i2s (&n->peer));
3415 n->bw_out_external_limit = pt->inbound_bw_limit;
3416 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3417 n->bw_out_internal_limit);
3418 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3420 GNUNET_TRANSPORT_set_quota (transport,
3424 GNUNET_TIME_UNIT_FOREVER_REL,
3427 n->last_activity = GNUNET_TIME_absolute_get ();
3428 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3429 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3431 = GNUNET_SCHEDULER_add_delayed (sched,
3432 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3435 GNUNET_STATISTICS_set (stats,
3436 gettext_noop ("# bytes of payload decrypted"),
3437 size - sizeof (struct EncryptedMessage),
3439 deliver_messages (n, buf, size, sizeof (struct EncryptedMessage));
3444 * Function called by the transport for each received message.
3446 * @param cls closure
3447 * @param peer (claimed) identity of the other peer
3448 * @param message the message
3449 * @param latency estimated latency for communicating with the
3450 * given peer (round-trip)
3451 * @param distance in overlay hops, as given by transport plugin
3454 handle_transport_receive (void *cls,
3455 const struct GNUNET_PeerIdentity *peer,
3456 const struct GNUNET_MessageHeader *message,
3457 struct GNUNET_TIME_Relative latency,
3458 unsigned int distance)
3460 struct Neighbour *n;
3461 struct GNUNET_TIME_Absolute now;
3467 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3468 "Received message of type %u from `%4s', demultiplexing.\n",
3469 (unsigned int) ntohs (message->type),
3472 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3477 n = find_neighbour (peer);
3479 n = create_neighbour (peer);
3480 n->last_latency = latency;
3481 n->last_distance = distance;
3482 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3483 type = ntohs (message->type);
3484 size = ntohs (message->size);
3487 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3488 if (size != sizeof (struct SetKeyMessage))
3490 GNUNET_break_op (0);
3493 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3494 handle_set_key (n, (const struct SetKeyMessage *) message);
3496 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3497 if (size < sizeof (struct EncryptedMessage) +
3498 sizeof (struct GNUNET_MessageHeader))
3500 GNUNET_break_op (0);
3503 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3504 (n->status != PEER_STATE_KEY_CONFIRMED))
3506 GNUNET_break_op (0);
3509 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3511 case GNUNET_MESSAGE_TYPE_CORE_PING:
3512 if (size != sizeof (struct PingMessage))
3514 GNUNET_break_op (0);
3517 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3518 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3519 (n->status != PEER_STATE_KEY_CONFIRMED))
3522 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3523 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3524 "PING", GNUNET_i2s (&n->peer));
3526 GNUNET_free_non_null (n->pending_ping);
3527 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3528 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3531 handle_ping (n, (const struct PingMessage *) message);
3533 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3534 if (size != sizeof (struct PongMessage))
3536 GNUNET_break_op (0);
3539 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3540 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3541 (n->status != PEER_STATE_KEY_CONFIRMED) )
3544 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3545 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3546 "PONG", GNUNET_i2s (&n->peer));
3548 GNUNET_free_non_null (n->pending_pong);
3549 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3550 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3553 handle_pong (n, (const struct PongMessage *) message);
3556 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3557 _("Unsupported message of type %u received.\n"),
3558 (unsigned int) type);
3561 if (n->status == PEER_STATE_KEY_CONFIRMED)
3563 now = GNUNET_TIME_absolute_get ();
3564 n->last_activity = now;
3567 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3568 n->time_established = now;
3570 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3571 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3573 = GNUNET_SCHEDULER_add_delayed (sched,
3574 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3582 * Function that recalculates the bandwidth quota for the
3583 * given neighbour and transmits it to the transport service.
3585 * @param cls neighbour for the quota update
3589 neighbour_quota_update (void *cls,
3590 const struct GNUNET_SCHEDULER_TaskContext *tc)
3592 struct Neighbour *n = cls;
3593 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3596 unsigned long long distributable;
3597 uint64_t need_per_peer;
3598 uint64_t need_per_second;
3601 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3602 "Neighbour quota update calculation running for peer `%4s'\n",
3603 GNUNET_i2s (&n->peer));
3605 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3606 /* calculate relative preference among all neighbours;
3607 divides by a bit more to avoid division by zero AND to
3608 account for possibility of new neighbours joining any time
3609 AND to convert to double... */
3610 if (preference_sum == 0)
3612 pref_rel = 1.0 / (double) neighbour_count;
3616 pref_rel = n->current_preference / preference_sum;
3618 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3619 GNUNET_TIME_UNIT_SECONDS);
3620 need_per_second = need_per_peer * neighbour_count;
3622 if (bandwidth_target_out_bps > need_per_second)
3623 distributable = bandwidth_target_out_bps - need_per_second;
3624 share = distributable * pref_rel;
3625 if (share + need_per_peer > UINT32_MAX)
3626 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
3628 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3629 /* check if we want to disconnect for good due to inactivity */
3630 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3631 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3634 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3635 "Forcing disconnect of `%4s' due to inactivity\n",
3636 GNUNET_i2s (&n->peer));
3638 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3640 #if DEBUG_CORE_QUOTA
3641 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3642 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3643 GNUNET_i2s (&n->peer),
3644 (unsigned int) ntohl (q_in.value__),
3645 bandwidth_target_out_bps,
3646 (unsigned int) ntohl (n->bw_in.value__),
3647 (unsigned int) ntohl (n->bw_out.value__),
3648 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3650 if (n->bw_in.value__ != q_in.value__)
3653 if (GNUNET_YES == n->is_connected)
3654 GNUNET_TRANSPORT_set_quota (transport,
3658 GNUNET_TIME_UNIT_FOREVER_REL,
3661 schedule_quota_update (n);
3666 * Function called by transport to notify us that
3667 * a peer connected to us (on the network level).
3669 * @param cls closure
3670 * @param peer the peer that connected
3671 * @param latency current latency of the connection
3672 * @param distance in overlay hops, as given by transport plugin
3675 handle_transport_notify_connect (void *cls,
3676 const struct GNUNET_PeerIdentity *peer,
3677 struct GNUNET_TIME_Relative latency,
3678 unsigned int distance)
3680 struct Neighbour *n;
3682 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3687 n = find_neighbour (peer);
3690 if (GNUNET_YES == n->is_connected)
3692 /* duplicate connect notification!? */
3699 n = create_neighbour (peer);
3701 GNUNET_STATISTICS_update (stats,
3702 gettext_noop ("# peers connected (transport)"),
3705 n->is_connected = GNUNET_YES;
3706 n->last_latency = latency;
3707 n->last_distance = distance;
3708 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3711 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3715 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3716 "Received connection from `%4s'.\n",
3717 GNUNET_i2s (&n->peer));
3719 GNUNET_TRANSPORT_set_quota (transport,
3723 GNUNET_TIME_UNIT_FOREVER_REL,
3730 * Function called by transport telling us that a peer
3733 * @param cls closure
3734 * @param peer the peer that disconnected
3737 handle_transport_notify_disconnect (void *cls,
3738 const struct GNUNET_PeerIdentity *peer)
3740 struct DisconnectNotifyMessage cnm;
3741 struct Neighbour *n;
3744 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3745 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3747 n = find_neighbour (peer);
3753 GNUNET_break (n->is_connected);
3754 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3755 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3757 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3758 n->is_connected = GNUNET_NO;
3759 GNUNET_STATISTICS_update (stats,
3760 gettext_noop ("# peers connected (transport)"),
3767 * Last task run during shutdown. Disconnects us from
3771 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3773 struct Neighbour *n;
3777 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3778 "Core service shutting down.\n");
3780 GNUNET_assert (transport != NULL);
3781 GNUNET_TRANSPORT_disconnect (transport);
3783 while (NULL != (n = neighbours))
3785 neighbours = n->next;
3786 GNUNET_assert (neighbour_count > 0);
3790 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
3791 GNUNET_SERVER_notification_context_destroy (notifier);
3793 while (NULL != (c = clients))
3794 handle_client_disconnect (NULL, c->client_handle);
3795 if (my_private_key != NULL)
3796 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3798 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3799 if (peerinfo != NULL)
3800 GNUNET_PEERINFO_disconnect (peerinfo);
3805 * Initiate core service.
3807 * @param cls closure
3808 * @param s scheduler to use
3809 * @param serv the initialized server
3810 * @param c configuration to use
3814 struct GNUNET_SCHEDULER_Handle *s,
3815 struct GNUNET_SERVER_Handle *serv,
3816 const struct GNUNET_CONFIGURATION_Handle *c)
3818 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3819 {&handle_client_init, NULL,
3820 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
3821 {&handle_client_request_info, NULL,
3822 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
3823 sizeof (struct RequestInfoMessage)},
3824 {&handle_client_send, NULL,
3825 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
3826 {&handle_client_request_connect, NULL,
3827 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
3828 sizeof (struct ConnectMessage)},
3835 /* parse configuration */
3838 GNUNET_CONFIGURATION_get_value_number (c,
3841 &bandwidth_target_in_bps)) ||
3843 GNUNET_CONFIGURATION_get_value_number (c,
3846 &bandwidth_target_out_bps)) ||
3848 GNUNET_CONFIGURATION_get_value_filename (c,
3850 "HOSTKEY", &keyfile)))
3852 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3854 ("Core service is lacking key configuration settings. Exiting.\n"));
3855 GNUNET_SCHEDULER_shutdown (s);
3858 peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
3859 if (NULL == peerinfo)
3861 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3862 _("Could not access PEERINFO service. Exiting.\n"));
3863 GNUNET_SCHEDULER_shutdown (s);
3864 GNUNET_free (keyfile);
3867 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3868 GNUNET_free (keyfile);
3869 if (my_private_key == NULL)
3871 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3872 _("Core service could not access hostkey. Exiting.\n"));
3873 GNUNET_PEERINFO_disconnect (peerinfo);
3874 GNUNET_SCHEDULER_shutdown (s);
3877 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3878 GNUNET_CRYPTO_hash (&my_public_key,
3879 sizeof (my_public_key), &my_identity.hashPubKey);
3880 /* setup notification */
3882 notifier = GNUNET_SERVER_notification_context_create (server,
3884 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3885 /* setup transport connection */
3886 transport = GNUNET_TRANSPORT_connect (sched,
3889 &handle_transport_receive,
3890 &handle_transport_notify_connect,
3891 &handle_transport_notify_disconnect);
3892 GNUNET_assert (NULL != transport);
3893 stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3894 GNUNET_SCHEDULER_add_delayed (sched,
3895 GNUNET_TIME_UNIT_FOREVER_REL,
3896 &cleaning_task, NULL);
3897 /* process client requests */
3898 GNUNET_SERVER_add_handlers (server, handlers);
3899 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3900 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3906 * The main function for the transport service.
3908 * @param argc number of arguments from the command line
3909 * @param argv command line arguments
3910 * @return 0 ok, 1 on error
3913 main (int argc, char *const *argv)
3915 return (GNUNET_OK ==
3916 GNUNET_SERVICE_run (argc,
3919 GNUNET_SERVICE_OPTION_NONE,
3920 &run, NULL)) ? 0 : 1;
3923 /* end of gnunet-service-core.c */