2 This file is part of GNUnet.
3 (C) 2009 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file core/gnunet-service-core.c
23 * @brief high-level P2P messaging
24 * @author Christian Grothoff
26 * Considerations for later:
27 * - check that hostkey used by transport (for HELLOs) is the
28 * same as the hostkey that we are using!
29 * - add code to send PINGs if we are about to time-out otherwise
30 * - optimize lookup (many O(n) list traversals
31 * could ideally be changed to O(1) hash map lookups)
34 #include "gnunet_constants.h"
35 #include "gnunet_util_lib.h"
36 #include "gnunet_hello_lib.h"
37 #include "gnunet_peerinfo_service.h"
38 #include "gnunet_protocols.h"
39 #include "gnunet_signatures.h"
40 #include "gnunet_transport_service.h"
44 #define DEBUG_HANDSHAKE GNUNET_NO
46 #define DEBUG_CORE_QUOTA GNUNET_NO
49 * Receive and send buffer windows grow over time. For
50 * how long can 'unused' bandwidth accumulate before we
51 * need to cap it? (specified in seconds).
53 #define MAX_WINDOW_TIME_S (5 * 60)
56 * How many messages do we queue up at most for optional
57 * notifications to a client? (this can cause notifications
58 * about outgoing messages to be dropped).
60 #define MAX_NOTIFY_QUEUE 16
63 * Minimum bandwidth (out) to assign to any connected peer.
64 * Should be rather low; values larger than DEFAULT_BW_IN_OUT make no
67 #define MIN_BANDWIDTH_PER_PEER GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT
70 * After how much time past the "official" expiration time do
71 * we discard messages? Should not be zero since we may
72 * intentionally defer transmission until close to the deadline
73 * and then may be slightly past the deadline due to inaccuracy
74 * in sleep and our own CPU consumption.
76 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
79 * How long do we delay messages to get larger packet sizes (CORKing)?
81 #define MAX_CORK_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
84 * What is the maximum delay for a SET_KEY message?
86 #define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
89 * What how long do we wait for SET_KEY confirmation initially?
91 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 3)
94 * What is the maximum delay for a PING message?
96 #define MAX_PING_DELAY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 2)
99 * What is the maximum delay for a PONG message?
101 #define MAX_PONG_DELAY GNUNET_TIME_relative_multiply (MAX_PING_DELAY, 2)
104 * What is the minimum frequency for a PING message?
106 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
109 * How often do we recalculate bandwidth quotas?
111 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
114 * What is the priority for a SET_KEY message?
116 #define SET_KEY_PRIORITY 0xFFFFFF
119 * What is the priority for a PING message?
121 #define PING_PRIORITY 0xFFFFFF
124 * What is the priority for a PONG message?
126 #define PONG_PRIORITY 0xFFFFFF
129 * How many messages do we queue per peer at most? Must be at
132 #define MAX_PEER_QUEUE_SIZE 16
135 * How many non-mandatory messages do we queue per client at most?
137 #define MAX_CLIENT_QUEUE_SIZE 32
140 * What is the maximum age of a message for us to consider
141 * processing it? Note that this looks at the timestamp used
142 * by the other peer, so clock skew between machines does
143 * come into play here. So this should be picked high enough
144 * so that a little bit of clock skew does not prevent peers
145 * from connecting to us.
147 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
150 * What is the maximum size for encrypted messages? Note that this
151 * number imposes a clear limit on the maximum size of any message.
152 * Set to a value close to 64k but not so close that transports will
153 * have trouble with their headers.
155 #define MAX_ENCRYPTED_MESSAGE_SIZE (63 * 1024)
159 * State machine for our P2P encryption handshake. Everyone starts in
160 * "DOWN", if we receive the other peer's key (other peer initiated)
161 * we start in state RECEIVED (since we will immediately send our
162 * own); otherwise we start in SENT. If we get back a PONG from
163 * within either state, we move up to CONFIRMED (the PONG will always
164 * be sent back encrypted with the key we sent to the other peer).
166 enum PeerStateMachine
170 PEER_STATE_KEY_RECEIVED,
171 PEER_STATE_KEY_CONFIRMED
176 * Number of bytes (at the beginning) of "struct EncryptedMessage"
177 * that are NOT encrypted.
179 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t))
183 * Encapsulation for encrypted messages exchanged between
184 * peers. Followed by the actual encrypted data.
186 struct EncryptedMessage
189 * Message type is either CORE_ENCRYPTED_MESSAGE.
191 struct GNUNET_MessageHeader header;
194 * Random value used for IV generation. ENCRYPTED_HEADER_SIZE must
195 * be set to the offset of the *next* field.
197 uint32_t iv_seed GNUNET_PACKED;
200 * Hash of the plaintext (starting at 'sequence_number'), used to
201 * verify message integrity. Everything after this hash (including
202 * this hash itself) will be encrypted.
204 GNUNET_HashCode plaintext_hash;
207 * Sequence number, in network byte order. This field
208 * must be the first encrypted/decrypted field and the
209 * first byte that is hashed for the plaintext hash.
211 uint32_t sequence_number GNUNET_PACKED;
214 * Desired bandwidth (how much we should send to this peer / how
215 * much is the sender willing to receive)?
217 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
220 * Timestamp. Used to prevent reply of ancient messages
221 * (recent messages are caught with the sequence number).
223 struct GNUNET_TIME_AbsoluteNBO timestamp;
229 * We're sending an (encrypted) PING to the other peer to check if he
230 * can decrypt. The other peer should respond with a PONG with the
231 * same content, except this time encrypted with the receiver's key.
236 * Message type is CORE_PING.
238 struct GNUNET_MessageHeader header;
241 * Random number chosen to make reply harder.
243 uint32_t challenge GNUNET_PACKED;
246 * Intended target of the PING, used primarily to check
247 * that decryption actually worked.
249 struct GNUNET_PeerIdentity target;
255 * Response to a PING. Includes data from the original PING
256 * plus initial bandwidth quota information.
261 * Message type is CORE_PONG.
263 struct GNUNET_MessageHeader header;
266 * Random number proochosen to make reply harder. Must be
267 * first field after header (this is where we start to encrypt!).
269 uint32_t challenge GNUNET_PACKED;
274 uint32_t reserved GNUNET_PACKED;
277 * Desired bandwidth (how much we should send to this
278 * peer / how much is the sender willing to receive).
280 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
283 * Intended target of the PING, used primarily to check
284 * that decryption actually worked.
286 struct GNUNET_PeerIdentity target;
291 * Message transmitted to set (or update) a session key.
297 * Message type is either CORE_SET_KEY.
299 struct GNUNET_MessageHeader header;
302 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
304 int32_t sender_status GNUNET_PACKED;
307 * Purpose of the signature, will be
308 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
310 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
313 * At what time was this key created?
315 struct GNUNET_TIME_AbsoluteNBO creation_time;
318 * The encrypted session key.
320 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
323 * Who is the intended recipient?
325 struct GNUNET_PeerIdentity target;
328 * Signature of the stuff above (starting at purpose).
330 struct GNUNET_CRYPTO_RsaSignature signature;
336 * Message waiting for transmission. This struct
337 * is followed by the actual content of the message.
343 * We keep messages in a doubly linked list.
345 struct MessageEntry *next;
348 * We keep messages in a doubly linked list.
350 struct MessageEntry *prev;
353 * By when are we supposed to transmit this message?
355 struct GNUNET_TIME_Absolute deadline;
358 * By when are we supposed to transmit this message (after
361 struct GNUNET_TIME_Absolute slack_deadline;
364 * How important is this message to us?
366 unsigned int priority;
369 * How long is the message? (number of bytes following
370 * the "struct MessageEntry", but not including the
371 * size of "struct MessageEntry" itself!)
376 * Was this message selected for transmission in the
377 * current round? GNUNET_YES or GNUNET_NO.
382 * Did we give this message some slack (delayed sending) previously
383 * (and hence should not give it any more slack)? GNUNET_YES or
394 * We keep neighbours in a linked list (for now).
396 struct Neighbour *next;
399 * Unencrypted messages destined for this peer.
401 struct MessageEntry *messages;
404 * Head of the batched, encrypted message queue (already ordered,
405 * transmit starting with the head).
407 struct MessageEntry *encrypted_head;
410 * Tail of the batched, encrypted message queue (already ordered,
411 * append new messages to tail)
413 struct MessageEntry *encrypted_tail;
416 * Handle for pending requests for transmission to this peer
417 * with the transport service. NULL if no request is pending.
419 struct GNUNET_TRANSPORT_TransmitHandle *th;
422 * Public key of the neighbour, NULL if we don't have it yet.
424 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
427 * We received a PING message before we got the "public_key"
428 * (or the SET_KEY). We keep it here until we have a key
429 * to decrypt it. NULL if no PING is pending.
431 struct PingMessage *pending_ping;
434 * We received a PONG message before we got the "public_key"
435 * (or the SET_KEY). We keep it here until we have a key
436 * to decrypt it. NULL if no PONG is pending.
438 struct PongMessage *pending_pong;
441 * Non-NULL if we are currently looking up HELLOs for this peer.
444 struct GNUNET_PEERINFO_IteratorContext *pitr;
447 * SetKeyMessage to transmit, NULL if we are not currently trying
450 struct SetKeyMessage *skm;
453 * Identity of the neighbour.
455 struct GNUNET_PeerIdentity peer;
458 * Key we use to encrypt our messages for the other peer
459 * (initialized by us when we do the handshake).
461 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
464 * Key we use to decrypt messages from the other peer
465 * (given to us by the other peer during the handshake).
467 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
470 * ID of task used for re-trying plaintext scheduling.
472 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
475 * ID of task used for re-trying SET_KEY and PING message.
477 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
480 * ID of task used for updating bandwidth quota for this neighbour.
482 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
485 * ID of task used for sending keep-alive pings.
487 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
490 * ID of task used for cleaning up dead neighbour entries.
492 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
495 * At what time did we generate our encryption key?
497 struct GNUNET_TIME_Absolute encrypt_key_created;
500 * At what time did the other peer generate the decryption key?
502 struct GNUNET_TIME_Absolute decrypt_key_created;
505 * At what time did we initially establish (as in, complete session
506 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
508 struct GNUNET_TIME_Absolute time_established;
511 * At what time did we last receive an encrypted message from the
512 * other peer? Should be zero if status != KEY_CONFIRMED.
514 struct GNUNET_TIME_Absolute last_activity;
517 * Last latency observed from this peer.
519 struct GNUNET_TIME_Relative last_latency;
522 * At what frequency are we currently re-trying SET_KEY messages?
524 struct GNUNET_TIME_Relative set_key_retry_frequency;
527 * Tracking bandwidth for sending to this peer.
529 struct GNUNET_BANDWIDTH_Tracker available_send_window;
532 * Tracking bandwidth for receiving from this peer.
534 struct GNUNET_BANDWIDTH_Tracker available_recv_window;
537 * How valueable were the messages of this peer recently?
539 unsigned long long current_preference;
542 * Bit map indicating which of the 32 sequence numbers before the last
543 * were received (good for accepting out-of-order packets and
544 * estimating reliability of the connection)
546 unsigned int last_packets_bitmap;
549 * last sequence number received on this connection (highest)
551 uint32_t last_sequence_number_received;
554 * last sequence number transmitted
556 uint32_t last_sequence_number_sent;
559 * Available bandwidth in for this peer (current target).
561 struct GNUNET_BANDWIDTH_Value32NBO bw_in;
564 * Available bandwidth out for this peer (current target).
566 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
569 * Internal bandwidth limit set for this peer (initially typically
570 * set to "-1"). Actual "bw_out" is MIN of
571 * "bpm_out_internal_limit" and "bw_out_external_limit".
573 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
576 * External bandwidth limit set for this peer by the
577 * peer that we are communicating with. "bw_out" is MIN of
578 * "bw_out_internal_limit" and "bw_out_external_limit".
580 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
583 * What was our PING challenge number (for this peer)?
585 uint32_t ping_challenge;
588 * What was the last distance to this peer as reported by the transports?
590 uint32_t last_distance;
593 * What is our connection status?
595 enum PeerStateMachine status;
598 * Are we currently connected to this neighbour?
606 * Data structure for each client connected to the core service.
611 * Clients are kept in a linked list.
616 * Handle for the client with the server API.
618 struct GNUNET_SERVER_Client *client_handle;
621 * Array of the types of messages this peer cares
622 * about (with "tcnt" entries). Allocated as part
623 * of this client struct, do not free!
625 const uint16_t *types;
628 * Options for messages this client cares about,
629 * see GNUNET_CORE_OPTION_ values.
634 * Number of types of incoming messages this client
635 * specifically cares about. Size of the "types" array.
645 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
650 static struct GNUNET_PeerIdentity my_identity;
655 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
660 struct GNUNET_SCHEDULER_Handle *sched;
665 const struct GNUNET_CONFIGURATION_Handle *cfg;
670 static struct GNUNET_SERVER_Handle *server;
675 static struct GNUNET_TRANSPORT_Handle *transport;
678 * Linked list of our clients.
680 static struct Client *clients;
683 * Context for notifications we need to send to our clients.
685 static struct GNUNET_SERVER_NotificationContext *notifier;
688 * We keep neighbours in a linked list (for now).
690 static struct Neighbour *neighbours;
693 * Sum of all preferences among all neighbours.
695 static unsigned long long preference_sum;
698 * Total number of neighbours we have.
700 static unsigned int neighbour_count;
703 * How much inbound bandwidth are we supposed to be using per second?
704 * FIXME: this value is not used!
706 static unsigned long long bandwidth_target_in_bps;
709 * How much outbound bandwidth are we supposed to be using per second?
711 static unsigned long long bandwidth_target_out_bps;
716 * A preference value for a neighbour was update. Update
717 * the preference sum accordingly.
719 * @param inc how much was a preference value increased?
722 update_preference_sum (unsigned long long inc)
725 unsigned long long os;
728 preference_sum += inc;
729 if (preference_sum >= os)
731 /* overflow! compensate by cutting all values in half! */
736 n->current_preference /= 2;
737 preference_sum += n->current_preference;
744 * Find the entry for the given neighbour.
746 * @param peer identity of the neighbour
747 * @return NULL if we are not connected, otherwise the
750 static struct Neighbour *
751 find_neighbour (const struct GNUNET_PeerIdentity *peer)
753 struct Neighbour *ret;
756 while ((ret != NULL) &&
757 (0 != memcmp (&ret->peer,
758 peer, sizeof (struct GNUNET_PeerIdentity))))
765 * Send a message to one of our clients.
767 * @param client target for the message
768 * @param msg message to transmit
769 * @param can_drop could this message be dropped if the
770 * client's queue is getting too large?
773 send_to_client (struct Client *client,
774 const struct GNUNET_MessageHeader *msg,
777 #if DEBUG_CORE_CLIENT
778 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
779 "Preparing to send message of type %u to client.\n",
782 GNUNET_SERVER_notification_context_unicast (notifier,
783 client->client_handle,
790 * Send a message to all of our current clients that have
791 * the right options set.
793 * @param msg message to multicast
794 * @param can_drop can this message be discarded if the queue is too long
795 * @param options mask to use
798 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
807 if (0 != (c->options & options))
808 send_to_client (c, msg, can_drop);
815 * Handle CORE_INIT request.
818 handle_client_init (void *cls,
819 struct GNUNET_SERVER_Client *client,
820 const struct GNUNET_MessageHeader *message)
822 const struct InitMessage *im;
823 struct InitReplyMessage irm;
826 const uint16_t *types;
829 struct ConnectNotifyMessage cnm;
832 #if DEBUG_CORE_CLIENT
833 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
834 "Client connecting to core service with `%s' message\n",
837 /* check that we don't have an entry already */
841 if (client == c->client_handle)
844 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
849 msize = ntohs (message->size);
850 if (msize < sizeof (struct InitMessage))
853 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
856 GNUNET_SERVER_notification_context_add (notifier, client);
857 im = (const struct InitMessage *) message;
858 types = (const uint16_t *) &im[1];
859 msize -= sizeof (struct InitMessage);
860 c = GNUNET_malloc (sizeof (struct Client) + msize);
861 c->client_handle = client;
864 c->tcnt = msize / sizeof (uint16_t);
865 c->types = (const uint16_t *) &c[1];
866 wtypes = (uint16_t *) &c[1];
867 for (i=0;i<c->tcnt;i++)
868 wtypes[i] = ntohs (types[i]);
869 c->options = ntohl (im->options);
870 #if DEBUG_CORE_CLIENT
871 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
872 "Client %p is interested in %u message types\n",
876 /* send init reply message */
877 irm.header.size = htons (sizeof (struct InitReplyMessage));
878 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
879 irm.reserved = htonl (0);
880 memcpy (&irm.publicKey,
882 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
883 #if DEBUG_CORE_CLIENT
884 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
885 "Sending `%s' message to client.\n", "INIT_REPLY");
887 send_to_client (c, &irm.header, GNUNET_NO);
888 if (c->options & GNUNET_CORE_OPTION_SEND_CONNECT)
890 /* notify new client about existing neighbours */
891 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
892 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
896 if (n->status == PEER_STATE_KEY_CONFIRMED)
898 #if DEBUG_CORE_CLIENT
899 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
900 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
902 cnm.distance = htonl (n->last_distance);
903 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
905 send_to_client (c, &cnm.header, GNUNET_NO);
910 GNUNET_SERVER_receive_done (client, GNUNET_OK);
915 * A client disconnected, clean up.
918 * @param client identification of the client
921 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
928 #if DEBUG_CORE_CLIENT
929 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
930 "Client %p has disconnected from core service.\n",
937 if (client == pos->client_handle)
942 prev->next = pos->next;
949 /* client never sent INIT */
954 * Handle REQUEST_INFO request.
957 handle_client_request_info (void *cls,
958 struct GNUNET_SERVER_Client *client,
959 const struct GNUNET_MessageHeader *message)
961 const struct RequestInfoMessage *rcm;
963 struct ConfigurationInfoMessage cim;
966 unsigned long long old_preference;
967 struct GNUNET_SERVER_TransmitContext *tc;
969 #if DEBUG_CORE_CLIENT
970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
971 "Core service receives `%s' request.\n", "REQUEST_INFO");
973 rcm = (const struct RequestInfoMessage *) message;
974 n = find_neighbour (&rcm->peer);
975 memset (&cim, 0, sizeof (cim));
978 want_reserv = ntohl (rcm->reserve_inbound);
979 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
981 n->bw_out_internal_limit = rcm->limit_outbound;
982 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
983 n->bw_out_external_limit);
984 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
986 GNUNET_TRANSPORT_set_quota (transport,
990 GNUNET_TIME_UNIT_FOREVER_REL,
995 got_reserv = want_reserv;
997 else if (want_reserv > 0)
999 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1000 want_reserv).value == 0)
1001 got_reserv = want_reserv;
1003 got_reserv = 0; /* all or nothing */
1007 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1009 old_preference = n->current_preference;
1010 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1011 if (old_preference > n->current_preference)
1013 /* overflow; cap at maximum value */
1014 n->current_preference = (unsigned long long) -1;
1016 update_preference_sum (n->current_preference - old_preference);
1017 #if DEBUG_CORE_QUOTA
1018 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1019 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1021 GNUNET_i2s (&rcm->peer),
1024 cim.reserved_amount = htonl (got_reserv);
1025 cim.bw_in = n->bw_in;
1026 cim.bw_out = n->bw_out;
1027 cim.preference = n->current_preference;
1029 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1030 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1031 cim.peer = rcm->peer;
1033 #if DEBUG_CORE_CLIENT
1034 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1035 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1037 tc = GNUNET_SERVER_transmit_context_create (client);
1038 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1039 GNUNET_SERVER_transmit_context_run (tc,
1040 GNUNET_TIME_UNIT_FOREVER_REL);
1045 * Free the given entry for the neighbour (it has
1046 * already been removed from the list at this point).
1048 * @param n neighbour to free
1051 free_neighbour (struct Neighbour *n)
1053 struct MessageEntry *m;
1055 if (n->pitr != NULL)
1057 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1062 GNUNET_free (n->skm);
1065 while (NULL != (m = n->messages))
1067 n->messages = m->next;
1070 while (NULL != (m = n->encrypted_head))
1072 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1079 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1082 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1083 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1084 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1085 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1086 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1087 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1088 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1089 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1090 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1091 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1092 GNUNET_free_non_null (n->public_key);
1093 GNUNET_free_non_null (n->pending_ping);
1094 GNUNET_free_non_null (n->pending_pong);
1100 * Check if we have encrypted messages for the specified neighbour
1101 * pending, and if so, check with the transport about sending them
1104 * @param n neighbour to check.
1106 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1110 * Encrypt size bytes from in and write the result to out. Use the
1111 * key for outbound traffic of the given neighbour.
1113 * @param n neighbour we are sending to
1114 * @param iv initialization vector to use
1115 * @param in ciphertext
1116 * @param out plaintext
1117 * @param size size of in/out
1118 * @return GNUNET_OK on success
1121 do_encrypt (struct Neighbour *n,
1122 const GNUNET_HashCode * iv,
1123 const void *in, void *out, size_t size)
1125 if (size != (uint16_t) size)
1130 GNUNET_assert (size ==
1131 GNUNET_CRYPTO_aes_encrypt (in,
1135 GNUNET_CRYPTO_AesInitializationVector
1138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1139 "Encrypted %u bytes for `%4s' using key %u\n", size,
1140 GNUNET_i2s (&n->peer), n->encrypt_key.crc32);
1147 * Consider freeing the given neighbour since we may not need
1148 * to keep it around anymore.
1150 * @param n neighbour to consider discarding
1153 consider_free_neighbour (struct Neighbour *n);
1157 * Task triggered when a neighbour entry is about to time out
1158 * (and we should prevent this by sending a PING).
1160 * @param cls the 'struct Neighbour'
1161 * @param tc scheduler context (not used)
1164 send_keep_alive (void *cls,
1165 const struct GNUNET_SCHEDULER_TaskContext *tc)
1167 struct Neighbour *n = cls;
1168 struct GNUNET_TIME_Relative retry;
1169 struct GNUNET_TIME_Relative left;
1170 struct MessageEntry *me;
1171 struct PingMessage pp;
1172 struct PingMessage *pm;
1174 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1176 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1177 sizeof (struct PingMessage));
1178 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1179 me->priority = PING_PRIORITY;
1180 me->size = sizeof (struct PingMessage);
1181 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1185 pm = (struct PingMessage *) &me[1];
1186 pm->header.size = htons (sizeof (struct PingMessage));
1187 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1188 pp.challenge = htonl (n->ping_challenge);
1189 pp.target = n->peer;
1191 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1192 "Encrypting `%s' and `%s' messages for `%4s'.\n",
1193 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
1194 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1195 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
1197 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
1200 &n->peer.hashPubKey,
1203 sizeof (struct PingMessage) -
1204 sizeof (struct GNUNET_MessageHeader));
1205 process_encrypted_neighbour_queue (n);
1206 /* reschedule PING job */
1207 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1208 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1209 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1210 MIN_PING_FREQUENCY);
1212 = GNUNET_SCHEDULER_add_delayed (sched,
1221 * Task triggered when a neighbour entry might have gotten stale.
1223 * @param cls the 'struct Neighbour'
1224 * @param tc scheduler context (not used)
1227 consider_free_task (void *cls,
1228 const struct GNUNET_SCHEDULER_TaskContext *tc)
1230 struct Neighbour *n = cls;
1232 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1233 consider_free_neighbour (n);
1238 * Consider freeing the given neighbour since we may not need
1239 * to keep it around anymore.
1241 * @param n neighbour to consider discarding
1244 consider_free_neighbour (struct Neighbour *n)
1246 struct Neighbour *pos;
1247 struct Neighbour *prev;
1248 struct GNUNET_TIME_Relative left;
1250 if ( (n->th != NULL) ||
1251 (n->pitr != NULL) ||
1252 (n->status == PEER_STATE_KEY_CONFIRMED) ||
1253 (GNUNET_YES == n->is_connected) )
1254 return; /* no chance */
1256 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1257 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1260 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1261 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1262 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1264 &consider_free_task,
1268 /* actually free the neighbour... */
1277 neighbours = n->next;
1279 prev->next = n->next;
1280 GNUNET_assert (neighbour_count > 0);
1287 * Function called when the transport service is ready to
1288 * receive an encrypted message for the respective peer
1290 * @param cls neighbour to use message from
1291 * @param size number of bytes we can transmit
1292 * @param buf where to copy the message
1293 * @return number of bytes transmitted
1296 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1298 struct Neighbour *n = cls;
1299 struct MessageEntry *m;
1304 GNUNET_assert (NULL != (m = n->encrypted_head));
1305 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1312 GNUNET_assert (size >= m->size);
1313 memcpy (cbuf, &m[1], m->size);
1315 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1318 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1319 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1320 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1321 ret, GNUNET_i2s (&n->peer));
1323 process_encrypted_neighbour_queue (n);
1328 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1329 "Transmission of message of type %u and size %u failed\n",
1330 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1335 consider_free_neighbour (n);
1341 * Check if we have plaintext messages for the specified neighbour
1342 * pending, and if so, consider batching and encrypting them (and
1343 * then trigger processing of the encrypted queue if needed).
1345 * @param n neighbour to check.
1347 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1351 * Check if we have encrypted messages for the specified neighbour
1352 * pending, and if so, check with the transport about sending them
1355 * @param n neighbour to check.
1358 process_encrypted_neighbour_queue (struct Neighbour *n)
1360 struct MessageEntry *m;
1363 return; /* request already pending */
1364 m = n->encrypted_head;
1367 /* encrypted queue empty, try plaintext instead */
1368 process_plaintext_neighbour_queue (n);
1372 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1373 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1375 GNUNET_i2s (&n->peer),
1376 GNUNET_TIME_absolute_get_remaining (m->deadline).
1380 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1383 GNUNET_TIME_absolute_get_remaining
1385 ¬ify_encrypted_transmit_ready,
1389 /* message request too large or duplicate request */
1391 /* discard encrypted message */
1392 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1396 process_encrypted_neighbour_queue (n);
1402 * Decrypt size bytes from in and write the result to out. Use the
1403 * key for inbound traffic of the given neighbour. This function does
1404 * NOT do any integrity-checks on the result.
1406 * @param n neighbour we are receiving from
1407 * @param iv initialization vector to use
1408 * @param in ciphertext
1409 * @param out plaintext
1410 * @param size size of in/out
1411 * @return GNUNET_OK on success
1414 do_decrypt (struct Neighbour *n,
1415 const GNUNET_HashCode * iv,
1416 const void *in, void *out, size_t size)
1418 if (size != (uint16_t) size)
1423 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1424 (n->status != PEER_STATE_KEY_CONFIRMED))
1426 GNUNET_break_op (0);
1427 return GNUNET_SYSERR;
1430 GNUNET_CRYPTO_aes_decrypt (in,
1434 GNUNET_CRYPTO_AesInitializationVector *) iv,
1438 return GNUNET_SYSERR;
1441 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1442 "Decrypted %u bytes from `%4s' using key %u\n",
1443 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1450 * Select messages for transmission. This heuristic uses a combination
1451 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1452 * and priority-based discard (in case no feasible schedule exist) and
1453 * speculative optimization (defer any kind of transmission until
1454 * we either create a batch of significant size, 25% of max, or until
1455 * we are close to a deadline). Furthermore, when scheduling the
1456 * heuristic also packs as many messages into the batch as possible,
1457 * starting with those with the earliest deadline. Yes, this is fun.
1459 * @param n neighbour to select messages from
1460 * @param size number of bytes to select for transmission
1461 * @param retry_time set to the time when we should try again
1462 * (only valid if this function returns zero)
1463 * @return number of bytes selected, or 0 if we decided to
1464 * defer scheduling overall; in that case, retry_time is set.
1467 select_messages (struct Neighbour *n,
1468 size_t size, struct GNUNET_TIME_Relative *retry_time)
1470 struct MessageEntry *pos;
1471 struct MessageEntry *min;
1472 struct MessageEntry *last;
1473 unsigned int min_prio;
1474 struct GNUNET_TIME_Absolute t;
1475 struct GNUNET_TIME_Absolute now;
1476 struct GNUNET_TIME_Relative delta;
1478 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1481 unsigned int queue_size;
1482 int discard_low_prio;
1484 GNUNET_assert (NULL != n->messages);
1485 now = GNUNET_TIME_absolute_get ();
1486 /* last entry in linked list of messages processed */
1488 /* should we remove the entry with the lowest
1489 priority from consideration for scheduling at the
1500 discard_low_prio = GNUNET_YES;
1501 while (GNUNET_YES == discard_low_prio)
1505 discard_low_prio = GNUNET_NO;
1506 /* calculate number of bytes available for transmission at time "t" */
1507 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1509 /* how many bytes have we (hypothetically) scheduled so far */
1511 /* maximum time we can wait before transmitting anything
1512 and still make all of our deadlines */
1513 slack = MAX_CORK_DELAY;
1515 /* note that we use "*2" here because we want to look
1516 a bit further into the future; much more makes no
1517 sense since new message might be scheduled in the
1519 while ((pos != NULL) && (off < size * 2))
1521 if (pos->do_transmit == GNUNET_YES)
1523 /* already removed from consideration */
1527 if (discard_low_prio == GNUNET_NO)
1529 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1530 if (delta.value > 0)
1532 // FIXME: HUH? Check!
1534 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1537 if (avail < pos->size)
1539 // FIXME: HUH? Check!
1540 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1545 /* update slack, considering both its absolute deadline
1546 and relative deadlines caused by other messages
1547 with their respective load */
1548 slack = GNUNET_TIME_relative_min (slack,
1549 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1551 if (pos->deadline.value <= now.value)
1554 slack = GNUNET_TIME_UNIT_ZERO;
1556 else if (GNUNET_YES == pos->got_slack)
1558 /* should be soon now! */
1559 slack = GNUNET_TIME_relative_min (slack,
1560 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1565 GNUNET_TIME_relative_min (slack,
1566 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1567 pos->got_slack = GNUNET_YES;
1568 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1569 GNUNET_TIME_relative_to_absolute (MAX_CORK_DELAY));
1574 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1575 if (pos->priority <= min_prio)
1577 /* update min for discard */
1578 min_prio = pos->priority;
1583 if (discard_low_prio)
1585 GNUNET_assert (min != NULL);
1586 /* remove lowest-priority entry from consideration */
1587 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1591 /* guard against sending "tiny" messages with large headers without
1593 if ( (slack.value > 0) &&
1595 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1597 /* less than 25% of message would be filled with deadlines still
1598 being met if we delay by one second or more; so just wait for
1599 more data; but do not wait longer than 1s (since we don't want
1600 to delay messages for a really long time either). */
1601 *retry_time = MAX_CORK_DELAY;
1602 /* reset do_transmit values for next time */
1605 pos->do_transmit = GNUNET_NO;
1609 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1610 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1611 (unsigned long long) slack.value,
1613 (unsigned int) size);
1617 /* select marked messages (up to size) for transmission */
1622 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1624 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1629 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1633 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1634 "Selected %u/%u bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1636 queue_size, MAX_PEER_QUEUE_SIZE,
1637 GNUNET_i2s (&n->peer));
1644 * Batch multiple messages into a larger buffer.
1646 * @param n neighbour to take messages from
1647 * @param buf target buffer
1648 * @param size size of buf
1649 * @param deadline set to transmission deadline for the result
1650 * @param retry_time set to the time when we should try again
1651 * (only valid if this function returns zero)
1652 * @param priority set to the priority of the batch
1653 * @return number of bytes written to buf (can be zero)
1656 batch_message (struct Neighbour *n,
1659 struct GNUNET_TIME_Absolute *deadline,
1660 struct GNUNET_TIME_Relative *retry_time,
1661 unsigned int *priority)
1663 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1664 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1665 struct MessageEntry *pos;
1666 struct MessageEntry *prev;
1667 struct MessageEntry *next;
1672 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1673 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1674 if (0 == select_messages (n, size, retry_time))
1677 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1678 "No messages selected, will try again in %llu ms\n",
1683 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1684 ntm->distance = htonl (n->last_distance);
1685 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1686 ntm->peer = n->peer;
1690 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1693 if (GNUNET_YES == pos->do_transmit)
1695 GNUNET_assert (pos->size <= size);
1696 /* do notifications */
1697 /* FIXME: track if we have *any* client that wants
1698 full notifications and only do this if that is
1700 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1702 memcpy (&ntm[1], &pos[1], pos->size);
1703 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1704 sizeof (struct GNUNET_MessageHeader));
1705 send_to_all_clients (&ntm->header,
1707 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1711 /* message too large for 'full' notifications, we do at
1712 least the 'hdr' type */
1715 sizeof (struct GNUNET_MessageHeader));
1717 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1719 send_to_all_clients (&ntm->header,
1721 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1724 "Encrypting message of type %u\n",
1725 ntohs(((struct GNUNET_MessageHeader*)&pos[1])->type));
1727 /* copy for encrypted transmission */
1728 memcpy (&buf[ret], &pos[1], pos->size);
1731 *priority += pos->priority;
1733 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1734 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1736 GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1738 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1752 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1753 "Deadline for message batch is %llu ms\n",
1754 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1761 * Remove messages with deadlines that have long expired from
1764 * @param n neighbour to inspect
1767 discard_expired_messages (struct Neighbour *n)
1769 struct MessageEntry *prev;
1770 struct MessageEntry *next;
1771 struct MessageEntry *pos;
1772 struct GNUNET_TIME_Absolute now;
1773 struct GNUNET_TIME_Relative delta;
1775 now = GNUNET_TIME_absolute_get ();
1781 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1782 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1785 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1786 "Message is %llu ms past due, discarding.\n",
1803 * Signature of the main function of a task.
1805 * @param cls closure
1806 * @param tc context information (why was this task triggered now)
1809 retry_plaintext_processing (void *cls,
1810 const struct GNUNET_SCHEDULER_TaskContext *tc)
1812 struct Neighbour *n = cls;
1814 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1815 process_plaintext_neighbour_queue (n);
1820 * Send our key (and encrypted PING) to the other peer.
1822 * @param n the other peer
1824 static void send_key (struct Neighbour *n);
1827 * Task that will retry "send_key" if our previous attempt failed
1831 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1833 struct Neighbour *n = cls;
1836 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1837 "Retrying key transmission to `%4s'\n",
1838 GNUNET_i2s (&n->peer));
1840 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1841 n->set_key_retry_frequency =
1842 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1848 * Check if we have plaintext messages for the specified neighbour
1849 * pending, and if so, consider batching and encrypting them (and
1850 * then trigger processing of the encrypted queue if needed).
1852 * @param n neighbour to check.
1855 process_plaintext_neighbour_queue (struct Neighbour *n)
1857 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1860 struct EncryptedMessage *em; /* encrypted message */
1861 struct EncryptedMessage *ph; /* plaintext header */
1862 struct MessageEntry *me;
1863 unsigned int priority;
1864 struct GNUNET_TIME_Absolute deadline;
1865 struct GNUNET_TIME_Relative retry_time;
1868 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1870 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1871 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1875 case PEER_STATE_DOWN:
1878 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1879 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1880 GNUNET_i2s(&n->peer));
1883 case PEER_STATE_KEY_SENT:
1884 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1885 n->retry_set_key_task
1886 = GNUNET_SCHEDULER_add_delayed (sched,
1887 n->set_key_retry_frequency,
1888 &set_key_retry_task, n);
1890 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1891 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1892 GNUNET_i2s(&n->peer));
1895 case PEER_STATE_KEY_RECEIVED:
1896 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1897 n->retry_set_key_task
1898 = GNUNET_SCHEDULER_add_delayed (sched,
1899 n->set_key_retry_frequency,
1900 &set_key_retry_task, n);
1902 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1903 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1904 GNUNET_i2s(&n->peer));
1907 case PEER_STATE_KEY_CONFIRMED:
1908 /* ready to continue */
1911 discard_expired_messages (n);
1912 if (n->messages == NULL)
1915 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1916 "Plaintext message queue for `%4s' is empty.\n",
1917 GNUNET_i2s(&n->peer));
1919 return; /* no pending messages */
1921 if (n->encrypted_head != NULL)
1924 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1925 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1926 GNUNET_i2s(&n->peer));
1928 return; /* wait for messages already encrypted to be
1931 ph = (struct EncryptedMessage *) pbuf;
1932 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1934 used = sizeof (struct EncryptedMessage);
1935 used += batch_message (n,
1937 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1938 &deadline, &retry_time, &priority);
1939 if (used == sizeof (struct EncryptedMessage))
1942 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1943 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1944 GNUNET_i2s(&n->peer));
1946 /* no messages selected for sending, try again later... */
1947 n->retry_plaintext_task =
1948 GNUNET_SCHEDULER_add_delayed (sched,
1950 &retry_plaintext_processing, n);
1953 #if DEBUG_CORE_QUOTA
1954 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1955 "Sending %u b/s as new limit to peer `%4s'\n",
1956 (unsigned int) ntohl (n->bw_in.value__),
1957 GNUNET_i2s (&n->peer));
1959 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1));
1960 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1961 ph->inbound_bw_limit = n->bw_in;
1962 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1964 /* setup encryption message header */
1965 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1966 me->deadline = deadline;
1967 me->priority = priority;
1969 em = (struct EncryptedMessage *) &me[1];
1970 em->header.size = htons (used);
1971 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1972 em->iv_seed = ph->iv_seed;
1973 esize = used - ENCRYPTED_HEADER_SIZE;
1974 GNUNET_CRYPTO_hash (&ph->sequence_number,
1975 esize - sizeof (GNUNET_HashCode),
1976 &ph->plaintext_hash);
1977 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
1980 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1981 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
1983 GNUNET_i2s(&n->peer),
1984 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
1986 GNUNET_assert (GNUNET_OK ==
1989 &ph->plaintext_hash,
1990 &em->plaintext_hash, esize));
1991 /* append to transmission list */
1992 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1996 process_encrypted_neighbour_queue (n);
2001 * Function that recalculates the bandwidth quota for the
2002 * given neighbour and transmits it to the transport service.
2004 * @param cls neighbour for the quota update
2008 neighbour_quota_update (void *cls,
2009 const struct GNUNET_SCHEDULER_TaskContext *tc);
2013 * Schedule the task that will recalculate the bandwidth
2014 * quota for this peer (and possibly force a disconnect of
2015 * idle peers by calculating a bandwidth of zero).
2018 schedule_quota_update (struct Neighbour *n)
2020 GNUNET_assert (n->quota_update_task ==
2021 GNUNET_SCHEDULER_NO_TASK);
2022 n->quota_update_task
2023 = GNUNET_SCHEDULER_add_delayed (sched,
2024 QUOTA_UPDATE_FREQUENCY,
2025 &neighbour_quota_update,
2031 * Initialize a new 'struct Neighbour'.
2033 * @param pid ID of the new neighbour
2034 * @return handle for the new neighbour
2036 static struct Neighbour *
2037 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2039 struct Neighbour *n;
2040 struct GNUNET_TIME_Absolute now;
2042 n = GNUNET_malloc (sizeof (struct Neighbour));
2043 n->next = neighbours;
2047 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2048 now = GNUNET_TIME_absolute_get ();
2049 n->encrypt_key_created = now;
2050 n->last_activity = now;
2051 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2052 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2053 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2054 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init ((uint32_t) - 1);
2055 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2056 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2058 neighbour_quota_update (n, NULL);
2064 * Handle CORE_SEND request.
2067 * @param client the client issuing the request
2068 * @param message the "struct SendMessage"
2071 handle_client_send (void *cls,
2072 struct GNUNET_SERVER_Client *client,
2073 const struct GNUNET_MessageHeader *message)
2075 const struct SendMessage *sm;
2076 struct Neighbour *n;
2077 struct MessageEntry *prev;
2078 struct MessageEntry *pos;
2079 struct MessageEntry *e;
2080 struct MessageEntry *min_prio_entry;
2081 struct MessageEntry *min_prio_prev;
2082 unsigned int min_prio;
2083 unsigned int queue_size;
2086 msize = ntohs (message->size);
2088 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2092 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2095 sm = (const struct SendMessage *) message;
2096 msize -= sizeof (struct SendMessage);
2097 n = find_neighbour (&sm->peer);
2099 n = create_neighbour (&sm->peer);
2101 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2102 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2105 GNUNET_i2s (&sm->peer));
2107 /* bound queue size */
2108 discard_expired_messages (n);
2109 min_prio = (unsigned int) -1;
2110 min_prio_entry = NULL;
2111 min_prio_prev = NULL;
2117 if (pos->priority < min_prio)
2119 min_prio_entry = pos;
2120 min_prio_prev = prev;
2121 min_prio = pos->priority;
2127 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2130 if (ntohl(sm->priority) <= min_prio)
2132 /* discard new entry */
2134 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2135 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2137 MAX_PEER_QUEUE_SIZE,
2139 ntohs (message->type));
2142 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2145 /* discard "min_prio_entry" */
2147 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2148 "Queue full, discarding existing older request\n");
2150 if (min_prio_prev == NULL)
2151 n->messages = min_prio_entry->next;
2153 min_prio_prev->next = min_prio_entry->next;
2154 GNUNET_free (min_prio_entry);
2158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2159 "Adding transmission request for `%4s' of size %u to queue\n",
2160 GNUNET_i2s (&sm->peer),
2163 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2164 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2165 e->priority = ntohl (sm->priority);
2167 memcpy (&e[1], &sm[1], msize);
2169 /* insert, keep list sorted by deadline */
2172 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2183 /* consider scheduling now */
2184 process_plaintext_neighbour_queue (n);
2186 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2191 * Function called when the transport service is ready to
2192 * receive a message. Only resets 'n->th' to NULL.
2194 * @param cls neighbour to use message from
2195 * @param size number of bytes we can transmit
2196 * @param buf where to copy the message
2197 * @return number of bytes transmitted
2200 notify_transport_connect_done (void *cls, size_t size, void *buf)
2202 struct Neighbour *n = cls;
2207 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2208 _("Failed to connect to `%4s': transport failed to connect\n"),
2209 GNUNET_i2s (&n->peer));
2218 * Handle CORE_REQUEST_CONNECT request.
2221 * @param client the client issuing the request
2222 * @param message the "struct ConnectMessage"
2225 handle_client_request_connect (void *cls,
2226 struct GNUNET_SERVER_Client *client,
2227 const struct GNUNET_MessageHeader *message)
2229 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2230 struct Neighbour *n;
2231 struct GNUNET_TIME_Relative timeout;
2233 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2236 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2239 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2240 n = find_neighbour (&cm->peer);
2242 n = create_neighbour (&cm->peer);
2243 if ( (n->is_connected) ||
2245 return; /* already connected, or at least trying */
2247 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2248 "Core received `%s' request for `%4s', will try to establish connection\n",
2250 GNUNET_i2s (&cm->peer));
2252 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2253 /* ask transport to connect to the peer */
2254 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2256 sizeof (struct GNUNET_MessageHeader), 0,
2258 ¬ify_transport_connect_done,
2260 GNUNET_break (NULL != n->th);
2265 * List of handlers for the messages understood by this
2268 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2269 {&handle_client_init, NULL,
2270 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2271 {&handle_client_request_info, NULL,
2272 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2273 sizeof (struct RequestInfoMessage)},
2274 {&handle_client_send, NULL,
2275 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2276 {&handle_client_request_connect, NULL,
2277 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2278 sizeof (struct ConnectMessage)},
2284 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2285 * the neighbour's struct and retry send_key. Or, if we did not get a
2286 * HELLO, just do nothing.
2288 * @param cls the 'struct Neighbour' to retry sending the key for
2289 * @param peer the peer for which this is the HELLO
2290 * @param hello HELLO message of that peer
2291 * @param trust amount of trust we currently have in that peer
2294 process_hello_retry_send_key (void *cls,
2295 const struct GNUNET_PeerIdentity *peer,
2296 const struct GNUNET_HELLO_Message *hello,
2299 struct Neighbour *n = cls;
2304 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2305 "Entered `process_hello_retry_send_key' and `peer' is NULL!\n");
2308 if (n->public_key != NULL)
2314 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2315 n->retry_set_key_task
2316 = GNUNET_SCHEDULER_add_delayed (sched,
2317 n->set_key_retry_frequency,
2318 &set_key_retry_task, n);
2324 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2325 "Entered `process_hello_retry_send_key' for peer `%4s'\n",
2328 if (n->public_key != NULL)
2331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2332 "already have public key for peer %s!! (so why are we here?)\n",
2339 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2340 "Received new `%s' message for `%4s', initiating key exchange.\n",
2345 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2346 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2348 GNUNET_free (n->public_key);
2349 n->public_key = NULL;
2351 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2352 "GNUNET_HELLO_get_key returned awfully\n");
2360 * Send our key (and encrypted PING) to the other peer.
2362 * @param n the other peer
2365 send_key (struct Neighbour *n)
2367 struct SetKeyMessage *sm;
2368 struct MessageEntry *me;
2369 struct PingMessage pp;
2370 struct PingMessage *pm;
2372 if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2377 "Key exchange in progress with `%4s'.\n",
2378 GNUNET_i2s (&n->peer));
2380 return; /* already in progress */
2384 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2385 "Asked to perform key exchange with `%4s'.\n",
2386 GNUNET_i2s (&n->peer));
2388 if (n->public_key == NULL)
2390 /* lookup n's public key, then try again */
2392 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2393 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2394 GNUNET_i2s (&n->peer));
2396 GNUNET_assert (n->pitr == NULL);
2397 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2401 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2402 &process_hello_retry_send_key, n);
2405 /* first, set key message */
2406 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2407 sizeof (struct SetKeyMessage));
2408 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2409 me->priority = SET_KEY_PRIORITY;
2410 me->size = sizeof (struct SetKeyMessage);
2411 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2415 sm = (struct SetKeyMessage *) &me[1];
2416 sm->header.size = htons (sizeof (struct SetKeyMessage));
2417 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2418 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2419 PEER_STATE_KEY_SENT : n->status));
2421 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2422 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2423 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2424 sizeof (struct GNUNET_PeerIdentity));
2425 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2426 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2427 sm->target = n->peer;
2428 GNUNET_assert (GNUNET_OK ==
2429 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2431 GNUNET_CRYPTO_AesSessionKey),
2433 &sm->encrypted_key));
2434 GNUNET_assert (GNUNET_OK ==
2435 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2438 /* second, encrypted PING message */
2439 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2440 sizeof (struct PingMessage));
2441 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2442 me->priority = PING_PRIORITY;
2443 me->size = sizeof (struct PingMessage);
2444 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2448 pm = (struct PingMessage *) &me[1];
2449 pm->header.size = htons (sizeof (struct PingMessage));
2450 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2451 pp.challenge = htonl (n->ping_challenge);
2452 pp.target = n->peer;
2454 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2455 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2456 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2457 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2458 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2460 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2463 &n->peer.hashPubKey,
2466 sizeof (struct PingMessage) -
2467 sizeof (struct GNUNET_MessageHeader));
2471 case PEER_STATE_DOWN:
2472 n->status = PEER_STATE_KEY_SENT;
2474 case PEER_STATE_KEY_SENT:
2476 case PEER_STATE_KEY_RECEIVED:
2478 case PEER_STATE_KEY_CONFIRMED:
2485 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2486 "Have %llu ms left for `%s' transmission.\n",
2487 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2490 /* trigger queue processing */
2491 process_encrypted_neighbour_queue (n);
2492 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2493 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2494 n->retry_set_key_task
2495 = GNUNET_SCHEDULER_add_delayed (sched,
2496 n->set_key_retry_frequency,
2497 &set_key_retry_task, n);
2502 * We received a SET_KEY message. Validate and update
2503 * our key material and status.
2505 * @param n the neighbour from which we received message m
2506 * @param m the set key message we received
2509 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2513 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2514 * the neighbour's struct and retry handling the set_key message. Or,
2515 * if we did not get a HELLO, just free the set key message.
2517 * @param cls pointer to the set key message
2518 * @param peer the peer for which this is the HELLO
2519 * @param hello HELLO message of that peer
2520 * @param trust amount of trust we currently have in that peer
2523 process_hello_retry_handle_set_key (void *cls,
2524 const struct GNUNET_PeerIdentity *peer,
2525 const struct GNUNET_HELLO_Message *hello,
2528 struct Neighbour *n = cls;
2529 struct SetKeyMessage *sm = n->skm;
2538 if (n->public_key != NULL)
2539 return; /* multiple HELLOs match!? */
2541 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2542 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2544 GNUNET_break_op (0);
2545 GNUNET_free (n->public_key);
2546 n->public_key = NULL;
2550 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2551 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2552 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2554 handle_set_key (n, sm);
2559 * We received a PING message. Validate and transmit
2562 * @param n sender of the PING
2563 * @param m the encrypted PING message itself
2566 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2568 struct PingMessage t;
2569 struct PongMessage tx;
2570 struct PongMessage *tp;
2571 struct MessageEntry *me;
2574 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2575 "Core service receives `%s' request from `%4s'.\n",
2576 "PING", GNUNET_i2s (&n->peer));
2580 &my_identity.hashPubKey,
2583 sizeof (struct PingMessage) -
2584 sizeof (struct GNUNET_MessageHeader)))
2587 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2588 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2590 GNUNET_i2s (&t.target),
2591 ntohl (t.challenge), n->decrypt_key.crc32);
2592 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2593 "Target of `%s' request is `%4s'.\n",
2594 "PING", GNUNET_i2s (&t.target));
2596 if (0 != memcmp (&t.target,
2597 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2599 GNUNET_break_op (0);
2602 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2603 sizeof (struct PongMessage));
2604 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2608 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2609 me->priority = PONG_PRIORITY;
2610 me->size = sizeof (struct PongMessage);
2611 tx.reserved = htonl (0);
2612 tx.inbound_bw_limit = n->bw_in;
2613 tx.challenge = t.challenge;
2614 tx.target = t.target;
2615 tp = (struct PongMessage *) &me[1];
2616 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2617 tp->header.size = htons (sizeof (struct PongMessage));
2619 &my_identity.hashPubKey,
2622 sizeof (struct PongMessage) -
2623 sizeof (struct GNUNET_MessageHeader));
2625 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2626 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2627 ntohl (t.challenge), n->encrypt_key.crc32);
2629 /* trigger queue processing */
2630 process_encrypted_neighbour_queue (n);
2635 * We received a PONG message. Validate and update our status.
2637 * @param n sender of the PONG
2638 * @param m the encrypted PONG message itself
2641 handle_pong (struct Neighbour *n,
2642 const struct PongMessage *m)
2644 struct PongMessage t;
2645 struct ConnectNotifyMessage cnm;
2648 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2649 "Core service receives `%s' request from `%4s'.\n",
2650 "PONG", GNUNET_i2s (&n->peer));
2654 &n->peer.hashPubKey,
2657 sizeof (struct PongMessage) -
2658 sizeof (struct GNUNET_MessageHeader)))
2660 if (0 != ntohl (t.reserved))
2662 GNUNET_break_op (0);
2666 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2667 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2669 GNUNET_i2s (&t.target),
2670 ntohl (t.challenge), n->decrypt_key.crc32);
2672 if ((0 != memcmp (&t.target,
2674 sizeof (struct GNUNET_PeerIdentity))) ||
2675 (n->ping_challenge != ntohl (t.challenge)))
2677 /* PONG malformed */
2679 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2680 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2681 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2682 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2683 "Received malformed `%s' received from `%4s' with challenge %u\n",
2684 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2686 GNUNET_break_op (0);
2691 case PEER_STATE_DOWN:
2692 GNUNET_break (0); /* should be impossible */
2694 case PEER_STATE_KEY_SENT:
2695 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2697 case PEER_STATE_KEY_RECEIVED:
2698 n->status = PEER_STATE_KEY_CONFIRMED;
2699 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2701 n->bw_out_external_limit = t.inbound_bw_limit;
2702 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2703 n->bw_out_internal_limit);
2704 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2706 GNUNET_TRANSPORT_set_quota (transport,
2710 GNUNET_TIME_UNIT_FOREVER_REL,
2714 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2715 "Confirmed key via `%s' message for peer `%4s'\n",
2716 "PONG", GNUNET_i2s (&n->peer));
2718 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2720 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2721 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2723 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2724 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2725 cnm.distance = htonl (n->last_distance);
2726 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2728 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2729 process_encrypted_neighbour_queue (n);
2731 case PEER_STATE_KEY_CONFIRMED:
2732 n->last_activity = GNUNET_TIME_absolute_get ();
2733 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2734 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2736 = GNUNET_SCHEDULER_add_delayed (sched,
2737 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2749 * We received a SET_KEY message. Validate and update
2750 * our key material and status.
2752 * @param n the neighbour from which we received message m
2753 * @param m the set key message we received
2756 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2758 struct SetKeyMessage *m_cpy;
2759 struct GNUNET_TIME_Absolute t;
2760 struct GNUNET_CRYPTO_AesSessionKey k;
2761 struct PingMessage *ping;
2762 struct PongMessage *pong;
2763 enum PeerStateMachine sender_status;
2766 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2767 "Core service receives `%s' request from `%4s'.\n",
2768 "SET_KEY", GNUNET_i2s (&n->peer));
2770 if (n->public_key == NULL)
2772 if (n->pitr != NULL)
2775 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2776 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2782 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2783 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2785 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2786 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2787 /* lookup n's public key, then try again */
2788 GNUNET_assert (n->skm == NULL);
2790 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2794 GNUNET_TIME_UNIT_MINUTES,
2795 &process_hello_retry_handle_set_key, n);
2798 if (0 != memcmp (&m->target,
2800 sizeof (struct GNUNET_PeerIdentity)))
2802 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2803 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
2805 GNUNET_i2s (&m->target));
2808 if ((ntohl (m->purpose.size) !=
2809 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2810 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2811 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2812 sizeof (struct GNUNET_PeerIdentity)) ||
2814 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2815 &m->purpose, &m->signature, n->public_key)))
2817 /* invalid signature */
2818 GNUNET_break_op (0);
2821 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2822 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2823 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2824 (t.value < n->decrypt_key_created.value))
2826 /* this could rarely happen due to massive re-ordering of
2827 messages on the network level, but is most likely either
2828 a bug or some adversary messing with us. Report. */
2829 GNUNET_break_op (0);
2833 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2834 "Decrypting key material.\n");
2836 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2839 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2840 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2841 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2843 /* failed to decrypt !? */
2844 GNUNET_break_op (0);
2849 if (n->decrypt_key_created.value != t.value)
2851 /* fresh key, reset sequence numbers */
2852 n->last_sequence_number_received = 0;
2853 n->last_packets_bitmap = 0;
2854 n->decrypt_key_created = t;
2856 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2859 case PEER_STATE_DOWN:
2860 n->status = PEER_STATE_KEY_RECEIVED;
2862 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2863 "Responding to `%s' with my own key.\n", "SET_KEY");
2867 case PEER_STATE_KEY_SENT:
2868 case PEER_STATE_KEY_RECEIVED:
2869 n->status = PEER_STATE_KEY_RECEIVED;
2870 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2871 (sender_status != PEER_STATE_KEY_CONFIRMED))
2874 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2875 "Responding to `%s' with my own key (other peer has status %u).\n",
2876 "SET_KEY", sender_status);
2881 case PEER_STATE_KEY_CONFIRMED:
2882 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2883 (sender_status != PEER_STATE_KEY_CONFIRMED))
2886 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2887 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2888 "SET_KEY", sender_status);
2897 if (n->pending_ping != NULL)
2899 ping = n->pending_ping;
2900 n->pending_ping = NULL;
2901 handle_ping (n, ping);
2904 if (n->pending_pong != NULL)
2906 pong = n->pending_pong;
2907 n->pending_pong = NULL;
2908 handle_pong (n, pong);
2915 * Send a P2P message to a client.
2917 * @param sender who sent us the message?
2918 * @param client who should we give the message to?
2919 * @param m contains the message to transmit
2920 * @param msize number of bytes in buf to transmit
2923 send_p2p_message_to_client (struct Neighbour *sender,
2924 struct Client *client,
2925 const void *m, size_t msize)
2927 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2928 struct NotifyTrafficMessage *ntm;
2931 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2932 "Core service passes message from `%4s' of type %u to client.\n",
2933 GNUNET_i2s(&sender->peer),
2934 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2936 ntm = (struct NotifyTrafficMessage *) buf;
2937 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2938 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2939 ntm->distance = htonl (sender->last_distance);
2940 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
2941 ntm->peer = sender->peer;
2942 memcpy (&ntm[1], m, msize);
2943 send_to_client (client, &ntm->header, GNUNET_YES);
2948 * Deliver P2P message to interested clients.
2950 * @param sender who sent us the message?
2951 * @param m the message
2952 * @param msize size of the message (including header)
2955 deliver_message (struct Neighbour *sender,
2956 const struct GNUNET_MessageHeader *m, size_t msize)
2958 struct Client *cpos;
2964 type = ntohs (m->type);
2966 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2967 "Received encapsulated message of type %u from `%4s'\n",
2969 GNUNET_i2s (&sender->peer));
2971 dropped = GNUNET_YES;
2973 while (cpos != NULL)
2975 deliver_full = GNUNET_NO;
2976 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
2977 deliver_full = GNUNET_YES;
2980 for (tpos = 0; tpos < cpos->tcnt; tpos++)
2982 if (type != cpos->types[tpos])
2984 deliver_full = GNUNET_YES;
2988 if (GNUNET_YES == deliver_full)
2990 send_p2p_message_to_client (sender, cpos, m, msize);
2991 dropped = GNUNET_NO;
2993 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2995 send_p2p_message_to_client (sender, cpos, m,
2996 sizeof (struct GNUNET_MessageHeader));
3000 if (dropped == GNUNET_YES)
3003 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3004 "Message of type %u from `%4s' not delivered to any client.\n",
3006 GNUNET_i2s (&sender->peer));
3008 /* FIXME: stats... */
3014 * Align P2P message and then deliver to interested clients.
3016 * @param sender who sent us the message?
3017 * @param buffer unaligned (!) buffer containing message
3018 * @param msize size of the message (including header)
3021 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
3025 /* TODO: call to statistics? */
3026 memcpy (abuf, buffer, msize);
3027 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
3032 * Deliver P2P messages to interested clients.
3034 * @param sender who sent us the message?
3035 * @param buffer buffer containing messages, can be modified
3036 * @param buffer_size size of the buffer (overall)
3037 * @param offset offset where messages in the buffer start
3040 deliver_messages (struct Neighbour *sender,
3041 const char *buffer, size_t buffer_size, size_t offset)
3043 struct GNUNET_MessageHeader *mhp;
3044 struct GNUNET_MessageHeader mh;
3048 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
3050 if (0 != offset % sizeof (uint16_t))
3052 /* outch, need to copy to access header */
3053 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
3058 /* can access header directly */
3059 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
3061 msize = ntohs (mhp->size);
3062 if (msize + offset > buffer_size)
3064 /* malformed message, header says it is larger than what
3065 would fit into the overall buffer */
3066 GNUNET_break_op (0);
3069 #if HAVE_UNALIGNED_64_ACCESS
3070 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
3072 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
3074 if (GNUNET_YES == need_align)
3075 align_and_deliver (sender, &buffer[offset], msize);
3077 deliver_message (sender,
3078 (const struct GNUNET_MessageHeader *)
3079 &buffer[offset], msize);
3086 * We received an encrypted message. Decrypt, validate and
3087 * pass on to the appropriate clients.
3090 handle_encrypted_message (struct Neighbour *n,
3091 const struct EncryptedMessage *m)
3093 size_t size = ntohs (m->header.size);
3095 struct EncryptedMessage *pt; /* plaintext */
3099 struct GNUNET_TIME_Absolute t;
3103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3104 "Core service receives `%s' request from `%4s'.\n",
3105 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3107 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3113 &buf[ENCRYPTED_HEADER_SIZE],
3114 size - ENCRYPTED_HEADER_SIZE))
3116 pt = (struct EncryptedMessage *) buf;
3119 GNUNET_CRYPTO_hash (&pt->sequence_number,
3120 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3121 if (0 != memcmp (&ph,
3122 &pt->plaintext_hash,
3123 sizeof (GNUNET_HashCode)))
3125 /* checksum failed */
3126 GNUNET_break_op (0);
3130 /* validate sequence number */
3131 snum = ntohl (pt->sequence_number);
3132 if (n->last_sequence_number_received == snum)
3134 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3135 "Received duplicate message, ignoring.\n");
3136 /* duplicate, ignore */
3139 if ((n->last_sequence_number_received > snum) &&
3140 (n->last_sequence_number_received - snum > 32))
3142 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3143 "Received ancient out of sequence message, ignoring.\n");
3144 /* ancient out of sequence, ignore */
3147 if (n->last_sequence_number_received > snum)
3149 unsigned int rotbit =
3150 1 << (n->last_sequence_number_received - snum - 1);
3151 if ((n->last_packets_bitmap & rotbit) != 0)
3153 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3154 "Received duplicate message, ignoring.\n");
3155 /* duplicate, ignore */
3158 n->last_packets_bitmap |= rotbit;
3160 if (n->last_sequence_number_received < snum)
3162 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3163 n->last_sequence_number_received = snum;
3166 /* check timestamp */
3167 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3168 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3170 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3172 ("Message received far too old (%llu ms). Content ignored.\n"),
3173 GNUNET_TIME_absolute_get_duration (t).value);
3177 /* process decrypted message(s) */
3178 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3180 #if DEBUG_CORE_SET_QUOTA
3181 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3182 "Received %u b/s as new inbound limit for peer `%4s'\n",
3183 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3184 GNUNET_i2s (&n->peer));
3186 n->bw_out_external_limit = pt->inbound_bw_limit;
3187 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3188 n->bw_out_internal_limit);
3189 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3191 GNUNET_TRANSPORT_set_quota (transport,
3195 GNUNET_TIME_UNIT_FOREVER_REL,
3198 n->last_activity = GNUNET_TIME_absolute_get ();
3199 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3200 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3202 = GNUNET_SCHEDULER_add_delayed (sched,
3203 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3206 off = sizeof (struct EncryptedMessage);
3207 deliver_messages (n, buf, size, off);
3212 * Function called by the transport for each received message.
3214 * @param cls closure
3215 * @param peer (claimed) identity of the other peer
3216 * @param message the message
3217 * @param latency estimated latency for communicating with the
3218 * given peer (round-trip)
3219 * @param distance in overlay hops, as given by transport plugin
3222 handle_transport_receive (void *cls,
3223 const struct GNUNET_PeerIdentity *peer,
3224 const struct GNUNET_MessageHeader *message,
3225 struct GNUNET_TIME_Relative latency,
3226 unsigned int distance)
3228 struct Neighbour *n;
3229 struct GNUNET_TIME_Absolute now;
3235 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3236 "Received message of type %u from `%4s', demultiplexing.\n",
3237 ntohs (message->type), GNUNET_i2s (peer));
3239 n = find_neighbour (peer);
3241 n = create_neighbour (peer);
3244 n->last_latency = latency;
3245 n->last_distance = distance;
3246 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3247 type = ntohs (message->type);
3248 size = ntohs (message->size);
3251 "Received message of type %u from `%4s'\n",
3257 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3258 if (size != sizeof (struct SetKeyMessage))
3260 GNUNET_break_op (0);
3263 handle_set_key (n, (const struct SetKeyMessage *) message);
3265 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3266 if (size < sizeof (struct EncryptedMessage) +
3267 sizeof (struct GNUNET_MessageHeader))
3269 GNUNET_break_op (0);
3272 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3273 (n->status != PEER_STATE_KEY_CONFIRMED))
3275 GNUNET_break_op (0);
3278 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3280 case GNUNET_MESSAGE_TYPE_CORE_PING:
3281 if (size != sizeof (struct PingMessage))
3283 GNUNET_break_op (0);
3286 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3287 (n->status != PEER_STATE_KEY_CONFIRMED))
3290 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3291 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3292 "PING", GNUNET_i2s (&n->peer));
3294 GNUNET_free_non_null (n->pending_ping);
3295 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3296 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3299 handle_ping (n, (const struct PingMessage *) message);
3301 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3302 if (size != sizeof (struct PongMessage))
3304 GNUNET_break_op (0);
3307 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3308 (n->status != PEER_STATE_KEY_CONFIRMED) )
3311 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3312 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3313 "PONG", GNUNET_i2s (&n->peer));
3315 GNUNET_free_non_null (n->pending_pong);
3316 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3317 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3320 handle_pong (n, (const struct PongMessage *) message);
3323 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3324 _("Unsupported message of type %u received.\n"), type);
3327 if (n->status == PEER_STATE_KEY_CONFIRMED)
3329 now = GNUNET_TIME_absolute_get ();
3330 n->last_activity = now;
3332 n->time_established = now;
3333 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3334 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3336 = GNUNET_SCHEDULER_add_delayed (sched,
3337 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3345 * Function that recalculates the bandwidth quota for the
3346 * given neighbour and transmits it to the transport service.
3348 * @param cls neighbour for the quota update
3352 neighbour_quota_update (void *cls,
3353 const struct GNUNET_SCHEDULER_TaskContext *tc)
3355 struct Neighbour *n = cls;
3356 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3359 unsigned long long distributable;
3360 uint64_t need_per_peer;
3361 uint64_t need_per_second;
3363 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3364 /* calculate relative preference among all neighbours;
3365 divides by a bit more to avoid division by zero AND to
3366 account for possibility of new neighbours joining any time
3367 AND to convert to double... */
3368 if (preference_sum == 0)
3370 pref_rel = 1.0 / (double) neighbour_count;
3374 pref_rel = n->current_preference / preference_sum;
3376 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3377 GNUNET_TIME_UNIT_SECONDS);
3378 need_per_second = need_per_peer * neighbour_count;
3380 if (bandwidth_target_out_bps > need_per_second)
3381 distributable = bandwidth_target_out_bps - need_per_second;
3382 share = distributable * pref_rel;
3383 if (share + need_per_peer > ( (uint32_t)-1))
3384 q_in = GNUNET_BANDWIDTH_value_init ((uint32_t) -1);
3386 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3387 /* check if we want to disconnect for good due to inactivity */
3388 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3389 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3392 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3393 "Forcing disconnect of `%4s' due to inactivity (?).\n",
3394 GNUNET_i2s (&n->peer));
3396 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3398 #if DEBUG_CORE_QUOTA
3399 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3400 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3401 GNUNET_i2s (&n->peer),
3402 (unsigned int) ntohl (q_in.value__),
3403 bandwidth_target_out_bps,
3404 (unsigned int) ntohl (n->bw_in.value__),
3405 (unsigned int) ntohl (n->bw_out.value__),
3406 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3408 if (n->bw_in.value__ != q_in.value__)
3411 GNUNET_TRANSPORT_set_quota (transport,
3415 GNUNET_TIME_UNIT_FOREVER_REL,
3418 schedule_quota_update (n);
3423 * Function called by transport to notify us that
3424 * a peer connected to us (on the network level).
3426 * @param cls closure
3427 * @param peer the peer that connected
3428 * @param latency current latency of the connection
3429 * @param distance in overlay hops, as given by transport plugin
3432 handle_transport_notify_connect (void *cls,
3433 const struct GNUNET_PeerIdentity *peer,
3434 struct GNUNET_TIME_Relative latency,
3435 unsigned int distance)
3437 struct Neighbour *n;
3438 struct ConnectNotifyMessage cnm;
3440 n = find_neighbour (peer);
3443 if (n->is_connected)
3445 /* duplicate connect notification!? */
3452 n = create_neighbour (peer);
3454 n->is_connected = GNUNET_YES;
3455 n->last_latency = latency;
3456 n->last_distance = distance;
3457 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3460 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3464 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3465 "Received connection from `%4s'.\n",
3466 GNUNET_i2s (&n->peer));
3468 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3469 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3470 cnm.distance = htonl (n->last_distance);
3471 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3473 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3474 GNUNET_TRANSPORT_set_quota (transport,
3478 GNUNET_TIME_UNIT_FOREVER_REL,
3485 * Function called by transport telling us that a peer
3488 * @param cls closure
3489 * @param peer the peer that disconnected
3492 handle_transport_notify_disconnect (void *cls,
3493 const struct GNUNET_PeerIdentity *peer)
3495 struct DisconnectNotifyMessage cnm;
3496 struct Neighbour *n;
3499 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3500 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3502 n = find_neighbour (peer);
3508 GNUNET_break (n->is_connected);
3509 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3510 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3512 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3513 n->is_connected = GNUNET_NO;
3518 * Last task run during shutdown. Disconnects us from
3522 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3524 struct Neighbour *n;
3528 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3529 "Core service shutting down.\n");
3531 GNUNET_assert (transport != NULL);
3532 GNUNET_TRANSPORT_disconnect (transport);
3534 while (NULL != (n = neighbours))
3536 neighbours = n->next;
3537 GNUNET_assert (neighbour_count > 0);
3541 GNUNET_SERVER_notification_context_destroy (notifier);
3543 while (NULL != (c = clients))
3544 handle_client_disconnect (NULL, c->client_handle);
3545 if (my_private_key != NULL)
3546 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3551 * Initiate core service.
3553 * @param cls closure
3554 * @param s scheduler to use
3555 * @param serv the initialized server
3556 * @param c configuration to use
3560 struct GNUNET_SCHEDULER_Handle *s,
3561 struct GNUNET_SERVER_Handle *serv,
3562 const struct GNUNET_CONFIGURATION_Handle *c)
3568 /* parse configuration */
3571 GNUNET_CONFIGURATION_get_value_number (c,
3574 &bandwidth_target_in_bps)) ||
3576 GNUNET_CONFIGURATION_get_value_number (c,
3579 &bandwidth_target_out_bps)) ||
3581 GNUNET_CONFIGURATION_get_value_filename (c,
3583 "HOSTKEY", &keyfile)))
3585 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3587 ("Core service is lacking key configuration settings. Exiting.\n"));
3588 GNUNET_SCHEDULER_shutdown (s);
3591 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3592 GNUNET_free (keyfile);
3593 if (my_private_key == NULL)
3595 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3596 _("Core service could not access hostkey. Exiting.\n"));
3597 GNUNET_SCHEDULER_shutdown (s);
3600 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3601 GNUNET_CRYPTO_hash (&my_public_key,
3602 sizeof (my_public_key), &my_identity.hashPubKey);
3603 /* setup notification */
3605 notifier = GNUNET_SERVER_notification_context_create (server,
3607 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3608 /* setup transport connection */
3609 transport = GNUNET_TRANSPORT_connect (sched,
3612 &handle_transport_receive,
3613 &handle_transport_notify_connect,
3614 &handle_transport_notify_disconnect);
3615 GNUNET_assert (NULL != transport);
3616 GNUNET_SCHEDULER_add_delayed (sched,
3617 GNUNET_TIME_UNIT_FOREVER_REL,
3618 &cleaning_task, NULL);
3619 /* process client requests */
3620 GNUNET_SERVER_add_handlers (server, handlers);
3621 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3622 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3628 * The main function for the transport service.
3630 * @param argc number of arguments from the command line
3631 * @param argv command line arguments
3632 * @return 0 ok, 1 on error
3635 main (int argc, char *const *argv)
3637 return (GNUNET_OK ==
3638 GNUNET_SERVICE_run (argc,
3641 GNUNET_SERVICE_OPTION_NONE,
3642 &run, NULL)) ? 0 : 1;
3645 /* end of gnunet-service-core.c */