2 This file is part of GNUnet.
3 (C) 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file core/gnunet-service-core.c
23 * @brief high-level P2P messaging
24 * @author Christian Grothoff
26 * Considerations for later:
27 * - check that hostkey used by transport (for HELLOs) is the
28 * same as the hostkey that we are using!
29 * - add code to send PINGs if we are about to time-out otherwise
30 * - optimize lookup (many O(n) list traversals
31 * could ideally be changed to O(1) hash map lookups)
34 #include "gnunet_constants.h"
35 #include "gnunet_util_lib.h"
36 #include "gnunet_hello_lib.h"
37 #include "gnunet_peerinfo_service.h"
38 #include "gnunet_protocols.h"
39 #include "gnunet_signatures.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet_transport_service.h"
45 #define DEBUG_HANDSHAKE GNUNET_NO
47 #define DEBUG_CORE_QUOTA GNUNET_YES
50 * Receive and send buffer windows grow over time. For
51 * how long can 'unused' bandwidth accumulate before we
52 * need to cap it? (specified in seconds).
54 #define MAX_WINDOW_TIME_S (5 * 60)
57 * How many messages do we queue up at most for optional
58 * notifications to a client? (this can cause notifications
59 * about outgoing messages to be dropped).
61 #define MAX_NOTIFY_QUEUE 1024
64 * Minimum bandwidth (out) to assign to any connected peer.
65 * Should be rather low; values larger than DEFAULT_BW_IN_OUT make no
68 #define MIN_BANDWIDTH_PER_PEER GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT
71 * After how much time past the "official" expiration time do
72 * we discard messages? Should not be zero since we may
73 * intentionally defer transmission until close to the deadline
74 * and then may be slightly past the deadline due to inaccuracy
75 * in sleep and our own CPU consumption.
77 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
80 * What is the maximum delay for a SET_KEY message?
82 #define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
85 * How long do we wait for SET_KEY confirmation initially?
87 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 1)
90 * What is the maximum delay for a PING message?
92 #define MAX_PING_DELAY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 2)
95 * What is the maximum delay for a PONG message?
97 #define MAX_PONG_DELAY GNUNET_TIME_relative_multiply (MAX_PING_DELAY, 2)
100 * What is the minimum frequency for a PING message?
102 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
105 * How often do we recalculate bandwidth quotas?
107 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
110 * What is the priority for a SET_KEY message?
112 #define SET_KEY_PRIORITY 0xFFFFFF
115 * What is the priority for a PING message?
117 #define PING_PRIORITY 0xFFFFFF
120 * What is the priority for a PONG message?
122 #define PONG_PRIORITY 0xFFFFFF
125 * How many messages do we queue per peer at most? Must be at
128 #define MAX_PEER_QUEUE_SIZE 16
131 * How many non-mandatory messages do we queue per client at most?
133 #define MAX_CLIENT_QUEUE_SIZE 32
136 * What is the maximum age of a message for us to consider
137 * processing it? Note that this looks at the timestamp used
138 * by the other peer, so clock skew between machines does
139 * come into play here. So this should be picked high enough
140 * so that a little bit of clock skew does not prevent peers
141 * from connecting to us.
143 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
147 * State machine for our P2P encryption handshake. Everyone starts in
148 * "DOWN", if we receive the other peer's key (other peer initiated)
149 * we start in state RECEIVED (since we will immediately send our
150 * own); otherwise we start in SENT. If we get back a PONG from
151 * within either state, we move up to CONFIRMED (the PONG will always
152 * be sent back encrypted with the key we sent to the other peer).
154 enum PeerStateMachine
158 PEER_STATE_KEY_RECEIVED,
159 PEER_STATE_KEY_CONFIRMED
164 * Encapsulation for encrypted messages exchanged between
165 * peers. Followed by the actual encrypted data.
167 struct EncryptedMessage
170 * Message type is either CORE_ENCRYPTED_MESSAGE.
172 struct GNUNET_MessageHeader header;
175 * Random value used for IV generation.
177 uint32_t iv_seed GNUNET_PACKED;
180 * MAC of the encrypted message (starting at 'sequence_number'),
181 * used to verify message integrity. Everything after this value
182 * (excluding this value itself) will be encrypted and authenticated.
183 * ENCRYPTED_HEADER_SIZE must be set to the offset of the *next* field.
185 GNUNET_HashCode hmac;
188 * Sequence number, in network byte order. This field
189 * must be the first encrypted/decrypted field
191 uint32_t sequence_number GNUNET_PACKED;
194 * Desired bandwidth (how much we should send to this peer / how
195 * much is the sender willing to receive)?
197 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
200 * Timestamp. Used to prevent reply of ancient messages
201 * (recent messages are caught with the sequence number).
203 struct GNUNET_TIME_AbsoluteNBO timestamp;
209 * Number of bytes (at the beginning) of "struct EncryptedMessage"
210 * that are NOT encrypted.
212 #define ENCRYPTED_HEADER_SIZE (offsetof(struct EncryptedMessage, sequence_number))
216 * We're sending an (encrypted) PING to the other peer to check if he
217 * can decrypt. The other peer should respond with a PONG with the
218 * same content, except this time encrypted with the receiver's key.
223 * Message type is CORE_PING.
225 struct GNUNET_MessageHeader header;
230 uint32_t iv_seed GNUNET_PACKED;
233 * Intended target of the PING, used primarily to check
234 * that decryption actually worked.
236 struct GNUNET_PeerIdentity target;
239 * Random number chosen to make reply harder.
241 uint32_t challenge GNUNET_PACKED;
247 * Response to a PING. Includes data from the original PING
248 * plus initial bandwidth quota information.
253 * Message type is CORE_PONG.
255 struct GNUNET_MessageHeader header;
260 uint32_t iv_seed GNUNET_PACKED;
263 * Random number to make faking the reply harder. Must be
264 * first field after header (this is where we start to encrypt!).
266 uint32_t challenge GNUNET_PACKED;
269 * Desired bandwidth (how much we should send to this
270 * peer / how much is the sender willing to receive).
272 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
275 * Intended target of the PING, used primarily to check
276 * that decryption actually worked.
278 struct GNUNET_PeerIdentity target;
283 * Message transmitted to set (or update) a session key.
289 * Message type is either CORE_SET_KEY.
291 struct GNUNET_MessageHeader header;
294 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
296 int32_t sender_status GNUNET_PACKED;
299 * Purpose of the signature, will be
300 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
302 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
305 * At what time was this key created?
307 struct GNUNET_TIME_AbsoluteNBO creation_time;
310 * The encrypted session key.
312 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
315 * Who is the intended recipient?
317 struct GNUNET_PeerIdentity target;
320 * Signature of the stuff above (starting at purpose).
322 struct GNUNET_CRYPTO_RsaSignature signature;
328 * Message waiting for transmission. This struct
329 * is followed by the actual content of the message.
335 * We keep messages in a doubly linked list.
337 struct MessageEntry *next;
340 * We keep messages in a doubly linked list.
342 struct MessageEntry *prev;
345 * By when are we supposed to transmit this message?
347 struct GNUNET_TIME_Absolute deadline;
350 * By when are we supposed to transmit this message (after
353 struct GNUNET_TIME_Absolute slack_deadline;
356 * How important is this message to us?
358 unsigned int priority;
361 * If this is a SET_KEY message, what was our connection status when this
362 * message was queued?
364 enum PeerStateMachine sender_status;
367 * Is this a SET_KEY message?
372 * How long is the message? (number of bytes following
373 * the "struct MessageEntry", but not including the
374 * size of "struct MessageEntry" itself!)
379 * Was this message selected for transmission in the
380 * current round? GNUNET_YES or GNUNET_NO.
385 * Did we give this message some slack (delayed sending) previously
386 * (and hence should not give it any more slack)? GNUNET_YES or
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 * Identity of the neighbour.
479 struct GNUNET_PeerIdentity peer;
482 * Key we use to encrypt our messages for the other peer
483 * (initialized by us when we do the handshake).
485 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
488 * Key we use to decrypt messages from the other peer
489 * (given to us by the other peer during the handshake).
491 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
494 * ID of task used for re-trying plaintext scheduling.
496 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
499 * ID of task used for re-trying SET_KEY and PING message.
501 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
504 * ID of task used for updating bandwidth quota for this neighbour.
506 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
509 * ID of task used for sending keep-alive pings.
511 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
514 * ID of task used for cleaning up dead neighbour entries.
516 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
519 * At what time did we generate our encryption key?
521 struct GNUNET_TIME_Absolute encrypt_key_created;
524 * At what time did the other peer generate the decryption key?
526 struct GNUNET_TIME_Absolute decrypt_key_created;
529 * At what time did we initially establish (as in, complete session
530 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
532 struct GNUNET_TIME_Absolute time_established;
535 * At what time did we last receive an encrypted message from the
536 * other peer? Should be zero if status != KEY_CONFIRMED.
538 struct GNUNET_TIME_Absolute last_activity;
541 * At what frequency are we currently re-trying SET_KEY messages?
543 struct GNUNET_TIME_Relative set_key_retry_frequency;
546 * Tracking bandwidth for sending to this peer.
548 struct GNUNET_BANDWIDTH_Tracker available_send_window;
551 * Tracking bandwidth for receiving from this peer.
553 struct GNUNET_BANDWIDTH_Tracker available_recv_window;
556 * How valueable were the messages of this peer recently?
558 unsigned long long current_preference;
561 * Bit map indicating which of the 32 sequence numbers before the last
562 * were received (good for accepting out-of-order packets and
563 * estimating reliability of the connection)
565 unsigned int last_packets_bitmap;
568 * last sequence number received on this connection (highest)
570 uint32_t last_sequence_number_received;
573 * last sequence number transmitted
575 uint32_t last_sequence_number_sent;
578 * Available bandwidth in for this peer (current target).
580 struct GNUNET_BANDWIDTH_Value32NBO bw_in;
583 * Available bandwidth out for this peer (current target).
585 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
588 * Internal bandwidth limit set for this peer (initially typically
589 * set to "-1"). Actual "bw_out" is MIN of
590 * "bpm_out_internal_limit" and "bw_out_external_limit".
592 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
595 * External bandwidth limit set for this peer by the
596 * peer that we are communicating with. "bw_out" is MIN of
597 * "bw_out_internal_limit" and "bw_out_external_limit".
599 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
602 * What was our PING challenge number (for this peer)?
604 uint32_t ping_challenge;
607 * What is our connection status?
609 enum PeerStateMachine status;
612 * Are we currently connected to this neighbour?
620 * Data structure for each client connected to the core service.
625 * Clients are kept in a linked list.
630 * Handle for the client with the server API.
632 struct GNUNET_SERVER_Client *client_handle;
635 * Array of the types of messages this peer cares
636 * about (with "tcnt" entries). Allocated as part
637 * of this client struct, do not free!
639 const uint16_t *types;
642 * Map of peer identities to active transmission requests of this
643 * client to the peer (of type 'struct ClientActiveRequest').
645 struct GNUNET_CONTAINER_MultiHashMap *requests;
648 * Options for messages this client cares about,
649 * see GNUNET_CORE_OPTION_ values.
654 * Number of types of incoming messages this client
655 * specifically cares about. Size of the "types" array.
663 * Record kept for each request for transmission issued by a
664 * client that is still pending.
666 struct ClientActiveRequest
670 * Active requests are kept in a doubly-linked list of
671 * the respective target peer.
673 struct ClientActiveRequest *next;
676 * Active requests are kept in a doubly-linked list of
677 * the respective target peer.
679 struct ClientActiveRequest *prev;
682 * Handle to the client.
684 struct Client *client;
687 * By what time would the client want to see this message out?
689 struct GNUNET_TIME_Absolute deadline;
692 * How important is this request.
697 * How many more requests does this client have?
702 * How many bytes does the client intend to send?
707 * Unique request ID (in big endian).
718 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
723 static struct GNUNET_PeerIdentity my_identity;
728 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
732 * Handle to peerinfo service.
734 static struct GNUNET_PEERINFO_Handle *peerinfo;
737 * Our message stream tokenizer (for encrypted payload).
739 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
744 const struct GNUNET_CONFIGURATION_Handle *cfg;
749 static struct GNUNET_TRANSPORT_Handle *transport;
752 * Linked list of our clients.
754 static struct Client *clients;
757 * Context for notifications we need to send to our clients.
759 static struct GNUNET_SERVER_NotificationContext *notifier;
762 * We keep neighbours in a linked list (for now).
764 static struct Neighbour *neighbours;
767 * For creating statistics.
769 static struct GNUNET_STATISTICS_Handle *stats;
772 * Sum of all preferences among all neighbours.
774 static unsigned long long preference_sum;
777 * Total number of neighbours we have.
779 static unsigned int neighbour_count;
782 * How much inbound bandwidth are we supposed to be using per second?
783 * FIXME: this value is not used!
785 static unsigned long long bandwidth_target_in_bps;
788 * How much outbound bandwidth are we supposed to be using per second?
790 static unsigned long long bandwidth_target_out_bps;
793 * Derive an authentication key from "set key" information
796 derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
797 const struct GNUNET_CRYPTO_AesSessionKey *skey,
799 struct GNUNET_TIME_Absolute creation_time)
801 static const char ctx[] = "authentication key";
802 struct GNUNET_TIME_AbsoluteNBO ctbe;
805 ctbe = GNUNET_TIME_absolute_hton (creation_time);
806 GNUNET_CRYPTO_hmac_derive_key (akey,
820 * Derive an IV from packet information
823 derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
824 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
825 const struct GNUNET_PeerIdentity *identity)
827 static const char ctx[] = "initialization vector";
829 GNUNET_CRYPTO_aes_derive_iv (iv,
833 &identity->hashPubKey.bits,
834 sizeof(identity->hashPubKey.bits),
840 * Derive an IV from pong packet information
843 derive_pong_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
844 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
845 uint32_t challenge, const struct GNUNET_PeerIdentity *identity)
847 static const char ctx[] = "pong initialization vector";
849 GNUNET_CRYPTO_aes_derive_iv (iv,
853 &identity->hashPubKey.bits,
854 sizeof(identity->hashPubKey.bits),
863 * A preference value for a neighbour was update. Update
864 * the preference sum accordingly.
866 * @param inc how much was a preference value increased?
869 update_preference_sum (unsigned long long inc)
872 unsigned long long os;
875 preference_sum += inc;
876 if (preference_sum >= os)
878 /* overflow! compensate by cutting all values in half! */
883 n->current_preference /= 2;
884 preference_sum += n->current_preference;
887 GNUNET_STATISTICS_set (stats, gettext_noop ("# total peer preference"), preference_sum, GNUNET_NO);
892 * Find the entry for the given neighbour.
894 * @param peer identity of the neighbour
895 * @return NULL if we are not connected, otherwise the
898 static struct Neighbour *
899 find_neighbour (const struct GNUNET_PeerIdentity *peer)
901 struct Neighbour *ret;
904 while ((ret != NULL) &&
905 (0 != memcmp (&ret->peer,
906 peer, sizeof (struct GNUNET_PeerIdentity))))
913 * Send a message to one of our clients.
915 * @param client target for the message
916 * @param msg message to transmit
917 * @param can_drop could this message be dropped if the
918 * client's queue is getting too large?
921 send_to_client (struct Client *client,
922 const struct GNUNET_MessageHeader *msg,
925 #if DEBUG_CORE_CLIENT
926 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
927 "Preparing to send %u bytes of message of type %u to client.\n",
928 (unsigned int) ntohs (msg->size),
929 (unsigned int) ntohs (msg->type));
931 GNUNET_SERVER_notification_context_unicast (notifier,
932 client->client_handle,
939 * Send a message to all of our current clients that have
940 * the right options set.
942 * @param msg message to multicast
943 * @param can_drop can this message be discarded if the queue is too long
944 * @param options mask to use
947 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
956 if (0 != (c->options & options))
958 #if DEBUG_CORE_CLIENT
959 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
960 "Sending message of type %u to client.\n",
961 (unsigned int) ntohs (msg->type));
963 send_to_client (c, msg, can_drop);
971 * Function called by transport telling us that a peer
974 * @param n the peer that changed status
977 handle_peer_status_change (struct Neighbour *n)
979 struct PeerStatusNotifyMessage psnm;
981 if ( (! n->is_connected) ||
982 (n->status != PEER_STATE_KEY_CONFIRMED) )
985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
986 "Peer `%4s' changed status\n",
987 GNUNET_i2s (&n->peer));
989 psnm.header.size = htons (sizeof (struct PeerStatusNotifyMessage));
990 psnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_STATUS_CHANGE);
991 psnm.ats_count = htonl (0);
992 psnm.ats.type = htonl (0);
993 psnm.ats.value = htonl (0);
994 psnm.timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_add (n->last_activity,
995 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
996 psnm.bandwidth_in = n->bw_in;
997 psnm.bandwidth_out = n->bw_out;
999 send_to_all_clients (&psnm.header,
1001 GNUNET_CORE_OPTION_SEND_STATUS_CHANGE);
1002 GNUNET_STATISTICS_update (stats,
1003 gettext_noop ("# peer status changes"),
1010 * Go over our message queue and if it is not too long, go
1011 * over the pending requests from clients for this
1012 * neighbour and send some clients a 'READY' notification.
1014 * @param n which peer to process
1017 schedule_peer_messages (struct Neighbour *n)
1019 struct SendMessageReady smr;
1020 struct ClientActiveRequest *car;
1021 struct ClientActiveRequest *pos;
1023 struct MessageEntry *mqe;
1024 unsigned int queue_size;
1026 /* check if neighbour queue is empty enough! */
1034 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1036 #if DEBUG_CORE_CLIENT
1037 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1038 "Not considering client transmission requests: queue full\n");
1040 return; /* queue still full */
1042 /* find highest priority request */
1043 pos = n->active_client_request_head;
1047 if ( (car == NULL) ||
1048 (pos->priority > car->priority) )
1053 return; /* no pending requests */
1054 #if DEBUG_CORE_CLIENT
1055 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1056 "Permitting client transmission request to `%s'\n",
1057 GNUNET_i2s (&n->peer));
1060 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1061 n->active_client_request_tail,
1063 GNUNET_CONTAINER_multihashmap_remove (c->requests,
1064 &n->peer.hashPubKey,
1066 smr.header.size = htons (sizeof (struct SendMessageReady));
1067 smr.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND_READY);
1068 smr.size = htons (car->msize);
1069 smr.smr_id = car->smr_id;
1071 send_to_client (c, &smr.header, GNUNET_NO);
1077 * Handle CORE_SEND_REQUEST message.
1080 handle_client_send_request (void *cls,
1081 struct GNUNET_SERVER_Client *client,
1082 const struct GNUNET_MessageHeader *message)
1084 const struct SendMessageRequest *req;
1085 struct Neighbour *n;
1087 struct ClientActiveRequest *car;
1089 req = (const struct SendMessageRequest*) message;
1090 n = find_neighbour (&req->peer);
1092 (GNUNET_YES != n->is_connected) ||
1093 (n->status != PEER_STATE_KEY_CONFIRMED) )
1095 /* neighbour must have disconnected since request was issued,
1096 ignore (client will realize it once it processes the
1097 disconnect notification) */
1098 #if DEBUG_CORE_CLIENT
1099 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1100 "Dropped client request for transmission (am disconnected)\n");
1102 GNUNET_STATISTICS_update (stats,
1103 gettext_noop ("# send requests dropped (disconnected)"),
1106 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1110 while ( (c != NULL) &&
1111 (c->client_handle != client) )
1115 /* client did not send INIT first! */
1117 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1120 if (c->requests == NULL)
1121 c->requests = GNUNET_CONTAINER_multihashmap_create (16);
1122 #if DEBUG_CORE_CLIENT
1123 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1124 "Received client transmission request. queueing\n");
1126 car = GNUNET_CONTAINER_multihashmap_get (c->requests,
1127 &req->peer.hashPubKey);
1130 /* create new entry */
1131 car = GNUNET_malloc (sizeof (struct ClientActiveRequest));
1132 GNUNET_assert (GNUNET_OK ==
1133 GNUNET_CONTAINER_multihashmap_put (c->requests,
1134 &req->peer.hashPubKey,
1136 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1137 GNUNET_CONTAINER_DLL_insert (n->active_client_request_head,
1138 n->active_client_request_tail,
1142 car->deadline = GNUNET_TIME_absolute_ntoh (req->deadline);
1143 car->priority = ntohl (req->priority);
1144 car->queue_size = ntohl (req->queue_size);
1145 car->msize = ntohs (req->size);
1146 car->smr_id = req->smr_id;
1147 schedule_peer_messages (n);
1148 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1153 * Handle CORE_INIT request.
1156 handle_client_init (void *cls,
1157 struct GNUNET_SERVER_Client *client,
1158 const struct GNUNET_MessageHeader *message)
1160 const struct InitMessage *im;
1161 struct InitReplyMessage irm;
1164 const uint16_t *types;
1166 struct Neighbour *n;
1167 struct ConnectNotifyMessage cnm;
1170 #if DEBUG_CORE_CLIENT
1171 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1172 "Client connecting to core service with `%s' message\n",
1175 /* check that we don't have an entry already */
1179 if (client == c->client_handle)
1182 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1187 msize = ntohs (message->size);
1188 if (msize < sizeof (struct InitMessage))
1191 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1194 GNUNET_SERVER_notification_context_add (notifier, client);
1195 im = (const struct InitMessage *) message;
1196 types = (const uint16_t *) &im[1];
1197 msize -= sizeof (struct InitMessage);
1198 c = GNUNET_malloc (sizeof (struct Client) + msize);
1199 c->client_handle = client;
1202 c->tcnt = msize / sizeof (uint16_t);
1203 c->types = (const uint16_t *) &c[1];
1204 wtypes = (uint16_t *) &c[1];
1205 for (i=0;i<c->tcnt;i++)
1206 wtypes[i] = ntohs (types[i]);
1207 c->options = ntohl (im->options);
1208 #if DEBUG_CORE_CLIENT
1209 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1210 "Client %p is interested in %u message types\n",
1212 (unsigned int) c->tcnt);
1214 /* send init reply message */
1215 irm.header.size = htons (sizeof (struct InitReplyMessage));
1216 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
1217 irm.reserved = htonl (0);
1218 memcpy (&irm.publicKey,
1220 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1221 #if DEBUG_CORE_CLIENT
1222 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1223 "Sending `%s' message to client.\n", "INIT_REPLY");
1225 send_to_client (c, &irm.header, GNUNET_NO);
1226 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
1228 /* notify new client about existing neighbours */
1229 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
1230 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1231 cnm.ats_count = htonl (0);
1232 cnm.ats.type = htonl (0);
1233 cnm.ats.value = htonl (0);
1237 if (n->status == PEER_STATE_KEY_CONFIRMED)
1239 #if DEBUG_CORE_CLIENT
1240 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1241 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
1244 send_to_client (c, &cnm.header, GNUNET_NO);
1249 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1254 * Free client request records.
1257 * @param key identity of peer for which this is an active request
1258 * @param value the 'struct ClientActiveRequest' to free
1259 * @return GNUNET_YES (continue iteration)
1262 destroy_active_client_request (void *cls,
1263 const GNUNET_HashCode *key,
1266 struct ClientActiveRequest *car = cls;
1267 struct Neighbour *n;
1268 struct GNUNET_PeerIdentity peer;
1270 peer.hashPubKey = *key;
1271 n = find_neighbour (&peer);
1272 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1273 n->active_client_request_tail,
1281 * A client disconnected, clean up.
1283 * @param cls closure
1284 * @param client identification of the client
1287 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1290 struct Client *prev;
1294 #if DEBUG_CORE_CLIENT
1295 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1296 "Client %p has disconnected from core service.\n",
1303 if (client == pos->client_handle)
1310 /* client never sent INIT */
1314 clients = pos->next;
1316 prev->next = pos->next;
1317 if (pos->requests != NULL)
1319 GNUNET_CONTAINER_multihashmap_iterate (pos->requests,
1320 &destroy_active_client_request,
1322 GNUNET_CONTAINER_multihashmap_destroy (pos->requests);
1329 * Handle CORE_ITERATE_PEERS request.
1332 handle_client_iterate_peers (void *cls,
1333 struct GNUNET_SERVER_Client *client,
1334 const struct GNUNET_MessageHeader *message)
1337 struct Neighbour *n;
1338 struct ConnectNotifyMessage cnm;
1339 struct GNUNET_MessageHeader done_msg;
1340 struct GNUNET_SERVER_TransmitContext *tc;
1342 /* notify new client about existing neighbours */
1343 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
1344 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1345 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
1346 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1347 tc = GNUNET_SERVER_transmit_context_create (client);
1349 cnm.ats_count = htonl (0);
1350 cnm.ats.type = htonl (0);
1351 cnm.ats.value = htonl (0);
1354 if (n->status == PEER_STATE_KEY_CONFIRMED)
1356 #if DEBUG_CORE_CLIENT
1357 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1358 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
1361 GNUNET_SERVER_transmit_context_append_message (tc, &cnm.header);
1365 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
1366 GNUNET_SERVER_transmit_context_run (tc,
1367 GNUNET_TIME_UNIT_FOREVER_REL);
1372 * Handle REQUEST_INFO request.
1375 handle_client_request_info (void *cls,
1376 struct GNUNET_SERVER_Client *client,
1377 const struct GNUNET_MessageHeader *message)
1379 const struct RequestInfoMessage *rcm;
1380 struct Neighbour *n;
1381 struct ConfigurationInfoMessage cim;
1382 int32_t want_reserv;
1384 unsigned long long old_preference;
1385 struct GNUNET_SERVER_TransmitContext *tc;
1387 #if DEBUG_CORE_CLIENT
1388 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1389 "Core service receives `%s' request.\n", "REQUEST_INFO");
1391 rcm = (const struct RequestInfoMessage *) message;
1392 n = find_neighbour (&rcm->peer);
1393 memset (&cim, 0, sizeof (cim));
1396 want_reserv = ntohl (rcm->reserve_inbound);
1397 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1399 n->bw_out_internal_limit = rcm->limit_outbound;
1400 if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1401 n->bw_out_external_limit).value__)
1403 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1404 n->bw_out_external_limit);
1405 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1407 GNUNET_TRANSPORT_set_quota (transport,
1411 GNUNET_TIME_UNIT_FOREVER_REL,
1413 handle_peer_status_change (n);
1416 if (want_reserv < 0)
1418 got_reserv = want_reserv;
1420 else if (want_reserv > 0)
1422 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1423 want_reserv).rel_value == 0)
1424 got_reserv = want_reserv;
1426 got_reserv = 0; /* all or nothing */
1430 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1432 old_preference = n->current_preference;
1433 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1434 if (old_preference > n->current_preference)
1436 /* overflow; cap at maximum value */
1437 n->current_preference = ULLONG_MAX;
1439 update_preference_sum (n->current_preference - old_preference);
1440 #if DEBUG_CORE_QUOTA
1441 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1442 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1444 GNUNET_i2s (&rcm->peer),
1447 cim.reserved_amount = htonl (got_reserv);
1448 cim.rim_id = rcm->rim_id;
1449 cim.bw_out = n->bw_out;
1450 cim.preference = n->current_preference;
1452 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1453 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1454 cim.peer = rcm->peer;
1456 #if DEBUG_CORE_CLIENT
1457 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1458 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1460 tc = GNUNET_SERVER_transmit_context_create (client);
1461 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1462 GNUNET_SERVER_transmit_context_run (tc,
1463 GNUNET_TIME_UNIT_FOREVER_REL);
1468 * Free the given entry for the neighbour (it has
1469 * already been removed from the list at this point).
1471 * @param n neighbour to free
1474 free_neighbour (struct Neighbour *n)
1476 struct MessageEntry *m;
1477 struct ClientActiveRequest *car;
1480 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1481 "Destroying neighbour entry for peer `%4s'\n",
1482 GNUNET_i2s (&n->peer));
1484 if (n->pitr != NULL)
1486 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1491 GNUNET_free (n->skm);
1494 while (NULL != (m = n->messages))
1496 n->messages = m->next;
1499 while (NULL != (m = n->encrypted_head))
1501 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1506 while (NULL != (car = n->active_client_request_head))
1508 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1509 n->active_client_request_tail,
1511 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
1512 &n->peer.hashPubKey,
1518 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1521 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1522 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
1523 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1524 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
1525 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1526 GNUNET_SCHEDULER_cancel (n->quota_update_task);
1527 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1528 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1529 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1530 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
1531 if (n->status == PEER_STATE_KEY_CONFIRMED)
1532 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1533 GNUNET_free_non_null (n->public_key);
1534 GNUNET_free_non_null (n->pending_ping);
1535 GNUNET_free_non_null (n->pending_pong);
1541 * Check if we have encrypted messages for the specified neighbour
1542 * pending, and if so, check with the transport about sending them
1545 * @param n neighbour to check.
1547 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1551 * Encrypt size bytes from in and write the result to out. Use the
1552 * key for outbound traffic of the given neighbour.
1554 * @param n neighbour we are sending to
1555 * @param iv initialization vector to use
1556 * @param in ciphertext
1557 * @param out plaintext
1558 * @param size size of in/out
1559 * @return GNUNET_OK on success
1562 do_encrypt (struct Neighbour *n,
1563 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1564 const void *in, void *out, size_t size)
1566 if (size != (uint16_t) size)
1571 GNUNET_assert (size ==
1572 GNUNET_CRYPTO_aes_encrypt (in,
1576 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1578 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1579 "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
1580 (unsigned int) size,
1581 GNUNET_i2s (&n->peer),
1582 (unsigned int) n->encrypt_key.crc32,
1583 GNUNET_CRYPTO_crc32_n (iv, sizeof(iv)));
1590 * Consider freeing the given neighbour since we may not need
1591 * to keep it around anymore.
1593 * @param n neighbour to consider discarding
1596 consider_free_neighbour (struct Neighbour *n);
1600 * Task triggered when a neighbour entry is about to time out
1601 * (and we should prevent this by sending a PING).
1603 * @param cls the 'struct Neighbour'
1604 * @param tc scheduler context (not used)
1607 send_keep_alive (void *cls,
1608 const struct GNUNET_SCHEDULER_TaskContext *tc)
1610 struct Neighbour *n = cls;
1611 struct GNUNET_TIME_Relative retry;
1612 struct GNUNET_TIME_Relative left;
1613 struct MessageEntry *me;
1614 struct PingMessage pp;
1615 struct PingMessage *pm;
1616 struct GNUNET_CRYPTO_AesInitializationVector iv;
1618 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1620 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1621 sizeof (struct PingMessage));
1622 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1623 me->priority = PING_PRIORITY;
1624 me->size = sizeof (struct PingMessage);
1625 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1629 pm = (struct PingMessage *) &me[1];
1630 pm->header.size = htons (sizeof (struct PingMessage));
1631 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1632 pm->iv_seed = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1634 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
1635 pp.challenge = n->ping_challenge;
1636 pp.target = n->peer;
1638 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1639 "Encrypting `%s' message with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
1641 (unsigned int) n->ping_challenge,
1642 GNUNET_i2s (&n->peer),
1643 (unsigned int) n->encrypt_key.crc32,
1644 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
1651 sizeof (struct PingMessage) -
1652 ((void *) &pm->target - (void *) pm));
1653 process_encrypted_neighbour_queue (n);
1654 /* reschedule PING job */
1655 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1656 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1657 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1658 MIN_PING_FREQUENCY);
1660 = GNUNET_SCHEDULER_add_delayed (retry,
1668 * Task triggered when a neighbour entry might have gotten stale.
1670 * @param cls the 'struct Neighbour'
1671 * @param tc scheduler context (not used)
1674 consider_free_task (void *cls,
1675 const struct GNUNET_SCHEDULER_TaskContext *tc)
1677 struct Neighbour *n = cls;
1679 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1680 consider_free_neighbour (n);
1685 * Consider freeing the given neighbour since we may not need
1686 * to keep it around anymore.
1688 * @param n neighbour to consider discarding
1691 consider_free_neighbour (struct Neighbour *n)
1693 struct Neighbour *pos;
1694 struct Neighbour *prev;
1695 struct GNUNET_TIME_Relative left;
1697 if ( (n->th != NULL) ||
1698 (n->pitr != NULL) ||
1699 (GNUNET_YES == n->is_connected) )
1700 return; /* no chance */
1702 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1703 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1704 if (left.rel_value > 0)
1706 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1707 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1708 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (left,
1709 &consider_free_task,
1713 /* actually free the neighbour... */
1722 neighbours = n->next;
1724 prev->next = n->next;
1725 GNUNET_assert (neighbour_count > 0);
1727 GNUNET_STATISTICS_set (stats,
1728 gettext_noop ("# neighbour entries allocated"),
1736 * Function called when the transport service is ready to
1737 * receive an encrypted message for the respective peer
1739 * @param cls neighbour to use message from
1740 * @param size number of bytes we can transmit
1741 * @param buf where to copy the message
1742 * @return number of bytes transmitted
1745 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1747 struct Neighbour *n = cls;
1748 struct MessageEntry *m;
1753 m = n->encrypted_head;
1757 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1758 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1759 GNUNET_i2s (&n->peer));
1763 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1770 GNUNET_assert (size >= m->size);
1771 memcpy (cbuf, &m[1], m->size);
1773 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1776 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1777 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1778 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1780 GNUNET_i2s (&n->peer));
1782 process_encrypted_neighbour_queue (n);
1787 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1788 "Transmission of message of type %u and size %u failed\n",
1789 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1790 (unsigned int) m->size);
1794 consider_free_neighbour (n);
1800 * Check if we have plaintext messages for the specified neighbour
1801 * pending, and if so, consider batching and encrypting them (and
1802 * then trigger processing of the encrypted queue if needed).
1804 * @param n neighbour to check.
1806 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1810 * Check if we have encrypted messages for the specified neighbour
1811 * pending, and if so, check with the transport about sending them
1814 * @param n neighbour to check.
1817 process_encrypted_neighbour_queue (struct Neighbour *n)
1819 struct MessageEntry *m;
1822 return; /* request already pending */
1823 m = n->encrypted_head;
1826 /* encrypted queue empty, try plaintext instead */
1827 process_plaintext_neighbour_queue (n);
1831 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1832 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1833 (unsigned int) m->size,
1834 GNUNET_i2s (&n->peer),
1835 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).rel_value);
1838 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1841 GNUNET_TIME_absolute_get_remaining
1843 ¬ify_encrypted_transmit_ready,
1847 /* message request too large or duplicate request */
1849 /* discard encrypted message */
1850 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1854 process_encrypted_neighbour_queue (n);
1860 * Decrypt size bytes from in and write the result to out. Use the
1861 * key for inbound traffic of the given neighbour. This function does
1862 * NOT do any integrity-checks on the result.
1864 * @param n neighbour we are receiving from
1865 * @param iv initialization vector to use
1866 * @param in ciphertext
1867 * @param out plaintext
1868 * @param size size of in/out
1869 * @return GNUNET_OK on success
1872 do_decrypt (struct Neighbour *n,
1873 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1874 const void *in, void *out, size_t size)
1876 if (size != (uint16_t) size)
1881 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1882 (n->status != PEER_STATE_KEY_CONFIRMED))
1884 GNUNET_break_op (0);
1885 return GNUNET_SYSERR;
1888 GNUNET_CRYPTO_aes_decrypt (in,
1895 return GNUNET_SYSERR;
1897 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1899 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1900 "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
1901 (unsigned int) size,
1902 GNUNET_i2s (&n->peer),
1903 (unsigned int) n->decrypt_key.crc32,
1904 GNUNET_CRYPTO_crc32_n (iv, sizeof(*iv)));
1911 * Select messages for transmission. This heuristic uses a combination
1912 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1913 * and priority-based discard (in case no feasible schedule exist) and
1914 * speculative optimization (defer any kind of transmission until
1915 * we either create a batch of significant size, 25% of max, or until
1916 * we are close to a deadline). Furthermore, when scheduling the
1917 * heuristic also packs as many messages into the batch as possible,
1918 * starting with those with the earliest deadline. Yes, this is fun.
1920 * @param n neighbour to select messages from
1921 * @param size number of bytes to select for transmission
1922 * @param retry_time set to the time when we should try again
1923 * (only valid if this function returns zero)
1924 * @return number of bytes selected, or 0 if we decided to
1925 * defer scheduling overall; in that case, retry_time is set.
1928 select_messages (struct Neighbour *n,
1929 size_t size, struct GNUNET_TIME_Relative *retry_time)
1931 struct MessageEntry *pos;
1932 struct MessageEntry *min;
1933 struct MessageEntry *last;
1934 unsigned int min_prio;
1935 struct GNUNET_TIME_Absolute t;
1936 struct GNUNET_TIME_Absolute now;
1937 struct GNUNET_TIME_Relative delta;
1939 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1942 unsigned int queue_size;
1943 int discard_low_prio;
1945 GNUNET_assert (NULL != n->messages);
1946 now = GNUNET_TIME_absolute_get ();
1947 /* last entry in linked list of messages processed */
1949 /* should we remove the entry with the lowest
1950 priority from consideration for scheduling at the
1961 discard_low_prio = GNUNET_YES;
1962 while (GNUNET_YES == discard_low_prio)
1965 min_prio = UINT_MAX;
1966 discard_low_prio = GNUNET_NO;
1967 /* calculate number of bytes available for transmission at time "t" */
1968 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1970 /* how many bytes have we (hypothetically) scheduled so far */
1972 /* maximum time we can wait before transmitting anything
1973 and still make all of our deadlines */
1974 slack = GNUNET_TIME_UNIT_FOREVER_REL;
1976 /* note that we use "*2" here because we want to look
1977 a bit further into the future; much more makes no
1978 sense since new message might be scheduled in the
1980 while ((pos != NULL) && (off < size * 2))
1982 if (pos->do_transmit == GNUNET_YES)
1984 /* already removed from consideration */
1988 if (discard_low_prio == GNUNET_NO)
1990 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1991 if (delta.rel_value > 0)
1993 // FIXME: HUH? Check!
1995 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1998 if (avail < pos->size)
2000 // FIXME: HUH? Check!
2001 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
2006 /* update slack, considering both its absolute deadline
2007 and relative deadlines caused by other messages
2008 with their respective load */
2009 slack = GNUNET_TIME_relative_min (slack,
2010 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
2012 if (pos->deadline.abs_value <= now.abs_value)
2015 slack = GNUNET_TIME_UNIT_ZERO;
2017 else if (GNUNET_YES == pos->got_slack)
2019 /* should be soon now! */
2020 slack = GNUNET_TIME_relative_min (slack,
2021 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
2026 GNUNET_TIME_relative_min (slack,
2027 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
2028 pos->got_slack = GNUNET_YES;
2029 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
2030 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
2035 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
2036 if (pos->priority <= min_prio)
2038 /* update min for discard */
2039 min_prio = pos->priority;
2044 if (discard_low_prio)
2046 GNUNET_assert (min != NULL);
2047 /* remove lowest-priority entry from consideration */
2048 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
2052 /* guard against sending "tiny" messages with large headers without
2054 if ( (slack.rel_value > GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value) &&
2056 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
2058 /* less than 25% of message would be filled with deadlines still
2059 being met if we delay by one second or more; so just wait for
2060 more data; but do not wait longer than 1s (since we don't want
2061 to delay messages for a really long time either). */
2062 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
2063 /* reset do_transmit values for next time */
2066 pos->do_transmit = GNUNET_NO;
2069 GNUNET_STATISTICS_update (stats,
2070 gettext_noop ("# transmissions delayed due to corking"),
2073 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2074 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
2075 (unsigned long long) retry_time->rel_value,
2077 (unsigned int) size);
2081 /* select marked messages (up to size) for transmission */
2086 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
2088 pos->do_transmit = GNUNET_YES; /* mark for transmission */
2092 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2093 "Selecting message of size %u for transmission\n",
2094 (unsigned int) pos->size);
2100 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2101 "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
2102 (unsigned int) pos->size,
2105 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
2110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2111 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
2112 (unsigned long long) off, (unsigned long long) tsize,
2113 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
2114 GNUNET_i2s (&n->peer));
2121 * Batch multiple messages into a larger buffer.
2123 * @param n neighbour to take messages from
2124 * @param buf target buffer
2125 * @param size size of buf
2126 * @param deadline set to transmission deadline for the result
2127 * @param retry_time set to the time when we should try again
2128 * (only valid if this function returns zero)
2129 * @param priority set to the priority of the batch
2130 * @return number of bytes written to buf (can be zero)
2133 batch_message (struct Neighbour *n,
2136 struct GNUNET_TIME_Absolute *deadline,
2137 struct GNUNET_TIME_Relative *retry_time,
2138 unsigned int *priority)
2140 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
2141 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
2142 struct MessageEntry *pos;
2143 struct MessageEntry *prev;
2144 struct MessageEntry *next;
2149 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2150 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
2151 if (0 == select_messages (n, size, retry_time))
2154 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2155 "No messages selected, will try again in %llu ms\n",
2156 retry_time->rel_value);
2160 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
2161 ntm->ats_count = htonl (0);
2162 ntm->ats.type = htonl (0);
2163 ntm->ats.value = htonl (0);
2164 ntm->peer = n->peer;
2167 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
2170 if (GNUNET_YES == pos->do_transmit)
2172 GNUNET_assert (pos->size <= size);
2173 /* do notifications */
2174 /* FIXME: track if we have *any* client that wants
2175 full notifications and only do this if that is
2177 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
2179 memcpy (&ntm[1], &pos[1], pos->size);
2180 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
2181 sizeof (struct GNUNET_MessageHeader));
2182 send_to_all_clients (&ntm->header,
2184 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
2188 /* message too large for 'full' notifications, we do at
2189 least the 'hdr' type */
2192 sizeof (struct GNUNET_MessageHeader));
2194 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
2196 send_to_all_clients (&ntm->header,
2198 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
2200 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2201 "Encrypting %u bytes with message of type %u and size %u\n",
2203 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
2204 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
2206 /* copy for encrypted transmission */
2207 memcpy (&buf[ret], &pos[1], pos->size);
2210 *priority += pos->priority;
2212 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2213 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
2214 (unsigned int) pos->size,
2215 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).rel_value);
2217 deadline->abs_value = GNUNET_MIN (deadline->abs_value, pos->deadline.abs_value);
2231 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2232 "Deadline for message batch is %llu ms\n",
2233 GNUNET_TIME_absolute_get_remaining (*deadline).rel_value);
2240 * Remove messages with deadlines that have long expired from
2243 * @param n neighbour to inspect
2246 discard_expired_messages (struct Neighbour *n)
2248 struct MessageEntry *prev;
2249 struct MessageEntry *next;
2250 struct MessageEntry *pos;
2251 struct GNUNET_TIME_Absolute now;
2252 struct GNUNET_TIME_Relative delta;
2256 now = GNUNET_TIME_absolute_get ();
2262 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
2263 if (delta.rel_value > PAST_EXPIRATION_DISCARD_TIME.rel_value)
2266 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2267 "Message is %llu ms past due, discarding.\n",
2274 GNUNET_STATISTICS_update (stats,
2275 gettext_noop ("# messages discarded (expired prior to transmission)"),
2285 if (GNUNET_YES == disc)
2286 schedule_peer_messages (n);
2291 * Signature of the main function of a task.
2293 * @param cls closure
2294 * @param tc context information (why was this task triggered now)
2297 retry_plaintext_processing (void *cls,
2298 const struct GNUNET_SCHEDULER_TaskContext *tc)
2300 struct Neighbour *n = cls;
2302 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2303 process_plaintext_neighbour_queue (n);
2308 * Send our key (and encrypted PING) to the other peer.
2310 * @param n the other peer
2312 static void send_key (struct Neighbour *n);
2315 * Task that will retry "send_key" if our previous attempt failed
2319 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2321 struct Neighbour *n = cls;
2324 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2325 "Retrying key transmission to `%4s'\n",
2326 GNUNET_i2s (&n->peer));
2328 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2329 n->set_key_retry_frequency =
2330 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2336 * Check if we have plaintext messages for the specified neighbour
2337 * pending, and if so, consider batching and encrypting them (and
2338 * then trigger processing of the encrypted queue if needed).
2340 * @param n neighbour to check.
2343 process_plaintext_neighbour_queue (struct Neighbour *n)
2345 char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)]; /* plaintext */
2347 struct EncryptedMessage *em; /* encrypted message */
2348 struct EncryptedMessage *ph; /* plaintext header */
2349 struct MessageEntry *me;
2350 unsigned int priority;
2351 struct GNUNET_TIME_Absolute deadline;
2352 struct GNUNET_TIME_Relative retry_time;
2353 struct GNUNET_CRYPTO_AesInitializationVector iv;
2354 struct GNUNET_CRYPTO_AuthKey auth_key;
2356 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2358 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
2359 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2363 case PEER_STATE_DOWN:
2366 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2367 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2368 GNUNET_i2s(&n->peer));
2371 case PEER_STATE_KEY_SENT:
2372 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2373 n->retry_set_key_task
2374 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2375 &set_key_retry_task, n);
2377 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2378 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2379 GNUNET_i2s(&n->peer));
2382 case PEER_STATE_KEY_RECEIVED:
2383 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2384 n->retry_set_key_task
2385 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2386 &set_key_retry_task, n);
2388 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2389 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2390 GNUNET_i2s(&n->peer));
2393 case PEER_STATE_KEY_CONFIRMED:
2394 /* ready to continue */
2397 discard_expired_messages (n);
2398 if (n->messages == NULL)
2401 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2402 "Plaintext message queue for `%4s' is empty.\n",
2403 GNUNET_i2s(&n->peer));
2405 return; /* no pending messages */
2407 if (n->encrypted_head != NULL)
2410 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2411 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2412 GNUNET_i2s(&n->peer));
2414 return; /* wait for messages already encrypted to be
2417 ph = (struct EncryptedMessage *) pbuf;
2418 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2420 used = sizeof (struct EncryptedMessage);
2421 used += batch_message (n,
2423 GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2424 &deadline, &retry_time, &priority);
2425 if (used == sizeof (struct EncryptedMessage))
2428 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2429 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2430 GNUNET_i2s(&n->peer));
2432 /* no messages selected for sending, try again later... */
2433 n->retry_plaintext_task =
2434 GNUNET_SCHEDULER_add_delayed (retry_time,
2435 &retry_plaintext_processing, n);
2438 #if DEBUG_CORE_QUOTA
2439 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2440 "Sending %u b/s as new limit to peer `%4s'\n",
2441 (unsigned int) ntohl (n->bw_in.value__),
2442 GNUNET_i2s (&n->peer));
2444 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
2445 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2446 ph->inbound_bw_limit = n->bw_in;
2447 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2449 /* setup encryption message header */
2450 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2451 me->deadline = deadline;
2452 me->priority = priority;
2454 em = (struct EncryptedMessage *) &me[1];
2455 em->header.size = htons (used);
2456 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2457 em->iv_seed = ph->iv_seed;
2458 derive_iv (&iv, &n->encrypt_key, ph->iv_seed, &n->peer);
2461 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2462 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2463 (unsigned int) used - ENCRYPTED_HEADER_SIZE,
2464 GNUNET_i2s(&n->peer),
2465 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).rel_value);
2467 GNUNET_assert (GNUNET_OK ==
2470 &ph->sequence_number,
2471 &em->sequence_number, used - ENCRYPTED_HEADER_SIZE));
2472 derive_auth_key (&auth_key,
2475 n->encrypt_key_created);
2476 GNUNET_CRYPTO_hmac (&auth_key,
2477 &em->sequence_number,
2478 used - ENCRYPTED_HEADER_SIZE,
2481 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2482 "Authenticated %u bytes of ciphertext %u: `%s'\n",
2483 used - ENCRYPTED_HEADER_SIZE,
2484 GNUNET_CRYPTO_crc32_n (&em->sequence_number,
2485 used - ENCRYPTED_HEADER_SIZE),
2486 GNUNET_h2s (&em->hmac));
2488 /* append to transmission list */
2489 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2493 process_encrypted_neighbour_queue (n);
2494 schedule_peer_messages (n);
2499 * Function that recalculates the bandwidth quota for the
2500 * given neighbour and transmits it to the transport service.
2502 * @param cls neighbour for the quota update
2506 neighbour_quota_update (void *cls,
2507 const struct GNUNET_SCHEDULER_TaskContext *tc);
2511 * Schedule the task that will recalculate the bandwidth
2512 * quota for this peer (and possibly force a disconnect of
2513 * idle peers by calculating a bandwidth of zero).
2516 schedule_quota_update (struct Neighbour *n)
2518 GNUNET_assert (n->quota_update_task ==
2519 GNUNET_SCHEDULER_NO_TASK);
2520 n->quota_update_task
2521 = GNUNET_SCHEDULER_add_delayed (QUOTA_UPDATE_FREQUENCY,
2522 &neighbour_quota_update,
2528 * Initialize a new 'struct Neighbour'.
2530 * @param pid ID of the new neighbour
2531 * @return handle for the new neighbour
2533 static struct Neighbour *
2534 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2536 struct Neighbour *n;
2537 struct GNUNET_TIME_Absolute now;
2540 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2541 "Creating neighbour entry for peer `%4s'\n",
2544 n = GNUNET_malloc (sizeof (struct Neighbour));
2545 n->next = neighbours;
2548 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2550 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2551 now = GNUNET_TIME_absolute_get ();
2552 n->encrypt_key_created = now;
2553 n->last_activity = now;
2554 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2555 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2556 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2557 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2558 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2559 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
2561 neighbour_quota_update (n, NULL);
2562 consider_free_neighbour (n);
2568 * Handle CORE_SEND request.
2571 * @param client the client issuing the request
2572 * @param message the "struct SendMessage"
2575 handle_client_send (void *cls,
2576 struct GNUNET_SERVER_Client *client,
2577 const struct GNUNET_MessageHeader *message)
2579 const struct SendMessage *sm;
2580 struct Neighbour *n;
2581 struct MessageEntry *prev;
2582 struct MessageEntry *pos;
2583 struct MessageEntry *e;
2584 struct MessageEntry *min_prio_entry;
2585 struct MessageEntry *min_prio_prev;
2586 unsigned int min_prio;
2587 unsigned int queue_size;
2590 msize = ntohs (message->size);
2592 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2594 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));
2597 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2600 sm = (const struct SendMessage *) message;
2601 msize -= sizeof (struct SendMessage);
2602 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2604 /* FIXME: should we not allow loopback-injection here? */
2607 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2610 n = find_neighbour (&sm->peer);
2612 n = create_neighbour (&sm->peer);
2614 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2615 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2617 (unsigned int) msize,
2618 GNUNET_i2s (&sm->peer));
2620 discard_expired_messages (n);
2621 /* bound queue size */
2622 /* NOTE: this entire block to bound the queue size should be
2623 obsolete with the new client-request code and the
2624 'schedule_peer_messages' mechanism; we still have this code in
2625 here for now as a sanity check for the new mechanmism;
2626 ultimately, we should probably simply reject SEND messages that
2627 are not 'approved' (or provide a new core API for very unreliable
2628 delivery that always sends with priority 0). Food for thought. */
2629 min_prio = UINT32_MAX;
2630 min_prio_entry = NULL;
2631 min_prio_prev = NULL;
2637 if (pos->priority <= min_prio)
2639 min_prio_entry = pos;
2640 min_prio_prev = prev;
2641 min_prio = pos->priority;
2647 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2650 if (ntohl(sm->priority) <= min_prio)
2652 /* discard new entry; this should no longer happen! */
2655 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2656 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2658 (unsigned int) MAX_PEER_QUEUE_SIZE,
2659 (unsigned int) msize,
2660 (unsigned int) ntohs (message->type));
2662 GNUNET_STATISTICS_update (stats,
2663 gettext_noop ("# discarded CORE_SEND requests"),
2667 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2670 GNUNET_assert (min_prio_entry != NULL);
2671 /* discard "min_prio_entry" */
2673 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2674 "Queue full, discarding existing older request\n");
2676 GNUNET_STATISTICS_update (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 1, GNUNET_NO);
2677 if (min_prio_prev == NULL)
2678 n->messages = min_prio_entry->next;
2680 min_prio_prev->next = min_prio_entry->next;
2681 GNUNET_free (min_prio_entry);
2685 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2686 "Adding transmission request for `%4s' of size %u to queue\n",
2687 GNUNET_i2s (&sm->peer),
2688 (unsigned int) msize);
2690 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2691 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2692 e->priority = ntohl (sm->priority);
2694 memcpy (&e[1], &sm[1], msize);
2696 /* insert, keep list sorted by deadline */
2699 while ((pos != NULL) && (pos->deadline.abs_value < e->deadline.abs_value))
2710 /* consider scheduling now */
2711 process_plaintext_neighbour_queue (n);
2713 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2718 * Function called when the transport service is ready to
2719 * receive a message. Only resets 'n->th' to NULL.
2721 * @param cls neighbour to use message from
2722 * @param size number of bytes we can transmit
2723 * @param buf where to copy the message
2724 * @return number of bytes transmitted
2727 notify_transport_connect_done (void *cls, size_t size, void *buf)
2729 struct Neighbour *n = cls;
2731 if (GNUNET_YES != n->is_connected)
2733 /* transport should only call us to transmit a message after
2734 * telling us about a successful connection to the respective peer */
2735 n->th = NULL; /* If this happens because of a timeout, reset n-th so another message may be sent for this peer! */
2737 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Timeout on notify connect!\n");
2744 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2745 _("Failed to connect to `%4s': transport failed to connect\n"),
2746 GNUNET_i2s (&n->peer));
2749 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2750 _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2751 GNUNET_i2s (&n->peer));
2752 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2753 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2754 n->retry_set_key_task = GNUNET_SCHEDULER_add_now (&set_key_retry_task,
2761 * Handle CORE_REQUEST_CONNECT request.
2764 * @param client the client issuing the request
2765 * @param message the "struct ConnectMessage"
2768 handle_client_request_connect (void *cls,
2769 struct GNUNET_SERVER_Client *client,
2770 const struct GNUNET_MessageHeader *message)
2772 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2773 struct Neighbour *n;
2774 struct GNUNET_TIME_Relative timeout;
2776 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2779 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2782 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2783 n = find_neighbour (&cm->peer);
2785 n = create_neighbour (&cm->peer);
2786 if ( (GNUNET_YES == n->is_connected) ||
2789 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2790 "Core received `%s' request for `%4s', already connected!\n",
2792 GNUNET_i2s (&cm->peer));
2793 return; /* already connected, or at least trying */
2795 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2797 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2798 "Core received `%s' request for `%4s', will try to establish connection\n",
2800 GNUNET_i2s (&cm->peer));
2802 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2803 /* ask transport to connect to the peer */
2804 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2806 sizeof (struct GNUNET_MessageHeader), 0,
2808 ¬ify_transport_connect_done,
2810 GNUNET_break (NULL != n->th);
2815 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2816 * the neighbour's struct and retry send_key. Or, if we did not get a
2817 * HELLO, just do nothing.
2819 * @param cls the 'struct Neighbour' to retry sending the key for
2820 * @param peer the peer for which this is the HELLO
2821 * @param hello HELLO message of that peer
2824 process_hello_retry_send_key (void *cls,
2825 const struct GNUNET_PeerIdentity *peer,
2826 const struct GNUNET_HELLO_Message *hello)
2828 struct Neighbour *n = cls;
2833 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2834 "Entered `%s' and `%s' is NULL!\n",
2835 "process_hello_retry_send_key",
2839 if (n->public_key != NULL)
2841 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2843 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2844 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2846 GNUNET_STATISTICS_update (stats,
2847 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2855 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2856 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
2857 GNUNET_i2s (&n->peer));
2859 GNUNET_STATISTICS_update (stats,
2860 gettext_noop ("# Delayed connecting due to lack of public key"),
2863 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2864 n->retry_set_key_task
2865 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2866 &set_key_retry_task, n);
2872 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2873 "Entered `%s' for peer `%4s'\n",
2874 "process_hello_retry_send_key",
2877 if (n->public_key != NULL)
2879 /* already have public key, why are we here? */
2885 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2886 "Received new `%s' message for `%4s', initiating key exchange.\n",
2891 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2892 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2894 GNUNET_STATISTICS_update (stats,
2895 gettext_noop ("# Error extracting public key from HELLO"),
2898 GNUNET_free (n->public_key);
2899 n->public_key = NULL;
2901 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2902 "GNUNET_HELLO_get_key returned awfully\n");
2910 * Send our key (and encrypted PING) to the other peer.
2912 * @param n the other peer
2915 send_key (struct Neighbour *n)
2917 struct MessageEntry *pos;
2918 struct SetKeyMessage *sm;
2919 struct MessageEntry *me;
2920 struct PingMessage pp;
2921 struct PingMessage *pm;
2922 struct GNUNET_CRYPTO_AesInitializationVector iv;
2924 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2926 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2927 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2929 if (n->pitr != NULL)
2932 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2933 "Key exchange in progress with `%4s'.\n",
2934 GNUNET_i2s (&n->peer));
2936 return; /* already in progress */
2938 if (GNUNET_YES != n->is_connected)
2941 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2942 "Not yet connected to peer `%4s'!\n",
2943 GNUNET_i2s (&n->peer));
2947 GNUNET_STATISTICS_update (stats,
2948 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
2951 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2953 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2955 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2956 ¬ify_encrypted_transmit_ready,
2962 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2963 "Asked to perform key exchange with `%4s'.\n",
2964 GNUNET_i2s (&n->peer));
2966 if (n->public_key == NULL)
2968 /* lookup n's public key, then try again */
2970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2971 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2972 GNUNET_i2s (&n->peer));
2974 GNUNET_assert (n->pitr == NULL);
2975 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2977 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2978 &process_hello_retry_send_key, n);
2981 pos = n->encrypted_head;
2984 if (GNUNET_YES == pos->is_setkey)
2986 if (pos->sender_status == n->status)
2989 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2990 "`%s' message for `%4s' queued already\n",
2992 GNUNET_i2s (&n->peer));
2994 goto trigger_processing;
2996 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
3001 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3002 "Removing queued `%s' message for `%4s', will create a new one\n",
3004 GNUNET_i2s (&n->peer));
3014 case PEER_STATE_DOWN:
3015 n->status = PEER_STATE_KEY_SENT;
3017 case PEER_STATE_KEY_SENT:
3019 case PEER_STATE_KEY_RECEIVED:
3021 case PEER_STATE_KEY_CONFIRMED:
3029 /* first, set key message */
3030 me = GNUNET_malloc (sizeof (struct MessageEntry) +
3031 sizeof (struct SetKeyMessage) +
3032 sizeof (struct PingMessage));
3033 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
3034 me->priority = SET_KEY_PRIORITY;
3035 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
3036 me->is_setkey = GNUNET_YES;
3037 me->got_slack = GNUNET_YES; /* do not defer this one! */
3038 me->sender_status = n->status;
3039 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3043 sm = (struct SetKeyMessage *) &me[1];
3044 sm->header.size = htons (sizeof (struct SetKeyMessage));
3045 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
3046 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
3047 PEER_STATE_KEY_SENT : n->status));
3049 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3050 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3051 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3052 sizeof (struct GNUNET_PeerIdentity));
3053 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
3054 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
3055 sm->target = n->peer;
3056 GNUNET_assert (GNUNET_OK ==
3057 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
3059 GNUNET_CRYPTO_AesSessionKey),
3061 &sm->encrypted_key));
3062 GNUNET_assert (GNUNET_OK ==
3063 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
3065 pm = (struct PingMessage *) &sm[1];
3066 pm->header.size = htons (sizeof (struct PingMessage));
3067 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
3068 pm->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3069 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
3070 pp.challenge = n->ping_challenge;
3071 pp.target = n->peer;
3073 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3074 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
3076 (unsigned int) n->ping_challenge,
3077 GNUNET_i2s (&n->peer),
3078 (unsigned int) n->encrypt_key.crc32,
3079 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3086 sizeof (struct PingMessage) -
3087 ((void *) &pm->target - (void *) pm));
3088 GNUNET_STATISTICS_update (stats,
3089 gettext_noop ("# SET_KEY and PING messages created"),
3093 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3094 "Have %llu ms left for `%s' transmission.\n",
3095 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).rel_value,
3099 /* trigger queue processing */
3100 process_encrypted_neighbour_queue (n);
3101 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
3102 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
3103 n->retry_set_key_task
3104 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3105 &set_key_retry_task, n);
3110 * We received a SET_KEY message. Validate and update
3111 * our key material and status.
3113 * @param n the neighbour from which we received message m
3114 * @param m the set key message we received
3117 handle_set_key (struct Neighbour *n,
3118 const struct SetKeyMessage *m);
3122 * PEERINFO is giving us a HELLO for a peer. Add the public key to
3123 * the neighbour's struct and retry handling the set_key message. Or,
3124 * if we did not get a HELLO, just free the set key message.
3126 * @param cls pointer to the set key message
3127 * @param peer the peer for which this is the HELLO
3128 * @param hello HELLO message of that peer
3131 process_hello_retry_handle_set_key (void *cls,
3132 const struct GNUNET_PeerIdentity *peer,
3133 const struct GNUNET_HELLO_Message *hello)
3135 struct Neighbour *n = cls;
3136 struct SetKeyMessage *sm = n->skm;
3142 if (n->public_key != NULL)
3145 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3146 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
3148 GNUNET_i2s (&n->peer),
3151 handle_set_key (n, sm);
3155 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3156 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
3158 GNUNET_i2s (&n->peer));
3163 if (n->public_key != NULL)
3164 return; /* multiple HELLOs match!? */
3166 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3167 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3169 GNUNET_break_op (0);
3170 GNUNET_free (n->public_key);
3171 n->public_key = NULL;
3177 * We received a PING message. Validate and transmit
3180 * @param n sender of the PING
3181 * @param m the encrypted PING message itself
3184 handle_ping (struct Neighbour *n, const struct PingMessage *m)
3186 struct PingMessage t;
3187 struct PongMessage tx;
3188 struct PongMessage *tp;
3189 struct MessageEntry *me;
3190 struct GNUNET_CRYPTO_AesInitializationVector iv;
3193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3194 "Core service receives `%s' request from `%4s'.\n",
3195 "PING", GNUNET_i2s (&n->peer));
3197 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3203 sizeof (struct PingMessage) -
3204 ((void *) &m->target - (void *) m)))
3207 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3208 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u, IV %u (salt %u)\n",
3210 GNUNET_i2s (&t.target),
3211 (unsigned int) t.challenge,
3212 (unsigned int) n->decrypt_key.crc32,
3213 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3216 GNUNET_STATISTICS_update (stats,
3217 gettext_noop ("# PING messages decrypted"),
3220 if (0 != memcmp (&t.target,
3221 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3223 GNUNET_break_op (0);
3226 me = GNUNET_malloc (sizeof (struct MessageEntry) +
3227 sizeof (struct PongMessage));
3228 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3232 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
3233 me->priority = PONG_PRIORITY;
3234 me->size = sizeof (struct PongMessage);
3235 tx.inbound_bw_limit = n->bw_in;
3236 tx.challenge = t.challenge;
3237 tx.target = t.target;
3238 tp = (struct PongMessage *) &me[1];
3239 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
3240 tp->header.size = htons (sizeof (struct PongMessage));
3241 tp->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3242 derive_pong_iv (&iv, &n->encrypt_key, tp->iv_seed, t.challenge, &n->peer);
3247 sizeof (struct PongMessage) -
3248 ((void *) &tp->challenge - (void *) tp));
3249 GNUNET_STATISTICS_update (stats,
3250 gettext_noop ("# PONG messages created"),
3254 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3255 "Encrypting `%s' with challenge %u using key %u, IV %u (salt %u)\n",
3257 (unsigned int) t.challenge,
3258 (unsigned int) n->encrypt_key.crc32,
3259 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3262 /* trigger queue processing */
3263 process_encrypted_neighbour_queue (n);
3268 * We received a PONG message. Validate and update our status.
3270 * @param n sender of the PONG
3271 * @param m the encrypted PONG message itself
3274 handle_pong (struct Neighbour *n,
3275 const struct PongMessage *m)
3277 struct PongMessage t;
3278 struct ConnectNotifyMessage cnm;
3279 struct GNUNET_CRYPTO_AesInitializationVector iv;
3282 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3283 "Core service receives `%s' response from `%4s'.\n",
3284 "PONG", GNUNET_i2s (&n->peer));
3286 /* mark as garbage, just to be sure */
3287 memset (&t, 255, sizeof (t));
3288 derive_pong_iv (&iv, &n->decrypt_key, m->iv_seed, n->ping_challenge,
3295 sizeof (struct PongMessage) -
3296 ((void *) &m->challenge - (void *) m)))
3298 GNUNET_break_op (0);
3301 GNUNET_STATISTICS_update (stats,
3302 gettext_noop ("# PONG messages decrypted"),
3306 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3307 "Decrypted `%s' from `%4s' with challenge %u using key %u, IV %u (salt %u)\n",
3309 GNUNET_i2s (&t.target),
3310 (unsigned int) t.challenge,
3311 (unsigned int) n->decrypt_key.crc32,
3312 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3315 if ((0 != memcmp (&t.target,
3317 sizeof (struct GNUNET_PeerIdentity))) ||
3318 (n->ping_challenge != t.challenge))
3320 /* PONG malformed */
3322 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3323 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
3325 GNUNET_i2s (&n->peer),
3326 (unsigned int) n->ping_challenge);
3327 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3328 "Received malformed `%s' received from `%4s' with challenge %u\n",
3329 "PONG", GNUNET_i2s (&t.target),
3330 (unsigned int) t.challenge);
3332 GNUNET_break_op (0);
3337 case PEER_STATE_DOWN:
3338 GNUNET_break (0); /* should be impossible */
3340 case PEER_STATE_KEY_SENT:
3341 GNUNET_break (0); /* should be impossible, how did we decrypt? */
3343 case PEER_STATE_KEY_RECEIVED:
3344 GNUNET_STATISTICS_update (stats,
3345 gettext_noop ("# Session keys confirmed via PONG"),
3348 n->status = PEER_STATE_KEY_CONFIRMED;
3349 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
3351 n->bw_out_external_limit = t.inbound_bw_limit;
3352 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3353 n->bw_out_internal_limit);
3354 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3356 GNUNET_TRANSPORT_set_quota (transport,
3360 GNUNET_TIME_UNIT_FOREVER_REL,
3364 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3365 "Confirmed key via `%s' message for peer `%4s'\n",
3366 "PONG", GNUNET_i2s (&n->peer));
3368 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3370 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3371 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3373 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3374 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3376 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
3377 process_encrypted_neighbour_queue (n);
3379 case PEER_STATE_KEY_CONFIRMED:
3380 n->last_activity = GNUNET_TIME_absolute_get ();
3381 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3382 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3384 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3387 handle_peer_status_change (n);
3397 * We received a SET_KEY message. Validate and update
3398 * our key material and status.
3400 * @param n the neighbour from which we received message m
3401 * @param m the set key message we received
3404 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
3406 struct SetKeyMessage *m_cpy;
3407 struct GNUNET_TIME_Absolute t;
3408 struct GNUNET_CRYPTO_AesSessionKey k;
3409 struct PingMessage *ping;
3410 struct PongMessage *pong;
3411 enum PeerStateMachine sender_status;
3414 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3415 "Core service receives `%s' request from `%4s'.\n",
3416 "SET_KEY", GNUNET_i2s (&n->peer));
3418 if (n->public_key == NULL)
3420 if (n->pitr != NULL)
3423 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3424 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3430 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3431 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3433 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3434 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3435 /* lookup n's public key, then try again */
3436 GNUNET_assert (n->skm == NULL);
3438 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3440 GNUNET_TIME_UNIT_MINUTES,
3441 &process_hello_retry_handle_set_key, n);
3442 GNUNET_STATISTICS_update (stats,
3443 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3448 if (0 != memcmp (&m->target,
3450 sizeof (struct GNUNET_PeerIdentity)))
3452 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3453 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3455 GNUNET_i2s (&m->target));
3458 if ((ntohl (m->purpose.size) !=
3459 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3460 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3461 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3462 sizeof (struct GNUNET_PeerIdentity)) ||
3464 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3465 &m->purpose, &m->signature, n->public_key)))
3467 /* invalid signature */
3468 GNUNET_break_op (0);
3471 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3472 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3473 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3474 (t.abs_value < n->decrypt_key_created.abs_value))
3476 /* this could rarely happen due to massive re-ordering of
3477 messages on the network level, but is most likely either
3478 a bug or some adversary messing with us. Report. */
3479 GNUNET_break_op (0);
3483 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3484 "Decrypting key material.\n");
3486 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3489 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3490 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3491 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3493 /* failed to decrypt !? */
3494 GNUNET_break_op (0);
3497 GNUNET_STATISTICS_update (stats,
3498 gettext_noop ("# SET_KEY messages decrypted"),
3502 if (n->decrypt_key_created.abs_value != t.abs_value)
3504 /* fresh key, reset sequence numbers */
3505 n->last_sequence_number_received = 0;
3506 n->last_packets_bitmap = 0;
3507 n->decrypt_key_created = t;
3509 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3512 case PEER_STATE_DOWN:
3513 n->status = PEER_STATE_KEY_RECEIVED;
3515 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3516 "Responding to `%s' with my own key.\n", "SET_KEY");
3520 case PEER_STATE_KEY_SENT:
3521 case PEER_STATE_KEY_RECEIVED:
3522 n->status = PEER_STATE_KEY_RECEIVED;
3523 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3524 (sender_status != PEER_STATE_KEY_CONFIRMED))
3527 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3528 "Responding to `%s' with my own key (other peer has status %u).\n",
3530 (unsigned int) sender_status);
3535 case PEER_STATE_KEY_CONFIRMED:
3536 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3537 (sender_status != PEER_STATE_KEY_CONFIRMED))
3540 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3541 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3543 (unsigned int) sender_status);
3552 if (n->pending_ping != NULL)
3554 ping = n->pending_ping;
3555 n->pending_ping = NULL;
3556 handle_ping (n, ping);
3559 if (n->pending_pong != NULL)
3561 pong = n->pending_pong;
3562 n->pending_pong = NULL;
3563 handle_pong (n, pong);
3570 * Send a P2P message to a client.
3572 * @param sender who sent us the message?
3573 * @param client who should we give the message to?
3574 * @param m contains the message to transmit
3575 * @param msize number of bytes in buf to transmit
3578 send_p2p_message_to_client (struct Neighbour *sender,
3579 struct Client *client,
3580 const void *m, size_t msize)
3582 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3583 struct NotifyTrafficMessage *ntm;
3586 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3587 "Core service passes message from `%4s' of type %u to client.\n",
3588 GNUNET_i2s(&sender->peer),
3589 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3591 ntm = (struct NotifyTrafficMessage *) buf;
3592 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3593 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3594 ntm->ats_count = htonl (0);
3595 ntm->ats.type = htonl (0);
3596 ntm->ats.value = htonl (0);
3597 ntm->peer = sender->peer;
3598 memcpy (&ntm[1], m, msize);
3599 send_to_client (client, &ntm->header, GNUNET_YES);
3604 * Deliver P2P message to interested clients.
3606 * @param cls always NULL
3607 * @param client who sent us the message (struct Neighbour)
3608 * @param m the message
3611 deliver_message (void *cls,
3613 const struct GNUNET_MessageHeader *m)
3615 struct Neighbour *sender = client;
3616 size_t msize = ntohs (m->size);
3618 struct Client *cpos;
3624 type = ntohs (m->type);
3626 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3627 "Received encapsulated message of type %u and size %u from `%4s'\n",
3628 (unsigned int) type,
3630 GNUNET_i2s (&sender->peer));
3632 GNUNET_snprintf (buf,
3634 gettext_noop ("# bytes of messages of type %u received"),
3635 (unsigned int) type);
3636 GNUNET_STATISTICS_set (stats,
3640 dropped = GNUNET_YES;
3642 while (cpos != NULL)
3644 deliver_full = GNUNET_NO;
3645 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3646 deliver_full = GNUNET_YES;
3649 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3651 if (type != cpos->types[tpos])
3653 deliver_full = GNUNET_YES;
3657 if (GNUNET_YES == deliver_full)
3659 send_p2p_message_to_client (sender, cpos, m, msize);
3660 dropped = GNUNET_NO;
3662 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3664 send_p2p_message_to_client (sender, cpos, m,
3665 sizeof (struct GNUNET_MessageHeader));
3669 if (dropped == GNUNET_YES)
3672 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3673 "Message of type %u from `%4s' not delivered to any client.\n",
3674 (unsigned int) type,
3675 GNUNET_i2s (&sender->peer));
3677 GNUNET_STATISTICS_update (stats,
3678 gettext_noop ("# messages not delivered to any client"),
3685 * We received an encrypted message. Decrypt, validate and
3686 * pass on to the appropriate clients.
3689 handle_encrypted_message (struct Neighbour *n,
3690 const struct EncryptedMessage *m)
3692 size_t size = ntohs (m->header.size);
3694 struct EncryptedMessage *pt; /* plaintext */
3697 struct GNUNET_TIME_Absolute t;
3698 struct GNUNET_CRYPTO_AesInitializationVector iv;
3699 struct GNUNET_CRYPTO_AuthKey auth_key;
3702 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3703 "Core service receives `%s' request from `%4s'.\n",
3704 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3707 derive_auth_key (&auth_key,
3710 n->decrypt_key_created);
3711 GNUNET_CRYPTO_hmac (&auth_key,
3712 &m->sequence_number,
3713 size - ENCRYPTED_HEADER_SIZE, &ph);
3715 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3716 "Re-Authenticated %u bytes of ciphertext (`%u'): `%s'\n",
3717 (unsigned int) size - ENCRYPTED_HEADER_SIZE,
3718 GNUNET_CRYPTO_crc32_n (&m->sequence_number,
3719 size - ENCRYPTED_HEADER_SIZE),
3723 if (0 != memcmp (&ph,
3725 sizeof (GNUNET_HashCode)))
3727 /* checksum failed */
3728 GNUNET_break_op (0);
3731 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3736 &m->sequence_number,
3737 &buf[ENCRYPTED_HEADER_SIZE],
3738 size - ENCRYPTED_HEADER_SIZE))
3740 pt = (struct EncryptedMessage *) buf;
3742 /* validate sequence number */
3743 snum = ntohl (pt->sequence_number);
3744 if (n->last_sequence_number_received == snum)
3746 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3747 "Received duplicate message, ignoring.\n");
3748 /* duplicate, ignore */
3749 GNUNET_STATISTICS_set (stats,
3750 gettext_noop ("# bytes dropped (duplicates)"),
3755 if ((n->last_sequence_number_received > snum) &&
3756 (n->last_sequence_number_received - snum > 32))
3758 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3759 "Received ancient out of sequence message, ignoring.\n");
3760 /* ancient out of sequence, ignore */
3761 GNUNET_STATISTICS_set (stats,
3762 gettext_noop ("# bytes dropped (out of sequence)"),
3767 if (n->last_sequence_number_received > snum)
3769 unsigned int rotbit =
3770 1 << (n->last_sequence_number_received - snum - 1);
3771 if ((n->last_packets_bitmap & rotbit) != 0)
3773 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3774 "Received duplicate message, ignoring.\n");
3775 GNUNET_STATISTICS_set (stats,
3776 gettext_noop ("# bytes dropped (duplicates)"),
3779 /* duplicate, ignore */
3782 n->last_packets_bitmap |= rotbit;
3784 if (n->last_sequence_number_received < snum)
3786 int shift = (snum - n->last_sequence_number_received);
3787 if (shift >= 8 * sizeof(n->last_packets_bitmap))
3788 n->last_packets_bitmap = 0;
3790 n->last_packets_bitmap <<= shift;
3791 n->last_sequence_number_received = snum;
3794 /* check timestamp */
3795 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3796 if (GNUNET_TIME_absolute_get_duration (t).rel_value > MAX_MESSAGE_AGE.rel_value)
3798 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3800 ("Message received far too old (%llu ms). Content ignored.\n"),
3801 GNUNET_TIME_absolute_get_duration (t).rel_value);
3802 GNUNET_STATISTICS_set (stats,
3803 gettext_noop ("# bytes dropped (ancient message)"),
3809 /* process decrypted message(s) */
3810 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3812 #if DEBUG_CORE_SET_QUOTA
3813 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3814 "Received %u b/s as new inbound limit for peer `%4s'\n",
3815 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3816 GNUNET_i2s (&n->peer));
3818 n->bw_out_external_limit = pt->inbound_bw_limit;
3819 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3820 n->bw_out_internal_limit);
3821 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3823 GNUNET_TRANSPORT_set_quota (transport,
3827 GNUNET_TIME_UNIT_FOREVER_REL,
3830 n->last_activity = GNUNET_TIME_absolute_get ();
3831 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3832 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3834 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3837 GNUNET_STATISTICS_set (stats,
3838 gettext_noop ("# bytes of payload decrypted"),
3839 size - sizeof (struct EncryptedMessage),
3841 handle_peer_status_change (n);
3842 if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst,
3844 &buf[sizeof (struct EncryptedMessage)],
3845 size - sizeof (struct EncryptedMessage),
3846 GNUNET_YES, GNUNET_NO))
3847 GNUNET_break_op (0);
3852 * Function called by the transport for each received message.
3854 * @param cls closure
3855 * @param peer (claimed) identity of the other peer
3856 * @param message the message
3857 * @param latency estimated latency for communicating with the
3858 * given peer (round-trip)
3859 * @param distance in overlay hops, as given by transport plugin
3862 handle_transport_receive (void *cls,
3863 const struct GNUNET_PeerIdentity *peer,
3864 const struct GNUNET_MessageHeader *message,
3865 struct GNUNET_TIME_Relative latency,
3866 unsigned int distance)
3868 struct Neighbour *n;
3869 struct GNUNET_TIME_Absolute now;
3876 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3877 "Received message of type %u from `%4s', demultiplexing.\n",
3878 (unsigned int) ntohs (message->type),
3881 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3886 n = find_neighbour (peer);
3888 n = create_neighbour (peer);
3889 changed = GNUNET_YES; /* FIXME... */
3890 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3891 type = ntohs (message->type);
3892 size = ntohs (message->size);
3895 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3896 if (size != sizeof (struct SetKeyMessage))
3898 GNUNET_break_op (0);
3901 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3902 handle_set_key (n, (const struct SetKeyMessage *) message);
3904 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3905 if (size < sizeof (struct EncryptedMessage) +
3906 sizeof (struct GNUNET_MessageHeader))
3908 GNUNET_break_op (0);
3911 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3912 (n->status != PEER_STATE_KEY_CONFIRMED))
3914 GNUNET_break_op (0);
3917 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3919 case GNUNET_MESSAGE_TYPE_CORE_PING:
3920 if (size != sizeof (struct PingMessage))
3922 GNUNET_break_op (0);
3925 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3926 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3927 (n->status != PEER_STATE_KEY_CONFIRMED))
3930 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3931 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3932 "PING", GNUNET_i2s (&n->peer));
3934 GNUNET_free_non_null (n->pending_ping);
3935 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3936 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3939 handle_ping (n, (const struct PingMessage *) message);
3941 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3942 if (size != sizeof (struct PongMessage))
3944 GNUNET_break_op (0);
3947 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3948 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3949 (n->status != PEER_STATE_KEY_CONFIRMED) )
3952 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3953 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3954 "PONG", GNUNET_i2s (&n->peer));
3956 GNUNET_free_non_null (n->pending_pong);
3957 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3958 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3961 handle_pong (n, (const struct PongMessage *) message);
3964 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3965 _("Unsupported message of type %u received.\n"),
3966 (unsigned int) type);
3969 if (n->status == PEER_STATE_KEY_CONFIRMED)
3971 now = GNUNET_TIME_absolute_get ();
3972 n->last_activity = now;
3973 changed = GNUNET_YES;
3976 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3977 n->time_established = now;
3979 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3980 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3982 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3987 handle_peer_status_change (n);
3992 * Function that recalculates the bandwidth quota for the
3993 * given neighbour and transmits it to the transport service.
3995 * @param cls neighbour for the quota update
3999 neighbour_quota_update (void *cls,
4000 const struct GNUNET_SCHEDULER_TaskContext *tc)
4002 struct Neighbour *n = cls;
4003 struct GNUNET_BANDWIDTH_Value32NBO q_in;
4006 unsigned long long distributable;
4007 uint64_t need_per_peer;
4008 uint64_t need_per_second;
4011 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4012 "Neighbour quota update calculation running for peer `%4s'\n",
4013 GNUNET_i2s (&n->peer));
4015 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
4016 /* calculate relative preference among all neighbours;
4017 divides by a bit more to avoid division by zero AND to
4018 account for possibility of new neighbours joining any time
4019 AND to convert to double... */
4020 if (preference_sum == 0)
4022 pref_rel = 1.0 / (double) neighbour_count;
4026 pref_rel = n->current_preference / preference_sum;
4028 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
4029 GNUNET_TIME_UNIT_SECONDS);
4030 need_per_second = need_per_peer * neighbour_count;
4032 if (bandwidth_target_out_bps > need_per_second)
4033 distributable = bandwidth_target_out_bps - need_per_second;
4034 share = distributable * pref_rel;
4035 if (share + need_per_peer > UINT32_MAX)
4036 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4038 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4039 /* check if we want to disconnect for good due to inactivity */
4040 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) &&
4041 (GNUNET_TIME_absolute_get_duration (n->time_established).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) )
4044 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4045 "Forcing disconnect of `%4s' due to inactivity\n",
4046 GNUNET_i2s (&n->peer));
4048 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
4050 #if DEBUG_CORE_QUOTA
4051 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4052 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
4053 GNUNET_i2s (&n->peer),
4054 (unsigned int) ntohl (q_in.value__),
4055 bandwidth_target_out_bps,
4056 (unsigned int) ntohl (n->bw_in.value__),
4057 (unsigned int) ntohl (n->bw_out.value__),
4058 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
4060 if (n->bw_in.value__ != q_in.value__)
4063 if (GNUNET_YES == n->is_connected)
4064 GNUNET_TRANSPORT_set_quota (transport,
4068 GNUNET_TIME_UNIT_FOREVER_REL,
4070 handle_peer_status_change (n);
4072 schedule_quota_update (n);
4077 * Function called by transport to notify us that
4078 * a peer connected to us (on the network level).
4080 * @param cls closure
4081 * @param peer the peer that connected
4082 * @param latency current latency of the connection
4083 * @param distance in overlay hops, as given by transport plugin
4086 handle_transport_notify_connect (void *cls,
4087 const struct GNUNET_PeerIdentity *peer,
4088 struct GNUNET_TIME_Relative latency,
4089 unsigned int distance)
4091 struct Neighbour *n;
4093 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4098 n = find_neighbour (peer);
4101 if (GNUNET_YES == n->is_connected)
4103 /* duplicate connect notification!? */
4110 n = create_neighbour (peer);
4112 GNUNET_STATISTICS_update (stats,
4113 gettext_noop ("# peers connected (transport)"),
4116 n->is_connected = GNUNET_YES;
4117 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
4120 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
4124 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4125 "Received connection from `%4s'.\n",
4126 GNUNET_i2s (&n->peer));
4128 GNUNET_TRANSPORT_set_quota (transport,
4132 GNUNET_TIME_UNIT_FOREVER_REL,
4139 * Function called by transport telling us that a peer
4142 * @param cls closure
4143 * @param peer the peer that disconnected
4146 handle_transport_notify_disconnect (void *cls,
4147 const struct GNUNET_PeerIdentity *peer)
4149 struct DisconnectNotifyMessage cnm;
4150 struct Neighbour *n;
4151 struct ClientActiveRequest *car;
4152 struct GNUNET_TIME_Relative left;
4155 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4156 "Peer `%4s' disconnected from us; received notification from transport.\n", GNUNET_i2s (peer));
4159 n = find_neighbour (peer);
4165 GNUNET_break (n->is_connected);
4166 if (n->status == PEER_STATE_KEY_CONFIRMED)
4168 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
4169 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
4171 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
4173 n->is_connected = GNUNET_NO;
4174 while (NULL != (car = n->active_client_request_head))
4176 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
4177 n->active_client_request_tail,
4179 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
4180 &n->peer.hashPubKey,
4185 GNUNET_STATISTICS_update (stats,
4186 gettext_noop ("# peers connected (transport)"),
4189 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
4190 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
4191 left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4192 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
4193 n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (),
4195 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
4196 &consider_free_task,
4202 * Last task run during shutdown. Disconnects us from
4206 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4208 struct Neighbour *n;
4212 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4213 "Core service shutting down.\n");
4215 GNUNET_assert (transport != NULL);
4216 GNUNET_TRANSPORT_disconnect (transport);
4218 while (NULL != (n = neighbours))
4220 neighbours = n->next;
4221 GNUNET_assert (neighbour_count > 0);
4225 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
4226 GNUNET_SERVER_notification_context_destroy (notifier);
4228 while (NULL != (c = clients))
4229 handle_client_disconnect (NULL, c->client_handle);
4230 if (my_private_key != NULL)
4231 GNUNET_CRYPTO_rsa_key_free (my_private_key);
4233 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4234 if (peerinfo != NULL)
4235 GNUNET_PEERINFO_disconnect (peerinfo);
4237 GNUNET_SERVER_mst_destroy (mst);
4242 * Initiate core service.
4244 * @param cls closure
4245 * @param server the initialized server
4246 * @param c configuration to use
4250 struct GNUNET_SERVER_Handle *server,
4251 const struct GNUNET_CONFIGURATION_Handle *c)
4253 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4254 {&handle_client_init, NULL,
4255 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
4256 {&handle_client_iterate_peers, NULL,
4257 GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
4258 sizeof (struct GNUNET_MessageHeader)},
4259 {&handle_client_request_info, NULL,
4260 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
4261 sizeof (struct RequestInfoMessage)},
4262 {&handle_client_send_request, NULL,
4263 GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST,
4264 sizeof (struct SendMessageRequest)},
4265 {&handle_client_send, NULL,
4266 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
4267 {&handle_client_request_connect, NULL,
4268 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
4269 sizeof (struct ConnectMessage)},
4275 /* parse configuration */
4278 GNUNET_CONFIGURATION_get_value_number (c,
4281 &bandwidth_target_in_bps)) ||
4283 GNUNET_CONFIGURATION_get_value_number (c,
4286 &bandwidth_target_out_bps)) ||
4288 GNUNET_CONFIGURATION_get_value_filename (c,
4290 "HOSTKEY", &keyfile)))
4292 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4294 ("Core service is lacking key configuration settings. Exiting.\n"));
4295 GNUNET_SCHEDULER_shutdown ();
4298 peerinfo = GNUNET_PEERINFO_connect (cfg);
4299 if (NULL == peerinfo)
4301 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4302 _("Could not access PEERINFO service. Exiting.\n"));
4303 GNUNET_SCHEDULER_shutdown ();
4304 GNUNET_free (keyfile);
4307 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4308 GNUNET_free (keyfile);
4309 if (my_private_key == NULL)
4311 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4312 _("Core service could not access hostkey. Exiting.\n"));
4313 GNUNET_PEERINFO_disconnect (peerinfo);
4314 GNUNET_SCHEDULER_shutdown ();
4317 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4318 GNUNET_CRYPTO_hash (&my_public_key,
4319 sizeof (my_public_key), &my_identity.hashPubKey);
4320 /* setup notification */
4321 notifier = GNUNET_SERVER_notification_context_create (server,
4323 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4324 /* setup transport connection */
4325 transport = GNUNET_TRANSPORT_connect (cfg,
4328 &handle_transport_receive,
4329 &handle_transport_notify_connect,
4330 &handle_transport_notify_disconnect);
4331 GNUNET_assert (NULL != transport);
4332 stats = GNUNET_STATISTICS_create ("core", cfg);
4334 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded CORE_SEND requests"), 0, GNUNET_NO);
4335 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 0, GNUNET_NO);
4337 mst = GNUNET_SERVER_mst_create (&deliver_message,
4339 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4340 &cleaning_task, NULL);
4341 /* process client requests */
4342 GNUNET_SERVER_add_handlers (server, handlers);
4343 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4344 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
4350 * The main function for the transport service.
4352 * @param argc number of arguments from the command line
4353 * @param argv command line arguments
4354 * @return 0 ok, 1 on error
4357 main (int argc, char *const *argv)
4359 return (GNUNET_OK ==
4360 GNUNET_SERVICE_run (argc,
4363 GNUNET_SERVICE_OPTION_NONE,
4364 &run, NULL)) ? 0 : 1;
4367 /* end of gnunet-service-core.c */