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) )
1083 /* neighbour must have disconnected since request was issued,
1084 ignore (client will realize it once it processes the
1085 disconnect notification) */
1086 GNUNET_STATISTICS_update (stats,
1087 gettext_noop ("# send requests dropped (disconnected)"),
1090 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1094 while ( (c != NULL) &&
1095 (c->client_handle != client) )
1099 /* client did not send INIT first! */
1101 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1104 if (c->requests == NULL)
1105 c->requests = GNUNET_CONTAINER_multihashmap_create (16);
1106 car = GNUNET_CONTAINER_multihashmap_get (c->requests,
1107 &req->peer.hashPubKey);
1110 /* create new entry */
1111 car = GNUNET_malloc (sizeof (struct ClientActiveRequest));
1112 GNUNET_assert (GNUNET_OK ==
1113 GNUNET_CONTAINER_multihashmap_put (c->requests,
1114 &req->peer.hashPubKey,
1116 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1117 GNUNET_CONTAINER_DLL_insert (n->active_client_request_head,
1118 n->active_client_request_tail,
1122 car->deadline = GNUNET_TIME_absolute_ntoh (req->deadline);
1123 car->priority = ntohl (req->priority);
1124 car->queue_size = ntohl (req->queue_size);
1125 car->msize = ntohs (req->size);
1126 car->smr_id = req->smr_id;
1127 schedule_peer_messages (n);
1128 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1133 * Handle CORE_INIT request.
1136 handle_client_init (void *cls,
1137 struct GNUNET_SERVER_Client *client,
1138 const struct GNUNET_MessageHeader *message)
1140 const struct InitMessage *im;
1141 struct InitReplyMessage irm;
1144 const uint16_t *types;
1146 struct Neighbour *n;
1147 struct ConnectNotifyMessage cnm;
1150 #if DEBUG_CORE_CLIENT
1151 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1152 "Client connecting to core service with `%s' message\n",
1155 /* check that we don't have an entry already */
1159 if (client == c->client_handle)
1162 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1167 msize = ntohs (message->size);
1168 if (msize < sizeof (struct InitMessage))
1171 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1174 GNUNET_SERVER_notification_context_add (notifier, client);
1175 im = (const struct InitMessage *) message;
1176 types = (const uint16_t *) &im[1];
1177 msize -= sizeof (struct InitMessage);
1178 c = GNUNET_malloc (sizeof (struct Client) + msize);
1179 c->client_handle = client;
1182 c->tcnt = msize / sizeof (uint16_t);
1183 c->types = (const uint16_t *) &c[1];
1184 wtypes = (uint16_t *) &c[1];
1185 for (i=0;i<c->tcnt;i++)
1186 wtypes[i] = ntohs (types[i]);
1187 c->options = ntohl (im->options);
1188 #if DEBUG_CORE_CLIENT
1189 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1190 "Client %p is interested in %u message types\n",
1192 (unsigned int) c->tcnt);
1194 /* send init reply message */
1195 irm.header.size = htons (sizeof (struct InitReplyMessage));
1196 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
1197 irm.reserved = htonl (0);
1198 memcpy (&irm.publicKey,
1200 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1201 #if DEBUG_CORE_CLIENT
1202 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1203 "Sending `%s' message to client.\n", "INIT_REPLY");
1205 send_to_client (c, &irm.header, GNUNET_NO);
1206 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
1208 /* notify new client about existing neighbours */
1209 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
1210 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1211 cnm.ats_count = htonl (0);
1212 cnm.ats.type = htonl (0);
1213 cnm.ats.value = htonl (0);
1217 if (n->status == PEER_STATE_KEY_CONFIRMED)
1219 #if DEBUG_CORE_CLIENT
1220 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1221 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
1224 send_to_client (c, &cnm.header, GNUNET_NO);
1229 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1234 * Free client request records.
1237 * @param key identity of peer for which this is an active request
1238 * @param value the 'struct ClientActiveRequest' to free
1239 * @return GNUNET_YES (continue iteration)
1242 destroy_active_client_request (void *cls,
1243 const GNUNET_HashCode *key,
1246 struct ClientActiveRequest *car = cls;
1247 struct Neighbour *n;
1248 struct GNUNET_PeerIdentity peer;
1250 peer.hashPubKey = *key;
1251 n = find_neighbour (&peer);
1252 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1253 n->active_client_request_tail,
1261 * A client disconnected, clean up.
1263 * @param cls closure
1264 * @param client identification of the client
1267 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1270 struct Client *prev;
1274 #if DEBUG_CORE_CLIENT
1275 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1276 "Client %p has disconnected from core service.\n",
1283 if (client == pos->client_handle)
1290 /* client never sent INIT */
1294 clients = pos->next;
1296 prev->next = pos->next;
1297 if (pos->requests != NULL)
1299 GNUNET_CONTAINER_multihashmap_iterate (pos->requests,
1300 &destroy_active_client_request,
1302 GNUNET_CONTAINER_multihashmap_destroy (pos->requests);
1309 * Handle REQUEST_INFO request.
1312 handle_client_request_info (void *cls,
1313 struct GNUNET_SERVER_Client *client,
1314 const struct GNUNET_MessageHeader *message)
1316 const struct RequestInfoMessage *rcm;
1317 struct Neighbour *n;
1318 struct ConfigurationInfoMessage cim;
1319 int32_t want_reserv;
1321 unsigned long long old_preference;
1322 struct GNUNET_SERVER_TransmitContext *tc;
1324 #if DEBUG_CORE_CLIENT
1325 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1326 "Core service receives `%s' request.\n", "REQUEST_INFO");
1328 rcm = (const struct RequestInfoMessage *) message;
1329 n = find_neighbour (&rcm->peer);
1330 memset (&cim, 0, sizeof (cim));
1333 want_reserv = ntohl (rcm->reserve_inbound);
1334 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1336 n->bw_out_internal_limit = rcm->limit_outbound;
1337 if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1338 n->bw_out_external_limit).value__)
1340 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1341 n->bw_out_external_limit);
1342 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1344 GNUNET_TRANSPORT_set_quota (transport,
1348 GNUNET_TIME_UNIT_FOREVER_REL,
1350 handle_peer_status_change (n);
1353 if (want_reserv < 0)
1355 got_reserv = want_reserv;
1357 else if (want_reserv > 0)
1359 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1360 want_reserv).rel_value == 0)
1361 got_reserv = want_reserv;
1363 got_reserv = 0; /* all or nothing */
1367 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1369 old_preference = n->current_preference;
1370 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1371 if (old_preference > n->current_preference)
1373 /* overflow; cap at maximum value */
1374 n->current_preference = ULLONG_MAX;
1376 update_preference_sum (n->current_preference - old_preference);
1377 #if DEBUG_CORE_QUOTA
1378 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1379 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1381 GNUNET_i2s (&rcm->peer),
1384 cim.reserved_amount = htonl (got_reserv);
1385 cim.rim_id = rcm->rim_id;
1386 cim.bw_out = n->bw_out;
1387 cim.preference = n->current_preference;
1389 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1390 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1391 cim.peer = rcm->peer;
1393 #if DEBUG_CORE_CLIENT
1394 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1395 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1397 tc = GNUNET_SERVER_transmit_context_create (client);
1398 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1399 GNUNET_SERVER_transmit_context_run (tc,
1400 GNUNET_TIME_UNIT_FOREVER_REL);
1405 * Free the given entry for the neighbour (it has
1406 * already been removed from the list at this point).
1408 * @param n neighbour to free
1411 free_neighbour (struct Neighbour *n)
1413 struct MessageEntry *m;
1414 struct ClientActiveRequest *car;
1417 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1418 "Destroying neighbour entry for peer `%4s'\n",
1419 GNUNET_i2s (&n->peer));
1421 if (n->pitr != NULL)
1423 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1428 GNUNET_free (n->skm);
1431 while (NULL != (m = n->messages))
1433 n->messages = m->next;
1436 while (NULL != (m = n->encrypted_head))
1438 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1443 while (NULL != (car = n->active_client_request_head))
1445 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1446 n->active_client_request_tail,
1448 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
1449 &n->peer.hashPubKey,
1455 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1458 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1459 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
1460 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1461 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
1462 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1463 GNUNET_SCHEDULER_cancel (n->quota_update_task);
1464 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1465 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1466 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1467 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
1468 if (n->status == PEER_STATE_KEY_CONFIRMED)
1469 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1470 GNUNET_free_non_null (n->public_key);
1471 GNUNET_free_non_null (n->pending_ping);
1472 GNUNET_free_non_null (n->pending_pong);
1478 * Check if we have encrypted messages for the specified neighbour
1479 * pending, and if so, check with the transport about sending them
1482 * @param n neighbour to check.
1484 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1488 * Encrypt size bytes from in and write the result to out. Use the
1489 * key for outbound traffic of the given neighbour.
1491 * @param n neighbour we are sending to
1492 * @param iv initialization vector to use
1493 * @param in ciphertext
1494 * @param out plaintext
1495 * @param size size of in/out
1496 * @return GNUNET_OK on success
1499 do_encrypt (struct Neighbour *n,
1500 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1501 const void *in, void *out, size_t size)
1503 if (size != (uint16_t) size)
1508 GNUNET_assert (size ==
1509 GNUNET_CRYPTO_aes_encrypt (in,
1513 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1515 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1516 "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
1517 (unsigned int) size,
1518 GNUNET_i2s (&n->peer),
1519 (unsigned int) n->encrypt_key.crc32,
1520 GNUNET_CRYPTO_crc32_n (iv, sizeof(iv)));
1527 * Consider freeing the given neighbour since we may not need
1528 * to keep it around anymore.
1530 * @param n neighbour to consider discarding
1533 consider_free_neighbour (struct Neighbour *n);
1537 * Task triggered when a neighbour entry is about to time out
1538 * (and we should prevent this by sending a PING).
1540 * @param cls the 'struct Neighbour'
1541 * @param tc scheduler context (not used)
1544 send_keep_alive (void *cls,
1545 const struct GNUNET_SCHEDULER_TaskContext *tc)
1547 struct Neighbour *n = cls;
1548 struct GNUNET_TIME_Relative retry;
1549 struct GNUNET_TIME_Relative left;
1550 struct MessageEntry *me;
1551 struct PingMessage pp;
1552 struct PingMessage *pm;
1553 struct GNUNET_CRYPTO_AesInitializationVector iv;
1555 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1557 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1558 sizeof (struct PingMessage));
1559 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1560 me->priority = PING_PRIORITY;
1561 me->size = sizeof (struct PingMessage);
1562 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1566 pm = (struct PingMessage *) &me[1];
1567 pm->header.size = htons (sizeof (struct PingMessage));
1568 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1569 pm->iv_seed = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1571 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
1572 pp.challenge = n->ping_challenge;
1573 pp.target = n->peer;
1575 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1576 "Encrypting `%s' message with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
1578 (unsigned int) n->ping_challenge,
1579 GNUNET_i2s (&n->peer),
1580 (unsigned int) n->encrypt_key.crc32,
1581 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
1588 sizeof (struct PingMessage) -
1589 ((void *) &pm->target - (void *) pm));
1590 process_encrypted_neighbour_queue (n);
1591 /* reschedule PING job */
1592 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1593 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1594 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1595 MIN_PING_FREQUENCY);
1597 = GNUNET_SCHEDULER_add_delayed (retry,
1605 * Task triggered when a neighbour entry might have gotten stale.
1607 * @param cls the 'struct Neighbour'
1608 * @param tc scheduler context (not used)
1611 consider_free_task (void *cls,
1612 const struct GNUNET_SCHEDULER_TaskContext *tc)
1614 struct Neighbour *n = cls;
1616 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1617 consider_free_neighbour (n);
1622 * Consider freeing the given neighbour since we may not need
1623 * to keep it around anymore.
1625 * @param n neighbour to consider discarding
1628 consider_free_neighbour (struct Neighbour *n)
1630 struct Neighbour *pos;
1631 struct Neighbour *prev;
1632 struct GNUNET_TIME_Relative left;
1634 if ( (n->th != NULL) ||
1635 (n->pitr != NULL) ||
1636 (GNUNET_YES == n->is_connected) )
1637 return; /* no chance */
1639 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1640 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1641 if (left.rel_value > 0)
1643 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1644 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1645 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (left,
1646 &consider_free_task,
1650 /* actually free the neighbour... */
1659 neighbours = n->next;
1661 prev->next = n->next;
1662 GNUNET_assert (neighbour_count > 0);
1664 GNUNET_STATISTICS_set (stats,
1665 gettext_noop ("# neighbour entries allocated"),
1673 * Function called when the transport service is ready to
1674 * receive an encrypted message for the respective peer
1676 * @param cls neighbour to use message from
1677 * @param size number of bytes we can transmit
1678 * @param buf where to copy the message
1679 * @return number of bytes transmitted
1682 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1684 struct Neighbour *n = cls;
1685 struct MessageEntry *m;
1690 m = n->encrypted_head;
1694 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1695 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1696 GNUNET_i2s (&n->peer));
1700 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1707 GNUNET_assert (size >= m->size);
1708 memcpy (cbuf, &m[1], m->size);
1710 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1713 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1714 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1715 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1717 GNUNET_i2s (&n->peer));
1719 process_encrypted_neighbour_queue (n);
1724 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1725 "Transmission of message of type %u and size %u failed\n",
1726 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1727 (unsigned int) m->size);
1731 consider_free_neighbour (n);
1737 * Check if we have plaintext messages for the specified neighbour
1738 * pending, and if so, consider batching and encrypting them (and
1739 * then trigger processing of the encrypted queue if needed).
1741 * @param n neighbour to check.
1743 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1747 * Check if we have encrypted messages for the specified neighbour
1748 * pending, and if so, check with the transport about sending them
1751 * @param n neighbour to check.
1754 process_encrypted_neighbour_queue (struct Neighbour *n)
1756 struct MessageEntry *m;
1759 return; /* request already pending */
1760 m = n->encrypted_head;
1763 /* encrypted queue empty, try plaintext instead */
1764 process_plaintext_neighbour_queue (n);
1768 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1769 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1770 (unsigned int) m->size,
1771 GNUNET_i2s (&n->peer),
1772 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).rel_value);
1775 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1778 GNUNET_TIME_absolute_get_remaining
1780 ¬ify_encrypted_transmit_ready,
1784 /* message request too large or duplicate request */
1786 /* discard encrypted message */
1787 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1791 process_encrypted_neighbour_queue (n);
1797 * Decrypt size bytes from in and write the result to out. Use the
1798 * key for inbound traffic of the given neighbour. This function does
1799 * NOT do any integrity-checks on the result.
1801 * @param n neighbour we are receiving from
1802 * @param iv initialization vector to use
1803 * @param in ciphertext
1804 * @param out plaintext
1805 * @param size size of in/out
1806 * @return GNUNET_OK on success
1809 do_decrypt (struct Neighbour *n,
1810 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1811 const void *in, void *out, size_t size)
1813 if (size != (uint16_t) size)
1818 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1819 (n->status != PEER_STATE_KEY_CONFIRMED))
1821 GNUNET_break_op (0);
1822 return GNUNET_SYSERR;
1825 GNUNET_CRYPTO_aes_decrypt (in,
1832 return GNUNET_SYSERR;
1834 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1836 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1837 "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
1838 (unsigned int) size,
1839 GNUNET_i2s (&n->peer),
1840 (unsigned int) n->decrypt_key.crc32,
1841 GNUNET_CRYPTO_crc32_n (iv, sizeof(*iv)));
1848 * Select messages for transmission. This heuristic uses a combination
1849 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1850 * and priority-based discard (in case no feasible schedule exist) and
1851 * speculative optimization (defer any kind of transmission until
1852 * we either create a batch of significant size, 25% of max, or until
1853 * we are close to a deadline). Furthermore, when scheduling the
1854 * heuristic also packs as many messages into the batch as possible,
1855 * starting with those with the earliest deadline. Yes, this is fun.
1857 * @param n neighbour to select messages from
1858 * @param size number of bytes to select for transmission
1859 * @param retry_time set to the time when we should try again
1860 * (only valid if this function returns zero)
1861 * @return number of bytes selected, or 0 if we decided to
1862 * defer scheduling overall; in that case, retry_time is set.
1865 select_messages (struct Neighbour *n,
1866 size_t size, struct GNUNET_TIME_Relative *retry_time)
1868 struct MessageEntry *pos;
1869 struct MessageEntry *min;
1870 struct MessageEntry *last;
1871 unsigned int min_prio;
1872 struct GNUNET_TIME_Absolute t;
1873 struct GNUNET_TIME_Absolute now;
1874 struct GNUNET_TIME_Relative delta;
1876 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1879 unsigned int queue_size;
1880 int discard_low_prio;
1882 GNUNET_assert (NULL != n->messages);
1883 now = GNUNET_TIME_absolute_get ();
1884 /* last entry in linked list of messages processed */
1886 /* should we remove the entry with the lowest
1887 priority from consideration for scheduling at the
1898 discard_low_prio = GNUNET_YES;
1899 while (GNUNET_YES == discard_low_prio)
1902 min_prio = UINT_MAX;
1903 discard_low_prio = GNUNET_NO;
1904 /* calculate number of bytes available for transmission at time "t" */
1905 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1907 /* how many bytes have we (hypothetically) scheduled so far */
1909 /* maximum time we can wait before transmitting anything
1910 and still make all of our deadlines */
1911 slack = GNUNET_TIME_UNIT_FOREVER_REL;
1913 /* note that we use "*2" here because we want to look
1914 a bit further into the future; much more makes no
1915 sense since new message might be scheduled in the
1917 while ((pos != NULL) && (off < size * 2))
1919 if (pos->do_transmit == GNUNET_YES)
1921 /* already removed from consideration */
1925 if (discard_low_prio == GNUNET_NO)
1927 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1928 if (delta.rel_value > 0)
1930 // FIXME: HUH? Check!
1932 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1935 if (avail < pos->size)
1937 // FIXME: HUH? Check!
1938 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1943 /* update slack, considering both its absolute deadline
1944 and relative deadlines caused by other messages
1945 with their respective load */
1946 slack = GNUNET_TIME_relative_min (slack,
1947 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1949 if (pos->deadline.abs_value <= now.abs_value)
1952 slack = GNUNET_TIME_UNIT_ZERO;
1954 else if (GNUNET_YES == pos->got_slack)
1956 /* should be soon now! */
1957 slack = GNUNET_TIME_relative_min (slack,
1958 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1963 GNUNET_TIME_relative_min (slack,
1964 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1965 pos->got_slack = GNUNET_YES;
1966 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1967 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
1972 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1973 if (pos->priority <= min_prio)
1975 /* update min for discard */
1976 min_prio = pos->priority;
1981 if (discard_low_prio)
1983 GNUNET_assert (min != NULL);
1984 /* remove lowest-priority entry from consideration */
1985 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1989 /* guard against sending "tiny" messages with large headers without
1991 if ( (slack.rel_value > GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value) &&
1993 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1995 /* less than 25% of message would be filled with deadlines still
1996 being met if we delay by one second or more; so just wait for
1997 more data; but do not wait longer than 1s (since we don't want
1998 to delay messages for a really long time either). */
1999 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
2000 /* reset do_transmit values for next time */
2003 pos->do_transmit = GNUNET_NO;
2006 GNUNET_STATISTICS_update (stats,
2007 gettext_noop ("# transmissions delayed due to corking"),
2010 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2011 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
2012 (unsigned long long) retry_time->rel_value,
2014 (unsigned int) size);
2018 /* select marked messages (up to size) for transmission */
2023 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
2025 pos->do_transmit = GNUNET_YES; /* mark for transmission */
2029 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2030 "Selecting message of size %u for transmission\n",
2031 (unsigned int) pos->size);
2037 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2038 "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
2039 (unsigned int) pos->size,
2042 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
2047 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2048 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
2049 (unsigned long long) off, (unsigned long long) tsize,
2050 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
2051 GNUNET_i2s (&n->peer));
2058 * Batch multiple messages into a larger buffer.
2060 * @param n neighbour to take messages from
2061 * @param buf target buffer
2062 * @param size size of buf
2063 * @param deadline set to transmission deadline for the result
2064 * @param retry_time set to the time when we should try again
2065 * (only valid if this function returns zero)
2066 * @param priority set to the priority of the batch
2067 * @return number of bytes written to buf (can be zero)
2070 batch_message (struct Neighbour *n,
2073 struct GNUNET_TIME_Absolute *deadline,
2074 struct GNUNET_TIME_Relative *retry_time,
2075 unsigned int *priority)
2077 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
2078 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
2079 struct MessageEntry *pos;
2080 struct MessageEntry *prev;
2081 struct MessageEntry *next;
2086 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2087 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
2088 if (0 == select_messages (n, size, retry_time))
2091 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2092 "No messages selected, will try again in %llu ms\n",
2093 retry_time->rel_value);
2097 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
2098 ntm->ats_count = htonl (0);
2099 ntm->ats.type = htonl (0);
2100 ntm->ats.value = htonl (0);
2101 ntm->peer = n->peer;
2104 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
2107 if (GNUNET_YES == pos->do_transmit)
2109 GNUNET_assert (pos->size <= size);
2110 /* do notifications */
2111 /* FIXME: track if we have *any* client that wants
2112 full notifications and only do this if that is
2114 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
2116 memcpy (&ntm[1], &pos[1], pos->size);
2117 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
2118 sizeof (struct GNUNET_MessageHeader));
2119 send_to_all_clients (&ntm->header,
2121 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
2125 /* message too large for 'full' notifications, we do at
2126 least the 'hdr' type */
2129 sizeof (struct GNUNET_MessageHeader));
2131 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
2133 send_to_all_clients (&ntm->header,
2135 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
2137 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2138 "Encrypting %u bytes with message of type %u and size %u\n",
2140 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
2141 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
2143 /* copy for encrypted transmission */
2144 memcpy (&buf[ret], &pos[1], pos->size);
2147 *priority += pos->priority;
2149 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2150 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
2151 (unsigned int) pos->size,
2152 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).rel_value);
2154 deadline->abs_value = GNUNET_MIN (deadline->abs_value, pos->deadline.abs_value);
2168 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2169 "Deadline for message batch is %llu ms\n",
2170 GNUNET_TIME_absolute_get_remaining (*deadline).rel_value);
2177 * Remove messages with deadlines that have long expired from
2180 * @param n neighbour to inspect
2183 discard_expired_messages (struct Neighbour *n)
2185 struct MessageEntry *prev;
2186 struct MessageEntry *next;
2187 struct MessageEntry *pos;
2188 struct GNUNET_TIME_Absolute now;
2189 struct GNUNET_TIME_Relative delta;
2193 now = GNUNET_TIME_absolute_get ();
2199 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
2200 if (delta.rel_value > PAST_EXPIRATION_DISCARD_TIME.rel_value)
2203 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2204 "Message is %llu ms past due, discarding.\n",
2211 GNUNET_STATISTICS_update (stats,
2212 gettext_noop ("# messages discarded (expired prior to transmission)"),
2222 if (GNUNET_YES == disc)
2223 schedule_peer_messages (n);
2228 * Signature of the main function of a task.
2230 * @param cls closure
2231 * @param tc context information (why was this task triggered now)
2234 retry_plaintext_processing (void *cls,
2235 const struct GNUNET_SCHEDULER_TaskContext *tc)
2237 struct Neighbour *n = cls;
2239 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2240 process_plaintext_neighbour_queue (n);
2245 * Send our key (and encrypted PING) to the other peer.
2247 * @param n the other peer
2249 static void send_key (struct Neighbour *n);
2252 * Task that will retry "send_key" if our previous attempt failed
2256 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2258 struct Neighbour *n = cls;
2261 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2262 "Retrying key transmission to `%4s'\n",
2263 GNUNET_i2s (&n->peer));
2265 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2266 n->set_key_retry_frequency =
2267 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2273 * Check if we have plaintext messages for the specified neighbour
2274 * pending, and if so, consider batching and encrypting them (and
2275 * then trigger processing of the encrypted queue if needed).
2277 * @param n neighbour to check.
2280 process_plaintext_neighbour_queue (struct Neighbour *n)
2282 char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)]; /* plaintext */
2284 struct EncryptedMessage *em; /* encrypted message */
2285 struct EncryptedMessage *ph; /* plaintext header */
2286 struct MessageEntry *me;
2287 unsigned int priority;
2288 struct GNUNET_TIME_Absolute deadline;
2289 struct GNUNET_TIME_Relative retry_time;
2290 struct GNUNET_CRYPTO_AesInitializationVector iv;
2291 struct GNUNET_CRYPTO_AuthKey auth_key;
2293 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2295 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
2296 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2300 case PEER_STATE_DOWN:
2303 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2304 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2305 GNUNET_i2s(&n->peer));
2308 case PEER_STATE_KEY_SENT:
2309 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2310 n->retry_set_key_task
2311 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2312 &set_key_retry_task, n);
2314 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2315 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2316 GNUNET_i2s(&n->peer));
2319 case PEER_STATE_KEY_RECEIVED:
2320 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2321 n->retry_set_key_task
2322 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2323 &set_key_retry_task, n);
2325 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2326 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2327 GNUNET_i2s(&n->peer));
2330 case PEER_STATE_KEY_CONFIRMED:
2331 /* ready to continue */
2334 discard_expired_messages (n);
2335 if (n->messages == NULL)
2338 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2339 "Plaintext message queue for `%4s' is empty.\n",
2340 GNUNET_i2s(&n->peer));
2342 return; /* no pending messages */
2344 if (n->encrypted_head != NULL)
2347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2348 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2349 GNUNET_i2s(&n->peer));
2351 return; /* wait for messages already encrypted to be
2354 ph = (struct EncryptedMessage *) pbuf;
2355 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2357 used = sizeof (struct EncryptedMessage);
2358 used += batch_message (n,
2360 GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2361 &deadline, &retry_time, &priority);
2362 if (used == sizeof (struct EncryptedMessage))
2365 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2366 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2367 GNUNET_i2s(&n->peer));
2369 /* no messages selected for sending, try again later... */
2370 n->retry_plaintext_task =
2371 GNUNET_SCHEDULER_add_delayed (retry_time,
2372 &retry_plaintext_processing, n);
2375 #if DEBUG_CORE_QUOTA
2376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2377 "Sending %u b/s as new limit to peer `%4s'\n",
2378 (unsigned int) ntohl (n->bw_in.value__),
2379 GNUNET_i2s (&n->peer));
2381 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
2382 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2383 ph->inbound_bw_limit = n->bw_in;
2384 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2386 /* setup encryption message header */
2387 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2388 me->deadline = deadline;
2389 me->priority = priority;
2391 em = (struct EncryptedMessage *) &me[1];
2392 em->header.size = htons (used);
2393 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2394 em->iv_seed = ph->iv_seed;
2395 derive_iv (&iv, &n->encrypt_key, ph->iv_seed, &n->peer);
2398 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2399 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2400 (unsigned int) used - ENCRYPTED_HEADER_SIZE,
2401 GNUNET_i2s(&n->peer),
2402 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).rel_value);
2404 GNUNET_assert (GNUNET_OK ==
2407 &ph->sequence_number,
2408 &em->sequence_number, used - ENCRYPTED_HEADER_SIZE));
2409 derive_auth_key (&auth_key,
2412 n->encrypt_key_created);
2413 GNUNET_CRYPTO_hmac (&auth_key,
2414 &em->sequence_number,
2415 used - ENCRYPTED_HEADER_SIZE,
2418 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2419 "Authenticated %u bytes of ciphertext %u: `%s'\n",
2420 used - ENCRYPTED_HEADER_SIZE,
2421 GNUNET_CRYPTO_crc32_n (&em->sequence_number,
2422 used - ENCRYPTED_HEADER_SIZE),
2423 GNUNET_h2s (&em->hmac));
2425 /* append to transmission list */
2426 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2430 process_encrypted_neighbour_queue (n);
2431 schedule_peer_messages (n);
2436 * Function that recalculates the bandwidth quota for the
2437 * given neighbour and transmits it to the transport service.
2439 * @param cls neighbour for the quota update
2443 neighbour_quota_update (void *cls,
2444 const struct GNUNET_SCHEDULER_TaskContext *tc);
2448 * Schedule the task that will recalculate the bandwidth
2449 * quota for this peer (and possibly force a disconnect of
2450 * idle peers by calculating a bandwidth of zero).
2453 schedule_quota_update (struct Neighbour *n)
2455 GNUNET_assert (n->quota_update_task ==
2456 GNUNET_SCHEDULER_NO_TASK);
2457 n->quota_update_task
2458 = GNUNET_SCHEDULER_add_delayed (QUOTA_UPDATE_FREQUENCY,
2459 &neighbour_quota_update,
2465 * Initialize a new 'struct Neighbour'.
2467 * @param pid ID of the new neighbour
2468 * @return handle for the new neighbour
2470 static struct Neighbour *
2471 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2473 struct Neighbour *n;
2474 struct GNUNET_TIME_Absolute now;
2477 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2478 "Creating neighbour entry for peer `%4s'\n",
2481 n = GNUNET_malloc (sizeof (struct Neighbour));
2482 n->next = neighbours;
2485 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2487 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2488 now = GNUNET_TIME_absolute_get ();
2489 n->encrypt_key_created = now;
2490 n->last_activity = now;
2491 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2492 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2493 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2494 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2495 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2496 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
2498 neighbour_quota_update (n, NULL);
2499 consider_free_neighbour (n);
2505 * Handle CORE_SEND request.
2508 * @param client the client issuing the request
2509 * @param message the "struct SendMessage"
2512 handle_client_send (void *cls,
2513 struct GNUNET_SERVER_Client *client,
2514 const struct GNUNET_MessageHeader *message)
2516 const struct SendMessage *sm;
2517 struct Neighbour *n;
2518 struct MessageEntry *prev;
2519 struct MessageEntry *pos;
2520 struct MessageEntry *e;
2521 struct MessageEntry *min_prio_entry;
2522 struct MessageEntry *min_prio_prev;
2523 unsigned int min_prio;
2524 unsigned int queue_size;
2527 msize = ntohs (message->size);
2529 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2531 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));
2534 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2537 sm = (const struct SendMessage *) message;
2538 msize -= sizeof (struct SendMessage);
2539 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2541 /* FIXME: should we not allow loopback-injection here? */
2544 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2547 n = find_neighbour (&sm->peer);
2549 n = create_neighbour (&sm->peer);
2551 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2552 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2554 (unsigned int) msize,
2555 GNUNET_i2s (&sm->peer));
2557 discard_expired_messages (n);
2558 /* bound queue size */
2559 /* NOTE: this entire block to bound the queue size should be
2560 obsolete with the new client-request code and the
2561 'schedule_peer_messages' mechanism; we still have this code in
2562 here for now as a sanity check for the new mechanmism;
2563 ultimately, we should probably simply reject SEND messages that
2564 are not 'approved' (or provide a new core API for very unreliable
2565 delivery that always sends with priority 0). Food for thought. */
2566 min_prio = UINT32_MAX;
2567 min_prio_entry = NULL;
2568 min_prio_prev = NULL;
2574 if (pos->priority <= min_prio)
2576 min_prio_entry = pos;
2577 min_prio_prev = prev;
2578 min_prio = pos->priority;
2584 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2587 if (ntohl(sm->priority) <= min_prio)
2589 /* discard new entry; this should no longer happen! */
2592 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2593 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2595 (unsigned int) MAX_PEER_QUEUE_SIZE,
2596 (unsigned int) msize,
2597 (unsigned int) ntohs (message->type));
2599 GNUNET_STATISTICS_update (stats,
2600 gettext_noop ("# discarded CORE_SEND requests"),
2604 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2607 GNUNET_assert (min_prio_entry != NULL);
2608 /* discard "min_prio_entry" */
2610 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2611 "Queue full, discarding existing older request\n");
2613 GNUNET_STATISTICS_update (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 1, GNUNET_NO);
2614 if (min_prio_prev == NULL)
2615 n->messages = min_prio_entry->next;
2617 min_prio_prev->next = min_prio_entry->next;
2618 GNUNET_free (min_prio_entry);
2622 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2623 "Adding transmission request for `%4s' of size %u to queue\n",
2624 GNUNET_i2s (&sm->peer),
2625 (unsigned int) msize);
2627 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2628 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2629 e->priority = ntohl (sm->priority);
2631 memcpy (&e[1], &sm[1], msize);
2633 /* insert, keep list sorted by deadline */
2636 while ((pos != NULL) && (pos->deadline.abs_value < e->deadline.abs_value))
2647 /* consider scheduling now */
2648 process_plaintext_neighbour_queue (n);
2650 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2655 * Function called when the transport service is ready to
2656 * receive a message. Only resets 'n->th' to NULL.
2658 * @param cls neighbour to use message from
2659 * @param size number of bytes we can transmit
2660 * @param buf where to copy the message
2661 * @return number of bytes transmitted
2664 notify_transport_connect_done (void *cls, size_t size, void *buf)
2666 struct Neighbour *n = cls;
2668 if (GNUNET_YES != n->is_connected)
2670 /* transport should only call us to transmit a message after
2671 * telling us about a successful connection to the respective peer */
2672 n->th = NULL; /* If this happens because of a timeout, reset n-th so another message may be sent for this peer! */
2674 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Timeout on notify connect!\n");
2681 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2682 _("Failed to connect to `%4s': transport failed to connect\n"),
2683 GNUNET_i2s (&n->peer));
2686 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2687 _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2688 GNUNET_i2s (&n->peer));
2689 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2690 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2691 n->retry_set_key_task = GNUNET_SCHEDULER_add_now (&set_key_retry_task,
2698 * Handle CORE_REQUEST_CONNECT request.
2701 * @param client the client issuing the request
2702 * @param message the "struct ConnectMessage"
2705 handle_client_request_connect (void *cls,
2706 struct GNUNET_SERVER_Client *client,
2707 const struct GNUNET_MessageHeader *message)
2709 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2710 struct Neighbour *n;
2711 struct GNUNET_TIME_Relative timeout;
2713 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2716 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2719 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2720 n = find_neighbour (&cm->peer);
2722 n = create_neighbour (&cm->peer);
2723 if ( (GNUNET_YES == n->is_connected) ||
2726 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2727 "Core received `%s' request for `%4s', already connected!\n",
2729 GNUNET_i2s (&cm->peer));
2730 return; /* already connected, or at least trying */
2732 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2734 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2735 "Core received `%s' request for `%4s', will try to establish connection\n",
2737 GNUNET_i2s (&cm->peer));
2739 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2740 /* ask transport to connect to the peer */
2741 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2743 sizeof (struct GNUNET_MessageHeader), 0,
2745 ¬ify_transport_connect_done,
2747 GNUNET_break (NULL != n->th);
2752 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2753 * the neighbour's struct and retry send_key. Or, if we did not get a
2754 * HELLO, just do nothing.
2756 * @param cls the 'struct Neighbour' to retry sending the key for
2757 * @param peer the peer for which this is the HELLO
2758 * @param hello HELLO message of that peer
2761 process_hello_retry_send_key (void *cls,
2762 const struct GNUNET_PeerIdentity *peer,
2763 const struct GNUNET_HELLO_Message *hello)
2765 struct Neighbour *n = cls;
2770 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2771 "Entered `%s' and `%s' is NULL!\n",
2772 "process_hello_retry_send_key",
2776 if (n->public_key != NULL)
2778 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2780 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2781 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2783 GNUNET_STATISTICS_update (stats,
2784 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2792 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2793 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
2794 GNUNET_i2s (&n->peer));
2796 GNUNET_STATISTICS_update (stats,
2797 gettext_noop ("# Delayed connecting due to lack of public key"),
2800 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2801 n->retry_set_key_task
2802 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2803 &set_key_retry_task, n);
2809 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2810 "Entered `%s' for peer `%4s'\n",
2811 "process_hello_retry_send_key",
2814 if (n->public_key != NULL)
2816 /* already have public key, why are we here? */
2822 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2823 "Received new `%s' message for `%4s', initiating key exchange.\n",
2828 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2829 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2831 GNUNET_STATISTICS_update (stats,
2832 gettext_noop ("# Error extracting public key from HELLO"),
2835 GNUNET_free (n->public_key);
2836 n->public_key = NULL;
2838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2839 "GNUNET_HELLO_get_key returned awfully\n");
2847 * Send our key (and encrypted PING) to the other peer.
2849 * @param n the other peer
2852 send_key (struct Neighbour *n)
2854 struct MessageEntry *pos;
2855 struct SetKeyMessage *sm;
2856 struct MessageEntry *me;
2857 struct PingMessage pp;
2858 struct PingMessage *pm;
2859 struct GNUNET_CRYPTO_AesInitializationVector iv;
2861 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2863 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2864 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2866 if (n->pitr != NULL)
2869 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2870 "Key exchange in progress with `%4s'.\n",
2871 GNUNET_i2s (&n->peer));
2873 return; /* already in progress */
2875 if (GNUNET_YES != n->is_connected)
2878 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2879 "Not yet connected to peer `%4s'!\n",
2880 GNUNET_i2s (&n->peer));
2884 GNUNET_STATISTICS_update (stats,
2885 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
2888 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2890 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2892 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2893 ¬ify_encrypted_transmit_ready,
2899 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2900 "Asked to perform key exchange with `%4s'.\n",
2901 GNUNET_i2s (&n->peer));
2903 if (n->public_key == NULL)
2905 /* lookup n's public key, then try again */
2907 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2908 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2909 GNUNET_i2s (&n->peer));
2911 GNUNET_assert (n->pitr == NULL);
2912 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2914 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2915 &process_hello_retry_send_key, n);
2918 pos = n->encrypted_head;
2921 if (GNUNET_YES == pos->is_setkey)
2923 if (pos->sender_status == n->status)
2926 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2927 "`%s' message for `%4s' queued already\n",
2929 GNUNET_i2s (&n->peer));
2931 goto trigger_processing;
2933 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2938 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2939 "Removing queued `%s' message for `%4s', will create a new one\n",
2941 GNUNET_i2s (&n->peer));
2951 case PEER_STATE_DOWN:
2952 n->status = PEER_STATE_KEY_SENT;
2954 case PEER_STATE_KEY_SENT:
2956 case PEER_STATE_KEY_RECEIVED:
2958 case PEER_STATE_KEY_CONFIRMED:
2966 /* first, set key message */
2967 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2968 sizeof (struct SetKeyMessage) +
2969 sizeof (struct PingMessage));
2970 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2971 me->priority = SET_KEY_PRIORITY;
2972 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
2973 me->is_setkey = GNUNET_YES;
2974 me->got_slack = GNUNET_YES; /* do not defer this one! */
2975 me->sender_status = n->status;
2976 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2980 sm = (struct SetKeyMessage *) &me[1];
2981 sm->header.size = htons (sizeof (struct SetKeyMessage));
2982 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2983 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2984 PEER_STATE_KEY_SENT : n->status));
2986 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2987 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2988 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2989 sizeof (struct GNUNET_PeerIdentity));
2990 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2991 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2992 sm->target = n->peer;
2993 GNUNET_assert (GNUNET_OK ==
2994 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2996 GNUNET_CRYPTO_AesSessionKey),
2998 &sm->encrypted_key));
2999 GNUNET_assert (GNUNET_OK ==
3000 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
3002 pm = (struct PingMessage *) &sm[1];
3003 pm->header.size = htons (sizeof (struct PingMessage));
3004 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
3005 pm->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3006 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
3007 pp.challenge = n->ping_challenge;
3008 pp.target = n->peer;
3010 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3011 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
3013 (unsigned int) n->ping_challenge,
3014 GNUNET_i2s (&n->peer),
3015 (unsigned int) n->encrypt_key.crc32,
3016 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3023 sizeof (struct PingMessage) -
3024 ((void *) &pm->target - (void *) pm));
3025 GNUNET_STATISTICS_update (stats,
3026 gettext_noop ("# SET_KEY and PING messages created"),
3030 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3031 "Have %llu ms left for `%s' transmission.\n",
3032 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).rel_value,
3036 /* trigger queue processing */
3037 process_encrypted_neighbour_queue (n);
3038 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
3039 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
3040 n->retry_set_key_task
3041 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3042 &set_key_retry_task, n);
3047 * We received a SET_KEY message. Validate and update
3048 * our key material and status.
3050 * @param n the neighbour from which we received message m
3051 * @param m the set key message we received
3054 handle_set_key (struct Neighbour *n,
3055 const struct SetKeyMessage *m);
3059 * PEERINFO is giving us a HELLO for a peer. Add the public key to
3060 * the neighbour's struct and retry handling the set_key message. Or,
3061 * if we did not get a HELLO, just free the set key message.
3063 * @param cls pointer to the set key message
3064 * @param peer the peer for which this is the HELLO
3065 * @param hello HELLO message of that peer
3068 process_hello_retry_handle_set_key (void *cls,
3069 const struct GNUNET_PeerIdentity *peer,
3070 const struct GNUNET_HELLO_Message *hello)
3072 struct Neighbour *n = cls;
3073 struct SetKeyMessage *sm = n->skm;
3079 if (n->public_key != NULL)
3082 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3083 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
3085 GNUNET_i2s (&n->peer),
3088 handle_set_key (n, sm);
3092 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3093 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
3095 GNUNET_i2s (&n->peer));
3100 if (n->public_key != NULL)
3101 return; /* multiple HELLOs match!? */
3103 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3104 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3106 GNUNET_break_op (0);
3107 GNUNET_free (n->public_key);
3108 n->public_key = NULL;
3114 * We received a PING message. Validate and transmit
3117 * @param n sender of the PING
3118 * @param m the encrypted PING message itself
3121 handle_ping (struct Neighbour *n, const struct PingMessage *m)
3123 struct PingMessage t;
3124 struct PongMessage tx;
3125 struct PongMessage *tp;
3126 struct MessageEntry *me;
3127 struct GNUNET_CRYPTO_AesInitializationVector iv;
3130 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3131 "Core service receives `%s' request from `%4s'.\n",
3132 "PING", GNUNET_i2s (&n->peer));
3134 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3140 sizeof (struct PingMessage) -
3141 ((void *) &m->target - (void *) m)))
3144 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3145 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u, IV %u (salt %u)\n",
3147 GNUNET_i2s (&t.target),
3148 (unsigned int) t.challenge,
3149 (unsigned int) n->decrypt_key.crc32,
3150 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3153 GNUNET_STATISTICS_update (stats,
3154 gettext_noop ("# PING messages decrypted"),
3157 if (0 != memcmp (&t.target,
3158 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3160 GNUNET_break_op (0);
3163 me = GNUNET_malloc (sizeof (struct MessageEntry) +
3164 sizeof (struct PongMessage));
3165 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3169 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
3170 me->priority = PONG_PRIORITY;
3171 me->size = sizeof (struct PongMessage);
3172 tx.inbound_bw_limit = n->bw_in;
3173 tx.challenge = t.challenge;
3174 tx.target = t.target;
3175 tp = (struct PongMessage *) &me[1];
3176 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
3177 tp->header.size = htons (sizeof (struct PongMessage));
3178 tp->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3179 derive_pong_iv (&iv, &n->encrypt_key, tp->iv_seed, t.challenge, &n->peer);
3184 sizeof (struct PongMessage) -
3185 ((void *) &tp->challenge - (void *) tp));
3186 GNUNET_STATISTICS_update (stats,
3187 gettext_noop ("# PONG messages created"),
3191 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3192 "Encrypting `%s' with challenge %u using key %u, IV %u (salt %u)\n",
3194 (unsigned int) t.challenge,
3195 (unsigned int) n->encrypt_key.crc32,
3196 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3199 /* trigger queue processing */
3200 process_encrypted_neighbour_queue (n);
3205 * We received a PONG message. Validate and update our status.
3207 * @param n sender of the PONG
3208 * @param m the encrypted PONG message itself
3211 handle_pong (struct Neighbour *n,
3212 const struct PongMessage *m)
3214 struct PongMessage t;
3215 struct ConnectNotifyMessage cnm;
3216 struct GNUNET_CRYPTO_AesInitializationVector iv;
3219 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3220 "Core service receives `%s' response from `%4s'.\n",
3221 "PONG", GNUNET_i2s (&n->peer));
3223 /* mark as garbage, just to be sure */
3224 memset (&t, 255, sizeof (t));
3225 derive_pong_iv (&iv, &n->decrypt_key, m->iv_seed, n->ping_challenge,
3232 sizeof (struct PongMessage) -
3233 ((void *) &m->challenge - (void *) m)))
3235 GNUNET_break_op (0);
3238 GNUNET_STATISTICS_update (stats,
3239 gettext_noop ("# PONG messages decrypted"),
3243 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3244 "Decrypted `%s' from `%4s' with challenge %u using key %u, IV %u (salt %u)\n",
3246 GNUNET_i2s (&t.target),
3247 (unsigned int) t.challenge,
3248 (unsigned int) n->decrypt_key.crc32,
3249 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3252 if ((0 != memcmp (&t.target,
3254 sizeof (struct GNUNET_PeerIdentity))) ||
3255 (n->ping_challenge != t.challenge))
3257 /* PONG malformed */
3259 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3260 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
3262 GNUNET_i2s (&n->peer),
3263 (unsigned int) n->ping_challenge);
3264 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3265 "Received malformed `%s' received from `%4s' with challenge %u\n",
3266 "PONG", GNUNET_i2s (&t.target),
3267 (unsigned int) t.challenge);
3269 GNUNET_break_op (0);
3274 case PEER_STATE_DOWN:
3275 GNUNET_break (0); /* should be impossible */
3277 case PEER_STATE_KEY_SENT:
3278 GNUNET_break (0); /* should be impossible, how did we decrypt? */
3280 case PEER_STATE_KEY_RECEIVED:
3281 GNUNET_STATISTICS_update (stats,
3282 gettext_noop ("# Session keys confirmed via PONG"),
3285 n->status = PEER_STATE_KEY_CONFIRMED;
3286 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
3288 n->bw_out_external_limit = t.inbound_bw_limit;
3289 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3290 n->bw_out_internal_limit);
3291 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3293 GNUNET_TRANSPORT_set_quota (transport,
3297 GNUNET_TIME_UNIT_FOREVER_REL,
3301 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3302 "Confirmed key via `%s' message for peer `%4s'\n",
3303 "PONG", GNUNET_i2s (&n->peer));
3305 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3307 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3308 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3310 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3311 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3313 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
3314 process_encrypted_neighbour_queue (n);
3316 case PEER_STATE_KEY_CONFIRMED:
3317 n->last_activity = GNUNET_TIME_absolute_get ();
3318 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3319 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3321 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3324 handle_peer_status_change (n);
3334 * We received a SET_KEY message. Validate and update
3335 * our key material and status.
3337 * @param n the neighbour from which we received message m
3338 * @param m the set key message we received
3341 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
3343 struct SetKeyMessage *m_cpy;
3344 struct GNUNET_TIME_Absolute t;
3345 struct GNUNET_CRYPTO_AesSessionKey k;
3346 struct PingMessage *ping;
3347 struct PongMessage *pong;
3348 enum PeerStateMachine sender_status;
3351 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3352 "Core service receives `%s' request from `%4s'.\n",
3353 "SET_KEY", GNUNET_i2s (&n->peer));
3355 if (n->public_key == NULL)
3357 if (n->pitr != NULL)
3360 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3361 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3367 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3368 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3370 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3371 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3372 /* lookup n's public key, then try again */
3373 GNUNET_assert (n->skm == NULL);
3375 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3377 GNUNET_TIME_UNIT_MINUTES,
3378 &process_hello_retry_handle_set_key, n);
3379 GNUNET_STATISTICS_update (stats,
3380 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3385 if (0 != memcmp (&m->target,
3387 sizeof (struct GNUNET_PeerIdentity)))
3389 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3390 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3392 GNUNET_i2s (&m->target));
3395 if ((ntohl (m->purpose.size) !=
3396 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3397 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3398 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3399 sizeof (struct GNUNET_PeerIdentity)) ||
3401 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3402 &m->purpose, &m->signature, n->public_key)))
3404 /* invalid signature */
3405 GNUNET_break_op (0);
3408 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3409 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3410 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3411 (t.abs_value < n->decrypt_key_created.abs_value))
3413 /* this could rarely happen due to massive re-ordering of
3414 messages on the network level, but is most likely either
3415 a bug or some adversary messing with us. Report. */
3416 GNUNET_break_op (0);
3420 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3421 "Decrypting key material.\n");
3423 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3426 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3427 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3428 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3430 /* failed to decrypt !? */
3431 GNUNET_break_op (0);
3434 GNUNET_STATISTICS_update (stats,
3435 gettext_noop ("# SET_KEY messages decrypted"),
3439 if (n->decrypt_key_created.abs_value != t.abs_value)
3441 /* fresh key, reset sequence numbers */
3442 n->last_sequence_number_received = 0;
3443 n->last_packets_bitmap = 0;
3444 n->decrypt_key_created = t;
3446 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3449 case PEER_STATE_DOWN:
3450 n->status = PEER_STATE_KEY_RECEIVED;
3452 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3453 "Responding to `%s' with my own key.\n", "SET_KEY");
3457 case PEER_STATE_KEY_SENT:
3458 case PEER_STATE_KEY_RECEIVED:
3459 n->status = PEER_STATE_KEY_RECEIVED;
3460 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3461 (sender_status != PEER_STATE_KEY_CONFIRMED))
3464 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3465 "Responding to `%s' with my own key (other peer has status %u).\n",
3467 (unsigned int) sender_status);
3472 case PEER_STATE_KEY_CONFIRMED:
3473 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3474 (sender_status != PEER_STATE_KEY_CONFIRMED))
3477 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3478 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3480 (unsigned int) sender_status);
3489 if (n->pending_ping != NULL)
3491 ping = n->pending_ping;
3492 n->pending_ping = NULL;
3493 handle_ping (n, ping);
3496 if (n->pending_pong != NULL)
3498 pong = n->pending_pong;
3499 n->pending_pong = NULL;
3500 handle_pong (n, pong);
3507 * Send a P2P message to a client.
3509 * @param sender who sent us the message?
3510 * @param client who should we give the message to?
3511 * @param m contains the message to transmit
3512 * @param msize number of bytes in buf to transmit
3515 send_p2p_message_to_client (struct Neighbour *sender,
3516 struct Client *client,
3517 const void *m, size_t msize)
3519 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3520 struct NotifyTrafficMessage *ntm;
3523 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3524 "Core service passes message from `%4s' of type %u to client.\n",
3525 GNUNET_i2s(&sender->peer),
3526 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3528 ntm = (struct NotifyTrafficMessage *) buf;
3529 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3530 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3531 ntm->ats_count = htonl (0);
3532 ntm->ats.type = htonl (0);
3533 ntm->ats.value = htonl (0);
3534 ntm->peer = sender->peer;
3535 memcpy (&ntm[1], m, msize);
3536 send_to_client (client, &ntm->header, GNUNET_YES);
3541 * Deliver P2P message to interested clients.
3543 * @param cls always NULL
3544 * @param client who sent us the message (struct Neighbour)
3545 * @param m the message
3548 deliver_message (void *cls,
3550 const struct GNUNET_MessageHeader *m)
3552 struct Neighbour *sender = client;
3553 size_t msize = ntohs (m->size);
3555 struct Client *cpos;
3561 type = ntohs (m->type);
3563 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3564 "Received encapsulated message of type %u and size %u from `%4s'\n",
3565 (unsigned int) type,
3567 GNUNET_i2s (&sender->peer));
3569 GNUNET_snprintf (buf,
3571 gettext_noop ("# bytes of messages of type %u received"),
3572 (unsigned int) type);
3573 GNUNET_STATISTICS_set (stats,
3577 dropped = GNUNET_YES;
3579 while (cpos != NULL)
3581 deliver_full = GNUNET_NO;
3582 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3583 deliver_full = GNUNET_YES;
3586 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3588 if (type != cpos->types[tpos])
3590 deliver_full = GNUNET_YES;
3594 if (GNUNET_YES == deliver_full)
3596 send_p2p_message_to_client (sender, cpos, m, msize);
3597 dropped = GNUNET_NO;
3599 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3601 send_p2p_message_to_client (sender, cpos, m,
3602 sizeof (struct GNUNET_MessageHeader));
3606 if (dropped == GNUNET_YES)
3609 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3610 "Message of type %u from `%4s' not delivered to any client.\n",
3611 (unsigned int) type,
3612 GNUNET_i2s (&sender->peer));
3614 GNUNET_STATISTICS_update (stats,
3615 gettext_noop ("# messages not delivered to any client"),
3622 * We received an encrypted message. Decrypt, validate and
3623 * pass on to the appropriate clients.
3626 handle_encrypted_message (struct Neighbour *n,
3627 const struct EncryptedMessage *m)
3629 size_t size = ntohs (m->header.size);
3631 struct EncryptedMessage *pt; /* plaintext */
3634 struct GNUNET_TIME_Absolute t;
3635 struct GNUNET_CRYPTO_AesInitializationVector iv;
3636 struct GNUNET_CRYPTO_AuthKey auth_key;
3639 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3640 "Core service receives `%s' request from `%4s'.\n",
3641 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3644 derive_auth_key (&auth_key,
3647 n->decrypt_key_created);
3648 GNUNET_CRYPTO_hmac (&auth_key,
3649 &m->sequence_number,
3650 size - ENCRYPTED_HEADER_SIZE, &ph);
3652 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3653 "Re-Authenticated %u bytes of ciphertext (`%u'): `%s'\n",
3654 (unsigned int) size - ENCRYPTED_HEADER_SIZE,
3655 GNUNET_CRYPTO_crc32_n (&m->sequence_number,
3656 size - ENCRYPTED_HEADER_SIZE),
3660 if (0 != memcmp (&ph,
3662 sizeof (GNUNET_HashCode)))
3664 /* checksum failed */
3665 GNUNET_break_op (0);
3668 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3673 &m->sequence_number,
3674 &buf[ENCRYPTED_HEADER_SIZE],
3675 size - ENCRYPTED_HEADER_SIZE))
3677 pt = (struct EncryptedMessage *) buf;
3679 /* validate sequence number */
3680 snum = ntohl (pt->sequence_number);
3681 if (n->last_sequence_number_received == snum)
3683 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3684 "Received duplicate message, ignoring.\n");
3685 /* duplicate, ignore */
3686 GNUNET_STATISTICS_set (stats,
3687 gettext_noop ("# bytes dropped (duplicates)"),
3692 if ((n->last_sequence_number_received > snum) &&
3693 (n->last_sequence_number_received - snum > 32))
3695 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3696 "Received ancient out of sequence message, ignoring.\n");
3697 /* ancient out of sequence, ignore */
3698 GNUNET_STATISTICS_set (stats,
3699 gettext_noop ("# bytes dropped (out of sequence)"),
3704 if (n->last_sequence_number_received > snum)
3706 unsigned int rotbit =
3707 1 << (n->last_sequence_number_received - snum - 1);
3708 if ((n->last_packets_bitmap & rotbit) != 0)
3710 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3711 "Received duplicate message, ignoring.\n");
3712 GNUNET_STATISTICS_set (stats,
3713 gettext_noop ("# bytes dropped (duplicates)"),
3716 /* duplicate, ignore */
3719 n->last_packets_bitmap |= rotbit;
3721 if (n->last_sequence_number_received < snum)
3723 int shift = (snum - n->last_sequence_number_received);
3724 if (shift >= 8 * sizeof(n->last_packets_bitmap))
3725 n->last_packets_bitmap = 0;
3727 n->last_packets_bitmap <<= shift;
3728 n->last_sequence_number_received = snum;
3731 /* check timestamp */
3732 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3733 if (GNUNET_TIME_absolute_get_duration (t).rel_value > MAX_MESSAGE_AGE.rel_value)
3735 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3737 ("Message received far too old (%llu ms). Content ignored.\n"),
3738 GNUNET_TIME_absolute_get_duration (t).rel_value);
3739 GNUNET_STATISTICS_set (stats,
3740 gettext_noop ("# bytes dropped (ancient message)"),
3746 /* process decrypted message(s) */
3747 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3749 #if DEBUG_CORE_SET_QUOTA
3750 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3751 "Received %u b/s as new inbound limit for peer `%4s'\n",
3752 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3753 GNUNET_i2s (&n->peer));
3755 n->bw_out_external_limit = pt->inbound_bw_limit;
3756 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3757 n->bw_out_internal_limit);
3758 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3760 GNUNET_TRANSPORT_set_quota (transport,
3764 GNUNET_TIME_UNIT_FOREVER_REL,
3767 n->last_activity = GNUNET_TIME_absolute_get ();
3768 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3769 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3771 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3774 GNUNET_STATISTICS_set (stats,
3775 gettext_noop ("# bytes of payload decrypted"),
3776 size - sizeof (struct EncryptedMessage),
3778 handle_peer_status_change (n);
3779 if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst,
3781 &buf[sizeof (struct EncryptedMessage)],
3782 size - sizeof (struct EncryptedMessage),
3783 GNUNET_YES, GNUNET_NO))
3784 GNUNET_break_op (0);
3789 * Function called by the transport for each received message.
3791 * @param cls closure
3792 * @param peer (claimed) identity of the other peer
3793 * @param message the message
3794 * @param latency estimated latency for communicating with the
3795 * given peer (round-trip)
3796 * @param distance in overlay hops, as given by transport plugin
3799 handle_transport_receive (void *cls,
3800 const struct GNUNET_PeerIdentity *peer,
3801 const struct GNUNET_MessageHeader *message,
3802 struct GNUNET_TIME_Relative latency,
3803 unsigned int distance)
3805 struct Neighbour *n;
3806 struct GNUNET_TIME_Absolute now;
3813 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3814 "Received message of type %u from `%4s', demultiplexing.\n",
3815 (unsigned int) ntohs (message->type),
3818 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3823 n = find_neighbour (peer);
3825 n = create_neighbour (peer);
3826 changed = GNUNET_YES; /* FIXME... */
3827 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3828 type = ntohs (message->type);
3829 size = ntohs (message->size);
3832 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3833 if (size != sizeof (struct SetKeyMessage))
3835 GNUNET_break_op (0);
3838 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3839 handle_set_key (n, (const struct SetKeyMessage *) message);
3841 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3842 if (size < sizeof (struct EncryptedMessage) +
3843 sizeof (struct GNUNET_MessageHeader))
3845 GNUNET_break_op (0);
3848 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3849 (n->status != PEER_STATE_KEY_CONFIRMED))
3851 GNUNET_break_op (0);
3854 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3856 case GNUNET_MESSAGE_TYPE_CORE_PING:
3857 if (size != sizeof (struct PingMessage))
3859 GNUNET_break_op (0);
3862 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3863 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3864 (n->status != PEER_STATE_KEY_CONFIRMED))
3867 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3868 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3869 "PING", GNUNET_i2s (&n->peer));
3871 GNUNET_free_non_null (n->pending_ping);
3872 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3873 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3876 handle_ping (n, (const struct PingMessage *) message);
3878 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3879 if (size != sizeof (struct PongMessage))
3881 GNUNET_break_op (0);
3884 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3885 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3886 (n->status != PEER_STATE_KEY_CONFIRMED) )
3889 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3890 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3891 "PONG", GNUNET_i2s (&n->peer));
3893 GNUNET_free_non_null (n->pending_pong);
3894 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3895 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3898 handle_pong (n, (const struct PongMessage *) message);
3901 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3902 _("Unsupported message of type %u received.\n"),
3903 (unsigned int) type);
3906 if (n->status == PEER_STATE_KEY_CONFIRMED)
3908 now = GNUNET_TIME_absolute_get ();
3909 n->last_activity = now;
3910 changed = GNUNET_YES;
3913 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3914 n->time_established = now;
3916 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3917 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3919 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3924 handle_peer_status_change (n);
3929 * Function that recalculates the bandwidth quota for the
3930 * given neighbour and transmits it to the transport service.
3932 * @param cls neighbour for the quota update
3936 neighbour_quota_update (void *cls,
3937 const struct GNUNET_SCHEDULER_TaskContext *tc)
3939 struct Neighbour *n = cls;
3940 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3943 unsigned long long distributable;
3944 uint64_t need_per_peer;
3945 uint64_t need_per_second;
3948 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3949 "Neighbour quota update calculation running for peer `%4s'\n",
3950 GNUNET_i2s (&n->peer));
3952 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3953 /* calculate relative preference among all neighbours;
3954 divides by a bit more to avoid division by zero AND to
3955 account for possibility of new neighbours joining any time
3956 AND to convert to double... */
3957 if (preference_sum == 0)
3959 pref_rel = 1.0 / (double) neighbour_count;
3963 pref_rel = n->current_preference / preference_sum;
3965 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3966 GNUNET_TIME_UNIT_SECONDS);
3967 need_per_second = need_per_peer * neighbour_count;
3969 if (bandwidth_target_out_bps > need_per_second)
3970 distributable = bandwidth_target_out_bps - need_per_second;
3971 share = distributable * pref_rel;
3972 if (share + need_per_peer > UINT32_MAX)
3973 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
3975 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3976 /* check if we want to disconnect for good due to inactivity */
3977 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) &&
3978 (GNUNET_TIME_absolute_get_duration (n->time_established).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) )
3981 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3982 "Forcing disconnect of `%4s' due to inactivity\n",
3983 GNUNET_i2s (&n->peer));
3985 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3987 #if DEBUG_CORE_QUOTA
3988 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3989 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3990 GNUNET_i2s (&n->peer),
3991 (unsigned int) ntohl (q_in.value__),
3992 bandwidth_target_out_bps,
3993 (unsigned int) ntohl (n->bw_in.value__),
3994 (unsigned int) ntohl (n->bw_out.value__),
3995 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3997 if (n->bw_in.value__ != q_in.value__)
4000 if (GNUNET_YES == n->is_connected)
4001 GNUNET_TRANSPORT_set_quota (transport,
4005 GNUNET_TIME_UNIT_FOREVER_REL,
4007 handle_peer_status_change (n);
4009 schedule_quota_update (n);
4014 * Function called by transport to notify us that
4015 * a peer connected to us (on the network level).
4017 * @param cls closure
4018 * @param peer the peer that connected
4019 * @param latency current latency of the connection
4020 * @param distance in overlay hops, as given by transport plugin
4023 handle_transport_notify_connect (void *cls,
4024 const struct GNUNET_PeerIdentity *peer,
4025 struct GNUNET_TIME_Relative latency,
4026 unsigned int distance)
4028 struct Neighbour *n;
4030 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4035 n = find_neighbour (peer);
4038 if (GNUNET_YES == n->is_connected)
4040 /* duplicate connect notification!? */
4047 n = create_neighbour (peer);
4049 GNUNET_STATISTICS_update (stats,
4050 gettext_noop ("# peers connected (transport)"),
4053 n->is_connected = GNUNET_YES;
4054 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
4057 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
4061 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4062 "Received connection from `%4s'.\n",
4063 GNUNET_i2s (&n->peer));
4065 GNUNET_TRANSPORT_set_quota (transport,
4069 GNUNET_TIME_UNIT_FOREVER_REL,
4076 * Function called by transport telling us that a peer
4079 * @param cls closure
4080 * @param peer the peer that disconnected
4083 handle_transport_notify_disconnect (void *cls,
4084 const struct GNUNET_PeerIdentity *peer)
4086 struct DisconnectNotifyMessage cnm;
4087 struct Neighbour *n;
4088 struct ClientActiveRequest *car;
4089 struct GNUNET_TIME_Relative left;
4092 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4093 "Peer `%4s' disconnected from us; received notification from transport.\n", GNUNET_i2s (peer));
4096 n = find_neighbour (peer);
4102 GNUNET_break (n->is_connected);
4103 if (n->status == PEER_STATE_KEY_CONFIRMED)
4105 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
4106 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
4108 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
4110 n->is_connected = GNUNET_NO;
4111 while (NULL != (car = n->active_client_request_head))
4113 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
4114 n->active_client_request_tail,
4116 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
4117 &n->peer.hashPubKey,
4122 GNUNET_STATISTICS_update (stats,
4123 gettext_noop ("# peers connected (transport)"),
4126 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
4127 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
4128 left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4129 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
4130 n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (),
4132 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
4133 &consider_free_task,
4139 * Last task run during shutdown. Disconnects us from
4143 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4145 struct Neighbour *n;
4149 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4150 "Core service shutting down.\n");
4152 GNUNET_assert (transport != NULL);
4153 GNUNET_TRANSPORT_disconnect (transport);
4155 while (NULL != (n = neighbours))
4157 neighbours = n->next;
4158 GNUNET_assert (neighbour_count > 0);
4162 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
4163 GNUNET_SERVER_notification_context_destroy (notifier);
4165 while (NULL != (c = clients))
4166 handle_client_disconnect (NULL, c->client_handle);
4167 if (my_private_key != NULL)
4168 GNUNET_CRYPTO_rsa_key_free (my_private_key);
4170 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4171 if (peerinfo != NULL)
4172 GNUNET_PEERINFO_disconnect (peerinfo);
4174 GNUNET_SERVER_mst_destroy (mst);
4179 * Initiate core service.
4181 * @param cls closure
4182 * @param server the initialized server
4183 * @param c configuration to use
4187 struct GNUNET_SERVER_Handle *server,
4188 const struct GNUNET_CONFIGURATION_Handle *c)
4190 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4191 {&handle_client_init, NULL,
4192 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
4193 {&handle_client_request_info, NULL,
4194 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
4195 sizeof (struct RequestInfoMessage)},
4196 {&handle_client_send_request, NULL,
4197 GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST,
4198 sizeof (struct SendMessageRequest)},
4199 {&handle_client_send, NULL,
4200 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
4201 {&handle_client_request_connect, NULL,
4202 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
4203 sizeof (struct ConnectMessage)},
4209 /* parse configuration */
4212 GNUNET_CONFIGURATION_get_value_number (c,
4215 &bandwidth_target_in_bps)) ||
4217 GNUNET_CONFIGURATION_get_value_number (c,
4220 &bandwidth_target_out_bps)) ||
4222 GNUNET_CONFIGURATION_get_value_filename (c,
4224 "HOSTKEY", &keyfile)))
4226 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4228 ("Core service is lacking key configuration settings. Exiting.\n"));
4229 GNUNET_SCHEDULER_shutdown ();
4232 peerinfo = GNUNET_PEERINFO_connect (cfg);
4233 if (NULL == peerinfo)
4235 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4236 _("Could not access PEERINFO service. Exiting.\n"));
4237 GNUNET_SCHEDULER_shutdown ();
4238 GNUNET_free (keyfile);
4241 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4242 GNUNET_free (keyfile);
4243 if (my_private_key == NULL)
4245 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4246 _("Core service could not access hostkey. Exiting.\n"));
4247 GNUNET_PEERINFO_disconnect (peerinfo);
4248 GNUNET_SCHEDULER_shutdown ();
4251 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4252 GNUNET_CRYPTO_hash (&my_public_key,
4253 sizeof (my_public_key), &my_identity.hashPubKey);
4254 /* setup notification */
4255 notifier = GNUNET_SERVER_notification_context_create (server,
4257 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4258 /* setup transport connection */
4259 transport = GNUNET_TRANSPORT_connect (cfg,
4262 &handle_transport_receive,
4263 &handle_transport_notify_connect,
4264 &handle_transport_notify_disconnect);
4265 GNUNET_assert (NULL != transport);
4266 stats = GNUNET_STATISTICS_create ("core", cfg);
4268 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded CORE_SEND requests"), 0, GNUNET_NO);
4269 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 0, GNUNET_NO);
4271 mst = GNUNET_SERVER_mst_create (&deliver_message,
4273 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4274 &cleaning_task, NULL);
4275 /* process client requests */
4276 GNUNET_SERVER_add_handlers (server, handlers);
4277 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4278 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
4284 * The main function for the transport service.
4286 * @param argc number of arguments from the command line
4287 * @param argv command line arguments
4288 * @return 0 ok, 1 on error
4291 main (int argc, char *const *argv)
4293 return (GNUNET_OK ==
4294 GNUNET_SERVICE_run (argc,
4297 GNUNET_SERVICE_OPTION_NONE,
4298 &run, NULL)) ? 0 : 1;
4301 /* end of gnunet-service-core.c */