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));
2779 &n->peer.hashPubKey,
2782 sizeof (struct PongMessage) -
2783 sizeof (struct GNUNET_MessageHeader)))
2785 GNUNET_break_op (0);
2788 GNUNET_STATISTICS_update (stats,
2789 gettext_noop ("# PONG messages decrypted"),
2792 if (0 != ntohl (t.reserved))
2794 GNUNET_break_op (0);
2798 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2799 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2801 GNUNET_i2s (&t.target),
2802 (unsigned int) ntohl (t.challenge),
2803 (unsigned int) n->decrypt_key.crc32);
2805 if ((0 != memcmp (&t.target,
2807 sizeof (struct GNUNET_PeerIdentity))) ||
2808 (n->ping_challenge != ntohl (t.challenge)))
2810 /* PONG malformed */
2812 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2813 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2815 GNUNET_i2s (&n->peer),
2816 (unsigned int) n->ping_challenge);
2817 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2818 "Received malformed `%s' received from `%4s' with challenge %u\n",
2819 "PONG", GNUNET_i2s (&t.target),
2820 (unsigned int) ntohl (t.challenge));
2822 GNUNET_break_op (0);
2827 case PEER_STATE_DOWN:
2828 GNUNET_break (0); /* should be impossible */
2830 case PEER_STATE_KEY_SENT:
2831 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2833 case PEER_STATE_KEY_RECEIVED:
2834 GNUNET_STATISTICS_update (stats,
2835 gettext_noop ("# Session keys confirmed via PONG"),
2838 n->status = PEER_STATE_KEY_CONFIRMED;
2839 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2841 n->bw_out_external_limit = t.inbound_bw_limit;
2842 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2843 n->bw_out_internal_limit);
2844 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2846 GNUNET_TRANSPORT_set_quota (transport,
2850 GNUNET_TIME_UNIT_FOREVER_REL,
2854 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2855 "Confirmed key via `%s' message for peer `%4s'\n",
2856 "PONG", GNUNET_i2s (&n->peer));
2858 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2860 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2861 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2863 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2864 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2865 cnm.distance = htonl (n->last_distance);
2866 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2868 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2869 process_encrypted_neighbour_queue (n);
2871 case PEER_STATE_KEY_CONFIRMED:
2872 n->last_activity = GNUNET_TIME_absolute_get ();
2873 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2874 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2876 = GNUNET_SCHEDULER_add_delayed (sched,
2877 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2889 * We received a SET_KEY message. Validate and update
2890 * our key material and status.
2892 * @param n the neighbour from which we received message m
2893 * @param m the set key message we received
2896 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2898 struct SetKeyMessage *m_cpy;
2899 struct GNUNET_TIME_Absolute t;
2900 struct GNUNET_CRYPTO_AesSessionKey k;
2901 struct PingMessage *ping;
2902 struct PongMessage *pong;
2903 enum PeerStateMachine sender_status;
2906 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2907 "Core service receives `%s' request from `%4s'.\n",
2908 "SET_KEY", GNUNET_i2s (&n->peer));
2910 if (n->public_key == NULL)
2912 if (n->pitr != NULL)
2915 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2916 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2922 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2923 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2925 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2926 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2927 /* lookup n's public key, then try again */
2928 GNUNET_assert (n->skm == NULL);
2930 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2933 GNUNET_TIME_UNIT_MINUTES,
2934 &process_hello_retry_handle_set_key, n);
2935 GNUNET_STATISTICS_update (stats,
2936 gettext_noop ("# SETKEY messages deferred (need public key)"),
2941 if (0 != memcmp (&m->target,
2943 sizeof (struct GNUNET_PeerIdentity)))
2945 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2946 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
2948 GNUNET_i2s (&m->target));
2951 if ((ntohl (m->purpose.size) !=
2952 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2953 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2954 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2955 sizeof (struct GNUNET_PeerIdentity)) ||
2957 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2958 &m->purpose, &m->signature, n->public_key)))
2960 /* invalid signature */
2961 GNUNET_break_op (0);
2964 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2965 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2966 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2967 (t.value < n->decrypt_key_created.value))
2969 /* this could rarely happen due to massive re-ordering of
2970 messages on the network level, but is most likely either
2971 a bug or some adversary messing with us. Report. */
2972 GNUNET_break_op (0);
2976 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2977 "Decrypting key material.\n");
2979 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2982 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2983 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2984 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2986 /* failed to decrypt !? */
2987 GNUNET_break_op (0);
2990 GNUNET_STATISTICS_update (stats,
2991 gettext_noop ("# SETKEY messages decrypted"),
2995 if (n->decrypt_key_created.value != t.value)
2997 /* fresh key, reset sequence numbers */
2998 n->last_sequence_number_received = 0;
2999 n->last_packets_bitmap = 0;
3000 n->decrypt_key_created = t;
3002 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3005 case PEER_STATE_DOWN:
3006 n->status = PEER_STATE_KEY_RECEIVED;
3008 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3009 "Responding to `%s' with my own key.\n", "SET_KEY");
3013 case PEER_STATE_KEY_SENT:
3014 case PEER_STATE_KEY_RECEIVED:
3015 n->status = PEER_STATE_KEY_RECEIVED;
3016 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3017 (sender_status != PEER_STATE_KEY_CONFIRMED))
3020 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3021 "Responding to `%s' with my own key (other peer has status %u).\n",
3023 (unsigned int) sender_status);
3028 case PEER_STATE_KEY_CONFIRMED:
3029 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3030 (sender_status != PEER_STATE_KEY_CONFIRMED))
3033 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3034 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3036 (unsigned int) sender_status);
3045 if (n->pending_ping != NULL)
3047 ping = n->pending_ping;
3048 n->pending_ping = NULL;
3049 handle_ping (n, ping);
3052 if (n->pending_pong != NULL)
3054 pong = n->pending_pong;
3055 n->pending_pong = NULL;
3056 handle_pong (n, pong);
3063 * Send a P2P message to a client.
3065 * @param sender who sent us the message?
3066 * @param client who should we give the message to?
3067 * @param m contains the message to transmit
3068 * @param msize number of bytes in buf to transmit
3071 send_p2p_message_to_client (struct Neighbour *sender,
3072 struct Client *client,
3073 const void *m, size_t msize)
3075 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3076 struct NotifyTrafficMessage *ntm;
3079 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3080 "Core service passes message from `%4s' of type %u to client.\n",
3081 GNUNET_i2s(&sender->peer),
3082 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3084 ntm = (struct NotifyTrafficMessage *) buf;
3085 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3086 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3087 ntm->distance = htonl (sender->last_distance);
3088 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3089 ntm->peer = sender->peer;
3090 memcpy (&ntm[1], m, msize);
3091 send_to_client (client, &ntm->header, GNUNET_YES);
3096 * Deliver P2P message to interested clients.
3098 * @param sender who sent us the message?
3099 * @param m the message
3100 * @param msize size of the message (including header)
3103 deliver_message (struct Neighbour *sender,
3104 const struct GNUNET_MessageHeader *m, size_t msize)
3107 struct Client *cpos;
3113 type = ntohs (m->type);
3115 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3116 "Received encapsulated message of type %u from `%4s'\n",
3117 (unsigned int) type,
3118 GNUNET_i2s (&sender->peer));
3120 GNUNET_snprintf (buf,
3122 gettext_noop ("# bytes of messages of type %u received"),
3123 (unsigned int) type);
3124 GNUNET_STATISTICS_set (stats,
3128 dropped = GNUNET_YES;
3130 while (cpos != NULL)
3132 deliver_full = GNUNET_NO;
3133 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3134 deliver_full = GNUNET_YES;
3137 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3139 if (type != cpos->types[tpos])
3141 deliver_full = GNUNET_YES;
3145 if (GNUNET_YES == deliver_full)
3147 send_p2p_message_to_client (sender, cpos, m, msize);
3148 dropped = GNUNET_NO;
3150 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3152 send_p2p_message_to_client (sender, cpos, m,
3153 sizeof (struct GNUNET_MessageHeader));
3157 if (dropped == GNUNET_YES)
3160 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3161 "Message of type %u from `%4s' not delivered to any client.\n",
3162 (unsigned int) type,
3163 GNUNET_i2s (&sender->peer));
3165 /* FIXME: stats... */
3171 * Align P2P message and then deliver to interested clients.
3173 * @param sender who sent us the message?
3174 * @param buffer unaligned (!) buffer containing message
3175 * @param msize size of the message (including header)
3178 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
3182 /* TODO: call to statistics? */
3183 memcpy (abuf, buffer, msize);
3184 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
3189 * Deliver P2P messages to interested clients.
3191 * @param sender who sent us the message?
3192 * @param buffer buffer containing messages, can be modified
3193 * @param buffer_size size of the buffer (overall)
3194 * @param offset offset where messages in the buffer start
3197 deliver_messages (struct Neighbour *sender,
3198 const char *buffer, size_t buffer_size, size_t offset)
3200 struct GNUNET_MessageHeader *mhp;
3201 struct GNUNET_MessageHeader mh;
3205 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
3207 if (0 != offset % sizeof (uint16_t))
3209 /* outch, need to copy to access header */
3210 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
3215 /* can access header directly */
3216 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
3218 msize = ntohs (mhp->size);
3219 if (msize + offset > buffer_size)
3221 /* malformed message, header says it is larger than what
3222 would fit into the overall buffer */
3223 GNUNET_break_op (0);
3226 #if HAVE_UNALIGNED_64_ACCESS
3227 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
3229 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
3231 if (GNUNET_YES == need_align)
3232 align_and_deliver (sender, &buffer[offset], msize);
3234 deliver_message (sender,
3235 (const struct GNUNET_MessageHeader *)
3236 &buffer[offset], msize);
3243 * We received an encrypted message. Decrypt, validate and
3244 * pass on to the appropriate clients.
3247 handle_encrypted_message (struct Neighbour *n,
3248 const struct EncryptedMessage *m)
3250 size_t size = ntohs (m->header.size);
3252 struct EncryptedMessage *pt; /* plaintext */
3255 struct GNUNET_TIME_Absolute t;
3259 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3260 "Core service receives `%s' request from `%4s'.\n",
3261 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3263 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3269 &buf[ENCRYPTED_HEADER_SIZE],
3270 size - ENCRYPTED_HEADER_SIZE))
3272 pt = (struct EncryptedMessage *) buf;
3274 GNUNET_CRYPTO_hash (&pt->sequence_number,
3275 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3277 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3278 "V-Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
3279 (unsigned int) (size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode)),
3283 if (0 != memcmp (&ph,
3284 &pt->plaintext_hash,
3285 sizeof (GNUNET_HashCode)))
3287 /* checksum failed */
3288 GNUNET_break_op (0);
3292 /* validate sequence number */
3293 snum = ntohl (pt->sequence_number);
3294 if (n->last_sequence_number_received == snum)
3296 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3297 "Received duplicate message, ignoring.\n");
3298 /* duplicate, ignore */
3299 GNUNET_STATISTICS_set (stats,
3300 gettext_noop ("# bytes dropped (duplicates)"),
3305 if ((n->last_sequence_number_received > snum) &&
3306 (n->last_sequence_number_received - snum > 32))
3308 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3309 "Received ancient out of sequence message, ignoring.\n");
3310 /* ancient out of sequence, ignore */
3311 GNUNET_STATISTICS_set (stats,
3312 gettext_noop ("# bytes dropped (out of sequence)"),
3317 if (n->last_sequence_number_received > snum)
3319 unsigned int rotbit =
3320 1 << (n->last_sequence_number_received - snum - 1);
3321 if ((n->last_packets_bitmap & rotbit) != 0)
3323 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3324 "Received duplicate message, ignoring.\n");
3325 GNUNET_STATISTICS_set (stats,
3326 gettext_noop ("# bytes dropped (duplicates)"),
3329 /* duplicate, ignore */
3332 n->last_packets_bitmap |= rotbit;
3334 if (n->last_sequence_number_received < snum)
3336 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3337 n->last_sequence_number_received = snum;
3340 /* check timestamp */
3341 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3342 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3344 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3346 ("Message received far too old (%llu ms). Content ignored.\n"),
3347 GNUNET_TIME_absolute_get_duration (t).value);
3348 GNUNET_STATISTICS_set (stats,
3349 gettext_noop ("# bytes dropped (ancient message)"),
3355 /* process decrypted message(s) */
3356 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3358 #if DEBUG_CORE_SET_QUOTA
3359 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3360 "Received %u b/s as new inbound limit for peer `%4s'\n",
3361 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3362 GNUNET_i2s (&n->peer));
3364 n->bw_out_external_limit = pt->inbound_bw_limit;
3365 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3366 n->bw_out_internal_limit);
3367 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3369 GNUNET_TRANSPORT_set_quota (transport,
3373 GNUNET_TIME_UNIT_FOREVER_REL,
3376 n->last_activity = GNUNET_TIME_absolute_get ();
3377 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3378 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3380 = GNUNET_SCHEDULER_add_delayed (sched,
3381 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3384 GNUNET_STATISTICS_set (stats,
3385 gettext_noop ("# bytes of payload decrypted"),
3386 size - sizeof (struct EncryptedMessage),
3388 deliver_messages (n, buf, size, sizeof (struct EncryptedMessage));
3393 * Function called by the transport for each received message.
3395 * @param cls closure
3396 * @param peer (claimed) identity of the other peer
3397 * @param message the message
3398 * @param latency estimated latency for communicating with the
3399 * given peer (round-trip)
3400 * @param distance in overlay hops, as given by transport plugin
3403 handle_transport_receive (void *cls,
3404 const struct GNUNET_PeerIdentity *peer,
3405 const struct GNUNET_MessageHeader *message,
3406 struct GNUNET_TIME_Relative latency,
3407 unsigned int distance)
3409 struct Neighbour *n;
3410 struct GNUNET_TIME_Absolute now;
3416 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3417 "Received message of type %u from `%4s', demultiplexing.\n",
3418 (unsigned int) ntohs (message->type),
3421 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3426 n = find_neighbour (peer);
3428 n = create_neighbour (peer);
3429 n->last_latency = latency;
3430 n->last_distance = distance;
3431 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3432 type = ntohs (message->type);
3433 size = ntohs (message->size);
3436 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3437 if (size != sizeof (struct SetKeyMessage))
3439 GNUNET_break_op (0);
3442 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3443 handle_set_key (n, (const struct SetKeyMessage *) message);
3445 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3446 if (size < sizeof (struct EncryptedMessage) +
3447 sizeof (struct GNUNET_MessageHeader))
3449 GNUNET_break_op (0);
3452 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3453 (n->status != PEER_STATE_KEY_CONFIRMED))
3455 GNUNET_break_op (0);
3458 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3460 case GNUNET_MESSAGE_TYPE_CORE_PING:
3461 if (size != sizeof (struct PingMessage))
3463 GNUNET_break_op (0);
3466 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3467 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3468 (n->status != PEER_STATE_KEY_CONFIRMED))
3471 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3472 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3473 "PING", GNUNET_i2s (&n->peer));
3475 GNUNET_free_non_null (n->pending_ping);
3476 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3477 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3480 handle_ping (n, (const struct PingMessage *) message);
3482 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3483 if (size != sizeof (struct PongMessage))
3485 GNUNET_break_op (0);
3488 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3489 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3490 (n->status != PEER_STATE_KEY_CONFIRMED) )
3493 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3494 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3495 "PONG", GNUNET_i2s (&n->peer));
3497 GNUNET_free_non_null (n->pending_pong);
3498 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3499 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3502 handle_pong (n, (const struct PongMessage *) message);
3505 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3506 _("Unsupported message of type %u received.\n"),
3507 (unsigned int) type);
3510 if (n->status == PEER_STATE_KEY_CONFIRMED)
3512 now = GNUNET_TIME_absolute_get ();
3513 n->last_activity = now;
3516 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3517 n->time_established = now;
3519 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3520 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3522 = GNUNET_SCHEDULER_add_delayed (sched,
3523 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3531 * Function that recalculates the bandwidth quota for the
3532 * given neighbour and transmits it to the transport service.
3534 * @param cls neighbour for the quota update
3538 neighbour_quota_update (void *cls,
3539 const struct GNUNET_SCHEDULER_TaskContext *tc)
3541 struct Neighbour *n = cls;
3542 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3545 unsigned long long distributable;
3546 uint64_t need_per_peer;
3547 uint64_t need_per_second;
3549 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3550 /* calculate relative preference among all neighbours;
3551 divides by a bit more to avoid division by zero AND to
3552 account for possibility of new neighbours joining any time
3553 AND to convert to double... */
3554 if (preference_sum == 0)
3556 pref_rel = 1.0 / (double) neighbour_count;
3560 pref_rel = n->current_preference / preference_sum;
3562 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3563 GNUNET_TIME_UNIT_SECONDS);
3564 need_per_second = need_per_peer * neighbour_count;
3566 if (bandwidth_target_out_bps > need_per_second)
3567 distributable = bandwidth_target_out_bps - need_per_second;
3568 share = distributable * pref_rel;
3569 if (share + need_per_peer > ( (uint32_t)-1))
3570 q_in = GNUNET_BANDWIDTH_value_init ((uint32_t) -1);
3572 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3573 /* check if we want to disconnect for good due to inactivity */
3574 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3575 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3578 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3579 "Forcing disconnect of `%4s' due to inactivity\n",
3580 GNUNET_i2s (&n->peer));
3582 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3584 #if DEBUG_CORE_QUOTA
3585 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3586 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3587 GNUNET_i2s (&n->peer),
3588 (unsigned int) ntohl (q_in.value__),
3589 bandwidth_target_out_bps,
3590 (unsigned int) ntohl (n->bw_in.value__),
3591 (unsigned int) ntohl (n->bw_out.value__),
3592 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3594 if (n->bw_in.value__ != q_in.value__)
3597 if (GNUNET_YES == n->is_connected)
3598 GNUNET_TRANSPORT_set_quota (transport,
3602 GNUNET_TIME_UNIT_FOREVER_REL,
3605 schedule_quota_update (n);
3610 * Function called by transport to notify us that
3611 * a peer connected to us (on the network level).
3613 * @param cls closure
3614 * @param peer the peer that connected
3615 * @param latency current latency of the connection
3616 * @param distance in overlay hops, as given by transport plugin
3619 handle_transport_notify_connect (void *cls,
3620 const struct GNUNET_PeerIdentity *peer,
3621 struct GNUNET_TIME_Relative latency,
3622 unsigned int distance)
3624 struct Neighbour *n;
3626 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3631 n = find_neighbour (peer);
3634 if (GNUNET_YES == n->is_connected)
3636 /* duplicate connect notification!? */
3643 n = create_neighbour (peer);
3645 GNUNET_STATISTICS_update (stats,
3646 gettext_noop ("# peers connected (transport)"),
3649 n->is_connected = GNUNET_YES;
3650 n->last_latency = latency;
3651 n->last_distance = distance;
3652 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3655 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3659 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3660 "Received connection from `%4s'.\n",
3661 GNUNET_i2s (&n->peer));
3663 GNUNET_TRANSPORT_set_quota (transport,
3667 GNUNET_TIME_UNIT_FOREVER_REL,
3674 * Function called by transport telling us that a peer
3677 * @param cls closure
3678 * @param peer the peer that disconnected
3681 handle_transport_notify_disconnect (void *cls,
3682 const struct GNUNET_PeerIdentity *peer)
3684 struct DisconnectNotifyMessage cnm;
3685 struct Neighbour *n;
3688 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3689 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3691 n = find_neighbour (peer);
3697 GNUNET_break (n->is_connected);
3698 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3699 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3701 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3702 n->is_connected = GNUNET_NO;
3703 GNUNET_STATISTICS_update (stats,
3704 gettext_noop ("# peers connected (transport)"),
3711 * Last task run during shutdown. Disconnects us from
3715 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3717 struct Neighbour *n;
3721 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3722 "Core service shutting down.\n");
3724 GNUNET_assert (transport != NULL);
3725 GNUNET_TRANSPORT_disconnect (transport);
3727 while (NULL != (n = neighbours))
3729 neighbours = n->next;
3730 GNUNET_assert (neighbour_count > 0);
3734 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
3735 GNUNET_SERVER_notification_context_destroy (notifier);
3737 while (NULL != (c = clients))
3738 handle_client_disconnect (NULL, c->client_handle);
3739 if (my_private_key != NULL)
3740 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3742 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3743 if (peerinfo != NULL)
3744 GNUNET_PEERINFO_disconnect (peerinfo);
3749 * Initiate core service.
3751 * @param cls closure
3752 * @param s scheduler to use
3753 * @param serv the initialized server
3754 * @param c configuration to use
3758 struct GNUNET_SCHEDULER_Handle *s,
3759 struct GNUNET_SERVER_Handle *serv,
3760 const struct GNUNET_CONFIGURATION_Handle *c)
3766 /* parse configuration */
3769 GNUNET_CONFIGURATION_get_value_number (c,
3772 &bandwidth_target_in_bps)) ||
3774 GNUNET_CONFIGURATION_get_value_number (c,
3777 &bandwidth_target_out_bps)) ||
3779 GNUNET_CONFIGURATION_get_value_filename (c,
3781 "HOSTKEY", &keyfile)))
3783 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3785 ("Core service is lacking key configuration settings. Exiting.\n"));
3786 GNUNET_SCHEDULER_shutdown (s);
3789 peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
3790 if (NULL == peerinfo)
3792 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3793 _("Could not access PEERINFO service. Exiting.\n"));
3794 GNUNET_SCHEDULER_shutdown (s);
3795 GNUNET_free (keyfile);
3798 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3799 GNUNET_free (keyfile);
3800 if (my_private_key == NULL)
3802 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3803 _("Core service could not access hostkey. Exiting.\n"));
3804 GNUNET_PEERINFO_disconnect (peerinfo);
3805 GNUNET_SCHEDULER_shutdown (s);
3808 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3809 GNUNET_CRYPTO_hash (&my_public_key,
3810 sizeof (my_public_key), &my_identity.hashPubKey);
3811 /* setup notification */
3813 notifier = GNUNET_SERVER_notification_context_create (server,
3815 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3816 /* setup transport connection */
3817 transport = GNUNET_TRANSPORT_connect (sched,
3820 &handle_transport_receive,
3821 &handle_transport_notify_connect,
3822 &handle_transport_notify_disconnect);
3823 GNUNET_assert (NULL != transport);
3824 stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3825 GNUNET_SCHEDULER_add_delayed (sched,
3826 GNUNET_TIME_UNIT_FOREVER_REL,
3827 &cleaning_task, NULL);
3828 /* process client requests */
3829 GNUNET_SERVER_add_handlers (server, handlers);
3830 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3831 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3837 * The main function for the transport service.
3839 * @param argc number of arguments from the command line
3840 * @param argv command line arguments
3841 * @return 0 ok, 1 on error
3844 main (int argc, char *const *argv)
3846 return (GNUNET_OK ==
3847 GNUNET_SERVICE_run (argc,
3850 GNUNET_SERVICE_OPTION_NONE,
3851 &run, NULL)) ? 0 : 1;
3854 /* end of gnunet-service-core.c */