2 This file is part of GNUnet.
3 (C) 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file core/gnunet-service-core.c
23 * @brief high-level P2P messaging
24 * @author Christian Grothoff
26 * Considerations for later:
27 * - check that hostkey used by transport (for HELLOs) is the
28 * same as the hostkey that we are using!
29 * - add code to send PINGs if we are about to time-out otherwise
30 * - optimize lookup (many O(n) list traversals
31 * could ideally be changed to O(1) hash map lookups)
34 #include "gnunet_constants.h"
35 #include "gnunet_util_lib.h"
36 #include "gnunet_hello_lib.h"
37 #include "gnunet_peerinfo_service.h"
38 #include "gnunet_protocols.h"
39 #include "gnunet_signatures.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet_transport_service.h"
45 #define DEBUG_HANDSHAKE GNUNET_NO
47 #define DEBUG_CORE_QUOTA GNUNET_NO
50 * Receive and send buffer windows grow over time. For
51 * how long can 'unused' bandwidth accumulate before we
52 * need to cap it? (specified in seconds).
54 #define MAX_WINDOW_TIME_S (5 * 60)
57 * How many messages do we queue up at most for optional
58 * notifications to a client? (this can cause notifications
59 * about outgoing messages to be dropped).
61 #define MAX_NOTIFY_QUEUE 1024
64 * Minimum bandwidth (out) to assign to any connected peer.
65 * Should be rather low; values larger than DEFAULT_BW_IN_OUT make no
68 #define MIN_BANDWIDTH_PER_PEER GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT
71 * After how much time past the "official" expiration time do
72 * we discard messages? Should not be zero since we may
73 * intentionally defer transmission until close to the deadline
74 * and then may be slightly past the deadline due to inaccuracy
75 * in sleep and our own CPU consumption.
77 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
80 * What is the maximum delay for a SET_KEY message?
82 #define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
85 * How long do we wait for SET_KEY confirmation initially?
87 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 1)
90 * What is the maximum delay for a PING message?
92 #define MAX_PING_DELAY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 2)
95 * What is the maximum delay for a PONG message?
97 #define MAX_PONG_DELAY GNUNET_TIME_relative_multiply (MAX_PING_DELAY, 2)
100 * What is the minimum frequency for a PING message?
102 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
105 * How often do we recalculate bandwidth quotas?
107 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
110 * What is the priority for a SET_KEY message?
112 #define SET_KEY_PRIORITY 0xFFFFFF
115 * What is the priority for a PING message?
117 #define PING_PRIORITY 0xFFFFFF
120 * What is the priority for a PONG message?
122 #define PONG_PRIORITY 0xFFFFFF
125 * How many messages do we queue per peer at most? Must be at
128 #define MAX_PEER_QUEUE_SIZE 16
131 * How many non-mandatory messages do we queue per client at most?
133 #define MAX_CLIENT_QUEUE_SIZE 32
136 * What is the maximum age of a message for us to consider
137 * processing it? Note that this looks at the timestamp used
138 * by the other peer, so clock skew between machines does
139 * come into play here. So this should be picked high enough
140 * so that a little bit of clock skew does not prevent peers
141 * from connecting to us.
143 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
147 * State machine for our P2P encryption handshake. Everyone starts in
148 * "DOWN", if we receive the other peer's key (other peer initiated)
149 * we start in state RECEIVED (since we will immediately send our
150 * own); otherwise we start in SENT. If we get back a PONG from
151 * within either state, we move up to CONFIRMED (the PONG will always
152 * be sent back encrypted with the key we sent to the other peer).
154 enum PeerStateMachine
158 PEER_STATE_KEY_RECEIVED,
159 PEER_STATE_KEY_CONFIRMED
164 * Encapsulation for encrypted messages exchanged between
165 * peers. Followed by the actual encrypted data.
167 struct EncryptedMessage
170 * Message type is either CORE_ENCRYPTED_MESSAGE.
172 struct GNUNET_MessageHeader header;
175 * Random value used for IV generation.
177 uint32_t iv_seed GNUNET_PACKED;
180 * MAC of the encrypted message (starting at 'sequence_number'),
181 * used to verify message integrity. Everything after this value
182 * (excluding this value itself) will be encrypted and authenticated.
183 * ENCRYPTED_HEADER_SIZE must be set to the offset of the *next* field.
185 GNUNET_HashCode hmac;
188 * Sequence number, in network byte order. This field
189 * must be the first encrypted/decrypted field
191 uint32_t sequence_number GNUNET_PACKED;
194 * Desired bandwidth (how much we should send to this peer / how
195 * much is the sender willing to receive)?
197 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
200 * Timestamp. Used to prevent reply of ancient messages
201 * (recent messages are caught with the sequence number).
203 struct GNUNET_TIME_AbsoluteNBO timestamp;
209 * Number of bytes (at the beginning) of "struct EncryptedMessage"
210 * that are NOT encrypted.
212 #define ENCRYPTED_HEADER_SIZE (offsetof(struct EncryptedMessage, sequence_number))
216 * We're sending an (encrypted) PING to the other peer to check if he
217 * can decrypt. The other peer should respond with a PONG with the
218 * same content, except this time encrypted with the receiver's key.
223 * Message type is CORE_PING.
225 struct GNUNET_MessageHeader header;
230 uint32_t iv_seed GNUNET_PACKED;
233 * Intended target of the PING, used primarily to check
234 * that decryption actually worked.
236 struct GNUNET_PeerIdentity target;
239 * Random number chosen to make reply harder.
241 uint32_t challenge GNUNET_PACKED;
247 * Response to a PING. Includes data from the original PING
248 * plus initial bandwidth quota information.
253 * Message type is CORE_PONG.
255 struct GNUNET_MessageHeader header;
260 uint32_t iv_seed GNUNET_PACKED;
263 * Random number to make faking the reply harder. Must be
264 * first field after header (this is where we start to encrypt!).
266 uint32_t challenge GNUNET_PACKED;
269 * Desired bandwidth (how much we should send to this
270 * peer / how much is the sender willing to receive).
272 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
275 * Intended target of the PING, used primarily to check
276 * that decryption actually worked.
278 struct GNUNET_PeerIdentity target;
283 * Message transmitted to set (or update) a session key.
289 * Message type is either CORE_SET_KEY.
291 struct GNUNET_MessageHeader header;
294 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
296 int32_t sender_status GNUNET_PACKED;
299 * Purpose of the signature, will be
300 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
302 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
305 * At what time was this key created?
307 struct GNUNET_TIME_AbsoluteNBO creation_time;
310 * The encrypted session key.
312 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
315 * Who is the intended recipient?
317 struct GNUNET_PeerIdentity target;
320 * Signature of the stuff above (starting at purpose).
322 struct GNUNET_CRYPTO_RsaSignature signature;
328 * Message waiting for transmission. This struct
329 * is followed by the actual content of the message.
335 * We keep messages in a doubly linked list.
337 struct MessageEntry *next;
340 * We keep messages in a doubly linked list.
342 struct MessageEntry *prev;
345 * By when are we supposed to transmit this message?
347 struct GNUNET_TIME_Absolute deadline;
350 * By when are we supposed to transmit this message (after
353 struct GNUNET_TIME_Absolute slack_deadline;
356 * How important is this message to us?
358 unsigned int priority;
361 * If this is a SET_KEY message, what was our connection status when this
362 * message was queued?
364 enum PeerStateMachine sender_status;
367 * Is this a SET_KEY message?
372 * How long is the message? (number of bytes following
373 * the "struct MessageEntry", but not including the
374 * size of "struct MessageEntry" itself!)
379 * Was this message selected for transmission in the
380 * current round? GNUNET_YES or GNUNET_NO.
385 * Did we give this message some slack (delayed sending) previously
386 * (and hence should not give it any more slack)? GNUNET_YES or
395 * Record kept for each request for transmission issued by a
396 * client that is still pending.
398 struct ClientActiveRequest;
401 * Data kept per neighbouring peer.
406 * We keep neighbours in a linked list (for now).
408 struct Neighbour *next;
411 * Unencrypted messages destined for this peer.
413 struct MessageEntry *messages;
416 * Head of the batched, encrypted message queue (already ordered,
417 * transmit starting with the head).
419 struct MessageEntry *encrypted_head;
422 * Tail of the batched, encrypted message queue (already ordered,
423 * append new messages to tail)
425 struct MessageEntry *encrypted_tail;
428 * Head of list of requests from clients for transmission to
431 struct ClientActiveRequest *active_client_request_head;
434 * Tail of list of requests from clients for transmission to
437 struct ClientActiveRequest *active_client_request_tail;
440 * Handle for pending requests for transmission to this peer
441 * with the transport service. NULL if no request is pending.
443 struct GNUNET_TRANSPORT_TransmitHandle *th;
446 * Public key of the neighbour, NULL if we don't have it yet.
448 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
451 * We received a PING message before we got the "public_key"
452 * (or the SET_KEY). We keep it here until we have a key
453 * to decrypt it. NULL if no PING is pending.
455 struct PingMessage *pending_ping;
458 * We received a PONG message before we got the "public_key"
459 * (or the SET_KEY). We keep it here until we have a key
460 * to decrypt it. NULL if no PONG is pending.
462 struct PongMessage *pending_pong;
465 * Non-NULL if we are currently looking up HELLOs for this peer.
468 struct GNUNET_PEERINFO_IteratorContext *pitr;
471 * SetKeyMessage to transmit, NULL if we are not currently trying
474 struct SetKeyMessage *skm;
477 * Performance data for the peer.
479 struct GNUNET_TRANSPORT_ATS_Information *ats;
482 * Identity of the neighbour.
484 struct GNUNET_PeerIdentity peer;
487 * Key we use to encrypt our messages for the other peer
488 * (initialized by us when we do the handshake).
490 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
493 * Key we use to decrypt messages from the other peer
494 * (given to us by the other peer during the handshake).
496 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
499 * ID of task used for re-trying plaintext scheduling.
501 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
504 * ID of task used for re-trying SET_KEY and PING message.
506 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
509 * ID of task used for updating bandwidth quota for this neighbour.
511 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
514 * ID of task used for sending keep-alive pings.
516 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
519 * ID of task used for cleaning up dead neighbour entries.
521 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
524 * At what time did we generate our encryption key?
526 struct GNUNET_TIME_Absolute encrypt_key_created;
529 * At what time did the other peer generate the decryption key?
531 struct GNUNET_TIME_Absolute decrypt_key_created;
534 * At what time did we initially establish (as in, complete session
535 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
537 struct GNUNET_TIME_Absolute time_established;
540 * At what time did we last receive an encrypted message from the
541 * other peer? Should be zero if status != KEY_CONFIRMED.
543 struct GNUNET_TIME_Absolute last_activity;
546 * At what frequency are we currently re-trying SET_KEY messages?
548 struct GNUNET_TIME_Relative set_key_retry_frequency;
551 * Tracking bandwidth for sending to this peer.
553 struct GNUNET_BANDWIDTH_Tracker available_send_window;
556 * Tracking bandwidth for receiving from this peer.
558 struct GNUNET_BANDWIDTH_Tracker available_recv_window;
561 * How valueable were the messages of this peer recently?
563 unsigned long long current_preference;
566 * Number of entries in 'ats'.
568 unsigned int ats_count;
571 * Bit map indicating which of the 32 sequence numbers before the last
572 * were received (good for accepting out-of-order packets and
573 * estimating reliability of the connection)
575 unsigned int last_packets_bitmap;
578 * last sequence number received on this connection (highest)
580 uint32_t last_sequence_number_received;
583 * last sequence number transmitted
585 uint32_t last_sequence_number_sent;
588 * Available bandwidth in for this peer (current target).
590 struct GNUNET_BANDWIDTH_Value32NBO bw_in;
593 * Available bandwidth out for this peer (current target).
595 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
598 * Internal bandwidth limit set for this peer (initially typically
599 * set to "-1"). Actual "bw_out" is MIN of
600 * "bpm_out_internal_limit" and "bw_out_external_limit".
602 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
605 * External bandwidth limit set for this peer by the
606 * peer that we are communicating with. "bw_out" is MIN of
607 * "bw_out_internal_limit" and "bw_out_external_limit".
609 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
612 * What was our PING challenge number (for this peer)?
614 uint32_t ping_challenge;
617 * What is our connection status?
619 enum PeerStateMachine status;
622 * Are we currently connected to this neighbour?
630 * Data structure for each client connected to the core service.
635 * Clients are kept in a linked list.
640 * Handle for the client with the server API.
642 struct GNUNET_SERVER_Client *client_handle;
645 * Array of the types of messages this peer cares
646 * about (with "tcnt" entries). Allocated as part
647 * of this client struct, do not free!
649 const uint16_t *types;
652 * Map of peer identities to active transmission requests of this
653 * client to the peer (of type 'struct ClientActiveRequest').
655 struct GNUNET_CONTAINER_MultiHashMap *requests;
658 * Options for messages this client cares about,
659 * see GNUNET_CORE_OPTION_ values.
664 * Number of types of incoming messages this client
665 * specifically cares about. Size of the "types" array.
673 * Record kept for each request for transmission issued by a
674 * client that is still pending.
676 struct ClientActiveRequest
680 * Active requests are kept in a doubly-linked list of
681 * the respective target peer.
683 struct ClientActiveRequest *next;
686 * Active requests are kept in a doubly-linked list of
687 * the respective target peer.
689 struct ClientActiveRequest *prev;
692 * Handle to the client.
694 struct Client *client;
697 * By what time would the client want to see this message out?
699 struct GNUNET_TIME_Absolute deadline;
702 * How important is this request.
707 * How many more requests does this client have?
712 * How many bytes does the client intend to send?
717 * Unique request ID (in big endian).
728 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
733 static struct GNUNET_PeerIdentity my_identity;
738 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
742 * Handle to peerinfo service.
744 static struct GNUNET_PEERINFO_Handle *peerinfo;
747 * Our message stream tokenizer (for encrypted payload).
749 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
754 const struct GNUNET_CONFIGURATION_Handle *cfg;
759 static struct GNUNET_TRANSPORT_Handle *transport;
762 * Linked list of our clients.
764 static struct Client *clients;
767 * Context for notifications we need to send to our clients.
769 static struct GNUNET_SERVER_NotificationContext *notifier;
772 * We keep neighbours in a linked list (for now).
774 static struct Neighbour *neighbours;
777 * For creating statistics.
779 static struct GNUNET_STATISTICS_Handle *stats;
782 * Sum of all preferences among all neighbours.
784 static unsigned long long preference_sum;
787 * Total number of neighbours we have.
789 static unsigned int neighbour_count;
792 * How much inbound bandwidth are we supposed to be using per second?
793 * FIXME: this value is not used!
795 static unsigned long long bandwidth_target_in_bps;
798 * How much outbound bandwidth are we supposed to be using per second?
800 static unsigned long long bandwidth_target_out_bps;
803 * Derive an authentication key from "set key" information
806 derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
807 const struct GNUNET_CRYPTO_AesSessionKey *skey,
809 struct GNUNET_TIME_Absolute creation_time)
811 static const char ctx[] = "authentication key";
812 struct GNUNET_TIME_AbsoluteNBO ctbe;
815 ctbe = GNUNET_TIME_absolute_hton (creation_time);
816 GNUNET_CRYPTO_hmac_derive_key (akey,
830 * Derive an IV from packet information
833 derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
834 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
835 const struct GNUNET_PeerIdentity *identity)
837 static const char ctx[] = "initialization vector";
839 GNUNET_CRYPTO_aes_derive_iv (iv,
843 &identity->hashPubKey.bits,
844 sizeof(identity->hashPubKey.bits),
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,
863 &identity->hashPubKey.bits,
864 sizeof(identity->hashPubKey.bits),
873 * At what time should the connection to the given neighbour
874 * time out (given no further activity?)
876 * @param n neighbour in question
877 * @return absolute timeout
879 static struct GNUNET_TIME_Absolute
880 get_neighbour_timeout (struct Neighbour *n)
882 return GNUNET_TIME_absolute_add (n->last_activity,
883 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
888 * A preference value for a neighbour was update. Update
889 * the preference sum accordingly.
891 * @param inc how much was a preference value increased?
894 update_preference_sum (unsigned long long inc)
897 unsigned long long os;
900 preference_sum += inc;
901 if (preference_sum >= os)
903 /* overflow! compensate by cutting all values in half! */
908 n->current_preference /= 2;
909 preference_sum += n->current_preference;
912 GNUNET_STATISTICS_set (stats, gettext_noop ("# total peer preference"), preference_sum, GNUNET_NO);
917 * Find the entry for the given neighbour.
919 * @param peer identity of the neighbour
920 * @return NULL if we are not connected, otherwise the
923 static struct Neighbour *
924 find_neighbour (const struct GNUNET_PeerIdentity *peer)
926 struct Neighbour *ret;
929 while ((ret != NULL) &&
930 (0 != memcmp (&ret->peer,
931 peer, sizeof (struct GNUNET_PeerIdentity))))
938 * Send a message to one of our clients.
940 * @param client target for the message
941 * @param msg message to transmit
942 * @param can_drop could this message be dropped if the
943 * client's queue is getting too large?
946 send_to_client (struct Client *client,
947 const struct GNUNET_MessageHeader *msg,
950 #if DEBUG_CORE_CLIENT
951 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
952 "Preparing to send %u bytes of message of type %u to client.\n",
953 (unsigned int) ntohs (msg->size),
954 (unsigned int) ntohs (msg->type));
956 GNUNET_SERVER_notification_context_unicast (notifier,
957 client->client_handle,
964 * Send a message to all of our current clients that have
965 * the right options set.
967 * @param msg message to multicast
968 * @param can_drop can this message be discarded if the queue is too long
969 * @param options mask to use
972 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
981 if (0 != (c->options & options))
983 #if DEBUG_CORE_CLIENT
984 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
985 "Sending message of type %u to client.\n",
986 (unsigned int) ntohs (msg->type));
988 send_to_client (c, msg, can_drop);
996 * Function called by transport telling us that a peer
999 * @param n the peer that changed status
1002 handle_peer_status_change (struct Neighbour *n)
1004 struct PeerStatusNotifyMessage *psnm;
1005 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1006 struct GNUNET_TRANSPORT_ATS_Information *ats;
1009 if ( (! n->is_connected) ||
1010 (n->status != PEER_STATE_KEY_CONFIRMED) )
1013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1014 "Peer `%4s' changed status\n",
1015 GNUNET_i2s (&n->peer));
1017 size = sizeof (struct PeerStatusNotifyMessage) +
1018 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1019 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1022 /* recovery strategy: throw away performance data */
1023 GNUNET_array_grow (n->ats,
1026 size = sizeof (struct PeerStatusNotifyMessage) +
1027 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1029 psnm = (struct PeerStatusNotifyMessage*) buf;
1030 psnm->header.size = htons (size);
1031 psnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_STATUS_CHANGE);
1032 psnm->timeout = GNUNET_TIME_absolute_hton (get_neighbour_timeout (n));
1033 psnm->bandwidth_in = n->bw_in;
1034 psnm->bandwidth_out = n->bw_out;
1035 psnm->peer = n->peer;
1036 psnm->ats_count = htonl (n->ats_count);
1040 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
1041 ats[n->ats_count].type = htonl (0);
1042 ats[n->ats_count].value = htonl (0);
1043 send_to_all_clients (&psnm->header,
1045 GNUNET_CORE_OPTION_SEND_STATUS_CHANGE);
1046 GNUNET_STATISTICS_update (stats,
1047 gettext_noop ("# peer status changes"),
1054 * Go over our message queue and if it is not too long, go
1055 * over the pending requests from clients for this
1056 * neighbour and send some clients a 'READY' notification.
1058 * @param n which peer to process
1061 schedule_peer_messages (struct Neighbour *n)
1063 struct SendMessageReady smr;
1064 struct ClientActiveRequest *car;
1065 struct ClientActiveRequest *pos;
1067 struct MessageEntry *mqe;
1068 unsigned int queue_size;
1070 /* check if neighbour queue is empty enough! */
1078 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1080 #if DEBUG_CORE_CLIENT
1081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1082 "Not considering client transmission requests: queue full\n");
1084 return; /* queue still full */
1086 /* find highest priority request */
1087 pos = n->active_client_request_head;
1091 if ( (car == NULL) ||
1092 (pos->priority > car->priority) )
1097 return; /* no pending requests */
1098 #if DEBUG_CORE_CLIENT
1099 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1100 "Permitting client transmission request to `%s'\n",
1101 GNUNET_i2s (&n->peer));
1104 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1105 n->active_client_request_tail,
1107 GNUNET_CONTAINER_multihashmap_remove (c->requests,
1108 &n->peer.hashPubKey,
1110 smr.header.size = htons (sizeof (struct SendMessageReady));
1111 smr.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND_READY);
1112 smr.size = htons (car->msize);
1113 smr.smr_id = car->smr_id;
1115 send_to_client (c, &smr.header, GNUNET_NO);
1121 * Handle CORE_SEND_REQUEST message.
1124 handle_client_send_request (void *cls,
1125 struct GNUNET_SERVER_Client *client,
1126 const struct GNUNET_MessageHeader *message)
1128 const struct SendMessageRequest *req;
1129 struct Neighbour *n;
1131 struct ClientActiveRequest *car;
1133 req = (const struct SendMessageRequest*) message;
1134 n = find_neighbour (&req->peer);
1136 (GNUNET_YES != n->is_connected) ||
1137 (n->status != PEER_STATE_KEY_CONFIRMED) )
1139 /* neighbour must have disconnected since request was issued,
1140 ignore (client will realize it once it processes the
1141 disconnect notification) */
1142 #if DEBUG_CORE_CLIENT
1143 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1144 "Dropped client request for transmission (am disconnected)\n");
1146 GNUNET_STATISTICS_update (stats,
1147 gettext_noop ("# send requests dropped (disconnected)"),
1150 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1154 while ( (c != NULL) &&
1155 (c->client_handle != client) )
1159 /* client did not send INIT first! */
1161 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1164 if (c->requests == NULL)
1165 c->requests = GNUNET_CONTAINER_multihashmap_create (16);
1166 #if DEBUG_CORE_CLIENT
1167 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1168 "Received client transmission request. queueing\n");
1170 car = GNUNET_CONTAINER_multihashmap_get (c->requests,
1171 &req->peer.hashPubKey);
1174 /* create new entry */
1175 car = GNUNET_malloc (sizeof (struct ClientActiveRequest));
1176 GNUNET_assert (GNUNET_OK ==
1177 GNUNET_CONTAINER_multihashmap_put (c->requests,
1178 &req->peer.hashPubKey,
1180 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1181 GNUNET_CONTAINER_DLL_insert (n->active_client_request_head,
1182 n->active_client_request_tail,
1186 car->deadline = GNUNET_TIME_absolute_ntoh (req->deadline);
1187 car->priority = ntohl (req->priority);
1188 car->queue_size = ntohl (req->queue_size);
1189 car->msize = ntohs (req->size);
1190 car->smr_id = req->smr_id;
1191 schedule_peer_messages (n);
1192 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1197 * Handle CORE_INIT request.
1200 handle_client_init (void *cls,
1201 struct GNUNET_SERVER_Client *client,
1202 const struct GNUNET_MessageHeader *message)
1204 const struct InitMessage *im;
1205 struct InitReplyMessage irm;
1208 const uint16_t *types;
1210 struct Neighbour *n;
1211 struct ConnectNotifyMessage *cnm;
1212 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1213 struct GNUNET_TRANSPORT_ATS_Information *ats;
1217 #if DEBUG_CORE_CLIENT
1218 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1219 "Client connecting to core service with `%s' message\n",
1222 /* check that we don't have an entry already */
1226 if (client == c->client_handle)
1229 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1234 msize = ntohs (message->size);
1235 if (msize < sizeof (struct InitMessage))
1238 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1241 GNUNET_SERVER_notification_context_add (notifier, client);
1242 im = (const struct InitMessage *) message;
1243 types = (const uint16_t *) &im[1];
1244 msize -= sizeof (struct InitMessage);
1245 c = GNUNET_malloc (sizeof (struct Client) + msize);
1246 c->client_handle = client;
1249 c->tcnt = msize / sizeof (uint16_t);
1250 c->types = (const uint16_t *) &c[1];
1251 wtypes = (uint16_t *) &c[1];
1252 for (i=0;i<c->tcnt;i++)
1253 wtypes[i] = ntohs (types[i]);
1254 c->options = ntohl (im->options);
1255 #if DEBUG_CORE_CLIENT
1256 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1257 "Client %p is interested in %u message types\n",
1259 (unsigned int) c->tcnt);
1261 /* send init reply message */
1262 irm.header.size = htons (sizeof (struct InitReplyMessage));
1263 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
1264 irm.reserved = htonl (0);
1265 memcpy (&irm.publicKey,
1267 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1268 #if DEBUG_CORE_CLIENT
1269 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1270 "Sending `%s' message to client.\n", "INIT_REPLY");
1272 send_to_client (c, &irm.header, GNUNET_NO);
1273 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
1275 /* notify new client about existing neighbours */
1279 size = sizeof (struct ConnectNotifyMessage) +
1280 (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1281 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1284 /* recovery strategy: throw away performance data */
1285 GNUNET_array_grow (n->ats,
1288 size = sizeof (struct ConnectNotifyMessage) +
1289 (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1291 cnm = (struct ConnectNotifyMessage*) buf;
1292 cnm->header.size = htons (size);
1293 cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1294 cnm->ats_count = htonl (n->ats_count);
1298 sizeof (struct GNUNET_TRANSPORT_ATS_Information) * n->ats_count);
1299 ats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
1300 ats[n->ats_count].value = htonl (0);
1301 if (n->status == PEER_STATE_KEY_CONFIRMED)
1303 #if DEBUG_CORE_CLIENT
1304 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1305 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
1307 cnm->peer = n->peer;
1308 send_to_client (c, &cnm->header, GNUNET_NO);
1313 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1318 * Free client request records.
1321 * @param key identity of peer for which this is an active request
1322 * @param value the 'struct ClientActiveRequest' to free
1323 * @return GNUNET_YES (continue iteration)
1326 destroy_active_client_request (void *cls,
1327 const GNUNET_HashCode *key,
1330 struct ClientActiveRequest *car = value;
1331 struct Neighbour *n;
1332 struct GNUNET_PeerIdentity peer;
1334 peer.hashPubKey = *key;
1335 n = find_neighbour (&peer);
1336 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1337 n->active_client_request_tail,
1345 * A client disconnected, clean up.
1347 * @param cls closure
1348 * @param client identification of the client
1351 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1354 struct Client *prev;
1358 #if DEBUG_CORE_CLIENT
1359 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1360 "Client %p has disconnected from core service.\n",
1367 if (client == pos->client_handle)
1374 /* client never sent INIT */
1378 clients = pos->next;
1380 prev->next = pos->next;
1381 if (pos->requests != NULL)
1383 GNUNET_CONTAINER_multihashmap_iterate (pos->requests,
1384 &destroy_active_client_request,
1386 GNUNET_CONTAINER_multihashmap_destroy (pos->requests);
1393 * Handle CORE_ITERATE_PEERS request.
1396 * @param client client sending the iteration request
1397 * @param message iteration request message
1400 handle_client_iterate_peers (void *cls,
1401 struct GNUNET_SERVER_Client *client,
1402 const struct GNUNET_MessageHeader *message)
1405 struct Neighbour *n;
1406 struct ConnectNotifyMessage *cnm;
1407 struct GNUNET_MessageHeader done_msg;
1408 struct GNUNET_SERVER_TransmitContext *tc;
1409 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1410 struct GNUNET_TRANSPORT_ATS_Information *ats;
1413 /* notify new client about existing neighbours */
1414 tc = GNUNET_SERVER_transmit_context_create (client);
1415 cnm = (struct ConnectNotifyMessage*) buf;
1419 if (n->status == PEER_STATE_KEY_CONFIRMED)
1421 size = sizeof (struct ConnectNotifyMessage) +
1422 (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1423 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1426 /* recovery strategy: throw away performance data */
1427 GNUNET_array_grow (n->ats,
1430 size = sizeof (struct PeerStatusNotifyMessage) +
1431 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1433 cnm = (struct ConnectNotifyMessage*) buf;
1434 cnm->header.size = htons (size);
1435 cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1436 cnm->ats_count = htonl (n->ats_count);
1440 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
1441 ats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
1442 ats[n->ats_count].value = htonl (0);
1443 #if DEBUG_CORE_CLIENT
1444 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1445 "Sending `%s' message to client.\n",
1448 cnm->peer = n->peer;
1449 GNUNET_SERVER_transmit_context_append_message (tc,
1454 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
1455 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
1456 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
1457 GNUNET_SERVER_transmit_context_run (tc,
1458 GNUNET_TIME_UNIT_FOREVER_REL);
1463 * Handle REQUEST_INFO request.
1466 handle_client_request_info (void *cls,
1467 struct GNUNET_SERVER_Client *client,
1468 const struct GNUNET_MessageHeader *message)
1470 const struct RequestInfoMessage *rcm;
1472 struct Neighbour *n;
1473 struct ConfigurationInfoMessage cim;
1474 int32_t want_reserv;
1476 unsigned long long old_preference;
1478 #if DEBUG_CORE_CLIENT
1479 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1480 "Core service receives `%s' request.\n", "REQUEST_INFO");
1485 if (client == pos->client_handle)
1492 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1496 rcm = (const struct RequestInfoMessage *) message;
1497 n = find_neighbour (&rcm->peer);
1498 memset (&cim, 0, sizeof (cim));
1501 want_reserv = ntohl (rcm->reserve_inbound);
1502 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1504 n->bw_out_internal_limit = rcm->limit_outbound;
1505 if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1506 n->bw_out_external_limit).value__)
1508 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1509 n->bw_out_external_limit);
1510 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1512 GNUNET_TRANSPORT_set_quota (transport,
1516 GNUNET_TIME_UNIT_FOREVER_REL,
1518 handle_peer_status_change (n);
1521 if (want_reserv < 0)
1523 got_reserv = want_reserv;
1525 else if (want_reserv > 0)
1527 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1528 want_reserv).rel_value == 0)
1529 got_reserv = want_reserv;
1531 got_reserv = 0; /* all or nothing */
1535 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1537 old_preference = n->current_preference;
1538 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1539 if (old_preference > n->current_preference)
1541 /* overflow; cap at maximum value */
1542 n->current_preference = ULLONG_MAX;
1544 update_preference_sum (n->current_preference - old_preference);
1545 #if DEBUG_CORE_QUOTA
1546 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1547 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1549 GNUNET_i2s (&rcm->peer),
1552 cim.reserved_amount = htonl (got_reserv);
1553 cim.rim_id = rcm->rim_id;
1554 cim.bw_out = n->bw_out;
1555 cim.preference = n->current_preference;
1557 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1558 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1559 cim.peer = rcm->peer;
1560 #if DEBUG_CORE_CLIENT
1561 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1562 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1564 send_to_client (pos, &cim.header, GNUNET_NO);
1565 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1570 * Free the given entry for the neighbour (it has
1571 * already been removed from the list at this point).
1573 * @param n neighbour to free
1576 free_neighbour (struct Neighbour *n)
1578 struct MessageEntry *m;
1579 struct ClientActiveRequest *car;
1582 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1583 "Destroying neighbour entry for peer `%4s'\n",
1584 GNUNET_i2s (&n->peer));
1586 if (n->pitr != NULL)
1588 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1593 GNUNET_free (n->skm);
1596 while (NULL != (m = n->messages))
1598 n->messages = m->next;
1601 while (NULL != (m = n->encrypted_head))
1603 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1608 while (NULL != (car = n->active_client_request_head))
1610 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1611 n->active_client_request_tail,
1613 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
1614 &n->peer.hashPubKey,
1620 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1623 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1624 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
1625 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1626 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
1627 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1628 GNUNET_SCHEDULER_cancel (n->quota_update_task);
1629 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1630 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1631 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1632 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
1633 if (n->status == PEER_STATE_KEY_CONFIRMED)
1634 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1635 GNUNET_array_grow (n->ats, n->ats_count, 0);
1636 GNUNET_free_non_null (n->public_key);
1637 GNUNET_free_non_null (n->pending_ping);
1638 GNUNET_free_non_null (n->pending_pong);
1644 * Check if we have encrypted messages for the specified neighbour
1645 * pending, and if so, check with the transport about sending them
1648 * @param n neighbour to check.
1650 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1654 * Encrypt size bytes from in and write the result to out. Use the
1655 * key for outbound traffic of the given neighbour.
1657 * @param n neighbour we are sending to
1658 * @param iv initialization vector to use
1659 * @param in ciphertext
1660 * @param out plaintext
1661 * @param size size of in/out
1662 * @return GNUNET_OK on success
1665 do_encrypt (struct Neighbour *n,
1666 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1667 const void *in, void *out, size_t size)
1669 if (size != (uint16_t) size)
1674 GNUNET_assert (size ==
1675 GNUNET_CRYPTO_aes_encrypt (in,
1679 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1681 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1682 "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
1683 (unsigned int) size,
1684 GNUNET_i2s (&n->peer),
1685 (unsigned int) n->encrypt_key.crc32,
1686 GNUNET_CRYPTO_crc32_n (iv, sizeof(iv)));
1693 * Consider freeing the given neighbour since we may not need
1694 * to keep it around anymore.
1696 * @param n neighbour to consider discarding
1699 consider_free_neighbour (struct Neighbour *n);
1703 * Task triggered when a neighbour entry is about to time out
1704 * (and we should prevent this by sending a PING).
1706 * @param cls the 'struct Neighbour'
1707 * @param tc scheduler context (not used)
1710 send_keep_alive (void *cls,
1711 const struct GNUNET_SCHEDULER_TaskContext *tc)
1713 struct Neighbour *n = cls;
1714 struct GNUNET_TIME_Relative retry;
1715 struct GNUNET_TIME_Relative left;
1716 struct MessageEntry *me;
1717 struct PingMessage pp;
1718 struct PingMessage *pm;
1719 struct GNUNET_CRYPTO_AesInitializationVector iv;
1721 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1723 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1724 sizeof (struct PingMessage));
1725 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1726 me->priority = PING_PRIORITY;
1727 me->size = sizeof (struct PingMessage);
1728 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1732 pm = (struct PingMessage *) &me[1];
1733 pm->header.size = htons (sizeof (struct PingMessage));
1734 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1735 pm->iv_seed = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1737 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
1738 pp.challenge = n->ping_challenge;
1739 pp.target = n->peer;
1741 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1742 "Encrypting `%s' message with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
1744 (unsigned int) n->ping_challenge,
1745 GNUNET_i2s (&n->peer),
1746 (unsigned int) n->encrypt_key.crc32,
1747 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
1754 sizeof (struct PingMessage) -
1755 ((void *) &pm->target - (void *) pm));
1756 process_encrypted_neighbour_queue (n);
1757 /* reschedule PING job */
1758 left = GNUNET_TIME_absolute_get_remaining (get_neighbour_timeout (n));
1759 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1760 MIN_PING_FREQUENCY);
1762 = GNUNET_SCHEDULER_add_delayed (retry,
1770 * Task triggered when a neighbour entry might have gotten stale.
1772 * @param cls the 'struct Neighbour'
1773 * @param tc scheduler context (not used)
1776 consider_free_task (void *cls,
1777 const struct GNUNET_SCHEDULER_TaskContext *tc)
1779 struct Neighbour *n = cls;
1781 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1782 consider_free_neighbour (n);
1787 * Consider freeing the given neighbour since we may not need
1788 * to keep it around anymore.
1790 * @param n neighbour to consider discarding
1793 consider_free_neighbour (struct Neighbour *n)
1795 struct Neighbour *pos;
1796 struct Neighbour *prev;
1797 struct GNUNET_TIME_Relative left;
1799 if ( (n->th != NULL) ||
1800 (n->pitr != NULL) ||
1801 (GNUNET_YES == n->is_connected) )
1802 return; /* no chance */
1804 left = GNUNET_TIME_absolute_get_remaining (get_neighbour_timeout (n));
1805 if (left.rel_value > 0)
1807 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1808 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1809 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (left,
1810 &consider_free_task,
1814 /* actually free the neighbour... */
1823 neighbours = n->next;
1825 prev->next = n->next;
1826 GNUNET_assert (neighbour_count > 0);
1828 GNUNET_STATISTICS_set (stats,
1829 gettext_noop ("# neighbour entries allocated"),
1837 * Function called when the transport service is ready to
1838 * receive an encrypted message for the respective peer
1840 * @param cls neighbour to use message from
1841 * @param size number of bytes we can transmit
1842 * @param buf where to copy the message
1843 * @return number of bytes transmitted
1846 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1848 struct Neighbour *n = cls;
1849 struct MessageEntry *m;
1854 m = n->encrypted_head;
1858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1859 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1860 GNUNET_i2s (&n->peer));
1864 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1871 GNUNET_assert (size >= m->size);
1872 memcpy (cbuf, &m[1], m->size);
1874 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1877 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1878 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1879 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1881 GNUNET_i2s (&n->peer));
1883 process_encrypted_neighbour_queue (n);
1888 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1889 "Transmission of message of type %u and size %u failed\n",
1890 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1891 (unsigned int) m->size);
1895 consider_free_neighbour (n);
1901 * Check if we have plaintext messages for the specified neighbour
1902 * pending, and if so, consider batching and encrypting them (and
1903 * then trigger processing of the encrypted queue if needed).
1905 * @param n neighbour to check.
1907 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1911 * Check if we have encrypted messages for the specified neighbour
1912 * pending, and if so, check with the transport about sending them
1915 * @param n neighbour to check.
1918 process_encrypted_neighbour_queue (struct Neighbour *n)
1920 struct MessageEntry *m;
1923 return; /* request already pending */
1924 m = n->encrypted_head;
1927 /* encrypted queue empty, try plaintext instead */
1928 process_plaintext_neighbour_queue (n);
1932 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1933 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1934 (unsigned int) m->size,
1935 GNUNET_i2s (&n->peer),
1936 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).rel_value);
1939 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1942 GNUNET_TIME_absolute_get_remaining
1944 ¬ify_encrypted_transmit_ready,
1948 /* message request too large or duplicate request */
1950 /* discard encrypted message */
1951 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1955 process_encrypted_neighbour_queue (n);
1961 * Decrypt size bytes from in and write the result to out. Use the
1962 * key for inbound traffic of the given neighbour. This function does
1963 * NOT do any integrity-checks on the result.
1965 * @param n neighbour we are receiving from
1966 * @param iv initialization vector to use
1967 * @param in ciphertext
1968 * @param out plaintext
1969 * @param size size of in/out
1970 * @return GNUNET_OK on success
1973 do_decrypt (struct Neighbour *n,
1974 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1975 const void *in, void *out, size_t size)
1977 if (size != (uint16_t) size)
1982 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1983 (n->status != PEER_STATE_KEY_CONFIRMED))
1985 GNUNET_break_op (0);
1986 return GNUNET_SYSERR;
1989 GNUNET_CRYPTO_aes_decrypt (in,
1996 return GNUNET_SYSERR;
1998 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
2000 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2001 "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
2002 (unsigned int) size,
2003 GNUNET_i2s (&n->peer),
2004 (unsigned int) n->decrypt_key.crc32,
2005 GNUNET_CRYPTO_crc32_n (iv, sizeof(*iv)));
2012 * Select messages for transmission. This heuristic uses a combination
2013 * of earliest deadline first (EDF) scheduling (with bounded horizon)
2014 * and priority-based discard (in case no feasible schedule exist) and
2015 * speculative optimization (defer any kind of transmission until
2016 * we either create a batch of significant size, 25% of max, or until
2017 * we are close to a deadline). Furthermore, when scheduling the
2018 * heuristic also packs as many messages into the batch as possible,
2019 * starting with those with the earliest deadline. Yes, this is fun.
2021 * @param n neighbour to select messages from
2022 * @param size number of bytes to select for transmission
2023 * @param retry_time set to the time when we should try again
2024 * (only valid if this function returns zero)
2025 * @return number of bytes selected, or 0 if we decided to
2026 * defer scheduling overall; in that case, retry_time is set.
2029 select_messages (struct Neighbour *n,
2030 size_t size, struct GNUNET_TIME_Relative *retry_time)
2032 struct MessageEntry *pos;
2033 struct MessageEntry *min;
2034 struct MessageEntry *last;
2035 unsigned int min_prio;
2036 struct GNUNET_TIME_Absolute t;
2037 struct GNUNET_TIME_Absolute now;
2038 struct GNUNET_TIME_Relative delta;
2040 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
2043 unsigned int queue_size;
2044 int discard_low_prio;
2046 GNUNET_assert (NULL != n->messages);
2047 now = GNUNET_TIME_absolute_get ();
2048 /* last entry in linked list of messages processed */
2050 /* should we remove the entry with the lowest
2051 priority from consideration for scheduling at the
2062 discard_low_prio = GNUNET_YES;
2063 while (GNUNET_YES == discard_low_prio)
2066 min_prio = UINT_MAX;
2067 discard_low_prio = GNUNET_NO;
2068 /* calculate number of bytes available for transmission at time "t" */
2069 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
2071 /* how many bytes have we (hypothetically) scheduled so far */
2073 /* maximum time we can wait before transmitting anything
2074 and still make all of our deadlines */
2075 slack = GNUNET_TIME_UNIT_FOREVER_REL;
2077 /* note that we use "*2" here because we want to look
2078 a bit further into the future; much more makes no
2079 sense since new message might be scheduled in the
2081 while ((pos != NULL) && (off < size * 2))
2083 if (pos->do_transmit == GNUNET_YES)
2085 /* already removed from consideration */
2089 if (discard_low_prio == GNUNET_NO)
2091 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
2092 if (delta.rel_value > 0)
2094 // FIXME: HUH? Check!
2096 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
2099 if (avail < pos->size)
2101 // FIXME: HUH? Check!
2102 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
2107 /* update slack, considering both its absolute deadline
2108 and relative deadlines caused by other messages
2109 with their respective load */
2110 slack = GNUNET_TIME_relative_min (slack,
2111 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
2113 if (pos->deadline.abs_value <= now.abs_value)
2116 slack = GNUNET_TIME_UNIT_ZERO;
2118 else if (GNUNET_YES == pos->got_slack)
2120 /* should be soon now! */
2121 slack = GNUNET_TIME_relative_min (slack,
2122 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
2127 GNUNET_TIME_relative_min (slack,
2128 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
2129 pos->got_slack = GNUNET_YES;
2130 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
2131 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
2136 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
2137 if (pos->priority <= min_prio)
2139 /* update min for discard */
2140 min_prio = pos->priority;
2145 if (discard_low_prio)
2147 GNUNET_assert (min != NULL);
2148 /* remove lowest-priority entry from consideration */
2149 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
2153 /* guard against sending "tiny" messages with large headers without
2155 if ( (slack.rel_value > GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value) &&
2157 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
2159 /* less than 25% of message would be filled with deadlines still
2160 being met if we delay by one second or more; so just wait for
2161 more data; but do not wait longer than 1s (since we don't want
2162 to delay messages for a really long time either). */
2163 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
2164 /* reset do_transmit values for next time */
2167 pos->do_transmit = GNUNET_NO;
2170 GNUNET_STATISTICS_update (stats,
2171 gettext_noop ("# transmissions delayed due to corking"),
2174 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2175 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
2176 (unsigned long long) retry_time->rel_value,
2178 (unsigned int) size);
2182 /* select marked messages (up to size) for transmission */
2187 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
2189 pos->do_transmit = GNUNET_YES; /* mark for transmission */
2193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2194 "Selecting message of size %u for transmission\n",
2195 (unsigned int) pos->size);
2201 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2202 "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
2203 (unsigned int) pos->size,
2206 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
2211 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2212 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
2213 (unsigned long long) off, (unsigned long long) tsize,
2214 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
2215 GNUNET_i2s (&n->peer));
2222 * Batch multiple messages into a larger buffer.
2224 * @param n neighbour to take messages from
2225 * @param buf target buffer
2226 * @param size size of buf
2227 * @param deadline set to transmission deadline for the result
2228 * @param retry_time set to the time when we should try again
2229 * (only valid if this function returns zero)
2230 * @param priority set to the priority of the batch
2231 * @return number of bytes written to buf (can be zero)
2234 batch_message (struct Neighbour *n,
2237 struct GNUNET_TIME_Absolute *deadline,
2238 struct GNUNET_TIME_Relative *retry_time,
2239 unsigned int *priority)
2241 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
2242 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
2243 struct MessageEntry *pos;
2244 struct MessageEntry *prev;
2245 struct MessageEntry *next;
2250 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2251 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
2252 if (0 == select_messages (n, size, retry_time))
2255 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2256 "No messages selected, will try again in %llu ms\n",
2257 retry_time->rel_value);
2261 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
2262 ntm->ats_count = htonl (0);
2263 ntm->ats.type = htonl (0);
2264 ntm->ats.value = htonl (0);
2265 ntm->peer = n->peer;
2268 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
2271 if (GNUNET_YES == pos->do_transmit)
2273 GNUNET_assert (pos->size <= size);
2274 /* do notifications */
2275 /* FIXME: track if we have *any* client that wants
2276 full notifications and only do this if that is
2278 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
2280 memcpy (&ntm[1], &pos[1], pos->size);
2281 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
2282 sizeof (struct GNUNET_MessageHeader));
2283 send_to_all_clients (&ntm->header,
2285 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
2289 /* message too large for 'full' notifications, we do at
2290 least the 'hdr' type */
2293 sizeof (struct GNUNET_MessageHeader));
2295 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
2297 send_to_all_clients (&ntm->header,
2299 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
2301 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2302 "Encrypting %u bytes with message of type %u and size %u\n",
2304 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
2305 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
2307 /* copy for encrypted transmission */
2308 memcpy (&buf[ret], &pos[1], pos->size);
2311 *priority += pos->priority;
2313 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2314 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
2315 (unsigned int) pos->size,
2316 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).rel_value);
2318 deadline->abs_value = GNUNET_MIN (deadline->abs_value, pos->deadline.abs_value);
2332 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2333 "Deadline for message batch is %llu ms\n",
2334 GNUNET_TIME_absolute_get_remaining (*deadline).rel_value);
2341 * Remove messages with deadlines that have long expired from
2344 * @param n neighbour to inspect
2347 discard_expired_messages (struct Neighbour *n)
2349 struct MessageEntry *prev;
2350 struct MessageEntry *next;
2351 struct MessageEntry *pos;
2352 struct GNUNET_TIME_Absolute now;
2353 struct GNUNET_TIME_Relative delta;
2357 now = GNUNET_TIME_absolute_get ();
2363 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
2364 if (delta.rel_value > PAST_EXPIRATION_DISCARD_TIME.rel_value)
2367 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2368 "Message is %llu ms past due, discarding.\n",
2375 GNUNET_STATISTICS_update (stats,
2376 gettext_noop ("# messages discarded (expired prior to transmission)"),
2386 if (GNUNET_YES == disc)
2387 schedule_peer_messages (n);
2392 * Signature of the main function of a task.
2394 * @param cls closure
2395 * @param tc context information (why was this task triggered now)
2398 retry_plaintext_processing (void *cls,
2399 const struct GNUNET_SCHEDULER_TaskContext *tc)
2401 struct Neighbour *n = cls;
2403 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2404 process_plaintext_neighbour_queue (n);
2409 * Send our key (and encrypted PING) to the other peer.
2411 * @param n the other peer
2413 static void send_key (struct Neighbour *n);
2416 * Task that will retry "send_key" if our previous attempt failed
2420 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2422 struct Neighbour *n = cls;
2425 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2426 "Retrying key transmission to `%4s'\n",
2427 GNUNET_i2s (&n->peer));
2429 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2430 n->set_key_retry_frequency =
2431 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2437 * Check if we have plaintext messages for the specified neighbour
2438 * pending, and if so, consider batching and encrypting them (and
2439 * then trigger processing of the encrypted queue if needed).
2441 * @param n neighbour to check.
2444 process_plaintext_neighbour_queue (struct Neighbour *n)
2446 char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)]; /* plaintext */
2448 struct EncryptedMessage *em; /* encrypted message */
2449 struct EncryptedMessage *ph; /* plaintext header */
2450 struct MessageEntry *me;
2451 unsigned int priority;
2452 struct GNUNET_TIME_Absolute deadline;
2453 struct GNUNET_TIME_Relative retry_time;
2454 struct GNUNET_CRYPTO_AesInitializationVector iv;
2455 struct GNUNET_CRYPTO_AuthKey auth_key;
2457 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2459 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
2460 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2464 case PEER_STATE_DOWN:
2467 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2468 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2469 GNUNET_i2s(&n->peer));
2472 case PEER_STATE_KEY_SENT:
2473 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2474 n->retry_set_key_task
2475 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2476 &set_key_retry_task, n);
2478 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2479 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2480 GNUNET_i2s(&n->peer));
2483 case PEER_STATE_KEY_RECEIVED:
2484 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2485 n->retry_set_key_task
2486 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2487 &set_key_retry_task, n);
2489 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2490 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2491 GNUNET_i2s(&n->peer));
2494 case PEER_STATE_KEY_CONFIRMED:
2495 /* ready to continue */
2498 discard_expired_messages (n);
2499 if (n->messages == NULL)
2502 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2503 "Plaintext message queue for `%4s' is empty.\n",
2504 GNUNET_i2s(&n->peer));
2506 return; /* no pending messages */
2508 if (n->encrypted_head != NULL)
2511 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2512 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2513 GNUNET_i2s(&n->peer));
2515 return; /* wait for messages already encrypted to be
2518 ph = (struct EncryptedMessage *) pbuf;
2519 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2521 used = sizeof (struct EncryptedMessage);
2522 used += batch_message (n,
2524 GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2525 &deadline, &retry_time, &priority);
2526 if (used == sizeof (struct EncryptedMessage))
2529 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2530 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2531 GNUNET_i2s(&n->peer));
2533 /* no messages selected for sending, try again later... */
2534 n->retry_plaintext_task =
2535 GNUNET_SCHEDULER_add_delayed (retry_time,
2536 &retry_plaintext_processing, n);
2539 #if DEBUG_CORE_QUOTA
2540 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2541 "Sending %u b/s as new limit to peer `%4s'\n",
2542 (unsigned int) ntohl (n->bw_in.value__),
2543 GNUNET_i2s (&n->peer));
2545 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
2546 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2547 ph->inbound_bw_limit = n->bw_in;
2548 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2550 /* setup encryption message header */
2551 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2552 me->deadline = deadline;
2553 me->priority = priority;
2555 em = (struct EncryptedMessage *) &me[1];
2556 em->header.size = htons (used);
2557 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2558 em->iv_seed = ph->iv_seed;
2559 derive_iv (&iv, &n->encrypt_key, ph->iv_seed, &n->peer);
2562 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2563 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2564 (unsigned int) used - ENCRYPTED_HEADER_SIZE,
2565 GNUNET_i2s(&n->peer),
2566 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).rel_value);
2568 GNUNET_assert (GNUNET_OK ==
2571 &ph->sequence_number,
2572 &em->sequence_number, used - ENCRYPTED_HEADER_SIZE));
2573 derive_auth_key (&auth_key,
2576 n->encrypt_key_created);
2577 GNUNET_CRYPTO_hmac (&auth_key,
2578 &em->sequence_number,
2579 used - ENCRYPTED_HEADER_SIZE,
2582 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2583 "Authenticated %u bytes of ciphertext %u: `%s'\n",
2584 used - ENCRYPTED_HEADER_SIZE,
2585 GNUNET_CRYPTO_crc32_n (&em->sequence_number,
2586 used - ENCRYPTED_HEADER_SIZE),
2587 GNUNET_h2s (&em->hmac));
2589 /* append to transmission list */
2590 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2594 process_encrypted_neighbour_queue (n);
2595 schedule_peer_messages (n);
2600 * Function that recalculates the bandwidth quota for the
2601 * given neighbour and transmits it to the transport service.
2603 * @param cls neighbour for the quota update
2607 neighbour_quota_update (void *cls,
2608 const struct GNUNET_SCHEDULER_TaskContext *tc);
2612 * Schedule the task that will recalculate the bandwidth
2613 * quota for this peer (and possibly force a disconnect of
2614 * idle peers by calculating a bandwidth of zero).
2617 schedule_quota_update (struct Neighbour *n)
2619 GNUNET_assert (n->quota_update_task ==
2620 GNUNET_SCHEDULER_NO_TASK);
2621 n->quota_update_task
2622 = GNUNET_SCHEDULER_add_delayed (QUOTA_UPDATE_FREQUENCY,
2623 &neighbour_quota_update,
2629 * Initialize a new 'struct Neighbour'.
2631 * @param pid ID of the new neighbour
2632 * @return handle for the new neighbour
2634 static struct Neighbour *
2635 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2637 struct Neighbour *n;
2638 struct GNUNET_TIME_Absolute now;
2641 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2642 "Creating neighbour entry for peer `%4s'\n",
2645 n = GNUNET_malloc (sizeof (struct Neighbour));
2646 n->next = neighbours;
2649 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2651 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2652 now = GNUNET_TIME_absolute_get ();
2653 n->encrypt_key_created = now;
2654 n->last_activity = now;
2655 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2656 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2657 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2658 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2659 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2660 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
2662 neighbour_quota_update (n, NULL);
2663 consider_free_neighbour (n);
2669 * Handle CORE_SEND request.
2672 * @param client the client issuing the request
2673 * @param message the "struct SendMessage"
2676 handle_client_send (void *cls,
2677 struct GNUNET_SERVER_Client *client,
2678 const struct GNUNET_MessageHeader *message)
2680 const struct SendMessage *sm;
2681 struct Neighbour *n;
2682 struct MessageEntry *prev;
2683 struct MessageEntry *pos;
2684 struct MessageEntry *e;
2685 struct MessageEntry *min_prio_entry;
2686 struct MessageEntry *min_prio_prev;
2687 unsigned int min_prio;
2688 unsigned int queue_size;
2691 msize = ntohs (message->size);
2693 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2695 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "about to assert fail, msize is %d, should be at least %d\n", msize, sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader));
2698 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2701 sm = (const struct SendMessage *) message;
2702 msize -= sizeof (struct SendMessage);
2703 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2705 /* FIXME: should we not allow loopback-injection here? */
2708 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2711 n = find_neighbour (&sm->peer);
2713 n = create_neighbour (&sm->peer);
2715 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2716 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2718 (unsigned int) msize,
2719 GNUNET_i2s (&sm->peer));
2721 discard_expired_messages (n);
2722 /* bound queue size */
2723 /* NOTE: this entire block to bound the queue size should be
2724 obsolete with the new client-request code and the
2725 'schedule_peer_messages' mechanism; we still have this code in
2726 here for now as a sanity check for the new mechanmism;
2727 ultimately, we should probably simply reject SEND messages that
2728 are not 'approved' (or provide a new core API for very unreliable
2729 delivery that always sends with priority 0). Food for thought. */
2730 min_prio = UINT32_MAX;
2731 min_prio_entry = NULL;
2732 min_prio_prev = NULL;
2738 if (pos->priority <= min_prio)
2740 min_prio_entry = pos;
2741 min_prio_prev = prev;
2742 min_prio = pos->priority;
2748 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2751 if (ntohl(sm->priority) <= min_prio)
2753 /* discard new entry; this should no longer happen! */
2756 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2757 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2759 (unsigned int) MAX_PEER_QUEUE_SIZE,
2760 (unsigned int) msize,
2761 (unsigned int) ntohs (message->type));
2763 GNUNET_STATISTICS_update (stats,
2764 gettext_noop ("# discarded CORE_SEND requests"),
2768 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2771 GNUNET_assert (min_prio_entry != NULL);
2772 /* discard "min_prio_entry" */
2774 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2775 "Queue full, discarding existing older request\n");
2777 GNUNET_STATISTICS_update (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 1, GNUNET_NO);
2778 if (min_prio_prev == NULL)
2779 n->messages = min_prio_entry->next;
2781 min_prio_prev->next = min_prio_entry->next;
2782 GNUNET_free (min_prio_entry);
2786 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2787 "Adding transmission request for `%4s' of size %u to queue\n",
2788 GNUNET_i2s (&sm->peer),
2789 (unsigned int) msize);
2791 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2792 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2793 e->priority = ntohl (sm->priority);
2795 memcpy (&e[1], &sm[1], msize);
2797 /* insert, keep list sorted by deadline */
2800 while ((pos != NULL) && (pos->deadline.abs_value < e->deadline.abs_value))
2811 /* consider scheduling now */
2812 process_plaintext_neighbour_queue (n);
2814 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2819 * Function called when the transport service is ready to
2820 * receive a message. Only resets 'n->th' to NULL.
2822 * @param cls neighbour to use message from
2823 * @param size number of bytes we can transmit
2824 * @param buf where to copy the message
2825 * @return number of bytes transmitted
2828 notify_transport_connect_done (void *cls, size_t size, void *buf)
2830 struct Neighbour *n = cls;
2833 if (GNUNET_YES != n->is_connected)
2835 /* transport should only call us to transmit a message after
2836 * telling us about a successful connection to the respective peer */
2838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Timeout on notify connect!\n");
2844 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2845 _("Failed to connect to `%4s': transport failed to connect\n"),
2846 GNUNET_i2s (&n->peer));
2849 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2850 _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2851 GNUNET_i2s (&n->peer));
2852 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2853 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2854 n->retry_set_key_task = GNUNET_SCHEDULER_add_now (&set_key_retry_task,
2861 * Handle CORE_REQUEST_CONNECT request.
2864 * @param client the client issuing the request
2865 * @param message the "struct ConnectMessage"
2868 handle_client_request_connect (void *cls,
2869 struct GNUNET_SERVER_Client *client,
2870 const struct GNUNET_MessageHeader *message)
2872 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2873 struct Neighbour *n;
2874 struct GNUNET_TIME_Relative timeout;
2876 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2879 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2882 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2883 n = find_neighbour (&cm->peer);
2885 n = create_neighbour (&cm->peer);
2886 if ( (GNUNET_YES == n->is_connected) ||
2889 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2890 "Core received `%s' request for `%4s', already connected!\n",
2892 GNUNET_i2s (&cm->peer));
2893 return; /* already connected, or at least trying */
2895 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2897 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2898 "Core received `%s' request for `%4s', will try to establish connection\n",
2900 GNUNET_i2s (&cm->peer));
2902 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2903 /* ask transport to connect to the peer */
2904 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2906 sizeof (struct GNUNET_MessageHeader), 0,
2908 ¬ify_transport_connect_done,
2910 GNUNET_break (NULL != n->th);
2915 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2916 * the neighbour's struct and retry send_key. Or, if we did not get a
2917 * HELLO, just do nothing.
2919 * @param cls the 'struct Neighbour' to retry sending the key for
2920 * @param peer the peer for which this is the HELLO
2921 * @param hello HELLO message of that peer
2924 process_hello_retry_send_key (void *cls,
2925 const struct GNUNET_PeerIdentity *peer,
2926 const struct GNUNET_HELLO_Message *hello)
2928 struct Neighbour *n = cls;
2933 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2934 "Entered `%s' and `%s' is NULL!\n",
2935 "process_hello_retry_send_key",
2939 if (n->public_key != NULL)
2941 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2943 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2944 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2946 GNUNET_STATISTICS_update (stats,
2947 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2955 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2956 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
2957 GNUNET_i2s (&n->peer));
2959 GNUNET_STATISTICS_update (stats,
2960 gettext_noop ("# Delayed connecting due to lack of public key"),
2963 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2964 n->retry_set_key_task
2965 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2966 &set_key_retry_task, n);
2972 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2973 "Entered `%s' for peer `%4s'\n",
2974 "process_hello_retry_send_key",
2977 if (n->public_key != NULL)
2979 /* already have public key, why are we here? */
2985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2986 "Received new `%s' message for `%4s', initiating key exchange.\n",
2991 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2992 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2994 GNUNET_STATISTICS_update (stats,
2995 gettext_noop ("# Error extracting public key from HELLO"),
2998 GNUNET_free (n->public_key);
2999 n->public_key = NULL;
3001 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3002 "GNUNET_HELLO_get_key returned awfully\n");
3010 * Send our key (and encrypted PING) to the other peer.
3012 * @param n the other peer
3015 send_key (struct Neighbour *n)
3017 struct MessageEntry *pos;
3018 struct SetKeyMessage *sm;
3019 struct MessageEntry *me;
3020 struct PingMessage pp;
3021 struct PingMessage *pm;
3022 struct GNUNET_CRYPTO_AesInitializationVector iv;
3024 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3026 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3027 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3029 if (n->pitr != NULL)
3032 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3033 "Key exchange in progress with `%4s'.\n",
3034 GNUNET_i2s (&n->peer));
3036 return; /* already in progress */
3038 if (GNUNET_YES != n->is_connected)
3041 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3042 "Not yet connected to peer `%4s'!\n",
3043 GNUNET_i2s (&n->peer));
3047 GNUNET_STATISTICS_update (stats,
3048 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
3051 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
3053 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
3055 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3056 ¬ify_encrypted_transmit_ready,
3062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3063 "Asked to perform key exchange with `%4s'.\n",
3064 GNUNET_i2s (&n->peer));
3066 if (n->public_key == NULL)
3068 /* lookup n's public key, then try again */
3070 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3071 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
3072 GNUNET_i2s (&n->peer));
3074 GNUNET_assert (n->pitr == NULL);
3075 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3077 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
3078 &process_hello_retry_send_key, n);
3081 pos = n->encrypted_head;
3084 if (GNUNET_YES == pos->is_setkey)
3086 if (pos->sender_status == n->status)
3089 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3090 "`%s' message for `%4s' queued already\n",
3092 GNUNET_i2s (&n->peer));
3094 goto trigger_processing;
3096 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
3101 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3102 "Removing queued `%s' message for `%4s', will create a new one\n",
3104 GNUNET_i2s (&n->peer));
3114 case PEER_STATE_DOWN:
3115 n->status = PEER_STATE_KEY_SENT;
3117 case PEER_STATE_KEY_SENT:
3119 case PEER_STATE_KEY_RECEIVED:
3121 case PEER_STATE_KEY_CONFIRMED:
3129 /* first, set key message */
3130 me = GNUNET_malloc (sizeof (struct MessageEntry) +
3131 sizeof (struct SetKeyMessage) +
3132 sizeof (struct PingMessage));
3133 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
3134 me->priority = SET_KEY_PRIORITY;
3135 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
3136 me->is_setkey = GNUNET_YES;
3137 me->got_slack = GNUNET_YES; /* do not defer this one! */
3138 me->sender_status = n->status;
3139 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3143 sm = (struct SetKeyMessage *) &me[1];
3144 sm->header.size = htons (sizeof (struct SetKeyMessage));
3145 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
3146 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
3147 PEER_STATE_KEY_SENT : n->status));
3149 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3150 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3151 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3152 sizeof (struct GNUNET_PeerIdentity));
3153 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
3154 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
3155 sm->target = n->peer;
3156 GNUNET_assert (GNUNET_OK ==
3157 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
3159 GNUNET_CRYPTO_AesSessionKey),
3161 &sm->encrypted_key));
3162 GNUNET_assert (GNUNET_OK ==
3163 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
3165 pm = (struct PingMessage *) &sm[1];
3166 pm->header.size = htons (sizeof (struct PingMessage));
3167 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
3168 pm->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3169 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
3170 pp.challenge = n->ping_challenge;
3171 pp.target = n->peer;
3173 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3174 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
3176 (unsigned int) n->ping_challenge,
3177 GNUNET_i2s (&n->peer),
3178 (unsigned int) n->encrypt_key.crc32,
3179 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3186 sizeof (struct PingMessage) -
3187 ((void *) &pm->target - (void *) pm));
3188 GNUNET_STATISTICS_update (stats,
3189 gettext_noop ("# SET_KEY and PING messages created"),
3193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3194 "Have %llu ms left for `%s' transmission.\n",
3195 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).rel_value,
3199 /* trigger queue processing */
3200 process_encrypted_neighbour_queue (n);
3201 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
3202 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
3203 n->retry_set_key_task
3204 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3205 &set_key_retry_task, n);
3210 * We received a SET_KEY message. Validate and update
3211 * our key material and status.
3213 * @param n the neighbour from which we received message m
3214 * @param m the set key message we received
3215 * @param ats performance data
3216 * @param ats_count number of entries in ats (excluding 0-termination)
3219 handle_set_key (struct Neighbour *n,
3220 const struct SetKeyMessage *m,
3221 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3222 uint32_t ats_count);
3227 * PEERINFO is giving us a HELLO for a peer. Add the public key to
3228 * the neighbour's struct and retry handling the set_key message. Or,
3229 * if we did not get a HELLO, just free the set key message.
3231 * @param cls pointer to the set key message
3232 * @param peer the peer for which this is the HELLO
3233 * @param hello HELLO message of that peer
3236 process_hello_retry_handle_set_key (void *cls,
3237 const struct GNUNET_PeerIdentity *peer,
3238 const struct GNUNET_HELLO_Message *hello)
3240 struct Neighbour *n = cls;
3241 struct SetKeyMessage *sm = n->skm;
3247 if (n->public_key != NULL)
3250 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3251 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
3253 GNUNET_i2s (&n->peer),
3256 handle_set_key (n, sm, NULL, 0);
3260 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3261 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
3263 GNUNET_i2s (&n->peer));
3268 if (n->public_key != NULL)
3269 return; /* multiple HELLOs match!? */
3271 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3272 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3274 GNUNET_break_op (0);
3275 GNUNET_free (n->public_key);
3276 n->public_key = NULL;
3282 * Merge the given performance data with the data we currently
3283 * track for the given neighbour.
3285 * @param n neighbour
3286 * @param ats new performance data
3287 * @param ats_count number of records in ats
3290 update_neighbour_performance (struct Neighbour *n,
3291 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3299 for (i = 0; i < ats_count; i++)
3301 for (j=0;j < n->ats_count; j++)
3303 if (n->ats[j].type == ats[i].type)
3305 n->ats[j].value = ats[i].value;
3309 if (j == n->ats_count)
3311 GNUNET_array_append (n->ats,
3320 * We received a PING message. Validate and transmit
3323 * @param n sender of the PING
3324 * @param m the encrypted PING message itself
3325 * @param ats performance data
3326 * @param ats_count number of entries in ats (excluding 0-termination)
3329 handle_ping (struct Neighbour *n,
3330 const struct PingMessage *m,
3331 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3334 struct PingMessage t;
3335 struct PongMessage tx;
3336 struct PongMessage *tp;
3337 struct MessageEntry *me;
3338 struct GNUNET_CRYPTO_AesInitializationVector iv;
3341 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3342 "Core service receives `%s' request from `%4s'.\n",
3343 "PING", GNUNET_i2s (&n->peer));
3345 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3351 sizeof (struct PingMessage) -
3352 ((void *) &m->target - (void *) m)))
3355 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3356 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u, IV %u (salt %u)\n",
3358 GNUNET_i2s (&t.target),
3359 (unsigned int) t.challenge,
3360 (unsigned int) n->decrypt_key.crc32,
3361 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3364 GNUNET_STATISTICS_update (stats,
3365 gettext_noop ("# PING messages decrypted"),
3368 if (0 != memcmp (&t.target,
3369 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3371 GNUNET_break_op (0);
3374 update_neighbour_performance (n, ats, ats_count);
3375 me = GNUNET_malloc (sizeof (struct MessageEntry) +
3376 sizeof (struct PongMessage));
3377 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3381 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
3382 me->priority = PONG_PRIORITY;
3383 me->size = sizeof (struct PongMessage);
3384 tx.inbound_bw_limit = n->bw_in;
3385 tx.challenge = t.challenge;
3386 tx.target = t.target;
3387 tp = (struct PongMessage *) &me[1];
3388 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
3389 tp->header.size = htons (sizeof (struct PongMessage));
3390 tp->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3391 derive_pong_iv (&iv, &n->encrypt_key, tp->iv_seed, t.challenge, &n->peer);
3396 sizeof (struct PongMessage) -
3397 ((void *) &tp->challenge - (void *) tp));
3398 GNUNET_STATISTICS_update (stats,
3399 gettext_noop ("# PONG messages created"),
3403 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3404 "Encrypting `%s' with challenge %u using key %u, IV %u (salt %u)\n",
3406 (unsigned int) t.challenge,
3407 (unsigned int) n->encrypt_key.crc32,
3408 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3411 /* trigger queue processing */
3412 process_encrypted_neighbour_queue (n);
3417 * We received a PONG message. Validate and update our status.
3419 * @param n sender of the PONG
3420 * @param m the encrypted PONG message itself
3421 * @param ats performance data
3422 * @param ats_count number of entries in ats (excluding 0-termination)
3425 handle_pong (struct Neighbour *n,
3426 const struct PongMessage *m,
3427 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3430 struct PongMessage t;
3431 struct ConnectNotifyMessage *cnm;
3432 struct GNUNET_CRYPTO_AesInitializationVector iv;
3433 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
3434 struct GNUNET_TRANSPORT_ATS_Information *mats;
3438 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3439 "Core service receives `%s' response from `%4s'.\n",
3440 "PONG", GNUNET_i2s (&n->peer));
3442 /* mark as garbage, just to be sure */
3443 memset (&t, 255, sizeof (t));
3444 derive_pong_iv (&iv, &n->decrypt_key, m->iv_seed, n->ping_challenge,
3451 sizeof (struct PongMessage) -
3452 ((void *) &m->challenge - (void *) m)))
3454 GNUNET_break_op (0);
3457 GNUNET_STATISTICS_update (stats,
3458 gettext_noop ("# PONG messages decrypted"),
3462 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3463 "Decrypted `%s' from `%4s' with challenge %u using key %u, IV %u (salt %u)\n",
3465 GNUNET_i2s (&t.target),
3466 (unsigned int) t.challenge,
3467 (unsigned int) n->decrypt_key.crc32,
3468 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3471 if ((0 != memcmp (&t.target,
3473 sizeof (struct GNUNET_PeerIdentity))) ||
3474 (n->ping_challenge != t.challenge))
3476 /* PONG malformed */
3478 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3479 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
3481 GNUNET_i2s (&n->peer),
3482 (unsigned int) n->ping_challenge);
3483 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3484 "Received malformed `%s' received from `%4s' with challenge %u\n",
3485 "PONG", GNUNET_i2s (&t.target),
3486 (unsigned int) t.challenge);
3488 GNUNET_break_op (n->ping_challenge != t.challenge);
3493 case PEER_STATE_DOWN:
3494 GNUNET_break (0); /* should be impossible */
3496 case PEER_STATE_KEY_SENT:
3497 GNUNET_break (0); /* should be impossible, how did we decrypt? */
3499 case PEER_STATE_KEY_RECEIVED:
3500 GNUNET_STATISTICS_update (stats,
3501 gettext_noop ("# Session keys confirmed via PONG"),
3504 n->status = PEER_STATE_KEY_CONFIRMED;
3505 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
3507 n->bw_out_external_limit = t.inbound_bw_limit;
3508 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3509 n->bw_out_internal_limit);
3510 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3512 GNUNET_TRANSPORT_set_quota (transport,
3516 GNUNET_TIME_UNIT_FOREVER_REL,
3520 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3521 "Confirmed key via `%s' message for peer `%4s'\n",
3522 "PONG", GNUNET_i2s (&n->peer));
3524 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3526 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3527 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3529 update_neighbour_performance (n, ats, ats_count);
3530 size = sizeof (struct ConnectNotifyMessage) +
3531 (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3532 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3535 /* recovery strategy: throw away performance data */
3536 GNUNET_array_grow (n->ats,
3539 size = sizeof (struct PeerStatusNotifyMessage) +
3540 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3542 cnm = (struct ConnectNotifyMessage*) buf;
3543 cnm->header.size = htons (size);
3544 cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3545 cnm->ats_count = htonl (n->ats_count);
3546 cnm->peer = n->peer;
3550 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
3551 mats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3552 mats[n->ats_count].value = htonl (0);
3553 send_to_all_clients (&cnm->header,
3555 GNUNET_CORE_OPTION_SEND_CONNECT);
3556 process_encrypted_neighbour_queue (n);
3558 case PEER_STATE_KEY_CONFIRMED:
3559 n->last_activity = GNUNET_TIME_absolute_get ();
3560 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3561 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3563 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3566 handle_peer_status_change (n);
3576 * We received a SET_KEY message. Validate and update
3577 * our key material and status.
3579 * @param n the neighbour from which we received message m
3580 * @param m the set key message we received
3581 * @param ats performance data
3582 * @param ats_count number of entries in ats (excluding 0-termination)
3585 handle_set_key (struct Neighbour *n,
3586 const struct SetKeyMessage *m,
3587 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3590 struct SetKeyMessage *m_cpy;
3591 struct GNUNET_TIME_Absolute t;
3592 struct GNUNET_CRYPTO_AesSessionKey k;
3593 struct PingMessage *ping;
3594 struct PongMessage *pong;
3595 enum PeerStateMachine sender_status;
3598 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3599 "Core service receives `%s' request from `%4s'.\n",
3600 "SET_KEY", GNUNET_i2s (&n->peer));
3602 if (n->public_key == NULL)
3604 if (n->pitr != NULL)
3607 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3608 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3614 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3615 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3617 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3618 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3619 /* lookup n's public key, then try again */
3620 GNUNET_assert (n->skm == NULL);
3622 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3624 GNUNET_TIME_UNIT_MINUTES,
3625 &process_hello_retry_handle_set_key, n);
3626 GNUNET_STATISTICS_update (stats,
3627 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3632 if (0 != memcmp (&m->target,
3634 sizeof (struct GNUNET_PeerIdentity)))
3636 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3637 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3639 GNUNET_i2s (&m->target));
3642 if ((ntohl (m->purpose.size) !=
3643 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3644 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3645 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3646 sizeof (struct GNUNET_PeerIdentity)) ||
3648 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3649 &m->purpose, &m->signature, n->public_key)))
3651 /* invalid signature */
3652 GNUNET_break_op (0);
3655 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3656 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3657 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3658 (t.abs_value < n->decrypt_key_created.abs_value))
3660 /* this could rarely happen due to massive re-ordering of
3661 messages on the network level, but is most likely either
3662 a bug or some adversary messing with us. Report. */
3663 GNUNET_break_op (0);
3667 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3668 "Decrypting key material.\n");
3670 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3673 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3674 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3675 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3677 /* failed to decrypt !? */
3678 GNUNET_break_op (0);
3681 GNUNET_STATISTICS_update (stats,
3682 gettext_noop ("# SET_KEY messages decrypted"),
3686 if (n->decrypt_key_created.abs_value != t.abs_value)
3688 /* fresh key, reset sequence numbers */
3689 n->last_sequence_number_received = 0;
3690 n->last_packets_bitmap = 0;
3691 n->decrypt_key_created = t;
3693 update_neighbour_performance (n, ats, ats_count);
3694 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3697 case PEER_STATE_DOWN:
3698 n->status = PEER_STATE_KEY_RECEIVED;
3700 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3701 "Responding to `%s' with my own key.\n", "SET_KEY");
3705 case PEER_STATE_KEY_SENT:
3706 case PEER_STATE_KEY_RECEIVED:
3707 n->status = PEER_STATE_KEY_RECEIVED;
3708 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3709 (sender_status != PEER_STATE_KEY_CONFIRMED))
3712 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3713 "Responding to `%s' with my own key (other peer has status %u).\n",
3715 (unsigned int) sender_status);
3720 case PEER_STATE_KEY_CONFIRMED:
3721 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3722 (sender_status != PEER_STATE_KEY_CONFIRMED))
3725 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3726 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3728 (unsigned int) sender_status);
3737 if (n->pending_ping != NULL)
3739 ping = n->pending_ping;
3740 n->pending_ping = NULL;
3741 handle_ping (n, ping, NULL, 0);
3744 if (n->pending_pong != NULL)
3746 pong = n->pending_pong;
3747 n->pending_pong = NULL;
3748 handle_pong (n, pong, NULL, 0);
3755 * Send a P2P message to a client.
3757 * @param sender who sent us the message?
3758 * @param client who should we give the message to?
3759 * @param m contains the message to transmit
3760 * @param msize number of bytes in buf to transmit
3763 send_p2p_message_to_client (struct Neighbour *sender,
3764 struct Client *client,
3765 const void *m, size_t msize)
3767 size_t size = msize + sizeof (struct NotifyTrafficMessage) +
3768 (sender->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3770 struct NotifyTrafficMessage *ntm;
3771 struct GNUNET_TRANSPORT_ATS_Information *ats;
3773 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3776 /* recovery strategy: throw performance data away... */
3777 GNUNET_array_grow (sender->ats,
3780 size = msize + sizeof (struct NotifyTrafficMessage) +
3781 (sender->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3784 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3785 "Core service passes message from `%4s' of type %u to client.\n",
3786 GNUNET_i2s(&sender->peer),
3787 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3789 ntm = (struct NotifyTrafficMessage *) buf;
3790 ntm->header.size = htons (size);
3791 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3792 ntm->ats_count = htonl (sender->ats_count);
3793 ntm->peer = sender->peer;
3797 sizeof (struct GNUNET_TRANSPORT_ATS_Information) * sender->ats_count);
3798 ats[sender->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3799 ats[sender->ats_count].value = htonl (0);
3800 memcpy (&ats[sender->ats_count+1],
3803 send_to_client (client, &ntm->header, GNUNET_YES);
3808 * Deliver P2P message to interested clients.
3810 * @param cls always NULL
3811 * @param client who sent us the message (struct Neighbour)
3812 * @param m the message
3815 deliver_message (void *cls,
3817 const struct GNUNET_MessageHeader *m)
3819 struct Neighbour *sender = client;
3820 size_t msize = ntohs (m->size);
3822 struct Client *cpos;
3828 type = ntohs (m->type);
3830 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3831 "Received encapsulated message of type %u and size %u from `%4s'\n",
3832 (unsigned int) type,
3834 GNUNET_i2s (&sender->peer));
3836 GNUNET_snprintf (buf,
3838 gettext_noop ("# bytes of messages of type %u received"),
3839 (unsigned int) type);
3840 GNUNET_STATISTICS_set (stats,
3844 dropped = GNUNET_YES;
3846 while (cpos != NULL)
3848 deliver_full = GNUNET_NO;
3849 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3850 deliver_full = GNUNET_YES;
3853 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3855 if (type != cpos->types[tpos])
3857 deliver_full = GNUNET_YES;
3861 if (GNUNET_YES == deliver_full)
3863 send_p2p_message_to_client (sender, cpos, m, msize);
3864 dropped = GNUNET_NO;
3866 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3868 send_p2p_message_to_client (sender, cpos, m,
3869 sizeof (struct GNUNET_MessageHeader));
3873 if (dropped == GNUNET_YES)
3876 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3877 "Message of type %u from `%4s' not delivered to any client.\n",
3878 (unsigned int) type,
3879 GNUNET_i2s (&sender->peer));
3881 GNUNET_STATISTICS_update (stats,
3882 gettext_noop ("# messages not delivered to any client"),
3889 * We received an encrypted message. Decrypt, validate and
3890 * pass on to the appropriate clients.
3892 * @param n target of the message
3893 * @param m encrypted message
3894 * @param ats performance data
3895 * @param ats_count number of entries in ats (excluding 0-termination)
3898 handle_encrypted_message (struct Neighbour *n,
3899 const struct EncryptedMessage *m,
3900 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3903 size_t size = ntohs (m->header.size);
3905 struct EncryptedMessage *pt; /* plaintext */
3908 struct GNUNET_TIME_Absolute t;
3909 struct GNUNET_CRYPTO_AesInitializationVector iv;
3910 struct GNUNET_CRYPTO_AuthKey auth_key;
3913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3914 "Core service receives `%s' request from `%4s'.\n",
3915 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3918 derive_auth_key (&auth_key,
3921 n->decrypt_key_created);
3922 GNUNET_CRYPTO_hmac (&auth_key,
3923 &m->sequence_number,
3924 size - ENCRYPTED_HEADER_SIZE, &ph);
3926 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3927 "Re-Authenticated %u bytes of ciphertext (`%u'): `%s'\n",
3928 (unsigned int) size - ENCRYPTED_HEADER_SIZE,
3929 GNUNET_CRYPTO_crc32_n (&m->sequence_number,
3930 size - ENCRYPTED_HEADER_SIZE),
3934 if (0 != memcmp (&ph,
3936 sizeof (GNUNET_HashCode)))
3938 /* checksum failed */
3939 GNUNET_break_op (0);
3942 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3947 &m->sequence_number,
3948 &buf[ENCRYPTED_HEADER_SIZE],
3949 size - ENCRYPTED_HEADER_SIZE))
3951 pt = (struct EncryptedMessage *) buf;
3953 /* validate sequence number */
3954 snum = ntohl (pt->sequence_number);
3955 if (n->last_sequence_number_received == snum)
3957 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3958 "Received duplicate message, ignoring.\n");
3959 /* duplicate, ignore */
3960 GNUNET_STATISTICS_set (stats,
3961 gettext_noop ("# bytes dropped (duplicates)"),
3966 if ((n->last_sequence_number_received > snum) &&
3967 (n->last_sequence_number_received - snum > 32))
3969 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3970 "Received ancient out of sequence message, ignoring.\n");
3971 /* ancient out of sequence, ignore */
3972 GNUNET_STATISTICS_set (stats,
3973 gettext_noop ("# bytes dropped (out of sequence)"),
3978 if (n->last_sequence_number_received > snum)
3980 unsigned int rotbit =
3981 1 << (n->last_sequence_number_received - snum - 1);
3982 if ((n->last_packets_bitmap & rotbit) != 0)
3984 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3985 "Received duplicate message, ignoring.\n");
3986 GNUNET_STATISTICS_set (stats,
3987 gettext_noop ("# bytes dropped (duplicates)"),
3990 /* duplicate, ignore */
3993 n->last_packets_bitmap |= rotbit;
3995 if (n->last_sequence_number_received < snum)
3997 int shift = (snum - n->last_sequence_number_received);
3998 if (shift >= 8 * sizeof(n->last_packets_bitmap))
3999 n->last_packets_bitmap = 0;
4001 n->last_packets_bitmap <<= shift;
4002 n->last_sequence_number_received = snum;
4005 /* check timestamp */
4006 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
4007 if (GNUNET_TIME_absolute_get_duration (t).rel_value > MAX_MESSAGE_AGE.rel_value)
4009 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4011 ("Message received far too old (%llu ms). Content ignored.\n"),
4012 GNUNET_TIME_absolute_get_duration (t).rel_value);
4013 GNUNET_STATISTICS_set (stats,
4014 gettext_noop ("# bytes dropped (ancient message)"),
4020 /* process decrypted message(s) */
4021 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
4023 #if DEBUG_CORE_SET_QUOTA
4024 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4025 "Received %u b/s as new inbound limit for peer `%4s'\n",
4026 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
4027 GNUNET_i2s (&n->peer));
4029 n->bw_out_external_limit = pt->inbound_bw_limit;
4030 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
4031 n->bw_out_internal_limit);
4032 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
4034 GNUNET_TRANSPORT_set_quota (transport,
4038 GNUNET_TIME_UNIT_FOREVER_REL,
4041 n->last_activity = GNUNET_TIME_absolute_get ();
4042 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
4043 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
4045 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
4048 GNUNET_STATISTICS_set (stats,
4049 gettext_noop ("# bytes of payload decrypted"),
4050 size - sizeof (struct EncryptedMessage),
4052 handle_peer_status_change (n);
4053 update_neighbour_performance (n, ats, ats_count);
4054 if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst,
4056 &buf[sizeof (struct EncryptedMessage)],
4057 size - sizeof (struct EncryptedMessage),
4058 GNUNET_YES, GNUNET_NO))
4059 GNUNET_break_op (0);
4064 * Function called by the transport for each received message.
4066 * @param cls closure
4067 * @param peer (claimed) identity of the other peer
4068 * @param message the message
4069 * @param ats performance data
4070 * @param ats_count number of entries in ats (excluding 0-termination)
4073 handle_transport_receive (void *cls,
4074 const struct GNUNET_PeerIdentity *peer,
4075 const struct GNUNET_MessageHeader *message,
4076 const struct GNUNET_TRANSPORT_ATS_Information *ats,
4079 struct Neighbour *n;
4080 struct GNUNET_TIME_Absolute now;
4087 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4088 "Received message of type %u from `%4s', demultiplexing.\n",
4089 (unsigned int) ntohs (message->type),
4092 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4097 n = find_neighbour (peer);
4099 n = create_neighbour (peer);
4100 changed = GNUNET_YES; /* FIXME... */
4101 up = (n->status == PEER_STATE_KEY_CONFIRMED);
4102 type = ntohs (message->type);
4103 size = ntohs (message->size);
4106 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
4107 if (size != sizeof (struct SetKeyMessage))
4109 GNUNET_break_op (0);
4112 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
4114 (const struct SetKeyMessage *) message,
4117 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
4118 if (size < sizeof (struct EncryptedMessage) +
4119 sizeof (struct GNUNET_MessageHeader))
4121 GNUNET_break_op (0);
4124 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
4125 (n->status != PEER_STATE_KEY_CONFIRMED))
4127 GNUNET_break_op (0);
4130 handle_encrypted_message (n,
4131 (const struct EncryptedMessage *) message,
4134 case GNUNET_MESSAGE_TYPE_CORE_PING:
4135 if (size != sizeof (struct PingMessage))
4137 GNUNET_break_op (0);
4140 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
4141 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
4142 (n->status != PEER_STATE_KEY_CONFIRMED))
4145 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4146 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
4147 "PING", GNUNET_i2s (&n->peer));
4149 GNUNET_free_non_null (n->pending_ping);
4150 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
4151 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
4154 handle_ping (n, (const struct PingMessage *) message,
4157 case GNUNET_MESSAGE_TYPE_CORE_PONG:
4158 if (size != sizeof (struct PongMessage))
4160 GNUNET_break_op (0);
4163 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
4164 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
4165 (n->status != PEER_STATE_KEY_CONFIRMED) )
4168 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4169 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
4170 "PONG", GNUNET_i2s (&n->peer));
4172 GNUNET_free_non_null (n->pending_pong);
4173 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
4174 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
4177 handle_pong (n, (const struct PongMessage *) message,
4181 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4182 _("Unsupported message of type %u received.\n"),
4183 (unsigned int) type);
4186 if (n->status == PEER_STATE_KEY_CONFIRMED)
4188 now = GNUNET_TIME_absolute_get ();
4189 n->last_activity = now;
4190 changed = GNUNET_YES;
4193 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
4194 n->time_established = now;
4196 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
4197 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
4199 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
4204 handle_peer_status_change (n);
4209 * Function that recalculates the bandwidth quota for the
4210 * given neighbour and transmits it to the transport service.
4212 * @param cls neighbour for the quota update
4216 neighbour_quota_update (void *cls,
4217 const struct GNUNET_SCHEDULER_TaskContext *tc)
4219 struct Neighbour *n = cls;
4220 struct GNUNET_BANDWIDTH_Value32NBO q_in;
4221 struct GNUNET_BANDWIDTH_Value32NBO q_out;
4222 struct GNUNET_BANDWIDTH_Value32NBO q_out_min;
4225 unsigned long long distributable;
4226 uint64_t need_per_peer;
4227 uint64_t need_per_second;
4230 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4231 "Neighbour quota update calculation running for peer `%4s'\n",
4232 GNUNET_i2s (&n->peer));
4234 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
4235 /* calculate relative preference among all neighbours;
4236 divides by a bit more to avoid division by zero AND to
4237 account for possibility of new neighbours joining any time
4238 AND to convert to double... */
4239 if (preference_sum == 0)
4241 pref_rel = 1.0 / (double) neighbour_count;
4245 pref_rel = n->current_preference / preference_sum;
4247 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
4248 GNUNET_TIME_UNIT_SECONDS);
4249 need_per_second = need_per_peer * neighbour_count;
4251 /* calculate inbound bandwidth per peer */
4253 if (bandwidth_target_in_bps > need_per_second)
4254 distributable = bandwidth_target_in_bps - need_per_second;
4255 share = distributable * pref_rel;
4256 if (share + need_per_peer > UINT32_MAX)
4257 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4259 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4261 /* calculate outbound bandwidth per peer */
4263 if (bandwidth_target_out_bps > need_per_second)
4264 distributable = bandwidth_target_out_bps - need_per_second;
4265 share = distributable * pref_rel;
4266 if (share + need_per_peer > UINT32_MAX)
4267 q_out = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4269 q_out = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4270 n->bw_out_internal_limit = q_out;
4272 q_out_min = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit, n->bw_out_internal_limit);
4273 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window, n->bw_out);
4275 /* check if we want to disconnect for good due to inactivity */
4276 if ( (GNUNET_TIME_absolute_get_duration (get_neighbour_timeout (n)).rel_value > 0) &&
4277 (GNUNET_TIME_absolute_get_duration (n->time_established).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) )
4280 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4281 "Forcing disconnect of `%4s' due to inactivity\n",
4282 GNUNET_i2s (&n->peer));
4284 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
4286 #if DEBUG_CORE_QUOTA
4287 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4288 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
4289 GNUNET_i2s (&n->peer),
4290 (unsigned int) ntohl (q_in.value__),
4291 bandwidth_target_out_bps,
4292 (unsigned int) ntohl (n->bw_in.value__),
4293 (unsigned int) ntohl (n->bw_out.value__),
4294 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
4296 if ((n->bw_in.value__ != q_in.value__) || (n->bw_out.value__ != q_out_min.value__))
4298 if (n->bw_in.value__ != q_in.value__)
4300 if (n->bw_out.value__ != q_out_min.value__)
4301 n->bw_out = q_out_min;
4302 if (GNUNET_YES == n->is_connected)
4303 GNUNET_TRANSPORT_set_quota (transport,
4307 GNUNET_TIME_UNIT_FOREVER_REL,
4309 handle_peer_status_change (n);
4311 schedule_quota_update (n);
4316 * Function called by transport to notify us that
4317 * a peer connected to us (on the network level).
4319 * @param cls closure
4320 * @param peer the peer that connected
4321 * @param ats performance data
4322 * @param ats_count number of entries in ats (excluding 0-termination)
4325 handle_transport_notify_connect (void *cls,
4326 const struct GNUNET_PeerIdentity *peer,
4327 const struct GNUNET_TRANSPORT_ATS_Information *ats,
4330 struct Neighbour *n;
4332 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4337 n = find_neighbour (peer);
4340 if (GNUNET_YES == n->is_connected)
4342 /* duplicate connect notification!? */
4349 n = create_neighbour (peer);
4351 GNUNET_STATISTICS_update (stats,
4352 gettext_noop ("# peers connected (transport)"),
4355 n->is_connected = GNUNET_YES;
4356 update_neighbour_performance (n, ats, ats_count);
4357 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
4360 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
4364 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4365 "Received connection from `%4s'.\n",
4366 GNUNET_i2s (&n->peer));
4368 GNUNET_TRANSPORT_set_quota (transport,
4372 GNUNET_TIME_UNIT_FOREVER_REL,
4379 * Function called by transport telling us that a peer
4382 * @param cls closure
4383 * @param peer the peer that disconnected
4386 handle_transport_notify_disconnect (void *cls,
4387 const struct GNUNET_PeerIdentity *peer)
4389 struct DisconnectNotifyMessage cnm;
4390 struct Neighbour *n;
4391 struct ClientActiveRequest *car;
4392 struct GNUNET_TIME_Relative left;
4395 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4396 "Peer `%4s' disconnected from us; received notification from transport.\n", GNUNET_i2s (peer));
4399 n = find_neighbour (peer);
4405 GNUNET_break (n->is_connected);
4406 if (n->status == PEER_STATE_KEY_CONFIRMED)
4408 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
4409 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
4411 send_to_all_clients (&cnm.header, GNUNET_NO, GNUNET_CORE_OPTION_SEND_DISCONNECT);
4414 /* On transport disconnect transport doesn't cancel requests, so must do so here. */
4417 GNUNET_TRANSPORT_notify_transmit_ready_cancel(n->th);
4421 n->is_connected = GNUNET_NO;
4422 n->status = PEER_STATE_DOWN;
4423 while (NULL != (car = n->active_client_request_head))
4425 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
4426 n->active_client_request_tail,
4428 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
4429 &n->peer.hashPubKey,
4434 GNUNET_STATISTICS_update (stats,
4435 gettext_noop ("# peers connected (transport)"),
4438 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
4439 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
4440 left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4441 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
4442 n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (),
4444 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
4445 &consider_free_task,
4451 * Last task run during shutdown. Disconnects us from
4455 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4457 struct Neighbour *n;
4461 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4462 "Core service shutting down.\n");
4464 while (NULL != (n = neighbours))
4466 neighbours = n->next;
4467 GNUNET_assert (neighbour_count > 0);
4471 GNUNET_assert (transport != NULL);
4472 GNUNET_TRANSPORT_disconnect (transport);
4474 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
4475 GNUNET_SERVER_notification_context_destroy (notifier);
4477 while (NULL != (c = clients))
4478 handle_client_disconnect (NULL, c->client_handle);
4479 if (my_private_key != NULL)
4480 GNUNET_CRYPTO_rsa_key_free (my_private_key);
4482 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4483 if (peerinfo != NULL)
4484 GNUNET_PEERINFO_disconnect (peerinfo);
4486 GNUNET_SERVER_mst_destroy (mst);
4491 * Initiate core service.
4493 * @param cls closure
4494 * @param server the initialized server
4495 * @param c configuration to use
4499 struct GNUNET_SERVER_Handle *server,
4500 const struct GNUNET_CONFIGURATION_Handle *c)
4502 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4503 {&handle_client_init, NULL,
4504 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
4505 {&handle_client_iterate_peers, NULL,
4506 GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
4507 sizeof (struct GNUNET_MessageHeader)},
4508 {&handle_client_request_info, NULL,
4509 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
4510 sizeof (struct RequestInfoMessage)},
4511 {&handle_client_send_request, NULL,
4512 GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST,
4513 sizeof (struct SendMessageRequest)},
4514 {&handle_client_send, NULL,
4515 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
4516 {&handle_client_request_connect, NULL,
4517 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
4518 sizeof (struct ConnectMessage)},
4524 /* parse configuration */
4527 GNUNET_CONFIGURATION_get_value_number (c,
4530 &bandwidth_target_in_bps)) ||
4532 GNUNET_CONFIGURATION_get_value_number (c,
4535 &bandwidth_target_out_bps)) ||
4537 GNUNET_CONFIGURATION_get_value_filename (c,
4539 "HOSTKEY", &keyfile)))
4541 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4543 ("Core service is lacking key configuration settings. Exiting.\n"));
4544 GNUNET_SCHEDULER_shutdown ();
4547 peerinfo = GNUNET_PEERINFO_connect (cfg);
4548 if (NULL == peerinfo)
4550 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4551 _("Could not access PEERINFO service. Exiting.\n"));
4552 GNUNET_SCHEDULER_shutdown ();
4553 GNUNET_free (keyfile);
4556 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4557 GNUNET_free (keyfile);
4558 if (my_private_key == NULL)
4560 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4561 _("Core service could not access hostkey. Exiting.\n"));
4562 GNUNET_PEERINFO_disconnect (peerinfo);
4563 GNUNET_SCHEDULER_shutdown ();
4566 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4567 GNUNET_CRYPTO_hash (&my_public_key,
4568 sizeof (my_public_key), &my_identity.hashPubKey);
4569 /* setup notification */
4570 notifier = GNUNET_SERVER_notification_context_create (server,
4572 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4573 /* setup transport connection */
4574 transport = GNUNET_TRANSPORT_connect (cfg,
4577 &handle_transport_receive,
4578 &handle_transport_notify_connect,
4579 &handle_transport_notify_disconnect);
4580 GNUNET_assert (NULL != transport);
4581 stats = GNUNET_STATISTICS_create ("core", cfg);
4583 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded CORE_SEND requests"), 0, GNUNET_NO);
4584 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 0, GNUNET_NO);
4586 mst = GNUNET_SERVER_mst_create (&deliver_message,
4588 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4589 &cleaning_task, NULL);
4590 /* process client requests */
4591 GNUNET_SERVER_add_handlers (server, handlers);
4592 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4593 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
4599 * The main function for the transport service.
4601 * @param argc number of arguments from the command line
4602 * @param argv command line arguments
4603 * @return 0 ok, 1 on error
4606 main (int argc, char *const *argv)
4608 return (GNUNET_OK ==
4609 GNUNET_SERVICE_run (argc,
4612 GNUNET_SERVICE_OPTION_NONE,
4613 &run, NULL)) ? 0 : 1;
4616 /* end of gnunet-service-core.c */