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+1) * 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+1) * 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)
3310 GNUNET_array_append (n->ats,
3318 * We received a PING message. Validate and transmit
3321 * @param n sender of the PING
3322 * @param m the encrypted PING message itself
3323 * @param ats performance data
3324 * @param ats_count number of entries in ats (excluding 0-termination)
3327 handle_ping (struct Neighbour *n,
3328 const struct PingMessage *m,
3329 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3332 struct PingMessage t;
3333 struct PongMessage tx;
3334 struct PongMessage *tp;
3335 struct MessageEntry *me;
3336 struct GNUNET_CRYPTO_AesInitializationVector iv;
3339 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3340 "Core service receives `%s' request from `%4s'.\n",
3341 "PING", GNUNET_i2s (&n->peer));
3343 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3349 sizeof (struct PingMessage) -
3350 ((void *) &m->target - (void *) m)))
3353 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3354 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u, IV %u (salt %u)\n",
3356 GNUNET_i2s (&t.target),
3357 (unsigned int) t.challenge,
3358 (unsigned int) n->decrypt_key.crc32,
3359 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3362 GNUNET_STATISTICS_update (stats,
3363 gettext_noop ("# PING messages decrypted"),
3366 if (0 != memcmp (&t.target,
3367 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3369 GNUNET_break_op (0);
3372 update_neighbour_performance (n, ats, ats_count);
3373 me = GNUNET_malloc (sizeof (struct MessageEntry) +
3374 sizeof (struct PongMessage));
3375 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3379 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
3380 me->priority = PONG_PRIORITY;
3381 me->size = sizeof (struct PongMessage);
3382 tx.inbound_bw_limit = n->bw_in;
3383 tx.challenge = t.challenge;
3384 tx.target = t.target;
3385 tp = (struct PongMessage *) &me[1];
3386 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
3387 tp->header.size = htons (sizeof (struct PongMessage));
3388 tp->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3389 derive_pong_iv (&iv, &n->encrypt_key, tp->iv_seed, t.challenge, &n->peer);
3394 sizeof (struct PongMessage) -
3395 ((void *) &tp->challenge - (void *) tp));
3396 GNUNET_STATISTICS_update (stats,
3397 gettext_noop ("# PONG messages created"),
3401 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3402 "Encrypting `%s' with challenge %u using key %u, IV %u (salt %u)\n",
3404 (unsigned int) t.challenge,
3405 (unsigned int) n->encrypt_key.crc32,
3406 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3409 /* trigger queue processing */
3410 process_encrypted_neighbour_queue (n);
3415 * We received a PONG message. Validate and update our status.
3417 * @param n sender of the PONG
3418 * @param m the encrypted PONG message itself
3419 * @param ats performance data
3420 * @param ats_count number of entries in ats (excluding 0-termination)
3423 handle_pong (struct Neighbour *n,
3424 const struct PongMessage *m,
3425 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3428 struct PongMessage t;
3429 struct ConnectNotifyMessage *cnm;
3430 struct GNUNET_CRYPTO_AesInitializationVector iv;
3431 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
3432 struct GNUNET_TRANSPORT_ATS_Information *mats;
3436 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3437 "Core service receives `%s' response from `%4s'.\n",
3438 "PONG", GNUNET_i2s (&n->peer));
3440 /* mark as garbage, just to be sure */
3441 memset (&t, 255, sizeof (t));
3442 derive_pong_iv (&iv, &n->decrypt_key, m->iv_seed, n->ping_challenge,
3449 sizeof (struct PongMessage) -
3450 ((void *) &m->challenge - (void *) m)))
3452 GNUNET_break_op (0);
3455 GNUNET_STATISTICS_update (stats,
3456 gettext_noop ("# PONG messages decrypted"),
3460 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3461 "Decrypted `%s' from `%4s' with challenge %u using key %u, IV %u (salt %u)\n",
3463 GNUNET_i2s (&t.target),
3464 (unsigned int) t.challenge,
3465 (unsigned int) n->decrypt_key.crc32,
3466 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3469 if ((0 != memcmp (&t.target,
3471 sizeof (struct GNUNET_PeerIdentity))) ||
3472 (n->ping_challenge != t.challenge))
3474 /* PONG malformed */
3476 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3477 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
3479 GNUNET_i2s (&n->peer),
3480 (unsigned int) n->ping_challenge);
3481 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3482 "Received malformed `%s' received from `%4s' with challenge %u\n",
3483 "PONG", GNUNET_i2s (&t.target),
3484 (unsigned int) t.challenge);
3486 GNUNET_break_op (n->ping_challenge != t.challenge);
3491 case PEER_STATE_DOWN:
3492 GNUNET_break (0); /* should be impossible */
3494 case PEER_STATE_KEY_SENT:
3495 GNUNET_break (0); /* should be impossible, how did we decrypt? */
3497 case PEER_STATE_KEY_RECEIVED:
3498 GNUNET_STATISTICS_update (stats,
3499 gettext_noop ("# Session keys confirmed via PONG"),
3502 n->status = PEER_STATE_KEY_CONFIRMED;
3503 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
3505 n->bw_out_external_limit = t.inbound_bw_limit;
3506 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3507 n->bw_out_internal_limit);
3508 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3510 GNUNET_TRANSPORT_set_quota (transport,
3514 GNUNET_TIME_UNIT_FOREVER_REL,
3518 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3519 "Confirmed key via `%s' message for peer `%4s'\n",
3520 "PONG", GNUNET_i2s (&n->peer));
3522 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3524 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3525 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3527 update_neighbour_performance (n, ats, ats_count);
3528 size = sizeof (struct ConnectNotifyMessage) +
3529 (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3530 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3533 /* recovery strategy: throw away performance data */
3534 GNUNET_array_grow (n->ats,
3537 size = sizeof (struct PeerStatusNotifyMessage) +
3538 (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3540 cnm = (struct ConnectNotifyMessage*) buf;
3541 cnm->header.size = htons (size);
3542 cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3543 cnm->ats_count = htonl (n->ats_count);
3547 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
3548 mats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3549 mats[n->ats_count].value = htonl (0);
3550 send_to_all_clients (&cnm->header,
3552 GNUNET_CORE_OPTION_SEND_CONNECT);
3553 process_encrypted_neighbour_queue (n);
3555 case PEER_STATE_KEY_CONFIRMED:
3556 n->last_activity = GNUNET_TIME_absolute_get ();
3557 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3558 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3560 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3563 handle_peer_status_change (n);
3573 * We received a SET_KEY message. Validate and update
3574 * our key material and status.
3576 * @param n the neighbour from which we received message m
3577 * @param m the set key message we received
3578 * @param ats performance data
3579 * @param ats_count number of entries in ats (excluding 0-termination)
3582 handle_set_key (struct Neighbour *n,
3583 const struct SetKeyMessage *m,
3584 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3587 struct SetKeyMessage *m_cpy;
3588 struct GNUNET_TIME_Absolute t;
3589 struct GNUNET_CRYPTO_AesSessionKey k;
3590 struct PingMessage *ping;
3591 struct PongMessage *pong;
3592 enum PeerStateMachine sender_status;
3595 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3596 "Core service receives `%s' request from `%4s'.\n",
3597 "SET_KEY", GNUNET_i2s (&n->peer));
3599 if (n->public_key == NULL)
3601 if (n->pitr != NULL)
3604 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3605 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3611 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3612 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3614 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3615 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3616 /* lookup n's public key, then try again */
3617 GNUNET_assert (n->skm == NULL);
3619 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3621 GNUNET_TIME_UNIT_MINUTES,
3622 &process_hello_retry_handle_set_key, n);
3623 GNUNET_STATISTICS_update (stats,
3624 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3629 if (0 != memcmp (&m->target,
3631 sizeof (struct GNUNET_PeerIdentity)))
3633 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3634 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3636 GNUNET_i2s (&m->target));
3639 if ((ntohl (m->purpose.size) !=
3640 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3641 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3642 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3643 sizeof (struct GNUNET_PeerIdentity)) ||
3645 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3646 &m->purpose, &m->signature, n->public_key)))
3648 /* invalid signature */
3649 GNUNET_break_op (0);
3652 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3653 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3654 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3655 (t.abs_value < n->decrypt_key_created.abs_value))
3657 /* this could rarely happen due to massive re-ordering of
3658 messages on the network level, but is most likely either
3659 a bug or some adversary messing with us. Report. */
3660 GNUNET_break_op (0);
3664 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3665 "Decrypting key material.\n");
3667 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3670 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3671 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3672 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3674 /* failed to decrypt !? */
3675 GNUNET_break_op (0);
3678 GNUNET_STATISTICS_update (stats,
3679 gettext_noop ("# SET_KEY messages decrypted"),
3683 if (n->decrypt_key_created.abs_value != t.abs_value)
3685 /* fresh key, reset sequence numbers */
3686 n->last_sequence_number_received = 0;
3687 n->last_packets_bitmap = 0;
3688 n->decrypt_key_created = t;
3690 update_neighbour_performance (n, ats, ats_count);
3691 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3694 case PEER_STATE_DOWN:
3695 n->status = PEER_STATE_KEY_RECEIVED;
3697 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3698 "Responding to `%s' with my own key.\n", "SET_KEY");
3702 case PEER_STATE_KEY_SENT:
3703 case PEER_STATE_KEY_RECEIVED:
3704 n->status = PEER_STATE_KEY_RECEIVED;
3705 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3706 (sender_status != PEER_STATE_KEY_CONFIRMED))
3709 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3710 "Responding to `%s' with my own key (other peer has status %u).\n",
3712 (unsigned int) sender_status);
3717 case PEER_STATE_KEY_CONFIRMED:
3718 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3719 (sender_status != PEER_STATE_KEY_CONFIRMED))
3722 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3723 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3725 (unsigned int) sender_status);
3734 if (n->pending_ping != NULL)
3736 ping = n->pending_ping;
3737 n->pending_ping = NULL;
3738 handle_ping (n, ping, NULL, 0);
3741 if (n->pending_pong != NULL)
3743 pong = n->pending_pong;
3744 n->pending_pong = NULL;
3745 handle_pong (n, pong, NULL, 0);
3752 * Send a P2P message to a client.
3754 * @param sender who sent us the message?
3755 * @param client who should we give the message to?
3756 * @param m contains the message to transmit
3757 * @param msize number of bytes in buf to transmit
3760 send_p2p_message_to_client (struct Neighbour *sender,
3761 struct Client *client,
3762 const void *m, size_t msize)
3764 size_t size = msize + sizeof (struct NotifyTrafficMessage) +
3765 (sender->ats_count+1) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3767 struct NotifyTrafficMessage *ntm;
3768 struct GNUNET_TRANSPORT_ATS_Information *ats;
3770 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3773 /* recovery strategy: throw performance data away... */
3774 GNUNET_array_grow (sender->ats,
3777 size = msize + sizeof (struct NotifyTrafficMessage) +
3778 (sender->ats_count+1) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3781 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3782 "Core service passes message from `%4s' of type %u to client.\n",
3783 GNUNET_i2s(&sender->peer),
3784 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3786 ntm = (struct NotifyTrafficMessage *) buf;
3787 ntm->header.size = htons (size);
3788 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3789 ntm->ats_count = htonl (sender->ats_count);
3790 ntm->peer = sender->peer;
3794 sizeof (struct GNUNET_TRANSPORT_ATS_Information) * sender->ats_count);
3795 ats[sender->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3796 ats[sender->ats_count].value = htonl (0);
3797 memcpy (&ats[sender->ats_count+1],
3800 send_to_client (client, &ntm->header, GNUNET_YES);
3805 * Deliver P2P message to interested clients.
3807 * @param cls always NULL
3808 * @param client who sent us the message (struct Neighbour)
3809 * @param m the message
3812 deliver_message (void *cls,
3814 const struct GNUNET_MessageHeader *m)
3816 struct Neighbour *sender = client;
3817 size_t msize = ntohs (m->size);
3819 struct Client *cpos;
3825 type = ntohs (m->type);
3827 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3828 "Received encapsulated message of type %u and size %u from `%4s'\n",
3829 (unsigned int) type,
3831 GNUNET_i2s (&sender->peer));
3833 GNUNET_snprintf (buf,
3835 gettext_noop ("# bytes of messages of type %u received"),
3836 (unsigned int) type);
3837 GNUNET_STATISTICS_set (stats,
3841 dropped = GNUNET_YES;
3843 while (cpos != NULL)
3845 deliver_full = GNUNET_NO;
3846 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3847 deliver_full = GNUNET_YES;
3850 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3852 if (type != cpos->types[tpos])
3854 deliver_full = GNUNET_YES;
3858 if (GNUNET_YES == deliver_full)
3860 send_p2p_message_to_client (sender, cpos, m, msize);
3861 dropped = GNUNET_NO;
3863 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3865 send_p2p_message_to_client (sender, cpos, m,
3866 sizeof (struct GNUNET_MessageHeader));
3870 if (dropped == GNUNET_YES)
3873 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3874 "Message of type %u from `%4s' not delivered to any client.\n",
3875 (unsigned int) type,
3876 GNUNET_i2s (&sender->peer));
3878 GNUNET_STATISTICS_update (stats,
3879 gettext_noop ("# messages not delivered to any client"),
3886 * We received an encrypted message. Decrypt, validate and
3887 * pass on to the appropriate clients.
3889 * @param n target of the message
3890 * @param m encrypted message
3891 * @param ats performance data
3892 * @param ats_count number of entries in ats (excluding 0-termination)
3895 handle_encrypted_message (struct Neighbour *n,
3896 const struct EncryptedMessage *m,
3897 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3900 size_t size = ntohs (m->header.size);
3902 struct EncryptedMessage *pt; /* plaintext */
3905 struct GNUNET_TIME_Absolute t;
3906 struct GNUNET_CRYPTO_AesInitializationVector iv;
3907 struct GNUNET_CRYPTO_AuthKey auth_key;
3910 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3911 "Core service receives `%s' request from `%4s'.\n",
3912 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3915 derive_auth_key (&auth_key,
3918 n->decrypt_key_created);
3919 GNUNET_CRYPTO_hmac (&auth_key,
3920 &m->sequence_number,
3921 size - ENCRYPTED_HEADER_SIZE, &ph);
3923 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3924 "Re-Authenticated %u bytes of ciphertext (`%u'): `%s'\n",
3925 (unsigned int) size - ENCRYPTED_HEADER_SIZE,
3926 GNUNET_CRYPTO_crc32_n (&m->sequence_number,
3927 size - ENCRYPTED_HEADER_SIZE),
3931 if (0 != memcmp (&ph,
3933 sizeof (GNUNET_HashCode)))
3935 /* checksum failed */
3936 GNUNET_break_op (0);
3939 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3944 &m->sequence_number,
3945 &buf[ENCRYPTED_HEADER_SIZE],
3946 size - ENCRYPTED_HEADER_SIZE))
3948 pt = (struct EncryptedMessage *) buf;
3950 /* validate sequence number */
3951 snum = ntohl (pt->sequence_number);
3952 if (n->last_sequence_number_received == snum)
3954 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3955 "Received duplicate message, ignoring.\n");
3956 /* duplicate, ignore */
3957 GNUNET_STATISTICS_set (stats,
3958 gettext_noop ("# bytes dropped (duplicates)"),
3963 if ((n->last_sequence_number_received > snum) &&
3964 (n->last_sequence_number_received - snum > 32))
3966 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3967 "Received ancient out of sequence message, ignoring.\n");
3968 /* ancient out of sequence, ignore */
3969 GNUNET_STATISTICS_set (stats,
3970 gettext_noop ("# bytes dropped (out of sequence)"),
3975 if (n->last_sequence_number_received > snum)
3977 unsigned int rotbit =
3978 1 << (n->last_sequence_number_received - snum - 1);
3979 if ((n->last_packets_bitmap & rotbit) != 0)
3981 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3982 "Received duplicate message, ignoring.\n");
3983 GNUNET_STATISTICS_set (stats,
3984 gettext_noop ("# bytes dropped (duplicates)"),
3987 /* duplicate, ignore */
3990 n->last_packets_bitmap |= rotbit;
3992 if (n->last_sequence_number_received < snum)
3994 int shift = (snum - n->last_sequence_number_received);
3995 if (shift >= 8 * sizeof(n->last_packets_bitmap))
3996 n->last_packets_bitmap = 0;
3998 n->last_packets_bitmap <<= shift;
3999 n->last_sequence_number_received = snum;
4002 /* check timestamp */
4003 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
4004 if (GNUNET_TIME_absolute_get_duration (t).rel_value > MAX_MESSAGE_AGE.rel_value)
4006 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4008 ("Message received far too old (%llu ms). Content ignored.\n"),
4009 GNUNET_TIME_absolute_get_duration (t).rel_value);
4010 GNUNET_STATISTICS_set (stats,
4011 gettext_noop ("# bytes dropped (ancient message)"),
4017 /* process decrypted message(s) */
4018 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
4020 #if DEBUG_CORE_SET_QUOTA
4021 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4022 "Received %u b/s as new inbound limit for peer `%4s'\n",
4023 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
4024 GNUNET_i2s (&n->peer));
4026 n->bw_out_external_limit = pt->inbound_bw_limit;
4027 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
4028 n->bw_out_internal_limit);
4029 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
4031 GNUNET_TRANSPORT_set_quota (transport,
4035 GNUNET_TIME_UNIT_FOREVER_REL,
4038 n->last_activity = GNUNET_TIME_absolute_get ();
4039 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
4040 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
4042 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
4045 GNUNET_STATISTICS_set (stats,
4046 gettext_noop ("# bytes of payload decrypted"),
4047 size - sizeof (struct EncryptedMessage),
4049 handle_peer_status_change (n);
4050 update_neighbour_performance (n, ats, ats_count);
4051 if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst,
4053 &buf[sizeof (struct EncryptedMessage)],
4054 size - sizeof (struct EncryptedMessage),
4055 GNUNET_YES, GNUNET_NO))
4056 GNUNET_break_op (0);
4061 * Function called by the transport for each received message.
4063 * @param cls closure
4064 * @param peer (claimed) identity of the other peer
4065 * @param message the message
4066 * @param ats performance data
4067 * @param ats_count number of entries in ats (excluding 0-termination)
4070 handle_transport_receive (void *cls,
4071 const struct GNUNET_PeerIdentity *peer,
4072 const struct GNUNET_MessageHeader *message,
4073 const struct GNUNET_TRANSPORT_ATS_Information *ats,
4076 struct Neighbour *n;
4077 struct GNUNET_TIME_Absolute now;
4084 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4085 "Received message of type %u from `%4s', demultiplexing.\n",
4086 (unsigned int) ntohs (message->type),
4089 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4094 n = find_neighbour (peer);
4096 n = create_neighbour (peer);
4097 changed = GNUNET_YES; /* FIXME... */
4098 up = (n->status == PEER_STATE_KEY_CONFIRMED);
4099 type = ntohs (message->type);
4100 size = ntohs (message->size);
4103 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
4104 if (size != sizeof (struct SetKeyMessage))
4106 GNUNET_break_op (0);
4109 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
4111 (const struct SetKeyMessage *) message,
4114 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
4115 if (size < sizeof (struct EncryptedMessage) +
4116 sizeof (struct GNUNET_MessageHeader))
4118 GNUNET_break_op (0);
4121 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
4122 (n->status != PEER_STATE_KEY_CONFIRMED))
4124 GNUNET_break_op (0);
4127 handle_encrypted_message (n,
4128 (const struct EncryptedMessage *) message,
4131 case GNUNET_MESSAGE_TYPE_CORE_PING:
4132 if (size != sizeof (struct PingMessage))
4134 GNUNET_break_op (0);
4137 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
4138 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
4139 (n->status != PEER_STATE_KEY_CONFIRMED))
4142 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4143 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
4144 "PING", GNUNET_i2s (&n->peer));
4146 GNUNET_free_non_null (n->pending_ping);
4147 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
4148 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
4151 handle_ping (n, (const struct PingMessage *) message,
4154 case GNUNET_MESSAGE_TYPE_CORE_PONG:
4155 if (size != sizeof (struct PongMessage))
4157 GNUNET_break_op (0);
4160 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
4161 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
4162 (n->status != PEER_STATE_KEY_CONFIRMED) )
4165 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4166 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
4167 "PONG", GNUNET_i2s (&n->peer));
4169 GNUNET_free_non_null (n->pending_pong);
4170 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
4171 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
4174 handle_pong (n, (const struct PongMessage *) message,
4178 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4179 _("Unsupported message of type %u received.\n"),
4180 (unsigned int) type);
4183 if (n->status == PEER_STATE_KEY_CONFIRMED)
4185 now = GNUNET_TIME_absolute_get ();
4186 n->last_activity = now;
4187 changed = GNUNET_YES;
4190 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
4191 n->time_established = now;
4193 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
4194 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
4196 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
4201 handle_peer_status_change (n);
4206 * Function that recalculates the bandwidth quota for the
4207 * given neighbour and transmits it to the transport service.
4209 * @param cls neighbour for the quota update
4213 neighbour_quota_update (void *cls,
4214 const struct GNUNET_SCHEDULER_TaskContext *tc)
4216 struct Neighbour *n = cls;
4217 struct GNUNET_BANDWIDTH_Value32NBO q_in;
4218 struct GNUNET_BANDWIDTH_Value32NBO q_out;
4219 struct GNUNET_BANDWIDTH_Value32NBO q_out_min;
4222 unsigned long long distributable;
4223 uint64_t need_per_peer;
4224 uint64_t need_per_second;
4227 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4228 "Neighbour quota update calculation running for peer `%4s'\n",
4229 GNUNET_i2s (&n->peer));
4231 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
4232 /* calculate relative preference among all neighbours;
4233 divides by a bit more to avoid division by zero AND to
4234 account for possibility of new neighbours joining any time
4235 AND to convert to double... */
4236 if (preference_sum == 0)
4238 pref_rel = 1.0 / (double) neighbour_count;
4242 pref_rel = n->current_preference / preference_sum;
4244 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
4245 GNUNET_TIME_UNIT_SECONDS);
4246 need_per_second = need_per_peer * neighbour_count;
4248 /* calculate inbound bandwidth per peer */
4250 if (bandwidth_target_in_bps > need_per_second)
4251 distributable = bandwidth_target_in_bps - need_per_second;
4252 share = distributable * pref_rel;
4253 if (share + need_per_peer > UINT32_MAX)
4254 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4256 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4258 /* calculate outbound bandwidth per peer */
4260 if (bandwidth_target_out_bps > need_per_second)
4261 distributable = bandwidth_target_out_bps - need_per_second;
4262 share = distributable * pref_rel;
4263 if (share + need_per_peer > UINT32_MAX)
4264 q_out = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4266 q_out = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4267 n->bw_out_internal_limit = q_out;
4269 q_out_min = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit, n->bw_out_internal_limit);
4270 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window, n->bw_out);
4272 /* check if we want to disconnect for good due to inactivity */
4273 if ( (GNUNET_TIME_absolute_get_duration (get_neighbour_timeout (n)).rel_value > 0) &&
4274 (GNUNET_TIME_absolute_get_duration (n->time_established).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) )
4277 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4278 "Forcing disconnect of `%4s' due to inactivity\n",
4279 GNUNET_i2s (&n->peer));
4281 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
4283 #if DEBUG_CORE_QUOTA
4284 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4285 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
4286 GNUNET_i2s (&n->peer),
4287 (unsigned int) ntohl (q_in.value__),
4288 bandwidth_target_out_bps,
4289 (unsigned int) ntohl (n->bw_in.value__),
4290 (unsigned int) ntohl (n->bw_out.value__),
4291 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
4293 if ((n->bw_in.value__ != q_in.value__) || (n->bw_out.value__ != q_out_min.value__))
4295 if (n->bw_in.value__ != q_in.value__)
4297 if (n->bw_out.value__ != q_out_min.value__)
4298 n->bw_out = q_out_min;
4299 if (GNUNET_YES == n->is_connected)
4300 GNUNET_TRANSPORT_set_quota (transport,
4304 GNUNET_TIME_UNIT_FOREVER_REL,
4306 handle_peer_status_change (n);
4308 schedule_quota_update (n);
4313 * Function called by transport to notify us that
4314 * a peer connected to us (on the network level).
4316 * @param cls closure
4317 * @param peer the peer that connected
4318 * @param ats performance data
4319 * @param ats_count number of entries in ats (excluding 0-termination)
4322 handle_transport_notify_connect (void *cls,
4323 const struct GNUNET_PeerIdentity *peer,
4324 const struct GNUNET_TRANSPORT_ATS_Information *ats,
4327 struct Neighbour *n;
4329 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4334 n = find_neighbour (peer);
4337 if (GNUNET_YES == n->is_connected)
4339 /* duplicate connect notification!? */
4346 n = create_neighbour (peer);
4348 GNUNET_STATISTICS_update (stats,
4349 gettext_noop ("# peers connected (transport)"),
4352 n->is_connected = GNUNET_YES;
4353 update_neighbour_performance (n, ats, ats_count);
4354 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
4357 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
4361 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4362 "Received connection from `%4s'.\n",
4363 GNUNET_i2s (&n->peer));
4365 GNUNET_TRANSPORT_set_quota (transport,
4369 GNUNET_TIME_UNIT_FOREVER_REL,
4376 * Function called by transport telling us that a peer
4379 * @param cls closure
4380 * @param peer the peer that disconnected
4383 handle_transport_notify_disconnect (void *cls,
4384 const struct GNUNET_PeerIdentity *peer)
4386 struct DisconnectNotifyMessage cnm;
4387 struct Neighbour *n;
4388 struct ClientActiveRequest *car;
4389 struct GNUNET_TIME_Relative left;
4392 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4393 "Peer `%4s' disconnected from us; received notification from transport.\n", GNUNET_i2s (peer));
4396 n = find_neighbour (peer);
4402 GNUNET_break (n->is_connected);
4403 if (n->status == PEER_STATE_KEY_CONFIRMED)
4405 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
4406 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
4408 send_to_all_clients (&cnm.header, GNUNET_NO, GNUNET_CORE_OPTION_SEND_DISCONNECT);
4411 /* On transport disconnect transport doesn't cancel requests, so must do so here. */
4414 GNUNET_TRANSPORT_notify_transmit_ready_cancel(n->th);
4418 n->is_connected = GNUNET_NO;
4419 n->status = PEER_STATE_DOWN;
4420 while (NULL != (car = n->active_client_request_head))
4422 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
4423 n->active_client_request_tail,
4425 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
4426 &n->peer.hashPubKey,
4431 GNUNET_STATISTICS_update (stats,
4432 gettext_noop ("# peers connected (transport)"),
4435 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
4436 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
4437 left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4438 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
4439 n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (),
4441 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
4442 &consider_free_task,
4448 * Last task run during shutdown. Disconnects us from
4452 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4454 struct Neighbour *n;
4458 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4459 "Core service shutting down.\n");
4461 while (NULL != (n = neighbours))
4463 neighbours = n->next;
4464 GNUNET_assert (neighbour_count > 0);
4468 GNUNET_assert (transport != NULL);
4469 GNUNET_TRANSPORT_disconnect (transport);
4471 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
4472 GNUNET_SERVER_notification_context_destroy (notifier);
4474 while (NULL != (c = clients))
4475 handle_client_disconnect (NULL, c->client_handle);
4476 if (my_private_key != NULL)
4477 GNUNET_CRYPTO_rsa_key_free (my_private_key);
4479 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4480 if (peerinfo != NULL)
4481 GNUNET_PEERINFO_disconnect (peerinfo);
4483 GNUNET_SERVER_mst_destroy (mst);
4488 * Initiate core service.
4490 * @param cls closure
4491 * @param server the initialized server
4492 * @param c configuration to use
4496 struct GNUNET_SERVER_Handle *server,
4497 const struct GNUNET_CONFIGURATION_Handle *c)
4499 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4500 {&handle_client_init, NULL,
4501 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
4502 {&handle_client_iterate_peers, NULL,
4503 GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
4504 sizeof (struct GNUNET_MessageHeader)},
4505 {&handle_client_request_info, NULL,
4506 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
4507 sizeof (struct RequestInfoMessage)},
4508 {&handle_client_send_request, NULL,
4509 GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST,
4510 sizeof (struct SendMessageRequest)},
4511 {&handle_client_send, NULL,
4512 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
4513 {&handle_client_request_connect, NULL,
4514 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
4515 sizeof (struct ConnectMessage)},
4521 /* parse configuration */
4524 GNUNET_CONFIGURATION_get_value_number (c,
4527 &bandwidth_target_in_bps)) ||
4529 GNUNET_CONFIGURATION_get_value_number (c,
4532 &bandwidth_target_out_bps)) ||
4534 GNUNET_CONFIGURATION_get_value_filename (c,
4536 "HOSTKEY", &keyfile)))
4538 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4540 ("Core service is lacking key configuration settings. Exiting.\n"));
4541 GNUNET_SCHEDULER_shutdown ();
4544 peerinfo = GNUNET_PEERINFO_connect (cfg);
4545 if (NULL == peerinfo)
4547 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4548 _("Could not access PEERINFO service. Exiting.\n"));
4549 GNUNET_SCHEDULER_shutdown ();
4550 GNUNET_free (keyfile);
4553 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4554 GNUNET_free (keyfile);
4555 if (my_private_key == NULL)
4557 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4558 _("Core service could not access hostkey. Exiting.\n"));
4559 GNUNET_PEERINFO_disconnect (peerinfo);
4560 GNUNET_SCHEDULER_shutdown ();
4563 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4564 GNUNET_CRYPTO_hash (&my_public_key,
4565 sizeof (my_public_key), &my_identity.hashPubKey);
4566 /* setup notification */
4567 notifier = GNUNET_SERVER_notification_context_create (server,
4569 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4570 /* setup transport connection */
4571 transport = GNUNET_TRANSPORT_connect (cfg,
4574 &handle_transport_receive,
4575 &handle_transport_notify_connect,
4576 &handle_transport_notify_disconnect);
4577 GNUNET_assert (NULL != transport);
4578 stats = GNUNET_STATISTICS_create ("core", cfg);
4580 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded CORE_SEND requests"), 0, GNUNET_NO);
4581 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 0, GNUNET_NO);
4583 mst = GNUNET_SERVER_mst_create (&deliver_message,
4585 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4586 &cleaning_task, NULL);
4587 /* process client requests */
4588 GNUNET_SERVER_add_handlers (server, handlers);
4589 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4590 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
4596 * The main function for the transport service.
4598 * @param argc number of arguments from the command line
4599 * @param argv command line arguments
4600 * @return 0 ok, 1 on error
4603 main (int argc, char *const *argv)
4605 return (GNUNET_OK ==
4606 GNUNET_SERVICE_run (argc,
4609 GNUNET_SERVICE_OPTION_NONE,
4610 &run, NULL)) ? 0 : 1;
4613 /* end of gnunet-service-core.c */