2 This file is part of GNUnet.
3 (C) 2009, 2010 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 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file core/gnunet-service-core.c
23 * @brief high-level P2P messaging
24 * @author Christian Grothoff
26 * Considerations for later:
27 * - check that hostkey used by transport (for HELLOs) is the
28 * same as the hostkey that we are using!
29 * - add code to send PINGs if we are about to time-out otherwise
30 * - optimize lookup (many O(n) list traversals
31 * could ideally be changed to O(1) hash map lookups)
34 #include "gnunet_constants.h"
35 #include "gnunet_util_lib.h"
36 #include "gnunet_hello_lib.h"
37 #include "gnunet_peerinfo_service.h"
38 #include "gnunet_protocols.h"
39 #include "gnunet_signatures.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet_transport_service.h"
45 #define DEBUG_HANDSHAKE GNUNET_NO
47 #define DEBUG_CORE_QUOTA GNUNET_YES
50 * Receive and send buffer windows grow over time. For
51 * how long can 'unused' bandwidth accumulate before we
52 * need to cap it? (specified in seconds).
54 #define MAX_WINDOW_TIME_S (5 * 60)
57 * How many messages do we queue up at most for optional
58 * notifications to a client? (this can cause notifications
59 * about outgoing messages to be dropped).
61 #define MAX_NOTIFY_QUEUE 1024
64 * Minimum bandwidth (out) to assign to any connected peer.
65 * Should be rather low; values larger than DEFAULT_BW_IN_OUT make no
68 #define MIN_BANDWIDTH_PER_PEER GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT
71 * After how much time past the "official" expiration time do
72 * we discard messages? Should not be zero since we may
73 * intentionally defer transmission until close to the deadline
74 * and then may be slightly past the deadline due to inaccuracy
75 * in sleep and our own CPU consumption.
77 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
80 * What is the maximum delay for a SET_KEY message?
82 #define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
85 * How long do we wait for SET_KEY confirmation initially?
87 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 1)
90 * What is the maximum delay for a PING message?
92 #define MAX_PING_DELAY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 2)
95 * What is the maximum delay for a PONG message?
97 #define MAX_PONG_DELAY GNUNET_TIME_relative_multiply (MAX_PING_DELAY, 2)
100 * What is the minimum frequency for a PING message?
102 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
105 * How often do we recalculate bandwidth quotas?
107 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
110 * What is the priority for a SET_KEY message?
112 #define SET_KEY_PRIORITY 0xFFFFFF
115 * What is the priority for a PING message?
117 #define PING_PRIORITY 0xFFFFFF
120 * What is the priority for a PONG message?
122 #define PONG_PRIORITY 0xFFFFFF
125 * How many messages do we queue per peer at most? Must be at
128 #define MAX_PEER_QUEUE_SIZE 16
131 * How many non-mandatory messages do we queue per client at most?
133 #define MAX_CLIENT_QUEUE_SIZE 32
136 * What is the maximum age of a message for us to consider
137 * processing it? Note that this looks at the timestamp used
138 * by the other peer, so clock skew between machines does
139 * come into play here. So this should be picked high enough
140 * so that a little bit of clock skew does not prevent peers
141 * from connecting to us.
143 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
147 * State machine for our P2P encryption handshake. Everyone starts in
148 * "DOWN", if we receive the other peer's key (other peer initiated)
149 * we start in state RECEIVED (since we will immediately send our
150 * own); otherwise we start in SENT. If we get back a PONG from
151 * within either state, we move up to CONFIRMED (the PONG will always
152 * be sent back encrypted with the key we sent to the other peer).
154 enum PeerStateMachine
158 PEER_STATE_KEY_RECEIVED,
159 PEER_STATE_KEY_CONFIRMED
164 * Number of bytes (at the beginning) of "struct EncryptedMessage"
165 * that are NOT encrypted.
167 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t))
171 * Encapsulation for encrypted messages exchanged between
172 * peers. Followed by the actual encrypted data.
174 struct EncryptedMessage
177 * Message type is either CORE_ENCRYPTED_MESSAGE.
179 struct GNUNET_MessageHeader header;
182 * Random value used for IV generation. ENCRYPTED_HEADER_SIZE must
183 * be set to the offset of the *next* field.
185 uint32_t iv_seed GNUNET_PACKED;
188 * Hash of the plaintext (starting at 'sequence_number'), used to
189 * verify message integrity. Everything after this hash (including
190 * this hash itself) will be encrypted.
192 GNUNET_HashCode hmac;
195 * Sequence number, in network byte order. This field
196 * must be the first encrypted/decrypted field and the
197 * first byte that is hashed for the plaintext hash.
199 uint32_t sequence_number GNUNET_PACKED;
202 * Desired bandwidth (how much we should send to this peer / how
203 * much is the sender willing to receive)?
205 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
208 * Timestamp. Used to prevent reply of ancient messages
209 * (recent messages are caught with the sequence number).
211 struct GNUNET_TIME_AbsoluteNBO timestamp;
217 * We're sending an (encrypted) PING to the other peer to check if he
218 * can decrypt. The other peer should respond with a PONG with the
219 * same content, except this time encrypted with the receiver's key.
224 * Message type is CORE_PING.
226 struct GNUNET_MessageHeader header;
231 /* FIXME: Does adding this member break things (why?) */
232 /*uint32_t iv_seed GNUNET_PACKED;*/
235 * Random number chosen to make reply harder.
237 uint32_t challenge GNUNET_PACKED;
240 * Intended target of the PING, used primarily to check
241 * that decryption actually worked.
243 struct GNUNET_PeerIdentity target;
249 * Response to a PING. Includes data from the original PING
250 * plus initial bandwidth quota information.
255 * Message type is CORE_PONG.
257 struct GNUNET_MessageHeader header;
262 /* FIXME: Does adding this member break things (why?) */
263 /*uint32_t iv_seed GNUNET_PACKED;*/
266 * Random number proochosen to make reply harder. Must be
267 * first field after header (this is where we start to encrypt!).
269 uint32_t challenge GNUNET_PACKED;
274 uint32_t reserved GNUNET_PACKED;
277 * Desired bandwidth (how much we should send to this
278 * peer / how much is the sender willing to receive).
280 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
283 * Intended target of the PING, used primarily to check
284 * that decryption actually worked.
286 struct GNUNET_PeerIdentity target;
291 * Message transmitted to set (or update) a session key.
297 * Message type is either CORE_SET_KEY.
299 struct GNUNET_MessageHeader header;
302 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
304 int32_t sender_status GNUNET_PACKED;
307 * Purpose of the signature, will be
308 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
310 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
313 * At what time was this key created?
315 struct GNUNET_TIME_AbsoluteNBO creation_time;
318 * The encrypted session key.
320 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
323 * Who is the intended recipient?
325 struct GNUNET_PeerIdentity target;
328 * Signature of the stuff above (starting at purpose).
330 struct GNUNET_CRYPTO_RsaSignature signature;
336 * Message waiting for transmission. This struct
337 * is followed by the actual content of the message.
343 * We keep messages in a doubly linked list.
345 struct MessageEntry *next;
348 * We keep messages in a doubly linked list.
350 struct MessageEntry *prev;
353 * By when are we supposed to transmit this message?
355 struct GNUNET_TIME_Absolute deadline;
358 * By when are we supposed to transmit this message (after
361 struct GNUNET_TIME_Absolute slack_deadline;
364 * How important is this message to us?
366 unsigned int priority;
369 * If this is a SET_KEY message, what was our connection status when this
370 * message was queued?
372 enum PeerStateMachine sender_status;
375 * Is this a SET_KEY message?
380 * How long is the message? (number of bytes following
381 * the "struct MessageEntry", but not including the
382 * size of "struct MessageEntry" itself!)
387 * Was this message selected for transmission in the
388 * current round? GNUNET_YES or GNUNET_NO.
393 * Did we give this message some slack (delayed sending) previously
394 * (and hence should not give it any more slack)? GNUNET_YES or
405 * We keep neighbours in a linked list (for now).
407 struct Neighbour *next;
410 * Unencrypted messages destined for this peer.
412 struct MessageEntry *messages;
415 * Head of the batched, encrypted message queue (already ordered,
416 * transmit starting with the head).
418 struct MessageEntry *encrypted_head;
421 * Tail of the batched, encrypted message queue (already ordered,
422 * append new messages to tail)
424 struct MessageEntry *encrypted_tail;
427 * Handle for pending requests for transmission to this peer
428 * with the transport service. NULL if no request is pending.
430 struct GNUNET_TRANSPORT_TransmitHandle *th;
433 * Public key of the neighbour, NULL if we don't have it yet.
435 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
438 * We received a PING message before we got the "public_key"
439 * (or the SET_KEY). We keep it here until we have a key
440 * to decrypt it. NULL if no PING is pending.
442 struct PingMessage *pending_ping;
445 * We received a PONG message before we got the "public_key"
446 * (or the SET_KEY). We keep it here until we have a key
447 * to decrypt it. NULL if no PONG is pending.
449 struct PongMessage *pending_pong;
452 * Non-NULL if we are currently looking up HELLOs for this peer.
455 struct GNUNET_PEERINFO_IteratorContext *pitr;
458 * SetKeyMessage to transmit, NULL if we are not currently trying
461 struct SetKeyMessage *skm;
464 * Identity of the neighbour.
466 struct GNUNET_PeerIdentity peer;
469 * Key we use to encrypt our messages for the other peer
470 * (initialized by us when we do the handshake).
472 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
475 * Key we use to decrypt messages from the other peer
476 * (given to us by the other peer during the handshake).
478 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
481 * ID of task used for re-trying plaintext scheduling.
483 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
486 * ID of task used for re-trying SET_KEY and PING message.
488 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
491 * ID of task used for updating bandwidth quota for this neighbour.
493 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
496 * ID of task used for sending keep-alive pings.
498 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
501 * ID of task used for cleaning up dead neighbour entries.
503 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
506 * At what time did we generate our encryption key?
508 struct GNUNET_TIME_Absolute encrypt_key_created;
511 * At what time did the other peer generate the decryption key?
513 struct GNUNET_TIME_Absolute decrypt_key_created;
516 * At what time did we initially establish (as in, complete session
517 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
519 struct GNUNET_TIME_Absolute time_established;
522 * At what time did we last receive an encrypted message from the
523 * other peer? Should be zero if status != KEY_CONFIRMED.
525 struct GNUNET_TIME_Absolute last_activity;
528 * Last latency observed from this peer.
530 struct GNUNET_TIME_Relative last_latency;
533 * At what frequency are we currently re-trying SET_KEY messages?
535 struct GNUNET_TIME_Relative set_key_retry_frequency;
538 * Tracking bandwidth for sending to this peer.
540 struct GNUNET_BANDWIDTH_Tracker available_send_window;
543 * Tracking bandwidth for receiving from this peer.
545 struct GNUNET_BANDWIDTH_Tracker available_recv_window;
548 * How valueable were the messages of this peer recently?
550 unsigned long long current_preference;
553 * Bit map indicating which of the 32 sequence numbers before the last
554 * were received (good for accepting out-of-order packets and
555 * estimating reliability of the connection)
557 unsigned int last_packets_bitmap;
560 * last sequence number received on this connection (highest)
562 uint32_t last_sequence_number_received;
565 * last sequence number transmitted
567 uint32_t last_sequence_number_sent;
570 * Available bandwidth in for this peer (current target).
572 struct GNUNET_BANDWIDTH_Value32NBO bw_in;
575 * Available bandwidth out for this peer (current target).
577 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
580 * Internal bandwidth limit set for this peer (initially typically
581 * set to "-1"). Actual "bw_out" is MIN of
582 * "bpm_out_internal_limit" and "bw_out_external_limit".
584 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
587 * External bandwidth limit set for this peer by the
588 * peer that we are communicating with. "bw_out" is MIN of
589 * "bw_out_internal_limit" and "bw_out_external_limit".
591 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
594 * What was our PING challenge number (for this peer)?
596 uint32_t ping_challenge;
599 * What was the last distance to this peer as reported by the transports?
601 uint32_t last_distance;
604 * What is our connection status?
606 enum PeerStateMachine status;
609 * Are we currently connected to this neighbour?
617 * Data structure for each client connected to the core service.
622 * Clients are kept in a linked list.
627 * Handle for the client with the server API.
629 struct GNUNET_SERVER_Client *client_handle;
632 * Array of the types of messages this peer cares
633 * about (with "tcnt" entries). Allocated as part
634 * of this client struct, do not free!
636 const uint16_t *types;
639 * Options for messages this client cares about,
640 * see GNUNET_CORE_OPTION_ values.
645 * Number of types of incoming messages this client
646 * specifically cares about. Size of the "types" array.
656 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
661 static struct GNUNET_PeerIdentity my_identity;
666 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
671 struct GNUNET_SCHEDULER_Handle *sched;
674 * Handle to peerinfo service.
676 static struct GNUNET_PEERINFO_Handle *peerinfo;
679 * Our message stream tokenizer (for encrypted payload).
681 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
686 const struct GNUNET_CONFIGURATION_Handle *cfg;
691 static struct GNUNET_TRANSPORT_Handle *transport;
694 * Linked list of our clients.
696 static struct Client *clients;
699 * Context for notifications we need to send to our clients.
701 static struct GNUNET_SERVER_NotificationContext *notifier;
704 * We keep neighbours in a linked list (for now).
706 static struct Neighbour *neighbours;
709 * For creating statistics.
711 static struct GNUNET_STATISTICS_Handle *stats;
714 * Sum of all preferences among all neighbours.
716 static unsigned long long preference_sum;
719 * Total number of neighbours we have.
721 static unsigned int neighbour_count;
724 * How much inbound bandwidth are we supposed to be using per second?
725 * FIXME: this value is not used!
727 static unsigned long long bandwidth_target_in_bps;
730 * How much outbound bandwidth are we supposed to be using per second?
732 static unsigned long long bandwidth_target_out_bps;
737 * A preference value for a neighbour was update. Update
738 * the preference sum accordingly.
740 * @param inc how much was a preference value increased?
743 update_preference_sum (unsigned long long inc)
746 unsigned long long os;
749 preference_sum += inc;
750 if (preference_sum >= os)
752 /* overflow! compensate by cutting all values in half! */
757 n->current_preference /= 2;
758 preference_sum += n->current_preference;
761 GNUNET_STATISTICS_set (stats, gettext_noop ("# total peer preference"), preference_sum, GNUNET_NO);
766 * Find the entry for the given neighbour.
768 * @param peer identity of the neighbour
769 * @return NULL if we are not connected, otherwise the
772 static struct Neighbour *
773 find_neighbour (const struct GNUNET_PeerIdentity *peer)
775 struct Neighbour *ret;
778 while ((ret != NULL) &&
779 (0 != memcmp (&ret->peer,
780 peer, sizeof (struct GNUNET_PeerIdentity))))
787 * Send a message to one of our clients.
789 * @param client target for the message
790 * @param msg message to transmit
791 * @param can_drop could this message be dropped if the
792 * client's queue is getting too large?
795 send_to_client (struct Client *client,
796 const struct GNUNET_MessageHeader *msg,
799 #if DEBUG_CORE_CLIENT
800 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
801 "Preparing to send %u bytes of message of type %u to client.\n",
802 (unsigned int) ntohs (msg->size),
803 (unsigned int) ntohs (msg->type));
805 GNUNET_SERVER_notification_context_unicast (notifier,
806 client->client_handle,
813 * Send a message to all of our current clients that have
814 * the right options set.
816 * @param msg message to multicast
817 * @param can_drop can this message be discarded if the queue is too long
818 * @param options mask to use
821 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
830 if (0 != (c->options & options))
832 #if DEBUG_CORE_CLIENT
833 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
834 "Sending message of type %u to client.\n",
835 (unsigned int) ntohs (msg->type));
837 send_to_client (c, msg, can_drop);
845 * Function called by transport telling us that a peer
848 * @param n the peer that changed status
851 handle_peer_status_change (struct Neighbour *n)
853 struct PeerStatusNotifyMessage psnm;
855 if (! n->is_connected)
858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
859 "Peer `%4s' changed status\n",
860 GNUNET_i2s (&n->peer));
862 psnm.header.size = htons (sizeof (struct PeerStatusNotifyMessage));
863 psnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_STATUS_CHANGE);
864 psnm.distance = htonl (n->last_distance);
865 psnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
866 psnm.timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_add (n->last_activity,
867 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
868 psnm.bandwidth_in = n->bw_in;
869 psnm.bandwidth_out = n->bw_out;
871 send_to_all_clients (&psnm.header,
873 GNUNET_CORE_OPTION_SEND_STATUS_CHANGE);
874 GNUNET_STATISTICS_update (stats,
875 gettext_noop ("# peer status changes"),
881 * Handle CORE_ITERATE_PEERS request.
884 handle_client_iterate_peers (void *cls,
885 struct GNUNET_SERVER_Client *client,
886 const struct GNUNET_MessageHeader *message)
889 struct ConnectNotifyMessage cnm;
890 struct GNUNET_MessageHeader done_msg;
891 struct GNUNET_SERVER_TransmitContext *tc;
893 /* notify new client about existing neighbours */
894 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
895 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
896 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
897 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
898 tc = GNUNET_SERVER_transmit_context_create (client);
902 if (n->status == PEER_STATE_KEY_CONFIRMED)
904 #if DEBUG_CORE_CLIENT
905 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
906 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
908 cnm.distance = htonl (n->last_distance);
909 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
911 GNUNET_SERVER_transmit_context_append_message (tc, &cnm.header);
912 /*send_to_client (c, &cnm.header, GNUNET_NO);*/
917 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
918 GNUNET_SERVER_transmit_context_run (tc,
919 GNUNET_TIME_UNIT_FOREVER_REL);
924 * Handle CORE_INIT request.
927 handle_client_init (void *cls,
928 struct GNUNET_SERVER_Client *client,
929 const struct GNUNET_MessageHeader *message)
931 const struct InitMessage *im;
932 struct InitReplyMessage irm;
935 const uint16_t *types;
938 struct ConnectNotifyMessage cnm;
941 #if DEBUG_CORE_CLIENT
942 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
943 "Client connecting to core service with `%s' message\n",
946 /* check that we don't have an entry already */
950 if (client == c->client_handle)
953 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
958 msize = ntohs (message->size);
959 if (msize < sizeof (struct InitMessage))
962 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
965 GNUNET_SERVER_notification_context_add (notifier, client);
966 im = (const struct InitMessage *) message;
967 types = (const uint16_t *) &im[1];
968 msize -= sizeof (struct InitMessage);
969 c = GNUNET_malloc (sizeof (struct Client) + msize);
970 c->client_handle = client;
973 c->tcnt = msize / sizeof (uint16_t);
974 c->types = (const uint16_t *) &c[1];
975 wtypes = (uint16_t *) &c[1];
976 for (i=0;i<c->tcnt;i++)
977 wtypes[i] = ntohs (types[i]);
978 c->options = ntohl (im->options);
979 #if DEBUG_CORE_CLIENT
980 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
981 "Client %p is interested in %u message types\n",
983 (unsigned int) c->tcnt);
985 /* send init reply message */
986 irm.header.size = htons (sizeof (struct InitReplyMessage));
987 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
988 irm.reserved = htonl (0);
989 memcpy (&irm.publicKey,
991 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
992 #if DEBUG_CORE_CLIENT
993 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
994 "Sending `%s' message to client.\n", "INIT_REPLY");
996 send_to_client (c, &irm.header, GNUNET_NO);
997 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
999 /* notify new client about existing neighbours */
1000 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
1001 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1005 if (n->status == PEER_STATE_KEY_CONFIRMED)
1007 #if DEBUG_CORE_CLIENT
1008 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1009 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
1011 cnm.distance = htonl (n->last_distance);
1012 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
1014 send_to_client (c, &cnm.header, GNUNET_NO);
1019 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1024 * A client disconnected, clean up.
1026 * @param cls closure
1027 * @param client identification of the client
1030 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1033 struct Client *prev;
1037 #if DEBUG_CORE_CLIENT
1038 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1039 "Client %p has disconnected from core service.\n",
1046 if (client == pos->client_handle)
1049 clients = pos->next;
1051 prev->next = pos->next;
1058 /* client never sent INIT */
1063 * Handle REQUEST_INFO request.
1066 handle_client_request_info (void *cls,
1067 struct GNUNET_SERVER_Client *client,
1068 const struct GNUNET_MessageHeader *message)
1070 const struct RequestInfoMessage *rcm;
1071 struct Neighbour *n;
1072 struct ConfigurationInfoMessage cim;
1073 int32_t want_reserv;
1075 unsigned long long old_preference;
1076 struct GNUNET_SERVER_TransmitContext *tc;
1078 #if DEBUG_CORE_CLIENT
1079 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1080 "Core service receives `%s' request.\n", "REQUEST_INFO");
1082 rcm = (const struct RequestInfoMessage *) message;
1083 n = find_neighbour (&rcm->peer);
1084 memset (&cim, 0, sizeof (cim));
1087 want_reserv = ntohl (rcm->reserve_inbound);
1088 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1090 n->bw_out_internal_limit = rcm->limit_outbound;
1091 if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1092 n->bw_out_external_limit).value__)
1094 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1095 n->bw_out_external_limit);
1096 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1098 GNUNET_TRANSPORT_set_quota (transport,
1102 GNUNET_TIME_UNIT_FOREVER_REL,
1104 handle_peer_status_change (n);
1107 if (want_reserv < 0)
1109 got_reserv = want_reserv;
1111 else if (want_reserv > 0)
1113 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1114 want_reserv).value == 0)
1115 got_reserv = want_reserv;
1117 got_reserv = 0; /* all or nothing */
1121 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1123 old_preference = n->current_preference;
1124 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1125 if (old_preference > n->current_preference)
1127 /* overflow; cap at maximum value */
1128 n->current_preference = ULLONG_MAX;
1130 update_preference_sum (n->current_preference - old_preference);
1131 #if DEBUG_CORE_QUOTA
1132 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1133 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1135 GNUNET_i2s (&rcm->peer),
1138 cim.reserved_amount = htonl (got_reserv);
1139 cim.bw_in = n->bw_in;
1140 cim.bw_out = n->bw_out;
1141 cim.preference = n->current_preference;
1143 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1144 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1145 cim.peer = rcm->peer;
1147 #if DEBUG_CORE_CLIENT
1148 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1149 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1151 tc = GNUNET_SERVER_transmit_context_create (client);
1152 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1153 GNUNET_SERVER_transmit_context_run (tc,
1154 GNUNET_TIME_UNIT_FOREVER_REL);
1159 * Free the given entry for the neighbour (it has
1160 * already been removed from the list at this point).
1162 * @param n neighbour to free
1165 free_neighbour (struct Neighbour *n)
1167 struct MessageEntry *m;
1170 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1171 "Destroying neighbour entry for peer `%4s'\n",
1172 GNUNET_i2s (&n->peer));
1174 if (n->pitr != NULL)
1176 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1181 GNUNET_free (n->skm);
1184 while (NULL != (m = n->messages))
1186 n->messages = m->next;
1189 while (NULL != (m = n->encrypted_head))
1191 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1198 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1201 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1202 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1203 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1204 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1205 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1206 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1207 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1208 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1209 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1210 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1211 if (n->status == PEER_STATE_KEY_CONFIRMED)
1212 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1213 GNUNET_free_non_null (n->public_key);
1214 GNUNET_free_non_null (n->pending_ping);
1215 GNUNET_free_non_null (n->pending_pong);
1221 * Check if we have encrypted messages for the specified neighbour
1222 * pending, and if so, check with the transport about sending them
1225 * @param n neighbour to check.
1227 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1231 * Encrypt size bytes from in and write the result to out. Use the
1232 * key for outbound traffic of the given neighbour.
1234 * @param n neighbour we are sending to
1235 * @param iv initialization vector to use
1236 * @param in ciphertext
1237 * @param out plaintext
1238 * @param size size of in/out
1239 * @return GNUNET_OK on success
1242 do_encrypt (struct Neighbour *n,
1243 const GNUNET_HashCode * iv,
1244 const void *in, void *out, size_t size)
1246 if (size != (uint16_t) size)
1251 GNUNET_assert (size ==
1252 GNUNET_CRYPTO_aes_encrypt (in,
1256 GNUNET_CRYPTO_AesInitializationVector
1258 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1260 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1261 "Encrypted %u bytes for `%4s' using key %u\n",
1262 (unsigned int) size,
1263 GNUNET_i2s (&n->peer),
1264 (unsigned int) n->encrypt_key.crc32);
1271 * Consider freeing the given neighbour since we may not need
1272 * to keep it around anymore.
1274 * @param n neighbour to consider discarding
1277 consider_free_neighbour (struct Neighbour *n);
1281 * Task triggered when a neighbour entry is about to time out
1282 * (and we should prevent this by sending a PING).
1284 * @param cls the 'struct Neighbour'
1285 * @param tc scheduler context (not used)
1288 send_keep_alive (void *cls,
1289 const struct GNUNET_SCHEDULER_TaskContext *tc)
1291 struct Neighbour *n = cls;
1292 struct GNUNET_TIME_Relative retry;
1293 struct GNUNET_TIME_Relative left;
1294 struct MessageEntry *me;
1295 struct PingMessage pp;
1296 struct PingMessage *pm;
1298 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1300 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1301 sizeof (struct PingMessage));
1302 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1303 me->priority = PING_PRIORITY;
1304 me->size = sizeof (struct PingMessage);
1305 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1309 pm = (struct PingMessage *) &me[1];
1310 pm->header.size = htons (sizeof (struct PingMessage));
1311 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1312 pp.challenge = htonl (n->ping_challenge);
1313 pp.target = n->peer;
1315 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1316 "Encrypting `%s' message with challenge %u for `%4s' using key %u.\n",
1318 (unsigned int) n->ping_challenge,
1319 GNUNET_i2s (&n->peer),
1320 (unsigned int) n->encrypt_key.crc32);
1323 &n->peer.hashPubKey,
1326 sizeof (struct PingMessage) -
1327 sizeof (struct GNUNET_MessageHeader));
1328 process_encrypted_neighbour_queue (n);
1329 /* reschedule PING job */
1330 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1331 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1332 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1333 MIN_PING_FREQUENCY);
1335 = GNUNET_SCHEDULER_add_delayed (sched,
1344 * Task triggered when a neighbour entry might have gotten stale.
1346 * @param cls the 'struct Neighbour'
1347 * @param tc scheduler context (not used)
1350 consider_free_task (void *cls,
1351 const struct GNUNET_SCHEDULER_TaskContext *tc)
1353 struct Neighbour *n = cls;
1355 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1356 consider_free_neighbour (n);
1361 * Consider freeing the given neighbour since we may not need
1362 * to keep it around anymore.
1364 * @param n neighbour to consider discarding
1367 consider_free_neighbour (struct Neighbour *n)
1369 struct Neighbour *pos;
1370 struct Neighbour *prev;
1371 struct GNUNET_TIME_Relative left;
1373 if ( (n->th != NULL) ||
1374 (n->pitr != NULL) ||
1375 (GNUNET_YES == n->is_connected) )
1376 return; /* no chance */
1378 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1379 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1382 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1383 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1384 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1386 &consider_free_task,
1390 /* actually free the neighbour... */
1399 neighbours = n->next;
1401 prev->next = n->next;
1402 GNUNET_assert (neighbour_count > 0);
1404 GNUNET_STATISTICS_set (stats,
1405 gettext_noop ("# neighbour entries allocated"),
1413 * Function called when the transport service is ready to
1414 * receive an encrypted message for the respective peer
1416 * @param cls neighbour to use message from
1417 * @param size number of bytes we can transmit
1418 * @param buf where to copy the message
1419 * @return number of bytes transmitted
1422 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1424 struct Neighbour *n = cls;
1425 struct MessageEntry *m;
1430 m = n->encrypted_head;
1434 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1435 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1436 GNUNET_i2s (&n->peer));
1440 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1447 GNUNET_assert (size >= m->size);
1448 memcpy (cbuf, &m[1], m->size);
1450 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1453 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1454 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1455 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1457 GNUNET_i2s (&n->peer));
1459 process_encrypted_neighbour_queue (n);
1464 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1465 "Transmission of message of type %u and size %u failed\n",
1466 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1467 (unsigned int) m->size);
1471 consider_free_neighbour (n);
1477 * Check if we have plaintext messages for the specified neighbour
1478 * pending, and if so, consider batching and encrypting them (and
1479 * then trigger processing of the encrypted queue if needed).
1481 * @param n neighbour to check.
1483 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1487 * Check if we have encrypted messages for the specified neighbour
1488 * pending, and if so, check with the transport about sending them
1491 * @param n neighbour to check.
1494 process_encrypted_neighbour_queue (struct Neighbour *n)
1496 struct MessageEntry *m;
1499 return; /* request already pending */
1500 m = n->encrypted_head;
1503 /* encrypted queue empty, try plaintext instead */
1504 process_plaintext_neighbour_queue (n);
1508 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1509 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1510 (unsigned int) m->size,
1511 GNUNET_i2s (&n->peer),
1512 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).
1516 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1519 GNUNET_TIME_absolute_get_remaining
1521 ¬ify_encrypted_transmit_ready,
1525 /* message request too large or duplicate request */
1527 /* discard encrypted message */
1528 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1532 process_encrypted_neighbour_queue (n);
1538 * Decrypt size bytes from in and write the result to out. Use the
1539 * key for inbound traffic of the given neighbour. This function does
1540 * NOT do any integrity-checks on the result.
1542 * @param n neighbour we are receiving from
1543 * @param iv initialization vector to use
1544 * @param in ciphertext
1545 * @param out plaintext
1546 * @param size size of in/out
1547 * @return GNUNET_OK on success
1550 do_decrypt (struct Neighbour *n,
1551 const GNUNET_HashCode * iv,
1552 const void *in, void *out, size_t size)
1554 if (size != (uint16_t) size)
1559 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1560 (n->status != PEER_STATE_KEY_CONFIRMED))
1562 GNUNET_break_op (0);
1563 return GNUNET_SYSERR;
1566 GNUNET_CRYPTO_aes_decrypt (in,
1570 GNUNET_CRYPTO_AesInitializationVector *) iv,
1574 return GNUNET_SYSERR;
1576 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1578 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1579 "Decrypted %u bytes from `%4s' using key %u\n",
1580 (unsigned int) size,
1581 GNUNET_i2s (&n->peer),
1582 (unsigned int) n->decrypt_key.crc32);
1589 * Select messages for transmission. This heuristic uses a combination
1590 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1591 * and priority-based discard (in case no feasible schedule exist) and
1592 * speculative optimization (defer any kind of transmission until
1593 * we either create a batch of significant size, 25% of max, or until
1594 * we are close to a deadline). Furthermore, when scheduling the
1595 * heuristic also packs as many messages into the batch as possible,
1596 * starting with those with the earliest deadline. Yes, this is fun.
1598 * @param n neighbour to select messages from
1599 * @param size number of bytes to select for transmission
1600 * @param retry_time set to the time when we should try again
1601 * (only valid if this function returns zero)
1602 * @return number of bytes selected, or 0 if we decided to
1603 * defer scheduling overall; in that case, retry_time is set.
1606 select_messages (struct Neighbour *n,
1607 size_t size, struct GNUNET_TIME_Relative *retry_time)
1609 struct MessageEntry *pos;
1610 struct MessageEntry *min;
1611 struct MessageEntry *last;
1612 unsigned int min_prio;
1613 struct GNUNET_TIME_Absolute t;
1614 struct GNUNET_TIME_Absolute now;
1615 struct GNUNET_TIME_Relative delta;
1617 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1620 unsigned int queue_size;
1621 int discard_low_prio;
1623 GNUNET_assert (NULL != n->messages);
1624 now = GNUNET_TIME_absolute_get ();
1625 /* last entry in linked list of messages processed */
1627 /* should we remove the entry with the lowest
1628 priority from consideration for scheduling at the
1639 discard_low_prio = GNUNET_YES;
1640 while (GNUNET_YES == discard_low_prio)
1643 min_prio = UINT_MAX;
1644 discard_low_prio = GNUNET_NO;
1645 /* calculate number of bytes available for transmission at time "t" */
1646 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1648 /* how many bytes have we (hypothetically) scheduled so far */
1650 /* maximum time we can wait before transmitting anything
1651 and still make all of our deadlines */
1652 slack = GNUNET_TIME_UNIT_FOREVER_REL;
1654 /* note that we use "*2" here because we want to look
1655 a bit further into the future; much more makes no
1656 sense since new message might be scheduled in the
1658 while ((pos != NULL) && (off < size * 2))
1660 if (pos->do_transmit == GNUNET_YES)
1662 /* already removed from consideration */
1666 if (discard_low_prio == GNUNET_NO)
1668 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1669 if (delta.value > 0)
1671 // FIXME: HUH? Check!
1673 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1676 if (avail < pos->size)
1678 // FIXME: HUH? Check!
1679 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1684 /* update slack, considering both its absolute deadline
1685 and relative deadlines caused by other messages
1686 with their respective load */
1687 slack = GNUNET_TIME_relative_min (slack,
1688 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1690 if (pos->deadline.value <= now.value)
1693 slack = GNUNET_TIME_UNIT_ZERO;
1695 else if (GNUNET_YES == pos->got_slack)
1697 /* should be soon now! */
1698 slack = GNUNET_TIME_relative_min (slack,
1699 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1704 GNUNET_TIME_relative_min (slack,
1705 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1706 pos->got_slack = GNUNET_YES;
1707 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1708 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
1713 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1714 if (pos->priority <= min_prio)
1716 /* update min for discard */
1717 min_prio = pos->priority;
1722 if (discard_low_prio)
1724 GNUNET_assert (min != NULL);
1725 /* remove lowest-priority entry from consideration */
1726 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1730 /* guard against sending "tiny" messages with large headers without
1732 if ( (slack.value > GNUNET_CONSTANTS_MAX_CORK_DELAY.value) &&
1734 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1736 /* less than 25% of message would be filled with deadlines still
1737 being met if we delay by one second or more; so just wait for
1738 more data; but do not wait longer than 1s (since we don't want
1739 to delay messages for a really long time either). */
1740 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1741 /* reset do_transmit values for next time */
1744 pos->do_transmit = GNUNET_NO;
1748 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1749 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1750 (unsigned long long) retry_time->value,
1752 (unsigned int) size);
1756 /* select marked messages (up to size) for transmission */
1761 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1763 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1767 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1768 "Selecting message of size %u for transmission\n",
1769 (unsigned int) pos->size);
1775 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1776 "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
1777 (unsigned int) pos->size,
1780 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1785 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1786 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1787 (unsigned long long) off, (unsigned long long) tsize,
1788 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
1789 GNUNET_i2s (&n->peer));
1796 * Batch multiple messages into a larger buffer.
1798 * @param n neighbour to take messages from
1799 * @param buf target buffer
1800 * @param size size of buf
1801 * @param deadline set to transmission deadline for the result
1802 * @param retry_time set to the time when we should try again
1803 * (only valid if this function returns zero)
1804 * @param priority set to the priority of the batch
1805 * @return number of bytes written to buf (can be zero)
1808 batch_message (struct Neighbour *n,
1811 struct GNUNET_TIME_Absolute *deadline,
1812 struct GNUNET_TIME_Relative *retry_time,
1813 unsigned int *priority)
1815 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1816 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1817 struct MessageEntry *pos;
1818 struct MessageEntry *prev;
1819 struct MessageEntry *next;
1824 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1825 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1826 if (0 == select_messages (n, size, retry_time))
1829 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1830 "No messages selected, will try again in %llu ms\n",
1835 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1836 ntm->distance = htonl (n->last_distance);
1837 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1838 ntm->peer = n->peer;
1841 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1844 if (GNUNET_YES == pos->do_transmit)
1846 GNUNET_assert (pos->size <= size);
1847 /* do notifications */
1848 /* FIXME: track if we have *any* client that wants
1849 full notifications and only do this if that is
1851 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1853 memcpy (&ntm[1], &pos[1], pos->size);
1854 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1855 sizeof (struct GNUNET_MessageHeader));
1856 send_to_all_clients (&ntm->header,
1858 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1862 /* message too large for 'full' notifications, we do at
1863 least the 'hdr' type */
1866 sizeof (struct GNUNET_MessageHeader));
1868 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1870 send_to_all_clients (&ntm->header,
1872 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1874 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1875 "Encrypting %u bytes with message of type %u and size %u\n",
1877 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
1878 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
1880 /* copy for encrypted transmission */
1881 memcpy (&buf[ret], &pos[1], pos->size);
1884 *priority += pos->priority;
1886 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1887 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1888 (unsigned int) pos->size,
1889 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1891 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1905 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1906 "Deadline for message batch is %llu ms\n",
1907 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1914 * Remove messages with deadlines that have long expired from
1917 * @param n neighbour to inspect
1920 discard_expired_messages (struct Neighbour *n)
1922 struct MessageEntry *prev;
1923 struct MessageEntry *next;
1924 struct MessageEntry *pos;
1925 struct GNUNET_TIME_Absolute now;
1926 struct GNUNET_TIME_Relative delta;
1928 now = GNUNET_TIME_absolute_get ();
1934 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1935 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1938 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1939 "Message is %llu ms past due, discarding.\n",
1956 * Signature of the main function of a task.
1958 * @param cls closure
1959 * @param tc context information (why was this task triggered now)
1962 retry_plaintext_processing (void *cls,
1963 const struct GNUNET_SCHEDULER_TaskContext *tc)
1965 struct Neighbour *n = cls;
1967 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1968 process_plaintext_neighbour_queue (n);
1973 * Send our key (and encrypted PING) to the other peer.
1975 * @param n the other peer
1977 static void send_key (struct Neighbour *n);
1980 * Task that will retry "send_key" if our previous attempt failed
1984 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1986 struct Neighbour *n = cls;
1989 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1990 "Retrying key transmission to `%4s'\n",
1991 GNUNET_i2s (&n->peer));
1993 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1994 n->set_key_retry_frequency =
1995 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2001 * Check if we have plaintext messages for the specified neighbour
2002 * pending, and if so, consider batching and encrypting them (and
2003 * then trigger processing of the encrypted queue if needed).
2005 * @param n neighbour to check.
2008 process_plaintext_neighbour_queue (struct Neighbour *n)
2010 char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)]; /* plaintext */
2013 struct EncryptedMessage *em; /* encrypted message */
2014 struct EncryptedMessage *ph; /* plaintext header */
2015 struct MessageEntry *me;
2016 unsigned int priority;
2017 struct GNUNET_TIME_Absolute deadline;
2018 struct GNUNET_TIME_Relative retry_time;
2021 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2023 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
2024 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2028 case PEER_STATE_DOWN:
2031 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2032 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2033 GNUNET_i2s(&n->peer));
2036 case PEER_STATE_KEY_SENT:
2037 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2038 n->retry_set_key_task
2039 = GNUNET_SCHEDULER_add_delayed (sched,
2040 n->set_key_retry_frequency,
2041 &set_key_retry_task, n);
2043 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2044 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2045 GNUNET_i2s(&n->peer));
2048 case PEER_STATE_KEY_RECEIVED:
2049 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2050 n->retry_set_key_task
2051 = GNUNET_SCHEDULER_add_delayed (sched,
2052 n->set_key_retry_frequency,
2053 &set_key_retry_task, n);
2055 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2056 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2057 GNUNET_i2s(&n->peer));
2060 case PEER_STATE_KEY_CONFIRMED:
2061 /* ready to continue */
2064 discard_expired_messages (n);
2065 if (n->messages == NULL)
2068 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2069 "Plaintext message queue for `%4s' is empty.\n",
2070 GNUNET_i2s(&n->peer));
2072 return; /* no pending messages */
2074 if (n->encrypted_head != NULL)
2077 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2078 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2079 GNUNET_i2s(&n->peer));
2081 return; /* wait for messages already encrypted to be
2084 ph = (struct EncryptedMessage *) pbuf;
2085 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2087 used = sizeof (struct EncryptedMessage);
2088 used += batch_message (n,
2090 GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2091 &deadline, &retry_time, &priority);
2092 if (used == sizeof (struct EncryptedMessage))
2095 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2096 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2097 GNUNET_i2s(&n->peer));
2099 /* no messages selected for sending, try again later... */
2100 n->retry_plaintext_task =
2101 GNUNET_SCHEDULER_add_delayed (sched,
2103 &retry_plaintext_processing, n);
2106 #if DEBUG_CORE_QUOTA
2107 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2108 "Sending %u b/s as new limit to peer `%4s'\n",
2109 (unsigned int) ntohl (n->bw_in.value__),
2110 GNUNET_i2s (&n->peer));
2112 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX));
2113 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2114 ph->inbound_bw_limit = n->bw_in;
2115 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2117 /* setup encryption message header */
2118 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2119 me->deadline = deadline;
2120 me->priority = priority;
2122 em = (struct EncryptedMessage *) &me[1];
2123 em->header.size = htons (used);
2124 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2125 em->iv_seed = ph->iv_seed;
2126 esize = used - ENCRYPTED_HEADER_SIZE;
2127 GNUNET_CRYPTO_hmac (&n->encrypt_key,
2128 &ph->sequence_number,
2129 esize - sizeof (GNUNET_HashCode),
2131 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
2133 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2134 "Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
2135 (unsigned int) (esize - sizeof (GNUNET_HashCode)),
2136 GNUNET_h2s (&ph->hmac),
2141 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2142 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2143 (unsigned int) esize,
2144 GNUNET_i2s(&n->peer),
2145 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2147 GNUNET_assert (GNUNET_OK ==
2152 /* append to transmission list */
2153 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2157 process_encrypted_neighbour_queue (n);
2162 * Function that recalculates the bandwidth quota for the
2163 * given neighbour and transmits it to the transport service.
2165 * @param cls neighbour for the quota update
2169 neighbour_quota_update (void *cls,
2170 const struct GNUNET_SCHEDULER_TaskContext *tc);
2174 * Schedule the task that will recalculate the bandwidth
2175 * quota for this peer (and possibly force a disconnect of
2176 * idle peers by calculating a bandwidth of zero).
2179 schedule_quota_update (struct Neighbour *n)
2181 GNUNET_assert (n->quota_update_task ==
2182 GNUNET_SCHEDULER_NO_TASK);
2183 n->quota_update_task
2184 = GNUNET_SCHEDULER_add_delayed (sched,
2185 QUOTA_UPDATE_FREQUENCY,
2186 &neighbour_quota_update,
2192 * Initialize a new 'struct Neighbour'.
2194 * @param pid ID of the new neighbour
2195 * @return handle for the new neighbour
2197 static struct Neighbour *
2198 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2200 struct Neighbour *n;
2201 struct GNUNET_TIME_Absolute now;
2204 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2205 "Creating neighbour entry for peer `%4s'\n",
2208 n = GNUNET_malloc (sizeof (struct Neighbour));
2209 n->next = neighbours;
2212 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2214 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2215 now = GNUNET_TIME_absolute_get ();
2216 n->encrypt_key_created = now;
2217 n->last_activity = now;
2218 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2219 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2220 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2221 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2222 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2223 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2225 neighbour_quota_update (n, NULL);
2226 consider_free_neighbour (n);
2232 * Handle CORE_SEND request.
2235 * @param client the client issuing the request
2236 * @param message the "struct SendMessage"
2239 handle_client_send (void *cls,
2240 struct GNUNET_SERVER_Client *client,
2241 const struct GNUNET_MessageHeader *message)
2243 const struct SendMessage *sm;
2244 struct Neighbour *n;
2245 struct MessageEntry *prev;
2246 struct MessageEntry *pos;
2247 struct MessageEntry *e;
2248 struct MessageEntry *min_prio_entry;
2249 struct MessageEntry *min_prio_prev;
2250 unsigned int min_prio;
2251 unsigned int queue_size;
2254 msize = ntohs (message->size);
2256 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2258 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "about to assert fail, msize is %d, should be at least %d\n", msize, sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader));
2261 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2264 sm = (const struct SendMessage *) message;
2265 msize -= sizeof (struct SendMessage);
2266 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2268 /* FIXME: should we not allow loopback-injection here? */
2271 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2274 n = find_neighbour (&sm->peer);
2276 n = create_neighbour (&sm->peer);
2278 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2279 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2281 (unsigned int) msize,
2282 GNUNET_i2s (&sm->peer));
2284 /* bound queue size */
2285 discard_expired_messages (n);
2286 min_prio = UINT32_MAX;
2287 min_prio_entry = NULL;
2288 min_prio_prev = NULL;
2294 if (pos->priority <= min_prio)
2296 min_prio_entry = pos;
2297 min_prio_prev = prev;
2298 min_prio = pos->priority;
2304 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2307 if (ntohl(sm->priority) <= min_prio)
2309 /* discard new entry */
2311 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2312 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2314 (unsigned int) MAX_PEER_QUEUE_SIZE,
2315 (unsigned int) msize,
2316 (unsigned int) ntohs (message->type));
2319 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2322 GNUNET_assert (min_prio_entry != NULL);
2323 /* discard "min_prio_entry" */
2325 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2326 "Queue full, discarding existing older request\n");
2328 if (min_prio_prev == NULL)
2329 n->messages = min_prio_entry->next;
2331 min_prio_prev->next = min_prio_entry->next;
2332 GNUNET_free (min_prio_entry);
2336 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2337 "Adding transmission request for `%4s' of size %u to queue\n",
2338 GNUNET_i2s (&sm->peer),
2339 (unsigned int) msize);
2341 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2342 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2343 e->priority = ntohl (sm->priority);
2345 memcpy (&e[1], &sm[1], msize);
2347 /* insert, keep list sorted by deadline */
2350 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2361 /* consider scheduling now */
2362 process_plaintext_neighbour_queue (n);
2364 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2369 * Function called when the transport service is ready to
2370 * receive a message. Only resets 'n->th' to NULL.
2372 * @param cls neighbour to use message from
2373 * @param size number of bytes we can transmit
2374 * @param buf where to copy the message
2375 * @return number of bytes transmitted
2378 notify_transport_connect_done (void *cls, size_t size, void *buf)
2380 struct Neighbour *n = cls;
2382 if (GNUNET_YES != n->is_connected)
2384 /* transport should only call us to transmit a message after
2385 * telling us about a successful connection to the respective peer */
2386 n->th = NULL; /* If this happens because of a timeout, reset n-th so another message may be sent for this peer! */
2388 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Timeout on notify connect!\n");
2395 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2396 _("Failed to connect to `%4s': transport failed to connect\n"),
2397 GNUNET_i2s (&n->peer));
2400 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2401 _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2402 GNUNET_i2s (&n->peer));
2403 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2404 GNUNET_SCHEDULER_cancel (sched,
2405 n->retry_set_key_task);
2406 n->retry_set_key_task = GNUNET_SCHEDULER_add_now (sched,
2407 &set_key_retry_task,
2414 * Handle CORE_REQUEST_CONNECT request.
2417 * @param client the client issuing the request
2418 * @param message the "struct ConnectMessage"
2421 handle_client_request_connect (void *cls,
2422 struct GNUNET_SERVER_Client *client,
2423 const struct GNUNET_MessageHeader *message)
2425 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2426 struct Neighbour *n;
2427 struct GNUNET_TIME_Relative timeout;
2429 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2432 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2435 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2436 n = find_neighbour (&cm->peer);
2438 n = create_neighbour (&cm->peer);
2439 if ( (GNUNET_YES == n->is_connected) ||
2442 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2443 "Core received `%s' request for `%4s', already connected!\n",
2445 GNUNET_i2s (&cm->peer));
2446 return; /* already connected, or at least trying */
2448 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2450 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2451 "Core received `%s' request for `%4s', will try to establish connection\n",
2453 GNUNET_i2s (&cm->peer));
2455 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2456 /* ask transport to connect to the peer */
2457 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2459 sizeof (struct GNUNET_MessageHeader), 0,
2461 ¬ify_transport_connect_done,
2463 GNUNET_break (NULL != n->th);
2468 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2469 * the neighbour's struct and retry send_key. Or, if we did not get a
2470 * HELLO, just do nothing.
2472 * @param cls the 'struct Neighbour' to retry sending the key for
2473 * @param peer the peer for which this is the HELLO
2474 * @param hello HELLO message of that peer
2477 process_hello_retry_send_key (void *cls,
2478 const struct GNUNET_PeerIdentity *peer,
2479 const struct GNUNET_HELLO_Message *hello)
2481 struct Neighbour *n = cls;
2486 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2487 "Entered `%s' and `%s' is NULL!\n",
2488 "process_hello_retry_send_key",
2492 if (n->public_key != NULL)
2494 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2496 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2497 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2499 GNUNET_STATISTICS_update (stats,
2500 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2508 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2509 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
2510 GNUNET_i2s (&n->peer));
2512 GNUNET_STATISTICS_update (stats,
2513 gettext_noop ("# Delayed connecting due to lack of public key"),
2516 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2517 n->retry_set_key_task
2518 = GNUNET_SCHEDULER_add_delayed (sched,
2519 n->set_key_retry_frequency,
2520 &set_key_retry_task, n);
2526 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2527 "Entered `%s' for peer `%4s'\n",
2528 "process_hello_retry_send_key",
2531 if (n->public_key != NULL)
2533 /* already have public key, why are we here? */
2539 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2540 "Received new `%s' message for `%4s', initiating key exchange.\n",
2545 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2546 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2548 GNUNET_STATISTICS_update (stats,
2549 gettext_noop ("# Error extracting public key from HELLO"),
2552 GNUNET_free (n->public_key);
2553 n->public_key = NULL;
2555 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2556 "GNUNET_HELLO_get_key returned awfully\n");
2564 * Send our key (and encrypted PING) to the other peer.
2566 * @param n the other peer
2569 send_key (struct Neighbour *n)
2571 struct MessageEntry *pos;
2572 struct SetKeyMessage *sm;
2573 struct MessageEntry *me;
2574 struct PingMessage pp;
2575 struct PingMessage *pm;
2577 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2579 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2580 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2582 if (n->pitr != NULL)
2585 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2586 "Key exchange in progress with `%4s'.\n",
2587 GNUNET_i2s (&n->peer));
2589 return; /* already in progress */
2591 if (GNUNET_YES != n->is_connected)
2594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2595 "Not yet connected to peer `%4s'!\n",
2596 GNUNET_i2s (&n->peer));
2600 GNUNET_STATISTICS_update (stats,
2601 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
2604 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2606 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2608 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2609 ¬ify_encrypted_transmit_ready,
2615 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2616 "Asked to perform key exchange with `%4s'.\n",
2617 GNUNET_i2s (&n->peer));
2619 if (n->public_key == NULL)
2621 /* lookup n's public key, then try again */
2623 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2624 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2625 GNUNET_i2s (&n->peer));
2627 GNUNET_assert (n->pitr == NULL);
2628 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2630 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2631 &process_hello_retry_send_key, n);
2634 pos = n->encrypted_head;
2637 if (GNUNET_YES == pos->is_setkey)
2639 if (pos->sender_status == n->status)
2642 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2643 "`%s' message for `%4s' queued already\n",
2645 GNUNET_i2s (&n->peer));
2647 goto trigger_processing;
2649 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2654 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2655 "Removing queued `%s' message for `%4s', will create a new one\n",
2657 GNUNET_i2s (&n->peer));
2667 case PEER_STATE_DOWN:
2668 n->status = PEER_STATE_KEY_SENT;
2670 case PEER_STATE_KEY_SENT:
2672 case PEER_STATE_KEY_RECEIVED:
2674 case PEER_STATE_KEY_CONFIRMED:
2682 /* first, set key message */
2683 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2684 sizeof (struct SetKeyMessage) +
2685 sizeof (struct PingMessage));
2686 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2687 me->priority = SET_KEY_PRIORITY;
2688 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
2689 me->is_setkey = GNUNET_YES;
2690 me->got_slack = GNUNET_YES; /* do not defer this one! */
2691 me->sender_status = n->status;
2692 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2696 sm = (struct SetKeyMessage *) &me[1];
2697 sm->header.size = htons (sizeof (struct SetKeyMessage));
2698 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2699 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2700 PEER_STATE_KEY_SENT : n->status));
2702 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2703 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2704 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2705 sizeof (struct GNUNET_PeerIdentity));
2706 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2707 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2708 sm->target = n->peer;
2709 GNUNET_assert (GNUNET_OK ==
2710 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2712 GNUNET_CRYPTO_AesSessionKey),
2714 &sm->encrypted_key));
2715 GNUNET_assert (GNUNET_OK ==
2716 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2718 pm = (struct PingMessage *) &sm[1];
2719 pm->header.size = htons (sizeof (struct PingMessage));
2720 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2721 pp.challenge = htonl (n->ping_challenge);
2722 pp.target = n->peer;
2724 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2725 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u.\n",
2727 (unsigned int) n->ping_challenge,
2728 GNUNET_i2s (&n->peer),
2729 (unsigned int) n->encrypt_key.crc32);
2732 &n->peer.hashPubKey,
2735 sizeof (struct PingMessage) -
2736 sizeof (struct GNUNET_MessageHeader));
2737 GNUNET_STATISTICS_update (stats,
2738 gettext_noop ("# SET_KEY and PING messages created"),
2742 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2743 "Have %llu ms left for `%s' transmission.\n",
2744 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2748 /* trigger queue processing */
2749 process_encrypted_neighbour_queue (n);
2750 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2751 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2752 n->retry_set_key_task
2753 = GNUNET_SCHEDULER_add_delayed (sched,
2754 n->set_key_retry_frequency,
2755 &set_key_retry_task, n);
2760 * We received a SET_KEY message. Validate and update
2761 * our key material and status.
2763 * @param n the neighbour from which we received message m
2764 * @param m the set key message we received
2767 handle_set_key (struct Neighbour *n,
2768 const struct SetKeyMessage *m);
2772 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2773 * the neighbour's struct and retry handling the set_key message. Or,
2774 * if we did not get a HELLO, just free the set key message.
2776 * @param cls pointer to the set key message
2777 * @param peer the peer for which this is the HELLO
2778 * @param hello HELLO message of that peer
2781 process_hello_retry_handle_set_key (void *cls,
2782 const struct GNUNET_PeerIdentity *peer,
2783 const struct GNUNET_HELLO_Message *hello)
2785 struct Neighbour *n = cls;
2786 struct SetKeyMessage *sm = n->skm;
2792 if (n->public_key != NULL)
2795 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2796 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2798 GNUNET_i2s (&n->peer),
2801 handle_set_key (n, sm);
2805 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2806 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
2808 GNUNET_i2s (&n->peer));
2813 if (n->public_key != NULL)
2814 return; /* multiple HELLOs match!? */
2816 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2817 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2819 GNUNET_break_op (0);
2820 GNUNET_free (n->public_key);
2821 n->public_key = NULL;
2827 * We received a PING message. Validate and transmit
2830 * @param n sender of the PING
2831 * @param m the encrypted PING message itself
2834 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2836 struct PingMessage t;
2837 struct PongMessage tx;
2838 struct PongMessage *tp;
2839 struct MessageEntry *me;
2842 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2843 "Core service receives `%s' request from `%4s'.\n",
2844 "PING", GNUNET_i2s (&n->peer));
2848 &my_identity.hashPubKey,
2851 sizeof (struct PingMessage) -
2852 sizeof (struct GNUNET_MessageHeader)))
2855 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2856 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2858 GNUNET_i2s (&t.target),
2859 (unsigned int) ntohl (t.challenge),
2860 (unsigned int) n->decrypt_key.crc32);
2862 GNUNET_STATISTICS_update (stats,
2863 gettext_noop ("# PING messages decrypted"),
2866 if (0 != memcmp (&t.target,
2867 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2869 GNUNET_break_op (0);
2872 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2873 sizeof (struct PongMessage));
2874 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2878 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2879 me->priority = PONG_PRIORITY;
2880 me->size = sizeof (struct PongMessage);
2881 tx.reserved = htonl (0);
2882 tx.inbound_bw_limit = n->bw_in;
2883 tx.challenge = t.challenge;
2884 tx.target = t.target;
2885 tp = (struct PongMessage *) &me[1];
2886 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2887 tp->header.size = htons (sizeof (struct PongMessage));
2889 &my_identity.hashPubKey,
2892 sizeof (struct PongMessage) -
2893 sizeof (struct GNUNET_MessageHeader));
2894 GNUNET_STATISTICS_update (stats,
2895 gettext_noop ("# PONG messages created"),
2899 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2900 "Encrypting `%s' with challenge %u using key %u\n",
2902 (unsigned int) ntohl (t.challenge),
2903 (unsigned int) n->encrypt_key.crc32);
2905 /* trigger queue processing */
2906 process_encrypted_neighbour_queue (n);
2911 * We received a PONG message. Validate and update our status.
2913 * @param n sender of the PONG
2914 * @param m the encrypted PONG message itself
2917 handle_pong (struct Neighbour *n,
2918 const struct PongMessage *m)
2920 struct PongMessage t;
2921 struct ConnectNotifyMessage cnm;
2924 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2925 "Core service receives `%s' response from `%4s'.\n",
2926 "PONG", GNUNET_i2s (&n->peer));
2928 /* mark as garbage, just to be sure */
2929 memset (&t, 255, sizeof (t));
2932 &n->peer.hashPubKey,
2935 sizeof (struct PongMessage) -
2936 sizeof (struct GNUNET_MessageHeader)))
2938 GNUNET_break_op (0);
2941 GNUNET_STATISTICS_update (stats,
2942 gettext_noop ("# PONG messages decrypted"),
2945 if (0 != ntohl (t.reserved))
2947 GNUNET_break_op (0);
2951 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2952 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2954 GNUNET_i2s (&t.target),
2955 (unsigned int) ntohl (t.challenge),
2956 (unsigned int) n->decrypt_key.crc32);
2958 if ((0 != memcmp (&t.target,
2960 sizeof (struct GNUNET_PeerIdentity))) ||
2961 (n->ping_challenge != ntohl (t.challenge)))
2963 /* PONG malformed */
2965 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2966 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2968 GNUNET_i2s (&n->peer),
2969 (unsigned int) n->ping_challenge);
2970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2971 "Received malformed `%s' received from `%4s' with challenge %u\n",
2972 "PONG", GNUNET_i2s (&t.target),
2973 (unsigned int) ntohl (t.challenge));
2975 GNUNET_break_op (0);
2980 case PEER_STATE_DOWN:
2981 GNUNET_break (0); /* should be impossible */
2983 case PEER_STATE_KEY_SENT:
2984 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2986 case PEER_STATE_KEY_RECEIVED:
2987 GNUNET_STATISTICS_update (stats,
2988 gettext_noop ("# Session keys confirmed via PONG"),
2991 n->status = PEER_STATE_KEY_CONFIRMED;
2992 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2994 n->bw_out_external_limit = t.inbound_bw_limit;
2995 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2996 n->bw_out_internal_limit);
2997 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2999 GNUNET_TRANSPORT_set_quota (transport,
3003 GNUNET_TIME_UNIT_FOREVER_REL,
3007 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3008 "Confirmed key via `%s' message for peer `%4s'\n",
3009 "PONG", GNUNET_i2s (&n->peer));
3011 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3013 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
3014 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3016 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3017 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3018 cnm.distance = htonl (n->last_distance);
3019 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3021 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
3022 process_encrypted_neighbour_queue (n);
3024 case PEER_STATE_KEY_CONFIRMED:
3025 n->last_activity = GNUNET_TIME_absolute_get ();
3026 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3027 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3029 = GNUNET_SCHEDULER_add_delayed (sched,
3030 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3033 handle_peer_status_change (n);
3043 * We received a SET_KEY message. Validate and update
3044 * our key material and status.
3046 * @param n the neighbour from which we received message m
3047 * @param m the set key message we received
3050 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
3052 struct SetKeyMessage *m_cpy;
3053 struct GNUNET_TIME_Absolute t;
3054 struct GNUNET_CRYPTO_AesSessionKey k;
3055 struct PingMessage *ping;
3056 struct PongMessage *pong;
3057 enum PeerStateMachine sender_status;
3060 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3061 "Core service receives `%s' request from `%4s'.\n",
3062 "SET_KEY", GNUNET_i2s (&n->peer));
3064 if (n->public_key == NULL)
3066 if (n->pitr != NULL)
3069 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3070 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3076 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3077 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3079 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3080 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3081 /* lookup n's public key, then try again */
3082 GNUNET_assert (n->skm == NULL);
3084 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3086 GNUNET_TIME_UNIT_MINUTES,
3087 &process_hello_retry_handle_set_key, n);
3088 GNUNET_STATISTICS_update (stats,
3089 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3094 if (0 != memcmp (&m->target,
3096 sizeof (struct GNUNET_PeerIdentity)))
3098 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3099 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3101 GNUNET_i2s (&m->target));
3104 if ((ntohl (m->purpose.size) !=
3105 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3106 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3107 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3108 sizeof (struct GNUNET_PeerIdentity)) ||
3110 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3111 &m->purpose, &m->signature, n->public_key)))
3113 /* invalid signature */
3114 GNUNET_break_op (0);
3117 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3118 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3119 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3120 (t.value < n->decrypt_key_created.value))
3122 /* this could rarely happen due to massive re-ordering of
3123 messages on the network level, but is most likely either
3124 a bug or some adversary messing with us. Report. */
3125 GNUNET_break_op (0);
3129 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3130 "Decrypting key material.\n");
3132 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3135 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3136 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3137 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3139 /* failed to decrypt !? */
3140 GNUNET_break_op (0);
3143 GNUNET_STATISTICS_update (stats,
3144 gettext_noop ("# SET_KEY messages decrypted"),
3148 if (n->decrypt_key_created.value != t.value)
3150 /* fresh key, reset sequence numbers */
3151 n->last_sequence_number_received = 0;
3152 n->last_packets_bitmap = 0;
3153 n->decrypt_key_created = t;
3155 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3158 case PEER_STATE_DOWN:
3159 n->status = PEER_STATE_KEY_RECEIVED;
3161 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3162 "Responding to `%s' with my own key.\n", "SET_KEY");
3166 case PEER_STATE_KEY_SENT:
3167 case PEER_STATE_KEY_RECEIVED:
3168 n->status = PEER_STATE_KEY_RECEIVED;
3169 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3170 (sender_status != PEER_STATE_KEY_CONFIRMED))
3173 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3174 "Responding to `%s' with my own key (other peer has status %u).\n",
3176 (unsigned int) sender_status);
3181 case PEER_STATE_KEY_CONFIRMED:
3182 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3183 (sender_status != PEER_STATE_KEY_CONFIRMED))
3186 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3187 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3189 (unsigned int) sender_status);
3198 if (n->pending_ping != NULL)
3200 ping = n->pending_ping;
3201 n->pending_ping = NULL;
3202 handle_ping (n, ping);
3205 if (n->pending_pong != NULL)
3207 pong = n->pending_pong;
3208 n->pending_pong = NULL;
3209 handle_pong (n, pong);
3216 * Send a P2P message to a client.
3218 * @param sender who sent us the message?
3219 * @param client who should we give the message to?
3220 * @param m contains the message to transmit
3221 * @param msize number of bytes in buf to transmit
3224 send_p2p_message_to_client (struct Neighbour *sender,
3225 struct Client *client,
3226 const void *m, size_t msize)
3228 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3229 struct NotifyTrafficMessage *ntm;
3232 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3233 "Core service passes message from `%4s' of type %u to client.\n",
3234 GNUNET_i2s(&sender->peer),
3235 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3237 ntm = (struct NotifyTrafficMessage *) buf;
3238 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3239 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3240 ntm->distance = htonl (sender->last_distance);
3241 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3242 ntm->peer = sender->peer;
3243 memcpy (&ntm[1], m, msize);
3244 send_to_client (client, &ntm->header, GNUNET_YES);
3249 * Deliver P2P message to interested clients.
3251 * @param cls always NULL
3252 * @param client who sent us the message (struct Neighbour)
3253 * @param m the message
3256 deliver_message (void *cls,
3258 const struct GNUNET_MessageHeader *m)
3260 struct Neighbour *sender = client;
3261 size_t msize = ntohs (m->size);
3263 struct Client *cpos;
3269 type = ntohs (m->type);
3271 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3272 "Received encapsulated message of type %u and size %u from `%4s'\n",
3273 (unsigned int) type,
3275 GNUNET_i2s (&sender->peer));
3277 GNUNET_snprintf (buf,
3279 gettext_noop ("# bytes of messages of type %u received"),
3280 (unsigned int) type);
3281 GNUNET_STATISTICS_set (stats,
3285 dropped = GNUNET_YES;
3287 while (cpos != NULL)
3289 deliver_full = GNUNET_NO;
3290 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3291 deliver_full = GNUNET_YES;
3294 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3296 if (type != cpos->types[tpos])
3298 deliver_full = GNUNET_YES;
3302 if (GNUNET_YES == deliver_full)
3304 send_p2p_message_to_client (sender, cpos, m, msize);
3305 dropped = GNUNET_NO;
3307 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3309 send_p2p_message_to_client (sender, cpos, m,
3310 sizeof (struct GNUNET_MessageHeader));
3314 if (dropped == GNUNET_YES)
3317 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3318 "Message of type %u from `%4s' not delivered to any client.\n",
3319 (unsigned int) type,
3320 GNUNET_i2s (&sender->peer));
3322 GNUNET_STATISTICS_update (stats,
3323 gettext_noop ("# messages not delivered to any client"),
3330 * We received an encrypted message. Decrypt, validate and
3331 * pass on to the appropriate clients.
3334 handle_encrypted_message (struct Neighbour *n,
3335 const struct EncryptedMessage *m)
3337 size_t size = ntohs (m->header.size);
3339 struct EncryptedMessage *pt; /* plaintext */
3342 struct GNUNET_TIME_Absolute t;
3346 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3347 "Core service receives `%s' request from `%4s'.\n",
3348 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3350 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3356 &buf[ENCRYPTED_HEADER_SIZE],
3357 size - ENCRYPTED_HEADER_SIZE))
3359 pt = (struct EncryptedMessage *) buf;
3361 GNUNET_CRYPTO_hmac (&n->decrypt_key,
3362 &pt->sequence_number,
3363 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3365 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3366 "V-Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
3367 (unsigned int) (size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode)),
3371 if (0 != memcmp (&ph,
3373 sizeof (GNUNET_HashCode)))
3375 /* checksum failed */
3376 GNUNET_break_op (0);
3380 /* validate sequence number */
3381 snum = ntohl (pt->sequence_number);
3382 if (n->last_sequence_number_received == snum)
3384 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3385 "Received duplicate message, ignoring.\n");
3386 /* duplicate, ignore */
3387 GNUNET_STATISTICS_set (stats,
3388 gettext_noop ("# bytes dropped (duplicates)"),
3393 if ((n->last_sequence_number_received > snum) &&
3394 (n->last_sequence_number_received - snum > 32))
3396 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3397 "Received ancient out of sequence message, ignoring.\n");
3398 /* ancient out of sequence, ignore */
3399 GNUNET_STATISTICS_set (stats,
3400 gettext_noop ("# bytes dropped (out of sequence)"),
3405 if (n->last_sequence_number_received > snum)
3407 unsigned int rotbit =
3408 1 << (n->last_sequence_number_received - snum - 1);
3409 if ((n->last_packets_bitmap & rotbit) != 0)
3411 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3412 "Received duplicate message, ignoring.\n");
3413 GNUNET_STATISTICS_set (stats,
3414 gettext_noop ("# bytes dropped (duplicates)"),
3417 /* duplicate, ignore */
3420 n->last_packets_bitmap |= rotbit;
3422 if (n->last_sequence_number_received < snum)
3424 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3425 n->last_sequence_number_received = snum;
3428 /* check timestamp */
3429 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3430 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3432 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3434 ("Message received far too old (%llu ms). Content ignored.\n"),
3435 GNUNET_TIME_absolute_get_duration (t).value);
3436 GNUNET_STATISTICS_set (stats,
3437 gettext_noop ("# bytes dropped (ancient message)"),
3443 /* process decrypted message(s) */
3444 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3446 #if DEBUG_CORE_SET_QUOTA
3447 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3448 "Received %u b/s as new inbound limit for peer `%4s'\n",
3449 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3450 GNUNET_i2s (&n->peer));
3452 n->bw_out_external_limit = pt->inbound_bw_limit;
3453 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3454 n->bw_out_internal_limit);
3455 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3457 GNUNET_TRANSPORT_set_quota (transport,
3461 GNUNET_TIME_UNIT_FOREVER_REL,
3464 n->last_activity = GNUNET_TIME_absolute_get ();
3465 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3466 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3468 = GNUNET_SCHEDULER_add_delayed (sched,
3469 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3472 GNUNET_STATISTICS_set (stats,
3473 gettext_noop ("# bytes of payload decrypted"),
3474 size - sizeof (struct EncryptedMessage),
3476 handle_peer_status_change (n);
3477 if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst,
3479 &buf[sizeof (struct EncryptedMessage)],
3480 size - sizeof (struct EncryptedMessage),
3481 GNUNET_YES, GNUNET_NO))
3482 GNUNET_break_op (0);
3487 * Function called by the transport for each received message.
3489 * @param cls closure
3490 * @param peer (claimed) identity of the other peer
3491 * @param message the message
3492 * @param latency estimated latency for communicating with the
3493 * given peer (round-trip)
3494 * @param distance in overlay hops, as given by transport plugin
3497 handle_transport_receive (void *cls,
3498 const struct GNUNET_PeerIdentity *peer,
3499 const struct GNUNET_MessageHeader *message,
3500 struct GNUNET_TIME_Relative latency,
3501 unsigned int distance)
3503 struct Neighbour *n;
3504 struct GNUNET_TIME_Absolute now;
3511 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3512 "Received message of type %u from `%4s', demultiplexing.\n",
3513 (unsigned int) ntohs (message->type),
3516 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3521 n = find_neighbour (peer);
3523 n = create_neighbour (peer);
3524 changed = (latency.value != n->last_latency.value) || (distance != n->last_distance);
3525 n->last_latency = latency;
3526 n->last_distance = distance;
3527 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3528 type = ntohs (message->type);
3529 size = ntohs (message->size);
3532 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3533 if (size != sizeof (struct SetKeyMessage))
3535 GNUNET_break_op (0);
3538 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3539 handle_set_key (n, (const struct SetKeyMessage *) message);
3541 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3542 if (size < sizeof (struct EncryptedMessage) +
3543 sizeof (struct GNUNET_MessageHeader))
3545 GNUNET_break_op (0);
3548 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3549 (n->status != PEER_STATE_KEY_CONFIRMED))
3551 GNUNET_break_op (0);
3554 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3556 case GNUNET_MESSAGE_TYPE_CORE_PING:
3557 if (size != sizeof (struct PingMessage))
3559 GNUNET_break_op (0);
3562 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3563 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3564 (n->status != PEER_STATE_KEY_CONFIRMED))
3567 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3568 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3569 "PING", GNUNET_i2s (&n->peer));
3571 GNUNET_free_non_null (n->pending_ping);
3572 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3573 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3576 handle_ping (n, (const struct PingMessage *) message);
3578 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3579 if (size != sizeof (struct PongMessage))
3581 GNUNET_break_op (0);
3584 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3585 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3586 (n->status != PEER_STATE_KEY_CONFIRMED) )
3589 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3590 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3591 "PONG", GNUNET_i2s (&n->peer));
3593 GNUNET_free_non_null (n->pending_pong);
3594 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3595 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3598 handle_pong (n, (const struct PongMessage *) message);
3601 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3602 _("Unsupported message of type %u received.\n"),
3603 (unsigned int) type);
3606 if (n->status == PEER_STATE_KEY_CONFIRMED)
3608 now = GNUNET_TIME_absolute_get ();
3609 n->last_activity = now;
3610 changed = GNUNET_YES;
3613 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3614 n->time_established = now;
3616 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3617 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3619 = GNUNET_SCHEDULER_add_delayed (sched,
3620 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3625 handle_peer_status_change (n);
3630 * Function that recalculates the bandwidth quota for the
3631 * given neighbour and transmits it to the transport service.
3633 * @param cls neighbour for the quota update
3637 neighbour_quota_update (void *cls,
3638 const struct GNUNET_SCHEDULER_TaskContext *tc)
3640 struct Neighbour *n = cls;
3641 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3644 unsigned long long distributable;
3645 uint64_t need_per_peer;
3646 uint64_t need_per_second;
3649 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3650 "Neighbour quota update calculation running for peer `%4s'\n",
3651 GNUNET_i2s (&n->peer));
3653 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3654 /* calculate relative preference among all neighbours;
3655 divides by a bit more to avoid division by zero AND to
3656 account for possibility of new neighbours joining any time
3657 AND to convert to double... */
3658 if (preference_sum == 0)
3660 pref_rel = 1.0 / (double) neighbour_count;
3664 pref_rel = n->current_preference / preference_sum;
3666 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3667 GNUNET_TIME_UNIT_SECONDS);
3668 need_per_second = need_per_peer * neighbour_count;
3670 if (bandwidth_target_out_bps > need_per_second)
3671 distributable = bandwidth_target_out_bps - need_per_second;
3672 share = distributable * pref_rel;
3673 if (share + need_per_peer > UINT32_MAX)
3674 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
3676 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3677 /* check if we want to disconnect for good due to inactivity */
3678 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3679 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3682 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3683 "Forcing disconnect of `%4s' due to inactivity\n",
3684 GNUNET_i2s (&n->peer));
3686 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3688 #if DEBUG_CORE_QUOTA
3689 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3690 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3691 GNUNET_i2s (&n->peer),
3692 (unsigned int) ntohl (q_in.value__),
3693 bandwidth_target_out_bps,
3694 (unsigned int) ntohl (n->bw_in.value__),
3695 (unsigned int) ntohl (n->bw_out.value__),
3696 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3698 if (n->bw_in.value__ != q_in.value__)
3701 if (GNUNET_YES == n->is_connected)
3702 GNUNET_TRANSPORT_set_quota (transport,
3706 GNUNET_TIME_UNIT_FOREVER_REL,
3708 handle_peer_status_change (n);
3710 schedule_quota_update (n);
3715 * Function called by transport to notify us that
3716 * a peer connected to us (on the network level).
3718 * @param cls closure
3719 * @param peer the peer that connected
3720 * @param latency current latency of the connection
3721 * @param distance in overlay hops, as given by transport plugin
3724 handle_transport_notify_connect (void *cls,
3725 const struct GNUNET_PeerIdentity *peer,
3726 struct GNUNET_TIME_Relative latency,
3727 unsigned int distance)
3729 struct Neighbour *n;
3731 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3736 n = find_neighbour (peer);
3739 if (GNUNET_YES == n->is_connected)
3741 /* duplicate connect notification!? */
3748 n = create_neighbour (peer);
3750 GNUNET_STATISTICS_update (stats,
3751 gettext_noop ("# peers connected (transport)"),
3754 n->is_connected = GNUNET_YES;
3755 n->last_latency = latency;
3756 n->last_distance = distance;
3757 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3760 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3764 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3765 "Received connection from `%4s'.\n",
3766 GNUNET_i2s (&n->peer));
3768 GNUNET_TRANSPORT_set_quota (transport,
3772 GNUNET_TIME_UNIT_FOREVER_REL,
3779 * Function called by transport telling us that a peer
3782 * @param cls closure
3783 * @param peer the peer that disconnected
3786 handle_transport_notify_disconnect (void *cls,
3787 const struct GNUNET_PeerIdentity *peer)
3789 struct DisconnectNotifyMessage cnm;
3790 struct Neighbour *n;
3791 struct GNUNET_TIME_Relative left;
3794 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3795 "Peer `%4s' disconnected from us; received notification from transport.\n", GNUNET_i2s (peer));
3798 n = find_neighbour (peer);
3804 GNUNET_break (n->is_connected);
3805 if (n->status == PEER_STATE_KEY_CONFIRMED)
3807 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3808 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3810 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3812 n->is_connected = GNUNET_NO;
3813 GNUNET_STATISTICS_update (stats,
3814 gettext_noop ("# peers connected (transport)"),
3817 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
3818 GNUNET_SCHEDULER_cancel (sched,
3819 n->dead_clean_task);
3820 left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3821 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
3822 n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (),
3824 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
3825 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
3826 &consider_free_task,
3832 * Last task run during shutdown. Disconnects us from
3836 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3838 struct Neighbour *n;
3842 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3843 "Core service shutting down.\n");
3845 GNUNET_assert (transport != NULL);
3846 GNUNET_TRANSPORT_disconnect (transport);
3848 while (NULL != (n = neighbours))
3850 neighbours = n->next;
3851 GNUNET_assert (neighbour_count > 0);
3855 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
3856 GNUNET_SERVER_notification_context_destroy (notifier);
3858 while (NULL != (c = clients))
3859 handle_client_disconnect (NULL, c->client_handle);
3860 if (my_private_key != NULL)
3861 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3863 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3864 if (peerinfo != NULL)
3865 GNUNET_PEERINFO_disconnect (peerinfo);
3867 GNUNET_SERVER_mst_destroy (mst);
3872 * Initiate core service.
3874 * @param cls closure
3875 * @param s scheduler to use
3876 * @param server the initialized server
3877 * @param c configuration to use
3881 struct GNUNET_SCHEDULER_Handle *s,
3882 struct GNUNET_SERVER_Handle *server,
3883 const struct GNUNET_CONFIGURATION_Handle *c)
3885 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3886 {&handle_client_init, NULL,
3887 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
3888 {&handle_client_request_info, NULL,
3889 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
3890 sizeof (struct RequestInfoMessage)},
3891 {&handle_client_iterate_peers, NULL,
3892 GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
3893 sizeof (struct GNUNET_MessageHeader)},
3894 {&handle_client_send, NULL,
3895 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
3896 {&handle_client_request_connect, NULL,
3897 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
3898 sizeof (struct ConnectMessage)},
3905 /* parse configuration */
3908 GNUNET_CONFIGURATION_get_value_number (c,
3911 &bandwidth_target_in_bps)) ||
3913 GNUNET_CONFIGURATION_get_value_number (c,
3916 &bandwidth_target_out_bps)) ||
3918 GNUNET_CONFIGURATION_get_value_filename (c,
3920 "HOSTKEY", &keyfile)))
3922 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3924 ("Core service is lacking key configuration settings. Exiting.\n"));
3925 GNUNET_SCHEDULER_shutdown (s);
3928 peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
3929 if (NULL == peerinfo)
3931 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3932 _("Could not access PEERINFO service. Exiting.\n"));
3933 GNUNET_SCHEDULER_shutdown (s);
3934 GNUNET_free (keyfile);
3937 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3938 GNUNET_free (keyfile);
3939 if (my_private_key == NULL)
3941 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3942 _("Core service could not access hostkey. Exiting.\n"));
3943 GNUNET_PEERINFO_disconnect (peerinfo);
3944 GNUNET_SCHEDULER_shutdown (s);
3947 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3948 GNUNET_CRYPTO_hash (&my_public_key,
3949 sizeof (my_public_key), &my_identity.hashPubKey);
3950 /* setup notification */
3951 notifier = GNUNET_SERVER_notification_context_create (server,
3953 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3954 /* setup transport connection */
3955 transport = GNUNET_TRANSPORT_connect (sched,
3959 &handle_transport_receive,
3960 &handle_transport_notify_connect,
3961 &handle_transport_notify_disconnect);
3962 GNUNET_assert (NULL != transport);
3963 stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3964 mst = GNUNET_SERVER_mst_create (&deliver_message,
3966 GNUNET_SCHEDULER_add_delayed (sched,
3967 GNUNET_TIME_UNIT_FOREVER_REL,
3968 &cleaning_task, NULL);
3969 /* process client requests */
3970 GNUNET_SERVER_add_handlers (server, handlers);
3971 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3972 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3978 * The main function for the transport service.
3980 * @param argc number of arguments from the command line
3981 * @param argv command line arguments
3982 * @return 0 ok, 1 on error
3985 main (int argc, char *const *argv)
3987 return (GNUNET_OK ==
3988 GNUNET_SERVICE_run (argc,
3991 GNUNET_SERVICE_OPTION_NONE,
3992 &run, NULL)) ? 0 : 1;
3995 /* end of gnunet-service-core.c */