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 * Type map implementation:
27 * - track type maps for neighbours (can wait)
28 * - only notify clients about peers with matching type maps (can wait)
30 * Considerations for later:
31 * - check that hostkey used by transport (for HELLOs) is the
32 * same as the hostkey that we are using!
36 #include "gnunet_constants.h"
37 #include "gnunet_util_lib.h"
38 #include "gnunet_hello_lib.h"
39 #include "gnunet_peerinfo_service.h"
40 #include "gnunet_protocols.h"
41 #include "gnunet_signatures.h"
42 #include "gnunet_statistics_service.h"
43 #include "gnunet_transport_service.h"
47 #define DEBUG_HANDSHAKE GNUNET_EXTRA_LOGGING
49 #define DEBUG_CORE_QUOTA GNUNET_EXTRA_LOGGING
52 * Receive and send buffer windows grow over time. For
53 * how long can 'unused' bandwidth accumulate before we
54 * need to cap it? (specified in seconds).
56 #define MAX_WINDOW_TIME_S (5 * 60)
59 * How many messages do we queue up at most for optional
60 * notifications to a client? (this can cause notifications
61 * about outgoing messages to be dropped).
63 #define MAX_NOTIFY_QUEUE 1024
66 * Minimum bandwidth (out) to assign to any connected peer.
67 * Should be rather low; values larger than DEFAULT_BW_IN_OUT make no
70 #define MIN_BANDWIDTH_PER_PEER GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT
73 * After how much time past the "official" expiration time do
74 * we discard messages? Should not be zero since we may
75 * intentionally defer transmission until close to the deadline
76 * and then may be slightly past the deadline due to inaccuracy
77 * in sleep and our own CPU consumption.
79 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
82 * What is the maximum delay for a SET_KEY message?
84 #define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
87 * How long do we wait for SET_KEY confirmation initially?
89 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 1)
92 * What is the maximum delay for a PING message?
94 #define MAX_PING_DELAY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 2)
97 * What is the maximum delay for a PONG message?
99 #define MAX_PONG_DELAY GNUNET_TIME_relative_multiply (MAX_PING_DELAY, 2)
102 * What is the minimum frequency for a PING message?
104 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
107 * How often do we recalculate bandwidth quotas?
109 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
112 * What is the priority for a SET_KEY message?
114 #define SET_KEY_PRIORITY 0xFFFFFF
117 * What is the priority for a PING message?
119 #define PING_PRIORITY 0xFFFFFF
122 * What is the priority for a PONG message?
124 #define PONG_PRIORITY 0xFFFFFF
127 * How many messages do we queue per peer at most? Must be at
130 #define MAX_PEER_QUEUE_SIZE 16
133 * How many non-mandatory messages do we queue per client at most?
135 #define MAX_CLIENT_QUEUE_SIZE 32
138 * What is the maximum age of a message for us to consider
139 * processing it? Note that this looks at the timestamp used
140 * by the other peer, so clock skew between machines does
141 * come into play here. So this should be picked high enough
142 * so that a little bit of clock skew does not prevent peers
143 * from connecting to us.
145 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
149 * State machine for our P2P encryption handshake. Everyone starts in
150 * "DOWN", if we receive the other peer's key (other peer initiated)
151 * we start in state RECEIVED (since we will immediately send our
152 * own); otherwise we start in SENT. If we get back a PONG from
153 * within either state, we move up to CONFIRMED (the PONG will always
154 * be sent back encrypted with the key we sent to the other peer).
156 enum PeerStateMachine
164 * We've sent our session key.
169 * We've received the other peers session key.
171 PEER_STATE_KEY_RECEIVED,
174 * The other peer has confirmed our session key with a message
175 * encrypted with his session key (which we got). Session is now fully up.
177 PEER_STATE_KEY_CONFIRMED
182 * Encapsulation for encrypted messages exchanged between
183 * peers. Followed by the actual encrypted data.
185 struct EncryptedMessage
188 * Message type is either CORE_ENCRYPTED_MESSAGE.
190 struct GNUNET_MessageHeader header;
193 * Random value used for IV generation.
195 uint32_t iv_seed GNUNET_PACKED;
198 * MAC of the encrypted message (starting at 'sequence_number'),
199 * used to verify message integrity. Everything after this value
200 * (excluding this value itself) will be encrypted and authenticated.
201 * ENCRYPTED_HEADER_SIZE must be set to the offset of the *next* field.
203 GNUNET_HashCode hmac;
206 * Sequence number, in network byte order. This field
207 * must be the first encrypted/decrypted field
209 uint32_t sequence_number GNUNET_PACKED;
212 * Desired bandwidth (how much we should send to this peer / how
213 * much is the sender willing to receive)?
215 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
218 * Timestamp. Used to prevent reply of ancient messages
219 * (recent messages are caught with the sequence number).
221 struct GNUNET_TIME_AbsoluteNBO timestamp;
227 * Number of bytes (at the beginning) of "struct EncryptedMessage"
228 * that are NOT encrypted.
230 #define ENCRYPTED_HEADER_SIZE (offsetof(struct EncryptedMessage, sequence_number))
234 * We're sending an (encrypted) PING to the other peer to check if he
235 * can decrypt. The other peer should respond with a PONG with the
236 * same content, except this time encrypted with the receiver's key.
241 * Message type is CORE_PING.
243 struct GNUNET_MessageHeader header;
248 uint32_t iv_seed GNUNET_PACKED;
251 * Intended target of the PING, used primarily to check
252 * that decryption actually worked.
254 struct GNUNET_PeerIdentity target;
257 * Random number chosen to make reply harder.
259 uint32_t challenge GNUNET_PACKED;
265 * Response to a PING. Includes data from the original PING
266 * plus initial bandwidth quota information.
271 * Message type is CORE_PONG.
273 struct GNUNET_MessageHeader header;
278 uint32_t iv_seed GNUNET_PACKED;
281 * Random number to make faking the reply harder. Must be
282 * first field after header (this is where we start to encrypt!).
284 uint32_t challenge GNUNET_PACKED;
287 * Desired bandwidth (how much we should send to this
288 * peer / how much is the sender willing to receive).
290 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
293 * Intended target of the PING, used primarily to check
294 * that decryption actually worked.
296 struct GNUNET_PeerIdentity target;
301 * Message transmitted to set (or update) a session key.
307 * Message type is either CORE_SET_KEY.
309 struct GNUNET_MessageHeader header;
312 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
314 int32_t sender_status GNUNET_PACKED;
317 * Purpose of the signature, will be
318 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
320 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
323 * At what time was this key created?
325 struct GNUNET_TIME_AbsoluteNBO creation_time;
328 * The encrypted session key.
330 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
333 * Who is the intended recipient?
335 struct GNUNET_PeerIdentity target;
338 * Signature of the stuff above (starting at purpose).
340 struct GNUNET_CRYPTO_RsaSignature signature;
346 * Message waiting for transmission. This struct
347 * is followed by the actual content of the message.
353 * We keep messages in a doubly linked list.
355 struct MessageEntry *next;
358 * We keep messages in a doubly linked list.
360 struct MessageEntry *prev;
363 * By when are we supposed to transmit this message?
365 struct GNUNET_TIME_Absolute deadline;
368 * By when are we supposed to transmit this message (after
371 struct GNUNET_TIME_Absolute slack_deadline;
374 * How important is this message to us?
376 unsigned int priority;
379 * If this is a SET_KEY message, what was our connection status when this
380 * message was queued?
382 enum PeerStateMachine sender_status;
385 * Is this a SET_KEY message?
390 * How long is the message? (number of bytes following
391 * the "struct MessageEntry", but not including the
392 * size of "struct MessageEntry" itself!)
397 * Was this message selected for transmission in the
398 * current round? GNUNET_YES or GNUNET_NO.
403 * Did we give this message some slack (delayed sending) previously
404 * (and hence should not give it any more slack)? GNUNET_YES or
413 * Record kept for each request for transmission issued by a
414 * client that is still pending.
416 struct ClientActiveRequest;
419 * Data kept per neighbouring peer.
425 * Unencrypted messages destined for this peer.
427 struct MessageEntry *messages;
430 * Head of the batched, encrypted message queue (already ordered,
431 * transmit starting with the head).
433 struct MessageEntry *encrypted_head;
436 * Tail of the batched, encrypted message queue (already ordered,
437 * append new messages to tail)
439 struct MessageEntry *encrypted_tail;
442 * Head of list of requests from clients for transmission to
445 struct ClientActiveRequest *active_client_request_head;
448 * Tail of list of requests from clients for transmission to
451 struct ClientActiveRequest *active_client_request_tail;
454 * Handle for pending requests for transmission to this peer
455 * with the transport service. NULL if no request is pending.
457 struct GNUNET_TRANSPORT_TransmitHandle *th;
460 * Public key of the neighbour, NULL if we don't have it yet.
462 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
465 * We received a PING message before we got the "public_key"
466 * (or the SET_KEY). We keep it here until we have a key
467 * to decrypt it. NULL if no PING is pending.
469 struct PingMessage *pending_ping;
472 * We received a PONG message before we got the "public_key"
473 * (or the SET_KEY). We keep it here until we have a key
474 * to decrypt it. NULL if no PONG is pending.
476 struct PongMessage *pending_pong;
479 * Non-NULL if we are currently looking up HELLOs for this peer.
482 struct GNUNET_PEERINFO_IteratorContext *pitr;
485 * SetKeyMessage to transmit, NULL if we are not currently trying
488 struct SetKeyMessage *skm;
491 * Performance data for the peer.
493 struct GNUNET_ATS_Information *ats;
496 * Identity of the neighbour.
498 struct GNUNET_PeerIdentity peer;
501 * Key we use to encrypt our messages for the other peer
502 * (initialized by us when we do the handshake).
504 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
507 * Key we use to decrypt messages from the other peer
508 * (given to us by the other peer during the handshake).
510 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
513 * ID of task used for re-trying plaintext scheduling.
515 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
518 * ID of task used for re-trying SET_KEY and PING message.
520 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
523 * ID of task used for updating bandwidth quota for this neighbour.
525 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
528 * ID of task used for sending keep-alive pings.
530 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
533 * ID of task used for cleaning up dead neighbour entries.
535 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
538 * At what time did we generate our encryption key?
540 struct GNUNET_TIME_Absolute encrypt_key_created;
543 * At what time did the other peer generate the decryption key?
545 struct GNUNET_TIME_Absolute decrypt_key_created;
548 * At what time did we initially establish (as in, complete session
549 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
551 struct GNUNET_TIME_Absolute time_established;
554 * At what time did we last receive an encrypted message from the
555 * other peer? Should be zero if status != KEY_CONFIRMED.
557 struct GNUNET_TIME_Absolute last_activity;
560 * At what frequency are we currently re-trying SET_KEY messages?
562 struct GNUNET_TIME_Relative set_key_retry_frequency;
565 * Tracking bandwidth for sending to this peer.
567 struct GNUNET_BANDWIDTH_Tracker available_send_window;
570 * How valueable were the messages of this peer recently?
572 unsigned long long current_preference;
575 * Number of entries in 'ats'.
577 unsigned int ats_count;
580 * Bit map indicating which of the 32 sequence numbers before the last
581 * were received (good for accepting out-of-order packets and
582 * estimating reliability of the connection)
584 unsigned int last_packets_bitmap;
587 * last sequence number received on this connection (highest)
589 uint32_t last_sequence_number_received;
592 * last sequence number transmitted
594 uint32_t last_sequence_number_sent;
597 * Available bandwidth in for this peer (current target).
599 struct GNUNET_BANDWIDTH_Value32NBO bw_in;
602 * Available bandwidth out for this peer (current target).
604 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
607 * Internal bandwidth limit set for this peer (initially typically
608 * set to "-1"). Actual "bw_out" is MIN of
609 * "bpm_out_internal_limit" and "bw_out_external_limit".
611 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
614 * External bandwidth limit set for this peer by the
615 * peer that we are communicating with. "bw_out" is MIN of
616 * "bw_out_internal_limit" and "bw_out_external_limit".
618 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
621 * What was our PING challenge number (for this peer)?
623 uint32_t ping_challenge;
626 * What is our connection status?
628 enum PeerStateMachine status;
631 * Are we currently connected to this neighbour?
639 * Data structure for each client connected to the core service.
644 * Clients are kept in a linked list.
649 * Handle for the client with the server API.
651 struct GNUNET_SERVER_Client *client_handle;
654 * Array of the types of messages this peer cares
655 * about (with "tcnt" entries). Allocated as part
656 * of this client struct, do not free!
658 const uint16_t *types;
661 * Map of peer identities to active transmission requests of this
662 * client to the peer (of type 'struct ClientActiveRequest').
664 struct GNUNET_CONTAINER_MultiHashMap *requests;
667 * Options for messages this client cares about,
668 * see GNUNET_CORE_OPTION_ values.
673 * Number of types of incoming messages this client
674 * specifically cares about. Size of the "types" array.
682 * Record kept for each request for transmission issued by a
683 * client that is still pending.
685 struct ClientActiveRequest
689 * Active requests are kept in a doubly-linked list of
690 * the respective target peer.
692 struct ClientActiveRequest *next;
695 * Active requests are kept in a doubly-linked list of
696 * the respective target peer.
698 struct ClientActiveRequest *prev;
701 * Handle to the client.
703 struct Client *client;
706 * By what time would the client want to see this message out?
708 struct GNUNET_TIME_Absolute deadline;
711 * How important is this request.
716 * How many more requests does this client have?
721 * How many bytes does the client intend to send?
726 * Unique request ID (in big endian).
737 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
742 static struct GNUNET_PeerIdentity my_identity;
747 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
750 * Bitmap of message types this peer is able to handle.
752 static uint32_t my_type_map[(UINT16_MAX + 1) / 32];
755 * Handle to peerinfo service.
757 static struct GNUNET_PEERINFO_Handle *peerinfo;
760 * Our message stream tokenizer (for encrypted payload).
762 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
767 const struct GNUNET_CONFIGURATION_Handle *cfg;
772 static struct GNUNET_TRANSPORT_Handle *transport;
775 * Linked list of our clients.
777 static struct Client *clients;
780 * Context for notifications we need to send to our clients.
782 static struct GNUNET_SERVER_NotificationContext *notifier;
785 * Map of peer identities to 'struct Neighbour'.
787 static struct GNUNET_CONTAINER_MultiHashMap *neighbours;
790 * Neighbour entry for "this" peer.
792 static struct Neighbour self;
795 * For creating statistics.
797 static struct GNUNET_STATISTICS_Handle *stats;
800 * Sum of all preferences among all neighbours.
802 static unsigned long long preference_sum;
805 * How much inbound bandwidth are we supposed to be using per second?
807 static unsigned long long bandwidth_target_in_bps;
810 * How much outbound bandwidth are we supposed to be using per second?
812 static unsigned long long bandwidth_target_out_bps;
815 * Derive an authentication key from "set key" information
818 derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
819 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
820 struct GNUNET_TIME_Absolute creation_time)
822 static const char ctx[] = "authentication key";
823 struct GNUNET_TIME_AbsoluteNBO ctbe;
826 ctbe = GNUNET_TIME_absolute_hton (creation_time);
827 GNUNET_CRYPTO_hmac_derive_key (akey, skey, &seed, sizeof (seed), &skey->key,
828 sizeof (skey->key), &ctbe, sizeof (ctbe), ctx,
834 * Derive an IV from packet information
837 derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
838 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
839 const struct GNUNET_PeerIdentity *identity)
841 static const char ctx[] = "initialization vector";
843 GNUNET_CRYPTO_aes_derive_iv (iv, skey, &seed, sizeof (seed),
844 &identity->hashPubKey.bits,
845 sizeof (identity->hashPubKey.bits), ctx,
850 * Derive an IV from pong packet information
853 derive_pong_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
854 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
855 uint32_t challenge, const struct GNUNET_PeerIdentity *identity)
857 static const char ctx[] = "pong initialization vector";
859 GNUNET_CRYPTO_aes_derive_iv (iv, skey, &seed, sizeof (seed),
860 &identity->hashPubKey.bits,
861 sizeof (identity->hashPubKey.bits), &challenge,
862 sizeof (challenge), ctx, sizeof (ctx), NULL);
867 * At what time should the connection to the given neighbour
868 * time out (given no further activity?)
870 * @param n neighbour in question
871 * @return absolute timeout
873 static struct GNUNET_TIME_Absolute
874 get_neighbour_timeout (struct Neighbour *n)
876 return GNUNET_TIME_absolute_add (n->last_activity,
877 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
882 * Find the entry for the given neighbour.
884 * @param peer identity of the neighbour
885 * @return NULL if we are not connected, otherwise the
888 static struct Neighbour *
889 find_neighbour (const struct GNUNET_PeerIdentity *peer)
891 return GNUNET_CONTAINER_multihashmap_get (neighbours, &peer->hashPubKey);
896 * Send a message to one of our clients.
898 * @param client target for the message
899 * @param msg message to transmit
900 * @param can_drop could this message be dropped if the
901 * client's queue is getting too large?
904 send_to_client (struct Client *client, const struct GNUNET_MessageHeader *msg,
907 #if DEBUG_CORE_CLIENT
908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
909 "Preparing to send %u bytes of message of type %u to client.\n",
910 (unsigned int) ntohs (msg->size),
911 (unsigned int) ntohs (msg->type));
913 GNUNET_SERVER_notification_context_unicast (notifier, client->client_handle,
919 * Send a message to all of our current clients that have
920 * the right options set.
922 * @param msg message to multicast
923 * @param can_drop can this message be discarded if the queue is too long
924 * @param options mask to use
927 send_to_all_clients (const struct GNUNET_MessageHeader *msg, int can_drop,
935 if (0 != (c->options & options))
937 #if DEBUG_CORE_CLIENT > 1
938 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
939 "Sending message of type %u to client.\n",
940 (unsigned int) ntohs (msg->type));
942 send_to_client (c, msg, can_drop);
950 * Function called by transport telling us that a peer
953 * @param n the peer that changed status
956 handle_peer_status_change (struct Neighbour *n)
958 struct PeerStatusNotifyMessage *psnm;
959 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
960 struct GNUNET_ATS_Information *ats;
963 if ((!n->is_connected) || (n->status != PEER_STATE_KEY_CONFIRMED))
966 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%4s' changed status\n",
967 GNUNET_i2s (&n->peer));
970 sizeof (struct PeerStatusNotifyMessage) +
971 n->ats_count * sizeof (struct GNUNET_ATS_Information);
972 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
975 /* recovery strategy: throw away performance data */
976 GNUNET_array_grow (n->ats, n->ats_count, 0);
978 sizeof (struct PeerStatusNotifyMessage) +
979 n->ats_count * sizeof (struct GNUNET_ATS_Information);
981 psnm = (struct PeerStatusNotifyMessage *) buf;
982 psnm->header.size = htons (size);
983 psnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_STATUS_CHANGE);
984 psnm->timeout = GNUNET_TIME_absolute_hton (get_neighbour_timeout (n));
985 psnm->bandwidth_in = n->bw_in;
986 psnm->bandwidth_out = n->bw_out;
987 psnm->peer = n->peer;
988 psnm->ats_count = htonl (n->ats_count);
991 n->ats_count * sizeof (struct GNUNET_ATS_Information));
992 ats[n->ats_count].type = htonl (0);
993 ats[n->ats_count].value = htonl (0);
994 send_to_all_clients (&psnm->header, GNUNET_YES,
995 GNUNET_CORE_OPTION_SEND_STATUS_CHANGE);
996 GNUNET_STATISTICS_update (stats, gettext_noop ("# peer status changes"), 1,
1002 * Go over our message queue and if it is not too long, go
1003 * over the pending requests from clients for this
1004 * neighbour and send some clients a 'READY' notification.
1006 * @param n which peer to process
1009 schedule_peer_messages (struct Neighbour *n)
1011 struct SendMessageReady smr;
1012 struct ClientActiveRequest *car;
1013 struct ClientActiveRequest *pos;
1015 struct MessageEntry *mqe;
1016 unsigned int queue_size;
1018 /* check if neighbour queue is empty enough! */
1028 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1030 #if DEBUG_CORE_CLIENT
1031 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1032 "Not considering client transmission requests: queue full\n");
1034 return; /* queue still full */
1036 /* find highest priority request */
1037 pos = n->active_client_request_head;
1041 if ((car == NULL) || (pos->priority > car->priority))
1048 car = n->active_client_request_head;
1051 return; /* no pending requests */
1052 #if DEBUG_CORE_CLIENT
1053 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1054 "Permitting client transmission request to `%s'\n",
1055 GNUNET_i2s (&n->peer));
1058 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1059 n->active_client_request_tail, car);
1060 GNUNET_assert (GNUNET_YES ==
1061 GNUNET_CONTAINER_multihashmap_remove (c->requests,
1062 &n->peer.hashPubKey,
1064 smr.header.size = htons (sizeof (struct SendMessageReady));
1065 smr.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND_READY);
1066 smr.size = htons (car->msize);
1067 smr.smr_id = car->smr_id;
1069 send_to_client (c, &smr.header, GNUNET_NO);
1075 * Compute a type map message for this peer.
1077 * @return this peers current type map message.
1079 static struct GNUNET_MessageHeader *
1080 compute_type_map_message ()
1084 struct GNUNET_MessageHeader *hdr;
1086 #ifdef compressBound
1087 dlen = compressBound (sizeof (my_type_map));
1089 dlen = sizeof (my_type_map) + (sizeof (my_type_map) / 100) + 20;
1090 /* documentation says 100.1% oldSize + 12 bytes, but we
1091 * should be able to overshoot by more to be safe */
1093 hdr = GNUNET_malloc (dlen + sizeof (struct GNUNET_MessageHeader));
1094 hdr->size = htons ((uint16_t) dlen + sizeof (struct GNUNET_MessageHeader));
1095 tmp = (char *) &hdr[1];
1097 compress2 ((Bytef *) tmp, &dlen, (const Bytef *) my_type_map,
1098 sizeof (my_type_map), 9)) || (dlen >= sizeof (my_type_map)))
1100 dlen = sizeof (my_type_map);
1101 memcpy (tmp, my_type_map, sizeof (my_type_map));
1102 hdr->type = htons (GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP);
1106 hdr->type = htons (GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP);
1113 * Send a type map message to the neighbour.
1115 * @param cls the type map message
1116 * @param key neighbour's identity
1117 * @param value 'struct Neighbour' of the target
1118 * @return always GNUNET_OK
1121 send_type_map_to_neighbour (void *cls, const GNUNET_HashCode * key, void *value)
1123 struct GNUNET_MessageHeader *hdr = cls;
1124 struct Neighbour *n = value;
1125 struct MessageEntry *m;
1130 size = ntohs (hdr->size);
1131 m = GNUNET_malloc (sizeof (struct MessageEntry) + size);
1132 memcpy (&m[1], hdr, size);
1133 m->deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1134 m->slack_deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1135 m->priority = UINT_MAX;
1136 m->sender_status = n->status;
1138 m->next = n->messages;
1146 * Send my type map to all connected peers (it got changed).
1149 broadcast_my_type_map ()
1151 struct GNUNET_MessageHeader *hdr;
1153 if (NULL == neighbours)
1155 hdr = compute_type_map_message ();
1156 GNUNET_CONTAINER_multihashmap_iterate (neighbours,
1157 &send_type_map_to_neighbour, hdr);
1163 * Handle CORE_SEND_REQUEST message.
1166 handle_client_send_request (void *cls, struct GNUNET_SERVER_Client *client,
1167 const struct GNUNET_MessageHeader *message)
1169 const struct SendMessageRequest *req;
1170 struct Neighbour *n;
1172 struct ClientActiveRequest *car;
1174 req = (const struct SendMessageRequest *) message;
1176 memcmp (&req->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
1179 n = find_neighbour (&req->peer);
1180 if ((n == NULL) || (GNUNET_YES != n->is_connected) ||
1181 (n->status != PEER_STATE_KEY_CONFIRMED))
1183 /* neighbour must have disconnected since request was issued,
1184 * ignore (client will realize it once it processes the
1185 * disconnect notification) */
1186 #if DEBUG_CORE_CLIENT
1187 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1188 "Dropped client request for transmission (am disconnected)\n");
1190 GNUNET_STATISTICS_update (stats,
1192 ("# send requests dropped (disconnected)"), 1,
1194 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1198 while ((c != NULL) && (c->client_handle != client))
1202 /* client did not send INIT first! */
1204 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1207 if (c->requests == NULL)
1208 c->requests = GNUNET_CONTAINER_multihashmap_create (16);
1209 #if DEBUG_CORE_CLIENT
1210 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1211 "Received client transmission request. queueing\n");
1213 car = GNUNET_CONTAINER_multihashmap_get (c->requests, &req->peer.hashPubKey);
1216 /* create new entry */
1217 car = GNUNET_malloc (sizeof (struct ClientActiveRequest));
1218 GNUNET_assert (GNUNET_OK ==
1219 GNUNET_CONTAINER_multihashmap_put (c->requests,
1220 &req->peer.hashPubKey,
1222 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1223 GNUNET_CONTAINER_DLL_insert (n->active_client_request_head,
1224 n->active_client_request_tail, car);
1227 car->deadline = GNUNET_TIME_absolute_ntoh (req->deadline);
1228 car->priority = ntohl (req->priority);
1229 car->queue_size = ntohl (req->queue_size);
1230 car->msize = ntohs (req->size);
1231 car->smr_id = req->smr_id;
1232 schedule_peer_messages (n);
1233 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1238 * Notify client about an existing connection to one of our neighbours.
1241 notify_client_about_neighbour (void *cls, const GNUNET_HashCode * key,
1244 struct Client *c = cls;
1245 struct Neighbour *n = value;
1247 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1248 struct GNUNET_ATS_Information *ats;
1249 struct ConnectNotifyMessage *cnm;
1252 sizeof (struct ConnectNotifyMessage) +
1253 (n->ats_count) * sizeof (struct GNUNET_ATS_Information);
1254 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1257 /* recovery strategy: throw away performance data */
1258 GNUNET_array_grow (n->ats, n->ats_count, 0);
1260 sizeof (struct ConnectNotifyMessage) +
1261 (n->ats_count) * sizeof (struct GNUNET_ATS_Information);
1263 cnm = (struct ConnectNotifyMessage *) buf;
1264 cnm->header.size = htons (size);
1265 cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1266 cnm->ats_count = htonl (n->ats_count);
1268 memcpy (ats, n->ats,
1269 sizeof (struct GNUNET_ATS_Information) * n->ats_count);
1270 ats[n->ats_count].type = htonl (GNUNET_ATS_ARRAY_TERMINATOR);
1271 ats[n->ats_count].value = htonl (0);
1272 if (n->status == PEER_STATE_KEY_CONFIRMED)
1274 #if DEBUG_CORE_CLIENT
1275 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message to client.\n",
1278 cnm->peer = n->peer;
1279 send_to_client (c, &cnm->header, GNUNET_NO);
1287 * Handle CORE_INIT request.
1290 handle_client_init (void *cls, struct GNUNET_SERVER_Client *client,
1291 const struct GNUNET_MessageHeader *message)
1293 const struct InitMessage *im;
1294 struct InitReplyMessage irm;
1297 const uint16_t *types;
1301 #if DEBUG_CORE_CLIENT
1302 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1303 "Client connecting to core service with `%s' message\n", "INIT");
1305 /* check that we don't have an entry already */
1309 if (client == c->client_handle)
1312 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1317 msize = ntohs (message->size);
1318 if (msize < sizeof (struct InitMessage))
1321 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1324 GNUNET_SERVER_notification_context_add (notifier, client);
1325 im = (const struct InitMessage *) message;
1326 types = (const uint16_t *) &im[1];
1327 msize -= sizeof (struct InitMessage);
1328 c = GNUNET_malloc (sizeof (struct Client) + msize);
1329 c->client_handle = client;
1332 c->tcnt = msize / sizeof (uint16_t);
1333 c->types = (const uint16_t *) &c[1];
1334 wtypes = (uint16_t *) & c[1];
1335 for (i = 0; i < c->tcnt; i++)
1337 wtypes[i] = ntohs (types[i]);
1338 my_type_map[wtypes[i] / 32] |= (1 << (wtypes[i] % 32));
1341 broadcast_my_type_map ();
1342 c->options = ntohl (im->options);
1343 #if DEBUG_CORE_CLIENT
1344 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1345 "Client %p is interested in %u message types\n", c,
1346 (unsigned int) c->tcnt);
1348 /* send init reply message */
1349 irm.header.size = htons (sizeof (struct InitReplyMessage));
1350 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
1351 irm.reserved = htonl (0);
1352 irm.my_identity = my_identity;
1353 #if DEBUG_CORE_CLIENT
1354 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message to client.\n",
1357 send_to_client (c, &irm.header, GNUNET_NO);
1358 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
1360 /* notify new client about existing neighbours */
1361 GNUNET_CONTAINER_multihashmap_iterate (neighbours,
1362 ¬ify_client_about_neighbour, c);
1364 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1369 * Free client request records.
1372 * @param key identity of peer for which this is an active request
1373 * @param value the 'struct ClientActiveRequest' to free
1374 * @return GNUNET_YES (continue iteration)
1377 destroy_active_client_request (void *cls, const GNUNET_HashCode * key,
1380 struct ClientActiveRequest *car = value;
1381 struct Neighbour *n;
1382 struct GNUNET_PeerIdentity peer;
1384 peer.hashPubKey = *key;
1385 n = find_neighbour (&peer);
1386 GNUNET_assert (NULL != n);
1387 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1388 n->active_client_request_tail, car);
1395 * A client disconnected, clean up.
1397 * @param cls closure
1398 * @param client identification of the client
1401 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1404 struct Client *prev;
1406 const uint16_t *wtypes;
1410 #if DEBUG_CORE_CLIENT
1411 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1412 "Client %p has disconnected from core service.\n", client);
1418 if (client == pos->client_handle)
1425 /* client never sent INIT */
1429 clients = pos->next;
1431 prev->next = pos->next;
1432 if (pos->requests != NULL)
1434 GNUNET_CONTAINER_multihashmap_iterate (pos->requests,
1435 &destroy_active_client_request,
1437 GNUNET_CONTAINER_multihashmap_destroy (pos->requests);
1441 /* rebuild my_type_map */
1442 memset (my_type_map, 0, sizeof (my_type_map));
1443 for (pos = clients; NULL != pos; pos = pos->next)
1445 wtypes = (const uint16_t *) &pos[1];
1446 for (i = 0; i < pos->tcnt; i++)
1447 my_type_map[wtypes[i] / 32] |= (1 << (wtypes[i] % 32));
1449 broadcast_my_type_map ();
1454 * Helper function for handle_client_iterate_peers.
1456 * @param cls the 'struct GNUNET_SERVER_TransmitContext' to queue replies
1457 * @param key identity of the connected peer
1458 * @param value the 'struct Neighbour' for the peer
1459 * @return GNUNET_OK (continue to iterate)
1462 queue_connect_message (void *cls, const GNUNET_HashCode * key, void *value)
1464 struct GNUNET_SERVER_TransmitContext *tc = cls;
1465 struct Neighbour *n = value;
1466 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1467 struct GNUNET_ATS_Information *ats;
1469 struct ConnectNotifyMessage *cnm;
1471 cnm = (struct ConnectNotifyMessage *) buf;
1472 if (n->status != PEER_STATE_KEY_CONFIRMED)
1475 sizeof (struct ConnectNotifyMessage) +
1476 (n->ats_count) * sizeof (struct GNUNET_ATS_Information);
1477 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1480 /* recovery strategy: throw away performance data */
1481 GNUNET_array_grow (n->ats, n->ats_count, 0);
1483 sizeof (struct PeerStatusNotifyMessage) +
1484 n->ats_count * sizeof (struct GNUNET_ATS_Information);
1486 cnm = (struct ConnectNotifyMessage *) buf;
1487 cnm->header.size = htons (size);
1488 cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1489 cnm->ats_count = htonl (n->ats_count);
1491 memcpy (ats, n->ats,
1492 n->ats_count * sizeof (struct GNUNET_ATS_Information));
1493 ats[n->ats_count].type = htonl (GNUNET_ATS_ARRAY_TERMINATOR);
1494 ats[n->ats_count].value = htonl (0);
1495 #if DEBUG_CORE_CLIENT
1496 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message to client.\n",
1499 cnm->peer = n->peer;
1500 GNUNET_SERVER_transmit_context_append_message (tc, &cnm->header);
1506 * Handle CORE_ITERATE_PEERS request.
1509 * @param client client sending the iteration request
1510 * @param message iteration request message
1513 handle_client_iterate_peers (void *cls, struct GNUNET_SERVER_Client *client,
1514 const struct GNUNET_MessageHeader *message)
1516 struct GNUNET_MessageHeader done_msg;
1517 struct GNUNET_SERVER_TransmitContext *tc;
1520 /* notify new client about existing neighbours */
1522 msize = ntohs (message->size);
1523 tc = GNUNET_SERVER_transmit_context_create (client);
1524 if (msize == sizeof (struct GNUNET_MessageHeader))
1525 GNUNET_CONTAINER_multihashmap_iterate (neighbours, &queue_connect_message,
1530 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
1531 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
1532 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
1533 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
1538 * Handle CORE_PEER_CONNECTED request. Notify client about existing neighbours.
1541 * @param client client sending the iteration request
1542 * @param message iteration request message
1545 handle_client_have_peer (void *cls, struct GNUNET_SERVER_Client *client,
1546 const struct GNUNET_MessageHeader *message)
1548 struct GNUNET_MessageHeader done_msg;
1549 struct GNUNET_SERVER_TransmitContext *tc;
1550 struct GNUNET_PeerIdentity *peer;
1552 tc = GNUNET_SERVER_transmit_context_create (client);
1553 peer = (struct GNUNET_PeerIdentity *) &message[1];
1554 GNUNET_CONTAINER_multihashmap_get_multiple (neighbours, &peer->hashPubKey,
1555 &queue_connect_message, tc);
1556 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
1557 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
1558 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
1559 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
1564 * Free the given entry for the neighbour (it has
1565 * already been removed from the list at this point).
1567 * @param n neighbour to free
1570 free_neighbour (struct Neighbour *n)
1572 struct MessageEntry *m;
1573 struct ClientActiveRequest *car;
1576 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1577 "Destroying neighbour entry for peer `%4s'\n",
1578 GNUNET_i2s (&n->peer));
1580 if (n->pitr != NULL)
1582 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1587 GNUNET_free (n->skm);
1590 while (NULL != (m = n->messages))
1592 n->messages = m->next;
1595 while (NULL != (m = n->encrypted_head))
1597 GNUNET_CONTAINER_DLL_remove (n->encrypted_head, n->encrypted_tail, m);
1600 while (NULL != (car = n->active_client_request_head))
1602 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1603 n->active_client_request_tail, car);
1604 GNUNET_assert (GNUNET_YES ==
1605 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
1606 &n->peer.hashPubKey,
1612 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1615 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1616 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
1617 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1618 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
1619 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1620 GNUNET_SCHEDULER_cancel (n->quota_update_task);
1621 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1622 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1623 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1624 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
1625 if (n->status == PEER_STATE_KEY_CONFIRMED)
1626 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"),
1628 GNUNET_array_grow (n->ats, n->ats_count, 0);
1629 GNUNET_free_non_null (n->public_key);
1630 GNUNET_free_non_null (n->pending_ping);
1631 GNUNET_free_non_null (n->pending_pong);
1637 * Check if we have encrypted messages for the specified neighbour
1638 * pending, and if so, check with the transport about sending them
1641 * @param n neighbour to check.
1644 process_encrypted_neighbour_queue (struct Neighbour *n);
1648 * Encrypt size bytes from in and write the result to out. Use the
1649 * key for outbound traffic of the given neighbour.
1651 * @param n neighbour we are sending to
1652 * @param iv initialization vector to use
1653 * @param in ciphertext
1654 * @param out plaintext
1655 * @param size size of in/out
1656 * @return GNUNET_OK on success
1659 do_encrypt (struct Neighbour *n,
1660 const struct GNUNET_CRYPTO_AesInitializationVector *iv,
1661 const void *in, void *out, size_t size)
1663 if (size != (uint16_t) size)
1668 GNUNET_assert (size ==
1669 GNUNET_CRYPTO_aes_encrypt (in, (uint16_t) size,
1670 &n->encrypt_key, iv, out));
1671 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size,
1674 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1675 "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
1676 (unsigned int) size, GNUNET_i2s (&n->peer),
1677 (unsigned int) n->encrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
1686 * Consider freeing the given neighbour since we may not need
1687 * to keep it around anymore.
1689 * @param n neighbour to consider discarding
1692 consider_free_neighbour (struct Neighbour *n);
1696 * Task triggered when a neighbour entry is about to time out
1697 * (and we should prevent this by sending a PING).
1699 * @param cls the 'struct Neighbour'
1700 * @param tc scheduler context (not used)
1703 send_keep_alive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1705 struct Neighbour *n = cls;
1706 struct GNUNET_TIME_Relative retry;
1707 struct GNUNET_TIME_Relative left;
1708 struct MessageEntry *me;
1709 struct PingMessage pp;
1710 struct PingMessage *pm;
1711 struct GNUNET_CRYPTO_AesInitializationVector iv;
1713 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1715 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1716 sizeof (struct PingMessage));
1717 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1718 me->priority = PING_PRIORITY;
1719 me->size = sizeof (struct PingMessage);
1720 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head, n->encrypted_tail,
1721 n->encrypted_tail, me);
1722 pm = (struct PingMessage *) &me[1];
1723 pm->header.size = htons (sizeof (struct PingMessage));
1724 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1726 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1727 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
1728 pp.challenge = n->ping_challenge;
1729 pp.target = n->peer;
1731 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1732 "Encrypting `%s' message with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
1733 "PING", (unsigned int) n->ping_challenge, GNUNET_i2s (&n->peer),
1734 (unsigned int) n->encrypt_key.crc32, GNUNET_CRYPTO_crc32_n (&iv,
1739 do_encrypt (n, &iv, &pp.target, &pm->target,
1740 sizeof (struct PingMessage) - ((void *) &pm->target -
1742 process_encrypted_neighbour_queue (n);
1743 /* reschedule PING job */
1744 left = GNUNET_TIME_absolute_get_remaining (get_neighbour_timeout (n));
1746 GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1747 MIN_PING_FREQUENCY);
1748 n->keep_alive_task =
1749 GNUNET_SCHEDULER_add_delayed (retry, &send_keep_alive, n);
1755 * Task triggered when a neighbour entry might have gotten stale.
1757 * @param cls the 'struct Neighbour'
1758 * @param tc scheduler context (not used)
1761 consider_free_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1763 struct Neighbour *n = cls;
1765 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1766 consider_free_neighbour (n);
1771 * Consider freeing the given neighbour since we may not need
1772 * to keep it around anymore.
1774 * @param n neighbour to consider discarding
1777 consider_free_neighbour (struct Neighbour *n)
1779 struct GNUNET_TIME_Relative left;
1781 if ((n->th != NULL) || (n->pitr != NULL) || (GNUNET_YES == n->is_connected))
1782 return; /* no chance */
1784 left = GNUNET_TIME_absolute_get_remaining (get_neighbour_timeout (n));
1785 if (left.rel_value > 0)
1787 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1788 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1789 n->dead_clean_task =
1790 GNUNET_SCHEDULER_add_delayed (left, &consider_free_task, n);
1793 /* actually free the neighbour... */
1794 GNUNET_assert (GNUNET_YES ==
1795 GNUNET_CONTAINER_multihashmap_remove (neighbours,
1796 &n->peer.hashPubKey, n));
1797 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"),
1798 GNUNET_CONTAINER_multihashmap_size (neighbours),
1805 * Function called when the transport service is ready to
1806 * receive an encrypted message for the respective peer
1808 * @param cls neighbour to use message from
1809 * @param size number of bytes we can transmit
1810 * @param buf where to copy the message
1811 * @return number of bytes transmitted
1814 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1816 struct Neighbour *n = cls;
1817 struct MessageEntry *m;
1822 m = n->encrypted_head;
1826 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1827 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1828 GNUNET_i2s (&n->peer));
1832 GNUNET_CONTAINER_DLL_remove (n->encrypted_head, n->encrypted_tail, m);
1837 GNUNET_assert (size >= m->size);
1838 memcpy (cbuf, &m[1], m->size);
1840 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window, m->size);
1842 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1843 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1845 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1846 (unsigned int) ret, GNUNET_i2s (&n->peer));
1848 process_encrypted_neighbour_queue (n);
1853 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1854 "Transmission of message of type %u and size %u failed\n",
1856 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1857 (unsigned int) m->size);
1861 consider_free_neighbour (n);
1862 GNUNET_STATISTICS_update (stats,
1864 ("# encrypted bytes given to transport"), ret,
1871 * Check if we have plaintext messages for the specified neighbour
1872 * pending, and if so, consider batching and encrypting them (and
1873 * then trigger processing of the encrypted queue if needed).
1875 * @param n neighbour to check.
1878 process_plaintext_neighbour_queue (struct Neighbour *n);
1882 * Check if we have encrypted messages for the specified neighbour
1883 * pending, and if so, check with the transport about sending them
1886 * @param n neighbour to check.
1889 process_encrypted_neighbour_queue (struct Neighbour *n)
1891 struct MessageEntry *m;
1894 return; /* request already pending */
1895 if (GNUNET_YES != n->is_connected)
1900 m = n->encrypted_head;
1903 /* encrypted queue empty, try plaintext instead */
1904 process_plaintext_neighbour_queue (n);
1908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1909 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1910 (unsigned int) m->size, GNUNET_i2s (&n->peer),
1911 (unsigned long long)
1912 GNUNET_TIME_absolute_get_remaining (m->deadline).rel_value);
1915 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer, m->size,
1917 GNUNET_TIME_absolute_get_remaining
1919 ¬ify_encrypted_transmit_ready,
1923 /* message request too large or duplicate request */
1925 /* discard encrypted message */
1926 GNUNET_CONTAINER_DLL_remove (n->encrypted_head, n->encrypted_tail, m);
1928 process_encrypted_neighbour_queue (n);
1934 * Decrypt size bytes from in and write the result to out. Use the
1935 * key for inbound traffic of the given neighbour. This function does
1936 * NOT do any integrity-checks on the result.
1938 * @param n neighbour we are receiving from
1939 * @param iv initialization vector to use
1940 * @param in ciphertext
1941 * @param out plaintext
1942 * @param size size of in/out
1943 * @return GNUNET_OK on success
1946 do_decrypt (struct Neighbour *n,
1947 const struct GNUNET_CRYPTO_AesInitializationVector *iv,
1948 const void *in, void *out, size_t size)
1950 if (size != (uint16_t) size)
1955 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1956 (n->status != PEER_STATE_KEY_CONFIRMED))
1958 GNUNET_break_op (0);
1959 return GNUNET_SYSERR;
1962 GNUNET_CRYPTO_aes_decrypt (in, (uint16_t) size, &n->decrypt_key, iv, out))
1965 return GNUNET_SYSERR;
1967 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size,
1970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1971 "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
1972 (unsigned int) size, GNUNET_i2s (&n->peer),
1973 (unsigned int) n->decrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
1982 * Select messages for transmission. This heuristic uses a combination
1983 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1984 * and priority-based discard (in case no feasible schedule exist) and
1985 * speculative optimization (defer any kind of transmission until
1986 * we either create a batch of significant size, 25% of max, or until
1987 * we are close to a deadline). Furthermore, when scheduling the
1988 * heuristic also packs as many messages into the batch as possible,
1989 * starting with those with the earliest deadline. Yes, this is fun.
1991 * @param n neighbour to select messages from
1992 * @param size number of bytes to select for transmission
1993 * @param retry_time set to the time when we should try again
1994 * (only valid if this function returns zero)
1995 * @return number of bytes selected, or 0 if we decided to
1996 * defer scheduling overall; in that case, retry_time is set.
1999 select_messages (struct Neighbour *n, size_t size,
2000 struct GNUNET_TIME_Relative *retry_time)
2002 struct MessageEntry *pos;
2003 struct MessageEntry *min;
2004 struct MessageEntry *last;
2005 unsigned int min_prio;
2006 struct GNUNET_TIME_Absolute t;
2007 struct GNUNET_TIME_Absolute now;
2008 struct GNUNET_TIME_Relative delta;
2010 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
2013 unsigned int queue_size;
2014 int discard_low_prio;
2016 GNUNET_assert (NULL != n->messages);
2017 now = GNUNET_TIME_absolute_get ();
2018 /* last entry in linked list of messages processed */
2020 /* should we remove the entry with the lowest
2021 * priority from consideration for scheduling at the
2022 * end of the loop? */
2032 discard_low_prio = GNUNET_YES;
2033 while (GNUNET_YES == discard_low_prio)
2036 min_prio = UINT_MAX;
2037 discard_low_prio = GNUNET_NO;
2038 /* calculate number of bytes available for transmission at time "t" */
2039 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
2041 /* how many bytes have we (hypothetically) scheduled so far */
2043 /* maximum time we can wait before transmitting anything
2044 * and still make all of our deadlines */
2045 slack = GNUNET_TIME_UNIT_FOREVER_REL;
2047 /* note that we use "*2" here because we want to look
2048 * a bit further into the future; much more makes no
2049 * sense since new message might be scheduled in the
2051 while ((pos != NULL) && (off < size * 2))
2053 if (pos->do_transmit == GNUNET_YES)
2055 /* already removed from consideration */
2059 if (discard_low_prio == GNUNET_NO)
2061 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
2062 if (delta.rel_value > 0)
2064 // FIXME: HUH? Check!
2067 GNUNET_BANDWIDTH_value_get_available_until (n->bw_out, delta);
2069 if (avail < pos->size)
2071 // FIXME: HUH? Check!
2072 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
2077 /* update slack, considering both its absolute deadline
2078 * and relative deadlines caused by other messages
2079 * with their respective load */
2081 GNUNET_TIME_relative_min (slack,
2082 GNUNET_BANDWIDTH_value_get_delay_for
2083 (n->bw_out, avail));
2084 if (pos->deadline.abs_value <= now.abs_value)
2087 slack = GNUNET_TIME_UNIT_ZERO;
2089 else if (GNUNET_YES == pos->got_slack)
2091 /* should be soon now! */
2093 GNUNET_TIME_relative_min (slack,
2094 GNUNET_TIME_absolute_get_remaining
2095 (pos->slack_deadline));
2100 GNUNET_TIME_relative_min (slack,
2101 GNUNET_TIME_absolute_get_difference
2102 (now, pos->deadline));
2103 pos->got_slack = GNUNET_YES;
2104 pos->slack_deadline =
2105 GNUNET_TIME_absolute_min (pos->deadline,
2106 GNUNET_TIME_relative_to_absolute
2107 (GNUNET_CONSTANTS_MAX_CORK_DELAY));
2112 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
2113 if (pos->priority <= min_prio)
2115 /* update min for discard */
2116 min_prio = pos->priority;
2121 if (discard_low_prio)
2123 GNUNET_assert (min != NULL);
2124 /* remove lowest-priority entry from consideration */
2125 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
2129 /* guard against sending "tiny" messages with large headers without
2130 * urgent deadlines */
2131 if ((slack.rel_value > GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value) &&
2132 (size > 4 * off) && (queue_size <= MAX_PEER_QUEUE_SIZE - 2))
2134 /* less than 25% of message would be filled with deadlines still
2135 * being met if we delay by one second or more; so just wait for
2136 * more data; but do not wait longer than 1s (since we don't want
2137 * to delay messages for a really long time either). */
2138 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
2139 /* reset do_transmit values for next time */
2142 pos->do_transmit = GNUNET_NO;
2145 GNUNET_STATISTICS_update (stats,
2147 ("# transmissions delayed due to corking"), 1,
2150 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2151 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
2152 (unsigned long long) retry_time->rel_value, (unsigned int) off,
2153 (unsigned int) size);
2157 /* select marked messages (up to size) for transmission */
2162 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
2164 pos->do_transmit = GNUNET_YES; /* mark for transmission */
2168 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2169 "Selecting message of size %u for transmission\n",
2170 (unsigned int) pos->size);
2176 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2177 "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
2178 (unsigned int) pos->size, size);
2180 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
2185 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2186 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
2187 (unsigned long long) off, (unsigned long long) tsize, queue_size,
2188 (unsigned int) MAX_PEER_QUEUE_SIZE, GNUNET_i2s (&n->peer));
2195 * Batch multiple messages into a larger buffer.
2197 * @param n neighbour to take messages from
2198 * @param buf target buffer
2199 * @param size size of buf
2200 * @param deadline set to transmission deadline for the result
2201 * @param retry_time set to the time when we should try again
2202 * (only valid if this function returns zero)
2203 * @param priority set to the priority of the batch
2204 * @return number of bytes written to buf (can be zero)
2207 batch_message (struct Neighbour *n, char *buf, size_t size,
2208 struct GNUNET_TIME_Absolute *deadline,
2209 struct GNUNET_TIME_Relative *retry_time, unsigned int *priority)
2211 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
2212 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage *) ntmb;
2213 struct MessageEntry *pos;
2214 struct MessageEntry *prev;
2215 struct MessageEntry *next;
2220 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2221 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
2222 if (0 == select_messages (n, size, retry_time))
2225 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2226 "No messages selected, will try again in %llu ms\n",
2227 retry_time->rel_value);
2231 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
2232 ntm->ats_count = htonl (0);
2233 ntm->ats.type = htonl (0);
2234 ntm->ats.value = htonl (0);
2235 ntm->peer = n->peer;
2238 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
2241 if (GNUNET_YES == pos->do_transmit)
2243 GNUNET_assert (pos->size <= size);
2244 /* do notifications */
2245 /* FIXME: track if we have *any* client that wants
2246 * full notifications and only do this if that is
2249 GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
2251 memcpy (&ntm[1], &pos[1], pos->size);
2253 htons (sizeof (struct NotifyTrafficMessage) +
2254 sizeof (struct GNUNET_MessageHeader));
2255 send_to_all_clients (&ntm->header, GNUNET_YES,
2256 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
2260 /* message too large for 'full' notifications, we do at
2261 * least the 'hdr' type */
2262 memcpy (&ntm[1], &pos[1], sizeof (struct GNUNET_MessageHeader));
2265 htons (sizeof (struct NotifyTrafficMessage) + pos->size);
2266 send_to_all_clients (&ntm->header, GNUNET_YES,
2267 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
2269 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2270 "Encrypting %u bytes with message of type %u and size %u\n",
2273 ntohs (((const struct GNUNET_MessageHeader *) &pos[1])->type),
2275 ntohs (((const struct GNUNET_MessageHeader *)
2278 /* copy for encrypted transmission */
2279 memcpy (&buf[ret], &pos[1], pos->size);
2282 *priority += pos->priority;
2284 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2285 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
2286 (unsigned int) pos->size,
2287 (unsigned long long)
2288 GNUNET_TIME_absolute_get_remaining (pos->deadline).rel_value);
2290 deadline->abs_value =
2291 GNUNET_MIN (deadline->abs_value, pos->deadline.abs_value);
2305 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2306 "Deadline for message batch is %llu ms\n",
2307 GNUNET_TIME_absolute_get_remaining (*deadline).rel_value);
2314 * Remove messages with deadlines that have long expired from
2317 * @param n neighbour to inspect
2320 discard_expired_messages (struct Neighbour *n)
2322 struct MessageEntry *prev;
2323 struct MessageEntry *next;
2324 struct MessageEntry *pos;
2325 struct GNUNET_TIME_Absolute now;
2326 struct GNUNET_TIME_Relative delta;
2328 unsigned int queue_length;
2331 now = GNUNET_TIME_absolute_get ();
2339 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
2340 if (delta.rel_value > PAST_EXPIRATION_DISCARD_TIME.rel_value)
2343 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2344 "Message is %llu ms past due, discarding.\n",
2351 GNUNET_STATISTICS_update (stats,
2353 ("# messages discarded (expired prior to transmission)"),
2362 if ( (GNUNET_YES == disc) &&
2363 (queue_length == MAX_PEER_QUEUE_SIZE) )
2364 schedule_peer_messages (n);
2369 * Signature of the main function of a task.
2371 * @param cls closure
2372 * @param tc context information (why was this task triggered now)
2375 retry_plaintext_processing (void *cls,
2376 const struct GNUNET_SCHEDULER_TaskContext *tc)
2378 struct Neighbour *n = cls;
2380 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2381 process_plaintext_neighbour_queue (n);
2386 * Send our key (and encrypted PING) to the other peer.
2388 * @param n the other peer
2391 send_key (struct Neighbour *n);
2394 * Task that will retry "send_key" if our previous attempt failed
2398 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2400 struct Neighbour *n = cls;
2403 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Retrying key transmission to `%4s'\n",
2404 GNUNET_i2s (&n->peer));
2406 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2407 n->set_key_retry_frequency =
2408 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2414 * Check if we have plaintext messages for the specified neighbour
2415 * pending, and if so, consider batching and encrypting them (and
2416 * then trigger processing of the encrypted queue if needed).
2418 * @param n neighbour to check.
2421 process_plaintext_neighbour_queue (struct Neighbour *n)
2423 char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)]; /* plaintext */
2425 struct EncryptedMessage *em; /* encrypted message */
2426 struct EncryptedMessage *ph; /* plaintext header */
2427 struct MessageEntry *me;
2428 unsigned int priority;
2429 struct GNUNET_TIME_Absolute deadline;
2430 struct GNUNET_TIME_Relative retry_time;
2431 struct GNUNET_CRYPTO_AesInitializationVector iv;
2432 struct GNUNET_CRYPTO_AuthKey auth_key;
2434 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2436 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
2437 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2441 case PEER_STATE_DOWN:
2444 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2445 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2446 GNUNET_i2s (&n->peer));
2449 case PEER_STATE_KEY_SENT:
2450 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2451 n->retry_set_key_task =
2452 GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2453 &set_key_retry_task, n);
2455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2456 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2457 GNUNET_i2s (&n->peer));
2460 case PEER_STATE_KEY_RECEIVED:
2461 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2462 n->retry_set_key_task =
2463 GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2464 &set_key_retry_task, n);
2466 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2467 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2468 GNUNET_i2s (&n->peer));
2471 case PEER_STATE_KEY_CONFIRMED:
2472 /* ready to continue */
2475 discard_expired_messages (n);
2476 if (n->messages == NULL)
2479 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2480 "Plaintext message queue for `%4s' is empty.\n",
2481 GNUNET_i2s (&n->peer));
2483 return; /* no pending messages */
2485 if (n->encrypted_head != NULL)
2488 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2489 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2490 GNUNET_i2s (&n->peer));
2492 return; /* wait for messages already encrypted to be
2493 * processed first! */
2495 ph = (struct EncryptedMessage *) pbuf;
2496 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2498 used = sizeof (struct EncryptedMessage);
2500 batch_message (n, &pbuf[used],
2501 GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE, &deadline,
2502 &retry_time, &priority);
2503 if (used == sizeof (struct EncryptedMessage))
2506 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2507 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2508 GNUNET_i2s (&n->peer));
2510 /* no messages selected for sending, try again later... */
2511 n->retry_plaintext_task =
2512 GNUNET_SCHEDULER_add_delayed (retry_time, &retry_plaintext_processing,
2516 #if DEBUG_CORE_QUOTA
2517 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2518 "Sending %u b/s as new limit to peer `%4s'\n",
2519 (unsigned int) ntohl (n->bw_in.value__), GNUNET_i2s (&n->peer));
2522 htonl (GNUNET_CRYPTO_random_u32
2523 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
2524 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2525 ph->inbound_bw_limit = n->bw_in;
2526 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2528 /* setup encryption message header */
2529 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2530 me->deadline = deadline;
2531 me->priority = priority;
2533 em = (struct EncryptedMessage *) &me[1];
2534 em->header.size = htons (used);
2535 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2536 em->iv_seed = ph->iv_seed;
2537 derive_iv (&iv, &n->encrypt_key, ph->iv_seed, &n->peer);
2540 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2541 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2542 (unsigned int) used - ENCRYPTED_HEADER_SIZE,
2543 GNUNET_i2s (&n->peer),
2544 (unsigned long long)
2545 GNUNET_TIME_absolute_get_remaining (deadline).rel_value);
2547 GNUNET_assert (GNUNET_OK ==
2548 do_encrypt (n, &iv, &ph->sequence_number, &em->sequence_number,
2549 used - ENCRYPTED_HEADER_SIZE));
2550 derive_auth_key (&auth_key, &n->encrypt_key, ph->iv_seed,
2551 n->encrypt_key_created);
2552 GNUNET_CRYPTO_hmac (&auth_key, &em->sequence_number,
2553 used - ENCRYPTED_HEADER_SIZE, &em->hmac);
2555 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2556 "Authenticated %u bytes of ciphertext %u: `%s'\n",
2557 used - ENCRYPTED_HEADER_SIZE,
2558 GNUNET_CRYPTO_crc32_n (&em->sequence_number,
2559 used - ENCRYPTED_HEADER_SIZE),
2560 GNUNET_h2s (&em->hmac));
2562 /* append to transmission list */
2563 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head, n->encrypted_tail,
2564 n->encrypted_tail, me);
2565 process_encrypted_neighbour_queue (n);
2566 schedule_peer_messages (n);
2571 * Function that recalculates the bandwidth quota for the
2572 * given neighbour and transmits it to the transport service.
2574 * @param cls neighbour for the quota update
2578 neighbour_quota_update (void *cls,
2579 const struct GNUNET_SCHEDULER_TaskContext *tc);
2583 * Schedule the task that will recalculate the bandwidth
2584 * quota for this peer (and possibly force a disconnect of
2585 * idle peers by calculating a bandwidth of zero).
2588 schedule_quota_update (struct Neighbour *n)
2590 GNUNET_assert (n->quota_update_task == GNUNET_SCHEDULER_NO_TASK);
2591 n->quota_update_task =
2592 GNUNET_SCHEDULER_add_delayed (QUOTA_UPDATE_FREQUENCY,
2593 &neighbour_quota_update, n);
2598 * Initialize a new 'struct Neighbour'.
2600 * @param pid ID of the new neighbour
2601 * @return handle for the new neighbour
2603 static struct Neighbour *
2604 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2606 struct Neighbour *n;
2607 struct GNUNET_TIME_Absolute now;
2610 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2611 "Creating neighbour entry for peer `%4s'\n", GNUNET_i2s (pid));
2613 n = GNUNET_malloc (sizeof (struct Neighbour));
2615 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2616 now = GNUNET_TIME_absolute_get ();
2617 n->encrypt_key_created = now;
2618 n->last_activity = now;
2619 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2620 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2621 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2622 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2623 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2625 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2626 GNUNET_assert (GNUNET_OK ==
2627 GNUNET_CONTAINER_multihashmap_put (neighbours,
2628 &n->peer.hashPubKey, n,
2629 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2630 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"),
2631 GNUNET_CONTAINER_multihashmap_size (neighbours),
2633 neighbour_quota_update (n, NULL);
2634 consider_free_neighbour (n);
2640 * Handle CORE_SEND request.
2643 * @param client the client issuing the request
2644 * @param message the "struct SendMessage"
2647 handle_client_send (void *cls, struct GNUNET_SERVER_Client *client,
2648 const struct GNUNET_MessageHeader *message)
2650 const struct SendMessage *sm;
2651 struct Neighbour *n;
2652 struct MessageEntry *prev;
2653 struct MessageEntry *pos;
2654 struct MessageEntry *e;
2655 struct MessageEntry *min_prio_entry;
2656 struct MessageEntry *min_prio_prev;
2657 unsigned int min_prio;
2658 unsigned int queue_size;
2661 msize = ntohs (message->size);
2663 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2665 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2666 "msize is %u, should be at least %u (in %s:%d)\n", msize,
2667 sizeof (struct SendMessage) +
2668 sizeof (struct GNUNET_MessageHeader), __FILE__, __LINE__);
2671 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2674 sm = (const struct SendMessage *) message;
2675 msize -= sizeof (struct SendMessage);
2677 memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2680 GNUNET_SERVER_mst_receive (mst, &self, (const char *) &sm[1], msize,
2681 GNUNET_YES, GNUNET_NO);
2683 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2686 n = find_neighbour (&sm->peer);
2687 if ((n == NULL) || (GNUNET_YES != n->is_connected) ||
2688 (n->status != PEER_STATE_KEY_CONFIRMED))
2690 /* attempt to send message to peer that is not connected anymore
2691 * (can happen due to asynchrony) */
2692 GNUNET_STATISTICS_update (stats,
2694 ("# messages discarded (disconnected)"), 1,
2697 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2701 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2702 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2703 "SEND", (unsigned int) msize, GNUNET_i2s (&sm->peer));
2705 discard_expired_messages (n);
2706 /* bound queue size */
2707 /* NOTE: this entire block to bound the queue size should be
2708 * obsolete with the new client-request code and the
2709 * 'schedule_peer_messages' mechanism; we still have this code in
2710 * here for now as a sanity check for the new mechanmism;
2711 * ultimately, we should probably simply reject SEND messages that
2712 * are not 'approved' (or provide a new core API for very unreliable
2713 * delivery that always sends with priority 0). Food for thought. */
2714 min_prio = UINT32_MAX;
2715 min_prio_entry = NULL;
2716 min_prio_prev = NULL;
2722 if (pos->priority <= min_prio)
2724 min_prio_entry = pos;
2725 min_prio_prev = prev;
2726 min_prio = pos->priority;
2732 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2735 if (ntohl (sm->priority) <= min_prio)
2737 /* discard new entry; this should no longer happen! */
2740 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2741 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2742 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
2743 (unsigned int) msize, (unsigned int) ntohs (message->type));
2745 GNUNET_STATISTICS_update (stats,
2746 gettext_noop ("# discarded CORE_SEND requests"),
2750 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2753 GNUNET_assert (min_prio_entry != NULL);
2754 /* discard "min_prio_entry" */
2756 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2757 "Queue full, discarding existing older request\n");
2759 GNUNET_STATISTICS_update (stats,
2761 ("# discarded lower priority CORE_SEND requests"),
2763 if (min_prio_prev == NULL)
2764 n->messages = min_prio_entry->next;
2766 min_prio_prev->next = min_prio_entry->next;
2767 GNUNET_free (min_prio_entry);
2771 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2772 "Adding transmission request for `%4s' of size %u to queue\n",
2773 GNUNET_i2s (&sm->peer), (unsigned int) msize);
2775 GNUNET_break (0 == ntohl (sm->reserved));
2776 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2777 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2778 e->priority = ntohl (sm->priority);
2780 if (GNUNET_YES != (int) ntohl (sm->cork))
2781 e->got_slack = GNUNET_YES;
2782 memcpy (&e[1], &sm[1], msize);
2784 /* insert, keep list sorted by deadline */
2787 while ((pos != NULL) && (pos->deadline.abs_value < e->deadline.abs_value))
2798 /* consider scheduling now */
2799 process_plaintext_neighbour_queue (n);
2801 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2806 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2807 * the neighbour's struct and retry send_key. Or, if we did not get a
2808 * HELLO, just do nothing.
2810 * @param cls the 'struct Neighbour' to retry sending the key for
2811 * @param peer the peer for which this is the HELLO
2812 * @param hello HELLO message of that peer
2813 * @param err_msg NULL if successful, otherwise contains error message
2816 process_hello_retry_send_key (void *cls, const struct GNUNET_PeerIdentity *peer,
2817 const struct GNUNET_HELLO_Message *hello,
2818 const char *err_msg)
2820 struct Neighbour *n = cls;
2822 if (err_msg != NULL)
2824 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2825 _("Error in communication with PEERINFO service\n"));
2832 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Entered `%s' and `%s' is NULL!\n",
2833 "process_hello_retry_send_key", "peer");
2836 if (n->public_key != NULL)
2838 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2840 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2841 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2843 GNUNET_STATISTICS_update (stats,
2845 ("# SET_KEY messages deferred (need public key)"),
2852 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2853 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
2854 GNUNET_i2s (&n->peer));
2856 GNUNET_STATISTICS_update (stats,
2858 ("# Delayed connecting due to lack of public key"),
2860 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2861 n->retry_set_key_task =
2862 GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2863 &set_key_retry_task, n);
2869 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Entered `%s' for peer `%4s'\n",
2870 "process_hello_retry_send_key", GNUNET_i2s (peer));
2872 if (n->public_key != NULL)
2874 /* already have public key, why are we here? */
2880 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2881 "Received new `%s' message for `%4s', initiating key exchange.\n",
2882 "HELLO", GNUNET_i2s (peer));
2885 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2886 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2888 GNUNET_STATISTICS_update (stats,
2890 ("# Error extracting public key from HELLO"), 1,
2892 GNUNET_free (n->public_key);
2893 n->public_key = NULL;
2895 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2896 "GNUNET_HELLO_get_key returned awfully\n");
2904 * Send our key (and encrypted PING) to the other peer.
2906 * @param n the other peer
2909 send_key (struct Neighbour *n)
2911 struct MessageEntry *pos;
2912 struct SetKeyMessage *sm;
2913 struct MessageEntry *me;
2914 struct PingMessage pp;
2915 struct PingMessage *pm;
2916 struct GNUNET_CRYPTO_AesInitializationVector iv;
2918 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2920 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2921 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2923 if (n->pitr != NULL)
2926 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2927 "Key exchange in progress with `%4s'.\n",
2928 GNUNET_i2s (&n->peer));
2930 return; /* already in progress */
2932 if (GNUNET_YES != n->is_connected)
2934 GNUNET_STATISTICS_update (stats,
2936 ("# Asking transport to connect (for SET_KEY)"),
2938 GNUNET_TRANSPORT_try_connect (transport, &n->peer);
2942 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2943 "Asked to perform key exchange with `%4s'.\n",
2944 GNUNET_i2s (&n->peer));
2946 if (n->public_key == NULL)
2948 /* lookup n's public key, then try again */
2950 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2951 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2952 GNUNET_i2s (&n->peer));
2954 GNUNET_assert (n->pitr == NULL);
2956 GNUNET_PEERINFO_iterate (peerinfo, &n->peer,
2957 GNUNET_TIME_relative_multiply
2958 (GNUNET_TIME_UNIT_SECONDS, 20),
2959 &process_hello_retry_send_key, n);
2962 pos = n->encrypted_head;
2965 if (GNUNET_YES == pos->is_setkey)
2967 if (pos->sender_status == n->status)
2970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2971 "`%s' message for `%4s' queued already\n", "SET_KEY",
2972 GNUNET_i2s (&n->peer));
2974 goto trigger_processing;
2976 GNUNET_CONTAINER_DLL_remove (n->encrypted_head, n->encrypted_tail, pos);
2979 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2980 "Removing queued `%s' message for `%4s', will create a new one\n",
2981 "SET_KEY", GNUNET_i2s (&n->peer));
2991 case PEER_STATE_DOWN:
2992 n->status = PEER_STATE_KEY_SENT;
2994 case PEER_STATE_KEY_SENT:
2996 case PEER_STATE_KEY_RECEIVED:
2998 case PEER_STATE_KEY_CONFIRMED:
3006 /* first, set key message */
3007 me = GNUNET_malloc (sizeof (struct MessageEntry) +
3008 sizeof (struct SetKeyMessage) +
3009 sizeof (struct PingMessage));
3010 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
3011 me->priority = SET_KEY_PRIORITY;
3012 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
3013 me->is_setkey = GNUNET_YES;
3014 me->got_slack = GNUNET_YES; /* do not defer this one! */
3015 me->sender_status = n->status;
3016 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head, n->encrypted_tail,
3017 n->encrypted_tail, me);
3018 sm = (struct SetKeyMessage *) &me[1];
3019 sm->header.size = htons (sizeof (struct SetKeyMessage));
3020 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
3024 PEER_STATE_DOWN) ? PEER_STATE_KEY_SENT : n->status));
3026 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3027 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3028 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3029 sizeof (struct GNUNET_PeerIdentity));
3030 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
3031 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
3032 sm->target = n->peer;
3033 GNUNET_assert (GNUNET_OK ==
3034 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
3036 GNUNET_CRYPTO_AesSessionKey),
3037 n->public_key, &sm->encrypted_key));
3038 GNUNET_assert (GNUNET_OK ==
3039 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
3041 pm = (struct PingMessage *) &sm[1];
3042 pm->header.size = htons (sizeof (struct PingMessage));
3043 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
3045 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3046 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
3047 pp.challenge = n->ping_challenge;
3048 pp.target = n->peer;
3050 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3051 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
3052 "SET_KEY", "PING", (unsigned int) n->ping_challenge,
3053 GNUNET_i2s (&n->peer), (unsigned int) n->encrypt_key.crc32,
3054 GNUNET_CRYPTO_crc32_n (&iv, sizeof (iv)), pm->iv_seed);
3056 do_encrypt (n, &iv, &pp.target, &pm->target,
3057 sizeof (struct PingMessage) - ((void *) &pm->target -
3059 GNUNET_STATISTICS_update (stats,
3061 ("# SET_KEY and PING messages created"), 1,
3064 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3065 "Have %llu ms left for `%s' transmission.\n",
3066 (unsigned long long)
3067 GNUNET_TIME_absolute_get_remaining (me->deadline).rel_value,
3071 /* trigger queue processing */
3072 process_encrypted_neighbour_queue (n);
3073 if ((n->status != PEER_STATE_KEY_CONFIRMED) &&
3074 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task))
3075 n->retry_set_key_task =
3076 GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3077 &set_key_retry_task, n);
3082 * We received a SET_KEY message. Validate and update
3083 * our key material and status.
3085 * @param n the neighbour from which we received message m
3086 * @param m the set key message we received
3087 * @param ats performance data
3088 * @param ats_count number of entries in ats (excluding 0-termination)
3091 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m,
3092 const struct GNUNET_ATS_Information *ats,
3093 uint32_t ats_count);
3098 * PEERINFO is giving us a HELLO for a peer. Add the public key to
3099 * the neighbour's struct and retry handling the set_key message. Or,
3100 * if we did not get a HELLO, just free the set key message.
3102 * @param cls pointer to the set key message
3103 * @param peer the peer for which this is the HELLO
3104 * @param hello HELLO message of that peer
3105 * @param err_msg NULL if successful, otherwise contains error message
3108 process_hello_retry_handle_set_key (void *cls,
3109 const struct GNUNET_PeerIdentity *peer,
3110 const struct GNUNET_HELLO_Message *hello,
3111 const char *err_msg)
3113 struct Neighbour *n = cls;
3114 struct SetKeyMessage *sm = n->skm;
3116 if (err_msg != NULL)
3118 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3119 _("Error in communication with PEERINFO service\n"));
3127 if (n->public_key != NULL)
3130 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3131 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
3132 "HELLO", GNUNET_i2s (&n->peer), "SET_KEY");
3134 handle_set_key (n, sm, NULL, 0);
3138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3140 ("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
3141 "SET_KEY", GNUNET_i2s (&n->peer));
3146 if (n->public_key != NULL)
3147 return; /* multiple HELLOs match!? */
3149 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3150 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3152 GNUNET_break_op (0);
3153 GNUNET_free (n->public_key);
3154 n->public_key = NULL;
3160 * Merge the given performance data with the data we currently
3161 * track for the given neighbour.
3163 * @param n neighbour
3164 * @param ats new performance data
3165 * @param ats_count number of records in ats
3168 update_neighbour_performance (struct Neighbour *n,
3169 const struct GNUNET_ATS_Information
3170 *ats, uint32_t ats_count)
3177 for (i = 0; i < ats_count; i++)
3179 for (j = 0; j < n->ats_count; j++)
3181 if (n->ats[j].type == ats[i].type)
3183 n->ats[j].value = ats[i].value;
3187 if (j == n->ats_count)
3189 GNUNET_array_append (n->ats, n->ats_count, ats[i]);
3196 * We received a PING message. Validate and transmit
3199 * @param n sender of the PING
3200 * @param m the encrypted PING message itself
3201 * @param ats performance data
3202 * @param ats_count number of entries in ats (excluding 0-termination)
3205 handle_ping (struct Neighbour *n, const struct PingMessage *m,
3206 const struct GNUNET_ATS_Information *ats,
3209 struct PingMessage t;
3210 struct PongMessage tx;
3211 struct PongMessage *tp;
3212 struct MessageEntry *me;
3213 struct GNUNET_CRYPTO_AesInitializationVector iv;
3216 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3217 "Core service receives `%s' request from `%4s'.\n", "PING",
3218 GNUNET_i2s (&n->peer));
3220 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3222 do_decrypt (n, &iv, &m->target, &t.target,
3223 sizeof (struct PingMessage) - ((void *) &m->target -
3227 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3228 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u, IV %u (salt %u)\n",
3229 "PING", GNUNET_i2s (&t.target), (unsigned int) t.challenge,
3230 (unsigned int) n->decrypt_key.crc32, GNUNET_CRYPTO_crc32_n (&iv,
3235 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages decrypted"),
3238 memcmp (&t.target, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3243 GNUNET_snprintf (sender, sizeof (sender), "%8s", GNUNET_i2s (&n->peer));
3244 GNUNET_snprintf (peer, sizeof (peer), "%8s", GNUNET_i2s (&t.target));
3245 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3247 ("Received PING from `%s' for different identity: I am `%s', PONG identity: `%s'\n"),
3248 sender, GNUNET_i2s (&my_identity), peer);
3249 GNUNET_break_op (0);
3252 update_neighbour_performance (n, ats, ats_count);
3253 me = GNUNET_malloc (sizeof (struct MessageEntry) +
3254 sizeof (struct PongMessage));
3255 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head, n->encrypted_tail,
3256 n->encrypted_tail, me);
3257 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
3258 me->priority = PONG_PRIORITY;
3259 me->size = sizeof (struct PongMessage);
3260 tx.inbound_bw_limit = n->bw_in;
3261 tx.challenge = t.challenge;
3262 tx.target = t.target;
3263 tp = (struct PongMessage *) &me[1];
3264 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
3265 tp->header.size = htons (sizeof (struct PongMessage));
3267 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3268 derive_pong_iv (&iv, &n->encrypt_key, tp->iv_seed, t.challenge, &n->peer);
3269 do_encrypt (n, &iv, &tx.challenge, &tp->challenge,
3270 sizeof (struct PongMessage) - ((void *) &tp->challenge -
3272 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages created"), 1,
3275 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3276 "Encrypting `%s' with challenge %u using key %u, IV %u (salt %u)\n",
3277 "PONG", (unsigned int) t.challenge,
3278 (unsigned int) n->encrypt_key.crc32, GNUNET_CRYPTO_crc32_n (&iv,
3283 /* trigger queue processing */
3284 process_encrypted_neighbour_queue (n);
3289 * We received a PONG message. Validate and update our status.
3291 * @param n sender of the PONG
3292 * @param m the encrypted PONG message itself
3293 * @param ats performance data
3294 * @param ats_count number of entries in ats (excluding 0-termination)
3297 handle_pong (struct Neighbour *n, const struct PongMessage *m,
3298 const struct GNUNET_ATS_Information *ats,
3301 struct PongMessage t;
3302 struct ConnectNotifyMessage *cnm;
3303 struct GNUNET_CRYPTO_AesInitializationVector iv;
3304 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
3305 struct GNUNET_ATS_Information *mats;
3309 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3310 "Core service receives `%s' response from `%4s'.\n", "PONG",
3311 GNUNET_i2s (&n->peer));
3313 /* mark as garbage, just to be sure */
3314 memset (&t, 255, sizeof (t));
3315 derive_pong_iv (&iv, &n->decrypt_key, m->iv_seed, n->ping_challenge,
3318 do_decrypt (n, &iv, &m->challenge, &t.challenge,
3319 sizeof (struct PongMessage) - ((void *) &m->challenge -
3322 GNUNET_break_op (0);
3325 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages decrypted"),
3328 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3329 "Decrypted `%s' from `%4s' with challenge %u using key %u, IV %u (salt %u)\n",
3330 "PONG", GNUNET_i2s (&t.target), (unsigned int) t.challenge,
3331 (unsigned int) n->decrypt_key.crc32, GNUNET_CRYPTO_crc32_n (&iv,
3336 if ((0 != memcmp (&t.target, &n->peer, sizeof (struct GNUNET_PeerIdentity)))
3337 || (n->ping_challenge != t.challenge))
3339 /* PONG malformed */
3341 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3342 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
3343 "PONG", GNUNET_i2s (&n->peer),
3344 (unsigned int) n->ping_challenge);
3345 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3346 "Received malformed `%s' received from `%4s' with challenge %u\n",
3347 "PONG", GNUNET_i2s (&t.target), (unsigned int) t.challenge);
3349 GNUNET_break_op (n->ping_challenge != t.challenge);
3354 case PEER_STATE_DOWN:
3355 GNUNET_break (0); /* should be impossible */
3357 case PEER_STATE_KEY_SENT:
3358 GNUNET_break (0); /* should be impossible, how did we decrypt? */
3360 case PEER_STATE_KEY_RECEIVED:
3361 GNUNET_STATISTICS_update (stats,
3363 ("# Session keys confirmed via PONG"), 1,
3365 n->status = PEER_STATE_KEY_CONFIRMED;
3367 struct GNUNET_MessageHeader *hdr;
3369 hdr = compute_type_map_message ();
3370 send_type_map_to_neighbour (hdr, &n->peer.hashPubKey, n);
3373 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
3375 n->bw_out_external_limit = t.inbound_bw_limit;
3377 GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3378 n->bw_out_internal_limit);
3379 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3381 GNUNET_TRANSPORT_set_quota (transport, &n->peer, n->bw_in, n->bw_out);
3384 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3385 "Confirmed key via `%s' message for peer `%4s'\n", "PONG",
3386 GNUNET_i2s (&n->peer));
3388 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3390 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3391 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3393 update_neighbour_performance (n, ats, ats_count);
3395 sizeof (struct ConnectNotifyMessage) +
3396 (n->ats_count) * sizeof (struct GNUNET_ATS_Information);
3397 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3400 /* recovery strategy: throw away performance data */
3401 GNUNET_array_grow (n->ats, n->ats_count, 0);
3403 sizeof (struct PeerStatusNotifyMessage) +
3404 n->ats_count * sizeof (struct GNUNET_ATS_Information);
3406 cnm = (struct ConnectNotifyMessage *) buf;
3407 cnm->header.size = htons (size);
3408 cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3409 cnm->ats_count = htonl (n->ats_count);
3410 cnm->peer = n->peer;
3412 memcpy (mats, n->ats,
3413 n->ats_count * sizeof (struct GNUNET_ATS_Information));
3414 mats[n->ats_count].type = htonl (GNUNET_ATS_ARRAY_TERMINATOR);
3415 mats[n->ats_count].value = htonl (0);
3416 send_to_all_clients (&cnm->header, GNUNET_NO,
3417 GNUNET_CORE_OPTION_SEND_CONNECT);
3418 process_encrypted_neighbour_queue (n);
3420 case PEER_STATE_KEY_CONFIRMED:
3421 n->last_activity = GNUNET_TIME_absolute_get ();
3422 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3423 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3424 n->keep_alive_task =
3425 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
3426 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3427 2), &send_keep_alive, n);
3428 handle_peer_status_change (n);
3438 * We received a SET_KEY message. Validate and update
3439 * our key material and status.
3441 * @param n the neighbour from which we received message m
3442 * @param m the set key message we received
3443 * @param ats performance data
3444 * @param ats_count number of entries in ats (excluding 0-termination)
3447 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m,
3448 const struct GNUNET_ATS_Information *ats,
3451 struct SetKeyMessage *m_cpy;
3452 struct GNUNET_TIME_Absolute t;
3453 struct GNUNET_CRYPTO_AesSessionKey k;
3454 struct PingMessage *ping;
3455 struct PongMessage *pong;
3456 enum PeerStateMachine sender_status;
3459 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3460 "Core service receives `%s' request from `%4s'.\n", "SET_KEY",
3461 GNUNET_i2s (&n->peer));
3463 if (n->public_key == NULL)
3465 if (n->pitr != NULL)
3468 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3469 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3475 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3476 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3478 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3479 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3480 /* lookup n's public key, then try again */
3481 GNUNET_assert (n->skm == NULL);
3484 GNUNET_PEERINFO_iterate (peerinfo, &n->peer, GNUNET_TIME_UNIT_MINUTES,
3485 &process_hello_retry_handle_set_key, n);
3486 GNUNET_STATISTICS_update (stats,
3488 ("# SET_KEY messages deferred (need public key)"),
3493 memcmp (&m->target, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3495 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3497 ("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3498 "SET_KEY", GNUNET_i2s (&m->target));
3501 if ((ntohl (m->purpose.size) !=
3502 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3503 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3504 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3505 sizeof (struct GNUNET_PeerIdentity)) ||
3507 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY, &m->purpose,
3508 &m->signature, n->public_key)))
3510 /* invalid signature */
3511 GNUNET_break_op (0);
3514 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3515 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3516 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3517 (t.abs_value < n->decrypt_key_created.abs_value))
3519 /* this could rarely happen due to massive re-ordering of
3520 * messages on the network level, but is most likely either
3521 * a bug or some adversary messing with us. Report. */
3522 GNUNET_break_op (0);
3526 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
3528 if ((GNUNET_CRYPTO_rsa_decrypt
3529 (my_private_key, &m->encrypted_key, &k,
3530 sizeof (struct GNUNET_CRYPTO_AesSessionKey)) !=
3531 sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3532 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3534 /* failed to decrypt !? */
3535 GNUNET_break_op (0);
3538 GNUNET_STATISTICS_update (stats,
3539 gettext_noop ("# SET_KEY messages decrypted"), 1,
3542 if (n->decrypt_key_created.abs_value != t.abs_value)
3544 /* fresh key, reset sequence numbers */
3545 n->last_sequence_number_received = 0;
3546 n->last_packets_bitmap = 0;
3547 n->decrypt_key_created = t;
3549 update_neighbour_performance (n, ats, ats_count);
3550 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3553 case PEER_STATE_DOWN:
3554 n->status = PEER_STATE_KEY_RECEIVED;
3556 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3557 "Responding to `%s' with my own key.\n", "SET_KEY");
3561 case PEER_STATE_KEY_SENT:
3562 case PEER_STATE_KEY_RECEIVED:
3563 n->status = PEER_STATE_KEY_RECEIVED;
3564 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3565 (sender_status != PEER_STATE_KEY_CONFIRMED))
3568 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3569 "Responding to `%s' with my own key (other peer has status %u).\n",
3570 "SET_KEY", (unsigned int) sender_status);
3575 case PEER_STATE_KEY_CONFIRMED:
3576 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3577 (sender_status != PEER_STATE_KEY_CONFIRMED))
3580 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3581 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3582 "SET_KEY", (unsigned int) sender_status);
3591 if (n->pending_ping != NULL)
3593 ping = n->pending_ping;
3594 n->pending_ping = NULL;
3595 handle_ping (n, ping, NULL, 0);
3598 if (n->pending_pong != NULL)
3600 pong = n->pending_pong;
3601 n->pending_pong = NULL;
3602 handle_pong (n, pong, NULL, 0);
3609 * Send a P2P message to a client.
3611 * @param sender who sent us the message?
3612 * @param client who should we give the message to?
3613 * @param m contains the message to transmit
3614 * @param msize number of bytes in buf to transmit
3617 send_p2p_message_to_client (struct Neighbour *sender, struct Client *client,
3618 const void *m, size_t msize)
3621 msize + sizeof (struct NotifyTrafficMessage) +
3622 (sender->ats_count) * sizeof (struct GNUNET_ATS_Information);
3624 struct NotifyTrafficMessage *ntm;
3625 struct GNUNET_ATS_Information *ats;
3627 GNUNET_assert (GNUNET_YES == sender->is_connected);
3628 GNUNET_break (sender->status == PEER_STATE_KEY_CONFIRMED);
3629 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3632 /* recovery strategy: throw performance data away... */
3633 GNUNET_array_grow (sender->ats, sender->ats_count, 0);
3635 msize + sizeof (struct NotifyTrafficMessage) +
3636 (sender->ats_count) * sizeof (struct GNUNET_ATS_Information);
3639 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3640 "Core service passes message from `%4s' of type %u to client.\n",
3641 GNUNET_i2s (&sender->peer),
3643 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3645 ntm = (struct NotifyTrafficMessage *) buf;
3646 ntm->header.size = htons (size);
3647 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3648 ntm->ats_count = htonl (sender->ats_count);
3649 ntm->peer = sender->peer;
3651 memcpy (ats, sender->ats,
3652 sizeof (struct GNUNET_ATS_Information) * sender->ats_count);
3653 ats[sender->ats_count].type = htonl (GNUNET_ATS_ARRAY_TERMINATOR);
3654 ats[sender->ats_count].value = htonl (0);
3655 memcpy (&ats[sender->ats_count + 1], m, msize);
3656 send_to_client (client, &ntm->header, GNUNET_YES);
3661 * Deliver P2P message to interested clients.
3663 * @param cls always NULL
3664 * @param client who sent us the message (struct Neighbour)
3665 * @param m the message
3668 deliver_message (void *cls, void *client, const struct GNUNET_MessageHeader *m)
3670 struct Neighbour *sender = client;
3671 size_t msize = ntohs (m->size);
3673 struct Client *cpos;
3679 GNUNET_break (sender->status == PEER_STATE_KEY_CONFIRMED);
3680 type = ntohs (m->type);
3682 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3683 "Received encapsulated message of type %u and size %u from `%4s'\n",
3684 (unsigned int) type, ntohs (m->size), GNUNET_i2s (&sender->peer));
3686 GNUNET_snprintf (buf, sizeof (buf),
3687 gettext_noop ("# bytes of messages of type %u received"),
3688 (unsigned int) type);
3689 GNUNET_STATISTICS_update (stats, buf, msize, GNUNET_NO);
3690 if ((GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP == type) ||
3691 (GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP == type))
3693 /* FIXME: update message type map for 'Neighbour' */
3696 dropped = GNUNET_YES;
3698 while (cpos != NULL)
3700 deliver_full = GNUNET_NO;
3701 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3702 deliver_full = GNUNET_YES;
3705 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3707 if (type != cpos->types[tpos])
3709 deliver_full = GNUNET_YES;
3713 if (GNUNET_YES == deliver_full)
3715 send_p2p_message_to_client (sender, cpos, m, msize);
3716 dropped = GNUNET_NO;
3718 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3720 send_p2p_message_to_client (sender, cpos, m,
3721 sizeof (struct GNUNET_MessageHeader));
3725 if (dropped == GNUNET_YES)
3728 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3729 "Message of type %u from `%4s' not delivered to any client.\n",
3730 (unsigned int) type, GNUNET_i2s (&sender->peer));
3732 GNUNET_STATISTICS_update (stats,
3734 ("# messages not delivered to any client"), 1,
3741 * We received an encrypted message. Decrypt, validate and
3742 * pass on to the appropriate clients.
3744 * @param n target of the message
3745 * @param m encrypted message
3746 * @param ats performance data
3747 * @param ats_count number of entries in ats (excluding 0-termination)
3750 handle_encrypted_message (struct Neighbour *n, const struct EncryptedMessage *m,
3751 const struct GNUNET_ATS_Information *ats,
3754 size_t size = ntohs (m->header.size);
3756 struct EncryptedMessage *pt; /* plaintext */
3759 struct GNUNET_TIME_Absolute t;
3760 struct GNUNET_CRYPTO_AesInitializationVector iv;
3761 struct GNUNET_CRYPTO_AuthKey auth_key;
3764 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3765 "Core service receives `%s' request from `%4s'.\n",
3766 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3769 derive_auth_key (&auth_key, &n->decrypt_key, m->iv_seed,
3770 n->decrypt_key_created);
3771 GNUNET_CRYPTO_hmac (&auth_key, &m->sequence_number,
3772 size - ENCRYPTED_HEADER_SIZE, &ph);
3774 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3775 "Re-Authenticated %u bytes of ciphertext (`%u'): `%s'\n",
3776 (unsigned int) size - ENCRYPTED_HEADER_SIZE,
3777 GNUNET_CRYPTO_crc32_n (&m->sequence_number,
3778 size - ENCRYPTED_HEADER_SIZE),
3782 if (0 != memcmp (&ph, &m->hmac, sizeof (GNUNET_HashCode)))
3784 /* checksum failed */
3785 GNUNET_break_op (0);
3788 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3791 do_decrypt (n, &iv, &m->sequence_number, &buf[ENCRYPTED_HEADER_SIZE],
3792 size - ENCRYPTED_HEADER_SIZE))
3794 pt = (struct EncryptedMessage *) buf;
3796 /* validate sequence number */
3797 snum = ntohl (pt->sequence_number);
3798 if (n->last_sequence_number_received == snum)
3800 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3801 "Received duplicate message, ignoring.\n");
3802 /* duplicate, ignore */
3803 GNUNET_STATISTICS_update (stats,
3804 gettext_noop ("# bytes dropped (duplicates)"),
3808 if ((n->last_sequence_number_received > snum) &&
3809 (n->last_sequence_number_received - snum > 32))
3811 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3812 "Received ancient out of sequence message, ignoring.\n");
3813 /* ancient out of sequence, ignore */
3814 GNUNET_STATISTICS_update (stats,
3816 ("# bytes dropped (out of sequence)"), size,
3820 if (n->last_sequence_number_received > snum)
3822 unsigned int rotbit = 1 << (n->last_sequence_number_received - snum - 1);
3824 if ((n->last_packets_bitmap & rotbit) != 0)
3826 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3827 "Received duplicate message, ignoring.\n");
3828 GNUNET_STATISTICS_update (stats,
3829 gettext_noop ("# bytes dropped (duplicates)"),
3831 /* duplicate, ignore */
3834 n->last_packets_bitmap |= rotbit;
3836 if (n->last_sequence_number_received < snum)
3838 int shift = (snum - n->last_sequence_number_received);
3840 if (shift >= 8 * sizeof (n->last_packets_bitmap))
3841 n->last_packets_bitmap = 0;
3843 n->last_packets_bitmap <<= shift;
3844 n->last_sequence_number_received = snum;
3847 /* check timestamp */
3848 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3849 if (GNUNET_TIME_absolute_get_duration (t).rel_value >
3850 MAX_MESSAGE_AGE.rel_value)
3852 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3853 _("Message received far too old (%llu ms). Content ignored.\n"),
3854 GNUNET_TIME_absolute_get_duration (t).rel_value);
3855 GNUNET_STATISTICS_update (stats,
3857 ("# bytes dropped (ancient message)"), size,
3862 /* process decrypted message(s) */
3863 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3865 #if DEBUG_CORE_SET_QUOTA
3866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3867 "Received %u b/s as new inbound limit for peer `%4s'\n",
3868 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3869 GNUNET_i2s (&n->peer));
3871 n->bw_out_external_limit = pt->inbound_bw_limit;
3873 GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3874 n->bw_out_internal_limit);
3875 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3877 GNUNET_TRANSPORT_set_quota (transport, &n->peer, n->bw_in, n->bw_out);
3879 n->last_activity = GNUNET_TIME_absolute_get ();
3880 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3881 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3882 n->keep_alive_task =
3883 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
3884 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3885 2), &send_keep_alive, n);
3886 GNUNET_STATISTICS_update (stats,
3887 gettext_noop ("# bytes of payload decrypted"),
3888 size - sizeof (struct EncryptedMessage), GNUNET_NO);
3889 handle_peer_status_change (n);
3890 update_neighbour_performance (n, ats, ats_count);
3892 GNUNET_SERVER_mst_receive (mst, n, &buf[sizeof (struct EncryptedMessage)],
3893 size - sizeof (struct EncryptedMessage),
3894 GNUNET_YES, GNUNET_NO))
3895 GNUNET_break_op (0);
3900 * Function called by the transport for each received message.
3902 * @param cls closure
3903 * @param peer (claimed) identity of the other peer
3904 * @param message the message
3905 * @param ats performance data
3906 * @param ats_count number of entries in ats (excluding 0-termination)
3909 handle_transport_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
3910 const struct GNUNET_MessageHeader *message,
3911 const struct GNUNET_ATS_Information *ats,
3914 struct Neighbour *n;
3915 struct GNUNET_TIME_Absolute now;
3922 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3923 "Received message of type %u from `%4s', demultiplexing.\n",
3924 (unsigned int) ntohs (message->type), GNUNET_i2s (peer));
3926 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3931 n = find_neighbour (peer);
3932 if ((n == NULL) || (GNUNET_NO == n->is_connected))
3934 /* received message from peer that is not connected!? */
3938 changed = GNUNET_NO;
3939 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3940 type = ntohs (message->type);
3941 size = ntohs (message->size);
3944 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3945 if (size != sizeof (struct SetKeyMessage))
3947 GNUNET_break_op (0);
3950 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"),
3952 handle_set_key (n, (const struct SetKeyMessage *) message, ats, ats_count);
3954 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3956 sizeof (struct EncryptedMessage) + sizeof (struct GNUNET_MessageHeader))
3958 GNUNET_break_op (0);
3961 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3962 (n->status != PEER_STATE_KEY_CONFIRMED))
3964 GNUNET_STATISTICS_update (stats,
3966 ("# failed to decrypt message (no session key)"),
3971 handle_encrypted_message (n, (const struct EncryptedMessage *) message, ats,
3974 case GNUNET_MESSAGE_TYPE_CORE_PING:
3975 if (size != sizeof (struct PingMessage))
3977 GNUNET_break_op (0);
3980 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"),
3982 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3983 (n->status != PEER_STATE_KEY_CONFIRMED))
3986 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3987 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3988 "PING", GNUNET_i2s (&n->peer));
3990 GNUNET_free_non_null (n->pending_ping);
3991 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3992 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3995 handle_ping (n, (const struct PingMessage *) message, ats, ats_count);
3997 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3998 if (size != sizeof (struct PongMessage))
4000 GNUNET_break_op (0);
4003 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"),
4005 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
4006 (n->status != PEER_STATE_KEY_CONFIRMED))
4009 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4010 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
4011 "PONG", GNUNET_i2s (&n->peer));
4013 GNUNET_free_non_null (n->pending_pong);
4014 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
4015 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
4018 handle_pong (n, (const struct PongMessage *) message, ats, ats_count);
4021 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4022 _("Unsupported message of type %u received.\n"),
4023 (unsigned int) type);
4026 if (n->status == PEER_STATE_KEY_CONFIRMED)
4028 now = GNUNET_TIME_absolute_get ();
4029 n->last_activity = now;
4030 changed = GNUNET_YES;
4033 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"),
4035 n->time_established = now;
4037 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
4038 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
4039 n->keep_alive_task =
4040 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
4041 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4042 2), &send_keep_alive, n);
4045 handle_peer_status_change (n);
4050 * Function that recalculates the bandwidth quota for the
4051 * given neighbour and transmits it to the transport service.
4053 * @param cls neighbour for the quota update
4057 neighbour_quota_update (void *cls,
4058 const struct GNUNET_SCHEDULER_TaskContext *tc)
4060 struct Neighbour *n = cls;
4061 struct GNUNET_BANDWIDTH_Value32NBO q_in;
4062 struct GNUNET_BANDWIDTH_Value32NBO q_out;
4063 struct GNUNET_BANDWIDTH_Value32NBO q_out_min;
4066 unsigned long long distributable;
4067 uint64_t need_per_peer;
4068 uint64_t need_per_second;
4069 unsigned int neighbour_count;
4072 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4073 "Neighbour quota update calculation running for peer `%4s'\n",
4074 GNUNET_i2s (&n->peer));
4076 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
4077 /* calculate relative preference among all neighbours;
4078 * divides by a bit more to avoid division by zero AND to
4079 * account for possibility of new neighbours joining any time
4080 * AND to convert to double... */
4081 neighbour_count = GNUNET_CONTAINER_multihashmap_size (neighbours);
4082 if (neighbour_count == 0)
4084 if (preference_sum == 0)
4086 pref_rel = 1.0 / (double) neighbour_count;
4090 pref_rel = (double) n->current_preference / preference_sum;
4093 GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
4094 GNUNET_TIME_UNIT_SECONDS);
4095 need_per_second = need_per_peer * neighbour_count;
4097 /* calculate inbound bandwidth per peer */
4099 if (bandwidth_target_in_bps > need_per_second)
4100 distributable = bandwidth_target_in_bps - need_per_second;
4101 share = distributable * pref_rel;
4102 if (share + need_per_peer > UINT32_MAX)
4103 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4105 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4107 /* calculate outbound bandwidth per peer */
4109 if (bandwidth_target_out_bps > need_per_second)
4110 distributable = bandwidth_target_out_bps - need_per_second;
4111 share = distributable * pref_rel;
4112 if (share + need_per_peer > UINT32_MAX)
4113 q_out = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4115 q_out = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4116 n->bw_out_internal_limit = q_out;
4119 GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
4120 n->bw_out_internal_limit);
4121 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window, n->bw_out);
4123 /* check if we want to disconnect for good due to inactivity */
4124 if ((GNUNET_TIME_absolute_get_duration (get_neighbour_timeout (n)).rel_value >
4126 (GNUNET_TIME_absolute_get_duration (n->time_established).rel_value >
4127 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value))
4130 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4131 "Forcing disconnect of `%4s' due to inactivity\n",
4132 GNUNET_i2s (&n->peer));
4134 GNUNET_STATISTICS_update (stats,
4135 gettext_noop ("# peers disconnected due to inactivity"), 1,
4137 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
4139 #if DEBUG_CORE_QUOTA
4140 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4141 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
4142 GNUNET_i2s (&n->peer), (unsigned int) ntohl (q_in.value__),
4143 bandwidth_target_out_bps, (unsigned int) ntohl (n->bw_in.value__),
4144 (unsigned int) ntohl (n->bw_out.value__),
4145 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
4147 if ((n->bw_in.value__ != q_in.value__) ||
4148 (n->bw_out.value__ != q_out_min.value__))
4150 if (n->bw_in.value__ != q_in.value__)
4152 if (n->bw_out.value__ != q_out_min.value__)
4153 n->bw_out = q_out_min;
4154 if (GNUNET_YES == n->is_connected)
4155 GNUNET_TRANSPORT_set_quota (transport, &n->peer, n->bw_in, n->bw_out);
4156 handle_peer_status_change (n);
4158 schedule_quota_update (n);
4163 * Function called by transport to notify us that
4164 * a peer connected to us (on the network level).
4166 * @param cls closure
4167 * @param peer the peer that connected
4168 * @param ats performance data
4169 * @param ats_count number of entries in ats (excluding 0-termination)
4172 handle_transport_notify_connect (void *cls,
4173 const struct GNUNET_PeerIdentity *peer,
4174 const struct GNUNET_ATS_Information
4175 *ats, uint32_t ats_count)
4177 struct Neighbour *n;
4179 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4184 n = find_neighbour (peer);
4187 if (GNUNET_YES == n->is_connected)
4189 /* duplicate connect notification!? */
4196 n = create_neighbour (peer);
4198 GNUNET_STATISTICS_update (stats,
4199 gettext_noop ("# peers connected (transport)"), 1,
4201 n->is_connected = GNUNET_YES;
4202 update_neighbour_performance (n, ats, ats_count);
4203 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window, n->bw_out,
4206 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received connection from `%4s'.\n",
4207 GNUNET_i2s (&n->peer));
4209 GNUNET_TRANSPORT_set_quota (transport, &n->peer, n->bw_in, n->bw_out);
4215 * Function called by transport telling us that a peer
4218 * @param cls closure
4219 * @param peer the peer that disconnected
4222 handle_transport_notify_disconnect (void *cls,
4223 const struct GNUNET_PeerIdentity *peer)
4225 struct DisconnectNotifyMessage cnm;
4226 struct Neighbour *n;
4227 struct ClientActiveRequest *car;
4228 struct GNUNET_TIME_Relative left;
4231 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4232 "Peer `%4s' disconnected from us; received notification from transport.\n",
4235 n = find_neighbour (peer);
4241 GNUNET_break (n->is_connected == GNUNET_YES);
4242 if (n->status == PEER_STATE_KEY_CONFIRMED)
4244 GNUNET_STATISTICS_update (stats,
4245 gettext_noop ("# peers disconnected due to transport disconnect"), 1,
4247 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
4248 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
4249 cnm.reserved = htonl (0);
4251 send_to_all_clients (&cnm.header, GNUNET_NO,
4252 GNUNET_CORE_OPTION_SEND_DISCONNECT);
4253 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"),
4257 /* On transport disconnect transport doesn't cancel requests, so must do so here. */
4260 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
4263 if (GNUNET_SCHEDULER_NO_TASK != n->keep_alive_task)
4265 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
4266 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
4268 n->is_connected = GNUNET_NO;
4269 n->status = PEER_STATE_DOWN;
4270 while (NULL != (car = n->active_client_request_head))
4272 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
4273 n->active_client_request_tail, car);
4274 GNUNET_assert (GNUNET_YES ==
4275 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
4276 &n->peer.hashPubKey,
4281 GNUNET_STATISTICS_update (stats,
4282 gettext_noop ("# peers connected (transport)"), -1,
4284 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
4285 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
4287 GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4288 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
4290 GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (), left);
4291 n->dead_clean_task =
4292 GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
4293 &consider_free_task, n);
4298 * Wrapper around 'free_neighbour'; helper for 'cleaning_task'.
4301 free_neighbour_helper (void *cls, const GNUNET_HashCode * key, void *value)
4303 struct Neighbour *n = value;
4311 * Last task run during shutdown. Disconnects us from
4315 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4320 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core service shutting down.\n");
4322 GNUNET_assert (transport != NULL);
4323 GNUNET_TRANSPORT_disconnect (transport);
4325 GNUNET_CONTAINER_multihashmap_iterate (neighbours, &free_neighbour_helper,
4327 GNUNET_CONTAINER_multihashmap_destroy (neighbours);
4329 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"),
4331 GNUNET_SERVER_notification_context_destroy (notifier);
4333 while (NULL != (c = clients))
4334 handle_client_disconnect (NULL, c->client_handle);
4335 if (my_private_key != NULL)
4336 GNUNET_CRYPTO_rsa_key_free (my_private_key);
4338 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4339 if (peerinfo != NULL)
4340 GNUNET_PEERINFO_disconnect (peerinfo);
4342 GNUNET_SERVER_mst_destroy (mst);
4347 * Initiate core service.
4349 * @param cls closure
4350 * @param server the initialized server
4351 * @param c configuration to use
4354 run (void *cls, struct GNUNET_SERVER_Handle *server,
4355 const struct GNUNET_CONFIGURATION_Handle *c)
4357 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4358 {&handle_client_init, NULL,
4359 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
4360 {&handle_client_iterate_peers, NULL,
4361 GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
4362 sizeof (struct GNUNET_MessageHeader)},
4363 {&handle_client_have_peer, NULL,
4364 GNUNET_MESSAGE_TYPE_CORE_PEER_CONNECTED,
4365 sizeof (struct GNUNET_MessageHeader) +
4366 sizeof (struct GNUNET_PeerIdentity)},
4367 {&handle_client_send_request, NULL,
4368 GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST,
4369 sizeof (struct SendMessageRequest)},
4370 {&handle_client_send, NULL,
4371 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
4377 /* parse configuration */
4379 GNUNET_CONFIGURATION_get_value_number (c, "CORE", "TOTAL_QUOTA_IN",
4380 &bandwidth_target_in_bps)) ||
4382 GNUNET_CONFIGURATION_get_value_number (c, "CORE", "TOTAL_QUOTA_OUT",
4383 &bandwidth_target_out_bps)) ||
4385 GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
4388 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4390 ("Core service is lacking key configuration settings. Exiting.\n"));
4391 GNUNET_SCHEDULER_shutdown ();
4394 peerinfo = GNUNET_PEERINFO_connect (cfg);
4395 if (NULL == peerinfo)
4397 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4398 _("Could not access PEERINFO service. Exiting.\n"));
4399 GNUNET_SCHEDULER_shutdown ();
4400 GNUNET_free (keyfile);
4403 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4404 GNUNET_free (keyfile);
4405 if (my_private_key == NULL)
4407 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4408 _("Core service could not access hostkey. Exiting.\n"));
4409 GNUNET_PEERINFO_disconnect (peerinfo);
4410 GNUNET_SCHEDULER_shutdown ();
4413 neighbours = GNUNET_CONTAINER_multihashmap_create (128);
4414 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4415 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
4416 &my_identity.hashPubKey);
4417 self.public_key = &my_public_key;
4418 self.peer = my_identity;
4419 self.last_activity = GNUNET_TIME_UNIT_FOREVER_ABS;
4420 self.status = PEER_STATE_KEY_CONFIRMED;
4421 self.is_connected = GNUNET_YES;
4422 /* setup notification */
4424 GNUNET_SERVER_notification_context_create (server, MAX_NOTIFY_QUEUE);
4425 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4426 /* setup transport connection */
4428 GNUNET_TRANSPORT_connect (cfg, &my_identity, NULL,
4429 &handle_transport_receive,
4430 &handle_transport_notify_connect,
4431 &handle_transport_notify_disconnect);
4432 GNUNET_assert (NULL != transport);
4433 stats = GNUNET_STATISTICS_create ("core", cfg);
4434 mst = GNUNET_SERVER_mst_create (&deliver_message, NULL);
4435 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleaning_task,
4437 /* process client requests */
4438 GNUNET_SERVER_add_handlers (server, handlers);
4439 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Core service of `%4s' ready.\n"),
4440 GNUNET_i2s (&my_identity));
4446 * The main function for the transport service.
4448 * @param argc number of arguments from the command line
4449 * @param argv command line arguments
4450 * @return 0 ok, 1 on error
4453 main (int argc, char *const *argv)
4455 return (GNUNET_OK ==
4456 GNUNET_SERVICE_run (argc, argv, "core", GNUNET_SERVICE_OPTION_NONE,
4457 &run, NULL)) ? 0 : 1;
4460 /* end of gnunet-service-core.c */