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))
809 #if DEBUG_CORE_CLIENT
810 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
811 "Sending message of type %u to client.\n",
814 send_to_client (c, msg, can_drop);
822 * Handle CORE_INIT request.
825 handle_client_init (void *cls,
826 struct GNUNET_SERVER_Client *client,
827 const struct GNUNET_MessageHeader *message)
829 const struct InitMessage *im;
830 struct InitReplyMessage irm;
833 const uint16_t *types;
836 struct ConnectNotifyMessage cnm;
839 #if DEBUG_CORE_CLIENT
840 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
841 "Client connecting to core service with `%s' message\n",
844 /* check that we don't have an entry already */
848 if (client == c->client_handle)
851 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
856 msize = ntohs (message->size);
857 if (msize < sizeof (struct InitMessage))
860 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
863 GNUNET_SERVER_notification_context_add (notifier, client);
864 im = (const struct InitMessage *) message;
865 types = (const uint16_t *) &im[1];
866 msize -= sizeof (struct InitMessage);
867 c = GNUNET_malloc (sizeof (struct Client) + msize);
868 c->client_handle = client;
871 c->tcnt = msize / sizeof (uint16_t);
872 c->types = (const uint16_t *) &c[1];
873 wtypes = (uint16_t *) &c[1];
874 for (i=0;i<c->tcnt;i++)
875 wtypes[i] = ntohs (types[i]);
876 c->options = ntohl (im->options);
877 #if DEBUG_CORE_CLIENT
878 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
879 "Client %p is interested in %u message types\n",
883 /* send init reply message */
884 irm.header.size = htons (sizeof (struct InitReplyMessage));
885 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
886 irm.reserved = htonl (0);
887 memcpy (&irm.publicKey,
889 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
890 #if DEBUG_CORE_CLIENT
891 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
892 "Sending `%s' message to client.\n", "INIT_REPLY");
894 send_to_client (c, &irm.header, GNUNET_NO);
895 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
897 /* notify new client about existing neighbours */
898 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
899 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
903 if (n->status == PEER_STATE_KEY_CONFIRMED)
905 #if DEBUG_CORE_CLIENT
906 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
907 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
909 cnm.distance = htonl (n->last_distance);
910 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
912 send_to_client (c, &cnm.header, GNUNET_NO);
917 GNUNET_SERVER_receive_done (client, GNUNET_OK);
922 * A client disconnected, clean up.
925 * @param client identification of the client
928 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
935 #if DEBUG_CORE_CLIENT
936 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
937 "Client %p has disconnected from core service.\n",
944 if (client == pos->client_handle)
949 prev->next = pos->next;
956 /* client never sent INIT */
961 * Handle REQUEST_INFO request.
964 handle_client_request_info (void *cls,
965 struct GNUNET_SERVER_Client *client,
966 const struct GNUNET_MessageHeader *message)
968 const struct RequestInfoMessage *rcm;
970 struct ConfigurationInfoMessage cim;
973 unsigned long long old_preference;
974 struct GNUNET_SERVER_TransmitContext *tc;
976 #if DEBUG_CORE_CLIENT
977 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
978 "Core service receives `%s' request.\n", "REQUEST_INFO");
980 rcm = (const struct RequestInfoMessage *) message;
981 n = find_neighbour (&rcm->peer);
982 memset (&cim, 0, sizeof (cim));
985 want_reserv = ntohl (rcm->reserve_inbound);
986 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
988 n->bw_out_internal_limit = rcm->limit_outbound;
989 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
990 n->bw_out_external_limit);
991 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
993 GNUNET_TRANSPORT_set_quota (transport,
997 GNUNET_TIME_UNIT_FOREVER_REL,
1000 if (want_reserv < 0)
1002 got_reserv = want_reserv;
1004 else if (want_reserv > 0)
1006 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1007 want_reserv).value == 0)
1008 got_reserv = want_reserv;
1010 got_reserv = 0; /* all or nothing */
1014 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1016 old_preference = n->current_preference;
1017 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1018 if (old_preference > n->current_preference)
1020 /* overflow; cap at maximum value */
1021 n->current_preference = (unsigned long long) -1;
1023 update_preference_sum (n->current_preference - old_preference);
1024 #if DEBUG_CORE_QUOTA
1025 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1026 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1028 GNUNET_i2s (&rcm->peer),
1031 cim.reserved_amount = htonl (got_reserv);
1032 cim.bw_in = n->bw_in;
1033 cim.bw_out = n->bw_out;
1034 cim.preference = n->current_preference;
1036 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1037 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1038 cim.peer = rcm->peer;
1040 #if DEBUG_CORE_CLIENT
1041 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1042 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1044 tc = GNUNET_SERVER_transmit_context_create (client);
1045 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1046 GNUNET_SERVER_transmit_context_run (tc,
1047 GNUNET_TIME_UNIT_FOREVER_REL);
1052 * Free the given entry for the neighbour (it has
1053 * already been removed from the list at this point).
1055 * @param n neighbour to free
1058 free_neighbour (struct Neighbour *n)
1060 struct MessageEntry *m;
1062 if (n->pitr != NULL)
1064 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1069 GNUNET_free (n->skm);
1072 while (NULL != (m = n->messages))
1074 n->messages = m->next;
1077 while (NULL != (m = n->encrypted_head))
1079 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1086 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1089 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1090 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1091 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1092 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1093 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1094 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1095 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1096 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1097 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1098 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1099 GNUNET_free_non_null (n->public_key);
1100 GNUNET_free_non_null (n->pending_ping);
1101 GNUNET_free_non_null (n->pending_pong);
1107 * Check if we have encrypted messages for the specified neighbour
1108 * pending, and if so, check with the transport about sending them
1111 * @param n neighbour to check.
1113 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1117 * Encrypt size bytes from in and write the result to out. Use the
1118 * key for outbound traffic of the given neighbour.
1120 * @param n neighbour we are sending to
1121 * @param iv initialization vector to use
1122 * @param in ciphertext
1123 * @param out plaintext
1124 * @param size size of in/out
1125 * @return GNUNET_OK on success
1128 do_encrypt (struct Neighbour *n,
1129 const GNUNET_HashCode * iv,
1130 const void *in, void *out, size_t size)
1132 if (size != (uint16_t) size)
1137 GNUNET_assert (size ==
1138 GNUNET_CRYPTO_aes_encrypt (in,
1142 GNUNET_CRYPTO_AesInitializationVector
1145 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1146 "Encrypted %u bytes for `%4s' using key %u\n", size,
1147 GNUNET_i2s (&n->peer), n->encrypt_key.crc32);
1154 * Consider freeing the given neighbour since we may not need
1155 * to keep it around anymore.
1157 * @param n neighbour to consider discarding
1160 consider_free_neighbour (struct Neighbour *n);
1164 * Task triggered when a neighbour entry is about to time out
1165 * (and we should prevent this by sending a PING).
1167 * @param cls the 'struct Neighbour'
1168 * @param tc scheduler context (not used)
1171 send_keep_alive (void *cls,
1172 const struct GNUNET_SCHEDULER_TaskContext *tc)
1174 struct Neighbour *n = cls;
1175 struct GNUNET_TIME_Relative retry;
1176 struct GNUNET_TIME_Relative left;
1177 struct MessageEntry *me;
1178 struct PingMessage pp;
1179 struct PingMessage *pm;
1181 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1183 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1184 sizeof (struct PingMessage));
1185 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1186 me->priority = PING_PRIORITY;
1187 me->size = sizeof (struct PingMessage);
1188 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1192 pm = (struct PingMessage *) &me[1];
1193 pm->header.size = htons (sizeof (struct PingMessage));
1194 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1195 pp.challenge = htonl (n->ping_challenge);
1196 pp.target = n->peer;
1198 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1199 "Encrypting `%s' and `%s' messages for `%4s'.\n",
1200 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
1201 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1202 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
1204 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
1207 &n->peer.hashPubKey,
1210 sizeof (struct PingMessage) -
1211 sizeof (struct GNUNET_MessageHeader));
1212 process_encrypted_neighbour_queue (n);
1213 /* reschedule PING job */
1214 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1215 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1216 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1217 MIN_PING_FREQUENCY);
1219 = GNUNET_SCHEDULER_add_delayed (sched,
1228 * Task triggered when a neighbour entry might have gotten stale.
1230 * @param cls the 'struct Neighbour'
1231 * @param tc scheduler context (not used)
1234 consider_free_task (void *cls,
1235 const struct GNUNET_SCHEDULER_TaskContext *tc)
1237 struct Neighbour *n = cls;
1239 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1240 consider_free_neighbour (n);
1245 * Consider freeing the given neighbour since we may not need
1246 * to keep it around anymore.
1248 * @param n neighbour to consider discarding
1251 consider_free_neighbour (struct Neighbour *n)
1253 struct Neighbour *pos;
1254 struct Neighbour *prev;
1255 struct GNUNET_TIME_Relative left;
1257 if ( (n->th != NULL) ||
1258 (n->pitr != NULL) ||
1259 (n->status == PEER_STATE_KEY_CONFIRMED) ||
1260 (GNUNET_YES == n->is_connected) )
1261 return; /* no chance */
1263 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1264 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1267 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1268 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1269 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1271 &consider_free_task,
1275 /* actually free the neighbour... */
1284 neighbours = n->next;
1286 prev->next = n->next;
1287 GNUNET_assert (neighbour_count > 0);
1294 * Function called when the transport service is ready to
1295 * receive an encrypted message for the respective peer
1297 * @param cls neighbour to use message from
1298 * @param size number of bytes we can transmit
1299 * @param buf where to copy the message
1300 * @return number of bytes transmitted
1303 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1305 struct Neighbour *n = cls;
1306 struct MessageEntry *m;
1311 GNUNET_assert (NULL != (m = n->encrypted_head));
1312 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1319 GNUNET_assert (size >= m->size);
1320 memcpy (cbuf, &m[1], m->size);
1322 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1325 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1326 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1327 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1328 ret, GNUNET_i2s (&n->peer));
1330 process_encrypted_neighbour_queue (n);
1335 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1336 "Transmission of message of type %u and size %u failed\n",
1337 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1342 consider_free_neighbour (n);
1348 * Check if we have plaintext messages for the specified neighbour
1349 * pending, and if so, consider batching and encrypting them (and
1350 * then trigger processing of the encrypted queue if needed).
1352 * @param n neighbour to check.
1354 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1358 * Check if we have encrypted messages for the specified neighbour
1359 * pending, and if so, check with the transport about sending them
1362 * @param n neighbour to check.
1365 process_encrypted_neighbour_queue (struct Neighbour *n)
1367 struct MessageEntry *m;
1370 return; /* request already pending */
1371 m = n->encrypted_head;
1374 /* encrypted queue empty, try plaintext instead */
1375 process_plaintext_neighbour_queue (n);
1379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1380 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1382 GNUNET_i2s (&n->peer),
1383 GNUNET_TIME_absolute_get_remaining (m->deadline).
1387 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1390 GNUNET_TIME_absolute_get_remaining
1392 ¬ify_encrypted_transmit_ready,
1396 /* message request too large or duplicate request */
1398 /* discard encrypted message */
1399 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1403 process_encrypted_neighbour_queue (n);
1409 * Decrypt size bytes from in and write the result to out. Use the
1410 * key for inbound traffic of the given neighbour. This function does
1411 * NOT do any integrity-checks on the result.
1413 * @param n neighbour we are receiving from
1414 * @param iv initialization vector to use
1415 * @param in ciphertext
1416 * @param out plaintext
1417 * @param size size of in/out
1418 * @return GNUNET_OK on success
1421 do_decrypt (struct Neighbour *n,
1422 const GNUNET_HashCode * iv,
1423 const void *in, void *out, size_t size)
1425 if (size != (uint16_t) size)
1430 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1431 (n->status != PEER_STATE_KEY_CONFIRMED))
1433 GNUNET_break_op (0);
1434 return GNUNET_SYSERR;
1437 GNUNET_CRYPTO_aes_decrypt (in,
1441 GNUNET_CRYPTO_AesInitializationVector *) iv,
1445 return GNUNET_SYSERR;
1448 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1449 "Decrypted %u bytes from `%4s' using key %u\n",
1450 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1457 * Select messages for transmission. This heuristic uses a combination
1458 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1459 * and priority-based discard (in case no feasible schedule exist) and
1460 * speculative optimization (defer any kind of transmission until
1461 * we either create a batch of significant size, 25% of max, or until
1462 * we are close to a deadline). Furthermore, when scheduling the
1463 * heuristic also packs as many messages into the batch as possible,
1464 * starting with those with the earliest deadline. Yes, this is fun.
1466 * @param n neighbour to select messages from
1467 * @param size number of bytes to select for transmission
1468 * @param retry_time set to the time when we should try again
1469 * (only valid if this function returns zero)
1470 * @return number of bytes selected, or 0 if we decided to
1471 * defer scheduling overall; in that case, retry_time is set.
1474 select_messages (struct Neighbour *n,
1475 size_t size, struct GNUNET_TIME_Relative *retry_time)
1477 struct MessageEntry *pos;
1478 struct MessageEntry *min;
1479 struct MessageEntry *last;
1480 unsigned int min_prio;
1481 struct GNUNET_TIME_Absolute t;
1482 struct GNUNET_TIME_Absolute now;
1483 struct GNUNET_TIME_Relative delta;
1485 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1488 unsigned int queue_size;
1489 int discard_low_prio;
1491 GNUNET_assert (NULL != n->messages);
1492 now = GNUNET_TIME_absolute_get ();
1493 /* last entry in linked list of messages processed */
1495 /* should we remove the entry with the lowest
1496 priority from consideration for scheduling at the
1507 discard_low_prio = GNUNET_YES;
1508 while (GNUNET_YES == discard_low_prio)
1512 discard_low_prio = GNUNET_NO;
1513 /* calculate number of bytes available for transmission at time "t" */
1514 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1516 /* how many bytes have we (hypothetically) scheduled so far */
1518 /* maximum time we can wait before transmitting anything
1519 and still make all of our deadlines */
1520 slack = MAX_CORK_DELAY;
1522 /* note that we use "*2" here because we want to look
1523 a bit further into the future; much more makes no
1524 sense since new message might be scheduled in the
1526 while ((pos != NULL) && (off < size * 2))
1528 if (pos->do_transmit == GNUNET_YES)
1530 /* already removed from consideration */
1534 if (discard_low_prio == GNUNET_NO)
1536 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1537 if (delta.value > 0)
1539 // FIXME: HUH? Check!
1541 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1544 if (avail < pos->size)
1546 // FIXME: HUH? Check!
1547 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1552 /* update slack, considering both its absolute deadline
1553 and relative deadlines caused by other messages
1554 with their respective load */
1555 slack = GNUNET_TIME_relative_min (slack,
1556 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1558 if (pos->deadline.value <= now.value)
1561 slack = GNUNET_TIME_UNIT_ZERO;
1563 else if (GNUNET_YES == pos->got_slack)
1565 /* should be soon now! */
1566 slack = GNUNET_TIME_relative_min (slack,
1567 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1572 GNUNET_TIME_relative_min (slack,
1573 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1574 pos->got_slack = GNUNET_YES;
1575 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1576 GNUNET_TIME_relative_to_absolute (MAX_CORK_DELAY));
1581 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1582 if (pos->priority <= min_prio)
1584 /* update min for discard */
1585 min_prio = pos->priority;
1590 if (discard_low_prio)
1592 GNUNET_assert (min != NULL);
1593 /* remove lowest-priority entry from consideration */
1594 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1598 /* guard against sending "tiny" messages with large headers without
1600 if ( (slack.value > 0) &&
1602 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1604 /* less than 25% of message would be filled with deadlines still
1605 being met if we delay by one second or more; so just wait for
1606 more data; but do not wait longer than 1s (since we don't want
1607 to delay messages for a really long time either). */
1608 *retry_time = MAX_CORK_DELAY;
1609 /* reset do_transmit values for next time */
1612 pos->do_transmit = GNUNET_NO;
1616 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1617 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1618 (unsigned long long) slack.value,
1620 (unsigned int) size);
1624 /* select marked messages (up to size) for transmission */
1629 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1631 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1636 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1640 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1641 "Selected %u/%u bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1643 queue_size, MAX_PEER_QUEUE_SIZE,
1644 GNUNET_i2s (&n->peer));
1651 * Batch multiple messages into a larger buffer.
1653 * @param n neighbour to take messages from
1654 * @param buf target buffer
1655 * @param size size of buf
1656 * @param deadline set to transmission deadline for the result
1657 * @param retry_time set to the time when we should try again
1658 * (only valid if this function returns zero)
1659 * @param priority set to the priority of the batch
1660 * @return number of bytes written to buf (can be zero)
1663 batch_message (struct Neighbour *n,
1666 struct GNUNET_TIME_Absolute *deadline,
1667 struct GNUNET_TIME_Relative *retry_time,
1668 unsigned int *priority)
1670 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1671 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1672 struct MessageEntry *pos;
1673 struct MessageEntry *prev;
1674 struct MessageEntry *next;
1679 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1680 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1681 if (0 == select_messages (n, size, retry_time))
1684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1685 "No messages selected, will try again in %llu ms\n",
1690 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1691 ntm->distance = htonl (n->last_distance);
1692 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1693 ntm->peer = n->peer;
1697 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1700 if (GNUNET_YES == pos->do_transmit)
1702 GNUNET_assert (pos->size <= size);
1703 /* do notifications */
1704 /* FIXME: track if we have *any* client that wants
1705 full notifications and only do this if that is
1707 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1709 memcpy (&ntm[1], &pos[1], pos->size);
1710 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1711 sizeof (struct GNUNET_MessageHeader));
1712 send_to_all_clients (&ntm->header,
1714 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1718 /* message too large for 'full' notifications, we do at
1719 least the 'hdr' type */
1722 sizeof (struct GNUNET_MessageHeader));
1724 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1726 send_to_all_clients (&ntm->header,
1728 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1731 "Encrypting message of type %u\n",
1732 ntohs(((struct GNUNET_MessageHeader*)&pos[1])->type));
1734 /* copy for encrypted transmission */
1735 memcpy (&buf[ret], &pos[1], pos->size);
1738 *priority += pos->priority;
1740 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1741 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1743 GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1745 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1759 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1760 "Deadline for message batch is %llu ms\n",
1761 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1768 * Remove messages with deadlines that have long expired from
1771 * @param n neighbour to inspect
1774 discard_expired_messages (struct Neighbour *n)
1776 struct MessageEntry *prev;
1777 struct MessageEntry *next;
1778 struct MessageEntry *pos;
1779 struct GNUNET_TIME_Absolute now;
1780 struct GNUNET_TIME_Relative delta;
1782 now = GNUNET_TIME_absolute_get ();
1788 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1789 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1792 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1793 "Message is %llu ms past due, discarding.\n",
1810 * Signature of the main function of a task.
1812 * @param cls closure
1813 * @param tc context information (why was this task triggered now)
1816 retry_plaintext_processing (void *cls,
1817 const struct GNUNET_SCHEDULER_TaskContext *tc)
1819 struct Neighbour *n = cls;
1821 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1822 process_plaintext_neighbour_queue (n);
1827 * Send our key (and encrypted PING) to the other peer.
1829 * @param n the other peer
1831 static void send_key (struct Neighbour *n);
1834 * Task that will retry "send_key" if our previous attempt failed
1838 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1840 struct Neighbour *n = cls;
1843 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1844 "Retrying key transmission to `%4s'\n",
1845 GNUNET_i2s (&n->peer));
1847 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1848 n->set_key_retry_frequency =
1849 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1855 * Check if we have plaintext messages for the specified neighbour
1856 * pending, and if so, consider batching and encrypting them (and
1857 * then trigger processing of the encrypted queue if needed).
1859 * @param n neighbour to check.
1862 process_plaintext_neighbour_queue (struct Neighbour *n)
1864 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1867 struct EncryptedMessage *em; /* encrypted message */
1868 struct EncryptedMessage *ph; /* plaintext header */
1869 struct MessageEntry *me;
1870 unsigned int priority;
1871 struct GNUNET_TIME_Absolute deadline;
1872 struct GNUNET_TIME_Relative retry_time;
1875 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1877 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1878 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1882 case PEER_STATE_DOWN:
1885 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1886 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1887 GNUNET_i2s(&n->peer));
1890 case PEER_STATE_KEY_SENT:
1891 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1892 n->retry_set_key_task
1893 = GNUNET_SCHEDULER_add_delayed (sched,
1894 n->set_key_retry_frequency,
1895 &set_key_retry_task, n);
1897 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1898 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1899 GNUNET_i2s(&n->peer));
1902 case PEER_STATE_KEY_RECEIVED:
1903 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1904 n->retry_set_key_task
1905 = GNUNET_SCHEDULER_add_delayed (sched,
1906 n->set_key_retry_frequency,
1907 &set_key_retry_task, n);
1909 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1910 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1911 GNUNET_i2s(&n->peer));
1914 case PEER_STATE_KEY_CONFIRMED:
1915 /* ready to continue */
1918 discard_expired_messages (n);
1919 if (n->messages == NULL)
1922 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1923 "Plaintext message queue for `%4s' is empty.\n",
1924 GNUNET_i2s(&n->peer));
1926 return; /* no pending messages */
1928 if (n->encrypted_head != NULL)
1931 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1932 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1933 GNUNET_i2s(&n->peer));
1935 return; /* wait for messages already encrypted to be
1938 ph = (struct EncryptedMessage *) pbuf;
1939 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1941 used = sizeof (struct EncryptedMessage);
1942 used += batch_message (n,
1944 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1945 &deadline, &retry_time, &priority);
1946 if (used == sizeof (struct EncryptedMessage))
1949 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1950 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1951 GNUNET_i2s(&n->peer));
1953 /* no messages selected for sending, try again later... */
1954 n->retry_plaintext_task =
1955 GNUNET_SCHEDULER_add_delayed (sched,
1957 &retry_plaintext_processing, n);
1960 #if DEBUG_CORE_QUOTA
1961 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1962 "Sending %u b/s as new limit to peer `%4s'\n",
1963 (unsigned int) ntohl (n->bw_in.value__),
1964 GNUNET_i2s (&n->peer));
1966 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1));
1967 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1968 ph->inbound_bw_limit = n->bw_in;
1969 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1971 /* setup encryption message header */
1972 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1973 me->deadline = deadline;
1974 me->priority = priority;
1976 em = (struct EncryptedMessage *) &me[1];
1977 em->header.size = htons (used);
1978 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1979 em->iv_seed = ph->iv_seed;
1980 esize = used - ENCRYPTED_HEADER_SIZE;
1981 GNUNET_CRYPTO_hash (&ph->sequence_number,
1982 esize - sizeof (GNUNET_HashCode),
1983 &ph->plaintext_hash);
1984 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
1987 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1988 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
1990 GNUNET_i2s(&n->peer),
1991 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
1993 GNUNET_assert (GNUNET_OK ==
1996 &ph->plaintext_hash,
1997 &em->plaintext_hash, esize));
1998 /* append to transmission list */
1999 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2003 process_encrypted_neighbour_queue (n);
2008 * Function that recalculates the bandwidth quota for the
2009 * given neighbour and transmits it to the transport service.
2011 * @param cls neighbour for the quota update
2015 neighbour_quota_update (void *cls,
2016 const struct GNUNET_SCHEDULER_TaskContext *tc);
2020 * Schedule the task that will recalculate the bandwidth
2021 * quota for this peer (and possibly force a disconnect of
2022 * idle peers by calculating a bandwidth of zero).
2025 schedule_quota_update (struct Neighbour *n)
2027 GNUNET_assert (n->quota_update_task ==
2028 GNUNET_SCHEDULER_NO_TASK);
2029 n->quota_update_task
2030 = GNUNET_SCHEDULER_add_delayed (sched,
2031 QUOTA_UPDATE_FREQUENCY,
2032 &neighbour_quota_update,
2038 * Initialize a new 'struct Neighbour'.
2040 * @param pid ID of the new neighbour
2041 * @return handle for the new neighbour
2043 static struct Neighbour *
2044 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2046 struct Neighbour *n;
2047 struct GNUNET_TIME_Absolute now;
2049 n = GNUNET_malloc (sizeof (struct Neighbour));
2050 n->next = neighbours;
2054 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2055 now = GNUNET_TIME_absolute_get ();
2056 n->encrypt_key_created = now;
2057 n->last_activity = now;
2058 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2059 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2060 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2061 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init ((uint32_t) - 1);
2062 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2063 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2065 neighbour_quota_update (n, NULL);
2071 * Handle CORE_SEND request.
2074 * @param client the client issuing the request
2075 * @param message the "struct SendMessage"
2078 handle_client_send (void *cls,
2079 struct GNUNET_SERVER_Client *client,
2080 const struct GNUNET_MessageHeader *message)
2082 const struct SendMessage *sm;
2083 struct Neighbour *n;
2084 struct MessageEntry *prev;
2085 struct MessageEntry *pos;
2086 struct MessageEntry *e;
2087 struct MessageEntry *min_prio_entry;
2088 struct MessageEntry *min_prio_prev;
2089 unsigned int min_prio;
2090 unsigned int queue_size;
2093 msize = ntohs (message->size);
2095 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2099 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2102 sm = (const struct SendMessage *) message;
2103 msize -= sizeof (struct SendMessage);
2104 n = find_neighbour (&sm->peer);
2106 n = create_neighbour (&sm->peer);
2108 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2109 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2112 GNUNET_i2s (&sm->peer));
2114 /* bound queue size */
2115 discard_expired_messages (n);
2116 min_prio = (unsigned int) -1;
2117 min_prio_entry = NULL;
2118 min_prio_prev = NULL;
2124 if (pos->priority < min_prio)
2126 min_prio_entry = pos;
2127 min_prio_prev = prev;
2128 min_prio = pos->priority;
2134 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2137 if (ntohl(sm->priority) <= min_prio)
2139 /* discard new entry */
2141 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2142 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2144 MAX_PEER_QUEUE_SIZE,
2146 ntohs (message->type));
2149 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2152 /* discard "min_prio_entry" */
2154 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2155 "Queue full, discarding existing older request\n");
2157 if (min_prio_prev == NULL)
2158 n->messages = min_prio_entry->next;
2160 min_prio_prev->next = min_prio_entry->next;
2161 GNUNET_free (min_prio_entry);
2165 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2166 "Adding transmission request for `%4s' of size %u to queue\n",
2167 GNUNET_i2s (&sm->peer),
2170 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2171 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2172 e->priority = ntohl (sm->priority);
2174 memcpy (&e[1], &sm[1], msize);
2176 /* insert, keep list sorted by deadline */
2179 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2190 /* consider scheduling now */
2191 process_plaintext_neighbour_queue (n);
2193 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2198 * Function called when the transport service is ready to
2199 * receive a message. Only resets 'n->th' to NULL.
2201 * @param cls neighbour to use message from
2202 * @param size number of bytes we can transmit
2203 * @param buf where to copy the message
2204 * @return number of bytes transmitted
2207 notify_transport_connect_done (void *cls, size_t size, void *buf)
2209 struct Neighbour *n = cls;
2214 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2215 _("Failed to connect to `%4s': transport failed to connect\n"),
2216 GNUNET_i2s (&n->peer));
2225 * Handle CORE_REQUEST_CONNECT request.
2228 * @param client the client issuing the request
2229 * @param message the "struct ConnectMessage"
2232 handle_client_request_connect (void *cls,
2233 struct GNUNET_SERVER_Client *client,
2234 const struct GNUNET_MessageHeader *message)
2236 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2237 struct Neighbour *n;
2238 struct GNUNET_TIME_Relative timeout;
2240 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2243 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2246 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2247 n = find_neighbour (&cm->peer);
2249 n = create_neighbour (&cm->peer);
2250 if ( (n->is_connected) ||
2252 return; /* already connected, or at least trying */
2254 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2255 "Core received `%s' request for `%4s', will try to establish connection\n",
2257 GNUNET_i2s (&cm->peer));
2259 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2260 /* ask transport to connect to the peer */
2261 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2263 sizeof (struct GNUNET_MessageHeader), 0,
2265 ¬ify_transport_connect_done,
2267 GNUNET_break (NULL != n->th);
2272 * List of handlers for the messages understood by this
2275 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2276 {&handle_client_init, NULL,
2277 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2278 {&handle_client_request_info, NULL,
2279 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2280 sizeof (struct RequestInfoMessage)},
2281 {&handle_client_send, NULL,
2282 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2283 {&handle_client_request_connect, NULL,
2284 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2285 sizeof (struct ConnectMessage)},
2291 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2292 * the neighbour's struct and retry send_key. Or, if we did not get a
2293 * HELLO, just do nothing.
2295 * @param cls the 'struct Neighbour' to retry sending the key for
2296 * @param peer the peer for which this is the HELLO
2297 * @param hello HELLO message of that peer
2298 * @param trust amount of trust we currently have in that peer
2301 process_hello_retry_send_key (void *cls,
2302 const struct GNUNET_PeerIdentity *peer,
2303 const struct GNUNET_HELLO_Message *hello,
2306 struct Neighbour *n = cls;
2311 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2312 "Entered `process_hello_retry_send_key' and `peer' is NULL!\n");
2315 if (n->public_key != NULL)
2321 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2322 n->retry_set_key_task
2323 = GNUNET_SCHEDULER_add_delayed (sched,
2324 n->set_key_retry_frequency,
2325 &set_key_retry_task, n);
2331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2332 "Entered `process_hello_retry_send_key' for peer `%4s'\n",
2335 if (n->public_key != NULL)
2338 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2339 "already have public key for peer %s!! (so why are we here?)\n",
2346 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2347 "Received new `%s' message for `%4s', initiating key exchange.\n",
2352 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2353 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2355 GNUNET_free (n->public_key);
2356 n->public_key = NULL;
2358 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2359 "GNUNET_HELLO_get_key returned awfully\n");
2367 * Send our key (and encrypted PING) to the other peer.
2369 * @param n the other peer
2372 send_key (struct Neighbour *n)
2374 struct SetKeyMessage *sm;
2375 struct MessageEntry *me;
2376 struct PingMessage pp;
2377 struct PingMessage *pm;
2379 if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2383 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2384 "Key exchange in progress with `%4s'.\n",
2385 GNUNET_i2s (&n->peer));
2387 return; /* already in progress */
2391 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2392 "Asked to perform key exchange with `%4s'.\n",
2393 GNUNET_i2s (&n->peer));
2395 if (n->public_key == NULL)
2397 /* lookup n's public key, then try again */
2399 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2400 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2401 GNUNET_i2s (&n->peer));
2403 GNUNET_assert (n->pitr == NULL);
2404 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2408 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2409 &process_hello_retry_send_key, n);
2412 /* first, set key message */
2413 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2414 sizeof (struct SetKeyMessage));
2415 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2416 me->priority = SET_KEY_PRIORITY;
2417 me->size = sizeof (struct SetKeyMessage);
2418 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2422 sm = (struct SetKeyMessage *) &me[1];
2423 sm->header.size = htons (sizeof (struct SetKeyMessage));
2424 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2425 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2426 PEER_STATE_KEY_SENT : n->status));
2428 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2429 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2430 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2431 sizeof (struct GNUNET_PeerIdentity));
2432 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2433 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2434 sm->target = n->peer;
2435 GNUNET_assert (GNUNET_OK ==
2436 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2438 GNUNET_CRYPTO_AesSessionKey),
2440 &sm->encrypted_key));
2441 GNUNET_assert (GNUNET_OK ==
2442 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2445 /* second, encrypted PING message */
2446 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2447 sizeof (struct PingMessage));
2448 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2449 me->priority = PING_PRIORITY;
2450 me->size = sizeof (struct PingMessage);
2451 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2455 pm = (struct PingMessage *) &me[1];
2456 pm->header.size = htons (sizeof (struct PingMessage));
2457 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2458 pp.challenge = htonl (n->ping_challenge);
2459 pp.target = n->peer;
2461 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2462 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2463 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2464 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2465 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2467 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2470 &n->peer.hashPubKey,
2473 sizeof (struct PingMessage) -
2474 sizeof (struct GNUNET_MessageHeader));
2478 case PEER_STATE_DOWN:
2479 n->status = PEER_STATE_KEY_SENT;
2481 case PEER_STATE_KEY_SENT:
2483 case PEER_STATE_KEY_RECEIVED:
2485 case PEER_STATE_KEY_CONFIRMED:
2492 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2493 "Have %llu ms left for `%s' transmission.\n",
2494 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2497 /* trigger queue processing */
2498 process_encrypted_neighbour_queue (n);
2499 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2500 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2501 n->retry_set_key_task
2502 = GNUNET_SCHEDULER_add_delayed (sched,
2503 n->set_key_retry_frequency,
2504 &set_key_retry_task, n);
2509 * We received a SET_KEY message. Validate and update
2510 * our key material and status.
2512 * @param n the neighbour from which we received message m
2513 * @param m the set key message we received
2516 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2520 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2521 * the neighbour's struct and retry handling the set_key message. Or,
2522 * if we did not get a HELLO, just free the set key message.
2524 * @param cls pointer to the set key message
2525 * @param peer the peer for which this is the HELLO
2526 * @param hello HELLO message of that peer
2527 * @param trust amount of trust we currently have in that peer
2530 process_hello_retry_handle_set_key (void *cls,
2531 const struct GNUNET_PeerIdentity *peer,
2532 const struct GNUNET_HELLO_Message *hello,
2535 struct Neighbour *n = cls;
2536 struct SetKeyMessage *sm = n->skm;
2545 if (n->public_key != NULL)
2546 return; /* multiple HELLOs match!? */
2548 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2549 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2551 GNUNET_break_op (0);
2552 GNUNET_free (n->public_key);
2553 n->public_key = NULL;
2557 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2558 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2559 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2561 handle_set_key (n, sm);
2566 * We received a PING message. Validate and transmit
2569 * @param n sender of the PING
2570 * @param m the encrypted PING message itself
2573 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2575 struct PingMessage t;
2576 struct PongMessage tx;
2577 struct PongMessage *tp;
2578 struct MessageEntry *me;
2581 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2582 "Core service receives `%s' request from `%4s'.\n",
2583 "PING", GNUNET_i2s (&n->peer));
2587 &my_identity.hashPubKey,
2590 sizeof (struct PingMessage) -
2591 sizeof (struct GNUNET_MessageHeader)))
2594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2595 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2597 GNUNET_i2s (&t.target),
2598 ntohl (t.challenge), n->decrypt_key.crc32);
2599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2600 "Target of `%s' request is `%4s'.\n",
2601 "PING", GNUNET_i2s (&t.target));
2603 if (0 != memcmp (&t.target,
2604 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2606 GNUNET_break_op (0);
2609 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2610 sizeof (struct PongMessage));
2611 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2615 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2616 me->priority = PONG_PRIORITY;
2617 me->size = sizeof (struct PongMessage);
2618 tx.reserved = htonl (0);
2619 tx.inbound_bw_limit = n->bw_in;
2620 tx.challenge = t.challenge;
2621 tx.target = t.target;
2622 tp = (struct PongMessage *) &me[1];
2623 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2624 tp->header.size = htons (sizeof (struct PongMessage));
2626 &my_identity.hashPubKey,
2629 sizeof (struct PongMessage) -
2630 sizeof (struct GNUNET_MessageHeader));
2632 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2633 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2634 ntohl (t.challenge), n->encrypt_key.crc32);
2636 /* trigger queue processing */
2637 process_encrypted_neighbour_queue (n);
2642 * We received a PONG message. Validate and update our status.
2644 * @param n sender of the PONG
2645 * @param m the encrypted PONG message itself
2648 handle_pong (struct Neighbour *n,
2649 const struct PongMessage *m)
2651 struct PongMessage t;
2652 struct ConnectNotifyMessage cnm;
2655 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2656 "Core service receives `%s' request from `%4s'.\n",
2657 "PONG", GNUNET_i2s (&n->peer));
2661 &n->peer.hashPubKey,
2664 sizeof (struct PongMessage) -
2665 sizeof (struct GNUNET_MessageHeader)))
2667 if (0 != ntohl (t.reserved))
2669 GNUNET_break_op (0);
2673 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2674 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2676 GNUNET_i2s (&t.target),
2677 ntohl (t.challenge), n->decrypt_key.crc32);
2679 if ((0 != memcmp (&t.target,
2681 sizeof (struct GNUNET_PeerIdentity))) ||
2682 (n->ping_challenge != ntohl (t.challenge)))
2684 /* PONG malformed */
2686 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2687 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2688 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2689 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2690 "Received malformed `%s' received from `%4s' with challenge %u\n",
2691 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2693 GNUNET_break_op (0);
2698 case PEER_STATE_DOWN:
2699 GNUNET_break (0); /* should be impossible */
2701 case PEER_STATE_KEY_SENT:
2702 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2704 case PEER_STATE_KEY_RECEIVED:
2705 n->status = PEER_STATE_KEY_CONFIRMED;
2706 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2708 n->bw_out_external_limit = t.inbound_bw_limit;
2709 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2710 n->bw_out_internal_limit);
2711 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2713 GNUNET_TRANSPORT_set_quota (transport,
2717 GNUNET_TIME_UNIT_FOREVER_REL,
2721 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2722 "Confirmed key via `%s' message for peer `%4s'\n",
2723 "PONG", GNUNET_i2s (&n->peer));
2725 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2727 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2728 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2730 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2731 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2732 cnm.distance = htonl (n->last_distance);
2733 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2735 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2736 process_encrypted_neighbour_queue (n);
2738 case PEER_STATE_KEY_CONFIRMED:
2739 n->last_activity = GNUNET_TIME_absolute_get ();
2740 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2741 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2743 = GNUNET_SCHEDULER_add_delayed (sched,
2744 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2756 * We received a SET_KEY message. Validate and update
2757 * our key material and status.
2759 * @param n the neighbour from which we received message m
2760 * @param m the set key message we received
2763 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2765 struct SetKeyMessage *m_cpy;
2766 struct GNUNET_TIME_Absolute t;
2767 struct GNUNET_CRYPTO_AesSessionKey k;
2768 struct PingMessage *ping;
2769 struct PongMessage *pong;
2770 enum PeerStateMachine sender_status;
2773 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2774 "Core service receives `%s' request from `%4s'.\n",
2775 "SET_KEY", GNUNET_i2s (&n->peer));
2777 if (n->public_key == NULL)
2779 if (n->pitr != NULL)
2782 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2783 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2789 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2790 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2792 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2793 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2794 /* lookup n's public key, then try again */
2795 GNUNET_assert (n->skm == NULL);
2797 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2801 GNUNET_TIME_UNIT_MINUTES,
2802 &process_hello_retry_handle_set_key, n);
2805 if (0 != memcmp (&m->target,
2807 sizeof (struct GNUNET_PeerIdentity)))
2809 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2810 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
2812 GNUNET_i2s (&m->target));
2815 if ((ntohl (m->purpose.size) !=
2816 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2817 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2818 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2819 sizeof (struct GNUNET_PeerIdentity)) ||
2821 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2822 &m->purpose, &m->signature, n->public_key)))
2824 /* invalid signature */
2825 GNUNET_break_op (0);
2828 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2829 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2830 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2831 (t.value < n->decrypt_key_created.value))
2833 /* this could rarely happen due to massive re-ordering of
2834 messages on the network level, but is most likely either
2835 a bug or some adversary messing with us. Report. */
2836 GNUNET_break_op (0);
2840 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2841 "Decrypting key material.\n");
2843 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2846 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2847 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2848 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2850 /* failed to decrypt !? */
2851 GNUNET_break_op (0);
2856 if (n->decrypt_key_created.value != t.value)
2858 /* fresh key, reset sequence numbers */
2859 n->last_sequence_number_received = 0;
2860 n->last_packets_bitmap = 0;
2861 n->decrypt_key_created = t;
2863 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2866 case PEER_STATE_DOWN:
2867 n->status = PEER_STATE_KEY_RECEIVED;
2869 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2870 "Responding to `%s' with my own key.\n", "SET_KEY");
2874 case PEER_STATE_KEY_SENT:
2875 case PEER_STATE_KEY_RECEIVED:
2876 n->status = PEER_STATE_KEY_RECEIVED;
2877 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2878 (sender_status != PEER_STATE_KEY_CONFIRMED))
2881 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2882 "Responding to `%s' with my own key (other peer has status %u).\n",
2883 "SET_KEY", sender_status);
2888 case PEER_STATE_KEY_CONFIRMED:
2889 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2890 (sender_status != PEER_STATE_KEY_CONFIRMED))
2893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2894 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2895 "SET_KEY", sender_status);
2904 if (n->pending_ping != NULL)
2906 ping = n->pending_ping;
2907 n->pending_ping = NULL;
2908 handle_ping (n, ping);
2911 if (n->pending_pong != NULL)
2913 pong = n->pending_pong;
2914 n->pending_pong = NULL;
2915 handle_pong (n, pong);
2922 * Send a P2P message to a client.
2924 * @param sender who sent us the message?
2925 * @param client who should we give the message to?
2926 * @param m contains the message to transmit
2927 * @param msize number of bytes in buf to transmit
2930 send_p2p_message_to_client (struct Neighbour *sender,
2931 struct Client *client,
2932 const void *m, size_t msize)
2934 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2935 struct NotifyTrafficMessage *ntm;
2938 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2939 "Core service passes message from `%4s' of type %u to client.\n",
2940 GNUNET_i2s(&sender->peer),
2941 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2943 ntm = (struct NotifyTrafficMessage *) buf;
2944 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2945 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2946 ntm->distance = htonl (sender->last_distance);
2947 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
2948 ntm->peer = sender->peer;
2949 memcpy (&ntm[1], m, msize);
2950 send_to_client (client, &ntm->header, GNUNET_YES);
2955 * Deliver P2P message to interested clients.
2957 * @param sender who sent us the message?
2958 * @param m the message
2959 * @param msize size of the message (including header)
2962 deliver_message (struct Neighbour *sender,
2963 const struct GNUNET_MessageHeader *m, size_t msize)
2965 struct Client *cpos;
2971 type = ntohs (m->type);
2973 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2974 "Received encapsulated message of type %u from `%4s'\n",
2976 GNUNET_i2s (&sender->peer));
2978 dropped = GNUNET_YES;
2980 while (cpos != NULL)
2982 deliver_full = GNUNET_NO;
2983 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
2984 deliver_full = GNUNET_YES;
2987 for (tpos = 0; tpos < cpos->tcnt; tpos++)
2989 if (type != cpos->types[tpos])
2991 deliver_full = GNUNET_YES;
2995 if (GNUNET_YES == deliver_full)
2997 send_p2p_message_to_client (sender, cpos, m, msize);
2998 dropped = GNUNET_NO;
3000 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3002 send_p2p_message_to_client (sender, cpos, m,
3003 sizeof (struct GNUNET_MessageHeader));
3007 if (dropped == GNUNET_YES)
3010 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3011 "Message of type %u from `%4s' not delivered to any client.\n",
3013 GNUNET_i2s (&sender->peer));
3015 /* FIXME: stats... */
3021 * Align P2P message and then deliver to interested clients.
3023 * @param sender who sent us the message?
3024 * @param buffer unaligned (!) buffer containing message
3025 * @param msize size of the message (including header)
3028 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
3032 /* TODO: call to statistics? */
3033 memcpy (abuf, buffer, msize);
3034 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
3039 * Deliver P2P messages to interested clients.
3041 * @param sender who sent us the message?
3042 * @param buffer buffer containing messages, can be modified
3043 * @param buffer_size size of the buffer (overall)
3044 * @param offset offset where messages in the buffer start
3047 deliver_messages (struct Neighbour *sender,
3048 const char *buffer, size_t buffer_size, size_t offset)
3050 struct GNUNET_MessageHeader *mhp;
3051 struct GNUNET_MessageHeader mh;
3055 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
3057 if (0 != offset % sizeof (uint16_t))
3059 /* outch, need to copy to access header */
3060 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
3065 /* can access header directly */
3066 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
3068 msize = ntohs (mhp->size);
3069 if (msize + offset > buffer_size)
3071 /* malformed message, header says it is larger than what
3072 would fit into the overall buffer */
3073 GNUNET_break_op (0);
3076 #if HAVE_UNALIGNED_64_ACCESS
3077 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
3079 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
3081 if (GNUNET_YES == need_align)
3082 align_and_deliver (sender, &buffer[offset], msize);
3084 deliver_message (sender,
3085 (const struct GNUNET_MessageHeader *)
3086 &buffer[offset], msize);
3093 * We received an encrypted message. Decrypt, validate and
3094 * pass on to the appropriate clients.
3097 handle_encrypted_message (struct Neighbour *n,
3098 const struct EncryptedMessage *m)
3100 size_t size = ntohs (m->header.size);
3102 struct EncryptedMessage *pt; /* plaintext */
3106 struct GNUNET_TIME_Absolute t;
3110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3111 "Core service receives `%s' request from `%4s'.\n",
3112 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3114 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3120 &buf[ENCRYPTED_HEADER_SIZE],
3121 size - ENCRYPTED_HEADER_SIZE))
3123 pt = (struct EncryptedMessage *) buf;
3126 GNUNET_CRYPTO_hash (&pt->sequence_number,
3127 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3128 if (0 != memcmp (&ph,
3129 &pt->plaintext_hash,
3130 sizeof (GNUNET_HashCode)))
3132 /* checksum failed */
3133 GNUNET_break_op (0);
3137 /* validate sequence number */
3138 snum = ntohl (pt->sequence_number);
3139 if (n->last_sequence_number_received == snum)
3141 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3142 "Received duplicate message, ignoring.\n");
3143 /* duplicate, ignore */
3146 if ((n->last_sequence_number_received > snum) &&
3147 (n->last_sequence_number_received - snum > 32))
3149 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3150 "Received ancient out of sequence message, ignoring.\n");
3151 /* ancient out of sequence, ignore */
3154 if (n->last_sequence_number_received > snum)
3156 unsigned int rotbit =
3157 1 << (n->last_sequence_number_received - snum - 1);
3158 if ((n->last_packets_bitmap & rotbit) != 0)
3160 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3161 "Received duplicate message, ignoring.\n");
3162 /* duplicate, ignore */
3165 n->last_packets_bitmap |= rotbit;
3167 if (n->last_sequence_number_received < snum)
3169 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3170 n->last_sequence_number_received = snum;
3173 /* check timestamp */
3174 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3175 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3177 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3179 ("Message received far too old (%llu ms). Content ignored.\n"),
3180 GNUNET_TIME_absolute_get_duration (t).value);
3184 /* process decrypted message(s) */
3185 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3187 #if DEBUG_CORE_SET_QUOTA
3188 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3189 "Received %u b/s as new inbound limit for peer `%4s'\n",
3190 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3191 GNUNET_i2s (&n->peer));
3193 n->bw_out_external_limit = pt->inbound_bw_limit;
3194 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3195 n->bw_out_internal_limit);
3196 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3198 GNUNET_TRANSPORT_set_quota (transport,
3202 GNUNET_TIME_UNIT_FOREVER_REL,
3205 n->last_activity = GNUNET_TIME_absolute_get ();
3206 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3207 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3209 = GNUNET_SCHEDULER_add_delayed (sched,
3210 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3213 off = sizeof (struct EncryptedMessage);
3214 deliver_messages (n, buf, size, off);
3219 * Function called by the transport for each received message.
3221 * @param cls closure
3222 * @param peer (claimed) identity of the other peer
3223 * @param message the message
3224 * @param latency estimated latency for communicating with the
3225 * given peer (round-trip)
3226 * @param distance in overlay hops, as given by transport plugin
3229 handle_transport_receive (void *cls,
3230 const struct GNUNET_PeerIdentity *peer,
3231 const struct GNUNET_MessageHeader *message,
3232 struct GNUNET_TIME_Relative latency,
3233 unsigned int distance)
3235 struct Neighbour *n;
3236 struct GNUNET_TIME_Absolute now;
3242 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3243 "Received message of type %u from `%4s', demultiplexing.\n",
3244 ntohs (message->type), GNUNET_i2s (peer));
3246 n = find_neighbour (peer);
3248 n = create_neighbour (peer);
3251 n->last_latency = latency;
3252 n->last_distance = distance;
3253 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3254 type = ntohs (message->type);
3255 size = ntohs (message->size);
3258 "Received message of type %u from `%4s'\n",
3264 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3265 if (size != sizeof (struct SetKeyMessage))
3267 GNUNET_break_op (0);
3270 handle_set_key (n, (const struct SetKeyMessage *) message);
3272 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3273 if (size < sizeof (struct EncryptedMessage) +
3274 sizeof (struct GNUNET_MessageHeader))
3276 GNUNET_break_op (0);
3279 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3280 (n->status != PEER_STATE_KEY_CONFIRMED))
3282 GNUNET_break_op (0);
3285 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3287 case GNUNET_MESSAGE_TYPE_CORE_PING:
3288 if (size != sizeof (struct PingMessage))
3290 GNUNET_break_op (0);
3293 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3294 (n->status != PEER_STATE_KEY_CONFIRMED))
3297 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3298 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3299 "PING", GNUNET_i2s (&n->peer));
3301 GNUNET_free_non_null (n->pending_ping);
3302 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3303 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3306 handle_ping (n, (const struct PingMessage *) message);
3308 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3309 if (size != sizeof (struct PongMessage))
3311 GNUNET_break_op (0);
3314 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3315 (n->status != PEER_STATE_KEY_CONFIRMED) )
3318 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3319 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3320 "PONG", GNUNET_i2s (&n->peer));
3322 GNUNET_free_non_null (n->pending_pong);
3323 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3324 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3327 handle_pong (n, (const struct PongMessage *) message);
3330 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3331 _("Unsupported message of type %u received.\n"), type);
3334 if (n->status == PEER_STATE_KEY_CONFIRMED)
3336 now = GNUNET_TIME_absolute_get ();
3337 n->last_activity = now;
3339 n->time_established = now;
3340 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3341 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3343 = GNUNET_SCHEDULER_add_delayed (sched,
3344 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3352 * Function that recalculates the bandwidth quota for the
3353 * given neighbour and transmits it to the transport service.
3355 * @param cls neighbour for the quota update
3359 neighbour_quota_update (void *cls,
3360 const struct GNUNET_SCHEDULER_TaskContext *tc)
3362 struct Neighbour *n = cls;
3363 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3366 unsigned long long distributable;
3367 uint64_t need_per_peer;
3368 uint64_t need_per_second;
3370 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3371 /* calculate relative preference among all neighbours;
3372 divides by a bit more to avoid division by zero AND to
3373 account for possibility of new neighbours joining any time
3374 AND to convert to double... */
3375 if (preference_sum == 0)
3377 pref_rel = 1.0 / (double) neighbour_count;
3381 pref_rel = n->current_preference / preference_sum;
3383 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3384 GNUNET_TIME_UNIT_SECONDS);
3385 need_per_second = need_per_peer * neighbour_count;
3387 if (bandwidth_target_out_bps > need_per_second)
3388 distributable = bandwidth_target_out_bps - need_per_second;
3389 share = distributable * pref_rel;
3390 if (share + need_per_peer > ( (uint32_t)-1))
3391 q_in = GNUNET_BANDWIDTH_value_init ((uint32_t) -1);
3393 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3394 /* check if we want to disconnect for good due to inactivity */
3395 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3396 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3399 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3400 "Forcing disconnect of `%4s' due to inactivity (?).\n",
3401 GNUNET_i2s (&n->peer));
3403 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3405 #if DEBUG_CORE_QUOTA
3406 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3407 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3408 GNUNET_i2s (&n->peer),
3409 (unsigned int) ntohl (q_in.value__),
3410 bandwidth_target_out_bps,
3411 (unsigned int) ntohl (n->bw_in.value__),
3412 (unsigned int) ntohl (n->bw_out.value__),
3413 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3415 if (n->bw_in.value__ != q_in.value__)
3418 GNUNET_TRANSPORT_set_quota (transport,
3422 GNUNET_TIME_UNIT_FOREVER_REL,
3425 schedule_quota_update (n);
3430 * Function called by transport to notify us that
3431 * a peer connected to us (on the network level).
3433 * @param cls closure
3434 * @param peer the peer that connected
3435 * @param latency current latency of the connection
3436 * @param distance in overlay hops, as given by transport plugin
3439 handle_transport_notify_connect (void *cls,
3440 const struct GNUNET_PeerIdentity *peer,
3441 struct GNUNET_TIME_Relative latency,
3442 unsigned int distance)
3444 struct Neighbour *n;
3445 struct ConnectNotifyMessage cnm;
3447 n = find_neighbour (peer);
3450 if (n->is_connected)
3452 /* duplicate connect notification!? */
3459 n = create_neighbour (peer);
3461 n->is_connected = GNUNET_YES;
3462 n->last_latency = latency;
3463 n->last_distance = distance;
3464 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3467 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3471 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3472 "Received connection from `%4s'.\n",
3473 GNUNET_i2s (&n->peer));
3475 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3476 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3477 cnm.distance = htonl (n->last_distance);
3478 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3480 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3481 GNUNET_TRANSPORT_set_quota (transport,
3485 GNUNET_TIME_UNIT_FOREVER_REL,
3492 * Function called by transport telling us that a peer
3495 * @param cls closure
3496 * @param peer the peer that disconnected
3499 handle_transport_notify_disconnect (void *cls,
3500 const struct GNUNET_PeerIdentity *peer)
3502 struct DisconnectNotifyMessage cnm;
3503 struct Neighbour *n;
3506 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3507 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3509 n = find_neighbour (peer);
3515 GNUNET_break (n->is_connected);
3516 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3517 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3519 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3520 n->is_connected = GNUNET_NO;
3525 * Last task run during shutdown. Disconnects us from
3529 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3531 struct Neighbour *n;
3535 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3536 "Core service shutting down.\n");
3538 GNUNET_assert (transport != NULL);
3539 GNUNET_TRANSPORT_disconnect (transport);
3541 while (NULL != (n = neighbours))
3543 neighbours = n->next;
3544 GNUNET_assert (neighbour_count > 0);
3548 GNUNET_SERVER_notification_context_destroy (notifier);
3550 while (NULL != (c = clients))
3551 handle_client_disconnect (NULL, c->client_handle);
3552 if (my_private_key != NULL)
3553 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3558 * Initiate core service.
3560 * @param cls closure
3561 * @param s scheduler to use
3562 * @param serv the initialized server
3563 * @param c configuration to use
3567 struct GNUNET_SCHEDULER_Handle *s,
3568 struct GNUNET_SERVER_Handle *serv,
3569 const struct GNUNET_CONFIGURATION_Handle *c)
3575 /* parse configuration */
3578 GNUNET_CONFIGURATION_get_value_number (c,
3581 &bandwidth_target_in_bps)) ||
3583 GNUNET_CONFIGURATION_get_value_number (c,
3586 &bandwidth_target_out_bps)) ||
3588 GNUNET_CONFIGURATION_get_value_filename (c,
3590 "HOSTKEY", &keyfile)))
3592 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3594 ("Core service is lacking key configuration settings. Exiting.\n"));
3595 GNUNET_SCHEDULER_shutdown (s);
3598 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3599 GNUNET_free (keyfile);
3600 if (my_private_key == NULL)
3602 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3603 _("Core service could not access hostkey. Exiting.\n"));
3604 GNUNET_SCHEDULER_shutdown (s);
3607 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3608 GNUNET_CRYPTO_hash (&my_public_key,
3609 sizeof (my_public_key), &my_identity.hashPubKey);
3610 /* setup notification */
3612 notifier = GNUNET_SERVER_notification_context_create (server,
3614 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3615 /* setup transport connection */
3616 transport = GNUNET_TRANSPORT_connect (sched,
3619 &handle_transport_receive,
3620 &handle_transport_notify_connect,
3621 &handle_transport_notify_disconnect);
3622 GNUNET_assert (NULL != transport);
3623 GNUNET_SCHEDULER_add_delayed (sched,
3624 GNUNET_TIME_UNIT_FOREVER_REL,
3625 &cleaning_task, NULL);
3626 /* process client requests */
3627 GNUNET_SERVER_add_handlers (server, handlers);
3628 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3629 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3635 * The main function for the transport service.
3637 * @param argc number of arguments from the command line
3638 * @param argv command line arguments
3639 * @return 0 ok, 1 on error
3642 main (int argc, char *const *argv)
3644 return (GNUNET_OK ==
3645 GNUNET_SERVICE_run (argc,
3648 GNUNET_SERVICE_OPTION_NONE,
3649 &run, NULL)) ? 0 : 1;
3652 /* end of gnunet-service-core.c */