2 This file is part of GNUnet.
3 (C) 2009, 2010 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 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file core/gnunet-service-core.c
23 * @brief high-level P2P messaging
24 * @author Christian Grothoff
26 * Considerations for later:
27 * - check that hostkey used by transport (for HELLOs) is the
28 * same as the hostkey that we are using!
29 * - add code to send PINGs if we are about to time-out otherwise
30 * - optimize lookup (many O(n) list traversals
31 * could ideally be changed to O(1) hash map lookups)
34 #include "gnunet_constants.h"
35 #include "gnunet_util_lib.h"
36 #include "gnunet_hello_lib.h"
37 #include "gnunet_peerinfo_service.h"
38 #include "gnunet_protocols.h"
39 #include "gnunet_signatures.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet_transport_service.h"
45 #define DEBUG_HANDSHAKE GNUNET_NO
47 #define DEBUG_CORE_QUOTA GNUNET_NO
50 * Receive and send buffer windows grow over time. For
51 * how long can 'unused' bandwidth accumulate before we
52 * need to cap it? (specified in seconds).
54 #define MAX_WINDOW_TIME_S (5 * 60)
57 * How many messages do we queue up at most for optional
58 * notifications to a client? (this can cause notifications
59 * about outgoing messages to be dropped).
61 #define MAX_NOTIFY_QUEUE 1024
64 * Minimum bandwidth (out) to assign to any connected peer.
65 * Should be rather low; values larger than DEFAULT_BW_IN_OUT make no
68 #define MIN_BANDWIDTH_PER_PEER GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT
71 * After how much time past the "official" expiration time do
72 * we discard messages? Should not be zero since we may
73 * intentionally defer transmission until close to the deadline
74 * and then may be slightly past the deadline due to inaccuracy
75 * in sleep and our own CPU consumption.
77 #define PAST_EXPIRATION_DISCARD_TIME GNUNET_TIME_UNIT_SECONDS
80 * What is the maximum delay for a SET_KEY message?
82 #define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
85 * How long do we wait for SET_KEY confirmation initially?
87 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 1)
90 * What is the maximum delay for a PING message?
92 #define MAX_PING_DELAY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 2)
95 * What is the maximum delay for a PONG message?
97 #define MAX_PONG_DELAY GNUNET_TIME_relative_multiply (MAX_PING_DELAY, 2)
100 * What is the minimum frequency for a PING message?
102 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
105 * How often do we recalculate bandwidth quotas?
107 #define QUOTA_UPDATE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
110 * What is the priority for a SET_KEY message?
112 #define SET_KEY_PRIORITY 0xFFFFFF
115 * What is the priority for a PING message?
117 #define PING_PRIORITY 0xFFFFFF
120 * What is the priority for a PONG message?
122 #define PONG_PRIORITY 0xFFFFFF
125 * How many messages do we queue per peer at most? Must be at
128 #define MAX_PEER_QUEUE_SIZE 16
131 * How many non-mandatory messages do we queue per client at most?
133 #define MAX_CLIENT_QUEUE_SIZE 32
136 * What is the maximum age of a message for us to consider
137 * processing it? Note that this looks at the timestamp used
138 * by the other peer, so clock skew between machines does
139 * come into play here. So this should be picked high enough
140 * so that a little bit of clock skew does not prevent peers
141 * from connecting to us.
143 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
147 * State machine for our P2P encryption handshake. Everyone starts in
148 * "DOWN", if we receive the other peer's key (other peer initiated)
149 * we start in state RECEIVED (since we will immediately send our
150 * own); otherwise we start in SENT. If we get back a PONG from
151 * within either state, we move up to CONFIRMED (the PONG will always
152 * be sent back encrypted with the key we sent to the other peer).
154 enum PeerStateMachine
162 * We've sent our session key.
167 * We've received the other peers session key.
169 PEER_STATE_KEY_RECEIVED,
172 * The other peer has confirmed our session key with a message
173 * encrypted with his session key (which we got). Session is now fully up.
175 PEER_STATE_KEY_CONFIRMED
180 * Encapsulation for encrypted messages exchanged between
181 * peers. Followed by the actual encrypted data.
183 struct EncryptedMessage
186 * Message type is either CORE_ENCRYPTED_MESSAGE.
188 struct GNUNET_MessageHeader header;
191 * Random value used for IV generation.
193 uint32_t iv_seed GNUNET_PACKED;
196 * MAC of the encrypted message (starting at 'sequence_number'),
197 * used to verify message integrity. Everything after this value
198 * (excluding this value itself) will be encrypted and authenticated.
199 * ENCRYPTED_HEADER_SIZE must be set to the offset of the *next* field.
201 GNUNET_HashCode hmac;
204 * Sequence number, in network byte order. This field
205 * must be the first encrypted/decrypted field
207 uint32_t sequence_number GNUNET_PACKED;
210 * Desired bandwidth (how much we should send to this peer / how
211 * much is the sender willing to receive)?
213 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
216 * Timestamp. Used to prevent reply of ancient messages
217 * (recent messages are caught with the sequence number).
219 struct GNUNET_TIME_AbsoluteNBO timestamp;
225 * Number of bytes (at the beginning) of "struct EncryptedMessage"
226 * that are NOT encrypted.
228 #define ENCRYPTED_HEADER_SIZE (offsetof(struct EncryptedMessage, sequence_number))
232 * We're sending an (encrypted) PING to the other peer to check if he
233 * can decrypt. The other peer should respond with a PONG with the
234 * same content, except this time encrypted with the receiver's key.
239 * Message type is CORE_PING.
241 struct GNUNET_MessageHeader header;
246 uint32_t iv_seed GNUNET_PACKED;
249 * Intended target of the PING, used primarily to check
250 * that decryption actually worked.
252 struct GNUNET_PeerIdentity target;
255 * Random number chosen to make reply harder.
257 uint32_t challenge GNUNET_PACKED;
263 * Response to a PING. Includes data from the original PING
264 * plus initial bandwidth quota information.
269 * Message type is CORE_PONG.
271 struct GNUNET_MessageHeader header;
276 uint32_t iv_seed GNUNET_PACKED;
279 * Random number to make faking the reply harder. Must be
280 * first field after header (this is where we start to encrypt!).
282 uint32_t challenge GNUNET_PACKED;
285 * Desired bandwidth (how much we should send to this
286 * peer / how much is the sender willing to receive).
288 struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
291 * Intended target of the PING, used primarily to check
292 * that decryption actually worked.
294 struct GNUNET_PeerIdentity target;
299 * Message transmitted to set (or update) a session key.
305 * Message type is either CORE_SET_KEY.
307 struct GNUNET_MessageHeader header;
310 * Status of the sender (should be in "enum PeerStateMachine"), nbo.
312 int32_t sender_status GNUNET_PACKED;
315 * Purpose of the signature, will be
316 * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
318 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
321 * At what time was this key created?
323 struct GNUNET_TIME_AbsoluteNBO creation_time;
326 * The encrypted session key.
328 struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
331 * Who is the intended recipient?
333 struct GNUNET_PeerIdentity target;
336 * Signature of the stuff above (starting at purpose).
338 struct GNUNET_CRYPTO_RsaSignature signature;
344 * Message waiting for transmission. This struct
345 * is followed by the actual content of the message.
351 * We keep messages in a doubly linked list.
353 struct MessageEntry *next;
356 * We keep messages in a doubly linked list.
358 struct MessageEntry *prev;
361 * By when are we supposed to transmit this message?
363 struct GNUNET_TIME_Absolute deadline;
366 * By when are we supposed to transmit this message (after
369 struct GNUNET_TIME_Absolute slack_deadline;
372 * How important is this message to us?
374 unsigned int priority;
377 * If this is a SET_KEY message, what was our connection status when this
378 * message was queued?
380 enum PeerStateMachine sender_status;
383 * Is this a SET_KEY message?
388 * How long is the message? (number of bytes following
389 * the "struct MessageEntry", but not including the
390 * size of "struct MessageEntry" itself!)
395 * Was this message selected for transmission in the
396 * current round? GNUNET_YES or GNUNET_NO.
401 * Did we give this message some slack (delayed sending) previously
402 * (and hence should not give it any more slack)? GNUNET_YES or
411 * Record kept for each request for transmission issued by a
412 * client that is still pending.
414 struct ClientActiveRequest;
417 * Data kept per neighbouring peer.
423 * Unencrypted messages destined for this peer.
425 struct MessageEntry *messages;
428 * Head of the batched, encrypted message queue (already ordered,
429 * transmit starting with the head).
431 struct MessageEntry *encrypted_head;
434 * Tail of the batched, encrypted message queue (already ordered,
435 * append new messages to tail)
437 struct MessageEntry *encrypted_tail;
440 * Head of list of requests from clients for transmission to
443 struct ClientActiveRequest *active_client_request_head;
446 * Tail of list of requests from clients for transmission to
449 struct ClientActiveRequest *active_client_request_tail;
452 * Handle for pending requests for transmission to this peer
453 * with the transport service. NULL if no request is pending.
455 struct GNUNET_TRANSPORT_TransmitHandle *th;
458 * Public key of the neighbour, NULL if we don't have it yet.
460 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
463 * We received a PING message before we got the "public_key"
464 * (or the SET_KEY). We keep it here until we have a key
465 * to decrypt it. NULL if no PING is pending.
467 struct PingMessage *pending_ping;
470 * We received a PONG message before we got the "public_key"
471 * (or the SET_KEY). We keep it here until we have a key
472 * to decrypt it. NULL if no PONG is pending.
474 struct PongMessage *pending_pong;
477 * Non-NULL if we are currently looking up HELLOs for this peer.
480 struct GNUNET_PEERINFO_IteratorContext *pitr;
483 * SetKeyMessage to transmit, NULL if we are not currently trying
486 struct SetKeyMessage *skm;
489 * Performance data for the peer.
491 struct GNUNET_TRANSPORT_ATS_Information *ats;
494 * Identity of the neighbour.
496 struct GNUNET_PeerIdentity peer;
499 * Key we use to encrypt our messages for the other peer
500 * (initialized by us when we do the handshake).
502 struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
505 * Key we use to decrypt messages from the other peer
506 * (given to us by the other peer during the handshake).
508 struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
511 * ID of task used for re-trying plaintext scheduling.
513 GNUNET_SCHEDULER_TaskIdentifier retry_plaintext_task;
516 * ID of task used for re-trying SET_KEY and PING message.
518 GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
521 * ID of task used for updating bandwidth quota for this neighbour.
523 GNUNET_SCHEDULER_TaskIdentifier quota_update_task;
526 * ID of task used for sending keep-alive pings.
528 GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
531 * ID of task used for cleaning up dead neighbour entries.
533 GNUNET_SCHEDULER_TaskIdentifier dead_clean_task;
536 * At what time did we generate our encryption key?
538 struct GNUNET_TIME_Absolute encrypt_key_created;
541 * At what time did the other peer generate the decryption key?
543 struct GNUNET_TIME_Absolute decrypt_key_created;
546 * At what time did we initially establish (as in, complete session
547 * key handshake) this connection? Should be zero if status != KEY_CONFIRMED.
549 struct GNUNET_TIME_Absolute time_established;
552 * At what time did we last receive an encrypted message from the
553 * other peer? Should be zero if status != KEY_CONFIRMED.
555 struct GNUNET_TIME_Absolute last_activity;
558 * At what frequency are we currently re-trying SET_KEY messages?
560 struct GNUNET_TIME_Relative set_key_retry_frequency;
563 * Tracking bandwidth for sending to this peer.
565 struct GNUNET_BANDWIDTH_Tracker available_send_window;
568 * Tracking bandwidth for receiving from this peer.
570 struct GNUNET_BANDWIDTH_Tracker available_recv_window;
573 * How valueable were the messages of this peer recently?
575 unsigned long long current_preference;
578 * Number of entries in 'ats'.
580 unsigned int ats_count;
583 * Bit map indicating which of the 32 sequence numbers before the last
584 * were received (good for accepting out-of-order packets and
585 * estimating reliability of the connection)
587 unsigned int last_packets_bitmap;
590 * last sequence number received on this connection (highest)
592 uint32_t last_sequence_number_received;
595 * last sequence number transmitted
597 uint32_t last_sequence_number_sent;
600 * Available bandwidth in for this peer (current target).
602 struct GNUNET_BANDWIDTH_Value32NBO bw_in;
605 * Available bandwidth out for this peer (current target).
607 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
610 * Internal bandwidth limit set for this peer (initially typically
611 * set to "-1"). Actual "bw_out" is MIN of
612 * "bpm_out_internal_limit" and "bw_out_external_limit".
614 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
617 * External bandwidth limit set for this peer by the
618 * peer that we are communicating with. "bw_out" is MIN of
619 * "bw_out_internal_limit" and "bw_out_external_limit".
621 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
624 * What was our PING challenge number (for this peer)?
626 uint32_t ping_challenge;
629 * What is our connection status?
631 enum PeerStateMachine status;
634 * Are we currently connected to this neighbour?
642 * Data structure for each client connected to the core service.
647 * Clients are kept in a linked list.
652 * Handle for the client with the server API.
654 struct GNUNET_SERVER_Client *client_handle;
657 * Array of the types of messages this peer cares
658 * about (with "tcnt" entries). Allocated as part
659 * of this client struct, do not free!
661 const uint16_t *types;
664 * Map of peer identities to active transmission requests of this
665 * client to the peer (of type 'struct ClientActiveRequest').
667 struct GNUNET_CONTAINER_MultiHashMap *requests;
670 * Options for messages this client cares about,
671 * see GNUNET_CORE_OPTION_ values.
676 * Number of types of incoming messages this client
677 * specifically cares about. Size of the "types" array.
685 * Record kept for each request for transmission issued by a
686 * client that is still pending.
688 struct ClientActiveRequest
692 * Active requests are kept in a doubly-linked list of
693 * the respective target peer.
695 struct ClientActiveRequest *next;
698 * Active requests are kept in a doubly-linked list of
699 * the respective target peer.
701 struct ClientActiveRequest *prev;
704 * Handle to the client.
706 struct Client *client;
709 * By what time would the client want to see this message out?
711 struct GNUNET_TIME_Absolute deadline;
714 * How important is this request.
719 * How many more requests does this client have?
724 * How many bytes does the client intend to send?
729 * Unique request ID (in big endian).
740 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
745 static struct GNUNET_PeerIdentity my_identity;
750 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
754 * Handle to peerinfo service.
756 static struct GNUNET_PEERINFO_Handle *peerinfo;
759 * Our message stream tokenizer (for encrypted payload).
761 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
766 const struct GNUNET_CONFIGURATION_Handle *cfg;
771 static struct GNUNET_TRANSPORT_Handle *transport;
774 * Linked list of our clients.
776 static struct Client *clients;
779 * Context for notifications we need to send to our clients.
781 static struct GNUNET_SERVER_NotificationContext *notifier;
784 * Map of peer identities to 'struct Neighbour'.
786 static struct GNUNET_CONTAINER_MultiHashMap *neighbours;
789 * Neighbour entry for "this" peer.
791 static struct Neighbour self;
794 * For creating statistics.
796 static struct GNUNET_STATISTICS_Handle *stats;
799 * Sum of all preferences among all neighbours.
801 static unsigned long long preference_sum;
804 * How much inbound bandwidth are we supposed to be using per second?
806 static unsigned long long bandwidth_target_in_bps;
809 * How much outbound bandwidth are we supposed to be using per second?
811 static unsigned long long bandwidth_target_out_bps;
814 * Derive an authentication key from "set key" information
817 derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
818 const struct GNUNET_CRYPTO_AesSessionKey *skey,
820 struct GNUNET_TIME_Absolute creation_time)
822 static const char ctx[] = "authentication key";
823 struct GNUNET_TIME_AbsoluteNBO ctbe;
826 ctbe = GNUNET_TIME_absolute_hton (creation_time);
827 GNUNET_CRYPTO_hmac_derive_key (akey,
841 * Derive an IV from packet information
844 derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
845 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
846 const struct GNUNET_PeerIdentity *identity)
848 static const char ctx[] = "initialization vector";
850 GNUNET_CRYPTO_aes_derive_iv (iv,
854 &identity->hashPubKey.bits,
855 sizeof(identity->hashPubKey.bits),
861 * Derive an IV from pong packet information
864 derive_pong_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
865 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
866 uint32_t challenge, const struct GNUNET_PeerIdentity *identity)
868 static const char ctx[] = "pong initialization vector";
870 GNUNET_CRYPTO_aes_derive_iv (iv,
874 &identity->hashPubKey.bits,
875 sizeof(identity->hashPubKey.bits),
884 * At what time should the connection to the given neighbour
885 * time out (given no further activity?)
887 * @param n neighbour in question
888 * @return absolute timeout
890 static struct GNUNET_TIME_Absolute
891 get_neighbour_timeout (struct Neighbour *n)
893 return GNUNET_TIME_absolute_add (n->last_activity,
894 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
899 * Helper function for update_preference_sum.
902 update_preference (void *cls,
903 const GNUNET_HashCode *key,
906 unsigned long long *ps = cls;
907 struct Neighbour *n = value;
909 n->current_preference /= 2;
910 *ps += n->current_preference;
916 * A preference value for a neighbour was update. Update
917 * the preference sum accordingly.
919 * @param inc how much was a preference value increased?
922 update_preference_sum (unsigned long long inc)
924 unsigned long long os;
927 preference_sum += inc;
928 if (preference_sum >= os)
930 /* overflow! compensate by cutting all values in half! */
932 GNUNET_CONTAINER_multihashmap_iterate (neighbours,
935 GNUNET_STATISTICS_set (stats, gettext_noop ("# total peer preference"), preference_sum, GNUNET_NO);
940 * Find the entry for the given neighbour.
942 * @param peer identity of the neighbour
943 * @return NULL if we are not connected, otherwise the
946 static struct Neighbour *
947 find_neighbour (const struct GNUNET_PeerIdentity *peer)
949 return GNUNET_CONTAINER_multihashmap_get (neighbours, &peer->hashPubKey);
954 * Send a message to one of our clients.
956 * @param client target for the message
957 * @param msg message to transmit
958 * @param can_drop could this message be dropped if the
959 * client's queue is getting too large?
962 send_to_client (struct Client *client,
963 const struct GNUNET_MessageHeader *msg,
966 #if DEBUG_CORE_CLIENT
967 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
968 "Preparing to send %u bytes of message of type %u to client.\n",
969 (unsigned int) ntohs (msg->size),
970 (unsigned int) ntohs (msg->type));
972 GNUNET_SERVER_notification_context_unicast (notifier,
973 client->client_handle,
980 * Send a message to all of our current clients that have
981 * the right options set.
983 * @param msg message to multicast
984 * @param can_drop can this message be discarded if the queue is too long
985 * @param options mask to use
988 send_to_all_clients (const struct GNUNET_MessageHeader *msg,
997 if (0 != (c->options & options))
999 #if DEBUG_CORE_CLIENT
1000 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1001 "Sending message of type %u to client.\n",
1002 (unsigned int) ntohs (msg->type));
1004 send_to_client (c, msg, can_drop);
1012 * Function called by transport telling us that a peer
1015 * @param n the peer that changed status
1018 handle_peer_status_change (struct Neighbour *n)
1020 struct PeerStatusNotifyMessage *psnm;
1021 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1022 struct GNUNET_TRANSPORT_ATS_Information *ats;
1025 if ( (! n->is_connected) ||
1026 (n->status != PEER_STATE_KEY_CONFIRMED) )
1029 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1030 "Peer `%4s' changed status\n",
1031 GNUNET_i2s (&n->peer));
1033 size = sizeof (struct PeerStatusNotifyMessage) +
1034 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1035 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1038 /* recovery strategy: throw away performance data */
1039 GNUNET_array_grow (n->ats,
1042 size = sizeof (struct PeerStatusNotifyMessage) +
1043 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1045 psnm = (struct PeerStatusNotifyMessage*) buf;
1046 psnm->header.size = htons (size);
1047 psnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_STATUS_CHANGE);
1048 psnm->timeout = GNUNET_TIME_absolute_hton (get_neighbour_timeout (n));
1049 psnm->bandwidth_in = n->bw_in;
1050 psnm->bandwidth_out = n->bw_out;
1051 psnm->peer = n->peer;
1052 psnm->ats_count = htonl (n->ats_count);
1056 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
1057 ats[n->ats_count].type = htonl (0);
1058 ats[n->ats_count].value = htonl (0);
1059 send_to_all_clients (&psnm->header,
1061 GNUNET_CORE_OPTION_SEND_STATUS_CHANGE);
1062 GNUNET_STATISTICS_update (stats,
1063 gettext_noop ("# peer status changes"),
1070 * Go over our message queue and if it is not too long, go
1071 * over the pending requests from clients for this
1072 * neighbour and send some clients a 'READY' notification.
1074 * @param n which peer to process
1077 schedule_peer_messages (struct Neighbour *n)
1079 struct SendMessageReady smr;
1080 struct ClientActiveRequest *car;
1081 struct ClientActiveRequest *pos;
1083 struct MessageEntry *mqe;
1084 unsigned int queue_size;
1086 /* check if neighbour queue is empty enough! */
1096 if (queue_size >= MAX_PEER_QUEUE_SIZE)
1098 #if DEBUG_CORE_CLIENT
1099 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1100 "Not considering client transmission requests: queue full\n");
1102 return; /* queue still full */
1104 /* find highest priority request */
1105 pos = n->active_client_request_head;
1109 if ( (car == NULL) ||
1110 (pos->priority > car->priority) )
1117 car = n->active_client_request_head;
1120 return; /* no pending requests */
1121 #if DEBUG_CORE_CLIENT
1122 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1123 "Permitting client transmission request to `%s'\n",
1124 GNUNET_i2s (&n->peer));
1127 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1128 n->active_client_request_tail,
1130 GNUNET_assert (GNUNET_YES ==
1131 GNUNET_CONTAINER_multihashmap_remove (c->requests,
1132 &n->peer.hashPubKey,
1134 smr.header.size = htons (sizeof (struct SendMessageReady));
1135 smr.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND_READY);
1136 smr.size = htons (car->msize);
1137 smr.smr_id = car->smr_id;
1139 send_to_client (c, &smr.header, GNUNET_NO);
1145 * Handle CORE_SEND_REQUEST message.
1148 handle_client_send_request (void *cls,
1149 struct GNUNET_SERVER_Client *client,
1150 const struct GNUNET_MessageHeader *message)
1152 const struct SendMessageRequest *req;
1153 struct Neighbour *n;
1155 struct ClientActiveRequest *car;
1157 req = (const struct SendMessageRequest*) message;
1158 if (0 == memcmp (&req->peer,
1160 sizeof (struct GNUNET_PeerIdentity)))
1163 n = find_neighbour (&req->peer);
1165 (GNUNET_YES != n->is_connected) ||
1166 (n->status != PEER_STATE_KEY_CONFIRMED) )
1168 /* neighbour must have disconnected since request was issued,
1169 ignore (client will realize it once it processes the
1170 disconnect notification) */
1171 #if DEBUG_CORE_CLIENT
1172 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1173 "Dropped client request for transmission (am disconnected)\n");
1175 GNUNET_STATISTICS_update (stats,
1176 gettext_noop ("# send requests dropped (disconnected)"),
1179 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1183 while ( (c != NULL) &&
1184 (c->client_handle != client) )
1188 /* client did not send INIT first! */
1190 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1193 if (c->requests == NULL)
1194 c->requests = GNUNET_CONTAINER_multihashmap_create (16);
1195 #if DEBUG_CORE_CLIENT
1196 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1197 "Received client transmission request. queueing\n");
1199 car = GNUNET_CONTAINER_multihashmap_get (c->requests,
1200 &req->peer.hashPubKey);
1203 /* create new entry */
1204 car = GNUNET_malloc (sizeof (struct ClientActiveRequest));
1205 GNUNET_assert (GNUNET_OK ==
1206 GNUNET_CONTAINER_multihashmap_put (c->requests,
1207 &req->peer.hashPubKey,
1209 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1210 GNUNET_CONTAINER_DLL_insert (n->active_client_request_head,
1211 n->active_client_request_tail,
1215 car->deadline = GNUNET_TIME_absolute_ntoh (req->deadline);
1216 car->priority = ntohl (req->priority);
1217 car->queue_size = ntohl (req->queue_size);
1218 car->msize = ntohs (req->size);
1219 car->smr_id = req->smr_id;
1220 schedule_peer_messages (n);
1221 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1226 * Notify client about an existing connection to one of our neighbours.
1229 notify_client_about_neighbour (void *cls,
1230 const GNUNET_HashCode *key,
1233 struct Client *c = cls;
1234 struct Neighbour *n = value;
1236 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1237 struct GNUNET_TRANSPORT_ATS_Information *ats;
1238 struct ConnectNotifyMessage *cnm;
1240 size = sizeof (struct ConnectNotifyMessage) +
1241 (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1242 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1245 /* recovery strategy: throw away performance data */
1246 GNUNET_array_grow (n->ats,
1249 size = sizeof (struct ConnectNotifyMessage) +
1250 (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1252 cnm = (struct ConnectNotifyMessage*) buf;
1253 cnm->header.size = htons (size);
1254 cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1255 cnm->ats_count = htonl (n->ats_count);
1259 sizeof (struct GNUNET_TRANSPORT_ATS_Information) * n->ats_count);
1260 ats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
1261 ats[n->ats_count].value = htonl (0);
1262 if (n->status == PEER_STATE_KEY_CONFIRMED)
1264 #if DEBUG_CORE_CLIENT
1265 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1266 "Sending `%s' message to client.\n", "NOTIFY_CONNECT");
1268 cnm->peer = n->peer;
1269 send_to_client (c, &cnm->header, GNUNET_NO);
1277 * Handle CORE_INIT request.
1280 handle_client_init (void *cls,
1281 struct GNUNET_SERVER_Client *client,
1282 const struct GNUNET_MessageHeader *message)
1284 const struct InitMessage *im;
1285 struct InitReplyMessage irm;
1288 const uint16_t *types;
1292 #if DEBUG_CORE_CLIENT
1293 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1294 "Client connecting to core service with `%s' message\n",
1297 /* check that we don't have an entry already */
1301 if (client == c->client_handle)
1304 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1309 msize = ntohs (message->size);
1310 if (msize < sizeof (struct InitMessage))
1313 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1316 GNUNET_SERVER_notification_context_add (notifier, client);
1317 im = (const struct InitMessage *) message;
1318 types = (const uint16_t *) &im[1];
1319 msize -= sizeof (struct InitMessage);
1320 c = GNUNET_malloc (sizeof (struct Client) + msize);
1321 c->client_handle = client;
1324 c->tcnt = msize / sizeof (uint16_t);
1325 c->types = (const uint16_t *) &c[1];
1326 wtypes = (uint16_t *) &c[1];
1327 for (i=0;i<c->tcnt;i++)
1328 wtypes[i] = ntohs (types[i]);
1329 c->options = ntohl (im->options);
1330 #if DEBUG_CORE_CLIENT
1331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1332 "Client %p is interested in %u message types\n",
1334 (unsigned int) c->tcnt);
1336 /* send init reply message */
1337 irm.header.size = htons (sizeof (struct InitReplyMessage));
1338 irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
1339 irm.reserved = htonl (0);
1340 memcpy (&irm.publicKey,
1342 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1343 #if DEBUG_CORE_CLIENT
1344 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1345 "Sending `%s' message to client.\n", "INIT_REPLY");
1347 send_to_client (c, &irm.header, GNUNET_NO);
1348 if (0 != (c->options & GNUNET_CORE_OPTION_SEND_CONNECT))
1350 /* notify new client about existing neighbours */
1351 GNUNET_CONTAINER_multihashmap_iterate (neighbours,
1352 ¬ify_client_about_neighbour,
1355 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1360 * Free client request records.
1363 * @param key identity of peer for which this is an active request
1364 * @param value the 'struct ClientActiveRequest' to free
1365 * @return GNUNET_YES (continue iteration)
1368 destroy_active_client_request (void *cls,
1369 const GNUNET_HashCode *key,
1372 struct ClientActiveRequest *car = value;
1373 struct Neighbour *n;
1374 struct GNUNET_PeerIdentity peer;
1376 peer.hashPubKey = *key;
1377 n = find_neighbour (&peer);
1378 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1379 n->active_client_request_tail,
1387 * A client disconnected, clean up.
1389 * @param cls closure
1390 * @param client identification of the client
1393 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1396 struct Client *prev;
1400 #if DEBUG_CORE_CLIENT
1401 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1402 "Client %p has disconnected from core service.\n",
1409 if (client == pos->client_handle)
1416 /* client never sent INIT */
1420 clients = pos->next;
1422 prev->next = pos->next;
1423 if (pos->requests != NULL)
1425 GNUNET_CONTAINER_multihashmap_iterate (pos->requests,
1426 &destroy_active_client_request,
1428 GNUNET_CONTAINER_multihashmap_destroy (pos->requests);
1435 * Helper function for handle_client_iterate_peers.
1438 queue_connect_message (void *cls,
1439 const GNUNET_HashCode *key,
1442 struct GNUNET_SERVER_TransmitContext *tc = cls;
1443 struct Neighbour *n = value;
1444 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1445 struct GNUNET_TRANSPORT_ATS_Information *ats;
1447 struct ConnectNotifyMessage *cnm;
1449 cnm = (struct ConnectNotifyMessage*) buf;
1450 if (n->status != PEER_STATE_KEY_CONFIRMED)
1452 size = sizeof (struct ConnectNotifyMessage) +
1453 (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1454 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1457 /* recovery strategy: throw away performance data */
1458 GNUNET_array_grow (n->ats,
1461 size = sizeof (struct PeerStatusNotifyMessage) +
1462 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1464 cnm = (struct ConnectNotifyMessage*) buf;
1465 cnm->header.size = htons (size);
1466 cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1467 cnm->ats_count = htonl (n->ats_count);
1471 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
1472 ats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
1473 ats[n->ats_count].value = htonl (0);
1474 #if DEBUG_CORE_CLIENT
1475 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1476 "Sending `%s' message to client.\n",
1479 cnm->peer = n->peer;
1480 GNUNET_SERVER_transmit_context_append_message (tc,
1487 * Handle CORE_ITERATE_PEERS request.
1490 * @param client client sending the iteration request
1491 * @param message iteration request message
1494 handle_client_iterate_peers (void *cls,
1495 struct GNUNET_SERVER_Client *client,
1496 const struct GNUNET_MessageHeader *message)
1499 struct GNUNET_MessageHeader done_msg;
1500 struct GNUNET_SERVER_TransmitContext *tc;
1502 /* notify new client about existing neighbours */
1503 tc = GNUNET_SERVER_transmit_context_create (client);
1504 GNUNET_CONTAINER_multihashmap_iterate (neighbours, &queue_connect_message, tc);
1505 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
1506 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
1507 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
1508 GNUNET_SERVER_transmit_context_run (tc,
1509 GNUNET_TIME_UNIT_FOREVER_REL);
1514 * Handle REQUEST_INFO request.
1517 handle_client_request_info (void *cls,
1518 struct GNUNET_SERVER_Client *client,
1519 const struct GNUNET_MessageHeader *message)
1521 const struct RequestInfoMessage *rcm;
1523 struct Neighbour *n;
1524 struct ConfigurationInfoMessage cim;
1525 int32_t want_reserv;
1527 unsigned long long old_preference;
1529 #if DEBUG_CORE_CLIENT
1530 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1531 "Core service receives `%s' request.\n", "REQUEST_INFO");
1536 if (client == pos->client_handle)
1543 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1547 rcm = (const struct RequestInfoMessage *) message;
1548 n = find_neighbour (&rcm->peer);
1549 memset (&cim, 0, sizeof (cim));
1552 want_reserv = ntohl (rcm->reserve_inbound);
1553 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1555 n->bw_out_internal_limit = rcm->limit_outbound;
1556 if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1557 n->bw_out_external_limit).value__)
1559 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1560 n->bw_out_external_limit);
1561 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1563 GNUNET_TRANSPORT_set_quota (transport,
1567 GNUNET_TIME_UNIT_FOREVER_REL,
1569 handle_peer_status_change (n);
1572 if (want_reserv < 0)
1574 got_reserv = want_reserv;
1576 else if (want_reserv > 0)
1578 if (GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1579 want_reserv).rel_value == 0)
1580 got_reserv = want_reserv;
1582 got_reserv = 0; /* all or nothing */
1586 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1588 old_preference = n->current_preference;
1589 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1590 if (old_preference > n->current_preference)
1592 /* overflow; cap at maximum value */
1593 n->current_preference = ULLONG_MAX;
1595 update_preference_sum (n->current_preference - old_preference);
1596 #if DEBUG_CORE_QUOTA
1597 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1598 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes\n",
1600 GNUNET_i2s (&rcm->peer),
1603 cim.reserved_amount = htonl (got_reserv);
1604 cim.rim_id = rcm->rim_id;
1605 cim.bw_out = n->bw_out;
1606 cim.preference = n->current_preference;
1608 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1609 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1610 cim.peer = rcm->peer;
1611 #if DEBUG_CORE_CLIENT
1612 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1613 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1615 send_to_client (pos, &cim.header, GNUNET_NO);
1616 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1621 * Free the given entry for the neighbour (it has
1622 * already been removed from the list at this point).
1624 * @param n neighbour to free
1627 free_neighbour (struct Neighbour *n)
1629 struct MessageEntry *m;
1630 struct ClientActiveRequest *car;
1633 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1634 "Destroying neighbour entry for peer `%4s'\n",
1635 GNUNET_i2s (&n->peer));
1637 if (n->pitr != NULL)
1639 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1644 GNUNET_free (n->skm);
1647 while (NULL != (m = n->messages))
1649 n->messages = m->next;
1652 while (NULL != (m = n->encrypted_head))
1654 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1659 while (NULL != (car = n->active_client_request_head))
1661 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1662 n->active_client_request_tail,
1664 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
1665 &n->peer.hashPubKey,
1671 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1674 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1675 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
1676 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1677 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
1678 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1679 GNUNET_SCHEDULER_cancel (n->quota_update_task);
1680 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1681 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1682 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1683 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
1684 if (n->status == PEER_STATE_KEY_CONFIRMED)
1685 GNUNET_STATISTICS_update (stats,
1686 gettext_noop ("# established sessions"),
1689 GNUNET_array_grow (n->ats, n->ats_count, 0);
1690 GNUNET_free_non_null (n->public_key);
1691 GNUNET_free_non_null (n->pending_ping);
1692 GNUNET_free_non_null (n->pending_pong);
1698 * Check if we have encrypted messages for the specified neighbour
1699 * pending, and if so, check with the transport about sending them
1702 * @param n neighbour to check.
1704 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1708 * Encrypt size bytes from in and write the result to out. Use the
1709 * key for outbound traffic of the given neighbour.
1711 * @param n neighbour we are sending to
1712 * @param iv initialization vector to use
1713 * @param in ciphertext
1714 * @param out plaintext
1715 * @param size size of in/out
1716 * @return GNUNET_OK on success
1719 do_encrypt (struct Neighbour *n,
1720 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1721 const void *in, void *out, size_t size)
1723 if (size != (uint16_t) size)
1728 GNUNET_assert (size ==
1729 GNUNET_CRYPTO_aes_encrypt (in,
1733 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1735 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1736 "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
1737 (unsigned int) size,
1738 GNUNET_i2s (&n->peer),
1739 (unsigned int) n->encrypt_key.crc32,
1740 GNUNET_CRYPTO_crc32_n (iv, sizeof(iv)));
1747 * Consider freeing the given neighbour since we may not need
1748 * to keep it around anymore.
1750 * @param n neighbour to consider discarding
1753 consider_free_neighbour (struct Neighbour *n);
1757 * Task triggered when a neighbour entry is about to time out
1758 * (and we should prevent this by sending a PING).
1760 * @param cls the 'struct Neighbour'
1761 * @param tc scheduler context (not used)
1764 send_keep_alive (void *cls,
1765 const struct GNUNET_SCHEDULER_TaskContext *tc)
1767 struct Neighbour *n = cls;
1768 struct GNUNET_TIME_Relative retry;
1769 struct GNUNET_TIME_Relative left;
1770 struct MessageEntry *me;
1771 struct PingMessage pp;
1772 struct PingMessage *pm;
1773 struct GNUNET_CRYPTO_AesInitializationVector iv;
1775 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1777 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1778 sizeof (struct PingMessage));
1779 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1780 me->priority = PING_PRIORITY;
1781 me->size = sizeof (struct PingMessage);
1782 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1786 pm = (struct PingMessage *) &me[1];
1787 pm->header.size = htons (sizeof (struct PingMessage));
1788 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1789 pm->iv_seed = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1791 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
1792 pp.challenge = n->ping_challenge;
1793 pp.target = n->peer;
1795 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1796 "Encrypting `%s' message with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
1798 (unsigned int) n->ping_challenge,
1799 GNUNET_i2s (&n->peer),
1800 (unsigned int) n->encrypt_key.crc32,
1801 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
1808 sizeof (struct PingMessage) -
1809 ((void *) &pm->target - (void *) pm));
1810 process_encrypted_neighbour_queue (n);
1811 /* reschedule PING job */
1812 left = GNUNET_TIME_absolute_get_remaining (get_neighbour_timeout (n));
1813 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1814 MIN_PING_FREQUENCY);
1816 = GNUNET_SCHEDULER_add_delayed (retry,
1824 * Task triggered when a neighbour entry might have gotten stale.
1826 * @param cls the 'struct Neighbour'
1827 * @param tc scheduler context (not used)
1830 consider_free_task (void *cls,
1831 const struct GNUNET_SCHEDULER_TaskContext *tc)
1833 struct Neighbour *n = cls;
1835 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1836 consider_free_neighbour (n);
1841 * Consider freeing the given neighbour since we may not need
1842 * to keep it around anymore.
1844 * @param n neighbour to consider discarding
1847 consider_free_neighbour (struct Neighbour *n)
1849 struct GNUNET_TIME_Relative left;
1851 if ( (n->th != NULL) ||
1852 (n->pitr != NULL) ||
1853 (GNUNET_YES == n->is_connected) )
1854 return; /* no chance */
1856 left = GNUNET_TIME_absolute_get_remaining (get_neighbour_timeout (n));
1857 if (left.rel_value > 0)
1859 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1860 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1861 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (left,
1862 &consider_free_task,
1866 /* actually free the neighbour... */
1867 GNUNET_assert (GNUNET_OK ==
1868 GNUNET_CONTAINER_multihashmap_remove (neighbours,
1869 &n->peer.hashPubKey,
1871 GNUNET_STATISTICS_set (stats,
1872 gettext_noop ("# neighbour entries allocated"),
1873 GNUNET_CONTAINER_multihashmap_size (neighbours),
1880 * Function called when the transport service is ready to
1881 * receive an encrypted message for the respective peer
1883 * @param cls neighbour to use message from
1884 * @param size number of bytes we can transmit
1885 * @param buf where to copy the message
1886 * @return number of bytes transmitted
1889 notify_encrypted_transmit_ready (void *cls,
1893 struct Neighbour *n = cls;
1894 struct MessageEntry *m;
1899 m = n->encrypted_head;
1903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1904 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1905 GNUNET_i2s (&n->peer));
1909 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1916 GNUNET_assert (size >= m->size);
1917 memcpy (cbuf, &m[1], m->size);
1919 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1922 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1923 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1924 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1926 GNUNET_i2s (&n->peer));
1928 process_encrypted_neighbour_queue (n);
1933 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1934 "Transmission of message of type %u and size %u failed\n",
1935 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1936 (unsigned int) m->size);
1940 consider_free_neighbour (n);
1941 GNUNET_STATISTICS_update (stats,
1942 gettext_noop ("# encrypted bytes given to transport"),
1950 * Check if we have plaintext messages for the specified neighbour
1951 * pending, and if so, consider batching and encrypting them (and
1952 * then trigger processing of the encrypted queue if needed).
1954 * @param n neighbour to check.
1956 static void process_plaintext_neighbour_queue (struct Neighbour *n);
1960 * Check if we have encrypted messages for the specified neighbour
1961 * pending, and if so, check with the transport about sending them
1964 * @param n neighbour to check.
1967 process_encrypted_neighbour_queue (struct Neighbour *n)
1969 struct MessageEntry *m;
1972 return; /* request already pending */
1973 m = n->encrypted_head;
1976 /* encrypted queue empty, try plaintext instead */
1977 process_plaintext_neighbour_queue (n);
1981 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1982 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
1983 (unsigned int) m->size,
1984 GNUNET_i2s (&n->peer),
1985 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).rel_value);
1988 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
1991 GNUNET_TIME_absolute_get_remaining
1993 ¬ify_encrypted_transmit_ready,
1997 /* message request too large or duplicate request */
1999 /* discard encrypted message */
2000 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2004 process_encrypted_neighbour_queue (n);
2010 * Decrypt size bytes from in and write the result to out. Use the
2011 * key for inbound traffic of the given neighbour. This function does
2012 * NOT do any integrity-checks on the result.
2014 * @param n neighbour we are receiving from
2015 * @param iv initialization vector to use
2016 * @param in ciphertext
2017 * @param out plaintext
2018 * @param size size of in/out
2019 * @return GNUNET_OK on success
2022 do_decrypt (struct Neighbour *n,
2023 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
2024 const void *in, void *out, size_t size)
2026 if (size != (uint16_t) size)
2031 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2032 (n->status != PEER_STATE_KEY_CONFIRMED))
2034 GNUNET_break_op (0);
2035 return GNUNET_SYSERR;
2038 GNUNET_CRYPTO_aes_decrypt (in,
2045 return GNUNET_SYSERR;
2047 GNUNET_STATISTICS_update (stats,
2048 gettext_noop ("# bytes decrypted"),
2052 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2053 "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
2054 (unsigned int) size,
2055 GNUNET_i2s (&n->peer),
2056 (unsigned int) n->decrypt_key.crc32,
2057 GNUNET_CRYPTO_crc32_n (iv, sizeof(*iv)));
2064 * Select messages for transmission. This heuristic uses a combination
2065 * of earliest deadline first (EDF) scheduling (with bounded horizon)
2066 * and priority-based discard (in case no feasible schedule exist) and
2067 * speculative optimization (defer any kind of transmission until
2068 * we either create a batch of significant size, 25% of max, or until
2069 * we are close to a deadline). Furthermore, when scheduling the
2070 * heuristic also packs as many messages into the batch as possible,
2071 * starting with those with the earliest deadline. Yes, this is fun.
2073 * @param n neighbour to select messages from
2074 * @param size number of bytes to select for transmission
2075 * @param retry_time set to the time when we should try again
2076 * (only valid if this function returns zero)
2077 * @return number of bytes selected, or 0 if we decided to
2078 * defer scheduling overall; in that case, retry_time is set.
2081 select_messages (struct Neighbour *n,
2082 size_t size, struct GNUNET_TIME_Relative *retry_time)
2084 struct MessageEntry *pos;
2085 struct MessageEntry *min;
2086 struct MessageEntry *last;
2087 unsigned int min_prio;
2088 struct GNUNET_TIME_Absolute t;
2089 struct GNUNET_TIME_Absolute now;
2090 struct GNUNET_TIME_Relative delta;
2092 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
2095 unsigned int queue_size;
2096 int discard_low_prio;
2098 GNUNET_assert (NULL != n->messages);
2099 now = GNUNET_TIME_absolute_get ();
2100 /* last entry in linked list of messages processed */
2102 /* should we remove the entry with the lowest
2103 priority from consideration for scheduling at the
2114 discard_low_prio = GNUNET_YES;
2115 while (GNUNET_YES == discard_low_prio)
2118 min_prio = UINT_MAX;
2119 discard_low_prio = GNUNET_NO;
2120 /* calculate number of bytes available for transmission at time "t" */
2121 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
2123 /* how many bytes have we (hypothetically) scheduled so far */
2125 /* maximum time we can wait before transmitting anything
2126 and still make all of our deadlines */
2127 slack = GNUNET_TIME_UNIT_FOREVER_REL;
2129 /* note that we use "*2" here because we want to look
2130 a bit further into the future; much more makes no
2131 sense since new message might be scheduled in the
2133 while ((pos != NULL) && (off < size * 2))
2135 if (pos->do_transmit == GNUNET_YES)
2137 /* already removed from consideration */
2141 if (discard_low_prio == GNUNET_NO)
2143 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
2144 if (delta.rel_value > 0)
2146 // FIXME: HUH? Check!
2148 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
2151 if (avail < pos->size)
2153 // FIXME: HUH? Check!
2154 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
2159 /* update slack, considering both its absolute deadline
2160 and relative deadlines caused by other messages
2161 with their respective load */
2162 slack = GNUNET_TIME_relative_min (slack,
2163 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
2165 if (pos->deadline.abs_value <= now.abs_value)
2168 slack = GNUNET_TIME_UNIT_ZERO;
2170 else if (GNUNET_YES == pos->got_slack)
2172 /* should be soon now! */
2173 slack = GNUNET_TIME_relative_min (slack,
2174 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
2179 GNUNET_TIME_relative_min (slack,
2180 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
2181 pos->got_slack = GNUNET_YES;
2182 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
2183 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
2188 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
2189 if (pos->priority <= min_prio)
2191 /* update min for discard */
2192 min_prio = pos->priority;
2197 if (discard_low_prio)
2199 GNUNET_assert (min != NULL);
2200 /* remove lowest-priority entry from consideration */
2201 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
2205 /* guard against sending "tiny" messages with large headers without
2207 if ( (slack.rel_value > GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value) &&
2209 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
2211 /* less than 25% of message would be filled with deadlines still
2212 being met if we delay by one second or more; so just wait for
2213 more data; but do not wait longer than 1s (since we don't want
2214 to delay messages for a really long time either). */
2215 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
2216 /* reset do_transmit values for next time */
2219 pos->do_transmit = GNUNET_NO;
2222 GNUNET_STATISTICS_update (stats,
2223 gettext_noop ("# transmissions delayed due to corking"),
2226 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2227 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
2228 (unsigned long long) retry_time->rel_value,
2230 (unsigned int) size);
2234 /* select marked messages (up to size) for transmission */
2239 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
2241 pos->do_transmit = GNUNET_YES; /* mark for transmission */
2245 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2246 "Selecting message of size %u for transmission\n",
2247 (unsigned int) pos->size);
2253 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2254 "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
2255 (unsigned int) pos->size,
2258 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
2263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2264 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
2265 (unsigned long long) off, (unsigned long long) tsize,
2266 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
2267 GNUNET_i2s (&n->peer));
2274 * Batch multiple messages into a larger buffer.
2276 * @param n neighbour to take messages from
2277 * @param buf target buffer
2278 * @param size size of buf
2279 * @param deadline set to transmission deadline for the result
2280 * @param retry_time set to the time when we should try again
2281 * (only valid if this function returns zero)
2282 * @param priority set to the priority of the batch
2283 * @return number of bytes written to buf (can be zero)
2286 batch_message (struct Neighbour *n,
2289 struct GNUNET_TIME_Absolute *deadline,
2290 struct GNUNET_TIME_Relative *retry_time,
2291 unsigned int *priority)
2293 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
2294 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
2295 struct MessageEntry *pos;
2296 struct MessageEntry *prev;
2297 struct MessageEntry *next;
2302 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2303 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
2304 if (0 == select_messages (n, size, retry_time))
2307 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2308 "No messages selected, will try again in %llu ms\n",
2309 retry_time->rel_value);
2313 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
2314 ntm->ats_count = htonl (0);
2315 ntm->ats.type = htonl (0);
2316 ntm->ats.value = htonl (0);
2317 ntm->peer = n->peer;
2320 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
2323 if (GNUNET_YES == pos->do_transmit)
2325 GNUNET_assert (pos->size <= size);
2326 /* do notifications */
2327 /* FIXME: track if we have *any* client that wants
2328 full notifications and only do this if that is
2330 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
2332 memcpy (&ntm[1], &pos[1], pos->size);
2333 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
2334 sizeof (struct GNUNET_MessageHeader));
2335 send_to_all_clients (&ntm->header,
2337 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
2341 /* message too large for 'full' notifications, we do at
2342 least the 'hdr' type */
2345 sizeof (struct GNUNET_MessageHeader));
2347 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
2349 send_to_all_clients (&ntm->header,
2351 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
2353 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2354 "Encrypting %u bytes with message of type %u and size %u\n",
2356 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
2357 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
2359 /* copy for encrypted transmission */
2360 memcpy (&buf[ret], &pos[1], pos->size);
2363 *priority += pos->priority;
2365 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2366 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
2367 (unsigned int) pos->size,
2368 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).rel_value);
2370 deadline->abs_value = GNUNET_MIN (deadline->abs_value, pos->deadline.abs_value);
2384 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2385 "Deadline for message batch is %llu ms\n",
2386 GNUNET_TIME_absolute_get_remaining (*deadline).rel_value);
2393 * Remove messages with deadlines that have long expired from
2396 * @param n neighbour to inspect
2399 discard_expired_messages (struct Neighbour *n)
2401 struct MessageEntry *prev;
2402 struct MessageEntry *next;
2403 struct MessageEntry *pos;
2404 struct GNUNET_TIME_Absolute now;
2405 struct GNUNET_TIME_Relative delta;
2409 now = GNUNET_TIME_absolute_get ();
2415 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
2416 if (delta.rel_value > PAST_EXPIRATION_DISCARD_TIME.rel_value)
2419 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2420 "Message is %llu ms past due, discarding.\n",
2427 GNUNET_STATISTICS_update (stats,
2428 gettext_noop ("# messages discarded (expired prior to transmission)"),
2438 if (GNUNET_YES == disc)
2439 schedule_peer_messages (n);
2444 * Signature of the main function of a task.
2446 * @param cls closure
2447 * @param tc context information (why was this task triggered now)
2450 retry_plaintext_processing (void *cls,
2451 const struct GNUNET_SCHEDULER_TaskContext *tc)
2453 struct Neighbour *n = cls;
2455 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2456 process_plaintext_neighbour_queue (n);
2461 * Send our key (and encrypted PING) to the other peer.
2463 * @param n the other peer
2465 static void send_key (struct Neighbour *n);
2468 * Task that will retry "send_key" if our previous attempt failed
2472 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2474 struct Neighbour *n = cls;
2477 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2478 "Retrying key transmission to `%4s'\n",
2479 GNUNET_i2s (&n->peer));
2481 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2482 n->set_key_retry_frequency =
2483 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2489 * Check if we have plaintext messages for the specified neighbour
2490 * pending, and if so, consider batching and encrypting them (and
2491 * then trigger processing of the encrypted queue if needed).
2493 * @param n neighbour to check.
2496 process_plaintext_neighbour_queue (struct Neighbour *n)
2498 char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)]; /* plaintext */
2500 struct EncryptedMessage *em; /* encrypted message */
2501 struct EncryptedMessage *ph; /* plaintext header */
2502 struct MessageEntry *me;
2503 unsigned int priority;
2504 struct GNUNET_TIME_Absolute deadline;
2505 struct GNUNET_TIME_Relative retry_time;
2506 struct GNUNET_CRYPTO_AesInitializationVector iv;
2507 struct GNUNET_CRYPTO_AuthKey auth_key;
2509 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2511 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
2512 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2516 case PEER_STATE_DOWN:
2519 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2520 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2521 GNUNET_i2s(&n->peer));
2524 case PEER_STATE_KEY_SENT:
2525 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2526 n->retry_set_key_task
2527 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2528 &set_key_retry_task, n);
2530 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2531 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2532 GNUNET_i2s(&n->peer));
2535 case PEER_STATE_KEY_RECEIVED:
2536 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2537 n->retry_set_key_task
2538 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2539 &set_key_retry_task, n);
2541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2542 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2543 GNUNET_i2s(&n->peer));
2546 case PEER_STATE_KEY_CONFIRMED:
2547 /* ready to continue */
2550 discard_expired_messages (n);
2551 if (n->messages == NULL)
2554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2555 "Plaintext message queue for `%4s' is empty.\n",
2556 GNUNET_i2s(&n->peer));
2558 return; /* no pending messages */
2560 if (n->encrypted_head != NULL)
2563 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2564 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2565 GNUNET_i2s(&n->peer));
2567 return; /* wait for messages already encrypted to be
2570 ph = (struct EncryptedMessage *) pbuf;
2571 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2573 used = sizeof (struct EncryptedMessage);
2574 used += batch_message (n,
2576 GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2577 &deadline, &retry_time, &priority);
2578 if (used == sizeof (struct EncryptedMessage))
2581 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2582 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2583 GNUNET_i2s(&n->peer));
2585 /* no messages selected for sending, try again later... */
2586 n->retry_plaintext_task =
2587 GNUNET_SCHEDULER_add_delayed (retry_time,
2588 &retry_plaintext_processing, n);
2591 #if DEBUG_CORE_QUOTA
2592 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2593 "Sending %u b/s as new limit to peer `%4s'\n",
2594 (unsigned int) ntohl (n->bw_in.value__),
2595 GNUNET_i2s (&n->peer));
2597 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
2598 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2599 ph->inbound_bw_limit = n->bw_in;
2600 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2602 /* setup encryption message header */
2603 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2604 me->deadline = deadline;
2605 me->priority = priority;
2607 em = (struct EncryptedMessage *) &me[1];
2608 em->header.size = htons (used);
2609 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2610 em->iv_seed = ph->iv_seed;
2611 derive_iv (&iv, &n->encrypt_key, ph->iv_seed, &n->peer);
2614 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2615 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2616 (unsigned int) used - ENCRYPTED_HEADER_SIZE,
2617 GNUNET_i2s(&n->peer),
2618 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).rel_value);
2620 GNUNET_assert (GNUNET_OK ==
2623 &ph->sequence_number,
2624 &em->sequence_number, used - ENCRYPTED_HEADER_SIZE));
2625 derive_auth_key (&auth_key,
2628 n->encrypt_key_created);
2629 GNUNET_CRYPTO_hmac (&auth_key,
2630 &em->sequence_number,
2631 used - ENCRYPTED_HEADER_SIZE,
2634 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2635 "Authenticated %u bytes of ciphertext %u: `%s'\n",
2636 used - ENCRYPTED_HEADER_SIZE,
2637 GNUNET_CRYPTO_crc32_n (&em->sequence_number,
2638 used - ENCRYPTED_HEADER_SIZE),
2639 GNUNET_h2s (&em->hmac));
2641 /* append to transmission list */
2642 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2646 process_encrypted_neighbour_queue (n);
2647 schedule_peer_messages (n);
2652 * Function that recalculates the bandwidth quota for the
2653 * given neighbour and transmits it to the transport service.
2655 * @param cls neighbour for the quota update
2659 neighbour_quota_update (void *cls,
2660 const struct GNUNET_SCHEDULER_TaskContext *tc);
2664 * Schedule the task that will recalculate the bandwidth
2665 * quota for this peer (and possibly force a disconnect of
2666 * idle peers by calculating a bandwidth of zero).
2669 schedule_quota_update (struct Neighbour *n)
2671 GNUNET_assert (n->quota_update_task ==
2672 GNUNET_SCHEDULER_NO_TASK);
2673 n->quota_update_task
2674 = GNUNET_SCHEDULER_add_delayed (QUOTA_UPDATE_FREQUENCY,
2675 &neighbour_quota_update,
2681 * Initialize a new 'struct Neighbour'.
2683 * @param pid ID of the new neighbour
2684 * @return handle for the new neighbour
2686 static struct Neighbour *
2687 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2689 struct Neighbour *n;
2690 struct GNUNET_TIME_Absolute now;
2693 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2694 "Creating neighbour entry for peer `%4s'\n",
2697 n = GNUNET_malloc (sizeof (struct Neighbour));
2699 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2700 now = GNUNET_TIME_absolute_get ();
2701 n->encrypt_key_created = now;
2702 n->last_activity = now;
2703 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2704 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2705 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2706 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2707 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2708 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
2710 GNUNET_assert (GNUNET_OK ==
2711 GNUNET_CONTAINER_multihashmap_put (neighbours,
2712 &n->peer.hashPubKey,
2714 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2715 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"),
2716 GNUNET_CONTAINER_multihashmap_size (neighbours), GNUNET_NO);
2717 neighbour_quota_update (n, NULL);
2718 consider_free_neighbour (n);
2724 * Handle CORE_SEND request.
2727 * @param client the client issuing the request
2728 * @param message the "struct SendMessage"
2731 handle_client_send (void *cls,
2732 struct GNUNET_SERVER_Client *client,
2733 const struct GNUNET_MessageHeader *message)
2735 const struct SendMessage *sm;
2736 struct Neighbour *n;
2737 struct MessageEntry *prev;
2738 struct MessageEntry *pos;
2739 struct MessageEntry *e;
2740 struct MessageEntry *min_prio_entry;
2741 struct MessageEntry *min_prio_prev;
2742 unsigned int min_prio;
2743 unsigned int queue_size;
2746 msize = ntohs (message->size);
2748 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2750 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "about to assert fail, msize is %d, should be at least %d\n", msize, sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader));
2753 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2756 sm = (const struct SendMessage *) message;
2757 msize -= sizeof (struct SendMessage);
2758 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2761 GNUNET_SERVER_mst_receive (mst,
2763 (const char*) &sm[1],
2768 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2771 n = find_neighbour (&sm->peer);
2773 n = create_neighbour (&sm->peer);
2775 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2776 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2778 (unsigned int) msize,
2779 GNUNET_i2s (&sm->peer));
2781 discard_expired_messages (n);
2782 /* bound queue size */
2783 /* NOTE: this entire block to bound the queue size should be
2784 obsolete with the new client-request code and the
2785 'schedule_peer_messages' mechanism; we still have this code in
2786 here for now as a sanity check for the new mechanmism;
2787 ultimately, we should probably simply reject SEND messages that
2788 are not 'approved' (or provide a new core API for very unreliable
2789 delivery that always sends with priority 0). Food for thought. */
2790 min_prio = UINT32_MAX;
2791 min_prio_entry = NULL;
2792 min_prio_prev = NULL;
2798 if (pos->priority <= min_prio)
2800 min_prio_entry = pos;
2801 min_prio_prev = prev;
2802 min_prio = pos->priority;
2808 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2811 if (ntohl(sm->priority) <= min_prio)
2813 /* discard new entry; this should no longer happen! */
2816 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2817 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2819 (unsigned int) MAX_PEER_QUEUE_SIZE,
2820 (unsigned int) msize,
2821 (unsigned int) ntohs (message->type));
2823 GNUNET_STATISTICS_update (stats,
2824 gettext_noop ("# discarded CORE_SEND requests"),
2828 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2831 GNUNET_assert (min_prio_entry != NULL);
2832 /* discard "min_prio_entry" */
2834 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2835 "Queue full, discarding existing older request\n");
2837 GNUNET_STATISTICS_update (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 1, GNUNET_NO);
2838 if (min_prio_prev == NULL)
2839 n->messages = min_prio_entry->next;
2841 min_prio_prev->next = min_prio_entry->next;
2842 GNUNET_free (min_prio_entry);
2846 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2847 "Adding transmission request for `%4s' of size %u to queue\n",
2848 GNUNET_i2s (&sm->peer),
2849 (unsigned int) msize);
2851 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2852 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2853 e->priority = ntohl (sm->priority);
2855 memcpy (&e[1], &sm[1], msize);
2857 /* insert, keep list sorted by deadline */
2860 while ((pos != NULL) && (pos->deadline.abs_value < e->deadline.abs_value))
2871 /* consider scheduling now */
2872 process_plaintext_neighbour_queue (n);
2874 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2879 * Function called when the transport service is ready to
2880 * receive a message. Only resets 'n->th' to NULL.
2882 * @param cls neighbour to use message from
2883 * @param size number of bytes we can transmit
2884 * @param buf where to copy the message
2885 * @return number of bytes transmitted
2888 notify_transport_connect_done (void *cls,
2892 struct Neighbour *n = cls;
2895 if (GNUNET_YES != n->is_connected)
2897 /* transport should only call us to transmit a message after
2898 * telling us about a successful connection to the respective peer */
2900 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2901 "Timeout on notify connect!\n");
2903 GNUNET_STATISTICS_update (stats,
2904 gettext_noop ("# connection requests timed out in transport"),
2911 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2912 _("Failed to connect to `%4s': transport failed to connect\n"),
2913 GNUNET_i2s (&n->peer));
2916 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2917 _("TRANSPORT connection to peer `%4s' is up, trying to establish CORE connection\n"),
2918 GNUNET_i2s (&n->peer));
2919 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
2920 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
2921 n->retry_set_key_task = GNUNET_SCHEDULER_add_now (&set_key_retry_task,
2928 * Handle CORE_REQUEST_CONNECT request.
2931 * @param client the client issuing the request
2932 * @param message the "struct ConnectMessage"
2935 handle_client_request_connect (void *cls,
2936 struct GNUNET_SERVER_Client *client,
2937 const struct GNUNET_MessageHeader *message)
2939 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2940 struct Neighbour *n;
2941 struct GNUNET_TIME_Relative timeout;
2943 if (0 == memcmp (&cm->peer,
2945 sizeof (struct GNUNET_PeerIdentity)))
2948 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2951 GNUNET_break (ntohl (cm->reserved) == 0);
2952 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2953 n = find_neighbour (&cm->peer);
2955 n = create_neighbour (&cm->peer);
2956 if ( (GNUNET_YES == n->is_connected) ||
2959 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2960 "Core received `%s' request for `%4s', already connected!\n",
2962 GNUNET_i2s (&cm->peer));
2963 if (GNUNET_YES == n->is_connected)
2964 GNUNET_STATISTICS_update (stats,
2965 gettext_noop ("# connection requests ignored (already connected)"),
2969 GNUNET_STATISTICS_update (stats,
2970 gettext_noop ("# connection requests ignored (already trying)"),
2973 return; /* already connected, or at least trying */
2975 GNUNET_STATISTICS_update (stats,
2976 gettext_noop ("# connection requests received"),
2980 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2981 "Core received `%s' request for `%4s', will try to establish connection\n",
2983 GNUNET_i2s (&cm->peer));
2985 timeout = GNUNET_TIME_relative_ntoh (cm->timeout);
2986 /* ask transport to connect to the peer */
2987 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
2989 sizeof (struct GNUNET_MessageHeader), 0,
2991 ¬ify_transport_connect_done,
2993 GNUNET_break (NULL != n->th);
2998 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2999 * the neighbour's struct and retry send_key. Or, if we did not get a
3000 * HELLO, just do nothing.
3002 * @param cls the 'struct Neighbour' to retry sending the key for
3003 * @param peer the peer for which this is the HELLO
3004 * @param hello HELLO message of that peer
3007 process_hello_retry_send_key (void *cls,
3008 const struct GNUNET_PeerIdentity *peer,
3009 const struct GNUNET_HELLO_Message *hello)
3011 struct Neighbour *n = cls;
3016 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3017 "Entered `%s' and `%s' is NULL!\n",
3018 "process_hello_retry_send_key",
3022 if (n->public_key != NULL)
3024 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3026 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3027 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3029 GNUNET_STATISTICS_update (stats,
3030 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3038 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3039 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
3040 GNUNET_i2s (&n->peer));
3042 GNUNET_STATISTICS_update (stats,
3043 gettext_noop ("# Delayed connecting due to lack of public key"),
3046 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
3047 n->retry_set_key_task
3048 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3049 &set_key_retry_task, n);
3055 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3056 "Entered `%s' for peer `%4s'\n",
3057 "process_hello_retry_send_key",
3060 if (n->public_key != NULL)
3062 /* already have public key, why are we here? */
3068 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3069 "Received new `%s' message for `%4s', initiating key exchange.\n",
3074 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3075 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3077 GNUNET_STATISTICS_update (stats,
3078 gettext_noop ("# Error extracting public key from HELLO"),
3081 GNUNET_free (n->public_key);
3082 n->public_key = NULL;
3084 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3085 "GNUNET_HELLO_get_key returned awfully\n");
3093 * Send our key (and encrypted PING) to the other peer.
3095 * @param n the other peer
3098 send_key (struct Neighbour *n)
3100 struct MessageEntry *pos;
3101 struct SetKeyMessage *sm;
3102 struct MessageEntry *me;
3103 struct PingMessage pp;
3104 struct PingMessage *pm;
3105 struct GNUNET_CRYPTO_AesInitializationVector iv;
3107 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3109 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3110 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3112 if (n->pitr != NULL)
3115 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3116 "Key exchange in progress with `%4s'.\n",
3117 GNUNET_i2s (&n->peer));
3119 return; /* already in progress */
3121 if (GNUNET_YES != n->is_connected)
3124 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3125 "Not yet connected to peer `%4s'!\n",
3126 GNUNET_i2s (&n->peer));
3130 GNUNET_STATISTICS_update (stats,
3131 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
3134 n->th = GNUNET_TRANSPORT_notify_transmit_ready (transport,
3136 sizeof (struct SetKeyMessage) + sizeof (struct PingMessage),
3138 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3139 ¬ify_encrypted_transmit_ready,
3145 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3146 "Asked to perform key exchange with `%4s'.\n",
3147 GNUNET_i2s (&n->peer));
3149 if (n->public_key == NULL)
3151 /* lookup n's public key, then try again */
3153 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3154 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
3155 GNUNET_i2s (&n->peer));
3157 GNUNET_assert (n->pitr == NULL);
3158 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3160 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
3161 &process_hello_retry_send_key, n);
3164 pos = n->encrypted_head;
3167 if (GNUNET_YES == pos->is_setkey)
3169 if (pos->sender_status == n->status)
3172 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3173 "`%s' message for `%4s' queued already\n",
3175 GNUNET_i2s (&n->peer));
3177 goto trigger_processing;
3179 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
3184 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3185 "Removing queued `%s' message for `%4s', will create a new one\n",
3187 GNUNET_i2s (&n->peer));
3197 case PEER_STATE_DOWN:
3198 n->status = PEER_STATE_KEY_SENT;
3200 case PEER_STATE_KEY_SENT:
3202 case PEER_STATE_KEY_RECEIVED:
3204 case PEER_STATE_KEY_CONFIRMED:
3212 /* first, set key message */
3213 me = GNUNET_malloc (sizeof (struct MessageEntry) +
3214 sizeof (struct SetKeyMessage) +
3215 sizeof (struct PingMessage));
3216 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
3217 me->priority = SET_KEY_PRIORITY;
3218 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
3219 me->is_setkey = GNUNET_YES;
3220 me->got_slack = GNUNET_YES; /* do not defer this one! */
3221 me->sender_status = n->status;
3222 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3226 sm = (struct SetKeyMessage *) &me[1];
3227 sm->header.size = htons (sizeof (struct SetKeyMessage));
3228 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
3229 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
3230 PEER_STATE_KEY_SENT : n->status));
3232 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3233 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3234 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3235 sizeof (struct GNUNET_PeerIdentity));
3236 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
3237 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
3238 sm->target = n->peer;
3239 GNUNET_assert (GNUNET_OK ==
3240 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
3242 GNUNET_CRYPTO_AesSessionKey),
3244 &sm->encrypted_key));
3245 GNUNET_assert (GNUNET_OK ==
3246 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
3248 pm = (struct PingMessage *) &sm[1];
3249 pm->header.size = htons (sizeof (struct PingMessage));
3250 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
3251 pm->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3252 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
3253 pp.challenge = n->ping_challenge;
3254 pp.target = n->peer;
3256 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3257 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
3259 (unsigned int) n->ping_challenge,
3260 GNUNET_i2s (&n->peer),
3261 (unsigned int) n->encrypt_key.crc32,
3262 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3269 sizeof (struct PingMessage) -
3270 ((void *) &pm->target - (void *) pm));
3271 GNUNET_STATISTICS_update (stats,
3272 gettext_noop ("# SET_KEY and PING messages created"),
3276 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3277 "Have %llu ms left for `%s' transmission.\n",
3278 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).rel_value,
3282 /* trigger queue processing */
3283 process_encrypted_neighbour_queue (n);
3284 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
3285 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
3286 n->retry_set_key_task
3287 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3288 &set_key_retry_task, n);
3293 * We received a SET_KEY message. Validate and update
3294 * our key material and status.
3296 * @param n the neighbour from which we received message m
3297 * @param m the set key message we received
3298 * @param ats performance data
3299 * @param ats_count number of entries in ats (excluding 0-termination)
3302 handle_set_key (struct Neighbour *n,
3303 const struct SetKeyMessage *m,
3304 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3305 uint32_t ats_count);
3310 * PEERINFO is giving us a HELLO for a peer. Add the public key to
3311 * the neighbour's struct and retry handling the set_key message. Or,
3312 * if we did not get a HELLO, just free the set key message.
3314 * @param cls pointer to the set key message
3315 * @param peer the peer for which this is the HELLO
3316 * @param hello HELLO message of that peer
3319 process_hello_retry_handle_set_key (void *cls,
3320 const struct GNUNET_PeerIdentity *peer,
3321 const struct GNUNET_HELLO_Message *hello)
3323 struct Neighbour *n = cls;
3324 struct SetKeyMessage *sm = n->skm;
3330 if (n->public_key != NULL)
3333 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3334 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
3336 GNUNET_i2s (&n->peer),
3339 handle_set_key (n, sm, NULL, 0);
3343 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3344 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
3346 GNUNET_i2s (&n->peer));
3351 if (n->public_key != NULL)
3352 return; /* multiple HELLOs match!? */
3354 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3355 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3357 GNUNET_break_op (0);
3358 GNUNET_free (n->public_key);
3359 n->public_key = NULL;
3365 * Merge the given performance data with the data we currently
3366 * track for the given neighbour.
3368 * @param n neighbour
3369 * @param ats new performance data
3370 * @param ats_count number of records in ats
3373 update_neighbour_performance (struct Neighbour *n,
3374 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3382 for (i = 0; i < ats_count; i++)
3384 for (j=0;j < n->ats_count; j++)
3386 if (n->ats[j].type == ats[i].type)
3388 n->ats[j].value = ats[i].value;
3392 if (j == n->ats_count)
3394 GNUNET_array_append (n->ats,
3403 * We received a PING message. Validate and transmit
3406 * @param n sender of the PING
3407 * @param m the encrypted PING message itself
3408 * @param ats performance data
3409 * @param ats_count number of entries in ats (excluding 0-termination)
3412 handle_ping (struct Neighbour *n,
3413 const struct PingMessage *m,
3414 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3417 struct PingMessage t;
3418 struct PongMessage tx;
3419 struct PongMessage *tp;
3420 struct MessageEntry *me;
3421 struct GNUNET_CRYPTO_AesInitializationVector iv;
3424 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3425 "Core service receives `%s' request from `%4s'.\n",
3426 "PING", GNUNET_i2s (&n->peer));
3428 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3434 sizeof (struct PingMessage) -
3435 ((void *) &m->target - (void *) m)))
3438 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3439 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u, IV %u (salt %u)\n",
3441 GNUNET_i2s (&t.target),
3442 (unsigned int) t.challenge,
3443 (unsigned int) n->decrypt_key.crc32,
3444 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3447 GNUNET_STATISTICS_update (stats,
3448 gettext_noop ("# PING messages decrypted"),
3451 if (0 != memcmp (&t.target,
3452 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3454 GNUNET_break_op (0);
3457 update_neighbour_performance (n, ats, ats_count);
3458 me = GNUNET_malloc (sizeof (struct MessageEntry) +
3459 sizeof (struct PongMessage));
3460 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3464 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
3465 me->priority = PONG_PRIORITY;
3466 me->size = sizeof (struct PongMessage);
3467 tx.inbound_bw_limit = n->bw_in;
3468 tx.challenge = t.challenge;
3469 tx.target = t.target;
3470 tp = (struct PongMessage *) &me[1];
3471 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
3472 tp->header.size = htons (sizeof (struct PongMessage));
3473 tp->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3474 derive_pong_iv (&iv, &n->encrypt_key, tp->iv_seed, t.challenge, &n->peer);
3479 sizeof (struct PongMessage) -
3480 ((void *) &tp->challenge - (void *) tp));
3481 GNUNET_STATISTICS_update (stats,
3482 gettext_noop ("# PONG messages created"),
3486 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3487 "Encrypting `%s' with challenge %u using key %u, IV %u (salt %u)\n",
3489 (unsigned int) t.challenge,
3490 (unsigned int) n->encrypt_key.crc32,
3491 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3494 /* trigger queue processing */
3495 process_encrypted_neighbour_queue (n);
3500 * We received a PONG message. Validate and update our status.
3502 * @param n sender of the PONG
3503 * @param m the encrypted PONG message itself
3504 * @param ats performance data
3505 * @param ats_count number of entries in ats (excluding 0-termination)
3508 handle_pong (struct Neighbour *n,
3509 const struct PongMessage *m,
3510 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3513 struct PongMessage t;
3514 struct ConnectNotifyMessage *cnm;
3515 struct GNUNET_CRYPTO_AesInitializationVector iv;
3516 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
3517 struct GNUNET_TRANSPORT_ATS_Information *mats;
3521 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3522 "Core service receives `%s' response from `%4s'.\n",
3523 "PONG", GNUNET_i2s (&n->peer));
3525 /* mark as garbage, just to be sure */
3526 memset (&t, 255, sizeof (t));
3527 derive_pong_iv (&iv, &n->decrypt_key, m->iv_seed, n->ping_challenge,
3534 sizeof (struct PongMessage) -
3535 ((void *) &m->challenge - (void *) m)))
3537 GNUNET_break_op (0);
3540 GNUNET_STATISTICS_update (stats,
3541 gettext_noop ("# PONG messages decrypted"),
3545 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3546 "Decrypted `%s' from `%4s' with challenge %u using key %u, IV %u (salt %u)\n",
3548 GNUNET_i2s (&t.target),
3549 (unsigned int) t.challenge,
3550 (unsigned int) n->decrypt_key.crc32,
3551 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3554 if ((0 != memcmp (&t.target,
3556 sizeof (struct GNUNET_PeerIdentity))) ||
3557 (n->ping_challenge != t.challenge))
3559 /* PONG malformed */
3561 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3562 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
3564 GNUNET_i2s (&n->peer),
3565 (unsigned int) n->ping_challenge);
3566 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3567 "Received malformed `%s' received from `%4s' with challenge %u\n",
3568 "PONG", GNUNET_i2s (&t.target),
3569 (unsigned int) t.challenge);
3571 GNUNET_break_op (n->ping_challenge != t.challenge);
3576 case PEER_STATE_DOWN:
3577 GNUNET_break (0); /* should be impossible */
3579 case PEER_STATE_KEY_SENT:
3580 GNUNET_break (0); /* should be impossible, how did we decrypt? */
3582 case PEER_STATE_KEY_RECEIVED:
3583 GNUNET_STATISTICS_update (stats,
3584 gettext_noop ("# Session keys confirmed via PONG"),
3587 n->status = PEER_STATE_KEY_CONFIRMED;
3588 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
3590 n->bw_out_external_limit = t.inbound_bw_limit;
3591 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3592 n->bw_out_internal_limit);
3593 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3595 GNUNET_TRANSPORT_set_quota (transport,
3599 GNUNET_TIME_UNIT_FOREVER_REL,
3603 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3604 "Confirmed key via `%s' message for peer `%4s'\n",
3605 "PONG", GNUNET_i2s (&n->peer));
3607 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3609 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3610 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3612 update_neighbour_performance (n, ats, ats_count);
3613 size = sizeof (struct ConnectNotifyMessage) +
3614 (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3615 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3618 /* recovery strategy: throw away performance data */
3619 GNUNET_array_grow (n->ats,
3622 size = sizeof (struct PeerStatusNotifyMessage) +
3623 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3625 cnm = (struct ConnectNotifyMessage*) buf;
3626 cnm->header.size = htons (size);
3627 cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3628 cnm->ats_count = htonl (n->ats_count);
3629 cnm->peer = n->peer;
3633 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
3634 mats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3635 mats[n->ats_count].value = htonl (0);
3636 send_to_all_clients (&cnm->header,
3638 GNUNET_CORE_OPTION_SEND_CONNECT);
3639 process_encrypted_neighbour_queue (n);
3641 case PEER_STATE_KEY_CONFIRMED:
3642 n->last_activity = GNUNET_TIME_absolute_get ();
3643 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3644 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3646 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3649 handle_peer_status_change (n);
3659 * We received a SET_KEY message. Validate and update
3660 * our key material and status.
3662 * @param n the neighbour from which we received message m
3663 * @param m the set key message we received
3664 * @param ats performance data
3665 * @param ats_count number of entries in ats (excluding 0-termination)
3668 handle_set_key (struct Neighbour *n,
3669 const struct SetKeyMessage *m,
3670 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3673 struct SetKeyMessage *m_cpy;
3674 struct GNUNET_TIME_Absolute t;
3675 struct GNUNET_CRYPTO_AesSessionKey k;
3676 struct PingMessage *ping;
3677 struct PongMessage *pong;
3678 enum PeerStateMachine sender_status;
3681 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3682 "Core service receives `%s' request from `%4s'.\n",
3683 "SET_KEY", GNUNET_i2s (&n->peer));
3685 if (n->public_key == NULL)
3687 if (n->pitr != NULL)
3690 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3691 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3697 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3698 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3700 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3701 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3702 /* lookup n's public key, then try again */
3703 GNUNET_assert (n->skm == NULL);
3705 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3707 GNUNET_TIME_UNIT_MINUTES,
3708 &process_hello_retry_handle_set_key, n);
3709 GNUNET_STATISTICS_update (stats,
3710 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3715 if (0 != memcmp (&m->target,
3717 sizeof (struct GNUNET_PeerIdentity)))
3719 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3720 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3722 GNUNET_i2s (&m->target));
3725 if ((ntohl (m->purpose.size) !=
3726 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3727 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3728 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3729 sizeof (struct GNUNET_PeerIdentity)) ||
3731 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3732 &m->purpose, &m->signature, n->public_key)))
3734 /* invalid signature */
3735 GNUNET_break_op (0);
3738 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3739 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3740 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3741 (t.abs_value < n->decrypt_key_created.abs_value))
3743 /* this could rarely happen due to massive re-ordering of
3744 messages on the network level, but is most likely either
3745 a bug or some adversary messing with us. Report. */
3746 GNUNET_break_op (0);
3750 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3751 "Decrypting key material.\n");
3753 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3756 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3757 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3758 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3760 /* failed to decrypt !? */
3761 GNUNET_break_op (0);
3764 GNUNET_STATISTICS_update (stats,
3765 gettext_noop ("# SET_KEY messages decrypted"),
3769 if (n->decrypt_key_created.abs_value != t.abs_value)
3771 /* fresh key, reset sequence numbers */
3772 n->last_sequence_number_received = 0;
3773 n->last_packets_bitmap = 0;
3774 n->decrypt_key_created = t;
3776 update_neighbour_performance (n, ats, ats_count);
3777 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3780 case PEER_STATE_DOWN:
3781 n->status = PEER_STATE_KEY_RECEIVED;
3783 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3784 "Responding to `%s' with my own key.\n", "SET_KEY");
3788 case PEER_STATE_KEY_SENT:
3789 case PEER_STATE_KEY_RECEIVED:
3790 n->status = PEER_STATE_KEY_RECEIVED;
3791 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3792 (sender_status != PEER_STATE_KEY_CONFIRMED))
3795 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3796 "Responding to `%s' with my own key (other peer has status %u).\n",
3798 (unsigned int) sender_status);
3803 case PEER_STATE_KEY_CONFIRMED:
3804 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3805 (sender_status != PEER_STATE_KEY_CONFIRMED))
3808 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3809 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3811 (unsigned int) sender_status);
3820 if (n->pending_ping != NULL)
3822 ping = n->pending_ping;
3823 n->pending_ping = NULL;
3824 handle_ping (n, ping, NULL, 0);
3827 if (n->pending_pong != NULL)
3829 pong = n->pending_pong;
3830 n->pending_pong = NULL;
3831 handle_pong (n, pong, NULL, 0);
3838 * Send a P2P message to a client.
3840 * @param sender who sent us the message?
3841 * @param client who should we give the message to?
3842 * @param m contains the message to transmit
3843 * @param msize number of bytes in buf to transmit
3846 send_p2p_message_to_client (struct Neighbour *sender,
3847 struct Client *client,
3848 const void *m, size_t msize)
3850 size_t size = msize + sizeof (struct NotifyTrafficMessage) +
3851 (sender->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3853 struct NotifyTrafficMessage *ntm;
3854 struct GNUNET_TRANSPORT_ATS_Information *ats;
3856 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3859 /* recovery strategy: throw performance data away... */
3860 GNUNET_array_grow (sender->ats,
3863 size = msize + sizeof (struct NotifyTrafficMessage) +
3864 (sender->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3867 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3868 "Core service passes message from `%4s' of type %u to client.\n",
3869 GNUNET_i2s(&sender->peer),
3870 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3872 ntm = (struct NotifyTrafficMessage *) buf;
3873 ntm->header.size = htons (size);
3874 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3875 ntm->ats_count = htonl (sender->ats_count);
3876 ntm->peer = sender->peer;
3880 sizeof (struct GNUNET_TRANSPORT_ATS_Information) * sender->ats_count);
3881 ats[sender->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3882 ats[sender->ats_count].value = htonl (0);
3883 memcpy (&ats[sender->ats_count+1],
3886 send_to_client (client, &ntm->header, GNUNET_YES);
3891 * Deliver P2P message to interested clients.
3893 * @param cls always NULL
3894 * @param client who sent us the message (struct Neighbour)
3895 * @param m the message
3898 deliver_message (void *cls,
3900 const struct GNUNET_MessageHeader *m)
3902 struct Neighbour *sender = client;
3903 size_t msize = ntohs (m->size);
3905 struct Client *cpos;
3911 type = ntohs (m->type);
3913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3914 "Received encapsulated message of type %u and size %u from `%4s'\n",
3915 (unsigned int) type,
3917 GNUNET_i2s (&sender->peer));
3919 GNUNET_snprintf (buf,
3921 gettext_noop ("# bytes of messages of type %u received"),
3922 (unsigned int) type);
3923 GNUNET_STATISTICS_set (stats,
3927 dropped = GNUNET_YES;
3929 while (cpos != NULL)
3931 deliver_full = GNUNET_NO;
3932 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3933 deliver_full = GNUNET_YES;
3936 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3938 if (type != cpos->types[tpos])
3940 deliver_full = GNUNET_YES;
3944 if (GNUNET_YES == deliver_full)
3946 send_p2p_message_to_client (sender, cpos, m, msize);
3947 dropped = GNUNET_NO;
3949 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3951 send_p2p_message_to_client (sender, cpos, m,
3952 sizeof (struct GNUNET_MessageHeader));
3956 if (dropped == GNUNET_YES)
3959 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3960 "Message of type %u from `%4s' not delivered to any client.\n",
3961 (unsigned int) type,
3962 GNUNET_i2s (&sender->peer));
3964 GNUNET_STATISTICS_update (stats,
3965 gettext_noop ("# messages not delivered to any client"),
3972 * We received an encrypted message. Decrypt, validate and
3973 * pass on to the appropriate clients.
3975 * @param n target of the message
3976 * @param m encrypted message
3977 * @param ats performance data
3978 * @param ats_count number of entries in ats (excluding 0-termination)
3981 handle_encrypted_message (struct Neighbour *n,
3982 const struct EncryptedMessage *m,
3983 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3986 size_t size = ntohs (m->header.size);
3988 struct EncryptedMessage *pt; /* plaintext */
3991 struct GNUNET_TIME_Absolute t;
3992 struct GNUNET_CRYPTO_AesInitializationVector iv;
3993 struct GNUNET_CRYPTO_AuthKey auth_key;
3996 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3997 "Core service receives `%s' request from `%4s'.\n",
3998 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
4001 derive_auth_key (&auth_key,
4004 n->decrypt_key_created);
4005 GNUNET_CRYPTO_hmac (&auth_key,
4006 &m->sequence_number,
4007 size - ENCRYPTED_HEADER_SIZE, &ph);
4009 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4010 "Re-Authenticated %u bytes of ciphertext (`%u'): `%s'\n",
4011 (unsigned int) size - ENCRYPTED_HEADER_SIZE,
4012 GNUNET_CRYPTO_crc32_n (&m->sequence_number,
4013 size - ENCRYPTED_HEADER_SIZE),
4017 if (0 != memcmp (&ph,
4019 sizeof (GNUNET_HashCode)))
4021 /* checksum failed */
4022 GNUNET_break_op (0);
4025 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
4030 &m->sequence_number,
4031 &buf[ENCRYPTED_HEADER_SIZE],
4032 size - ENCRYPTED_HEADER_SIZE))
4034 pt = (struct EncryptedMessage *) buf;
4036 /* validate sequence number */
4037 snum = ntohl (pt->sequence_number);
4038 if (n->last_sequence_number_received == snum)
4040 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4041 "Received duplicate message, ignoring.\n");
4042 /* duplicate, ignore */
4043 GNUNET_STATISTICS_set (stats,
4044 gettext_noop ("# bytes dropped (duplicates)"),
4049 if ((n->last_sequence_number_received > snum) &&
4050 (n->last_sequence_number_received - snum > 32))
4052 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4053 "Received ancient out of sequence message, ignoring.\n");
4054 /* ancient out of sequence, ignore */
4055 GNUNET_STATISTICS_set (stats,
4056 gettext_noop ("# bytes dropped (out of sequence)"),
4061 if (n->last_sequence_number_received > snum)
4063 unsigned int rotbit =
4064 1 << (n->last_sequence_number_received - snum - 1);
4065 if ((n->last_packets_bitmap & rotbit) != 0)
4067 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4068 "Received duplicate message, ignoring.\n");
4069 GNUNET_STATISTICS_set (stats,
4070 gettext_noop ("# bytes dropped (duplicates)"),
4073 /* duplicate, ignore */
4076 n->last_packets_bitmap |= rotbit;
4078 if (n->last_sequence_number_received < snum)
4080 int shift = (snum - n->last_sequence_number_received);
4081 if (shift >= 8 * sizeof(n->last_packets_bitmap))
4082 n->last_packets_bitmap = 0;
4084 n->last_packets_bitmap <<= shift;
4085 n->last_sequence_number_received = snum;
4088 /* check timestamp */
4089 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
4090 if (GNUNET_TIME_absolute_get_duration (t).rel_value > MAX_MESSAGE_AGE.rel_value)
4092 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4094 ("Message received far too old (%llu ms). Content ignored.\n"),
4095 GNUNET_TIME_absolute_get_duration (t).rel_value);
4096 GNUNET_STATISTICS_set (stats,
4097 gettext_noop ("# bytes dropped (ancient message)"),
4103 /* process decrypted message(s) */
4104 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
4106 #if DEBUG_CORE_SET_QUOTA
4107 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4108 "Received %u b/s as new inbound limit for peer `%4s'\n",
4109 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
4110 GNUNET_i2s (&n->peer));
4112 n->bw_out_external_limit = pt->inbound_bw_limit;
4113 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
4114 n->bw_out_internal_limit);
4115 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
4117 GNUNET_TRANSPORT_set_quota (transport,
4121 GNUNET_TIME_UNIT_FOREVER_REL,
4124 n->last_activity = GNUNET_TIME_absolute_get ();
4125 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
4126 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
4128 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
4131 GNUNET_STATISTICS_set (stats,
4132 gettext_noop ("# bytes of payload decrypted"),
4133 size - sizeof (struct EncryptedMessage),
4135 handle_peer_status_change (n);
4136 update_neighbour_performance (n, ats, ats_count);
4137 if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst,
4139 &buf[sizeof (struct EncryptedMessage)],
4140 size - sizeof (struct EncryptedMessage),
4141 GNUNET_YES, GNUNET_NO))
4142 GNUNET_break_op (0);
4147 * Function called by the transport for each received message.
4149 * @param cls closure
4150 * @param peer (claimed) identity of the other peer
4151 * @param message the message
4152 * @param ats performance data
4153 * @param ats_count number of entries in ats (excluding 0-termination)
4156 handle_transport_receive (void *cls,
4157 const struct GNUNET_PeerIdentity *peer,
4158 const struct GNUNET_MessageHeader *message,
4159 const struct GNUNET_TRANSPORT_ATS_Information *ats,
4162 struct Neighbour *n;
4163 struct GNUNET_TIME_Absolute now;
4170 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4171 "Received message of type %u from `%4s', demultiplexing.\n",
4172 (unsigned int) ntohs (message->type),
4175 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4180 n = find_neighbour (peer);
4182 n = create_neighbour (peer);
4183 changed = GNUNET_NO;
4184 up = (n->status == PEER_STATE_KEY_CONFIRMED);
4185 type = ntohs (message->type);
4186 size = ntohs (message->size);
4189 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
4190 if (size != sizeof (struct SetKeyMessage))
4192 GNUNET_break_op (0);
4195 GNUNET_STATISTICS_update (stats,
4196 gettext_noop ("# session keys received"),
4200 (const struct SetKeyMessage *) message,
4203 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
4204 if (size < sizeof (struct EncryptedMessage) +
4205 sizeof (struct GNUNET_MessageHeader))
4207 GNUNET_break_op (0);
4210 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
4211 (n->status != PEER_STATE_KEY_CONFIRMED))
4213 GNUNET_STATISTICS_update (stats,
4214 gettext_noop ("# failed to decrypt message (no session key)"),
4220 handle_encrypted_message (n,
4221 (const struct EncryptedMessage *) message,
4224 case GNUNET_MESSAGE_TYPE_CORE_PING:
4225 if (size != sizeof (struct PingMessage))
4227 GNUNET_break_op (0);
4230 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
4231 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
4232 (n->status != PEER_STATE_KEY_CONFIRMED))
4235 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4236 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
4237 "PING", GNUNET_i2s (&n->peer));
4239 GNUNET_free_non_null (n->pending_ping);
4240 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
4241 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
4244 handle_ping (n, (const struct PingMessage *) message,
4247 case GNUNET_MESSAGE_TYPE_CORE_PONG:
4248 if (size != sizeof (struct PongMessage))
4250 GNUNET_break_op (0);
4253 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
4254 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
4255 (n->status != PEER_STATE_KEY_CONFIRMED) )
4258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4259 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
4260 "PONG", GNUNET_i2s (&n->peer));
4262 GNUNET_free_non_null (n->pending_pong);
4263 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
4264 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
4267 handle_pong (n, (const struct PongMessage *) message,
4271 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4272 _("Unsupported message of type %u received.\n"),
4273 (unsigned int) type);
4276 if (n->status == PEER_STATE_KEY_CONFIRMED)
4278 now = GNUNET_TIME_absolute_get ();
4279 n->last_activity = now;
4280 changed = GNUNET_YES;
4283 GNUNET_STATISTICS_update (stats,
4284 gettext_noop ("# established sessions"),
4287 n->time_established = now;
4289 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
4290 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
4292 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
4297 handle_peer_status_change (n);
4302 * Function that recalculates the bandwidth quota for the
4303 * given neighbour and transmits it to the transport service.
4305 * @param cls neighbour for the quota update
4309 neighbour_quota_update (void *cls,
4310 const struct GNUNET_SCHEDULER_TaskContext *tc)
4312 struct Neighbour *n = cls;
4313 struct GNUNET_BANDWIDTH_Value32NBO q_in;
4314 struct GNUNET_BANDWIDTH_Value32NBO q_out;
4315 struct GNUNET_BANDWIDTH_Value32NBO q_out_min;
4318 unsigned long long distributable;
4319 uint64_t need_per_peer;
4320 uint64_t need_per_second;
4321 unsigned int neighbour_count;
4324 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4325 "Neighbour quota update calculation running for peer `%4s'\n",
4326 GNUNET_i2s (&n->peer));
4328 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
4329 /* calculate relative preference among all neighbours;
4330 divides by a bit more to avoid division by zero AND to
4331 account for possibility of new neighbours joining any time
4332 AND to convert to double... */
4333 neighbour_count = GNUNET_CONTAINER_multihashmap_size (neighbours);
4334 if (neighbour_count == 0)
4336 if (preference_sum == 0)
4338 pref_rel = 1.0 / (double) neighbour_count;
4342 pref_rel = n->current_preference / preference_sum;
4344 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
4345 GNUNET_TIME_UNIT_SECONDS);
4346 need_per_second = need_per_peer * neighbour_count;
4348 /* calculate inbound bandwidth per peer */
4350 if (bandwidth_target_in_bps > need_per_second)
4351 distributable = bandwidth_target_in_bps - need_per_second;
4352 share = distributable * pref_rel;
4353 if (share + need_per_peer > UINT32_MAX)
4354 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4356 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4358 /* calculate outbound bandwidth per peer */
4360 if (bandwidth_target_out_bps > need_per_second)
4361 distributable = bandwidth_target_out_bps - need_per_second;
4362 share = distributable * pref_rel;
4363 if (share + need_per_peer > UINT32_MAX)
4364 q_out = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4366 q_out = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4367 n->bw_out_internal_limit = q_out;
4369 q_out_min = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit, n->bw_out_internal_limit);
4370 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window, n->bw_out);
4372 /* check if we want to disconnect for good due to inactivity */
4373 if ( (GNUNET_TIME_absolute_get_duration (get_neighbour_timeout (n)).rel_value > 0) &&
4374 (GNUNET_TIME_absolute_get_duration (n->time_established).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) )
4377 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4378 "Forcing disconnect of `%4s' due to inactivity\n",
4379 GNUNET_i2s (&n->peer));
4381 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
4383 #if DEBUG_CORE_QUOTA
4384 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4385 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
4386 GNUNET_i2s (&n->peer),
4387 (unsigned int) ntohl (q_in.value__),
4388 bandwidth_target_out_bps,
4389 (unsigned int) ntohl (n->bw_in.value__),
4390 (unsigned int) ntohl (n->bw_out.value__),
4391 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
4393 if ((n->bw_in.value__ != q_in.value__) || (n->bw_out.value__ != q_out_min.value__))
4395 if (n->bw_in.value__ != q_in.value__)
4397 if (n->bw_out.value__ != q_out_min.value__)
4398 n->bw_out = q_out_min;
4399 if (GNUNET_YES == n->is_connected)
4400 GNUNET_TRANSPORT_set_quota (transport,
4404 GNUNET_TIME_UNIT_FOREVER_REL,
4406 handle_peer_status_change (n);
4408 schedule_quota_update (n);
4413 * Function called by transport to notify us that
4414 * a peer connected to us (on the network level).
4416 * @param cls closure
4417 * @param peer the peer that connected
4418 * @param ats performance data
4419 * @param ats_count number of entries in ats (excluding 0-termination)
4422 handle_transport_notify_connect (void *cls,
4423 const struct GNUNET_PeerIdentity *peer,
4424 const struct GNUNET_TRANSPORT_ATS_Information *ats,
4427 struct Neighbour *n;
4429 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4434 n = find_neighbour (peer);
4437 if (GNUNET_YES == n->is_connected)
4439 /* duplicate connect notification!? */
4446 n = create_neighbour (peer);
4448 GNUNET_STATISTICS_update (stats,
4449 gettext_noop ("# peers connected (transport)"),
4452 n->is_connected = GNUNET_YES;
4453 update_neighbour_performance (n, ats, ats_count);
4454 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
4457 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
4461 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4462 "Received connection from `%4s'.\n",
4463 GNUNET_i2s (&n->peer));
4465 GNUNET_TRANSPORT_set_quota (transport,
4469 GNUNET_TIME_UNIT_FOREVER_REL,
4476 * Function called by transport telling us that a peer
4479 * @param cls closure
4480 * @param peer the peer that disconnected
4483 handle_transport_notify_disconnect (void *cls,
4484 const struct GNUNET_PeerIdentity *peer)
4486 struct DisconnectNotifyMessage cnm;
4487 struct Neighbour *n;
4488 struct ClientActiveRequest *car;
4489 struct GNUNET_TIME_Relative left;
4492 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4493 "Peer `%4s' disconnected from us; received notification from transport.\n",
4496 n = find_neighbour (peer);
4502 GNUNET_break (n->is_connected == GNUNET_YES);
4503 if (n->status == PEER_STATE_KEY_CONFIRMED)
4505 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
4506 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
4507 cnm.reserved = htonl (0);
4509 send_to_all_clients (&cnm.header, GNUNET_NO, GNUNET_CORE_OPTION_SEND_DISCONNECT);
4510 GNUNET_STATISTICS_update (stats,
4511 gettext_noop ("# established sessions"),
4516 /* On transport disconnect transport doesn't cancel requests, so must do so here. */
4519 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
4522 n->is_connected = GNUNET_NO;
4523 n->status = PEER_STATE_DOWN;
4524 while (NULL != (car = n->active_client_request_head))
4526 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
4527 n->active_client_request_tail,
4529 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
4530 &n->peer.hashPubKey,
4535 GNUNET_STATISTICS_update (stats,
4536 gettext_noop ("# peers connected (transport)"),
4539 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
4540 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
4541 left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4542 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
4543 n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (),
4545 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
4546 &consider_free_task,
4552 * Wrapper around 'free_neighbour'; helper for 'cleaning_task'.
4555 free_neighbour_helper (void *cls,
4556 const GNUNET_HashCode *key,
4559 struct Neighbour *n = value;
4567 * Last task run during shutdown. Disconnects us from
4571 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4576 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4577 "Core service shutting down.\n");
4579 GNUNET_CONTAINER_multihashmap_iterate (neighbours,
4580 &free_neighbour_helper,
4582 GNUNET_CONTAINER_multihashmap_destroy (neighbours);
4584 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), 0, GNUNET_NO);
4585 GNUNET_assert (transport != NULL);
4586 GNUNET_TRANSPORT_disconnect (transport);
4588 GNUNET_SERVER_notification_context_destroy (notifier);
4590 while (NULL != (c = clients))
4591 handle_client_disconnect (NULL, c->client_handle);
4592 if (my_private_key != NULL)
4593 GNUNET_CRYPTO_rsa_key_free (my_private_key);
4595 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4596 if (peerinfo != NULL)
4597 GNUNET_PEERINFO_disconnect (peerinfo);
4599 GNUNET_SERVER_mst_destroy (mst);
4604 * Initiate core service.
4606 * @param cls closure
4607 * @param server the initialized server
4608 * @param c configuration to use
4612 struct GNUNET_SERVER_Handle *server,
4613 const struct GNUNET_CONFIGURATION_Handle *c)
4615 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4616 {&handle_client_init, NULL,
4617 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
4618 {&handle_client_iterate_peers, NULL,
4619 GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
4620 sizeof (struct GNUNET_MessageHeader)},
4621 {&handle_client_request_info, NULL,
4622 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
4623 sizeof (struct RequestInfoMessage)},
4624 {&handle_client_send_request, NULL,
4625 GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST,
4626 sizeof (struct SendMessageRequest)},
4627 {&handle_client_send, NULL,
4628 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
4629 {&handle_client_request_connect, NULL,
4630 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
4631 sizeof (struct ConnectMessage)},
4637 /* parse configuration */
4640 GNUNET_CONFIGURATION_get_value_number (c,
4643 &bandwidth_target_in_bps)) ||
4645 GNUNET_CONFIGURATION_get_value_number (c,
4648 &bandwidth_target_out_bps)) ||
4650 GNUNET_CONFIGURATION_get_value_filename (c,
4652 "HOSTKEY", &keyfile)))
4654 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4656 ("Core service is lacking key configuration settings. Exiting.\n"));
4657 GNUNET_SCHEDULER_shutdown ();
4660 peerinfo = GNUNET_PEERINFO_connect (cfg);
4661 if (NULL == peerinfo)
4663 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4664 _("Could not access PEERINFO service. Exiting.\n"));
4665 GNUNET_SCHEDULER_shutdown ();
4666 GNUNET_free (keyfile);
4669 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4670 GNUNET_free (keyfile);
4671 if (my_private_key == NULL)
4673 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4674 _("Core service could not access hostkey. Exiting.\n"));
4675 GNUNET_PEERINFO_disconnect (peerinfo);
4676 GNUNET_SCHEDULER_shutdown ();
4679 neighbours = GNUNET_CONTAINER_multihashmap_create (128);
4680 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4681 GNUNET_CRYPTO_hash (&my_public_key,
4682 sizeof (my_public_key), &my_identity.hashPubKey);
4683 self.public_key = &my_public_key;
4684 self.peer = my_identity;
4685 self.last_activity = GNUNET_TIME_UNIT_FOREVER_ABS;
4686 self.status = PEER_STATE_KEY_CONFIRMED;
4687 self.is_connected = GNUNET_YES;
4688 /* setup notification */
4689 notifier = GNUNET_SERVER_notification_context_create (server,
4691 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4692 /* setup transport connection */
4693 transport = GNUNET_TRANSPORT_connect (cfg,
4696 &handle_transport_receive,
4697 &handle_transport_notify_connect,
4698 &handle_transport_notify_disconnect);
4699 GNUNET_assert (NULL != transport);
4700 stats = GNUNET_STATISTICS_create ("core", cfg);
4702 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded CORE_SEND requests"), 0, GNUNET_NO);
4703 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 0, GNUNET_NO);
4705 mst = GNUNET_SERVER_mst_create (&deliver_message,
4707 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4708 &cleaning_task, NULL);
4709 /* process client requests */
4710 GNUNET_SERVER_add_handlers (server, handlers);
4711 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4712 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
4718 * The main function for the transport service.
4720 * @param argc number of arguments from the command line
4721 * @param argv command line arguments
4722 * @return 0 ok, 1 on error
4725 main (int argc, char *const *argv)
4727 return (GNUNET_OK ==
4728 GNUNET_SERVICE_run (argc,
4731 GNUNET_SERVICE_OPTION_NONE,
4732 &run, NULL)) ? 0 : 1;
4735 /* end of gnunet-service-core.c */