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 * Encapsulation for encrypted messages exchanged between
165 * peers. Followed by the actual encrypted data.
167 struct EncryptedMessage
170 * Message type is either CORE_ENCRYPTED_MESSAGE.
172 struct GNUNET_MessageHeader header;
175 * Random value used for IV generation.
177 uint32_t iv_seed GNUNET_PACKED;
180 * MAC of the encrypted message (starting at 'sequence_number'),
181 * used to verify message integrity. Everything after this value
182 * (excluding this value itself) will be encrypted and authenticated.
183 * ENCRYPTED_HEADER_SIZE must be set to the offset of the *next* field.
185 GNUNET_HashCode hmac;
188 * Sequence number, in network byte order. This field
189 * must be the first encrypted/decrypted field
191 uint32_t sequence_number GNUNET_PACKED;
194 * Desired bandwidth (how much we should send to this peer / how
195 * much is the sender willing to receive)?
197 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
200 * Timestamp. Used to prevent reply of ancient messages
201 * (recent messages are caught with the sequence number).
203 struct GNUNET_TIME_AbsoluteNBO timestamp;
209 * Number of bytes (at the beginning) of "struct EncryptedMessage"
210 * that are NOT encrypted.
212 #define ENCRYPTED_HEADER_SIZE (offsetof(struct EncryptedMessage, sequence_number))
216 * We're sending an (encrypted) PING to the other peer to check if he
217 * can decrypt. The other peer should respond with a PONG with the
218 * same content, except this time encrypted with the receiver's key.
223 * Message type is CORE_PING.
225 struct GNUNET_MessageHeader header;
230 uint32_t iv_seed GNUNET_PACKED;
233 * Intended target of the PING, used primarily to check
234 * that decryption actually worked.
236 struct GNUNET_PeerIdentity target;
239 * Random number chosen to make reply harder.
241 uint32_t challenge GNUNET_PACKED;
247 * Response to a PING. Includes data from the original PING
248 * plus initial bandwidth quota information.
253 * Message type is CORE_PONG.
255 struct GNUNET_MessageHeader header;
260 uint32_t iv_seed GNUNET_PACKED;
263 * Random number to make faking the reply harder. Must be
264 * first field after header (this is where we start to encrypt!).
266 uint32_t challenge GNUNET_PACKED;
269 * Desired bandwidth (how much we should send to this
270 * peer / how much is the sender willing to receive).
272 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
275 * Intended target of the PING, used primarily to check
276 * that decryption actually worked.
278 struct GNUNET_PeerIdentity target;
283 * Message transmitted to set (or update) a session key.
289 * Message type is either CORE_SET_KEY.
291 struct GNUNET_MessageHeader header;
294 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
296 int32_t sender_status GNUNET_PACKED;
299 * Purpose of the signature, will be
300 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
302 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
305 * At what time was this key created?
307 struct GNUNET_TIME_AbsoluteNBO creation_time;
310 * The encrypted session key.
312 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
315 * Who is the intended recipient?
317 struct GNUNET_PeerIdentity target;
320 * Signature of the stuff above (starting at purpose).
322 struct GNUNET_CRYPTO_RsaSignature signature;
328 * Message waiting for transmission. This struct
329 * is followed by the actual content of the message.
335 * We keep messages in a doubly linked list.
337 struct MessageEntry *next;
340 * We keep messages in a doubly linked list.
342 struct MessageEntry *prev;
345 * By when are we supposed to transmit this message?
347 struct GNUNET_TIME_Absolute deadline;
350 * By when are we supposed to transmit this message (after
353 struct GNUNET_TIME_Absolute slack_deadline;
356 * How important is this message to us?
358 unsigned int priority;
361 * If this is a SET_KEY message, what was our connection status when this
362 * message was queued?
364 enum PeerStateMachine sender_status;
367 * Is this a SET_KEY message?
372 * How long is the message? (number of bytes following
373 * the "struct MessageEntry", but not including the
374 * size of "struct MessageEntry" itself!)
379 * Was this message selected for transmission in the
380 * current round? GNUNET_YES or GNUNET_NO.
385 * Did we give this message some slack (delayed sending) previously
386 * (and hence should not give it any more slack)? GNUNET_YES or
397 * We keep neighbours in a linked list (for now).
399 struct Neighbour *next;
402 * Unencrypted messages destined for this peer.
404 struct MessageEntry *messages;
407 * Head of the batched, encrypted message queue (already ordered,
408 * transmit starting with the head).
410 struct MessageEntry *encrypted_head;
413 * Tail of the batched, encrypted message queue (already ordered,
414 * append new messages to tail)
416 struct MessageEntry *encrypted_tail;
419 * Handle for pending requests for transmission to this peer
420 * with the transport service. NULL if no request is pending.
422 struct GNUNET_TRANSPORT_TransmitHandle *th;
425 * Public key of the neighbour, NULL if we don't have it yet.
427 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
430 * We received a PING message before we got the "public_key"
431 * (or the SET_KEY). We keep it here until we have a key
432 * to decrypt it. NULL if no PING is pending.
434 struct PingMessage *pending_ping;
437 * We received a PONG message before we got the "public_key"
438 * (or the SET_KEY). We keep it here until we have a key
439 * to decrypt it. NULL if no PONG is pending.
441 struct PongMessage *pending_pong;
444 * Non-NULL if we are currently looking up HELLOs for this peer.
447 struct GNUNET_PEERINFO_IteratorContext *pitr;
450 * SetKeyMessage to transmit, NULL if we are not currently trying
453 struct SetKeyMessage *skm;
456 * Identity of the neighbour.
458 struct GNUNET_PeerIdentity peer;
461 * Key we use to encrypt our messages for the other peer
462 * (initialized by us when we do the handshake).
464 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
467 * Key we use to decrypt messages from the other peer
468 * (given to us by the other peer during the handshake).
470 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
473 * ID of task used for re-trying plaintext scheduling.
475 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
478 * ID of task used for re-trying SET_KEY and PING message.
480 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
483 * ID of task used for updating bandwidth quota for this neighbour.
485 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
488 * ID of task used for sending keep-alive pings.
490 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
493 * ID of task used for cleaning up dead neighbour entries.
495 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
498 * At what time did we generate our encryption key?
500 struct GNUNET_TIME_Absolute encrypt_key_created;
503 * At what time did the other peer generate the decryption key?
505 struct GNUNET_TIME_Absolute decrypt_key_created;
508 * At what time did we initially establish (as in, complete session
509 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
511 struct GNUNET_TIME_Absolute time_established;
514 * At what time did we last receive an encrypted message from the
515 * other peer? Should be zero if status != KEY_CONFIRMED.
517 struct GNUNET_TIME_Absolute last_activity;
520 * Last latency observed from this peer.
522 struct GNUNET_TIME_Relative last_latency;
525 * At what frequency are we currently re-trying SET_KEY messages?
527 struct GNUNET_TIME_Relative set_key_retry_frequency;
530 * Tracking bandwidth for sending to this peer.
532 struct GNUNET_BANDWIDTH_Tracker available_send_window;
535 * Tracking bandwidth for receiving from this peer.
537 struct GNUNET_BANDWIDTH_Tracker available_recv_window;
540 * How valueable were the messages of this peer recently?
542 unsigned long long current_preference;
545 * Bit map indicating which of the 32 sequence numbers before the last
546 * were received (good for accepting out-of-order packets and
547 * estimating reliability of the connection)
549 unsigned int last_packets_bitmap;
552 * last sequence number received on this connection (highest)
554 uint32_t last_sequence_number_received;
557 * last sequence number transmitted
559 uint32_t last_sequence_number_sent;
562 * Available bandwidth in for this peer (current target).
564 struct GNUNET_BANDWIDTH_Value32NBO bw_in;
567 * Available bandwidth out for this peer (current target).
569 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
572 * Internal bandwidth limit set for this peer (initially typically
573 * set to "-1"). Actual "bw_out" is MIN of
574 * "bpm_out_internal_limit" and "bw_out_external_limit".
576 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
579 * External bandwidth limit set for this peer by the
580 * peer that we are communicating with. "bw_out" is MIN of
581 * "bw_out_internal_limit" and "bw_out_external_limit".
583 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
586 * What was our PING challenge number (for this peer)?
588 uint32_t ping_challenge;
591 * What was the last distance to this peer as reported by the transports?
593 uint32_t last_distance;
596 * What is our connection status?
598 enum PeerStateMachine status;
601 * Are we currently connected to this neighbour?
609 * Data structure for each client connected to the core service.
614 * Clients are kept in a linked list.
619 * Handle for the client with the server API.
621 struct GNUNET_SERVER_Client *client_handle;
624 * Array of the types of messages this peer cares
625 * about (with "tcnt" entries). Allocated as part
626 * of this client struct, do not free!
628 const uint16_t *types;
631 * Options for messages this client cares about,
632 * see GNUNET_CORE_OPTION_ values.
637 * Number of types of incoming messages this client
638 * specifically cares about. Size of the "types" array.
648 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
653 static struct GNUNET_PeerIdentity my_identity;
658 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
663 struct GNUNET_SCHEDULER_Handle *sched;
666 * Handle to peerinfo service.
668 static struct GNUNET_PEERINFO_Handle *peerinfo;
671 * Our message stream tokenizer (for encrypted payload).
673 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
678 const struct GNUNET_CONFIGURATION_Handle *cfg;
683 static struct GNUNET_TRANSPORT_Handle *transport;
686 * Linked list of our clients.
688 static struct Client *clients;
691 * Context for notifications we need to send to our clients.
693 static struct GNUNET_SERVER_NotificationContext *notifier;
696 * We keep neighbours in a linked list (for now).
698 static struct Neighbour *neighbours;
701 * For creating statistics.
703 static struct GNUNET_STATISTICS_Handle *stats;
706 * Sum of all preferences among all neighbours.
708 static unsigned long long preference_sum;
711 * Total number of neighbours we have.
713 static unsigned int neighbour_count;
716 * How much inbound bandwidth are we supposed to be using per second?
717 * FIXME: this value is not used!
719 static unsigned long long bandwidth_target_in_bps;
722 * How much outbound bandwidth are we supposed to be using per second?
724 static unsigned long long bandwidth_target_out_bps;
727 * Derive an authentication key from "set key" information
730 derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
731 const struct GNUNET_CRYPTO_AesSessionKey *skey,
733 struct GNUNET_TIME_Absolute creation_time)
735 static const char ctx[] = "authentication key";
736 struct GNUNET_TIME_AbsoluteNBO ctbe;
739 ctbe = GNUNET_TIME_absolute_hton (creation_time);
740 GNUNET_CRYPTO_hmac_derive_key (akey,
754 * Derive an IV from packet information
757 derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
758 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
759 const struct GNUNET_PeerIdentity *identity)
761 static const char ctx[] = "initialization vector";
763 GNUNET_CRYPTO_aes_derive_iv (iv,
767 &identity->hashPubKey.bits,
768 sizeof(identity->hashPubKey.bits),
774 * Derive an IV from pong packet information
777 derive_pong_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
778 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
779 uint32_t challenge, const struct GNUNET_PeerIdentity *identity)
781 static const char ctx[] = "pong initialization vector";
783 GNUNET_CRYPTO_aes_derive_iv (iv,
787 &identity->hashPubKey.bits,
788 sizeof(identity->hashPubKey.bits),
797 * A preference value for a neighbour was update. Update
798 * the preference sum accordingly.
800 * @param inc how much was a preference value increased?
803 update_preference_sum (unsigned long long inc)
806 unsigned long long os;
809 preference_sum += inc;
810 if (preference_sum >= os)
812 /* overflow! compensate by cutting all values in half! */
817 n->current_preference /= 2;
818 preference_sum += n->current_preference;
821 GNUNET_STATISTICS_set (stats, gettext_noop ("# total peer preference"), preference_sum, GNUNET_NO);
826 * Find the entry for the given neighbour.
828 * @param peer identity of the neighbour
829 * @return NULL if we are not connected, otherwise the
832 static struct Neighbour *
833 find_neighbour (const struct GNUNET_PeerIdentity *peer)
835 struct Neighbour *ret;
838 while ((ret != NULL) &&
839 (0 != memcmp (&ret->peer,
840 peer, sizeof (struct GNUNET_PeerIdentity))))
847 * Send a message to one of our clients.
849 * @param client target for the message
850 * @param msg message to transmit
851 * @param can_drop could this message be dropped if the
852 * client's queue is getting too large?
855 send_to_client (struct Client *client,
856 const struct GNUNET_MessageHeader *msg,
859 #if DEBUG_CORE_CLIENT
860 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
861 "Preparing to send %u bytes of message of type %u to client.\n",
862 (unsigned int) ntohs (msg->size),
863 (unsigned int) ntohs (msg->type));
865 GNUNET_SERVER_notification_context_unicast (notifier,
866 client->client_handle,
873 * Send a message to all of our current clients that have
874 * the right options set.
876 * @param msg message to multicast
877 * @param can_drop can this message be discarded if the queue is too long
878 * @param options mask to use
881 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
890 if (0 != (c->options & options))
892 #if DEBUG_CORE_CLIENT
893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
894 "Sending message of type %u to client.\n",
895 (unsigned int) ntohs (msg->type));
897 send_to_client (c, msg, can_drop);
905 * Function called by transport telling us that a peer
908 * @param n the peer that changed status
911 handle_peer_status_change (struct Neighbour *n)
913 struct PeerStatusNotifyMessage psnm;
915 if (! n->is_connected)
918 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
919 "Peer `%4s' changed status\n",
920 GNUNET_i2s (&n->peer));
922 psnm.header.size = htons (sizeof (struct PeerStatusNotifyMessage));
923 psnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_STATUS_CHANGE);
924 psnm.distance = htonl (n->last_distance);
925 psnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
926 psnm.timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_add (n->last_activity,
927 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
928 psnm.bandwidth_in = n->bw_in;
929 psnm.bandwidth_out = n->bw_out;
931 send_to_all_clients (&psnm.header,
933 GNUNET_CORE_OPTION_SEND_STATUS_CHANGE);
934 GNUNET_STATISTICS_update (stats,
935 gettext_noop ("# peer status changes"),
941 * Handle CORE_ITERATE_PEERS request.
944 handle_client_iterate_peers (void *cls,
945 struct GNUNET_SERVER_Client *client,
946 const struct GNUNET_MessageHeader *message)
949 struct ConnectNotifyMessage cnm;
950 struct GNUNET_MessageHeader done_msg;
951 struct GNUNET_SERVER_TransmitContext *tc;
953 /* notify new client about existing neighbours */
954 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
955 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
956 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
957 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
958 tc = GNUNET_SERVER_transmit_context_create (client);
962 if (n->status == PEER_STATE_KEY_CONFIRMED)
964 #if DEBUG_CORE_CLIENT
965 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
966 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
968 cnm.distance = htonl (n->last_distance);
969 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
971 GNUNET_SERVER_transmit_context_append_message (tc, &cnm.header);
972 /*send_to_client (c, &cnm.header, GNUNET_NO);*/
977 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
978 GNUNET_SERVER_transmit_context_run (tc,
979 GNUNET_TIME_UNIT_FOREVER_REL);
984 * Handle CORE_INIT request.
987 handle_client_init (void *cls,
988 struct GNUNET_SERVER_Client *client,
989 const struct GNUNET_MessageHeader *message)
991 const struct InitMessage *im;
992 struct InitReplyMessage irm;
995 const uint16_t *types;
998 struct ConnectNotifyMessage cnm;
1001 #if DEBUG_CORE_CLIENT
1002 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1003 "Client connecting to core service with `%s' message\n",
1006 /* check that we don't have an entry already */
1010 if (client == c->client_handle)
1013 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1018 msize = ntohs (message->size);
1019 if (msize < sizeof (struct InitMessage))
1022 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1025 GNUNET_SERVER_notification_context_add (notifier, client);
1026 im = (const struct InitMessage *) message;
1027 types = (const uint16_t *) &im[1];
1028 msize -= sizeof (struct InitMessage);
1029 c = GNUNET_malloc (sizeof (struct Client) + msize);
1030 c->client_handle = client;
1033 c->tcnt = msize / sizeof (uint16_t);
1034 c->types = (const uint16_t *) &c[1];
1035 wtypes = (uint16_t *) &c[1];
1036 for (i=0;i<c->tcnt;i++)
1037 wtypes[i] = ntohs (types[i]);
1038 c->options = ntohl (im->options);
1039 #if DEBUG_CORE_CLIENT
1040 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1041 "Client %p is interested in %u message types\n",
1043 (unsigned int) c->tcnt);
1045 /* send init reply message */
1046 irm.header.size = htons (sizeof (struct InitReplyMessage));
1047 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
1048 memcpy (&irm.publicKey,
1050 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1051 #if DEBUG_CORE_CLIENT
1052 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1053 "Sending `%s' message to client.\n", "INIT_REPLY");
1055 send_to_client (c, &irm.header, GNUNET_NO);
1056 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
1058 /* notify new client about existing neighbours */
1059 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
1060 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1064 if (n->status == PEER_STATE_KEY_CONFIRMED)
1066 #if DEBUG_CORE_CLIENT
1067 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1068 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
1070 cnm.distance = htonl (n->last_distance);
1071 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
1073 send_to_client (c, &cnm.header, GNUNET_NO);
1078 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1083 * A client disconnected, clean up.
1085 * @param cls closure
1086 * @param client identification of the client
1089 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1092 struct Client *prev;
1096 #if DEBUG_CORE_CLIENT
1097 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1098 "Client %p has disconnected from core service.\n",
1105 if (client == pos->client_handle)
1108 clients = pos->next;
1110 prev->next = pos->next;
1117 /* client never sent INIT */
1122 * Handle REQUEST_INFO request.
1125 handle_client_request_info (void *cls,
1126 struct GNUNET_SERVER_Client *client,
1127 const struct GNUNET_MessageHeader *message)
1129 const struct RequestInfoMessage *rcm;
1130 struct Neighbour *n;
1131 struct ConfigurationInfoMessage cim;
1132 int32_t want_reserv;
1134 unsigned long long old_preference;
1135 struct GNUNET_SERVER_TransmitContext *tc;
1137 #if DEBUG_CORE_CLIENT
1138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1139 "Core service receives `%s' request.\n", "REQUEST_INFO");
1141 rcm = (const struct RequestInfoMessage *) message;
1142 n = find_neighbour (&rcm->peer);
1143 memset (&cim, 0, sizeof (cim));
1146 want_reserv = ntohl (rcm->reserve_inbound);
1147 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1149 n->bw_out_internal_limit = rcm->limit_outbound;
1150 if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1151 n->bw_out_external_limit).value__)
1153 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1154 n->bw_out_external_limit);
1155 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1157 GNUNET_TRANSPORT_set_quota (transport,
1161 GNUNET_TIME_UNIT_FOREVER_REL,
1163 handle_peer_status_change (n);
1166 if (want_reserv < 0)
1168 got_reserv = want_reserv;
1170 else if (want_reserv > 0)
1172 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1173 want_reserv).value == 0)
1174 got_reserv = want_reserv;
1176 got_reserv = 0; /* all or nothing */
1180 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1182 old_preference = n->current_preference;
1183 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1184 if (old_preference > n->current_preference)
1186 /* overflow; cap at maximum value */
1187 n->current_preference = ULLONG_MAX;
1189 update_preference_sum (n->current_preference - old_preference);
1190 #if DEBUG_CORE_QUOTA
1191 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1192 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1194 GNUNET_i2s (&rcm->peer),
1197 cim.reserved_amount = htonl (got_reserv);
1198 cim.bw_in = n->bw_in;
1199 cim.bw_out = n->bw_out;
1200 cim.preference = n->current_preference;
1202 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1203 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1204 cim.peer = rcm->peer;
1206 #if DEBUG_CORE_CLIENT
1207 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1208 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1210 tc = GNUNET_SERVER_transmit_context_create (client);
1211 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1212 GNUNET_SERVER_transmit_context_run (tc,
1213 GNUNET_TIME_UNIT_FOREVER_REL);
1218 * Free the given entry for the neighbour (it has
1219 * already been removed from the list at this point).
1221 * @param n neighbour to free
1224 free_neighbour (struct Neighbour *n)
1226 struct MessageEntry *m;
1229 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1230 "Destroying neighbour entry for peer `%4s'\n",
1231 GNUNET_i2s (&n->peer));
1233 if (n->pitr != NULL)
1235 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1240 GNUNET_free (n->skm);
1243 while (NULL != (m = n->messages))
1245 n->messages = m->next;
1248 while (NULL != (m = n->encrypted_head))
1250 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1257 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1260 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1261 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1262 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1263 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1264 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1265 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1266 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1267 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1268 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1269 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1270 if (n->status == PEER_STATE_KEY_CONFIRMED)
1271 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1272 GNUNET_free_non_null (n->public_key);
1273 GNUNET_free_non_null (n->pending_ping);
1274 GNUNET_free_non_null (n->pending_pong);
1280 * Check if we have encrypted messages for the specified neighbour
1281 * pending, and if so, check with the transport about sending them
1284 * @param n neighbour to check.
1286 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1290 * Encrypt size bytes from in and write the result to out. Use the
1291 * key for outbound traffic of the given neighbour.
1293 * @param n neighbour we are sending to
1294 * @param iv initialization vector to use
1295 * @param in ciphertext
1296 * @param out plaintext
1297 * @param size size of in/out
1298 * @return GNUNET_OK on success
1301 do_encrypt (struct Neighbour *n,
1302 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1303 const void *in, void *out, size_t size)
1305 if (size != (uint16_t) size)
1310 GNUNET_assert (size ==
1311 GNUNET_CRYPTO_aes_encrypt (in,
1315 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1317 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1318 "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
1319 (unsigned int) size,
1320 GNUNET_i2s (&n->peer),
1321 (unsigned int) n->encrypt_key.crc32,
1322 GNUNET_CRYPTO_crc32_n (iv, sizeof(iv)));
1329 * Consider freeing the given neighbour since we may not need
1330 * to keep it around anymore.
1332 * @param n neighbour to consider discarding
1335 consider_free_neighbour (struct Neighbour *n);
1339 * Task triggered when a neighbour entry is about to time out
1340 * (and we should prevent this by sending a PING).
1342 * @param cls the 'struct Neighbour'
1343 * @param tc scheduler context (not used)
1346 send_keep_alive (void *cls,
1347 const struct GNUNET_SCHEDULER_TaskContext *tc)
1349 struct Neighbour *n = cls;
1350 struct GNUNET_TIME_Relative retry;
1351 struct GNUNET_TIME_Relative left;
1352 struct MessageEntry *me;
1353 struct PingMessage pp;
1354 struct PingMessage *pm;
1355 struct GNUNET_CRYPTO_AesInitializationVector iv;
1357 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1359 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1360 sizeof (struct PingMessage));
1361 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1362 me->priority = PING_PRIORITY;
1363 me->size = sizeof (struct PingMessage);
1364 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1368 pm = (struct PingMessage *) &me[1];
1369 pm->header.size = htons (sizeof (struct PingMessage));
1370 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1371 pm->iv_seed = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1373 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
1374 pp.challenge = n->ping_challenge;
1375 pp.target = n->peer;
1377 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1378 "Encrypting `%s' message with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
1380 (unsigned int) n->ping_challenge,
1381 GNUNET_i2s (&n->peer),
1382 (unsigned int) n->encrypt_key.crc32,
1383 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
1390 sizeof (struct PingMessage) -
1391 ((void *) &pm->target - (void *) pm));
1392 process_encrypted_neighbour_queue (n);
1393 /* reschedule PING job */
1394 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1395 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1396 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1397 MIN_PING_FREQUENCY);
1399 = GNUNET_SCHEDULER_add_delayed (sched,
1408 * Task triggered when a neighbour entry might have gotten stale.
1410 * @param cls the 'struct Neighbour'
1411 * @param tc scheduler context (not used)
1414 consider_free_task (void *cls,
1415 const struct GNUNET_SCHEDULER_TaskContext *tc)
1417 struct Neighbour *n = cls;
1419 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1420 consider_free_neighbour (n);
1425 * Consider freeing the given neighbour since we may not need
1426 * to keep it around anymore.
1428 * @param n neighbour to consider discarding
1431 consider_free_neighbour (struct Neighbour *n)
1433 struct Neighbour *pos;
1434 struct Neighbour *prev;
1435 struct GNUNET_TIME_Relative left;
1437 if ( (n->th != NULL) ||
1438 (n->pitr != NULL) ||
1439 (GNUNET_YES == n->is_connected) )
1440 return; /* no chance */
1442 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1443 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1446 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1447 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1448 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1450 &consider_free_task,
1454 /* actually free the neighbour... */
1463 neighbours = n->next;
1465 prev->next = n->next;
1466 GNUNET_assert (neighbour_count > 0);
1468 GNUNET_STATISTICS_set (stats,
1469 gettext_noop ("# neighbour entries allocated"),
1477 * Function called when the transport service is ready to
1478 * receive an encrypted message for the respective peer
1480 * @param cls neighbour to use message from
1481 * @param size number of bytes we can transmit
1482 * @param buf where to copy the message
1483 * @return number of bytes transmitted
1486 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1488 struct Neighbour *n = cls;
1489 struct MessageEntry *m;
1494 m = n->encrypted_head;
1498 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1499 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1500 GNUNET_i2s (&n->peer));
1504 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1511 GNUNET_assert (size >= m->size);
1512 memcpy (cbuf, &m[1], m->size);
1514 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1517 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1518 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1519 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1521 GNUNET_i2s (&n->peer));
1523 process_encrypted_neighbour_queue (n);
1528 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1529 "Transmission of message of type %u and size %u failed\n",
1530 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1531 (unsigned int) m->size);
1535 consider_free_neighbour (n);
1541 * Check if we have plaintext messages for the specified neighbour
1542 * pending, and if so, consider batching and encrypting them (and
1543 * then trigger processing of the encrypted queue if needed).
1545 * @param n neighbour to check.
1547 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1551 * Check if we have encrypted messages for the specified neighbour
1552 * pending, and if so, check with the transport about sending them
1555 * @param n neighbour to check.
1558 process_encrypted_neighbour_queue (struct Neighbour *n)
1560 struct MessageEntry *m;
1563 return; /* request already pending */
1564 m = n->encrypted_head;
1567 /* encrypted queue empty, try plaintext instead */
1568 process_plaintext_neighbour_queue (n);
1572 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1573 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1574 (unsigned int) m->size,
1575 GNUNET_i2s (&n->peer),
1576 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).
1580 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1583 GNUNET_TIME_absolute_get_remaining
1585 ¬ify_encrypted_transmit_ready,
1589 /* message request too large or duplicate request */
1591 /* discard encrypted message */
1592 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1596 process_encrypted_neighbour_queue (n);
1602 * Decrypt size bytes from in and write the result to out. Use the
1603 * key for inbound traffic of the given neighbour. This function does
1604 * NOT do any integrity-checks on the result.
1606 * @param n neighbour we are receiving from
1607 * @param iv initialization vector to use
1608 * @param in ciphertext
1609 * @param out plaintext
1610 * @param size size of in/out
1611 * @return GNUNET_OK on success
1614 do_decrypt (struct Neighbour *n,
1615 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1616 const void *in, void *out, size_t size)
1618 if (size != (uint16_t) size)
1623 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1624 (n->status != PEER_STATE_KEY_CONFIRMED))
1626 GNUNET_break_op (0);
1627 return GNUNET_SYSERR;
1630 GNUNET_CRYPTO_aes_decrypt (in,
1637 return GNUNET_SYSERR;
1639 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1641 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1642 "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
1643 (unsigned int) size,
1644 GNUNET_i2s (&n->peer),
1645 (unsigned int) n->decrypt_key.crc32,
1646 GNUNET_CRYPTO_crc32_n (iv, sizeof(*iv)));
1653 * Select messages for transmission. This heuristic uses a combination
1654 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1655 * and priority-based discard (in case no feasible schedule exist) and
1656 * speculative optimization (defer any kind of transmission until
1657 * we either create a batch of significant size, 25% of max, or until
1658 * we are close to a deadline). Furthermore, when scheduling the
1659 * heuristic also packs as many messages into the batch as possible,
1660 * starting with those with the earliest deadline. Yes, this is fun.
1662 * @param n neighbour to select messages from
1663 * @param size number of bytes to select for transmission
1664 * @param retry_time set to the time when we should try again
1665 * (only valid if this function returns zero)
1666 * @return number of bytes selected, or 0 if we decided to
1667 * defer scheduling overall; in that case, retry_time is set.
1670 select_messages (struct Neighbour *n,
1671 size_t size, struct GNUNET_TIME_Relative *retry_time)
1673 struct MessageEntry *pos;
1674 struct MessageEntry *min;
1675 struct MessageEntry *last;
1676 unsigned int min_prio;
1677 struct GNUNET_TIME_Absolute t;
1678 struct GNUNET_TIME_Absolute now;
1679 struct GNUNET_TIME_Relative delta;
1681 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1684 unsigned int queue_size;
1685 int discard_low_prio;
1687 GNUNET_assert (NULL != n->messages);
1688 now = GNUNET_TIME_absolute_get ();
1689 /* last entry in linked list of messages processed */
1691 /* should we remove the entry with the lowest
1692 priority from consideration for scheduling at the
1703 discard_low_prio = GNUNET_YES;
1704 while (GNUNET_YES == discard_low_prio)
1707 min_prio = UINT_MAX;
1708 discard_low_prio = GNUNET_NO;
1709 /* calculate number of bytes available for transmission at time "t" */
1710 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1712 /* how many bytes have we (hypothetically) scheduled so far */
1714 /* maximum time we can wait before transmitting anything
1715 and still make all of our deadlines */
1716 slack = GNUNET_TIME_UNIT_FOREVER_REL;
1718 /* note that we use "*2" here because we want to look
1719 a bit further into the future; much more makes no
1720 sense since new message might be scheduled in the
1722 while ((pos != NULL) && (off < size * 2))
1724 if (pos->do_transmit == GNUNET_YES)
1726 /* already removed from consideration */
1730 if (discard_low_prio == GNUNET_NO)
1732 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1733 if (delta.value > 0)
1735 // FIXME: HUH? Check!
1737 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1740 if (avail < pos->size)
1742 // FIXME: HUH? Check!
1743 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1748 /* update slack, considering both its absolute deadline
1749 and relative deadlines caused by other messages
1750 with their respective load */
1751 slack = GNUNET_TIME_relative_min (slack,
1752 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1754 if (pos->deadline.value <= now.value)
1757 slack = GNUNET_TIME_UNIT_ZERO;
1759 else if (GNUNET_YES == pos->got_slack)
1761 /* should be soon now! */
1762 slack = GNUNET_TIME_relative_min (slack,
1763 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1768 GNUNET_TIME_relative_min (slack,
1769 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1770 pos->got_slack = GNUNET_YES;
1771 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1772 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
1777 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1778 if (pos->priority <= min_prio)
1780 /* update min for discard */
1781 min_prio = pos->priority;
1786 if (discard_low_prio)
1788 GNUNET_assert (min != NULL);
1789 /* remove lowest-priority entry from consideration */
1790 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1794 /* guard against sending "tiny" messages with large headers without
1796 if ( (slack.value > GNUNET_CONSTANTS_MAX_CORK_DELAY.value) &&
1798 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1800 /* less than 25% of message would be filled with deadlines still
1801 being met if we delay by one second or more; so just wait for
1802 more data; but do not wait longer than 1s (since we don't want
1803 to delay messages for a really long time either). */
1804 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1805 /* reset do_transmit values for next time */
1808 pos->do_transmit = GNUNET_NO;
1812 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1813 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1814 (unsigned long long) retry_time->value,
1816 (unsigned int) size);
1820 /* select marked messages (up to size) for transmission */
1825 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1827 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1831 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1832 "Selecting message of size %u for transmission\n",
1833 (unsigned int) pos->size);
1839 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1840 "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
1841 (unsigned int) pos->size,
1844 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1849 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1850 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1851 (unsigned long long) off, (unsigned long long) tsize,
1852 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
1853 GNUNET_i2s (&n->peer));
1860 * Batch multiple messages into a larger buffer.
1862 * @param n neighbour to take messages from
1863 * @param buf target buffer
1864 * @param size size of buf
1865 * @param deadline set to transmission deadline for the result
1866 * @param retry_time set to the time when we should try again
1867 * (only valid if this function returns zero)
1868 * @param priority set to the priority of the batch
1869 * @return number of bytes written to buf (can be zero)
1872 batch_message (struct Neighbour *n,
1875 struct GNUNET_TIME_Absolute *deadline,
1876 struct GNUNET_TIME_Relative *retry_time,
1877 unsigned int *priority)
1879 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1880 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1881 struct MessageEntry *pos;
1882 struct MessageEntry *prev;
1883 struct MessageEntry *next;
1888 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1889 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1890 if (0 == select_messages (n, size, retry_time))
1893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1894 "No messages selected, will try again in %llu ms\n",
1899 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1900 ntm->distance = htonl (n->last_distance);
1901 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1902 ntm->peer = n->peer;
1905 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1908 if (GNUNET_YES == pos->do_transmit)
1910 GNUNET_assert (pos->size <= size);
1911 /* do notifications */
1912 /* FIXME: track if we have *any* client that wants
1913 full notifications and only do this if that is
1915 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1917 memcpy (&ntm[1], &pos[1], pos->size);
1918 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1919 sizeof (struct GNUNET_MessageHeader));
1920 send_to_all_clients (&ntm->header,
1922 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1926 /* message too large for 'full' notifications, we do at
1927 least the 'hdr' type */
1930 sizeof (struct GNUNET_MessageHeader));
1932 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1934 send_to_all_clients (&ntm->header,
1936 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1938 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1939 "Encrypting %u bytes with message of type %u and size %u\n",
1941 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
1942 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
1944 /* copy for encrypted transmission */
1945 memcpy (&buf[ret], &pos[1], pos->size);
1948 *priority += pos->priority;
1950 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1951 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1952 (unsigned int) pos->size,
1953 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1955 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1969 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1970 "Deadline for message batch is %llu ms\n",
1971 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1978 * Remove messages with deadlines that have long expired from
1981 * @param n neighbour to inspect
1984 discard_expired_messages (struct Neighbour *n)
1986 struct MessageEntry *prev;
1987 struct MessageEntry *next;
1988 struct MessageEntry *pos;
1989 struct GNUNET_TIME_Absolute now;
1990 struct GNUNET_TIME_Relative delta;
1992 now = GNUNET_TIME_absolute_get ();
1998 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1999 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
2002 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2003 "Message is %llu ms past due, discarding.\n",
2020 * Signature of the main function of a task.
2022 * @param cls closure
2023 * @param tc context information (why was this task triggered now)
2026 retry_plaintext_processing (void *cls,
2027 const struct GNUNET_SCHEDULER_TaskContext *tc)
2029 struct Neighbour *n = cls;
2031 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2032 process_plaintext_neighbour_queue (n);
2037 * Send our key (and encrypted PING) to the other peer.
2039 * @param n the other peer
2041 static void send_key (struct Neighbour *n);
2044 * Task that will retry "send_key" if our previous attempt failed
2048 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2050 struct Neighbour *n = cls;
2053 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2054 "Retrying key transmission to `%4s'\n",
2055 GNUNET_i2s (&n->peer));
2057 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2058 n->set_key_retry_frequency =
2059 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2065 * Check if we have plaintext messages for the specified neighbour
2066 * pending, and if so, consider batching and encrypting them (and
2067 * then trigger processing of the encrypted queue if needed).
2069 * @param n neighbour to check.
2072 process_plaintext_neighbour_queue (struct Neighbour *n)
2074 char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)]; /* plaintext */
2076 struct EncryptedMessage *em; /* encrypted message */
2077 struct EncryptedMessage *ph; /* plaintext header */
2078 struct MessageEntry *me;
2079 unsigned int priority;
2080 struct GNUNET_TIME_Absolute deadline;
2081 struct GNUNET_TIME_Relative retry_time;
2082 struct GNUNET_CRYPTO_AesInitializationVector iv;
2083 struct GNUNET_CRYPTO_AuthKey auth_key;
2085 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2087 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
2088 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2092 case PEER_STATE_DOWN:
2095 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2096 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2097 GNUNET_i2s(&n->peer));
2100 case PEER_STATE_KEY_SENT:
2101 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2102 n->retry_set_key_task
2103 = GNUNET_SCHEDULER_add_delayed (sched,
2104 n->set_key_retry_frequency,
2105 &set_key_retry_task, n);
2107 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2108 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2109 GNUNET_i2s(&n->peer));
2112 case PEER_STATE_KEY_RECEIVED:
2113 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2114 n->retry_set_key_task
2115 = GNUNET_SCHEDULER_add_delayed (sched,
2116 n->set_key_retry_frequency,
2117 &set_key_retry_task, n);
2119 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2120 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2121 GNUNET_i2s(&n->peer));
2124 case PEER_STATE_KEY_CONFIRMED:
2125 /* ready to continue */
2128 discard_expired_messages (n);
2129 if (n->messages == NULL)
2132 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2133 "Plaintext message queue for `%4s' is empty.\n",
2134 GNUNET_i2s(&n->peer));
2136 return; /* no pending messages */
2138 if (n->encrypted_head != NULL)
2141 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2142 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2143 GNUNET_i2s(&n->peer));
2145 return; /* wait for messages already encrypted to be
2148 ph = (struct EncryptedMessage *) pbuf;
2149 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2151 used = sizeof (struct EncryptedMessage);
2152 used += batch_message (n,
2154 GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2155 &deadline, &retry_time, &priority);
2156 if (used == sizeof (struct EncryptedMessage))
2159 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2160 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2161 GNUNET_i2s(&n->peer));
2163 /* no messages selected for sending, try again later... */
2164 n->retry_plaintext_task =
2165 GNUNET_SCHEDULER_add_delayed (sched,
2167 &retry_plaintext_processing, n);
2170 #if DEBUG_CORE_QUOTA
2171 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2172 "Sending %u b/s as new limit to peer `%4s'\n",
2173 (unsigned int) ntohl (n->bw_in.value__),
2174 GNUNET_i2s (&n->peer));
2176 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
2177 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2178 ph->inbound_bw_limit = n->bw_in;
2179 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2181 /* setup encryption message header */
2182 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2183 me->deadline = deadline;
2184 me->priority = priority;
2186 em = (struct EncryptedMessage *) &me[1];
2187 em->header.size = htons (used);
2188 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2189 em->iv_seed = ph->iv_seed;
2190 derive_iv (&iv, &n->encrypt_key, ph->iv_seed, &n->peer);
2193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2194 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2195 (unsigned int) used - ENCRYPTED_HEADER_SIZE,
2196 GNUNET_i2s(&n->peer),
2197 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2199 GNUNET_assert (GNUNET_OK ==
2202 &ph->sequence_number,
2203 &em->sequence_number, used - ENCRYPTED_HEADER_SIZE));
2204 derive_auth_key (&auth_key,
2207 n->encrypt_key_created);
2208 GNUNET_CRYPTO_hmac (&auth_key,
2209 &em->sequence_number,
2210 used - ENCRYPTED_HEADER_SIZE,
2213 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2214 "Authenticated %u bytes of ciphertext %u: `%s'\n",
2215 used - ENCRYPTED_HEADER_SIZE,
2216 GNUNET_CRYPTO_crc32_n (&em->sequence_number,
2217 used - ENCRYPTED_HEADER_SIZE),
2218 GNUNET_h2s (&em->hmac));
2220 /* append to transmission list */
2221 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2225 process_encrypted_neighbour_queue (n);
2230 * Function that recalculates the bandwidth quota for the
2231 * given neighbour and transmits it to the transport service.
2233 * @param cls neighbour for the quota update
2237 neighbour_quota_update (void *cls,
2238 const struct GNUNET_SCHEDULER_TaskContext *tc);
2242 * Schedule the task that will recalculate the bandwidth
2243 * quota for this peer (and possibly force a disconnect of
2244 * idle peers by calculating a bandwidth of zero).
2247 schedule_quota_update (struct Neighbour *n)
2249 GNUNET_assert (n->quota_update_task ==
2250 GNUNET_SCHEDULER_NO_TASK);
2251 n->quota_update_task
2252 = GNUNET_SCHEDULER_add_delayed (sched,
2253 QUOTA_UPDATE_FREQUENCY,
2254 &neighbour_quota_update,
2260 * Initialize a new 'struct Neighbour'.
2262 * @param pid ID of the new neighbour
2263 * @return handle for the new neighbour
2265 static struct Neighbour *
2266 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2268 struct Neighbour *n;
2269 struct GNUNET_TIME_Absolute now;
2272 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2273 "Creating neighbour entry for peer `%4s'\n",
2276 n = GNUNET_malloc (sizeof (struct Neighbour));
2277 n->next = neighbours;
2280 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2282 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2283 now = GNUNET_TIME_absolute_get ();
2284 n->encrypt_key_created = now;
2285 n->last_activity = now;
2286 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2287 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2288 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2289 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2290 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2291 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
2293 neighbour_quota_update (n, NULL);
2294 consider_free_neighbour (n);
2300 * Handle CORE_SEND request.
2303 * @param client the client issuing the request
2304 * @param message the "struct SendMessage"
2307 handle_client_send (void *cls,
2308 struct GNUNET_SERVER_Client *client,
2309 const struct GNUNET_MessageHeader *message)
2311 const struct SendMessage *sm;
2312 struct Neighbour *n;
2313 struct MessageEntry *prev;
2314 struct MessageEntry *pos;
2315 struct MessageEntry *e;
2316 struct MessageEntry *min_prio_entry;
2317 struct MessageEntry *min_prio_prev;
2318 unsigned int min_prio;
2319 unsigned int queue_size;
2322 msize = ntohs (message->size);
2324 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2326 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));
2329 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2332 sm = (const struct SendMessage *) message;
2333 msize -= sizeof (struct SendMessage);
2334 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2336 /* FIXME: should we not allow loopback-injection here? */
2339 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2342 n = find_neighbour (&sm->peer);
2344 n = create_neighbour (&sm->peer);
2346 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2347 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2349 (unsigned int) msize,
2350 GNUNET_i2s (&sm->peer));
2352 /* bound queue size */
2353 discard_expired_messages (n);
2354 min_prio = UINT32_MAX;
2355 min_prio_entry = NULL;
2356 min_prio_prev = NULL;
2362 if (pos->priority <= min_prio)
2364 min_prio_entry = pos;
2365 min_prio_prev = prev;
2366 min_prio = pos->priority;
2372 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2375 if (ntohl(sm->priority) <= min_prio)
2377 /* discard new entry */
2379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2380 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2382 (unsigned int) MAX_PEER_QUEUE_SIZE,
2383 (unsigned int) msize,
2384 (unsigned int) ntohs (message->type));
2387 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2390 GNUNET_assert (min_prio_entry != NULL);
2391 /* discard "min_prio_entry" */
2393 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2394 "Queue full, discarding existing older request\n");
2396 if (min_prio_prev == NULL)
2397 n->messages = min_prio_entry->next;
2399 min_prio_prev->next = min_prio_entry->next;
2400 GNUNET_free (min_prio_entry);
2404 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2405 "Adding transmission request for `%4s' of size %u to queue\n",
2406 GNUNET_i2s (&sm->peer),
2407 (unsigned int) msize);
2409 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2410 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2411 e->priority = ntohl (sm->priority);
2413 memcpy (&e[1], &sm[1], msize);
2415 /* insert, keep list sorted by deadline */
2418 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2429 /* consider scheduling now */
2430 process_plaintext_neighbour_queue (n);
2432 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2437 * Function called when the transport service is ready to
2438 * receive a message. Only resets 'n->th' to NULL.
2440 * @param cls neighbour to use message from
2441 * @param size number of bytes we can transmit
2442 * @param buf where to copy the message
2443 * @return number of bytes transmitted
2446 notify_transport_connect_done (void *cls, size_t size, void *buf)
2448 struct Neighbour *n = cls;
2450 if (GNUNET_YES != n->is_connected)
2452 /* transport should only call us to transmit a message after
2453 * telling us about a successful connection to the respective peer */
2454 n->th = NULL; /* If this happens because of a timeout, reset n-th so another message may be sent for this peer! */
2456 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Timeout on notify connect!\n");
2463 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2464 _("Failed to connect to `%4s': transport failed to connect\n"),
2465 GNUNET_i2s (&n->peer));
2468 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2469 _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2470 GNUNET_i2s (&n->peer));
2471 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2472 GNUNET_SCHEDULER_cancel (sched,
2473 n->retry_set_key_task);
2474 n->retry_set_key_task = GNUNET_SCHEDULER_add_now (sched,
2475 &set_key_retry_task,
2482 * Handle CORE_REQUEST_CONNECT request.
2485 * @param client the client issuing the request
2486 * @param message the "struct ConnectMessage"
2489 handle_client_request_connect (void *cls,
2490 struct GNUNET_SERVER_Client *client,
2491 const struct GNUNET_MessageHeader *message)
2493 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2494 struct Neighbour *n;
2495 struct GNUNET_TIME_Relative timeout;
2497 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2500 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2503 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2504 n = find_neighbour (&cm->peer);
2506 n = create_neighbour (&cm->peer);
2507 if ( (GNUNET_YES == n->is_connected) ||
2510 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2511 "Core received `%s' request for `%4s', already connected!\n",
2513 GNUNET_i2s (&cm->peer));
2514 return; /* already connected, or at least trying */
2516 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2518 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2519 "Core received `%s' request for `%4s', will try to establish connection\n",
2521 GNUNET_i2s (&cm->peer));
2523 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2524 /* ask transport to connect to the peer */
2525 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2527 sizeof (struct GNUNET_MessageHeader), 0,
2529 ¬ify_transport_connect_done,
2531 GNUNET_break (NULL != n->th);
2536 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2537 * the neighbour's struct and retry send_key. Or, if we did not get a
2538 * HELLO, just do nothing.
2540 * @param cls the 'struct Neighbour' to retry sending the key for
2541 * @param peer the peer for which this is the HELLO
2542 * @param hello HELLO message of that peer
2545 process_hello_retry_send_key (void *cls,
2546 const struct GNUNET_PeerIdentity *peer,
2547 const struct GNUNET_HELLO_Message *hello)
2549 struct Neighbour *n = cls;
2554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2555 "Entered `%s' and `%s' is NULL!\n",
2556 "process_hello_retry_send_key",
2560 if (n->public_key != NULL)
2562 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2564 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2565 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2567 GNUNET_STATISTICS_update (stats,
2568 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2576 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2577 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
2578 GNUNET_i2s (&n->peer));
2580 GNUNET_STATISTICS_update (stats,
2581 gettext_noop ("# Delayed connecting due to lack of public key"),
2584 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2585 n->retry_set_key_task
2586 = GNUNET_SCHEDULER_add_delayed (sched,
2587 n->set_key_retry_frequency,
2588 &set_key_retry_task, n);
2594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2595 "Entered `%s' for peer `%4s'\n",
2596 "process_hello_retry_send_key",
2599 if (n->public_key != NULL)
2601 /* already have public key, why are we here? */
2607 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2608 "Received new `%s' message for `%4s', initiating key exchange.\n",
2613 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2614 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2616 GNUNET_STATISTICS_update (stats,
2617 gettext_noop ("# Error extracting public key from HELLO"),
2620 GNUNET_free (n->public_key);
2621 n->public_key = NULL;
2623 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2624 "GNUNET_HELLO_get_key returned awfully\n");
2632 * Send our key (and encrypted PING) to the other peer.
2634 * @param n the other peer
2637 send_key (struct Neighbour *n)
2639 struct MessageEntry *pos;
2640 struct SetKeyMessage *sm;
2641 struct MessageEntry *me;
2642 struct PingMessage pp;
2643 struct PingMessage *pm;
2644 struct GNUNET_CRYPTO_AesInitializationVector iv;
2646 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2648 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2649 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2651 if (n->pitr != NULL)
2654 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2655 "Key exchange in progress with `%4s'.\n",
2656 GNUNET_i2s (&n->peer));
2658 return; /* already in progress */
2660 if (GNUNET_YES != n->is_connected)
2663 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2664 "Not yet connected to peer `%4s'!\n",
2665 GNUNET_i2s (&n->peer));
2669 GNUNET_STATISTICS_update (stats,
2670 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
2673 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2675 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2677 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2678 ¬ify_encrypted_transmit_ready,
2684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2685 "Asked to perform key exchange with `%4s'.\n",
2686 GNUNET_i2s (&n->peer));
2688 if (n->public_key == NULL)
2690 /* lookup n's public key, then try again */
2692 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2693 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2694 GNUNET_i2s (&n->peer));
2696 GNUNET_assert (n->pitr == NULL);
2697 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2699 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2700 &process_hello_retry_send_key, n);
2703 pos = n->encrypted_head;
2706 if (GNUNET_YES == pos->is_setkey)
2708 if (pos->sender_status == n->status)
2711 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2712 "`%s' message for `%4s' queued already\n",
2714 GNUNET_i2s (&n->peer));
2716 goto trigger_processing;
2718 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2723 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2724 "Removing queued `%s' message for `%4s', will create a new one\n",
2726 GNUNET_i2s (&n->peer));
2736 case PEER_STATE_DOWN:
2737 n->status = PEER_STATE_KEY_SENT;
2739 case PEER_STATE_KEY_SENT:
2741 case PEER_STATE_KEY_RECEIVED:
2743 case PEER_STATE_KEY_CONFIRMED:
2751 /* first, set key message */
2752 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2753 sizeof (struct SetKeyMessage) +
2754 sizeof (struct PingMessage));
2755 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2756 me->priority = SET_KEY_PRIORITY;
2757 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
2758 me->is_setkey = GNUNET_YES;
2759 me->got_slack = GNUNET_YES; /* do not defer this one! */
2760 me->sender_status = n->status;
2761 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2765 sm = (struct SetKeyMessage *) &me[1];
2766 sm->header.size = htons (sizeof (struct SetKeyMessage));
2767 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2768 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2769 PEER_STATE_KEY_SENT : n->status));
2771 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2772 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2773 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2774 sizeof (struct GNUNET_PeerIdentity));
2775 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2776 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2777 sm->target = n->peer;
2778 GNUNET_assert (GNUNET_OK ==
2779 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2781 GNUNET_CRYPTO_AesSessionKey),
2783 &sm->encrypted_key));
2784 GNUNET_assert (GNUNET_OK ==
2785 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2787 pm = (struct PingMessage *) &sm[1];
2788 pm->header.size = htons (sizeof (struct PingMessage));
2789 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2790 pm->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2791 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
2792 pp.challenge = n->ping_challenge;
2793 pp.target = n->peer;
2795 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2796 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
2798 (unsigned int) n->ping_challenge,
2799 GNUNET_i2s (&n->peer),
2800 (unsigned int) n->encrypt_key.crc32,
2801 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
2808 sizeof (struct PingMessage) -
2809 ((void *) &pm->target - (void *) pm));
2810 GNUNET_STATISTICS_update (stats,
2811 gettext_noop ("# SET_KEY and PING messages created"),
2815 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2816 "Have %llu ms left for `%s' transmission.\n",
2817 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2821 /* trigger queue processing */
2822 process_encrypted_neighbour_queue (n);
2823 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2824 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2825 n->retry_set_key_task
2826 = GNUNET_SCHEDULER_add_delayed (sched,
2827 n->set_key_retry_frequency,
2828 &set_key_retry_task, n);
2833 * We received a SET_KEY message. Validate and update
2834 * our key material and status.
2836 * @param n the neighbour from which we received message m
2837 * @param m the set key message we received
2840 handle_set_key (struct Neighbour *n,
2841 const struct SetKeyMessage *m);
2845 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2846 * the neighbour's struct and retry handling the set_key message. Or,
2847 * if we did not get a HELLO, just free the set key message.
2849 * @param cls pointer to the set key message
2850 * @param peer the peer for which this is the HELLO
2851 * @param hello HELLO message of that peer
2854 process_hello_retry_handle_set_key (void *cls,
2855 const struct GNUNET_PeerIdentity *peer,
2856 const struct GNUNET_HELLO_Message *hello)
2858 struct Neighbour *n = cls;
2859 struct SetKeyMessage *sm = n->skm;
2865 if (n->public_key != NULL)
2868 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2869 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2871 GNUNET_i2s (&n->peer),
2874 handle_set_key (n, sm);
2878 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2879 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
2881 GNUNET_i2s (&n->peer));
2886 if (n->public_key != NULL)
2887 return; /* multiple HELLOs match!? */
2889 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2890 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2892 GNUNET_break_op (0);
2893 GNUNET_free (n->public_key);
2894 n->public_key = NULL;
2900 * We received a PING message. Validate and transmit
2903 * @param n sender of the PING
2904 * @param m the encrypted PING message itself
2907 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2909 struct PingMessage t;
2910 struct PongMessage tx;
2911 struct PongMessage *tp;
2912 struct MessageEntry *me;
2913 struct GNUNET_CRYPTO_AesInitializationVector iv;
2916 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2917 "Core service receives `%s' request from `%4s'.\n",
2918 "PING", GNUNET_i2s (&n->peer));
2920 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
2926 sizeof (struct PingMessage) -
2927 ((void *) &m->target - (void *) m)))
2930 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2931 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u, IV %u (salt %u)\n",
2933 GNUNET_i2s (&t.target),
2934 (unsigned int) t.challenge,
2935 (unsigned int) n->decrypt_key.crc32,
2936 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
2939 GNUNET_STATISTICS_update (stats,
2940 gettext_noop ("# PING messages decrypted"),
2943 if (0 != memcmp (&t.target,
2944 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2946 GNUNET_break_op (0);
2949 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2950 sizeof (struct PongMessage));
2951 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2955 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2956 me->priority = PONG_PRIORITY;
2957 me->size = sizeof (struct PongMessage);
2958 tx.inbound_bw_limit = n->bw_in;
2959 tx.challenge = t.challenge;
2960 tx.target = t.target;
2961 tp = (struct PongMessage *) &me[1];
2962 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2963 tp->header.size = htons (sizeof (struct PongMessage));
2964 tp->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2965 derive_pong_iv (&iv, &n->encrypt_key, tp->iv_seed, t.challenge, &n->peer);
2970 sizeof (struct PongMessage) -
2971 ((void *) &tp->challenge - (void *) tp));
2972 GNUNET_STATISTICS_update (stats,
2973 gettext_noop ("# PONG messages created"),
2977 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2978 "Encrypting `%s' with challenge %u using key %u, IV %u (salt %u)\n",
2980 (unsigned int) t.challenge,
2981 (unsigned int) n->encrypt_key.crc32,
2982 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
2985 /* trigger queue processing */
2986 process_encrypted_neighbour_queue (n);
2991 * We received a PONG message. Validate and update our status.
2993 * @param n sender of the PONG
2994 * @param m the encrypted PONG message itself
2997 handle_pong (struct Neighbour *n,
2998 const struct PongMessage *m)
3000 struct PongMessage t;
3001 struct ConnectNotifyMessage cnm;
3002 struct GNUNET_CRYPTO_AesInitializationVector iv;
3005 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3006 "Core service receives `%s' response from `%4s'.\n",
3007 "PONG", GNUNET_i2s (&n->peer));
3009 /* mark as garbage, just to be sure */
3010 memset (&t, 255, sizeof (t));
3011 derive_pong_iv (&iv, &n->decrypt_key, m->iv_seed, n->ping_challenge,
3018 sizeof (struct PongMessage) -
3019 ((void *) &m->challenge - (void *) m)))
3021 GNUNET_break_op (0);
3024 GNUNET_STATISTICS_update (stats,
3025 gettext_noop ("# PONG messages decrypted"),
3029 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3030 "Decrypted `%s' from `%4s' with challenge %u using key %u, IV %u (salt %u)\n",
3032 GNUNET_i2s (&t.target),
3033 (unsigned int) t.challenge,
3034 (unsigned int) n->decrypt_key.crc32,
3035 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3038 if ((0 != memcmp (&t.target,
3040 sizeof (struct GNUNET_PeerIdentity))) ||
3041 (n->ping_challenge != t.challenge))
3043 /* PONG malformed */
3045 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3046 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
3048 GNUNET_i2s (&n->peer),
3049 (unsigned int) n->ping_challenge);
3050 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3051 "Received malformed `%s' received from `%4s' with challenge %u\n",
3052 "PONG", GNUNET_i2s (&t.target),
3053 (unsigned int) t.challenge);
3055 GNUNET_break_op (0);
3060 case PEER_STATE_DOWN:
3061 GNUNET_break (0); /* should be impossible */
3063 case PEER_STATE_KEY_SENT:
3064 GNUNET_break (0); /* should be impossible, how did we decrypt? */
3066 case PEER_STATE_KEY_RECEIVED:
3067 GNUNET_STATISTICS_update (stats,
3068 gettext_noop ("# Session keys confirmed via PONG"),
3071 n->status = PEER_STATE_KEY_CONFIRMED;
3072 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
3074 n->bw_out_external_limit = t.inbound_bw_limit;
3075 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3076 n->bw_out_internal_limit);
3077 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3079 GNUNET_TRANSPORT_set_quota (transport,
3083 GNUNET_TIME_UNIT_FOREVER_REL,
3087 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3088 "Confirmed key via `%s' message for peer `%4s'\n",
3089 "PONG", GNUNET_i2s (&n->peer));
3091 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3093 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
3094 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3096 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3097 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3098 cnm.distance = htonl (n->last_distance);
3099 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3101 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
3102 process_encrypted_neighbour_queue (n);
3104 case PEER_STATE_KEY_CONFIRMED:
3105 n->last_activity = GNUNET_TIME_absolute_get ();
3106 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3107 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3109 = GNUNET_SCHEDULER_add_delayed (sched,
3110 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3113 handle_peer_status_change (n);
3123 * We received a SET_KEY message. Validate and update
3124 * our key material and status.
3126 * @param n the neighbour from which we received message m
3127 * @param m the set key message we received
3130 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
3132 struct SetKeyMessage *m_cpy;
3133 struct GNUNET_TIME_Absolute t;
3134 struct GNUNET_CRYPTO_AesSessionKey k;
3135 struct PingMessage *ping;
3136 struct PongMessage *pong;
3137 enum PeerStateMachine sender_status;
3140 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3141 "Core service receives `%s' request from `%4s'.\n",
3142 "SET_KEY", GNUNET_i2s (&n->peer));
3144 if (n->public_key == NULL)
3146 if (n->pitr != NULL)
3149 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3150 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3156 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3157 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3159 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3160 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3161 /* lookup n's public key, then try again */
3162 GNUNET_assert (n->skm == NULL);
3164 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3166 GNUNET_TIME_UNIT_MINUTES,
3167 &process_hello_retry_handle_set_key, n);
3168 GNUNET_STATISTICS_update (stats,
3169 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3174 if (0 != memcmp (&m->target,
3176 sizeof (struct GNUNET_PeerIdentity)))
3178 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3179 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3181 GNUNET_i2s (&m->target));
3184 if ((ntohl (m->purpose.size) !=
3185 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3186 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3187 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3188 sizeof (struct GNUNET_PeerIdentity)) ||
3190 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3191 &m->purpose, &m->signature, n->public_key)))
3193 /* invalid signature */
3194 GNUNET_break_op (0);
3197 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3198 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3199 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3200 (t.value < n->decrypt_key_created.value))
3202 /* this could rarely happen due to massive re-ordering of
3203 messages on the network level, but is most likely either
3204 a bug or some adversary messing with us. Report. */
3205 GNUNET_break_op (0);
3209 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3210 "Decrypting key material.\n");
3212 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3215 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3216 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3217 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3219 /* failed to decrypt !? */
3220 GNUNET_break_op (0);
3223 GNUNET_STATISTICS_update (stats,
3224 gettext_noop ("# SET_KEY messages decrypted"),
3228 if (n->decrypt_key_created.value != t.value)
3230 /* fresh key, reset sequence numbers */
3231 n->last_sequence_number_received = 0;
3232 n->last_packets_bitmap = 0;
3233 n->decrypt_key_created = t;
3235 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3238 case PEER_STATE_DOWN:
3239 n->status = PEER_STATE_KEY_RECEIVED;
3241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3242 "Responding to `%s' with my own key.\n", "SET_KEY");
3246 case PEER_STATE_KEY_SENT:
3247 case PEER_STATE_KEY_RECEIVED:
3248 n->status = PEER_STATE_KEY_RECEIVED;
3249 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3250 (sender_status != PEER_STATE_KEY_CONFIRMED))
3253 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3254 "Responding to `%s' with my own key (other peer has status %u).\n",
3256 (unsigned int) sender_status);
3261 case PEER_STATE_KEY_CONFIRMED:
3262 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3263 (sender_status != PEER_STATE_KEY_CONFIRMED))
3266 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3267 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3269 (unsigned int) sender_status);
3278 if (n->pending_ping != NULL)
3280 ping = n->pending_ping;
3281 n->pending_ping = NULL;
3282 handle_ping (n, ping);
3285 if (n->pending_pong != NULL)
3287 pong = n->pending_pong;
3288 n->pending_pong = NULL;
3289 handle_pong (n, pong);
3296 * Send a P2P message to a client.
3298 * @param sender who sent us the message?
3299 * @param client who should we give the message to?
3300 * @param m contains the message to transmit
3301 * @param msize number of bytes in buf to transmit
3304 send_p2p_message_to_client (struct Neighbour *sender,
3305 struct Client *client,
3306 const void *m, size_t msize)
3308 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3309 struct NotifyTrafficMessage *ntm;
3312 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3313 "Core service passes message from `%4s' of type %u to client.\n",
3314 GNUNET_i2s(&sender->peer),
3315 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3317 ntm = (struct NotifyTrafficMessage *) buf;
3318 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3319 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3320 ntm->distance = htonl (sender->last_distance);
3321 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3322 ntm->peer = sender->peer;
3323 memcpy (&ntm[1], m, msize);
3324 send_to_client (client, &ntm->header, GNUNET_YES);
3329 * Deliver P2P message to interested clients.
3331 * @param cls always NULL
3332 * @param client who sent us the message (struct Neighbour)
3333 * @param m the message
3336 deliver_message (void *cls,
3338 const struct GNUNET_MessageHeader *m)
3340 struct Neighbour *sender = client;
3341 size_t msize = ntohs (m->size);
3343 struct Client *cpos;
3349 type = ntohs (m->type);
3351 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3352 "Received encapsulated message of type %u and size %u from `%4s'\n",
3353 (unsigned int) type,
3355 GNUNET_i2s (&sender->peer));
3357 GNUNET_snprintf (buf,
3359 gettext_noop ("# bytes of messages of type %u received"),
3360 (unsigned int) type);
3361 GNUNET_STATISTICS_set (stats,
3365 dropped = GNUNET_YES;
3367 while (cpos != NULL)
3369 deliver_full = GNUNET_NO;
3370 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3371 deliver_full = GNUNET_YES;
3374 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3376 if (type != cpos->types[tpos])
3378 deliver_full = GNUNET_YES;
3382 if (GNUNET_YES == deliver_full)
3384 send_p2p_message_to_client (sender, cpos, m, msize);
3385 dropped = GNUNET_NO;
3387 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3389 send_p2p_message_to_client (sender, cpos, m,
3390 sizeof (struct GNUNET_MessageHeader));
3394 if (dropped == GNUNET_YES)
3397 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3398 "Message of type %u from `%4s' not delivered to any client.\n",
3399 (unsigned int) type,
3400 GNUNET_i2s (&sender->peer));
3402 GNUNET_STATISTICS_update (stats,
3403 gettext_noop ("# messages not delivered to any client"),
3410 * We received an encrypted message. Decrypt, validate and
3411 * pass on to the appropriate clients.
3414 handle_encrypted_message (struct Neighbour *n,
3415 const struct EncryptedMessage *m)
3417 size_t size = ntohs (m->header.size);
3419 struct EncryptedMessage *pt; /* plaintext */
3422 struct GNUNET_TIME_Absolute t;
3423 struct GNUNET_CRYPTO_AesInitializationVector iv;
3424 struct GNUNET_CRYPTO_AuthKey auth_key;
3427 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3428 "Core service receives `%s' request from `%4s'.\n",
3429 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3432 derive_auth_key (&auth_key,
3435 n->decrypt_key_created);
3436 GNUNET_CRYPTO_hmac (&auth_key,
3437 &m->sequence_number,
3438 size - ENCRYPTED_HEADER_SIZE, &ph);
3440 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3441 "Re-Authenticated %u bytes of ciphertext (`%u'): `%s'\n",
3442 (unsigned int) size - ENCRYPTED_HEADER_SIZE,
3443 GNUNET_CRYPTO_crc32_n (&m->sequence_number,
3444 size - ENCRYPTED_HEADER_SIZE),
3448 if (0 != memcmp (&ph,
3450 sizeof (GNUNET_HashCode)))
3452 /* checksum failed */
3453 GNUNET_break_op (0);
3456 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3461 &m->sequence_number,
3462 &buf[ENCRYPTED_HEADER_SIZE],
3463 size - ENCRYPTED_HEADER_SIZE))
3465 pt = (struct EncryptedMessage *) buf;
3467 /* validate sequence number */
3468 snum = ntohl (pt->sequence_number);
3469 if (n->last_sequence_number_received == snum)
3471 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3472 "Received duplicate message, ignoring.\n");
3473 /* duplicate, ignore */
3474 GNUNET_STATISTICS_set (stats,
3475 gettext_noop ("# bytes dropped (duplicates)"),
3480 if ((n->last_sequence_number_received > snum) &&
3481 (n->last_sequence_number_received - snum > 32))
3483 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3484 "Received ancient out of sequence message, ignoring.\n");
3485 /* ancient out of sequence, ignore */
3486 GNUNET_STATISTICS_set (stats,
3487 gettext_noop ("# bytes dropped (out of sequence)"),
3492 if (n->last_sequence_number_received > snum)
3494 unsigned int rotbit =
3495 1 << (n->last_sequence_number_received - snum - 1);
3496 if ((n->last_packets_bitmap & rotbit) != 0)
3498 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3499 "Received duplicate message, ignoring.\n");
3500 GNUNET_STATISTICS_set (stats,
3501 gettext_noop ("# bytes dropped (duplicates)"),
3504 /* duplicate, ignore */
3507 n->last_packets_bitmap |= rotbit;
3509 if (n->last_sequence_number_received < snum)
3511 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3512 n->last_sequence_number_received = snum;
3515 /* check timestamp */
3516 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3517 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3519 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3521 ("Message received far too old (%llu ms). Content ignored.\n"),
3522 GNUNET_TIME_absolute_get_duration (t).value);
3523 GNUNET_STATISTICS_set (stats,
3524 gettext_noop ("# bytes dropped (ancient message)"),
3530 /* process decrypted message(s) */
3531 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3533 #if DEBUG_CORE_SET_QUOTA
3534 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3535 "Received %u b/s as new inbound limit for peer `%4s'\n",
3536 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3537 GNUNET_i2s (&n->peer));
3539 n->bw_out_external_limit = pt->inbound_bw_limit;
3540 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3541 n->bw_out_internal_limit);
3542 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3544 GNUNET_TRANSPORT_set_quota (transport,
3548 GNUNET_TIME_UNIT_FOREVER_REL,
3551 n->last_activity = GNUNET_TIME_absolute_get ();
3552 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3553 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3555 = GNUNET_SCHEDULER_add_delayed (sched,
3556 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3559 GNUNET_STATISTICS_set (stats,
3560 gettext_noop ("# bytes of payload decrypted"),
3561 size - sizeof (struct EncryptedMessage),
3563 handle_peer_status_change (n);
3564 if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst,
3566 &buf[sizeof (struct EncryptedMessage)],
3567 size - sizeof (struct EncryptedMessage),
3568 GNUNET_YES, GNUNET_NO))
3569 GNUNET_break_op (0);
3574 * Function called by the transport for each received message.
3576 * @param cls closure
3577 * @param peer (claimed) identity of the other peer
3578 * @param message the message
3579 * @param latency estimated latency for communicating with the
3580 * given peer (round-trip)
3581 * @param distance in overlay hops, as given by transport plugin
3584 handle_transport_receive (void *cls,
3585 const struct GNUNET_PeerIdentity *peer,
3586 const struct GNUNET_MessageHeader *message,
3587 struct GNUNET_TIME_Relative latency,
3588 unsigned int distance)
3590 struct Neighbour *n;
3591 struct GNUNET_TIME_Absolute now;
3598 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3599 "Received message of type %u from `%4s', demultiplexing.\n",
3600 (unsigned int) ntohs (message->type),
3603 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3608 n = find_neighbour (peer);
3610 n = create_neighbour (peer);
3611 changed = (latency.value != n->last_latency.value) || (distance != n->last_distance);
3612 n->last_latency = latency;
3613 n->last_distance = distance;
3614 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3615 type = ntohs (message->type);
3616 size = ntohs (message->size);
3619 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3620 if (size != sizeof (struct SetKeyMessage))
3622 GNUNET_break_op (0);
3625 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3626 handle_set_key (n, (const struct SetKeyMessage *) message);
3628 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3629 if (size < sizeof (struct EncryptedMessage) +
3630 sizeof (struct GNUNET_MessageHeader))
3632 GNUNET_break_op (0);
3635 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3636 (n->status != PEER_STATE_KEY_CONFIRMED))
3638 GNUNET_break_op (0);
3641 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3643 case GNUNET_MESSAGE_TYPE_CORE_PING:
3644 if (size != sizeof (struct PingMessage))
3646 GNUNET_break_op (0);
3649 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3650 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3651 (n->status != PEER_STATE_KEY_CONFIRMED))
3654 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3655 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3656 "PING", GNUNET_i2s (&n->peer));
3658 GNUNET_free_non_null (n->pending_ping);
3659 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3660 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3663 handle_ping (n, (const struct PingMessage *) message);
3665 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3666 if (size != sizeof (struct PongMessage))
3668 GNUNET_break_op (0);
3671 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3672 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3673 (n->status != PEER_STATE_KEY_CONFIRMED) )
3676 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3677 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3678 "PONG", GNUNET_i2s (&n->peer));
3680 GNUNET_free_non_null (n->pending_pong);
3681 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3682 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3685 handle_pong (n, (const struct PongMessage *) message);
3688 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3689 _("Unsupported message of type %u received.\n"),
3690 (unsigned int) type);
3693 if (n->status == PEER_STATE_KEY_CONFIRMED)
3695 now = GNUNET_TIME_absolute_get ();
3696 n->last_activity = now;
3697 changed = GNUNET_YES;
3700 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3701 n->time_established = now;
3703 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3704 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3706 = GNUNET_SCHEDULER_add_delayed (sched,
3707 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3712 handle_peer_status_change (n);
3717 * Function that recalculates the bandwidth quota for the
3718 * given neighbour and transmits it to the transport service.
3720 * @param cls neighbour for the quota update
3724 neighbour_quota_update (void *cls,
3725 const struct GNUNET_SCHEDULER_TaskContext *tc)
3727 struct Neighbour *n = cls;
3728 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3731 unsigned long long distributable;
3732 uint64_t need_per_peer;
3733 uint64_t need_per_second;
3736 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3737 "Neighbour quota update calculation running for peer `%4s'\n",
3738 GNUNET_i2s (&n->peer));
3740 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3741 /* calculate relative preference among all neighbours;
3742 divides by a bit more to avoid division by zero AND to
3743 account for possibility of new neighbours joining any time
3744 AND to convert to double... */
3745 if (preference_sum == 0)
3747 pref_rel = 1.0 / (double) neighbour_count;
3751 pref_rel = n->current_preference / preference_sum;
3753 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3754 GNUNET_TIME_UNIT_SECONDS);
3755 need_per_second = need_per_peer * neighbour_count;
3757 if (bandwidth_target_out_bps > need_per_second)
3758 distributable = bandwidth_target_out_bps - need_per_second;
3759 share = distributable * pref_rel;
3760 if (share + need_per_peer > UINT32_MAX)
3761 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
3763 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3764 /* check if we want to disconnect for good due to inactivity */
3765 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3766 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3769 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3770 "Forcing disconnect of `%4s' due to inactivity\n",
3771 GNUNET_i2s (&n->peer));
3773 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3775 #if DEBUG_CORE_QUOTA
3776 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3777 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3778 GNUNET_i2s (&n->peer),
3779 (unsigned int) ntohl (q_in.value__),
3780 bandwidth_target_out_bps,
3781 (unsigned int) ntohl (n->bw_in.value__),
3782 (unsigned int) ntohl (n->bw_out.value__),
3783 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3785 if (n->bw_in.value__ != q_in.value__)
3788 if (GNUNET_YES == n->is_connected)
3789 GNUNET_TRANSPORT_set_quota (transport,
3793 GNUNET_TIME_UNIT_FOREVER_REL,
3795 handle_peer_status_change (n);
3797 schedule_quota_update (n);
3802 * Function called by transport to notify us that
3803 * a peer connected to us (on the network level).
3805 * @param cls closure
3806 * @param peer the peer that connected
3807 * @param latency current latency of the connection
3808 * @param distance in overlay hops, as given by transport plugin
3811 handle_transport_notify_connect (void *cls,
3812 const struct GNUNET_PeerIdentity *peer,
3813 struct GNUNET_TIME_Relative latency,
3814 unsigned int distance)
3816 struct Neighbour *n;
3818 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3823 n = find_neighbour (peer);
3826 if (GNUNET_YES == n->is_connected)
3828 /* duplicate connect notification!? */
3835 n = create_neighbour (peer);
3837 GNUNET_STATISTICS_update (stats,
3838 gettext_noop ("# peers connected (transport)"),
3841 n->is_connected = GNUNET_YES;
3842 n->last_latency = latency;
3843 n->last_distance = distance;
3844 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3847 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3851 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3852 "Received connection from `%4s'.\n",
3853 GNUNET_i2s (&n->peer));
3855 GNUNET_TRANSPORT_set_quota (transport,
3859 GNUNET_TIME_UNIT_FOREVER_REL,
3866 * Function called by transport telling us that a peer
3869 * @param cls closure
3870 * @param peer the peer that disconnected
3873 handle_transport_notify_disconnect (void *cls,
3874 const struct GNUNET_PeerIdentity *peer)
3876 struct DisconnectNotifyMessage cnm;
3877 struct Neighbour *n;
3878 struct GNUNET_TIME_Relative left;
3881 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3882 "Peer `%4s' disconnected from us; received notification from transport.\n", GNUNET_i2s (peer));
3885 n = find_neighbour (peer);
3891 GNUNET_break (n->is_connected);
3892 if (n->status == PEER_STATE_KEY_CONFIRMED)
3894 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3895 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3897 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3899 n->is_connected = GNUNET_NO;
3900 GNUNET_STATISTICS_update (stats,
3901 gettext_noop ("# peers connected (transport)"),
3904 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
3905 GNUNET_SCHEDULER_cancel (sched,
3906 n->dead_clean_task);
3907 left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3908 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
3909 n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (),
3911 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
3912 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
3913 &consider_free_task,
3919 * Last task run during shutdown. Disconnects us from
3923 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3925 struct Neighbour *n;
3929 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3930 "Core service shutting down.\n");
3932 GNUNET_assert (transport != NULL);
3933 GNUNET_TRANSPORT_disconnect (transport);
3935 while (NULL != (n = neighbours))
3937 neighbours = n->next;
3938 GNUNET_assert (neighbour_count > 0);
3942 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
3943 GNUNET_SERVER_notification_context_destroy (notifier);
3945 while (NULL != (c = clients))
3946 handle_client_disconnect (NULL, c->client_handle);
3947 if (my_private_key != NULL)
3948 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3950 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3951 if (peerinfo != NULL)
3952 GNUNET_PEERINFO_disconnect (peerinfo);
3954 GNUNET_SERVER_mst_destroy (mst);
3959 * Initiate core service.
3961 * @param cls closure
3962 * @param s scheduler to use
3963 * @param server the initialized server
3964 * @param c configuration to use
3968 struct GNUNET_SCHEDULER_Handle *s,
3969 struct GNUNET_SERVER_Handle *server,
3970 const struct GNUNET_CONFIGURATION_Handle *c)
3972 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3973 {&handle_client_init, NULL,
3974 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
3975 {&handle_client_request_info, NULL,
3976 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
3977 sizeof (struct RequestInfoMessage)},
3978 {&handle_client_iterate_peers, NULL,
3979 GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
3980 sizeof (struct GNUNET_MessageHeader)},
3981 {&handle_client_send, NULL,
3982 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
3983 {&handle_client_request_connect, NULL,
3984 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
3985 sizeof (struct ConnectMessage)},
3992 /* parse configuration */
3995 GNUNET_CONFIGURATION_get_value_number (c,
3998 &bandwidth_target_in_bps)) ||
4000 GNUNET_CONFIGURATION_get_value_number (c,
4003 &bandwidth_target_out_bps)) ||
4005 GNUNET_CONFIGURATION_get_value_filename (c,
4007 "HOSTKEY", &keyfile)))
4009 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4011 ("Core service is lacking key configuration settings. Exiting.\n"));
4012 GNUNET_SCHEDULER_shutdown (s);
4015 peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
4016 if (NULL == peerinfo)
4018 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4019 _("Could not access PEERINFO service. Exiting.\n"));
4020 GNUNET_SCHEDULER_shutdown (s);
4021 GNUNET_free (keyfile);
4024 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4025 GNUNET_free (keyfile);
4026 if (my_private_key == NULL)
4028 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4029 _("Core service could not access hostkey. Exiting.\n"));
4030 GNUNET_PEERINFO_disconnect (peerinfo);
4031 GNUNET_SCHEDULER_shutdown (s);
4034 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4035 GNUNET_CRYPTO_hash (&my_public_key,
4036 sizeof (my_public_key), &my_identity.hashPubKey);
4037 /* setup notification */
4038 notifier = GNUNET_SERVER_notification_context_create (server,
4040 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4041 /* setup transport connection */
4042 transport = GNUNET_TRANSPORT_connect (sched,
4046 &handle_transport_receive,
4047 &handle_transport_notify_connect,
4048 &handle_transport_notify_disconnect);
4049 GNUNET_assert (NULL != transport);
4050 stats = GNUNET_STATISTICS_create (sched, "core", cfg);
4051 mst = GNUNET_SERVER_mst_create (&deliver_message,
4053 GNUNET_SCHEDULER_add_delayed (sched,
4054 GNUNET_TIME_UNIT_FOREVER_REL,
4055 &cleaning_task, NULL);
4056 /* process client requests */
4057 GNUNET_SERVER_add_handlers (server, handlers);
4058 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4059 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
4065 * The main function for the transport service.
4067 * @param argc number of arguments from the command line
4068 * @param argv command line arguments
4069 * @return 0 ok, 1 on error
4072 main (int argc, char *const *argv)
4074 return (GNUNET_OK ==
4075 GNUNET_SERVICE_run (argc,
4078 GNUNET_SERVICE_OPTION_NONE,
4079 &run, NULL)) ? 0 : 1;
4082 /* end of gnunet-service-core.c */