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.ats_count = htonl (0);
991 psnm.ats.type = htonl (0);
992 psnm.ats.value = htonl (0);
993 psnm.timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_add (n->last_activity,
994 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
995 psnm.bandwidth_in = n->bw_in;
996 psnm.bandwidth_out = n->bw_out;
998 send_to_all_clients (&psnm.header,
1000 GNUNET_CORE_OPTION_SEND_STATUS_CHANGE);
1001 GNUNET_STATISTICS_update (stats,
1002 gettext_noop ("# peer status changes"),
1009 * Go over our message queue and if it is not too long, go
1010 * over the pending requests from clients for this
1011 * neighbour and send some clients a 'READY' notification.
1013 * @param n which peer to process
1016 schedule_peer_messages (struct Neighbour *n)
1018 struct SendMessageReady smr;
1019 struct ClientActiveRequest *car;
1020 struct ClientActiveRequest *pos;
1022 struct MessageEntry *mqe;
1023 unsigned int queue_size;
1025 /* check if neighbour queue is empty enough! */
1033 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1034 return; /* queue still full */
1035 /* find highest priority request */
1036 pos = n->active_client_request_head;
1040 if ( (car == NULL) ||
1041 (pos->priority > car->priority) )
1046 return; /* no pending requests */
1048 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1049 n->active_client_request_tail,
1051 GNUNET_CONTAINER_multihashmap_remove (c->requests,
1052 &n->peer.hashPubKey,
1054 smr.header.size = htons (sizeof (struct SendMessageReady));
1055 smr.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND_READY);
1056 smr.size = htons (car->msize);
1057 smr.smr_id = car->smr_id;
1059 send_to_client (c, &smr.header, GNUNET_NO);
1065 * Handle CORE_SEND_REQUEST message.
1068 handle_client_send_request (void *cls,
1069 struct GNUNET_SERVER_Client *client,
1070 const struct GNUNET_MessageHeader *message)
1072 const struct SendMessageRequest *req;
1073 struct Neighbour *n;
1075 struct ClientActiveRequest *car;
1077 req = (const struct SendMessageRequest*) message;
1078 n = find_neighbour (&req->peer);
1080 (GNUNET_YES != n->is_connected) )
1082 /* neighbour must have disconnected since request was issued,
1083 ignore (client will realize it once it processes the
1084 disconnect notification) */
1085 GNUNET_STATISTICS_update (stats,
1086 gettext_noop ("# send requests dropped (disconnected)"),
1089 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1093 while ( (c != NULL) &&
1094 (c->client_handle != client) )
1098 /* client did not send INIT first! */
1100 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1103 if (c->requests == NULL)
1104 c->requests = GNUNET_CONTAINER_multihashmap_create (16);
1105 car = GNUNET_CONTAINER_multihashmap_get (c->requests,
1106 &req->peer.hashPubKey);
1109 /* create new entry */
1110 car = GNUNET_malloc (sizeof (struct ClientActiveRequest));
1111 GNUNET_assert (GNUNET_OK ==
1112 GNUNET_CONTAINER_multihashmap_put (c->requests,
1113 &req->peer.hashPubKey,
1115 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1116 GNUNET_CONTAINER_DLL_insert (n->active_client_request_head,
1117 n->active_client_request_tail,
1121 car->deadline = GNUNET_TIME_absolute_ntoh (req->deadline);
1122 car->priority = ntohl (req->priority);
1123 car->queue_size = ntohl (req->queue_size);
1124 car->msize = ntohs (req->size);
1125 car->smr_id = req->smr_id;
1126 schedule_peer_messages (n);
1127 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1132 * Handle CORE_INIT request.
1135 handle_client_init (void *cls,
1136 struct GNUNET_SERVER_Client *client,
1137 const struct GNUNET_MessageHeader *message)
1139 const struct InitMessage *im;
1140 struct InitReplyMessage irm;
1143 const uint16_t *types;
1145 struct Neighbour *n;
1146 struct ConnectNotifyMessage cnm;
1149 #if DEBUG_CORE_CLIENT
1150 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1151 "Client connecting to core service with `%s' message\n",
1154 /* check that we don't have an entry already */
1158 if (client == c->client_handle)
1161 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1166 msize = ntohs (message->size);
1167 if (msize < sizeof (struct InitMessage))
1170 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1173 GNUNET_SERVER_notification_context_add (notifier, client);
1174 im = (const struct InitMessage *) message;
1175 types = (const uint16_t *) &im[1];
1176 msize -= sizeof (struct InitMessage);
1177 c = GNUNET_malloc (sizeof (struct Client) + msize);
1178 c->client_handle = client;
1181 c->tcnt = msize / sizeof (uint16_t);
1182 c->types = (const uint16_t *) &c[1];
1183 wtypes = (uint16_t *) &c[1];
1184 for (i=0;i<c->tcnt;i++)
1185 wtypes[i] = ntohs (types[i]);
1186 c->options = ntohl (im->options);
1187 #if DEBUG_CORE_CLIENT
1188 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1189 "Client %p is interested in %u message types\n",
1191 (unsigned int) c->tcnt);
1193 /* send init reply message */
1194 irm.header.size = htons (sizeof (struct InitReplyMessage));
1195 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
1196 irm.reserved = htonl (0);
1197 memcpy (&irm.publicKey,
1199 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1200 #if DEBUG_CORE_CLIENT
1201 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1202 "Sending `%s' message to client.\n", "INIT_REPLY");
1204 send_to_client (c, &irm.header, GNUNET_NO);
1205 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
1207 /* notify new client about existing neighbours */
1208 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
1209 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1210 cnm.ats_count = htonl (0);
1211 cnm.ats.type = htonl (0);
1212 cnm.ats.value = htonl (0);
1216 if (n->status == PEER_STATE_KEY_CONFIRMED)
1218 #if DEBUG_CORE_CLIENT
1219 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1220 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
1223 send_to_client (c, &cnm.header, GNUNET_NO);
1228 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1233 * Free client request records.
1236 * @param key identity of peer for which this is an active request
1237 * @param value the 'struct ClientActiveRequest' to free
1238 * @return GNUNET_YES (continue iteration)
1241 destroy_active_client_request (void *cls,
1242 const GNUNET_HashCode *key,
1245 struct ClientActiveRequest *car = cls;
1246 struct Neighbour *n;
1247 struct GNUNET_PeerIdentity peer;
1249 peer.hashPubKey = *key;
1250 n = find_neighbour (&peer);
1251 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1252 n->active_client_request_tail,
1260 * A client disconnected, clean up.
1262 * @param cls closure
1263 * @param client identification of the client
1266 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1269 struct Client *prev;
1273 #if DEBUG_CORE_CLIENT
1274 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1275 "Client %p has disconnected from core service.\n",
1282 if (client == pos->client_handle)
1289 /* client never sent INIT */
1293 clients = pos->next;
1295 prev->next = pos->next;
1296 if (pos->requests != NULL)
1298 GNUNET_CONTAINER_multihashmap_iterate (pos->requests,
1299 &destroy_active_client_request,
1301 GNUNET_CONTAINER_multihashmap_destroy (pos->requests);
1308 * Handle REQUEST_INFO request.
1311 handle_client_request_info (void *cls,
1312 struct GNUNET_SERVER_Client *client,
1313 const struct GNUNET_MessageHeader *message)
1315 const struct RequestInfoMessage *rcm;
1316 struct Neighbour *n;
1317 struct ConfigurationInfoMessage cim;
1318 int32_t want_reserv;
1320 unsigned long long old_preference;
1321 struct GNUNET_SERVER_TransmitContext *tc;
1323 #if DEBUG_CORE_CLIENT
1324 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1325 "Core service receives `%s' request.\n", "REQUEST_INFO");
1327 rcm = (const struct RequestInfoMessage *) message;
1328 n = find_neighbour (&rcm->peer);
1329 memset (&cim, 0, sizeof (cim));
1332 want_reserv = ntohl (rcm->reserve_inbound);
1333 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1335 n->bw_out_internal_limit = rcm->limit_outbound;
1336 if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1337 n->bw_out_external_limit).value__)
1339 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1340 n->bw_out_external_limit);
1341 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1343 GNUNET_TRANSPORT_set_quota (transport,
1347 GNUNET_TIME_UNIT_FOREVER_REL,
1349 handle_peer_status_change (n);
1352 if (want_reserv < 0)
1354 got_reserv = want_reserv;
1356 else if (want_reserv > 0)
1358 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1359 want_reserv).rel_value == 0)
1360 got_reserv = want_reserv;
1362 got_reserv = 0; /* all or nothing */
1366 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1368 old_preference = n->current_preference;
1369 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1370 if (old_preference > n->current_preference)
1372 /* overflow; cap at maximum value */
1373 n->current_preference = ULLONG_MAX;
1375 update_preference_sum (n->current_preference - old_preference);
1376 #if DEBUG_CORE_QUOTA
1377 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1378 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1380 GNUNET_i2s (&rcm->peer),
1383 cim.reserved_amount = htonl (got_reserv);
1384 cim.rim_id = rcm->rim_id;
1385 cim.bw_out = n->bw_out;
1386 cim.preference = n->current_preference;
1388 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1389 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1390 cim.peer = rcm->peer;
1392 #if DEBUG_CORE_CLIENT
1393 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1394 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1396 tc = GNUNET_SERVER_transmit_context_create (client);
1397 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1398 GNUNET_SERVER_transmit_context_run (tc,
1399 GNUNET_TIME_UNIT_FOREVER_REL);
1404 * Free the given entry for the neighbour (it has
1405 * already been removed from the list at this point).
1407 * @param n neighbour to free
1410 free_neighbour (struct Neighbour *n)
1412 struct MessageEntry *m;
1413 struct ClientActiveRequest *car;
1416 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1417 "Destroying neighbour entry for peer `%4s'\n",
1418 GNUNET_i2s (&n->peer));
1420 if (n->pitr != NULL)
1422 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1427 GNUNET_free (n->skm);
1430 while (NULL != (m = n->messages))
1432 n->messages = m->next;
1435 while (NULL != (m = n->encrypted_head))
1437 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1442 while (NULL != (car = n->active_client_request_head))
1444 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1445 n->active_client_request_tail,
1447 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
1448 &n->peer.hashPubKey,
1454 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1457 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1458 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
1459 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1460 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
1461 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1462 GNUNET_SCHEDULER_cancel (n->quota_update_task);
1463 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1464 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1465 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1466 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
1467 if (n->status == PEER_STATE_KEY_CONFIRMED)
1468 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1469 GNUNET_free_non_null (n->public_key);
1470 GNUNET_free_non_null (n->pending_ping);
1471 GNUNET_free_non_null (n->pending_pong);
1477 * Check if we have encrypted messages for the specified neighbour
1478 * pending, and if so, check with the transport about sending them
1481 * @param n neighbour to check.
1483 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1487 * Encrypt size bytes from in and write the result to out. Use the
1488 * key for outbound traffic of the given neighbour.
1490 * @param n neighbour we are sending to
1491 * @param iv initialization vector to use
1492 * @param in ciphertext
1493 * @param out plaintext
1494 * @param size size of in/out
1495 * @return GNUNET_OK on success
1498 do_encrypt (struct Neighbour *n,
1499 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1500 const void *in, void *out, size_t size)
1502 if (size != (uint16_t) size)
1507 GNUNET_assert (size ==
1508 GNUNET_CRYPTO_aes_encrypt (in,
1512 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1514 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1515 "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
1516 (unsigned int) size,
1517 GNUNET_i2s (&n->peer),
1518 (unsigned int) n->encrypt_key.crc32,
1519 GNUNET_CRYPTO_crc32_n (iv, sizeof(iv)));
1526 * Consider freeing the given neighbour since we may not need
1527 * to keep it around anymore.
1529 * @param n neighbour to consider discarding
1532 consider_free_neighbour (struct Neighbour *n);
1536 * Task triggered when a neighbour entry is about to time out
1537 * (and we should prevent this by sending a PING).
1539 * @param cls the 'struct Neighbour'
1540 * @param tc scheduler context (not used)
1543 send_keep_alive (void *cls,
1544 const struct GNUNET_SCHEDULER_TaskContext *tc)
1546 struct Neighbour *n = cls;
1547 struct GNUNET_TIME_Relative retry;
1548 struct GNUNET_TIME_Relative left;
1549 struct MessageEntry *me;
1550 struct PingMessage pp;
1551 struct PingMessage *pm;
1552 struct GNUNET_CRYPTO_AesInitializationVector iv;
1554 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1556 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1557 sizeof (struct PingMessage));
1558 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1559 me->priority = PING_PRIORITY;
1560 me->size = sizeof (struct PingMessage);
1561 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1565 pm = (struct PingMessage *) &me[1];
1566 pm->header.size = htons (sizeof (struct PingMessage));
1567 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1568 pm->iv_seed = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1570 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
1571 pp.challenge = n->ping_challenge;
1572 pp.target = n->peer;
1574 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1575 "Encrypting `%s' message with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
1577 (unsigned int) n->ping_challenge,
1578 GNUNET_i2s (&n->peer),
1579 (unsigned int) n->encrypt_key.crc32,
1580 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
1587 sizeof (struct PingMessage) -
1588 ((void *) &pm->target - (void *) pm));
1589 process_encrypted_neighbour_queue (n);
1590 /* reschedule PING job */
1591 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1592 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1593 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1594 MIN_PING_FREQUENCY);
1596 = GNUNET_SCHEDULER_add_delayed (retry,
1604 * Task triggered when a neighbour entry might have gotten stale.
1606 * @param cls the 'struct Neighbour'
1607 * @param tc scheduler context (not used)
1610 consider_free_task (void *cls,
1611 const struct GNUNET_SCHEDULER_TaskContext *tc)
1613 struct Neighbour *n = cls;
1615 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1616 consider_free_neighbour (n);
1621 * Consider freeing the given neighbour since we may not need
1622 * to keep it around anymore.
1624 * @param n neighbour to consider discarding
1627 consider_free_neighbour (struct Neighbour *n)
1629 struct Neighbour *pos;
1630 struct Neighbour *prev;
1631 struct GNUNET_TIME_Relative left;
1633 if ( (n->th != NULL) ||
1634 (n->pitr != NULL) ||
1635 (GNUNET_YES == n->is_connected) )
1636 return; /* no chance */
1638 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1639 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1640 if (left.rel_value > 0)
1642 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1643 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1644 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (left,
1645 &consider_free_task,
1649 /* actually free the neighbour... */
1658 neighbours = n->next;
1660 prev->next = n->next;
1661 GNUNET_assert (neighbour_count > 0);
1663 GNUNET_STATISTICS_set (stats,
1664 gettext_noop ("# neighbour entries allocated"),
1672 * Function called when the transport service is ready to
1673 * receive an encrypted message for the respective peer
1675 * @param cls neighbour to use message from
1676 * @param size number of bytes we can transmit
1677 * @param buf where to copy the message
1678 * @return number of bytes transmitted
1681 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1683 struct Neighbour *n = cls;
1684 struct MessageEntry *m;
1689 m = n->encrypted_head;
1693 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1694 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1695 GNUNET_i2s (&n->peer));
1699 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1706 GNUNET_assert (size >= m->size);
1707 memcpy (cbuf, &m[1], m->size);
1709 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1712 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1713 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1714 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1716 GNUNET_i2s (&n->peer));
1718 process_encrypted_neighbour_queue (n);
1723 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1724 "Transmission of message of type %u and size %u failed\n",
1725 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1726 (unsigned int) m->size);
1730 consider_free_neighbour (n);
1736 * Check if we have plaintext messages for the specified neighbour
1737 * pending, and if so, consider batching and encrypting them (and
1738 * then trigger processing of the encrypted queue if needed).
1740 * @param n neighbour to check.
1742 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1746 * Check if we have encrypted messages for the specified neighbour
1747 * pending, and if so, check with the transport about sending them
1750 * @param n neighbour to check.
1753 process_encrypted_neighbour_queue (struct Neighbour *n)
1755 struct MessageEntry *m;
1758 return; /* request already pending */
1759 m = n->encrypted_head;
1762 /* encrypted queue empty, try plaintext instead */
1763 process_plaintext_neighbour_queue (n);
1767 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1768 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1769 (unsigned int) m->size,
1770 GNUNET_i2s (&n->peer),
1771 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).rel_value);
1774 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1777 GNUNET_TIME_absolute_get_remaining
1779 ¬ify_encrypted_transmit_ready,
1783 /* message request too large or duplicate request */
1785 /* discard encrypted message */
1786 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1790 process_encrypted_neighbour_queue (n);
1796 * Decrypt size bytes from in and write the result to out. Use the
1797 * key for inbound traffic of the given neighbour. This function does
1798 * NOT do any integrity-checks on the result.
1800 * @param n neighbour we are receiving from
1801 * @param iv initialization vector to use
1802 * @param in ciphertext
1803 * @param out plaintext
1804 * @param size size of in/out
1805 * @return GNUNET_OK on success
1808 do_decrypt (struct Neighbour *n,
1809 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1810 const void *in, void *out, size_t size)
1812 if (size != (uint16_t) size)
1817 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1818 (n->status != PEER_STATE_KEY_CONFIRMED))
1820 GNUNET_break_op (0);
1821 return GNUNET_SYSERR;
1824 GNUNET_CRYPTO_aes_decrypt (in,
1831 return GNUNET_SYSERR;
1833 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1835 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1836 "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
1837 (unsigned int) size,
1838 GNUNET_i2s (&n->peer),
1839 (unsigned int) n->decrypt_key.crc32,
1840 GNUNET_CRYPTO_crc32_n (iv, sizeof(*iv)));
1847 * Select messages for transmission. This heuristic uses a combination
1848 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1849 * and priority-based discard (in case no feasible schedule exist) and
1850 * speculative optimization (defer any kind of transmission until
1851 * we either create a batch of significant size, 25% of max, or until
1852 * we are close to a deadline). Furthermore, when scheduling the
1853 * heuristic also packs as many messages into the batch as possible,
1854 * starting with those with the earliest deadline. Yes, this is fun.
1856 * @param n neighbour to select messages from
1857 * @param size number of bytes to select for transmission
1858 * @param retry_time set to the time when we should try again
1859 * (only valid if this function returns zero)
1860 * @return number of bytes selected, or 0 if we decided to
1861 * defer scheduling overall; in that case, retry_time is set.
1864 select_messages (struct Neighbour *n,
1865 size_t size, struct GNUNET_TIME_Relative *retry_time)
1867 struct MessageEntry *pos;
1868 struct MessageEntry *min;
1869 struct MessageEntry *last;
1870 unsigned int min_prio;
1871 struct GNUNET_TIME_Absolute t;
1872 struct GNUNET_TIME_Absolute now;
1873 struct GNUNET_TIME_Relative delta;
1875 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1878 unsigned int queue_size;
1879 int discard_low_prio;
1881 GNUNET_assert (NULL != n->messages);
1882 now = GNUNET_TIME_absolute_get ();
1883 /* last entry in linked list of messages processed */
1885 /* should we remove the entry with the lowest
1886 priority from consideration for scheduling at the
1897 discard_low_prio = GNUNET_YES;
1898 while (GNUNET_YES == discard_low_prio)
1901 min_prio = UINT_MAX;
1902 discard_low_prio = GNUNET_NO;
1903 /* calculate number of bytes available for transmission at time "t" */
1904 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1906 /* how many bytes have we (hypothetically) scheduled so far */
1908 /* maximum time we can wait before transmitting anything
1909 and still make all of our deadlines */
1910 slack = GNUNET_TIME_UNIT_FOREVER_REL;
1912 /* note that we use "*2" here because we want to look
1913 a bit further into the future; much more makes no
1914 sense since new message might be scheduled in the
1916 while ((pos != NULL) && (off < size * 2))
1918 if (pos->do_transmit == GNUNET_YES)
1920 /* already removed from consideration */
1924 if (discard_low_prio == GNUNET_NO)
1926 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1927 if (delta.rel_value > 0)
1929 // FIXME: HUH? Check!
1931 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1934 if (avail < pos->size)
1936 // FIXME: HUH? Check!
1937 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1942 /* update slack, considering both its absolute deadline
1943 and relative deadlines caused by other messages
1944 with their respective load */
1945 slack = GNUNET_TIME_relative_min (slack,
1946 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1948 if (pos->deadline.abs_value <= now.abs_value)
1951 slack = GNUNET_TIME_UNIT_ZERO;
1953 else if (GNUNET_YES == pos->got_slack)
1955 /* should be soon now! */
1956 slack = GNUNET_TIME_relative_min (slack,
1957 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1962 GNUNET_TIME_relative_min (slack,
1963 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1964 pos->got_slack = GNUNET_YES;
1965 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1966 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
1971 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1972 if (pos->priority <= min_prio)
1974 /* update min for discard */
1975 min_prio = pos->priority;
1980 if (discard_low_prio)
1982 GNUNET_assert (min != NULL);
1983 /* remove lowest-priority entry from consideration */
1984 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1988 /* guard against sending "tiny" messages with large headers without
1990 if ( (slack.rel_value > GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value) &&
1992 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1994 /* less than 25% of message would be filled with deadlines still
1995 being met if we delay by one second or more; so just wait for
1996 more data; but do not wait longer than 1s (since we don't want
1997 to delay messages for a really long time either). */
1998 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1999 /* reset do_transmit values for next time */
2002 pos->do_transmit = GNUNET_NO;
2005 GNUNET_STATISTICS_update (stats,
2006 gettext_noop ("# transmissions delayed due to corking"),
2009 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2010 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
2011 (unsigned long long) retry_time->rel_value,
2013 (unsigned int) size);
2017 /* select marked messages (up to size) for transmission */
2022 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
2024 pos->do_transmit = GNUNET_YES; /* mark for transmission */
2028 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2029 "Selecting message of size %u for transmission\n",
2030 (unsigned int) pos->size);
2036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2037 "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
2038 (unsigned int) pos->size,
2041 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
2046 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2047 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
2048 (unsigned long long) off, (unsigned long long) tsize,
2049 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
2050 GNUNET_i2s (&n->peer));
2057 * Batch multiple messages into a larger buffer.
2059 * @param n neighbour to take messages from
2060 * @param buf target buffer
2061 * @param size size of buf
2062 * @param deadline set to transmission deadline for the result
2063 * @param retry_time set to the time when we should try again
2064 * (only valid if this function returns zero)
2065 * @param priority set to the priority of the batch
2066 * @return number of bytes written to buf (can be zero)
2069 batch_message (struct Neighbour *n,
2072 struct GNUNET_TIME_Absolute *deadline,
2073 struct GNUNET_TIME_Relative *retry_time,
2074 unsigned int *priority)
2076 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
2077 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
2078 struct MessageEntry *pos;
2079 struct MessageEntry *prev;
2080 struct MessageEntry *next;
2085 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2086 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
2087 if (0 == select_messages (n, size, retry_time))
2090 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2091 "No messages selected, will try again in %llu ms\n",
2092 retry_time->rel_value);
2096 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
2097 ntm->ats_count = htonl (0);
2098 ntm->ats.type = htonl (0);
2099 ntm->ats.value = htonl (0);
2100 ntm->peer = n->peer;
2103 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
2106 if (GNUNET_YES == pos->do_transmit)
2108 GNUNET_assert (pos->size <= size);
2109 /* do notifications */
2110 /* FIXME: track if we have *any* client that wants
2111 full notifications and only do this if that is
2113 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
2115 memcpy (&ntm[1], &pos[1], pos->size);
2116 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
2117 sizeof (struct GNUNET_MessageHeader));
2118 send_to_all_clients (&ntm->header,
2120 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
2124 /* message too large for 'full' notifications, we do at
2125 least the 'hdr' type */
2128 sizeof (struct GNUNET_MessageHeader));
2130 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
2132 send_to_all_clients (&ntm->header,
2134 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
2136 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2137 "Encrypting %u bytes with message of type %u and size %u\n",
2139 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
2140 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
2142 /* copy for encrypted transmission */
2143 memcpy (&buf[ret], &pos[1], pos->size);
2146 *priority += pos->priority;
2148 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2149 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
2150 (unsigned int) pos->size,
2151 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).rel_value);
2153 deadline->abs_value = GNUNET_MIN (deadline->abs_value, pos->deadline.abs_value);
2167 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2168 "Deadline for message batch is %llu ms\n",
2169 GNUNET_TIME_absolute_get_remaining (*deadline).rel_value);
2176 * Remove messages with deadlines that have long expired from
2179 * @param n neighbour to inspect
2182 discard_expired_messages (struct Neighbour *n)
2184 struct MessageEntry *prev;
2185 struct MessageEntry *next;
2186 struct MessageEntry *pos;
2187 struct GNUNET_TIME_Absolute now;
2188 struct GNUNET_TIME_Relative delta;
2192 now = GNUNET_TIME_absolute_get ();
2198 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
2199 if (delta.rel_value > PAST_EXPIRATION_DISCARD_TIME.rel_value)
2202 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2203 "Message is %llu ms past due, discarding.\n",
2210 GNUNET_STATISTICS_update (stats,
2211 gettext_noop ("# messages discarded (expired prior to transmission)"),
2221 if (GNUNET_YES == disc)
2222 schedule_peer_messages (n);
2227 * Signature of the main function of a task.
2229 * @param cls closure
2230 * @param tc context information (why was this task triggered now)
2233 retry_plaintext_processing (void *cls,
2234 const struct GNUNET_SCHEDULER_TaskContext *tc)
2236 struct Neighbour *n = cls;
2238 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2239 process_plaintext_neighbour_queue (n);
2244 * Send our key (and encrypted PING) to the other peer.
2246 * @param n the other peer
2248 static void send_key (struct Neighbour *n);
2251 * Task that will retry "send_key" if our previous attempt failed
2255 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2257 struct Neighbour *n = cls;
2260 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2261 "Retrying key transmission to `%4s'\n",
2262 GNUNET_i2s (&n->peer));
2264 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2265 n->set_key_retry_frequency =
2266 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2272 * Check if we have plaintext messages for the specified neighbour
2273 * pending, and if so, consider batching and encrypting them (and
2274 * then trigger processing of the encrypted queue if needed).
2276 * @param n neighbour to check.
2279 process_plaintext_neighbour_queue (struct Neighbour *n)
2281 char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)]; /* plaintext */
2283 struct EncryptedMessage *em; /* encrypted message */
2284 struct EncryptedMessage *ph; /* plaintext header */
2285 struct MessageEntry *me;
2286 unsigned int priority;
2287 struct GNUNET_TIME_Absolute deadline;
2288 struct GNUNET_TIME_Relative retry_time;
2289 struct GNUNET_CRYPTO_AesInitializationVector iv;
2290 struct GNUNET_CRYPTO_AuthKey auth_key;
2292 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2294 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
2295 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2299 case PEER_STATE_DOWN:
2302 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2303 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2304 GNUNET_i2s(&n->peer));
2307 case PEER_STATE_KEY_SENT:
2308 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2309 n->retry_set_key_task
2310 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2311 &set_key_retry_task, n);
2313 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2314 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2315 GNUNET_i2s(&n->peer));
2318 case PEER_STATE_KEY_RECEIVED:
2319 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2320 n->retry_set_key_task
2321 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2322 &set_key_retry_task, n);
2324 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2325 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2326 GNUNET_i2s(&n->peer));
2329 case PEER_STATE_KEY_CONFIRMED:
2330 /* ready to continue */
2333 discard_expired_messages (n);
2334 if (n->messages == NULL)
2337 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2338 "Plaintext message queue for `%4s' is empty.\n",
2339 GNUNET_i2s(&n->peer));
2341 return; /* no pending messages */
2343 if (n->encrypted_head != NULL)
2346 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2347 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2348 GNUNET_i2s(&n->peer));
2350 return; /* wait for messages already encrypted to be
2353 ph = (struct EncryptedMessage *) pbuf;
2354 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2356 used = sizeof (struct EncryptedMessage);
2357 used += batch_message (n,
2359 GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2360 &deadline, &retry_time, &priority);
2361 if (used == sizeof (struct EncryptedMessage))
2364 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2365 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2366 GNUNET_i2s(&n->peer));
2368 /* no messages selected for sending, try again later... */
2369 n->retry_plaintext_task =
2370 GNUNET_SCHEDULER_add_delayed (retry_time,
2371 &retry_plaintext_processing, n);
2374 #if DEBUG_CORE_QUOTA
2375 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2376 "Sending %u b/s as new limit to peer `%4s'\n",
2377 (unsigned int) ntohl (n->bw_in.value__),
2378 GNUNET_i2s (&n->peer));
2380 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
2381 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2382 ph->inbound_bw_limit = n->bw_in;
2383 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2385 /* setup encryption message header */
2386 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2387 me->deadline = deadline;
2388 me->priority = priority;
2390 em = (struct EncryptedMessage *) &me[1];
2391 em->header.size = htons (used);
2392 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2393 em->iv_seed = ph->iv_seed;
2394 derive_iv (&iv, &n->encrypt_key, ph->iv_seed, &n->peer);
2397 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2398 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2399 (unsigned int) used - ENCRYPTED_HEADER_SIZE,
2400 GNUNET_i2s(&n->peer),
2401 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).rel_value);
2403 GNUNET_assert (GNUNET_OK ==
2406 &ph->sequence_number,
2407 &em->sequence_number, used - ENCRYPTED_HEADER_SIZE));
2408 derive_auth_key (&auth_key,
2411 n->encrypt_key_created);
2412 GNUNET_CRYPTO_hmac (&auth_key,
2413 &em->sequence_number,
2414 used - ENCRYPTED_HEADER_SIZE,
2417 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2418 "Authenticated %u bytes of ciphertext %u: `%s'\n",
2419 used - ENCRYPTED_HEADER_SIZE,
2420 GNUNET_CRYPTO_crc32_n (&em->sequence_number,
2421 used - ENCRYPTED_HEADER_SIZE),
2422 GNUNET_h2s (&em->hmac));
2424 /* append to transmission list */
2425 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2429 process_encrypted_neighbour_queue (n);
2430 schedule_peer_messages (n);
2435 * Function that recalculates the bandwidth quota for the
2436 * given neighbour and transmits it to the transport service.
2438 * @param cls neighbour for the quota update
2442 neighbour_quota_update (void *cls,
2443 const struct GNUNET_SCHEDULER_TaskContext *tc);
2447 * Schedule the task that will recalculate the bandwidth
2448 * quota for this peer (and possibly force a disconnect of
2449 * idle peers by calculating a bandwidth of zero).
2452 schedule_quota_update (struct Neighbour *n)
2454 GNUNET_assert (n->quota_update_task ==
2455 GNUNET_SCHEDULER_NO_TASK);
2456 n->quota_update_task
2457 = GNUNET_SCHEDULER_add_delayed (QUOTA_UPDATE_FREQUENCY,
2458 &neighbour_quota_update,
2464 * Initialize a new 'struct Neighbour'.
2466 * @param pid ID of the new neighbour
2467 * @return handle for the new neighbour
2469 static struct Neighbour *
2470 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2472 struct Neighbour *n;
2473 struct GNUNET_TIME_Absolute now;
2476 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2477 "Creating neighbour entry for peer `%4s'\n",
2480 n = GNUNET_malloc (sizeof (struct Neighbour));
2481 n->next = neighbours;
2484 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2486 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2487 now = GNUNET_TIME_absolute_get ();
2488 n->encrypt_key_created = now;
2489 n->last_activity = now;
2490 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2491 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2492 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2493 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2494 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2495 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
2497 neighbour_quota_update (n, NULL);
2498 consider_free_neighbour (n);
2504 * Handle CORE_SEND request.
2507 * @param client the client issuing the request
2508 * @param message the "struct SendMessage"
2511 handle_client_send (void *cls,
2512 struct GNUNET_SERVER_Client *client,
2513 const struct GNUNET_MessageHeader *message)
2515 const struct SendMessage *sm;
2516 struct Neighbour *n;
2517 struct MessageEntry *prev;
2518 struct MessageEntry *pos;
2519 struct MessageEntry *e;
2520 struct MessageEntry *min_prio_entry;
2521 struct MessageEntry *min_prio_prev;
2522 unsigned int min_prio;
2523 unsigned int queue_size;
2526 msize = ntohs (message->size);
2528 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2530 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));
2533 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2536 sm = (const struct SendMessage *) message;
2537 msize -= sizeof (struct SendMessage);
2538 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2540 /* FIXME: should we not allow loopback-injection here? */
2543 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2546 n = find_neighbour (&sm->peer);
2548 n = create_neighbour (&sm->peer);
2550 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2551 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2553 (unsigned int) msize,
2554 GNUNET_i2s (&sm->peer));
2556 discard_expired_messages (n);
2557 /* bound queue size */
2558 /* NOTE: this entire block to bound the queue size should be
2559 obsolete with the new client-request code and the
2560 'schedule_peer_messages' mechanism; we still have this code in
2561 here for now as a sanity check for the new mechanmism;
2562 ultimately, we should probably simply reject SEND messages that
2563 are not 'approved' (or provide a new core API for very unreliable
2564 delivery that always sends with priority 0). Food for thought. */
2565 min_prio = UINT32_MAX;
2566 min_prio_entry = NULL;
2567 min_prio_prev = NULL;
2573 if (pos->priority <= min_prio)
2575 min_prio_entry = pos;
2576 min_prio_prev = prev;
2577 min_prio = pos->priority;
2583 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2586 if (ntohl(sm->priority) <= min_prio)
2588 /* discard new entry; this should no longer happen! */
2591 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2592 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2594 (unsigned int) MAX_PEER_QUEUE_SIZE,
2595 (unsigned int) msize,
2596 (unsigned int) ntohs (message->type));
2598 GNUNET_STATISTICS_update (stats,
2599 gettext_noop ("# discarded CORE_SEND requests"),
2603 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2606 GNUNET_assert (min_prio_entry != NULL);
2607 /* discard "min_prio_entry" */
2609 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2610 "Queue full, discarding existing older request\n");
2612 GNUNET_STATISTICS_update (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 1, GNUNET_NO);
2613 if (min_prio_prev == NULL)
2614 n->messages = min_prio_entry->next;
2616 min_prio_prev->next = min_prio_entry->next;
2617 GNUNET_free (min_prio_entry);
2621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2622 "Adding transmission request for `%4s' of size %u to queue\n",
2623 GNUNET_i2s (&sm->peer),
2624 (unsigned int) msize);
2626 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2627 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2628 e->priority = ntohl (sm->priority);
2630 memcpy (&e[1], &sm[1], msize);
2632 /* insert, keep list sorted by deadline */
2635 while ((pos != NULL) && (pos->deadline.abs_value < e->deadline.abs_value))
2646 /* consider scheduling now */
2647 process_plaintext_neighbour_queue (n);
2649 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2654 * Function called when the transport service is ready to
2655 * receive a message. Only resets 'n->th' to NULL.
2657 * @param cls neighbour to use message from
2658 * @param size number of bytes we can transmit
2659 * @param buf where to copy the message
2660 * @return number of bytes transmitted
2663 notify_transport_connect_done (void *cls, size_t size, void *buf)
2665 struct Neighbour *n = cls;
2667 if (GNUNET_YES != n->is_connected)
2669 /* transport should only call us to transmit a message after
2670 * telling us about a successful connection to the respective peer */
2671 n->th = NULL; /* If this happens because of a timeout, reset n-th so another message may be sent for this peer! */
2673 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Timeout on notify connect!\n");
2680 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2681 _("Failed to connect to `%4s': transport failed to connect\n"),
2682 GNUNET_i2s (&n->peer));
2685 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2686 _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2687 GNUNET_i2s (&n->peer));
2688 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2689 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2690 n->retry_set_key_task = GNUNET_SCHEDULER_add_now (&set_key_retry_task,
2697 * Handle CORE_REQUEST_CONNECT request.
2700 * @param client the client issuing the request
2701 * @param message the "struct ConnectMessage"
2704 handle_client_request_connect (void *cls,
2705 struct GNUNET_SERVER_Client *client,
2706 const struct GNUNET_MessageHeader *message)
2708 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2709 struct Neighbour *n;
2710 struct GNUNET_TIME_Relative timeout;
2712 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2715 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2718 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2719 n = find_neighbour (&cm->peer);
2721 n = create_neighbour (&cm->peer);
2722 if ( (GNUNET_YES == n->is_connected) ||
2725 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2726 "Core received `%s' request for `%4s', already connected!\n",
2728 GNUNET_i2s (&cm->peer));
2729 return; /* already connected, or at least trying */
2731 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2733 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2734 "Core received `%s' request for `%4s', will try to establish connection\n",
2736 GNUNET_i2s (&cm->peer));
2738 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2739 /* ask transport to connect to the peer */
2740 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2742 sizeof (struct GNUNET_MessageHeader), 0,
2744 ¬ify_transport_connect_done,
2746 GNUNET_break (NULL != n->th);
2751 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2752 * the neighbour's struct and retry send_key. Or, if we did not get a
2753 * HELLO, just do nothing.
2755 * @param cls the 'struct Neighbour' to retry sending the key for
2756 * @param peer the peer for which this is the HELLO
2757 * @param hello HELLO message of that peer
2760 process_hello_retry_send_key (void *cls,
2761 const struct GNUNET_PeerIdentity *peer,
2762 const struct GNUNET_HELLO_Message *hello)
2764 struct Neighbour *n = cls;
2769 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2770 "Entered `%s' and `%s' is NULL!\n",
2771 "process_hello_retry_send_key",
2775 if (n->public_key != NULL)
2777 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2779 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2780 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2782 GNUNET_STATISTICS_update (stats,
2783 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2791 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2792 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
2793 GNUNET_i2s (&n->peer));
2795 GNUNET_STATISTICS_update (stats,
2796 gettext_noop ("# Delayed connecting due to lack of public key"),
2799 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2800 n->retry_set_key_task
2801 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2802 &set_key_retry_task, n);
2808 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2809 "Entered `%s' for peer `%4s'\n",
2810 "process_hello_retry_send_key",
2813 if (n->public_key != NULL)
2815 /* already have public key, why are we here? */
2821 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2822 "Received new `%s' message for `%4s', initiating key exchange.\n",
2827 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2828 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2830 GNUNET_STATISTICS_update (stats,
2831 gettext_noop ("# Error extracting public key from HELLO"),
2834 GNUNET_free (n->public_key);
2835 n->public_key = NULL;
2837 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2838 "GNUNET_HELLO_get_key returned awfully\n");
2846 * Send our key (and encrypted PING) to the other peer.
2848 * @param n the other peer
2851 send_key (struct Neighbour *n)
2853 struct MessageEntry *pos;
2854 struct SetKeyMessage *sm;
2855 struct MessageEntry *me;
2856 struct PingMessage pp;
2857 struct PingMessage *pm;
2858 struct GNUNET_CRYPTO_AesInitializationVector iv;
2860 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2862 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2863 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2865 if (n->pitr != NULL)
2868 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2869 "Key exchange in progress with `%4s'.\n",
2870 GNUNET_i2s (&n->peer));
2872 return; /* already in progress */
2874 if (GNUNET_YES != n->is_connected)
2877 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2878 "Not yet connected to peer `%4s'!\n",
2879 GNUNET_i2s (&n->peer));
2883 GNUNET_STATISTICS_update (stats,
2884 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
2887 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2889 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2891 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2892 ¬ify_encrypted_transmit_ready,
2898 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2899 "Asked to perform key exchange with `%4s'.\n",
2900 GNUNET_i2s (&n->peer));
2902 if (n->public_key == NULL)
2904 /* lookup n's public key, then try again */
2906 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2907 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2908 GNUNET_i2s (&n->peer));
2910 GNUNET_assert (n->pitr == NULL);
2911 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2913 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2914 &process_hello_retry_send_key, n);
2917 pos = n->encrypted_head;
2920 if (GNUNET_YES == pos->is_setkey)
2922 if (pos->sender_status == n->status)
2925 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2926 "`%s' message for `%4s' queued already\n",
2928 GNUNET_i2s (&n->peer));
2930 goto trigger_processing;
2932 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2938 "Removing queued `%s' message for `%4s', will create a new one\n",
2940 GNUNET_i2s (&n->peer));
2950 case PEER_STATE_DOWN:
2951 n->status = PEER_STATE_KEY_SENT;
2953 case PEER_STATE_KEY_SENT:
2955 case PEER_STATE_KEY_RECEIVED:
2957 case PEER_STATE_KEY_CONFIRMED:
2965 /* first, set key message */
2966 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2967 sizeof (struct SetKeyMessage) +
2968 sizeof (struct PingMessage));
2969 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2970 me->priority = SET_KEY_PRIORITY;
2971 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
2972 me->is_setkey = GNUNET_YES;
2973 me->got_slack = GNUNET_YES; /* do not defer this one! */
2974 me->sender_status = n->status;
2975 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2979 sm = (struct SetKeyMessage *) &me[1];
2980 sm->header.size = htons (sizeof (struct SetKeyMessage));
2981 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2982 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2983 PEER_STATE_KEY_SENT : n->status));
2985 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2986 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2987 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2988 sizeof (struct GNUNET_PeerIdentity));
2989 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2990 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2991 sm->target = n->peer;
2992 GNUNET_assert (GNUNET_OK ==
2993 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2995 GNUNET_CRYPTO_AesSessionKey),
2997 &sm->encrypted_key));
2998 GNUNET_assert (GNUNET_OK ==
2999 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
3001 pm = (struct PingMessage *) &sm[1];
3002 pm->header.size = htons (sizeof (struct PingMessage));
3003 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
3004 pm->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3005 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
3006 pp.challenge = n->ping_challenge;
3007 pp.target = n->peer;
3009 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3010 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
3012 (unsigned int) n->ping_challenge,
3013 GNUNET_i2s (&n->peer),
3014 (unsigned int) n->encrypt_key.crc32,
3015 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3022 sizeof (struct PingMessage) -
3023 ((void *) &pm->target - (void *) pm));
3024 GNUNET_STATISTICS_update (stats,
3025 gettext_noop ("# SET_KEY and PING messages created"),
3029 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3030 "Have %llu ms left for `%s' transmission.\n",
3031 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).rel_value,
3035 /* trigger queue processing */
3036 process_encrypted_neighbour_queue (n);
3037 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
3038 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
3039 n->retry_set_key_task
3040 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3041 &set_key_retry_task, n);
3046 * We received a SET_KEY message. Validate and update
3047 * our key material and status.
3049 * @param n the neighbour from which we received message m
3050 * @param m the set key message we received
3053 handle_set_key (struct Neighbour *n,
3054 const struct SetKeyMessage *m);
3058 * PEERINFO is giving us a HELLO for a peer. Add the public key to
3059 * the neighbour's struct and retry handling the set_key message. Or,
3060 * if we did not get a HELLO, just free the set key message.
3062 * @param cls pointer to the set key message
3063 * @param peer the peer for which this is the HELLO
3064 * @param hello HELLO message of that peer
3067 process_hello_retry_handle_set_key (void *cls,
3068 const struct GNUNET_PeerIdentity *peer,
3069 const struct GNUNET_HELLO_Message *hello)
3071 struct Neighbour *n = cls;
3072 struct SetKeyMessage *sm = n->skm;
3078 if (n->public_key != NULL)
3081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3082 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
3084 GNUNET_i2s (&n->peer),
3087 handle_set_key (n, sm);
3091 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3092 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
3094 GNUNET_i2s (&n->peer));
3099 if (n->public_key != NULL)
3100 return; /* multiple HELLOs match!? */
3102 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3103 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3105 GNUNET_break_op (0);
3106 GNUNET_free (n->public_key);
3107 n->public_key = NULL;
3113 * We received a PING message. Validate and transmit
3116 * @param n sender of the PING
3117 * @param m the encrypted PING message itself
3120 handle_ping (struct Neighbour *n, const struct PingMessage *m)
3122 struct PingMessage t;
3123 struct PongMessage tx;
3124 struct PongMessage *tp;
3125 struct MessageEntry *me;
3126 struct GNUNET_CRYPTO_AesInitializationVector iv;
3129 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3130 "Core service receives `%s' request from `%4s'.\n",
3131 "PING", GNUNET_i2s (&n->peer));
3133 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3139 sizeof (struct PingMessage) -
3140 ((void *) &m->target - (void *) m)))
3143 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3144 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u, IV %u (salt %u)\n",
3146 GNUNET_i2s (&t.target),
3147 (unsigned int) t.challenge,
3148 (unsigned int) n->decrypt_key.crc32,
3149 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3152 GNUNET_STATISTICS_update (stats,
3153 gettext_noop ("# PING messages decrypted"),
3156 if (0 != memcmp (&t.target,
3157 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3159 GNUNET_break_op (0);
3162 me = GNUNET_malloc (sizeof (struct MessageEntry) +
3163 sizeof (struct PongMessage));
3164 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3168 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
3169 me->priority = PONG_PRIORITY;
3170 me->size = sizeof (struct PongMessage);
3171 tx.inbound_bw_limit = n->bw_in;
3172 tx.challenge = t.challenge;
3173 tx.target = t.target;
3174 tp = (struct PongMessage *) &me[1];
3175 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
3176 tp->header.size = htons (sizeof (struct PongMessage));
3177 tp->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3178 derive_pong_iv (&iv, &n->encrypt_key, tp->iv_seed, t.challenge, &n->peer);
3183 sizeof (struct PongMessage) -
3184 ((void *) &tp->challenge - (void *) tp));
3185 GNUNET_STATISTICS_update (stats,
3186 gettext_noop ("# PONG messages created"),
3190 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3191 "Encrypting `%s' with challenge %u using key %u, IV %u (salt %u)\n",
3193 (unsigned int) t.challenge,
3194 (unsigned int) n->encrypt_key.crc32,
3195 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3198 /* trigger queue processing */
3199 process_encrypted_neighbour_queue (n);
3204 * We received a PONG message. Validate and update our status.
3206 * @param n sender of the PONG
3207 * @param m the encrypted PONG message itself
3210 handle_pong (struct Neighbour *n,
3211 const struct PongMessage *m)
3213 struct PongMessage t;
3214 struct ConnectNotifyMessage cnm;
3215 struct GNUNET_CRYPTO_AesInitializationVector iv;
3218 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3219 "Core service receives `%s' response from `%4s'.\n",
3220 "PONG", GNUNET_i2s (&n->peer));
3222 /* mark as garbage, just to be sure */
3223 memset (&t, 255, sizeof (t));
3224 derive_pong_iv (&iv, &n->decrypt_key, m->iv_seed, n->ping_challenge,
3231 sizeof (struct PongMessage) -
3232 ((void *) &m->challenge - (void *) m)))
3234 GNUNET_break_op (0);
3237 GNUNET_STATISTICS_update (stats,
3238 gettext_noop ("# PONG messages decrypted"),
3242 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3243 "Decrypted `%s' from `%4s' with challenge %u using key %u, IV %u (salt %u)\n",
3245 GNUNET_i2s (&t.target),
3246 (unsigned int) t.challenge,
3247 (unsigned int) n->decrypt_key.crc32,
3248 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3251 if ((0 != memcmp (&t.target,
3253 sizeof (struct GNUNET_PeerIdentity))) ||
3254 (n->ping_challenge != t.challenge))
3256 /* PONG malformed */
3258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3259 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
3261 GNUNET_i2s (&n->peer),
3262 (unsigned int) n->ping_challenge);
3263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3264 "Received malformed `%s' received from `%4s' with challenge %u\n",
3265 "PONG", GNUNET_i2s (&t.target),
3266 (unsigned int) t.challenge);
3268 GNUNET_break_op (0);
3273 case PEER_STATE_DOWN:
3274 GNUNET_break (0); /* should be impossible */
3276 case PEER_STATE_KEY_SENT:
3277 GNUNET_break (0); /* should be impossible, how did we decrypt? */
3279 case PEER_STATE_KEY_RECEIVED:
3280 GNUNET_STATISTICS_update (stats,
3281 gettext_noop ("# Session keys confirmed via PONG"),
3284 n->status = PEER_STATE_KEY_CONFIRMED;
3285 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
3287 n->bw_out_external_limit = t.inbound_bw_limit;
3288 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3289 n->bw_out_internal_limit);
3290 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3292 GNUNET_TRANSPORT_set_quota (transport,
3296 GNUNET_TIME_UNIT_FOREVER_REL,
3300 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3301 "Confirmed key via `%s' message for peer `%4s'\n",
3302 "PONG", GNUNET_i2s (&n->peer));
3304 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3306 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3307 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3309 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3310 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3312 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
3313 process_encrypted_neighbour_queue (n);
3315 case PEER_STATE_KEY_CONFIRMED:
3316 n->last_activity = GNUNET_TIME_absolute_get ();
3317 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3318 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3320 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3323 handle_peer_status_change (n);
3333 * We received a SET_KEY message. Validate and update
3334 * our key material and status.
3336 * @param n the neighbour from which we received message m
3337 * @param m the set key message we received
3340 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
3342 struct SetKeyMessage *m_cpy;
3343 struct GNUNET_TIME_Absolute t;
3344 struct GNUNET_CRYPTO_AesSessionKey k;
3345 struct PingMessage *ping;
3346 struct PongMessage *pong;
3347 enum PeerStateMachine sender_status;
3350 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3351 "Core service receives `%s' request from `%4s'.\n",
3352 "SET_KEY", GNUNET_i2s (&n->peer));
3354 if (n->public_key == NULL)
3356 if (n->pitr != NULL)
3359 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3360 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3366 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3367 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3369 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3370 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3371 /* lookup n's public key, then try again */
3372 GNUNET_assert (n->skm == NULL);
3374 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3376 GNUNET_TIME_UNIT_MINUTES,
3377 &process_hello_retry_handle_set_key, n);
3378 GNUNET_STATISTICS_update (stats,
3379 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3384 if (0 != memcmp (&m->target,
3386 sizeof (struct GNUNET_PeerIdentity)))
3388 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3389 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3391 GNUNET_i2s (&m->target));
3394 if ((ntohl (m->purpose.size) !=
3395 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3396 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3397 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3398 sizeof (struct GNUNET_PeerIdentity)) ||
3400 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3401 &m->purpose, &m->signature, n->public_key)))
3403 /* invalid signature */
3404 GNUNET_break_op (0);
3407 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3408 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3409 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3410 (t.abs_value < n->decrypt_key_created.abs_value))
3412 /* this could rarely happen due to massive re-ordering of
3413 messages on the network level, but is most likely either
3414 a bug or some adversary messing with us. Report. */
3415 GNUNET_break_op (0);
3419 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3420 "Decrypting key material.\n");
3422 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3425 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3426 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3427 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3429 /* failed to decrypt !? */
3430 GNUNET_break_op (0);
3433 GNUNET_STATISTICS_update (stats,
3434 gettext_noop ("# SET_KEY messages decrypted"),
3438 if (n->decrypt_key_created.abs_value != t.abs_value)
3440 /* fresh key, reset sequence numbers */
3441 n->last_sequence_number_received = 0;
3442 n->last_packets_bitmap = 0;
3443 n->decrypt_key_created = t;
3445 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3448 case PEER_STATE_DOWN:
3449 n->status = PEER_STATE_KEY_RECEIVED;
3451 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3452 "Responding to `%s' with my own key.\n", "SET_KEY");
3456 case PEER_STATE_KEY_SENT:
3457 case PEER_STATE_KEY_RECEIVED:
3458 n->status = PEER_STATE_KEY_RECEIVED;
3459 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3460 (sender_status != PEER_STATE_KEY_CONFIRMED))
3463 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3464 "Responding to `%s' with my own key (other peer has status %u).\n",
3466 (unsigned int) sender_status);
3471 case PEER_STATE_KEY_CONFIRMED:
3472 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3473 (sender_status != PEER_STATE_KEY_CONFIRMED))
3476 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3477 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3479 (unsigned int) sender_status);
3488 if (n->pending_ping != NULL)
3490 ping = n->pending_ping;
3491 n->pending_ping = NULL;
3492 handle_ping (n, ping);
3495 if (n->pending_pong != NULL)
3497 pong = n->pending_pong;
3498 n->pending_pong = NULL;
3499 handle_pong (n, pong);
3506 * Send a P2P message to a client.
3508 * @param sender who sent us the message?
3509 * @param client who should we give the message to?
3510 * @param m contains the message to transmit
3511 * @param msize number of bytes in buf to transmit
3514 send_p2p_message_to_client (struct Neighbour *sender,
3515 struct Client *client,
3516 const void *m, size_t msize)
3518 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3519 struct NotifyTrafficMessage *ntm;
3522 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3523 "Core service passes message from `%4s' of type %u to client.\n",
3524 GNUNET_i2s(&sender->peer),
3525 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3527 ntm = (struct NotifyTrafficMessage *) buf;
3528 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3529 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3530 ntm->ats_count = htonl (0);
3531 ntm->ats.type = htonl (0);
3532 ntm->ats.value = htonl (0);
3533 ntm->peer = sender->peer;
3534 memcpy (&ntm[1], m, msize);
3535 send_to_client (client, &ntm->header, GNUNET_YES);
3540 * Deliver P2P message to interested clients.
3542 * @param cls always NULL
3543 * @param client who sent us the message (struct Neighbour)
3544 * @param m the message
3547 deliver_message (void *cls,
3549 const struct GNUNET_MessageHeader *m)
3551 struct Neighbour *sender = client;
3552 size_t msize = ntohs (m->size);
3554 struct Client *cpos;
3560 type = ntohs (m->type);
3562 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3563 "Received encapsulated message of type %u and size %u from `%4s'\n",
3564 (unsigned int) type,
3566 GNUNET_i2s (&sender->peer));
3568 GNUNET_snprintf (buf,
3570 gettext_noop ("# bytes of messages of type %u received"),
3571 (unsigned int) type);
3572 GNUNET_STATISTICS_set (stats,
3576 dropped = GNUNET_YES;
3578 while (cpos != NULL)
3580 deliver_full = GNUNET_NO;
3581 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3582 deliver_full = GNUNET_YES;
3585 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3587 if (type != cpos->types[tpos])
3589 deliver_full = GNUNET_YES;
3593 if (GNUNET_YES == deliver_full)
3595 send_p2p_message_to_client (sender, cpos, m, msize);
3596 dropped = GNUNET_NO;
3598 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3600 send_p2p_message_to_client (sender, cpos, m,
3601 sizeof (struct GNUNET_MessageHeader));
3605 if (dropped == GNUNET_YES)
3608 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3609 "Message of type %u from `%4s' not delivered to any client.\n",
3610 (unsigned int) type,
3611 GNUNET_i2s (&sender->peer));
3613 GNUNET_STATISTICS_update (stats,
3614 gettext_noop ("# messages not delivered to any client"),
3621 * We received an encrypted message. Decrypt, validate and
3622 * pass on to the appropriate clients.
3625 handle_encrypted_message (struct Neighbour *n,
3626 const struct EncryptedMessage *m)
3628 size_t size = ntohs (m->header.size);
3630 struct EncryptedMessage *pt; /* plaintext */
3633 struct GNUNET_TIME_Absolute t;
3634 struct GNUNET_CRYPTO_AesInitializationVector iv;
3635 struct GNUNET_CRYPTO_AuthKey auth_key;
3638 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3639 "Core service receives `%s' request from `%4s'.\n",
3640 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3643 derive_auth_key (&auth_key,
3646 n->decrypt_key_created);
3647 GNUNET_CRYPTO_hmac (&auth_key,
3648 &m->sequence_number,
3649 size - ENCRYPTED_HEADER_SIZE, &ph);
3651 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3652 "Re-Authenticated %u bytes of ciphertext (`%u'): `%s'\n",
3653 (unsigned int) size - ENCRYPTED_HEADER_SIZE,
3654 GNUNET_CRYPTO_crc32_n (&m->sequence_number,
3655 size - ENCRYPTED_HEADER_SIZE),
3659 if (0 != memcmp (&ph,
3661 sizeof (GNUNET_HashCode)))
3663 /* checksum failed */
3664 GNUNET_break_op (0);
3667 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3672 &m->sequence_number,
3673 &buf[ENCRYPTED_HEADER_SIZE],
3674 size - ENCRYPTED_HEADER_SIZE))
3676 pt = (struct EncryptedMessage *) buf;
3678 /* validate sequence number */
3679 snum = ntohl (pt->sequence_number);
3680 if (n->last_sequence_number_received == snum)
3682 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3683 "Received duplicate message, ignoring.\n");
3684 /* duplicate, ignore */
3685 GNUNET_STATISTICS_set (stats,
3686 gettext_noop ("# bytes dropped (duplicates)"),
3691 if ((n->last_sequence_number_received > snum) &&
3692 (n->last_sequence_number_received - snum > 32))
3694 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3695 "Received ancient out of sequence message, ignoring.\n");
3696 /* ancient out of sequence, ignore */
3697 GNUNET_STATISTICS_set (stats,
3698 gettext_noop ("# bytes dropped (out of sequence)"),
3703 if (n->last_sequence_number_received > snum)
3705 unsigned int rotbit =
3706 1 << (n->last_sequence_number_received - snum - 1);
3707 if ((n->last_packets_bitmap & rotbit) != 0)
3709 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3710 "Received duplicate message, ignoring.\n");
3711 GNUNET_STATISTICS_set (stats,
3712 gettext_noop ("# bytes dropped (duplicates)"),
3715 /* duplicate, ignore */
3718 n->last_packets_bitmap |= rotbit;
3720 if (n->last_sequence_number_received < snum)
3722 int shift = (snum - n->last_sequence_number_received);
3723 if (shift >= 8 * sizeof(n->last_packets_bitmap))
3724 n->last_packets_bitmap = 0;
3726 n->last_packets_bitmap <<= shift;
3727 n->last_sequence_number_received = snum;
3730 /* check timestamp */
3731 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3732 if (GNUNET_TIME_absolute_get_duration (t).rel_value > MAX_MESSAGE_AGE.rel_value)
3734 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3736 ("Message received far too old (%llu ms). Content ignored.\n"),
3737 GNUNET_TIME_absolute_get_duration (t).rel_value);
3738 GNUNET_STATISTICS_set (stats,
3739 gettext_noop ("# bytes dropped (ancient message)"),
3745 /* process decrypted message(s) */
3746 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3748 #if DEBUG_CORE_SET_QUOTA
3749 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3750 "Received %u b/s as new inbound limit for peer `%4s'\n",
3751 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3752 GNUNET_i2s (&n->peer));
3754 n->bw_out_external_limit = pt->inbound_bw_limit;
3755 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3756 n->bw_out_internal_limit);
3757 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3759 GNUNET_TRANSPORT_set_quota (transport,
3763 GNUNET_TIME_UNIT_FOREVER_REL,
3766 n->last_activity = GNUNET_TIME_absolute_get ();
3767 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3768 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3770 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3773 GNUNET_STATISTICS_set (stats,
3774 gettext_noop ("# bytes of payload decrypted"),
3775 size - sizeof (struct EncryptedMessage),
3777 handle_peer_status_change (n);
3778 if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst,
3780 &buf[sizeof (struct EncryptedMessage)],
3781 size - sizeof (struct EncryptedMessage),
3782 GNUNET_YES, GNUNET_NO))
3783 GNUNET_break_op (0);
3788 * Function called by the transport for each received message.
3790 * @param cls closure
3791 * @param peer (claimed) identity of the other peer
3792 * @param message the message
3793 * @param latency estimated latency for communicating with the
3794 * given peer (round-trip)
3795 * @param distance in overlay hops, as given by transport plugin
3798 handle_transport_receive (void *cls,
3799 const struct GNUNET_PeerIdentity *peer,
3800 const struct GNUNET_MessageHeader *message,
3801 struct GNUNET_TIME_Relative latency,
3802 unsigned int distance)
3804 struct Neighbour *n;
3805 struct GNUNET_TIME_Absolute now;
3812 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3813 "Received message of type %u from `%4s', demultiplexing.\n",
3814 (unsigned int) ntohs (message->type),
3817 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3822 n = find_neighbour (peer);
3824 n = create_neighbour (peer);
3825 changed = GNUNET_YES; /* FIXME... */
3826 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3827 type = ntohs (message->type);
3828 size = ntohs (message->size);
3831 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3832 if (size != sizeof (struct SetKeyMessage))
3834 GNUNET_break_op (0);
3837 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3838 handle_set_key (n, (const struct SetKeyMessage *) message);
3840 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3841 if (size < sizeof (struct EncryptedMessage) +
3842 sizeof (struct GNUNET_MessageHeader))
3844 GNUNET_break_op (0);
3847 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3848 (n->status != PEER_STATE_KEY_CONFIRMED))
3850 GNUNET_break_op (0);
3853 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3855 case GNUNET_MESSAGE_TYPE_CORE_PING:
3856 if (size != sizeof (struct PingMessage))
3858 GNUNET_break_op (0);
3861 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3862 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3863 (n->status != PEER_STATE_KEY_CONFIRMED))
3866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3867 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3868 "PING", GNUNET_i2s (&n->peer));
3870 GNUNET_free_non_null (n->pending_ping);
3871 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3872 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3875 handle_ping (n, (const struct PingMessage *) message);
3877 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3878 if (size != sizeof (struct PongMessage))
3880 GNUNET_break_op (0);
3883 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3884 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3885 (n->status != PEER_STATE_KEY_CONFIRMED) )
3888 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3889 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3890 "PONG", GNUNET_i2s (&n->peer));
3892 GNUNET_free_non_null (n->pending_pong);
3893 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3894 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3897 handle_pong (n, (const struct PongMessage *) message);
3900 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3901 _("Unsupported message of type %u received.\n"),
3902 (unsigned int) type);
3905 if (n->status == PEER_STATE_KEY_CONFIRMED)
3907 now = GNUNET_TIME_absolute_get ();
3908 n->last_activity = now;
3909 changed = GNUNET_YES;
3912 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3913 n->time_established = now;
3915 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3916 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3918 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3923 handle_peer_status_change (n);
3928 * Function that recalculates the bandwidth quota for the
3929 * given neighbour and transmits it to the transport service.
3931 * @param cls neighbour for the quota update
3935 neighbour_quota_update (void *cls,
3936 const struct GNUNET_SCHEDULER_TaskContext *tc)
3938 struct Neighbour *n = cls;
3939 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3942 unsigned long long distributable;
3943 uint64_t need_per_peer;
3944 uint64_t need_per_second;
3947 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3948 "Neighbour quota update calculation running for peer `%4s'\n",
3949 GNUNET_i2s (&n->peer));
3951 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3952 /* calculate relative preference among all neighbours;
3953 divides by a bit more to avoid division by zero AND to
3954 account for possibility of new neighbours joining any time
3955 AND to convert to double... */
3956 if (preference_sum == 0)
3958 pref_rel = 1.0 / (double) neighbour_count;
3962 pref_rel = n->current_preference / preference_sum;
3964 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3965 GNUNET_TIME_UNIT_SECONDS);
3966 need_per_second = need_per_peer * neighbour_count;
3968 if (bandwidth_target_out_bps > need_per_second)
3969 distributable = bandwidth_target_out_bps - need_per_second;
3970 share = distributable * pref_rel;
3971 if (share + need_per_peer > UINT32_MAX)
3972 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
3974 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3975 /* check if we want to disconnect for good due to inactivity */
3976 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) &&
3977 (GNUNET_TIME_absolute_get_duration (n->time_established).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) )
3980 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3981 "Forcing disconnect of `%4s' due to inactivity\n",
3982 GNUNET_i2s (&n->peer));
3984 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3986 #if DEBUG_CORE_QUOTA
3987 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3988 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3989 GNUNET_i2s (&n->peer),
3990 (unsigned int) ntohl (q_in.value__),
3991 bandwidth_target_out_bps,
3992 (unsigned int) ntohl (n->bw_in.value__),
3993 (unsigned int) ntohl (n->bw_out.value__),
3994 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3996 if (n->bw_in.value__ != q_in.value__)
3999 if (GNUNET_YES == n->is_connected)
4000 GNUNET_TRANSPORT_set_quota (transport,
4004 GNUNET_TIME_UNIT_FOREVER_REL,
4006 handle_peer_status_change (n);
4008 schedule_quota_update (n);
4013 * Function called by transport to notify us that
4014 * a peer connected to us (on the network level).
4016 * @param cls closure
4017 * @param peer the peer that connected
4018 * @param latency current latency of the connection
4019 * @param distance in overlay hops, as given by transport plugin
4022 handle_transport_notify_connect (void *cls,
4023 const struct GNUNET_PeerIdentity *peer,
4024 struct GNUNET_TIME_Relative latency,
4025 unsigned int distance)
4027 struct Neighbour *n;
4029 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4034 n = find_neighbour (peer);
4037 if (GNUNET_YES == n->is_connected)
4039 /* duplicate connect notification!? */
4046 n = create_neighbour (peer);
4048 GNUNET_STATISTICS_update (stats,
4049 gettext_noop ("# peers connected (transport)"),
4052 n->is_connected = GNUNET_YES;
4053 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
4056 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
4060 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4061 "Received connection from `%4s'.\n",
4062 GNUNET_i2s (&n->peer));
4064 GNUNET_TRANSPORT_set_quota (transport,
4068 GNUNET_TIME_UNIT_FOREVER_REL,
4075 * Function called by transport telling us that a peer
4078 * @param cls closure
4079 * @param peer the peer that disconnected
4082 handle_transport_notify_disconnect (void *cls,
4083 const struct GNUNET_PeerIdentity *peer)
4085 struct DisconnectNotifyMessage cnm;
4086 struct Neighbour *n;
4087 struct ClientActiveRequest *car;
4088 struct GNUNET_TIME_Relative left;
4091 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4092 "Peer `%4s' disconnected from us; received notification from transport.\n", GNUNET_i2s (peer));
4095 n = find_neighbour (peer);
4101 GNUNET_break (n->is_connected);
4102 if (n->status == PEER_STATE_KEY_CONFIRMED)
4104 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
4105 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
4107 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
4109 n->is_connected = GNUNET_NO;
4110 while (NULL != (car = n->active_client_request_head))
4112 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
4113 n->active_client_request_tail,
4115 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
4116 &n->peer.hashPubKey,
4121 GNUNET_STATISTICS_update (stats,
4122 gettext_noop ("# peers connected (transport)"),
4125 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
4126 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
4127 left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4128 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
4129 n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (),
4131 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
4132 &consider_free_task,
4138 * Last task run during shutdown. Disconnects us from
4142 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4144 struct Neighbour *n;
4148 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4149 "Core service shutting down.\n");
4151 GNUNET_assert (transport != NULL);
4152 GNUNET_TRANSPORT_disconnect (transport);
4154 while (NULL != (n = neighbours))
4156 neighbours = n->next;
4157 GNUNET_assert (neighbour_count > 0);
4161 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
4162 GNUNET_SERVER_notification_context_destroy (notifier);
4164 while (NULL != (c = clients))
4165 handle_client_disconnect (NULL, c->client_handle);
4166 if (my_private_key != NULL)
4167 GNUNET_CRYPTO_rsa_key_free (my_private_key);
4169 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4170 if (peerinfo != NULL)
4171 GNUNET_PEERINFO_disconnect (peerinfo);
4173 GNUNET_SERVER_mst_destroy (mst);
4178 * Initiate core service.
4180 * @param cls closure
4181 * @param server the initialized server
4182 * @param c configuration to use
4186 struct GNUNET_SERVER_Handle *server,
4187 const struct GNUNET_CONFIGURATION_Handle *c)
4189 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4190 {&handle_client_init, NULL,
4191 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
4192 {&handle_client_request_info, NULL,
4193 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
4194 sizeof (struct RequestInfoMessage)},
4195 {&handle_client_send_request, NULL,
4196 GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST,
4197 sizeof (struct SendMessageRequest)},
4198 {&handle_client_send, NULL,
4199 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
4200 {&handle_client_request_connect, NULL,
4201 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
4202 sizeof (struct ConnectMessage)},
4208 /* parse configuration */
4211 GNUNET_CONFIGURATION_get_value_number (c,
4214 &bandwidth_target_in_bps)) ||
4216 GNUNET_CONFIGURATION_get_value_number (c,
4219 &bandwidth_target_out_bps)) ||
4221 GNUNET_CONFIGURATION_get_value_filename (c,
4223 "HOSTKEY", &keyfile)))
4225 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4227 ("Core service is lacking key configuration settings. Exiting.\n"));
4228 GNUNET_SCHEDULER_shutdown ();
4231 peerinfo = GNUNET_PEERINFO_connect (cfg);
4232 if (NULL == peerinfo)
4234 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4235 _("Could not access PEERINFO service. Exiting.\n"));
4236 GNUNET_SCHEDULER_shutdown ();
4237 GNUNET_free (keyfile);
4240 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4241 GNUNET_free (keyfile);
4242 if (my_private_key == NULL)
4244 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4245 _("Core service could not access hostkey. Exiting.\n"));
4246 GNUNET_PEERINFO_disconnect (peerinfo);
4247 GNUNET_SCHEDULER_shutdown ();
4250 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4251 GNUNET_CRYPTO_hash (&my_public_key,
4252 sizeof (my_public_key), &my_identity.hashPubKey);
4253 /* setup notification */
4254 notifier = GNUNET_SERVER_notification_context_create (server,
4256 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4257 /* setup transport connection */
4258 transport = GNUNET_TRANSPORT_connect (cfg,
4261 &handle_transport_receive,
4262 &handle_transport_notify_connect,
4263 &handle_transport_notify_disconnect);
4264 GNUNET_assert (NULL != transport);
4265 stats = GNUNET_STATISTICS_create ("core", cfg);
4267 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded CORE_SEND requests"), 0, GNUNET_NO);
4268 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 0, GNUNET_NO);
4270 mst = GNUNET_SERVER_mst_create (&deliver_message,
4272 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4273 &cleaning_task, NULL);
4274 /* process client requests */
4275 GNUNET_SERVER_add_handlers (server, handlers);
4276 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4277 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
4283 * The main function for the transport service.
4285 * @param argc number of arguments from the command line
4286 * @param argv command line arguments
4287 * @return 0 ok, 1 on error
4290 main (int argc, char *const *argv)
4292 return (GNUNET_OK ==
4293 GNUNET_SERVICE_run (argc,
4296 GNUNET_SERVICE_OPTION_NONE,
4297 &run, NULL)) ? 0 : 1;
4300 /* end of gnunet-service-core.c */