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 * Number of bytes (at the beginning) of "struct EncryptedMessage"
165 * that are NOT encrypted.
167 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t))
171 * Encapsulation for encrypted messages exchanged between
172 * peers. Followed by the actual encrypted data.
174 struct EncryptedMessage
177 * Message type is either CORE_ENCRYPTED_MESSAGE.
179 struct GNUNET_MessageHeader header;
182 * Random value used for IV generation. ENCRYPTED_HEADER_SIZE must
183 * be set to the offset of the *next* field.
185 uint32_t iv_seed GNUNET_PACKED;
188 * Hash of the plaintext (starting at 'sequence_number'), used to
189 * verify message integrity. Everything after this hash (including
190 * this hash itself) will be encrypted.
192 GNUNET_HashCode hmac;
195 * Sequence number, in network byte order. This field
196 * must be the first encrypted/decrypted field and the
197 * first byte that is hashed for the plaintext hash.
199 uint32_t sequence_number GNUNET_PACKED;
202 * Desired bandwidth (how much we should send to this peer / how
203 * much is the sender willing to receive)?
205 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
208 * Timestamp. Used to prevent reply of ancient messages
209 * (recent messages are caught with the sequence number).
211 struct GNUNET_TIME_AbsoluteNBO timestamp;
217 * We're sending an (encrypted) PING to the other peer to check if he
218 * can decrypt. The other peer should respond with a PONG with the
219 * same content, except this time encrypted with the receiver's key.
224 * Message type is CORE_PING.
226 struct GNUNET_MessageHeader header;
231 uint32_t iv_seed GNUNET_PACKED;
234 * Random number chosen to make reply harder.
236 uint32_t challenge GNUNET_PACKED;
239 * Intended target of the PING, used primarily to check
240 * that decryption actually worked.
242 struct GNUNET_PeerIdentity target;
248 * Response to a PING. Includes data from the original PING
249 * plus initial bandwidth quota information.
254 * Message type is CORE_PONG.
256 struct GNUNET_MessageHeader header;
261 uint32_t iv_seed GNUNET_PACKED;
264 * Random number proochosen to make reply harder. Must be
265 * first field after header (this is where we start to encrypt!).
267 uint32_t challenge GNUNET_PACKED;
272 uint32_t reserved GNUNET_PACKED;
275 * Desired bandwidth (how much we should send to this
276 * peer / how much is the sender willing to receive).
278 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
281 * Intended target of the PING, used primarily to check
282 * that decryption actually worked.
284 struct GNUNET_PeerIdentity target;
289 * Message transmitted to set (or update) a session key.
295 * Message type is either CORE_SET_KEY.
297 struct GNUNET_MessageHeader header;
300 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
302 int32_t sender_status GNUNET_PACKED;
305 * Purpose of the signature, will be
306 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
308 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
311 * At what time was this key created?
313 struct GNUNET_TIME_AbsoluteNBO creation_time;
316 * The encrypted session key.
318 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
321 * Who is the intended recipient?
323 struct GNUNET_PeerIdentity target;
326 * Signature of the stuff above (starting at purpose).
328 struct GNUNET_CRYPTO_RsaSignature signature;
334 * Message waiting for transmission. This struct
335 * is followed by the actual content of the message.
341 * We keep messages in a doubly linked list.
343 struct MessageEntry *next;
346 * We keep messages in a doubly linked list.
348 struct MessageEntry *prev;
351 * By when are we supposed to transmit this message?
353 struct GNUNET_TIME_Absolute deadline;
356 * By when are we supposed to transmit this message (after
359 struct GNUNET_TIME_Absolute slack_deadline;
362 * How important is this message to us?
364 unsigned int priority;
367 * If this is a SET_KEY message, what was our connection status when this
368 * message was queued?
370 enum PeerStateMachine sender_status;
373 * Is this a SET_KEY message?
378 * How long is the message? (number of bytes following
379 * the "struct MessageEntry", but not including the
380 * size of "struct MessageEntry" itself!)
385 * Was this message selected for transmission in the
386 * current round? GNUNET_YES or GNUNET_NO.
391 * Did we give this message some slack (delayed sending) previously
392 * (and hence should not give it any more slack)? GNUNET_YES or
403 * We keep neighbours in a linked list (for now).
405 struct Neighbour *next;
408 * Unencrypted messages destined for this peer.
410 struct MessageEntry *messages;
413 * Head of the batched, encrypted message queue (already ordered,
414 * transmit starting with the head).
416 struct MessageEntry *encrypted_head;
419 * Tail of the batched, encrypted message queue (already ordered,
420 * append new messages to tail)
422 struct MessageEntry *encrypted_tail;
425 * Handle for pending requests for transmission to this peer
426 * with the transport service. NULL if no request is pending.
428 struct GNUNET_TRANSPORT_TransmitHandle *th;
431 * Public key of the neighbour, NULL if we don't have it yet.
433 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
436 * We received a PING message before we got the "public_key"
437 * (or the SET_KEY). We keep it here until we have a key
438 * to decrypt it. NULL if no PING is pending.
440 struct PingMessage *pending_ping;
443 * We received a PONG message before we got the "public_key"
444 * (or the SET_KEY). We keep it here until we have a key
445 * to decrypt it. NULL if no PONG is pending.
447 struct PongMessage *pending_pong;
450 * Non-NULL if we are currently looking up HELLOs for this peer.
453 struct GNUNET_PEERINFO_IteratorContext *pitr;
456 * SetKeyMessage to transmit, NULL if we are not currently trying
459 struct SetKeyMessage *skm;
462 * Identity of the neighbour.
464 struct GNUNET_PeerIdentity peer;
467 * Key we use to encrypt our messages for the other peer
468 * (initialized by us when we do the handshake).
470 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
473 * Key we use to decrypt messages from the other peer
474 * (given to us by the other peer during the handshake).
476 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
479 * Key we use to authenticate messages sent to the other peer
480 * (derived from the encrypt_key during the handshake)
482 struct GNUNET_CRYPTO_AuthKey encrypt_auth_key;
485 * Key we use to authenticate messages sent from the other peer
486 * (derived from the decrypt_key during the handshake)
488 struct GNUNET_CRYPTO_AuthKey decrypt_auth_key;
491 * ID of task used for re-trying plaintext scheduling.
493 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
496 * ID of task used for re-trying SET_KEY and PING message.
498 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
501 * ID of task used for updating bandwidth quota for this neighbour.
503 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
506 * ID of task used for sending keep-alive pings.
508 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
511 * ID of task used for cleaning up dead neighbour entries.
513 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
516 * At what time did we generate our encryption key?
518 struct GNUNET_TIME_Absolute encrypt_key_created;
521 * At what time did the other peer generate the decryption key?
523 struct GNUNET_TIME_Absolute decrypt_key_created;
526 * At what time did we initially establish (as in, complete session
527 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
529 struct GNUNET_TIME_Absolute time_established;
532 * At what time did we last receive an encrypted message from the
533 * other peer? Should be zero if status != KEY_CONFIRMED.
535 struct GNUNET_TIME_Absolute last_activity;
538 * Last latency observed from this peer.
540 struct GNUNET_TIME_Relative last_latency;
543 * At what frequency are we currently re-trying SET_KEY messages?
545 struct GNUNET_TIME_Relative set_key_retry_frequency;
548 * Tracking bandwidth for sending to this peer.
550 struct GNUNET_BANDWIDTH_Tracker available_send_window;
553 * Tracking bandwidth for receiving from this peer.
555 struct GNUNET_BANDWIDTH_Tracker available_recv_window;
558 * How valueable were the messages of this peer recently?
560 unsigned long long current_preference;
563 * Bit map indicating which of the 32 sequence numbers before the last
564 * were received (good for accepting out-of-order packets and
565 * estimating reliability of the connection)
567 unsigned int last_packets_bitmap;
570 * last sequence number received on this connection (highest)
572 uint32_t last_sequence_number_received;
575 * last sequence number transmitted
577 uint32_t last_sequence_number_sent;
580 * Available bandwidth in for this peer (current target).
582 struct GNUNET_BANDWIDTH_Value32NBO bw_in;
585 * Available bandwidth out for this peer (current target).
587 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
590 * Internal bandwidth limit set for this peer (initially typically
591 * set to "-1"). Actual "bw_out" is MIN of
592 * "bpm_out_internal_limit" and "bw_out_external_limit".
594 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
597 * External bandwidth limit set for this peer by the
598 * peer that we are communicating with. "bw_out" is MIN of
599 * "bw_out_internal_limit" and "bw_out_external_limit".
601 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
604 * What was our PING challenge number (for this peer)?
606 uint32_t ping_challenge;
609 * What was the last distance to this peer as reported by the transports?
611 uint32_t last_distance;
614 * What is our connection status?
616 enum PeerStateMachine status;
619 * Are we currently connected to this neighbour?
627 * Data structure for each client connected to the core service.
632 * Clients are kept in a linked list.
637 * Handle for the client with the server API.
639 struct GNUNET_SERVER_Client *client_handle;
642 * Array of the types of messages this peer cares
643 * about (with "tcnt" entries). Allocated as part
644 * of this client struct, do not free!
646 const uint16_t *types;
649 * Options for messages this client cares about,
650 * see GNUNET_CORE_OPTION_ values.
655 * Number of types of incoming messages this client
656 * specifically cares about. Size of the "types" array.
666 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
671 static struct GNUNET_PeerIdentity my_identity;
676 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
681 struct GNUNET_SCHEDULER_Handle *sched;
684 * Handle to peerinfo service.
686 static struct GNUNET_PEERINFO_Handle *peerinfo;
689 * Our message stream tokenizer (for encrypted payload).
691 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
696 const struct GNUNET_CONFIGURATION_Handle *cfg;
701 static struct GNUNET_TRANSPORT_Handle *transport;
704 * Linked list of our clients.
706 static struct Client *clients;
709 * Context for notifications we need to send to our clients.
711 static struct GNUNET_SERVER_NotificationContext *notifier;
714 * We keep neighbours in a linked list (for now).
716 static struct Neighbour *neighbours;
719 * For creating statistics.
721 static struct GNUNET_STATISTICS_Handle *stats;
724 * Sum of all preferences among all neighbours.
726 static unsigned long long preference_sum;
729 * Total number of neighbours we have.
731 static unsigned int neighbour_count;
734 * How much inbound bandwidth are we supposed to be using per second?
735 * FIXME: this value is not used!
737 static unsigned long long bandwidth_target_in_bps;
740 * How much outbound bandwidth are we supposed to be using per second?
742 static unsigned long long bandwidth_target_out_bps;
745 * Derive an authentication key from "set key" information
748 derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
749 const struct GNUNET_CRYPTO_AesSessionKey *skey,
750 const struct GNUNET_TIME_Absolute creation_time,
751 const struct GNUNET_PeerIdentity *identity)
753 static char ctx[] = "authentication key";
755 GNUNET_CRYPTO_hmac_derive_key (akey,
759 &identity->hashPubKey.bits,
760 sizeof(identity->hashPubKey.bits),
762 sizeof(creation_time),
769 * A preference value for a neighbour was update. Update
770 * the preference sum accordingly.
772 * @param inc how much was a preference value increased?
775 update_preference_sum (unsigned long long inc)
778 unsigned long long os;
781 preference_sum += inc;
782 if (preference_sum >= os)
784 /* overflow! compensate by cutting all values in half! */
789 n->current_preference /= 2;
790 preference_sum += n->current_preference;
793 GNUNET_STATISTICS_set (stats, gettext_noop ("# total peer preference"), preference_sum, GNUNET_NO);
798 * Find the entry for the given neighbour.
800 * @param peer identity of the neighbour
801 * @return NULL if we are not connected, otherwise the
804 static struct Neighbour *
805 find_neighbour (const struct GNUNET_PeerIdentity *peer)
807 struct Neighbour *ret;
810 while ((ret != NULL) &&
811 (0 != memcmp (&ret->peer,
812 peer, sizeof (struct GNUNET_PeerIdentity))))
819 * Send a message to one of our clients.
821 * @param client target for the message
822 * @param msg message to transmit
823 * @param can_drop could this message be dropped if the
824 * client's queue is getting too large?
827 send_to_client (struct Client *client,
828 const struct GNUNET_MessageHeader *msg,
831 #if DEBUG_CORE_CLIENT
832 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
833 "Preparing to send %u bytes of message of type %u to client.\n",
834 (unsigned int) ntohs (msg->size),
835 (unsigned int) ntohs (msg->type));
837 GNUNET_SERVER_notification_context_unicast (notifier,
838 client->client_handle,
845 * Send a message to all of our current clients that have
846 * the right options set.
848 * @param msg message to multicast
849 * @param can_drop can this message be discarded if the queue is too long
850 * @param options mask to use
853 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
862 if (0 != (c->options & options))
864 #if DEBUG_CORE_CLIENT
865 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
866 "Sending message of type %u to client.\n",
867 (unsigned int) ntohs (msg->type));
869 send_to_client (c, msg, can_drop);
877 * Function called by transport telling us that a peer
880 * @param n the peer that changed status
883 handle_peer_status_change (struct Neighbour *n)
885 struct PeerStatusNotifyMessage psnm;
887 if (! n->is_connected)
890 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
891 "Peer `%4s' changed status\n",
892 GNUNET_i2s (&n->peer));
894 psnm.header.size = htons (sizeof (struct PeerStatusNotifyMessage));
895 psnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_STATUS_CHANGE);
896 psnm.distance = htonl (n->last_distance);
897 psnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
898 psnm.timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_add (n->last_activity,
899 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
900 psnm.bandwidth_in = n->bw_in;
901 psnm.bandwidth_out = n->bw_out;
903 send_to_all_clients (&psnm.header,
905 GNUNET_CORE_OPTION_SEND_STATUS_CHANGE);
906 GNUNET_STATISTICS_update (stats,
907 gettext_noop ("# peer status changes"),
913 * Handle CORE_ITERATE_PEERS request.
916 handle_client_iterate_peers (void *cls,
917 struct GNUNET_SERVER_Client *client,
918 const struct GNUNET_MessageHeader *message)
921 struct ConnectNotifyMessage cnm;
922 struct GNUNET_MessageHeader done_msg;
923 struct GNUNET_SERVER_TransmitContext *tc;
925 /* notify new client about existing neighbours */
926 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
927 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
928 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
929 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
930 tc = GNUNET_SERVER_transmit_context_create (client);
934 if (n->status == PEER_STATE_KEY_CONFIRMED)
936 #if DEBUG_CORE_CLIENT
937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
938 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
940 cnm.distance = htonl (n->last_distance);
941 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
943 GNUNET_SERVER_transmit_context_append_message (tc, &cnm.header);
944 /*send_to_client (c, &cnm.header, GNUNET_NO);*/
949 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
950 GNUNET_SERVER_transmit_context_run (tc,
951 GNUNET_TIME_UNIT_FOREVER_REL);
956 * Handle CORE_INIT request.
959 handle_client_init (void *cls,
960 struct GNUNET_SERVER_Client *client,
961 const struct GNUNET_MessageHeader *message)
963 const struct InitMessage *im;
964 struct InitReplyMessage irm;
967 const uint16_t *types;
970 struct ConnectNotifyMessage cnm;
973 #if DEBUG_CORE_CLIENT
974 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
975 "Client connecting to core service with `%s' message\n",
978 /* check that we don't have an entry already */
982 if (client == c->client_handle)
985 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
990 msize = ntohs (message->size);
991 if (msize < sizeof (struct InitMessage))
994 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
997 GNUNET_SERVER_notification_context_add (notifier, client);
998 im = (const struct InitMessage *) message;
999 types = (const uint16_t *) &im[1];
1000 msize -= sizeof (struct InitMessage);
1001 c = GNUNET_malloc (sizeof (struct Client) + msize);
1002 c->client_handle = client;
1005 c->tcnt = msize / sizeof (uint16_t);
1006 c->types = (const uint16_t *) &c[1];
1007 wtypes = (uint16_t *) &c[1];
1008 for (i=0;i<c->tcnt;i++)
1009 wtypes[i] = ntohs (types[i]);
1010 c->options = ntohl (im->options);
1011 #if DEBUG_CORE_CLIENT
1012 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1013 "Client %p is interested in %u message types\n",
1015 (unsigned int) c->tcnt);
1017 /* send init reply message */
1018 irm.header.size = htons (sizeof (struct InitReplyMessage));
1019 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
1020 irm.reserved = htonl (0);
1021 memcpy (&irm.publicKey,
1023 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1024 #if DEBUG_CORE_CLIENT
1025 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1026 "Sending `%s' message to client.\n", "INIT_REPLY");
1028 send_to_client (c, &irm.header, GNUNET_NO);
1029 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
1031 /* notify new client about existing neighbours */
1032 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
1033 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1037 if (n->status == PEER_STATE_KEY_CONFIRMED)
1039 #if DEBUG_CORE_CLIENT
1040 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1041 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
1043 cnm.distance = htonl (n->last_distance);
1044 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
1046 send_to_client (c, &cnm.header, GNUNET_NO);
1051 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1056 * A client disconnected, clean up.
1058 * @param cls closure
1059 * @param client identification of the client
1062 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1065 struct Client *prev;
1069 #if DEBUG_CORE_CLIENT
1070 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1071 "Client %p has disconnected from core service.\n",
1078 if (client == pos->client_handle)
1081 clients = pos->next;
1083 prev->next = pos->next;
1090 /* client never sent INIT */
1095 * Handle REQUEST_INFO request.
1098 handle_client_request_info (void *cls,
1099 struct GNUNET_SERVER_Client *client,
1100 const struct GNUNET_MessageHeader *message)
1102 const struct RequestInfoMessage *rcm;
1103 struct Neighbour *n;
1104 struct ConfigurationInfoMessage cim;
1105 int32_t want_reserv;
1107 unsigned long long old_preference;
1108 struct GNUNET_SERVER_TransmitContext *tc;
1110 #if DEBUG_CORE_CLIENT
1111 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1112 "Core service receives `%s' request.\n", "REQUEST_INFO");
1114 rcm = (const struct RequestInfoMessage *) message;
1115 n = find_neighbour (&rcm->peer);
1116 memset (&cim, 0, sizeof (cim));
1119 want_reserv = ntohl (rcm->reserve_inbound);
1120 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1122 n->bw_out_internal_limit = rcm->limit_outbound;
1123 if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1124 n->bw_out_external_limit).value__)
1126 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1127 n->bw_out_external_limit);
1128 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1130 GNUNET_TRANSPORT_set_quota (transport,
1134 GNUNET_TIME_UNIT_FOREVER_REL,
1136 handle_peer_status_change (n);
1139 if (want_reserv < 0)
1141 got_reserv = want_reserv;
1143 else if (want_reserv > 0)
1145 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1146 want_reserv).value == 0)
1147 got_reserv = want_reserv;
1149 got_reserv = 0; /* all or nothing */
1153 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1155 old_preference = n->current_preference;
1156 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1157 if (old_preference > n->current_preference)
1159 /* overflow; cap at maximum value */
1160 n->current_preference = ULLONG_MAX;
1162 update_preference_sum (n->current_preference - old_preference);
1163 #if DEBUG_CORE_QUOTA
1164 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1165 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1167 GNUNET_i2s (&rcm->peer),
1170 cim.reserved_amount = htonl (got_reserv);
1171 cim.bw_in = n->bw_in;
1172 cim.bw_out = n->bw_out;
1173 cim.preference = n->current_preference;
1175 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1176 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1177 cim.peer = rcm->peer;
1179 #if DEBUG_CORE_CLIENT
1180 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1181 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1183 tc = GNUNET_SERVER_transmit_context_create (client);
1184 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1185 GNUNET_SERVER_transmit_context_run (tc,
1186 GNUNET_TIME_UNIT_FOREVER_REL);
1191 * Free the given entry for the neighbour (it has
1192 * already been removed from the list at this point).
1194 * @param n neighbour to free
1197 free_neighbour (struct Neighbour *n)
1199 struct MessageEntry *m;
1202 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1203 "Destroying neighbour entry for peer `%4s'\n",
1204 GNUNET_i2s (&n->peer));
1206 if (n->pitr != NULL)
1208 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1213 GNUNET_free (n->skm);
1216 while (NULL != (m = n->messages))
1218 n->messages = m->next;
1221 while (NULL != (m = n->encrypted_head))
1223 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1230 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1233 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1234 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1235 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1236 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1237 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1238 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1239 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1240 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1241 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1242 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1243 if (n->status == PEER_STATE_KEY_CONFIRMED)
1244 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1245 GNUNET_free_non_null (n->public_key);
1246 GNUNET_free_non_null (n->pending_ping);
1247 GNUNET_free_non_null (n->pending_pong);
1253 * Check if we have encrypted messages for the specified neighbour
1254 * pending, and if so, check with the transport about sending them
1257 * @param n neighbour to check.
1259 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1263 * Encrypt size bytes from in and write the result to out. Use the
1264 * key for outbound traffic of the given neighbour.
1266 * @param n neighbour we are sending to
1267 * @param iv initialization vector to use
1268 * @param in ciphertext
1269 * @param out plaintext
1270 * @param size size of in/out
1271 * @return GNUNET_OK on success
1274 do_encrypt (struct Neighbour *n,
1275 const GNUNET_HashCode * iv,
1276 const void *in, void *out, size_t size)
1278 if (size != (uint16_t) size)
1283 GNUNET_assert (size ==
1284 GNUNET_CRYPTO_aes_encrypt (in,
1288 GNUNET_CRYPTO_AesInitializationVector
1290 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1292 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1293 "Encrypted %u bytes for `%4s' using key %u\n",
1294 (unsigned int) size,
1295 GNUNET_i2s (&n->peer),
1296 (unsigned int) n->encrypt_key.crc32);
1303 * Consider freeing the given neighbour since we may not need
1304 * to keep it around anymore.
1306 * @param n neighbour to consider discarding
1309 consider_free_neighbour (struct Neighbour *n);
1313 * Task triggered when a neighbour entry is about to time out
1314 * (and we should prevent this by sending a PING).
1316 * @param cls the 'struct Neighbour'
1317 * @param tc scheduler context (not used)
1320 send_keep_alive (void *cls,
1321 const struct GNUNET_SCHEDULER_TaskContext *tc)
1323 struct Neighbour *n = cls;
1324 struct GNUNET_TIME_Relative retry;
1325 struct GNUNET_TIME_Relative left;
1326 struct MessageEntry *me;
1327 struct PingMessage pp;
1328 struct PingMessage *pm;
1330 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1332 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1333 sizeof (struct PingMessage));
1334 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1335 me->priority = PING_PRIORITY;
1336 me->size = sizeof (struct PingMessage);
1337 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1341 pm = (struct PingMessage *) &me[1];
1342 pm->header.size = htons (sizeof (struct PingMessage));
1343 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1344 pp.challenge = htonl (n->ping_challenge);
1345 pp.target = n->peer;
1347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1348 "Encrypting `%s' message with challenge %u for `%4s' using key %u.\n",
1350 (unsigned int) n->ping_challenge,
1351 GNUNET_i2s (&n->peer),
1352 (unsigned int) n->encrypt_key.crc32);
1355 &n->peer.hashPubKey,
1358 sizeof (struct PingMessage) -
1359 ((void *) &pm->challenge - (void *) pm));
1360 process_encrypted_neighbour_queue (n);
1361 /* reschedule PING job */
1362 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1363 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1364 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1365 MIN_PING_FREQUENCY);
1367 = GNUNET_SCHEDULER_add_delayed (sched,
1376 * Task triggered when a neighbour entry might have gotten stale.
1378 * @param cls the 'struct Neighbour'
1379 * @param tc scheduler context (not used)
1382 consider_free_task (void *cls,
1383 const struct GNUNET_SCHEDULER_TaskContext *tc)
1385 struct Neighbour *n = cls;
1387 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1388 consider_free_neighbour (n);
1393 * Consider freeing the given neighbour since we may not need
1394 * to keep it around anymore.
1396 * @param n neighbour to consider discarding
1399 consider_free_neighbour (struct Neighbour *n)
1401 struct Neighbour *pos;
1402 struct Neighbour *prev;
1403 struct GNUNET_TIME_Relative left;
1405 if ( (n->th != NULL) ||
1406 (n->pitr != NULL) ||
1407 (GNUNET_YES == n->is_connected) )
1408 return; /* no chance */
1410 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1411 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1414 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1415 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1416 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1418 &consider_free_task,
1422 /* actually free the neighbour... */
1431 neighbours = n->next;
1433 prev->next = n->next;
1434 GNUNET_assert (neighbour_count > 0);
1436 GNUNET_STATISTICS_set (stats,
1437 gettext_noop ("# neighbour entries allocated"),
1445 * Function called when the transport service is ready to
1446 * receive an encrypted message for the respective peer
1448 * @param cls neighbour to use message from
1449 * @param size number of bytes we can transmit
1450 * @param buf where to copy the message
1451 * @return number of bytes transmitted
1454 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1456 struct Neighbour *n = cls;
1457 struct MessageEntry *m;
1462 m = n->encrypted_head;
1466 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1467 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1468 GNUNET_i2s (&n->peer));
1472 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1479 GNUNET_assert (size >= m->size);
1480 memcpy (cbuf, &m[1], m->size);
1482 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1485 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1486 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1487 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1489 GNUNET_i2s (&n->peer));
1491 process_encrypted_neighbour_queue (n);
1496 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1497 "Transmission of message of type %u and size %u failed\n",
1498 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1499 (unsigned int) m->size);
1503 consider_free_neighbour (n);
1509 * Check if we have plaintext messages for the specified neighbour
1510 * pending, and if so, consider batching and encrypting them (and
1511 * then trigger processing of the encrypted queue if needed).
1513 * @param n neighbour to check.
1515 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1519 * Check if we have encrypted messages for the specified neighbour
1520 * pending, and if so, check with the transport about sending them
1523 * @param n neighbour to check.
1526 process_encrypted_neighbour_queue (struct Neighbour *n)
1528 struct MessageEntry *m;
1531 return; /* request already pending */
1532 m = n->encrypted_head;
1535 /* encrypted queue empty, try plaintext instead */
1536 process_plaintext_neighbour_queue (n);
1540 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1541 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1542 (unsigned int) m->size,
1543 GNUNET_i2s (&n->peer),
1544 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).
1548 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1551 GNUNET_TIME_absolute_get_remaining
1553 ¬ify_encrypted_transmit_ready,
1557 /* message request too large or duplicate request */
1559 /* discard encrypted message */
1560 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1564 process_encrypted_neighbour_queue (n);
1570 * Decrypt size bytes from in and write the result to out. Use the
1571 * key for inbound traffic of the given neighbour. This function does
1572 * NOT do any integrity-checks on the result.
1574 * @param n neighbour we are receiving from
1575 * @param iv initialization vector to use
1576 * @param in ciphertext
1577 * @param out plaintext
1578 * @param size size of in/out
1579 * @return GNUNET_OK on success
1582 do_decrypt (struct Neighbour *n,
1583 const GNUNET_HashCode * iv,
1584 const void *in, void *out, size_t size)
1586 if (size != (uint16_t) size)
1591 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1592 (n->status != PEER_STATE_KEY_CONFIRMED))
1594 GNUNET_break_op (0);
1595 return GNUNET_SYSERR;
1598 GNUNET_CRYPTO_aes_decrypt (in,
1602 GNUNET_CRYPTO_AesInitializationVector *) iv,
1606 return GNUNET_SYSERR;
1608 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1610 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1611 "Decrypted %u bytes from `%4s' using key %u\n",
1612 (unsigned int) size,
1613 GNUNET_i2s (&n->peer),
1614 (unsigned int) n->decrypt_key.crc32);
1621 * Select messages for transmission. This heuristic uses a combination
1622 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1623 * and priority-based discard (in case no feasible schedule exist) and
1624 * speculative optimization (defer any kind of transmission until
1625 * we either create a batch of significant size, 25% of max, or until
1626 * we are close to a deadline). Furthermore, when scheduling the
1627 * heuristic also packs as many messages into the batch as possible,
1628 * starting with those with the earliest deadline. Yes, this is fun.
1630 * @param n neighbour to select messages from
1631 * @param size number of bytes to select for transmission
1632 * @param retry_time set to the time when we should try again
1633 * (only valid if this function returns zero)
1634 * @return number of bytes selected, or 0 if we decided to
1635 * defer scheduling overall; in that case, retry_time is set.
1638 select_messages (struct Neighbour *n,
1639 size_t size, struct GNUNET_TIME_Relative *retry_time)
1641 struct MessageEntry *pos;
1642 struct MessageEntry *min;
1643 struct MessageEntry *last;
1644 unsigned int min_prio;
1645 struct GNUNET_TIME_Absolute t;
1646 struct GNUNET_TIME_Absolute now;
1647 struct GNUNET_TIME_Relative delta;
1649 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1652 unsigned int queue_size;
1653 int discard_low_prio;
1655 GNUNET_assert (NULL != n->messages);
1656 now = GNUNET_TIME_absolute_get ();
1657 /* last entry in linked list of messages processed */
1659 /* should we remove the entry with the lowest
1660 priority from consideration for scheduling at the
1671 discard_low_prio = GNUNET_YES;
1672 while (GNUNET_YES == discard_low_prio)
1675 min_prio = UINT_MAX;
1676 discard_low_prio = GNUNET_NO;
1677 /* calculate number of bytes available for transmission at time "t" */
1678 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1680 /* how many bytes have we (hypothetically) scheduled so far */
1682 /* maximum time we can wait before transmitting anything
1683 and still make all of our deadlines */
1684 slack = GNUNET_TIME_UNIT_FOREVER_REL;
1686 /* note that we use "*2" here because we want to look
1687 a bit further into the future; much more makes no
1688 sense since new message might be scheduled in the
1690 while ((pos != NULL) && (off < size * 2))
1692 if (pos->do_transmit == GNUNET_YES)
1694 /* already removed from consideration */
1698 if (discard_low_prio == GNUNET_NO)
1700 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1701 if (delta.value > 0)
1703 // FIXME: HUH? Check!
1705 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1708 if (avail < pos->size)
1710 // FIXME: HUH? Check!
1711 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1716 /* update slack, considering both its absolute deadline
1717 and relative deadlines caused by other messages
1718 with their respective load */
1719 slack = GNUNET_TIME_relative_min (slack,
1720 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1722 if (pos->deadline.value <= now.value)
1725 slack = GNUNET_TIME_UNIT_ZERO;
1727 else if (GNUNET_YES == pos->got_slack)
1729 /* should be soon now! */
1730 slack = GNUNET_TIME_relative_min (slack,
1731 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1736 GNUNET_TIME_relative_min (slack,
1737 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1738 pos->got_slack = GNUNET_YES;
1739 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1740 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
1745 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1746 if (pos->priority <= min_prio)
1748 /* update min for discard */
1749 min_prio = pos->priority;
1754 if (discard_low_prio)
1756 GNUNET_assert (min != NULL);
1757 /* remove lowest-priority entry from consideration */
1758 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1762 /* guard against sending "tiny" messages with large headers without
1764 if ( (slack.value > GNUNET_CONSTANTS_MAX_CORK_DELAY.value) &&
1766 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1768 /* less than 25% of message would be filled with deadlines still
1769 being met if we delay by one second or more; so just wait for
1770 more data; but do not wait longer than 1s (since we don't want
1771 to delay messages for a really long time either). */
1772 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1773 /* reset do_transmit values for next time */
1776 pos->do_transmit = GNUNET_NO;
1780 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1781 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1782 (unsigned long long) retry_time->value,
1784 (unsigned int) size);
1788 /* select marked messages (up to size) for transmission */
1793 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1795 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1799 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1800 "Selecting message of size %u for transmission\n",
1801 (unsigned int) pos->size);
1807 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1808 "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
1809 (unsigned int) pos->size,
1812 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1817 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1818 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1819 (unsigned long long) off, (unsigned long long) tsize,
1820 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
1821 GNUNET_i2s (&n->peer));
1828 * Batch multiple messages into a larger buffer.
1830 * @param n neighbour to take messages from
1831 * @param buf target buffer
1832 * @param size size of buf
1833 * @param deadline set to transmission deadline for the result
1834 * @param retry_time set to the time when we should try again
1835 * (only valid if this function returns zero)
1836 * @param priority set to the priority of the batch
1837 * @return number of bytes written to buf (can be zero)
1840 batch_message (struct Neighbour *n,
1843 struct GNUNET_TIME_Absolute *deadline,
1844 struct GNUNET_TIME_Relative *retry_time,
1845 unsigned int *priority)
1847 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1848 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1849 struct MessageEntry *pos;
1850 struct MessageEntry *prev;
1851 struct MessageEntry *next;
1856 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1857 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1858 if (0 == select_messages (n, size, retry_time))
1861 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1862 "No messages selected, will try again in %llu ms\n",
1867 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1868 ntm->distance = htonl (n->last_distance);
1869 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1870 ntm->peer = n->peer;
1873 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1876 if (GNUNET_YES == pos->do_transmit)
1878 GNUNET_assert (pos->size <= size);
1879 /* do notifications */
1880 /* FIXME: track if we have *any* client that wants
1881 full notifications and only do this if that is
1883 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1885 memcpy (&ntm[1], &pos[1], pos->size);
1886 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1887 sizeof (struct GNUNET_MessageHeader));
1888 send_to_all_clients (&ntm->header,
1890 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1894 /* message too large for 'full' notifications, we do at
1895 least the 'hdr' type */
1898 sizeof (struct GNUNET_MessageHeader));
1900 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1902 send_to_all_clients (&ntm->header,
1904 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1906 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1907 "Encrypting %u bytes with message of type %u and size %u\n",
1909 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
1910 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
1912 /* copy for encrypted transmission */
1913 memcpy (&buf[ret], &pos[1], pos->size);
1916 *priority += pos->priority;
1918 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1919 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1920 (unsigned int) pos->size,
1921 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1923 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1938 "Deadline for message batch is %llu ms\n",
1939 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1946 * Remove messages with deadlines that have long expired from
1949 * @param n neighbour to inspect
1952 discard_expired_messages (struct Neighbour *n)
1954 struct MessageEntry *prev;
1955 struct MessageEntry *next;
1956 struct MessageEntry *pos;
1957 struct GNUNET_TIME_Absolute now;
1958 struct GNUNET_TIME_Relative delta;
1960 now = GNUNET_TIME_absolute_get ();
1966 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1967 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1970 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1971 "Message is %llu ms past due, discarding.\n",
1988 * Signature of the main function of a task.
1990 * @param cls closure
1991 * @param tc context information (why was this task triggered now)
1994 retry_plaintext_processing (void *cls,
1995 const struct GNUNET_SCHEDULER_TaskContext *tc)
1997 struct Neighbour *n = cls;
1999 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2000 process_plaintext_neighbour_queue (n);
2005 * Send our key (and encrypted PING) to the other peer.
2007 * @param n the other peer
2009 static void send_key (struct Neighbour *n);
2012 * Task that will retry "send_key" if our previous attempt failed
2016 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2018 struct Neighbour *n = cls;
2021 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2022 "Retrying key transmission to `%4s'\n",
2023 GNUNET_i2s (&n->peer));
2025 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2026 n->set_key_retry_frequency =
2027 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2033 * Check if we have plaintext messages for the specified neighbour
2034 * pending, and if so, consider batching and encrypting them (and
2035 * then trigger processing of the encrypted queue if needed).
2037 * @param n neighbour to check.
2040 process_plaintext_neighbour_queue (struct Neighbour *n)
2042 char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)]; /* plaintext */
2045 struct EncryptedMessage *em; /* encrypted message */
2046 struct EncryptedMessage *ph; /* plaintext header */
2047 struct MessageEntry *me;
2048 unsigned int priority;
2049 struct GNUNET_TIME_Absolute deadline;
2050 struct GNUNET_TIME_Relative retry_time;
2053 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2055 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
2056 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2060 case PEER_STATE_DOWN:
2063 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2064 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2065 GNUNET_i2s(&n->peer));
2068 case PEER_STATE_KEY_SENT:
2069 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2070 n->retry_set_key_task
2071 = GNUNET_SCHEDULER_add_delayed (sched,
2072 n->set_key_retry_frequency,
2073 &set_key_retry_task, n);
2075 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2076 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2077 GNUNET_i2s(&n->peer));
2080 case PEER_STATE_KEY_RECEIVED:
2081 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2082 n->retry_set_key_task
2083 = GNUNET_SCHEDULER_add_delayed (sched,
2084 n->set_key_retry_frequency,
2085 &set_key_retry_task, n);
2087 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2088 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2089 GNUNET_i2s(&n->peer));
2092 case PEER_STATE_KEY_CONFIRMED:
2093 /* ready to continue */
2096 discard_expired_messages (n);
2097 if (n->messages == NULL)
2100 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2101 "Plaintext message queue for `%4s' is empty.\n",
2102 GNUNET_i2s(&n->peer));
2104 return; /* no pending messages */
2106 if (n->encrypted_head != NULL)
2109 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2110 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2111 GNUNET_i2s(&n->peer));
2113 return; /* wait for messages already encrypted to be
2116 ph = (struct EncryptedMessage *) pbuf;
2117 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2119 used = sizeof (struct EncryptedMessage);
2120 used += batch_message (n,
2122 GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2123 &deadline, &retry_time, &priority);
2124 if (used == sizeof (struct EncryptedMessage))
2127 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2128 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2129 GNUNET_i2s(&n->peer));
2131 /* no messages selected for sending, try again later... */
2132 n->retry_plaintext_task =
2133 GNUNET_SCHEDULER_add_delayed (sched,
2135 &retry_plaintext_processing, n);
2138 #if DEBUG_CORE_QUOTA
2139 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2140 "Sending %u b/s as new limit to peer `%4s'\n",
2141 (unsigned int) ntohl (n->bw_in.value__),
2142 GNUNET_i2s (&n->peer));
2144 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX));
2145 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2146 ph->inbound_bw_limit = n->bw_in;
2147 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2149 /* setup encryption message header */
2150 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2151 me->deadline = deadline;
2152 me->priority = priority;
2154 em = (struct EncryptedMessage *) &me[1];
2155 em->header.size = htons (used);
2156 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2157 em->iv_seed = ph->iv_seed;
2158 esize = used - ENCRYPTED_HEADER_SIZE;
2159 GNUNET_CRYPTO_hmac (&n->encrypt_auth_key,
2160 &ph->sequence_number,
2161 esize - sizeof (GNUNET_HashCode),
2163 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
2165 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2166 "Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
2167 (unsigned int) (esize - sizeof (GNUNET_HashCode)),
2168 GNUNET_h2s (&ph->hmac),
2173 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2174 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2175 (unsigned int) esize,
2176 GNUNET_i2s(&n->peer),
2177 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2179 GNUNET_assert (GNUNET_OK ==
2184 /* append to transmission list */
2185 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2189 process_encrypted_neighbour_queue (n);
2194 * Function that recalculates the bandwidth quota for the
2195 * given neighbour and transmits it to the transport service.
2197 * @param cls neighbour for the quota update
2201 neighbour_quota_update (void *cls,
2202 const struct GNUNET_SCHEDULER_TaskContext *tc);
2206 * Schedule the task that will recalculate the bandwidth
2207 * quota for this peer (and possibly force a disconnect of
2208 * idle peers by calculating a bandwidth of zero).
2211 schedule_quota_update (struct Neighbour *n)
2213 GNUNET_assert (n->quota_update_task ==
2214 GNUNET_SCHEDULER_NO_TASK);
2215 n->quota_update_task
2216 = GNUNET_SCHEDULER_add_delayed (sched,
2217 QUOTA_UPDATE_FREQUENCY,
2218 &neighbour_quota_update,
2224 * Initialize a new 'struct Neighbour'.
2226 * @param pid ID of the new neighbour
2227 * @return handle for the new neighbour
2229 static struct Neighbour *
2230 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2232 struct Neighbour *n;
2233 struct GNUNET_TIME_Absolute now;
2236 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2237 "Creating neighbour entry for peer `%4s'\n",
2240 n = GNUNET_malloc (sizeof (struct Neighbour));
2241 n->next = neighbours;
2244 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2246 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2247 now = GNUNET_TIME_absolute_get ();
2248 n->encrypt_key_created = now;
2249 n->last_activity = now;
2250 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2251 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2252 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2253 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2254 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2255 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2257 derive_auth_key (&n->encrypt_auth_key, &n->encrypt_key, now, &n->peer);
2258 neighbour_quota_update (n, NULL);
2259 consider_free_neighbour (n);
2265 * Handle CORE_SEND request.
2268 * @param client the client issuing the request
2269 * @param message the "struct SendMessage"
2272 handle_client_send (void *cls,
2273 struct GNUNET_SERVER_Client *client,
2274 const struct GNUNET_MessageHeader *message)
2276 const struct SendMessage *sm;
2277 struct Neighbour *n;
2278 struct MessageEntry *prev;
2279 struct MessageEntry *pos;
2280 struct MessageEntry *e;
2281 struct MessageEntry *min_prio_entry;
2282 struct MessageEntry *min_prio_prev;
2283 unsigned int min_prio;
2284 unsigned int queue_size;
2287 msize = ntohs (message->size);
2289 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2291 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));
2294 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2297 sm = (const struct SendMessage *) message;
2298 msize -= sizeof (struct SendMessage);
2299 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2301 /* FIXME: should we not allow loopback-injection here? */
2304 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2307 n = find_neighbour (&sm->peer);
2309 n = create_neighbour (&sm->peer);
2311 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2312 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2314 (unsigned int) msize,
2315 GNUNET_i2s (&sm->peer));
2317 /* bound queue size */
2318 discard_expired_messages (n);
2319 min_prio = UINT32_MAX;
2320 min_prio_entry = NULL;
2321 min_prio_prev = NULL;
2327 if (pos->priority <= min_prio)
2329 min_prio_entry = pos;
2330 min_prio_prev = prev;
2331 min_prio = pos->priority;
2337 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2340 if (ntohl(sm->priority) <= min_prio)
2342 /* discard new entry */
2344 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2345 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2347 (unsigned int) MAX_PEER_QUEUE_SIZE,
2348 (unsigned int) msize,
2349 (unsigned int) ntohs (message->type));
2352 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2355 GNUNET_assert (min_prio_entry != NULL);
2356 /* discard "min_prio_entry" */
2358 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2359 "Queue full, discarding existing older request\n");
2361 if (min_prio_prev == NULL)
2362 n->messages = min_prio_entry->next;
2364 min_prio_prev->next = min_prio_entry->next;
2365 GNUNET_free (min_prio_entry);
2369 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2370 "Adding transmission request for `%4s' of size %u to queue\n",
2371 GNUNET_i2s (&sm->peer),
2372 (unsigned int) msize);
2374 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2375 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2376 e->priority = ntohl (sm->priority);
2378 memcpy (&e[1], &sm[1], msize);
2380 /* insert, keep list sorted by deadline */
2383 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2394 /* consider scheduling now */
2395 process_plaintext_neighbour_queue (n);
2397 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2402 * Function called when the transport service is ready to
2403 * receive a message. Only resets 'n->th' to NULL.
2405 * @param cls neighbour to use message from
2406 * @param size number of bytes we can transmit
2407 * @param buf where to copy the message
2408 * @return number of bytes transmitted
2411 notify_transport_connect_done (void *cls, size_t size, void *buf)
2413 struct Neighbour *n = cls;
2415 if (GNUNET_YES != n->is_connected)
2417 /* transport should only call us to transmit a message after
2418 * telling us about a successful connection to the respective peer */
2419 n->th = NULL; /* If this happens because of a timeout, reset n-th so another message may be sent for this peer! */
2421 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Timeout on notify connect!\n");
2428 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2429 _("Failed to connect to `%4s': transport failed to connect\n"),
2430 GNUNET_i2s (&n->peer));
2433 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2434 _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2435 GNUNET_i2s (&n->peer));
2436 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2437 GNUNET_SCHEDULER_cancel (sched,
2438 n->retry_set_key_task);
2439 n->retry_set_key_task = GNUNET_SCHEDULER_add_now (sched,
2440 &set_key_retry_task,
2447 * Handle CORE_REQUEST_CONNECT request.
2450 * @param client the client issuing the request
2451 * @param message the "struct ConnectMessage"
2454 handle_client_request_connect (void *cls,
2455 struct GNUNET_SERVER_Client *client,
2456 const struct GNUNET_MessageHeader *message)
2458 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2459 struct Neighbour *n;
2460 struct GNUNET_TIME_Relative timeout;
2462 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2465 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2468 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2469 n = find_neighbour (&cm->peer);
2471 n = create_neighbour (&cm->peer);
2472 if ( (GNUNET_YES == n->is_connected) ||
2475 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2476 "Core received `%s' request for `%4s', already connected!\n",
2478 GNUNET_i2s (&cm->peer));
2479 return; /* already connected, or at least trying */
2481 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2483 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2484 "Core received `%s' request for `%4s', will try to establish connection\n",
2486 GNUNET_i2s (&cm->peer));
2488 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2489 /* ask transport to connect to the peer */
2490 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2492 sizeof (struct GNUNET_MessageHeader), 0,
2494 ¬ify_transport_connect_done,
2496 GNUNET_break (NULL != n->th);
2501 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2502 * the neighbour's struct and retry send_key. Or, if we did not get a
2503 * HELLO, just do nothing.
2505 * @param cls the 'struct Neighbour' to retry sending the key for
2506 * @param peer the peer for which this is the HELLO
2507 * @param hello HELLO message of that peer
2510 process_hello_retry_send_key (void *cls,
2511 const struct GNUNET_PeerIdentity *peer,
2512 const struct GNUNET_HELLO_Message *hello)
2514 struct Neighbour *n = cls;
2519 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2520 "Entered `%s' and `%s' is NULL!\n",
2521 "process_hello_retry_send_key",
2525 if (n->public_key != NULL)
2527 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2529 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2530 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2532 GNUNET_STATISTICS_update (stats,
2533 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2542 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
2543 GNUNET_i2s (&n->peer));
2545 GNUNET_STATISTICS_update (stats,
2546 gettext_noop ("# Delayed connecting due to lack of public key"),
2549 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2550 n->retry_set_key_task
2551 = GNUNET_SCHEDULER_add_delayed (sched,
2552 n->set_key_retry_frequency,
2553 &set_key_retry_task, n);
2559 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2560 "Entered `%s' for peer `%4s'\n",
2561 "process_hello_retry_send_key",
2564 if (n->public_key != NULL)
2566 /* already have public key, why are we here? */
2572 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2573 "Received new `%s' message for `%4s', initiating key exchange.\n",
2578 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2579 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2581 GNUNET_STATISTICS_update (stats,
2582 gettext_noop ("# Error extracting public key from HELLO"),
2585 GNUNET_free (n->public_key);
2586 n->public_key = NULL;
2588 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2589 "GNUNET_HELLO_get_key returned awfully\n");
2597 * Send our key (and encrypted PING) to the other peer.
2599 * @param n the other peer
2602 send_key (struct Neighbour *n)
2604 struct MessageEntry *pos;
2605 struct SetKeyMessage *sm;
2606 struct MessageEntry *me;
2607 struct PingMessage pp;
2608 struct PingMessage *pm;
2610 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2612 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2613 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2615 if (n->pitr != NULL)
2618 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2619 "Key exchange in progress with `%4s'.\n",
2620 GNUNET_i2s (&n->peer));
2622 return; /* already in progress */
2624 if (GNUNET_YES != n->is_connected)
2627 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2628 "Not yet connected to peer `%4s'!\n",
2629 GNUNET_i2s (&n->peer));
2633 GNUNET_STATISTICS_update (stats,
2634 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
2637 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2639 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2641 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2642 ¬ify_encrypted_transmit_ready,
2648 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2649 "Asked to perform key exchange with `%4s'.\n",
2650 GNUNET_i2s (&n->peer));
2652 if (n->public_key == NULL)
2654 /* lookup n's public key, then try again */
2656 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2657 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2658 GNUNET_i2s (&n->peer));
2660 GNUNET_assert (n->pitr == NULL);
2661 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2663 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2664 &process_hello_retry_send_key, n);
2667 pos = n->encrypted_head;
2670 if (GNUNET_YES == pos->is_setkey)
2672 if (pos->sender_status == n->status)
2675 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2676 "`%s' message for `%4s' queued already\n",
2678 GNUNET_i2s (&n->peer));
2680 goto trigger_processing;
2682 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2687 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2688 "Removing queued `%s' message for `%4s', will create a new one\n",
2690 GNUNET_i2s (&n->peer));
2700 case PEER_STATE_DOWN:
2701 n->status = PEER_STATE_KEY_SENT;
2703 case PEER_STATE_KEY_SENT:
2705 case PEER_STATE_KEY_RECEIVED:
2707 case PEER_STATE_KEY_CONFIRMED:
2715 /* first, set key message */
2716 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2717 sizeof (struct SetKeyMessage) +
2718 sizeof (struct PingMessage));
2719 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2720 me->priority = SET_KEY_PRIORITY;
2721 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
2722 me->is_setkey = GNUNET_YES;
2723 me->got_slack = GNUNET_YES; /* do not defer this one! */
2724 me->sender_status = n->status;
2725 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2729 sm = (struct SetKeyMessage *) &me[1];
2730 sm->header.size = htons (sizeof (struct SetKeyMessage));
2731 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2732 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2733 PEER_STATE_KEY_SENT : n->status));
2735 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2736 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2737 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2738 sizeof (struct GNUNET_PeerIdentity));
2739 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2740 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2741 sm->target = n->peer;
2742 GNUNET_assert (GNUNET_OK ==
2743 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2745 GNUNET_CRYPTO_AesSessionKey),
2747 &sm->encrypted_key));
2748 GNUNET_assert (GNUNET_OK ==
2749 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2751 pm = (struct PingMessage *) &sm[1];
2752 pm->header.size = htons (sizeof (struct PingMessage));
2753 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2754 pp.challenge = htonl (n->ping_challenge);
2755 pp.target = n->peer;
2757 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2758 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u.\n",
2760 (unsigned int) n->ping_challenge,
2761 GNUNET_i2s (&n->peer),
2762 (unsigned int) n->encrypt_key.crc32);
2765 &n->peer.hashPubKey,
2768 sizeof (struct PingMessage) -
2769 ((void *) &pm->challenge - (void *) pm));
2770 GNUNET_STATISTICS_update (stats,
2771 gettext_noop ("# SET_KEY and PING messages created"),
2775 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2776 "Have %llu ms left for `%s' transmission.\n",
2777 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2781 /* trigger queue processing */
2782 process_encrypted_neighbour_queue (n);
2783 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2784 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2785 n->retry_set_key_task
2786 = GNUNET_SCHEDULER_add_delayed (sched,
2787 n->set_key_retry_frequency,
2788 &set_key_retry_task, n);
2793 * We received a SET_KEY message. Validate and update
2794 * our key material and status.
2796 * @param n the neighbour from which we received message m
2797 * @param m the set key message we received
2800 handle_set_key (struct Neighbour *n,
2801 const struct SetKeyMessage *m);
2805 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2806 * the neighbour's struct and retry handling the set_key message. Or,
2807 * if we did not get a HELLO, just free the set key message.
2809 * @param cls pointer to the set key message
2810 * @param peer the peer for which this is the HELLO
2811 * @param hello HELLO message of that peer
2814 process_hello_retry_handle_set_key (void *cls,
2815 const struct GNUNET_PeerIdentity *peer,
2816 const struct GNUNET_HELLO_Message *hello)
2818 struct Neighbour *n = cls;
2819 struct SetKeyMessage *sm = n->skm;
2825 if (n->public_key != NULL)
2828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2829 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2831 GNUNET_i2s (&n->peer),
2834 handle_set_key (n, sm);
2838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2839 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
2841 GNUNET_i2s (&n->peer));
2846 if (n->public_key != NULL)
2847 return; /* multiple HELLOs match!? */
2849 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2850 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2852 GNUNET_break_op (0);
2853 GNUNET_free (n->public_key);
2854 n->public_key = NULL;
2860 * We received a PING message. Validate and transmit
2863 * @param n sender of the PING
2864 * @param m the encrypted PING message itself
2867 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2869 struct PingMessage t;
2870 struct PongMessage tx;
2871 struct PongMessage *tp;
2872 struct MessageEntry *me;
2875 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2876 "Core service receives `%s' request from `%4s'.\n",
2877 "PING", GNUNET_i2s (&n->peer));
2881 &my_identity.hashPubKey,
2884 sizeof (struct PingMessage) -
2885 ((void *) &m->challenge - (void *) m)))
2888 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2889 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2891 GNUNET_i2s (&t.target),
2892 (unsigned int) ntohl (t.challenge),
2893 (unsigned int) n->decrypt_key.crc32);
2895 GNUNET_STATISTICS_update (stats,
2896 gettext_noop ("# PING messages decrypted"),
2899 if (0 != memcmp (&t.target,
2900 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2902 GNUNET_break_op (0);
2905 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2906 sizeof (struct PongMessage));
2907 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2911 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2912 me->priority = PONG_PRIORITY;
2913 me->size = sizeof (struct PongMessage);
2914 tx.reserved = htonl (0);
2915 tx.inbound_bw_limit = n->bw_in;
2916 tx.challenge = t.challenge;
2917 tx.target = t.target;
2918 tp = (struct PongMessage *) &me[1];
2919 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2920 tp->header.size = htons (sizeof (struct PongMessage));
2922 &my_identity.hashPubKey,
2925 sizeof (struct PongMessage) -
2926 ((void *) &tp->challenge - (void *) tp));
2927 GNUNET_STATISTICS_update (stats,
2928 gettext_noop ("# PONG messages created"),
2932 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2933 "Encrypting `%s' with challenge %u using key %u\n",
2935 (unsigned int) ntohl (t.challenge),
2936 (unsigned int) n->encrypt_key.crc32);
2938 /* trigger queue processing */
2939 process_encrypted_neighbour_queue (n);
2944 * We received a PONG message. Validate and update our status.
2946 * @param n sender of the PONG
2947 * @param m the encrypted PONG message itself
2950 handle_pong (struct Neighbour *n,
2951 const struct PongMessage *m)
2953 struct PongMessage t;
2954 struct ConnectNotifyMessage cnm;
2957 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2958 "Core service receives `%s' response from `%4s'.\n",
2959 "PONG", GNUNET_i2s (&n->peer));
2961 /* mark as garbage, just to be sure */
2962 memset (&t, 255, sizeof (t));
2965 &n->peer.hashPubKey,
2968 sizeof (struct PongMessage) -
2969 ((void *) &m->challenge - (void *) m)))
2971 GNUNET_break_op (0);
2974 GNUNET_STATISTICS_update (stats,
2975 gettext_noop ("# PONG messages decrypted"),
2978 if (0 != ntohl (t.reserved))
2980 GNUNET_break_op (0);
2984 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2985 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2987 GNUNET_i2s (&t.target),
2988 (unsigned int) ntohl (t.challenge),
2989 (unsigned int) n->decrypt_key.crc32);
2991 if ((0 != memcmp (&t.target,
2993 sizeof (struct GNUNET_PeerIdentity))) ||
2994 (n->ping_challenge != ntohl (t.challenge)))
2996 /* PONG malformed */
2998 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2999 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
3001 GNUNET_i2s (&n->peer),
3002 (unsigned int) n->ping_challenge);
3003 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3004 "Received malformed `%s' received from `%4s' with challenge %u\n",
3005 "PONG", GNUNET_i2s (&t.target),
3006 (unsigned int) ntohl (t.challenge));
3008 GNUNET_break_op (0);
3013 case PEER_STATE_DOWN:
3014 GNUNET_break (0); /* should be impossible */
3016 case PEER_STATE_KEY_SENT:
3017 GNUNET_break (0); /* should be impossible, how did we decrypt? */
3019 case PEER_STATE_KEY_RECEIVED:
3020 GNUNET_STATISTICS_update (stats,
3021 gettext_noop ("# Session keys confirmed via PONG"),
3024 n->status = PEER_STATE_KEY_CONFIRMED;
3025 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
3027 n->bw_out_external_limit = t.inbound_bw_limit;
3028 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3029 n->bw_out_internal_limit);
3030 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3032 GNUNET_TRANSPORT_set_quota (transport,
3036 GNUNET_TIME_UNIT_FOREVER_REL,
3040 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3041 "Confirmed key via `%s' message for peer `%4s'\n",
3042 "PONG", GNUNET_i2s (&n->peer));
3044 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3046 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
3047 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3049 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3050 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3051 cnm.distance = htonl (n->last_distance);
3052 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3054 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
3055 process_encrypted_neighbour_queue (n);
3057 case PEER_STATE_KEY_CONFIRMED:
3058 n->last_activity = GNUNET_TIME_absolute_get ();
3059 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3060 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3062 = GNUNET_SCHEDULER_add_delayed (sched,
3063 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3066 handle_peer_status_change (n);
3076 * We received a SET_KEY message. Validate and update
3077 * our key material and status.
3079 * @param n the neighbour from which we received message m
3080 * @param m the set key message we received
3083 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
3085 struct SetKeyMessage *m_cpy;
3086 struct GNUNET_TIME_Absolute t;
3087 struct GNUNET_CRYPTO_AesSessionKey k;
3088 struct PingMessage *ping;
3089 struct PongMessage *pong;
3090 enum PeerStateMachine sender_status;
3093 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3094 "Core service receives `%s' request from `%4s'.\n",
3095 "SET_KEY", GNUNET_i2s (&n->peer));
3097 if (n->public_key == NULL)
3099 if (n->pitr != NULL)
3102 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3103 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3109 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3110 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3112 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3113 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3114 /* lookup n's public key, then try again */
3115 GNUNET_assert (n->skm == NULL);
3117 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3119 GNUNET_TIME_UNIT_MINUTES,
3120 &process_hello_retry_handle_set_key, n);
3121 GNUNET_STATISTICS_update (stats,
3122 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3127 if (0 != memcmp (&m->target,
3129 sizeof (struct GNUNET_PeerIdentity)))
3131 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3132 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3134 GNUNET_i2s (&m->target));
3137 if ((ntohl (m->purpose.size) !=
3138 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3139 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3140 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3141 sizeof (struct GNUNET_PeerIdentity)) ||
3143 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3144 &m->purpose, &m->signature, n->public_key)))
3146 /* invalid signature */
3147 GNUNET_break_op (0);
3150 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3151 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3152 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3153 (t.value < n->decrypt_key_created.value))
3155 /* this could rarely happen due to massive re-ordering of
3156 messages on the network level, but is most likely either
3157 a bug or some adversary messing with us. Report. */
3158 GNUNET_break_op (0);
3162 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3163 "Decrypting key material.\n");
3165 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3168 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3169 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3170 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3172 /* failed to decrypt !? */
3173 GNUNET_break_op (0);
3176 GNUNET_STATISTICS_update (stats,
3177 gettext_noop ("# SET_KEY messages decrypted"),
3181 if (n->decrypt_key_created.value != t.value)
3183 /* fresh key, reset sequence numbers */
3184 n->last_sequence_number_received = 0;
3185 n->last_packets_bitmap = 0;
3186 n->decrypt_key_created = t;
3188 derive_auth_key(&n->decrypt_auth_key, &k, n->decrypt_key_created, &my_identity);
3189 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3192 case PEER_STATE_DOWN:
3193 n->status = PEER_STATE_KEY_RECEIVED;
3195 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3196 "Responding to `%s' with my own key.\n", "SET_KEY");
3200 case PEER_STATE_KEY_SENT:
3201 case PEER_STATE_KEY_RECEIVED:
3202 n->status = PEER_STATE_KEY_RECEIVED;
3203 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3204 (sender_status != PEER_STATE_KEY_CONFIRMED))
3207 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3208 "Responding to `%s' with my own key (other peer has status %u).\n",
3210 (unsigned int) sender_status);
3215 case PEER_STATE_KEY_CONFIRMED:
3216 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3217 (sender_status != PEER_STATE_KEY_CONFIRMED))
3220 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3221 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3223 (unsigned int) sender_status);
3232 if (n->pending_ping != NULL)
3234 ping = n->pending_ping;
3235 n->pending_ping = NULL;
3236 handle_ping (n, ping);
3239 if (n->pending_pong != NULL)
3241 pong = n->pending_pong;
3242 n->pending_pong = NULL;
3243 handle_pong (n, pong);
3250 * Send a P2P message to a client.
3252 * @param sender who sent us the message?
3253 * @param client who should we give the message to?
3254 * @param m contains the message to transmit
3255 * @param msize number of bytes in buf to transmit
3258 send_p2p_message_to_client (struct Neighbour *sender,
3259 struct Client *client,
3260 const void *m, size_t msize)
3262 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3263 struct NotifyTrafficMessage *ntm;
3266 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3267 "Core service passes message from `%4s' of type %u to client.\n",
3268 GNUNET_i2s(&sender->peer),
3269 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3271 ntm = (struct NotifyTrafficMessage *) buf;
3272 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3273 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3274 ntm->distance = htonl (sender->last_distance);
3275 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3276 ntm->peer = sender->peer;
3277 memcpy (&ntm[1], m, msize);
3278 send_to_client (client, &ntm->header, GNUNET_YES);
3283 * Deliver P2P message to interested clients.
3285 * @param cls always NULL
3286 * @param client who sent us the message (struct Neighbour)
3287 * @param m the message
3290 deliver_message (void *cls,
3292 const struct GNUNET_MessageHeader *m)
3294 struct Neighbour *sender = client;
3295 size_t msize = ntohs (m->size);
3297 struct Client *cpos;
3303 type = ntohs (m->type);
3305 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3306 "Received encapsulated message of type %u and size %u from `%4s'\n",
3307 (unsigned int) type,
3309 GNUNET_i2s (&sender->peer));
3311 GNUNET_snprintf (buf,
3313 gettext_noop ("# bytes of messages of type %u received"),
3314 (unsigned int) type);
3315 GNUNET_STATISTICS_set (stats,
3319 dropped = GNUNET_YES;
3321 while (cpos != NULL)
3323 deliver_full = GNUNET_NO;
3324 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3325 deliver_full = GNUNET_YES;
3328 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3330 if (type != cpos->types[tpos])
3332 deliver_full = GNUNET_YES;
3336 if (GNUNET_YES == deliver_full)
3338 send_p2p_message_to_client (sender, cpos, m, msize);
3339 dropped = GNUNET_NO;
3341 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3343 send_p2p_message_to_client (sender, cpos, m,
3344 sizeof (struct GNUNET_MessageHeader));
3348 if (dropped == GNUNET_YES)
3351 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3352 "Message of type %u from `%4s' not delivered to any client.\n",
3353 (unsigned int) type,
3354 GNUNET_i2s (&sender->peer));
3356 GNUNET_STATISTICS_update (stats,
3357 gettext_noop ("# messages not delivered to any client"),
3364 * We received an encrypted message. Decrypt, validate and
3365 * pass on to the appropriate clients.
3368 handle_encrypted_message (struct Neighbour *n,
3369 const struct EncryptedMessage *m)
3371 size_t size = ntohs (m->header.size);
3373 struct EncryptedMessage *pt; /* plaintext */
3376 struct GNUNET_TIME_Absolute t;
3380 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3381 "Core service receives `%s' request from `%4s'.\n",
3382 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3384 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3390 &buf[ENCRYPTED_HEADER_SIZE],
3391 size - ENCRYPTED_HEADER_SIZE))
3393 pt = (struct EncryptedMessage *) buf;
3395 GNUNET_CRYPTO_hmac (&n->decrypt_auth_key,
3396 &pt->sequence_number,
3397 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3399 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3400 "V-Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
3401 (unsigned int) (size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode)),
3405 if (0 != memcmp (&ph,
3407 sizeof (GNUNET_HashCode)))
3409 /* checksum failed */
3410 GNUNET_break_op (0);
3414 /* validate sequence number */
3415 snum = ntohl (pt->sequence_number);
3416 if (n->last_sequence_number_received == snum)
3418 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3419 "Received duplicate message, ignoring.\n");
3420 /* duplicate, ignore */
3421 GNUNET_STATISTICS_set (stats,
3422 gettext_noop ("# bytes dropped (duplicates)"),
3427 if ((n->last_sequence_number_received > snum) &&
3428 (n->last_sequence_number_received - snum > 32))
3430 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3431 "Received ancient out of sequence message, ignoring.\n");
3432 /* ancient out of sequence, ignore */
3433 GNUNET_STATISTICS_set (stats,
3434 gettext_noop ("# bytes dropped (out of sequence)"),
3439 if (n->last_sequence_number_received > snum)
3441 unsigned int rotbit =
3442 1 << (n->last_sequence_number_received - snum - 1);
3443 if ((n->last_packets_bitmap & rotbit) != 0)
3445 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3446 "Received duplicate message, ignoring.\n");
3447 GNUNET_STATISTICS_set (stats,
3448 gettext_noop ("# bytes dropped (duplicates)"),
3451 /* duplicate, ignore */
3454 n->last_packets_bitmap |= rotbit;
3456 if (n->last_sequence_number_received < snum)
3458 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3459 n->last_sequence_number_received = snum;
3462 /* check timestamp */
3463 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3464 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3466 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3468 ("Message received far too old (%llu ms). Content ignored.\n"),
3469 GNUNET_TIME_absolute_get_duration (t).value);
3470 GNUNET_STATISTICS_set (stats,
3471 gettext_noop ("# bytes dropped (ancient message)"),
3477 /* process decrypted message(s) */
3478 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3480 #if DEBUG_CORE_SET_QUOTA
3481 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3482 "Received %u b/s as new inbound limit for peer `%4s'\n",
3483 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3484 GNUNET_i2s (&n->peer));
3486 n->bw_out_external_limit = pt->inbound_bw_limit;
3487 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3488 n->bw_out_internal_limit);
3489 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3491 GNUNET_TRANSPORT_set_quota (transport,
3495 GNUNET_TIME_UNIT_FOREVER_REL,
3498 n->last_activity = GNUNET_TIME_absolute_get ();
3499 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3500 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3502 = GNUNET_SCHEDULER_add_delayed (sched,
3503 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3506 GNUNET_STATISTICS_set (stats,
3507 gettext_noop ("# bytes of payload decrypted"),
3508 size - sizeof (struct EncryptedMessage),
3510 handle_peer_status_change (n);
3511 if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst,
3513 &buf[sizeof (struct EncryptedMessage)],
3514 size - sizeof (struct EncryptedMessage),
3515 GNUNET_YES, GNUNET_NO))
3516 GNUNET_break_op (0);
3521 * Function called by the transport for each received message.
3523 * @param cls closure
3524 * @param peer (claimed) identity of the other peer
3525 * @param message the message
3526 * @param latency estimated latency for communicating with the
3527 * given peer (round-trip)
3528 * @param distance in overlay hops, as given by transport plugin
3531 handle_transport_receive (void *cls,
3532 const struct GNUNET_PeerIdentity *peer,
3533 const struct GNUNET_MessageHeader *message,
3534 struct GNUNET_TIME_Relative latency,
3535 unsigned int distance)
3537 struct Neighbour *n;
3538 struct GNUNET_TIME_Absolute now;
3545 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3546 "Received message of type %u from `%4s', demultiplexing.\n",
3547 (unsigned int) ntohs (message->type),
3550 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3555 n = find_neighbour (peer);
3557 n = create_neighbour (peer);
3558 changed = (latency.value != n->last_latency.value) || (distance != n->last_distance);
3559 n->last_latency = latency;
3560 n->last_distance = distance;
3561 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3562 type = ntohs (message->type);
3563 size = ntohs (message->size);
3566 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3567 if (size != sizeof (struct SetKeyMessage))
3569 GNUNET_break_op (0);
3572 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3573 handle_set_key (n, (const struct SetKeyMessage *) message);
3575 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3576 if (size < sizeof (struct EncryptedMessage) +
3577 sizeof (struct GNUNET_MessageHeader))
3579 GNUNET_break_op (0);
3582 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3583 (n->status != PEER_STATE_KEY_CONFIRMED))
3585 GNUNET_break_op (0);
3588 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3590 case GNUNET_MESSAGE_TYPE_CORE_PING:
3591 if (size != sizeof (struct PingMessage))
3593 GNUNET_break_op (0);
3596 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3597 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3598 (n->status != PEER_STATE_KEY_CONFIRMED))
3601 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3602 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3603 "PING", GNUNET_i2s (&n->peer));
3605 GNUNET_free_non_null (n->pending_ping);
3606 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3607 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3610 handle_ping (n, (const struct PingMessage *) message);
3612 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3613 if (size != sizeof (struct PongMessage))
3615 GNUNET_break_op (0);
3618 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3619 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3620 (n->status != PEER_STATE_KEY_CONFIRMED) )
3623 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3624 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3625 "PONG", GNUNET_i2s (&n->peer));
3627 GNUNET_free_non_null (n->pending_pong);
3628 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3629 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3632 handle_pong (n, (const struct PongMessage *) message);
3635 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3636 _("Unsupported message of type %u received.\n"),
3637 (unsigned int) type);
3640 if (n->status == PEER_STATE_KEY_CONFIRMED)
3642 now = GNUNET_TIME_absolute_get ();
3643 n->last_activity = now;
3644 changed = GNUNET_YES;
3647 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3648 n->time_established = now;
3650 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3651 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3653 = GNUNET_SCHEDULER_add_delayed (sched,
3654 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3659 handle_peer_status_change (n);
3664 * Function that recalculates the bandwidth quota for the
3665 * given neighbour and transmits it to the transport service.
3667 * @param cls neighbour for the quota update
3671 neighbour_quota_update (void *cls,
3672 const struct GNUNET_SCHEDULER_TaskContext *tc)
3674 struct Neighbour *n = cls;
3675 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3678 unsigned long long distributable;
3679 uint64_t need_per_peer;
3680 uint64_t need_per_second;
3683 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3684 "Neighbour quota update calculation running for peer `%4s'\n",
3685 GNUNET_i2s (&n->peer));
3687 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3688 /* calculate relative preference among all neighbours;
3689 divides by a bit more to avoid division by zero AND to
3690 account for possibility of new neighbours joining any time
3691 AND to convert to double... */
3692 if (preference_sum == 0)
3694 pref_rel = 1.0 / (double) neighbour_count;
3698 pref_rel = n->current_preference / preference_sum;
3700 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3701 GNUNET_TIME_UNIT_SECONDS);
3702 need_per_second = need_per_peer * neighbour_count;
3704 if (bandwidth_target_out_bps > need_per_second)
3705 distributable = bandwidth_target_out_bps - need_per_second;
3706 share = distributable * pref_rel;
3707 if (share + need_per_peer > UINT32_MAX)
3708 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
3710 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3711 /* check if we want to disconnect for good due to inactivity */
3712 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3713 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3716 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3717 "Forcing disconnect of `%4s' due to inactivity\n",
3718 GNUNET_i2s (&n->peer));
3720 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3722 #if DEBUG_CORE_QUOTA
3723 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3724 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3725 GNUNET_i2s (&n->peer),
3726 (unsigned int) ntohl (q_in.value__),
3727 bandwidth_target_out_bps,
3728 (unsigned int) ntohl (n->bw_in.value__),
3729 (unsigned int) ntohl (n->bw_out.value__),
3730 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3732 if (n->bw_in.value__ != q_in.value__)
3735 if (GNUNET_YES == n->is_connected)
3736 GNUNET_TRANSPORT_set_quota (transport,
3740 GNUNET_TIME_UNIT_FOREVER_REL,
3742 handle_peer_status_change (n);
3744 schedule_quota_update (n);
3749 * Function called by transport to notify us that
3750 * a peer connected to us (on the network level).
3752 * @param cls closure
3753 * @param peer the peer that connected
3754 * @param latency current latency of the connection
3755 * @param distance in overlay hops, as given by transport plugin
3758 handle_transport_notify_connect (void *cls,
3759 const struct GNUNET_PeerIdentity *peer,
3760 struct GNUNET_TIME_Relative latency,
3761 unsigned int distance)
3763 struct Neighbour *n;
3765 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3770 n = find_neighbour (peer);
3773 if (GNUNET_YES == n->is_connected)
3775 /* duplicate connect notification!? */
3782 n = create_neighbour (peer);
3784 GNUNET_STATISTICS_update (stats,
3785 gettext_noop ("# peers connected (transport)"),
3788 n->is_connected = GNUNET_YES;
3789 n->last_latency = latency;
3790 n->last_distance = distance;
3791 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3794 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3798 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3799 "Received connection from `%4s'.\n",
3800 GNUNET_i2s (&n->peer));
3802 GNUNET_TRANSPORT_set_quota (transport,
3806 GNUNET_TIME_UNIT_FOREVER_REL,
3813 * Function called by transport telling us that a peer
3816 * @param cls closure
3817 * @param peer the peer that disconnected
3820 handle_transport_notify_disconnect (void *cls,
3821 const struct GNUNET_PeerIdentity *peer)
3823 struct DisconnectNotifyMessage cnm;
3824 struct Neighbour *n;
3825 struct GNUNET_TIME_Relative left;
3828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3829 "Peer `%4s' disconnected from us; received notification from transport.\n", GNUNET_i2s (peer));
3832 n = find_neighbour (peer);
3838 GNUNET_break (n->is_connected);
3839 if (n->status == PEER_STATE_KEY_CONFIRMED)
3841 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3842 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3844 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3846 n->is_connected = GNUNET_NO;
3847 GNUNET_STATISTICS_update (stats,
3848 gettext_noop ("# peers connected (transport)"),
3851 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
3852 GNUNET_SCHEDULER_cancel (sched,
3853 n->dead_clean_task);
3854 left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3855 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
3856 n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (),
3858 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
3859 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
3860 &consider_free_task,
3866 * Last task run during shutdown. Disconnects us from
3870 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3872 struct Neighbour *n;
3876 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3877 "Core service shutting down.\n");
3879 GNUNET_assert (transport != NULL);
3880 GNUNET_TRANSPORT_disconnect (transport);
3882 while (NULL != (n = neighbours))
3884 neighbours = n->next;
3885 GNUNET_assert (neighbour_count > 0);
3889 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
3890 GNUNET_SERVER_notification_context_destroy (notifier);
3892 while (NULL != (c = clients))
3893 handle_client_disconnect (NULL, c->client_handle);
3894 if (my_private_key != NULL)
3895 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3897 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3898 if (peerinfo != NULL)
3899 GNUNET_PEERINFO_disconnect (peerinfo);
3901 GNUNET_SERVER_mst_destroy (mst);
3906 * Initiate core service.
3908 * @param cls closure
3909 * @param s scheduler to use
3910 * @param server the initialized server
3911 * @param c configuration to use
3915 struct GNUNET_SCHEDULER_Handle *s,
3916 struct GNUNET_SERVER_Handle *server,
3917 const struct GNUNET_CONFIGURATION_Handle *c)
3919 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3920 {&handle_client_init, NULL,
3921 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
3922 {&handle_client_request_info, NULL,
3923 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
3924 sizeof (struct RequestInfoMessage)},
3925 {&handle_client_iterate_peers, NULL,
3926 GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
3927 sizeof (struct GNUNET_MessageHeader)},
3928 {&handle_client_send, NULL,
3929 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
3930 {&handle_client_request_connect, NULL,
3931 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
3932 sizeof (struct ConnectMessage)},
3939 /* parse configuration */
3942 GNUNET_CONFIGURATION_get_value_number (c,
3945 &bandwidth_target_in_bps)) ||
3947 GNUNET_CONFIGURATION_get_value_number (c,
3950 &bandwidth_target_out_bps)) ||
3952 GNUNET_CONFIGURATION_get_value_filename (c,
3954 "HOSTKEY", &keyfile)))
3956 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3958 ("Core service is lacking key configuration settings. Exiting.\n"));
3959 GNUNET_SCHEDULER_shutdown (s);
3962 peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
3963 if (NULL == peerinfo)
3965 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3966 _("Could not access PEERINFO service. Exiting.\n"));
3967 GNUNET_SCHEDULER_shutdown (s);
3968 GNUNET_free (keyfile);
3971 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3972 GNUNET_free (keyfile);
3973 if (my_private_key == NULL)
3975 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3976 _("Core service could not access hostkey. Exiting.\n"));
3977 GNUNET_PEERINFO_disconnect (peerinfo);
3978 GNUNET_SCHEDULER_shutdown (s);
3981 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3982 GNUNET_CRYPTO_hash (&my_public_key,
3983 sizeof (my_public_key), &my_identity.hashPubKey);
3984 /* setup notification */
3985 notifier = GNUNET_SERVER_notification_context_create (server,
3987 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3988 /* setup transport connection */
3989 transport = GNUNET_TRANSPORT_connect (sched,
3993 &handle_transport_receive,
3994 &handle_transport_notify_connect,
3995 &handle_transport_notify_disconnect);
3996 GNUNET_assert (NULL != transport);
3997 stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3998 mst = GNUNET_SERVER_mst_create (&deliver_message,
4000 GNUNET_SCHEDULER_add_delayed (sched,
4001 GNUNET_TIME_UNIT_FOREVER_REL,
4002 &cleaning_task, NULL);
4003 /* process client requests */
4004 GNUNET_SERVER_add_handlers (server, handlers);
4005 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4006 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
4012 * The main function for the transport service.
4014 * @param argc number of arguments from the command line
4015 * @param argv command line arguments
4016 * @return 0 ok, 1 on error
4019 main (int argc, char *const *argv)
4021 return (GNUNET_OK ==
4022 GNUNET_SERVICE_run (argc,
4025 GNUNET_SERVICE_OPTION_NONE,
4026 &run, NULL)) ? 0 : 1;
4029 /* end of gnunet-service-core.c */