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
27 * - revisit API (which arguments are used, needed)?
28 * - add code to re-transmit key if first attempt failed
29 * + timeout on connect / key exchange, etc.
30 * + timeout for automatic re-try, etc.
31 * - add code to give up re-transmission of key if many attempts fail
32 * - add code to send PINGs if we are about to time-out otherwise
33 * ? add heuristic to do another send_key in "handle_set_key"
34 * in case previous attempt failed / didn't work / persist
35 * (but don't do it always to avoid storm of SET_KEY's going
36 * back and forth!) --- alternatively, add "status" field
37 * of the other peer to the set key message, that way we'd
39 * - check that hostkey used by transport (for HELLOs) is the
40 * same as the hostkey that we are using!
41 * - topology management:
42 * + bootstrapping (transport offer hello, plugins)
43 * + internal neighbour selection
44 * + update bandwidth usage statistics
45 * + bandwidth allocation (transport set quota)
46 * - optimize lookup (many O(n) list traversals
47 * could ideally be changed to O(1) hash map lookups)
50 #include "gnunet_util_lib.h"
51 #include "gnunet_hello_lib.h"
52 #include "gnunet_peerinfo_service.h"
53 #include "gnunet_protocols.h"
54 #include "gnunet_signatures.h"
55 #include "gnunet_transport_service.h"
60 * Receive and send buffer windows grow over time. For
61 * how long can 'unused' bandwidth accumulate before we
62 * need to cap it? (specified in ms).
64 #define MAX_WINDOW_TIME (5 * 60 * 1000)
68 * Amount of bytes per minute (in/out) to assume initially
69 * (before either peer has communicated any particular
70 * preference). Should be rather low.
72 #define DEFAULT_BPM_IN_OUT 2048
76 * After how much time past the "official" expiration time do
77 * we discard messages? Should not be zero since we may
78 * intentionally defer transmission until close to the deadline
79 * and then may be slightly past the deadline due to inaccuracy
80 * in sleep and our own CPU consumption.
82 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
86 * What is the maximum delay for a SET_KEY message?
88 #define MAX_SET_KEY_DELAY GNUNET_TIME_UNIT_SECONDS
92 * What how long do we wait for SET_KEY confirmation initially?
94 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3)
98 * What is the maximum delay for a PING message?
100 #define MAX_PING_DELAY GNUNET_TIME_UNIT_SECONDS
104 * What is the maximum delay for a PONG message?
106 #define MAX_PONG_DELAY GNUNET_TIME_UNIT_SECONDS
110 * What is the priority for a SET_KEY message?
112 #define SET_KEY_PRIORITY 0xFFFFFF
116 * What is the priority for a PING message?
118 #define PING_PRIORITY 0xFFFFFF
122 * What is the priority for a PONG message?
124 #define PONG_PRIORITY 0xFFFFFF
128 * How many messages do we queue per peer at most?
130 #define MAX_PEER_QUEUE_SIZE 16
134 * How many non-mandatory messages do we queue per client at most?
136 #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
151 * What is the maximum size for encrypted messages? Note that this
152 * number imposes a clear limit on the maximum size of any message.
153 * Set to a value close to 64k but not so close that transports will
154 * have trouble with their headers.
156 #define MAX_ENCRYPTED_MESSAGE_SIZE (63 * 1024)
160 * State machine for our P2P encryption handshake. Everyone starts in
161 * "DOWN", if we receive the other peer's key (other peer initiated)
162 * we start in state RECEIVED (since we will immediately send our
163 * own); otherwise we start in SENT. If we get back a PONG from
164 * within either state, we move up to CONFIRMED (the PONG will always
165 * be sent back encrypted with the key we sent to the other peer).
167 enum PeerStateMachine
171 PEER_STATE_KEY_RECEIVED,
172 PEER_STATE_KEY_CONFIRMED
177 * Number of bytes (at the beginning) of "struct EncryptedMessage"
178 * that are NOT encrypted.
180 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t) + sizeof(GNUNET_HashCode))
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;
196 uint32_t reserved GNUNET_PACKED;
199 * Hash of the plaintext, used to verify message integrity;
200 * ALSO used as the IV for the symmetric cipher! Everything
201 * after this hash will be encrypted. ENCRYPTED_HEADER_SIZE
202 * must be set to the offset of the next field.
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
215 * peer / how much is the sender willing to receive),
216 * in bytes per minute.
218 uint32_t inbound_bpm_limit GNUNET_PACKED;
221 * Timestamp. Used to prevent reply of ancient messages
222 * (recent messages are caught with the sequence number).
224 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 either CORE_PING or CORE_PONG.
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;
254 * Message transmitted to set (or update) a session key.
260 * Message type is either CORE_SET_KEY.
262 struct GNUNET_MessageHeader header;
265 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
267 int32_t sender_status GNUNET_PACKED;
270 * Purpose of the signature, will be
271 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
273 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
276 * At what time was this key created?
278 struct GNUNET_TIME_AbsoluteNBO creation_time;
281 * The encrypted session key.
283 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
286 * Who is the intended recipient?
288 struct GNUNET_PeerIdentity target;
291 * Signature of the stuff above (starting at purpose).
293 struct GNUNET_CRYPTO_RsaSignature signature;
299 * Message waiting for transmission. This struct
300 * is followed by the actual content of the message.
306 * We keep messages in a linked list (for now).
308 struct MessageEntry *next;
311 * By when are we supposed to transmit this message?
313 struct GNUNET_TIME_Absolute deadline;
316 * How important is this message to us?
318 unsigned int priority;
321 * How long is the message? (number of bytes following
322 * the "struct MessageEntry", but not including the
323 * size of "struct MessageEntry" itself!)
328 * Was this message selected for transmission in the
329 * current round? GNUNET_YES or GNUNET_NO.
339 * We keep neighbours in a linked list (for now).
341 struct Neighbour *next;
344 * Unencrypted messages destined for this peer.
346 struct MessageEntry *messages;
349 * Head of the batched, encrypted message queue (already ordered,
350 * transmit starting with the head).
352 struct MessageEntry *encrypted_head;
355 * Tail of the batched, encrypted message queue (already ordered,
356 * append new messages to tail)
358 struct MessageEntry *encrypted_tail;
361 * Handle for pending requests for transmission to this peer
362 * with the transport service. NULL if no request is pending.
364 struct GNUNET_TRANSPORT_TransmitHandle *th;
367 * Public key of the neighbour, NULL if we don't have it yet.
369 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
372 * We received a PING message before we got the "public_key"
373 * (or the SET_KEY). We keep it here until we have a key
374 * to decrypt it. NULL if no PING is pending.
376 struct PingMessage *pending_ping;
379 * Identity of the neighbour.
381 struct GNUNET_PeerIdentity peer;
384 * Key we use to encrypt our messages for the other peer
385 * (initialized by us when we do the handshake).
387 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
390 * Key we use to decrypt messages from the other peer
391 * (given to us by the other peer during the handshake).
393 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
396 * ID of task used for re-trying plaintext scheduling.
398 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
401 * ID of task used for re-trying SET_KEY and PING message.
403 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
406 * At what time did we generate our encryption key?
408 struct GNUNET_TIME_Absolute encrypt_key_created;
411 * At what time did the other peer generate the decryption key?
413 struct GNUNET_TIME_Absolute decrypt_key_created;
416 * At what time did we initially establish (as in, complete session
417 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
419 struct GNUNET_TIME_Absolute time_established;
422 * At what time did we last receive an encrypted message from the
423 * other peer? Should be zero if status != KEY_CONFIRMED.
425 struct GNUNET_TIME_Absolute last_activity;
428 * Last latency observed from this peer.
430 struct GNUNET_TIME_Relative last_latency;
433 * At what frequency are we currently re-trying SET KEY messages?
435 struct GNUNET_TIME_Relative set_key_retry_frequency;
438 * Time of our last update to the "available_send_window".
440 struct GNUNET_TIME_Absolute last_asw_update;
443 * Time of our last update to the "available_recv_window".
445 struct GNUNET_TIME_Absolute last_arw_update;
448 * Number of bytes that we are eligible to transmit to this
449 * peer at this point. Incremented every minute by max_out_bpm,
450 * bounded by max_bpm (no back-log larger than MAX_BUF_FACT minutes,
451 * bandwidth-hogs are sampled at a frequency of about 78s!);
452 * may get negative if we have VERY high priority content.
454 long long available_send_window;
457 * How much downstream capacity of this peer has been reserved for
458 * our traffic? (Our clients can request that a certain amount of
459 * bandwidth is available for replies to them; this value is used to
460 * make sure that this reserved amount of bandwidth is actually
463 long long available_recv_window;
466 * How valueable were the messages of this peer recently?
468 double current_preference;
471 * Bit map indicating which of the 32 sequence numbers before the last
472 * were received (good for accepting out-of-order packets and
473 * estimating reliability of the connection)
475 unsigned int last_packets_bitmap;
478 * Number of messages in the message queue for this peer.
480 unsigned int message_queue_size;
483 * last sequence number received on this connection (highest)
485 uint32_t last_sequence_number_received;
488 * last sequence number transmitted
490 uint32_t last_sequence_number_sent;
493 * Available bandwidth in for this peer (current target).
498 * Available bandwidth out for this peer (current target).
503 * Internal bandwidth limit set for this peer (initially
504 * typcially set to "-1"). "bpm_out" is MAX of
505 * "bpm_out_internal_limit" and "bpm_out_external_limit".
507 uint32_t bpm_out_internal_limit;
510 * External bandwidth limit set for this peer by the
511 * peer that we are communicating with. "bpm_out" is MAX of
512 * "bpm_out_internal_limit" and "bpm_out_external_limit".
514 uint32_t bpm_out_external_limit;
517 * What was our PING challenge number?
519 uint32_t ping_challenge;
522 * What is our connection status?
524 enum PeerStateMachine status;
530 * Events are messages for clients. The struct
531 * itself is followed by the actual message.
536 * This is a linked list.
541 * Size of the message.
546 * Could this event be dropped if this queue
547 * is getting too large? (NOT YET USED!)
555 * Data structure for each client connected to the core service.
560 * Clients are kept in a linked list.
565 * Handle for the client with the server API.
567 struct GNUNET_SERVER_Client *client_handle;
570 * Linked list of messages we still need to deliver to
573 struct Event *event_head;
576 * Tail of the linked list of events.
578 struct Event *event_tail;
581 * Current transmit handle, NULL if no transmission request
584 struct GNUNET_NETWORK_TransmitHandle *th;
587 * Array of the types of messages this peer cares
588 * about (with "tcnt" entries). Allocated as part
589 * of this client struct, do not free!
594 * Options for messages this client cares about,
595 * see GNUNET_CORE_OPTION_ values.
600 * Number of types of incoming messages this client
601 * specifically cares about. Size of the "types" array.
611 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
616 static struct GNUNET_PeerIdentity my_identity;
621 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
626 struct GNUNET_SCHEDULER_Handle *sched;
631 struct GNUNET_CONFIGURATION_Handle *cfg;
636 static struct GNUNET_SERVER_Handle *server;
641 static struct GNUNET_TRANSPORT_Handle *transport;
644 * We keep neighbours in a linked list (for now).
646 static struct Neighbour *neighbours;
649 * Linked list of our clients.
651 static struct Client *clients;
655 * Recalculate the number of bytes we expect to
656 * receive or transmit in a given window.
658 * @param window pointer to the byte counter (updated)
659 * @param ts pointer to the timestamp (updated)
660 * @param bpm number of bytes per minute that should
661 * be added to the window.
664 update_window (long long *window,
665 struct GNUNET_TIME_Absolute *ts, unsigned int bpm)
667 struct GNUNET_TIME_Relative since;
669 since = GNUNET_TIME_absolute_get_duration (*ts);
670 if (since.value < 60 * 1000)
671 return; /* not even a minute has passed */
672 *ts = GNUNET_TIME_absolute_get ();
673 *window += (bpm * since.value) / 60 / 1000;
674 if (*window > MAX_WINDOW_TIME * bpm)
675 *window = MAX_WINDOW_TIME * bpm;
680 * Find the entry for the given neighbour.
682 * @param peer identity of the neighbour
683 * @return NULL if we are not connected, otherwise the
686 static struct Neighbour *
687 find_neighbour (const struct GNUNET_PeerIdentity *peer)
689 struct Neighbour *ret;
692 while ((ret != NULL) &&
693 (0 != memcmp (&ret->peer,
694 peer, sizeof (struct GNUNET_PeerIdentity))))
701 * Find the entry for the given client.
703 * @param client handle for the client
704 * @return NULL if we are not connected, otherwise the
707 static struct Client *
708 find_client (const struct GNUNET_SERVER_Client *client)
713 while ((ret != NULL) && (client != ret->client_handle))
720 * If necessary, initiate a request with the server to
721 * transmit messages from the queue of the given client.
722 * @param client who to transfer messages to
724 static void request_transmit (struct Client *client);
728 * Client is ready to receive data, provide it.
731 * @param size number of bytes available in buf
732 * @param buf where the callee should write the message
733 * @return number of bytes written to buf
736 do_client_transmit (void *cls, size_t size, void *buf)
738 struct Client *client = cls;
744 #if DEBUG_CORE_CLIENT
745 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
746 "Client ready to receive %u bytes.\n", size);
751 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
752 "Failed to transmit data to client (disconnect)?\n");
754 return 0; /* we'll surely get a disconnect soon... */
758 while ((NULL != (e = client->event_head)) && (e->size <= size))
760 memcpy (&tgt[ret], &e[1], e->size);
763 client->event_head = e->next;
766 GNUNET_assert (ret > 0);
767 if (client->event_head == NULL)
768 client->event_tail = NULL;
769 #if DEBUG_CORE_CLIENT
770 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
771 "Transmitting %u bytes to client\n", ret);
773 request_transmit (client);
779 * If necessary, initiate a request with the server to
780 * transmit messages from the queue of the given client.
781 * @param client who to transfer messages to
784 request_transmit (struct Client *client)
787 if (NULL != client->th)
788 return; /* already pending */
789 if (NULL == client->event_head)
790 return; /* no more events pending */
791 #if DEBUG_CORE_CLIENT
792 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
793 "Asking server to transmit %u bytes to client\n",
794 client->event_head->size);
797 = GNUNET_SERVER_notify_transmit_ready (client->client_handle,
798 client->event_head->size,
799 GNUNET_TIME_UNIT_FOREVER_REL,
800 &do_client_transmit, client);
805 * Send a message to one of our clients.
806 * @param client target for the message
807 * @param msg message to transmit
808 * @param can_drop could this message be dropped if the
809 * client's queue is getting too large?
812 send_to_client (struct Client *client,
813 const struct GNUNET_MessageHeader *msg, int can_drop)
816 unsigned int queue_size;
819 #if DEBUG_CORE_CLIENT
820 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
821 "Preparing to send message of type %u to client.\n",
825 e = client->event_head;
831 if ( (queue_size >= MAX_CLIENT_QUEUE_SIZE) &&
832 (can_drop == GNUNET_YES) )
835 msize = ntohs (msg->size);
836 e = GNUNET_malloc (sizeof (struct Event) + msize);
838 if (client->event_tail != NULL)
839 client->event_tail->next = e;
841 client->event_head = e;
842 client->event_tail = e;
843 e->can_drop = can_drop;
845 memcpy (&e[1], msg, msize);
846 request_transmit (client);
851 * Send a message to all of our current clients.
854 send_to_all_clients (const struct GNUNET_MessageHeader *msg, int can_drop)
861 send_to_client (c, msg, can_drop);
868 * Handle CORE_INIT request.
871 handle_client_init (void *cls,
872 struct GNUNET_SERVER_Client *client,
873 const struct GNUNET_MessageHeader *message)
875 const struct InitMessage *im;
876 struct InitReplyMessage irm;
879 const uint16_t *types;
881 struct ConnectNotifyMessage cnm;
883 #if DEBUG_CORE_CLIENT
884 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
885 "Client connecting to core service with `%s' message\n",
888 /* check that we don't have an entry already */
892 if (client == c->client_handle)
895 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
900 msize = ntohs (message->size);
901 if (msize < sizeof (struct InitMessage))
904 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
907 im = (const struct InitMessage *) message;
908 types = (const uint16_t *) &im[1];
909 msize -= sizeof (struct InitMessage);
910 c = GNUNET_malloc (sizeof (struct Client) + msize);
911 c->client_handle = client;
914 memcpy (&c[1], types, msize);
915 c->types = (uint16_t *) & c[1];
916 c->options = ntohl (im->options);
917 c->tcnt = msize / sizeof (uint16_t);
918 /* send init reply message */
919 irm.header.size = htons (sizeof (struct InitReplyMessage));
920 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
921 irm.reserved = htonl (0);
922 memcpy (&irm.publicKey,
924 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
925 #if DEBUG_CORE_CLIENT
926 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
927 "Sending `%s' message to client.\n", "INIT_REPLY");
929 send_to_client (c, &irm.header, GNUNET_NO);
930 /* notify new client about existing neighbours */
931 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
932 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
936 #if DEBUG_CORE_CLIENT
937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
938 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
940 cnm.bpm_available = htonl (n->bpm_out);
941 cnm.last_activity = GNUNET_TIME_absolute_hton (n->last_activity);
943 send_to_client (c, &cnm.header, GNUNET_NO);
946 GNUNET_SERVER_receive_done (client, GNUNET_OK);
951 * A client disconnected, clean up.
954 * @param client identification of the client
957 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
963 #if DEBUG_CORE_CLIENT
964 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
965 "Client has disconnected from core service.\n");
971 if (client == pos->client_handle)
976 prev->next = pos->next;
978 GNUNET_NETWORK_notify_transmit_ready_cancel (pos->th);
979 while (NULL != (e = pos->event_head))
981 pos->event_head = e->next;
990 /* client never sent INIT */
995 * Handle REQUEST_CONFIGURE request.
998 handle_client_request_configure (void *cls,
999 struct GNUNET_SERVER_Client *client,
1000 const struct GNUNET_MessageHeader *message)
1002 const struct RequestConfigureMessage *rcm;
1003 struct Neighbour *n;
1004 struct ConfigurationInfoMessage cim;
1008 #if DEBUG_CORE_CLIENT
1009 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1010 "Core service receives `%s' request.\n", "CONFIGURE");
1012 rcm = (const struct RequestConfigureMessage *) message;
1013 n = find_neighbour (&rcm->peer);
1014 memset (&cim, 0, sizeof (cim));
1015 if ((n != NULL) && (n->status == PEER_STATE_KEY_CONFIRMED))
1017 n->bpm_out_internal_limit = ntohl (rcm->limit_outbound_bpm);
1018 n->bpm_out = GNUNET_MAX (n->bpm_out_internal_limit,
1019 n->bpm_out_external_limit);
1020 reserv = ntohl (rcm->reserve_inbound);
1023 n->available_recv_window += reserv;
1025 else if (reserv > 0)
1027 update_window (&n->available_recv_window,
1028 &n->last_arw_update, n->bpm_in);
1029 if (n->available_recv_window < reserv)
1030 reserv = n->available_recv_window;
1031 n->available_recv_window -= reserv;
1033 n->current_preference += rcm->preference_change;
1034 if (n->current_preference < 0)
1035 n->current_preference = 0;
1036 cim.reserved_amount = htonl (reserv);
1037 cim.bpm_in = htonl (n->bpm_in);
1038 cim.bpm_out = htonl (n->bpm_out);
1039 cim.latency = GNUNET_TIME_relative_hton (n->last_latency);
1040 cim.preference = n->current_preference;
1042 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1043 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1044 cim.peer = rcm->peer;
1045 c = find_client (client);
1051 #if DEBUG_CORE_CLIENT
1052 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1053 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1055 send_to_client (c, &cim.header, GNUNET_NO);
1060 * Check if we have encrypted messages for the specified neighbour
1061 * pending, and if so, check with the transport about sending them
1064 * @param n neighbour to check.
1066 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1070 * Function called when the transport service is ready to
1071 * receive an encrypted message for the respective peer
1073 * @param cls neighbour to use message from
1074 * @param size number of bytes we can transmit
1075 * @param buf where to copy the message
1076 * @return number of bytes transmitted
1079 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1081 struct Neighbour *n = cls;
1082 struct MessageEntry *m;
1087 GNUNET_assert (NULL != (m = n->encrypted_head));
1088 n->encrypted_head = m->next;
1089 if (m->next == NULL)
1090 n->encrypted_tail = NULL;
1095 GNUNET_assert (size >= m->size);
1096 memcpy (cbuf, &m[1], m->size);
1098 process_encrypted_neighbour_queue (n);
1100 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1101 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1102 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1103 ret, GNUNET_i2s (&n->peer));
1108 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1109 "Transmission for message of type %u and size %u failed\n",
1110 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1119 * Check if we have plaintext messages for the specified neighbour
1120 * pending, and if so, consider batching and encrypting them (and
1121 * then trigger processing of the encrypted queue if needed).
1123 * @param n neighbour to check.
1125 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1129 * Check if we have encrypted messages for the specified neighbour
1130 * pending, and if so, check with the transport about sending them
1133 * @param n neighbour to check.
1136 process_encrypted_neighbour_queue (struct Neighbour *n)
1138 struct MessageEntry *m;
1141 return; /* request already pending */
1142 if (n->encrypted_head == NULL)
1144 /* encrypted queue empty, try plaintext instead */
1145 process_plaintext_neighbour_queue (n);
1149 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1150 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1151 n->encrypted_head->size,
1152 GNUNET_i2s (&n->peer),
1153 GNUNET_TIME_absolute_get_remaining (n->
1154 encrypted_head->deadline).
1158 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1159 n->encrypted_head->size,
1160 GNUNET_TIME_absolute_get_remaining
1161 (n->encrypted_head->deadline),
1162 ¬ify_encrypted_transmit_ready,
1166 /* message request too large (oops) */
1168 /* discard encrypted message */
1169 GNUNET_assert (NULL != (m = n->encrypted_head));
1170 n->encrypted_head = m->next;
1171 if (m->next == NULL)
1172 n->encrypted_tail = NULL;
1174 process_encrypted_neighbour_queue (n);
1180 * Decrypt size bytes from in and write the result to out. Use the
1181 * key for inbound traffic of the given neighbour. This function does
1182 * NOT do any integrity-checks on the result.
1184 * @param n neighbour we are receiving from
1185 * @param iv initialization vector to use
1186 * @param in ciphertext
1187 * @param out plaintext
1188 * @param size size of in/out
1189 * @return GNUNET_OK on success
1192 do_decrypt (struct Neighbour *n,
1193 const GNUNET_HashCode * iv,
1194 const void *in, void *out, size_t size)
1196 if (size != (uint16_t) size)
1201 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1202 (n->status != PEER_STATE_KEY_CONFIRMED))
1204 GNUNET_break_op (0);
1205 return GNUNET_SYSERR;
1208 GNUNET_CRYPTO_aes_decrypt (&n->decrypt_key,
1212 GNUNET_CRYPTO_AesInitializationVector *) iv,
1216 return GNUNET_SYSERR;
1219 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1220 "Decrypted %u bytes from `%4s' using key %u\n",
1221 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1228 * Encrypt size bytes from in and write the result to out. Use the
1229 * key for outbound traffic of the given neighbour.
1231 * @param n neighbour we are sending to
1232 * @param iv initialization vector to use
1233 * @param in ciphertext
1234 * @param out plaintext
1235 * @param size size of in/out
1236 * @return GNUNET_OK on success
1239 do_encrypt (struct Neighbour *n,
1240 const GNUNET_HashCode * iv,
1241 const void *in, void *out, size_t size)
1243 if (size != (uint16_t) size)
1248 GNUNET_assert (size ==
1249 GNUNET_CRYPTO_aes_encrypt (in,
1253 GNUNET_CRYPTO_AesInitializationVector
1256 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1257 "Encrypted %u bytes for `%4s' using key %u\n", size,
1258 GNUNET_i2s (&n->peer), n->encrypt_key.crc32);
1265 * Select messages for transmission. This heuristic uses a combination
1266 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1267 * and priority-based discard (in case no feasible schedule exist) and
1268 * speculative optimization (defer any kind of transmission until
1269 * we either create a batch of significant size, 25% of max, or until
1270 * we are close to a deadline). Furthermore, when scheduling the
1271 * heuristic also packs as many messages into the batch as possible,
1272 * starting with those with the earliest deadline. Yes, this is fun.
1274 * @param n neighbour to select messages from
1275 * @param size number of bytes to select for transmission
1276 * @param retry_time set to the time when we should try again
1277 * (only valid if this function returns zero)
1278 * @return number of bytes selected, or 0 if we decided to
1279 * defer scheduling overall; in that case, retry_time is set.
1282 select_messages (struct Neighbour *n,
1283 size_t size, struct GNUNET_TIME_Relative *retry_time)
1285 struct MessageEntry *pos;
1286 struct MessageEntry *min;
1287 struct MessageEntry *last;
1288 unsigned int min_prio;
1289 struct GNUNET_TIME_Absolute t;
1290 struct GNUNET_TIME_Absolute now;
1293 unsigned long long slack; /* how long could we wait before missing deadlines? */
1295 int discard_low_prio;
1297 GNUNET_assert (NULL != n->messages);
1298 now = GNUNET_TIME_absolute_get ();
1299 /* last entry in linked list of messages processed */
1301 /* should we remove the entry with the lowest
1302 priority from consideration for scheduling at the
1304 discard_low_prio = GNUNET_YES;
1305 while (GNUNET_YES == discard_low_prio)
1309 discard_low_prio = GNUNET_NO;
1310 /* number of bytes available for transmission at time "t" */
1311 avail = n->available_send_window;
1312 t = n->last_asw_update;
1313 /* how many bytes have we (hyptothetically) scheduled so far */
1315 /* maximum time we can wait before transmitting anything
1316 and still make all of our deadlines */
1320 /* note that we use "*2" here because we want to look
1321 a bit further into the future; much more makes no
1322 sense since new message might be scheduled in the
1324 while ((pos != NULL) && (off < size * 2))
1326 if (pos->do_transmit == GNUNET_YES)
1328 /* already removed from consideration */
1332 if (discard_low_prio == GNUNET_NO)
1334 delta = pos->deadline.value;
1335 if (delta < t.value)
1338 delta = t.value - delta;
1339 avail += delta * n->bpm_out / 1000 / 60;
1340 if (avail < pos->size)
1342 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1347 /* update slack, considering both its absolute deadline
1348 and relative deadlines caused by other messages
1349 with their respective load */
1350 slack = GNUNET_MIN (slack, avail / n->bpm_out);
1351 if (pos->deadline.value < now.value)
1355 GNUNET_MIN (slack, pos->deadline.value - now.value);
1359 t.value = GNUNET_MAX (pos->deadline.value, t.value);
1360 if (pos->priority <= min_prio)
1362 /* update min for discard */
1363 min_prio = pos->priority;
1368 if (discard_low_prio)
1370 GNUNET_assert (min != NULL);
1371 /* remove lowest-priority entry from consideration */
1372 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1376 /* guard against sending "tiny" messages with large headers without
1378 if ((slack > 1000) && (size > 4 * off))
1380 /* less than 25% of message would be filled with
1381 deadlines still being met if we delay by one
1382 second or more; so just wait for more data */
1383 retry_time->value = slack / 2;
1384 /* reset do_transmit values for next time */
1387 pos->do_transmit = GNUNET_NO;
1392 /* select marked messages (up to size) for transmission */
1397 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1399 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1404 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1408 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1409 "Selected %u bytes of plaintext messages for transmission to `%4s'.\n",
1410 off, GNUNET_i2s (&n->peer));
1417 * Batch multiple messages into a larger buffer.
1419 * @param n neighbour to take messages from
1420 * @param buf target buffer
1421 * @param size size of buf
1422 * @param deadline set to transmission deadline for the result
1423 * @param retry_time set to the time when we should try again
1424 * (only valid if this function returns zero)
1425 * @param priority set to the priority of the batch
1426 * @return number of bytes written to buf (can be zero)
1429 batch_message (struct Neighbour *n,
1432 struct GNUNET_TIME_Absolute *deadline,
1433 struct GNUNET_TIME_Relative *retry_time,
1434 unsigned int *priority)
1436 struct MessageEntry *pos;
1437 struct MessageEntry *prev;
1438 struct MessageEntry *next;
1443 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1444 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1445 if (0 == select_messages (n, size, retry_time))
1447 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1448 "No messages selected, will try again in %llu ms\n",
1454 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1457 if (GNUNET_YES == pos->do_transmit)
1459 GNUNET_assert (pos->size <= size);
1460 memcpy (&buf[ret], &pos[1], pos->size);
1463 *priority += pos->priority;
1464 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1482 * Remove messages with deadlines that have long expired from
1485 * @param n neighbour to inspect
1488 discard_expired_messages (struct Neighbour *n)
1490 struct MessageEntry *prev;
1491 struct MessageEntry *next;
1492 struct MessageEntry *pos;
1493 struct GNUNET_TIME_Absolute cutoff;
1495 cutoff = GNUNET_TIME_relative_to_absolute(PAST_EXPIRATION_DISCARD_TIME);
1501 if (pos->deadline.value < cutoff.value)
1517 * Signature of the main function of a task.
1519 * @param cls closure
1520 * @param tc context information (why was this task triggered now)
1523 retry_plaintext_processing (void *cls,
1524 const struct GNUNET_SCHEDULER_TaskContext *tc)
1526 struct Neighbour *n = cls;
1528 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1529 process_plaintext_neighbour_queue (n);
1534 * Send our key (and encrypted PING) to the other peer.
1536 * @param n the other peer
1538 static void send_key (struct Neighbour *n);
1542 * Check if we have plaintext messages for the specified neighbour
1543 * pending, and if so, consider batching and encrypting them (and
1544 * then trigger processing of the encrypted queue if needed).
1546 * @param n neighbour to check.
1549 process_plaintext_neighbour_queue (struct Neighbour *n)
1551 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1554 struct EncryptedMessage *em; /* encrypted message */
1555 struct EncryptedMessage *ph; /* plaintext header */
1556 struct MessageEntry *me;
1557 unsigned int priority;
1558 struct GNUNET_TIME_Absolute deadline;
1559 struct GNUNET_TIME_Relative retry_time;
1561 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1563 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1564 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1568 case PEER_STATE_DOWN:
1571 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1572 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1573 GNUNET_i2s(&n->peer));
1576 case PEER_STATE_KEY_SENT:
1577 GNUNET_assert (n->retry_set_key_task !=
1578 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
1580 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1581 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1582 GNUNET_i2s(&n->peer));
1585 case PEER_STATE_KEY_RECEIVED:
1586 GNUNET_assert (n->retry_set_key_task !=
1587 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
1589 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1590 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1591 GNUNET_i2s(&n->peer));
1594 case PEER_STATE_KEY_CONFIRMED:
1595 /* ready to continue */
1598 if (n->messages == NULL)
1601 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1602 "Plaintext message queue for `%4s' is empty.\n",
1603 GNUNET_i2s(&n->peer));
1605 return; /* no pending messages */
1607 discard_expired_messages (n);
1608 if (n->encrypted_head != NULL)
1611 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1612 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1613 GNUNET_i2s(&n->peer));
1615 return; /* wait for messages already encrypted to be
1618 ph = (struct EncryptedMessage *) pbuf;
1619 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1621 used = sizeof (struct EncryptedMessage);
1623 used += batch_message (n,
1625 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1626 &deadline, &retry_time, &priority);
1627 if (used == sizeof (struct EncryptedMessage))
1630 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1631 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1632 GNUNET_i2s(&n->peer));
1634 /* no messages selected for sending, try again later... */
1635 n->retry_plaintext_task =
1636 GNUNET_SCHEDULER_add_delayed (sched,
1638 GNUNET_SCHEDULER_PRIORITY_IDLE,
1639 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1641 &retry_plaintext_processing, n);
1645 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1646 ph->inbound_bpm_limit = htonl (n->bpm_in);
1647 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1649 /* setup encryption message header */
1650 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1651 me->deadline = deadline;
1652 me->priority = priority;
1654 em = (struct EncryptedMessage *) &me[1];
1655 em->header.size = htons (used);
1656 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1657 em->reserved = htonl (0);
1658 esize = used - ENCRYPTED_HEADER_SIZE;
1659 GNUNET_CRYPTO_hash (&ph->sequence_number, esize, &em->plaintext_hash);
1662 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1663 "Encrypting %u bytes of plaintext messages for `%4s' for transmission.\n",
1665 GNUNET_i2s(&n->peer));
1667 GNUNET_assert (GNUNET_OK ==
1669 &em->plaintext_hash,
1670 &ph->sequence_number,
1671 &em->sequence_number, esize));
1672 /* append to transmission list */
1673 if (n->encrypted_tail == NULL)
1674 n->encrypted_head = me;
1676 n->encrypted_tail->next = me;
1677 n->encrypted_tail = me;
1678 process_encrypted_neighbour_queue (n);
1683 * Handle CORE_SEND request.
1686 handle_client_send (void *cls,
1687 struct GNUNET_SERVER_Client *client,
1688 const struct GNUNET_MessageHeader *message);
1692 * Function called to notify us that we either succeeded
1693 * or failed to connect (at the transport level) to another
1694 * peer. We should either free the message we were asked
1695 * to transmit or re-try adding it to the queue.
1697 * @param cls closure
1698 * @param size number of bytes available in buf
1699 * @param buf where the callee should write the message
1700 * @return number of bytes written to buf
1703 send_connect_continuation (void *cls, size_t size, void *buf)
1705 struct SendMessage *sm = cls;
1710 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1711 "Asked to send message to disconnected peer `%4s' and connection failed. Discarding message.\n",
1712 GNUNET_i2s (&sm->peer));
1718 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1719 "Connection to peer `%4s' succeeded, retrying original transmission request\n",
1720 GNUNET_i2s (&sm->peer));
1722 handle_client_send (NULL, NULL, &sm->header);
1729 * Handle CORE_SEND request.
1732 handle_client_send (void *cls,
1733 struct GNUNET_SERVER_Client *client,
1734 const struct GNUNET_MessageHeader *message)
1736 const struct SendMessage *sm;
1737 struct SendMessage *smc;
1738 const struct GNUNET_MessageHeader *mh;
1739 struct Neighbour *n;
1740 struct MessageEntry *prev;
1741 struct MessageEntry *pos;
1742 struct MessageEntry *e;
1743 struct MessageEntry *min_prio_entry;
1744 struct MessageEntry *min_prio_prev;
1745 unsigned int min_prio;
1746 unsigned int queue_size;
1749 msize = ntohs (message->size);
1751 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
1755 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1758 sm = (const struct SendMessage *) message;
1759 msize -= sizeof (struct SendMessage);
1760 mh = (const struct GNUNET_MessageHeader *) &sm[1];
1761 if (msize != ntohs (mh->size))
1765 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1768 n = find_neighbour (&sm->peer);
1772 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1773 "Core received `%s' request for `%4s', will try to establish connection within %llu ms\n",
1775 GNUNET_i2s (&sm->peer),
1776 sm->deadline.value);
1778 msize += sizeof (struct SendMessage);
1779 /* ask transport to connect to the peer */
1780 smc = GNUNET_malloc (msize);
1781 memcpy (smc, sm, msize);
1783 GNUNET_TRANSPORT_notify_transmit_ready (transport,
1786 GNUNET_TIME_absolute_get_remaining
1787 (GNUNET_TIME_absolute_ntoh
1789 &send_connect_continuation,
1792 /* transport has already a request pending for this peer! */
1794 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1795 "Dropped second message destined for `%4s' since connection is still down.\n",
1796 GNUNET_i2s(&sm->peer));
1801 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1805 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1806 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
1809 GNUNET_i2s (&sm->peer));
1811 /* bound queue size */
1812 discard_expired_messages (n);
1813 min_prio = (unsigned int) -1;
1819 if (pos->priority < min_prio)
1821 min_prio_entry = pos;
1822 min_prio_prev = prev;
1823 min_prio = pos->priority;
1829 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1832 if (ntohl(sm->priority) <= min_prio)
1834 /* discard new entry */
1836 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1837 "Queue full, discarding new request\n");
1840 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1843 /* discard "min_prio_entry" */
1845 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1846 "Queue full, discarding existing older request\n");
1848 if (min_prio_prev == NULL)
1849 n->messages = min_prio_entry->next;
1851 min_prio_prev->next = min_prio_entry->next;
1852 GNUNET_free (min_prio_entry);
1855 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
1856 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
1857 e->priority = ntohl (sm->priority);
1859 memcpy (&e[1], mh, msize);
1861 /* insert, keep list sorted by deadline */
1864 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
1875 /* consider scheduling now */
1876 process_plaintext_neighbour_queue (n);
1878 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1883 * List of handlers for the messages understood by this
1886 static struct GNUNET_SERVER_MessageHandler handlers[] = {
1887 {&handle_client_init, NULL,
1888 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
1889 {&handle_client_request_configure, NULL,
1890 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONFIGURE,
1891 sizeof (struct RequestConfigureMessage)},
1892 {&handle_client_send, NULL,
1893 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
1899 * PEERINFO is giving us a HELLO for a peer. Add the
1900 * public key to the neighbour's struct and retry
1901 * send_key. Or, if we did not get a HELLO, just do
1905 * @param peer the peer for which this is the HELLO
1906 * @param hello HELLO message of that peer
1907 * @param trust amount of trust we currently have in that peer
1910 process_hello_retry_send_key (void *cls,
1911 const struct GNUNET_PeerIdentity *peer,
1912 const struct GNUNET_HELLO_Message *hello,
1915 struct Neighbour *n;
1919 n = find_neighbour (peer);
1922 if (n->public_key != NULL)
1925 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1926 "Received new `%s' message for `%4s', initiating key exchange.\n",
1931 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1932 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
1934 GNUNET_free (n->public_key);
1935 n->public_key = NULL;
1943 * Task that will retry "send_key" if our previous attempt failed
1947 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1949 struct Neighbour *n = cls;
1951 GNUNET_assert (n->status != PEER_STATE_KEY_CONFIRMED);
1952 n->retry_set_key_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1953 n->set_key_retry_frequency =
1954 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1960 * Send our key (and encrypted PING) to the other peer.
1962 * @param n the other peer
1965 send_key (struct Neighbour *n)
1967 struct SetKeyMessage *sm;
1968 struct MessageEntry *me;
1969 struct PingMessage pp;
1970 struct PingMessage *pm;
1973 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1974 "Asked to perform key exchange with `%4s'.\n",
1975 GNUNET_i2s (&n->peer));
1977 if (n->public_key == NULL)
1979 /* lookup n's public key, then try again */
1981 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1982 "Lacking public key for `%4s', trying to obtain one.\n",
1983 GNUNET_i2s (&n->peer));
1985 GNUNET_PEERINFO_for_all (cfg,
1989 GNUNET_TIME_UNIT_MINUTES,
1990 &process_hello_retry_send_key, NULL);
1993 /* first, set key message */
1994 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1995 sizeof (struct SetKeyMessage));
1996 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
1997 me->priority = SET_KEY_PRIORITY;
1998 me->size = sizeof (struct SetKeyMessage);
1999 if (n->encrypted_head == NULL)
2000 n->encrypted_head = me;
2002 n->encrypted_tail->next = me;
2003 n->encrypted_tail = me;
2004 sm = (struct SetKeyMessage *) &me[1];
2005 sm->header.size = htons (sizeof (struct SetKeyMessage));
2006 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2007 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2008 PEER_STATE_KEY_SENT : n->status));
2010 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2011 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2012 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2013 sizeof (struct GNUNET_PeerIdentity));
2014 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2015 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2016 sm->target = n->peer;
2017 GNUNET_assert (GNUNET_OK ==
2018 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2020 GNUNET_CRYPTO_AesSessionKey),
2022 &sm->encrypted_key));
2023 GNUNET_assert (GNUNET_OK ==
2024 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2027 /* second, encrypted PING message */
2028 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2029 sizeof (struct PingMessage));
2030 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2031 me->priority = PING_PRIORITY;
2032 me->size = sizeof (struct PingMessage);
2033 n->encrypted_tail->next = me;
2034 n->encrypted_tail = me;
2035 pm = (struct PingMessage *) &me[1];
2036 pm->header.size = htons (sizeof (struct PingMessage));
2037 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2038 pp.challenge = htonl (n->ping_challenge);
2039 pp.target = n->peer;
2041 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2042 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2043 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2044 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2045 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2047 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2050 &n->peer.hashPubKey,
2053 sizeof (struct PingMessage) -
2054 sizeof (struct GNUNET_MessageHeader));
2058 case PEER_STATE_DOWN:
2059 n->status = PEER_STATE_KEY_SENT;
2061 case PEER_STATE_KEY_SENT:
2063 case PEER_STATE_KEY_RECEIVED:
2065 case PEER_STATE_KEY_CONFIRMED:
2072 /* trigger queue processing */
2073 process_encrypted_neighbour_queue (n);
2074 if (n->status != PEER_STATE_KEY_CONFIRMED)
2075 n->retry_set_key_task
2076 = GNUNET_SCHEDULER_add_delayed (sched,
2078 GNUNET_SCHEDULER_PRIORITY_KEEP,
2079 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
2080 n->set_key_retry_frequency,
2081 &set_key_retry_task, n);
2086 * We received a SET_KEY message. Validate and update
2087 * our key material and status.
2089 * @param n the neighbour from which we received message m
2090 * @param m the set key message we received
2093 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2097 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2098 * the neighbour's struct and retry handling the set_key message. Or,
2099 * if we did not get a HELLO, just free the set key message.
2101 * @param cls pointer to the set key message
2102 * @param peer the peer for which this is the HELLO
2103 * @param hello HELLO message of that peer
2104 * @param trust amount of trust we currently have in that peer
2107 process_hello_retry_handle_set_key (void *cls,
2108 const struct GNUNET_PeerIdentity *peer,
2109 const struct GNUNET_HELLO_Message *hello,
2112 struct SetKeyMessage *sm = cls;
2113 struct Neighbour *n;
2120 n = find_neighbour (peer);
2126 if (n->public_key != NULL)
2127 return; /* multiple HELLOs match!? */
2129 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2130 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2132 GNUNET_break_op (0);
2133 GNUNET_free (n->public_key);
2134 n->public_key = NULL;
2138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2139 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2140 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2142 handle_set_key (n, sm);
2147 * We received a PING message. Validate and transmit
2150 * @param n sender of the PING
2151 * @param m the encrypted PING message itself
2154 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2156 struct PingMessage t;
2157 struct PingMessage *tp;
2158 struct MessageEntry *me;
2161 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2162 "Core service receives `%s' request from `%4s'.\n",
2163 "PING", GNUNET_i2s (&n->peer));
2167 &my_identity.hashPubKey,
2170 sizeof (struct PingMessage) -
2171 sizeof (struct GNUNET_MessageHeader)))
2174 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2175 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2177 GNUNET_i2s (&t.target),
2178 ntohl (t.challenge), n->decrypt_key.crc32);
2179 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2180 "Target of `%s' request is `%4s'.\n",
2181 "PING", GNUNET_i2s (&t.target));
2183 if (0 != memcmp (&t.target,
2184 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2186 GNUNET_break_op (0);
2189 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2190 sizeof (struct PingMessage));
2191 if (n->encrypted_tail != NULL)
2192 n->encrypted_tail->next = me;
2195 n->encrypted_tail = me;
2196 n->encrypted_head = me;
2198 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2199 me->priority = PONG_PRIORITY;
2200 me->size = sizeof (struct PingMessage);
2201 tp = (struct PingMessage *) &me[1];
2202 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2203 tp->header.size = htons (sizeof (struct PingMessage));
2205 &my_identity.hashPubKey,
2208 sizeof (struct PingMessage) -
2209 sizeof (struct GNUNET_MessageHeader));
2211 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2212 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2213 ntohl (t.challenge), n->encrypt_key.crc32);
2215 /* trigger queue processing */
2216 process_encrypted_neighbour_queue (n);
2221 * We received a SET_KEY message. Validate and update
2222 * our key material and status.
2224 * @param n the neighbour from which we received message m
2225 * @param m the set key message we received
2228 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2230 struct SetKeyMessage *m_cpy;
2231 struct GNUNET_TIME_Absolute t;
2232 struct GNUNET_CRYPTO_AesSessionKey k;
2233 struct PingMessage *ping;
2234 enum PeerStateMachine sender_status;
2237 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2238 "Core service receives `%s' request from `%4s'.\n",
2239 "SET_KEY", GNUNET_i2s (&n->peer));
2241 if (n->public_key == NULL)
2243 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2244 "Lacking public key for peer, trying to obtain one.\n");
2245 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2246 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2247 /* lookup n's public key, then try again */
2248 GNUNET_PEERINFO_for_all (cfg,
2252 GNUNET_TIME_UNIT_MINUTES,
2253 &process_hello_retry_handle_set_key, m_cpy);
2256 if ((ntohl (m->purpose.size) !=
2257 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2258 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2259 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2260 sizeof (struct GNUNET_PeerIdentity)) ||
2262 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2263 &m->purpose, &m->signature, n->public_key)))
2265 /* invalid signature */
2266 GNUNET_break_op (0);
2269 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2270 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2271 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2272 (t.value < n->decrypt_key_created.value))
2274 /* this could rarely happen due to massive re-ordering of
2275 messages on the network level, but is most likely either
2276 a bug or some adversary messing with us. Report. */
2277 GNUNET_break_op (0);
2281 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
2283 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2286 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2287 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2288 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2290 /* failed to decrypt !? */
2291 GNUNET_break_op (0);
2296 if (n->decrypt_key_created.value != t.value)
2298 /* fresh key, reset sequence numbers */
2299 n->last_sequence_number_received = 0;
2300 n->last_packets_bitmap = 0;
2301 n->decrypt_key_created = t;
2303 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2306 case PEER_STATE_DOWN:
2307 n->status = PEER_STATE_KEY_RECEIVED;
2309 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2310 "Responding to `%s' with my own key.\n", "SET_KEY");
2314 case PEER_STATE_KEY_SENT:
2315 case PEER_STATE_KEY_RECEIVED:
2316 n->status = PEER_STATE_KEY_RECEIVED;
2317 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2318 (sender_status != PEER_STATE_KEY_CONFIRMED))
2321 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2322 "Responding to `%s' with my own key (other peer has status %u).\n",
2323 "SET_KEY", sender_status);
2328 case PEER_STATE_KEY_CONFIRMED:
2329 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2330 (sender_status != PEER_STATE_KEY_CONFIRMED))
2333 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2334 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2335 "SET_KEY", sender_status);
2344 if (n->pending_ping != NULL)
2346 ping = n->pending_ping;
2347 n->pending_ping = NULL;
2348 handle_ping (n, ping);
2355 * We received a PONG message. Validate and update
2358 * @param n sender of the PONG
2359 * @param m the encrypted PONG message itself
2362 handle_pong (struct Neighbour *n, const struct PingMessage *m)
2364 struct PingMessage t;
2367 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2368 "Core service receives `%s' request from `%4s'.\n",
2369 "PONG", GNUNET_i2s (&n->peer));
2373 &n->peer.hashPubKey,
2376 sizeof (struct PingMessage) -
2377 sizeof (struct GNUNET_MessageHeader)))
2380 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2381 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2383 GNUNET_i2s (&t.target),
2384 ntohl (t.challenge), n->decrypt_key.crc32);
2386 if ((0 != memcmp (&t.target,
2388 sizeof (struct GNUNET_PeerIdentity))) ||
2389 (n->ping_challenge != ntohl (t.challenge)))
2391 /* PONG malformed */
2393 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2394 "Received malfromed `%s' wanted sender `%4s' with challenge %u\n",
2395 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2396 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2397 "Received malfromed `%s' received from `%4s' with challenge %u\n",
2398 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2400 GNUNET_break_op (0);
2405 case PEER_STATE_DOWN:
2406 GNUNET_break (0); /* should be impossible */
2408 case PEER_STATE_KEY_SENT:
2409 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2411 case PEER_STATE_KEY_RECEIVED:
2412 n->status = PEER_STATE_KEY_CONFIRMED;
2413 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
2415 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2416 n->retry_set_key_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
2418 process_encrypted_neighbour_queue (n);
2420 case PEER_STATE_KEY_CONFIRMED:
2421 /* duplicate PONG? */
2431 * Send a P2P message to a client.
2433 * @param sender who sent us the message?
2434 * @param client who should we give the message to?
2435 * @param m contains the message to transmit
2436 * @param msize number of bytes in buf to transmit
2439 send_p2p_message_to_client (struct Neighbour *sender,
2440 struct Client *client,
2441 const void *m, size_t msize)
2443 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2444 struct NotifyTrafficMessage *ntm;
2447 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2448 "Core service passes message from `%4s' of type %u to client.\n",
2449 GNUNET_i2s(&sender->peer),
2450 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2452 ntm = (struct NotifyTrafficMessage *) buf;
2453 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2454 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2455 ntm->reserved = htonl (0);
2456 ntm->peer = sender->peer;
2457 memcpy (&ntm[1], m, msize);
2458 send_to_client (client, &ntm->header, GNUNET_YES);
2463 * Deliver P2P message to interested clients.
2465 * @param sender who sent us the message?
2466 * @param m the message
2467 * @param msize size of the message (including header)
2470 deliver_message (struct Neighbour *sender,
2471 const struct GNUNET_MessageHeader *m, size_t msize)
2473 struct Client *cpos;
2478 type = ntohs (m->type);
2480 while (cpos != NULL)
2482 deliver_full = GNUNET_NO;
2483 if (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND)
2484 deliver_full = GNUNET_YES;
2487 for (tpos = 0; tpos < cpos->tcnt; tpos++)
2489 if (type != cpos->types[tpos])
2491 deliver_full = GNUNET_YES;
2495 if (GNUNET_YES == deliver_full)
2496 send_p2p_message_to_client (sender, cpos, m, msize);
2497 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2498 send_p2p_message_to_client (sender, cpos, m,
2499 sizeof (struct GNUNET_MessageHeader));
2506 * Align P2P message and then deliver to interested clients.
2508 * @param sender who sent us the message?
2509 * @param buffer unaligned (!) buffer containing message
2510 * @param msize size of the message (including header)
2513 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
2517 /* TODO: call to statistics? */
2518 memcpy (abuf, buffer, msize);
2519 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
2524 * Deliver P2P messages to interested clients.
2526 * @param sender who sent us the message?
2527 * @param buffer buffer containing messages, can be modified
2528 * @param buffer_size size of the buffer (overall)
2529 * @param offset offset where messages in the buffer start
2532 deliver_messages (struct Neighbour *sender,
2533 const char *buffer, size_t buffer_size, size_t offset)
2535 struct GNUNET_MessageHeader *mhp;
2536 struct GNUNET_MessageHeader mh;
2540 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
2542 if (0 != offset % sizeof (uint16_t))
2544 /* outch, need to copy to access header */
2545 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
2550 /* can access header directly */
2551 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
2553 msize = ntohs (mhp->size);
2554 if (msize + offset > buffer_size)
2556 /* malformed message, header says it is larger than what
2557 would fit into the overall buffer */
2558 GNUNET_break_op (0);
2561 #if HAVE_UNALIGNED_64_ACCESS
2562 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
2564 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
2566 if (GNUNET_YES == need_align)
2567 align_and_deliver (sender, &buffer[offset], msize);
2569 deliver_message (sender,
2570 (const struct GNUNET_MessageHeader *)
2571 &buffer[offset], msize);
2578 * We received an encrypted message. Decrypt, validate and
2579 * pass on to the appropriate clients.
2582 handle_encrypted_message (struct Neighbour *n,
2583 const struct EncryptedMessage *m)
2585 size_t size = ntohs (m->header.size);
2587 struct EncryptedMessage *pt; /* plaintext */
2591 struct GNUNET_TIME_Absolute t;
2594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2595 "Core service receives `%s' request from `%4s'.\n",
2596 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
2602 &m->sequence_number,
2603 &buf[ENCRYPTED_HEADER_SIZE], size - ENCRYPTED_HEADER_SIZE))
2605 pt = (struct EncryptedMessage *) buf;
2608 GNUNET_CRYPTO_hash (&pt->sequence_number,
2609 size - ENCRYPTED_HEADER_SIZE, &ph);
2610 if (0 != memcmp (&ph, &m->plaintext_hash, sizeof (GNUNET_HashCode)))
2612 /* checksum failed */
2613 GNUNET_break_op (0);
2617 /* validate sequence number */
2618 snum = ntohl (pt->sequence_number);
2619 if (n->last_sequence_number_received == snum)
2621 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2622 "Received duplicate message, ignoring.\n");
2623 /* duplicate, ignore */
2626 if ((n->last_sequence_number_received > snum) &&
2627 (n->last_sequence_number_received - snum > 32))
2629 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2630 "Received ancient out of sequence message, ignoring.\n");
2631 /* ancient out of sequence, ignore */
2634 if (n->last_sequence_number_received > snum)
2636 unsigned int rotbit =
2637 1 << (n->last_sequence_number_received - snum - 1);
2638 if ((n->last_packets_bitmap & rotbit) != 0)
2640 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2641 "Received duplicate message, ignoring.\n");
2642 /* duplicate, ignore */
2645 n->last_packets_bitmap |= rotbit;
2647 if (n->last_sequence_number_received < snum)
2649 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
2650 n->last_sequence_number_received = snum;
2653 /* check timestamp */
2654 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
2655 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
2657 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2659 ("Message received far too old (%llu ms). Content ignored.\n"),
2660 GNUNET_TIME_absolute_get_duration (t).value);
2664 /* process decrypted message(s) */
2665 n->bpm_out_external_limit = ntohl (pt->inbound_bpm_limit);
2666 n->bpm_out = GNUNET_MAX (n->bpm_out_external_limit,
2667 n->bpm_out_internal_limit);
2668 n->last_activity = GNUNET_TIME_absolute_get ();
2669 off = sizeof (struct EncryptedMessage);
2670 deliver_messages (n, buf, size, off);
2675 * Function called by the transport for each received message.
2677 * @param cls closure
2678 * @param latency estimated latency for communicating with the
2680 * @param peer (claimed) identity of the other peer
2681 * @param message the message
2684 handle_transport_receive (void *cls,
2685 struct GNUNET_TIME_Relative latency,
2686 const struct GNUNET_PeerIdentity *peer,
2687 const struct GNUNET_MessageHeader *message)
2689 struct Neighbour *n;
2690 struct GNUNET_TIME_Absolute now;
2696 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2697 "Received message of type %u from `%4s', demultiplexing.\n",
2698 ntohs (message->type), GNUNET_i2s (peer));
2700 n = find_neighbour (peer);
2706 n->last_latency = latency;
2707 up = n->status == PEER_STATE_KEY_CONFIRMED;
2708 type = ntohs (message->type);
2709 size = ntohs (message->size);
2712 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
2713 if (size != sizeof (struct SetKeyMessage))
2715 GNUNET_break_op (0);
2718 handle_set_key (n, (const struct SetKeyMessage *) message);
2720 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
2721 if (size < sizeof (struct EncryptedMessage) +
2722 sizeof (struct GNUNET_MessageHeader))
2724 GNUNET_break_op (0);
2727 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2728 (n->status != PEER_STATE_KEY_CONFIRMED))
2730 GNUNET_break_op (0);
2733 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
2735 case GNUNET_MESSAGE_TYPE_CORE_PING:
2736 if (size != sizeof (struct PingMessage))
2738 GNUNET_break_op (0);
2741 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2742 (n->status != PEER_STATE_KEY_CONFIRMED))
2745 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2746 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
2747 "PING", GNUNET_i2s (&n->peer));
2749 GNUNET_free_non_null (n->pending_ping);
2750 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
2751 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
2754 handle_ping (n, (const struct PingMessage *) message);
2756 case GNUNET_MESSAGE_TYPE_CORE_PONG:
2757 if (size != sizeof (struct PingMessage))
2759 GNUNET_break_op (0);
2762 if ((n->status != PEER_STATE_KEY_SENT) &&
2763 (n->status != PEER_STATE_KEY_RECEIVED) &&
2764 (n->status != PEER_STATE_KEY_CONFIRMED))
2766 /* could not decrypt pong, oops! */
2767 GNUNET_break_op (0);
2770 handle_pong (n, (const struct PingMessage *) message);
2773 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2774 _("Unsupported message of type %u received.\n"), type);
2777 if (n->status == PEER_STATE_KEY_CONFIRMED)
2779 now = GNUNET_TIME_absolute_get ();
2780 n->last_activity = now;
2782 n->time_established = now;
2788 * Function called by transport to notify us that
2789 * a peer connected to us (on the network level).
2791 * @param cls closure
2792 * @param peer the peer that connected
2793 * @param latency current latency of the connection
2796 handle_transport_notify_connect (void *cls,
2797 const struct GNUNET_PeerIdentity *peer,
2798 struct GNUNET_TIME_Relative latency)
2800 struct Neighbour *n;
2801 struct GNUNET_TIME_Absolute now;
2802 struct ConnectNotifyMessage cnm;
2804 n = find_neighbour (peer);
2807 /* duplicate connect notification!? */
2811 now = GNUNET_TIME_absolute_get ();
2812 n = GNUNET_malloc (sizeof (struct Neighbour));
2813 n->next = neighbours;
2816 n->last_latency = latency;
2817 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2818 n->encrypt_key_created = now;
2819 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2820 n->last_asw_update = now;
2821 n->last_arw_update = now;
2822 n->bpm_in = DEFAULT_BPM_IN_OUT;
2823 n->bpm_out = DEFAULT_BPM_IN_OUT;
2824 n->bpm_out_internal_limit = (uint32_t) - 1;
2825 n->bpm_out_external_limit = DEFAULT_BPM_IN_OUT;
2826 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2829 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2830 "Received connection from `%4s'.\n",
2831 GNUNET_i2s (&n->peer));
2833 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2834 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2835 cnm.bpm_available = htonl (DEFAULT_BPM_IN_OUT);
2837 cnm.last_activity = GNUNET_TIME_absolute_hton (now);
2838 send_to_all_clients (&cnm.header, GNUNET_YES);
2843 * Free the given entry for the neighbour (it has
2844 * already been removed from the list at this point).
2845 * @param n neighbour to free
2848 free_neighbour (struct Neighbour *n)
2850 struct MessageEntry *m;
2852 while (NULL != (m = n->messages))
2854 n->messages = m->next;
2857 while (NULL != (m = n->encrypted_head))
2859 n->encrypted_head = m->next;
2863 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
2864 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
2865 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
2866 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
2867 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2868 GNUNET_free_non_null (n->public_key);
2869 GNUNET_free_non_null (n->pending_ping);
2875 * Function called by transport telling us that a peer
2878 * @param cls closure
2879 * @param peer the peer that disconnected
2882 handle_transport_notify_disconnect (void *cls,
2883 const struct GNUNET_PeerIdentity *peer)
2885 struct ConnectNotifyMessage cnm;
2886 struct Neighbour *n;
2887 struct Neighbour *p;
2890 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2891 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
2895 while ((n != NULL) &&
2896 (0 != memcmp (&n->peer, peer, sizeof (struct GNUNET_PeerIdentity))))
2907 neighbours = n->next;
2910 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2911 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
2912 cnm.bpm_available = htonl (0);
2914 cnm.last_activity = GNUNET_TIME_absolute_hton (n->last_activity);
2915 send_to_all_clients (&cnm.header, GNUNET_YES);
2921 * Last task run during shutdown. Disconnects us from
2925 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2927 struct Neighbour *n;
2931 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2932 "Core service shutting down.\n");
2934 GNUNET_assert (transport != NULL);
2935 GNUNET_TRANSPORT_disconnect (transport);
2937 while (NULL != (n = neighbours))
2939 neighbours = n->next;
2942 while (NULL != (c = clients))
2943 handle_client_disconnect (NULL, c->client_handle);
2948 * Initiate core service.
2950 * @param cls closure
2951 * @param s scheduler to use
2952 * @param serv the initialized server
2953 * @param c configuration to use
2957 struct GNUNET_SCHEDULER_Handle *s,
2958 struct GNUNET_SERVER_Handle *serv, struct GNUNET_CONFIGURATION_Handle *c)
2961 unsigned long long qin;
2962 unsigned long long qout;
2963 unsigned long long tneigh;
2969 /* parse configuration */
2973 GNUNET_CONFIGURATION_get_value_number (c,
2978 GNUNET_CONFIGURATION_get_value_number (c,
2983 GNUNET_CONFIGURATION_get_value_number (c,
2985 "ZZ_LIMIT", &tneigh)) ||
2988 GNUNET_CONFIGURATION_get_value_filename (c,
2990 "HOSTKEY", &keyfile)))
2992 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2994 ("Core service is lacking key configuration settings. Exiting.\n"));
2995 GNUNET_SCHEDULER_shutdown (s);
2998 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2999 GNUNET_free (keyfile);
3000 if (my_private_key == NULL)
3002 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3003 _("Core service could not access hostkey. Exiting.\n"));
3004 GNUNET_SCHEDULER_shutdown (s);
3007 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3008 GNUNET_CRYPTO_hash (&my_public_key,
3009 sizeof (my_public_key), &my_identity.hashPubKey);
3010 /* setup notification */
3012 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3013 /* setup transport connection */
3014 transport = GNUNET_TRANSPORT_connect (sched,
3017 &handle_transport_receive,
3018 &handle_transport_notify_connect,
3019 &handle_transport_notify_disconnect);
3020 GNUNET_assert (NULL != transport);
3021 GNUNET_SCHEDULER_add_delayed (sched,
3023 GNUNET_SCHEDULER_PRIORITY_IDLE,
3024 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
3025 GNUNET_TIME_UNIT_FOREVER_REL,
3026 &cleaning_task, NULL);
3027 /* process client requests */
3028 GNUNET_SERVER_add_handlers (server, handlers);
3029 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3030 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3035 * Function called during shutdown. Clean up our state.
3038 cleanup (void *cls, struct GNUNET_CONFIGURATION_Handle *cfg)
3042 if (my_private_key != NULL)
3043 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3048 * The main function for the transport service.
3050 * @param argc number of arguments from the command line
3051 * @param argv command line arguments
3052 * @return 0 ok, 1 on error
3055 main (int argc, char *const *argv)
3057 return (GNUNET_OK ==
3058 GNUNET_SERVICE_run (argc,
3060 "core", &run, NULL, &cleanup, NULL)) ? 0 : 1;
3063 /* end of gnunet-service-core.c */