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)
1035 return; /* queue still full */
1036 /* find highest priority request */
1037 pos = n->active_client_request_head;
1041 if ( (car == NULL) ||
1042 (pos->priority > car->priority) )
1047 return; /* no pending requests */
1049 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1050 n->active_client_request_tail,
1052 GNUNET_CONTAINER_multihashmap_remove (c->requests,
1053 &n->peer.hashPubKey,
1055 smr.header.size = htons (sizeof (struct SendMessageReady));
1056 smr.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND_READY);
1057 smr.size = htons (car->msize);
1058 smr.smr_id = car->smr_id;
1060 send_to_client (c, &smr.header, GNUNET_NO);
1066 * Handle CORE_SEND_REQUEST message.
1069 handle_client_send_request (void *cls,
1070 struct GNUNET_SERVER_Client *client,
1071 const struct GNUNET_MessageHeader *message)
1073 const struct SendMessageRequest *req;
1074 struct Neighbour *n;
1076 struct ClientActiveRequest *car;
1078 req = (const struct SendMessageRequest*) message;
1079 n = find_neighbour (&req->peer);
1081 (GNUNET_YES != n->is_connected) ||
1082 (n->status != PEER_STATE_KEY_CONFIRMED) )
1084 /* neighbour must have disconnected since request was issued,
1085 ignore (client will realize it once it processes the
1086 disconnect notification) */
1087 GNUNET_STATISTICS_update (stats,
1088 gettext_noop ("# send requests dropped (disconnected)"),
1091 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1095 while ( (c != NULL) &&
1096 (c->client_handle != client) )
1100 /* client did not send INIT first! */
1102 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1105 if (c->requests == NULL)
1106 c->requests = GNUNET_CONTAINER_multihashmap_create (16);
1107 car = GNUNET_CONTAINER_multihashmap_get (c->requests,
1108 &req->peer.hashPubKey);
1111 /* create new entry */
1112 car = GNUNET_malloc (sizeof (struct ClientActiveRequest));
1113 GNUNET_assert (GNUNET_OK ==
1114 GNUNET_CONTAINER_multihashmap_put (c->requests,
1115 &req->peer.hashPubKey,
1117 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1118 GNUNET_CONTAINER_DLL_insert (n->active_client_request_head,
1119 n->active_client_request_tail,
1123 car->deadline = GNUNET_TIME_absolute_ntoh (req->deadline);
1124 car->priority = ntohl (req->priority);
1125 car->queue_size = ntohl (req->queue_size);
1126 car->msize = ntohs (req->size);
1127 car->smr_id = req->smr_id;
1128 schedule_peer_messages (n);
1129 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1134 * Handle CORE_INIT request.
1137 handle_client_init (void *cls,
1138 struct GNUNET_SERVER_Client *client,
1139 const struct GNUNET_MessageHeader *message)
1141 const struct InitMessage *im;
1142 struct InitReplyMessage irm;
1145 const uint16_t *types;
1147 struct Neighbour *n;
1148 struct ConnectNotifyMessage cnm;
1151 #if DEBUG_CORE_CLIENT
1152 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1153 "Client connecting to core service with `%s' message\n",
1156 /* check that we don't have an entry already */
1160 if (client == c->client_handle)
1163 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1168 msize = ntohs (message->size);
1169 if (msize < sizeof (struct InitMessage))
1172 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1175 GNUNET_SERVER_notification_context_add (notifier, client);
1176 im = (const struct InitMessage *) message;
1177 types = (const uint16_t *) &im[1];
1178 msize -= sizeof (struct InitMessage);
1179 c = GNUNET_malloc (sizeof (struct Client) + msize);
1180 c->client_handle = client;
1183 c->tcnt = msize / sizeof (uint16_t);
1184 c->types = (const uint16_t *) &c[1];
1185 wtypes = (uint16_t *) &c[1];
1186 for (i=0;i<c->tcnt;i++)
1187 wtypes[i] = ntohs (types[i]);
1188 c->options = ntohl (im->options);
1189 #if DEBUG_CORE_CLIENT
1190 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1191 "Client %p is interested in %u message types\n",
1193 (unsigned int) c->tcnt);
1195 /* send init reply message */
1196 irm.header.size = htons (sizeof (struct InitReplyMessage));
1197 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
1198 irm.reserved = htonl (0);
1199 memcpy (&irm.publicKey,
1201 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1202 #if DEBUG_CORE_CLIENT
1203 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1204 "Sending `%s' message to client.\n", "INIT_REPLY");
1206 send_to_client (c, &irm.header, GNUNET_NO);
1207 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
1209 /* notify new client about existing neighbours */
1210 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
1211 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1212 cnm.ats_count = htonl (0);
1213 cnm.ats.type = htonl (0);
1214 cnm.ats.value = htonl (0);
1218 if (n->status == PEER_STATE_KEY_CONFIRMED)
1220 #if DEBUG_CORE_CLIENT
1221 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1222 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
1225 send_to_client (c, &cnm.header, GNUNET_NO);
1230 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1235 * Free client request records.
1238 * @param key identity of peer for which this is an active request
1239 * @param value the 'struct ClientActiveRequest' to free
1240 * @return GNUNET_YES (continue iteration)
1243 destroy_active_client_request (void *cls,
1244 const GNUNET_HashCode *key,
1247 struct ClientActiveRequest *car = cls;
1248 struct Neighbour *n;
1249 struct GNUNET_PeerIdentity peer;
1251 peer.hashPubKey = *key;
1252 n = find_neighbour (&peer);
1253 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1254 n->active_client_request_tail,
1262 * A client disconnected, clean up.
1264 * @param cls closure
1265 * @param client identification of the client
1268 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1271 struct Client *prev;
1275 #if DEBUG_CORE_CLIENT
1276 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1277 "Client %p has disconnected from core service.\n",
1284 if (client == pos->client_handle)
1291 /* client never sent INIT */
1295 clients = pos->next;
1297 prev->next = pos->next;
1298 if (pos->requests != NULL)
1300 GNUNET_CONTAINER_multihashmap_iterate (pos->requests,
1301 &destroy_active_client_request,
1303 GNUNET_CONTAINER_multihashmap_destroy (pos->requests);
1310 * Handle CORE_ITERATE_PEERS request.
1313 handle_client_iterate_peers (void *cls,
1314 struct GNUNET_SERVER_Client *client,
1315 const struct GNUNET_MessageHeader *message)
1318 struct Neighbour *n;
1319 struct ConnectNotifyMessage cnm;
1320 struct GNUNET_MessageHeader done_msg;
1321 struct GNUNET_SERVER_TransmitContext *tc;
1323 /* notify new client about existing neighbours */
1324 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
1325 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1326 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
1327 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1328 tc = GNUNET_SERVER_transmit_context_create (client);
1330 cnm.ats_count = htonl (0);
1331 cnm.ats.type = htonl (0);
1332 cnm.ats.value = htonl (0);
1335 if (n->status == PEER_STATE_KEY_CONFIRMED)
1337 #if DEBUG_CORE_CLIENT
1338 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1339 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
1342 GNUNET_SERVER_transmit_context_append_message (tc, &cnm.header);
1346 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
1347 GNUNET_SERVER_transmit_context_run (tc,
1348 GNUNET_TIME_UNIT_FOREVER_REL);
1353 * Handle REQUEST_INFO request.
1356 handle_client_request_info (void *cls,
1357 struct GNUNET_SERVER_Client *client,
1358 const struct GNUNET_MessageHeader *message)
1360 const struct RequestInfoMessage *rcm;
1361 struct Neighbour *n;
1362 struct ConfigurationInfoMessage cim;
1363 int32_t want_reserv;
1365 unsigned long long old_preference;
1366 struct GNUNET_SERVER_TransmitContext *tc;
1368 #if DEBUG_CORE_CLIENT
1369 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1370 "Core service receives `%s' request.\n", "REQUEST_INFO");
1372 rcm = (const struct RequestInfoMessage *) message;
1373 n = find_neighbour (&rcm->peer);
1374 memset (&cim, 0, sizeof (cim));
1377 want_reserv = ntohl (rcm->reserve_inbound);
1378 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1380 n->bw_out_internal_limit = rcm->limit_outbound;
1381 if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1382 n->bw_out_external_limit).value__)
1384 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1385 n->bw_out_external_limit);
1386 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1388 GNUNET_TRANSPORT_set_quota (transport,
1392 GNUNET_TIME_UNIT_FOREVER_REL,
1394 handle_peer_status_change (n);
1397 if (want_reserv < 0)
1399 got_reserv = want_reserv;
1401 else if (want_reserv > 0)
1403 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1404 want_reserv).rel_value == 0)
1405 got_reserv = want_reserv;
1407 got_reserv = 0; /* all or nothing */
1411 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1413 old_preference = n->current_preference;
1414 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1415 if (old_preference > n->current_preference)
1417 /* overflow; cap at maximum value */
1418 n->current_preference = ULLONG_MAX;
1420 update_preference_sum (n->current_preference - old_preference);
1421 #if DEBUG_CORE_QUOTA
1422 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1423 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1425 GNUNET_i2s (&rcm->peer),
1428 cim.reserved_amount = htonl (got_reserv);
1429 cim.rim_id = rcm->rim_id;
1430 cim.bw_out = n->bw_out;
1431 cim.preference = n->current_preference;
1433 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1434 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1435 cim.peer = rcm->peer;
1437 #if DEBUG_CORE_CLIENT
1438 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1439 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1441 tc = GNUNET_SERVER_transmit_context_create (client);
1442 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1443 GNUNET_SERVER_transmit_context_run (tc,
1444 GNUNET_TIME_UNIT_FOREVER_REL);
1449 * Free the given entry for the neighbour (it has
1450 * already been removed from the list at this point).
1452 * @param n neighbour to free
1455 free_neighbour (struct Neighbour *n)
1457 struct MessageEntry *m;
1458 struct ClientActiveRequest *car;
1461 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1462 "Destroying neighbour entry for peer `%4s'\n",
1463 GNUNET_i2s (&n->peer));
1465 if (n->pitr != NULL)
1467 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1472 GNUNET_free (n->skm);
1475 while (NULL != (m = n->messages))
1477 n->messages = m->next;
1480 while (NULL != (m = n->encrypted_head))
1482 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1487 while (NULL != (car = n->active_client_request_head))
1489 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1490 n->active_client_request_tail,
1492 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
1493 &n->peer.hashPubKey,
1499 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1502 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1503 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
1504 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1505 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
1506 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1507 GNUNET_SCHEDULER_cancel (n->quota_update_task);
1508 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1509 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1510 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1511 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
1512 if (n->status == PEER_STATE_KEY_CONFIRMED)
1513 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1514 GNUNET_free_non_null (n->public_key);
1515 GNUNET_free_non_null (n->pending_ping);
1516 GNUNET_free_non_null (n->pending_pong);
1522 * Check if we have encrypted messages for the specified neighbour
1523 * pending, and if so, check with the transport about sending them
1526 * @param n neighbour to check.
1528 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1532 * Encrypt size bytes from in and write the result to out. Use the
1533 * key for outbound traffic of the given neighbour.
1535 * @param n neighbour we are sending to
1536 * @param iv initialization vector to use
1537 * @param in ciphertext
1538 * @param out plaintext
1539 * @param size size of in/out
1540 * @return GNUNET_OK on success
1543 do_encrypt (struct Neighbour *n,
1544 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1545 const void *in, void *out, size_t size)
1547 if (size != (uint16_t) size)
1552 GNUNET_assert (size ==
1553 GNUNET_CRYPTO_aes_encrypt (in,
1557 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1559 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1560 "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
1561 (unsigned int) size,
1562 GNUNET_i2s (&n->peer),
1563 (unsigned int) n->encrypt_key.crc32,
1564 GNUNET_CRYPTO_crc32_n (iv, sizeof(iv)));
1571 * Consider freeing the given neighbour since we may not need
1572 * to keep it around anymore.
1574 * @param n neighbour to consider discarding
1577 consider_free_neighbour (struct Neighbour *n);
1581 * Task triggered when a neighbour entry is about to time out
1582 * (and we should prevent this by sending a PING).
1584 * @param cls the 'struct Neighbour'
1585 * @param tc scheduler context (not used)
1588 send_keep_alive (void *cls,
1589 const struct GNUNET_SCHEDULER_TaskContext *tc)
1591 struct Neighbour *n = cls;
1592 struct GNUNET_TIME_Relative retry;
1593 struct GNUNET_TIME_Relative left;
1594 struct MessageEntry *me;
1595 struct PingMessage pp;
1596 struct PingMessage *pm;
1597 struct GNUNET_CRYPTO_AesInitializationVector iv;
1599 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1601 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1602 sizeof (struct PingMessage));
1603 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1604 me->priority = PING_PRIORITY;
1605 me->size = sizeof (struct PingMessage);
1606 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1610 pm = (struct PingMessage *) &me[1];
1611 pm->header.size = htons (sizeof (struct PingMessage));
1612 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1613 pm->iv_seed = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1615 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
1616 pp.challenge = n->ping_challenge;
1617 pp.target = n->peer;
1619 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1620 "Encrypting `%s' message with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
1622 (unsigned int) n->ping_challenge,
1623 GNUNET_i2s (&n->peer),
1624 (unsigned int) n->encrypt_key.crc32,
1625 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
1632 sizeof (struct PingMessage) -
1633 ((void *) &pm->target - (void *) pm));
1634 process_encrypted_neighbour_queue (n);
1635 /* reschedule PING job */
1636 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1637 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1638 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1639 MIN_PING_FREQUENCY);
1641 = GNUNET_SCHEDULER_add_delayed (retry,
1649 * Task triggered when a neighbour entry might have gotten stale.
1651 * @param cls the 'struct Neighbour'
1652 * @param tc scheduler context (not used)
1655 consider_free_task (void *cls,
1656 const struct GNUNET_SCHEDULER_TaskContext *tc)
1658 struct Neighbour *n = cls;
1660 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1661 consider_free_neighbour (n);
1666 * Consider freeing the given neighbour since we may not need
1667 * to keep it around anymore.
1669 * @param n neighbour to consider discarding
1672 consider_free_neighbour (struct Neighbour *n)
1674 struct Neighbour *pos;
1675 struct Neighbour *prev;
1676 struct GNUNET_TIME_Relative left;
1678 if ( (n->th != NULL) ||
1679 (n->pitr != NULL) ||
1680 (GNUNET_YES == n->is_connected) )
1681 return; /* no chance */
1683 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1684 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1685 if (left.rel_value > 0)
1687 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1688 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1689 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (left,
1690 &consider_free_task,
1694 /* actually free the neighbour... */
1703 neighbours = n->next;
1705 prev->next = n->next;
1706 GNUNET_assert (neighbour_count > 0);
1708 GNUNET_STATISTICS_set (stats,
1709 gettext_noop ("# neighbour entries allocated"),
1717 * Function called when the transport service is ready to
1718 * receive an encrypted message for the respective peer
1720 * @param cls neighbour to use message from
1721 * @param size number of bytes we can transmit
1722 * @param buf where to copy the message
1723 * @return number of bytes transmitted
1726 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1728 struct Neighbour *n = cls;
1729 struct MessageEntry *m;
1734 m = n->encrypted_head;
1738 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1739 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1740 GNUNET_i2s (&n->peer));
1744 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1751 GNUNET_assert (size >= m->size);
1752 memcpy (cbuf, &m[1], m->size);
1754 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1757 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1758 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1759 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1761 GNUNET_i2s (&n->peer));
1763 process_encrypted_neighbour_queue (n);
1768 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1769 "Transmission of message of type %u and size %u failed\n",
1770 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1771 (unsigned int) m->size);
1775 consider_free_neighbour (n);
1781 * Check if we have plaintext messages for the specified neighbour
1782 * pending, and if so, consider batching and encrypting them (and
1783 * then trigger processing of the encrypted queue if needed).
1785 * @param n neighbour to check.
1787 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1791 * Check if we have encrypted messages for the specified neighbour
1792 * pending, and if so, check with the transport about sending them
1795 * @param n neighbour to check.
1798 process_encrypted_neighbour_queue (struct Neighbour *n)
1800 struct MessageEntry *m;
1803 return; /* request already pending */
1804 m = n->encrypted_head;
1807 /* encrypted queue empty, try plaintext instead */
1808 process_plaintext_neighbour_queue (n);
1812 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1813 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1814 (unsigned int) m->size,
1815 GNUNET_i2s (&n->peer),
1816 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).rel_value);
1819 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1822 GNUNET_TIME_absolute_get_remaining
1824 ¬ify_encrypted_transmit_ready,
1828 /* message request too large or duplicate request */
1830 /* discard encrypted message */
1831 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1835 process_encrypted_neighbour_queue (n);
1841 * Decrypt size bytes from in and write the result to out. Use the
1842 * key for inbound traffic of the given neighbour. This function does
1843 * NOT do any integrity-checks on the result.
1845 * @param n neighbour we are receiving from
1846 * @param iv initialization vector to use
1847 * @param in ciphertext
1848 * @param out plaintext
1849 * @param size size of in/out
1850 * @return GNUNET_OK on success
1853 do_decrypt (struct Neighbour *n,
1854 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1855 const void *in, void *out, size_t size)
1857 if (size != (uint16_t) size)
1862 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1863 (n->status != PEER_STATE_KEY_CONFIRMED))
1865 GNUNET_break_op (0);
1866 return GNUNET_SYSERR;
1869 GNUNET_CRYPTO_aes_decrypt (in,
1876 return GNUNET_SYSERR;
1878 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1880 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1881 "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
1882 (unsigned int) size,
1883 GNUNET_i2s (&n->peer),
1884 (unsigned int) n->decrypt_key.crc32,
1885 GNUNET_CRYPTO_crc32_n (iv, sizeof(*iv)));
1892 * Select messages for transmission. This heuristic uses a combination
1893 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1894 * and priority-based discard (in case no feasible schedule exist) and
1895 * speculative optimization (defer any kind of transmission until
1896 * we either create a batch of significant size, 25% of max, or until
1897 * we are close to a deadline). Furthermore, when scheduling the
1898 * heuristic also packs as many messages into the batch as possible,
1899 * starting with those with the earliest deadline. Yes, this is fun.
1901 * @param n neighbour to select messages from
1902 * @param size number of bytes to select for transmission
1903 * @param retry_time set to the time when we should try again
1904 * (only valid if this function returns zero)
1905 * @return number of bytes selected, or 0 if we decided to
1906 * defer scheduling overall; in that case, retry_time is set.
1909 select_messages (struct Neighbour *n,
1910 size_t size, struct GNUNET_TIME_Relative *retry_time)
1912 struct MessageEntry *pos;
1913 struct MessageEntry *min;
1914 struct MessageEntry *last;
1915 unsigned int min_prio;
1916 struct GNUNET_TIME_Absolute t;
1917 struct GNUNET_TIME_Absolute now;
1918 struct GNUNET_TIME_Relative delta;
1920 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1923 unsigned int queue_size;
1924 int discard_low_prio;
1926 GNUNET_assert (NULL != n->messages);
1927 now = GNUNET_TIME_absolute_get ();
1928 /* last entry in linked list of messages processed */
1930 /* should we remove the entry with the lowest
1931 priority from consideration for scheduling at the
1942 discard_low_prio = GNUNET_YES;
1943 while (GNUNET_YES == discard_low_prio)
1946 min_prio = UINT_MAX;
1947 discard_low_prio = GNUNET_NO;
1948 /* calculate number of bytes available for transmission at time "t" */
1949 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1951 /* how many bytes have we (hypothetically) scheduled so far */
1953 /* maximum time we can wait before transmitting anything
1954 and still make all of our deadlines */
1955 slack = GNUNET_TIME_UNIT_FOREVER_REL;
1957 /* note that we use "*2" here because we want to look
1958 a bit further into the future; much more makes no
1959 sense since new message might be scheduled in the
1961 while ((pos != NULL) && (off < size * 2))
1963 if (pos->do_transmit == GNUNET_YES)
1965 /* already removed from consideration */
1969 if (discard_low_prio == GNUNET_NO)
1971 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1972 if (delta.rel_value > 0)
1974 // FIXME: HUH? Check!
1976 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1979 if (avail < pos->size)
1981 // FIXME: HUH? Check!
1982 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1987 /* update slack, considering both its absolute deadline
1988 and relative deadlines caused by other messages
1989 with their respective load */
1990 slack = GNUNET_TIME_relative_min (slack,
1991 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1993 if (pos->deadline.abs_value <= now.abs_value)
1996 slack = GNUNET_TIME_UNIT_ZERO;
1998 else if (GNUNET_YES == pos->got_slack)
2000 /* should be soon now! */
2001 slack = GNUNET_TIME_relative_min (slack,
2002 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
2007 GNUNET_TIME_relative_min (slack,
2008 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
2009 pos->got_slack = GNUNET_YES;
2010 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
2011 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
2016 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
2017 if (pos->priority <= min_prio)
2019 /* update min for discard */
2020 min_prio = pos->priority;
2025 if (discard_low_prio)
2027 GNUNET_assert (min != NULL);
2028 /* remove lowest-priority entry from consideration */
2029 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
2033 /* guard against sending "tiny" messages with large headers without
2035 if ( (slack.rel_value > GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value) &&
2037 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
2039 /* less than 25% of message would be filled with deadlines still
2040 being met if we delay by one second or more; so just wait for
2041 more data; but do not wait longer than 1s (since we don't want
2042 to delay messages for a really long time either). */
2043 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
2044 /* reset do_transmit values for next time */
2047 pos->do_transmit = GNUNET_NO;
2050 GNUNET_STATISTICS_update (stats,
2051 gettext_noop ("# transmissions delayed due to corking"),
2054 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2055 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
2056 (unsigned long long) retry_time->rel_value,
2058 (unsigned int) size);
2062 /* select marked messages (up to size) for transmission */
2067 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
2069 pos->do_transmit = GNUNET_YES; /* mark for transmission */
2073 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2074 "Selecting message of size %u for transmission\n",
2075 (unsigned int) pos->size);
2081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2082 "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
2083 (unsigned int) pos->size,
2086 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
2091 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2092 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
2093 (unsigned long long) off, (unsigned long long) tsize,
2094 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
2095 GNUNET_i2s (&n->peer));
2102 * Batch multiple messages into a larger buffer.
2104 * @param n neighbour to take messages from
2105 * @param buf target buffer
2106 * @param size size of buf
2107 * @param deadline set to transmission deadline for the result
2108 * @param retry_time set to the time when we should try again
2109 * (only valid if this function returns zero)
2110 * @param priority set to the priority of the batch
2111 * @return number of bytes written to buf (can be zero)
2114 batch_message (struct Neighbour *n,
2117 struct GNUNET_TIME_Absolute *deadline,
2118 struct GNUNET_TIME_Relative *retry_time,
2119 unsigned int *priority)
2121 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
2122 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
2123 struct MessageEntry *pos;
2124 struct MessageEntry *prev;
2125 struct MessageEntry *next;
2130 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2131 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
2132 if (0 == select_messages (n, size, retry_time))
2135 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2136 "No messages selected, will try again in %llu ms\n",
2137 retry_time->rel_value);
2141 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
2142 ntm->ats_count = htonl (0);
2143 ntm->ats.type = htonl (0);
2144 ntm->ats.value = htonl (0);
2145 ntm->peer = n->peer;
2148 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
2151 if (GNUNET_YES == pos->do_transmit)
2153 GNUNET_assert (pos->size <= size);
2154 /* do notifications */
2155 /* FIXME: track if we have *any* client that wants
2156 full notifications and only do this if that is
2158 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
2160 memcpy (&ntm[1], &pos[1], pos->size);
2161 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
2162 sizeof (struct GNUNET_MessageHeader));
2163 send_to_all_clients (&ntm->header,
2165 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
2169 /* message too large for 'full' notifications, we do at
2170 least the 'hdr' type */
2173 sizeof (struct GNUNET_MessageHeader));
2175 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
2177 send_to_all_clients (&ntm->header,
2179 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
2181 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2182 "Encrypting %u bytes with message of type %u and size %u\n",
2184 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
2185 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
2187 /* copy for encrypted transmission */
2188 memcpy (&buf[ret], &pos[1], pos->size);
2191 *priority += pos->priority;
2193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2194 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
2195 (unsigned int) pos->size,
2196 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).rel_value);
2198 deadline->abs_value = GNUNET_MIN (deadline->abs_value, pos->deadline.abs_value);
2212 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2213 "Deadline for message batch is %llu ms\n",
2214 GNUNET_TIME_absolute_get_remaining (*deadline).rel_value);
2221 * Remove messages with deadlines that have long expired from
2224 * @param n neighbour to inspect
2227 discard_expired_messages (struct Neighbour *n)
2229 struct MessageEntry *prev;
2230 struct MessageEntry *next;
2231 struct MessageEntry *pos;
2232 struct GNUNET_TIME_Absolute now;
2233 struct GNUNET_TIME_Relative delta;
2237 now = GNUNET_TIME_absolute_get ();
2243 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
2244 if (delta.rel_value > PAST_EXPIRATION_DISCARD_TIME.rel_value)
2247 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2248 "Message is %llu ms past due, discarding.\n",
2255 GNUNET_STATISTICS_update (stats,
2256 gettext_noop ("# messages discarded (expired prior to transmission)"),
2266 if (GNUNET_YES == disc)
2267 schedule_peer_messages (n);
2272 * Signature of the main function of a task.
2274 * @param cls closure
2275 * @param tc context information (why was this task triggered now)
2278 retry_plaintext_processing (void *cls,
2279 const struct GNUNET_SCHEDULER_TaskContext *tc)
2281 struct Neighbour *n = cls;
2283 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2284 process_plaintext_neighbour_queue (n);
2289 * Send our key (and encrypted PING) to the other peer.
2291 * @param n the other peer
2293 static void send_key (struct Neighbour *n);
2296 * Task that will retry "send_key" if our previous attempt failed
2300 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2302 struct Neighbour *n = cls;
2305 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2306 "Retrying key transmission to `%4s'\n",
2307 GNUNET_i2s (&n->peer));
2309 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2310 n->set_key_retry_frequency =
2311 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2317 * Check if we have plaintext messages for the specified neighbour
2318 * pending, and if so, consider batching and encrypting them (and
2319 * then trigger processing of the encrypted queue if needed).
2321 * @param n neighbour to check.
2324 process_plaintext_neighbour_queue (struct Neighbour *n)
2326 char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)]; /* plaintext */
2328 struct EncryptedMessage *em; /* encrypted message */
2329 struct EncryptedMessage *ph; /* plaintext header */
2330 struct MessageEntry *me;
2331 unsigned int priority;
2332 struct GNUNET_TIME_Absolute deadline;
2333 struct GNUNET_TIME_Relative retry_time;
2334 struct GNUNET_CRYPTO_AesInitializationVector iv;
2335 struct GNUNET_CRYPTO_AuthKey auth_key;
2337 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2339 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
2340 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2344 case PEER_STATE_DOWN:
2347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2348 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2349 GNUNET_i2s(&n->peer));
2352 case PEER_STATE_KEY_SENT:
2353 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2354 n->retry_set_key_task
2355 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2356 &set_key_retry_task, n);
2358 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2359 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2360 GNUNET_i2s(&n->peer));
2363 case PEER_STATE_KEY_RECEIVED:
2364 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2365 n->retry_set_key_task
2366 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2367 &set_key_retry_task, n);
2369 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2370 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2371 GNUNET_i2s(&n->peer));
2374 case PEER_STATE_KEY_CONFIRMED:
2375 /* ready to continue */
2378 discard_expired_messages (n);
2379 if (n->messages == NULL)
2382 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2383 "Plaintext message queue for `%4s' is empty.\n",
2384 GNUNET_i2s(&n->peer));
2386 return; /* no pending messages */
2388 if (n->encrypted_head != NULL)
2391 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2392 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2393 GNUNET_i2s(&n->peer));
2395 return; /* wait for messages already encrypted to be
2398 ph = (struct EncryptedMessage *) pbuf;
2399 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2401 used = sizeof (struct EncryptedMessage);
2402 used += batch_message (n,
2404 GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2405 &deadline, &retry_time, &priority);
2406 if (used == sizeof (struct EncryptedMessage))
2409 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2410 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2411 GNUNET_i2s(&n->peer));
2413 /* no messages selected for sending, try again later... */
2414 n->retry_plaintext_task =
2415 GNUNET_SCHEDULER_add_delayed (retry_time,
2416 &retry_plaintext_processing, n);
2419 #if DEBUG_CORE_QUOTA
2420 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2421 "Sending %u b/s as new limit to peer `%4s'\n",
2422 (unsigned int) ntohl (n->bw_in.value__),
2423 GNUNET_i2s (&n->peer));
2425 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
2426 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2427 ph->inbound_bw_limit = n->bw_in;
2428 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2430 /* setup encryption message header */
2431 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2432 me->deadline = deadline;
2433 me->priority = priority;
2435 em = (struct EncryptedMessage *) &me[1];
2436 em->header.size = htons (used);
2437 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2438 em->iv_seed = ph->iv_seed;
2439 derive_iv (&iv, &n->encrypt_key, ph->iv_seed, &n->peer);
2442 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2443 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2444 (unsigned int) used - ENCRYPTED_HEADER_SIZE,
2445 GNUNET_i2s(&n->peer),
2446 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).rel_value);
2448 GNUNET_assert (GNUNET_OK ==
2451 &ph->sequence_number,
2452 &em->sequence_number, used - ENCRYPTED_HEADER_SIZE));
2453 derive_auth_key (&auth_key,
2456 n->encrypt_key_created);
2457 GNUNET_CRYPTO_hmac (&auth_key,
2458 &em->sequence_number,
2459 used - ENCRYPTED_HEADER_SIZE,
2462 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2463 "Authenticated %u bytes of ciphertext %u: `%s'\n",
2464 used - ENCRYPTED_HEADER_SIZE,
2465 GNUNET_CRYPTO_crc32_n (&em->sequence_number,
2466 used - ENCRYPTED_HEADER_SIZE),
2467 GNUNET_h2s (&em->hmac));
2469 /* append to transmission list */
2470 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2474 process_encrypted_neighbour_queue (n);
2475 schedule_peer_messages (n);
2480 * Function that recalculates the bandwidth quota for the
2481 * given neighbour and transmits it to the transport service.
2483 * @param cls neighbour for the quota update
2487 neighbour_quota_update (void *cls,
2488 const struct GNUNET_SCHEDULER_TaskContext *tc);
2492 * Schedule the task that will recalculate the bandwidth
2493 * quota for this peer (and possibly force a disconnect of
2494 * idle peers by calculating a bandwidth of zero).
2497 schedule_quota_update (struct Neighbour *n)
2499 GNUNET_assert (n->quota_update_task ==
2500 GNUNET_SCHEDULER_NO_TASK);
2501 n->quota_update_task
2502 = GNUNET_SCHEDULER_add_delayed (QUOTA_UPDATE_FREQUENCY,
2503 &neighbour_quota_update,
2509 * Initialize a new 'struct Neighbour'.
2511 * @param pid ID of the new neighbour
2512 * @return handle for the new neighbour
2514 static struct Neighbour *
2515 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2517 struct Neighbour *n;
2518 struct GNUNET_TIME_Absolute now;
2521 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2522 "Creating neighbour entry for peer `%4s'\n",
2525 n = GNUNET_malloc (sizeof (struct Neighbour));
2526 n->next = neighbours;
2529 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2531 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2532 now = GNUNET_TIME_absolute_get ();
2533 n->encrypt_key_created = now;
2534 n->last_activity = now;
2535 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2536 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2537 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2538 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2539 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2540 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
2542 neighbour_quota_update (n, NULL);
2543 consider_free_neighbour (n);
2549 * Handle CORE_SEND request.
2552 * @param client the client issuing the request
2553 * @param message the "struct SendMessage"
2556 handle_client_send (void *cls,
2557 struct GNUNET_SERVER_Client *client,
2558 const struct GNUNET_MessageHeader *message)
2560 const struct SendMessage *sm;
2561 struct Neighbour *n;
2562 struct MessageEntry *prev;
2563 struct MessageEntry *pos;
2564 struct MessageEntry *e;
2565 struct MessageEntry *min_prio_entry;
2566 struct MessageEntry *min_prio_prev;
2567 unsigned int min_prio;
2568 unsigned int queue_size;
2571 msize = ntohs (message->size);
2573 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2575 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));
2578 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2581 sm = (const struct SendMessage *) message;
2582 msize -= sizeof (struct SendMessage);
2583 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2585 /* FIXME: should we not allow loopback-injection here? */
2588 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2591 n = find_neighbour (&sm->peer);
2593 n = create_neighbour (&sm->peer);
2595 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2596 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2598 (unsigned int) msize,
2599 GNUNET_i2s (&sm->peer));
2601 discard_expired_messages (n);
2602 /* bound queue size */
2603 /* NOTE: this entire block to bound the queue size should be
2604 obsolete with the new client-request code and the
2605 'schedule_peer_messages' mechanism; we still have this code in
2606 here for now as a sanity check for the new mechanmism;
2607 ultimately, we should probably simply reject SEND messages that
2608 are not 'approved' (or provide a new core API for very unreliable
2609 delivery that always sends with priority 0). Food for thought. */
2610 min_prio = UINT32_MAX;
2611 min_prio_entry = NULL;
2612 min_prio_prev = NULL;
2618 if (pos->priority <= min_prio)
2620 min_prio_entry = pos;
2621 min_prio_prev = prev;
2622 min_prio = pos->priority;
2628 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2631 if (ntohl(sm->priority) <= min_prio)
2633 /* discard new entry; this should no longer happen! */
2636 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2637 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2639 (unsigned int) MAX_PEER_QUEUE_SIZE,
2640 (unsigned int) msize,
2641 (unsigned int) ntohs (message->type));
2643 GNUNET_STATISTICS_update (stats,
2644 gettext_noop ("# discarded CORE_SEND requests"),
2648 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2651 GNUNET_assert (min_prio_entry != NULL);
2652 /* discard "min_prio_entry" */
2654 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2655 "Queue full, discarding existing older request\n");
2657 GNUNET_STATISTICS_update (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 1, GNUNET_NO);
2658 if (min_prio_prev == NULL)
2659 n->messages = min_prio_entry->next;
2661 min_prio_prev->next = min_prio_entry->next;
2662 GNUNET_free (min_prio_entry);
2666 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2667 "Adding transmission request for `%4s' of size %u to queue\n",
2668 GNUNET_i2s (&sm->peer),
2669 (unsigned int) msize);
2671 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2672 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2673 e->priority = ntohl (sm->priority);
2675 memcpy (&e[1], &sm[1], msize);
2677 /* insert, keep list sorted by deadline */
2680 while ((pos != NULL) && (pos->deadline.abs_value < e->deadline.abs_value))
2691 /* consider scheduling now */
2692 process_plaintext_neighbour_queue (n);
2694 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2699 * Function called when the transport service is ready to
2700 * receive a message. Only resets 'n->th' to NULL.
2702 * @param cls neighbour to use message from
2703 * @param size number of bytes we can transmit
2704 * @param buf where to copy the message
2705 * @return number of bytes transmitted
2708 notify_transport_connect_done (void *cls, size_t size, void *buf)
2710 struct Neighbour *n = cls;
2712 if (GNUNET_YES != n->is_connected)
2714 /* transport should only call us to transmit a message after
2715 * telling us about a successful connection to the respective peer */
2716 n->th = NULL; /* If this happens because of a timeout, reset n-th so another message may be sent for this peer! */
2718 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Timeout on notify connect!\n");
2725 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2726 _("Failed to connect to `%4s': transport failed to connect\n"),
2727 GNUNET_i2s (&n->peer));
2730 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2731 _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2732 GNUNET_i2s (&n->peer));
2733 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2734 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2735 n->retry_set_key_task = GNUNET_SCHEDULER_add_now (&set_key_retry_task,
2742 * Handle CORE_REQUEST_CONNECT request.
2745 * @param client the client issuing the request
2746 * @param message the "struct ConnectMessage"
2749 handle_client_request_connect (void *cls,
2750 struct GNUNET_SERVER_Client *client,
2751 const struct GNUNET_MessageHeader *message)
2753 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2754 struct Neighbour *n;
2755 struct GNUNET_TIME_Relative timeout;
2757 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2760 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2763 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2764 n = find_neighbour (&cm->peer);
2766 n = create_neighbour (&cm->peer);
2767 if ( (GNUNET_YES == n->is_connected) ||
2770 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2771 "Core received `%s' request for `%4s', already connected!\n",
2773 GNUNET_i2s (&cm->peer));
2774 return; /* already connected, or at least trying */
2776 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2778 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2779 "Core received `%s' request for `%4s', will try to establish connection\n",
2781 GNUNET_i2s (&cm->peer));
2783 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2784 /* ask transport to connect to the peer */
2785 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2787 sizeof (struct GNUNET_MessageHeader), 0,
2789 ¬ify_transport_connect_done,
2791 GNUNET_break (NULL != n->th);
2796 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2797 * the neighbour's struct and retry send_key. Or, if we did not get a
2798 * HELLO, just do nothing.
2800 * @param cls the 'struct Neighbour' to retry sending the key for
2801 * @param peer the peer for which this is the HELLO
2802 * @param hello HELLO message of that peer
2805 process_hello_retry_send_key (void *cls,
2806 const struct GNUNET_PeerIdentity *peer,
2807 const struct GNUNET_HELLO_Message *hello)
2809 struct Neighbour *n = cls;
2814 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2815 "Entered `%s' and `%s' is NULL!\n",
2816 "process_hello_retry_send_key",
2820 if (n->public_key != NULL)
2822 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2824 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2825 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2827 GNUNET_STATISTICS_update (stats,
2828 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2836 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2837 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
2838 GNUNET_i2s (&n->peer));
2840 GNUNET_STATISTICS_update (stats,
2841 gettext_noop ("# Delayed connecting due to lack of public key"),
2844 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2845 n->retry_set_key_task
2846 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2847 &set_key_retry_task, n);
2853 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2854 "Entered `%s' for peer `%4s'\n",
2855 "process_hello_retry_send_key",
2858 if (n->public_key != NULL)
2860 /* already have public key, why are we here? */
2866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2867 "Received new `%s' message for `%4s', initiating key exchange.\n",
2872 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2873 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2875 GNUNET_STATISTICS_update (stats,
2876 gettext_noop ("# Error extracting public key from HELLO"),
2879 GNUNET_free (n->public_key);
2880 n->public_key = NULL;
2882 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2883 "GNUNET_HELLO_get_key returned awfully\n");
2891 * Send our key (and encrypted PING) to the other peer.
2893 * @param n the other peer
2896 send_key (struct Neighbour *n)
2898 struct MessageEntry *pos;
2899 struct SetKeyMessage *sm;
2900 struct MessageEntry *me;
2901 struct PingMessage pp;
2902 struct PingMessage *pm;
2903 struct GNUNET_CRYPTO_AesInitializationVector iv;
2905 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2907 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2908 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2910 if (n->pitr != NULL)
2913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2914 "Key exchange in progress with `%4s'.\n",
2915 GNUNET_i2s (&n->peer));
2917 return; /* already in progress */
2919 if (GNUNET_YES != n->is_connected)
2922 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2923 "Not yet connected to peer `%4s'!\n",
2924 GNUNET_i2s (&n->peer));
2928 GNUNET_STATISTICS_update (stats,
2929 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
2932 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2934 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2936 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2937 ¬ify_encrypted_transmit_ready,
2943 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2944 "Asked to perform key exchange with `%4s'.\n",
2945 GNUNET_i2s (&n->peer));
2947 if (n->public_key == NULL)
2949 /* lookup n's public key, then try again */
2951 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2952 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2953 GNUNET_i2s (&n->peer));
2955 GNUNET_assert (n->pitr == NULL);
2956 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2958 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2959 &process_hello_retry_send_key, n);
2962 pos = n->encrypted_head;
2965 if (GNUNET_YES == pos->is_setkey)
2967 if (pos->sender_status == n->status)
2970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2971 "`%s' message for `%4s' queued already\n",
2973 GNUNET_i2s (&n->peer));
2975 goto trigger_processing;
2977 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2982 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2983 "Removing queued `%s' message for `%4s', will create a new one\n",
2985 GNUNET_i2s (&n->peer));
2995 case PEER_STATE_DOWN:
2996 n->status = PEER_STATE_KEY_SENT;
2998 case PEER_STATE_KEY_SENT:
3000 case PEER_STATE_KEY_RECEIVED:
3002 case PEER_STATE_KEY_CONFIRMED:
3010 /* first, set key message */
3011 me = GNUNET_malloc (sizeof (struct MessageEntry) +
3012 sizeof (struct SetKeyMessage) +
3013 sizeof (struct PingMessage));
3014 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
3015 me->priority = SET_KEY_PRIORITY;
3016 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
3017 me->is_setkey = GNUNET_YES;
3018 me->got_slack = GNUNET_YES; /* do not defer this one! */
3019 me->sender_status = n->status;
3020 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3024 sm = (struct SetKeyMessage *) &me[1];
3025 sm->header.size = htons (sizeof (struct SetKeyMessage));
3026 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
3027 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
3028 PEER_STATE_KEY_SENT : n->status));
3030 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3031 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3032 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3033 sizeof (struct GNUNET_PeerIdentity));
3034 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
3035 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
3036 sm->target = n->peer;
3037 GNUNET_assert (GNUNET_OK ==
3038 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
3040 GNUNET_CRYPTO_AesSessionKey),
3042 &sm->encrypted_key));
3043 GNUNET_assert (GNUNET_OK ==
3044 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
3046 pm = (struct PingMessage *) &sm[1];
3047 pm->header.size = htons (sizeof (struct PingMessage));
3048 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
3049 pm->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3050 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
3051 pp.challenge = n->ping_challenge;
3052 pp.target = n->peer;
3054 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3055 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
3057 (unsigned int) n->ping_challenge,
3058 GNUNET_i2s (&n->peer),
3059 (unsigned int) n->encrypt_key.crc32,
3060 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3067 sizeof (struct PingMessage) -
3068 ((void *) &pm->target - (void *) pm));
3069 GNUNET_STATISTICS_update (stats,
3070 gettext_noop ("# SET_KEY and PING messages created"),
3074 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3075 "Have %llu ms left for `%s' transmission.\n",
3076 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).rel_value,
3080 /* trigger queue processing */
3081 process_encrypted_neighbour_queue (n);
3082 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
3083 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
3084 n->retry_set_key_task
3085 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3086 &set_key_retry_task, n);
3091 * We received a SET_KEY message. Validate and update
3092 * our key material and status.
3094 * @param n the neighbour from which we received message m
3095 * @param m the set key message we received
3098 handle_set_key (struct Neighbour *n,
3099 const struct SetKeyMessage *m);
3103 * PEERINFO is giving us a HELLO for a peer. Add the public key to
3104 * the neighbour's struct and retry handling the set_key message. Or,
3105 * if we did not get a HELLO, just free the set key message.
3107 * @param cls pointer to the set key message
3108 * @param peer the peer for which this is the HELLO
3109 * @param hello HELLO message of that peer
3112 process_hello_retry_handle_set_key (void *cls,
3113 const struct GNUNET_PeerIdentity *peer,
3114 const struct GNUNET_HELLO_Message *hello)
3116 struct Neighbour *n = cls;
3117 struct SetKeyMessage *sm = n->skm;
3123 if (n->public_key != NULL)
3126 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3127 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
3129 GNUNET_i2s (&n->peer),
3132 handle_set_key (n, sm);
3136 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3137 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
3139 GNUNET_i2s (&n->peer));
3144 if (n->public_key != NULL)
3145 return; /* multiple HELLOs match!? */
3147 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3148 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3150 GNUNET_break_op (0);
3151 GNUNET_free (n->public_key);
3152 n->public_key = NULL;
3158 * We received a PING message. Validate and transmit
3161 * @param n sender of the PING
3162 * @param m the encrypted PING message itself
3165 handle_ping (struct Neighbour *n, const struct PingMessage *m)
3167 struct PingMessage t;
3168 struct PongMessage tx;
3169 struct PongMessage *tp;
3170 struct MessageEntry *me;
3171 struct GNUNET_CRYPTO_AesInitializationVector iv;
3174 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3175 "Core service receives `%s' request from `%4s'.\n",
3176 "PING", GNUNET_i2s (&n->peer));
3178 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3184 sizeof (struct PingMessage) -
3185 ((void *) &m->target - (void *) m)))
3188 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3189 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u, IV %u (salt %u)\n",
3191 GNUNET_i2s (&t.target),
3192 (unsigned int) t.challenge,
3193 (unsigned int) n->decrypt_key.crc32,
3194 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3197 GNUNET_STATISTICS_update (stats,
3198 gettext_noop ("# PING messages decrypted"),
3201 if (0 != memcmp (&t.target,
3202 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3204 GNUNET_break_op (0);
3207 me = GNUNET_malloc (sizeof (struct MessageEntry) +
3208 sizeof (struct PongMessage));
3209 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3213 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
3214 me->priority = PONG_PRIORITY;
3215 me->size = sizeof (struct PongMessage);
3216 tx.inbound_bw_limit = n->bw_in;
3217 tx.challenge = t.challenge;
3218 tx.target = t.target;
3219 tp = (struct PongMessage *) &me[1];
3220 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
3221 tp->header.size = htons (sizeof (struct PongMessage));
3222 tp->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3223 derive_pong_iv (&iv, &n->encrypt_key, tp->iv_seed, t.challenge, &n->peer);
3228 sizeof (struct PongMessage) -
3229 ((void *) &tp->challenge - (void *) tp));
3230 GNUNET_STATISTICS_update (stats,
3231 gettext_noop ("# PONG messages created"),
3235 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3236 "Encrypting `%s' with challenge %u using key %u, IV %u (salt %u)\n",
3238 (unsigned int) t.challenge,
3239 (unsigned int) n->encrypt_key.crc32,
3240 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3243 /* trigger queue processing */
3244 process_encrypted_neighbour_queue (n);
3249 * We received a PONG message. Validate and update our status.
3251 * @param n sender of the PONG
3252 * @param m the encrypted PONG message itself
3255 handle_pong (struct Neighbour *n,
3256 const struct PongMessage *m)
3258 struct PongMessage t;
3259 struct ConnectNotifyMessage cnm;
3260 struct GNUNET_CRYPTO_AesInitializationVector iv;
3263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3264 "Core service receives `%s' response from `%4s'.\n",
3265 "PONG", GNUNET_i2s (&n->peer));
3267 /* mark as garbage, just to be sure */
3268 memset (&t, 255, sizeof (t));
3269 derive_pong_iv (&iv, &n->decrypt_key, m->iv_seed, n->ping_challenge,
3276 sizeof (struct PongMessage) -
3277 ((void *) &m->challenge - (void *) m)))
3279 GNUNET_break_op (0);
3282 GNUNET_STATISTICS_update (stats,
3283 gettext_noop ("# PONG messages decrypted"),
3287 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3288 "Decrypted `%s' from `%4s' with challenge %u using key %u, IV %u (salt %u)\n",
3290 GNUNET_i2s (&t.target),
3291 (unsigned int) t.challenge,
3292 (unsigned int) n->decrypt_key.crc32,
3293 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3296 if ((0 != memcmp (&t.target,
3298 sizeof (struct GNUNET_PeerIdentity))) ||
3299 (n->ping_challenge != t.challenge))
3301 /* PONG malformed */
3303 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3304 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
3306 GNUNET_i2s (&n->peer),
3307 (unsigned int) n->ping_challenge);
3308 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3309 "Received malformed `%s' received from `%4s' with challenge %u\n",
3310 "PONG", GNUNET_i2s (&t.target),
3311 (unsigned int) t.challenge);
3313 GNUNET_break_op (0);
3318 case PEER_STATE_DOWN:
3319 GNUNET_break (0); /* should be impossible */
3321 case PEER_STATE_KEY_SENT:
3322 GNUNET_break (0); /* should be impossible, how did we decrypt? */
3324 case PEER_STATE_KEY_RECEIVED:
3325 GNUNET_STATISTICS_update (stats,
3326 gettext_noop ("# Session keys confirmed via PONG"),
3329 n->status = PEER_STATE_KEY_CONFIRMED;
3330 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
3332 n->bw_out_external_limit = t.inbound_bw_limit;
3333 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3334 n->bw_out_internal_limit);
3335 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3337 GNUNET_TRANSPORT_set_quota (transport,
3341 GNUNET_TIME_UNIT_FOREVER_REL,
3345 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3346 "Confirmed key via `%s' message for peer `%4s'\n",
3347 "PONG", GNUNET_i2s (&n->peer));
3349 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3351 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3352 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3354 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3355 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3357 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
3358 process_encrypted_neighbour_queue (n);
3360 case PEER_STATE_KEY_CONFIRMED:
3361 n->last_activity = GNUNET_TIME_absolute_get ();
3362 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3363 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3365 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3368 handle_peer_status_change (n);
3378 * We received a SET_KEY message. Validate and update
3379 * our key material and status.
3381 * @param n the neighbour from which we received message m
3382 * @param m the set key message we received
3385 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
3387 struct SetKeyMessage *m_cpy;
3388 struct GNUNET_TIME_Absolute t;
3389 struct GNUNET_CRYPTO_AesSessionKey k;
3390 struct PingMessage *ping;
3391 struct PongMessage *pong;
3392 enum PeerStateMachine sender_status;
3395 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3396 "Core service receives `%s' request from `%4s'.\n",
3397 "SET_KEY", GNUNET_i2s (&n->peer));
3399 if (n->public_key == NULL)
3401 if (n->pitr != NULL)
3404 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3405 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3411 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3412 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3414 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3415 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3416 /* lookup n's public key, then try again */
3417 GNUNET_assert (n->skm == NULL);
3419 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3421 GNUNET_TIME_UNIT_MINUTES,
3422 &process_hello_retry_handle_set_key, n);
3423 GNUNET_STATISTICS_update (stats,
3424 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3429 if (0 != memcmp (&m->target,
3431 sizeof (struct GNUNET_PeerIdentity)))
3433 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3434 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3436 GNUNET_i2s (&m->target));
3439 if ((ntohl (m->purpose.size) !=
3440 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3441 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3442 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3443 sizeof (struct GNUNET_PeerIdentity)) ||
3445 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3446 &m->purpose, &m->signature, n->public_key)))
3448 /* invalid signature */
3449 GNUNET_break_op (0);
3452 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3453 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3454 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3455 (t.abs_value < n->decrypt_key_created.abs_value))
3457 /* this could rarely happen due to massive re-ordering of
3458 messages on the network level, but is most likely either
3459 a bug or some adversary messing with us. Report. */
3460 GNUNET_break_op (0);
3464 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3465 "Decrypting key material.\n");
3467 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3470 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3471 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3472 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3474 /* failed to decrypt !? */
3475 GNUNET_break_op (0);
3478 GNUNET_STATISTICS_update (stats,
3479 gettext_noop ("# SET_KEY messages decrypted"),
3483 if (n->decrypt_key_created.abs_value != t.abs_value)
3485 /* fresh key, reset sequence numbers */
3486 n->last_sequence_number_received = 0;
3487 n->last_packets_bitmap = 0;
3488 n->decrypt_key_created = t;
3490 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3493 case PEER_STATE_DOWN:
3494 n->status = PEER_STATE_KEY_RECEIVED;
3496 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3497 "Responding to `%s' with my own key.\n", "SET_KEY");
3501 case PEER_STATE_KEY_SENT:
3502 case PEER_STATE_KEY_RECEIVED:
3503 n->status = PEER_STATE_KEY_RECEIVED;
3504 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3505 (sender_status != PEER_STATE_KEY_CONFIRMED))
3508 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3509 "Responding to `%s' with my own key (other peer has status %u).\n",
3511 (unsigned int) sender_status);
3516 case PEER_STATE_KEY_CONFIRMED:
3517 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3518 (sender_status != PEER_STATE_KEY_CONFIRMED))
3521 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3522 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3524 (unsigned int) sender_status);
3533 if (n->pending_ping != NULL)
3535 ping = n->pending_ping;
3536 n->pending_ping = NULL;
3537 handle_ping (n, ping);
3540 if (n->pending_pong != NULL)
3542 pong = n->pending_pong;
3543 n->pending_pong = NULL;
3544 handle_pong (n, pong);
3551 * Send a P2P message to a client.
3553 * @param sender who sent us the message?
3554 * @param client who should we give the message to?
3555 * @param m contains the message to transmit
3556 * @param msize number of bytes in buf to transmit
3559 send_p2p_message_to_client (struct Neighbour *sender,
3560 struct Client *client,
3561 const void *m, size_t msize)
3563 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3564 struct NotifyTrafficMessage *ntm;
3567 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3568 "Core service passes message from `%4s' of type %u to client.\n",
3569 GNUNET_i2s(&sender->peer),
3570 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3572 ntm = (struct NotifyTrafficMessage *) buf;
3573 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3574 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3575 ntm->ats_count = htonl (0);
3576 ntm->ats.type = htonl (0);
3577 ntm->ats.value = htonl (0);
3578 ntm->peer = sender->peer;
3579 memcpy (&ntm[1], m, msize);
3580 send_to_client (client, &ntm->header, GNUNET_YES);
3585 * Deliver P2P message to interested clients.
3587 * @param cls always NULL
3588 * @param client who sent us the message (struct Neighbour)
3589 * @param m the message
3592 deliver_message (void *cls,
3594 const struct GNUNET_MessageHeader *m)
3596 struct Neighbour *sender = client;
3597 size_t msize = ntohs (m->size);
3599 struct Client *cpos;
3605 type = ntohs (m->type);
3607 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3608 "Received encapsulated message of type %u and size %u from `%4s'\n",
3609 (unsigned int) type,
3611 GNUNET_i2s (&sender->peer));
3613 GNUNET_snprintf (buf,
3615 gettext_noop ("# bytes of messages of type %u received"),
3616 (unsigned int) type);
3617 GNUNET_STATISTICS_set (stats,
3621 dropped = GNUNET_YES;
3623 while (cpos != NULL)
3625 deliver_full = GNUNET_NO;
3626 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3627 deliver_full = GNUNET_YES;
3630 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3632 if (type != cpos->types[tpos])
3634 deliver_full = GNUNET_YES;
3638 if (GNUNET_YES == deliver_full)
3640 send_p2p_message_to_client (sender, cpos, m, msize);
3641 dropped = GNUNET_NO;
3643 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3645 send_p2p_message_to_client (sender, cpos, m,
3646 sizeof (struct GNUNET_MessageHeader));
3650 if (dropped == GNUNET_YES)
3653 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3654 "Message of type %u from `%4s' not delivered to any client.\n",
3655 (unsigned int) type,
3656 GNUNET_i2s (&sender->peer));
3658 GNUNET_STATISTICS_update (stats,
3659 gettext_noop ("# messages not delivered to any client"),
3666 * We received an encrypted message. Decrypt, validate and
3667 * pass on to the appropriate clients.
3670 handle_encrypted_message (struct Neighbour *n,
3671 const struct EncryptedMessage *m)
3673 size_t size = ntohs (m->header.size);
3675 struct EncryptedMessage *pt; /* plaintext */
3678 struct GNUNET_TIME_Absolute t;
3679 struct GNUNET_CRYPTO_AesInitializationVector iv;
3680 struct GNUNET_CRYPTO_AuthKey auth_key;
3683 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3684 "Core service receives `%s' request from `%4s'.\n",
3685 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3688 derive_auth_key (&auth_key,
3691 n->decrypt_key_created);
3692 GNUNET_CRYPTO_hmac (&auth_key,
3693 &m->sequence_number,
3694 size - ENCRYPTED_HEADER_SIZE, &ph);
3696 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3697 "Re-Authenticated %u bytes of ciphertext (`%u'): `%s'\n",
3698 (unsigned int) size - ENCRYPTED_HEADER_SIZE,
3699 GNUNET_CRYPTO_crc32_n (&m->sequence_number,
3700 size - ENCRYPTED_HEADER_SIZE),
3704 if (0 != memcmp (&ph,
3706 sizeof (GNUNET_HashCode)))
3708 /* checksum failed */
3709 GNUNET_break_op (0);
3712 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3717 &m->sequence_number,
3718 &buf[ENCRYPTED_HEADER_SIZE],
3719 size - ENCRYPTED_HEADER_SIZE))
3721 pt = (struct EncryptedMessage *) buf;
3723 /* validate sequence number */
3724 snum = ntohl (pt->sequence_number);
3725 if (n->last_sequence_number_received == snum)
3727 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3728 "Received duplicate message, ignoring.\n");
3729 /* duplicate, ignore */
3730 GNUNET_STATISTICS_set (stats,
3731 gettext_noop ("# bytes dropped (duplicates)"),
3736 if ((n->last_sequence_number_received > snum) &&
3737 (n->last_sequence_number_received - snum > 32))
3739 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3740 "Received ancient out of sequence message, ignoring.\n");
3741 /* ancient out of sequence, ignore */
3742 GNUNET_STATISTICS_set (stats,
3743 gettext_noop ("# bytes dropped (out of sequence)"),
3748 if (n->last_sequence_number_received > snum)
3750 unsigned int rotbit =
3751 1 << (n->last_sequence_number_received - snum - 1);
3752 if ((n->last_packets_bitmap & rotbit) != 0)
3754 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3755 "Received duplicate message, ignoring.\n");
3756 GNUNET_STATISTICS_set (stats,
3757 gettext_noop ("# bytes dropped (duplicates)"),
3760 /* duplicate, ignore */
3763 n->last_packets_bitmap |= rotbit;
3765 if (n->last_sequence_number_received < snum)
3767 int shift = (snum - n->last_sequence_number_received);
3768 if (shift >= 8 * sizeof(n->last_packets_bitmap))
3769 n->last_packets_bitmap = 0;
3771 n->last_packets_bitmap <<= shift;
3772 n->last_sequence_number_received = snum;
3775 /* check timestamp */
3776 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3777 if (GNUNET_TIME_absolute_get_duration (t).rel_value > MAX_MESSAGE_AGE.rel_value)
3779 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3781 ("Message received far too old (%llu ms). Content ignored.\n"),
3782 GNUNET_TIME_absolute_get_duration (t).rel_value);
3783 GNUNET_STATISTICS_set (stats,
3784 gettext_noop ("# bytes dropped (ancient message)"),
3790 /* process decrypted message(s) */
3791 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3793 #if DEBUG_CORE_SET_QUOTA
3794 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3795 "Received %u b/s as new inbound limit for peer `%4s'\n",
3796 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3797 GNUNET_i2s (&n->peer));
3799 n->bw_out_external_limit = pt->inbound_bw_limit;
3800 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3801 n->bw_out_internal_limit);
3802 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3804 GNUNET_TRANSPORT_set_quota (transport,
3808 GNUNET_TIME_UNIT_FOREVER_REL,
3811 n->last_activity = GNUNET_TIME_absolute_get ();
3812 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3813 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3815 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3818 GNUNET_STATISTICS_set (stats,
3819 gettext_noop ("# bytes of payload decrypted"),
3820 size - sizeof (struct EncryptedMessage),
3822 handle_peer_status_change (n);
3823 if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst,
3825 &buf[sizeof (struct EncryptedMessage)],
3826 size - sizeof (struct EncryptedMessage),
3827 GNUNET_YES, GNUNET_NO))
3828 GNUNET_break_op (0);
3833 * Function called by the transport for each received message.
3835 * @param cls closure
3836 * @param peer (claimed) identity of the other peer
3837 * @param message the message
3838 * @param latency estimated latency for communicating with the
3839 * given peer (round-trip)
3840 * @param distance in overlay hops, as given by transport plugin
3843 handle_transport_receive (void *cls,
3844 const struct GNUNET_PeerIdentity *peer,
3845 const struct GNUNET_MessageHeader *message,
3846 struct GNUNET_TIME_Relative latency,
3847 unsigned int distance)
3849 struct Neighbour *n;
3850 struct GNUNET_TIME_Absolute now;
3857 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3858 "Received message of type %u from `%4s', demultiplexing.\n",
3859 (unsigned int) ntohs (message->type),
3862 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3867 n = find_neighbour (peer);
3869 n = create_neighbour (peer);
3870 changed = GNUNET_YES; /* FIXME... */
3871 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3872 type = ntohs (message->type);
3873 size = ntohs (message->size);
3876 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3877 if (size != sizeof (struct SetKeyMessage))
3879 GNUNET_break_op (0);
3882 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3883 handle_set_key (n, (const struct SetKeyMessage *) message);
3885 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3886 if (size < sizeof (struct EncryptedMessage) +
3887 sizeof (struct GNUNET_MessageHeader))
3889 GNUNET_break_op (0);
3892 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3893 (n->status != PEER_STATE_KEY_CONFIRMED))
3895 GNUNET_break_op (0);
3898 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3900 case GNUNET_MESSAGE_TYPE_CORE_PING:
3901 if (size != sizeof (struct PingMessage))
3903 GNUNET_break_op (0);
3906 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3907 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3908 (n->status != PEER_STATE_KEY_CONFIRMED))
3911 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3912 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3913 "PING", GNUNET_i2s (&n->peer));
3915 GNUNET_free_non_null (n->pending_ping);
3916 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3917 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3920 handle_ping (n, (const struct PingMessage *) message);
3922 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3923 if (size != sizeof (struct PongMessage))
3925 GNUNET_break_op (0);
3928 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3929 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3930 (n->status != PEER_STATE_KEY_CONFIRMED) )
3933 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3934 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3935 "PONG", GNUNET_i2s (&n->peer));
3937 GNUNET_free_non_null (n->pending_pong);
3938 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3939 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3942 handle_pong (n, (const struct PongMessage *) message);
3945 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3946 _("Unsupported message of type %u received.\n"),
3947 (unsigned int) type);
3950 if (n->status == PEER_STATE_KEY_CONFIRMED)
3952 now = GNUNET_TIME_absolute_get ();
3953 n->last_activity = now;
3954 changed = GNUNET_YES;
3957 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3958 n->time_established = now;
3960 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3961 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3963 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3968 handle_peer_status_change (n);
3973 * Function that recalculates the bandwidth quota for the
3974 * given neighbour and transmits it to the transport service.
3976 * @param cls neighbour for the quota update
3980 neighbour_quota_update (void *cls,
3981 const struct GNUNET_SCHEDULER_TaskContext *tc)
3983 struct Neighbour *n = cls;
3984 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3987 unsigned long long distributable;
3988 uint64_t need_per_peer;
3989 uint64_t need_per_second;
3992 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3993 "Neighbour quota update calculation running for peer `%4s'\n",
3994 GNUNET_i2s (&n->peer));
3996 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3997 /* calculate relative preference among all neighbours;
3998 divides by a bit more to avoid division by zero AND to
3999 account for possibility of new neighbours joining any time
4000 AND to convert to double... */
4001 if (preference_sum == 0)
4003 pref_rel = 1.0 / (double) neighbour_count;
4007 pref_rel = n->current_preference / preference_sum;
4009 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
4010 GNUNET_TIME_UNIT_SECONDS);
4011 need_per_second = need_per_peer * neighbour_count;
4013 if (bandwidth_target_out_bps > need_per_second)
4014 distributable = bandwidth_target_out_bps - need_per_second;
4015 share = distributable * pref_rel;
4016 if (share + need_per_peer > UINT32_MAX)
4017 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4019 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4020 /* check if we want to disconnect for good due to inactivity */
4021 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) &&
4022 (GNUNET_TIME_absolute_get_duration (n->time_established).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) )
4025 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4026 "Forcing disconnect of `%4s' due to inactivity\n",
4027 GNUNET_i2s (&n->peer));
4029 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
4031 #if DEBUG_CORE_QUOTA
4032 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4033 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
4034 GNUNET_i2s (&n->peer),
4035 (unsigned int) ntohl (q_in.value__),
4036 bandwidth_target_out_bps,
4037 (unsigned int) ntohl (n->bw_in.value__),
4038 (unsigned int) ntohl (n->bw_out.value__),
4039 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
4041 if (n->bw_in.value__ != q_in.value__)
4044 if (GNUNET_YES == n->is_connected)
4045 GNUNET_TRANSPORT_set_quota (transport,
4049 GNUNET_TIME_UNIT_FOREVER_REL,
4051 handle_peer_status_change (n);
4053 schedule_quota_update (n);
4058 * Function called by transport to notify us that
4059 * a peer connected to us (on the network level).
4061 * @param cls closure
4062 * @param peer the peer that connected
4063 * @param latency current latency of the connection
4064 * @param distance in overlay hops, as given by transport plugin
4067 handle_transport_notify_connect (void *cls,
4068 const struct GNUNET_PeerIdentity *peer,
4069 struct GNUNET_TIME_Relative latency,
4070 unsigned int distance)
4072 struct Neighbour *n;
4074 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4079 n = find_neighbour (peer);
4082 if (GNUNET_YES == n->is_connected)
4084 /* duplicate connect notification!? */
4091 n = create_neighbour (peer);
4093 GNUNET_STATISTICS_update (stats,
4094 gettext_noop ("# peers connected (transport)"),
4097 n->is_connected = GNUNET_YES;
4098 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
4101 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
4105 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4106 "Received connection from `%4s'.\n",
4107 GNUNET_i2s (&n->peer));
4109 GNUNET_TRANSPORT_set_quota (transport,
4113 GNUNET_TIME_UNIT_FOREVER_REL,
4120 * Function called by transport telling us that a peer
4123 * @param cls closure
4124 * @param peer the peer that disconnected
4127 handle_transport_notify_disconnect (void *cls,
4128 const struct GNUNET_PeerIdentity *peer)
4130 struct DisconnectNotifyMessage cnm;
4131 struct Neighbour *n;
4132 struct ClientActiveRequest *car;
4133 struct GNUNET_TIME_Relative left;
4136 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4137 "Peer `%4s' disconnected from us; received notification from transport.\n", GNUNET_i2s (peer));
4140 n = find_neighbour (peer);
4146 GNUNET_break (n->is_connected);
4147 if (n->status == PEER_STATE_KEY_CONFIRMED)
4149 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
4150 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
4152 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
4154 n->is_connected = GNUNET_NO;
4155 while (NULL != (car = n->active_client_request_head))
4157 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
4158 n->active_client_request_tail,
4160 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
4161 &n->peer.hashPubKey,
4166 GNUNET_STATISTICS_update (stats,
4167 gettext_noop ("# peers connected (transport)"),
4170 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
4171 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
4172 left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4173 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
4174 n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (),
4176 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
4177 &consider_free_task,
4183 * Last task run during shutdown. Disconnects us from
4187 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4189 struct Neighbour *n;
4193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4194 "Core service shutting down.\n");
4196 GNUNET_assert (transport != NULL);
4197 GNUNET_TRANSPORT_disconnect (transport);
4199 while (NULL != (n = neighbours))
4201 neighbours = n->next;
4202 GNUNET_assert (neighbour_count > 0);
4206 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
4207 GNUNET_SERVER_notification_context_destroy (notifier);
4209 while (NULL != (c = clients))
4210 handle_client_disconnect (NULL, c->client_handle);
4211 if (my_private_key != NULL)
4212 GNUNET_CRYPTO_rsa_key_free (my_private_key);
4214 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4215 if (peerinfo != NULL)
4216 GNUNET_PEERINFO_disconnect (peerinfo);
4218 GNUNET_SERVER_mst_destroy (mst);
4223 * Initiate core service.
4225 * @param cls closure
4226 * @param server the initialized server
4227 * @param c configuration to use
4231 struct GNUNET_SERVER_Handle *server,
4232 const struct GNUNET_CONFIGURATION_Handle *c)
4234 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4235 {&handle_client_init, NULL,
4236 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
4237 {&handle_client_iterate_peers, NULL,
4238 GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
4239 sizeof (struct GNUNET_MessageHeader)},
4240 {&handle_client_request_info, NULL,
4241 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
4242 sizeof (struct RequestInfoMessage)},
4243 {&handle_client_send_request, NULL,
4244 GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST,
4245 sizeof (struct SendMessageRequest)},
4246 {&handle_client_send, NULL,
4247 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
4248 {&handle_client_request_connect, NULL,
4249 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
4250 sizeof (struct ConnectMessage)},
4256 /* parse configuration */
4259 GNUNET_CONFIGURATION_get_value_number (c,
4262 &bandwidth_target_in_bps)) ||
4264 GNUNET_CONFIGURATION_get_value_number (c,
4267 &bandwidth_target_out_bps)) ||
4269 GNUNET_CONFIGURATION_get_value_filename (c,
4271 "HOSTKEY", &keyfile)))
4273 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4275 ("Core service is lacking key configuration settings. Exiting.\n"));
4276 GNUNET_SCHEDULER_shutdown ();
4279 peerinfo = GNUNET_PEERINFO_connect (cfg);
4280 if (NULL == peerinfo)
4282 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4283 _("Could not access PEERINFO service. Exiting.\n"));
4284 GNUNET_SCHEDULER_shutdown ();
4285 GNUNET_free (keyfile);
4288 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4289 GNUNET_free (keyfile);
4290 if (my_private_key == NULL)
4292 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4293 _("Core service could not access hostkey. Exiting.\n"));
4294 GNUNET_PEERINFO_disconnect (peerinfo);
4295 GNUNET_SCHEDULER_shutdown ();
4298 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4299 GNUNET_CRYPTO_hash (&my_public_key,
4300 sizeof (my_public_key), &my_identity.hashPubKey);
4301 /* setup notification */
4302 notifier = GNUNET_SERVER_notification_context_create (server,
4304 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4305 /* setup transport connection */
4306 transport = GNUNET_TRANSPORT_connect (cfg,
4309 &handle_transport_receive,
4310 &handle_transport_notify_connect,
4311 &handle_transport_notify_disconnect);
4312 GNUNET_assert (NULL != transport);
4313 stats = GNUNET_STATISTICS_create ("core", cfg);
4315 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded CORE_SEND requests"), 0, GNUNET_NO);
4316 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 0, GNUNET_NO);
4318 mst = GNUNET_SERVER_mst_create (&deliver_message,
4320 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4321 &cleaning_task, NULL);
4322 /* process client requests */
4323 GNUNET_SERVER_add_handlers (server, handlers);
4324 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4325 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
4331 * The main function for the transport service.
4333 * @param argc number of arguments from the command line
4334 * @param argv command line arguments
4335 * @return 0 ok, 1 on error
4338 main (int argc, char *const *argv)
4340 return (GNUNET_OK ==
4341 GNUNET_SERVICE_run (argc,
4344 GNUNET_SERVICE_OPTION_NONE,
4345 &run, NULL)) ? 0 : 1;
4348 /* end of gnunet-service-core.c */