2 This file is part of GNUnet.
3 (C) 2009 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 2, 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_YES
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 16
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, 5)
85 * What 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, 3)
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
146 * What is the maximum size for encrypted messages? Note that this
147 * number imposes a clear limit on the maximum size of any message.
148 * Set to a value close to 64k but not so close that transports will
149 * have trouble with their headers.
151 #define MAX_ENCRYPTED_MESSAGE_SIZE (63 * 1024)
155 * State machine for our P2P encryption handshake. Everyone starts in
156 * "DOWN", if we receive the other peer's key (other peer initiated)
157 * we start in state RECEIVED (since we will immediately send our
158 * own); otherwise we start in SENT. If we get back a PONG from
159 * within either state, we move up to CONFIRMED (the PONG will always
160 * be sent back encrypted with the key we sent to the other peer).
162 enum PeerStateMachine
166 PEER_STATE_KEY_RECEIVED,
167 PEER_STATE_KEY_CONFIRMED
172 * Number of bytes (at the beginning) of "struct EncryptedMessage"
173 * that are NOT encrypted.
175 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t))
179 * Encapsulation for encrypted messages exchanged between
180 * peers. Followed by the actual encrypted data.
182 struct EncryptedMessage
185 * Message type is either CORE_ENCRYPTED_MESSAGE.
187 struct GNUNET_MessageHeader header;
190 * Random value used for IV generation. ENCRYPTED_HEADER_SIZE must
191 * be set to the offset of the *next* field.
193 uint32_t iv_seed GNUNET_PACKED;
196 * Hash of the plaintext (starting at 'sequence_number'), used to
197 * verify message integrity. Everything after this hash (including
198 * this hash itself) will be encrypted.
200 GNUNET_HashCode plaintext_hash;
203 * Sequence number, in network byte order. This field
204 * must be the first encrypted/decrypted field and the
205 * first byte that is hashed for the plaintext hash.
207 uint32_t sequence_number GNUNET_PACKED;
210 * Desired bandwidth (how much we should send to this peer / how
211 * much is the sender willing to receive)?
213 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
216 * Timestamp. Used to prevent reply of ancient messages
217 * (recent messages are caught with the sequence number).
219 struct GNUNET_TIME_AbsoluteNBO timestamp;
225 * We're sending an (encrypted) PING to the other peer to check if he
226 * can decrypt. The other peer should respond with a PONG with the
227 * same content, except this time encrypted with the receiver's key.
232 * Message type is CORE_PING.
234 struct GNUNET_MessageHeader header;
237 * Random number chosen to make reply harder.
239 uint32_t challenge GNUNET_PACKED;
242 * Intended target of the PING, used primarily to check
243 * that decryption actually worked.
245 struct GNUNET_PeerIdentity target;
251 * Response to a PING. Includes data from the original PING
252 * plus initial bandwidth quota information.
257 * Message type is CORE_PONG.
259 struct GNUNET_MessageHeader header;
262 * Random number proochosen to make reply harder. Must be
263 * first field after header (this is where we start to encrypt!).
265 uint32_t challenge GNUNET_PACKED;
270 uint32_t reserved GNUNET_PACKED;
273 * Desired bandwidth (how much we should send to this
274 * peer / how much is the sender willing to receive).
276 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
279 * Intended target of the PING, used primarily to check
280 * that decryption actually worked.
282 struct GNUNET_PeerIdentity target;
287 * Message transmitted to set (or update) a session key.
293 * Message type is either CORE_SET_KEY.
295 struct GNUNET_MessageHeader header;
298 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
300 int32_t sender_status GNUNET_PACKED;
303 * Purpose of the signature, will be
304 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
306 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
309 * At what time was this key created?
311 struct GNUNET_TIME_AbsoluteNBO creation_time;
314 * The encrypted session key.
316 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
319 * Who is the intended recipient?
321 struct GNUNET_PeerIdentity target;
324 * Signature of the stuff above (starting at purpose).
326 struct GNUNET_CRYPTO_RsaSignature signature;
332 * Message waiting for transmission. This struct
333 * is followed by the actual content of the message.
339 * We keep messages in a doubly linked list.
341 struct MessageEntry *next;
344 * We keep messages in a doubly linked list.
346 struct MessageEntry *prev;
349 * By when are we supposed to transmit this message?
351 struct GNUNET_TIME_Absolute deadline;
354 * By when are we supposed to transmit this message (after
357 struct GNUNET_TIME_Absolute slack_deadline;
360 * How important is this message to us?
362 unsigned int priority;
365 * How long is the message? (number of bytes following
366 * the "struct MessageEntry", but not including the
367 * size of "struct MessageEntry" itself!)
372 * Was this message selected for transmission in the
373 * current round? GNUNET_YES or GNUNET_NO.
378 * Did we give this message some slack (delayed sending) previously
379 * (and hence should not give it any more slack)? GNUNET_YES or
390 * We keep neighbours in a linked list (for now).
392 struct Neighbour *next;
395 * Unencrypted messages destined for this peer.
397 struct MessageEntry *messages;
400 * Head of the batched, encrypted message queue (already ordered,
401 * transmit starting with the head).
403 struct MessageEntry *encrypted_head;
406 * Tail of the batched, encrypted message queue (already ordered,
407 * append new messages to tail)
409 struct MessageEntry *encrypted_tail;
412 * Handle for pending requests for transmission to this peer
413 * with the transport service. NULL if no request is pending.
415 struct GNUNET_TRANSPORT_TransmitHandle *th;
418 * Public key of the neighbour, NULL if we don't have it yet.
420 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
423 * We received a PING message before we got the "public_key"
424 * (or the SET_KEY). We keep it here until we have a key
425 * to decrypt it. NULL if no PING is pending.
427 struct PingMessage *pending_ping;
430 * We received a PONG message before we got the "public_key"
431 * (or the SET_KEY). We keep it here until we have a key
432 * to decrypt it. NULL if no PONG is pending.
434 struct PongMessage *pending_pong;
437 * Non-NULL if we are currently looking up HELLOs for this peer.
440 struct GNUNET_PEERINFO_IteratorContext *pitr;
443 * SetKeyMessage to transmit, NULL if we are not currently trying
446 struct SetKeyMessage *skm;
449 * Identity of the neighbour.
451 struct GNUNET_PeerIdentity peer;
454 * Key we use to encrypt our messages for the other peer
455 * (initialized by us when we do the handshake).
457 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
460 * Key we use to decrypt messages from the other peer
461 * (given to us by the other peer during the handshake).
463 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
466 * ID of task used for re-trying plaintext scheduling.
468 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
471 * ID of task used for re-trying SET_KEY and PING message.
473 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
476 * ID of task used for updating bandwidth quota for this neighbour.
478 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
481 * ID of task used for sending keep-alive pings.
483 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
486 * ID of task used for cleaning up dead neighbour entries.
488 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
491 * At what time did we generate our encryption key?
493 struct GNUNET_TIME_Absolute encrypt_key_created;
496 * At what time did the other peer generate the decryption key?
498 struct GNUNET_TIME_Absolute decrypt_key_created;
501 * At what time did we initially establish (as in, complete session
502 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
504 struct GNUNET_TIME_Absolute time_established;
507 * At what time did we last receive an encrypted message from the
508 * other peer? Should be zero if status != KEY_CONFIRMED.
510 struct GNUNET_TIME_Absolute last_activity;
513 * Last latency observed from this peer.
515 struct GNUNET_TIME_Relative last_latency;
518 * At what frequency are we currently re-trying SET_KEY messages?
520 struct GNUNET_TIME_Relative set_key_retry_frequency;
523 * Tracking bandwidth for sending to this peer.
525 struct GNUNET_BANDWIDTH_Tracker available_send_window;
528 * Tracking bandwidth for receiving from this peer.
530 struct GNUNET_BANDWIDTH_Tracker available_recv_window;
533 * How valueable were the messages of this peer recently?
535 unsigned long long current_preference;
538 * Bit map indicating which of the 32 sequence numbers before the last
539 * were received (good for accepting out-of-order packets and
540 * estimating reliability of the connection)
542 unsigned int last_packets_bitmap;
545 * last sequence number received on this connection (highest)
547 uint32_t last_sequence_number_received;
550 * last sequence number transmitted
552 uint32_t last_sequence_number_sent;
555 * Available bandwidth in for this peer (current target).
557 struct GNUNET_BANDWIDTH_Value32NBO bw_in;
560 * Available bandwidth out for this peer (current target).
562 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
565 * Internal bandwidth limit set for this peer (initially typically
566 * set to "-1"). Actual "bw_out" is MIN of
567 * "bpm_out_internal_limit" and "bw_out_external_limit".
569 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
572 * External bandwidth limit set for this peer by the
573 * peer that we are communicating with. "bw_out" is MIN of
574 * "bw_out_internal_limit" and "bw_out_external_limit".
576 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
579 * What was our PING challenge number (for this peer)?
581 uint32_t ping_challenge;
584 * What was the last distance to this peer as reported by the transports?
586 uint32_t last_distance;
589 * What is our connection status?
591 enum PeerStateMachine status;
594 * Are we currently connected to this neighbour?
602 * Data structure for each client connected to the core service.
607 * Clients are kept in a linked list.
612 * Handle for the client with the server API.
614 struct GNUNET_SERVER_Client *client_handle;
617 * Array of the types of messages this peer cares
618 * about (with "tcnt" entries). Allocated as part
619 * of this client struct, do not free!
621 const uint16_t *types;
624 * Options for messages this client cares about,
625 * see GNUNET_CORE_OPTION_ values.
630 * Number of types of incoming messages this client
631 * specifically cares about. Size of the "types" array.
641 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
646 static struct GNUNET_PeerIdentity my_identity;
651 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
656 struct GNUNET_SCHEDULER_Handle *sched;
659 * Handle to peerinfo service.
661 static struct GNUNET_PEERINFO_Handle *peerinfo;
666 const struct GNUNET_CONFIGURATION_Handle *cfg;
671 static struct GNUNET_SERVER_Handle *server;
676 static struct GNUNET_TRANSPORT_Handle *transport;
679 * Linked list of our clients.
681 static struct Client *clients;
684 * Context for notifications we need to send to our clients.
686 static struct GNUNET_SERVER_NotificationContext *notifier;
689 * We keep neighbours in a linked list (for now).
691 static struct Neighbour *neighbours;
694 * For creating statistics.
696 static struct GNUNET_STATISTICS_Handle *stats;
699 * Sum of all preferences among all neighbours.
701 static unsigned long long preference_sum;
704 * Total number of neighbours we have.
706 static unsigned int neighbour_count;
709 * How much inbound bandwidth are we supposed to be using per second?
710 * FIXME: this value is not used!
712 static unsigned long long bandwidth_target_in_bps;
715 * How much outbound bandwidth are we supposed to be using per second?
717 static unsigned long long bandwidth_target_out_bps;
722 * A preference value for a neighbour was update. Update
723 * the preference sum accordingly.
725 * @param inc how much was a preference value increased?
728 update_preference_sum (unsigned long long inc)
731 unsigned long long os;
734 preference_sum += inc;
735 if (preference_sum >= os)
737 /* overflow! compensate by cutting all values in half! */
742 n->current_preference /= 2;
743 preference_sum += n->current_preference;
746 GNUNET_STATISTICS_set (stats, gettext_noop ("# total peer preference"), preference_sum, GNUNET_NO);
751 * Find the entry for the given neighbour.
753 * @param peer identity of the neighbour
754 * @return NULL if we are not connected, otherwise the
757 static struct Neighbour *
758 find_neighbour (const struct GNUNET_PeerIdentity *peer)
760 struct Neighbour *ret;
763 while ((ret != NULL) &&
764 (0 != memcmp (&ret->peer,
765 peer, sizeof (struct GNUNET_PeerIdentity))))
772 * Send a message to one of our clients.
774 * @param client target for the message
775 * @param msg message to transmit
776 * @param can_drop could this message be dropped if the
777 * client's queue is getting too large?
780 send_to_client (struct Client *client,
781 const struct GNUNET_MessageHeader *msg,
784 #if DEBUG_CORE_CLIENT
785 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
786 "Preparing to send message of type %u to client.\n",
787 (unsigned int) ntohs (msg->type));
789 GNUNET_SERVER_notification_context_unicast (notifier,
790 client->client_handle,
797 * Send a message to all of our current clients that have
798 * the right options set.
800 * @param msg message to multicast
801 * @param can_drop can this message be discarded if the queue is too long
802 * @param options mask to use
805 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
814 if (0 != (c->options & options))
816 #if DEBUG_CORE_CLIENT
817 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
818 "Sending message of type %u to client.\n",
819 (unsigned int) ntohs (msg->type));
821 send_to_client (c, msg, can_drop);
829 * Handle CORE_INIT request.
832 handle_client_init (void *cls,
833 struct GNUNET_SERVER_Client *client,
834 const struct GNUNET_MessageHeader *message)
836 const struct InitMessage *im;
837 struct InitReplyMessage irm;
840 const uint16_t *types;
843 struct ConnectNotifyMessage cnm;
846 #if DEBUG_CORE_CLIENT
847 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
848 "Client connecting to core service with `%s' message\n",
851 /* check that we don't have an entry already */
855 if (client == c->client_handle)
858 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
863 msize = ntohs (message->size);
864 if (msize < sizeof (struct InitMessage))
867 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
870 GNUNET_SERVER_notification_context_add (notifier, client);
871 im = (const struct InitMessage *) message;
872 types = (const uint16_t *) &im[1];
873 msize -= sizeof (struct InitMessage);
874 c = GNUNET_malloc (sizeof (struct Client) + msize);
875 c->client_handle = client;
878 c->tcnt = msize / sizeof (uint16_t);
879 c->types = (const uint16_t *) &c[1];
880 wtypes = (uint16_t *) &c[1];
881 for (i=0;i<c->tcnt;i++)
882 wtypes[i] = ntohs (types[i]);
883 c->options = ntohl (im->options);
884 #if DEBUG_CORE_CLIENT
885 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
886 "Client %p is interested in %u message types\n",
888 (unsigned int) c->tcnt);
890 /* send init reply message */
891 irm.header.size = htons (sizeof (struct InitReplyMessage));
892 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
893 irm.reserved = htonl (0);
894 memcpy (&irm.publicKey,
896 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
897 #if DEBUG_CORE_CLIENT
898 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
899 "Sending `%s' message to client.\n", "INIT_REPLY");
901 send_to_client (c, &irm.header, GNUNET_NO);
902 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
904 /* notify new client about existing neighbours */
905 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
906 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
910 if (n->status == PEER_STATE_KEY_CONFIRMED)
912 #if DEBUG_CORE_CLIENT
913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
914 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
916 cnm.distance = htonl (n->last_distance);
917 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
919 send_to_client (c, &cnm.header, GNUNET_NO);
924 GNUNET_SERVER_receive_done (client, GNUNET_OK);
929 * A client disconnected, clean up.
932 * @param client identification of the client
935 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
942 #if DEBUG_CORE_CLIENT
943 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
944 "Client %p has disconnected from core service.\n",
951 if (client == pos->client_handle)
956 prev->next = pos->next;
963 /* client never sent INIT */
968 * Handle REQUEST_INFO request.
971 handle_client_request_info (void *cls,
972 struct GNUNET_SERVER_Client *client,
973 const struct GNUNET_MessageHeader *message)
975 const struct RequestInfoMessage *rcm;
977 struct ConfigurationInfoMessage cim;
980 unsigned long long old_preference;
981 struct GNUNET_SERVER_TransmitContext *tc;
983 #if DEBUG_CORE_CLIENT
984 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
985 "Core service receives `%s' request.\n", "REQUEST_INFO");
987 rcm = (const struct RequestInfoMessage *) message;
988 n = find_neighbour (&rcm->peer);
989 memset (&cim, 0, sizeof (cim));
992 want_reserv = ntohl (rcm->reserve_inbound);
993 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
995 n->bw_out_internal_limit = rcm->limit_outbound;
996 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
997 n->bw_out_external_limit);
998 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1000 GNUNET_TRANSPORT_set_quota (transport,
1004 GNUNET_TIME_UNIT_FOREVER_REL,
1007 if (want_reserv < 0)
1009 got_reserv = want_reserv;
1011 else if (want_reserv > 0)
1013 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1014 want_reserv).value == 0)
1015 got_reserv = want_reserv;
1017 got_reserv = 0; /* all or nothing */
1021 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1023 old_preference = n->current_preference;
1024 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1025 if (old_preference > n->current_preference)
1027 /* overflow; cap at maximum value */
1028 n->current_preference = (unsigned long long) -1;
1030 update_preference_sum (n->current_preference - old_preference);
1031 #if DEBUG_CORE_QUOTA
1032 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1033 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1035 GNUNET_i2s (&rcm->peer),
1038 cim.reserved_amount = htonl (got_reserv);
1039 cim.bw_in = n->bw_in;
1040 cim.bw_out = n->bw_out;
1041 cim.preference = n->current_preference;
1043 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1044 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1045 cim.peer = rcm->peer;
1047 #if DEBUG_CORE_CLIENT
1048 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1049 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1051 tc = GNUNET_SERVER_transmit_context_create (client);
1052 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1053 GNUNET_SERVER_transmit_context_run (tc,
1054 GNUNET_TIME_UNIT_FOREVER_REL);
1059 * Free the given entry for the neighbour (it has
1060 * already been removed from the list at this point).
1062 * @param n neighbour to free
1065 free_neighbour (struct Neighbour *n)
1067 struct MessageEntry *m;
1069 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1070 "Destroying neighbour entry for peer `%4s'\n",
1071 GNUNET_i2s (&n->peer));
1072 if (n->pitr != NULL)
1074 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1079 GNUNET_free (n->skm);
1082 while (NULL != (m = n->messages))
1084 n->messages = m->next;
1087 while (NULL != (m = n->encrypted_head))
1089 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1096 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1099 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1100 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1101 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1102 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1103 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1104 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1105 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1106 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1107 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1108 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1109 if (n->status == PEER_STATE_KEY_CONFIRMED)
1110 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1111 GNUNET_free_non_null (n->public_key);
1112 GNUNET_free_non_null (n->pending_ping);
1113 GNUNET_free_non_null (n->pending_pong);
1119 * Check if we have encrypted messages for the specified neighbour
1120 * pending, and if so, check with the transport about sending them
1123 * @param n neighbour to check.
1125 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1129 * Encrypt size bytes from in and write the result to out. Use the
1130 * key for outbound traffic of the given neighbour.
1132 * @param n neighbour we are sending to
1133 * @param iv initialization vector to use
1134 * @param in ciphertext
1135 * @param out plaintext
1136 * @param size size of in/out
1137 * @return GNUNET_OK on success
1140 do_encrypt (struct Neighbour *n,
1141 const GNUNET_HashCode * iv,
1142 const void *in, void *out, size_t size)
1144 if (size != (uint16_t) size)
1149 GNUNET_assert (size ==
1150 GNUNET_CRYPTO_aes_encrypt (in,
1154 GNUNET_CRYPTO_AesInitializationVector
1156 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1159 "Encrypted %u bytes for `%4s' using key %u\n",
1160 (unsigned int) size,
1161 GNUNET_i2s (&n->peer),
1162 (unsigned int) n->encrypt_key.crc32);
1169 * Consider freeing the given neighbour since we may not need
1170 * to keep it around anymore.
1172 * @param n neighbour to consider discarding
1175 consider_free_neighbour (struct Neighbour *n);
1179 * Task triggered when a neighbour entry is about to time out
1180 * (and we should prevent this by sending a PING).
1182 * @param cls the 'struct Neighbour'
1183 * @param tc scheduler context (not used)
1186 send_keep_alive (void *cls,
1187 const struct GNUNET_SCHEDULER_TaskContext *tc)
1189 struct Neighbour *n = cls;
1190 struct GNUNET_TIME_Relative retry;
1191 struct GNUNET_TIME_Relative left;
1192 struct MessageEntry *me;
1193 struct PingMessage pp;
1194 struct PingMessage *pm;
1196 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1198 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1199 sizeof (struct PingMessage));
1200 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1201 me->priority = PING_PRIORITY;
1202 me->size = sizeof (struct PingMessage);
1203 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1207 pm = (struct PingMessage *) &me[1];
1208 pm->header.size = htons (sizeof (struct PingMessage));
1209 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1210 pp.challenge = htonl (n->ping_challenge);
1211 pp.target = n->peer;
1213 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1214 "Encrypting `%s' message with challenge %u for `%4s' using key %u.\n",
1216 (unsigned int) n->ping_challenge,
1217 GNUNET_i2s (&n->peer),
1218 (unsigned int) n->encrypt_key.crc32);
1221 &n->peer.hashPubKey,
1224 sizeof (struct PingMessage) -
1225 sizeof (struct GNUNET_MessageHeader));
1226 process_encrypted_neighbour_queue (n);
1227 /* reschedule PING job */
1228 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1229 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1230 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1231 MIN_PING_FREQUENCY);
1233 = GNUNET_SCHEDULER_add_delayed (sched,
1242 * Task triggered when a neighbour entry might have gotten stale.
1244 * @param cls the 'struct Neighbour'
1245 * @param tc scheduler context (not used)
1248 consider_free_task (void *cls,
1249 const struct GNUNET_SCHEDULER_TaskContext *tc)
1251 struct Neighbour *n = cls;
1253 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1254 consider_free_neighbour (n);
1259 * Consider freeing the given neighbour since we may not need
1260 * to keep it around anymore.
1262 * @param n neighbour to consider discarding
1265 consider_free_neighbour (struct Neighbour *n)
1267 struct Neighbour *pos;
1268 struct Neighbour *prev;
1269 struct GNUNET_TIME_Relative left;
1271 if ( (n->th != NULL) ||
1272 (n->pitr != NULL) ||
1273 (n->status == PEER_STATE_KEY_CONFIRMED) ||
1274 (GNUNET_YES == n->is_connected) )
1275 return; /* no chance */
1277 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1278 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1281 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1282 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1283 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1285 &consider_free_task,
1289 /* actually free the neighbour... */
1298 neighbours = n->next;
1300 prev->next = n->next;
1301 GNUNET_assert (neighbour_count > 0);
1303 GNUNET_STATISTICS_set (stats,
1304 gettext_noop ("# neighbour entries allocated"),
1312 * Function called when the transport service is ready to
1313 * receive an encrypted message for the respective peer
1315 * @param cls neighbour to use message from
1316 * @param size number of bytes we can transmit
1317 * @param buf where to copy the message
1318 * @return number of bytes transmitted
1321 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1323 struct Neighbour *n = cls;
1324 struct MessageEntry *m;
1329 m = n->encrypted_head;
1333 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1334 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1335 GNUNET_i2s (&n->peer));
1339 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1346 GNUNET_assert (size >= m->size);
1347 memcpy (cbuf, &m[1], m->size);
1349 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1352 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1353 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1354 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1356 GNUNET_i2s (&n->peer));
1358 process_encrypted_neighbour_queue (n);
1363 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1364 "Transmission of message of type %u and size %u failed\n",
1365 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1366 (unsigned int) m->size);
1370 consider_free_neighbour (n);
1376 * Check if we have plaintext messages for the specified neighbour
1377 * pending, and if so, consider batching and encrypting them (and
1378 * then trigger processing of the encrypted queue if needed).
1380 * @param n neighbour to check.
1382 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1386 * Check if we have encrypted messages for the specified neighbour
1387 * pending, and if so, check with the transport about sending them
1390 * @param n neighbour to check.
1393 process_encrypted_neighbour_queue (struct Neighbour *n)
1395 struct MessageEntry *m;
1398 return; /* request already pending */
1399 m = n->encrypted_head;
1402 /* encrypted queue empty, try plaintext instead */
1403 process_plaintext_neighbour_queue (n);
1407 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1408 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1409 (unsigned int) m->size,
1410 GNUNET_i2s (&n->peer),
1411 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).
1415 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1418 GNUNET_TIME_absolute_get_remaining
1420 ¬ify_encrypted_transmit_ready,
1424 /* message request too large or duplicate request */
1426 /* discard encrypted message */
1427 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1431 process_encrypted_neighbour_queue (n);
1437 * Decrypt size bytes from in and write the result to out. Use the
1438 * key for inbound traffic of the given neighbour. This function does
1439 * NOT do any integrity-checks on the result.
1441 * @param n neighbour we are receiving from
1442 * @param iv initialization vector to use
1443 * @param in ciphertext
1444 * @param out plaintext
1445 * @param size size of in/out
1446 * @return GNUNET_OK on success
1449 do_decrypt (struct Neighbour *n,
1450 const GNUNET_HashCode * iv,
1451 const void *in, void *out, size_t size)
1453 if (size != (uint16_t) size)
1458 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1459 (n->status != PEER_STATE_KEY_CONFIRMED))
1461 GNUNET_break_op (0);
1462 return GNUNET_SYSERR;
1465 GNUNET_CRYPTO_aes_decrypt (in,
1469 GNUNET_CRYPTO_AesInitializationVector *) iv,
1473 return GNUNET_SYSERR;
1475 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1477 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1478 "Decrypted %u bytes from `%4s' using key %u\n",
1479 (unsigned int) size,
1480 GNUNET_i2s (&n->peer),
1481 (unsigned int) n->decrypt_key.crc32);
1488 * Select messages for transmission. This heuristic uses a combination
1489 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1490 * and priority-based discard (in case no feasible schedule exist) and
1491 * speculative optimization (defer any kind of transmission until
1492 * we either create a batch of significant size, 25% of max, or until
1493 * we are close to a deadline). Furthermore, when scheduling the
1494 * heuristic also packs as many messages into the batch as possible,
1495 * starting with those with the earliest deadline. Yes, this is fun.
1497 * @param n neighbour to select messages from
1498 * @param size number of bytes to select for transmission
1499 * @param retry_time set to the time when we should try again
1500 * (only valid if this function returns zero)
1501 * @return number of bytes selected, or 0 if we decided to
1502 * defer scheduling overall; in that case, retry_time is set.
1505 select_messages (struct Neighbour *n,
1506 size_t size, struct GNUNET_TIME_Relative *retry_time)
1508 struct MessageEntry *pos;
1509 struct MessageEntry *min;
1510 struct MessageEntry *last;
1511 unsigned int min_prio;
1512 struct GNUNET_TIME_Absolute t;
1513 struct GNUNET_TIME_Absolute now;
1514 struct GNUNET_TIME_Relative delta;
1516 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1519 unsigned int queue_size;
1520 int discard_low_prio;
1522 GNUNET_assert (NULL != n->messages);
1523 now = GNUNET_TIME_absolute_get ();
1524 /* last entry in linked list of messages processed */
1526 /* should we remove the entry with the lowest
1527 priority from consideration for scheduling at the
1538 discard_low_prio = GNUNET_YES;
1539 while (GNUNET_YES == discard_low_prio)
1543 discard_low_prio = GNUNET_NO;
1544 /* calculate number of bytes available for transmission at time "t" */
1545 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1547 /* how many bytes have we (hypothetically) scheduled so far */
1549 /* maximum time we can wait before transmitting anything
1550 and still make all of our deadlines */
1551 slack = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1553 /* note that we use "*2" here because we want to look
1554 a bit further into the future; much more makes no
1555 sense since new message might be scheduled in the
1557 while ((pos != NULL) && (off < size * 2))
1559 if (pos->do_transmit == GNUNET_YES)
1561 /* already removed from consideration */
1565 if (discard_low_prio == GNUNET_NO)
1567 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1568 if (delta.value > 0)
1570 // FIXME: HUH? Check!
1572 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1575 if (avail < pos->size)
1577 // FIXME: HUH? Check!
1578 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1583 /* update slack, considering both its absolute deadline
1584 and relative deadlines caused by other messages
1585 with their respective load */
1586 slack = GNUNET_TIME_relative_min (slack,
1587 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1589 if (pos->deadline.value <= now.value)
1592 slack = GNUNET_TIME_UNIT_ZERO;
1594 else if (GNUNET_YES == pos->got_slack)
1596 /* should be soon now! */
1597 slack = GNUNET_TIME_relative_min (slack,
1598 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1603 GNUNET_TIME_relative_min (slack,
1604 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1605 pos->got_slack = GNUNET_YES;
1606 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1607 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
1612 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1613 if (pos->priority <= min_prio)
1615 /* update min for discard */
1616 min_prio = pos->priority;
1621 if (discard_low_prio)
1623 GNUNET_assert (min != NULL);
1624 /* remove lowest-priority entry from consideration */
1625 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1629 /* guard against sending "tiny" messages with large headers without
1631 if ( (slack.value > 0) &&
1633 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1635 /* less than 25% of message would be filled with deadlines still
1636 being met if we delay by one second or more; so just wait for
1637 more data; but do not wait longer than 1s (since we don't want
1638 to delay messages for a really long time either). */
1639 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1640 /* reset do_transmit values for next time */
1643 pos->do_transmit = GNUNET_NO;
1647 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1648 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1649 (unsigned long long) slack.value,
1651 (unsigned int) size);
1655 /* select marked messages (up to size) for transmission */
1660 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1662 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1667 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1671 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1672 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1673 (unsigned long long) off, (unsigned long long) tsize,
1674 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
1675 GNUNET_i2s (&n->peer));
1682 * Batch multiple messages into a larger buffer.
1684 * @param n neighbour to take messages from
1685 * @param buf target buffer
1686 * @param size size of buf
1687 * @param deadline set to transmission deadline for the result
1688 * @param retry_time set to the time when we should try again
1689 * (only valid if this function returns zero)
1690 * @param priority set to the priority of the batch
1691 * @return number of bytes written to buf (can be zero)
1694 batch_message (struct Neighbour *n,
1697 struct GNUNET_TIME_Absolute *deadline,
1698 struct GNUNET_TIME_Relative *retry_time,
1699 unsigned int *priority)
1701 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1702 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1703 struct MessageEntry *pos;
1704 struct MessageEntry *prev;
1705 struct MessageEntry *next;
1710 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1711 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1712 if (0 == select_messages (n, size, retry_time))
1715 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1716 "No messages selected, will try again in %llu ms\n",
1721 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1722 ntm->distance = htonl (n->last_distance);
1723 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1724 ntm->peer = n->peer;
1728 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1731 if (GNUNET_YES == pos->do_transmit)
1733 GNUNET_assert (pos->size <= size);
1734 /* do notifications */
1735 /* FIXME: track if we have *any* client that wants
1736 full notifications and only do this if that is
1738 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1740 memcpy (&ntm[1], &pos[1], pos->size);
1741 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1742 sizeof (struct GNUNET_MessageHeader));
1743 send_to_all_clients (&ntm->header,
1745 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1749 /* message too large for 'full' notifications, we do at
1750 least the 'hdr' type */
1753 sizeof (struct GNUNET_MessageHeader));
1755 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1757 send_to_all_clients (&ntm->header,
1759 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1761 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1762 "Encrypting message of type %u\n",
1763 (unsigned int) ntohs(((struct GNUNET_MessageHeader*)&pos[1])->type));
1765 /* copy for encrypted transmission */
1766 memcpy (&buf[ret], &pos[1], pos->size);
1769 *priority += pos->priority;
1771 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1772 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1773 (unsigned int) pos->size,
1774 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1776 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1790 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1791 "Deadline for message batch is %llu ms\n",
1792 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1799 * Remove messages with deadlines that have long expired from
1802 * @param n neighbour to inspect
1805 discard_expired_messages (struct Neighbour *n)
1807 struct MessageEntry *prev;
1808 struct MessageEntry *next;
1809 struct MessageEntry *pos;
1810 struct GNUNET_TIME_Absolute now;
1811 struct GNUNET_TIME_Relative delta;
1813 now = GNUNET_TIME_absolute_get ();
1819 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1820 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1823 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1824 "Message is %llu ms past due, discarding.\n",
1841 * Signature of the main function of a task.
1843 * @param cls closure
1844 * @param tc context information (why was this task triggered now)
1847 retry_plaintext_processing (void *cls,
1848 const struct GNUNET_SCHEDULER_TaskContext *tc)
1850 struct Neighbour *n = cls;
1852 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1853 process_plaintext_neighbour_queue (n);
1858 * Send our key (and encrypted PING) to the other peer.
1860 * @param n the other peer
1862 static void send_key (struct Neighbour *n);
1865 * Task that will retry "send_key" if our previous attempt failed
1869 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1871 struct Neighbour *n = cls;
1874 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1875 "Retrying key transmission to `%4s'\n",
1876 GNUNET_i2s (&n->peer));
1878 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1879 n->set_key_retry_frequency =
1880 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1886 * Check if we have plaintext messages for the specified neighbour
1887 * pending, and if so, consider batching and encrypting them (and
1888 * then trigger processing of the encrypted queue if needed).
1890 * @param n neighbour to check.
1893 process_plaintext_neighbour_queue (struct Neighbour *n)
1895 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1898 struct EncryptedMessage *em; /* encrypted message */
1899 struct EncryptedMessage *ph; /* plaintext header */
1900 struct MessageEntry *me;
1901 unsigned int priority;
1902 struct GNUNET_TIME_Absolute deadline;
1903 struct GNUNET_TIME_Relative retry_time;
1906 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1908 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1909 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1913 case PEER_STATE_DOWN:
1916 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1917 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1918 GNUNET_i2s(&n->peer));
1921 case PEER_STATE_KEY_SENT:
1922 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1923 n->retry_set_key_task
1924 = GNUNET_SCHEDULER_add_delayed (sched,
1925 n->set_key_retry_frequency,
1926 &set_key_retry_task, n);
1928 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1929 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1930 GNUNET_i2s(&n->peer));
1933 case PEER_STATE_KEY_RECEIVED:
1934 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1935 n->retry_set_key_task
1936 = GNUNET_SCHEDULER_add_delayed (sched,
1937 n->set_key_retry_frequency,
1938 &set_key_retry_task, n);
1940 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1941 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1942 GNUNET_i2s(&n->peer));
1945 case PEER_STATE_KEY_CONFIRMED:
1946 /* ready to continue */
1949 discard_expired_messages (n);
1950 if (n->messages == NULL)
1953 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1954 "Plaintext message queue for `%4s' is empty.\n",
1955 GNUNET_i2s(&n->peer));
1957 return; /* no pending messages */
1959 if (n->encrypted_head != NULL)
1962 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1963 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1964 GNUNET_i2s(&n->peer));
1966 return; /* wait for messages already encrypted to be
1969 ph = (struct EncryptedMessage *) pbuf;
1970 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1972 used = sizeof (struct EncryptedMessage);
1973 used += batch_message (n,
1975 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1976 &deadline, &retry_time, &priority);
1977 if (used == sizeof (struct EncryptedMessage))
1980 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1981 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1982 GNUNET_i2s(&n->peer));
1984 /* no messages selected for sending, try again later... */
1985 n->retry_plaintext_task =
1986 GNUNET_SCHEDULER_add_delayed (sched,
1988 &retry_plaintext_processing, n);
1991 #if DEBUG_CORE_QUOTA
1992 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1993 "Sending %u b/s as new limit to peer `%4s'\n",
1994 (unsigned int) ntohl (n->bw_in.value__),
1995 GNUNET_i2s (&n->peer));
1997 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1));
1998 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1999 ph->inbound_bw_limit = n->bw_in;
2000 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2002 /* setup encryption message header */
2003 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2004 me->deadline = deadline;
2005 me->priority = priority;
2007 em = (struct EncryptedMessage *) &me[1];
2008 em->header.size = htons (used);
2009 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2010 em->iv_seed = ph->iv_seed;
2011 esize = used - ENCRYPTED_HEADER_SIZE;
2012 GNUNET_CRYPTO_hash (&ph->sequence_number,
2013 esize - sizeof (GNUNET_HashCode),
2014 &ph->plaintext_hash);
2015 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
2017 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2018 "Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
2019 (unsigned int) (esize - sizeof (GNUNET_HashCode)),
2020 GNUNET_h2s (&ph->plaintext_hash),
2025 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2026 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2027 (unsigned int) esize,
2028 GNUNET_i2s(&n->peer),
2029 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2031 GNUNET_assert (GNUNET_OK ==
2034 &ph->plaintext_hash,
2035 &em->plaintext_hash, esize));
2036 /* append to transmission list */
2037 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2041 process_encrypted_neighbour_queue (n);
2046 * Function that recalculates the bandwidth quota for the
2047 * given neighbour and transmits it to the transport service.
2049 * @param cls neighbour for the quota update
2053 neighbour_quota_update (void *cls,
2054 const struct GNUNET_SCHEDULER_TaskContext *tc);
2058 * Schedule the task that will recalculate the bandwidth
2059 * quota for this peer (and possibly force a disconnect of
2060 * idle peers by calculating a bandwidth of zero).
2063 schedule_quota_update (struct Neighbour *n)
2065 GNUNET_assert (n->quota_update_task ==
2066 GNUNET_SCHEDULER_NO_TASK);
2067 n->quota_update_task
2068 = GNUNET_SCHEDULER_add_delayed (sched,
2069 QUOTA_UPDATE_FREQUENCY,
2070 &neighbour_quota_update,
2076 * Initialize a new 'struct Neighbour'.
2078 * @param pid ID of the new neighbour
2079 * @return handle for the new neighbour
2081 static struct Neighbour *
2082 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2084 struct Neighbour *n;
2085 struct GNUNET_TIME_Absolute now;
2087 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2088 "Creating neighbour entry for peer `%4s'\n",
2090 n = GNUNET_malloc (sizeof (struct Neighbour));
2091 n->next = neighbours;
2094 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2096 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2097 now = GNUNET_TIME_absolute_get ();
2098 n->encrypt_key_created = now;
2099 n->last_activity = now;
2100 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2101 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2102 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2103 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init ((uint32_t) - 1);
2104 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2105 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2107 neighbour_quota_update (n, NULL);
2108 consider_free_neighbour (n);
2114 * Handle CORE_SEND request.
2117 * @param client the client issuing the request
2118 * @param message the "struct SendMessage"
2121 handle_client_send (void *cls,
2122 struct GNUNET_SERVER_Client *client,
2123 const struct GNUNET_MessageHeader *message)
2125 const struct SendMessage *sm;
2126 struct Neighbour *n;
2127 struct MessageEntry *prev;
2128 struct MessageEntry *pos;
2129 struct MessageEntry *e;
2130 struct MessageEntry *min_prio_entry;
2131 struct MessageEntry *min_prio_prev;
2132 unsigned int min_prio;
2133 unsigned int queue_size;
2136 msize = ntohs (message->size);
2138 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2142 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2145 sm = (const struct SendMessage *) message;
2146 msize -= sizeof (struct SendMessage);
2147 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2149 /* FIXME: should we not allow loopback-injection here? */
2152 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2155 n = find_neighbour (&sm->peer);
2157 n = create_neighbour (&sm->peer);
2159 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2160 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2162 (unsigned int) msize,
2163 GNUNET_i2s (&sm->peer));
2165 /* bound queue size */
2166 discard_expired_messages (n);
2167 min_prio = (unsigned int) -1;
2168 min_prio_entry = NULL;
2169 min_prio_prev = NULL;
2175 if (pos->priority < min_prio)
2177 min_prio_entry = pos;
2178 min_prio_prev = prev;
2179 min_prio = pos->priority;
2185 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2188 if (ntohl(sm->priority) <= min_prio)
2190 /* discard new entry */
2192 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2193 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2195 (unsigned int) MAX_PEER_QUEUE_SIZE,
2196 (unsigned int) msize,
2197 (unsigned int) ntohs (message->type));
2200 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2203 /* discard "min_prio_entry" */
2205 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2206 "Queue full, discarding existing older request\n");
2208 if (min_prio_prev == NULL)
2209 n->messages = min_prio_entry->next;
2211 min_prio_prev->next = min_prio_entry->next;
2212 GNUNET_free (min_prio_entry);
2216 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2217 "Adding transmission request for `%4s' of size %u to queue\n",
2218 GNUNET_i2s (&sm->peer),
2219 (unsigned int) msize);
2221 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2222 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2223 e->priority = ntohl (sm->priority);
2225 memcpy (&e[1], &sm[1], msize);
2227 /* insert, keep list sorted by deadline */
2230 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2241 /* consider scheduling now */
2242 process_plaintext_neighbour_queue (n);
2244 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2249 * Function called when the transport service is ready to
2250 * receive a message. Only resets 'n->th' to NULL.
2252 * @param cls neighbour to use message from
2253 * @param size number of bytes we can transmit
2254 * @param buf where to copy the message
2255 * @return number of bytes transmitted
2258 notify_transport_connect_done (void *cls, size_t size, void *buf)
2260 struct Neighbour *n = cls;
2265 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2266 _("Failed to connect to `%4s': transport failed to connect\n"),
2267 GNUNET_i2s (&n->peer));
2276 * Handle CORE_REQUEST_CONNECT request.
2279 * @param client the client issuing the request
2280 * @param message the "struct ConnectMessage"
2283 handle_client_request_connect (void *cls,
2284 struct GNUNET_SERVER_Client *client,
2285 const struct GNUNET_MessageHeader *message)
2287 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2288 struct Neighbour *n;
2289 struct GNUNET_TIME_Relative timeout;
2291 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2294 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2297 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2298 n = find_neighbour (&cm->peer);
2300 n = create_neighbour (&cm->peer);
2301 if ( (GNUNET_YES == n->is_connected) ||
2303 return; /* already connected, or at least trying */
2304 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2306 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2307 "Core received `%s' request for `%4s', will try to establish connection\n",
2309 GNUNET_i2s (&cm->peer));
2311 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2312 /* ask transport to connect to the peer */
2313 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2315 sizeof (struct GNUNET_MessageHeader), 0,
2317 ¬ify_transport_connect_done,
2319 GNUNET_break (NULL != n->th);
2324 * List of handlers for the messages understood by this
2327 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2328 {&handle_client_init, NULL,
2329 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2330 {&handle_client_request_info, NULL,
2331 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2332 sizeof (struct RequestInfoMessage)},
2333 {&handle_client_send, NULL,
2334 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2335 {&handle_client_request_connect, NULL,
2336 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2337 sizeof (struct ConnectMessage)},
2343 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2344 * the neighbour's struct and retry send_key. Or, if we did not get a
2345 * HELLO, just do nothing.
2347 * @param cls the 'struct Neighbour' to retry sending the key for
2348 * @param peer the peer for which this is the HELLO
2349 * @param hello HELLO message of that peer
2350 * @param trust amount of trust we currently have in that peer
2353 process_hello_retry_send_key (void *cls,
2354 const struct GNUNET_PeerIdentity *peer,
2355 const struct GNUNET_HELLO_Message *hello,
2358 struct Neighbour *n = cls;
2363 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2364 "Entered `%s' and `%s' is NULL!\n",
2365 "process_hello_retry_send_key",
2369 if (n->public_key != NULL)
2371 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2373 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2374 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2376 GNUNET_STATISTICS_update (stats,
2377 gettext_noop ("# SETKEY messages deferred (need public key)"),
2384 GNUNET_STATISTICS_update (stats,
2385 gettext_noop ("# Delayed connecting due to lack of public key"),
2388 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2389 n->retry_set_key_task
2390 = GNUNET_SCHEDULER_add_delayed (sched,
2391 n->set_key_retry_frequency,
2392 &set_key_retry_task, n);
2398 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2399 "Entered `%s' for peer `%4s'\n",
2400 "process_hello_retry_send_key",
2403 if (n->public_key != NULL)
2405 /* already have public key, why are we here? */
2411 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2412 "Received new `%s' message for `%4s', initiating key exchange.\n",
2417 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2418 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2420 GNUNET_STATISTICS_update (stats,
2421 gettext_noop ("# Error extracting public key from HELLO"),
2424 GNUNET_free (n->public_key);
2425 n->public_key = NULL;
2427 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2428 "GNUNET_HELLO_get_key returned awfully\n");
2436 * Send our key (and encrypted PING) to the other peer.
2438 * @param n the other peer
2441 send_key (struct Neighbour *n)
2443 struct SetKeyMessage *sm;
2444 struct MessageEntry *me;
2445 struct PingMessage pp;
2446 struct PingMessage *pm;
2448 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2450 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2451 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2453 if (n->pitr != NULL)
2456 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2457 "Key exchange in progress with `%4s'.\n",
2458 GNUNET_i2s (&n->peer));
2460 return; /* already in progress */
2462 if (GNUNET_YES != n->is_connected)
2465 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2466 "Not yet connected to peer `%4s'!\n",
2467 GNUNET_i2s (&n->peer));
2471 GNUNET_STATISTICS_update (stats,
2472 gettext_noop ("# Asking transport to connect (for SETKEY)"),
2475 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2477 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2479 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2480 ¬ify_encrypted_transmit_ready,
2486 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2487 "Asked to perform key exchange with `%4s'.\n",
2488 GNUNET_i2s (&n->peer));
2490 if (n->public_key == NULL)
2492 /* lookup n's public key, then try again */
2494 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2495 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2496 GNUNET_i2s (&n->peer));
2498 GNUNET_assert (n->pitr == NULL);
2499 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2502 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2503 &process_hello_retry_send_key, n);
2506 /* first, set key message */
2507 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2508 sizeof (struct SetKeyMessage));
2509 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2510 me->priority = SET_KEY_PRIORITY;
2511 me->size = sizeof (struct SetKeyMessage);
2512 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2516 sm = (struct SetKeyMessage *) &me[1];
2517 sm->header.size = htons (sizeof (struct SetKeyMessage));
2518 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2519 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2520 PEER_STATE_KEY_SENT : n->status));
2522 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2523 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2524 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2525 sizeof (struct GNUNET_PeerIdentity));
2526 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2527 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2528 sm->target = n->peer;
2529 GNUNET_assert (GNUNET_OK ==
2530 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2532 GNUNET_CRYPTO_AesSessionKey),
2534 &sm->encrypted_key));
2535 GNUNET_assert (GNUNET_OK ==
2536 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2539 /* second, encrypted PING message */
2540 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2541 sizeof (struct PingMessage));
2542 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2543 me->priority = PING_PRIORITY;
2544 me->size = sizeof (struct PingMessage);
2545 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2549 pm = (struct PingMessage *) &me[1];
2550 pm->header.size = htons (sizeof (struct PingMessage));
2551 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2552 pp.challenge = htonl (n->ping_challenge);
2553 pp.target = n->peer;
2555 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2556 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u.\n",
2558 (unsigned int) n->ping_challenge,
2559 GNUNET_i2s (&n->peer),
2560 (unsigned int) n->encrypt_key.crc32);
2563 &n->peer.hashPubKey,
2566 sizeof (struct PingMessage) -
2567 sizeof (struct GNUNET_MessageHeader));
2571 case PEER_STATE_DOWN:
2572 n->status = PEER_STATE_KEY_SENT;
2574 case PEER_STATE_KEY_SENT:
2576 case PEER_STATE_KEY_RECEIVED:
2578 case PEER_STATE_KEY_CONFIRMED:
2584 GNUNET_STATISTICS_update (stats,
2585 gettext_noop ("# SETKEY and PING messages created"),
2589 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2590 "Have %llu ms left for `%s' transmission.\n",
2591 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2594 /* trigger queue processing */
2595 process_encrypted_neighbour_queue (n);
2596 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2597 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2598 n->retry_set_key_task
2599 = GNUNET_SCHEDULER_add_delayed (sched,
2600 n->set_key_retry_frequency,
2601 &set_key_retry_task, n);
2606 * We received a SET_KEY message. Validate and update
2607 * our key material and status.
2609 * @param n the neighbour from which we received message m
2610 * @param m the set key message we received
2613 handle_set_key (struct Neighbour *n,
2614 const struct SetKeyMessage *m);
2618 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2619 * the neighbour's struct and retry handling the set_key message. Or,
2620 * if we did not get a HELLO, just free the set key message.
2622 * @param cls pointer to the set key message
2623 * @param peer the peer for which this is the HELLO
2624 * @param hello HELLO message of that peer
2625 * @param trust amount of trust we currently have in that peer
2628 process_hello_retry_handle_set_key (void *cls,
2629 const struct GNUNET_PeerIdentity *peer,
2630 const struct GNUNET_HELLO_Message *hello,
2633 struct Neighbour *n = cls;
2634 struct SetKeyMessage *sm = n->skm;
2640 if (n->public_key != NULL)
2643 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2644 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2646 GNUNET_i2s (&n->peer),
2649 handle_set_key (n, sm);
2654 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2655 "Ignoring `%s' message due to lack of public key for peer (failed to obtain one).\n",
2662 if (n->public_key != NULL)
2663 return; /* multiple HELLOs match!? */
2665 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2666 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2668 GNUNET_break_op (0);
2669 GNUNET_free (n->public_key);
2670 n->public_key = NULL;
2676 * We received a PING message. Validate and transmit
2679 * @param n sender of the PING
2680 * @param m the encrypted PING message itself
2683 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2685 struct PingMessage t;
2686 struct PongMessage tx;
2687 struct PongMessage *tp;
2688 struct MessageEntry *me;
2691 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2692 "Core service receives `%s' request from `%4s'.\n",
2693 "PING", GNUNET_i2s (&n->peer));
2697 &my_identity.hashPubKey,
2700 sizeof (struct PingMessage) -
2701 sizeof (struct GNUNET_MessageHeader)))
2704 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2705 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2707 GNUNET_i2s (&t.target),
2708 (unsigned int) ntohl (t.challenge),
2709 (unsigned int) n->decrypt_key.crc32);
2711 GNUNET_STATISTICS_update (stats,
2712 gettext_noop ("# PING messages decrypted"),
2715 if (0 != memcmp (&t.target,
2716 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2718 GNUNET_break_op (0);
2721 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2722 sizeof (struct PongMessage));
2723 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2727 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2728 me->priority = PONG_PRIORITY;
2729 me->size = sizeof (struct PongMessage);
2730 tx.reserved = htonl (0);
2731 tx.inbound_bw_limit = n->bw_in;
2732 tx.challenge = t.challenge;
2733 tx.target = t.target;
2734 tp = (struct PongMessage *) &me[1];
2735 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2736 tp->header.size = htons (sizeof (struct PongMessage));
2738 &my_identity.hashPubKey,
2741 sizeof (struct PongMessage) -
2742 sizeof (struct GNUNET_MessageHeader));
2743 GNUNET_STATISTICS_update (stats,
2744 gettext_noop ("# PONG messages created"),
2748 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2749 "Encrypting `%s' with challenge %u using key %u\n",
2751 (unsigned int) ntohl (t.challenge),
2752 (unsigned int) n->encrypt_key.crc32);
2754 /* trigger queue processing */
2755 process_encrypted_neighbour_queue (n);
2760 * We received a PONG message. Validate and update our status.
2762 * @param n sender of the PONG
2763 * @param m the encrypted PONG message itself
2766 handle_pong (struct Neighbour *n,
2767 const struct PongMessage *m)
2769 struct PongMessage t;
2770 struct ConnectNotifyMessage cnm;
2773 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2774 "Core service receives `%s' request from `%4s'.\n",
2775 "PONG", GNUNET_i2s (&n->peer));
2777 /* mark as garbage, just to be sure */
2778 memset (&t, 255, sizeof (t));
2781 &n->peer.hashPubKey,
2784 sizeof (struct PongMessage) -
2785 sizeof (struct GNUNET_MessageHeader)))
2787 GNUNET_break_op (0);
2790 GNUNET_STATISTICS_update (stats,
2791 gettext_noop ("# PONG messages decrypted"),
2794 if (0 != ntohl (t.reserved))
2796 GNUNET_break_op (0);
2800 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2801 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2803 GNUNET_i2s (&t.target),
2804 (unsigned int) ntohl (t.challenge),
2805 (unsigned int) n->decrypt_key.crc32);
2807 if ((0 != memcmp (&t.target,
2809 sizeof (struct GNUNET_PeerIdentity))) ||
2810 (n->ping_challenge != ntohl (t.challenge)))
2812 /* PONG malformed */
2814 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2815 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2817 GNUNET_i2s (&n->peer),
2818 (unsigned int) n->ping_challenge);
2819 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2820 "Received malformed `%s' received from `%4s' with challenge %u\n",
2821 "PONG", GNUNET_i2s (&t.target),
2822 (unsigned int) ntohl (t.challenge));
2824 GNUNET_break_op (0);
2829 case PEER_STATE_DOWN:
2830 GNUNET_break (0); /* should be impossible */
2832 case PEER_STATE_KEY_SENT:
2833 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2835 case PEER_STATE_KEY_RECEIVED:
2836 GNUNET_STATISTICS_update (stats,
2837 gettext_noop ("# Session keys confirmed via PONG"),
2840 n->status = PEER_STATE_KEY_CONFIRMED;
2841 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2843 n->bw_out_external_limit = t.inbound_bw_limit;
2844 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2845 n->bw_out_internal_limit);
2846 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2848 GNUNET_TRANSPORT_set_quota (transport,
2852 GNUNET_TIME_UNIT_FOREVER_REL,
2856 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2857 "Confirmed key via `%s' message for peer `%4s'\n",
2858 "PONG", GNUNET_i2s (&n->peer));
2860 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2862 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2863 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2865 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2866 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2867 cnm.distance = htonl (n->last_distance);
2868 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2870 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2871 process_encrypted_neighbour_queue (n);
2873 case PEER_STATE_KEY_CONFIRMED:
2874 n->last_activity = GNUNET_TIME_absolute_get ();
2875 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2876 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2878 = GNUNET_SCHEDULER_add_delayed (sched,
2879 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2891 * We received a SET_KEY message. Validate and update
2892 * our key material and status.
2894 * @param n the neighbour from which we received message m
2895 * @param m the set key message we received
2898 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2900 struct SetKeyMessage *m_cpy;
2901 struct GNUNET_TIME_Absolute t;
2902 struct GNUNET_CRYPTO_AesSessionKey k;
2903 struct PingMessage *ping;
2904 struct PongMessage *pong;
2905 enum PeerStateMachine sender_status;
2908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2909 "Core service receives `%s' request from `%4s'.\n",
2910 "SET_KEY", GNUNET_i2s (&n->peer));
2912 if (n->public_key == NULL)
2914 if (n->pitr != NULL)
2917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2918 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2924 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2925 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2927 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2928 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2929 /* lookup n's public key, then try again */
2930 GNUNET_assert (n->skm == NULL);
2932 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2935 GNUNET_TIME_UNIT_MINUTES,
2936 &process_hello_retry_handle_set_key, n);
2937 GNUNET_STATISTICS_update (stats,
2938 gettext_noop ("# SETKEY messages deferred (need public key)"),
2943 if (0 != memcmp (&m->target,
2945 sizeof (struct GNUNET_PeerIdentity)))
2947 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2948 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
2950 GNUNET_i2s (&m->target));
2953 if ((ntohl (m->purpose.size) !=
2954 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2955 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2956 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2957 sizeof (struct GNUNET_PeerIdentity)) ||
2959 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2960 &m->purpose, &m->signature, n->public_key)))
2962 /* invalid signature */
2963 GNUNET_break_op (0);
2966 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2967 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2968 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2969 (t.value < n->decrypt_key_created.value))
2971 /* this could rarely happen due to massive re-ordering of
2972 messages on the network level, but is most likely either
2973 a bug or some adversary messing with us. Report. */
2974 GNUNET_break_op (0);
2978 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2979 "Decrypting key material.\n");
2981 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2984 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2985 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2986 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2988 /* failed to decrypt !? */
2989 GNUNET_break_op (0);
2992 GNUNET_STATISTICS_update (stats,
2993 gettext_noop ("# SETKEY messages decrypted"),
2997 if (n->decrypt_key_created.value != t.value)
2999 /* fresh key, reset sequence numbers */
3000 n->last_sequence_number_received = 0;
3001 n->last_packets_bitmap = 0;
3002 n->decrypt_key_created = t;
3004 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3007 case PEER_STATE_DOWN:
3008 n->status = PEER_STATE_KEY_RECEIVED;
3010 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3011 "Responding to `%s' with my own key.\n", "SET_KEY");
3015 case PEER_STATE_KEY_SENT:
3016 case PEER_STATE_KEY_RECEIVED:
3017 n->status = PEER_STATE_KEY_RECEIVED;
3018 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3019 (sender_status != PEER_STATE_KEY_CONFIRMED))
3022 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3023 "Responding to `%s' with my own key (other peer has status %u).\n",
3025 (unsigned int) sender_status);
3030 case PEER_STATE_KEY_CONFIRMED:
3031 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3032 (sender_status != PEER_STATE_KEY_CONFIRMED))
3035 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3036 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3038 (unsigned int) sender_status);
3047 if (n->pending_ping != NULL)
3049 ping = n->pending_ping;
3050 n->pending_ping = NULL;
3051 handle_ping (n, ping);
3054 if (n->pending_pong != NULL)
3056 pong = n->pending_pong;
3057 n->pending_pong = NULL;
3058 handle_pong (n, pong);
3065 * Send a P2P message to a client.
3067 * @param sender who sent us the message?
3068 * @param client who should we give the message to?
3069 * @param m contains the message to transmit
3070 * @param msize number of bytes in buf to transmit
3073 send_p2p_message_to_client (struct Neighbour *sender,
3074 struct Client *client,
3075 const void *m, size_t msize)
3077 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3078 struct NotifyTrafficMessage *ntm;
3081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3082 "Core service passes message from `%4s' of type %u to client.\n",
3083 GNUNET_i2s(&sender->peer),
3084 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3086 ntm = (struct NotifyTrafficMessage *) buf;
3087 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3088 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3089 ntm->distance = htonl (sender->last_distance);
3090 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3091 ntm->peer = sender->peer;
3092 memcpy (&ntm[1], m, msize);
3093 send_to_client (client, &ntm->header, GNUNET_YES);
3098 * Deliver P2P message to interested clients.
3100 * @param sender who sent us the message?
3101 * @param m the message
3102 * @param msize size of the message (including header)
3105 deliver_message (struct Neighbour *sender,
3106 const struct GNUNET_MessageHeader *m, size_t msize)
3109 struct Client *cpos;
3115 type = ntohs (m->type);
3117 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3118 "Received encapsulated message of type %u from `%4s'\n",
3119 (unsigned int) type,
3120 GNUNET_i2s (&sender->peer));
3122 GNUNET_snprintf (buf,
3124 gettext_noop ("# bytes of messages of type %u received"),
3125 (unsigned int) type);
3126 GNUNET_STATISTICS_set (stats,
3130 dropped = GNUNET_YES;
3132 while (cpos != NULL)
3134 deliver_full = GNUNET_NO;
3135 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3136 deliver_full = GNUNET_YES;
3139 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3141 if (type != cpos->types[tpos])
3143 deliver_full = GNUNET_YES;
3147 if (GNUNET_YES == deliver_full)
3149 send_p2p_message_to_client (sender, cpos, m, msize);
3150 dropped = GNUNET_NO;
3152 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3154 send_p2p_message_to_client (sender, cpos, m,
3155 sizeof (struct GNUNET_MessageHeader));
3159 if (dropped == GNUNET_YES)
3162 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3163 "Message of type %u from `%4s' not delivered to any client.\n",
3164 (unsigned int) type,
3165 GNUNET_i2s (&sender->peer));
3167 /* FIXME: stats... */
3173 * Align P2P message and then deliver to interested clients.
3175 * @param sender who sent us the message?
3176 * @param buffer unaligned (!) buffer containing message
3177 * @param msize size of the message (including header)
3180 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
3184 /* TODO: call to statistics? */
3185 memcpy (abuf, buffer, msize);
3186 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
3191 * Deliver P2P messages to interested clients.
3193 * @param sender who sent us the message?
3194 * @param buffer buffer containing messages, can be modified
3195 * @param buffer_size size of the buffer (overall)
3196 * @param offset offset where messages in the buffer start
3199 deliver_messages (struct Neighbour *sender,
3200 const char *buffer, size_t buffer_size, size_t offset)
3202 struct GNUNET_MessageHeader *mhp;
3203 struct GNUNET_MessageHeader mh;
3207 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
3209 if (0 != offset % sizeof (uint16_t))
3211 /* outch, need to copy to access header */
3212 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
3217 /* can access header directly */
3218 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
3220 msize = ntohs (mhp->size);
3221 if (msize + offset > buffer_size)
3223 /* malformed message, header says it is larger than what
3224 would fit into the overall buffer */
3225 GNUNET_break_op (0);
3228 #if HAVE_UNALIGNED_64_ACCESS
3229 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
3231 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
3233 if (GNUNET_YES == need_align)
3234 align_and_deliver (sender, &buffer[offset], msize);
3236 deliver_message (sender,
3237 (const struct GNUNET_MessageHeader *)
3238 &buffer[offset], msize);
3245 * We received an encrypted message. Decrypt, validate and
3246 * pass on to the appropriate clients.
3249 handle_encrypted_message (struct Neighbour *n,
3250 const struct EncryptedMessage *m)
3252 size_t size = ntohs (m->header.size);
3254 struct EncryptedMessage *pt; /* plaintext */
3257 struct GNUNET_TIME_Absolute t;
3261 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3262 "Core service receives `%s' request from `%4s'.\n",
3263 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3265 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3271 &buf[ENCRYPTED_HEADER_SIZE],
3272 size - ENCRYPTED_HEADER_SIZE))
3274 pt = (struct EncryptedMessage *) buf;
3276 GNUNET_CRYPTO_hash (&pt->sequence_number,
3277 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3279 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3280 "V-Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
3281 (unsigned int) (size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode)),
3285 if (0 != memcmp (&ph,
3286 &pt->plaintext_hash,
3287 sizeof (GNUNET_HashCode)))
3289 /* checksum failed */
3290 GNUNET_break_op (0);
3294 /* validate sequence number */
3295 snum = ntohl (pt->sequence_number);
3296 if (n->last_sequence_number_received == snum)
3298 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3299 "Received duplicate message, ignoring.\n");
3300 /* duplicate, ignore */
3301 GNUNET_STATISTICS_set (stats,
3302 gettext_noop ("# bytes dropped (duplicates)"),
3307 if ((n->last_sequence_number_received > snum) &&
3308 (n->last_sequence_number_received - snum > 32))
3310 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3311 "Received ancient out of sequence message, ignoring.\n");
3312 /* ancient out of sequence, ignore */
3313 GNUNET_STATISTICS_set (stats,
3314 gettext_noop ("# bytes dropped (out of sequence)"),
3319 if (n->last_sequence_number_received > snum)
3321 unsigned int rotbit =
3322 1 << (n->last_sequence_number_received - snum - 1);
3323 if ((n->last_packets_bitmap & rotbit) != 0)
3325 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3326 "Received duplicate message, ignoring.\n");
3327 GNUNET_STATISTICS_set (stats,
3328 gettext_noop ("# bytes dropped (duplicates)"),
3331 /* duplicate, ignore */
3334 n->last_packets_bitmap |= rotbit;
3336 if (n->last_sequence_number_received < snum)
3338 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3339 n->last_sequence_number_received = snum;
3342 /* check timestamp */
3343 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3344 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3346 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3348 ("Message received far too old (%llu ms). Content ignored.\n"),
3349 GNUNET_TIME_absolute_get_duration (t).value);
3350 GNUNET_STATISTICS_set (stats,
3351 gettext_noop ("# bytes dropped (ancient message)"),
3357 /* process decrypted message(s) */
3358 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3360 #if DEBUG_CORE_SET_QUOTA
3361 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3362 "Received %u b/s as new inbound limit for peer `%4s'\n",
3363 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3364 GNUNET_i2s (&n->peer));
3366 n->bw_out_external_limit = pt->inbound_bw_limit;
3367 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3368 n->bw_out_internal_limit);
3369 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3371 GNUNET_TRANSPORT_set_quota (transport,
3375 GNUNET_TIME_UNIT_FOREVER_REL,
3378 n->last_activity = GNUNET_TIME_absolute_get ();
3379 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3380 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3382 = GNUNET_SCHEDULER_add_delayed (sched,
3383 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3386 GNUNET_STATISTICS_set (stats,
3387 gettext_noop ("# bytes of payload decrypted"),
3388 size - sizeof (struct EncryptedMessage),
3390 deliver_messages (n, buf, size, sizeof (struct EncryptedMessage));
3395 * Function called by the transport for each received message.
3397 * @param cls closure
3398 * @param peer (claimed) identity of the other peer
3399 * @param message the message
3400 * @param latency estimated latency for communicating with the
3401 * given peer (round-trip)
3402 * @param distance in overlay hops, as given by transport plugin
3405 handle_transport_receive (void *cls,
3406 const struct GNUNET_PeerIdentity *peer,
3407 const struct GNUNET_MessageHeader *message,
3408 struct GNUNET_TIME_Relative latency,
3409 unsigned int distance)
3411 struct Neighbour *n;
3412 struct GNUNET_TIME_Absolute now;
3418 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3419 "Received message of type %u from `%4s', demultiplexing.\n",
3420 (unsigned int) ntohs (message->type),
3423 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3428 n = find_neighbour (peer);
3430 n = create_neighbour (peer);
3431 n->last_latency = latency;
3432 n->last_distance = distance;
3433 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3434 type = ntohs (message->type);
3435 size = ntohs (message->size);
3438 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3439 if (size != sizeof (struct SetKeyMessage))
3441 GNUNET_break_op (0);
3444 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3445 handle_set_key (n, (const struct SetKeyMessage *) message);
3447 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3448 if (size < sizeof (struct EncryptedMessage) +
3449 sizeof (struct GNUNET_MessageHeader))
3451 GNUNET_break_op (0);
3454 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3455 (n->status != PEER_STATE_KEY_CONFIRMED))
3457 GNUNET_break_op (0);
3460 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3462 case GNUNET_MESSAGE_TYPE_CORE_PING:
3463 if (size != sizeof (struct PingMessage))
3465 GNUNET_break_op (0);
3468 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3469 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3470 (n->status != PEER_STATE_KEY_CONFIRMED))
3473 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3474 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3475 "PING", GNUNET_i2s (&n->peer));
3477 GNUNET_free_non_null (n->pending_ping);
3478 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3479 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3482 handle_ping (n, (const struct PingMessage *) message);
3484 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3485 if (size != sizeof (struct PongMessage))
3487 GNUNET_break_op (0);
3490 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3491 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3492 (n->status != PEER_STATE_KEY_CONFIRMED) )
3495 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3496 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3497 "PONG", GNUNET_i2s (&n->peer));
3499 GNUNET_free_non_null (n->pending_pong);
3500 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3501 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3504 handle_pong (n, (const struct PongMessage *) message);
3507 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3508 _("Unsupported message of type %u received.\n"),
3509 (unsigned int) type);
3512 if (n->status == PEER_STATE_KEY_CONFIRMED)
3514 now = GNUNET_TIME_absolute_get ();
3515 n->last_activity = now;
3518 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3519 n->time_established = now;
3521 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3522 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3524 = GNUNET_SCHEDULER_add_delayed (sched,
3525 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3533 * Function that recalculates the bandwidth quota for the
3534 * given neighbour and transmits it to the transport service.
3536 * @param cls neighbour for the quota update
3540 neighbour_quota_update (void *cls,
3541 const struct GNUNET_SCHEDULER_TaskContext *tc)
3543 struct Neighbour *n = cls;
3544 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3547 unsigned long long distributable;
3548 uint64_t need_per_peer;
3549 uint64_t need_per_second;
3551 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3552 /* calculate relative preference among all neighbours;
3553 divides by a bit more to avoid division by zero AND to
3554 account for possibility of new neighbours joining any time
3555 AND to convert to double... */
3556 if (preference_sum == 0)
3558 pref_rel = 1.0 / (double) neighbour_count;
3562 pref_rel = n->current_preference / preference_sum;
3564 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3565 GNUNET_TIME_UNIT_SECONDS);
3566 need_per_second = need_per_peer * neighbour_count;
3568 if (bandwidth_target_out_bps > need_per_second)
3569 distributable = bandwidth_target_out_bps - need_per_second;
3570 share = distributable * pref_rel;
3571 if (share + need_per_peer > ( (uint32_t)-1))
3572 q_in = GNUNET_BANDWIDTH_value_init ((uint32_t) -1);
3574 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3575 /* check if we want to disconnect for good due to inactivity */
3576 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3577 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3580 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3581 "Forcing disconnect of `%4s' due to inactivity\n",
3582 GNUNET_i2s (&n->peer));
3584 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3586 #if DEBUG_CORE_QUOTA
3587 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3588 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3589 GNUNET_i2s (&n->peer),
3590 (unsigned int) ntohl (q_in.value__),
3591 bandwidth_target_out_bps,
3592 (unsigned int) ntohl (n->bw_in.value__),
3593 (unsigned int) ntohl (n->bw_out.value__),
3594 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3596 if (n->bw_in.value__ != q_in.value__)
3599 if (GNUNET_YES == n->is_connected)
3600 GNUNET_TRANSPORT_set_quota (transport,
3604 GNUNET_TIME_UNIT_FOREVER_REL,
3607 schedule_quota_update (n);
3612 * Function called by transport to notify us that
3613 * a peer connected to us (on the network level).
3615 * @param cls closure
3616 * @param peer the peer that connected
3617 * @param latency current latency of the connection
3618 * @param distance in overlay hops, as given by transport plugin
3621 handle_transport_notify_connect (void *cls,
3622 const struct GNUNET_PeerIdentity *peer,
3623 struct GNUNET_TIME_Relative latency,
3624 unsigned int distance)
3626 struct Neighbour *n;
3628 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3633 n = find_neighbour (peer);
3636 if (GNUNET_YES == n->is_connected)
3638 /* duplicate connect notification!? */
3645 n = create_neighbour (peer);
3647 GNUNET_STATISTICS_update (stats,
3648 gettext_noop ("# peers connected (transport)"),
3651 n->is_connected = GNUNET_YES;
3652 n->last_latency = latency;
3653 n->last_distance = distance;
3654 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3657 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3661 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3662 "Received connection from `%4s'.\n",
3663 GNUNET_i2s (&n->peer));
3665 GNUNET_TRANSPORT_set_quota (transport,
3669 GNUNET_TIME_UNIT_FOREVER_REL,
3676 * Function called by transport telling us that a peer
3679 * @param cls closure
3680 * @param peer the peer that disconnected
3683 handle_transport_notify_disconnect (void *cls,
3684 const struct GNUNET_PeerIdentity *peer)
3686 struct DisconnectNotifyMessage cnm;
3687 struct Neighbour *n;
3690 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3691 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3693 n = find_neighbour (peer);
3699 GNUNET_break (n->is_connected);
3700 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3701 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3703 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3704 n->is_connected = GNUNET_NO;
3705 GNUNET_STATISTICS_update (stats,
3706 gettext_noop ("# peers connected (transport)"),
3713 * Last task run during shutdown. Disconnects us from
3717 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3719 struct Neighbour *n;
3723 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3724 "Core service shutting down.\n");
3726 GNUNET_assert (transport != NULL);
3727 GNUNET_TRANSPORT_disconnect (transport);
3729 while (NULL != (n = neighbours))
3731 neighbours = n->next;
3732 GNUNET_assert (neighbour_count > 0);
3736 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
3737 GNUNET_SERVER_notification_context_destroy (notifier);
3739 while (NULL != (c = clients))
3740 handle_client_disconnect (NULL, c->client_handle);
3741 if (my_private_key != NULL)
3742 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3744 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3745 if (peerinfo != NULL)
3746 GNUNET_PEERINFO_disconnect (peerinfo);
3751 * Initiate core service.
3753 * @param cls closure
3754 * @param s scheduler to use
3755 * @param serv the initialized server
3756 * @param c configuration to use
3760 struct GNUNET_SCHEDULER_Handle *s,
3761 struct GNUNET_SERVER_Handle *serv,
3762 const struct GNUNET_CONFIGURATION_Handle *c)
3768 /* parse configuration */
3771 GNUNET_CONFIGURATION_get_value_number (c,
3774 &bandwidth_target_in_bps)) ||
3776 GNUNET_CONFIGURATION_get_value_number (c,
3779 &bandwidth_target_out_bps)) ||
3781 GNUNET_CONFIGURATION_get_value_filename (c,
3783 "HOSTKEY", &keyfile)))
3785 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3787 ("Core service is lacking key configuration settings. Exiting.\n"));
3788 GNUNET_SCHEDULER_shutdown (s);
3791 peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
3792 if (NULL == peerinfo)
3794 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3795 _("Could not access PEERINFO service. Exiting.\n"));
3796 GNUNET_SCHEDULER_shutdown (s);
3797 GNUNET_free (keyfile);
3800 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3801 GNUNET_free (keyfile);
3802 if (my_private_key == NULL)
3804 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3805 _("Core service could not access hostkey. Exiting.\n"));
3806 GNUNET_PEERINFO_disconnect (peerinfo);
3807 GNUNET_SCHEDULER_shutdown (s);
3810 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3811 GNUNET_CRYPTO_hash (&my_public_key,
3812 sizeof (my_public_key), &my_identity.hashPubKey);
3813 /* setup notification */
3815 notifier = GNUNET_SERVER_notification_context_create (server,
3817 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3818 /* setup transport connection */
3819 transport = GNUNET_TRANSPORT_connect (sched,
3822 &handle_transport_receive,
3823 &handle_transport_notify_connect,
3824 &handle_transport_notify_disconnect);
3825 GNUNET_assert (NULL != transport);
3826 stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3827 GNUNET_SCHEDULER_add_delayed (sched,
3828 GNUNET_TIME_UNIT_FOREVER_REL,
3829 &cleaning_task, NULL);
3830 /* process client requests */
3831 GNUNET_SERVER_add_handlers (server, handlers);
3832 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3833 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3839 * The main function for the transport service.
3841 * @param argc number of arguments from the command line
3842 * @param argv command line arguments
3843 * @return 0 ok, 1 on error
3846 main (int argc, char *const *argv)
3848 return (GNUNET_OK ==
3849 GNUNET_SERVICE_run (argc,
3852 GNUNET_SERVICE_OPTION_NONE,
3853 &run, NULL)) ? 0 : 1;
3856 /* end of gnunet-service-core.c */