2 This file is part of GNUnet.
3 (C) 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file core/gnunet-service-core.c
23 * @brief high-level P2P messaging
24 * @author Christian Grothoff
26 * Considerations for later:
27 * - check that hostkey used by transport (for HELLOs) is the
28 * same as the hostkey that we are using!
29 * - add code to send PINGs if we are about to time-out otherwise
30 * - optimize lookup (many O(n) list traversals
31 * could ideally be changed to O(1) hash map lookups)
34 #include "gnunet_constants.h"
35 #include "gnunet_util_lib.h"
36 #include "gnunet_hello_lib.h"
37 #include "gnunet_peerinfo_service.h"
38 #include "gnunet_protocols.h"
39 #include "gnunet_signatures.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet_transport_service.h"
45 #define DEBUG_HANDSHAKE GNUNET_NO
47 #define DEBUG_CORE_QUOTA GNUNET_YES
50 * Receive and send buffer windows grow over time. For
51 * how long can 'unused' bandwidth accumulate before we
52 * need to cap it? (specified in seconds).
54 #define MAX_WINDOW_TIME_S (5 * 60)
57 * How many messages do we queue up at most for optional
58 * notifications to a client? (this can cause notifications
59 * about outgoing messages to be dropped).
61 #define MAX_NOTIFY_QUEUE 1024
64 * Minimum bandwidth (out) to assign to any connected peer.
65 * Should be rather low; values larger than DEFAULT_BW_IN_OUT make no
68 #define MIN_BANDWIDTH_PER_PEER GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT
71 * After how much time past the "official" expiration time do
72 * we discard messages? Should not be zero since we may
73 * intentionally defer transmission until close to the deadline
74 * and then may be slightly past the deadline due to inaccuracy
75 * in sleep and our own CPU consumption.
77 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
80 * What is the maximum delay for a SET_KEY message?
82 #define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
85 * How long do we wait for SET_KEY confirmation initially?
87 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 1)
90 * What is the maximum delay for a PING message?
92 #define MAX_PING_DELAY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 2)
95 * What is the maximum delay for a PONG message?
97 #define MAX_PONG_DELAY GNUNET_TIME_relative_multiply (MAX_PING_DELAY, 2)
100 * What is the minimum frequency for a PING message?
102 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
105 * How often do we recalculate bandwidth quotas?
107 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
110 * What is the priority for a SET_KEY message?
112 #define SET_KEY_PRIORITY 0xFFFFFF
115 * What is the priority for a PING message?
117 #define PING_PRIORITY 0xFFFFFF
120 * What is the priority for a PONG message?
122 #define PONG_PRIORITY 0xFFFFFF
125 * How many messages do we queue per peer at most? Must be at
128 #define MAX_PEER_QUEUE_SIZE 16
131 * How many non-mandatory messages do we queue per client at most?
133 #define MAX_CLIENT_QUEUE_SIZE 32
136 * What is the maximum age of a message for us to consider
137 * processing it? Note that this looks at the timestamp used
138 * by the other peer, so clock skew between machines does
139 * come into play here. So this should be picked high enough
140 * so that a little bit of clock skew does not prevent peers
141 * from connecting to us.
143 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
147 * State machine for our P2P encryption handshake. Everyone starts in
148 * "DOWN", if we receive the other peer's key (other peer initiated)
149 * we start in state RECEIVED (since we will immediately send our
150 * own); otherwise we start in SENT. If we get back a PONG from
151 * within either state, we move up to CONFIRMED (the PONG will always
152 * be sent back encrypted with the key we sent to the other peer).
154 enum PeerStateMachine
158 PEER_STATE_KEY_RECEIVED,
159 PEER_STATE_KEY_CONFIRMED
164 * Number of bytes (at the beginning) of "struct EncryptedMessage"
165 * that are NOT encrypted.
167 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t))
171 * Encapsulation for encrypted messages exchanged between
172 * peers. Followed by the actual encrypted data.
174 struct EncryptedMessage
177 * Message type is either CORE_ENCRYPTED_MESSAGE.
179 struct GNUNET_MessageHeader header;
182 * Random value used for IV generation. ENCRYPTED_HEADER_SIZE must
183 * be set to the offset of the *next* field.
185 uint32_t iv_seed GNUNET_PACKED;
188 * Hash of the plaintext (starting at 'sequence_number'), used to
189 * verify message integrity. Everything after this hash (including
190 * this hash itself) will be encrypted.
192 GNUNET_HashCode hmac;
195 * Sequence number, in network byte order. This field
196 * must be the first encrypted/decrypted field and the
197 * first byte that is hashed for the plaintext hash.
199 uint32_t sequence_number GNUNET_PACKED;
202 * Desired bandwidth (how much we should send to this peer / how
203 * much is the sender willing to receive)?
205 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
208 * Timestamp. Used to prevent reply of ancient messages
209 * (recent messages are caught with the sequence number).
211 struct GNUNET_TIME_AbsoluteNBO timestamp;
217 * We're sending an (encrypted) PING to the other peer to check if he
218 * can decrypt. The other peer should respond with a PONG with the
219 * same content, except this time encrypted with the receiver's key.
224 * Message type is CORE_PING.
226 struct GNUNET_MessageHeader header;
231 uint32_t iv_seed GNUNET_PACKED;
234 * Random number chosen to make reply harder.
236 uint32_t challenge GNUNET_PACKED;
239 * Intended target of the PING, used primarily to check
240 * that decryption actually worked.
242 struct GNUNET_PeerIdentity target;
248 * Response to a PING. Includes data from the original PING
249 * plus initial bandwidth quota information.
254 * Message type is CORE_PONG.
256 struct GNUNET_MessageHeader header;
261 uint32_t iv_seed GNUNET_PACKED;
264 * Random number proochosen to make reply harder. Must be
265 * first field after header (this is where we start to encrypt!).
267 uint32_t challenge GNUNET_PACKED;
272 uint32_t reserved GNUNET_PACKED;
275 * Desired bandwidth (how much we should send to this
276 * peer / how much is the sender willing to receive).
278 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
281 * Intended target of the PING, used primarily to check
282 * that decryption actually worked.
284 struct GNUNET_PeerIdentity target;
289 * Message transmitted to set (or update) a session key.
295 * Message type is either CORE_SET_KEY.
297 struct GNUNET_MessageHeader header;
300 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
302 int32_t sender_status GNUNET_PACKED;
305 * Purpose of the signature, will be
306 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
308 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
311 * At what time was this key created?
313 struct GNUNET_TIME_AbsoluteNBO creation_time;
316 * The encrypted session key.
318 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
321 * Who is the intended recipient?
323 struct GNUNET_PeerIdentity target;
326 * Signature of the stuff above (starting at purpose).
328 struct GNUNET_CRYPTO_RsaSignature signature;
334 * Message waiting for transmission. This struct
335 * is followed by the actual content of the message.
341 * We keep messages in a doubly linked list.
343 struct MessageEntry *next;
346 * We keep messages in a doubly linked list.
348 struct MessageEntry *prev;
351 * By when are we supposed to transmit this message?
353 struct GNUNET_TIME_Absolute deadline;
356 * By when are we supposed to transmit this message (after
359 struct GNUNET_TIME_Absolute slack_deadline;
362 * How important is this message to us?
364 unsigned int priority;
367 * If this is a SET_KEY message, what was our connection status when this
368 * message was queued?
370 enum PeerStateMachine sender_status;
373 * Is this a SET_KEY message?
378 * How long is the message? (number of bytes following
379 * the "struct MessageEntry", but not including the
380 * size of "struct MessageEntry" itself!)
385 * Was this message selected for transmission in the
386 * current round? GNUNET_YES or GNUNET_NO.
391 * Did we give this message some slack (delayed sending) previously
392 * (and hence should not give it any more slack)? GNUNET_YES or
403 * We keep neighbours in a linked list (for now).
405 struct Neighbour *next;
408 * Unencrypted messages destined for this peer.
410 struct MessageEntry *messages;
413 * Head of the batched, encrypted message queue (already ordered,
414 * transmit starting with the head).
416 struct MessageEntry *encrypted_head;
419 * Tail of the batched, encrypted message queue (already ordered,
420 * append new messages to tail)
422 struct MessageEntry *encrypted_tail;
425 * Handle for pending requests for transmission to this peer
426 * with the transport service. NULL if no request is pending.
428 struct GNUNET_TRANSPORT_TransmitHandle *th;
431 * Public key of the neighbour, NULL if we don't have it yet.
433 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
436 * We received a PING message before we got the "public_key"
437 * (or the SET_KEY). We keep it here until we have a key
438 * to decrypt it. NULL if no PING is pending.
440 struct PingMessage *pending_ping;
443 * We received a PONG message before we got the "public_key"
444 * (or the SET_KEY). We keep it here until we have a key
445 * to decrypt it. NULL if no PONG is pending.
447 struct PongMessage *pending_pong;
450 * Non-NULL if we are currently looking up HELLOs for this peer.
453 struct GNUNET_PEERINFO_IteratorContext *pitr;
456 * SetKeyMessage to transmit, NULL if we are not currently trying
459 struct SetKeyMessage *skm;
462 * Identity of the neighbour.
464 struct GNUNET_PeerIdentity peer;
467 * Key we use to encrypt our messages for the other peer
468 * (initialized by us when we do the handshake).
470 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
473 * Key we use to decrypt messages from the other peer
474 * (given to us by the other peer during the handshake).
476 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
479 * 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 ((void *) &pm->challenge - (void *) pm));
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;
2126 // GNUNET_CRYPTO_hmac (&n->encrypt_key,
2127 // &ph->sequence_number,
2128 // esize - sizeof (GNUNET_HashCode),
2130 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
2132 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2133 "Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
2134 (unsigned int) (esize - sizeof (GNUNET_HashCode)),
2135 GNUNET_h2s (&ph->hmac),
2140 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2141 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2142 (unsigned int) esize,
2143 GNUNET_i2s(&n->peer),
2144 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
2146 GNUNET_assert (GNUNET_OK ==
2151 /* append to transmission list */
2152 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2156 process_encrypted_neighbour_queue (n);
2161 * Function that recalculates the bandwidth quota for the
2162 * given neighbour and transmits it to the transport service.
2164 * @param cls neighbour for the quota update
2168 neighbour_quota_update (void *cls,
2169 const struct GNUNET_SCHEDULER_TaskContext *tc);
2173 * Schedule the task that will recalculate the bandwidth
2174 * quota for this peer (and possibly force a disconnect of
2175 * idle peers by calculating a bandwidth of zero).
2178 schedule_quota_update (struct Neighbour *n)
2180 GNUNET_assert (n->quota_update_task ==
2181 GNUNET_SCHEDULER_NO_TASK);
2182 n->quota_update_task
2183 = GNUNET_SCHEDULER_add_delayed (sched,
2184 QUOTA_UPDATE_FREQUENCY,
2185 &neighbour_quota_update,
2191 * Initialize a new 'struct Neighbour'.
2193 * @param pid ID of the new neighbour
2194 * @return handle for the new neighbour
2196 static struct Neighbour *
2197 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2199 struct Neighbour *n;
2200 struct GNUNET_TIME_Absolute now;
2203 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2204 "Creating neighbour entry for peer `%4s'\n",
2207 n = GNUNET_malloc (sizeof (struct Neighbour));
2208 n->next = neighbours;
2211 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
2213 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2214 now = GNUNET_TIME_absolute_get ();
2215 n->encrypt_key_created = now;
2216 n->last_activity = now;
2217 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2218 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2219 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2220 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2221 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2222 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2224 neighbour_quota_update (n, NULL);
2225 consider_free_neighbour (n);
2231 * Handle CORE_SEND request.
2234 * @param client the client issuing the request
2235 * @param message the "struct SendMessage"
2238 handle_client_send (void *cls,
2239 struct GNUNET_SERVER_Client *client,
2240 const struct GNUNET_MessageHeader *message)
2242 const struct SendMessage *sm;
2243 struct Neighbour *n;
2244 struct MessageEntry *prev;
2245 struct MessageEntry *pos;
2246 struct MessageEntry *e;
2247 struct MessageEntry *min_prio_entry;
2248 struct MessageEntry *min_prio_prev;
2249 unsigned int min_prio;
2250 unsigned int queue_size;
2253 msize = ntohs (message->size);
2255 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2257 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));
2260 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2263 sm = (const struct SendMessage *) message;
2264 msize -= sizeof (struct SendMessage);
2265 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2267 /* FIXME: should we not allow loopback-injection here? */
2270 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2273 n = find_neighbour (&sm->peer);
2275 n = create_neighbour (&sm->peer);
2277 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2278 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2280 (unsigned int) msize,
2281 GNUNET_i2s (&sm->peer));
2283 /* bound queue size */
2284 discard_expired_messages (n);
2285 min_prio = UINT32_MAX;
2286 min_prio_entry = NULL;
2287 min_prio_prev = NULL;
2293 if (pos->priority <= min_prio)
2295 min_prio_entry = pos;
2296 min_prio_prev = prev;
2297 min_prio = pos->priority;
2303 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2306 if (ntohl(sm->priority) <= min_prio)
2308 /* discard new entry */
2310 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2311 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2313 (unsigned int) MAX_PEER_QUEUE_SIZE,
2314 (unsigned int) msize,
2315 (unsigned int) ntohs (message->type));
2318 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2321 GNUNET_assert (min_prio_entry != NULL);
2322 /* discard "min_prio_entry" */
2324 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2325 "Queue full, discarding existing older request\n");
2327 if (min_prio_prev == NULL)
2328 n->messages = min_prio_entry->next;
2330 min_prio_prev->next = min_prio_entry->next;
2331 GNUNET_free (min_prio_entry);
2335 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2336 "Adding transmission request for `%4s' of size %u to queue\n",
2337 GNUNET_i2s (&sm->peer),
2338 (unsigned int) msize);
2340 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2341 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2342 e->priority = ntohl (sm->priority);
2344 memcpy (&e[1], &sm[1], msize);
2346 /* insert, keep list sorted by deadline */
2349 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2360 /* consider scheduling now */
2361 process_plaintext_neighbour_queue (n);
2363 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2368 * Function called when the transport service is ready to
2369 * receive a message. Only resets 'n->th' to NULL.
2371 * @param cls neighbour to use message from
2372 * @param size number of bytes we can transmit
2373 * @param buf where to copy the message
2374 * @return number of bytes transmitted
2377 notify_transport_connect_done (void *cls, size_t size, void *buf)
2379 struct Neighbour *n = cls;
2381 if (GNUNET_YES != n->is_connected)
2383 /* transport should only call us to transmit a message after
2384 * telling us about a successful connection to the respective peer */
2385 n->th = NULL; /* If this happens because of a timeout, reset n-th so another message may be sent for this peer! */
2387 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Timeout on notify connect!\n");
2394 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2395 _("Failed to connect to `%4s': transport failed to connect\n"),
2396 GNUNET_i2s (&n->peer));
2399 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2400 _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2401 GNUNET_i2s (&n->peer));
2402 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2403 GNUNET_SCHEDULER_cancel (sched,
2404 n->retry_set_key_task);
2405 n->retry_set_key_task = GNUNET_SCHEDULER_add_now (sched,
2406 &set_key_retry_task,
2413 * Handle CORE_REQUEST_CONNECT request.
2416 * @param client the client issuing the request
2417 * @param message the "struct ConnectMessage"
2420 handle_client_request_connect (void *cls,
2421 struct GNUNET_SERVER_Client *client,
2422 const struct GNUNET_MessageHeader *message)
2424 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2425 struct Neighbour *n;
2426 struct GNUNET_TIME_Relative timeout;
2428 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2431 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2434 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2435 n = find_neighbour (&cm->peer);
2437 n = create_neighbour (&cm->peer);
2438 if ( (GNUNET_YES == n->is_connected) ||
2441 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2442 "Core received `%s' request for `%4s', already connected!\n",
2444 GNUNET_i2s (&cm->peer));
2445 return; /* already connected, or at least trying */
2447 GNUNET_STATISTICS_update (stats, gettext_noop ("# connection requests received"), 1, GNUNET_NO);
2449 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2450 "Core received `%s' request for `%4s', will try to establish connection\n",
2452 GNUNET_i2s (&cm->peer));
2454 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2455 /* ask transport to connect to the peer */
2456 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2458 sizeof (struct GNUNET_MessageHeader), 0,
2460 ¬ify_transport_connect_done,
2462 GNUNET_break (NULL != n->th);
2467 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2468 * the neighbour's struct and retry send_key. Or, if we did not get a
2469 * HELLO, just do nothing.
2471 * @param cls the 'struct Neighbour' to retry sending the key for
2472 * @param peer the peer for which this is the HELLO
2473 * @param hello HELLO message of that peer
2476 process_hello_retry_send_key (void *cls,
2477 const struct GNUNET_PeerIdentity *peer,
2478 const struct GNUNET_HELLO_Message *hello)
2480 struct Neighbour *n = cls;
2485 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2486 "Entered `%s' and `%s' is NULL!\n",
2487 "process_hello_retry_send_key",
2491 if (n->public_key != NULL)
2493 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2495 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2496 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2498 GNUNET_STATISTICS_update (stats,
2499 gettext_noop ("# SET_KEY messages deferred (need public key)"),
2507 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2508 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
2509 GNUNET_i2s (&n->peer));
2511 GNUNET_STATISTICS_update (stats,
2512 gettext_noop ("# Delayed connecting due to lack of public key"),
2515 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2516 n->retry_set_key_task
2517 = GNUNET_SCHEDULER_add_delayed (sched,
2518 n->set_key_retry_frequency,
2519 &set_key_retry_task, n);
2525 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2526 "Entered `%s' for peer `%4s'\n",
2527 "process_hello_retry_send_key",
2530 if (n->public_key != NULL)
2532 /* already have public key, why are we here? */
2538 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2539 "Received new `%s' message for `%4s', initiating key exchange.\n",
2544 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2545 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2547 GNUNET_STATISTICS_update (stats,
2548 gettext_noop ("# Error extracting public key from HELLO"),
2551 GNUNET_free (n->public_key);
2552 n->public_key = NULL;
2554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2555 "GNUNET_HELLO_get_key returned awfully\n");
2563 * Send our key (and encrypted PING) to the other peer.
2565 * @param n the other peer
2568 send_key (struct Neighbour *n)
2570 struct MessageEntry *pos;
2571 struct SetKeyMessage *sm;
2572 struct MessageEntry *me;
2573 struct PingMessage pp;
2574 struct PingMessage *pm;
2576 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2578 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2579 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2581 if (n->pitr != NULL)
2584 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2585 "Key exchange in progress with `%4s'.\n",
2586 GNUNET_i2s (&n->peer));
2588 return; /* already in progress */
2590 if (GNUNET_YES != n->is_connected)
2593 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2594 "Not yet connected to peer `%4s'!\n",
2595 GNUNET_i2s (&n->peer));
2599 GNUNET_STATISTICS_update (stats,
2600 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
2603 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2605 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
2607 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2608 ¬ify_encrypted_transmit_ready,
2614 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2615 "Asked to perform key exchange with `%4s'.\n",
2616 GNUNET_i2s (&n->peer));
2618 if (n->public_key == NULL)
2620 /* lookup n's public key, then try again */
2622 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2623 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2624 GNUNET_i2s (&n->peer));
2626 GNUNET_assert (n->pitr == NULL);
2627 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
2629 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2630 &process_hello_retry_send_key, n);
2633 pos = n->encrypted_head;
2636 if (GNUNET_YES == pos->is_setkey)
2638 if (pos->sender_status == n->status)
2641 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2642 "`%s' message for `%4s' queued already\n",
2644 GNUNET_i2s (&n->peer));
2646 goto trigger_processing;
2648 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2653 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2654 "Removing queued `%s' message for `%4s', will create a new one\n",
2656 GNUNET_i2s (&n->peer));
2666 case PEER_STATE_DOWN:
2667 n->status = PEER_STATE_KEY_SENT;
2669 case PEER_STATE_KEY_SENT:
2671 case PEER_STATE_KEY_RECEIVED:
2673 case PEER_STATE_KEY_CONFIRMED:
2681 /* first, set key message */
2682 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2683 sizeof (struct SetKeyMessage) +
2684 sizeof (struct PingMessage));
2685 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2686 me->priority = SET_KEY_PRIORITY;
2687 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
2688 me->is_setkey = GNUNET_YES;
2689 me->got_slack = GNUNET_YES; /* do not defer this one! */
2690 me->sender_status = n->status;
2691 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2695 sm = (struct SetKeyMessage *) &me[1];
2696 sm->header.size = htons (sizeof (struct SetKeyMessage));
2697 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2698 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2699 PEER_STATE_KEY_SENT : n->status));
2701 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2702 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2703 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2704 sizeof (struct GNUNET_PeerIdentity));
2705 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2706 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2707 sm->target = n->peer;
2708 GNUNET_assert (GNUNET_OK ==
2709 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2711 GNUNET_CRYPTO_AesSessionKey),
2713 &sm->encrypted_key));
2714 GNUNET_assert (GNUNET_OK ==
2715 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2717 pm = (struct PingMessage *) &sm[1];
2718 pm->header.size = htons (sizeof (struct PingMessage));
2719 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2720 pp.challenge = htonl (n->ping_challenge);
2721 pp.target = n->peer;
2723 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2724 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u.\n",
2726 (unsigned int) n->ping_challenge,
2727 GNUNET_i2s (&n->peer),
2728 (unsigned int) n->encrypt_key.crc32);
2731 &n->peer.hashPubKey,
2734 sizeof (struct PingMessage) -
2735 ((void *) &pm->challenge - (void *) pm));
2736 GNUNET_STATISTICS_update (stats,
2737 gettext_noop ("# SET_KEY and PING messages created"),
2741 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2742 "Have %llu ms left for `%s' transmission.\n",
2743 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2747 /* trigger queue processing */
2748 process_encrypted_neighbour_queue (n);
2749 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2750 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2751 n->retry_set_key_task
2752 = GNUNET_SCHEDULER_add_delayed (sched,
2753 n->set_key_retry_frequency,
2754 &set_key_retry_task, n);
2759 * We received a SET_KEY message. Validate and update
2760 * our key material and status.
2762 * @param n the neighbour from which we received message m
2763 * @param m the set key message we received
2766 handle_set_key (struct Neighbour *n,
2767 const struct SetKeyMessage *m);
2771 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2772 * the neighbour's struct and retry handling the set_key message. Or,
2773 * if we did not get a HELLO, just free the set key message.
2775 * @param cls pointer to the set key message
2776 * @param peer the peer for which this is the HELLO
2777 * @param hello HELLO message of that peer
2780 process_hello_retry_handle_set_key (void *cls,
2781 const struct GNUNET_PeerIdentity *peer,
2782 const struct GNUNET_HELLO_Message *hello)
2784 struct Neighbour *n = cls;
2785 struct SetKeyMessage *sm = n->skm;
2791 if (n->public_key != NULL)
2794 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2795 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2797 GNUNET_i2s (&n->peer),
2800 handle_set_key (n, sm);
2804 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2805 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
2807 GNUNET_i2s (&n->peer));
2812 if (n->public_key != NULL)
2813 return; /* multiple HELLOs match!? */
2815 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2816 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2818 GNUNET_break_op (0);
2819 GNUNET_free (n->public_key);
2820 n->public_key = NULL;
2826 * We received a PING message. Validate and transmit
2829 * @param n sender of the PING
2830 * @param m the encrypted PING message itself
2833 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2835 struct PingMessage t;
2836 struct PongMessage tx;
2837 struct PongMessage *tp;
2838 struct MessageEntry *me;
2841 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2842 "Core service receives `%s' request from `%4s'.\n",
2843 "PING", GNUNET_i2s (&n->peer));
2847 &my_identity.hashPubKey,
2850 sizeof (struct PingMessage) -
2851 ((void *) &m->challenge - (void *) m)))
2854 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2855 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2857 GNUNET_i2s (&t.target),
2858 (unsigned int) ntohl (t.challenge),
2859 (unsigned int) n->decrypt_key.crc32);
2861 GNUNET_STATISTICS_update (stats,
2862 gettext_noop ("# PING messages decrypted"),
2865 if (0 != memcmp (&t.target,
2866 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2868 GNUNET_break_op (0);
2871 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2872 sizeof (struct PongMessage));
2873 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2877 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2878 me->priority = PONG_PRIORITY;
2879 me->size = sizeof (struct PongMessage);
2880 tx.reserved = htonl (0);
2881 tx.inbound_bw_limit = n->bw_in;
2882 tx.challenge = t.challenge;
2883 tx.target = t.target;
2884 tp = (struct PongMessage *) &me[1];
2885 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2886 tp->header.size = htons (sizeof (struct PongMessage));
2888 &my_identity.hashPubKey,
2891 sizeof (struct PongMessage) -
2892 ((void *) &tp->challenge - (void *) tp));
2893 GNUNET_STATISTICS_update (stats,
2894 gettext_noop ("# PONG messages created"),
2898 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2899 "Encrypting `%s' with challenge %u using key %u\n",
2901 (unsigned int) ntohl (t.challenge),
2902 (unsigned int) n->encrypt_key.crc32);
2904 /* trigger queue processing */
2905 process_encrypted_neighbour_queue (n);
2910 * We received a PONG message. Validate and update our status.
2912 * @param n sender of the PONG
2913 * @param m the encrypted PONG message itself
2916 handle_pong (struct Neighbour *n,
2917 const struct PongMessage *m)
2919 struct PongMessage t;
2920 struct ConnectNotifyMessage cnm;
2923 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2924 "Core service receives `%s' response from `%4s'.\n",
2925 "PONG", GNUNET_i2s (&n->peer));
2927 /* mark as garbage, just to be sure */
2928 memset (&t, 255, sizeof (t));
2931 &n->peer.hashPubKey,
2934 sizeof (struct PongMessage) -
2935 ((void *) &m->challenge - (void *) m)))
2937 GNUNET_break_op (0);
2940 GNUNET_STATISTICS_update (stats,
2941 gettext_noop ("# PONG messages decrypted"),
2944 if (0 != ntohl (t.reserved))
2946 GNUNET_break_op (0);
2950 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2951 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2953 GNUNET_i2s (&t.target),
2954 (unsigned int) ntohl (t.challenge),
2955 (unsigned int) n->decrypt_key.crc32);
2957 if ((0 != memcmp (&t.target,
2959 sizeof (struct GNUNET_PeerIdentity))) ||
2960 (n->ping_challenge != ntohl (t.challenge)))
2962 /* PONG malformed */
2964 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2965 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2967 GNUNET_i2s (&n->peer),
2968 (unsigned int) n->ping_challenge);
2969 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2970 "Received malformed `%s' received from `%4s' with challenge %u\n",
2971 "PONG", GNUNET_i2s (&t.target),
2972 (unsigned int) ntohl (t.challenge));
2974 GNUNET_break_op (0);
2979 case PEER_STATE_DOWN:
2980 GNUNET_break (0); /* should be impossible */
2982 case PEER_STATE_KEY_SENT:
2983 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2985 case PEER_STATE_KEY_RECEIVED:
2986 GNUNET_STATISTICS_update (stats,
2987 gettext_noop ("# Session keys confirmed via PONG"),
2990 n->status = PEER_STATE_KEY_CONFIRMED;
2991 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2993 n->bw_out_external_limit = t.inbound_bw_limit;
2994 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2995 n->bw_out_internal_limit);
2996 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2998 GNUNET_TRANSPORT_set_quota (transport,
3002 GNUNET_TIME_UNIT_FOREVER_REL,
3006 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3007 "Confirmed key via `%s' message for peer `%4s'\n",
3008 "PONG", GNUNET_i2s (&n->peer));
3010 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3012 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
3013 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3015 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3016 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3017 cnm.distance = htonl (n->last_distance);
3018 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3020 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
3021 process_encrypted_neighbour_queue (n);
3023 case PEER_STATE_KEY_CONFIRMED:
3024 n->last_activity = GNUNET_TIME_absolute_get ();
3025 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3026 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3028 = GNUNET_SCHEDULER_add_delayed (sched,
3029 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3032 handle_peer_status_change (n);
3042 * We received a SET_KEY message. Validate and update
3043 * our key material and status.
3045 * @param n the neighbour from which we received message m
3046 * @param m the set key message we received
3049 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
3051 struct SetKeyMessage *m_cpy;
3052 struct GNUNET_TIME_Absolute t;
3053 struct GNUNET_CRYPTO_AesSessionKey k;
3054 struct PingMessage *ping;
3055 struct PongMessage *pong;
3056 enum PeerStateMachine sender_status;
3059 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3060 "Core service receives `%s' request from `%4s'.\n",
3061 "SET_KEY", GNUNET_i2s (&n->peer));
3063 if (n->public_key == NULL)
3065 if (n->pitr != NULL)
3068 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3069 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3075 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3076 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3078 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3079 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3080 /* lookup n's public key, then try again */
3081 GNUNET_assert (n->skm == NULL);
3083 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3085 GNUNET_TIME_UNIT_MINUTES,
3086 &process_hello_retry_handle_set_key, n);
3087 GNUNET_STATISTICS_update (stats,
3088 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3093 if (0 != memcmp (&m->target,
3095 sizeof (struct GNUNET_PeerIdentity)))
3097 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3098 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3100 GNUNET_i2s (&m->target));
3103 if ((ntohl (m->purpose.size) !=
3104 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3105 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3106 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3107 sizeof (struct GNUNET_PeerIdentity)) ||
3109 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3110 &m->purpose, &m->signature, n->public_key)))
3112 /* invalid signature */
3113 GNUNET_break_op (0);
3116 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3117 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3118 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3119 (t.value < n->decrypt_key_created.value))
3121 /* this could rarely happen due to massive re-ordering of
3122 messages on the network level, but is most likely either
3123 a bug or some adversary messing with us. Report. */
3124 GNUNET_break_op (0);
3128 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3129 "Decrypting key material.\n");
3131 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3134 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3135 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3136 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3138 /* failed to decrypt !? */
3139 GNUNET_break_op (0);
3142 GNUNET_STATISTICS_update (stats,
3143 gettext_noop ("# SET_KEY messages decrypted"),
3147 if (n->decrypt_key_created.value != t.value)
3149 /* fresh key, reset sequence numbers */
3150 n->last_sequence_number_received = 0;
3151 n->last_packets_bitmap = 0;
3152 n->decrypt_key_created = t;
3154 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3157 case PEER_STATE_DOWN:
3158 n->status = PEER_STATE_KEY_RECEIVED;
3160 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3161 "Responding to `%s' with my own key.\n", "SET_KEY");
3165 case PEER_STATE_KEY_SENT:
3166 case PEER_STATE_KEY_RECEIVED:
3167 n->status = PEER_STATE_KEY_RECEIVED;
3168 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3169 (sender_status != PEER_STATE_KEY_CONFIRMED))
3172 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3173 "Responding to `%s' with my own key (other peer has status %u).\n",
3175 (unsigned int) sender_status);
3180 case PEER_STATE_KEY_CONFIRMED:
3181 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3182 (sender_status != PEER_STATE_KEY_CONFIRMED))
3185 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3186 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3188 (unsigned int) sender_status);
3197 if (n->pending_ping != NULL)
3199 ping = n->pending_ping;
3200 n->pending_ping = NULL;
3201 handle_ping (n, ping);
3204 if (n->pending_pong != NULL)
3206 pong = n->pending_pong;
3207 n->pending_pong = NULL;
3208 handle_pong (n, pong);
3215 * Send a P2P message to a client.
3217 * @param sender who sent us the message?
3218 * @param client who should we give the message to?
3219 * @param m contains the message to transmit
3220 * @param msize number of bytes in buf to transmit
3223 send_p2p_message_to_client (struct Neighbour *sender,
3224 struct Client *client,
3225 const void *m, size_t msize)
3227 char buf[msize + sizeof (struct NotifyTrafficMessage)];
3228 struct NotifyTrafficMessage *ntm;
3231 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3232 "Core service passes message from `%4s' of type %u to client.\n",
3233 GNUNET_i2s(&sender->peer),
3234 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3236 ntm = (struct NotifyTrafficMessage *) buf;
3237 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
3238 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3239 ntm->distance = htonl (sender->last_distance);
3240 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
3241 ntm->peer = sender->peer;
3242 memcpy (&ntm[1], m, msize);
3243 send_to_client (client, &ntm->header, GNUNET_YES);
3248 * Deliver P2P message to interested clients.
3250 * @param cls always NULL
3251 * @param client who sent us the message (struct Neighbour)
3252 * @param m the message
3255 deliver_message (void *cls,
3257 const struct GNUNET_MessageHeader *m)
3259 struct Neighbour *sender = client;
3260 size_t msize = ntohs (m->size);
3262 struct Client *cpos;
3268 type = ntohs (m->type);
3270 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3271 "Received encapsulated message of type %u and size %u from `%4s'\n",
3272 (unsigned int) type,
3274 GNUNET_i2s (&sender->peer));
3276 GNUNET_snprintf (buf,
3278 gettext_noop ("# bytes of messages of type %u received"),
3279 (unsigned int) type);
3280 GNUNET_STATISTICS_set (stats,
3284 dropped = GNUNET_YES;
3286 while (cpos != NULL)
3288 deliver_full = GNUNET_NO;
3289 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3290 deliver_full = GNUNET_YES;
3293 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3295 if (type != cpos->types[tpos])
3297 deliver_full = GNUNET_YES;
3301 if (GNUNET_YES == deliver_full)
3303 send_p2p_message_to_client (sender, cpos, m, msize);
3304 dropped = GNUNET_NO;
3306 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3308 send_p2p_message_to_client (sender, cpos, m,
3309 sizeof (struct GNUNET_MessageHeader));
3313 if (dropped == GNUNET_YES)
3316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3317 "Message of type %u from `%4s' not delivered to any client.\n",
3318 (unsigned int) type,
3319 GNUNET_i2s (&sender->peer));
3321 GNUNET_STATISTICS_update (stats,
3322 gettext_noop ("# messages not delivered to any client"),
3329 * We received an encrypted message. Decrypt, validate and
3330 * pass on to the appropriate clients.
3333 handle_encrypted_message (struct Neighbour *n,
3334 const struct EncryptedMessage *m)
3336 size_t size = ntohs (m->header.size);
3338 struct EncryptedMessage *pt; /* plaintext */
3341 struct GNUNET_TIME_Absolute t;
3345 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3346 "Core service receives `%s' request from `%4s'.\n",
3347 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3349 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3355 &buf[ENCRYPTED_HEADER_SIZE],
3356 size - ENCRYPTED_HEADER_SIZE))
3358 pt = (struct EncryptedMessage *) buf;
3361 // GNUNET_CRYPTO_hmac (&n->decrypt_key,
3362 // &pt->sequence_number,
3363 // size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3364 //#if DEBUG_HANDSHAKE
3365 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3366 // "V-Hashed %u bytes of plaintext (`%s') using IV `%d'\n",
3367 // (unsigned int) (size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode)),
3368 // GNUNET_h2s (&ph),
3369 // (int) m->iv_seed);
3371 // if (0 != memcmp (&ph,
3373 // sizeof (GNUNET_HashCode)))
3375 // /* checksum failed */
3376 // GNUNET_break_op (0);
3380 /* validate sequence number */
3381 snum = ntohl (pt->sequence_number);
3382 if (n->last_sequence_number_received == snum)
3384 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3385 "Received duplicate message, ignoring.\n");
3386 /* duplicate, ignore */
3387 GNUNET_STATISTICS_set (stats,
3388 gettext_noop ("# bytes dropped (duplicates)"),
3393 if ((n->last_sequence_number_received > snum) &&
3394 (n->last_sequence_number_received - snum > 32))
3396 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3397 "Received ancient out of sequence message, ignoring.\n");
3398 /* ancient out of sequence, ignore */
3399 GNUNET_STATISTICS_set (stats,
3400 gettext_noop ("# bytes dropped (out of sequence)"),
3405 if (n->last_sequence_number_received > snum)
3407 unsigned int rotbit =
3408 1 << (n->last_sequence_number_received - snum - 1);
3409 if ((n->last_packets_bitmap & rotbit) != 0)
3411 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3412 "Received duplicate message, ignoring.\n");
3413 GNUNET_STATISTICS_set (stats,
3414 gettext_noop ("# bytes dropped (duplicates)"),
3417 /* duplicate, ignore */
3420 n->last_packets_bitmap |= rotbit;
3422 if (n->last_sequence_number_received < snum)
3424 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3425 n->last_sequence_number_received = snum;
3428 /* check timestamp */
3429 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3430 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3432 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3434 ("Message received far too old (%llu ms). Content ignored.\n"),
3435 GNUNET_TIME_absolute_get_duration (t).value);
3436 GNUNET_STATISTICS_set (stats,
3437 gettext_noop ("# bytes dropped (ancient message)"),
3443 /* process decrypted message(s) */
3444 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3446 #if DEBUG_CORE_SET_QUOTA
3447 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3448 "Received %u b/s as new inbound limit for peer `%4s'\n",
3449 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3450 GNUNET_i2s (&n->peer));
3452 n->bw_out_external_limit = pt->inbound_bw_limit;
3453 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3454 n->bw_out_internal_limit);
3455 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3457 GNUNET_TRANSPORT_set_quota (transport,
3461 GNUNET_TIME_UNIT_FOREVER_REL,
3464 n->last_activity = GNUNET_TIME_absolute_get ();
3465 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3466 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3468 = GNUNET_SCHEDULER_add_delayed (sched,
3469 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3472 GNUNET_STATISTICS_set (stats,
3473 gettext_noop ("# bytes of payload decrypted"),
3474 size - sizeof (struct EncryptedMessage),
3476 handle_peer_status_change (n);
3477 if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst,
3479 &buf[sizeof (struct EncryptedMessage)],
3480 size - sizeof (struct EncryptedMessage),
3481 GNUNET_YES, GNUNET_NO))
3482 GNUNET_break_op (0);
3487 * Function called by the transport for each received message.
3489 * @param cls closure
3490 * @param peer (claimed) identity of the other peer
3491 * @param message the message
3492 * @param latency estimated latency for communicating with the
3493 * given peer (round-trip)
3494 * @param distance in overlay hops, as given by transport plugin
3497 handle_transport_receive (void *cls,
3498 const struct GNUNET_PeerIdentity *peer,
3499 const struct GNUNET_MessageHeader *message,
3500 struct GNUNET_TIME_Relative latency,
3501 unsigned int distance)
3503 struct Neighbour *n;
3504 struct GNUNET_TIME_Absolute now;
3511 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3512 "Received message of type %u from `%4s', demultiplexing.\n",
3513 (unsigned int) ntohs (message->type),
3516 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3521 n = find_neighbour (peer);
3523 n = create_neighbour (peer);
3524 changed = (latency.value != n->last_latency.value) || (distance != n->last_distance);
3525 n->last_latency = latency;
3526 n->last_distance = distance;
3527 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3528 type = ntohs (message->type);
3529 size = ntohs (message->size);
3532 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3533 if (size != sizeof (struct SetKeyMessage))
3535 GNUNET_break_op (0);
3538 GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"), 1, GNUNET_NO);
3539 handle_set_key (n, (const struct SetKeyMessage *) message);
3541 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3542 if (size < sizeof (struct EncryptedMessage) +
3543 sizeof (struct GNUNET_MessageHeader))
3545 GNUNET_break_op (0);
3548 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3549 (n->status != PEER_STATE_KEY_CONFIRMED))
3551 GNUNET_break_op (0);
3554 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3556 case GNUNET_MESSAGE_TYPE_CORE_PING:
3557 if (size != sizeof (struct PingMessage))
3559 GNUNET_break_op (0);
3562 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
3563 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3564 (n->status != PEER_STATE_KEY_CONFIRMED))
3567 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3568 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3569 "PING", GNUNET_i2s (&n->peer));
3571 GNUNET_free_non_null (n->pending_ping);
3572 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3573 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3576 handle_ping (n, (const struct PingMessage *) message);
3578 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3579 if (size != sizeof (struct PongMessage))
3581 GNUNET_break_op (0);
3584 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
3585 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3586 (n->status != PEER_STATE_KEY_CONFIRMED) )
3589 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3590 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3591 "PONG", GNUNET_i2s (&n->peer));
3593 GNUNET_free_non_null (n->pending_pong);
3594 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3595 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3598 handle_pong (n, (const struct PongMessage *) message);
3601 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3602 _("Unsupported message of type %u received.\n"),
3603 (unsigned int) type);
3606 if (n->status == PEER_STATE_KEY_CONFIRMED)
3608 now = GNUNET_TIME_absolute_get ();
3609 n->last_activity = now;
3610 changed = GNUNET_YES;
3613 GNUNET_STATISTICS_update (stats, gettext_noop ("# established sessions"), 1, GNUNET_NO);
3614 n->time_established = now;
3616 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3617 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3619 = GNUNET_SCHEDULER_add_delayed (sched,
3620 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3625 handle_peer_status_change (n);
3630 * Function that recalculates the bandwidth quota for the
3631 * given neighbour and transmits it to the transport service.
3633 * @param cls neighbour for the quota update
3637 neighbour_quota_update (void *cls,
3638 const struct GNUNET_SCHEDULER_TaskContext *tc)
3640 struct Neighbour *n = cls;
3641 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3644 unsigned long long distributable;
3645 uint64_t need_per_peer;
3646 uint64_t need_per_second;
3649 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3650 "Neighbour quota update calculation running for peer `%4s'\n",
3651 GNUNET_i2s (&n->peer));
3653 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3654 /* calculate relative preference among all neighbours;
3655 divides by a bit more to avoid division by zero AND to
3656 account for possibility of new neighbours joining any time
3657 AND to convert to double... */
3658 if (preference_sum == 0)
3660 pref_rel = 1.0 / (double) neighbour_count;
3664 pref_rel = n->current_preference / preference_sum;
3666 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3667 GNUNET_TIME_UNIT_SECONDS);
3668 need_per_second = need_per_peer * neighbour_count;
3670 if (bandwidth_target_out_bps > need_per_second)
3671 distributable = bandwidth_target_out_bps - need_per_second;
3672 share = distributable * pref_rel;
3673 if (share + need_per_peer > UINT32_MAX)
3674 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
3676 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3677 /* check if we want to disconnect for good due to inactivity */
3678 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3679 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3682 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3683 "Forcing disconnect of `%4s' due to inactivity\n",
3684 GNUNET_i2s (&n->peer));
3686 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3688 #if DEBUG_CORE_QUOTA
3689 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3690 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3691 GNUNET_i2s (&n->peer),
3692 (unsigned int) ntohl (q_in.value__),
3693 bandwidth_target_out_bps,
3694 (unsigned int) ntohl (n->bw_in.value__),
3695 (unsigned int) ntohl (n->bw_out.value__),
3696 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3698 if (n->bw_in.value__ != q_in.value__)
3701 if (GNUNET_YES == n->is_connected)
3702 GNUNET_TRANSPORT_set_quota (transport,
3706 GNUNET_TIME_UNIT_FOREVER_REL,
3708 handle_peer_status_change (n);
3710 schedule_quota_update (n);
3715 * Function called by transport to notify us that
3716 * a peer connected to us (on the network level).
3718 * @param cls closure
3719 * @param peer the peer that connected
3720 * @param latency current latency of the connection
3721 * @param distance in overlay hops, as given by transport plugin
3724 handle_transport_notify_connect (void *cls,
3725 const struct GNUNET_PeerIdentity *peer,
3726 struct GNUNET_TIME_Relative latency,
3727 unsigned int distance)
3729 struct Neighbour *n;
3731 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3736 n = find_neighbour (peer);
3739 if (GNUNET_YES == n->is_connected)
3741 /* duplicate connect notification!? */
3748 n = create_neighbour (peer);
3750 GNUNET_STATISTICS_update (stats,
3751 gettext_noop ("# peers connected (transport)"),
3754 n->is_connected = GNUNET_YES;
3755 n->last_latency = latency;
3756 n->last_distance = distance;
3757 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3760 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3764 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3765 "Received connection from `%4s'.\n",
3766 GNUNET_i2s (&n->peer));
3768 GNUNET_TRANSPORT_set_quota (transport,
3772 GNUNET_TIME_UNIT_FOREVER_REL,
3779 * Function called by transport telling us that a peer
3782 * @param cls closure
3783 * @param peer the peer that disconnected
3786 handle_transport_notify_disconnect (void *cls,
3787 const struct GNUNET_PeerIdentity *peer)
3789 struct DisconnectNotifyMessage cnm;
3790 struct Neighbour *n;
3791 struct GNUNET_TIME_Relative left;
3794 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3795 "Peer `%4s' disconnected from us; received notification from transport.\n", GNUNET_i2s (peer));
3798 n = find_neighbour (peer);
3804 GNUNET_break (n->is_connected);
3805 if (n->status == PEER_STATE_KEY_CONFIRMED)
3807 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3808 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3810 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3812 n->is_connected = GNUNET_NO;
3813 GNUNET_STATISTICS_update (stats,
3814 gettext_noop ("# peers connected (transport)"),
3817 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
3818 GNUNET_SCHEDULER_cancel (sched,
3819 n->dead_clean_task);
3820 left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3821 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
3822 n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (),
3824 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
3825 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
3826 &consider_free_task,
3832 * Last task run during shutdown. Disconnects us from
3836 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3838 struct Neighbour *n;
3842 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3843 "Core service shutting down.\n");
3845 GNUNET_assert (transport != NULL);
3846 GNUNET_TRANSPORT_disconnect (transport);
3848 while (NULL != (n = neighbours))
3850 neighbours = n->next;
3851 GNUNET_assert (neighbour_count > 0);
3855 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), neighbour_count, GNUNET_NO);
3856 GNUNET_SERVER_notification_context_destroy (notifier);
3858 while (NULL != (c = clients))
3859 handle_client_disconnect (NULL, c->client_handle);
3860 if (my_private_key != NULL)
3861 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3863 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3864 if (peerinfo != NULL)
3865 GNUNET_PEERINFO_disconnect (peerinfo);
3867 GNUNET_SERVER_mst_destroy (mst);
3872 * Initiate core service.
3874 * @param cls closure
3875 * @param s scheduler to use
3876 * @param server the initialized server
3877 * @param c configuration to use
3881 struct GNUNET_SCHEDULER_Handle *s,
3882 struct GNUNET_SERVER_Handle *server,
3883 const struct GNUNET_CONFIGURATION_Handle *c)
3885 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3886 {&handle_client_init, NULL,
3887 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
3888 {&handle_client_request_info, NULL,
3889 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
3890 sizeof (struct RequestInfoMessage)},
3891 {&handle_client_iterate_peers, NULL,
3892 GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
3893 sizeof (struct GNUNET_MessageHeader)},
3894 {&handle_client_send, NULL,
3895 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
3896 {&handle_client_request_connect, NULL,
3897 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
3898 sizeof (struct ConnectMessage)},
3905 /* parse configuration */
3908 GNUNET_CONFIGURATION_get_value_number (c,
3911 &bandwidth_target_in_bps)) ||
3913 GNUNET_CONFIGURATION_get_value_number (c,
3916 &bandwidth_target_out_bps)) ||
3918 GNUNET_CONFIGURATION_get_value_filename (c,
3920 "HOSTKEY", &keyfile)))
3922 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3924 ("Core service is lacking key configuration settings. Exiting.\n"));
3925 GNUNET_SCHEDULER_shutdown (s);
3928 peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
3929 if (NULL == peerinfo)
3931 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3932 _("Could not access PEERINFO service. Exiting.\n"));
3933 GNUNET_SCHEDULER_shutdown (s);
3934 GNUNET_free (keyfile);
3937 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3938 GNUNET_free (keyfile);
3939 if (my_private_key == NULL)
3941 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3942 _("Core service could not access hostkey. Exiting.\n"));
3943 GNUNET_PEERINFO_disconnect (peerinfo);
3944 GNUNET_SCHEDULER_shutdown (s);
3947 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3948 GNUNET_CRYPTO_hash (&my_public_key,
3949 sizeof (my_public_key), &my_identity.hashPubKey);
3950 /* setup notification */
3951 notifier = GNUNET_SERVER_notification_context_create (server,
3953 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3954 /* setup transport connection */
3955 transport = GNUNET_TRANSPORT_connect (sched,
3959 &handle_transport_receive,
3960 &handle_transport_notify_connect,
3961 &handle_transport_notify_disconnect);
3962 GNUNET_assert (NULL != transport);
3963 stats = GNUNET_STATISTICS_create (sched, "core", cfg);
3964 mst = GNUNET_SERVER_mst_create (&deliver_message,
3966 GNUNET_SCHEDULER_add_delayed (sched,
3967 GNUNET_TIME_UNIT_FOREVER_REL,
3968 &cleaning_task, NULL);
3969 /* process client requests */
3970 GNUNET_SERVER_add_handlers (server, handlers);
3971 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3972 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3978 * The main function for the transport service.
3980 * @param argc number of arguments from the command line
3981 * @param argv command line arguments
3982 * @return 0 ok, 1 on error
3985 main (int argc, char *const *argv)
3987 return (GNUNET_OK ==
3988 GNUNET_SERVICE_run (argc,
3991 GNUNET_SERVICE_OPTION_NONE,
3992 &run, NULL)) ? 0 : 1;
3995 /* end of gnunet-service-core.c */