2 This file is part of GNUnet.
3 (C) 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file core/gnunet-service-core.c
23 * @brief high-level P2P messaging
24 * @author Christian Grothoff
26 * Considerations for later:
27 * - check that hostkey used by transport (for HELLOs) is the
28 * same as the hostkey that we are using!
29 * - add code to send PINGs if we are about to time-out otherwise
30 * - optimize lookup (many O(n) list traversals
31 * could ideally be changed to O(1) hash map lookups)
34 #include "gnunet_constants.h"
35 #include "gnunet_util_lib.h"
36 #include "gnunet_hello_lib.h"
37 #include "gnunet_peerinfo_service.h"
38 #include "gnunet_protocols.h"
39 #include "gnunet_signatures.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet_transport_service.h"
45 #define DEBUG_HANDSHAKE GNUNET_NO
47 #define DEBUG_CORE_QUOTA GNUNET_YES
50 * Receive and send buffer windows grow over time. For
51 * how long can 'unused' bandwidth accumulate before we
52 * need to cap it? (specified in seconds).
54 #define MAX_WINDOW_TIME_S (5 * 60)
57 * How many messages do we queue up at most for optional
58 * notifications to a client? (this can cause notifications
59 * about outgoing messages to be dropped).
61 #define MAX_NOTIFY_QUEUE 1024
64 * Minimum bandwidth (out) to assign to any connected peer.
65 * Should be rather low; values larger than DEFAULT_BW_IN_OUT make no
68 #define MIN_BANDWIDTH_PER_PEER GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT
71 * After how much time past the "official" expiration time do
72 * we discard messages? Should not be zero since we may
73 * intentionally defer transmission until close to the deadline
74 * and then may be slightly past the deadline due to inaccuracy
75 * in sleep and our own CPU consumption.
77 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
80 * What is the maximum delay for a SET_KEY message?
82 #define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
85 * How long do we wait for SET_KEY confirmation initially?
87 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 1)
90 * What is the maximum delay for a PING message?
92 #define MAX_PING_DELAY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 2)
95 * What is the maximum delay for a PONG message?
97 #define MAX_PONG_DELAY GNUNET_TIME_relative_multiply (MAX_PING_DELAY, 2)
100 * What is the minimum frequency for a PING message?
102 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
105 * How often do we recalculate bandwidth quotas?
107 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
110 * What is the priority for a SET_KEY message?
112 #define SET_KEY_PRIORITY 0xFFFFFF
115 * What is the priority for a PING message?
117 #define PING_PRIORITY 0xFFFFFF
120 * What is the priority for a PONG message?
122 #define PONG_PRIORITY 0xFFFFFF
125 * How many messages do we queue per peer at most? Must be at
128 #define MAX_PEER_QUEUE_SIZE 16
131 * How many non-mandatory messages do we queue per client at most?
133 #define MAX_CLIENT_QUEUE_SIZE 32
136 * What is the maximum age of a message for us to consider
137 * processing it? Note that this looks at the timestamp used
138 * by the other peer, so clock skew between machines does
139 * come into play here. So this should be picked high enough
140 * so that a little bit of clock skew does not prevent peers
141 * from connecting to us.
143 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
147 * State machine for our P2P encryption handshake. Everyone starts in
148 * "DOWN", if we receive the other peer's key (other peer initiated)
149 * we start in state RECEIVED (since we will immediately send our
150 * own); otherwise we start in SENT. If we get back a PONG from
151 * within either state, we move up to CONFIRMED (the PONG will always
152 * be sent back encrypted with the key we sent to the other peer).
154 enum PeerStateMachine
158 PEER_STATE_KEY_RECEIVED,
159 PEER_STATE_KEY_CONFIRMED
164 * Number of bytes (at the beginning) of "struct EncryptedMessage"
165 * that are NOT encrypted.
167 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t))
171 * Encapsulation for encrypted messages exchanged between
172 * peers. Followed by the actual encrypted data.
174 struct EncryptedMessage
177 * Message type is either CORE_ENCRYPTED_MESSAGE.
179 struct GNUNET_MessageHeader header;
182 * Random value used for IV generation. ENCRYPTED_HEADER_SIZE must
183 * be set to the offset of the *next* field.
185 uint32_t iv_seed GNUNET_PACKED;
188 * Hash of the plaintext (starting at 'sequence_number'), used to
189 * verify message integrity. Everything after this hash (including
190 * this hash itself) will be encrypted.
192 GNUNET_HashCode hmac;
195 * Sequence number, in network byte order. This field
196 * must be the first encrypted/decrypted field and the
197 * first byte that is hashed for the plaintext hash.
199 uint32_t sequence_number GNUNET_PACKED;
202 * Desired bandwidth (how much we should send to this peer / how
203 * much is the sender willing to receive)?
205 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
208 * Timestamp. Used to prevent reply of ancient messages
209 * (recent messages are caught with the sequence number).
211 struct GNUNET_TIME_AbsoluteNBO timestamp;
217 * We're sending an (encrypted) PING to the other peer to check if he
218 * can decrypt. The other peer should respond with a PONG with the
219 * same content, except this time encrypted with the receiver's key.
224 * Message type is CORE_PING.
226 struct GNUNET_MessageHeader header;
234 * Random number chosen to make reply harder.
236 uint32_t challenge GNUNET_PACKED;
239 * Intended target of the PING, used primarily to check
240 * that decryption actually worked.
242 struct GNUNET_PeerIdentity target;
248 * Response to a PING. Includes data from the original PING
249 * plus initial bandwidth quota information.
254 * Message type is CORE_PONG.
256 struct GNUNET_MessageHeader header;
264 * Random number proochosen to make reply harder. Must be
265 * first field after header (this is where we start to encrypt!).
267 uint32_t challenge GNUNET_PACKED;
272 uint32_t reserved GNUNET_PACKED;
275 * Desired bandwidth (how much we should send to this
276 * peer / how much is the sender willing to receive).
278 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
281 * Intended target of the PING, used primarily to check
282 * that decryption actually worked.
284 struct GNUNET_PeerIdentity target;
289 * Message transmitted to set (or update) a session key.
295 * Message type is either CORE_SET_KEY.
297 struct GNUNET_MessageHeader header;
300 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
302 int32_t sender_status GNUNET_PACKED;
305 * Purpose of the signature, will be
306 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
308 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
311 * At what time was this key created?
313 struct GNUNET_TIME_AbsoluteNBO creation_time;
316 * The encrypted session key.
318 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
321 * Who is the intended recipient?
323 struct GNUNET_PeerIdentity target;
326 * Signature of the stuff above (starting at purpose).
328 struct GNUNET_CRYPTO_RsaSignature signature;
334 * Message waiting for transmission. This struct
335 * is followed by the actual content of the message.
341 * We keep messages in a doubly linked list.
343 struct MessageEntry *next;
346 * We keep messages in a doubly linked list.
348 struct MessageEntry *prev;
351 * By when are we supposed to transmit this message?
353 struct GNUNET_TIME_Absolute deadline;
356 * By when are we supposed to transmit this message (after
359 struct GNUNET_TIME_Absolute slack_deadline;
362 * How important is this message to us?
364 unsigned int priority;
367 * If this is a SET_KEY message, what was our connection status when this
368 * message was queued?
370 enum PeerStateMachine sender_status;
373 * Is this a SET_KEY message?
378 * How long is the message? (number of bytes following
379 * the "struct MessageEntry", but not including the
380 * size of "struct MessageEntry" itself!)
385 * Was this message selected for transmission in the
386 * current round? GNUNET_YES or GNUNET_NO.
391 * Did we give this message some slack (delayed sending) previously
392 * (and hence should not give it any more slack)? GNUNET_YES or
403 * We keep neighbours in a linked list (for now).
405 struct Neighbour *next;
408 * Unencrypted messages destined for this peer.
410 struct MessageEntry *messages;
413 * Head of the batched, encrypted message queue (already ordered,
414 * transmit starting with the head).
416 struct MessageEntry *encrypted_head;
419 * Tail of the batched, encrypted message queue (already ordered,
420 * append new messages to tail)
422 struct MessageEntry *encrypted_tail;
425 * Handle for pending requests for transmission to this peer
426 * with the transport service. NULL if no request is pending.
428 struct GNUNET_TRANSPORT_TransmitHandle *th;
431 * Public key of the neighbour, NULL if we don't have it yet.
433 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
436 * We received a PING message before we got the "public_key"
437 * (or the SET_KEY). We keep it here until we have a key
438 * to decrypt it. NULL if no PING is pending.
440 struct PingMessage *pending_ping;
443 * We received a PONG message before we got the "public_key"
444 * (or the SET_KEY). We keep it here until we have a key
445 * to decrypt it. NULL if no PONG is pending.
447 struct PongMessage *pending_pong;
450 * Non-NULL if we are currently looking up HELLOs for this peer.
453 struct GNUNET_PEERINFO_IteratorContext *pitr;
456 * SetKeyMessage to transmit, NULL if we are not currently trying
459 struct SetKeyMessage *skm;
462 * Identity of the neighbour.
464 struct GNUNET_PeerIdentity peer;
467 * Key we use to encrypt our messages for the other peer
468 * (initialized by us when we do the handshake).
470 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
473 * Key we use to decrypt messages from the other peer
474 * (given to us by the other peer during the handshake).
476 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
479 * ID of task used for re-trying plaintext scheduling.
481 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
484 * ID of task used for re-trying SET_KEY and PING message.
486 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
489 * ID of task used for updating bandwidth quota for this neighbour.
491 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
494 * ID of task used for sending keep-alive pings.
496 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
499 * ID of task used for cleaning up dead neighbour entries.
501 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
504 * At what time did we generate our encryption key?
506 struct GNUNET_TIME_Absolute encrypt_key_created;
509 * At what time did the other peer generate the decryption key?
511 struct GNUNET_TIME_Absolute decrypt_key_created;
514 * At what time did we initially establish (as in, complete session
515 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
517 struct GNUNET_TIME_Absolute time_established;
520 * At what time did we last receive an encrypted message from the
521 * other peer? Should be zero if status != KEY_CONFIRMED.
523 struct GNUNET_TIME_Absolute last_activity;
526 * Last latency observed from this peer.
528 struct GNUNET_TIME_Relative last_latency;
531 * At what frequency are we currently re-trying SET_KEY messages?
533 struct GNUNET_TIME_Relative set_key_retry_frequency;
536 * Tracking bandwidth for sending to this peer.
538 struct GNUNET_BANDWIDTH_Tracker available_send_window;
541 * Tracking bandwidth for receiving from this peer.
543 struct GNUNET_BANDWIDTH_Tracker available_recv_window;
546 * How valueable were the messages of this peer recently?
548 unsigned long long current_preference;
551 * Bit map indicating which of the 32 sequence numbers before the last
552 * were received (good for accepting out-of-order packets and
553 * estimating reliability of the connection)
555 unsigned int last_packets_bitmap;
558 * last sequence number received on this connection (highest)
560 uint32_t last_sequence_number_received;
563 * last sequence number transmitted
565 uint32_t last_sequence_number_sent;
568 * Available bandwidth in for this peer (current target).
570 struct GNUNET_BANDWIDTH_Value32NBO bw_in;
573 * Available bandwidth out for this peer (current target).
575 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
578 * Internal bandwidth limit set for this peer (initially typically
579 * set to "-1"). Actual "bw_out" is MIN of
580 * "bpm_out_internal_limit" and "bw_out_external_limit".
582 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
585 * External bandwidth limit set for this peer by the
586 * peer that we are communicating with. "bw_out" is MIN of
587 * "bw_out_internal_limit" and "bw_out_external_limit".
589 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
592 * What was our PING challenge number (for this peer)?
594 uint32_t ping_challenge;
597 * What was the last distance to this peer as reported by the transports?
599 uint32_t last_distance;
602 * What is our connection status?
604 enum PeerStateMachine status;
607 * Are we currently connected to this neighbour?
615 * Data structure for each client connected to the core service.
620 * Clients are kept in a linked list.
625 * Handle for the client with the server API.
627 struct GNUNET_SERVER_Client *client_handle;
630 * Array of the types of messages this peer cares
631 * about (with "tcnt" entries). Allocated as part
632 * of this client struct, do not free!
634 const uint16_t *types;
637 * Options for messages this client cares about,
638 * see GNUNET_CORE_OPTION_ values.
643 * Number of types of incoming messages this client
644 * specifically cares about. Size of the "types" array.
654 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
659 static struct GNUNET_PeerIdentity my_identity;
664 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
669 struct GNUNET_SCHEDULER_Handle *sched;
672 * Handle to peerinfo service.
674 static struct GNUNET_PEERINFO_Handle *peerinfo;
677 * Our message stream tokenizer (for encrypted payload).
679 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
684 const struct GNUNET_CONFIGURATION_Handle *cfg;
689 static struct GNUNET_TRANSPORT_Handle *transport;
692 * Linked list of our clients.
694 static struct Client *clients;
697 * Context for notifications we need to send to our clients.
699 static struct GNUNET_SERVER_NotificationContext *notifier;
702 * We keep neighbours in a linked list (for now).
704 static struct Neighbour *neighbours;
707 * For creating statistics.
709 static struct GNUNET_STATISTICS_Handle *stats;
712 * Sum of all preferences among all neighbours.
714 static unsigned long long preference_sum;
717 * Total number of neighbours we have.
719 static unsigned int neighbour_count;
722 * How much inbound bandwidth are we supposed to be using per second?
723 * FIXME: this value is not used!
725 static unsigned long long bandwidth_target_in_bps;
728 * How much outbound bandwidth are we supposed to be using per second?
730 static unsigned long long bandwidth_target_out_bps;
735 * A preference value for a neighbour was update. Update
736 * the preference sum accordingly.
738 * @param inc how much was a preference value increased?
741 update_preference_sum (unsigned long long inc)
744 unsigned long long os;
747 preference_sum += inc;
748 if (preference_sum >= os)
750 /* overflow! compensate by cutting all values in half! */
755 n->current_preference /= 2;
756 preference_sum += n->current_preference;
759 GNUNET_STATISTICS_set (stats, gettext_noop ("# total peer preference"), preference_sum, GNUNET_NO);
764 * Find the entry for the given neighbour.
766 * @param peer identity of the neighbour
767 * @return NULL if we are not connected, otherwise the
770 static struct Neighbour *
771 find_neighbour (const struct GNUNET_PeerIdentity *peer)
773 struct Neighbour *ret;
776 while ((ret != NULL) &&
777 (0 != memcmp (&ret->peer,
778 peer, sizeof (struct GNUNET_PeerIdentity))))
785 * Send a message to one of our clients.
787 * @param client target for the message
788 * @param msg message to transmit
789 * @param can_drop could this message be dropped if the
790 * client's queue is getting too large?
793 send_to_client (struct Client *client,
794 const struct GNUNET_MessageHeader *msg,
797 #if DEBUG_CORE_CLIENT
798 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
799 "Preparing to send %u bytes of message of type %u to client.\n",
800 (unsigned int) ntohs (msg->size),
801 (unsigned int) ntohs (msg->type));
803 GNUNET_SERVER_notification_context_unicast (notifier,
804 client->client_handle,
811 * Send a message to all of our current clients that have
812 * the right options set.
814 * @param msg message to multicast
815 * @param can_drop can this message be discarded if the queue is too long
816 * @param options mask to use
819 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
828 if (0 != (c->options & options))
830 #if DEBUG_CORE_CLIENT
831 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
832 "Sending message of type %u to client.\n",
833 (unsigned int) ntohs (msg->type));
835 send_to_client (c, msg, can_drop);
843 * Function called by transport telling us that a peer
846 * @param n the peer that changed status
849 handle_peer_status_change (struct Neighbour *n)
851 struct PeerStatusNotifyMessage psnm;
853 if (! n->is_connected)
856 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
857 "Peer `%4s' changed status\n",
858 GNUNET_i2s (&n->peer));
860 psnm.header.size = htons (sizeof (struct PeerStatusNotifyMessage));
861 psnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_STATUS_CHANGE);
862 psnm.distance = htonl (n->last_distance);
863 psnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
864 psnm.timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_add (n->last_activity,
865 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
866 psnm.bandwidth_in = n->bw_in;
867 psnm.bandwidth_out = n->bw_out;
869 send_to_all_clients (&psnm.header,
871 GNUNET_CORE_OPTION_SEND_STATUS_CHANGE);
872 GNUNET_STATISTICS_update (stats,
873 gettext_noop ("# peer status changes"),
879 * Handle CORE_ITERATE_PEERS request.
882 handle_client_iterate_peers (void *cls,
883 struct GNUNET_SERVER_Client *client,
884 const struct GNUNET_MessageHeader *message)
887 struct ConnectNotifyMessage cnm;
888 struct GNUNET_MessageHeader done_msg;
889 struct GNUNET_SERVER_TransmitContext *tc;
891 /* notify new client about existing neighbours */
892 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
893 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
894 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
895 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
896 tc = GNUNET_SERVER_transmit_context_create (client);
900 if (n->status == PEER_STATE_KEY_CONFIRMED)
902 #if DEBUG_CORE_CLIENT
903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
904 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
906 cnm.distance = htonl (n->last_distance);
907 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
909 GNUNET_SERVER_transmit_context_append_message (tc, &cnm.header);
910 /*send_to_client (c, &cnm.header, GNUNET_NO);*/
915 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
916 GNUNET_SERVER_transmit_context_run (tc,
917 GNUNET_TIME_UNIT_FOREVER_REL);
922 * Handle CORE_INIT request.
925 handle_client_init (void *cls,
926 struct GNUNET_SERVER_Client *client,
927 const struct GNUNET_MessageHeader *message)
929 const struct InitMessage *im;
930 struct InitReplyMessage irm;
933 const uint16_t *types;
936 struct ConnectNotifyMessage cnm;
939 #if DEBUG_CORE_CLIENT
940 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
941 "Client connecting to core service with `%s' message\n",
944 /* check that we don't have an entry already */
948 if (client == c->client_handle)
951 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
956 msize = ntohs (message->size);
957 if (msize < sizeof (struct InitMessage))
960 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
963 GNUNET_SERVER_notification_context_add (notifier, client);
964 im = (const struct InitMessage *) message;
965 types = (const uint16_t *) &im[1];
966 msize -= sizeof (struct InitMessage);
967 c = GNUNET_malloc (sizeof (struct Client) + msize);
968 c->client_handle = client;
971 c->tcnt = msize / sizeof (uint16_t);
972 c->types = (const uint16_t *) &c[1];
973 wtypes = (uint16_t *) &c[1];
974 for (i=0;i<c->tcnt;i++)
975 wtypes[i] = ntohs (types[i]);
976 c->options = ntohl (im->options);
977 #if DEBUG_CORE_CLIENT
978 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
979 "Client %p is interested in %u message types\n",
981 (unsigned int) c->tcnt);
983 /* send init reply message */
984 irm.header.size = htons (sizeof (struct InitReplyMessage));
985 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
986 irm.reserved = htonl (0);
987 memcpy (&irm.publicKey,
989 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
990 #if DEBUG_CORE_CLIENT
991 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
992 "Sending `%s' message to client.\n", "INIT_REPLY");
994 send_to_client (c, &irm.header, GNUNET_NO);
995 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
997 /* notify new client about existing neighbours */
998 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
999 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1003 if (n->status == PEER_STATE_KEY_CONFIRMED)
1005 #if DEBUG_CORE_CLIENT
1006 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1007 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
1009 cnm.distance = htonl (n->last_distance);
1010 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
1012 send_to_client (c, &cnm.header, GNUNET_NO);
1017 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1022 * A client disconnected, clean up.
1024 * @param cls closure
1025 * @param client identification of the client
1028 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1031 struct Client *prev;
1035 #if DEBUG_CORE_CLIENT
1036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1037 "Client %p has disconnected from core service.\n",
1044 if (client == pos->client_handle)
1047 clients = pos->next;
1049 prev->next = pos->next;
1056 /* client never sent INIT */
1061 * Handle REQUEST_INFO request.
1064 handle_client_request_info (void *cls,
1065 struct GNUNET_SERVER_Client *client,
1066 const struct GNUNET_MessageHeader *message)
1068 const struct RequestInfoMessage *rcm;
1069 struct Neighbour *n;
1070 struct ConfigurationInfoMessage cim;
1071 int32_t want_reserv;
1073 unsigned long long old_preference;
1074 struct GNUNET_SERVER_TransmitContext *tc;
1076 #if DEBUG_CORE_CLIENT
1077 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1078 "Core service receives `%s' request.\n", "REQUEST_INFO");
1080 rcm = (const struct RequestInfoMessage *) message;
1081 n = find_neighbour (&rcm->peer);
1082 memset (&cim, 0, sizeof (cim));
1085 want_reserv = ntohl (rcm->reserve_inbound);
1086 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1088 n->bw_out_internal_limit = rcm->limit_outbound;
1089 if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1090 n->bw_out_external_limit).value__)
1092 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1093 n->bw_out_external_limit);
1094 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1096 GNUNET_TRANSPORT_set_quota (transport,
1100 GNUNET_TIME_UNIT_FOREVER_REL,
1102 handle_peer_status_change (n);
1105 if (want_reserv < 0)
1107 got_reserv = want_reserv;
1109 else if (want_reserv > 0)
1111 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1112 want_reserv).value == 0)
1113 got_reserv = want_reserv;
1115 got_reserv = 0; /* all or nothing */
1119 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1121 old_preference = n->current_preference;
1122 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1123 if (old_preference > n->current_preference)
1125 /* overflow; cap at maximum value */
1126 n->current_preference = ULLONG_MAX;
1128 update_preference_sum (n->current_preference - old_preference);
1129 #if DEBUG_CORE_QUOTA
1130 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1131 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1133 GNUNET_i2s (&rcm->peer),
1136 cim.reserved_amount = htonl (got_reserv);
1137 cim.bw_in = n->bw_in;
1138 cim.bw_out = n->bw_out;
1139 cim.preference = n->current_preference;
1141 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1142 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1143 cim.peer = rcm->peer;
1145 #if DEBUG_CORE_CLIENT
1146 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1147 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1149 tc = GNUNET_SERVER_transmit_context_create (client);
1150 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1151 GNUNET_SERVER_transmit_context_run (tc,
1152 GNUNET_TIME_UNIT_FOREVER_REL);
1157 * Free the given entry for the neighbour (it has
1158 * already been removed from the list at this point).
1160 * @param n neighbour to free
1163 free_neighbour (struct Neighbour *n)
1165 struct MessageEntry *m;
1168 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1169 "Destroying neighbour entry for peer `%4s'\n",
1170 GNUNET_i2s (&n->peer));
1172 if (n->pitr != NULL)
1174 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1179 GNUNET_free (n->skm);
1182 while (NULL != (m = n->messages))
1184 n->messages = m->next;
1187 while (NULL != (m = n->encrypted_head))
1189 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1196 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1199 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1200 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1201 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1202 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1203 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1204 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1205 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1206 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1207 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1208 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1209 if (n->status == PEER_STATE_KEY_CONFIRMED)
1210 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), -1, GNUNET_NO);
1211 GNUNET_free_non_null (n->public_key);
1212 GNUNET_free_non_null (n->pending_ping);
1213 GNUNET_free_non_null (n->pending_pong);
1219 * Check if we have encrypted messages for the specified neighbour
1220 * pending, and if so, check with the transport about sending them
1223 * @param n neighbour to check.
1225 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1229 * Encrypt size bytes from in and write the result to out. Use the
1230 * key for outbound traffic of the given neighbour.
1232 * @param n neighbour we are sending to
1233 * @param iv initialization vector to use
1234 * @param in ciphertext
1235 * @param out plaintext
1236 * @param size size of in/out
1237 * @return GNUNET_OK on success
1240 do_encrypt (struct Neighbour *n,
1241 const GNUNET_HashCode * iv,
1242 const void *in, void *out, size_t size)
1244 if (size != (uint16_t) size)
1249 GNUNET_assert (size ==
1250 GNUNET_CRYPTO_aes_encrypt (in,
1254 GNUNET_CRYPTO_AesInitializationVector
1256 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1259 "Encrypted %u bytes for `%4s' using key %u\n",
1260 (unsigned int) size,
1261 GNUNET_i2s (&n->peer),
1262 (unsigned int) n->encrypt_key.crc32);
1269 * Consider freeing the given neighbour since we may not need
1270 * to keep it around anymore.
1272 * @param n neighbour to consider discarding
1275 consider_free_neighbour (struct Neighbour *n);
1279 * Task triggered when a neighbour entry is about to time out
1280 * (and we should prevent this by sending a PING).
1282 * @param cls the 'struct Neighbour'
1283 * @param tc scheduler context (not used)
1286 send_keep_alive (void *cls,
1287 const struct GNUNET_SCHEDULER_TaskContext *tc)
1289 struct Neighbour *n = cls;
1290 struct GNUNET_TIME_Relative retry;
1291 struct GNUNET_TIME_Relative left;
1292 struct MessageEntry *me;
1293 struct PingMessage pp;
1294 struct PingMessage *pm;
1296 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1298 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1299 sizeof (struct PingMessage));
1300 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1301 me->priority = PING_PRIORITY;
1302 me->size = sizeof (struct PingMessage);
1303 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1307 pm = (struct PingMessage *) &me[1];
1308 pm->header.size = htons (sizeof (struct PingMessage));
1309 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1310 pp.challenge = htonl (n->ping_challenge);
1311 pp.target = n->peer;
1313 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1314 "Encrypting `%s' message with challenge %u for `%4s' using key %u.\n",
1316 (unsigned int) n->ping_challenge,
1317 GNUNET_i2s (&n->peer),
1318 (unsigned int) n->encrypt_key.crc32);
1321 &n->peer.hashPubKey,
1324 sizeof (struct PingMessage) -
1325 sizeof (struct GNUNET_MessageHeader));
1326 process_encrypted_neighbour_queue (n);
1327 /* reschedule PING job */
1328 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1329 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1330 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1331 MIN_PING_FREQUENCY);
1333 = GNUNET_SCHEDULER_add_delayed (sched,
1342 * Task triggered when a neighbour entry might have gotten stale.
1344 * @param cls the 'struct Neighbour'
1345 * @param tc scheduler context (not used)
1348 consider_free_task (void *cls,
1349 const struct GNUNET_SCHEDULER_TaskContext *tc)
1351 struct Neighbour *n = cls;
1353 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1354 consider_free_neighbour (n);
1359 * Consider freeing the given neighbour since we may not need
1360 * to keep it around anymore.
1362 * @param n neighbour to consider discarding
1365 consider_free_neighbour (struct Neighbour *n)
1367 struct Neighbour *pos;
1368 struct Neighbour *prev;
1369 struct GNUNET_TIME_Relative left;
1371 if ( (n->th != NULL) ||
1372 (n->pitr != NULL) ||
1373 (GNUNET_YES == n->is_connected) )
1374 return; /* no chance */
1376 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1377 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1380 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1381 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1382 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1384 &consider_free_task,
1388 /* actually free the neighbour... */
1397 neighbours = n->next;
1399 prev->next = n->next;
1400 GNUNET_assert (neighbour_count > 0);
1402 GNUNET_STATISTICS_set (stats,
1403 gettext_noop ("# neighbour entries allocated"),
1411 * Function called when the transport service is ready to
1412 * receive an encrypted message for the respective peer
1414 * @param cls neighbour to use message from
1415 * @param size number of bytes we can transmit
1416 * @param buf where to copy the message
1417 * @return number of bytes transmitted
1420 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1422 struct Neighbour *n = cls;
1423 struct MessageEntry *m;
1428 m = n->encrypted_head;
1432 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1433 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1434 GNUNET_i2s (&n->peer));
1438 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1445 GNUNET_assert (size >= m->size);
1446 memcpy (cbuf, &m[1], m->size);
1448 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1451 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1452 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1453 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1455 GNUNET_i2s (&n->peer));
1457 process_encrypted_neighbour_queue (n);
1462 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1463 "Transmission of message of type %u and size %u failed\n",
1464 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1465 (unsigned int) m->size);
1469 consider_free_neighbour (n);
1475 * Check if we have plaintext messages for the specified neighbour
1476 * pending, and if so, consider batching and encrypting them (and
1477 * then trigger processing of the encrypted queue if needed).
1479 * @param n neighbour to check.
1481 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1485 * Check if we have encrypted messages for the specified neighbour
1486 * pending, and if so, check with the transport about sending them
1489 * @param n neighbour to check.
1492 process_encrypted_neighbour_queue (struct Neighbour *n)
1494 struct MessageEntry *m;
1497 return; /* request already pending */
1498 m = n->encrypted_head;
1501 /* encrypted queue empty, try plaintext instead */
1502 process_plaintext_neighbour_queue (n);
1506 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1507 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1508 (unsigned int) m->size,
1509 GNUNET_i2s (&n->peer),
1510 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).
1514 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1517 GNUNET_TIME_absolute_get_remaining
1519 ¬ify_encrypted_transmit_ready,
1523 /* message request too large or duplicate request */
1525 /* discard encrypted message */
1526 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1530 process_encrypted_neighbour_queue (n);
1536 * Decrypt size bytes from in and write the result to out. Use the
1537 * key for inbound traffic of the given neighbour. This function does
1538 * NOT do any integrity-checks on the result.
1540 * @param n neighbour we are receiving from
1541 * @param iv initialization vector to use
1542 * @param in ciphertext
1543 * @param out plaintext
1544 * @param size size of in/out
1545 * @return GNUNET_OK on success
1548 do_decrypt (struct Neighbour *n,
1549 const GNUNET_HashCode * iv,
1550 const void *in, void *out, size_t size)
1552 if (size != (uint16_t) size)
1557 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1558 (n->status != PEER_STATE_KEY_CONFIRMED))
1560 GNUNET_break_op (0);
1561 return GNUNET_SYSERR;
1564 GNUNET_CRYPTO_aes_decrypt (in,
1568 GNUNET_CRYPTO_AesInitializationVector *) iv,
1572 return GNUNET_SYSERR;
1574 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size, GNUNET_NO);
1576 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1577 "Decrypted %u bytes from `%4s' using key %u\n",
1578 (unsigned int) size,
1579 GNUNET_i2s (&n->peer),
1580 (unsigned int) n->decrypt_key.crc32);
1587 * Select messages for transmission. This heuristic uses a combination
1588 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1589 * and priority-based discard (in case no feasible schedule exist) and
1590 * speculative optimization (defer any kind of transmission until
1591 * we either create a batch of significant size, 25% of max, or until
1592 * we are close to a deadline). Furthermore, when scheduling the
1593 * heuristic also packs as many messages into the batch as possible,
1594 * starting with those with the earliest deadline. Yes, this is fun.
1596 * @param n neighbour to select messages from
1597 * @param size number of bytes to select for transmission
1598 * @param retry_time set to the time when we should try again
1599 * (only valid if this function returns zero)
1600 * @return number of bytes selected, or 0 if we decided to
1601 * defer scheduling overall; in that case, retry_time is set.
1604 select_messages (struct Neighbour *n,
1605 size_t size, struct GNUNET_TIME_Relative *retry_time)
1607 struct MessageEntry *pos;
1608 struct MessageEntry *min;
1609 struct MessageEntry *last;
1610 unsigned int min_prio;
1611 struct GNUNET_TIME_Absolute t;
1612 struct GNUNET_TIME_Absolute now;
1613 struct GNUNET_TIME_Relative delta;
1615 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1618 unsigned int queue_size;
1619 int discard_low_prio;
1621 GNUNET_assert (NULL != n->messages);
1622 now = GNUNET_TIME_absolute_get ();
1623 /* last entry in linked list of messages processed */
1625 /* should we remove the entry with the lowest
1626 priority from consideration for scheduling at the
1637 discard_low_prio = GNUNET_YES;
1638 while (GNUNET_YES == discard_low_prio)
1641 min_prio = UINT_MAX;
1642 discard_low_prio = GNUNET_NO;
1643 /* calculate number of bytes available for transmission at time "t" */
1644 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1646 /* how many bytes have we (hypothetically) scheduled so far */
1648 /* maximum time we can wait before transmitting anything
1649 and still make all of our deadlines */
1650 slack = GNUNET_TIME_UNIT_FOREVER_REL;
1652 /* note that we use "*2" here because we want to look
1653 a bit further into the future; much more makes no
1654 sense since new message might be scheduled in the
1656 while ((pos != NULL) && (off < size * 2))
1658 if (pos->do_transmit == GNUNET_YES)
1660 /* already removed from consideration */
1664 if (discard_low_prio == GNUNET_NO)
1666 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1667 if (delta.value > 0)
1669 // FIXME: HUH? Check!
1671 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1674 if (avail < pos->size)
1676 // FIXME: HUH? Check!
1677 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1682 /* update slack, considering both its absolute deadline
1683 and relative deadlines caused by other messages
1684 with their respective load */
1685 slack = GNUNET_TIME_relative_min (slack,
1686 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1688 if (pos->deadline.value <= now.value)
1691 slack = GNUNET_TIME_UNIT_ZERO;
1693 else if (GNUNET_YES == pos->got_slack)
1695 /* should be soon now! */
1696 slack = GNUNET_TIME_relative_min (slack,
1697 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1702 GNUNET_TIME_relative_min (slack,
1703 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1704 pos->got_slack = GNUNET_YES;
1705 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1706 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
1711 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1712 if (pos->priority <= min_prio)
1714 /* update min for discard */
1715 min_prio = pos->priority;
1720 if (discard_low_prio)
1722 GNUNET_assert (min != NULL);
1723 /* remove lowest-priority entry from consideration */
1724 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1728 /* guard against sending "tiny" messages with large headers without
1730 if ( (slack.value > GNUNET_CONSTANTS_MAX_CORK_DELAY.value) &&
1732 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1734 /* less than 25% of message would be filled with deadlines still
1735 being met if we delay by one second or more; so just wait for
1736 more data; but do not wait longer than 1s (since we don't want
1737 to delay messages for a really long time either). */
1738 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
1739 /* reset do_transmit values for next time */
1742 pos->do_transmit = GNUNET_NO;
1746 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1747 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1748 (unsigned long long) retry_time->value,
1750 (unsigned int) size);
1754 /* select marked messages (up to size) for transmission */
1759 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1761 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1765 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1766 "Selecting message of size %u for transmission\n",
1767 (unsigned int) pos->size);
1773 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1774 "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
1775 (unsigned int) pos->size,
1778 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1783 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1784 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1785 (unsigned long long) off, (unsigned long long) tsize,
1786 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
1787 GNUNET_i2s (&n->peer));
1794 * Batch multiple messages into a larger buffer.
1796 * @param n neighbour to take messages from
1797 * @param buf target buffer
1798 * @param size size of buf
1799 * @param deadline set to transmission deadline for the result
1800 * @param retry_time set to the time when we should try again
1801 * (only valid if this function returns zero)
1802 * @param priority set to the priority of the batch
1803 * @return number of bytes written to buf (can be zero)
1806 batch_message (struct Neighbour *n,
1809 struct GNUNET_TIME_Absolute *deadline,
1810 struct GNUNET_TIME_Relative *retry_time,
1811 unsigned int *priority)
1813 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1814 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1815 struct MessageEntry *pos;
1816 struct MessageEntry *prev;
1817 struct MessageEntry *next;
1822 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1823 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1824 if (0 == select_messages (n, size, retry_time))
1827 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1828 "No messages selected, will try again in %llu ms\n",
1833 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1834 ntm->distance = htonl (n->last_distance);
1835 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1836 ntm->peer = n->peer;
1839 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1842 if (GNUNET_YES == pos->do_transmit)
1844 GNUNET_assert (pos->size <= size);
1845 /* do notifications */
1846 /* FIXME: track if we have *any* client that wants
1847 full notifications and only do this if that is
1849 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1851 memcpy (&ntm[1], &pos[1], pos->size);
1852 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1853 sizeof (struct GNUNET_MessageHeader));
1854 send_to_all_clients (&ntm->header,
1856 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1860 /* message too large for 'full' notifications, we do at
1861 least the 'hdr' type */
1864 sizeof (struct GNUNET_MessageHeader));
1866 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1868 send_to_all_clients (&ntm->header,
1870 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1872 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1873 "Encrypting %u bytes with message of type %u and size %u\n",
1875 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
1876 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
1878 /* copy for encrypted transmission */
1879 memcpy (&buf[ret], &pos[1], pos->size);
1882 *priority += pos->priority;
1884 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1885 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1886 (unsigned int) pos->size,
1887 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1889 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1904 "Deadline for message batch is %llu ms\n",
1905 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1912 * Remove messages with deadlines that have long expired from
1915 * @param n neighbour to inspect
1918 discard_expired_messages (struct Neighbour *n)
1920 struct MessageEntry *prev;
1921 struct MessageEntry *next;
1922 struct MessageEntry *pos;
1923 struct GNUNET_TIME_Absolute now;
1924 struct GNUNET_TIME_Relative delta;
1926 now = GNUNET_TIME_absolute_get ();
1932 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1933 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1936 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1937 "Message is %llu ms past due, discarding.\n",
1954 * Signature of the main function of a task.
1956 * @param cls closure
1957 * @param tc context information (why was this task triggered now)
1960 retry_plaintext_processing (void *cls,
1961 const struct GNUNET_SCHEDULER_TaskContext *tc)
1963 struct Neighbour *n = cls;
1965 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1966 process_plaintext_neighbour_queue (n);
1971 * Send our key (and encrypted PING) to the other peer.
1973 * @param n the other peer
1975 static void send_key (struct Neighbour *n);
1978 * Task that will retry "send_key" if our previous attempt failed
1982 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1984 struct Neighbour *n = cls;
1987 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1988 "Retrying key transmission to `%4s'\n",
1989 GNUNET_i2s (&n->peer));
1991 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1992 n->set_key_retry_frequency =
1993 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1999 * Check if we have plaintext messages for the specified neighbour
2000 * pending, and if so, consider batching and encrypting them (and
2001 * then trigger processing of the encrypted queue if needed).
2003 * @param n neighbour to check.
2006 process_plaintext_neighbour_queue (struct Neighbour *n)
2008 char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)]; /* plaintext */
2011 struct EncryptedMessage *em; /* encrypted message */
2012 struct EncryptedMessage *ph; /* plaintext header */
2013 struct MessageEntry *me;
2014 unsigned int priority;
2015 struct GNUNET_TIME_Absolute deadline;
2016 struct GNUNET_TIME_Relative retry_time;
2019 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2021 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
2022 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2026 case PEER_STATE_DOWN:
2029 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2030 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2031 GNUNET_i2s(&n->peer));
2034 case PEER_STATE_KEY_SENT:
2035 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2036 n->retry_set_key_task
2037 = GNUNET_SCHEDULER_add_delayed (sched,
2038 n->set_key_retry_frequency,
2039 &set_key_retry_task, n);
2041 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2042 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2043 GNUNET_i2s(&n->peer));
2046 case PEER_STATE_KEY_RECEIVED:
2047 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2048 n->retry_set_key_task
2049 = GNUNET_SCHEDULER_add_delayed (sched,
2050 n->set_key_retry_frequency,
2051 &set_key_retry_task, n);
2053 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2054 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2055 GNUNET_i2s(&n->peer));
2058 case PEER_STATE_KEY_CONFIRMED:
2059 /* ready to continue */
2062 discard_expired_messages (n);
2063 if (n->messages == NULL)
2066 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2067 "Plaintext message queue for `%4s' is empty.\n",
2068 GNUNET_i2s(&n->peer));
2070 return; /* no pending messages */
2072 if (n->encrypted_head != NULL)
2075 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2076 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2077 GNUNET_i2s(&n->peer));
2079 return; /* wait for messages already encrypted to be
2082 ph = (struct EncryptedMessage *) pbuf;
2083 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2085 used = sizeof (struct EncryptedMessage);
2086 used += batch_message (n,
2088 GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2089 &deadline, &retry_time, &priority);
2090 if (used == sizeof (struct EncryptedMessage))
2093 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2094 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2095 GNUNET_i2s(&n->peer));
2097 /* no messages selected for sending, try again later... */
2098 n->retry_plaintext_task =
2099 GNUNET_SCHEDULER_add_delayed (sched,
2101 &retry_plaintext_processing, n);
2104 #if DEBUG_CORE_QUOTA
2105 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2106 "Sending %u b/s as new limit to peer `%4s'\n",
2107 (unsigned int) ntohl (n->bw_in.value__),
2108 GNUNET_i2s (&n->peer));
2110 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX));
2111 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2112 ph->inbound_bw_limit = n->bw_in;
2113 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2115 /* setup encryption message header */
2116 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2117 me->deadline = deadline;
2118 me->priority = priority;
2120 em = (struct EncryptedMessage *) &me[1];
2121 em->header.size = htons (used);
2122 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2123 em->iv_seed = ph->iv_seed;
2124 esize = used - ENCRYPTED_HEADER_SIZE;
2125 GNUNET_CRYPTO_hmac (&n->encrypt_key,
2126 &ph->sequence_number,
2127 esize - sizeof (GNUNET_HashCode),
2129 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
2131 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2132 "Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
2133 (unsigned int) (esize - sizeof (GNUNET_HashCode)),
2134 GNUNET_h2s (&ph->hmac),
2139 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2140 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2141 (unsigned int) esize,
2142 GNUNET_i2s(&n->peer),
2143 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2145 GNUNET_assert (GNUNET_OK ==
2150 /* append to transmission list */
2151 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2155 process_encrypted_neighbour_queue (n);
2160 * Function that recalculates the bandwidth quota for the
2161 * given neighbour and transmits it to the transport service.
2163 * @param cls neighbour for the quota update
2167 neighbour_quota_update (void *cls,
2168 const struct GNUNET_SCHEDULER_TaskContext *tc);
2172 * Schedule the task that will recalculate the bandwidth
2173 * quota for this peer (and possibly force a disconnect of
2174 * idle peers by calculating a bandwidth of zero).
2177 schedule_quota_update (struct Neighbour *n)
2179 GNUNET_assert (n->quota_update_task ==
2180 GNUNET_SCHEDULER_NO_TASK);
2181 n->quota_update_task
2182 = GNUNET_SCHEDULER_add_delayed (sched,
2183 QUOTA_UPDATE_FREQUENCY,
2184 &neighbour_quota_update,
2190 * Initialize a new 'struct Neighbour'.
2192 * @param pid ID of the new neighbour
2193 * @return handle for the new neighbour
2195 static struct Neighbour *
2196 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2198 struct Neighbour *n;
2199 struct GNUNET_TIME_Absolute now;
2202 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2203 "Creating neighbour entry for peer `%4s'\n",
2206 n = GNUNET_malloc (sizeof (struct Neighbour));
2207 n->next = neighbours;
2210 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2212 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2213 now = GNUNET_TIME_absolute_get ();
2214 n->encrypt_key_created = now;
2215 n->last_activity = now;
2216 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2217 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2218 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2219 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2220 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2221 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2223 neighbour_quota_update (n, NULL);
2224 consider_free_neighbour (n);
2230 * Handle CORE_SEND request.
2233 * @param client the client issuing the request
2234 * @param message the "struct SendMessage"
2237 handle_client_send (void *cls,
2238 struct GNUNET_SERVER_Client *client,
2239 const struct GNUNET_MessageHeader *message)
2241 const struct SendMessage *sm;
2242 struct Neighbour *n;
2243 struct MessageEntry *prev;
2244 struct MessageEntry *pos;
2245 struct MessageEntry *e;
2246 struct MessageEntry *min_prio_entry;
2247 struct MessageEntry *min_prio_prev;
2248 unsigned int min_prio;
2249 unsigned int queue_size;
2252 msize = ntohs (message->size);
2254 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2256 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));
2259 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2262 sm = (const struct SendMessage *) message;
2263 msize -= sizeof (struct SendMessage);
2264 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2266 /* FIXME: should we not allow loopback-injection here? */
2269 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2272 n = find_neighbour (&sm->peer);
2274 n = create_neighbour (&sm->peer);
2276 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2277 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2279 (unsigned int) msize,
2280 GNUNET_i2s (&sm->peer));
2282 /* bound queue size */
2283 discard_expired_messages (n);
2284 min_prio = UINT32_MAX;
2285 min_prio_entry = NULL;
2286 min_prio_prev = NULL;
2292 if (pos->priority <= min_prio)
2294 min_prio_entry = pos;
2295 min_prio_prev = prev;
2296 min_prio = pos->priority;
2302 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2305 if (ntohl(sm->priority) <= min_prio)
2307 /* discard new entry */
2309 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2310 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2312 (unsigned int) MAX_PEER_QUEUE_SIZE,
2313 (unsigned int) msize,
2314 (unsigned int) ntohs (message->type));
2317 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2320 GNUNET_assert (min_prio_entry != NULL);
2321 /* discard "min_prio_entry" */
2323 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2324 "Queue full, discarding existing older request\n");
2326 if (min_prio_prev == NULL)
2327 n->messages = min_prio_entry->next;
2329 min_prio_prev->next = min_prio_entry->next;
2330 GNUNET_free (min_prio_entry);
2334 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2335 "Adding transmission request for `%4s' of size %u to queue\n",
2336 GNUNET_i2s (&sm->peer),
2337 (unsigned int) msize);
2339 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2340 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2341 e->priority = ntohl (sm->priority);
2343 memcpy (&e[1], &sm[1], msize);
2345 /* insert, keep list sorted by deadline */
2348 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2359 /* consider scheduling now */
2360 process_plaintext_neighbour_queue (n);
2362 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2367 * Function called when the transport service is ready to
2368 * receive a message. Only resets 'n->th' to NULL.
2370 * @param cls neighbour to use message from
2371 * @param size number of bytes we can transmit
2372 * @param buf where to copy the message
2373 * @return number of bytes transmitted
2376 notify_transport_connect_done (void *cls, size_t size, void *buf)
2378 struct Neighbour *n = cls;
2380 if (GNUNET_YES != n->is_connected)
2382 /* transport should only call us to transmit a message after
2383 * telling us about a successful connection to the respective peer */
2384 n->th = NULL; /* If this happens because of a timeout, reset n-th so another message may be sent for this peer! */
2386 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Timeout on notify connect!\n");
2393 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2394 _("Failed to connect to `%4s': transport failed to connect\n"),
2395 GNUNET_i2s (&n->peer));
2398 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2399 _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2400 GNUNET_i2s (&n->peer));
2401 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2402 GNUNET_SCHEDULER_cancel (sched,
2403 n->retry_set_key_task);
2404 n->retry_set_key_task = GNUNET_SCHEDULER_add_now (sched,
2405 &set_key_retry_task,
2412 * Handle CORE_REQUEST_CONNECT request.
2415 * @param client the client issuing the request
2416 * @param message the "struct ConnectMessage"
2419 handle_client_request_connect (void *cls,
2420 struct GNUNET_SERVER_Client *client,
2421 const struct GNUNET_MessageHeader *message)
2423 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2424 struct Neighbour *n;
2425 struct GNUNET_TIME_Relative timeout;
2427 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2430 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2433 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2434 n = find_neighbour (&cm->peer);
2436 n = create_neighbour (&cm->peer);
2437 if ( (GNUNET_YES == n->is_connected) ||
2440 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2441 "Core received `%s' request for `%4s', already connected!\n",
2443 GNUNET_i2s (&cm->peer));
2444 return; /* already connected, or at least trying */
2446 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2448 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2449 "Core received `%s' request for `%4s', will try to establish connection\n",
2451 GNUNET_i2s (&cm->peer));
2453 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2454 /* ask transport to connect to the peer */
2455 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2457 sizeof (struct GNUNET_MessageHeader), 0,
2459 ¬ify_transport_connect_done,
2461 GNUNET_break (NULL != n->th);
2466 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2467 * the neighbour's struct and retry send_key. Or, if we did not get a
2468 * HELLO, just do nothing.
2470 * @param cls the 'struct Neighbour' to retry sending the key for
2471 * @param peer the peer for which this is the HELLO
2472 * @param hello HELLO message of that peer
2475 process_hello_retry_send_key (void *cls,
2476 const struct GNUNET_PeerIdentity *peer,
2477 const struct GNUNET_HELLO_Message *hello)
2479 struct Neighbour *n = cls;
2484 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2485 "Entered `%s' and `%s' is NULL!\n",
2486 "process_hello_retry_send_key",
2490 if (n->public_key != NULL)
2492 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2494 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2495 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2497 GNUNET_STATISTICS_update (stats,
2498 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2506 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2507 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
2508 GNUNET_i2s (&n->peer));
2510 GNUNET_STATISTICS_update (stats,
2511 gettext_noop ("# Delayed connecting due to lack of public key"),
2514 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2515 n->retry_set_key_task
2516 = GNUNET_SCHEDULER_add_delayed (sched,
2517 n->set_key_retry_frequency,
2518 &set_key_retry_task, n);
2524 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2525 "Entered `%s' for peer `%4s'\n",
2526 "process_hello_retry_send_key",
2529 if (n->public_key != NULL)
2531 /* already have public key, why are we here? */
2537 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2538 "Received new `%s' message for `%4s', initiating key exchange.\n",
2543 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2544 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2546 GNUNET_STATISTICS_update (stats,
2547 gettext_noop ("# Error extracting public key from HELLO"),
2550 GNUNET_free (n->public_key);
2551 n->public_key = NULL;
2553 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2554 "GNUNET_HELLO_get_key returned awfully\n");
2562 * Send our key (and encrypted PING) to the other peer.
2564 * @param n the other peer
2567 send_key (struct Neighbour *n)
2569 struct MessageEntry *pos;
2570 struct SetKeyMessage *sm;
2571 struct MessageEntry *me;
2572 struct PingMessage pp;
2573 struct PingMessage *pm;
2575 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2577 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2578 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2580 if (n->pitr != NULL)
2583 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2584 "Key exchange in progress with `%4s'.\n",
2585 GNUNET_i2s (&n->peer));
2587 return; /* already in progress */
2589 if (GNUNET_YES != n->is_connected)
2592 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2593 "Not yet connected to peer `%4s'!\n",
2594 GNUNET_i2s (&n->peer));
2598 GNUNET_STATISTICS_update (stats,
2599 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
2602 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2604 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2606 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2607 ¬ify_encrypted_transmit_ready,
2613 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2614 "Asked to perform key exchange with `%4s'.\n",
2615 GNUNET_i2s (&n->peer));
2617 if (n->public_key == NULL)
2619 /* lookup n's public key, then try again */
2621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2622 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2623 GNUNET_i2s (&n->peer));
2625 GNUNET_assert (n->pitr == NULL);
2626 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2628 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2629 &process_hello_retry_send_key, n);
2632 pos = n->encrypted_head;
2635 if (GNUNET_YES == pos->is_setkey)
2637 if (pos->sender_status == n->status)
2640 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2641 "`%s' message for `%4s' queued already\n",
2643 GNUNET_i2s (&n->peer));
2645 goto trigger_processing;
2647 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2652 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2653 "Removing queued `%s' message for `%4s', will create a new one\n",
2655 GNUNET_i2s (&n->peer));
2665 case PEER_STATE_DOWN:
2666 n->status = PEER_STATE_KEY_SENT;
2668 case PEER_STATE_KEY_SENT:
2670 case PEER_STATE_KEY_RECEIVED:
2672 case PEER_STATE_KEY_CONFIRMED:
2680 /* first, set key message */
2681 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2682 sizeof (struct SetKeyMessage) +
2683 sizeof (struct PingMessage));
2684 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2685 me->priority = SET_KEY_PRIORITY;
2686 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
2687 me->is_setkey = GNUNET_YES;
2688 me->got_slack = GNUNET_YES; /* do not defer this one! */
2689 me->sender_status = n->status;
2690 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2694 sm = (struct SetKeyMessage *) &me[1];
2695 sm->header.size = htons (sizeof (struct SetKeyMessage));
2696 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2697 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2698 PEER_STATE_KEY_SENT : n->status));
2700 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2701 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2702 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2703 sizeof (struct GNUNET_PeerIdentity));
2704 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2705 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2706 sm->target = n->peer;
2707 GNUNET_assert (GNUNET_OK ==
2708 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2710 GNUNET_CRYPTO_AesSessionKey),
2712 &sm->encrypted_key));
2713 GNUNET_assert (GNUNET_OK ==
2714 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2716 pm = (struct PingMessage *) &sm[1];
2717 pm->header.size = htons (sizeof (struct PingMessage));
2718 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2719 pp.challenge = htonl (n->ping_challenge);
2720 pp.target = n->peer;
2722 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2723 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u.\n",
2725 (unsigned int) n->ping_challenge,
2726 GNUNET_i2s (&n->peer),
2727 (unsigned int) n->encrypt_key.crc32);
2730 &n->peer.hashPubKey,
2733 sizeof (struct PingMessage) -
2734 sizeof (struct GNUNET_MessageHeader));
2735 GNUNET_STATISTICS_update (stats,
2736 gettext_noop ("# SET_KEY and PING messages created"),
2740 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2741 "Have %llu ms left for `%s' transmission.\n",
2742 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2746 /* trigger queue processing */
2747 process_encrypted_neighbour_queue (n);
2748 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2749 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2750 n->retry_set_key_task
2751 = GNUNET_SCHEDULER_add_delayed (sched,
2752 n->set_key_retry_frequency,
2753 &set_key_retry_task, n);
2758 * We received a SET_KEY message. Validate and update
2759 * our key material and status.
2761 * @param n the neighbour from which we received message m
2762 * @param m the set key message we received
2765 handle_set_key (struct Neighbour *n,
2766 const struct SetKeyMessage *m);
2770 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2771 * the neighbour's struct and retry handling the set_key message. Or,
2772 * if we did not get a HELLO, just free the set key message.
2774 * @param cls pointer to the set key message
2775 * @param peer the peer for which this is the HELLO
2776 * @param hello HELLO message of that peer
2779 process_hello_retry_handle_set_key (void *cls,
2780 const struct GNUNET_PeerIdentity *peer,
2781 const struct GNUNET_HELLO_Message *hello)
2783 struct Neighbour *n = cls;
2784 struct SetKeyMessage *sm = n->skm;
2790 if (n->public_key != NULL)
2793 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2794 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2796 GNUNET_i2s (&n->peer),
2799 handle_set_key (n, sm);
2803 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2804 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
2806 GNUNET_i2s (&n->peer));
2811 if (n->public_key != NULL)
2812 return; /* multiple HELLOs match!? */
2814 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2815 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2817 GNUNET_break_op (0);
2818 GNUNET_free (n->public_key);
2819 n->public_key = NULL;
2825 * We received a PING message. Validate and transmit
2828 * @param n sender of the PING
2829 * @param m the encrypted PING message itself
2832 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2834 struct PingMessage t;
2835 struct PongMessage tx;
2836 struct PongMessage *tp;
2837 struct MessageEntry *me;
2840 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2841 "Core service receives `%s' request from `%4s'.\n",
2842 "PING", GNUNET_i2s (&n->peer));
2846 &my_identity.hashPubKey,
2849 sizeof (struct PingMessage) -
2850 sizeof (struct GNUNET_MessageHeader)))
2853 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2854 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2856 GNUNET_i2s (&t.target),
2857 (unsigned int) ntohl (t.challenge),
2858 (unsigned int) n->decrypt_key.crc32);
2860 GNUNET_STATISTICS_update (stats,
2861 gettext_noop ("# PING messages decrypted"),
2864 if (0 != memcmp (&t.target,
2865 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2867 GNUNET_break_op (0);
2870 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2871 sizeof (struct PongMessage));
2872 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2876 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2877 me->priority = PONG_PRIORITY;
2878 me->size = sizeof (struct PongMessage);
2879 tx.reserved = htonl (0);
2880 tx.inbound_bw_limit = n->bw_in;
2881 tx.challenge = t.challenge;
2882 tx.target = t.target;
2883 tp = (struct PongMessage *) &me[1];
2884 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2885 tp->header.size = htons (sizeof (struct PongMessage));
2887 &my_identity.hashPubKey,
2890 sizeof (struct PongMessage) -
2891 sizeof (struct GNUNET_MessageHeader));
2892 GNUNET_STATISTICS_update (stats,
2893 gettext_noop ("# PONG messages created"),
2897 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2898 "Encrypting `%s' with challenge %u using key %u\n",
2900 (unsigned int) ntohl (t.challenge),
2901 (unsigned int) n->encrypt_key.crc32);
2903 /* trigger queue processing */
2904 process_encrypted_neighbour_queue (n);
2909 * We received a PONG message. Validate and update our status.
2911 * @param n sender of the PONG
2912 * @param m the encrypted PONG message itself
2915 handle_pong (struct Neighbour *n,
2916 const struct PongMessage *m)
2918 struct PongMessage t;
2919 struct ConnectNotifyMessage cnm;
2922 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2923 "Core service receives `%s' response from `%4s'.\n",
2924 "PONG", GNUNET_i2s (&n->peer));
2926 /* mark as garbage, just to be sure */
2927 memset (&t, 255, sizeof (t));
2930 &n->peer.hashPubKey,
2933 sizeof (struct PongMessage) -
2934 sizeof (struct GNUNET_MessageHeader)))
2936 GNUNET_break_op (0);
2939 GNUNET_STATISTICS_update (stats,
2940 gettext_noop ("# PONG messages decrypted"),
2943 if (0 != ntohl (t.reserved))
2945 GNUNET_break_op (0);
2949 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2950 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2952 GNUNET_i2s (&t.target),
2953 (unsigned int) ntohl (t.challenge),
2954 (unsigned int) n->decrypt_key.crc32);
2956 if ((0 != memcmp (&t.target,
2958 sizeof (struct GNUNET_PeerIdentity))) ||
2959 (n->ping_challenge != ntohl (t.challenge)))
2961 /* PONG malformed */
2963 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2964 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2966 GNUNET_i2s (&n->peer),
2967 (unsigned int) n->ping_challenge);
2968 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2969 "Received malformed `%s' received from `%4s' with challenge %u\n",
2970 "PONG", GNUNET_i2s (&t.target),
2971 (unsigned int) ntohl (t.challenge));
2973 GNUNET_break_op (0);
2978 case PEER_STATE_DOWN:
2979 GNUNET_break (0); /* should be impossible */
2981 case PEER_STATE_KEY_SENT:
2982 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2984 case PEER_STATE_KEY_RECEIVED:
2985 GNUNET_STATISTICS_update (stats,
2986 gettext_noop ("# Session keys confirmed via PONG"),
2989 n->status = PEER_STATE_KEY_CONFIRMED;
2990 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2992 n->bw_out_external_limit = t.inbound_bw_limit;
2993 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2994 n->bw_out_internal_limit);
2995 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2997 GNUNET_TRANSPORT_set_quota (transport,
3001 GNUNET_TIME_UNIT_FOREVER_REL,
3005 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3006 "Confirmed key via `%s' message for peer `%4s'\n",
3007 "PONG", GNUNET_i2s (&n->peer));
3009 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3011 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
3012 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3014 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3015 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3016 cnm.distance = htonl (n->last_distance);
3017 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3019 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
3020 process_encrypted_neighbour_queue (n);
3022 case PEER_STATE_KEY_CONFIRMED:
3023 n->last_activity = GNUNET_TIME_absolute_get ();
3024 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3025 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3027 = GNUNET_SCHEDULER_add_delayed (sched,
3028 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3031 handle_peer_status_change (n);
3041 * We received a SET_KEY message. Validate and update
3042 * our key material and status.
3044 * @param n the neighbour from which we received message m
3045 * @param m the set key message we received
3048 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
3050 struct SetKeyMessage *m_cpy;
3051 struct GNUNET_TIME_Absolute t;
3052 struct GNUNET_CRYPTO_AesSessionKey k;
3053 struct PingMessage *ping;
3054 struct PongMessage *pong;
3055 enum PeerStateMachine sender_status;
3058 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3059 "Core service receives `%s' request from `%4s'.\n",
3060 "SET_KEY", GNUNET_i2s (&n->peer));
3062 if (n->public_key == NULL)
3064 if (n->pitr != NULL)
3067 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3068 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3074 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3075 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3077 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3078 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3079 /* lookup n's public key, then try again */
3080 GNUNET_assert (n->skm == NULL);
3082 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3084 GNUNET_TIME_UNIT_MINUTES,
3085 &process_hello_retry_handle_set_key, n);
3086 GNUNET_STATISTICS_update (stats,
3087 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3092 if (0 != memcmp (&m->target,
3094 sizeof (struct GNUNET_PeerIdentity)))
3096 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3097 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3099 GNUNET_i2s (&m->target));
3102 if ((ntohl (m->purpose.size) !=
3103 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3104 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3105 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3106 sizeof (struct GNUNET_PeerIdentity)) ||
3108 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3109 &m->purpose, &m->signature, n->public_key)))
3111 /* invalid signature */
3112 GNUNET_break_op (0);
3115 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3116 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3117 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3118 (t.value < n->decrypt_key_created.value))
3120 /* this could rarely happen due to massive re-ordering of
3121 messages on the network level, but is most likely either
3122 a bug or some adversary messing with us. Report. */
3123 GNUNET_break_op (0);
3127 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3128 "Decrypting key material.\n");
3130 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3133 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3134 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3135 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3137 /* failed to decrypt !? */
3138 GNUNET_break_op (0);
3141 GNUNET_STATISTICS_update (stats,
3142 gettext_noop ("# SET_KEY messages decrypted"),
3146 if (n->decrypt_key_created.value != t.value)
3148 /* fresh key, reset sequence numbers */
3149 n->last_sequence_number_received = 0;
3150 n->last_packets_bitmap = 0;
3151 n->decrypt_key_created = t;
3153 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3156 case PEER_STATE_DOWN:
3157 n->status = PEER_STATE_KEY_RECEIVED;
3159 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3160 "Responding to `%s' with my own key.\n", "SET_KEY");
3164 case PEER_STATE_KEY_SENT:
3165 case PEER_STATE_KEY_RECEIVED:
3166 n->status = PEER_STATE_KEY_RECEIVED;
3167 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3168 (sender_status != PEER_STATE_KEY_CONFIRMED))
3171 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3172 "Responding to `%s' with my own key (other peer has status %u).\n",
3174 (unsigned int) sender_status);
3179 case PEER_STATE_KEY_CONFIRMED:
3180 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3181 (sender_status != PEER_STATE_KEY_CONFIRMED))
3184 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3185 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3187 (unsigned int) sender_status);
3196 if (n->pending_ping != NULL)
3198 ping = n->pending_ping;
3199 n->pending_ping = NULL;
3200 handle_ping (n, ping);
3203 if (n->pending_pong != NULL)
3205 pong = n->pending_pong;
3206 n->pending_pong = NULL;
3207 handle_pong (n, pong);
3214 * Send a P2P message to a client.
3216 * @param sender who sent us the message?
3217 * @param client who should we give the message to?
3218 * @param m contains the message to transmit
3219 * @param msize number of bytes in buf to transmit
3222 send_p2p_message_to_client (struct Neighbour *sender,
3223 struct Client *client,
3224 const void *m, size_t msize)
3226 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3227 struct NotifyTrafficMessage *ntm;
3230 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3231 "Core service passes message from `%4s' of type %u to client.\n",
3232 GNUNET_i2s(&sender->peer),
3233 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3235 ntm = (struct NotifyTrafficMessage *) buf;
3236 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3237 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3238 ntm->distance = htonl (sender->last_distance);
3239 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3240 ntm->peer = sender->peer;
3241 memcpy (&ntm[1], m, msize);
3242 send_to_client (client, &ntm->header, GNUNET_YES);
3247 * Deliver P2P message to interested clients.
3249 * @param cls always NULL
3250 * @param client who sent us the message (struct Neighbour)
3251 * @param m the message
3254 deliver_message (void *cls,
3256 const struct GNUNET_MessageHeader *m)
3258 struct Neighbour *sender = client;
3259 size_t msize = ntohs (m->size);
3261 struct Client *cpos;
3267 type = ntohs (m->type);
3269 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3270 "Received encapsulated message of type %u and size %u from `%4s'\n",
3271 (unsigned int) type,
3273 GNUNET_i2s (&sender->peer));
3275 GNUNET_snprintf (buf,
3277 gettext_noop ("# bytes of messages of type %u received"),
3278 (unsigned int) type);
3279 GNUNET_STATISTICS_set (stats,
3283 dropped = GNUNET_YES;
3285 while (cpos != NULL)
3287 deliver_full = GNUNET_NO;
3288 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3289 deliver_full = GNUNET_YES;
3292 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3294 if (type != cpos->types[tpos])
3296 deliver_full = GNUNET_YES;
3300 if (GNUNET_YES == deliver_full)
3302 send_p2p_message_to_client (sender, cpos, m, msize);
3303 dropped = GNUNET_NO;
3305 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3307 send_p2p_message_to_client (sender, cpos, m,
3308 sizeof (struct GNUNET_MessageHeader));
3312 if (dropped == GNUNET_YES)
3315 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3316 "Message of type %u from `%4s' not delivered to any client.\n",
3317 (unsigned int) type,
3318 GNUNET_i2s (&sender->peer));
3320 GNUNET_STATISTICS_update (stats,
3321 gettext_noop ("# messages not delivered to any client"),
3328 * We received an encrypted message. Decrypt, validate and
3329 * pass on to the appropriate clients.
3332 handle_encrypted_message (struct Neighbour *n,
3333 const struct EncryptedMessage *m)
3335 size_t size = ntohs (m->header.size);
3337 struct EncryptedMessage *pt; /* plaintext */
3340 struct GNUNET_TIME_Absolute t;
3344 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3345 "Core service receives `%s' request from `%4s'.\n",
3346 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3348 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3354 &buf[ENCRYPTED_HEADER_SIZE],
3355 size - ENCRYPTED_HEADER_SIZE))
3357 pt = (struct EncryptedMessage *) buf;
3359 GNUNET_CRYPTO_hmac (&n->decrypt_key,
3360 &pt->sequence_number,
3361 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3363 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3364 "V-Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
3365 (unsigned int) (size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode)),
3369 if (0 != memcmp (&ph,
3371 sizeof (GNUNET_HashCode)))
3373 /* checksum failed */
3374 GNUNET_break_op (0);
3378 /* validate sequence number */
3379 snum = ntohl (pt->sequence_number);
3380 if (n->last_sequence_number_received == snum)
3382 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3383 "Received duplicate message, ignoring.\n");
3384 /* duplicate, ignore */
3385 GNUNET_STATISTICS_set (stats,
3386 gettext_noop ("# bytes dropped (duplicates)"),
3391 if ((n->last_sequence_number_received > snum) &&
3392 (n->last_sequence_number_received - snum > 32))
3394 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3395 "Received ancient out of sequence message, ignoring.\n");
3396 /* ancient out of sequence, ignore */
3397 GNUNET_STATISTICS_set (stats,
3398 gettext_noop ("# bytes dropped (out of sequence)"),
3403 if (n->last_sequence_number_received > snum)
3405 unsigned int rotbit =
3406 1 << (n->last_sequence_number_received - snum - 1);
3407 if ((n->last_packets_bitmap & rotbit) != 0)
3409 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3410 "Received duplicate message, ignoring.\n");
3411 GNUNET_STATISTICS_set (stats,
3412 gettext_noop ("# bytes dropped (duplicates)"),
3415 /* duplicate, ignore */
3418 n->last_packets_bitmap |= rotbit;
3420 if (n->last_sequence_number_received < snum)
3422 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3423 n->last_sequence_number_received = snum;
3426 /* check timestamp */
3427 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3428 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3430 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3432 ("Message received far too old (%llu ms). Content ignored.\n"),
3433 GNUNET_TIME_absolute_get_duration (t).value);
3434 GNUNET_STATISTICS_set (stats,
3435 gettext_noop ("# bytes dropped (ancient message)"),
3441 /* process decrypted message(s) */
3442 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3444 #if DEBUG_CORE_SET_QUOTA
3445 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3446 "Received %u b/s as new inbound limit for peer `%4s'\n",
3447 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3448 GNUNET_i2s (&n->peer));
3450 n->bw_out_external_limit = pt->inbound_bw_limit;
3451 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3452 n->bw_out_internal_limit);
3453 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3455 GNUNET_TRANSPORT_set_quota (transport,
3459 GNUNET_TIME_UNIT_FOREVER_REL,
3462 n->last_activity = GNUNET_TIME_absolute_get ();
3463 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3464 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3466 = GNUNET_SCHEDULER_add_delayed (sched,
3467 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3470 GNUNET_STATISTICS_set (stats,
3471 gettext_noop ("# bytes of payload decrypted"),
3472 size - sizeof (struct EncryptedMessage),
3474 handle_peer_status_change (n);
3475 if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst,
3477 &buf[sizeof (struct EncryptedMessage)],
3478 size - sizeof (struct EncryptedMessage),
3479 GNUNET_YES, GNUNET_NO))
3480 GNUNET_break_op (0);
3485 * Function called by the transport for each received message.
3487 * @param cls closure
3488 * @param peer (claimed) identity of the other peer
3489 * @param message the message
3490 * @param latency estimated latency for communicating with the
3491 * given peer (round-trip)
3492 * @param distance in overlay hops, as given by transport plugin
3495 handle_transport_receive (void *cls,
3496 const struct GNUNET_PeerIdentity *peer,
3497 const struct GNUNET_MessageHeader *message,
3498 struct GNUNET_TIME_Relative latency,
3499 unsigned int distance)
3501 struct Neighbour *n;
3502 struct GNUNET_TIME_Absolute now;
3509 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3510 "Received message of type %u from `%4s', demultiplexing.\n",
3511 (unsigned int) ntohs (message->type),
3514 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3519 n = find_neighbour (peer);
3521 n = create_neighbour (peer);
3522 changed = (latency.value != n->last_latency.value) || (distance != n->last_distance);
3523 n->last_latency = latency;
3524 n->last_distance = distance;
3525 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3526 type = ntohs (message->type);
3527 size = ntohs (message->size);
3530 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3531 if (size != sizeof (struct SetKeyMessage))
3533 GNUNET_break_op (0);
3536 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3537 handle_set_key (n, (const struct SetKeyMessage *) message);
3539 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3540 if (size < sizeof (struct EncryptedMessage) +
3541 sizeof (struct GNUNET_MessageHeader))
3543 GNUNET_break_op (0);
3546 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3547 (n->status != PEER_STATE_KEY_CONFIRMED))
3549 GNUNET_break_op (0);
3552 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3554 case GNUNET_MESSAGE_TYPE_CORE_PING:
3555 if (size != sizeof (struct PingMessage))
3557 GNUNET_break_op (0);
3560 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3561 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3562 (n->status != PEER_STATE_KEY_CONFIRMED))
3565 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3566 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3567 "PING", GNUNET_i2s (&n->peer));
3569 GNUNET_free_non_null (n->pending_ping);
3570 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3571 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3574 handle_ping (n, (const struct PingMessage *) message);
3576 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3577 if (size != sizeof (struct PongMessage))
3579 GNUNET_break_op (0);
3582 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3583 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3584 (n->status != PEER_STATE_KEY_CONFIRMED) )
3587 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3588 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3589 "PONG", GNUNET_i2s (&n->peer));
3591 GNUNET_free_non_null (n->pending_pong);
3592 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3593 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3596 handle_pong (n, (const struct PongMessage *) message);
3599 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3600 _("Unsupported message of type %u received.\n"),
3601 (unsigned int) type);
3604 if (n->status == PEER_STATE_KEY_CONFIRMED)
3606 now = GNUNET_TIME_absolute_get ();
3607 n->last_activity = now;
3608 changed = GNUNET_YES;
3611 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3612 n->time_established = now;
3614 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3615 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3617 = GNUNET_SCHEDULER_add_delayed (sched,
3618 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3623 handle_peer_status_change (n);
3628 * Function that recalculates the bandwidth quota for the
3629 * given neighbour and transmits it to the transport service.
3631 * @param cls neighbour for the quota update
3635 neighbour_quota_update (void *cls,
3636 const struct GNUNET_SCHEDULER_TaskContext *tc)
3638 struct Neighbour *n = cls;
3639 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3642 unsigned long long distributable;
3643 uint64_t need_per_peer;
3644 uint64_t need_per_second;
3647 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3648 "Neighbour quota update calculation running for peer `%4s'\n",
3649 GNUNET_i2s (&n->peer));
3651 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3652 /* calculate relative preference among all neighbours;
3653 divides by a bit more to avoid division by zero AND to
3654 account for possibility of new neighbours joining any time
3655 AND to convert to double... */
3656 if (preference_sum == 0)
3658 pref_rel = 1.0 / (double) neighbour_count;
3662 pref_rel = n->current_preference / preference_sum;
3664 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3665 GNUNET_TIME_UNIT_SECONDS);
3666 need_per_second = need_per_peer * neighbour_count;
3668 if (bandwidth_target_out_bps > need_per_second)
3669 distributable = bandwidth_target_out_bps - need_per_second;
3670 share = distributable * pref_rel;
3671 if (share + need_per_peer > UINT32_MAX)
3672 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
3674 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3675 /* check if we want to disconnect for good due to inactivity */
3676 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3677 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3680 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3681 "Forcing disconnect of `%4s' due to inactivity\n",
3682 GNUNET_i2s (&n->peer));
3684 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3686 #if DEBUG_CORE_QUOTA
3687 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3688 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3689 GNUNET_i2s (&n->peer),
3690 (unsigned int) ntohl (q_in.value__),
3691 bandwidth_target_out_bps,
3692 (unsigned int) ntohl (n->bw_in.value__),
3693 (unsigned int) ntohl (n->bw_out.value__),
3694 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3696 if (n->bw_in.value__ != q_in.value__)
3699 if (GNUNET_YES == n->is_connected)
3700 GNUNET_TRANSPORT_set_quota (transport,
3704 GNUNET_TIME_UNIT_FOREVER_REL,
3706 handle_peer_status_change (n);
3708 schedule_quota_update (n);
3713 * Function called by transport to notify us that
3714 * a peer connected to us (on the network level).
3716 * @param cls closure
3717 * @param peer the peer that connected
3718 * @param latency current latency of the connection
3719 * @param distance in overlay hops, as given by transport plugin
3722 handle_transport_notify_connect (void *cls,
3723 const struct GNUNET_PeerIdentity *peer,
3724 struct GNUNET_TIME_Relative latency,
3725 unsigned int distance)
3727 struct Neighbour *n;
3729 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3734 n = find_neighbour (peer);
3737 if (GNUNET_YES == n->is_connected)
3739 /* duplicate connect notification!? */
3746 n = create_neighbour (peer);
3748 GNUNET_STATISTICS_update (stats,
3749 gettext_noop ("# peers connected (transport)"),
3752 n->is_connected = GNUNET_YES;
3753 n->last_latency = latency;
3754 n->last_distance = distance;
3755 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3758 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3762 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3763 "Received connection from `%4s'.\n",
3764 GNUNET_i2s (&n->peer));
3766 GNUNET_TRANSPORT_set_quota (transport,
3770 GNUNET_TIME_UNIT_FOREVER_REL,
3777 * Function called by transport telling us that a peer
3780 * @param cls closure
3781 * @param peer the peer that disconnected
3784 handle_transport_notify_disconnect (void *cls,
3785 const struct GNUNET_PeerIdentity *peer)
3787 struct DisconnectNotifyMessage cnm;
3788 struct Neighbour *n;
3789 struct GNUNET_TIME_Relative left;
3792 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3793 "Peer `%4s' disconnected from us; received notification from transport.\n", GNUNET_i2s (peer));
3796 n = find_neighbour (peer);
3802 GNUNET_break (n->is_connected);
3803 if (n->status == PEER_STATE_KEY_CONFIRMED)
3805 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3806 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3808 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3810 n->is_connected = GNUNET_NO;
3811 GNUNET_STATISTICS_update (stats,
3812 gettext_noop ("# peers connected (transport)"),
3815 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
3816 GNUNET_SCHEDULER_cancel (sched,
3817 n->dead_clean_task);
3818 left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3819 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
3820 n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (),
3822 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
3823 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
3824 &consider_free_task,
3830 * Last task run during shutdown. Disconnects us from
3834 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3836 struct Neighbour *n;
3840 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3841 "Core service shutting down.\n");
3843 GNUNET_assert (transport != NULL);
3844 GNUNET_TRANSPORT_disconnect (transport);
3846 while (NULL != (n = neighbours))
3848 neighbours = n->next;
3849 GNUNET_assert (neighbour_count > 0);
3853 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
3854 GNUNET_SERVER_notification_context_destroy (notifier);
3856 while (NULL != (c = clients))
3857 handle_client_disconnect (NULL, c->client_handle);
3858 if (my_private_key != NULL)
3859 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3861 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3862 if (peerinfo != NULL)
3863 GNUNET_PEERINFO_disconnect (peerinfo);
3865 GNUNET_SERVER_mst_destroy (mst);
3870 * Initiate core service.
3872 * @param cls closure
3873 * @param s scheduler to use
3874 * @param server the initialized server
3875 * @param c configuration to use
3879 struct GNUNET_SCHEDULER_Handle *s,
3880 struct GNUNET_SERVER_Handle *server,
3881 const struct GNUNET_CONFIGURATION_Handle *c)
3883 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3884 {&handle_client_init, NULL,
3885 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
3886 {&handle_client_request_info, NULL,
3887 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
3888 sizeof (struct RequestInfoMessage)},
3889 {&handle_client_iterate_peers, NULL,
3890 GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
3891 sizeof (struct GNUNET_MessageHeader)},
3892 {&handle_client_send, NULL,
3893 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
3894 {&handle_client_request_connect, NULL,
3895 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
3896 sizeof (struct ConnectMessage)},
3903 /* parse configuration */
3906 GNUNET_CONFIGURATION_get_value_number (c,
3909 &bandwidth_target_in_bps)) ||
3911 GNUNET_CONFIGURATION_get_value_number (c,
3914 &bandwidth_target_out_bps)) ||
3916 GNUNET_CONFIGURATION_get_value_filename (c,
3918 "HOSTKEY", &keyfile)))
3920 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3922 ("Core service is lacking key configuration settings. Exiting.\n"));
3923 GNUNET_SCHEDULER_shutdown (s);
3926 peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
3927 if (NULL == peerinfo)
3929 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3930 _("Could not access PEERINFO service. Exiting.\n"));
3931 GNUNET_SCHEDULER_shutdown (s);
3932 GNUNET_free (keyfile);
3935 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3936 GNUNET_free (keyfile);
3937 if (my_private_key == NULL)
3939 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3940 _("Core service could not access hostkey. Exiting.\n"));
3941 GNUNET_PEERINFO_disconnect (peerinfo);
3942 GNUNET_SCHEDULER_shutdown (s);
3945 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3946 GNUNET_CRYPTO_hash (&my_public_key,
3947 sizeof (my_public_key), &my_identity.hashPubKey);
3948 /* setup notification */
3949 notifier = GNUNET_SERVER_notification_context_create (server,
3951 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3952 /* setup transport connection */
3953 transport = GNUNET_TRANSPORT_connect (sched,
3957 &handle_transport_receive,
3958 &handle_transport_notify_connect,
3959 &handle_transport_notify_disconnect);
3960 GNUNET_assert (NULL != transport);
3961 stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3962 mst = GNUNET_SERVER_mst_create (&deliver_message,
3964 GNUNET_SCHEDULER_add_delayed (sched,
3965 GNUNET_TIME_UNIT_FOREVER_REL,
3966 &cleaning_task, NULL);
3967 /* process client requests */
3968 GNUNET_SERVER_add_handlers (server, handlers);
3969 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3970 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3976 * The main function for the transport service.
3978 * @param argc number of arguments from the command line
3979 * @param argv command line arguments
3980 * @return 0 ok, 1 on error
3983 main (int argc, char *const *argv)
3985 return (GNUNET_OK ==
3986 GNUNET_SERVICE_run (argc,
3989 GNUNET_SERVICE_OPTION_NONE,
3990 &run, NULL)) ? 0 : 1;
3993 /* end of gnunet-service-core.c */