2 This file is part of GNUnet.
3 (C) 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file core/gnunet-service-core.c
23 * @brief high-level P2P messaging
24 * @author Christian Grothoff
26 * Considerations for later:
27 * - check that hostkey used by transport (for HELLOs) is the
28 * same as the hostkey that we are using!
29 * - add code to send PINGs if we are about to time-out otherwise
30 * - optimize lookup (many O(n) list traversals
31 * could ideally be changed to O(1) hash map lookups)
34 #include "gnunet_constants.h"
35 #include "gnunet_util_lib.h"
36 #include "gnunet_hello_lib.h"
37 #include "gnunet_peerinfo_service.h"
38 #include "gnunet_protocols.h"
39 #include "gnunet_signatures.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet_transport_service.h"
45 #define DEBUG_HANDSHAKE GNUNET_NO
47 #define DEBUG_CORE_QUOTA GNUNET_NO
50 * Receive and send buffer windows grow over time. For
51 * how long can 'unused' bandwidth accumulate before we
52 * need to cap it? (specified in seconds).
54 #define MAX_WINDOW_TIME_S (5 * 60)
57 * How many messages do we queue up at most for optional
58 * notifications to a client? (this can cause notifications
59 * about outgoing messages to be dropped).
61 #define MAX_NOTIFY_QUEUE 1024
64 * Minimum bandwidth (out) to assign to any connected peer.
65 * Should be rather low; values larger than DEFAULT_BW_IN_OUT make no
68 #define MIN_BANDWIDTH_PER_PEER GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT
71 * After how much time past the "official" expiration time do
72 * we discard messages? Should not be zero since we may
73 * intentionally defer transmission until close to the deadline
74 * and then may be slightly past the deadline due to inaccuracy
75 * in sleep and our own CPU consumption.
77 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
80 * What is the maximum delay for a SET_KEY message?
82 #define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
85 * How long do we wait for SET_KEY confirmation initially?
87 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 1)
90 * What is the maximum delay for a PING message?
92 #define MAX_PING_DELAY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 2)
95 * What is the maximum delay for a PONG message?
97 #define MAX_PONG_DELAY GNUNET_TIME_relative_multiply (MAX_PING_DELAY, 2)
100 * What is the minimum frequency for a PING message?
102 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
105 * How often do we recalculate bandwidth quotas?
107 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
110 * What is the priority for a SET_KEY message?
112 #define SET_KEY_PRIORITY 0xFFFFFF
115 * What is the priority for a PING message?
117 #define PING_PRIORITY 0xFFFFFF
120 * What is the priority for a PONG message?
122 #define PONG_PRIORITY 0xFFFFFF
125 * How many messages do we queue per peer at most? Must be at
128 #define MAX_PEER_QUEUE_SIZE 16
131 * How many non-mandatory messages do we queue per client at most?
133 #define MAX_CLIENT_QUEUE_SIZE 32
136 * What is the maximum age of a message for us to consider
137 * processing it? Note that this looks at the timestamp used
138 * by the other peer, so clock skew between machines does
139 * come into play here. So this should be picked high enough
140 * so that a little bit of clock skew does not prevent peers
141 * from connecting to us.
143 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
147 * State machine for our P2P encryption handshake. Everyone starts in
148 * "DOWN", if we receive the other peer's key (other peer initiated)
149 * we start in state RECEIVED (since we will immediately send our
150 * own); otherwise we start in SENT. If we get back a PONG from
151 * within either state, we move up to CONFIRMED (the PONG will always
152 * be sent back encrypted with the key we sent to the other peer).
154 enum PeerStateMachine
158 PEER_STATE_KEY_RECEIVED,
159 PEER_STATE_KEY_CONFIRMED
164 * Number of bytes (at the beginning) of "struct EncryptedMessage"
165 * that are NOT encrypted.
167 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t))
171 * Encapsulation for encrypted messages exchanged between
172 * peers. Followed by the actual encrypted data.
174 struct EncryptedMessage
177 * Message type is either CORE_ENCRYPTED_MESSAGE.
179 struct GNUNET_MessageHeader header;
182 * Random value used for IV generation. ENCRYPTED_HEADER_SIZE must
183 * be set to the offset of the *next* field.
185 uint32_t iv_seed GNUNET_PACKED;
188 * Hash of the plaintext (starting at 'sequence_number'), used to
189 * verify message integrity. Everything after this hash (including
190 * this hash itself) will be encrypted.
192 GNUNET_HashCode hmac;
195 * Sequence number, in network byte order. This field
196 * must be the first encrypted/decrypted field and the
197 * first byte that is hashed for the plaintext hash.
199 uint32_t sequence_number GNUNET_PACKED;
202 * Desired bandwidth (how much we should send to this peer / how
203 * much is the sender willing to receive)?
205 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
208 * Timestamp. Used to prevent reply of ancient messages
209 * (recent messages are caught with the sequence number).
211 struct GNUNET_TIME_AbsoluteNBO timestamp;
217 * We're sending an (encrypted) PING to the other peer to check if he
218 * can decrypt. The other peer should respond with a PONG with the
219 * same content, except this time encrypted with the receiver's key.
224 * Message type is CORE_PING.
226 struct GNUNET_MessageHeader header;
229 * Random number chosen to make reply harder.
231 uint32_t challenge GNUNET_PACKED;
234 * Intended target of the PING, used primarily to check
235 * that decryption actually worked.
237 struct GNUNET_PeerIdentity target;
243 * Response to a PING. Includes data from the original PING
244 * plus initial bandwidth quota information.
249 * Message type is CORE_PONG.
251 struct GNUNET_MessageHeader header;
254 * Random number proochosen to make reply harder. Must be
255 * first field after header (this is where we start to encrypt!).
257 uint32_t challenge GNUNET_PACKED;
262 uint32_t reserved GNUNET_PACKED;
265 * Desired bandwidth (how much we should send to this
266 * peer / how much is the sender willing to receive).
268 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
271 * Intended target of the PING, used primarily to check
272 * that decryption actually worked.
274 struct GNUNET_PeerIdentity target;
279 * Message transmitted to set (or update) a session key.
285 * Message type is either CORE_SET_KEY.
287 struct GNUNET_MessageHeader header;
290 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
292 int32_t sender_status GNUNET_PACKED;
295 * Purpose of the signature, will be
296 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
298 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
301 * At what time was this key created?
303 struct GNUNET_TIME_AbsoluteNBO creation_time;
306 * The encrypted session key.
308 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
311 * Who is the intended recipient?
313 struct GNUNET_PeerIdentity target;
316 * Signature of the stuff above (starting at purpose).
318 struct GNUNET_CRYPTO_RsaSignature signature;
324 * Message waiting for transmission. This struct
325 * is followed by the actual content of the message.
331 * We keep messages in a doubly linked list.
333 struct MessageEntry *next;
336 * We keep messages in a doubly linked list.
338 struct MessageEntry *prev;
341 * By when are we supposed to transmit this message?
343 struct GNUNET_TIME_Absolute deadline;
346 * By when are we supposed to transmit this message (after
349 struct GNUNET_TIME_Absolute slack_deadline;
352 * How important is this message to us?
354 unsigned int priority;
357 * If this is a SET_KEY message, what was our connection status when this
358 * message was queued?
360 enum PeerStateMachine sender_status;
363 * Is this a SET_KEY message?
368 * How long is the message? (number of bytes following
369 * the "struct MessageEntry", but not including the
370 * size of "struct MessageEntry" itself!)
375 * Was this message selected for transmission in the
376 * current round? GNUNET_YES or GNUNET_NO.
381 * Did we give this message some slack (delayed sending) previously
382 * (and hence should not give it any more slack)? GNUNET_YES or
393 * We keep neighbours in a linked list (for now).
395 struct Neighbour *next;
398 * Unencrypted messages destined for this peer.
400 struct MessageEntry *messages;
403 * Head of the batched, encrypted message queue (already ordered,
404 * transmit starting with the head).
406 struct MessageEntry *encrypted_head;
409 * Tail of the batched, encrypted message queue (already ordered,
410 * append new messages to tail)
412 struct MessageEntry *encrypted_tail;
415 * Handle for pending requests for transmission to this peer
416 * with the transport service. NULL if no request is pending.
418 struct GNUNET_TRANSPORT_TransmitHandle *th;
421 * Public key of the neighbour, NULL if we don't have it yet.
423 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
426 * We received a PING message before we got the "public_key"
427 * (or the SET_KEY). We keep it here until we have a key
428 * to decrypt it. NULL if no PING is pending.
430 struct PingMessage *pending_ping;
433 * We received a PONG message before we got the "public_key"
434 * (or the SET_KEY). We keep it here until we have a key
435 * to decrypt it. NULL if no PONG is pending.
437 struct PongMessage *pending_pong;
440 * Non-NULL if we are currently looking up HELLOs for this peer.
443 struct GNUNET_PEERINFO_IteratorContext *pitr;
446 * SetKeyMessage to transmit, NULL if we are not currently trying
449 struct SetKeyMessage *skm;
452 * Identity of the neighbour.
454 struct GNUNET_PeerIdentity peer;
457 * Key we use to encrypt our messages for the other peer
458 * (initialized by us when we do the handshake).
460 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
463 * Key we use to decrypt messages from the other peer
464 * (given to us by the other peer during the handshake).
466 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
469 * ID of task used for re-trying plaintext scheduling.
471 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
474 * ID of task used for re-trying SET_KEY and PING message.
476 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
479 * ID of task used for updating bandwidth quota for this neighbour.
481 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
484 * ID of task used for sending keep-alive pings.
486 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
489 * ID of task used for cleaning up dead neighbour entries.
491 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
494 * At what time did we generate our encryption key?
496 struct GNUNET_TIME_Absolute encrypt_key_created;
499 * At what time did the other peer generate the decryption key?
501 struct GNUNET_TIME_Absolute decrypt_key_created;
504 * At what time did we initially establish (as in, complete session
505 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
507 struct GNUNET_TIME_Absolute time_established;
510 * At what time did we last receive an encrypted message from the
511 * other peer? Should be zero if status != KEY_CONFIRMED.
513 struct GNUNET_TIME_Absolute last_activity;
516 * Last latency observed from this peer.
518 struct GNUNET_TIME_Relative last_latency;
521 * At what frequency are we currently re-trying SET_KEY messages?
523 struct GNUNET_TIME_Relative set_key_retry_frequency;
526 * Tracking bandwidth for sending to this peer.
528 struct GNUNET_BANDWIDTH_Tracker available_send_window;
531 * Tracking bandwidth for receiving from this peer.
533 struct GNUNET_BANDWIDTH_Tracker available_recv_window;
536 * How valueable were the messages of this peer recently?
538 unsigned long long current_preference;
541 * Bit map indicating which of the 32 sequence numbers before the last
542 * were received (good for accepting out-of-order packets and
543 * estimating reliability of the connection)
545 unsigned int last_packets_bitmap;
548 * last sequence number received on this connection (highest)
550 uint32_t last_sequence_number_received;
553 * last sequence number transmitted
555 uint32_t last_sequence_number_sent;
558 * Available bandwidth in for this peer (current target).
560 struct GNUNET_BANDWIDTH_Value32NBO bw_in;
563 * Available bandwidth out for this peer (current target).
565 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
568 * Internal bandwidth limit set for this peer (initially typically
569 * set to "-1"). Actual "bw_out" is MIN of
570 * "bpm_out_internal_limit" and "bw_out_external_limit".
572 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
575 * External bandwidth limit set for this peer by the
576 * peer that we are communicating with. "bw_out" is MIN of
577 * "bw_out_internal_limit" and "bw_out_external_limit".
579 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
582 * What was our PING challenge number (for this peer)?
584 uint32_t ping_challenge;
587 * What was the last distance to this peer as reported by the transports?
589 uint32_t last_distance;
592 * What is our connection status?
594 enum PeerStateMachine status;
597 * Are we currently connected to this neighbour?
605 * Data structure for each client connected to the core service.
610 * Clients are kept in a linked list.
615 * Handle for the client with the server API.
617 struct GNUNET_SERVER_Client *client_handle;
620 * Array of the types of messages this peer cares
621 * about (with "tcnt" entries). Allocated as part
622 * of this client struct, do not free!
624 const uint16_t *types;
627 * Options for messages this client cares about,
628 * see GNUNET_CORE_OPTION_ values.
633 * Number of types of incoming messages this client
634 * specifically cares about. Size of the "types" array.
644 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
649 static struct GNUNET_PeerIdentity my_identity;
654 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
659 struct GNUNET_SCHEDULER_Handle *sched;
662 * Handle to peerinfo service.
664 static struct GNUNET_PEERINFO_Handle *peerinfo;
667 * Our message stream tokenizer (for encrypted payload).
669 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
674 const struct GNUNET_CONFIGURATION_Handle *cfg;
679 static struct GNUNET_TRANSPORT_Handle *transport;
682 * Linked list of our clients.
684 static struct Client *clients;
687 * Context for notifications we need to send to our clients.
689 static struct GNUNET_SERVER_NotificationContext *notifier;
692 * We keep neighbours in a linked list (for now).
694 static struct Neighbour *neighbours;
697 * For creating statistics.
699 static struct GNUNET_STATISTICS_Handle *stats;
702 * Sum of all preferences among all neighbours.
704 static unsigned long long preference_sum;
707 * Total number of neighbours we have.
709 static unsigned int neighbour_count;
712 * How much inbound bandwidth are we supposed to be using per second?
713 * FIXME: this value is not used!
715 static unsigned long long bandwidth_target_in_bps;
718 * How much outbound bandwidth are we supposed to be using per second?
720 static unsigned long long bandwidth_target_out_bps;
725 * A preference value for a neighbour was update. Update
726 * the preference sum accordingly.
728 * @param inc how much was a preference value increased?
731 update_preference_sum (unsigned long long inc)
734 unsigned long long os;
737 preference_sum += inc;
738 if (preference_sum >= os)
740 /* overflow! compensate by cutting all values in half! */
745 n->current_preference /= 2;
746 preference_sum += n->current_preference;
749 GNUNET_STATISTICS_set (stats, gettext_noop ("# total peer preference"), preference_sum, GNUNET_NO);
754 * Find the entry for the given neighbour.
756 * @param peer identity of the neighbour
757 * @return NULL if we are not connected, otherwise the
760 static struct Neighbour *
761 find_neighbour (const struct GNUNET_PeerIdentity *peer)
763 struct Neighbour *ret;
766 while ((ret != NULL) &&
767 (0 != memcmp (&ret->peer,
768 peer, sizeof (struct GNUNET_PeerIdentity))))
775 * Send a message to one of our clients.
777 * @param client target for the message
778 * @param msg message to transmit
779 * @param can_drop could this message be dropped if the
780 * client's queue is getting too large?
783 send_to_client (struct Client *client,
784 const struct GNUNET_MessageHeader *msg,
787 #if DEBUG_CORE_CLIENT
788 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
789 "Preparing to send %u bytes of message of type %u to client.\n",
790 (unsigned int) ntohs (msg->size),
791 (unsigned int) ntohs (msg->type));
793 GNUNET_SERVER_notification_context_unicast (notifier,
794 client->client_handle,
801 * Send a message to all of our current clients that have
802 * the right options set.
804 * @param msg message to multicast
805 * @param can_drop can this message be discarded if the queue is too long
806 * @param options mask to use
809 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
818 if (0 != (c->options & options))
820 #if DEBUG_CORE_CLIENT
821 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
822 "Sending message of type %u to client.\n",
823 (unsigned int) ntohs (msg->type));
825 send_to_client (c, msg, can_drop);
833 * Function called by transport telling us that a peer
836 * @param n the peer that changed status
839 handle_peer_status_change (struct Neighbour *n)
841 struct PeerStatusNotifyMessage psnm;
843 if (! n->is_connected)
846 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
847 "Peer `%4s' changed status\n",
848 GNUNET_i2s (&n->peer));
850 psnm.header.size = htons (sizeof (struct PeerStatusNotifyMessage));
851 psnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_STATUS_CHANGE);
852 psnm.distance = htonl (n->last_distance);
853 psnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
854 psnm.timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_add (n->last_activity,
855 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
856 psnm.bandwidth_in = n->bw_in;
857 psnm.bandwidth_out = n->bw_out;
859 send_to_all_clients (&psnm.header,
861 GNUNET_CORE_OPTION_SEND_STATUS_CHANGE);
862 GNUNET_STATISTICS_update (stats,
863 gettext_noop ("# peer status changes"),
869 * Handle CORE_ITERATE_PEERS request.
872 handle_client_iterate_peers (void *cls,
873 struct GNUNET_SERVER_Client *client,
874 const struct GNUNET_MessageHeader *message)
877 struct ConnectNotifyMessage cnm;
878 struct GNUNET_MessageHeader done_msg;
879 struct GNUNET_SERVER_TransmitContext *tc;
881 /* notify new client about existing neighbours */
882 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
883 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
884 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
885 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
886 tc = GNUNET_SERVER_transmit_context_create (client);
890 if (n->status == PEER_STATE_KEY_CONFIRMED)
892 #if DEBUG_CORE_CLIENT
893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
894 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
896 cnm.distance = htonl (n->last_distance);
897 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
899 GNUNET_SERVER_transmit_context_append_message (tc, &cnm.header);
900 /*send_to_client (c, &cnm.header, GNUNET_NO);*/
905 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
906 GNUNET_SERVER_transmit_context_run (tc,
907 GNUNET_TIME_UNIT_FOREVER_REL);
912 * Handle CORE_INIT request.
915 handle_client_init (void *cls,
916 struct GNUNET_SERVER_Client *client,
917 const struct GNUNET_MessageHeader *message)
919 const struct InitMessage *im;
920 struct InitReplyMessage irm;
923 const uint16_t *types;
926 struct ConnectNotifyMessage cnm;
929 #if DEBUG_CORE_CLIENT
930 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
931 "Client connecting to core service with `%s' message\n",
934 /* check that we don't have an entry already */
938 if (client == c->client_handle)
941 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
946 msize = ntohs (message->size);
947 if (msize < sizeof (struct InitMessage))
950 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
953 GNUNET_SERVER_notification_context_add (notifier, client);
954 im = (const struct InitMessage *) message;
955 types = (const uint16_t *) &im[1];
956 msize -= sizeof (struct InitMessage);
957 c = GNUNET_malloc (sizeof (struct Client) + msize);
958 c->client_handle = client;
961 c->tcnt = msize / sizeof (uint16_t);
962 c->types = (const uint16_t *) &c[1];
963 wtypes = (uint16_t *) &c[1];
964 for (i=0;i<c->tcnt;i++)
965 wtypes[i] = ntohs (types[i]);
966 c->options = ntohl (im->options);
967 #if DEBUG_CORE_CLIENT
968 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
969 "Client %p is interested in %u message types\n",
971 (unsigned int) c->tcnt);
973 /* send init reply message */
974 irm.header.size = htons (sizeof (struct InitReplyMessage));
975 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
976 irm.reserved = htonl (0);
977 memcpy (&irm.publicKey,
979 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
980 #if DEBUG_CORE_CLIENT
981 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
982 "Sending `%s' message to client.\n", "INIT_REPLY");
984 send_to_client (c, &irm.header, GNUNET_NO);
985 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
987 /* notify new client about existing neighbours */
988 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
989 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
993 if (n->status == PEER_STATE_KEY_CONFIRMED)
995 #if DEBUG_CORE_CLIENT
996 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
997 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
999 cnm.distance = htonl (n->last_distance);
1000 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
1002 send_to_client (c, &cnm.header, GNUNET_NO);
1007 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1012 * A client disconnected, clean up.
1014 * @param cls closure
1015 * @param client identification of the client
1018 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1021 struct Client *prev;
1025 #if DEBUG_CORE_CLIENT
1026 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1027 "Client %p has disconnected from core service.\n",
1034 if (client == pos->client_handle)
1037 clients = pos->next;
1039 prev->next = pos->next;
1046 /* client never sent INIT */
1051 * Handle REQUEST_INFO request.
1054 handle_client_request_info (void *cls,
1055 struct GNUNET_SERVER_Client *client,
1056 const struct GNUNET_MessageHeader *message)
1058 const struct RequestInfoMessage *rcm;
1059 struct Neighbour *n;
1060 struct ConfigurationInfoMessage cim;
1061 int32_t want_reserv;
1063 unsigned long long old_preference;
1064 struct GNUNET_SERVER_TransmitContext *tc;
1066 #if DEBUG_CORE_CLIENT
1067 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1068 "Core service receives `%s' request.\n", "REQUEST_INFO");
1070 rcm = (const struct RequestInfoMessage *) message;
1071 n = find_neighbour (&rcm->peer);
1072 memset (&cim, 0, sizeof (cim));
1075 want_reserv = ntohl (rcm->reserve_inbound);
1076 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1078 n->bw_out_internal_limit = rcm->limit_outbound;
1079 if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1080 n->bw_out_external_limit).value__)
1082 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1083 n->bw_out_external_limit);
1084 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1086 GNUNET_TRANSPORT_set_quota (transport,
1090 GNUNET_TIME_UNIT_FOREVER_REL,
1092 handle_peer_status_change (n);
1095 if (want_reserv < 0)
1097 got_reserv = want_reserv;
1099 else if (want_reserv > 0)
1101 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1102 want_reserv).value == 0)
1103 got_reserv = want_reserv;
1105 got_reserv = 0; /* all or nothing */
1109 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1111 old_preference = n->current_preference;
1112 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1113 if (old_preference > n->current_preference)
1115 /* overflow; cap at maximum value */
1116 n->current_preference = ULLONG_MAX;
1118 update_preference_sum (n->current_preference - old_preference);
1119 #if DEBUG_CORE_QUOTA
1120 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1121 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1123 GNUNET_i2s (&rcm->peer),
1126 cim.reserved_amount = htonl (got_reserv);
1127 cim.bw_in = n->bw_in;
1128 cim.bw_out = n->bw_out;
1129 cim.preference = n->current_preference;
1131 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1132 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1133 cim.peer = rcm->peer;
1135 #if DEBUG_CORE_CLIENT
1136 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1137 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1139 tc = GNUNET_SERVER_transmit_context_create (client);
1140 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1141 GNUNET_SERVER_transmit_context_run (tc,
1142 GNUNET_TIME_UNIT_FOREVER_REL);
1147 * Free the given entry for the neighbour (it has
1148 * already been removed from the list at this point).
1150 * @param n neighbour to free
1153 free_neighbour (struct Neighbour *n)
1155 struct MessageEntry *m;
1158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1159 "Destroying neighbour entry for peer `%4s'\n",
1160 GNUNET_i2s (&n->peer));
1162 if (n->pitr != NULL)
1164 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1169 GNUNET_free (n->skm);
1172 while (NULL != (m = n->messages))
1174 n->messages = m->next;
1177 while (NULL != (m = n->encrypted_head))
1179 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1186 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1189 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1190 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1191 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1192 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1193 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1194 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1195 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1196 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1197 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1198 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1199 if (n->status == PEER_STATE_KEY_CONFIRMED)
1200 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1201 GNUNET_free_non_null (n->public_key);
1202 GNUNET_free_non_null (n->pending_ping);
1203 GNUNET_free_non_null (n->pending_pong);
1209 * Check if we have encrypted messages for the specified neighbour
1210 * pending, and if so, check with the transport about sending them
1213 * @param n neighbour to check.
1215 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1219 * Encrypt size bytes from in and write the result to out. Use the
1220 * key for outbound traffic of the given neighbour.
1222 * @param n neighbour we are sending to
1223 * @param iv initialization vector to use
1224 * @param in ciphertext
1225 * @param out plaintext
1226 * @param size size of in/out
1227 * @return GNUNET_OK on success
1230 do_encrypt (struct Neighbour *n,
1231 const GNUNET_HashCode * iv,
1232 const void *in, void *out, size_t size)
1234 if (size != (uint16_t) size)
1239 GNUNET_assert (size ==
1240 GNUNET_CRYPTO_aes_encrypt (in,
1244 GNUNET_CRYPTO_AesInitializationVector
1246 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1248 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1249 "Encrypted %u bytes for `%4s' using key %u\n",
1250 (unsigned int) size,
1251 GNUNET_i2s (&n->peer),
1252 (unsigned int) n->encrypt_key.crc32);
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);
1269 * Task triggered when a neighbour entry is about to time out
1270 * (and we should prevent this by sending a PING).
1272 * @param cls the 'struct Neighbour'
1273 * @param tc scheduler context (not used)
1276 send_keep_alive (void *cls,
1277 const struct GNUNET_SCHEDULER_TaskContext *tc)
1279 struct Neighbour *n = cls;
1280 struct GNUNET_TIME_Relative retry;
1281 struct GNUNET_TIME_Relative left;
1282 struct MessageEntry *me;
1283 struct PingMessage pp;
1284 struct PingMessage *pm;
1286 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1288 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1289 sizeof (struct PingMessage));
1290 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1291 me->priority = PING_PRIORITY;
1292 me->size = sizeof (struct PingMessage);
1293 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1297 pm = (struct PingMessage *) &me[1];
1298 pm->header.size = htons (sizeof (struct PingMessage));
1299 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1300 pp.challenge = htonl (n->ping_challenge);
1301 pp.target = n->peer;
1303 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1304 "Encrypting `%s' message with challenge %u for `%4s' using key %u.\n",
1306 (unsigned int) n->ping_challenge,
1307 GNUNET_i2s (&n->peer),
1308 (unsigned int) n->encrypt_key.crc32);
1311 &n->peer.hashPubKey,
1314 sizeof (struct PingMessage) -
1315 sizeof (struct GNUNET_MessageHeader));
1316 process_encrypted_neighbour_queue (n);
1317 /* reschedule PING job */
1318 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1319 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1320 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1321 MIN_PING_FREQUENCY);
1323 = GNUNET_SCHEDULER_add_delayed (sched,
1332 * Task triggered when a neighbour entry might have gotten stale.
1334 * @param cls the 'struct Neighbour'
1335 * @param tc scheduler context (not used)
1338 consider_free_task (void *cls,
1339 const struct GNUNET_SCHEDULER_TaskContext *tc)
1341 struct Neighbour *n = cls;
1343 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1344 consider_free_neighbour (n);
1349 * Consider freeing the given neighbour since we may not need
1350 * to keep it around anymore.
1352 * @param n neighbour to consider discarding
1355 consider_free_neighbour (struct Neighbour *n)
1357 struct Neighbour *pos;
1358 struct Neighbour *prev;
1359 struct GNUNET_TIME_Relative left;
1361 if ( (n->th != NULL) ||
1362 (n->pitr != NULL) ||
1363 (GNUNET_YES == n->is_connected) )
1364 return; /* no chance */
1366 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1367 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1370 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1371 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1372 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1374 &consider_free_task,
1378 /* actually free the neighbour... */
1387 neighbours = n->next;
1389 prev->next = n->next;
1390 GNUNET_assert (neighbour_count > 0);
1392 GNUNET_STATISTICS_set (stats,
1393 gettext_noop ("# neighbour entries allocated"),
1401 * Function called when the transport service is ready to
1402 * receive an encrypted message for the respective peer
1404 * @param cls neighbour to use message from
1405 * @param size number of bytes we can transmit
1406 * @param buf where to copy the message
1407 * @return number of bytes transmitted
1410 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1412 struct Neighbour *n = cls;
1413 struct MessageEntry *m;
1418 m = n->encrypted_head;
1422 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1423 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1424 GNUNET_i2s (&n->peer));
1428 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1435 GNUNET_assert (size >= m->size);
1436 memcpy (cbuf, &m[1], m->size);
1438 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1441 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1442 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1443 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1445 GNUNET_i2s (&n->peer));
1447 process_encrypted_neighbour_queue (n);
1452 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1453 "Transmission of message of type %u and size %u failed\n",
1454 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1455 (unsigned int) m->size);
1459 consider_free_neighbour (n);
1465 * Check if we have plaintext messages for the specified neighbour
1466 * pending, and if so, consider batching and encrypting them (and
1467 * then trigger processing of the encrypted queue if needed).
1469 * @param n neighbour to check.
1471 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1475 * Check if we have encrypted messages for the specified neighbour
1476 * pending, and if so, check with the transport about sending them
1479 * @param n neighbour to check.
1482 process_encrypted_neighbour_queue (struct Neighbour *n)
1484 struct MessageEntry *m;
1487 return; /* request already pending */
1488 m = n->encrypted_head;
1491 /* encrypted queue empty, try plaintext instead */
1492 process_plaintext_neighbour_queue (n);
1496 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1497 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1498 (unsigned int) m->size,
1499 GNUNET_i2s (&n->peer),
1500 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).
1504 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1507 GNUNET_TIME_absolute_get_remaining
1509 ¬ify_encrypted_transmit_ready,
1513 /* message request too large or duplicate request */
1515 /* discard encrypted message */
1516 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1520 process_encrypted_neighbour_queue (n);
1526 * Decrypt size bytes from in and write the result to out. Use the
1527 * key for inbound traffic of the given neighbour. This function does
1528 * NOT do any integrity-checks on the result.
1530 * @param n neighbour we are receiving from
1531 * @param iv initialization vector to use
1532 * @param in ciphertext
1533 * @param out plaintext
1534 * @param size size of in/out
1535 * @return GNUNET_OK on success
1538 do_decrypt (struct Neighbour *n,
1539 const GNUNET_HashCode * iv,
1540 const void *in, void *out, size_t size)
1542 if (size != (uint16_t) size)
1547 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1548 (n->status != PEER_STATE_KEY_CONFIRMED))
1550 GNUNET_break_op (0);
1551 return GNUNET_SYSERR;
1554 GNUNET_CRYPTO_aes_decrypt (in,
1558 GNUNET_CRYPTO_AesInitializationVector *) iv,
1562 return GNUNET_SYSERR;
1564 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1566 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1567 "Decrypted %u bytes from `%4s' using key %u\n",
1568 (unsigned int) size,
1569 GNUNET_i2s (&n->peer),
1570 (unsigned int) n->decrypt_key.crc32);
1577 * Select messages for transmission. This heuristic uses a combination
1578 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1579 * and priority-based discard (in case no feasible schedule exist) and
1580 * speculative optimization (defer any kind of transmission until
1581 * we either create a batch of significant size, 25% of max, or until
1582 * we are close to a deadline). Furthermore, when scheduling the
1583 * heuristic also packs as many messages into the batch as possible,
1584 * starting with those with the earliest deadline. Yes, this is fun.
1586 * @param n neighbour to select messages from
1587 * @param size number of bytes to select for transmission
1588 * @param retry_time set to the time when we should try again
1589 * (only valid if this function returns zero)
1590 * @return number of bytes selected, or 0 if we decided to
1591 * defer scheduling overall; in that case, retry_time is set.
1594 select_messages (struct Neighbour *n,
1595 size_t size, struct GNUNET_TIME_Relative *retry_time)
1597 struct MessageEntry *pos;
1598 struct MessageEntry *min;
1599 struct MessageEntry *last;
1600 unsigned int min_prio;
1601 struct GNUNET_TIME_Absolute t;
1602 struct GNUNET_TIME_Absolute now;
1603 struct GNUNET_TIME_Relative delta;
1605 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1608 unsigned int queue_size;
1609 int discard_low_prio;
1611 GNUNET_assert (NULL != n->messages);
1612 now = GNUNET_TIME_absolute_get ();
1613 /* last entry in linked list of messages processed */
1615 /* should we remove the entry with the lowest
1616 priority from consideration for scheduling at the
1627 discard_low_prio = GNUNET_YES;
1628 while (GNUNET_YES == discard_low_prio)
1631 min_prio = UINT_MAX;
1632 discard_low_prio = GNUNET_NO;
1633 /* calculate number of bytes available for transmission at time "t" */
1634 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1636 /* how many bytes have we (hypothetically) scheduled so far */
1638 /* maximum time we can wait before transmitting anything
1639 and still make all of our deadlines */
1640 slack = GNUNET_TIME_UNIT_FOREVER_REL;
1642 /* note that we use "*2" here because we want to look
1643 a bit further into the future; much more makes no
1644 sense since new message might be scheduled in the
1646 while ((pos != NULL) && (off < size * 2))
1648 if (pos->do_transmit == GNUNET_YES)
1650 /* already removed from consideration */
1654 if (discard_low_prio == GNUNET_NO)
1656 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1657 if (delta.value > 0)
1659 // FIXME: HUH? Check!
1661 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1664 if (avail < pos->size)
1666 // FIXME: HUH? Check!
1667 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1672 /* update slack, considering both its absolute deadline
1673 and relative deadlines caused by other messages
1674 with their respective load */
1675 slack = GNUNET_TIME_relative_min (slack,
1676 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1678 if (pos->deadline.value <= now.value)
1681 slack = GNUNET_TIME_UNIT_ZERO;
1683 else if (GNUNET_YES == pos->got_slack)
1685 /* should be soon now! */
1686 slack = GNUNET_TIME_relative_min (slack,
1687 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1692 GNUNET_TIME_relative_min (slack,
1693 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1694 pos->got_slack = GNUNET_YES;
1695 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1696 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
1701 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1702 if (pos->priority <= min_prio)
1704 /* update min for discard */
1705 min_prio = pos->priority;
1710 if (discard_low_prio)
1712 GNUNET_assert (min != NULL);
1713 /* remove lowest-priority entry from consideration */
1714 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1718 /* guard against sending "tiny" messages with large headers without
1720 if ( (slack.value > GNUNET_CONSTANTS_MAX_CORK_DELAY.value) &&
1722 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1724 /* less than 25% of message would be filled with deadlines still
1725 being met if we delay by one second or more; so just wait for
1726 more data; but do not wait longer than 1s (since we don't want
1727 to delay messages for a really long time either). */
1728 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1729 /* reset do_transmit values for next time */
1732 pos->do_transmit = GNUNET_NO;
1736 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1737 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1738 (unsigned long long) retry_time->value,
1740 (unsigned int) size);
1744 /* select marked messages (up to size) for transmission */
1749 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1751 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1755 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1756 "Selecting message of size %u for transmission\n",
1757 (unsigned int) pos->size);
1763 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1764 "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
1765 (unsigned int) pos->size,
1768 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1773 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1774 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1775 (unsigned long long) off, (unsigned long long) tsize,
1776 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
1777 GNUNET_i2s (&n->peer));
1784 * Batch multiple messages into a larger buffer.
1786 * @param n neighbour to take messages from
1787 * @param buf target buffer
1788 * @param size size of buf
1789 * @param deadline set to transmission deadline for the result
1790 * @param retry_time set to the time when we should try again
1791 * (only valid if this function returns zero)
1792 * @param priority set to the priority of the batch
1793 * @return number of bytes written to buf (can be zero)
1796 batch_message (struct Neighbour *n,
1799 struct GNUNET_TIME_Absolute *deadline,
1800 struct GNUNET_TIME_Relative *retry_time,
1801 unsigned int *priority)
1803 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1804 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1805 struct MessageEntry *pos;
1806 struct MessageEntry *prev;
1807 struct MessageEntry *next;
1812 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1813 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1814 if (0 == select_messages (n, size, retry_time))
1817 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1818 "No messages selected, will try again in %llu ms\n",
1823 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1824 ntm->distance = htonl (n->last_distance);
1825 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1826 ntm->peer = n->peer;
1829 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1832 if (GNUNET_YES == pos->do_transmit)
1834 GNUNET_assert (pos->size <= size);
1835 /* do notifications */
1836 /* FIXME: track if we have *any* client that wants
1837 full notifications and only do this if that is
1839 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1841 memcpy (&ntm[1], &pos[1], pos->size);
1842 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1843 sizeof (struct GNUNET_MessageHeader));
1844 send_to_all_clients (&ntm->header,
1846 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1850 /* message too large for 'full' notifications, we do at
1851 least the 'hdr' type */
1854 sizeof (struct GNUNET_MessageHeader));
1856 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1858 send_to_all_clients (&ntm->header,
1860 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1862 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1863 "Encrypting %u bytes with message of type %u and size %u\n",
1865 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
1866 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
1868 /* copy for encrypted transmission */
1869 memcpy (&buf[ret], &pos[1], pos->size);
1872 *priority += pos->priority;
1874 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1875 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1876 (unsigned int) pos->size,
1877 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1879 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1894 "Deadline for message batch is %llu ms\n",
1895 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1902 * Remove messages with deadlines that have long expired from
1905 * @param n neighbour to inspect
1908 discard_expired_messages (struct Neighbour *n)
1910 struct MessageEntry *prev;
1911 struct MessageEntry *next;
1912 struct MessageEntry *pos;
1913 struct GNUNET_TIME_Absolute now;
1914 struct GNUNET_TIME_Relative delta;
1916 now = GNUNET_TIME_absolute_get ();
1922 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1923 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1926 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1927 "Message is %llu ms past due, discarding.\n",
1944 * Signature of the main function of a task.
1946 * @param cls closure
1947 * @param tc context information (why was this task triggered now)
1950 retry_plaintext_processing (void *cls,
1951 const struct GNUNET_SCHEDULER_TaskContext *tc)
1953 struct Neighbour *n = cls;
1955 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1956 process_plaintext_neighbour_queue (n);
1961 * Send our key (and encrypted PING) to the other peer.
1963 * @param n the other peer
1965 static void send_key (struct Neighbour *n);
1968 * Task that will retry "send_key" if our previous attempt failed
1972 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1974 struct Neighbour *n = cls;
1977 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1978 "Retrying key transmission to `%4s'\n",
1979 GNUNET_i2s (&n->peer));
1981 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1982 n->set_key_retry_frequency =
1983 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1989 * Check if we have plaintext messages for the specified neighbour
1990 * pending, and if so, consider batching and encrypting them (and
1991 * then trigger processing of the encrypted queue if needed).
1993 * @param n neighbour to check.
1996 process_plaintext_neighbour_queue (struct Neighbour *n)
1998 char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)]; /* plaintext */
2001 struct EncryptedMessage *em; /* encrypted message */
2002 struct EncryptedMessage *ph; /* plaintext header */
2003 struct MessageEntry *me;
2004 unsigned int priority;
2005 struct GNUNET_TIME_Absolute deadline;
2006 struct GNUNET_TIME_Relative retry_time;
2009 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2011 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
2012 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2016 case PEER_STATE_DOWN:
2019 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2020 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2021 GNUNET_i2s(&n->peer));
2024 case PEER_STATE_KEY_SENT:
2025 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2026 n->retry_set_key_task
2027 = GNUNET_SCHEDULER_add_delayed (sched,
2028 n->set_key_retry_frequency,
2029 &set_key_retry_task, n);
2031 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2032 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2033 GNUNET_i2s(&n->peer));
2036 case PEER_STATE_KEY_RECEIVED:
2037 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2038 n->retry_set_key_task
2039 = GNUNET_SCHEDULER_add_delayed (sched,
2040 n->set_key_retry_frequency,
2041 &set_key_retry_task, n);
2043 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2044 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2045 GNUNET_i2s(&n->peer));
2048 case PEER_STATE_KEY_CONFIRMED:
2049 /* ready to continue */
2052 discard_expired_messages (n);
2053 if (n->messages == NULL)
2056 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2057 "Plaintext message queue for `%4s' is empty.\n",
2058 GNUNET_i2s(&n->peer));
2060 return; /* no pending messages */
2062 if (n->encrypted_head != NULL)
2065 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2066 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2067 GNUNET_i2s(&n->peer));
2069 return; /* wait for messages already encrypted to be
2072 ph = (struct EncryptedMessage *) pbuf;
2073 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2075 used = sizeof (struct EncryptedMessage);
2076 used += batch_message (n,
2078 GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2079 &deadline, &retry_time, &priority);
2080 if (used == sizeof (struct EncryptedMessage))
2083 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2084 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2085 GNUNET_i2s(&n->peer));
2087 /* no messages selected for sending, try again later... */
2088 n->retry_plaintext_task =
2089 GNUNET_SCHEDULER_add_delayed (sched,
2091 &retry_plaintext_processing, n);
2094 #if DEBUG_CORE_QUOTA
2095 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2096 "Sending %u b/s as new limit to peer `%4s'\n",
2097 (unsigned int) ntohl (n->bw_in.value__),
2098 GNUNET_i2s (&n->peer));
2100 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX));
2101 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2102 ph->inbound_bw_limit = n->bw_in;
2103 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2105 /* setup encryption message header */
2106 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2107 me->deadline = deadline;
2108 me->priority = priority;
2110 em = (struct EncryptedMessage *) &me[1];
2111 em->header.size = htons (used);
2112 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2113 em->iv_seed = ph->iv_seed;
2114 esize = used - ENCRYPTED_HEADER_SIZE;
2115 GNUNET_CRYPTO_hmac (&n->encrypt_key,
2116 &ph->sequence_number,
2117 esize - sizeof (GNUNET_HashCode),
2119 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
2121 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2122 "Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
2123 (unsigned int) (esize - sizeof (GNUNET_HashCode)),
2124 GNUNET_h2s (&ph->hmac),
2129 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2130 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2131 (unsigned int) esize,
2132 GNUNET_i2s(&n->peer),
2133 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2135 GNUNET_assert (GNUNET_OK ==
2140 /* append to transmission list */
2141 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2145 process_encrypted_neighbour_queue (n);
2150 * Function that recalculates the bandwidth quota for the
2151 * given neighbour and transmits it to the transport service.
2153 * @param cls neighbour for the quota update
2157 neighbour_quota_update (void *cls,
2158 const struct GNUNET_SCHEDULER_TaskContext *tc);
2162 * Schedule the task that will recalculate the bandwidth
2163 * quota for this peer (and possibly force a disconnect of
2164 * idle peers by calculating a bandwidth of zero).
2167 schedule_quota_update (struct Neighbour *n)
2169 GNUNET_assert (n->quota_update_task ==
2170 GNUNET_SCHEDULER_NO_TASK);
2171 n->quota_update_task
2172 = GNUNET_SCHEDULER_add_delayed (sched,
2173 QUOTA_UPDATE_FREQUENCY,
2174 &neighbour_quota_update,
2180 * Initialize a new 'struct Neighbour'.
2182 * @param pid ID of the new neighbour
2183 * @return handle for the new neighbour
2185 static struct Neighbour *
2186 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2188 struct Neighbour *n;
2189 struct GNUNET_TIME_Absolute now;
2192 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2193 "Creating neighbour entry for peer `%4s'\n",
2196 n = GNUNET_malloc (sizeof (struct Neighbour));
2197 n->next = neighbours;
2200 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2202 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2203 now = GNUNET_TIME_absolute_get ();
2204 n->encrypt_key_created = now;
2205 n->last_activity = now;
2206 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2207 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2208 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2209 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2210 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2211 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2213 neighbour_quota_update (n, NULL);
2214 consider_free_neighbour (n);
2220 * Handle CORE_SEND request.
2223 * @param client the client issuing the request
2224 * @param message the "struct SendMessage"
2227 handle_client_send (void *cls,
2228 struct GNUNET_SERVER_Client *client,
2229 const struct GNUNET_MessageHeader *message)
2231 const struct SendMessage *sm;
2232 struct Neighbour *n;
2233 struct MessageEntry *prev;
2234 struct MessageEntry *pos;
2235 struct MessageEntry *e;
2236 struct MessageEntry *min_prio_entry;
2237 struct MessageEntry *min_prio_prev;
2238 unsigned int min_prio;
2239 unsigned int queue_size;
2242 msize = ntohs (message->size);
2244 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2246 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "about to assert fail, msize is %d, should be at least %d\n", msize, sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader));
2249 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2252 sm = (const struct SendMessage *) message;
2253 msize -= sizeof (struct SendMessage);
2254 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2256 /* FIXME: should we not allow loopback-injection here? */
2259 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2262 n = find_neighbour (&sm->peer);
2264 n = create_neighbour (&sm->peer);
2266 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2267 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2269 (unsigned int) msize,
2270 GNUNET_i2s (&sm->peer));
2272 /* bound queue size */
2273 discard_expired_messages (n);
2274 min_prio = UINT32_MAX;
2275 min_prio_entry = NULL;
2276 min_prio_prev = NULL;
2282 if (pos->priority <= min_prio)
2284 min_prio_entry = pos;
2285 min_prio_prev = prev;
2286 min_prio = pos->priority;
2292 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2295 if (ntohl(sm->priority) <= min_prio)
2297 /* discard new entry */
2299 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2300 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2302 (unsigned int) MAX_PEER_QUEUE_SIZE,
2303 (unsigned int) msize,
2304 (unsigned int) ntohs (message->type));
2307 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2310 GNUNET_assert (min_prio_entry != NULL);
2311 /* discard "min_prio_entry" */
2313 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2314 "Queue full, discarding existing older request\n");
2316 if (min_prio_prev == NULL)
2317 n->messages = min_prio_entry->next;
2319 min_prio_prev->next = min_prio_entry->next;
2320 GNUNET_free (min_prio_entry);
2324 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2325 "Adding transmission request for `%4s' of size %u to queue\n",
2326 GNUNET_i2s (&sm->peer),
2327 (unsigned int) msize);
2329 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2330 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2331 e->priority = ntohl (sm->priority);
2333 memcpy (&e[1], &sm[1], msize);
2335 /* insert, keep list sorted by deadline */
2338 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2349 /* consider scheduling now */
2350 process_plaintext_neighbour_queue (n);
2352 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2357 * Function called when the transport service is ready to
2358 * receive a message. Only resets 'n->th' to NULL.
2360 * @param cls neighbour to use message from
2361 * @param size number of bytes we can transmit
2362 * @param buf where to copy the message
2363 * @return number of bytes transmitted
2366 notify_transport_connect_done (void *cls, size_t size, void *buf)
2368 struct Neighbour *n = cls;
2370 if (GNUNET_YES != n->is_connected)
2372 /* transport should only call us to transmit a message after
2373 * telling us about a successful connection to the respective peer */
2374 n->th = NULL; /* If this happens because of a timeout, reset n-th so another message may be sent for this peer! */
2381 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2382 _("Failed to connect to `%4s': transport failed to connect\n"),
2383 GNUNET_i2s (&n->peer));
2386 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2387 _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2388 GNUNET_i2s (&n->peer));
2389 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2390 GNUNET_SCHEDULER_cancel (sched,
2391 n->retry_set_key_task);
2392 n->retry_set_key_task = GNUNET_SCHEDULER_add_now (sched,
2393 &set_key_retry_task,
2400 * Handle CORE_REQUEST_CONNECT request.
2403 * @param client the client issuing the request
2404 * @param message the "struct ConnectMessage"
2407 handle_client_request_connect (void *cls,
2408 struct GNUNET_SERVER_Client *client,
2409 const struct GNUNET_MessageHeader *message)
2411 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2412 struct Neighbour *n;
2413 struct GNUNET_TIME_Relative timeout;
2415 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2418 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2421 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2422 n = find_neighbour (&cm->peer);
2424 n = create_neighbour (&cm->peer);
2425 if ( (GNUNET_YES == n->is_connected) ||
2428 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2429 "Core received `%s' request for `%4s', already connected!\n",
2431 GNUNET_i2s (&cm->peer));
2432 return; /* already connected, or at least trying */
2434 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2436 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2437 "Core received `%s' request for `%4s', will try to establish connection\n",
2439 GNUNET_i2s (&cm->peer));
2441 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2442 /* ask transport to connect to the peer */
2443 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2445 sizeof (struct GNUNET_MessageHeader), 0,
2447 ¬ify_transport_connect_done,
2449 GNUNET_break (NULL != n->th);
2454 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2455 * the neighbour's struct and retry send_key. Or, if we did not get a
2456 * HELLO, just do nothing.
2458 * @param cls the 'struct Neighbour' to retry sending the key for
2459 * @param peer the peer for which this is the HELLO
2460 * @param hello HELLO message of that peer
2463 process_hello_retry_send_key (void *cls,
2464 const struct GNUNET_PeerIdentity *peer,
2465 const struct GNUNET_HELLO_Message *hello)
2467 struct Neighbour *n = cls;
2472 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2473 "Entered `%s' and `%s' is NULL!\n",
2474 "process_hello_retry_send_key",
2478 if (n->public_key != NULL)
2480 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2482 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2483 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2485 GNUNET_STATISTICS_update (stats,
2486 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2494 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2495 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
2496 GNUNET_i2s (&n->peer));
2498 GNUNET_STATISTICS_update (stats,
2499 gettext_noop ("# Delayed connecting due to lack of public key"),
2502 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2503 n->retry_set_key_task
2504 = GNUNET_SCHEDULER_add_delayed (sched,
2505 n->set_key_retry_frequency,
2506 &set_key_retry_task, n);
2512 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2513 "Entered `%s' for peer `%4s'\n",
2514 "process_hello_retry_send_key",
2517 if (n->public_key != NULL)
2519 /* already have public key, why are we here? */
2525 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2526 "Received new `%s' message for `%4s', initiating key exchange.\n",
2531 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2532 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2534 GNUNET_STATISTICS_update (stats,
2535 gettext_noop ("# Error extracting public key from HELLO"),
2538 GNUNET_free (n->public_key);
2539 n->public_key = NULL;
2541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2542 "GNUNET_HELLO_get_key returned awfully\n");
2550 * Send our key (and encrypted PING) to the other peer.
2552 * @param n the other peer
2555 send_key (struct Neighbour *n)
2557 struct MessageEntry *pos;
2558 struct SetKeyMessage *sm;
2559 struct MessageEntry *me;
2560 struct PingMessage pp;
2561 struct PingMessage *pm;
2563 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2565 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2566 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2568 if (n->pitr != NULL)
2571 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2572 "Key exchange in progress with `%4s'.\n",
2573 GNUNET_i2s (&n->peer));
2575 return; /* already in progress */
2577 if (GNUNET_YES != n->is_connected)
2580 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2581 "Not yet connected to peer `%4s'!\n",
2582 GNUNET_i2s (&n->peer));
2586 GNUNET_STATISTICS_update (stats,
2587 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
2590 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2592 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2594 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2595 ¬ify_encrypted_transmit_ready,
2601 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2602 "Asked to perform key exchange with `%4s'.\n",
2603 GNUNET_i2s (&n->peer));
2605 if (n->public_key == NULL)
2607 /* lookup n's public key, then try again */
2609 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2610 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2611 GNUNET_i2s (&n->peer));
2613 GNUNET_assert (n->pitr == NULL);
2614 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2616 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2617 &process_hello_retry_send_key, n);
2620 pos = n->encrypted_head;
2623 if (GNUNET_YES == pos->is_setkey)
2625 if (pos->sender_status == n->status)
2628 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2629 "`%s' message for `%4s' queued already\n",
2631 GNUNET_i2s (&n->peer));
2633 goto trigger_processing;
2635 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2640 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2641 "Removing queued `%s' message for `%4s', will create a new one\n",
2643 GNUNET_i2s (&n->peer));
2653 case PEER_STATE_DOWN:
2654 n->status = PEER_STATE_KEY_SENT;
2656 case PEER_STATE_KEY_SENT:
2658 case PEER_STATE_KEY_RECEIVED:
2660 case PEER_STATE_KEY_CONFIRMED:
2668 /* first, set key message */
2669 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2670 sizeof (struct SetKeyMessage) +
2671 sizeof (struct PingMessage));
2672 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2673 me->priority = SET_KEY_PRIORITY;
2674 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
2675 me->is_setkey = GNUNET_YES;
2676 me->got_slack = GNUNET_YES; /* do not defer this one! */
2677 me->sender_status = n->status;
2678 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2682 sm = (struct SetKeyMessage *) &me[1];
2683 sm->header.size = htons (sizeof (struct SetKeyMessage));
2684 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2685 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2686 PEER_STATE_KEY_SENT : n->status));
2688 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2689 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2690 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2691 sizeof (struct GNUNET_PeerIdentity));
2692 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2693 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2694 sm->target = n->peer;
2695 GNUNET_assert (GNUNET_OK ==
2696 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2698 GNUNET_CRYPTO_AesSessionKey),
2700 &sm->encrypted_key));
2701 GNUNET_assert (GNUNET_OK ==
2702 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2704 pm = (struct PingMessage *) &sm[1];
2705 pm->header.size = htons (sizeof (struct PingMessage));
2706 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2707 pp.challenge = htonl (n->ping_challenge);
2708 pp.target = n->peer;
2710 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2711 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u.\n",
2713 (unsigned int) n->ping_challenge,
2714 GNUNET_i2s (&n->peer),
2715 (unsigned int) n->encrypt_key.crc32);
2718 &n->peer.hashPubKey,
2721 sizeof (struct PingMessage) -
2722 sizeof (struct GNUNET_MessageHeader));
2723 GNUNET_STATISTICS_update (stats,
2724 gettext_noop ("# SET_KEY and PING messages created"),
2728 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2729 "Have %llu ms left for `%s' transmission.\n",
2730 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2734 /* trigger queue processing */
2735 process_encrypted_neighbour_queue (n);
2736 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2737 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2738 n->retry_set_key_task
2739 = GNUNET_SCHEDULER_add_delayed (sched,
2740 n->set_key_retry_frequency,
2741 &set_key_retry_task, n);
2746 * We received a SET_KEY message. Validate and update
2747 * our key material and status.
2749 * @param n the neighbour from which we received message m
2750 * @param m the set key message we received
2753 handle_set_key (struct Neighbour *n,
2754 const struct SetKeyMessage *m);
2758 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2759 * the neighbour's struct and retry handling the set_key message. Or,
2760 * if we did not get a HELLO, just free the set key message.
2762 * @param cls pointer to the set key message
2763 * @param peer the peer for which this is the HELLO
2764 * @param hello HELLO message of that peer
2767 process_hello_retry_handle_set_key (void *cls,
2768 const struct GNUNET_PeerIdentity *peer,
2769 const struct GNUNET_HELLO_Message *hello)
2771 struct Neighbour *n = cls;
2772 struct SetKeyMessage *sm = n->skm;
2778 if (n->public_key != NULL)
2781 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2782 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2784 GNUNET_i2s (&n->peer),
2787 handle_set_key (n, sm);
2791 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2792 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
2794 GNUNET_i2s (&n->peer));
2799 if (n->public_key != NULL)
2800 return; /* multiple HELLOs match!? */
2802 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2803 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2805 GNUNET_break_op (0);
2806 GNUNET_free (n->public_key);
2807 n->public_key = NULL;
2813 * We received a PING message. Validate and transmit
2816 * @param n sender of the PING
2817 * @param m the encrypted PING message itself
2820 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2822 struct PingMessage t;
2823 struct PongMessage tx;
2824 struct PongMessage *tp;
2825 struct MessageEntry *me;
2828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2829 "Core service receives `%s' request from `%4s'.\n",
2830 "PING", GNUNET_i2s (&n->peer));
2834 &my_identity.hashPubKey,
2837 sizeof (struct PingMessage) -
2838 sizeof (struct GNUNET_MessageHeader)))
2841 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2842 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2844 GNUNET_i2s (&t.target),
2845 (unsigned int) ntohl (t.challenge),
2846 (unsigned int) n->decrypt_key.crc32);
2848 GNUNET_STATISTICS_update (stats,
2849 gettext_noop ("# PING messages decrypted"),
2852 if (0 != memcmp (&t.target,
2853 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2855 GNUNET_break_op (0);
2858 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2859 sizeof (struct PongMessage));
2860 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2864 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2865 me->priority = PONG_PRIORITY;
2866 me->size = sizeof (struct PongMessage);
2867 tx.reserved = htonl (0);
2868 tx.inbound_bw_limit = n->bw_in;
2869 tx.challenge = t.challenge;
2870 tx.target = t.target;
2871 tp = (struct PongMessage *) &me[1];
2872 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2873 tp->header.size = htons (sizeof (struct PongMessage));
2875 &my_identity.hashPubKey,
2878 sizeof (struct PongMessage) -
2879 sizeof (struct GNUNET_MessageHeader));
2880 GNUNET_STATISTICS_update (stats,
2881 gettext_noop ("# PONG messages created"),
2885 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2886 "Encrypting `%s' with challenge %u using key %u\n",
2888 (unsigned int) ntohl (t.challenge),
2889 (unsigned int) n->encrypt_key.crc32);
2891 /* trigger queue processing */
2892 process_encrypted_neighbour_queue (n);
2897 * We received a PONG message. Validate and update our status.
2899 * @param n sender of the PONG
2900 * @param m the encrypted PONG message itself
2903 handle_pong (struct Neighbour *n,
2904 const struct PongMessage *m)
2906 struct PongMessage t;
2907 struct ConnectNotifyMessage cnm;
2910 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2911 "Core service receives `%s' response from `%4s'.\n",
2912 "PONG", GNUNET_i2s (&n->peer));
2914 /* mark as garbage, just to be sure */
2915 memset (&t, 255, sizeof (t));
2918 &n->peer.hashPubKey,
2921 sizeof (struct PongMessage) -
2922 sizeof (struct GNUNET_MessageHeader)))
2924 GNUNET_break_op (0);
2927 GNUNET_STATISTICS_update (stats,
2928 gettext_noop ("# PONG messages decrypted"),
2931 if (0 != ntohl (t.reserved))
2933 GNUNET_break_op (0);
2937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2938 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2940 GNUNET_i2s (&t.target),
2941 (unsigned int) ntohl (t.challenge),
2942 (unsigned int) n->decrypt_key.crc32);
2944 if ((0 != memcmp (&t.target,
2946 sizeof (struct GNUNET_PeerIdentity))) ||
2947 (n->ping_challenge != ntohl (t.challenge)))
2949 /* PONG malformed */
2951 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2952 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2954 GNUNET_i2s (&n->peer),
2955 (unsigned int) n->ping_challenge);
2956 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2957 "Received malformed `%s' received from `%4s' with challenge %u\n",
2958 "PONG", GNUNET_i2s (&t.target),
2959 (unsigned int) ntohl (t.challenge));
2961 GNUNET_break_op (0);
2966 case PEER_STATE_DOWN:
2967 GNUNET_break (0); /* should be impossible */
2969 case PEER_STATE_KEY_SENT:
2970 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2972 case PEER_STATE_KEY_RECEIVED:
2973 GNUNET_STATISTICS_update (stats,
2974 gettext_noop ("# Session keys confirmed via PONG"),
2977 n->status = PEER_STATE_KEY_CONFIRMED;
2978 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2980 n->bw_out_external_limit = t.inbound_bw_limit;
2981 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2982 n->bw_out_internal_limit);
2983 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2985 GNUNET_TRANSPORT_set_quota (transport,
2989 GNUNET_TIME_UNIT_FOREVER_REL,
2993 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2994 "Confirmed key via `%s' message for peer `%4s'\n",
2995 "PONG", GNUNET_i2s (&n->peer));
2997 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2999 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
3000 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3002 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3003 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3004 cnm.distance = htonl (n->last_distance);
3005 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3007 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
3008 process_encrypted_neighbour_queue (n);
3010 case PEER_STATE_KEY_CONFIRMED:
3011 n->last_activity = GNUNET_TIME_absolute_get ();
3012 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3013 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3015 = GNUNET_SCHEDULER_add_delayed (sched,
3016 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3019 handle_peer_status_change (n);
3029 * We received a SET_KEY message. Validate and update
3030 * our key material and status.
3032 * @param n the neighbour from which we received message m
3033 * @param m the set key message we received
3036 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
3038 struct SetKeyMessage *m_cpy;
3039 struct GNUNET_TIME_Absolute t;
3040 struct GNUNET_CRYPTO_AesSessionKey k;
3041 struct PingMessage *ping;
3042 struct PongMessage *pong;
3043 enum PeerStateMachine sender_status;
3046 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3047 "Core service receives `%s' request from `%4s'.\n",
3048 "SET_KEY", GNUNET_i2s (&n->peer));
3050 if (n->public_key == NULL)
3052 if (n->pitr != NULL)
3055 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3056 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3063 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3065 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3066 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3067 /* lookup n's public key, then try again */
3068 GNUNET_assert (n->skm == NULL);
3070 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3072 GNUNET_TIME_UNIT_MINUTES,
3073 &process_hello_retry_handle_set_key, n);
3074 GNUNET_STATISTICS_update (stats,
3075 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3080 if (0 != memcmp (&m->target,
3082 sizeof (struct GNUNET_PeerIdentity)))
3084 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3085 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3087 GNUNET_i2s (&m->target));
3090 if ((ntohl (m->purpose.size) !=
3091 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3092 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3093 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3094 sizeof (struct GNUNET_PeerIdentity)) ||
3096 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3097 &m->purpose, &m->signature, n->public_key)))
3099 /* invalid signature */
3100 GNUNET_break_op (0);
3103 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3104 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3105 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3106 (t.value < n->decrypt_key_created.value))
3108 /* this could rarely happen due to massive re-ordering of
3109 messages on the network level, but is most likely either
3110 a bug or some adversary messing with us. Report. */
3111 GNUNET_break_op (0);
3115 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3116 "Decrypting key material.\n");
3118 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3121 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3122 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3123 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3125 /* failed to decrypt !? */
3126 GNUNET_break_op (0);
3129 GNUNET_STATISTICS_update (stats,
3130 gettext_noop ("# SET_KEY messages decrypted"),
3134 if (n->decrypt_key_created.value != t.value)
3136 /* fresh key, reset sequence numbers */
3137 n->last_sequence_number_received = 0;
3138 n->last_packets_bitmap = 0;
3139 n->decrypt_key_created = t;
3141 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3144 case PEER_STATE_DOWN:
3145 n->status = PEER_STATE_KEY_RECEIVED;
3147 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3148 "Responding to `%s' with my own key.\n", "SET_KEY");
3152 case PEER_STATE_KEY_SENT:
3153 case PEER_STATE_KEY_RECEIVED:
3154 n->status = PEER_STATE_KEY_RECEIVED;
3155 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3156 (sender_status != PEER_STATE_KEY_CONFIRMED))
3159 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3160 "Responding to `%s' with my own key (other peer has status %u).\n",
3162 (unsigned int) sender_status);
3167 case PEER_STATE_KEY_CONFIRMED:
3168 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3169 (sender_status != PEER_STATE_KEY_CONFIRMED))
3172 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3173 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3175 (unsigned int) sender_status);
3184 if (n->pending_ping != NULL)
3186 ping = n->pending_ping;
3187 n->pending_ping = NULL;
3188 handle_ping (n, ping);
3191 if (n->pending_pong != NULL)
3193 pong = n->pending_pong;
3194 n->pending_pong = NULL;
3195 handle_pong (n, pong);
3202 * Send a P2P message to a client.
3204 * @param sender who sent us the message?
3205 * @param client who should we give the message to?
3206 * @param m contains the message to transmit
3207 * @param msize number of bytes in buf to transmit
3210 send_p2p_message_to_client (struct Neighbour *sender,
3211 struct Client *client,
3212 const void *m, size_t msize)
3214 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3215 struct NotifyTrafficMessage *ntm;
3218 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3219 "Core service passes message from `%4s' of type %u to client.\n",
3220 GNUNET_i2s(&sender->peer),
3221 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3223 ntm = (struct NotifyTrafficMessage *) buf;
3224 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3225 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3226 ntm->distance = htonl (sender->last_distance);
3227 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3228 ntm->peer = sender->peer;
3229 memcpy (&ntm[1], m, msize);
3230 send_to_client (client, &ntm->header, GNUNET_YES);
3235 * Deliver P2P message to interested clients.
3237 * @param cls always NULL
3238 * @param client who sent us the message (struct Neighbour)
3239 * @param m the message
3242 deliver_message (void *cls,
3244 const struct GNUNET_MessageHeader *m)
3246 struct Neighbour *sender = client;
3247 size_t msize = ntohs (m->size);
3249 struct Client *cpos;
3255 type = ntohs (m->type);
3257 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3258 "Received encapsulated message of type %u and size %u from `%4s'\n",
3259 (unsigned int) type,
3261 GNUNET_i2s (&sender->peer));
3263 GNUNET_snprintf (buf,
3265 gettext_noop ("# bytes of messages of type %u received"),
3266 (unsigned int) type);
3267 GNUNET_STATISTICS_set (stats,
3271 dropped = GNUNET_YES;
3273 while (cpos != NULL)
3275 deliver_full = GNUNET_NO;
3276 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3277 deliver_full = GNUNET_YES;
3280 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3282 if (type != cpos->types[tpos])
3284 deliver_full = GNUNET_YES;
3288 if (GNUNET_YES == deliver_full)
3290 send_p2p_message_to_client (sender, cpos, m, msize);
3291 dropped = GNUNET_NO;
3293 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3295 send_p2p_message_to_client (sender, cpos, m,
3296 sizeof (struct GNUNET_MessageHeader));
3300 if (dropped == GNUNET_YES)
3303 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3304 "Message of type %u from `%4s' not delivered to any client.\n",
3305 (unsigned int) type,
3306 GNUNET_i2s (&sender->peer));
3308 GNUNET_STATISTICS_update (stats,
3309 gettext_noop ("# messages not delivered to any client"),
3316 * We received an encrypted message. Decrypt, validate and
3317 * pass on to the appropriate clients.
3320 handle_encrypted_message (struct Neighbour *n,
3321 const struct EncryptedMessage *m)
3323 size_t size = ntohs (m->header.size);
3325 struct EncryptedMessage *pt; /* plaintext */
3328 struct GNUNET_TIME_Absolute t;
3332 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3333 "Core service receives `%s' request from `%4s'.\n",
3334 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3336 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3342 &buf[ENCRYPTED_HEADER_SIZE],
3343 size - ENCRYPTED_HEADER_SIZE))
3345 pt = (struct EncryptedMessage *) buf;
3347 GNUNET_CRYPTO_hmac (&n->decrypt_key,
3348 &pt->sequence_number,
3349 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3351 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3352 "V-Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
3353 (unsigned int) (size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode)),
3357 if (0 != memcmp (&ph,
3359 sizeof (GNUNET_HashCode)))
3361 /* checksum failed */
3362 GNUNET_break_op (0);
3366 /* validate sequence number */
3367 snum = ntohl (pt->sequence_number);
3368 if (n->last_sequence_number_received == snum)
3370 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3371 "Received duplicate message, ignoring.\n");
3372 /* duplicate, ignore */
3373 GNUNET_STATISTICS_set (stats,
3374 gettext_noop ("# bytes dropped (duplicates)"),
3379 if ((n->last_sequence_number_received > snum) &&
3380 (n->last_sequence_number_received - snum > 32))
3382 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3383 "Received ancient out of sequence message, ignoring.\n");
3384 /* ancient out of sequence, ignore */
3385 GNUNET_STATISTICS_set (stats,
3386 gettext_noop ("# bytes dropped (out of sequence)"),
3391 if (n->last_sequence_number_received > snum)
3393 unsigned int rotbit =
3394 1 << (n->last_sequence_number_received - snum - 1);
3395 if ((n->last_packets_bitmap & rotbit) != 0)
3397 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3398 "Received duplicate message, ignoring.\n");
3399 GNUNET_STATISTICS_set (stats,
3400 gettext_noop ("# bytes dropped (duplicates)"),
3403 /* duplicate, ignore */
3406 n->last_packets_bitmap |= rotbit;
3408 if (n->last_sequence_number_received < snum)
3410 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3411 n->last_sequence_number_received = snum;
3414 /* check timestamp */
3415 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3416 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3418 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3420 ("Message received far too old (%llu ms). Content ignored.\n"),
3421 GNUNET_TIME_absolute_get_duration (t).value);
3422 GNUNET_STATISTICS_set (stats,
3423 gettext_noop ("# bytes dropped (ancient message)"),
3429 /* process decrypted message(s) */
3430 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3432 #if DEBUG_CORE_SET_QUOTA
3433 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3434 "Received %u b/s as new inbound limit for peer `%4s'\n",
3435 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3436 GNUNET_i2s (&n->peer));
3438 n->bw_out_external_limit = pt->inbound_bw_limit;
3439 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3440 n->bw_out_internal_limit);
3441 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3443 GNUNET_TRANSPORT_set_quota (transport,
3447 GNUNET_TIME_UNIT_FOREVER_REL,
3450 n->last_activity = GNUNET_TIME_absolute_get ();
3451 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3452 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3454 = GNUNET_SCHEDULER_add_delayed (sched,
3455 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3458 GNUNET_STATISTICS_set (stats,
3459 gettext_noop ("# bytes of payload decrypted"),
3460 size - sizeof (struct EncryptedMessage),
3462 handle_peer_status_change (n);
3463 if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst,
3465 &buf[sizeof (struct EncryptedMessage)],
3466 size - sizeof (struct EncryptedMessage),
3467 GNUNET_YES, GNUNET_NO))
3468 GNUNET_break_op (0);
3473 * Function called by the transport for each received message.
3475 * @param cls closure
3476 * @param peer (claimed) identity of the other peer
3477 * @param message the message
3478 * @param latency estimated latency for communicating with the
3479 * given peer (round-trip)
3480 * @param distance in overlay hops, as given by transport plugin
3483 handle_transport_receive (void *cls,
3484 const struct GNUNET_PeerIdentity *peer,
3485 const struct GNUNET_MessageHeader *message,
3486 struct GNUNET_TIME_Relative latency,
3487 unsigned int distance)
3489 struct Neighbour *n;
3490 struct GNUNET_TIME_Absolute now;
3497 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3498 "Received message of type %u from `%4s', demultiplexing.\n",
3499 (unsigned int) ntohs (message->type),
3502 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3507 n = find_neighbour (peer);
3509 n = create_neighbour (peer);
3510 changed = (latency.value != n->last_latency.value) || (distance != n->last_distance);
3511 n->last_latency = latency;
3512 n->last_distance = distance;
3513 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3514 type = ntohs (message->type);
3515 size = ntohs (message->size);
3518 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3519 if (size != sizeof (struct SetKeyMessage))
3521 GNUNET_break_op (0);
3524 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3525 handle_set_key (n, (const struct SetKeyMessage *) message);
3527 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3528 if (size < sizeof (struct EncryptedMessage) +
3529 sizeof (struct GNUNET_MessageHeader))
3531 GNUNET_break_op (0);
3534 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3535 (n->status != PEER_STATE_KEY_CONFIRMED))
3537 GNUNET_break_op (0);
3540 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3542 case GNUNET_MESSAGE_TYPE_CORE_PING:
3543 if (size != sizeof (struct PingMessage))
3545 GNUNET_break_op (0);
3548 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3549 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3550 (n->status != PEER_STATE_KEY_CONFIRMED))
3553 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3554 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3555 "PING", GNUNET_i2s (&n->peer));
3557 GNUNET_free_non_null (n->pending_ping);
3558 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3559 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3562 handle_ping (n, (const struct PingMessage *) message);
3564 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3565 if (size != sizeof (struct PongMessage))
3567 GNUNET_break_op (0);
3570 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3571 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3572 (n->status != PEER_STATE_KEY_CONFIRMED) )
3575 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3576 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3577 "PONG", GNUNET_i2s (&n->peer));
3579 GNUNET_free_non_null (n->pending_pong);
3580 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3581 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3584 handle_pong (n, (const struct PongMessage *) message);
3587 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3588 _("Unsupported message of type %u received.\n"),
3589 (unsigned int) type);
3592 if (n->status == PEER_STATE_KEY_CONFIRMED)
3594 now = GNUNET_TIME_absolute_get ();
3595 n->last_activity = now;
3596 changed = GNUNET_YES;
3599 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3600 n->time_established = now;
3602 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3603 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3605 = GNUNET_SCHEDULER_add_delayed (sched,
3606 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3611 handle_peer_status_change (n);
3616 * Function that recalculates the bandwidth quota for the
3617 * given neighbour and transmits it to the transport service.
3619 * @param cls neighbour for the quota update
3623 neighbour_quota_update (void *cls,
3624 const struct GNUNET_SCHEDULER_TaskContext *tc)
3626 struct Neighbour *n = cls;
3627 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3630 unsigned long long distributable;
3631 uint64_t need_per_peer;
3632 uint64_t need_per_second;
3635 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3636 "Neighbour quota update calculation running for peer `%4s'\n",
3637 GNUNET_i2s (&n->peer));
3639 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3640 /* calculate relative preference among all neighbours;
3641 divides by a bit more to avoid division by zero AND to
3642 account for possibility of new neighbours joining any time
3643 AND to convert to double... */
3644 if (preference_sum == 0)
3646 pref_rel = 1.0 / (double) neighbour_count;
3650 pref_rel = n->current_preference / preference_sum;
3652 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3653 GNUNET_TIME_UNIT_SECONDS);
3654 need_per_second = need_per_peer * neighbour_count;
3656 if (bandwidth_target_out_bps > need_per_second)
3657 distributable = bandwidth_target_out_bps - need_per_second;
3658 share = distributable * pref_rel;
3659 if (share + need_per_peer > UINT32_MAX)
3660 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
3662 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3663 /* check if we want to disconnect for good due to inactivity */
3664 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3665 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3668 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3669 "Forcing disconnect of `%4s' due to inactivity\n",
3670 GNUNET_i2s (&n->peer));
3672 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3674 #if DEBUG_CORE_QUOTA
3675 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3676 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3677 GNUNET_i2s (&n->peer),
3678 (unsigned int) ntohl (q_in.value__),
3679 bandwidth_target_out_bps,
3680 (unsigned int) ntohl (n->bw_in.value__),
3681 (unsigned int) ntohl (n->bw_out.value__),
3682 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3684 if (n->bw_in.value__ != q_in.value__)
3687 if (GNUNET_YES == n->is_connected)
3688 GNUNET_TRANSPORT_set_quota (transport,
3692 GNUNET_TIME_UNIT_FOREVER_REL,
3694 handle_peer_status_change (n);
3696 schedule_quota_update (n);
3701 * Function called by transport to notify us that
3702 * a peer connected to us (on the network level).
3704 * @param cls closure
3705 * @param peer the peer that connected
3706 * @param latency current latency of the connection
3707 * @param distance in overlay hops, as given by transport plugin
3710 handle_transport_notify_connect (void *cls,
3711 const struct GNUNET_PeerIdentity *peer,
3712 struct GNUNET_TIME_Relative latency,
3713 unsigned int distance)
3715 struct Neighbour *n;
3717 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3722 n = find_neighbour (peer);
3725 if (GNUNET_YES == n->is_connected)
3727 /* duplicate connect notification!? */
3734 n = create_neighbour (peer);
3736 GNUNET_STATISTICS_update (stats,
3737 gettext_noop ("# peers connected (transport)"),
3740 n->is_connected = GNUNET_YES;
3741 n->last_latency = latency;
3742 n->last_distance = distance;
3743 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3746 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3750 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3751 "Received connection from `%4s'.\n",
3752 GNUNET_i2s (&n->peer));
3754 GNUNET_TRANSPORT_set_quota (transport,
3758 GNUNET_TIME_UNIT_FOREVER_REL,
3765 * Function called by transport telling us that a peer
3768 * @param cls closure
3769 * @param peer the peer that disconnected
3772 handle_transport_notify_disconnect (void *cls,
3773 const struct GNUNET_PeerIdentity *peer)
3775 struct DisconnectNotifyMessage cnm;
3776 struct Neighbour *n;
3777 struct GNUNET_TIME_Relative left;
3780 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3781 "Peer `%4s' disconnected from us; received notification from transport.\n", GNUNET_i2s (peer));
3784 n = find_neighbour (peer);
3790 GNUNET_break (n->is_connected);
3791 if (n->status == PEER_STATE_KEY_CONFIRMED)
3793 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3794 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3796 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3798 n->is_connected = GNUNET_NO;
3799 GNUNET_STATISTICS_update (stats,
3800 gettext_noop ("# peers connected (transport)"),
3803 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
3804 GNUNET_SCHEDULER_cancel (sched,
3805 n->dead_clean_task);
3806 left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3807 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
3808 n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (),
3810 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
3811 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
3812 &consider_free_task,
3818 * Last task run during shutdown. Disconnects us from
3822 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3824 struct Neighbour *n;
3828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3829 "Core service shutting down.\n");
3831 GNUNET_assert (transport != NULL);
3832 GNUNET_TRANSPORT_disconnect (transport);
3834 while (NULL != (n = neighbours))
3836 neighbours = n->next;
3837 GNUNET_assert (neighbour_count > 0);
3841 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
3842 GNUNET_SERVER_notification_context_destroy (notifier);
3844 while (NULL != (c = clients))
3845 handle_client_disconnect (NULL, c->client_handle);
3846 if (my_private_key != NULL)
3847 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3849 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3850 if (peerinfo != NULL)
3851 GNUNET_PEERINFO_disconnect (peerinfo);
3853 GNUNET_SERVER_mst_destroy (mst);
3858 * Initiate core service.
3860 * @param cls closure
3861 * @param s scheduler to use
3862 * @param server the initialized server
3863 * @param c configuration to use
3867 struct GNUNET_SCHEDULER_Handle *s,
3868 struct GNUNET_SERVER_Handle *server,
3869 const struct GNUNET_CONFIGURATION_Handle *c)
3871 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3872 {&handle_client_init, NULL,
3873 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
3874 {&handle_client_request_info, NULL,
3875 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
3876 sizeof (struct RequestInfoMessage)},
3877 {&handle_client_iterate_peers, NULL,
3878 GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
3879 sizeof (struct GNUNET_MessageHeader)},
3880 {&handle_client_send, NULL,
3881 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
3882 {&handle_client_request_connect, NULL,
3883 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
3884 sizeof (struct ConnectMessage)},
3891 /* parse configuration */
3894 GNUNET_CONFIGURATION_get_value_number (c,
3897 &bandwidth_target_in_bps)) ||
3899 GNUNET_CONFIGURATION_get_value_number (c,
3902 &bandwidth_target_out_bps)) ||
3904 GNUNET_CONFIGURATION_get_value_filename (c,
3906 "HOSTKEY", &keyfile)))
3908 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3910 ("Core service is lacking key configuration settings. Exiting.\n"));
3911 GNUNET_SCHEDULER_shutdown (s);
3914 peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
3915 if (NULL == peerinfo)
3917 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3918 _("Could not access PEERINFO service. Exiting.\n"));
3919 GNUNET_SCHEDULER_shutdown (s);
3920 GNUNET_free (keyfile);
3923 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3924 GNUNET_free (keyfile);
3925 if (my_private_key == NULL)
3927 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3928 _("Core service could not access hostkey. Exiting.\n"));
3929 GNUNET_PEERINFO_disconnect (peerinfo);
3930 GNUNET_SCHEDULER_shutdown (s);
3933 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3934 GNUNET_CRYPTO_hash (&my_public_key,
3935 sizeof (my_public_key), &my_identity.hashPubKey);
3936 /* setup notification */
3937 notifier = GNUNET_SERVER_notification_context_create (server,
3939 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3940 /* setup transport connection */
3941 transport = GNUNET_TRANSPORT_connect (sched,
3945 &handle_transport_receive,
3946 &handle_transport_notify_connect,
3947 &handle_transport_notify_disconnect);
3948 GNUNET_assert (NULL != transport);
3949 stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3950 mst = GNUNET_SERVER_mst_create (&deliver_message,
3952 GNUNET_SCHEDULER_add_delayed (sched,
3953 GNUNET_TIME_UNIT_FOREVER_REL,
3954 &cleaning_task, NULL);
3955 /* process client requests */
3956 GNUNET_SERVER_add_handlers (server, handlers);
3957 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3958 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3964 * The main function for the transport service.
3966 * @param argc number of arguments from the command line
3967 * @param argv command line arguments
3968 * @return 0 ok, 1 on error
3971 main (int argc, char *const *argv)
3973 return (GNUNET_OK ==
3974 GNUNET_SERVICE_run (argc,
3977 GNUNET_SERVICE_OPTION_NONE,
3978 &run, NULL)) ? 0 : 1;
3981 /* end of gnunet-service-core.c */