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)
984 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
985 "Peer `%4s' changed status\n",
986 GNUNET_i2s (&n->peer));
988 psnm.header.size = htons (sizeof (struct PeerStatusNotifyMessage));
989 psnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_STATUS_CHANGE);
990 psnm.timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_add (n->last_activity,
991 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
992 psnm.bandwidth_in = n->bw_in;
993 psnm.bandwidth_out = n->bw_out;
995 send_to_all_clients (&psnm.header,
997 GNUNET_CORE_OPTION_SEND_STATUS_CHANGE);
998 GNUNET_STATISTICS_update (stats,
999 gettext_noop ("# peer status changes"),
1006 * Go over our message queue and if it is not too long, go
1007 * over the pending requests from clients for this
1008 * neighbour and send some clients a 'READY' notification.
1010 * @param n which peer to process
1013 schedule_peer_messages (struct Neighbour *n)
1015 struct SendMessageReady smr;
1016 struct ClientActiveRequest *car;
1017 struct ClientActiveRequest *pos;
1019 struct MessageEntry *mqe;
1020 unsigned int queue_size;
1022 /* check if neighbour queue is empty enough! */
1030 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1031 return; /* queue still full */
1032 /* find highest priority request */
1033 pos = n->active_client_request_head;
1037 if ( (car == NULL) ||
1038 (pos->priority > car->priority) )
1043 return; /* no pending requests */
1045 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1046 n->active_client_request_tail,
1048 GNUNET_CONTAINER_multihashmap_remove (c->requests,
1049 &n->peer.hashPubKey,
1051 smr.header.size = htons (sizeof (struct SendMessageReady));
1052 smr.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND_READY);
1053 smr.size = htons (car->msize);
1054 smr.smr_id = car->smr_id;
1056 send_to_client (c, &smr.header, GNUNET_NO);
1062 * Handle CORE_SEND_REQUEST message.
1065 handle_client_send_request (void *cls,
1066 struct GNUNET_SERVER_Client *client,
1067 const struct GNUNET_MessageHeader *message)
1069 const struct SendMessageRequest *req;
1070 struct Neighbour *n;
1072 struct ClientActiveRequest *car;
1074 req = (const struct SendMessageRequest*) message;
1075 n = find_neighbour (&req->peer);
1077 (GNUNET_YES != n->is_connected) )
1079 /* neighbour must have disconnected since request was issued,
1080 ignore (client will realize it once it processes the
1081 disconnect notification) */
1082 GNUNET_STATISTICS_update (stats,
1083 gettext_noop ("# send requests dropped (disconnected)"),
1086 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1090 while ( (c != NULL) &&
1091 (c->client_handle != client) )
1095 /* client did not send INIT first! */
1097 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1100 if (c->requests == NULL)
1101 c->requests = GNUNET_CONTAINER_multihashmap_create (16);
1102 car = GNUNET_CONTAINER_multihashmap_get (c->requests,
1103 &req->peer.hashPubKey);
1106 /* create new entry */
1107 car = GNUNET_malloc (sizeof (struct ClientActiveRequest));
1108 GNUNET_assert (GNUNET_OK ==
1109 GNUNET_CONTAINER_multihashmap_put (c->requests,
1110 &req->peer.hashPubKey,
1112 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1113 GNUNET_CONTAINER_DLL_insert (n->active_client_request_head,
1114 n->active_client_request_tail,
1118 car->deadline = GNUNET_TIME_absolute_ntoh (req->deadline);
1119 car->priority = ntohl (req->priority);
1120 car->queue_size = ntohl (req->queue_size);
1121 car->msize = ntohs (req->size);
1122 car->smr_id = req->smr_id;
1123 schedule_peer_messages (n);
1124 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1129 * Handle CORE_INIT request.
1132 handle_client_init (void *cls,
1133 struct GNUNET_SERVER_Client *client,
1134 const struct GNUNET_MessageHeader *message)
1136 const struct InitMessage *im;
1137 struct InitReplyMessage irm;
1140 const uint16_t *types;
1142 struct Neighbour *n;
1143 struct ConnectNotifyMessage cnm;
1146 #if DEBUG_CORE_CLIENT
1147 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1148 "Client connecting to core service with `%s' message\n",
1151 /* check that we don't have an entry already */
1155 if (client == c->client_handle)
1159 msize = ntohs (message->size);
1160 if (msize < sizeof (struct InitMessage))
1163 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1166 GNUNET_SERVER_notification_context_add (notifier, client);
1167 im = (const struct InitMessage *) message;
1168 types = (const uint16_t *) &im[1];
1169 msize -= sizeof (struct InitMessage);
1172 c = GNUNET_malloc (sizeof (struct Client) + msize);
1173 c->client_handle = client;
1176 c->tcnt = msize / sizeof (uint16_t);
1177 c->types = (const uint16_t *) &c[1];
1178 wtypes = (uint16_t *) &c[1];
1179 for (i=0;i<c->tcnt;i++)
1180 wtypes[i] = ntohs (types[i]);
1181 c->options = ntohl (im->options);
1183 #if DEBUG_CORE_CLIENT
1184 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1185 "Client %p is interested in %u message types\n",
1187 (unsigned int) c->tcnt);
1189 /* send init reply message */
1190 irm.header.size = htons (sizeof (struct InitReplyMessage));
1191 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
1192 irm.reserved = htonl (0);
1193 memcpy (&irm.publicKey,
1195 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1196 #if DEBUG_CORE_CLIENT
1197 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1198 "Sending `%s' message to client.\n", "INIT_REPLY");
1200 send_to_client (c, &irm.header, GNUNET_NO);
1201 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
1203 /* notify new client about existing neighbours */
1204 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
1205 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1209 if (n->status == PEER_STATE_KEY_CONFIRMED)
1211 #if DEBUG_CORE_CLIENT
1212 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1213 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
1216 send_to_client (c, &cnm.header, GNUNET_NO);
1221 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1226 * Free client request records.
1229 * @param key identity of peer for which this is an active request
1230 * @param value the 'struct ClientActiveRequest' to free
1231 * @return GNUNET_YES (continue iteration)
1234 destroy_active_client_request (void *cls,
1235 const GNUNET_HashCode *key,
1238 struct ClientActiveRequest *car = cls;
1239 struct Neighbour *n;
1240 struct GNUNET_PeerIdentity peer;
1242 peer.hashPubKey = *key;
1243 n = find_neighbour (&peer);
1244 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1245 n->active_client_request_tail,
1253 * A client disconnected, clean up.
1255 * @param cls closure
1256 * @param client identification of the client
1259 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1262 struct Client *prev;
1266 #if DEBUG_CORE_CLIENT
1267 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1268 "Client %p has disconnected from core service.\n",
1275 if (client == pos->client_handle)
1282 /* client never sent INIT */
1286 clients = pos->next;
1288 prev->next = pos->next;
1289 if (pos->requests != NULL)
1291 GNUNET_CONTAINER_multihashmap_iterate (pos->requests,
1292 &destroy_active_client_request,
1294 GNUNET_CONTAINER_multihashmap_destroy (pos->requests);
1301 * Handle REQUEST_INFO request.
1304 handle_client_request_info (void *cls,
1305 struct GNUNET_SERVER_Client *client,
1306 const struct GNUNET_MessageHeader *message)
1308 const struct RequestInfoMessage *rcm;
1309 struct Neighbour *n;
1310 struct ConfigurationInfoMessage cim;
1311 int32_t want_reserv;
1313 unsigned long long old_preference;
1314 struct GNUNET_SERVER_TransmitContext *tc;
1316 #if DEBUG_CORE_CLIENT
1317 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1318 "Core service receives `%s' request.\n", "REQUEST_INFO");
1320 rcm = (const struct RequestInfoMessage *) message;
1321 n = find_neighbour (&rcm->peer);
1322 memset (&cim, 0, sizeof (cim));
1325 want_reserv = ntohl (rcm->reserve_inbound);
1326 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1328 n->bw_out_internal_limit = rcm->limit_outbound;
1329 if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1330 n->bw_out_external_limit).value__)
1332 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1333 n->bw_out_external_limit);
1334 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1336 GNUNET_TRANSPORT_set_quota (transport,
1340 GNUNET_TIME_UNIT_FOREVER_REL,
1342 handle_peer_status_change (n);
1345 if (want_reserv < 0)
1347 got_reserv = want_reserv;
1349 else if (want_reserv > 0)
1351 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1352 want_reserv).rel_value == 0)
1353 got_reserv = want_reserv;
1355 got_reserv = 0; /* all or nothing */
1359 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1361 old_preference = n->current_preference;
1362 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1363 if (old_preference > n->current_preference)
1365 /* overflow; cap at maximum value */
1366 n->current_preference = ULLONG_MAX;
1368 update_preference_sum (n->current_preference - old_preference);
1369 #if DEBUG_CORE_QUOTA
1370 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1371 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1373 GNUNET_i2s (&rcm->peer),
1376 cim.reserved_amount = htonl (got_reserv);
1377 cim.rim_id = rcm->rim_id;
1378 cim.bw_out = n->bw_out;
1379 cim.preference = n->current_preference;
1381 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1382 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1383 cim.peer = rcm->peer;
1385 #if DEBUG_CORE_CLIENT
1386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1387 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1389 tc = GNUNET_SERVER_transmit_context_create (client);
1390 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1391 GNUNET_SERVER_transmit_context_run (tc,
1392 GNUNET_TIME_UNIT_FOREVER_REL);
1397 * Free the given entry for the neighbour (it has
1398 * already been removed from the list at this point).
1400 * @param n neighbour to free
1403 free_neighbour (struct Neighbour *n)
1405 struct MessageEntry *m;
1406 struct ClientActiveRequest *car;
1409 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1410 "Destroying neighbour entry for peer `%4s'\n",
1411 GNUNET_i2s (&n->peer));
1413 if (n->pitr != NULL)
1415 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1420 GNUNET_free (n->skm);
1423 while (NULL != (m = n->messages))
1425 n->messages = m->next;
1428 while (NULL != (m = n->encrypted_head))
1430 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1435 while (NULL != (car = n->active_client_request_head))
1437 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1438 n->active_client_request_tail,
1440 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
1441 &n->peer.hashPubKey,
1447 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1450 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1451 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
1452 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1453 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
1454 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1455 GNUNET_SCHEDULER_cancel (n->quota_update_task);
1456 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1457 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1458 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1459 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
1460 if (n->status == PEER_STATE_KEY_CONFIRMED)
1461 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1462 GNUNET_free_non_null (n->public_key);
1463 GNUNET_free_non_null (n->pending_ping);
1464 GNUNET_free_non_null (n->pending_pong);
1470 * Check if we have encrypted messages for the specified neighbour
1471 * pending, and if so, check with the transport about sending them
1474 * @param n neighbour to check.
1476 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1480 * Encrypt size bytes from in and write the result to out. Use the
1481 * key for outbound traffic of the given neighbour.
1483 * @param n neighbour we are sending to
1484 * @param iv initialization vector to use
1485 * @param in ciphertext
1486 * @param out plaintext
1487 * @param size size of in/out
1488 * @return GNUNET_OK on success
1491 do_encrypt (struct Neighbour *n,
1492 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1493 const void *in, void *out, size_t size)
1495 if (size != (uint16_t) size)
1500 GNUNET_assert (size ==
1501 GNUNET_CRYPTO_aes_encrypt (in,
1505 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1507 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1508 "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
1509 (unsigned int) size,
1510 GNUNET_i2s (&n->peer),
1511 (unsigned int) n->encrypt_key.crc32,
1512 GNUNET_CRYPTO_crc32_n (iv, sizeof(iv)));
1519 * Consider freeing the given neighbour since we may not need
1520 * to keep it around anymore.
1522 * @param n neighbour to consider discarding
1525 consider_free_neighbour (struct Neighbour *n);
1529 * Task triggered when a neighbour entry is about to time out
1530 * (and we should prevent this by sending a PING).
1532 * @param cls the 'struct Neighbour'
1533 * @param tc scheduler context (not used)
1536 send_keep_alive (void *cls,
1537 const struct GNUNET_SCHEDULER_TaskContext *tc)
1539 struct Neighbour *n = cls;
1540 struct GNUNET_TIME_Relative retry;
1541 struct GNUNET_TIME_Relative left;
1542 struct MessageEntry *me;
1543 struct PingMessage pp;
1544 struct PingMessage *pm;
1545 struct GNUNET_CRYPTO_AesInitializationVector iv;
1547 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1549 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1550 sizeof (struct PingMessage));
1551 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1552 me->priority = PING_PRIORITY;
1553 me->size = sizeof (struct PingMessage);
1554 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1558 pm = (struct PingMessage *) &me[1];
1559 pm->header.size = htons (sizeof (struct PingMessage));
1560 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1561 pm->iv_seed = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1563 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
1564 pp.challenge = n->ping_challenge;
1565 pp.target = n->peer;
1567 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1568 "Encrypting `%s' message with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
1570 (unsigned int) n->ping_challenge,
1571 GNUNET_i2s (&n->peer),
1572 (unsigned int) n->encrypt_key.crc32,
1573 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
1580 sizeof (struct PingMessage) -
1581 ((void *) &pm->target - (void *) pm));
1582 process_encrypted_neighbour_queue (n);
1583 /* reschedule PING job */
1584 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1585 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1586 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1587 MIN_PING_FREQUENCY);
1589 = GNUNET_SCHEDULER_add_delayed (retry,
1597 * Task triggered when a neighbour entry might have gotten stale.
1599 * @param cls the 'struct Neighbour'
1600 * @param tc scheduler context (not used)
1603 consider_free_task (void *cls,
1604 const struct GNUNET_SCHEDULER_TaskContext *tc)
1606 struct Neighbour *n = cls;
1608 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1609 consider_free_neighbour (n);
1614 * Consider freeing the given neighbour since we may not need
1615 * to keep it around anymore.
1617 * @param n neighbour to consider discarding
1620 consider_free_neighbour (struct Neighbour *n)
1622 struct Neighbour *pos;
1623 struct Neighbour *prev;
1624 struct GNUNET_TIME_Relative left;
1626 if ( (n->th != NULL) ||
1627 (n->pitr != NULL) ||
1628 (GNUNET_YES == n->is_connected) )
1629 return; /* no chance */
1631 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1632 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1633 if (left.rel_value > 0)
1635 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1636 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1637 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (left,
1638 &consider_free_task,
1642 /* actually free the neighbour... */
1651 neighbours = n->next;
1653 prev->next = n->next;
1654 GNUNET_assert (neighbour_count > 0);
1656 GNUNET_STATISTICS_set (stats,
1657 gettext_noop ("# neighbour entries allocated"),
1665 * Function called when the transport service is ready to
1666 * receive an encrypted message for the respective peer
1668 * @param cls neighbour to use message from
1669 * @param size number of bytes we can transmit
1670 * @param buf where to copy the message
1671 * @return number of bytes transmitted
1674 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1676 struct Neighbour *n = cls;
1677 struct MessageEntry *m;
1682 m = n->encrypted_head;
1686 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1687 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1688 GNUNET_i2s (&n->peer));
1692 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1699 GNUNET_assert (size >= m->size);
1700 memcpy (cbuf, &m[1], m->size);
1702 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1705 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1706 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1707 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1709 GNUNET_i2s (&n->peer));
1711 process_encrypted_neighbour_queue (n);
1716 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1717 "Transmission of message of type %u and size %u failed\n",
1718 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1719 (unsigned int) m->size);
1723 consider_free_neighbour (n);
1729 * Check if we have plaintext messages for the specified neighbour
1730 * pending, and if so, consider batching and encrypting them (and
1731 * then trigger processing of the encrypted queue if needed).
1733 * @param n neighbour to check.
1735 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1739 * Check if we have encrypted messages for the specified neighbour
1740 * pending, and if so, check with the transport about sending them
1743 * @param n neighbour to check.
1746 process_encrypted_neighbour_queue (struct Neighbour *n)
1748 struct MessageEntry *m;
1751 return; /* request already pending */
1752 m = n->encrypted_head;
1755 /* encrypted queue empty, try plaintext instead */
1756 process_plaintext_neighbour_queue (n);
1760 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1761 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1762 (unsigned int) m->size,
1763 GNUNET_i2s (&n->peer),
1764 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).rel_value);
1767 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1770 GNUNET_TIME_absolute_get_remaining
1772 ¬ify_encrypted_transmit_ready,
1776 /* message request too large or duplicate request */
1778 /* discard encrypted message */
1779 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1783 process_encrypted_neighbour_queue (n);
1789 * Decrypt size bytes from in and write the result to out. Use the
1790 * key for inbound traffic of the given neighbour. This function does
1791 * NOT do any integrity-checks on the result.
1793 * @param n neighbour we are receiving from
1794 * @param iv initialization vector to use
1795 * @param in ciphertext
1796 * @param out plaintext
1797 * @param size size of in/out
1798 * @return GNUNET_OK on success
1801 do_decrypt (struct Neighbour *n,
1802 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1803 const void *in, void *out, size_t size)
1805 if (size != (uint16_t) size)
1810 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1811 (n->status != PEER_STATE_KEY_CONFIRMED))
1813 GNUNET_break_op (0);
1814 return GNUNET_SYSERR;
1817 GNUNET_CRYPTO_aes_decrypt (in,
1824 return GNUNET_SYSERR;
1826 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1829 "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
1830 (unsigned int) size,
1831 GNUNET_i2s (&n->peer),
1832 (unsigned int) n->decrypt_key.crc32,
1833 GNUNET_CRYPTO_crc32_n (iv, sizeof(*iv)));
1840 * Select messages for transmission. This heuristic uses a combination
1841 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1842 * and priority-based discard (in case no feasible schedule exist) and
1843 * speculative optimization (defer any kind of transmission until
1844 * we either create a batch of significant size, 25% of max, or until
1845 * we are close to a deadline). Furthermore, when scheduling the
1846 * heuristic also packs as many messages into the batch as possible,
1847 * starting with those with the earliest deadline. Yes, this is fun.
1849 * @param n neighbour to select messages from
1850 * @param size number of bytes to select for transmission
1851 * @param retry_time set to the time when we should try again
1852 * (only valid if this function returns zero)
1853 * @return number of bytes selected, or 0 if we decided to
1854 * defer scheduling overall; in that case, retry_time is set.
1857 select_messages (struct Neighbour *n,
1858 size_t size, struct GNUNET_TIME_Relative *retry_time)
1860 struct MessageEntry *pos;
1861 struct MessageEntry *min;
1862 struct MessageEntry *last;
1863 unsigned int min_prio;
1864 struct GNUNET_TIME_Absolute t;
1865 struct GNUNET_TIME_Absolute now;
1866 struct GNUNET_TIME_Relative delta;
1868 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1871 unsigned int queue_size;
1872 int discard_low_prio;
1874 GNUNET_assert (NULL != n->messages);
1875 now = GNUNET_TIME_absolute_get ();
1876 /* last entry in linked list of messages processed */
1878 /* should we remove the entry with the lowest
1879 priority from consideration for scheduling at the
1890 discard_low_prio = GNUNET_YES;
1891 while (GNUNET_YES == discard_low_prio)
1894 min_prio = UINT_MAX;
1895 discard_low_prio = GNUNET_NO;
1896 /* calculate number of bytes available for transmission at time "t" */
1897 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1899 /* how many bytes have we (hypothetically) scheduled so far */
1901 /* maximum time we can wait before transmitting anything
1902 and still make all of our deadlines */
1903 slack = GNUNET_TIME_UNIT_FOREVER_REL;
1905 /* note that we use "*2" here because we want to look
1906 a bit further into the future; much more makes no
1907 sense since new message might be scheduled in the
1909 while ((pos != NULL) && (off < size * 2))
1911 if (pos->do_transmit == GNUNET_YES)
1913 /* already removed from consideration */
1917 if (discard_low_prio == GNUNET_NO)
1919 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1920 if (delta.rel_value > 0)
1922 // FIXME: HUH? Check!
1924 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1927 if (avail < pos->size)
1929 // FIXME: HUH? Check!
1930 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1935 /* update slack, considering both its absolute deadline
1936 and relative deadlines caused by other messages
1937 with their respective load */
1938 slack = GNUNET_TIME_relative_min (slack,
1939 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1941 if (pos->deadline.abs_value <= now.abs_value)
1944 slack = GNUNET_TIME_UNIT_ZERO;
1946 else if (GNUNET_YES == pos->got_slack)
1948 /* should be soon now! */
1949 slack = GNUNET_TIME_relative_min (slack,
1950 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1955 GNUNET_TIME_relative_min (slack,
1956 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1957 pos->got_slack = GNUNET_YES;
1958 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1959 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
1964 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1965 if (pos->priority <= min_prio)
1967 /* update min for discard */
1968 min_prio = pos->priority;
1973 if (discard_low_prio)
1975 GNUNET_assert (min != NULL);
1976 /* remove lowest-priority entry from consideration */
1977 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1981 /* guard against sending "tiny" messages with large headers without
1983 if ( (slack.rel_value > GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value) &&
1985 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1987 /* less than 25% of message would be filled with deadlines still
1988 being met if we delay by one second or more; so just wait for
1989 more data; but do not wait longer than 1s (since we don't want
1990 to delay messages for a really long time either). */
1991 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1992 /* reset do_transmit values for next time */
1995 pos->do_transmit = GNUNET_NO;
1998 GNUNET_STATISTICS_update (stats,
1999 gettext_noop ("# transmissions delayed due to corking"),
2002 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2003 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
2004 (unsigned long long) retry_time->rel_value,
2006 (unsigned int) size);
2010 /* select marked messages (up to size) for transmission */
2015 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
2017 pos->do_transmit = GNUNET_YES; /* mark for transmission */
2021 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2022 "Selecting message of size %u for transmission\n",
2023 (unsigned int) pos->size);
2029 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2030 "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
2031 (unsigned int) pos->size,
2034 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
2039 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2040 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
2041 (unsigned long long) off, (unsigned long long) tsize,
2042 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
2043 GNUNET_i2s (&n->peer));
2050 * Batch multiple messages into a larger buffer.
2052 * @param n neighbour to take messages from
2053 * @param buf target buffer
2054 * @param size size of buf
2055 * @param deadline set to transmission deadline for the result
2056 * @param retry_time set to the time when we should try again
2057 * (only valid if this function returns zero)
2058 * @param priority set to the priority of the batch
2059 * @return number of bytes written to buf (can be zero)
2062 batch_message (struct Neighbour *n,
2065 struct GNUNET_TIME_Absolute *deadline,
2066 struct GNUNET_TIME_Relative *retry_time,
2067 unsigned int *priority)
2069 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
2070 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
2071 struct MessageEntry *pos;
2072 struct MessageEntry *prev;
2073 struct MessageEntry *next;
2078 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2079 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
2080 if (0 == select_messages (n, size, retry_time))
2083 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2084 "No messages selected, will try again in %llu ms\n",
2085 retry_time->rel_value);
2089 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
2090 ntm->peer = n->peer;
2093 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
2096 if (GNUNET_YES == pos->do_transmit)
2098 GNUNET_assert (pos->size <= size);
2099 /* do notifications */
2100 /* FIXME: track if we have *any* client that wants
2101 full notifications and only do this if that is
2103 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
2105 memcpy (&ntm[1], &pos[1], pos->size);
2106 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
2107 sizeof (struct GNUNET_MessageHeader));
2108 send_to_all_clients (&ntm->header,
2110 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
2114 /* message too large for 'full' notifications, we do at
2115 least the 'hdr' type */
2118 sizeof (struct GNUNET_MessageHeader));
2120 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
2122 send_to_all_clients (&ntm->header,
2124 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
2126 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2127 "Encrypting %u bytes with message of type %u and size %u\n",
2129 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
2130 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
2132 /* copy for encrypted transmission */
2133 memcpy (&buf[ret], &pos[1], pos->size);
2136 *priority += pos->priority;
2138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2139 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
2140 (unsigned int) pos->size,
2141 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).rel_value);
2143 deadline->abs_value = GNUNET_MIN (deadline->abs_value, pos->deadline.abs_value);
2157 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2158 "Deadline for message batch is %llu ms\n",
2159 GNUNET_TIME_absolute_get_remaining (*deadline).rel_value);
2166 * Remove messages with deadlines that have long expired from
2169 * @param n neighbour to inspect
2172 discard_expired_messages (struct Neighbour *n)
2174 struct MessageEntry *prev;
2175 struct MessageEntry *next;
2176 struct MessageEntry *pos;
2177 struct GNUNET_TIME_Absolute now;
2178 struct GNUNET_TIME_Relative delta;
2182 now = GNUNET_TIME_absolute_get ();
2188 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
2189 if (delta.rel_value > PAST_EXPIRATION_DISCARD_TIME.rel_value)
2192 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2193 "Message is %llu ms past due, discarding.\n",
2200 GNUNET_STATISTICS_update (stats,
2201 gettext_noop ("# messages discarded (expired prior to transmission)"),
2211 if (GNUNET_YES == disc)
2212 schedule_peer_messages (n);
2217 * Signature of the main function of a task.
2219 * @param cls closure
2220 * @param tc context information (why was this task triggered now)
2223 retry_plaintext_processing (void *cls,
2224 const struct GNUNET_SCHEDULER_TaskContext *tc)
2226 struct Neighbour *n = cls;
2228 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2229 process_plaintext_neighbour_queue (n);
2234 * Send our key (and encrypted PING) to the other peer.
2236 * @param n the other peer
2238 static void send_key (struct Neighbour *n);
2241 * Task that will retry "send_key" if our previous attempt failed
2245 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2247 struct Neighbour *n = cls;
2250 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2251 "Retrying key transmission to `%4s'\n",
2252 GNUNET_i2s (&n->peer));
2254 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2255 n->set_key_retry_frequency =
2256 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2262 * Check if we have plaintext messages for the specified neighbour
2263 * pending, and if so, consider batching and encrypting them (and
2264 * then trigger processing of the encrypted queue if needed).
2266 * @param n neighbour to check.
2269 process_plaintext_neighbour_queue (struct Neighbour *n)
2271 char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)]; /* plaintext */
2273 struct EncryptedMessage *em; /* encrypted message */
2274 struct EncryptedMessage *ph; /* plaintext header */
2275 struct MessageEntry *me;
2276 unsigned int priority;
2277 struct GNUNET_TIME_Absolute deadline;
2278 struct GNUNET_TIME_Relative retry_time;
2279 struct GNUNET_CRYPTO_AesInitializationVector iv;
2280 struct GNUNET_CRYPTO_AuthKey auth_key;
2282 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2284 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
2285 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2289 case PEER_STATE_DOWN:
2292 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2293 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2294 GNUNET_i2s(&n->peer));
2297 case PEER_STATE_KEY_SENT:
2298 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2299 n->retry_set_key_task
2300 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2301 &set_key_retry_task, n);
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_RECEIVED:
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_CONFIRMED:
2320 /* ready to continue */
2323 discard_expired_messages (n);
2324 if (n->messages == NULL)
2327 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2328 "Plaintext message queue for `%4s' is empty.\n",
2329 GNUNET_i2s(&n->peer));
2331 return; /* no pending messages */
2333 if (n->encrypted_head != NULL)
2336 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2337 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2338 GNUNET_i2s(&n->peer));
2340 return; /* wait for messages already encrypted to be
2343 ph = (struct EncryptedMessage *) pbuf;
2344 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2346 used = sizeof (struct EncryptedMessage);
2347 used += batch_message (n,
2349 GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2350 &deadline, &retry_time, &priority);
2351 if (used == sizeof (struct EncryptedMessage))
2354 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2355 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2356 GNUNET_i2s(&n->peer));
2358 /* no messages selected for sending, try again later... */
2359 n->retry_plaintext_task =
2360 GNUNET_SCHEDULER_add_delayed (retry_time,
2361 &retry_plaintext_processing, n);
2364 #if DEBUG_CORE_QUOTA
2365 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2366 "Sending %u b/s as new limit to peer `%4s'\n",
2367 (unsigned int) ntohl (n->bw_in.value__),
2368 GNUNET_i2s (&n->peer));
2370 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
2371 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2372 ph->inbound_bw_limit = n->bw_in;
2373 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2375 /* setup encryption message header */
2376 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2377 me->deadline = deadline;
2378 me->priority = priority;
2380 em = (struct EncryptedMessage *) &me[1];
2381 em->header.size = htons (used);
2382 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2383 em->iv_seed = ph->iv_seed;
2384 derive_iv (&iv, &n->encrypt_key, ph->iv_seed, &n->peer);
2387 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2388 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2389 (unsigned int) used - ENCRYPTED_HEADER_SIZE,
2390 GNUNET_i2s(&n->peer),
2391 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).rel_value);
2393 GNUNET_assert (GNUNET_OK ==
2396 &ph->sequence_number,
2397 &em->sequence_number, used - ENCRYPTED_HEADER_SIZE));
2398 derive_auth_key (&auth_key,
2401 n->encrypt_key_created);
2402 GNUNET_CRYPTO_hmac (&auth_key,
2403 &em->sequence_number,
2404 used - ENCRYPTED_HEADER_SIZE,
2407 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2408 "Authenticated %u bytes of ciphertext %u: `%s'\n",
2409 used - ENCRYPTED_HEADER_SIZE,
2410 GNUNET_CRYPTO_crc32_n (&em->sequence_number,
2411 used - ENCRYPTED_HEADER_SIZE),
2412 GNUNET_h2s (&em->hmac));
2414 /* append to transmission list */
2415 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2419 process_encrypted_neighbour_queue (n);
2420 schedule_peer_messages (n);
2425 * Function that recalculates the bandwidth quota for the
2426 * given neighbour and transmits it to the transport service.
2428 * @param cls neighbour for the quota update
2432 neighbour_quota_update (void *cls,
2433 const struct GNUNET_SCHEDULER_TaskContext *tc);
2437 * Schedule the task that will recalculate the bandwidth
2438 * quota for this peer (and possibly force a disconnect of
2439 * idle peers by calculating a bandwidth of zero).
2442 schedule_quota_update (struct Neighbour *n)
2444 GNUNET_assert (n->quota_update_task ==
2445 GNUNET_SCHEDULER_NO_TASK);
2446 n->quota_update_task
2447 = GNUNET_SCHEDULER_add_delayed (QUOTA_UPDATE_FREQUENCY,
2448 &neighbour_quota_update,
2454 * Initialize a new 'struct Neighbour'.
2456 * @param pid ID of the new neighbour
2457 * @return handle for the new neighbour
2459 static struct Neighbour *
2460 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2462 struct Neighbour *n;
2463 struct GNUNET_TIME_Absolute now;
2466 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2467 "Creating neighbour entry for peer `%4s'\n",
2470 n = GNUNET_malloc (sizeof (struct Neighbour));
2471 n->next = neighbours;
2474 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2476 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2477 now = GNUNET_TIME_absolute_get ();
2478 n->encrypt_key_created = now;
2479 n->last_activity = now;
2480 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2481 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2482 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2483 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2484 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2485 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
2487 neighbour_quota_update (n, NULL);
2488 consider_free_neighbour (n);
2494 * Handle CORE_SEND request.
2497 * @param client the client issuing the request
2498 * @param message the "struct SendMessage"
2501 handle_client_send (void *cls,
2502 struct GNUNET_SERVER_Client *client,
2503 const struct GNUNET_MessageHeader *message)
2505 const struct SendMessage *sm;
2506 struct Neighbour *n;
2507 struct MessageEntry *prev;
2508 struct MessageEntry *pos;
2509 struct MessageEntry *e;
2510 struct MessageEntry *min_prio_entry;
2511 struct MessageEntry *min_prio_prev;
2512 unsigned int min_prio;
2513 unsigned int queue_size;
2516 msize = ntohs (message->size);
2518 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2520 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));
2523 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2526 sm = (const struct SendMessage *) message;
2527 msize -= sizeof (struct SendMessage);
2528 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2530 /* FIXME: should we not allow loopback-injection here? */
2533 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2536 n = find_neighbour (&sm->peer);
2538 n = create_neighbour (&sm->peer);
2540 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2541 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2543 (unsigned int) msize,
2544 GNUNET_i2s (&sm->peer));
2546 discard_expired_messages (n);
2547 /* bound queue size */
2548 /* NOTE: this entire block to bound the queue size should be
2549 obsolete with the new client-request code and the
2550 'schedule_peer_messages' mechanism; we still have this code in
2551 here for now as a sanity check for the new mechanmism;
2552 ultimately, we should probably simply reject SEND messages that
2553 are not 'approved' (or provide a new core API for very unreliable
2554 delivery that always sends with priority 0). Food for thought. */
2555 min_prio = UINT32_MAX;
2556 min_prio_entry = NULL;
2557 min_prio_prev = NULL;
2563 if (pos->priority <= min_prio)
2565 min_prio_entry = pos;
2566 min_prio_prev = prev;
2567 min_prio = pos->priority;
2573 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2576 if (ntohl(sm->priority) <= min_prio)
2578 /* discard new entry; this should no longer happen! */
2581 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2582 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2584 (unsigned int) MAX_PEER_QUEUE_SIZE,
2585 (unsigned int) msize,
2586 (unsigned int) ntohs (message->type));
2588 GNUNET_STATISTICS_update (stats,
2589 gettext_noop ("# discarded CORE_SEND requests"),
2593 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2596 GNUNET_assert (min_prio_entry != NULL);
2597 /* discard "min_prio_entry" */
2599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2600 "Queue full, discarding existing older request\n");
2602 GNUNET_STATISTICS_update (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 1, GNUNET_NO);
2603 if (min_prio_prev == NULL)
2604 n->messages = min_prio_entry->next;
2606 min_prio_prev->next = min_prio_entry->next;
2607 GNUNET_free (min_prio_entry);
2611 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2612 "Adding transmission request for `%4s' of size %u to queue\n",
2613 GNUNET_i2s (&sm->peer),
2614 (unsigned int) msize);
2616 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2617 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2618 e->priority = ntohl (sm->priority);
2620 memcpy (&e[1], &sm[1], msize);
2622 /* insert, keep list sorted by deadline */
2625 while ((pos != NULL) && (pos->deadline.abs_value < e->deadline.abs_value))
2636 /* consider scheduling now */
2637 process_plaintext_neighbour_queue (n);
2639 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2644 * Function called when the transport service is ready to
2645 * receive a message. Only resets 'n->th' to NULL.
2647 * @param cls neighbour to use message from
2648 * @param size number of bytes we can transmit
2649 * @param buf where to copy the message
2650 * @return number of bytes transmitted
2653 notify_transport_connect_done (void *cls, size_t size, void *buf)
2655 struct Neighbour *n = cls;
2657 if (GNUNET_YES != n->is_connected)
2659 /* transport should only call us to transmit a message after
2660 * telling us about a successful connection to the respective peer */
2661 n->th = NULL; /* If this happens because of a timeout, reset n-th so another message may be sent for this peer! */
2663 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Timeout on notify connect!\n");
2670 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2671 _("Failed to connect to `%4s': transport failed to connect\n"),
2672 GNUNET_i2s (&n->peer));
2675 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2676 _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2677 GNUNET_i2s (&n->peer));
2678 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2679 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2680 n->retry_set_key_task = GNUNET_SCHEDULER_add_now (&set_key_retry_task,
2687 * Handle CORE_REQUEST_CONNECT request.
2690 * @param client the client issuing the request
2691 * @param message the "struct ConnectMessage"
2694 handle_client_request_connect (void *cls,
2695 struct GNUNET_SERVER_Client *client,
2696 const struct GNUNET_MessageHeader *message)
2698 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2699 struct Neighbour *n;
2700 struct GNUNET_TIME_Relative timeout;
2702 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2705 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2708 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2709 n = find_neighbour (&cm->peer);
2711 n = create_neighbour (&cm->peer);
2712 if ( (GNUNET_YES == n->is_connected) ||
2715 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2716 "Core received `%s' request for `%4s', already connected!\n",
2718 GNUNET_i2s (&cm->peer));
2719 return; /* already connected, or at least trying */
2721 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2723 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2724 "Core received `%s' request for `%4s', will try to establish connection\n",
2726 GNUNET_i2s (&cm->peer));
2728 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2729 /* ask transport to connect to the peer */
2730 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2732 sizeof (struct GNUNET_MessageHeader), 0,
2734 ¬ify_transport_connect_done,
2736 GNUNET_break (NULL != n->th);
2741 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2742 * the neighbour's struct and retry send_key. Or, if we did not get a
2743 * HELLO, just do nothing.
2745 * @param cls the 'struct Neighbour' to retry sending the key for
2746 * @param peer the peer for which this is the HELLO
2747 * @param hello HELLO message of that peer
2750 process_hello_retry_send_key (void *cls,
2751 const struct GNUNET_PeerIdentity *peer,
2752 const struct GNUNET_HELLO_Message *hello)
2754 struct Neighbour *n = cls;
2759 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2760 "Entered `%s' and `%s' is NULL!\n",
2761 "process_hello_retry_send_key",
2765 if (n->public_key != NULL)
2767 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2769 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2770 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2772 GNUNET_STATISTICS_update (stats,
2773 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2781 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2782 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
2783 GNUNET_i2s (&n->peer));
2785 GNUNET_STATISTICS_update (stats,
2786 gettext_noop ("# Delayed connecting due to lack of public key"),
2789 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2790 n->retry_set_key_task
2791 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2792 &set_key_retry_task, n);
2798 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2799 "Entered `%s' for peer `%4s'\n",
2800 "process_hello_retry_send_key",
2803 if (n->public_key != NULL)
2805 /* already have public key, why are we here? */
2811 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2812 "Received new `%s' message for `%4s', initiating key exchange.\n",
2817 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2818 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2820 GNUNET_STATISTICS_update (stats,
2821 gettext_noop ("# Error extracting public key from HELLO"),
2824 GNUNET_free (n->public_key);
2825 n->public_key = NULL;
2827 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2828 "GNUNET_HELLO_get_key returned awfully\n");
2836 * Send our key (and encrypted PING) to the other peer.
2838 * @param n the other peer
2841 send_key (struct Neighbour *n)
2843 struct MessageEntry *pos;
2844 struct SetKeyMessage *sm;
2845 struct MessageEntry *me;
2846 struct PingMessage pp;
2847 struct PingMessage *pm;
2848 struct GNUNET_CRYPTO_AesInitializationVector iv;
2850 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2852 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2853 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2855 if (n->pitr != NULL)
2858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2859 "Key exchange in progress with `%4s'.\n",
2860 GNUNET_i2s (&n->peer));
2862 return; /* already in progress */
2864 if (GNUNET_YES != n->is_connected)
2867 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2868 "Not yet connected to peer `%4s'!\n",
2869 GNUNET_i2s (&n->peer));
2873 GNUNET_STATISTICS_update (stats,
2874 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
2877 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2879 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2881 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2882 ¬ify_encrypted_transmit_ready,
2888 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2889 "Asked to perform key exchange with `%4s'.\n",
2890 GNUNET_i2s (&n->peer));
2892 if (n->public_key == NULL)
2894 /* lookup n's public key, then try again */
2896 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2897 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2898 GNUNET_i2s (&n->peer));
2900 GNUNET_assert (n->pitr == NULL);
2901 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2903 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2904 &process_hello_retry_send_key, n);
2907 pos = n->encrypted_head;
2910 if (GNUNET_YES == pos->is_setkey)
2912 if (pos->sender_status == n->status)
2915 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2916 "`%s' message for `%4s' queued already\n",
2918 GNUNET_i2s (&n->peer));
2920 goto trigger_processing;
2922 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2927 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2928 "Removing queued `%s' message for `%4s', will create a new one\n",
2930 GNUNET_i2s (&n->peer));
2940 case PEER_STATE_DOWN:
2941 n->status = PEER_STATE_KEY_SENT;
2943 case PEER_STATE_KEY_SENT:
2945 case PEER_STATE_KEY_RECEIVED:
2947 case PEER_STATE_KEY_CONFIRMED:
2955 /* first, set key message */
2956 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2957 sizeof (struct SetKeyMessage) +
2958 sizeof (struct PingMessage));
2959 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2960 me->priority = SET_KEY_PRIORITY;
2961 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
2962 me->is_setkey = GNUNET_YES;
2963 me->got_slack = GNUNET_YES; /* do not defer this one! */
2964 me->sender_status = n->status;
2965 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2969 sm = (struct SetKeyMessage *) &me[1];
2970 sm->header.size = htons (sizeof (struct SetKeyMessage));
2971 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2972 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2973 PEER_STATE_KEY_SENT : n->status));
2975 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2976 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2977 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2978 sizeof (struct GNUNET_PeerIdentity));
2979 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2980 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2981 sm->target = n->peer;
2982 GNUNET_assert (GNUNET_OK ==
2983 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2985 GNUNET_CRYPTO_AesSessionKey),
2987 &sm->encrypted_key));
2988 GNUNET_assert (GNUNET_OK ==
2989 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2991 pm = (struct PingMessage *) &sm[1];
2992 pm->header.size = htons (sizeof (struct PingMessage));
2993 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2994 pm->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2995 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
2996 pp.challenge = n->ping_challenge;
2997 pp.target = n->peer;
2999 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3000 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
3002 (unsigned int) n->ping_challenge,
3003 GNUNET_i2s (&n->peer),
3004 (unsigned int) n->encrypt_key.crc32,
3005 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3012 sizeof (struct PingMessage) -
3013 ((void *) &pm->target - (void *) pm));
3014 GNUNET_STATISTICS_update (stats,
3015 gettext_noop ("# SET_KEY and PING messages created"),
3019 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3020 "Have %llu ms left for `%s' transmission.\n",
3021 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).rel_value,
3025 /* trigger queue processing */
3026 process_encrypted_neighbour_queue (n);
3027 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
3028 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
3029 n->retry_set_key_task
3030 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3031 &set_key_retry_task, n);
3036 * We received a SET_KEY message. Validate and update
3037 * our key material and status.
3039 * @param n the neighbour from which we received message m
3040 * @param m the set key message we received
3043 handle_set_key (struct Neighbour *n,
3044 const struct SetKeyMessage *m);
3048 * PEERINFO is giving us a HELLO for a peer. Add the public key to
3049 * the neighbour's struct and retry handling the set_key message. Or,
3050 * if we did not get a HELLO, just free the set key message.
3052 * @param cls pointer to the set key message
3053 * @param peer the peer for which this is the HELLO
3054 * @param hello HELLO message of that peer
3057 process_hello_retry_handle_set_key (void *cls,
3058 const struct GNUNET_PeerIdentity *peer,
3059 const struct GNUNET_HELLO_Message *hello)
3061 struct Neighbour *n = cls;
3062 struct SetKeyMessage *sm = n->skm;
3068 if (n->public_key != NULL)
3071 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3072 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
3074 GNUNET_i2s (&n->peer),
3077 handle_set_key (n, sm);
3081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3082 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
3084 GNUNET_i2s (&n->peer));
3089 if (n->public_key != NULL)
3090 return; /* multiple HELLOs match!? */
3092 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3093 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3095 GNUNET_break_op (0);
3096 GNUNET_free (n->public_key);
3097 n->public_key = NULL;
3103 * We received a PING message. Validate and transmit
3106 * @param n sender of the PING
3107 * @param m the encrypted PING message itself
3110 handle_ping (struct Neighbour *n, const struct PingMessage *m)
3112 struct PingMessage t;
3113 struct PongMessage tx;
3114 struct PongMessage *tp;
3115 struct MessageEntry *me;
3116 struct GNUNET_CRYPTO_AesInitializationVector iv;
3119 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3120 "Core service receives `%s' request from `%4s'.\n",
3121 "PING", GNUNET_i2s (&n->peer));
3123 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3129 sizeof (struct PingMessage) -
3130 ((void *) &m->target - (void *) m)))
3133 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3134 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u, IV %u (salt %u)\n",
3136 GNUNET_i2s (&t.target),
3137 (unsigned int) t.challenge,
3138 (unsigned int) n->decrypt_key.crc32,
3139 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3142 GNUNET_STATISTICS_update (stats,
3143 gettext_noop ("# PING messages decrypted"),
3146 if (0 != memcmp (&t.target,
3147 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3149 GNUNET_break_op (0);
3152 me = GNUNET_malloc (sizeof (struct MessageEntry) +
3153 sizeof (struct PongMessage));
3154 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3158 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
3159 me->priority = PONG_PRIORITY;
3160 me->size = sizeof (struct PongMessage);
3161 tx.inbound_bw_limit = n->bw_in;
3162 tx.challenge = t.challenge;
3163 tx.target = t.target;
3164 tp = (struct PongMessage *) &me[1];
3165 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
3166 tp->header.size = htons (sizeof (struct PongMessage));
3167 tp->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3168 derive_pong_iv (&iv, &n->encrypt_key, tp->iv_seed, t.challenge, &n->peer);
3173 sizeof (struct PongMessage) -
3174 ((void *) &tp->challenge - (void *) tp));
3175 GNUNET_STATISTICS_update (stats,
3176 gettext_noop ("# PONG messages created"),
3180 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3181 "Encrypting `%s' with challenge %u using key %u, IV %u (salt %u)\n",
3183 (unsigned int) t.challenge,
3184 (unsigned int) n->encrypt_key.crc32,
3185 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3188 /* trigger queue processing */
3189 process_encrypted_neighbour_queue (n);
3194 * We received a PONG message. Validate and update our status.
3196 * @param n sender of the PONG
3197 * @param m the encrypted PONG message itself
3200 handle_pong (struct Neighbour *n,
3201 const struct PongMessage *m)
3203 struct PongMessage t;
3204 struct ConnectNotifyMessage cnm;
3205 struct GNUNET_CRYPTO_AesInitializationVector iv;
3208 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3209 "Core service receives `%s' response from `%4s'.\n",
3210 "PONG", GNUNET_i2s (&n->peer));
3212 /* mark as garbage, just to be sure */
3213 memset (&t, 255, sizeof (t));
3214 derive_pong_iv (&iv, &n->decrypt_key, m->iv_seed, n->ping_challenge,
3221 sizeof (struct PongMessage) -
3222 ((void *) &m->challenge - (void *) m)))
3224 GNUNET_break_op (0);
3227 GNUNET_STATISTICS_update (stats,
3228 gettext_noop ("# PONG messages decrypted"),
3232 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3233 "Decrypted `%s' from `%4s' with challenge %u using key %u, IV %u (salt %u)\n",
3235 GNUNET_i2s (&t.target),
3236 (unsigned int) t.challenge,
3237 (unsigned int) n->decrypt_key.crc32,
3238 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3241 if ((0 != memcmp (&t.target,
3243 sizeof (struct GNUNET_PeerIdentity))) ||
3244 (n->ping_challenge != t.challenge))
3246 /* PONG malformed */
3248 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3249 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
3251 GNUNET_i2s (&n->peer),
3252 (unsigned int) n->ping_challenge);
3253 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3254 "Received malformed `%s' received from `%4s' with challenge %u\n",
3255 "PONG", GNUNET_i2s (&t.target),
3256 (unsigned int) t.challenge);
3258 GNUNET_break_op (0);
3263 case PEER_STATE_DOWN:
3264 GNUNET_break (0); /* should be impossible */
3266 case PEER_STATE_KEY_SENT:
3267 GNUNET_break (0); /* should be impossible, how did we decrypt? */
3269 case PEER_STATE_KEY_RECEIVED:
3270 GNUNET_STATISTICS_update (stats,
3271 gettext_noop ("# Session keys confirmed via PONG"),
3274 n->status = PEER_STATE_KEY_CONFIRMED;
3275 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
3277 n->bw_out_external_limit = t.inbound_bw_limit;
3278 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3279 n->bw_out_internal_limit);
3280 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3282 GNUNET_TRANSPORT_set_quota (transport,
3286 GNUNET_TIME_UNIT_FOREVER_REL,
3290 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3291 "Confirmed key via `%s' message for peer `%4s'\n",
3292 "PONG", GNUNET_i2s (&n->peer));
3294 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3296 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3297 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3299 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3300 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3302 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
3303 process_encrypted_neighbour_queue (n);
3305 case PEER_STATE_KEY_CONFIRMED:
3306 n->last_activity = GNUNET_TIME_absolute_get ();
3307 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3308 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3310 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3313 handle_peer_status_change (n);
3323 * We received a SET_KEY message. Validate and update
3324 * our key material and status.
3326 * @param n the neighbour from which we received message m
3327 * @param m the set key message we received
3330 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
3332 struct SetKeyMessage *m_cpy;
3333 struct GNUNET_TIME_Absolute t;
3334 struct GNUNET_CRYPTO_AesSessionKey k;
3335 struct PingMessage *ping;
3336 struct PongMessage *pong;
3337 enum PeerStateMachine sender_status;
3340 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3341 "Core service receives `%s' request from `%4s'.\n",
3342 "SET_KEY", GNUNET_i2s (&n->peer));
3344 if (n->public_key == NULL)
3346 if (n->pitr != NULL)
3349 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3350 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3356 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3357 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3359 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3360 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3361 /* lookup n's public key, then try again */
3362 GNUNET_assert (n->skm == NULL);
3364 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3366 GNUNET_TIME_UNIT_MINUTES,
3367 &process_hello_retry_handle_set_key, n);
3368 GNUNET_STATISTICS_update (stats,
3369 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3374 if (0 != memcmp (&m->target,
3376 sizeof (struct GNUNET_PeerIdentity)))
3378 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3379 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3381 GNUNET_i2s (&m->target));
3384 if ((ntohl (m->purpose.size) !=
3385 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3386 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3387 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3388 sizeof (struct GNUNET_PeerIdentity)) ||
3390 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3391 &m->purpose, &m->signature, n->public_key)))
3393 /* invalid signature */
3394 GNUNET_break_op (0);
3397 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3398 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3399 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3400 (t.abs_value < n->decrypt_key_created.abs_value))
3402 /* this could rarely happen due to massive re-ordering of
3403 messages on the network level, but is most likely either
3404 a bug or some adversary messing with us. Report. */
3405 GNUNET_break_op (0);
3409 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3410 "Decrypting key material.\n");
3412 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3415 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3416 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3417 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3419 /* failed to decrypt !? */
3420 GNUNET_break_op (0);
3423 GNUNET_STATISTICS_update (stats,
3424 gettext_noop ("# SET_KEY messages decrypted"),
3428 if (n->decrypt_key_created.abs_value != t.abs_value)
3430 /* fresh key, reset sequence numbers */
3431 n->last_sequence_number_received = 0;
3432 n->last_packets_bitmap = 0;
3433 n->decrypt_key_created = t;
3435 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3438 case PEER_STATE_DOWN:
3439 n->status = PEER_STATE_KEY_RECEIVED;
3441 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3442 "Responding to `%s' with my own key.\n", "SET_KEY");
3446 case PEER_STATE_KEY_SENT:
3447 case PEER_STATE_KEY_RECEIVED:
3448 n->status = PEER_STATE_KEY_RECEIVED;
3449 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3450 (sender_status != PEER_STATE_KEY_CONFIRMED))
3453 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3454 "Responding to `%s' with my own key (other peer has status %u).\n",
3456 (unsigned int) sender_status);
3461 case PEER_STATE_KEY_CONFIRMED:
3462 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3463 (sender_status != PEER_STATE_KEY_CONFIRMED))
3466 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3467 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3469 (unsigned int) sender_status);
3478 if (n->pending_ping != NULL)
3480 ping = n->pending_ping;
3481 n->pending_ping = NULL;
3482 handle_ping (n, ping);
3485 if (n->pending_pong != NULL)
3487 pong = n->pending_pong;
3488 n->pending_pong = NULL;
3489 handle_pong (n, pong);
3496 * Send a P2P message to a client.
3498 * @param sender who sent us the message?
3499 * @param client who should we give the message to?
3500 * @param m contains the message to transmit
3501 * @param msize number of bytes in buf to transmit
3504 send_p2p_message_to_client (struct Neighbour *sender,
3505 struct Client *client,
3506 const void *m, size_t msize)
3508 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3509 struct NotifyTrafficMessage *ntm;
3512 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3513 "Core service passes message from `%4s' of type %u to client.\n",
3514 GNUNET_i2s(&sender->peer),
3515 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3517 ntm = (struct NotifyTrafficMessage *) buf;
3518 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3519 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3520 ntm->peer = sender->peer;
3521 memcpy (&ntm[1], m, msize);
3522 send_to_client (client, &ntm->header, GNUNET_YES);
3527 * Deliver P2P message to interested clients.
3529 * @param cls always NULL
3530 * @param client who sent us the message (struct Neighbour)
3531 * @param m the message
3534 deliver_message (void *cls,
3536 const struct GNUNET_MessageHeader *m)
3538 struct Neighbour *sender = client;
3539 size_t msize = ntohs (m->size);
3541 struct Client *cpos;
3547 type = ntohs (m->type);
3549 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3550 "Received encapsulated message of type %u and size %u from `%4s'\n",
3551 (unsigned int) type,
3553 GNUNET_i2s (&sender->peer));
3555 GNUNET_snprintf (buf,
3557 gettext_noop ("# bytes of messages of type %u received"),
3558 (unsigned int) type);
3559 GNUNET_STATISTICS_set (stats,
3563 dropped = GNUNET_YES;
3565 while (cpos != NULL)
3567 deliver_full = GNUNET_NO;
3568 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3569 deliver_full = GNUNET_YES;
3572 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3574 if (type != cpos->types[tpos])
3576 deliver_full = GNUNET_YES;
3580 if (GNUNET_YES == deliver_full)
3582 send_p2p_message_to_client (sender, cpos, m, msize);
3583 dropped = GNUNET_NO;
3585 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3587 send_p2p_message_to_client (sender, cpos, m,
3588 sizeof (struct GNUNET_MessageHeader));
3592 if (dropped == GNUNET_YES)
3595 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3596 "Message of type %u from `%4s' not delivered to any client.\n",
3597 (unsigned int) type,
3598 GNUNET_i2s (&sender->peer));
3600 GNUNET_STATISTICS_update (stats,
3601 gettext_noop ("# messages not delivered to any client"),
3608 * We received an encrypted message. Decrypt, validate and
3609 * pass on to the appropriate clients.
3612 handle_encrypted_message (struct Neighbour *n,
3613 const struct EncryptedMessage *m)
3615 size_t size = ntohs (m->header.size);
3617 struct EncryptedMessage *pt; /* plaintext */
3620 struct GNUNET_TIME_Absolute t;
3621 struct GNUNET_CRYPTO_AesInitializationVector iv;
3622 struct GNUNET_CRYPTO_AuthKey auth_key;
3625 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3626 "Core service receives `%s' request from `%4s'.\n",
3627 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3630 derive_auth_key (&auth_key,
3633 n->decrypt_key_created);
3634 GNUNET_CRYPTO_hmac (&auth_key,
3635 &m->sequence_number,
3636 size - ENCRYPTED_HEADER_SIZE, &ph);
3638 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3639 "Re-Authenticated %u bytes of ciphertext (`%u'): `%s'\n",
3640 (unsigned int) size - ENCRYPTED_HEADER_SIZE,
3641 GNUNET_CRYPTO_crc32_n (&m->sequence_number,
3642 size - ENCRYPTED_HEADER_SIZE),
3646 if (0 != memcmp (&ph,
3648 sizeof (GNUNET_HashCode)))
3650 /* checksum failed */
3651 GNUNET_break_op (0);
3654 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3659 &m->sequence_number,
3660 &buf[ENCRYPTED_HEADER_SIZE],
3661 size - ENCRYPTED_HEADER_SIZE))
3663 pt = (struct EncryptedMessage *) buf;
3665 /* validate sequence number */
3666 snum = ntohl (pt->sequence_number);
3667 if (n->last_sequence_number_received == snum)
3669 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3670 "Received duplicate message, ignoring.\n");
3671 /* duplicate, ignore */
3672 GNUNET_STATISTICS_set (stats,
3673 gettext_noop ("# bytes dropped (duplicates)"),
3678 if ((n->last_sequence_number_received > snum) &&
3679 (n->last_sequence_number_received - snum > 32))
3681 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3682 "Received ancient out of sequence message, ignoring.\n");
3683 /* ancient out of sequence, ignore */
3684 GNUNET_STATISTICS_set (stats,
3685 gettext_noop ("# bytes dropped (out of sequence)"),
3690 if (n->last_sequence_number_received > snum)
3692 unsigned int rotbit =
3693 1 << (n->last_sequence_number_received - snum - 1);
3694 if ((n->last_packets_bitmap & rotbit) != 0)
3696 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3697 "Received duplicate message, ignoring.\n");
3698 GNUNET_STATISTICS_set (stats,
3699 gettext_noop ("# bytes dropped (duplicates)"),
3702 /* duplicate, ignore */
3705 n->last_packets_bitmap |= rotbit;
3707 if (n->last_sequence_number_received < snum)
3709 int shift = (snum - n->last_sequence_number_received);
3710 if (shift >= 8 * sizeof(n->last_packets_bitmap))
3711 n->last_packets_bitmap = 0;
3713 n->last_packets_bitmap <<= shift;
3714 n->last_sequence_number_received = snum;
3717 /* check timestamp */
3718 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3719 if (GNUNET_TIME_absolute_get_duration (t).rel_value > MAX_MESSAGE_AGE.rel_value)
3721 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3723 ("Message received far too old (%llu ms). Content ignored.\n"),
3724 GNUNET_TIME_absolute_get_duration (t).rel_value);
3725 GNUNET_STATISTICS_set (stats,
3726 gettext_noop ("# bytes dropped (ancient message)"),
3732 /* process decrypted message(s) */
3733 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3735 #if DEBUG_CORE_SET_QUOTA
3736 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3737 "Received %u b/s as new inbound limit for peer `%4s'\n",
3738 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3739 GNUNET_i2s (&n->peer));
3741 n->bw_out_external_limit = pt->inbound_bw_limit;
3742 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3743 n->bw_out_internal_limit);
3744 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3746 GNUNET_TRANSPORT_set_quota (transport,
3750 GNUNET_TIME_UNIT_FOREVER_REL,
3753 n->last_activity = GNUNET_TIME_absolute_get ();
3754 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3755 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3757 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3760 GNUNET_STATISTICS_set (stats,
3761 gettext_noop ("# bytes of payload decrypted"),
3762 size - sizeof (struct EncryptedMessage),
3764 handle_peer_status_change (n);
3765 if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst,
3767 &buf[sizeof (struct EncryptedMessage)],
3768 size - sizeof (struct EncryptedMessage),
3769 GNUNET_YES, GNUNET_NO))
3770 GNUNET_break_op (0);
3775 * Function called by the transport for each received message.
3777 * @param cls closure
3778 * @param peer (claimed) identity of the other peer
3779 * @param message the message
3780 * @param latency estimated latency for communicating with the
3781 * given peer (round-trip)
3782 * @param distance in overlay hops, as given by transport plugin
3785 handle_transport_receive (void *cls,
3786 const struct GNUNET_PeerIdentity *peer,
3787 const struct GNUNET_MessageHeader *message,
3788 struct GNUNET_TIME_Relative latency,
3789 unsigned int distance)
3791 struct Neighbour *n;
3792 struct GNUNET_TIME_Absolute now;
3799 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3800 "Received message of type %u from `%4s', demultiplexing.\n",
3801 (unsigned int) ntohs (message->type),
3804 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3809 n = find_neighbour (peer);
3811 n = create_neighbour (peer);
3812 changed = GNUNET_YES; /* FIXME... */
3813 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3814 type = ntohs (message->type);
3815 size = ntohs (message->size);
3818 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3819 if (size != sizeof (struct SetKeyMessage))
3821 GNUNET_break_op (0);
3824 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3825 handle_set_key (n, (const struct SetKeyMessage *) message);
3827 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3828 if (size < sizeof (struct EncryptedMessage) +
3829 sizeof (struct GNUNET_MessageHeader))
3831 GNUNET_break_op (0);
3834 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3835 (n->status != PEER_STATE_KEY_CONFIRMED))
3837 GNUNET_break_op (0);
3840 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3842 case GNUNET_MESSAGE_TYPE_CORE_PING:
3843 if (size != sizeof (struct PingMessage))
3845 GNUNET_break_op (0);
3848 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3849 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3850 (n->status != PEER_STATE_KEY_CONFIRMED))
3853 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3854 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3855 "PING", GNUNET_i2s (&n->peer));
3857 GNUNET_free_non_null (n->pending_ping);
3858 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3859 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3862 handle_ping (n, (const struct PingMessage *) message);
3864 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3865 if (size != sizeof (struct PongMessage))
3867 GNUNET_break_op (0);
3870 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3871 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3872 (n->status != PEER_STATE_KEY_CONFIRMED) )
3875 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3876 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3877 "PONG", GNUNET_i2s (&n->peer));
3879 GNUNET_free_non_null (n->pending_pong);
3880 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3881 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3884 handle_pong (n, (const struct PongMessage *) message);
3887 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3888 _("Unsupported message of type %u received.\n"),
3889 (unsigned int) type);
3892 if (n->status == PEER_STATE_KEY_CONFIRMED)
3894 now = GNUNET_TIME_absolute_get ();
3895 n->last_activity = now;
3896 changed = GNUNET_YES;
3899 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3900 n->time_established = now;
3902 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3903 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3905 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3910 handle_peer_status_change (n);
3915 * Function that recalculates the bandwidth quota for the
3916 * given neighbour and transmits it to the transport service.
3918 * @param cls neighbour for the quota update
3922 neighbour_quota_update (void *cls,
3923 const struct GNUNET_SCHEDULER_TaskContext *tc)
3925 struct Neighbour *n = cls;
3926 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3929 unsigned long long distributable;
3930 uint64_t need_per_peer;
3931 uint64_t need_per_second;
3934 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3935 "Neighbour quota update calculation running for peer `%4s'\n",
3936 GNUNET_i2s (&n->peer));
3938 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3939 /* calculate relative preference among all neighbours;
3940 divides by a bit more to avoid division by zero AND to
3941 account for possibility of new neighbours joining any time
3942 AND to convert to double... */
3943 if (preference_sum == 0)
3945 pref_rel = 1.0 / (double) neighbour_count;
3949 pref_rel = n->current_preference / preference_sum;
3951 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3952 GNUNET_TIME_UNIT_SECONDS);
3953 need_per_second = need_per_peer * neighbour_count;
3955 if (bandwidth_target_out_bps > need_per_second)
3956 distributable = bandwidth_target_out_bps - need_per_second;
3957 share = distributable * pref_rel;
3958 if (share + need_per_peer > UINT32_MAX)
3959 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
3961 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3962 /* check if we want to disconnect for good due to inactivity */
3963 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) &&
3964 (GNUNET_TIME_absolute_get_duration (n->time_established).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) )
3967 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3968 "Forcing disconnect of `%4s' due to inactivity\n",
3969 GNUNET_i2s (&n->peer));
3971 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3973 #if DEBUG_CORE_QUOTA
3974 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3975 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3976 GNUNET_i2s (&n->peer),
3977 (unsigned int) ntohl (q_in.value__),
3978 bandwidth_target_out_bps,
3979 (unsigned int) ntohl (n->bw_in.value__),
3980 (unsigned int) ntohl (n->bw_out.value__),
3981 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3983 if (n->bw_in.value__ != q_in.value__)
3986 if (GNUNET_YES == n->is_connected)
3987 GNUNET_TRANSPORT_set_quota (transport,
3991 GNUNET_TIME_UNIT_FOREVER_REL,
3993 handle_peer_status_change (n);
3995 schedule_quota_update (n);
4000 * Function called by transport to notify us that
4001 * a peer connected to us (on the network level).
4003 * @param cls closure
4004 * @param peer the peer that connected
4005 * @param latency current latency of the connection
4006 * @param distance in overlay hops, as given by transport plugin
4009 handle_transport_notify_connect (void *cls,
4010 const struct GNUNET_PeerIdentity *peer,
4011 struct GNUNET_TIME_Relative latency,
4012 unsigned int distance)
4014 struct Neighbour *n;
4016 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4021 n = find_neighbour (peer);
4024 if (GNUNET_YES == n->is_connected)
4026 /* duplicate connect notification!? */
4033 n = create_neighbour (peer);
4035 GNUNET_STATISTICS_update (stats,
4036 gettext_noop ("# peers connected (transport)"),
4039 n->is_connected = GNUNET_YES;
4040 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
4043 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
4047 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4048 "Received connection from `%4s'.\n",
4049 GNUNET_i2s (&n->peer));
4051 GNUNET_TRANSPORT_set_quota (transport,
4055 GNUNET_TIME_UNIT_FOREVER_REL,
4062 * Function called by transport telling us that a peer
4065 * @param cls closure
4066 * @param peer the peer that disconnected
4069 handle_transport_notify_disconnect (void *cls,
4070 const struct GNUNET_PeerIdentity *peer)
4072 struct DisconnectNotifyMessage cnm;
4073 struct Neighbour *n;
4074 struct ClientActiveRequest *car;
4075 struct GNUNET_TIME_Relative left;
4078 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4079 "Peer `%4s' disconnected from us; received notification from transport.\n", GNUNET_i2s (peer));
4082 n = find_neighbour (peer);
4088 GNUNET_break (n->is_connected);
4089 if (n->status == PEER_STATE_KEY_CONFIRMED)
4091 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
4092 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
4094 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
4096 n->is_connected = GNUNET_NO;
4097 while (NULL != (car = n->active_client_request_head))
4099 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
4100 n->active_client_request_tail,
4102 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
4103 &n->peer.hashPubKey,
4108 GNUNET_STATISTICS_update (stats,
4109 gettext_noop ("# peers connected (transport)"),
4112 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
4113 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
4114 left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4115 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
4116 n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (),
4118 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
4119 &consider_free_task,
4125 * Last task run during shutdown. Disconnects us from
4129 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4131 struct Neighbour *n;
4135 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4136 "Core service shutting down.\n");
4138 GNUNET_assert (transport != NULL);
4139 GNUNET_TRANSPORT_disconnect (transport);
4141 while (NULL != (n = neighbours))
4143 neighbours = n->next;
4144 GNUNET_assert (neighbour_count > 0);
4148 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
4149 GNUNET_SERVER_notification_context_destroy (notifier);
4151 while (NULL != (c = clients))
4152 handle_client_disconnect (NULL, c->client_handle);
4153 if (my_private_key != NULL)
4154 GNUNET_CRYPTO_rsa_key_free (my_private_key);
4156 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4157 if (peerinfo != NULL)
4158 GNUNET_PEERINFO_disconnect (peerinfo);
4160 GNUNET_SERVER_mst_destroy (mst);
4165 * Initiate core service.
4167 * @param cls closure
4168 * @param server the initialized server
4169 * @param c configuration to use
4173 struct GNUNET_SERVER_Handle *server,
4174 const struct GNUNET_CONFIGURATION_Handle *c)
4176 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4177 {&handle_client_init, NULL,
4178 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
4179 {&handle_client_request_info, NULL,
4180 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
4181 sizeof (struct RequestInfoMessage)},
4182 {&handle_client_send_request, NULL,
4183 GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST,
4184 sizeof (struct SendMessageRequest)},
4185 {&handle_client_send, NULL,
4186 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
4187 {&handle_client_request_connect, NULL,
4188 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
4189 sizeof (struct ConnectMessage)},
4195 /* parse configuration */
4198 GNUNET_CONFIGURATION_get_value_number (c,
4201 &bandwidth_target_in_bps)) ||
4203 GNUNET_CONFIGURATION_get_value_number (c,
4206 &bandwidth_target_out_bps)) ||
4208 GNUNET_CONFIGURATION_get_value_filename (c,
4210 "HOSTKEY", &keyfile)))
4212 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4214 ("Core service is lacking key configuration settings. Exiting.\n"));
4215 GNUNET_SCHEDULER_shutdown ();
4218 peerinfo = GNUNET_PEERINFO_connect (cfg);
4219 if (NULL == peerinfo)
4221 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4222 _("Could not access PEERINFO service. Exiting.\n"));
4223 GNUNET_SCHEDULER_shutdown ();
4224 GNUNET_free (keyfile);
4227 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4228 GNUNET_free (keyfile);
4229 if (my_private_key == NULL)
4231 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4232 _("Core service could not access hostkey. Exiting.\n"));
4233 GNUNET_PEERINFO_disconnect (peerinfo);
4234 GNUNET_SCHEDULER_shutdown ();
4237 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4238 GNUNET_CRYPTO_hash (&my_public_key,
4239 sizeof (my_public_key), &my_identity.hashPubKey);
4240 /* setup notification */
4241 notifier = GNUNET_SERVER_notification_context_create (server,
4243 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4244 /* setup transport connection */
4245 transport = GNUNET_TRANSPORT_connect (cfg,
4248 &handle_transport_receive,
4249 &handle_transport_notify_connect,
4250 &handle_transport_notify_disconnect);
4251 GNUNET_assert (NULL != transport);
4252 stats = GNUNET_STATISTICS_create ("core", cfg);
4254 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded CORE_SEND requests"), 0, GNUNET_NO);
4255 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 0, GNUNET_NO);
4257 mst = GNUNET_SERVER_mst_create (&deliver_message,
4259 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4260 &cleaning_task, NULL);
4261 /* process client requests */
4262 GNUNET_SERVER_add_handlers (server, handlers);
4263 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4264 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
4270 * The main function for the transport service.
4272 * @param argc number of arguments from the command line
4273 * @param argv command line arguments
4274 * @return 0 ok, 1 on error
4277 main (int argc, char *const *argv)
4279 return (GNUNET_OK ==
4280 GNUNET_SERVICE_run (argc,
4283 GNUNET_SERVICE_OPTION_NONE,
4284 &run, NULL)) ? 0 : 1;
4287 /* end of gnunet-service-core.c */