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)
1503 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1504 "Message is %llu ms past due, discarding.\n",
1505 cutoff.value - pos->deadline.value);
1520 * Signature of the main function of a task.
1522 * @param cls closure
1523 * @param tc context information (why was this task triggered now)
1526 retry_plaintext_processing (void *cls,
1527 const struct GNUNET_SCHEDULER_TaskContext *tc)
1529 struct Neighbour *n = cls;
1531 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1532 process_plaintext_neighbour_queue (n);
1537 * Send our key (and encrypted PING) to the other peer.
1539 * @param n the other peer
1541 static void send_key (struct Neighbour *n);
1545 * Check if we have plaintext messages for the specified neighbour
1546 * pending, and if so, consider batching and encrypting them (and
1547 * then trigger processing of the encrypted queue if needed).
1549 * @param n neighbour to check.
1552 process_plaintext_neighbour_queue (struct Neighbour *n)
1554 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1557 struct EncryptedMessage *em; /* encrypted message */
1558 struct EncryptedMessage *ph; /* plaintext header */
1559 struct MessageEntry *me;
1560 unsigned int priority;
1561 struct GNUNET_TIME_Absolute deadline;
1562 struct GNUNET_TIME_Relative retry_time;
1564 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1566 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1567 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1571 case PEER_STATE_DOWN:
1574 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1575 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1576 GNUNET_i2s(&n->peer));
1579 case PEER_STATE_KEY_SENT:
1580 GNUNET_assert (n->retry_set_key_task !=
1581 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
1583 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1584 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1585 GNUNET_i2s(&n->peer));
1588 case PEER_STATE_KEY_RECEIVED:
1589 GNUNET_assert (n->retry_set_key_task !=
1590 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
1592 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1593 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1594 GNUNET_i2s(&n->peer));
1597 case PEER_STATE_KEY_CONFIRMED:
1598 /* ready to continue */
1601 discard_expired_messages (n);
1602 if (n->messages == NULL)
1605 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1606 "Plaintext message queue for `%4s' is empty.\n",
1607 GNUNET_i2s(&n->peer));
1609 return; /* no pending messages */
1611 if (n->encrypted_head != NULL)
1614 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1615 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1616 GNUNET_i2s(&n->peer));
1618 return; /* wait for messages already encrypted to be
1621 ph = (struct EncryptedMessage *) pbuf;
1622 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1624 used = sizeof (struct EncryptedMessage);
1625 used += batch_message (n,
1627 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1628 &deadline, &retry_time, &priority);
1629 if (used == sizeof (struct EncryptedMessage))
1632 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1633 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1634 GNUNET_i2s(&n->peer));
1636 /* no messages selected for sending, try again later... */
1637 n->retry_plaintext_task =
1638 GNUNET_SCHEDULER_add_delayed (sched,
1640 GNUNET_SCHEDULER_PRIORITY_IDLE,
1641 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1643 &retry_plaintext_processing, n);
1647 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1648 ph->inbound_bpm_limit = htonl (n->bpm_in);
1649 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1651 /* setup encryption message header */
1652 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1653 me->deadline = deadline;
1654 me->priority = priority;
1656 em = (struct EncryptedMessage *) &me[1];
1657 em->header.size = htons (used);
1658 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1659 em->reserved = htonl (0);
1660 esize = used - ENCRYPTED_HEADER_SIZE;
1661 GNUNET_CRYPTO_hash (&ph->sequence_number, esize, &em->plaintext_hash);
1664 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1665 "Encrypting %u bytes of plaintext messages for `%4s' for transmission.\n",
1667 GNUNET_i2s(&n->peer));
1669 GNUNET_assert (GNUNET_OK ==
1671 &em->plaintext_hash,
1672 &ph->sequence_number,
1673 &em->sequence_number, esize));
1674 /* append to transmission list */
1675 if (n->encrypted_tail == NULL)
1676 n->encrypted_head = me;
1678 n->encrypted_tail->next = me;
1679 n->encrypted_tail = me;
1680 process_encrypted_neighbour_queue (n);
1685 * Handle CORE_SEND request.
1688 handle_client_send (void *cls,
1689 struct GNUNET_SERVER_Client *client,
1690 const struct GNUNET_MessageHeader *message);
1694 * Function called to notify us that we either succeeded
1695 * or failed to connect (at the transport level) to another
1696 * peer. We should either free the message we were asked
1697 * to transmit or re-try adding it to the queue.
1699 * @param cls closure
1700 * @param size number of bytes available in buf
1701 * @param buf where the callee should write the message
1702 * @return number of bytes written to buf
1705 send_connect_continuation (void *cls, size_t size, void *buf)
1707 struct SendMessage *sm = cls;
1712 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1713 "Asked to send message to disconnected peer `%4s' and connection failed. Discarding message.\n",
1714 GNUNET_i2s (&sm->peer));
1720 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1721 "Connection to peer `%4s' succeeded, retrying original transmission request\n",
1722 GNUNET_i2s (&sm->peer));
1724 handle_client_send (NULL, NULL, &sm->header);
1731 * Handle CORE_SEND request.
1734 handle_client_send (void *cls,
1735 struct GNUNET_SERVER_Client *client,
1736 const struct GNUNET_MessageHeader *message)
1738 const struct SendMessage *sm;
1739 struct SendMessage *smc;
1740 const struct GNUNET_MessageHeader *mh;
1741 struct Neighbour *n;
1742 struct MessageEntry *prev;
1743 struct MessageEntry *pos;
1744 struct MessageEntry *e;
1745 struct MessageEntry *min_prio_entry;
1746 struct MessageEntry *min_prio_prev;
1747 unsigned int min_prio;
1748 unsigned int queue_size;
1751 msize = ntohs (message->size);
1753 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
1757 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1760 sm = (const struct SendMessage *) message;
1761 msize -= sizeof (struct SendMessage);
1762 mh = (const struct GNUNET_MessageHeader *) &sm[1];
1763 if (msize != ntohs (mh->size))
1767 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1770 n = find_neighbour (&sm->peer);
1774 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1775 "Core received `%s' request for `%4s', will try to establish connection within %llu ms\n",
1777 GNUNET_i2s (&sm->peer),
1778 sm->deadline.value);
1780 msize += sizeof (struct SendMessage);
1781 /* ask transport to connect to the peer */
1782 smc = GNUNET_malloc (msize);
1783 memcpy (smc, sm, msize);
1785 GNUNET_TRANSPORT_notify_transmit_ready (transport,
1788 GNUNET_TIME_absolute_get_remaining
1789 (GNUNET_TIME_absolute_ntoh
1791 &send_connect_continuation,
1794 /* transport has already a request pending for this peer! */
1796 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1797 "Dropped second message destined for `%4s' since connection is still down.\n",
1798 GNUNET_i2s(&sm->peer));
1803 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1807 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1808 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
1811 GNUNET_i2s (&sm->peer));
1813 /* bound queue size */
1814 discard_expired_messages (n);
1815 min_prio = (unsigned int) -1;
1821 if (pos->priority < min_prio)
1823 min_prio_entry = pos;
1824 min_prio_prev = prev;
1825 min_prio = pos->priority;
1831 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1834 if (ntohl(sm->priority) <= min_prio)
1836 /* discard new entry */
1838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1839 "Queue full, discarding new request\n");
1842 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1845 /* discard "min_prio_entry" */
1847 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1848 "Queue full, discarding existing older request\n");
1850 if (min_prio_prev == NULL)
1851 n->messages = min_prio_entry->next;
1853 min_prio_prev->next = min_prio_entry->next;
1854 GNUNET_free (min_prio_entry);
1857 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
1858 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
1859 e->priority = ntohl (sm->priority);
1861 memcpy (&e[1], mh, msize);
1863 /* insert, keep list sorted by deadline */
1866 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
1877 /* consider scheduling now */
1878 process_plaintext_neighbour_queue (n);
1880 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1885 * List of handlers for the messages understood by this
1888 static struct GNUNET_SERVER_MessageHandler handlers[] = {
1889 {&handle_client_init, NULL,
1890 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
1891 {&handle_client_request_configure, NULL,
1892 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONFIGURE,
1893 sizeof (struct RequestConfigureMessage)},
1894 {&handle_client_send, NULL,
1895 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
1901 * PEERINFO is giving us a HELLO for a peer. Add the
1902 * public key to the neighbour's struct and retry
1903 * send_key. Or, if we did not get a HELLO, just do
1907 * @param peer the peer for which this is the HELLO
1908 * @param hello HELLO message of that peer
1909 * @param trust amount of trust we currently have in that peer
1912 process_hello_retry_send_key (void *cls,
1913 const struct GNUNET_PeerIdentity *peer,
1914 const struct GNUNET_HELLO_Message *hello,
1917 struct Neighbour *n;
1921 n = find_neighbour (peer);
1924 if (n->public_key != NULL)
1927 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1928 "Received new `%s' message for `%4s', initiating key exchange.\n",
1933 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1934 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
1936 GNUNET_free (n->public_key);
1937 n->public_key = NULL;
1945 * Task that will retry "send_key" if our previous attempt failed
1949 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1951 struct Neighbour *n = cls;
1953 GNUNET_assert (n->status != PEER_STATE_KEY_CONFIRMED);
1954 n->retry_set_key_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1955 n->set_key_retry_frequency =
1956 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1962 * Send our key (and encrypted PING) to the other peer.
1964 * @param n the other peer
1967 send_key (struct Neighbour *n)
1969 struct SetKeyMessage *sm;
1970 struct MessageEntry *me;
1971 struct PingMessage pp;
1972 struct PingMessage *pm;
1975 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1976 "Asked to perform key exchange with `%4s'.\n",
1977 GNUNET_i2s (&n->peer));
1979 if (n->public_key == NULL)
1981 /* lookup n's public key, then try again */
1983 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1984 "Lacking public key for `%4s', trying to obtain one.\n",
1985 GNUNET_i2s (&n->peer));
1987 GNUNET_PEERINFO_for_all (cfg,
1991 GNUNET_TIME_UNIT_MINUTES,
1992 &process_hello_retry_send_key, NULL);
1995 /* first, set key message */
1996 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1997 sizeof (struct SetKeyMessage));
1998 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
1999 me->priority = SET_KEY_PRIORITY;
2000 me->size = sizeof (struct SetKeyMessage);
2001 if (n->encrypted_head == NULL)
2002 n->encrypted_head = me;
2004 n->encrypted_tail->next = me;
2005 n->encrypted_tail = me;
2006 sm = (struct SetKeyMessage *) &me[1];
2007 sm->header.size = htons (sizeof (struct SetKeyMessage));
2008 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
2009 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
2010 PEER_STATE_KEY_SENT : n->status));
2012 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2013 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2014 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2015 sizeof (struct GNUNET_PeerIdentity));
2016 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
2017 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
2018 sm->target = n->peer;
2019 GNUNET_assert (GNUNET_OK ==
2020 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
2022 GNUNET_CRYPTO_AesSessionKey),
2024 &sm->encrypted_key));
2025 GNUNET_assert (GNUNET_OK ==
2026 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
2029 /* second, encrypted PING message */
2030 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2031 sizeof (struct PingMessage));
2032 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
2033 me->priority = PING_PRIORITY;
2034 me->size = sizeof (struct PingMessage);
2035 n->encrypted_tail->next = me;
2036 n->encrypted_tail = me;
2037 pm = (struct PingMessage *) &me[1];
2038 pm->header.size = htons (sizeof (struct PingMessage));
2039 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
2040 pp.challenge = htonl (n->ping_challenge);
2041 pp.target = n->peer;
2043 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2044 "Encrypting `%s' and `%s' messages for `%4s'.\n",
2045 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
2046 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2047 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
2049 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
2052 &n->peer.hashPubKey,
2055 sizeof (struct PingMessage) -
2056 sizeof (struct GNUNET_MessageHeader));
2060 case PEER_STATE_DOWN:
2061 n->status = PEER_STATE_KEY_SENT;
2063 case PEER_STATE_KEY_SENT:
2065 case PEER_STATE_KEY_RECEIVED:
2067 case PEER_STATE_KEY_CONFIRMED:
2074 /* trigger queue processing */
2075 process_encrypted_neighbour_queue (n);
2076 if (n->status != PEER_STATE_KEY_CONFIRMED)
2077 n->retry_set_key_task
2078 = GNUNET_SCHEDULER_add_delayed (sched,
2080 GNUNET_SCHEDULER_PRIORITY_KEEP,
2081 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
2082 n->set_key_retry_frequency,
2083 &set_key_retry_task, n);
2088 * We received a SET_KEY message. Validate and update
2089 * our key material and status.
2091 * @param n the neighbour from which we received message m
2092 * @param m the set key message we received
2095 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
2099 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2100 * the neighbour's struct and retry handling the set_key message. Or,
2101 * if we did not get a HELLO, just free the set key message.
2103 * @param cls pointer to the set key message
2104 * @param peer the peer for which this is the HELLO
2105 * @param hello HELLO message of that peer
2106 * @param trust amount of trust we currently have in that peer
2109 process_hello_retry_handle_set_key (void *cls,
2110 const struct GNUNET_PeerIdentity *peer,
2111 const struct GNUNET_HELLO_Message *hello,
2114 struct SetKeyMessage *sm = cls;
2115 struct Neighbour *n;
2122 n = find_neighbour (peer);
2128 if (n->public_key != NULL)
2129 return; /* multiple HELLOs match!? */
2131 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2132 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
2134 GNUNET_break_op (0);
2135 GNUNET_free (n->public_key);
2136 n->public_key = NULL;
2140 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2141 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
2142 "HELLO", GNUNET_i2s (peer), "SET_KEY");
2144 handle_set_key (n, sm);
2149 * We received a PING message. Validate and transmit
2152 * @param n sender of the PING
2153 * @param m the encrypted PING message itself
2156 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2158 struct PingMessage t;
2159 struct PingMessage *tp;
2160 struct MessageEntry *me;
2163 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2164 "Core service receives `%s' request from `%4s'.\n",
2165 "PING", GNUNET_i2s (&n->peer));
2169 &my_identity.hashPubKey,
2172 sizeof (struct PingMessage) -
2173 sizeof (struct GNUNET_MessageHeader)))
2176 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2177 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2179 GNUNET_i2s (&t.target),
2180 ntohl (t.challenge), n->decrypt_key.crc32);
2181 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2182 "Target of `%s' request is `%4s'.\n",
2183 "PING", GNUNET_i2s (&t.target));
2185 if (0 != memcmp (&t.target,
2186 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2188 GNUNET_break_op (0);
2191 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2192 sizeof (struct PingMessage));
2193 if (n->encrypted_tail != NULL)
2194 n->encrypted_tail->next = me;
2197 n->encrypted_tail = me;
2198 n->encrypted_head = me;
2200 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2201 me->priority = PONG_PRIORITY;
2202 me->size = sizeof (struct PingMessage);
2203 tp = (struct PingMessage *) &me[1];
2204 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2205 tp->header.size = htons (sizeof (struct PingMessage));
2207 &my_identity.hashPubKey,
2210 sizeof (struct PingMessage) -
2211 sizeof (struct GNUNET_MessageHeader));
2213 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2214 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2215 ntohl (t.challenge), n->encrypt_key.crc32);
2217 /* trigger queue processing */
2218 process_encrypted_neighbour_queue (n);
2223 * We received a SET_KEY message. Validate and update
2224 * our key material and status.
2226 * @param n the neighbour from which we received message m
2227 * @param m the set key message we received
2230 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2232 struct SetKeyMessage *m_cpy;
2233 struct GNUNET_TIME_Absolute t;
2234 struct GNUNET_CRYPTO_AesSessionKey k;
2235 struct PingMessage *ping;
2236 enum PeerStateMachine sender_status;
2239 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2240 "Core service receives `%s' request from `%4s'.\n",
2241 "SET_KEY", GNUNET_i2s (&n->peer));
2243 if (n->public_key == NULL)
2245 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2246 "Lacking public key for peer, trying to obtain one.\n");
2247 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2248 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2249 /* lookup n's public key, then try again */
2250 GNUNET_PEERINFO_for_all (cfg,
2254 GNUNET_TIME_UNIT_MINUTES,
2255 &process_hello_retry_handle_set_key, m_cpy);
2258 if ((ntohl (m->purpose.size) !=
2259 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2260 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2261 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2262 sizeof (struct GNUNET_PeerIdentity)) ||
2264 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2265 &m->purpose, &m->signature, n->public_key)))
2267 /* invalid signature */
2268 GNUNET_break_op (0);
2271 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2272 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2273 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2274 (t.value < n->decrypt_key_created.value))
2276 /* this could rarely happen due to massive re-ordering of
2277 messages on the network level, but is most likely either
2278 a bug or some adversary messing with us. Report. */
2279 GNUNET_break_op (0);
2283 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
2285 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2288 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2289 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2290 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2292 /* failed to decrypt !? */
2293 GNUNET_break_op (0);
2298 if (n->decrypt_key_created.value != t.value)
2300 /* fresh key, reset sequence numbers */
2301 n->last_sequence_number_received = 0;
2302 n->last_packets_bitmap = 0;
2303 n->decrypt_key_created = t;
2305 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2308 case PEER_STATE_DOWN:
2309 n->status = PEER_STATE_KEY_RECEIVED;
2311 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2312 "Responding to `%s' with my own key.\n", "SET_KEY");
2316 case PEER_STATE_KEY_SENT:
2317 case PEER_STATE_KEY_RECEIVED:
2318 n->status = PEER_STATE_KEY_RECEIVED;
2319 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2320 (sender_status != PEER_STATE_KEY_CONFIRMED))
2323 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2324 "Responding to `%s' with my own key (other peer has status %u).\n",
2325 "SET_KEY", sender_status);
2330 case PEER_STATE_KEY_CONFIRMED:
2331 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2332 (sender_status != PEER_STATE_KEY_CONFIRMED))
2335 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2336 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2337 "SET_KEY", sender_status);
2346 if (n->pending_ping != NULL)
2348 ping = n->pending_ping;
2349 n->pending_ping = NULL;
2350 handle_ping (n, ping);
2357 * We received a PONG message. Validate and update
2360 * @param n sender of the PONG
2361 * @param m the encrypted PONG message itself
2364 handle_pong (struct Neighbour *n, const struct PingMessage *m)
2366 struct PingMessage t;
2369 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2370 "Core service receives `%s' request from `%4s'.\n",
2371 "PONG", GNUNET_i2s (&n->peer));
2375 &n->peer.hashPubKey,
2378 sizeof (struct PingMessage) -
2379 sizeof (struct GNUNET_MessageHeader)))
2382 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2383 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2385 GNUNET_i2s (&t.target),
2386 ntohl (t.challenge), n->decrypt_key.crc32);
2388 if ((0 != memcmp (&t.target,
2390 sizeof (struct GNUNET_PeerIdentity))) ||
2391 (n->ping_challenge != ntohl (t.challenge)))
2393 /* PONG malformed */
2395 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2396 "Received malfromed `%s' wanted sender `%4s' with challenge %u\n",
2397 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2398 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2399 "Received malfromed `%s' received from `%4s' with challenge %u\n",
2400 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2402 GNUNET_break_op (0);
2407 case PEER_STATE_DOWN:
2408 GNUNET_break (0); /* should be impossible */
2410 case PEER_STATE_KEY_SENT:
2411 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2413 case PEER_STATE_KEY_RECEIVED:
2414 n->status = PEER_STATE_KEY_CONFIRMED;
2415 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
2417 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2418 n->retry_set_key_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
2420 process_encrypted_neighbour_queue (n);
2422 case PEER_STATE_KEY_CONFIRMED:
2423 /* duplicate PONG? */
2433 * Send a P2P message to a client.
2435 * @param sender who sent us the message?
2436 * @param client who should we give the message to?
2437 * @param m contains the message to transmit
2438 * @param msize number of bytes in buf to transmit
2441 send_p2p_message_to_client (struct Neighbour *sender,
2442 struct Client *client,
2443 const void *m, size_t msize)
2445 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2446 struct NotifyTrafficMessage *ntm;
2449 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2450 "Core service passes message from `%4s' of type %u to client.\n",
2451 GNUNET_i2s(&sender->peer),
2452 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2454 ntm = (struct NotifyTrafficMessage *) buf;
2455 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2456 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2457 ntm->reserved = htonl (0);
2458 ntm->peer = sender->peer;
2459 memcpy (&ntm[1], m, msize);
2460 send_to_client (client, &ntm->header, GNUNET_YES);
2465 * Deliver P2P message to interested clients.
2467 * @param sender who sent us the message?
2468 * @param m the message
2469 * @param msize size of the message (including header)
2472 deliver_message (struct Neighbour *sender,
2473 const struct GNUNET_MessageHeader *m, size_t msize)
2475 struct Client *cpos;
2480 type = ntohs (m->type);
2482 while (cpos != NULL)
2484 deliver_full = GNUNET_NO;
2485 if (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND)
2486 deliver_full = GNUNET_YES;
2489 for (tpos = 0; tpos < cpos->tcnt; tpos++)
2491 if (type != cpos->types[tpos])
2493 deliver_full = GNUNET_YES;
2497 if (GNUNET_YES == deliver_full)
2498 send_p2p_message_to_client (sender, cpos, m, msize);
2499 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2500 send_p2p_message_to_client (sender, cpos, m,
2501 sizeof (struct GNUNET_MessageHeader));
2508 * Align P2P message and then deliver to interested clients.
2510 * @param sender who sent us the message?
2511 * @param buffer unaligned (!) buffer containing message
2512 * @param msize size of the message (including header)
2515 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
2519 /* TODO: call to statistics? */
2520 memcpy (abuf, buffer, msize);
2521 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
2526 * Deliver P2P messages to interested clients.
2528 * @param sender who sent us the message?
2529 * @param buffer buffer containing messages, can be modified
2530 * @param buffer_size size of the buffer (overall)
2531 * @param offset offset where messages in the buffer start
2534 deliver_messages (struct Neighbour *sender,
2535 const char *buffer, size_t buffer_size, size_t offset)
2537 struct GNUNET_MessageHeader *mhp;
2538 struct GNUNET_MessageHeader mh;
2542 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
2544 if (0 != offset % sizeof (uint16_t))
2546 /* outch, need to copy to access header */
2547 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
2552 /* can access header directly */
2553 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
2555 msize = ntohs (mhp->size);
2556 if (msize + offset > buffer_size)
2558 /* malformed message, header says it is larger than what
2559 would fit into the overall buffer */
2560 GNUNET_break_op (0);
2563 #if HAVE_UNALIGNED_64_ACCESS
2564 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
2566 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
2568 if (GNUNET_YES == need_align)
2569 align_and_deliver (sender, &buffer[offset], msize);
2571 deliver_message (sender,
2572 (const struct GNUNET_MessageHeader *)
2573 &buffer[offset], msize);
2580 * We received an encrypted message. Decrypt, validate and
2581 * pass on to the appropriate clients.
2584 handle_encrypted_message (struct Neighbour *n,
2585 const struct EncryptedMessage *m)
2587 size_t size = ntohs (m->header.size);
2589 struct EncryptedMessage *pt; /* plaintext */
2593 struct GNUNET_TIME_Absolute t;
2596 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2597 "Core service receives `%s' request from `%4s'.\n",
2598 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
2604 &m->sequence_number,
2605 &buf[ENCRYPTED_HEADER_SIZE], size - ENCRYPTED_HEADER_SIZE))
2607 pt = (struct EncryptedMessage *) buf;
2610 GNUNET_CRYPTO_hash (&pt->sequence_number,
2611 size - ENCRYPTED_HEADER_SIZE, &ph);
2612 if (0 != memcmp (&ph, &m->plaintext_hash, sizeof (GNUNET_HashCode)))
2614 /* checksum failed */
2615 GNUNET_break_op (0);
2619 /* validate sequence number */
2620 snum = ntohl (pt->sequence_number);
2621 if (n->last_sequence_number_received == snum)
2623 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2624 "Received duplicate message, ignoring.\n");
2625 /* duplicate, ignore */
2628 if ((n->last_sequence_number_received > snum) &&
2629 (n->last_sequence_number_received - snum > 32))
2631 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2632 "Received ancient out of sequence message, ignoring.\n");
2633 /* ancient out of sequence, ignore */
2636 if (n->last_sequence_number_received > snum)
2638 unsigned int rotbit =
2639 1 << (n->last_sequence_number_received - snum - 1);
2640 if ((n->last_packets_bitmap & rotbit) != 0)
2642 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2643 "Received duplicate message, ignoring.\n");
2644 /* duplicate, ignore */
2647 n->last_packets_bitmap |= rotbit;
2649 if (n->last_sequence_number_received < snum)
2651 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
2652 n->last_sequence_number_received = snum;
2655 /* check timestamp */
2656 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
2657 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
2659 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2661 ("Message received far too old (%llu ms). Content ignored.\n"),
2662 GNUNET_TIME_absolute_get_duration (t).value);
2666 /* process decrypted message(s) */
2667 n->bpm_out_external_limit = ntohl (pt->inbound_bpm_limit);
2668 n->bpm_out = GNUNET_MAX (n->bpm_out_external_limit,
2669 n->bpm_out_internal_limit);
2670 n->last_activity = GNUNET_TIME_absolute_get ();
2671 off = sizeof (struct EncryptedMessage);
2672 deliver_messages (n, buf, size, off);
2677 * Function called by the transport for each received message.
2679 * @param cls closure
2680 * @param latency estimated latency for communicating with the
2682 * @param peer (claimed) identity of the other peer
2683 * @param message the message
2686 handle_transport_receive (void *cls,
2687 struct GNUNET_TIME_Relative latency,
2688 const struct GNUNET_PeerIdentity *peer,
2689 const struct GNUNET_MessageHeader *message)
2691 struct Neighbour *n;
2692 struct GNUNET_TIME_Absolute now;
2698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2699 "Received message of type %u from `%4s', demultiplexing.\n",
2700 ntohs (message->type), GNUNET_i2s (peer));
2702 n = find_neighbour (peer);
2708 n->last_latency = latency;
2709 up = n->status == PEER_STATE_KEY_CONFIRMED;
2710 type = ntohs (message->type);
2711 size = ntohs (message->size);
2714 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
2715 if (size != sizeof (struct SetKeyMessage))
2717 GNUNET_break_op (0);
2720 handle_set_key (n, (const struct SetKeyMessage *) message);
2722 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
2723 if (size < sizeof (struct EncryptedMessage) +
2724 sizeof (struct GNUNET_MessageHeader))
2726 GNUNET_break_op (0);
2729 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2730 (n->status != PEER_STATE_KEY_CONFIRMED))
2732 GNUNET_break_op (0);
2735 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
2737 case GNUNET_MESSAGE_TYPE_CORE_PING:
2738 if (size != sizeof (struct PingMessage))
2740 GNUNET_break_op (0);
2743 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2744 (n->status != PEER_STATE_KEY_CONFIRMED))
2747 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2748 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
2749 "PING", GNUNET_i2s (&n->peer));
2751 GNUNET_free_non_null (n->pending_ping);
2752 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
2753 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
2756 handle_ping (n, (const struct PingMessage *) message);
2758 case GNUNET_MESSAGE_TYPE_CORE_PONG:
2759 if (size != sizeof (struct PingMessage))
2761 GNUNET_break_op (0);
2764 if ((n->status != PEER_STATE_KEY_SENT) &&
2765 (n->status != PEER_STATE_KEY_RECEIVED) &&
2766 (n->status != PEER_STATE_KEY_CONFIRMED))
2768 /* could not decrypt pong, oops! */
2769 GNUNET_break_op (0);
2772 handle_pong (n, (const struct PingMessage *) message);
2775 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2776 _("Unsupported message of type %u received.\n"), type);
2779 if (n->status == PEER_STATE_KEY_CONFIRMED)
2781 now = GNUNET_TIME_absolute_get ();
2782 n->last_activity = now;
2784 n->time_established = now;
2790 * Function called by transport to notify us that
2791 * a peer connected to us (on the network level).
2793 * @param cls closure
2794 * @param peer the peer that connected
2795 * @param latency current latency of the connection
2798 handle_transport_notify_connect (void *cls,
2799 const struct GNUNET_PeerIdentity *peer,
2800 struct GNUNET_TIME_Relative latency)
2802 struct Neighbour *n;
2803 struct GNUNET_TIME_Absolute now;
2804 struct ConnectNotifyMessage cnm;
2806 n = find_neighbour (peer);
2809 /* duplicate connect notification!? */
2813 now = GNUNET_TIME_absolute_get ();
2814 n = GNUNET_malloc (sizeof (struct Neighbour));
2815 n->next = neighbours;
2818 n->last_latency = latency;
2819 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2820 n->encrypt_key_created = now;
2821 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2822 n->last_asw_update = now;
2823 n->last_arw_update = now;
2824 n->bpm_in = DEFAULT_BPM_IN_OUT;
2825 n->bpm_out = DEFAULT_BPM_IN_OUT;
2826 n->bpm_out_internal_limit = (uint32_t) - 1;
2827 n->bpm_out_external_limit = DEFAULT_BPM_IN_OUT;
2828 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2831 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2832 "Received connection from `%4s'.\n",
2833 GNUNET_i2s (&n->peer));
2835 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2836 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2837 cnm.bpm_available = htonl (DEFAULT_BPM_IN_OUT);
2839 cnm.last_activity = GNUNET_TIME_absolute_hton (now);
2840 send_to_all_clients (&cnm.header, GNUNET_YES);
2845 * Free the given entry for the neighbour (it has
2846 * already been removed from the list at this point).
2847 * @param n neighbour to free
2850 free_neighbour (struct Neighbour *n)
2852 struct MessageEntry *m;
2854 while (NULL != (m = n->messages))
2856 n->messages = m->next;
2859 while (NULL != (m = n->encrypted_head))
2861 n->encrypted_head = m->next;
2865 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
2866 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
2867 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
2868 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
2869 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2870 GNUNET_free_non_null (n->public_key);
2871 GNUNET_free_non_null (n->pending_ping);
2877 * Function called by transport telling us that a peer
2880 * @param cls closure
2881 * @param peer the peer that disconnected
2884 handle_transport_notify_disconnect (void *cls,
2885 const struct GNUNET_PeerIdentity *peer)
2887 struct ConnectNotifyMessage cnm;
2888 struct Neighbour *n;
2889 struct Neighbour *p;
2892 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2893 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
2897 while ((n != NULL) &&
2898 (0 != memcmp (&n->peer, peer, sizeof (struct GNUNET_PeerIdentity))))
2909 neighbours = n->next;
2912 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2913 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
2914 cnm.bpm_available = htonl (0);
2916 cnm.last_activity = GNUNET_TIME_absolute_hton (n->last_activity);
2917 send_to_all_clients (&cnm.header, GNUNET_YES);
2923 * Last task run during shutdown. Disconnects us from
2927 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2929 struct Neighbour *n;
2933 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2934 "Core service shutting down.\n");
2936 GNUNET_assert (transport != NULL);
2937 GNUNET_TRANSPORT_disconnect (transport);
2939 while (NULL != (n = neighbours))
2941 neighbours = n->next;
2944 while (NULL != (c = clients))
2945 handle_client_disconnect (NULL, c->client_handle);
2950 * Initiate core service.
2952 * @param cls closure
2953 * @param s scheduler to use
2954 * @param serv the initialized server
2955 * @param c configuration to use
2959 struct GNUNET_SCHEDULER_Handle *s,
2960 struct GNUNET_SERVER_Handle *serv, struct GNUNET_CONFIGURATION_Handle *c)
2963 unsigned long long qin;
2964 unsigned long long qout;
2965 unsigned long long tneigh;
2971 /* parse configuration */
2975 GNUNET_CONFIGURATION_get_value_number (c,
2980 GNUNET_CONFIGURATION_get_value_number (c,
2985 GNUNET_CONFIGURATION_get_value_number (c,
2987 "ZZ_LIMIT", &tneigh)) ||
2990 GNUNET_CONFIGURATION_get_value_filename (c,
2992 "HOSTKEY", &keyfile)))
2994 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2996 ("Core service is lacking key configuration settings. Exiting.\n"));
2997 GNUNET_SCHEDULER_shutdown (s);
3000 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3001 GNUNET_free (keyfile);
3002 if (my_private_key == NULL)
3004 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3005 _("Core service could not access hostkey. Exiting.\n"));
3006 GNUNET_SCHEDULER_shutdown (s);
3009 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3010 GNUNET_CRYPTO_hash (&my_public_key,
3011 sizeof (my_public_key), &my_identity.hashPubKey);
3012 /* setup notification */
3014 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3015 /* setup transport connection */
3016 transport = GNUNET_TRANSPORT_connect (sched,
3019 &handle_transport_receive,
3020 &handle_transport_notify_connect,
3021 &handle_transport_notify_disconnect);
3022 GNUNET_assert (NULL != transport);
3023 GNUNET_SCHEDULER_add_delayed (sched,
3025 GNUNET_SCHEDULER_PRIORITY_IDLE,
3026 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
3027 GNUNET_TIME_UNIT_FOREVER_REL,
3028 &cleaning_task, NULL);
3029 /* process client requests */
3030 GNUNET_SERVER_add_handlers (server, handlers);
3031 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3032 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
3037 * Function called during shutdown. Clean up our state.
3040 cleanup (void *cls, struct GNUNET_CONFIGURATION_Handle *cfg)
3044 if (my_private_key != NULL)
3045 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3050 * The main function for the transport service.
3052 * @param argc number of arguments from the command line
3053 * @param argv command line arguments
3054 * @return 0 ok, 1 on error
3057 main (int argc, char *const *argv)
3059 return (GNUNET_OK ==
3060 GNUNET_SERVICE_run (argc,
3062 "core", &run, NULL, &cleanup, NULL)) ? 0 : 1;
3065 /* end of gnunet-service-core.c */