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
28 * - write test for basic core functions:
30 * + transmit (encrypted) message [with handshake]
31 * + receive (encrypted) message, forward plaintext to clients
33 * - revisit API (which arguments are used, needed)?
34 * - add code to bound queue size when handling client's SEND message
35 * - add code to bound message queue size when passing messages to clients
36 * - add code to discard_expired_messages
37 * - add code to re-transmit key if first attempt failed
38 * + timeout on connect / key exchange, etc.
39 * + timeout for automatic re-try, etc.
40 * - add code to give up re-transmission of key if many attempts fail
41 * - add code to send PINGs if we are about to time-out otherwise
42 * ? add heuristic to do another send_key in "handle_set_key"
43 * in case previous attempt failed / didn't work / persist
44 * (but don't do it always to avoid storm of SET_KEY's going
45 * back and forth!) --- alternatively, add "status" field
46 * of the other peer to the set key message, that way we'd
48 * - check that hostkey used by transport (for HELLOs) is the
49 * same as the hostkey that we are using!
50 * - free list of clients on exit
51 * - topology management:
52 * + bootstrapping (transport offer hello, plugins)
53 * + internal neighbour selection
54 * + update bandwidth usage statistics
55 * + bandwidth allocation (transport set quota)
56 * - optimize lookup (many O(n) list traversals
57 * could ideally be changed to O(1) hash map lookups)
60 #include "gnunet_util_lib.h"
61 #include "gnunet_hello_lib.h"
62 #include "gnunet_peerinfo_service.h"
63 #include "gnunet_protocols.h"
64 #include "gnunet_signatures.h"
65 #include "gnunet_transport_service.h"
70 * Receive and send buffer windows grow over time. For
71 * how long can 'unused' bandwidth accumulate before we
72 * need to cap it? (specified in ms).
74 #define MAX_WINDOW_TIME (5 * 60 * 1000)
78 * Amount of bytes per minute (in/out) to assume initially
79 * (before either peer has communicated any particular
80 * preference). Should be rather low.
82 #define DEFAULT_BPM_IN_OUT 2048
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 * What is the maximum age of a message for us to consider
129 * processing it? Note that this looks at the timestamp used
130 * by the other peer, so clock skew between machines does
131 * come into play here. So this should be picked high enough
132 * so that a little bit of clock skew does not prevent peers
133 * from connecting to us.
135 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
139 * What is the maximum size for encrypted messages? Note that this
140 * number imposes a clear limit on the maximum size of any message.
141 * Set to a value close to 64k but not so close that transports will
142 * have trouble with their headers.
144 #define MAX_ENCRYPTED_MESSAGE_SIZE (63 * 1024)
148 * State machine for our P2P encryption handshake. Everyone starts in
149 * "DOWN", if we receive the other peer's key (other peer initiated)
150 * we start in state RECEIVED (since we will immediately send our
151 * own); otherwise we start in SENT. If we get back a PONG from
152 * within either state, we move up to CONFIRMED (the PONG will always
153 * be sent back encrypted with the key we sent to the other peer).
155 enum PeerStateMachine
159 PEER_STATE_KEY_RECEIVED,
160 PEER_STATE_KEY_CONFIRMED
165 * Number of bytes (at the beginning) of "struct EncryptedMessage"
166 * that are NOT encrypted.
168 #define ENCRYPTED_HEADER_SIZE (sizeof(struct GNUNET_MessageHeader) + sizeof(uint32_t) + sizeof(GNUNET_HashCode))
171 * Encapsulation for encrypted messages exchanged between
172 * peers. Followed by the actual encrypted data.
174 struct EncryptedMessage
177 * Message type is either CORE_ENCRYPTED_MESSAGE.
179 struct GNUNET_MessageHeader header;
184 uint32_t reserved GNUNET_PACKED;
187 * Hash of the plaintext, used to verify message integrity;
188 * ALSO used as the IV for the symmetric cipher! Everything
189 * after this hash will be encrypted. ENCRYPTED_HEADER_SIZE
190 * must be set to the offset of the next field.
192 GNUNET_HashCode plaintext_hash;
195 * Sequence number, in network byte order. This field
196 * must be the first encrypted/decrypted field and the
197 * first byte that is hashed for the plaintext hash.
199 uint32_t sequence_number GNUNET_PACKED;
202 * Desired bandwidth (how much we should send to this
203 * peer / how much is the sender willing to receive),
204 * in bytes per minute.
206 uint32_t inbound_bpm_limit GNUNET_PACKED;
209 * Timestamp. Used to prevent reply of ancient messages
210 * (recent messages are caught with the sequence number).
212 struct GNUNET_TIME_AbsoluteNBO timestamp;
217 * We're sending an (encrypted) PING to the other peer to check if he
218 * can decrypt. The other peer should respond with a PONG with the
219 * same content, except this time encrypted with the receiver's key.
224 * Message type is either CORE_PING or CORE_PONG.
226 struct GNUNET_MessageHeader header;
229 * Random number chosen to make reply harder.
231 uint32_t challenge GNUNET_PACKED;
234 * Intended target of the PING, used primarily to check
235 * that decryption actually worked.
237 struct GNUNET_PeerIdentity target;
242 * Message transmitted to set (or update) a session key.
248 * Message type is either CORE_SET_KEY.
250 struct GNUNET_MessageHeader header;
253 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
255 int32_t sender_status GNUNET_PACKED;
258 * Purpose of the signature, will be
259 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
261 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
264 * At what time was this key created?
266 struct GNUNET_TIME_AbsoluteNBO creation_time;
269 * The encrypted session key.
271 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
274 * Who is the intended recipient?
276 struct GNUNET_PeerIdentity target;
279 * Signature of the stuff above (starting at purpose).
281 struct GNUNET_CRYPTO_RsaSignature signature;
287 * Message waiting for transmission. This struct
288 * is followed by the actual content of the message.
294 * We keep messages in a linked list (for now).
296 struct MessageEntry *next;
299 * By when are we supposed to transmit this message?
301 struct GNUNET_TIME_Absolute deadline;
304 * How important is this message to us?
306 unsigned int priority;
309 * How long is the message? (number of bytes following
310 * the "struct MessageEntry", but not including the
311 * size of "struct MessageEntry" itself!)
316 * Was this message selected for transmission in the
317 * current round? GNUNET_YES or GNUNET_NO.
327 * We keep neighbours in a linked list (for now).
329 struct Neighbour *next;
332 * Unencrypted messages destined for this peer.
334 struct MessageEntry *messages;
337 * Head of the batched, encrypted message queue (already ordered,
338 * transmit starting with the head).
340 struct MessageEntry *encrypted_head;
343 * Tail of the batched, encrypted message queue (already ordered,
344 * append new messages to tail)
346 struct MessageEntry *encrypted_tail;
349 * Handle for pending requests for transmission to this peer
350 * with the transport service. NULL if no request is pending.
352 struct GNUNET_TRANSPORT_TransmitHandle *th;
355 * Public key of the neighbour, NULL if we don't have it yet.
357 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
360 * We received a PING message before we got the "public_key"
361 * (or the SET_KEY). We keep it here until we have a key
362 * to decrypt it. NULL if no PING is pending.
364 struct PingMessage *pending_ping;
367 * Identity of the neighbour.
369 struct GNUNET_PeerIdentity peer;
372 * Key we use to encrypt our messages for the other peer
373 * (initialized by us when we do the handshake).
375 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
378 * Key we use to decrypt messages from the other peer
379 * (given to us by the other peer during the handshake).
381 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
384 * ID of task used for re-trying plaintext scheduling.
386 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
389 * ID of task used for re-trying SET_KEY and PING message.
391 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
394 * At what time did we generate our encryption key?
396 struct GNUNET_TIME_Absolute encrypt_key_created;
399 * At what time did the other peer generate the decryption key?
401 struct GNUNET_TIME_Absolute decrypt_key_created;
404 * At what time did we initially establish (as in, complete session
405 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
407 struct GNUNET_TIME_Absolute time_established;
410 * At what time did we last receive an encrypted message from the
411 * other peer? Should be zero if status != KEY_CONFIRMED.
413 struct GNUNET_TIME_Absolute last_activity;
416 * Last latency observed from this peer.
418 struct GNUNET_TIME_Relative last_latency;
421 * At what frequency are we currently re-trying SET KEY messages?
423 struct GNUNET_TIME_Relative set_key_retry_frequency;
426 * Time of our last update to the "available_send_window".
428 struct GNUNET_TIME_Absolute last_asw_update;
431 * Time of our last update to the "available_recv_window".
433 struct GNUNET_TIME_Absolute last_arw_update;
436 * Number of bytes that we are eligible to transmit to this
437 * peer at this point. Incremented every minute by max_out_bpm,
438 * bounded by max_bpm (no back-log larger than MAX_BUF_FACT minutes,
439 * bandwidth-hogs are sampled at a frequency of about 78s!);
440 * may get negative if we have VERY high priority content.
442 long long available_send_window;
445 * How much downstream capacity of this peer has been reserved for
446 * our traffic? (Our clients can request that a certain amount of
447 * bandwidth is available for replies to them; this value is used to
448 * make sure that this reserved amount of bandwidth is actually
451 long long available_recv_window;
454 * How valueable were the messages of this peer recently?
456 double current_preference;
459 * Bit map indicating which of the 32 sequence numbers before the last
460 * were received (good for accepting out-of-order packets and
461 * estimating reliability of the connection)
463 unsigned int last_packets_bitmap;
466 * Number of messages in the message queue for this peer.
468 unsigned int message_queue_size;
471 * last sequence number received on this connection (highest)
473 uint32_t last_sequence_number_received;
476 * last sequence number transmitted
478 uint32_t last_sequence_number_sent;
481 * Available bandwidth in for this peer (current target).
486 * Available bandwidth out for this peer (current target).
491 * Internal bandwidth limit set for this peer (initially
492 * typcially set to "-1"). "bpm_out" is MAX of
493 * "bpm_out_internal_limit" and "bpm_out_external_limit".
495 uint32_t bpm_out_internal_limit;
498 * External bandwidth limit set for this peer by the
499 * peer that we are communicating with. "bpm_out" is MAX of
500 * "bpm_out_internal_limit" and "bpm_out_external_limit".
502 uint32_t bpm_out_external_limit;
505 * What was our PING challenge number?
507 uint32_t ping_challenge;
510 * What is our connection status?
512 enum PeerStateMachine status;
518 * Events are messages for clients. The struct
519 * itself is followed by the actual message.
524 * This is a linked list.
529 * Size of the message.
534 * Could this event be dropped if this queue
535 * is getting too large? (NOT YET USED!)
543 * Data structure for each client connected to the core service.
548 * Clients are kept in a linked list.
553 * Handle for the client with the server API.
555 struct GNUNET_SERVER_Client *client_handle;
558 * Linked list of messages we still need to deliver to
561 struct Event *event_head;
564 * Tail of the linked list of events.
566 struct Event *event_tail;
569 * Current transmit handle, NULL if no transmission request
572 struct GNUNET_NETWORK_TransmitHandle *th;
575 * Array of the types of messages this peer cares
576 * about (with "tcnt" entries). Allocated as part
577 * of this client struct, do not free!
582 * Options for messages this client cares about,
583 * see GNUNET_CORE_OPTION_ values.
588 * Number of types of incoming messages this client
589 * specifically cares about. Size of the "types" array.
599 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
604 static struct GNUNET_PeerIdentity my_identity;
609 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
614 struct GNUNET_SCHEDULER_Handle *sched;
619 struct GNUNET_CONFIGURATION_Handle *cfg;
624 static struct GNUNET_SERVER_Handle *server;
629 static struct GNUNET_TRANSPORT_Handle *transport;
632 * We keep neighbours in a linked list (for now).
634 static struct Neighbour *neighbours;
637 * Linked list of our clients.
639 static struct Client *clients;
643 * Recalculate the number of bytes we expect to
644 * receive or transmit in a given window.
646 * @param window pointer to the byte counter (updated)
647 * @param ts pointer to the timestamp (updated)
648 * @param bpm number of bytes per minute that should
649 * be added to the window.
652 update_window (long long *window,
653 struct GNUNET_TIME_Absolute *ts, unsigned int bpm)
655 struct GNUNET_TIME_Relative since;
657 since = GNUNET_TIME_absolute_get_duration (*ts);
658 if (since.value < 60 * 1000)
659 return; /* not even a minute has passed */
660 *ts = GNUNET_TIME_absolute_get ();
661 *window += (bpm * since.value) / 60 / 1000;
662 if (*window > MAX_WINDOW_TIME * bpm)
663 *window = MAX_WINDOW_TIME * bpm;
668 * Find the entry for the given neighbour.
670 * @param peer identity of the neighbour
671 * @return NULL if we are not connected, otherwise the
674 static struct Neighbour *
675 find_neighbour (const struct GNUNET_PeerIdentity *peer)
677 struct Neighbour *ret;
680 while ((ret != NULL) &&
681 (0 != memcmp (&ret->peer,
682 peer, sizeof (struct GNUNET_PeerIdentity))))
689 * Find the entry for the given client.
691 * @param client handle for the client
692 * @return NULL if we are not connected, otherwise the
695 static struct Client *
696 find_client (const struct GNUNET_SERVER_Client *client)
701 while ((ret != NULL) && (client != ret->client_handle))
708 * If necessary, initiate a request with the server to
709 * transmit messages from the queue of the given client.
710 * @param client who to transfer messages to
712 static void request_transmit (struct Client *client);
716 * Client is ready to receive data, provide it.
718 * @param size number of bytes available in buf
719 * @param buf where the callee should write the message
720 * @return number of bytes written to buf
723 do_client_transmit (void *cls, size_t size, void *buf)
725 struct Client *client = cls;
731 #if DEBUG_CORE_CLIENT
732 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
733 "Client ready to receive %u bytes.\n", size);
738 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
739 "Failed to transmit data to client (disconnect)?\n");
741 return 0; /* we'll surely get a disconnect soon... */
745 while ((NULL != (e = client->event_head)) && (e->size <= size))
747 memcpy (&tgt[ret], &e[1], e->size);
750 client->event_head = e->next;
753 GNUNET_assert (ret > 0);
754 if (client->event_head == NULL)
755 client->event_tail = NULL;
756 #if DEBUG_CORE_CLIENT
757 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
758 "Transmitting %u bytes to client\n", ret);
760 request_transmit (client);
766 * If necessary, initiate a request with the server to
767 * transmit messages from the queue of the given client.
768 * @param client who to transfer messages to
771 request_transmit (struct Client *client)
774 if (NULL != client->th)
775 return; /* already pending */
776 if (NULL == client->event_head)
777 return; /* no more events pending */
778 #if DEBUG_CORE_CLIENT
779 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
780 "Asking server to transmit %u bytes to client\n",
781 client->event_head->size);
784 = GNUNET_SERVER_notify_transmit_ready (client->client_handle,
785 client->event_head->size,
786 GNUNET_TIME_UNIT_FOREVER_REL,
787 &do_client_transmit, client);
792 * Send a message to one of our clients.
793 * @param client target for the message
794 * @param msg message to transmit
795 * @param can_drop could this message be dropped if the
796 * client's queue is getting too large?
799 send_to_client (struct Client *client,
800 const struct GNUNET_MessageHeader *msg, int can_drop)
805 #if DEBUG_CORE_CLIENT
806 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
807 "Preparing to send message of type %u to client.\n",
810 msize = ntohs (msg->size);
811 e = GNUNET_malloc (sizeof (struct Event) + msize);
813 if (client->event_tail != NULL)
814 client->event_tail->next = e;
816 client->event_head = e;
817 client->event_tail = e;
818 e->can_drop = can_drop;
820 memcpy (&e[1], msg, msize);
821 request_transmit (client);
826 * Send a message to all of our current clients.
829 send_to_all_clients (const struct GNUNET_MessageHeader *msg, int can_drop)
836 send_to_client (c, msg, can_drop);
843 * Handle CORE_INIT request.
846 handle_client_init (void *cls,
847 struct GNUNET_SERVER_Client *client,
848 const struct GNUNET_MessageHeader *message)
850 const struct InitMessage *im;
851 struct InitReplyMessage irm;
854 const uint16_t *types;
856 struct ConnectNotifyMessage cnm;
858 #if DEBUG_CORE_CLIENT
859 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
860 "Client connecting to core service with `%s' message\n",
863 /* check that we don't have an entry already */
867 if (client == c->client_handle)
870 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
875 msize = ntohs (message->size);
876 if (msize < sizeof (struct InitMessage))
879 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
882 im = (const struct InitMessage *) message;
883 types = (const uint16_t *) &im[1];
884 msize -= sizeof (struct InitMessage);
885 c = GNUNET_malloc (sizeof (struct Client) + msize);
886 c->client_handle = client;
889 memcpy (&c[1], types, msize);
890 c->types = (uint16_t *) & c[1];
891 c->options = ntohl (im->options);
892 c->tcnt = msize / sizeof (uint16_t);
893 /* send init reply message */
894 irm.header.size = htons (sizeof (struct InitReplyMessage));
895 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
896 irm.reserved = htonl (0);
897 memcpy (&irm.publicKey,
899 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
900 #if DEBUG_CORE_CLIENT
901 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
902 "Sending `%s' message to client.\n", "INIT_REPLY");
904 send_to_client (c, &irm.header, GNUNET_NO);
905 /* notify new client about existing neighbours */
906 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
907 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
911 #if DEBUG_CORE_CLIENT
912 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
913 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
915 cnm.bpm_available = htonl (n->bpm_out);
916 cnm.last_activity = GNUNET_TIME_absolute_hton (n->last_activity);
918 send_to_client (c, &cnm.header, GNUNET_NO);
921 GNUNET_SERVER_receive_done (client, GNUNET_OK);
926 * A client disconnected, clean up.
929 * @param client identification of the client
932 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
937 #if DEBUG_CORE_CLIENT
938 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
939 "Client has disconnected from core service.\n");
945 if (client == pos->client_handle)
950 prev->next = pos->next;
952 GNUNET_NETWORK_notify_transmit_ready_cancel (pos->th);
959 /* client never sent INIT */
964 * Handle REQUEST_CONFIGURE request.
967 handle_client_request_configure (void *cls,
968 struct GNUNET_SERVER_Client *client,
969 const struct GNUNET_MessageHeader *message)
971 const struct RequestConfigureMessage *rcm;
973 struct ConfigurationInfoMessage cim;
977 #if DEBUG_CORE_CLIENT
978 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
979 "Core service receives `%s' request.\n", "CONFIGURE");
981 rcm = (const struct RequestConfigureMessage *) message;
982 n = find_neighbour (&rcm->peer);
983 memset (&cim, 0, sizeof (cim));
984 if ((n != NULL) && (n->status == PEER_STATE_KEY_CONFIRMED))
986 n->bpm_out_internal_limit = ntohl (rcm->limit_outbound_bpm);
987 n->bpm_out = GNUNET_MAX (n->bpm_out_internal_limit,
988 n->bpm_out_external_limit);
989 reserv = ntohl (rcm->reserve_inbound);
992 n->available_recv_window += reserv;
996 update_window (&n->available_recv_window,
997 &n->last_arw_update, n->bpm_in);
998 if (n->available_recv_window < reserv)
999 reserv = n->available_recv_window;
1000 n->available_recv_window -= reserv;
1002 n->current_preference += rcm->preference_change;
1003 if (n->current_preference < 0)
1004 n->current_preference = 0;
1005 cim.reserved_amount = htonl (reserv);
1006 cim.bpm_in = htonl (n->bpm_in);
1007 cim.bpm_out = htonl (n->bpm_out);
1008 cim.latency = GNUNET_TIME_relative_hton (n->last_latency);
1009 cim.preference = n->current_preference;
1011 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1012 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1013 cim.peer = rcm->peer;
1014 c = find_client (client);
1020 #if DEBUG_CORE_CLIENT
1021 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1022 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1024 send_to_client (c, &cim.header, GNUNET_NO);
1029 * Check if we have encrypted messages for the specified neighbour
1030 * pending, and if so, check with the transport about sending them
1033 * @param n neighbour to check.
1035 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1039 * Function called when the transport service is ready to
1040 * receive an encrypted message for the respective peer
1042 * @param cls neighbour to use message from
1043 * @param size number of bytes we can transmit
1044 * @param buf where to copy the message
1045 * @return number of bytes transmitted
1048 notify_encrypted_transmit_ready (void *cls, size_t size, void *buf)
1050 struct Neighbour *n = cls;
1051 struct MessageEntry *m;
1056 GNUNET_assert (NULL != (m = n->encrypted_head));
1057 n->encrypted_head = m->next;
1058 if (m->next == NULL)
1059 n->encrypted_tail = NULL;
1064 GNUNET_assert (size >= m->size);
1065 memcpy (cbuf, &m[1], m->size);
1067 process_encrypted_neighbour_queue (n);
1068 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1069 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1070 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1071 ret, GNUNET_i2s (&n->peer));
1075 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1076 "Transmission for message of type %u and size %u failed\n",
1077 ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1086 * Check if we have plaintext messages for the specified neighbour
1087 * pending, and if so, consider batching and encrypting them (and
1088 * then trigger processing of the encrypted queue if needed).
1090 * @param n neighbour to check.
1092 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1096 * Check if we have encrypted messages for the specified neighbour
1097 * pending, and if so, check with the transport about sending them
1100 * @param n neighbour to check.
1103 process_encrypted_neighbour_queue (struct Neighbour *n)
1106 return; /* request already pending */
1107 if (n->encrypted_head == NULL)
1109 /* encrypted queue empty, try plaintext instead */
1110 process_plaintext_neighbour_queue (n);
1113 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1114 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1115 n->encrypted_head->size,
1116 GNUNET_i2s (&n->peer),
1117 GNUNET_TIME_absolute_get_remaining (n->
1118 encrypted_head->deadline).
1121 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1122 n->encrypted_head->size,
1123 GNUNET_TIME_absolute_get_remaining
1124 (n->encrypted_head->deadline),
1125 ¬ify_encrypted_transmit_ready,
1129 /* message request too large (oops) */
1131 /* FIXME: handle error somehow! */
1137 * Decrypt size bytes from in and write the result to out. Use the
1138 * key for inbound traffic of the given neighbour. This function does
1139 * NOT do any integrity-checks on the result.
1141 * @param n neighbour we are receiving from
1142 * @param iv initialization vector to use
1143 * @param in ciphertext
1144 * @param out plaintext
1145 * @param size size of in/out
1146 * @return GNUNET_OK on success
1149 do_decrypt (struct Neighbour *n,
1150 const GNUNET_HashCode * iv,
1151 const void *in, void *out, size_t size)
1153 if (size != (uint16_t) size)
1158 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
1159 (n->status != PEER_STATE_KEY_CONFIRMED))
1161 GNUNET_break_op (0);
1162 return GNUNET_SYSERR;
1165 GNUNET_CRYPTO_aes_decrypt (&n->decrypt_key,
1169 GNUNET_CRYPTO_AesInitializationVector *) iv,
1173 return GNUNET_SYSERR;
1175 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1176 "Decrypted %u bytes from `%4s' using key %u\n",
1177 size, GNUNET_i2s (&n->peer), n->decrypt_key.crc32);
1183 * Encrypt size bytes from in and write the result to out. Use the
1184 * key for outbound traffic of the given neighbour.
1186 * @param n neighbour we are sending to
1187 * @param iv initialization vector to use
1188 * @param in ciphertext
1189 * @param out plaintext
1190 * @param size size of in/out
1191 * @return GNUNET_OK on success
1194 do_encrypt (struct Neighbour *n,
1195 const GNUNET_HashCode * iv,
1196 const void *in, void *out, size_t size)
1198 if (size != (uint16_t) size)
1203 GNUNET_assert (size ==
1204 GNUNET_CRYPTO_aes_encrypt (in,
1208 GNUNET_CRYPTO_AesInitializationVector
1210 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1211 "Encrypted %u bytes for `%4s' using key %u\n", size,
1212 GNUNET_i2s (&n->peer), n->encrypt_key.crc32);
1218 * Select messages for transmission. This heuristic uses a combination
1219 * of earliest deadline first (EDF) scheduling (with bounded horizon)
1220 * and priority-based discard (in case no feasible schedule exist) and
1221 * speculative optimization (defer any kind of transmission until
1222 * we either create a batch of significant size, 25% of max, or until
1223 * we are close to a deadline). Furthermore, when scheduling the
1224 * heuristic also packs as many messages into the batch as possible,
1225 * starting with those with the earliest deadline. Yes, this is fun.
1227 * @param n neighbour to select messages from
1228 * @param size number of bytes to select for transmission
1229 * @param retry_time set to the time when we should try again
1230 * (only valid if this function returns zero)
1231 * @return number of bytes selected, or 0 if we decided to
1232 * defer scheduling overall; in that case, retry_time is set.
1235 select_messages (struct Neighbour *n,
1236 size_t size, struct GNUNET_TIME_Relative *retry_time)
1238 struct MessageEntry *pos;
1239 struct MessageEntry *min;
1240 struct MessageEntry *last;
1241 unsigned int min_prio;
1242 struct GNUNET_TIME_Absolute t;
1243 struct GNUNET_TIME_Absolute now;
1246 unsigned long long slack; /* how long could we wait before missing deadlines? */
1248 int discard_low_prio;
1250 GNUNET_assert (NULL != n->messages);
1251 now = GNUNET_TIME_absolute_get ();
1252 /* last entry in linked list of messages processed */
1254 /* should we remove the entry with the lowest
1255 priority from consideration for scheduling at the
1257 discard_low_prio = GNUNET_YES;
1258 while (GNUNET_YES == discard_low_prio)
1262 discard_low_prio = GNUNET_NO;
1263 /* number of bytes available for transmission at time "t" */
1264 avail = n->available_send_window;
1265 t = n->last_asw_update;
1266 /* how many bytes have we (hyptothetically) scheduled so far */
1268 /* maximum time we can wait before transmitting anything
1269 and still make all of our deadlines */
1273 /* note that we use "*2" here because we want to look
1274 a bit further into the future; much more makes no
1275 sense since new message might be scheduled in the
1277 while ((pos != NULL) && (off < size * 2))
1279 if (pos->do_transmit == GNUNET_YES)
1281 /* already removed from consideration */
1285 if (discard_low_prio == GNUNET_NO)
1287 delta = pos->deadline.value;
1288 if (delta < t.value)
1291 delta = t.value - delta;
1292 avail += delta * n->bpm_out / 1000 / 60;
1293 if (avail < pos->size)
1295 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
1300 /* update slack, considering both its absolute deadline
1301 and relative deadlines caused by other messages
1302 with their respective load */
1303 slack = GNUNET_MIN (slack, avail / n->bpm_out);
1304 if (pos->deadline.value < now.value)
1308 GNUNET_MIN (slack, pos->deadline.value - now.value);
1312 t.value = GNUNET_MAX (pos->deadline.value, t.value);
1313 if (pos->priority <= min_prio)
1315 /* update min for discard */
1316 min_prio = pos->priority;
1321 if (discard_low_prio)
1323 GNUNET_assert (min != NULL);
1324 /* remove lowest-priority entry from consideration */
1325 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
1329 /* guard against sending "tiny" messages with large headers without
1331 if ((slack > 1000) && (size > 4 * off))
1333 /* less than 25% of message would be filled with
1334 deadlines still being met if we delay by one
1335 second or more; so just wait for more data */
1336 retry_time->value = slack / 2;
1337 /* reset do_transmit values for next time */
1340 pos->do_transmit = GNUNET_NO;
1345 /* select marked messages (up to size) for transmission */
1350 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
1352 pos->do_transmit = GNUNET_YES; /* mark for transmission */
1357 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
1360 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1361 "Selected %u bytes of plaintext messages for transmission to `%4s'.\n",
1362 off, GNUNET_i2s (&n->peer));
1368 * Batch multiple messages into a larger buffer.
1370 * @param n neighbour to take messages from
1371 * @param buf target buffer
1372 * @param size size of buf
1373 * @param deadline set to transmission deadline for the result
1374 * @param retry_time set to the time when we should try again
1375 * (only valid if this function returns zero)
1376 * @param priority set to the priority of the batch
1377 * @return number of bytes written to buf (can be zero)
1380 batch_message (struct Neighbour *n,
1383 struct GNUNET_TIME_Absolute *deadline,
1384 struct GNUNET_TIME_Relative *retry_time,
1385 unsigned int *priority)
1387 struct MessageEntry *pos;
1388 struct MessageEntry *prev;
1389 struct MessageEntry *next;
1394 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1395 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
1396 if (0 == select_messages (n, size, retry_time))
1398 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1399 "No messages selected, will try again in %llu ms\n",
1405 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
1408 if (GNUNET_YES == pos->do_transmit)
1410 GNUNET_assert (pos->size <= size);
1411 memcpy (&buf[ret], &pos[1], pos->size);
1414 *priority += pos->priority;
1415 deadline->value = GNUNET_MIN (deadline->value, pos->deadline.value);
1433 * Remove messages with deadlines that have long expired from
1436 * @param n neighbour to inspect
1439 discard_expired_messages (struct Neighbour *n)
1446 * Signature of the main function of a task.
1448 * @param cls closure
1449 * @param tc context information (why was this task triggered now)
1452 retry_plaintext_processing (void *cls,
1453 const struct GNUNET_SCHEDULER_TaskContext *tc)
1455 struct Neighbour *n = cls;
1457 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1458 process_plaintext_neighbour_queue (n);
1463 * Send our key (and encrypted PING) to the other peer.
1465 * @param n the other peer
1467 static void send_key (struct Neighbour *n);
1471 * Check if we have plaintext messages for the specified neighbour
1472 * pending, and if so, consider batching and encrypting them (and
1473 * then trigger processing of the encrypted queue if needed).
1475 * @param n neighbour to check.
1478 process_plaintext_neighbour_queue (struct Neighbour *n)
1480 char pbuf[MAX_ENCRYPTED_MESSAGE_SIZE]; /* plaintext */
1483 struct EncryptedMessage *em; /* encrypted message */
1484 struct EncryptedMessage *ph; /* plaintext header */
1485 struct MessageEntry *me;
1486 unsigned int priority;
1487 struct GNUNET_TIME_Absolute deadline;
1488 struct GNUNET_TIME_Relative retry_time;
1490 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1492 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
1493 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1497 case PEER_STATE_DOWN:
1499 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1500 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1501 GNUNET_i2s(&n->peer));
1503 case PEER_STATE_KEY_SENT:
1504 GNUNET_assert (n->retry_set_key_task !=
1505 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
1506 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1507 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1508 GNUNET_i2s(&n->peer));
1510 case PEER_STATE_KEY_RECEIVED:
1511 GNUNET_assert (n->retry_set_key_task !=
1512 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
1513 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1514 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
1515 GNUNET_i2s(&n->peer));
1517 case PEER_STATE_KEY_CONFIRMED:
1518 /* ready to continue */
1521 if (n->messages == NULL)
1523 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1524 "Plaintext message queue for `%4s' is empty.\n",
1525 GNUNET_i2s(&n->peer));
1526 return; /* no pending messages */
1528 discard_expired_messages (n);
1529 if (n->encrypted_head != NULL)
1531 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1532 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
1533 GNUNET_i2s(&n->peer));
1534 return; /* wait for messages already encrypted to be
1537 ph = (struct EncryptedMessage *) pbuf;
1538 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
1540 used = sizeof (struct EncryptedMessage);
1542 used += batch_message (n,
1544 MAX_ENCRYPTED_MESSAGE_SIZE - used,
1545 &deadline, &retry_time, &priority);
1546 if (used == sizeof (struct EncryptedMessage))
1548 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1549 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
1550 GNUNET_i2s(&n->peer));
1551 /* no messages selected for sending, try again later... */
1552 n->retry_plaintext_task =
1553 GNUNET_SCHEDULER_add_delayed (sched,
1555 GNUNET_SCHEDULER_PRIORITY_IDLE,
1556 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1558 &retry_plaintext_processing, n);
1562 ph->sequence_number = htonl (++n->last_sequence_number_sent);
1563 ph->inbound_bpm_limit = htonl (n->bpm_in);
1564 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1566 /* setup encryption message header */
1567 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
1568 me->deadline = deadline;
1569 me->priority = priority;
1571 em = (struct EncryptedMessage *) &me[1];
1572 em->header.size = htons (used);
1573 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1574 em->reserved = htonl (0);
1575 esize = used - ENCRYPTED_HEADER_SIZE;
1576 GNUNET_CRYPTO_hash (&ph->sequence_number, esize, &em->plaintext_hash);
1578 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1579 "Encrypting %u bytes of plaintext messages for `%4s' for transmission.\n",
1581 GNUNET_i2s(&n->peer));
1582 GNUNET_assert (GNUNET_OK ==
1584 &em->plaintext_hash,
1585 &ph->sequence_number,
1586 &em->sequence_number, esize));
1587 /* append to transmission list */
1588 if (n->encrypted_tail == NULL)
1589 n->encrypted_head = me;
1591 n->encrypted_tail->next = me;
1592 n->encrypted_tail = me;
1593 process_encrypted_neighbour_queue (n);
1598 * Handle CORE_SEND request.
1601 handle_client_send (void *cls,
1602 struct GNUNET_SERVER_Client *client,
1603 const struct GNUNET_MessageHeader *message);
1607 * Function called to notify us that we either succeeded
1608 * or failed to connect (at the transport level) to another
1609 * peer. We should either free the message we were asked
1610 * to transmit or re-try adding it to the queue.
1612 * @param cls closure
1613 * @param size number of bytes available in buf
1614 * @param buf where the callee should write the message
1615 * @return number of bytes written to buf
1618 send_connect_continuation (void *cls, size_t size, void *buf)
1620 struct SendMessage *sm = cls;
1624 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1625 "Asked to send message to disconnected peer `%4s' and connection failed. Discarding message.\n",
1626 GNUNET_i2s (&sm->peer));
1628 /* FIXME: do we need to do something here to let the
1629 client know about the failure!? */
1632 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1633 "Connection to peer `%4s' succeeded, retrying original transmission request\n",
1634 GNUNET_i2s (&sm->peer));
1635 handle_client_send (NULL, NULL, &sm->header);
1642 * Handle CORE_SEND request.
1645 handle_client_send (void *cls,
1646 struct GNUNET_SERVER_Client *client,
1647 const struct GNUNET_MessageHeader *message)
1649 const struct SendMessage *sm;
1650 struct SendMessage *smc;
1651 const struct GNUNET_MessageHeader *mh;
1652 struct Neighbour *n;
1653 struct MessageEntry *pred;
1654 struct MessageEntry *pos;
1655 struct MessageEntry *e;
1658 msize = ntohs (message->size);
1660 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
1664 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1667 sm = (const struct SendMessage *) message;
1668 msize -= sizeof (struct SendMessage);
1669 mh = (const struct GNUNET_MessageHeader *) &sm[1];
1670 if (msize != ntohs (mh->size))
1674 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1677 n = find_neighbour (&sm->peer);
1680 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1681 "Core received `%s' request for `%4s', will try to establish connection within %llu ms\n",
1683 GNUNET_i2s (&sm->peer),
1684 sm->deadline.value);
1685 msize += sizeof (struct SendMessage);
1686 /* ask transport to connect to the peer */
1687 /* FIXME: this code does not handle the
1688 case where we get multiple SendMessages before
1689 transport responds to this request;
1690 => need to track pending requests! */
1691 smc = GNUNET_malloc (msize);
1692 memcpy (smc, sm, msize);
1693 GNUNET_TRANSPORT_notify_transmit_ready (transport,
1696 GNUNET_TIME_absolute_get_remaining
1697 (GNUNET_TIME_absolute_ntoh
1699 &send_connect_continuation,
1702 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1705 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1706 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
1709 GNUNET_i2s (&sm->peer));
1710 /* FIXME: consider bounding queue size */
1711 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
1712 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
1713 e->priority = ntohl (sm->priority);
1715 memcpy (&e[1], mh, msize);
1717 /* insert, keep list sorted by deadline */
1720 while ((pos != NULL) && (pos->deadline.value < e->deadline.value))
1731 /* consider scheduling now */
1732 process_plaintext_neighbour_queue (n);
1734 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1739 * List of handlers for the messages understood by this
1742 static struct GNUNET_SERVER_MessageHandler handlers[] = {
1743 {&handle_client_init, NULL,
1744 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
1745 {&handle_client_request_configure, NULL,
1746 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONFIGURE,
1747 sizeof (struct RequestConfigureMessage)},
1748 {&handle_client_send, NULL,
1749 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
1755 * PEERINFO is giving us a HELLO for a peer. Add the
1756 * public key to the neighbour's struct and retry
1757 * send_key. Or, if we did not get a HELLO, just do
1761 * @param peer the peer for which this is the HELLO
1762 * @param hello HELLO message of that peer
1763 * @param trust amount of trust we currently have in that peer
1766 process_hello_retry_send_key (void *cls,
1767 const struct GNUNET_PeerIdentity *peer,
1768 const struct GNUNET_HELLO_Message *hello,
1771 struct Neighbour *n;
1775 n = find_neighbour (peer);
1778 if (n->public_key != NULL)
1780 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1781 "Received new `%s' message for `%4s', initiating key exchange.\n",
1785 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1786 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
1788 GNUNET_free (n->public_key);
1789 n->public_key = NULL;
1797 * Task that will retry "send_key" if our previous attempt failed
1801 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1803 struct Neighbour *n = cls;
1805 GNUNET_assert (n->status != PEER_STATE_KEY_CONFIRMED);
1806 n->retry_set_key_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1807 n->set_key_retry_frequency =
1808 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
1814 * Send our key (and encrypted PING) to the other peer.
1816 * @param n the other peer
1819 send_key (struct Neighbour *n)
1821 struct SetKeyMessage *sm;
1822 struct MessageEntry *me;
1823 struct PingMessage pp;
1824 struct PingMessage *pm;
1826 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1827 "Asked to perform key exchange with `%4s'.\n",
1828 GNUNET_i2s (&n->peer));
1829 if (n->public_key == NULL)
1831 /* lookup n's public key, then try again */
1832 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1833 "Lacking public key for `%4s', trying to obtain one.\n",
1834 GNUNET_i2s (&n->peer));
1835 GNUNET_PEERINFO_for_all (cfg,
1839 GNUNET_TIME_UNIT_MINUTES,
1840 &process_hello_retry_send_key, NULL);
1843 /* first, set key message */
1844 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1845 sizeof (struct SetKeyMessage));
1846 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
1847 me->priority = SET_KEY_PRIORITY;
1848 me->size = sizeof (struct SetKeyMessage);
1849 if (n->encrypted_head == NULL)
1850 n->encrypted_head = me;
1852 n->encrypted_tail->next = me;
1853 n->encrypted_tail = me;
1854 sm = (struct SetKeyMessage *) &me[1];
1855 sm->header.size = htons (sizeof (struct SetKeyMessage));
1856 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
1857 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
1858 PEER_STATE_KEY_SENT : n->status));
1860 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1861 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1862 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
1863 sizeof (struct GNUNET_PeerIdentity));
1864 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
1865 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
1866 sm->target = n->peer;
1867 GNUNET_assert (GNUNET_OK ==
1868 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
1870 GNUNET_CRYPTO_AesSessionKey),
1872 &sm->encrypted_key));
1873 GNUNET_assert (GNUNET_OK ==
1874 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
1877 /* second, encrypted PING message */
1878 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1879 sizeof (struct PingMessage));
1880 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1881 me->priority = PING_PRIORITY;
1882 me->size = sizeof (struct PingMessage);
1883 n->encrypted_tail->next = me;
1884 n->encrypted_tail = me;
1885 pm = (struct PingMessage *) &me[1];
1886 pm->header.size = htons (sizeof (struct PingMessage));
1887 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1888 pp.challenge = htonl (n->ping_challenge);
1889 pp.target = n->peer;
1890 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1891 "Encrypting `%s' and `%s' messages for `%4s'.\n",
1892 "SET_KEY", "PING", GNUNET_i2s (&n->peer));
1893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1894 "Sending `%s' to `%4s' with challenge %u encrypted using key %u\n",
1896 GNUNET_i2s (&n->peer), n->ping_challenge, n->encrypt_key.crc32);
1898 &n->peer.hashPubKey,
1901 sizeof (struct PingMessage) -
1902 sizeof (struct GNUNET_MessageHeader));
1906 case PEER_STATE_DOWN:
1907 n->status = PEER_STATE_KEY_SENT;
1909 case PEER_STATE_KEY_SENT:
1911 case PEER_STATE_KEY_RECEIVED:
1913 case PEER_STATE_KEY_CONFIRMED:
1920 /* trigger queue processing */
1921 process_encrypted_neighbour_queue (n);
1922 if (n->status != PEER_STATE_KEY_CONFIRMED)
1923 n->retry_set_key_task
1924 = GNUNET_SCHEDULER_add_delayed (sched,
1926 GNUNET_SCHEDULER_PRIORITY_KEEP,
1927 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1928 n->set_key_retry_frequency,
1929 &set_key_retry_task, n);
1934 * We received a SET_KEY message. Validate and update
1935 * our key material and status.
1937 * @param n the neighbour from which we received message m
1938 * @param m the set key message we received
1941 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m);
1945 * PEERINFO is giving us a HELLO for a peer. Add the public key to
1946 * the neighbour's struct and retry handling the set_key message. Or,
1947 * if we did not get a HELLO, just free the set key message.
1949 * @param cls pointer to the set key message
1950 * @param peer the peer for which this is the HELLO
1951 * @param hello HELLO message of that peer
1952 * @param trust amount of trust we currently have in that peer
1955 process_hello_retry_handle_set_key (void *cls,
1956 const struct GNUNET_PeerIdentity *peer,
1957 const struct GNUNET_HELLO_Message *hello,
1960 struct SetKeyMessage *sm = cls;
1961 struct Neighbour *n;
1968 n = find_neighbour (peer);
1974 if (n->public_key != NULL)
1975 return; /* multiple HELLOs match!? */
1977 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1978 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
1980 GNUNET_break_op (0);
1981 GNUNET_free (n->public_key);
1982 n->public_key = NULL;
1985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1986 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
1987 "HELLO", GNUNET_i2s (peer), "SET_KEY");
1988 handle_set_key (n, sm);
1993 * We received a PING message. Validate and transmit
1996 * @param n sender of the PING
1997 * @param m the encrypted PING message itself
2000 handle_ping (struct Neighbour *n, const struct PingMessage *m)
2002 struct PingMessage t;
2003 struct PingMessage *tp;
2004 struct MessageEntry *me;
2006 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2007 "Core service receives `%s' request from `%4s'.\n",
2008 "PING", GNUNET_i2s (&n->peer));
2011 &my_identity.hashPubKey,
2014 sizeof (struct PingMessage) -
2015 sizeof (struct GNUNET_MessageHeader)))
2017 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2018 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u\n",
2020 GNUNET_i2s (&t.target),
2021 ntohl (t.challenge), n->decrypt_key.crc32);
2022 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2023 "Target of `%s' request is `%4s'.\n",
2024 "PING", GNUNET_i2s (&t.target));
2025 if (0 != memcmp (&t.target,
2026 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2028 GNUNET_break_op (0);
2031 me = GNUNET_malloc (sizeof (struct MessageEntry) +
2032 sizeof (struct PingMessage));
2033 if (n->encrypted_tail != NULL)
2034 n->encrypted_tail->next = me;
2037 n->encrypted_tail = me;
2038 n->encrypted_head = me;
2040 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
2041 me->priority = PONG_PRIORITY;
2042 me->size = sizeof (struct PingMessage);
2043 tp = (struct PingMessage *) &me[1];
2044 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
2045 tp->header.size = htons (sizeof (struct PingMessage));
2047 &my_identity.hashPubKey,
2050 sizeof (struct PingMessage) -
2051 sizeof (struct GNUNET_MessageHeader));
2052 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2053 "Encrypting `%s' with challenge %u using key %u\n", "PONG",
2054 ntohl (t.challenge), n->encrypt_key.crc32);
2055 /* trigger queue processing */
2056 process_encrypted_neighbour_queue (n);
2061 * We received a SET_KEY message. Validate and update
2062 * our key material and status.
2064 * @param n the neighbour from which we received message m
2065 * @param m the set key message we received
2068 handle_set_key (struct Neighbour *n, const struct SetKeyMessage *m)
2070 struct SetKeyMessage *m_cpy;
2071 struct GNUNET_TIME_Absolute t;
2072 struct GNUNET_CRYPTO_AesSessionKey k;
2073 struct PingMessage *ping;
2074 enum PeerStateMachine sender_status;
2076 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2077 "Core service receives `%s' request from `%4s'.\n",
2078 "SET_KEY", GNUNET_i2s (&n->peer));
2079 if (n->public_key == NULL)
2081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2082 "Lacking public key for peer, trying to obtain one.\n");
2083 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
2084 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
2085 /* lookup n's public key, then try again */
2086 GNUNET_PEERINFO_for_all (cfg,
2090 GNUNET_TIME_UNIT_MINUTES,
2091 &process_hello_retry_handle_set_key, m_cpy);
2094 if ((ntohl (m->purpose.size) !=
2095 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2096 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
2097 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
2098 sizeof (struct GNUNET_PeerIdentity)) ||
2100 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
2101 &m->purpose, &m->signature, n->public_key)))
2103 /* invalid signature */
2104 GNUNET_break_op (0);
2107 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
2108 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
2109 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
2110 (t.value < n->decrypt_key_created.value))
2112 /* this could rarely happen due to massive re-ordering of
2113 messages on the network level, but is most likely either
2114 a bug or some adversary messing with us. Report. */
2115 GNUNET_break_op (0);
2118 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypting key material.\n");
2119 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
2122 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
2123 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
2124 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
2126 /* failed to decrypt !? */
2127 GNUNET_break_op (0);
2132 if (n->decrypt_key_created.value != t.value)
2134 /* fresh key, reset sequence numbers */
2135 n->last_sequence_number_received = 0;
2136 n->last_packets_bitmap = 0;
2137 n->decrypt_key_created = t;
2139 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
2142 case PEER_STATE_DOWN:
2143 n->status = PEER_STATE_KEY_RECEIVED;
2144 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2145 "Responding to `%s' with my own key.\n", "SET_KEY");
2148 case PEER_STATE_KEY_SENT:
2149 case PEER_STATE_KEY_RECEIVED:
2150 n->status = PEER_STATE_KEY_RECEIVED;
2151 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2152 (sender_status != PEER_STATE_KEY_CONFIRMED))
2154 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2155 "Responding to `%s' with my own key (other peer has status %u).\n",
2156 "SET_KEY", sender_status);
2160 case PEER_STATE_KEY_CONFIRMED:
2161 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
2162 (sender_status != PEER_STATE_KEY_CONFIRMED))
2164 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2165 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
2166 "SET_KEY", sender_status);
2174 if (n->pending_ping != NULL)
2176 ping = n->pending_ping;
2177 n->pending_ping = NULL;
2178 handle_ping (n, ping);
2185 * We received a PONG message. Validate and update
2188 * @param n sender of the PONG
2189 * @param m the encrypted PONG message itself
2192 handle_pong (struct Neighbour *n, const struct PingMessage *m)
2194 struct PingMessage t;
2196 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2197 "Core service receives `%s' request from `%4s'.\n",
2198 "PONG", GNUNET_i2s (&n->peer));
2201 &n->peer.hashPubKey,
2204 sizeof (struct PingMessage) -
2205 sizeof (struct GNUNET_MessageHeader)))
2207 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2208 "Decrypted `%s' from `%4s' with challenge %u using key %u\n",
2210 GNUNET_i2s (&t.target),
2211 ntohl (t.challenge), n->decrypt_key.crc32);
2212 if ((0 != memcmp (&t.target,
2214 sizeof (struct GNUNET_PeerIdentity))) ||
2215 (n->ping_challenge != ntohl (t.challenge)))
2217 /* PONG malformed */
2218 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2219 "Received malfromed `%s' wanted sender `%4s' with challenge %u\n",
2220 "PONG", GNUNET_i2s (&n->peer), n->ping_challenge);
2221 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2222 "Received malfromed `%s' received from `%4s' with challenge %u\n",
2223 "PONG", GNUNET_i2s (&t.target), ntohl (t.challenge));
2224 GNUNET_break_op (0);
2229 case PEER_STATE_DOWN:
2230 GNUNET_break (0); /* should be impossible */
2232 case PEER_STATE_KEY_SENT:
2233 GNUNET_break (0); /* should be impossible, how did we decrypt? */
2235 case PEER_STATE_KEY_RECEIVED:
2236 n->status = PEER_STATE_KEY_CONFIRMED;
2237 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
2239 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2240 n->retry_set_key_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
2242 process_encrypted_neighbour_queue (n);
2244 case PEER_STATE_KEY_CONFIRMED:
2245 /* duplicate PONG? */
2255 * Send a P2P message to a client.
2257 * @param sender who sent us the message?
2258 * @param client who should we give the message to?
2259 * @param m contains the message to transmit
2260 * @param msize number of bytes in buf to transmit
2263 send_p2p_message_to_client (struct Neighbour *sender,
2264 struct Client *client,
2265 const void *m, size_t msize)
2267 char buf[msize + sizeof (struct NotifyTrafficMessage)];
2268 struct NotifyTrafficMessage *ntm;
2270 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2271 "Core service passes message from `%4s' of type %u to client.\n",
2272 GNUNET_i2s(&sender->peer),
2273 ntohs (((const struct GNUNET_MessageHeader *) m)->type));
2274 ntm = (struct NotifyTrafficMessage *) buf;
2275 ntm->header.size = htons (msize + sizeof (struct NotifyTrafficMessage));
2276 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
2277 ntm->reserved = htonl (0);
2278 ntm->peer = sender->peer;
2279 memcpy (&ntm[1], m, msize);
2280 send_to_client (client, &ntm->header, GNUNET_YES);
2285 * Deliver P2P message to interested clients.
2287 * @param sender who sent us the message?
2288 * @param m the message
2289 * @param msize size of the message (including header)
2292 deliver_message (struct Neighbour *sender,
2293 const struct GNUNET_MessageHeader *m, size_t msize)
2295 struct Client *cpos;
2300 type = ntohs (m->type);
2302 while (cpos != NULL)
2304 deliver_full = GNUNET_NO;
2305 if (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND)
2306 deliver_full = GNUNET_YES;
2309 for (tpos = 0; tpos < cpos->tcnt; tpos++)
2311 if (type != cpos->types[tpos])
2313 deliver_full = GNUNET_YES;
2317 if (GNUNET_YES == deliver_full)
2318 send_p2p_message_to_client (sender, cpos, m, msize);
2319 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
2320 send_p2p_message_to_client (sender, cpos, m,
2321 sizeof (struct GNUNET_MessageHeader));
2328 * Align P2P message and then deliver to interested clients.
2330 * @param sender who sent us the message?
2331 * @param buffer unaligned (!) buffer containing message
2332 * @param msize size of the message (including header)
2335 align_and_deliver (struct Neighbour *sender, const char *buffer, size_t msize)
2339 /* TODO: call to statistics? */
2340 memcpy (abuf, buffer, msize);
2341 deliver_message (sender, (const struct GNUNET_MessageHeader *) abuf, msize);
2346 * Deliver P2P messages to interested clients.
2348 * @param sender who sent us the message?
2349 * @param buffer buffer containing messages, can be modified
2350 * @param buffer_size size of the buffer (overall)
2351 * @param offset offset where messages in the buffer start
2354 deliver_messages (struct Neighbour *sender,
2355 const char *buffer, size_t buffer_size, size_t offset)
2357 struct GNUNET_MessageHeader *mhp;
2358 struct GNUNET_MessageHeader mh;
2362 while (offset + sizeof (struct GNUNET_MessageHeader) <= buffer_size)
2364 if (0 != offset % sizeof (uint16_t))
2366 /* outch, need to copy to access header */
2367 memcpy (&mh, &buffer[offset], sizeof (struct GNUNET_MessageHeader));
2372 /* can access header directly */
2373 mhp = (struct GNUNET_MessageHeader *) &buffer[offset];
2375 msize = ntohs (mhp->size);
2376 if (msize + offset > buffer_size)
2378 /* malformed message, header says it is larger than what
2379 would fit into the overall buffer */
2380 GNUNET_break_op (0);
2383 #if HAVE_UNALIGNED_64_ACCESS
2384 need_align = (0 != offset % 4) ? GNUNET_YES : GNUNET_NO;
2386 need_align = (0 != offset % 8) ? GNUNET_YES : GNUNET_NO;
2388 if (GNUNET_YES == need_align)
2389 align_and_deliver (sender, &buffer[offset], msize);
2391 deliver_message (sender,
2392 (const struct GNUNET_MessageHeader *)
2393 &buffer[offset], msize);
2400 * We received an encrypted message. Decrypt, validate and
2401 * pass on to the appropriate clients.
2404 handle_encrypted_message (struct Neighbour *n,
2405 const struct EncryptedMessage *m)
2407 size_t size = ntohs (m->header.size);
2409 struct EncryptedMessage *pt; /* plaintext */
2413 struct GNUNET_TIME_Absolute t;
2415 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2416 "Core service receives `%s' request from `%4s'.\n",
2417 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
2422 &m->sequence_number,
2423 &buf[ENCRYPTED_HEADER_SIZE], size - ENCRYPTED_HEADER_SIZE))
2425 pt = (struct EncryptedMessage *) buf;
2428 GNUNET_CRYPTO_hash (&pt->sequence_number,
2429 size - ENCRYPTED_HEADER_SIZE, &ph);
2430 if (0 != memcmp (&ph, &m->plaintext_hash, sizeof (GNUNET_HashCode)))
2432 /* checksum failed */
2433 GNUNET_break_op (0);
2437 /* validate sequence number */
2438 snum = ntohl (pt->sequence_number);
2439 if (n->last_sequence_number_received == snum)
2441 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2442 "Received duplicate message, ignoring.\n");
2443 /* duplicate, ignore */
2446 if ((n->last_sequence_number_received > snum) &&
2447 (n->last_sequence_number_received - snum > 32))
2449 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2450 "Received ancient out of sequence message, ignoring.\n");
2451 /* ancient out of sequence, ignore */
2454 if (n->last_sequence_number_received > snum)
2456 unsigned int rotbit =
2457 1 << (n->last_sequence_number_received - snum - 1);
2458 if ((n->last_packets_bitmap & rotbit) != 0)
2460 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2461 "Received duplicate message, ignoring.\n");
2462 /* duplicate, ignore */
2465 n->last_packets_bitmap |= rotbit;
2467 if (n->last_sequence_number_received < snum)
2469 n->last_packets_bitmap <<= (snum - n->last_sequence_number_received);
2470 n->last_sequence_number_received = snum;
2473 /* check timestamp */
2474 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
2475 if (GNUNET_TIME_absolute_get_duration (t).value > MAX_MESSAGE_AGE.value)
2477 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2479 ("Message received far too old (%llu ms). Content ignored.\n"),
2480 GNUNET_TIME_absolute_get_duration (t).value);
2484 /* process decrypted message(s) */
2485 n->bpm_out_external_limit = ntohl (pt->inbound_bpm_limit);
2486 n->bpm_out = GNUNET_MAX (n->bpm_out_external_limit,
2487 n->bpm_out_internal_limit);
2488 n->last_activity = GNUNET_TIME_absolute_get ();
2489 off = sizeof (struct EncryptedMessage);
2490 deliver_messages (n, buf, size, off);
2495 * Function called by the transport for each received message.
2497 * @param cls closure
2498 * @param latency estimated latency for communicating with the
2500 * @param peer (claimed) identity of the other peer
2501 * @param message the message
2504 handle_transport_receive (void *cls,
2505 struct GNUNET_TIME_Relative latency,
2506 const struct GNUNET_PeerIdentity *peer,
2507 const struct GNUNET_MessageHeader *message)
2509 struct Neighbour *n;
2510 struct GNUNET_TIME_Absolute now;
2515 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2516 "Received message of type %u from `%4s', demultiplexing.\n",
2517 ntohs (message->type), GNUNET_i2s (peer));
2518 n = find_neighbour (peer);
2524 n->last_latency = latency;
2525 up = n->status == PEER_STATE_KEY_CONFIRMED;
2526 type = ntohs (message->type);
2527 size = ntohs (message->size);
2530 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
2531 if (size != sizeof (struct SetKeyMessage))
2533 GNUNET_break_op (0);
2536 handle_set_key (n, (const struct SetKeyMessage *) message);
2538 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
2539 if (size < sizeof (struct EncryptedMessage) +
2540 sizeof (struct GNUNET_MessageHeader))
2542 GNUNET_break_op (0);
2545 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2546 (n->status != PEER_STATE_KEY_CONFIRMED))
2548 GNUNET_break_op (0);
2551 handle_encrypted_message (n, (const struct EncryptedMessage *) message);
2553 case GNUNET_MESSAGE_TYPE_CORE_PING:
2554 if (size != sizeof (struct PingMessage))
2556 GNUNET_break_op (0);
2559 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2560 (n->status != PEER_STATE_KEY_CONFIRMED))
2562 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2563 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
2564 "PING", GNUNET_i2s (&n->peer));
2565 GNUNET_free_non_null (n->pending_ping);
2566 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
2567 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
2570 handle_ping (n, (const struct PingMessage *) message);
2572 case GNUNET_MESSAGE_TYPE_CORE_PONG:
2573 if (size != sizeof (struct PingMessage))
2575 GNUNET_break_op (0);
2578 if ((n->status != PEER_STATE_KEY_SENT) &&
2579 (n->status != PEER_STATE_KEY_RECEIVED) &&
2580 (n->status != PEER_STATE_KEY_CONFIRMED))
2582 /* could not decrypt pong, oops! */
2583 GNUNET_break_op (0);
2586 handle_pong (n, (const struct PingMessage *) message);
2589 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2590 _("Unsupported message of type %u received.\n"), type);
2593 if (n->status == PEER_STATE_KEY_CONFIRMED)
2595 now = GNUNET_TIME_absolute_get ();
2596 n->last_activity = now;
2598 n->time_established = now;
2604 * Function called by transport to notify us that
2605 * a peer connected to us (on the network level).
2607 * @param cls closure
2608 * @param peer the peer that connected
2609 * @param latency current latency of the connection
2612 handle_transport_notify_connect (void *cls,
2613 const struct GNUNET_PeerIdentity *peer,
2614 struct GNUNET_TIME_Relative latency)
2616 struct Neighbour *n;
2617 struct GNUNET_TIME_Absolute now;
2618 struct ConnectNotifyMessage cnm;
2620 n = find_neighbour (peer);
2623 /* duplicate connect notification!? */
2627 now = GNUNET_TIME_absolute_get ();
2628 n = GNUNET_malloc (sizeof (struct Neighbour));
2629 n->next = neighbours;
2632 n->last_latency = latency;
2633 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2634 n->encrypt_key_created = now;
2635 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2636 n->last_asw_update = now;
2637 n->last_arw_update = now;
2638 n->bpm_in = DEFAULT_BPM_IN_OUT;
2639 n->bpm_out = DEFAULT_BPM_IN_OUT;
2640 n->bpm_out_internal_limit = (uint32_t) - 1;
2641 n->bpm_out_external_limit = DEFAULT_BPM_IN_OUT;
2642 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2644 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2645 "Received connection from `%4s'.\n",
2646 GNUNET_i2s (&n->peer));
2647 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2648 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
2649 cnm.bpm_available = htonl (DEFAULT_BPM_IN_OUT);
2651 cnm.last_activity = GNUNET_TIME_absolute_hton (now);
2652 send_to_all_clients (&cnm.header, GNUNET_YES);
2657 * Free the given entry for the neighbour (it has
2658 * already been removed from the list at this point).
2659 * @param n neighbour to free
2662 free_neighbour (struct Neighbour *n)
2664 struct MessageEntry *m;
2666 while (NULL != (m = n->messages))
2668 n->messages = m->next;
2671 while (NULL != (m = n->encrypted_head))
2673 n->encrypted_head = m->next;
2677 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
2678 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
2679 GNUNET_SCHEDULER_cancel (sched, n->retry_plaintext_task);
2680 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
2681 GNUNET_SCHEDULER_cancel (sched, n->retry_set_key_task);
2682 GNUNET_free_non_null (n->public_key);
2683 GNUNET_free_non_null (n->pending_ping);
2689 * Function called by transport telling us that a peer
2692 * @param cls closure
2693 * @param peer the peer that disconnected
2696 handle_transport_notify_disconnect (void *cls,
2697 const struct GNUNET_PeerIdentity *peer)
2699 struct ConnectNotifyMessage cnm;
2700 struct Neighbour *n;
2701 struct Neighbour *p;
2703 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2704 "Peer `%4s' disconnected from us.\n", GNUNET_i2s (peer));
2707 while ((n != NULL) &&
2708 (0 != memcmp (&n->peer, peer, sizeof (struct GNUNET_PeerIdentity))))
2719 neighbours = n->next;
2722 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
2723 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
2724 cnm.bpm_available = htonl (0);
2726 cnm.last_activity = GNUNET_TIME_absolute_hton (n->last_activity);
2727 send_to_all_clients (&cnm.header, GNUNET_YES);
2733 * Last task run during shutdown. Disconnects us from
2737 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2739 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2740 "Core service shutting down.\n");
2741 GNUNET_assert (transport != NULL);
2742 GNUNET_TRANSPORT_disconnect (transport);
2748 * Initiate core service.
2750 * @param cls closure
2751 * @param s scheduler to use
2752 * @param serv the initialized server
2753 * @param c configuration to use
2757 struct GNUNET_SCHEDULER_Handle *s,
2758 struct GNUNET_SERVER_Handle *serv, struct GNUNET_CONFIGURATION_Handle *c)
2761 unsigned long long qin;
2762 unsigned long long qout;
2763 unsigned long long tneigh;
2769 /* parse configuration */
2773 GNUNET_CONFIGURATION_get_value_number (c,
2778 GNUNET_CONFIGURATION_get_value_number (c,
2783 GNUNET_CONFIGURATION_get_value_number (c,
2785 "ZZ_LIMIT", &tneigh)) ||
2788 GNUNET_CONFIGURATION_get_value_filename (c,
2790 "HOSTKEY", &keyfile)))
2792 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2794 ("Core service is lacking key configuration settings. Exiting.\n"));
2795 GNUNET_SCHEDULER_shutdown (s);
2798 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2799 GNUNET_free (keyfile);
2800 if (my_private_key == NULL)
2802 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2803 _("Core service could not access hostkey. Exiting.\n"));
2804 GNUNET_SCHEDULER_shutdown (s);
2807 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
2808 GNUNET_CRYPTO_hash (&my_public_key,
2809 sizeof (my_public_key), &my_identity.hashPubKey);
2810 /* setup notification */
2812 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
2813 /* setup transport connection */
2814 transport = GNUNET_TRANSPORT_connect (sched,
2817 &handle_transport_receive,
2818 &handle_transport_notify_connect,
2819 &handle_transport_notify_disconnect);
2820 GNUNET_assert (NULL != transport);
2821 GNUNET_SCHEDULER_add_delayed (sched,
2823 GNUNET_SCHEDULER_PRIORITY_IDLE,
2824 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
2825 GNUNET_TIME_UNIT_FOREVER_REL,
2826 &cleaning_task, NULL);
2827 /* process client requests */
2828 GNUNET_SERVER_add_handlers (server, handlers);
2829 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2830 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
2835 * Function called during shutdown. Clean up our state.
2838 cleanup (void *cls, struct GNUNET_CONFIGURATION_Handle *cfg)
2840 struct Neighbour *n;
2842 if (my_private_key != NULL)
2843 GNUNET_CRYPTO_rsa_key_free (my_private_key);
2844 while (NULL != (n = neighbours))
2846 neighbours = n->next;
2857 * The main function for the transport service.
2859 * @param argc number of arguments from the command line
2860 * @param argv command line arguments
2861 * @return 0 ok, 1 on error
2864 main (int argc, char *const *argv)
2866 return (GNUNET_OK ==
2867 GNUNET_SERVICE_run (argc,
2869 "core", &run, NULL, &cleanup, NULL)) ? 0 : 1;
2872 /* end of gnunet-service-core.c */