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 /* notify new client about existing neighbours */
889 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
890 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
894 if (n->status == PEER_STATE_KEY_CONFIRMED)
896 #if DEBUG_CORE_CLIENT
897 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
898 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
900 cnm.distance = htonl (n->last_distance);
901 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
903 send_to_client (c, &cnm.header, GNUNET_NO);
907 GNUNET_SERVER_receive_done (client, GNUNET_OK);
912 * A client disconnected, clean up.
915 * @param client identification of the client
918 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
925 #if DEBUG_CORE_CLIENT
926 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
927 "Client %p has disconnected from core service.\n",
934 if (client == pos->client_handle)
939 prev->next = pos->next;
946 /* client never sent INIT */
951 * Handle REQUEST_INFO request.
954 handle_client_request_info (void *cls,
955 struct GNUNET_SERVER_Client *client,
956 const struct GNUNET_MessageHeader *message)
958 const struct RequestInfoMessage *rcm;
960 struct ConfigurationInfoMessage cim;
963 unsigned long long old_preference;
964 struct GNUNET_SERVER_TransmitContext *tc;
966 #if DEBUG_CORE_CLIENT
967 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
968 "Core service receives `%s' request.\n", "REQUEST_INFO");
970 rcm = (const struct RequestInfoMessage *) message;
971 n = find_neighbour (&rcm->peer);
972 memset (&cim, 0, sizeof (cim));
975 want_reserv = ntohl (rcm->reserve_inbound);
976 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
978 n->bw_out_internal_limit = rcm->limit_outbound;
979 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
980 n->bw_out_external_limit);
981 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
983 GNUNET_TRANSPORT_set_quota (transport,
987 GNUNET_TIME_UNIT_FOREVER_REL,
992 got_reserv = want_reserv;
994 else if (want_reserv > 0)
996 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
997 want_reserv).value == 0)
998 got_reserv = want_reserv;
1000 got_reserv = 0; /* all or nothing */
1004 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1006 old_preference = n->current_preference;
1007 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1008 if (old_preference > n->current_preference)
1010 /* overflow; cap at maximum value */
1011 n->current_preference = (unsigned long long) -1;
1013 update_preference_sum (n->current_preference - old_preference);
1014 #if DEBUG_CORE_QUOTA
1015 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1016 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1018 GNUNET_i2s (&rcm->peer),
1021 cim.reserved_amount = htonl (got_reserv);
1022 cim.bw_in = n->bw_in;
1023 cim.bw_out = n->bw_out;
1024 cim.preference = n->current_preference;
1026 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1027 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1028 cim.peer = rcm->peer;
1030 #if DEBUG_CORE_CLIENT
1031 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1032 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1034 tc = GNUNET_SERVER_transmit_context_create (client);
1035 GNUNET_SERVER_transmit_context_append_message (tc, &cim.header);
1036 GNUNET_SERVER_transmit_context_run (tc,
1037 GNUNET_TIME_UNIT_FOREVER_REL);
1042 * Free the given entry for the neighbour (it has
1043 * already been removed from the list at this point).
1045 * @param n neighbour to free
1048 free_neighbour (struct Neighbour *n)
1050 struct MessageEntry *m;
1052 if (n->pitr != NULL)
1054 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1059 GNUNET_free (n->skm);
1062 while (NULL != (m = n->messages))
1064 n->messages = m->next;
1067 while (NULL != (m = n->encrypted_head))
1069 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1076 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1079 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1080 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1081 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1082 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
1083 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1084 GNUNET_SCHEDULER_cancel (sched, n->quota_update_task);
1085 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1086 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1087 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1088 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
1089 GNUNET_free_non_null (n->public_key);
1090 GNUNET_free_non_null (n->pending_ping);
1091 GNUNET_free_non_null (n->pending_pong);
1097 * Check if we have encrypted messages for the specified neighbour
1098 * pending, and if so, check with the transport about sending them
1101 * @param n neighbour to check.
1103 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1107 * Encrypt size bytes from in and write the result to out. Use the
1108 * key for outbound traffic of the given neighbour.
1110 * @param n neighbour we are sending to
1111 * @param iv initialization vector to use
1112 * @param in ciphertext
1113 * @param out plaintext
1114 * @param size size of in/out
1115 * @return GNUNET_OK on success
1118 do_encrypt (struct Neighbour *n,
1119 const GNUNET_HashCode * iv,
1120 const void *in, void *out, size_t size)
1122 if (size != (uint16_t) size)
1127 GNUNET_assert (size ==
1128 GNUNET_CRYPTO_aes_encrypt (in,
1132 GNUNET_CRYPTO_AesInitializationVector
1135 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1136 "Encrypted %u bytes for `%4s' using key %u\n", size,
1137 GNUNET_i2s (&n->peer), n->encrypt_key.crc32);
1144 * Consider freeing the given neighbour since we may not need
1145 * to keep it around anymore.
1147 * @param n neighbour to consider discarding
1150 consider_free_neighbour (struct Neighbour *n);
1154 * Task triggered when a neighbour entry is about to time out
1155 * (and we should prevent this by sending a PING).
1157 * @param cls the 'struct Neighbour'
1158 * @param tc scheduler context (not used)
1161 send_keep_alive (void *cls,
1162 const struct GNUNET_SCHEDULER_TaskContext *tc)
1164 struct Neighbour *n = cls;
1165 struct GNUNET_TIME_Relative retry;
1166 struct GNUNET_TIME_Relative left;
1167 struct MessageEntry *me;
1168 struct PingMessage pp;
1169 struct PingMessage *pm;
1171 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1173 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1174 sizeof (struct PingMessage));
1175 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1176 me->priority = PING_PRIORITY;
1177 me->size = sizeof (struct PingMessage);
1178 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1182 pm = (struct PingMessage *) &me[1];
1183 pm->header.size = htons (sizeof (struct PingMessage));
1184 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1185 pp.challenge = htonl (n->ping_challenge);
1186 pp.target = n->peer;
1188 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1189 "Encrypting `%s' and `%s' messages for `%4s'.\n",
1190 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
1191 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1192 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
1194 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
1197 &n->peer.hashPubKey,
1200 sizeof (struct PingMessage) -
1201 sizeof (struct GNUNET_MessageHeader));
1202 process_encrypted_neighbour_queue (n);
1203 /* reschedule PING job */
1204 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1205 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1206 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1207 MIN_PING_FREQUENCY);
1209 = GNUNET_SCHEDULER_add_delayed (sched,
1218 * Task triggered when a neighbour entry might have gotten stale.
1220 * @param cls the 'struct Neighbour'
1221 * @param tc scheduler context (not used)
1224 consider_free_task (void *cls,
1225 const struct GNUNET_SCHEDULER_TaskContext *tc)
1227 struct Neighbour *n = cls;
1229 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1230 consider_free_neighbour (n);
1235 * Consider freeing the given neighbour since we may not need
1236 * to keep it around anymore.
1238 * @param n neighbour to consider discarding
1241 consider_free_neighbour (struct Neighbour *n)
1243 struct Neighbour *pos;
1244 struct Neighbour *prev;
1245 struct GNUNET_TIME_Relative left;
1247 if ( (n->th != NULL) ||
1248 (n->pitr != NULL) ||
1249 (n->status == PEER_STATE_KEY_CONFIRMED) ||
1250 (GNUNET_YES == n->is_connected) )
1251 return; /* no chance */
1253 left = GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (n->last_activity,
1254 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT));
1257 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1258 GNUNET_SCHEDULER_cancel (sched, n->dead_clean_task);
1259 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (sched,
1261 &consider_free_task,
1265 /* actually free the neighbour... */
1274 neighbours = n->next;
1276 prev->next = n->next;
1277 GNUNET_assert (neighbour_count > 0);
1284 * Function called when the transport service is ready to
1285 * receive an encrypted message for the respective peer
1287 * @param cls neighbour to use message from
1288 * @param size number of bytes we can transmit
1289 * @param buf where to copy the message
1290 * @return number of bytes transmitted
1293 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1295 struct Neighbour *n = cls;
1296 struct MessageEntry *m;
1301 GNUNET_assert (NULL != (m = n->encrypted_head));
1302 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1309 GNUNET_assert (size >= m->size);
1310 memcpy (cbuf, &m[1], m->size);
1312 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1315 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1316 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1317 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1318 ret, GNUNET_i2s (&n->peer));
1320 process_encrypted_neighbour_queue (n);
1325 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1326 "Transmission of message of type %u and size %u failed\n",
1327 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1332 consider_free_neighbour (n);
1338 * Check if we have plaintext messages for the specified neighbour
1339 * pending, and if so, consider batching and encrypting them (and
1340 * then trigger processing of the encrypted queue if needed).
1342 * @param n neighbour to check.
1344 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1348 * Check if we have encrypted messages for the specified neighbour
1349 * pending, and if so, check with the transport about sending them
1352 * @param n neighbour to check.
1355 process_encrypted_neighbour_queue (struct Neighbour *n)
1357 struct MessageEntry *m;
1360 return; /* request already pending */
1361 m = n->encrypted_head;
1364 /* encrypted queue empty, try plaintext instead */
1365 process_plaintext_neighbour_queue (n);
1369 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1370 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1372 GNUNET_i2s (&n->peer),
1373 GNUNET_TIME_absolute_get_remaining (m->deadline).
1377 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1380 GNUNET_TIME_absolute_get_remaining
1382 ¬ify_encrypted_transmit_ready,
1386 /* message request too large or duplicate request */
1388 /* discard encrypted message */
1389 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1393 process_encrypted_neighbour_queue (n);
1399 * Decrypt size bytes from in and write the result to out. Use the
1400 * key for inbound traffic of the given neighbour. This function does
1401 * NOT do any integrity-checks on the result.
1403 * @param n neighbour we are receiving from
1404 * @param iv initialization vector to use
1405 * @param in ciphertext
1406 * @param out plaintext
1407 * @param size size of in/out
1408 * @return GNUNET_OK on success
1411 do_decrypt (struct Neighbour *n,
1412 const GNUNET_HashCode * iv,
1413 const void *in, void *out, size_t size)
1415 if (size != (uint16_t) size)
1420 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1421 (n->status != PEER_STATE_KEY_CONFIRMED))
1423 GNUNET_break_op (0);
1424 return GNUNET_SYSERR;
1427 GNUNET_CRYPTO_aes_decrypt (in,
1431 GNUNET_CRYPTO_AesInitializationVector *) iv,
1435 return GNUNET_SYSERR;
1438 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1439 "Decrypted %u bytes from `%4s' using key %u\n",
1440 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1447 * Select messages for transmission. This heuristic uses a combination
1448 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1449 * and priority-based discard (in case no feasible schedule exist) and
1450 * speculative optimization (defer any kind of transmission until
1451 * we either create a batch of significant size, 25% of max, or until
1452 * we are close to a deadline). Furthermore, when scheduling the
1453 * heuristic also packs as many messages into the batch as possible,
1454 * starting with those with the earliest deadline. Yes, this is fun.
1456 * @param n neighbour to select messages from
1457 * @param size number of bytes to select for transmission
1458 * @param retry_time set to the time when we should try again
1459 * (only valid if this function returns zero)
1460 * @return number of bytes selected, or 0 if we decided to
1461 * defer scheduling overall; in that case, retry_time is set.
1464 select_messages (struct Neighbour *n,
1465 size_t size, struct GNUNET_TIME_Relative *retry_time)
1467 struct MessageEntry *pos;
1468 struct MessageEntry *min;
1469 struct MessageEntry *last;
1470 unsigned int min_prio;
1471 struct GNUNET_TIME_Absolute t;
1472 struct GNUNET_TIME_Absolute now;
1473 struct GNUNET_TIME_Relative delta;
1475 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
1478 unsigned int queue_size;
1479 int discard_low_prio;
1481 GNUNET_assert (NULL != n->messages);
1482 now = GNUNET_TIME_absolute_get ();
1483 /* last entry in linked list of messages processed */
1485 /* should we remove the entry with the lowest
1486 priority from consideration for scheduling at the
1497 discard_low_prio = GNUNET_YES;
1498 while (GNUNET_YES == discard_low_prio)
1502 discard_low_prio = GNUNET_NO;
1503 /* calculate number of bytes available for transmission at time "t" */
1504 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
1506 /* how many bytes have we (hypothetically) scheduled so far */
1508 /* maximum time we can wait before transmitting anything
1509 and still make all of our deadlines */
1510 slack = MAX_CORK_DELAY;
1512 /* note that we use "*2" here because we want to look
1513 a bit further into the future; much more makes no
1514 sense since new message might be scheduled in the
1516 while ((pos != NULL) && (off < size * 2))
1518 if (pos->do_transmit == GNUNET_YES)
1520 /* already removed from consideration */
1524 if (discard_low_prio == GNUNET_NO)
1526 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
1527 if (delta.value > 0)
1529 // FIXME: HUH? Check!
1531 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
1534 if (avail < pos->size)
1536 // FIXME: HUH? Check!
1537 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1542 /* update slack, considering both its absolute deadline
1543 and relative deadlines caused by other messages
1544 with their respective load */
1545 slack = GNUNET_TIME_relative_min (slack,
1546 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
1548 if (pos->deadline.value <= now.value)
1551 slack = GNUNET_TIME_UNIT_ZERO;
1553 else if (GNUNET_YES == pos->got_slack)
1555 /* should be soon now! */
1556 slack = GNUNET_TIME_relative_min (slack,
1557 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
1562 GNUNET_TIME_relative_min (slack,
1563 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
1564 pos->got_slack = GNUNET_YES;
1565 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
1566 GNUNET_TIME_relative_to_absolute (MAX_CORK_DELAY));
1571 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
1572 if (pos->priority <= min_prio)
1574 /* update min for discard */
1575 min_prio = pos->priority;
1580 if (discard_low_prio)
1582 GNUNET_assert (min != NULL);
1583 /* remove lowest-priority entry from consideration */
1584 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1588 /* guard against sending "tiny" messages with large headers without
1590 if ( (slack.value > 0) &&
1592 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
1594 /* less than 25% of message would be filled with deadlines still
1595 being met if we delay by one second or more; so just wait for
1596 more data; but do not wait longer than 1s (since we don't want
1597 to delay messages for a really long time either). */
1598 *retry_time = MAX_CORK_DELAY;
1599 /* reset do_transmit values for next time */
1602 pos->do_transmit = GNUNET_NO;
1606 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1607 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
1608 (unsigned long long) slack.value,
1610 (unsigned int) size);
1614 /* select marked messages (up to size) for transmission */
1619 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1621 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1626 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1630 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1631 "Selected %u/%u bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
1633 queue_size, MAX_PEER_QUEUE_SIZE,
1634 GNUNET_i2s (&n->peer));
1641 * Batch multiple messages into a larger buffer.
1643 * @param n neighbour to take messages from
1644 * @param buf target buffer
1645 * @param size size of buf
1646 * @param deadline set to transmission deadline for the result
1647 * @param retry_time set to the time when we should try again
1648 * (only valid if this function returns zero)
1649 * @param priority set to the priority of the batch
1650 * @return number of bytes written to buf (can be zero)
1653 batch_message (struct Neighbour *n,
1656 struct GNUNET_TIME_Absolute *deadline,
1657 struct GNUNET_TIME_Relative *retry_time,
1658 unsigned int *priority)
1660 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1661 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
1662 struct MessageEntry *pos;
1663 struct MessageEntry *prev;
1664 struct MessageEntry *next;
1669 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1670 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1671 if (0 == select_messages (n, size, retry_time))
1674 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1675 "No messages selected, will try again in %llu ms\n",
1680 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
1681 ntm->distance = htonl (n->last_distance);
1682 ntm->latency = GNUNET_TIME_relative_hton (n->last_latency);
1683 ntm->peer = n->peer;
1687 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1690 if (GNUNET_YES == pos->do_transmit)
1692 GNUNET_assert (pos->size <= size);
1693 /* do notifications */
1694 /* FIXME: track if we have *any* client that wants
1695 full notifications and only do this if that is
1697 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
1699 memcpy (&ntm[1], &pos[1], pos->size);
1700 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1701 sizeof (struct GNUNET_MessageHeader));
1702 send_to_all_clients (&ntm->header,
1704 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
1708 /* message too large for 'full' notifications, we do at
1709 least the 'hdr' type */
1712 sizeof (struct GNUNET_MessageHeader));
1714 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
1716 send_to_all_clients (&ntm->header,
1718 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
1721 "Encrypting message of type %u\n",
1722 ntohs(((struct GNUNET_MessageHeader*)&pos[1])->type));
1724 /* copy for encrypted transmission */
1725 memcpy (&buf[ret], &pos[1], pos->size);
1728 *priority += pos->priority;
1730 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1731 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
1733 GNUNET_TIME_absolute_get_remaining (pos->deadline).value);
1735 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1749 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1750 "Deadline for message batch is %llu ms\n",
1751 GNUNET_TIME_absolute_get_remaining (*deadline).value);
1758 * Remove messages with deadlines that have long expired from
1761 * @param n neighbour to inspect
1764 discard_expired_messages (struct Neighbour *n)
1766 struct MessageEntry *prev;
1767 struct MessageEntry *next;
1768 struct MessageEntry *pos;
1769 struct GNUNET_TIME_Absolute now;
1770 struct GNUNET_TIME_Relative delta;
1772 now = GNUNET_TIME_absolute_get ();
1778 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
1779 if (delta.value > PAST_EXPIRATION_DISCARD_TIME.value)
1782 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1783 "Message is %llu ms past due, discarding.\n",
1800 * Signature of the main function of a task.
1802 * @param cls closure
1803 * @param tc context information (why was this task triggered now)
1806 retry_plaintext_processing (void *cls,
1807 const struct GNUNET_SCHEDULER_TaskContext *tc)
1809 struct Neighbour *n = cls;
1811 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1812 process_plaintext_neighbour_queue (n);
1817 * Send our key (and encrypted PING) to the other peer.
1819 * @param n the other peer
1821 static void send_key (struct Neighbour *n);
1824 * Task that will retry "send_key" if our previous attempt failed
1828 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1830 struct Neighbour *n = cls;
1833 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1834 "Retrying key transmission to `%4s'\n",
1835 GNUNET_i2s (&n->peer));
1837 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1838 n->set_key_retry_frequency =
1839 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1845 * Check if we have plaintext messages for the specified neighbour
1846 * pending, and if so, consider batching and encrypting them (and
1847 * then trigger processing of the encrypted queue if needed).
1849 * @param n neighbour to check.
1852 process_plaintext_neighbour_queue (struct Neighbour *n)
1854 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1857 struct EncryptedMessage *em; /* encrypted message */
1858 struct EncryptedMessage *ph; /* plaintext header */
1859 struct MessageEntry *me;
1860 unsigned int priority;
1861 struct GNUNET_TIME_Absolute deadline;
1862 struct GNUNET_TIME_Relative retry_time;
1865 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1867 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1868 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
1872 case PEER_STATE_DOWN:
1875 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1876 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1877 GNUNET_i2s(&n->peer));
1880 case PEER_STATE_KEY_SENT:
1881 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1882 n->retry_set_key_task
1883 = GNUNET_SCHEDULER_add_delayed (sched,
1884 n->set_key_retry_frequency,
1885 &set_key_retry_task, n);
1887 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1888 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1889 GNUNET_i2s(&n->peer));
1892 case PEER_STATE_KEY_RECEIVED:
1893 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
1894 n->retry_set_key_task
1895 = GNUNET_SCHEDULER_add_delayed (sched,
1896 n->set_key_retry_frequency,
1897 &set_key_retry_task, n);
1899 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1900 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1901 GNUNET_i2s(&n->peer));
1904 case PEER_STATE_KEY_CONFIRMED:
1905 /* ready to continue */
1908 discard_expired_messages (n);
1909 if (n->messages == NULL)
1912 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1913 "Plaintext message queue for `%4s' is empty.\n",
1914 GNUNET_i2s(&n->peer));
1916 return; /* no pending messages */
1918 if (n->encrypted_head != NULL)
1921 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1922 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1923 GNUNET_i2s(&n->peer));
1925 return; /* wait for messages already encrypted to be
1928 ph = (struct EncryptedMessage *) pbuf;
1929 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1931 used = sizeof (struct EncryptedMessage);
1932 used += batch_message (n,
1934 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1935 &deadline, &retry_time, &priority);
1936 if (used == sizeof (struct EncryptedMessage))
1939 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1940 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1941 GNUNET_i2s(&n->peer));
1943 /* no messages selected for sending, try again later... */
1944 n->retry_plaintext_task =
1945 GNUNET_SCHEDULER_add_delayed (sched,
1947 &retry_plaintext_processing, n);
1950 #if DEBUG_CORE_QUOTA
1951 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1952 "Sending %u b/s as new limit to peer `%4s'\n",
1953 (unsigned int) ntohl (n->bw_in.value__),
1954 GNUNET_i2s (&n->peer));
1956 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1));
1957 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1958 ph->inbound_bw_limit = n->bw_in;
1959 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1961 /* setup encryption message header */
1962 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1963 me->deadline = deadline;
1964 me->priority = priority;
1966 em = (struct EncryptedMessage *) &me[1];
1967 em->header.size = htons (used);
1968 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1969 em->iv_seed = ph->iv_seed;
1970 esize = used - ENCRYPTED_HEADER_SIZE;
1971 GNUNET_CRYPTO_hash (&ph->sequence_number,
1972 esize - sizeof (GNUNET_HashCode),
1973 &ph->plaintext_hash);
1974 GNUNET_CRYPTO_hash (&ph->iv_seed, sizeof (uint32_t), &iv);
1977 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1978 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
1980 GNUNET_i2s(&n->peer),
1981 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).value);
1983 GNUNET_assert (GNUNET_OK ==
1986 &ph->plaintext_hash,
1987 &em->plaintext_hash, esize));
1988 /* append to transmission list */
1989 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1993 process_encrypted_neighbour_queue (n);
1998 * Function that recalculates the bandwidth quota for the
1999 * given neighbour and transmits it to the transport service.
2001 * @param cls neighbour for the quota update
2005 neighbour_quota_update (void *cls,
2006 const struct GNUNET_SCHEDULER_TaskContext *tc);
2010 * Schedule the task that will recalculate the bandwidth
2011 * quota for this peer (and possibly force a disconnect of
2012 * idle peers by calculating a bandwidth of zero).
2015 schedule_quota_update (struct Neighbour *n)
2017 GNUNET_assert (n->quota_update_task ==
2018 GNUNET_SCHEDULER_NO_TASK);
2019 n->quota_update_task
2020 = GNUNET_SCHEDULER_add_delayed (sched,
2021 QUOTA_UPDATE_FREQUENCY,
2022 &neighbour_quota_update,
2028 * Initialize a new 'struct Neighbour'.
2030 * @param pid ID of the new neighbour
2031 * @return handle for the new neighbour
2033 static struct Neighbour *
2034 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2036 struct Neighbour *n;
2037 struct GNUNET_TIME_Absolute now;
2039 n = GNUNET_malloc (sizeof (struct Neighbour));
2040 n->next = neighbours;
2044 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2045 now = GNUNET_TIME_absolute_get ();
2046 n->encrypt_key_created = now;
2047 n->last_activity = now;
2048 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2049 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2050 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2051 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init ((uint32_t) - 1);
2052 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2053 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2055 neighbour_quota_update (n, NULL);
2061 * Handle CORE_SEND request.
2064 * @param client the client issuing the request
2065 * @param message the "struct SendMessage"
2068 handle_client_send (void *cls,
2069 struct GNUNET_SERVER_Client *client,
2070 const struct GNUNET_MessageHeader *message)
2072 const struct SendMessage *sm;
2073 struct Neighbour *n;
2074 struct MessageEntry *prev;
2075 struct MessageEntry *pos;
2076 struct MessageEntry *e;
2077 struct MessageEntry *min_prio_entry;
2078 struct MessageEntry *min_prio_prev;
2079 unsigned int min_prio;
2080 unsigned int queue_size;
2083 msize = ntohs (message->size);
2085 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2089 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2092 sm = (const struct SendMessage *) message;
2093 msize -= sizeof (struct SendMessage);
2094 n = find_neighbour (&sm->peer);
2096 n = create_neighbour (&sm->peer);
2098 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2099 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2102 GNUNET_i2s (&sm->peer));
2104 /* bound queue size */
2105 discard_expired_messages (n);
2106 min_prio = (unsigned int) -1;
2107 min_prio_entry = NULL;
2108 min_prio_prev = NULL;
2114 if (pos->priority < min_prio)
2116 min_prio_entry = pos;
2117 min_prio_prev = prev;
2118 min_prio = pos->priority;
2124 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2127 if (ntohl(sm->priority) <= min_prio)
2129 /* discard new entry */
2131 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2132 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2134 MAX_PEER_QUEUE_SIZE,
2136 ntohs (message->type));
2139 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2142 /* discard "min_prio_entry" */
2144 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2145 "Queue full, discarding existing older request\n");
2147 if (min_prio_prev == NULL)
2148 n->messages = min_prio_entry->next;
2150 min_prio_prev->next = min_prio_entry->next;
2151 GNUNET_free (min_prio_entry);
2155 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2156 "Adding transmission request for `%4s' of size %u to queue\n",
2157 GNUNET_i2s (&sm->peer),
2160 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2161 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2162 e->priority = ntohl (sm->priority);
2164 memcpy (&e[1], &sm[1], msize);
2166 /* insert, keep list sorted by deadline */
2169 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
2180 /* consider scheduling now */
2181 process_plaintext_neighbour_queue (n);
2183 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2188 * Function called when the transport service is ready to
2189 * receive a message. Only resets 'n->th' to NULL.
2191 * @param cls neighbour to use message from
2192 * @param size number of bytes we can transmit
2193 * @param buf where to copy the message
2194 * @return number of bytes transmitted
2197 notify_transport_connect_done (void *cls, size_t size, void *buf)
2199 struct Neighbour *n = cls;
2204 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2205 _("Failed to connect to `%4s': transport failed to connect\n"),
2206 GNUNET_i2s (&n->peer));
2215 * Handle CORE_REQUEST_CONNECT request.
2218 * @param client the client issuing the request
2219 * @param message the "struct ConnectMessage"
2222 handle_client_request_connect (void *cls,
2223 struct GNUNET_SERVER_Client *client,
2224 const struct GNUNET_MessageHeader *message)
2226 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2227 struct Neighbour *n;
2228 struct GNUNET_TIME_Relative timeout;
2230 if (0 == memcmp (&cm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2233 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2236 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2237 n = find_neighbour (&cm->peer);
2239 n = create_neighbour (&cm->peer);
2240 if ( (n->is_connected) ||
2242 return; /* already connected, or at least trying */
2244 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2245 "Core received `%s' request for `%4s', will try to establish connection\n",
2247 GNUNET_i2s (&cm->peer));
2249 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2250 /* ask transport to connect to the peer */
2251 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2253 sizeof (struct GNUNET_MessageHeader), 0,
2255 ¬ify_transport_connect_done,
2257 GNUNET_break (NULL != n->th);
2262 * List of handlers for the messages understood by this
2265 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2266 {&handle_client_init, NULL,
2267 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
2268 {&handle_client_request_info, NULL,
2269 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
2270 sizeof (struct RequestInfoMessage)},
2271 {&handle_client_send, NULL,
2272 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
2273 {&handle_client_request_connect, NULL,
2274 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
2275 sizeof (struct ConnectMessage)},
2281 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2282 * the neighbour's struct and retry send_key. Or, if we did not get a
2283 * HELLO, just do nothing.
2285 * @param cls the 'struct Neighbour' to retry sending the key for
2286 * @param peer the peer for which this is the HELLO
2287 * @param hello HELLO message of that peer
2288 * @param trust amount of trust we currently have in that peer
2291 process_hello_retry_send_key (void *cls,
2292 const struct GNUNET_PeerIdentity *peer,
2293 const struct GNUNET_HELLO_Message *hello,
2296 struct Neighbour *n = cls;
2301 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2302 "Entered `process_hello_retry_send_key' and `peer' is NULL!\n");
2305 if (n->public_key != NULL)
2311 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
2312 n->retry_set_key_task
2313 = GNUNET_SCHEDULER_add_delayed (sched,
2314 n->set_key_retry_frequency,
2315 &set_key_retry_task, n);
2321 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2322 "Entered `process_hello_retry_send_key' for peer `%4s'\n",
2325 if (n->public_key != NULL)
2328 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2329 "already have public key for peer %s!! (so why are we here?)\n",
2336 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2337 "Received new `%s' message for `%4s', initiating key exchange.\n",
2342 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2343 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2345 GNUNET_free (n->public_key);
2346 n->public_key = NULL;
2348 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2349 "GNUNET_HELLO_get_key returned awfully\n");
2357 * Send our key (and encrypted PING) to the other peer.
2359 * @param n the other peer
2362 send_key (struct Neighbour *n)
2364 struct SetKeyMessage *sm;
2365 struct MessageEntry *me;
2366 struct PingMessage pp;
2367 struct PingMessage *pm;
2369 if ( (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK) ||
2373 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2374 "Key exchange in progress with `%4s'.\n",
2375 GNUNET_i2s (&n->peer));
2377 return; /* already in progress */
2381 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2382 "Asked to perform key exchange with `%4s'.\n",
2383 GNUNET_i2s (&n->peer));
2385 if (n->public_key == NULL)
2387 /* lookup n's public key, then try again */
2389 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2390 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
2391 GNUNET_i2s (&n->peer));
2393 GNUNET_assert (n->pitr == NULL);
2394 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2398 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
2399 &process_hello_retry_send_key, n);
2402 /* first, set key message */
2403 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2404 sizeof (struct SetKeyMessage));
2405 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
2406 me->priority = SET_KEY_PRIORITY;
2407 me->size = sizeof (struct SetKeyMessage);
2408 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2412 sm = (struct SetKeyMessage *) &me[1];
2413 sm->header.size = htons (sizeof (struct SetKeyMessage));
2414 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2415 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2416 PEER_STATE_KEY_SENT : n->status));
2418 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2419 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2420 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2421 sizeof (struct GNUNET_PeerIdentity));
2422 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2423 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2424 sm->target = n->peer;
2425 GNUNET_assert (GNUNET_OK ==
2426 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2428 GNUNET_CRYPTO_AesSessionKey),
2430 &sm->encrypted_key));
2431 GNUNET_assert (GNUNET_OK ==
2432 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2435 /* second, encrypted PING message */
2436 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2437 sizeof (struct PingMessage));
2438 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2439 me->priority = PING_PRIORITY;
2440 me->size = sizeof (struct PingMessage);
2441 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2445 pm = (struct PingMessage *) &me[1];
2446 pm->header.size = htons (sizeof (struct PingMessage));
2447 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2448 pp.challenge = htonl (n->ping_challenge);
2449 pp.target = n->peer;
2451 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2452 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2453 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2454 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2455 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2457 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2460 &n->peer.hashPubKey,
2463 sizeof (struct PingMessage) -
2464 sizeof (struct GNUNET_MessageHeader));
2468 case PEER_STATE_DOWN:
2469 n->status = PEER_STATE_KEY_SENT;
2471 case PEER_STATE_KEY_SENT:
2473 case PEER_STATE_KEY_RECEIVED:
2475 case PEER_STATE_KEY_CONFIRMED:
2482 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2483 "Have %llu ms left for `%s' transmission.\n",
2484 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).value,
2487 /* trigger queue processing */
2488 process_encrypted_neighbour_queue (n);
2489 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
2490 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
2491 n->retry_set_key_task
2492 = GNUNET_SCHEDULER_add_delayed (sched,
2493 n->set_key_retry_frequency,
2494 &set_key_retry_task, n);
2499 * We received a SET_KEY message. Validate and update
2500 * our key material and status.
2502 * @param n the neighbour from which we received message m
2503 * @param m the set key message we received
2506 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2510 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2511 * the neighbour's struct and retry handling the set_key message. Or,
2512 * if we did not get a HELLO, just free the set key message.
2514 * @param cls pointer to the set key message
2515 * @param peer the peer for which this is the HELLO
2516 * @param hello HELLO message of that peer
2517 * @param trust amount of trust we currently have in that peer
2520 process_hello_retry_handle_set_key (void *cls,
2521 const struct GNUNET_PeerIdentity *peer,
2522 const struct GNUNET_HELLO_Message *hello,
2525 struct Neighbour *n = cls;
2526 struct SetKeyMessage *sm = n->skm;
2535 if (n->public_key != NULL)
2536 return; /* multiple HELLOs match!? */
2538 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2539 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2541 GNUNET_break_op (0);
2542 GNUNET_free (n->public_key);
2543 n->public_key = NULL;
2547 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2548 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2549 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2551 handle_set_key (n, sm);
2556 * We received a PING message. Validate and transmit
2559 * @param n sender of the PING
2560 * @param m the encrypted PING message itself
2563 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2565 struct PingMessage t;
2566 struct PongMessage tx;
2567 struct PongMessage *tp;
2568 struct MessageEntry *me;
2571 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2572 "Core service receives `%s' request from `%4s'.\n",
2573 "PING", GNUNET_i2s (&n->peer));
2577 &my_identity.hashPubKey,
2580 sizeof (struct PingMessage) -
2581 sizeof (struct GNUNET_MessageHeader)))
2584 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2585 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2587 GNUNET_i2s (&t.target),
2588 ntohl (t.challenge), n->decrypt_key.crc32);
2589 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2590 "Target of `%s' request is `%4s'.\n",
2591 "PING", GNUNET_i2s (&t.target));
2593 if (0 != memcmp (&t.target,
2594 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2596 GNUNET_break_op (0);
2599 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2600 sizeof (struct PongMessage));
2601 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2605 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2606 me->priority = PONG_PRIORITY;
2607 me->size = sizeof (struct PongMessage);
2608 tx.reserved = htonl (0);
2609 tx.inbound_bw_limit = n->bw_in;
2610 tx.challenge = t.challenge;
2611 tx.target = t.target;
2612 tp = (struct PongMessage *) &me[1];
2613 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2614 tp->header.size = htons (sizeof (struct PongMessage));
2616 &my_identity.hashPubKey,
2619 sizeof (struct PongMessage) -
2620 sizeof (struct GNUNET_MessageHeader));
2622 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2623 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2624 ntohl (t.challenge), n->encrypt_key.crc32);
2626 /* trigger queue processing */
2627 process_encrypted_neighbour_queue (n);
2632 * We received a PONG message. Validate and update our status.
2634 * @param n sender of the PONG
2635 * @param m the encrypted PONG message itself
2638 handle_pong (struct Neighbour *n,
2639 const struct PongMessage *m)
2641 struct PongMessage t;
2642 struct ConnectNotifyMessage cnm;
2645 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2646 "Core service receives `%s' request from `%4s'.\n",
2647 "PONG", GNUNET_i2s (&n->peer));
2651 &n->peer.hashPubKey,
2654 sizeof (struct PongMessage) -
2655 sizeof (struct GNUNET_MessageHeader)))
2657 if (0 != ntohl (t.reserved))
2659 GNUNET_break_op (0);
2663 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2664 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2666 GNUNET_i2s (&t.target),
2667 ntohl (t.challenge), n->decrypt_key.crc32);
2669 if ((0 != memcmp (&t.target,
2671 sizeof (struct GNUNET_PeerIdentity))) ||
2672 (n->ping_challenge != ntohl (t.challenge)))
2674 /* PONG malformed */
2676 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2677 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
2678 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2679 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2680 "Received malformed `%s' received from `%4s' with challenge %u\n",
2681 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2683 GNUNET_break_op (0);
2688 case PEER_STATE_DOWN:
2689 GNUNET_break (0); /* should be impossible */
2691 case PEER_STATE_KEY_SENT:
2692 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2694 case PEER_STATE_KEY_RECEIVED:
2695 n->status = PEER_STATE_KEY_CONFIRMED;
2696 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
2698 n->bw_out_external_limit = t.inbound_bw_limit;
2699 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
2700 n->bw_out_internal_limit);
2701 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
2703 GNUNET_TRANSPORT_set_quota (transport,
2707 GNUNET_TIME_UNIT_FOREVER_REL,
2711 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2712 "Confirmed key via `%s' message for peer `%4s'\n",
2713 "PONG", GNUNET_i2s (&n->peer));
2715 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2717 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2718 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2720 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2721 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2722 cnm.distance = htonl (n->last_distance);
2723 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
2725 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_CONNECT);
2726 process_encrypted_neighbour_queue (n);
2728 case PEER_STATE_KEY_CONFIRMED:
2729 n->last_activity = GNUNET_TIME_absolute_get ();
2730 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
2731 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
2733 = GNUNET_SCHEDULER_add_delayed (sched,
2734 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
2746 * We received a SET_KEY message. Validate and update
2747 * our key material and status.
2749 * @param n the neighbour from which we received message m
2750 * @param m the set key message we received
2753 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2755 struct SetKeyMessage *m_cpy;
2756 struct GNUNET_TIME_Absolute t;
2757 struct GNUNET_CRYPTO_AesSessionKey k;
2758 struct PingMessage *ping;
2759 struct PongMessage *pong;
2760 enum PeerStateMachine sender_status;
2763 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2764 "Core service receives `%s' request from `%4s'.\n",
2765 "SET_KEY", GNUNET_i2s (&n->peer));
2767 if (n->public_key == NULL)
2769 if (n->pitr != NULL)
2772 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2773 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
2779 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2780 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
2782 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2783 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2784 /* lookup n's public key, then try again */
2785 GNUNET_assert (n->skm == NULL);
2787 n->pitr = GNUNET_PEERINFO_iterate (cfg,
2791 GNUNET_TIME_UNIT_MINUTES,
2792 &process_hello_retry_handle_set_key, n);
2795 if (0 != memcmp (&m->target,
2797 sizeof (struct GNUNET_PeerIdentity)))
2799 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2800 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
2802 GNUNET_i2s (&m->target));
2805 if ((ntohl (m->purpose.size) !=
2806 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2807 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2808 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2809 sizeof (struct GNUNET_PeerIdentity)) ||
2811 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2812 &m->purpose, &m->signature, n->public_key)))
2814 /* invalid signature */
2815 GNUNET_break_op (0);
2818 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2819 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2820 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2821 (t.value < n->decrypt_key_created.value))
2823 /* this could rarely happen due to massive re-ordering of
2824 messages on the network level, but is most likely either
2825 a bug or some adversary messing with us. Report. */
2826 GNUNET_break_op (0);
2830 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2831 "Decrypting key material.\n");
2833 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2836 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2837 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2838 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2840 /* failed to decrypt !? */
2841 GNUNET_break_op (0);
2846 if (n->decrypt_key_created.value != t.value)
2848 /* fresh key, reset sequence numbers */
2849 n->last_sequence_number_received = 0;
2850 n->last_packets_bitmap = 0;
2851 n->decrypt_key_created = t;
2853 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2856 case PEER_STATE_DOWN:
2857 n->status = PEER_STATE_KEY_RECEIVED;
2859 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2860 "Responding to `%s' with my own key.\n", "SET_KEY");
2864 case PEER_STATE_KEY_SENT:
2865 case PEER_STATE_KEY_RECEIVED:
2866 n->status = PEER_STATE_KEY_RECEIVED;
2867 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2868 (sender_status != PEER_STATE_KEY_CONFIRMED))
2871 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2872 "Responding to `%s' with my own key (other peer has status %u).\n",
2873 "SET_KEY", sender_status);
2878 case PEER_STATE_KEY_CONFIRMED:
2879 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2880 (sender_status != PEER_STATE_KEY_CONFIRMED))
2883 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2884 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2885 "SET_KEY", sender_status);
2894 if (n->pending_ping != NULL)
2896 ping = n->pending_ping;
2897 n->pending_ping = NULL;
2898 handle_ping (n, ping);
2901 if (n->pending_pong != NULL)
2903 pong = n->pending_pong;
2904 n->pending_pong = NULL;
2905 handle_pong (n, pong);
2912 * Send a P2P message to a client.
2914 * @param sender who sent us the message?
2915 * @param client who should we give the message to?
2916 * @param m contains the message to transmit
2917 * @param msize number of bytes in buf to transmit
2920 send_p2p_message_to_client (struct Neighbour *sender,
2921 struct Client *client,
2922 const void *m, size_t msize)
2924 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2925 struct NotifyTrafficMessage *ntm;
2928 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2929 "Core service passes message from `%4s' of type %u to client.\n",
2930 GNUNET_i2s(&sender->peer),
2931 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2933 ntm = (struct NotifyTrafficMessage *) buf;
2934 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2935 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2936 ntm->distance = htonl (sender->last_distance);
2937 ntm->latency = GNUNET_TIME_relative_hton (sender->last_latency);
2938 ntm->peer = sender->peer;
2939 memcpy (&ntm[1], m, msize);
2940 send_to_client (client, &ntm->header, GNUNET_YES);
2945 * Deliver P2P message to interested clients.
2947 * @param sender who sent us the message?
2948 * @param m the message
2949 * @param msize size of the message (including header)
2952 deliver_message (struct Neighbour *sender,
2953 const struct GNUNET_MessageHeader *m, size_t msize)
2955 struct Client *cpos;
2961 type = ntohs (m->type);
2963 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2964 "Received encapsulated message of type %u from `%4s'\n",
2966 GNUNET_i2s (&sender->peer));
2968 dropped = GNUNET_YES;
2970 while (cpos != NULL)
2972 deliver_full = GNUNET_NO;
2973 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
2974 deliver_full = GNUNET_YES;
2977 for (tpos = 0; tpos < cpos->tcnt; tpos++)
2979 if (type != cpos->types[tpos])
2981 deliver_full = GNUNET_YES;
2985 if (GNUNET_YES == deliver_full)
2987 send_p2p_message_to_client (sender, cpos, m, msize);
2988 dropped = GNUNET_NO;
2990 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2992 send_p2p_message_to_client (sender, cpos, m,
2993 sizeof (struct GNUNET_MessageHeader));
2997 if (dropped == GNUNET_YES)
3000 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3001 "Message of type %u from `%4s' not delivered to any client.\n",
3003 GNUNET_i2s (&sender->peer));
3005 /* FIXME: stats... */
3011 * Align P2P message and then deliver to interested clients.
3013 * @param sender who sent us the message?
3014 * @param buffer unaligned (!) buffer containing message
3015 * @param msize size of the message (including header)
3018 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
3022 /* TODO: call to statistics? */
3023 memcpy (abuf, buffer, msize);
3024 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
3029 * Deliver P2P messages to interested clients.
3031 * @param sender who sent us the message?
3032 * @param buffer buffer containing messages, can be modified
3033 * @param buffer_size size of the buffer (overall)
3034 * @param offset offset where messages in the buffer start
3037 deliver_messages (struct Neighbour *sender,
3038 const char *buffer, size_t buffer_size, size_t offset)
3040 struct GNUNET_MessageHeader *mhp;
3041 struct GNUNET_MessageHeader mh;
3045 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
3047 if (0 != offset % sizeof (uint16_t))
3049 /* outch, need to copy to access header */
3050 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
3055 /* can access header directly */
3056 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
3058 msize = ntohs (mhp->size);
3059 if (msize + offset > buffer_size)
3061 /* malformed message, header says it is larger than what
3062 would fit into the overall buffer */
3063 GNUNET_break_op (0);
3066 #if HAVE_UNALIGNED_64_ACCESS
3067 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
3069 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
3071 if (GNUNET_YES == need_align)
3072 align_and_deliver (sender, &buffer[offset], msize);
3074 deliver_message (sender,
3075 (const struct GNUNET_MessageHeader *)
3076 &buffer[offset], msize);
3083 * We received an encrypted message. Decrypt, validate and
3084 * pass on to the appropriate clients.
3087 handle_encrypted_message (struct Neighbour *n,
3088 const struct EncryptedMessage *m)
3090 size_t size = ntohs (m->header.size);
3092 struct EncryptedMessage *pt; /* plaintext */
3096 struct GNUNET_TIME_Absolute t;
3100 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3101 "Core service receives `%s' request from `%4s'.\n",
3102 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
3104 GNUNET_CRYPTO_hash (&m->iv_seed, sizeof (uint32_t), &iv);
3110 &buf[ENCRYPTED_HEADER_SIZE],
3111 size - ENCRYPTED_HEADER_SIZE))
3113 pt = (struct EncryptedMessage *) buf;
3116 GNUNET_CRYPTO_hash (&pt->sequence_number,
3117 size - ENCRYPTED_HEADER_SIZE - sizeof (GNUNET_HashCode), &ph);
3118 if (0 != memcmp (&ph,
3119 &pt->plaintext_hash,
3120 sizeof (GNUNET_HashCode)))
3122 /* checksum failed */
3123 GNUNET_break_op (0);
3127 /* validate sequence number */
3128 snum = ntohl (pt->sequence_number);
3129 if (n->last_sequence_number_received == snum)
3131 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3132 "Received duplicate message, ignoring.\n");
3133 /* duplicate, ignore */
3136 if ((n->last_sequence_number_received > snum) &&
3137 (n->last_sequence_number_received - snum > 32))
3139 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3140 "Received ancient out of sequence message, ignoring.\n");
3141 /* ancient out of sequence, ignore */
3144 if (n->last_sequence_number_received > snum)
3146 unsigned int rotbit =
3147 1 << (n->last_sequence_number_received - snum - 1);
3148 if ((n->last_packets_bitmap & rotbit) != 0)
3150 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3151 "Received duplicate message, ignoring.\n");
3152 /* duplicate, ignore */
3155 n->last_packets_bitmap |= rotbit;
3157 if (n->last_sequence_number_received < snum)
3159 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
3160 n->last_sequence_number_received = snum;
3163 /* check timestamp */
3164 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
3165 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
3167 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3169 ("Message received far too old (%llu ms). Content ignored.\n"),
3170 GNUNET_TIME_absolute_get_duration (t).value);
3174 /* process decrypted message(s) */
3175 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
3177 #if DEBUG_CORE_SET_QUOTA
3178 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3179 "Received %u b/s as new inbound limit for peer `%4s'\n",
3180 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
3181 GNUNET_i2s (&n->peer));
3183 n->bw_out_external_limit = pt->inbound_bw_limit;
3184 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3185 n->bw_out_internal_limit);
3186 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3188 GNUNET_TRANSPORT_set_quota (transport,
3192 GNUNET_TIME_UNIT_FOREVER_REL,
3195 n->last_activity = GNUNET_TIME_absolute_get ();
3196 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3197 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3199 = GNUNET_SCHEDULER_add_delayed (sched,
3200 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3203 off = sizeof (struct EncryptedMessage);
3204 deliver_messages (n, buf, size, off);
3209 * Function called by the transport for each received message.
3211 * @param cls closure
3212 * @param peer (claimed) identity of the other peer
3213 * @param message the message
3214 * @param latency estimated latency for communicating with the
3215 * given peer (round-trip)
3216 * @param distance in overlay hops, as given by transport plugin
3219 handle_transport_receive (void *cls,
3220 const struct GNUNET_PeerIdentity *peer,
3221 const struct GNUNET_MessageHeader *message,
3222 struct GNUNET_TIME_Relative latency,
3223 unsigned int distance)
3225 struct Neighbour *n;
3226 struct GNUNET_TIME_Absolute now;
3232 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3233 "Received message of type %u from `%4s', demultiplexing.\n",
3234 ntohs (message->type), GNUNET_i2s (peer));
3236 n = find_neighbour (peer);
3238 n = create_neighbour (peer);
3241 n->last_latency = latency;
3242 n->last_distance = distance;
3243 up = (n->status == PEER_STATE_KEY_CONFIRMED);
3244 type = ntohs (message->type);
3245 size = ntohs (message->size);
3248 "Received message of type %u from `%4s'\n",
3254 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
3255 if (size != sizeof (struct SetKeyMessage))
3257 GNUNET_break_op (0);
3260 handle_set_key (n, (const struct SetKeyMessage *) message);
3262 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
3263 if (size < sizeof (struct EncryptedMessage) +
3264 sizeof (struct GNUNET_MessageHeader))
3266 GNUNET_break_op (0);
3269 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3270 (n->status != PEER_STATE_KEY_CONFIRMED))
3272 GNUNET_break_op (0);
3275 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
3277 case GNUNET_MESSAGE_TYPE_CORE_PING:
3278 if (size != sizeof (struct PingMessage))
3280 GNUNET_break_op (0);
3283 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
3284 (n->status != PEER_STATE_KEY_CONFIRMED))
3287 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3288 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3289 "PING", GNUNET_i2s (&n->peer));
3291 GNUNET_free_non_null (n->pending_ping);
3292 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
3293 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
3296 handle_ping (n, (const struct PingMessage *) message);
3298 case GNUNET_MESSAGE_TYPE_CORE_PONG:
3299 if (size != sizeof (struct PongMessage))
3301 GNUNET_break_op (0);
3304 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
3305 (n->status != PEER_STATE_KEY_CONFIRMED) )
3308 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3309 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
3310 "PONG", GNUNET_i2s (&n->peer));
3312 GNUNET_free_non_null (n->pending_pong);
3313 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
3314 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
3317 handle_pong (n, (const struct PongMessage *) message);
3320 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3321 _("Unsupported message of type %u received.\n"), type);
3324 if (n->status == PEER_STATE_KEY_CONFIRMED)
3326 now = GNUNET_TIME_absolute_get ();
3327 n->last_activity = now;
3329 n->time_established = now;
3330 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3331 GNUNET_SCHEDULER_cancel (sched, n->keep_alive_task);
3333 = GNUNET_SCHEDULER_add_delayed (sched,
3334 GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3342 * Function that recalculates the bandwidth quota for the
3343 * given neighbour and transmits it to the transport service.
3345 * @param cls neighbour for the quota update
3349 neighbour_quota_update (void *cls,
3350 const struct GNUNET_SCHEDULER_TaskContext *tc)
3352 struct Neighbour *n = cls;
3353 struct GNUNET_BANDWIDTH_Value32NBO q_in;
3356 unsigned long long distributable;
3357 uint64_t need_per_peer;
3358 uint64_t need_per_second;
3360 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
3361 /* calculate relative preference among all neighbours;
3362 divides by a bit more to avoid division by zero AND to
3363 account for possibility of new neighbours joining any time
3364 AND to convert to double... */
3365 if (preference_sum == 0)
3367 pref_rel = 1.0 / (double) neighbour_count;
3371 pref_rel = n->current_preference / preference_sum;
3373 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
3374 GNUNET_TIME_UNIT_SECONDS);
3375 need_per_second = need_per_peer * neighbour_count;
3377 if (bandwidth_target_out_bps > need_per_second)
3378 distributable = bandwidth_target_out_bps - need_per_second;
3379 share = distributable * pref_rel;
3380 if (share + need_per_peer > ( (uint32_t)-1))
3381 q_in = GNUNET_BANDWIDTH_value_init ((uint32_t) -1);
3383 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
3384 /* check if we want to disconnect for good due to inactivity */
3385 if ( (GNUNET_TIME_absolute_get_duration (n->last_activity).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) &&
3386 (GNUNET_TIME_absolute_get_duration (n->time_established).value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.value) )
3389 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3390 "Forcing disconnect of `%4s' due to inactivity (?).\n",
3391 GNUNET_i2s (&n->peer));
3393 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
3395 #if DEBUG_CORE_QUOTA
3396 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3397 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
3398 GNUNET_i2s (&n->peer),
3399 (unsigned int) ntohl (q_in.value__),
3400 bandwidth_target_out_bps,
3401 (unsigned int) ntohl (n->bw_in.value__),
3402 (unsigned int) ntohl (n->bw_out.value__),
3403 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
3405 if (n->bw_in.value__ != q_in.value__)
3408 GNUNET_TRANSPORT_set_quota (transport,
3412 GNUNET_TIME_UNIT_FOREVER_REL,
3415 schedule_quota_update (n);
3420 * Function called by transport to notify us that
3421 * a peer connected to us (on the network level).
3423 * @param cls closure
3424 * @param peer the peer that connected
3425 * @param latency current latency of the connection
3426 * @param distance in overlay hops, as given by transport plugin
3429 handle_transport_notify_connect (void *cls,
3430 const struct GNUNET_PeerIdentity *peer,
3431 struct GNUNET_TIME_Relative latency,
3432 unsigned int distance)
3434 struct Neighbour *n;
3435 struct ConnectNotifyMessage cnm;
3437 n = find_neighbour (peer);
3440 if (n->is_connected)
3442 /* duplicate connect notification!? */
3449 n = create_neighbour (peer);
3451 n->is_connected = GNUNET_YES;
3452 n->last_latency = latency;
3453 n->last_distance = distance;
3454 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
3457 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
3461 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3462 "Received connection from `%4s'.\n",
3463 GNUNET_i2s (&n->peer));
3465 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
3466 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT);
3467 cnm.distance = htonl (n->last_distance);
3468 cnm.latency = GNUNET_TIME_relative_hton (n->last_latency);
3470 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_PRE_CONNECT);
3471 GNUNET_TRANSPORT_set_quota (transport,
3475 GNUNET_TIME_UNIT_FOREVER_REL,
3482 * Function called by transport telling us that a peer
3485 * @param cls closure
3486 * @param peer the peer that disconnected
3489 handle_transport_notify_disconnect (void *cls,
3490 const struct GNUNET_PeerIdentity *peer)
3492 struct DisconnectNotifyMessage cnm;
3493 struct Neighbour *n;
3496 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3497 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
3499 n = find_neighbour (peer);
3505 GNUNET_break (n->is_connected);
3506 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
3507 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
3509 send_to_all_clients (&cnm.header, GNUNET_YES, GNUNET_CORE_OPTION_SEND_DISCONNECT);
3510 n->is_connected = GNUNET_NO;
3515 * Last task run during shutdown. Disconnects us from
3519 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3521 struct Neighbour *n;
3525 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3526 "Core service shutting down.\n");
3528 GNUNET_assert (transport != NULL);
3529 GNUNET_TRANSPORT_disconnect (transport);
3531 while (NULL != (n = neighbours))
3533 neighbours = n->next;
3534 GNUNET_assert (neighbour_count > 0);
3538 GNUNET_SERVER_notification_context_destroy (notifier);
3540 while (NULL != (c = clients))
3541 handle_client_disconnect (NULL, c->client_handle);
3542 if (my_private_key != NULL)
3543 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3548 * Initiate core service.
3550 * @param cls closure
3551 * @param s scheduler to use
3552 * @param serv the initialized server
3553 * @param c configuration to use
3557 struct GNUNET_SCHEDULER_Handle *s,
3558 struct GNUNET_SERVER_Handle *serv,
3559 const struct GNUNET_CONFIGURATION_Handle *c)
3565 /* parse configuration */
3568 GNUNET_CONFIGURATION_get_value_number (c,
3571 &bandwidth_target_in_bps)) ||
3573 GNUNET_CONFIGURATION_get_value_number (c,
3576 &bandwidth_target_out_bps)) ||
3578 GNUNET_CONFIGURATION_get_value_filename (c,
3580 "HOSTKEY", &keyfile)))
3582 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3584 ("Core service is lacking key configuration settings. Exiting.\n"));
3585 GNUNET_SCHEDULER_shutdown (s);
3588 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3589 GNUNET_free (keyfile);
3590 if (my_private_key == NULL)
3592 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3593 _("Core service could not access hostkey. Exiting.\n"));
3594 GNUNET_SCHEDULER_shutdown (s);
3597 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3598 GNUNET_CRYPTO_hash (&my_public_key,
3599 sizeof (my_public_key), &my_identity.hashPubKey);
3600 /* setup notification */
3602 notifier = GNUNET_SERVER_notification_context_create (server,
3604 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3605 /* setup transport connection */
3606 transport = GNUNET_TRANSPORT_connect (sched,
3609 &handle_transport_receive,
3610 &handle_transport_notify_connect,
3611 &handle_transport_notify_disconnect);
3612 GNUNET_assert (NULL != transport);
3613 GNUNET_SCHEDULER_add_delayed (sched,
3614 GNUNET_TIME_UNIT_FOREVER_REL,
3615 &cleaning_task, NULL);
3616 /* process client requests */
3617 GNUNET_SERVER_add_handlers (server, handlers);
3618 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3619 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3625 * The main function for the transport service.
3627 * @param argc number of arguments from the command line
3628 * @param argv command line arguments
3629 * @return 0 ok, 1 on error
3632 main (int argc, char *const *argv)
3634 return (GNUNET_OK ==
3635 GNUNET_SERVICE_run (argc,
3638 GNUNET_SERVICE_OPTION_NONE,
3639 &run, NULL)) ? 0 : 1;
3642 /* end of gnunet-service-core.c */