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 > 1
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_assert (NULL != n);
1379 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1380 n->active_client_request_tail,
1388 * A client disconnected, clean up.
1390 * @param cls closure
1391 * @param client identification of the client
1394 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1397 struct Client *prev;
1401 #if DEBUG_CORE_CLIENT
1402 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1403 "Client %p has disconnected from core service.\n",
1410 if (client == pos->client_handle)
1417 /* client never sent INIT */
1421 clients = pos->next;
1423 prev->next = pos->next;
1424 if (pos->requests != NULL)
1426 GNUNET_CONTAINER_multihashmap_iterate (pos->requests,
1427 &destroy_active_client_request,
1429 GNUNET_CONTAINER_multihashmap_destroy (pos->requests);
1436 * Helper function for handle_client_iterate_peers.
1438 * @param cls the 'struct GNUNET_SERVER_TransmitContext' to queue replies
1439 * @param key identity of the connected peer
1440 * @param value the 'struct Neighbour' for the peer
1441 * @return GNUNET_OK (continue to iterate)
1444 queue_connect_message (void *cls,
1445 const GNUNET_HashCode *key,
1448 struct GNUNET_SERVER_TransmitContext *tc = cls;
1449 struct Neighbour *n = value;
1450 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
1451 struct GNUNET_TRANSPORT_ATS_Information *ats;
1453 struct ConnectNotifyMessage *cnm;
1455 cnm = (struct ConnectNotifyMessage*) buf;
1456 if (n->status != PEER_STATE_KEY_CONFIRMED)
1458 size = sizeof (struct ConnectNotifyMessage) +
1459 (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1460 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1463 /* recovery strategy: throw away performance data */
1464 GNUNET_array_grow (n->ats,
1467 size = sizeof (struct PeerStatusNotifyMessage) +
1468 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
1470 cnm = (struct ConnectNotifyMessage*) buf;
1471 cnm->header.size = htons (size);
1472 cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
1473 cnm->ats_count = htonl (n->ats_count);
1477 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
1478 ats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
1479 ats[n->ats_count].value = htonl (0);
1480 #if DEBUG_CORE_CLIENT
1481 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1482 "Sending `%s' message to client.\n",
1485 cnm->peer = n->peer;
1486 GNUNET_SERVER_transmit_context_append_message (tc,
1493 * Handle CORE_ITERATE_PEERS request.
1496 * @param client client sending the iteration request
1497 * @param message iteration request message
1500 handle_client_iterate_peers (void *cls,
1501 struct GNUNET_SERVER_Client *client,
1502 const struct GNUNET_MessageHeader *message)
1505 struct GNUNET_MessageHeader done_msg;
1506 struct GNUNET_SERVER_TransmitContext *tc;
1508 /* notify new client about existing neighbours */
1510 msize = ntohs(message->size);
1511 tc = GNUNET_SERVER_transmit_context_create (client);
1512 if (msize == sizeof(struct GNUNET_MessageHeader))
1513 GNUNET_CONTAINER_multihashmap_iterate (neighbours, &queue_connect_message, tc);
1517 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
1518 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
1519 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
1520 GNUNET_SERVER_transmit_context_run (tc,
1521 GNUNET_TIME_UNIT_FOREVER_REL);
1525 * Handle CORE_ITERATE_PEERS request. Notify client about existing neighbours.
1528 * @param client client sending the iteration request
1529 * @param message iteration request message
1532 handle_client_have_peer (void *cls,
1533 struct GNUNET_SERVER_Client *client,
1534 const struct GNUNET_MessageHeader *message)
1537 struct GNUNET_MessageHeader done_msg;
1538 struct GNUNET_SERVER_TransmitContext *tc;
1539 struct GNUNET_PeerIdentity *peer;
1541 tc = GNUNET_SERVER_transmit_context_create (client);
1542 peer = (struct GNUNET_PeerIdentity *) &message[1];
1543 GNUNET_CONTAINER_multihashmap_get_multiple(neighbours,
1545 &queue_connect_message,
1547 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
1548 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
1549 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
1550 GNUNET_SERVER_transmit_context_run (tc,
1551 GNUNET_TIME_UNIT_FOREVER_REL);
1556 * Handle REQUEST_INFO request.
1559 * @param client client sending the request
1560 * @param message iteration request message
1563 handle_client_request_info (void *cls,
1564 struct GNUNET_SERVER_Client *client,
1565 const struct GNUNET_MessageHeader *message)
1567 const struct RequestInfoMessage *rcm;
1569 struct Neighbour *n;
1570 struct ConfigurationInfoMessage cim;
1571 int32_t want_reserv;
1573 unsigned long long old_preference;
1574 struct GNUNET_TIME_Relative rdelay;
1576 rdelay = GNUNET_TIME_relative_get_zero();
1577 #if DEBUG_CORE_CLIENT
1578 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1579 "Core service receives `%s' request.\n", "REQUEST_INFO");
1584 if (client == pos->client_handle)
1591 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1595 rcm = (const struct RequestInfoMessage *) message;
1596 n = find_neighbour (&rcm->peer);
1597 memset (&cim, 0, sizeof (cim));
1600 want_reserv = ntohl (rcm->reserve_inbound);
1601 if (n->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
1603 n->bw_out_internal_limit = rcm->limit_outbound;
1604 if (n->bw_out.value__ != GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1605 n->bw_out_external_limit).value__)
1607 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_internal_limit,
1608 n->bw_out_external_limit);
1609 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_recv_window,
1611 GNUNET_TRANSPORT_set_quota (transport,
1615 handle_peer_status_change (n);
1618 if (want_reserv < 0)
1620 got_reserv = want_reserv;
1622 else if (want_reserv > 0)
1624 rdelay = GNUNET_BANDWIDTH_tracker_get_delay (&n->available_recv_window,
1626 if (rdelay.rel_value == 0)
1627 got_reserv = want_reserv;
1629 got_reserv = 0; /* all or nothing */
1633 GNUNET_BANDWIDTH_tracker_consume (&n->available_recv_window,
1635 old_preference = n->current_preference;
1636 n->current_preference += GNUNET_ntohll(rcm->preference_change);
1637 if (old_preference > n->current_preference)
1639 /* overflow; cap at maximum value */
1640 n->current_preference = ULLONG_MAX;
1642 update_preference_sum (n->current_preference - old_preference);
1643 #if DEBUG_CORE_QUOTA
1644 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1645 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes, suggesting delay of %llu ms\n",
1647 GNUNET_i2s (&rcm->peer),
1649 (unsigned long long) rdelay.rel_value);
1651 cim.reserved_amount = htonl (got_reserv);
1652 cim.reserve_delay = GNUNET_TIME_relative_hton (rdelay);
1653 cim.bw_out = n->bw_out;
1654 cim.preference = n->current_preference;
1658 /* Technically, this COULD happen (due to asynchronous behavior),
1659 but it is very odd, so we should at least generate a stern
1661 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1662 "Client asked for preference change with peer `%s', which is not connected!\n",
1663 GNUNET_i2s (&rcm->peer));
1665 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
1666 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
1667 cim.peer = rcm->peer;
1668 cim.rim_id = rcm->rim_id;
1669 #if DEBUG_CORE_CLIENT
1670 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1671 "Sending `%s' message to client.\n", "CONFIGURATION_INFO");
1673 send_to_client (pos, &cim.header, GNUNET_NO);
1674 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1679 * Free the given entry for the neighbour (it has
1680 * already been removed from the list at this point).
1682 * @param n neighbour to free
1685 free_neighbour (struct Neighbour *n)
1687 struct MessageEntry *m;
1688 struct ClientActiveRequest *car;
1691 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1692 "Destroying neighbour entry for peer `%4s'\n",
1693 GNUNET_i2s (&n->peer));
1695 if (n->pitr != NULL)
1697 GNUNET_PEERINFO_iterate_cancel (n->pitr);
1702 GNUNET_free (n->skm);
1705 while (NULL != (m = n->messages))
1707 n->messages = m->next;
1710 while (NULL != (m = n->encrypted_head))
1712 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1717 while (NULL != (car = n->active_client_request_head))
1719 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
1720 n->active_client_request_tail,
1722 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
1723 &n->peer.hashPubKey,
1729 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
1732 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
1733 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
1734 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
1735 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
1736 if (n->quota_update_task != GNUNET_SCHEDULER_NO_TASK)
1737 GNUNET_SCHEDULER_cancel (n->quota_update_task);
1738 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1739 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1740 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1741 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
1742 if (n->status == PEER_STATE_KEY_CONFIRMED)
1743 GNUNET_STATISTICS_update (stats,
1744 gettext_noop ("# established sessions"),
1747 GNUNET_array_grow (n->ats, n->ats_count, 0);
1748 GNUNET_free_non_null (n->public_key);
1749 GNUNET_free_non_null (n->pending_ping);
1750 GNUNET_free_non_null (n->pending_pong);
1756 * Check if we have encrypted messages for the specified neighbour
1757 * pending, and if so, check with the transport about sending them
1760 * @param n neighbour to check.
1762 static void process_encrypted_neighbour_queue (struct Neighbour *n);
1766 * Encrypt size bytes from in and write the result to out. Use the
1767 * key for outbound traffic of the given neighbour.
1769 * @param n neighbour we are sending to
1770 * @param iv initialization vector to use
1771 * @param in ciphertext
1772 * @param out plaintext
1773 * @param size size of in/out
1774 * @return GNUNET_OK on success
1777 do_encrypt (struct Neighbour *n,
1778 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
1779 const void *in, void *out, size_t size)
1781 if (size != (uint16_t) size)
1786 GNUNET_assert (size ==
1787 GNUNET_CRYPTO_aes_encrypt (in,
1791 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size, GNUNET_NO);
1793 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1794 "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
1795 (unsigned int) size,
1796 GNUNET_i2s (&n->peer),
1797 (unsigned int) n->encrypt_key.crc32,
1798 GNUNET_CRYPTO_crc32_n (iv, sizeof(iv)));
1805 * Consider freeing the given neighbour since we may not need
1806 * to keep it around anymore.
1808 * @param n neighbour to consider discarding
1811 consider_free_neighbour (struct Neighbour *n);
1815 * Task triggered when a neighbour entry is about to time out
1816 * (and we should prevent this by sending a PING).
1818 * @param cls the 'struct Neighbour'
1819 * @param tc scheduler context (not used)
1822 send_keep_alive (void *cls,
1823 const struct GNUNET_SCHEDULER_TaskContext *tc)
1825 struct Neighbour *n = cls;
1826 struct GNUNET_TIME_Relative retry;
1827 struct GNUNET_TIME_Relative left;
1828 struct MessageEntry *me;
1829 struct PingMessage pp;
1830 struct PingMessage *pm;
1831 struct GNUNET_CRYPTO_AesInitializationVector iv;
1833 n->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
1835 me = GNUNET_malloc (sizeof (struct MessageEntry) +
1836 sizeof (struct PingMessage));
1837 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PING_DELAY);
1838 me->priority = PING_PRIORITY;
1839 me->size = sizeof (struct PingMessage);
1840 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
1844 pm = (struct PingMessage *) &me[1];
1845 pm->header.size = htons (sizeof (struct PingMessage));
1846 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
1847 pm->iv_seed = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1849 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
1850 pp.challenge = n->ping_challenge;
1851 pp.target = n->peer;
1853 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1854 "Encrypting `%s' message with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
1856 (unsigned int) n->ping_challenge,
1857 GNUNET_i2s (&n->peer),
1858 (unsigned int) n->encrypt_key.crc32,
1859 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
1866 sizeof (struct PingMessage) -
1867 ((void *) &pm->target - (void *) pm));
1868 process_encrypted_neighbour_queue (n);
1869 /* reschedule PING job */
1870 left = GNUNET_TIME_absolute_get_remaining (get_neighbour_timeout (n));
1871 retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1872 MIN_PING_FREQUENCY);
1874 = GNUNET_SCHEDULER_add_delayed (retry,
1882 * Task triggered when a neighbour entry might have gotten stale.
1884 * @param cls the 'struct Neighbour'
1885 * @param tc scheduler context (not used)
1888 consider_free_task (void *cls,
1889 const struct GNUNET_SCHEDULER_TaskContext *tc)
1891 struct Neighbour *n = cls;
1893 n->dead_clean_task = GNUNET_SCHEDULER_NO_TASK;
1894 consider_free_neighbour (n);
1899 * Consider freeing the given neighbour since we may not need
1900 * to keep it around anymore.
1902 * @param n neighbour to consider discarding
1905 consider_free_neighbour (struct Neighbour *n)
1907 struct GNUNET_TIME_Relative left;
1909 if ( (n->th != NULL) ||
1910 (n->pitr != NULL) ||
1911 (GNUNET_YES == n->is_connected) )
1912 return; /* no chance */
1914 left = GNUNET_TIME_absolute_get_remaining (get_neighbour_timeout (n));
1915 if (left.rel_value > 0)
1917 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
1918 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
1919 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (left,
1920 &consider_free_task,
1924 /* actually free the neighbour... */
1925 GNUNET_assert (GNUNET_OK ==
1926 GNUNET_CONTAINER_multihashmap_remove (neighbours,
1927 &n->peer.hashPubKey,
1929 GNUNET_STATISTICS_set (stats,
1930 gettext_noop ("# neighbour entries allocated"),
1931 GNUNET_CONTAINER_multihashmap_size (neighbours),
1938 * Function called when the transport service is ready to
1939 * receive an encrypted message for the respective peer
1941 * @param cls neighbour to use message from
1942 * @param size number of bytes we can transmit
1943 * @param buf where to copy the message
1944 * @return number of bytes transmitted
1947 notify_encrypted_transmit_ready (void *cls,
1951 struct Neighbour *n = cls;
1952 struct MessageEntry *m;
1957 m = n->encrypted_head;
1961 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1962 "Encrypted message queue empty, no messages added to buffer for `%4s'\n",
1963 GNUNET_i2s (&n->peer));
1967 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
1974 GNUNET_assert (size >= m->size);
1975 memcpy (cbuf, &m[1], m->size);
1977 GNUNET_BANDWIDTH_tracker_consume (&n->available_send_window,
1980 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1981 "Copied message of type %u and size %u into transport buffer for `%4s'\n",
1982 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1984 GNUNET_i2s (&n->peer));
1986 process_encrypted_neighbour_queue (n);
1991 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1992 "Transmission of message of type %u and size %u failed\n",
1993 (unsigned int) ntohs (((struct GNUNET_MessageHeader *) &m[1])->type),
1994 (unsigned int) m->size);
1998 consider_free_neighbour (n);
1999 GNUNET_STATISTICS_update (stats,
2000 gettext_noop ("# encrypted bytes given to transport"),
2008 * Check if we have plaintext messages for the specified neighbour
2009 * pending, and if so, consider batching and encrypting them (and
2010 * then trigger processing of the encrypted queue if needed).
2012 * @param n neighbour to check.
2014 static void process_plaintext_neighbour_queue (struct Neighbour *n);
2018 * Check if we have encrypted messages for the specified neighbour
2019 * pending, and if so, check with the transport about sending them
2022 * @param n neighbour to check.
2025 process_encrypted_neighbour_queue (struct Neighbour *n)
2027 struct MessageEntry *m;
2030 return; /* request already pending */
2031 m = n->encrypted_head;
2034 /* encrypted queue empty, try plaintext instead */
2035 process_plaintext_neighbour_queue (n);
2039 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2040 "Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
2041 (unsigned int) m->size,
2042 GNUNET_i2s (&n->peer),
2043 (unsigned long long) GNUNET_TIME_absolute_get_remaining (m->deadline).rel_value);
2046 GNUNET_TRANSPORT_notify_transmit_ready (transport, &n->peer,
2049 GNUNET_TIME_absolute_get_remaining
2051 ¬ify_encrypted_transmit_ready,
2055 /* message request too large or duplicate request */
2057 /* discard encrypted message */
2058 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
2062 process_encrypted_neighbour_queue (n);
2068 * Decrypt size bytes from in and write the result to out. Use the
2069 * key for inbound traffic of the given neighbour. This function does
2070 * NOT do any integrity-checks on the result.
2072 * @param n neighbour we are receiving from
2073 * @param iv initialization vector to use
2074 * @param in ciphertext
2075 * @param out plaintext
2076 * @param size size of in/out
2077 * @return GNUNET_OK on success
2080 do_decrypt (struct Neighbour *n,
2081 const struct GNUNET_CRYPTO_AesInitializationVector * iv,
2082 const void *in, void *out, size_t size)
2084 if (size != (uint16_t) size)
2089 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
2090 (n->status != PEER_STATE_KEY_CONFIRMED))
2092 GNUNET_break_op (0);
2093 return GNUNET_SYSERR;
2096 GNUNET_CRYPTO_aes_decrypt (in,
2103 return GNUNET_SYSERR;
2105 GNUNET_STATISTICS_update (stats,
2106 gettext_noop ("# bytes decrypted"),
2110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2111 "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
2112 (unsigned int) size,
2113 GNUNET_i2s (&n->peer),
2114 (unsigned int) n->decrypt_key.crc32,
2115 GNUNET_CRYPTO_crc32_n (iv, sizeof(*iv)));
2122 * Select messages for transmission. This heuristic uses a combination
2123 * of earliest deadline first (EDF) scheduling (with bounded horizon)
2124 * and priority-based discard (in case no feasible schedule exist) and
2125 * speculative optimization (defer any kind of transmission until
2126 * we either create a batch of significant size, 25% of max, or until
2127 * we are close to a deadline). Furthermore, when scheduling the
2128 * heuristic also packs as many messages into the batch as possible,
2129 * starting with those with the earliest deadline. Yes, this is fun.
2131 * @param n neighbour to select messages from
2132 * @param size number of bytes to select for transmission
2133 * @param retry_time set to the time when we should try again
2134 * (only valid if this function returns zero)
2135 * @return number of bytes selected, or 0 if we decided to
2136 * defer scheduling overall; in that case, retry_time is set.
2139 select_messages (struct Neighbour *n,
2140 size_t size, struct GNUNET_TIME_Relative *retry_time)
2142 struct MessageEntry *pos;
2143 struct MessageEntry *min;
2144 struct MessageEntry *last;
2145 unsigned int min_prio;
2146 struct GNUNET_TIME_Absolute t;
2147 struct GNUNET_TIME_Absolute now;
2148 struct GNUNET_TIME_Relative delta;
2150 struct GNUNET_TIME_Relative slack; /* how long could we wait before missing deadlines? */
2153 unsigned int queue_size;
2154 int discard_low_prio;
2156 GNUNET_assert (NULL != n->messages);
2157 now = GNUNET_TIME_absolute_get ();
2158 /* last entry in linked list of messages processed */
2160 /* should we remove the entry with the lowest
2161 priority from consideration for scheduling at the
2172 discard_low_prio = GNUNET_YES;
2173 while (GNUNET_YES == discard_low_prio)
2176 min_prio = UINT_MAX;
2177 discard_low_prio = GNUNET_NO;
2178 /* calculate number of bytes available for transmission at time "t" */
2179 avail = GNUNET_BANDWIDTH_tracker_get_available (&n->available_send_window);
2181 /* how many bytes have we (hypothetically) scheduled so far */
2183 /* maximum time we can wait before transmitting anything
2184 and still make all of our deadlines */
2185 slack = GNUNET_TIME_UNIT_FOREVER_REL;
2187 /* note that we use "*2" here because we want to look
2188 a bit further into the future; much more makes no
2189 sense since new message might be scheduled in the
2191 while ((pos != NULL) && (off < size * 2))
2193 if (pos->do_transmit == GNUNET_YES)
2195 /* already removed from consideration */
2199 if (discard_low_prio == GNUNET_NO)
2201 delta = GNUNET_TIME_absolute_get_difference (t, pos->deadline);
2202 if (delta.rel_value > 0)
2204 // FIXME: HUH? Check!
2206 avail += GNUNET_BANDWIDTH_value_get_available_until (n->bw_out,
2209 if (avail < pos->size)
2211 // FIXME: HUH? Check!
2212 discard_low_prio = GNUNET_YES; /* we could not schedule this one! */
2217 /* update slack, considering both its absolute deadline
2218 and relative deadlines caused by other messages
2219 with their respective load */
2220 slack = GNUNET_TIME_relative_min (slack,
2221 GNUNET_BANDWIDTH_value_get_delay_for (n->bw_out,
2223 if (pos->deadline.abs_value <= now.abs_value)
2226 slack = GNUNET_TIME_UNIT_ZERO;
2228 else if (GNUNET_YES == pos->got_slack)
2230 /* should be soon now! */
2231 slack = GNUNET_TIME_relative_min (slack,
2232 GNUNET_TIME_absolute_get_remaining (pos->slack_deadline));
2237 GNUNET_TIME_relative_min (slack,
2238 GNUNET_TIME_absolute_get_difference (now, pos->deadline));
2239 pos->got_slack = GNUNET_YES;
2240 pos->slack_deadline = GNUNET_TIME_absolute_min (pos->deadline,
2241 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY));
2246 t = GNUNET_TIME_absolute_max (pos->deadline, t); // HUH? Check!
2247 if (pos->priority <= min_prio)
2249 /* update min for discard */
2250 min_prio = pos->priority;
2255 if (discard_low_prio)
2257 GNUNET_assert (min != NULL);
2258 /* remove lowest-priority entry from consideration */
2259 min->do_transmit = GNUNET_YES; /* means: discard (for now) */
2263 /* guard against sending "tiny" messages with large headers without
2265 if ( (slack.rel_value > GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value) &&
2267 (queue_size <= MAX_PEER_QUEUE_SIZE - 2) )
2269 /* less than 25% of message would be filled with deadlines still
2270 being met if we delay by one second or more; so just wait for
2271 more data; but do not wait longer than 1s (since we don't want
2272 to delay messages for a really long time either). */
2273 *retry_time = GNUNET_CONSTANTS_MAX_CORK_DELAY;
2274 /* reset do_transmit values for next time */
2277 pos->do_transmit = GNUNET_NO;
2280 GNUNET_STATISTICS_update (stats,
2281 gettext_noop ("# transmissions delayed due to corking"),
2284 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2285 "Deferring transmission for %llums due to underfull message buffer size (%u/%u)\n",
2286 (unsigned long long) retry_time->rel_value,
2288 (unsigned int) size);
2292 /* select marked messages (up to size) for transmission */
2297 if ((pos->size <= size) && (pos->do_transmit == GNUNET_NO))
2299 pos->do_transmit = GNUNET_YES; /* mark for transmission */
2303 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2304 "Selecting message of size %u for transmission\n",
2305 (unsigned int) pos->size);
2311 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2312 "Not selecting message of size %u for transmission at this time (maximum is %u)\n",
2313 (unsigned int) pos->size,
2316 pos->do_transmit = GNUNET_NO; /* mark for not transmitting! */
2321 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2322 "Selected %llu/%llu bytes of %u/%u plaintext messages for transmission to `%4s'.\n",
2323 (unsigned long long) off, (unsigned long long) tsize,
2324 queue_size, (unsigned int) MAX_PEER_QUEUE_SIZE,
2325 GNUNET_i2s (&n->peer));
2332 * Batch multiple messages into a larger buffer.
2334 * @param n neighbour to take messages from
2335 * @param buf target buffer
2336 * @param size size of buf
2337 * @param deadline set to transmission deadline for the result
2338 * @param retry_time set to the time when we should try again
2339 * (only valid if this function returns zero)
2340 * @param priority set to the priority of the batch
2341 * @return number of bytes written to buf (can be zero)
2344 batch_message (struct Neighbour *n,
2347 struct GNUNET_TIME_Absolute *deadline,
2348 struct GNUNET_TIME_Relative *retry_time,
2349 unsigned int *priority)
2351 char ntmb[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
2352 struct NotifyTrafficMessage *ntm = (struct NotifyTrafficMessage*) ntmb;
2353 struct MessageEntry *pos;
2354 struct MessageEntry *prev;
2355 struct MessageEntry *next;
2360 *deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2361 *retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
2362 if (0 == select_messages (n, size, retry_time))
2365 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2366 "No messages selected, will try again in %llu ms\n",
2367 retry_time->rel_value);
2371 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND);
2372 ntm->ats_count = htonl (0);
2373 ntm->ats.type = htonl (0);
2374 ntm->ats.value = htonl (0);
2375 ntm->peer = n->peer;
2378 while ((pos != NULL) && (size >= sizeof (struct GNUNET_MessageHeader)))
2381 if (GNUNET_YES == pos->do_transmit)
2383 GNUNET_assert (pos->size <= size);
2384 /* do notifications */
2385 /* FIXME: track if we have *any* client that wants
2386 full notifications and only do this if that is
2388 if (pos->size < GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct NotifyTrafficMessage))
2390 memcpy (&ntm[1], &pos[1], pos->size);
2391 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
2392 sizeof (struct GNUNET_MessageHeader));
2393 send_to_all_clients (&ntm->header,
2395 GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);
2399 /* message too large for 'full' notifications, we do at
2400 least the 'hdr' type */
2403 sizeof (struct GNUNET_MessageHeader));
2405 ntm->header.size = htons (sizeof (struct NotifyTrafficMessage) +
2407 send_to_all_clients (&ntm->header,
2409 GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);
2411 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2412 "Encrypting %u bytes with message of type %u and size %u\n",
2414 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->type),
2415 (unsigned int) ntohs(((const struct GNUNET_MessageHeader*)&pos[1])->size));
2417 /* copy for encrypted transmission */
2418 memcpy (&buf[ret], &pos[1], pos->size);
2421 *priority += pos->priority;
2423 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2424 "Adding plaintext message of size %u with deadline %llu ms to batch\n",
2425 (unsigned int) pos->size,
2426 (unsigned long long) GNUNET_TIME_absolute_get_remaining (pos->deadline).rel_value);
2428 deadline->abs_value = GNUNET_MIN (deadline->abs_value, pos->deadline.abs_value);
2442 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2443 "Deadline for message batch is %llu ms\n",
2444 GNUNET_TIME_absolute_get_remaining (*deadline).rel_value);
2451 * Remove messages with deadlines that have long expired from
2454 * @param n neighbour to inspect
2457 discard_expired_messages (struct Neighbour *n)
2459 struct MessageEntry *prev;
2460 struct MessageEntry *next;
2461 struct MessageEntry *pos;
2462 struct GNUNET_TIME_Absolute now;
2463 struct GNUNET_TIME_Relative delta;
2467 now = GNUNET_TIME_absolute_get ();
2473 delta = GNUNET_TIME_absolute_get_difference (pos->deadline, now);
2474 if (delta.rel_value > PAST_EXPIRATION_DISCARD_TIME.rel_value)
2477 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2478 "Message is %llu ms past due, discarding.\n",
2485 GNUNET_STATISTICS_update (stats,
2486 gettext_noop ("# messages discarded (expired prior to transmission)"),
2496 if (GNUNET_YES == disc)
2497 schedule_peer_messages (n);
2502 * Signature of the main function of a task.
2504 * @param cls closure
2505 * @param tc context information (why was this task triggered now)
2508 retry_plaintext_processing (void *cls,
2509 const struct GNUNET_SCHEDULER_TaskContext *tc)
2511 struct Neighbour *n = cls;
2513 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2514 process_plaintext_neighbour_queue (n);
2519 * Send our key (and encrypted PING) to the other peer.
2521 * @param n the other peer
2523 static void send_key (struct Neighbour *n);
2526 * Task that will retry "send_key" if our previous attempt failed
2530 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2532 struct Neighbour *n = cls;
2535 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2536 "Retrying key transmission to `%4s'\n",
2537 GNUNET_i2s (&n->peer));
2539 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
2540 n->set_key_retry_frequency =
2541 GNUNET_TIME_relative_multiply (n->set_key_retry_frequency, 2);
2547 * Check if we have plaintext messages for the specified neighbour
2548 * pending, and if so, consider batching and encrypting them (and
2549 * then trigger processing of the encrypted queue if needed).
2551 * @param n neighbour to check.
2554 process_plaintext_neighbour_queue (struct Neighbour *n)
2556 char pbuf[GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE + sizeof (struct EncryptedMessage)]; /* plaintext */
2558 struct EncryptedMessage *em; /* encrypted message */
2559 struct EncryptedMessage *ph; /* plaintext header */
2560 struct MessageEntry *me;
2561 unsigned int priority;
2562 struct GNUNET_TIME_Absolute deadline;
2563 struct GNUNET_TIME_Relative retry_time;
2564 struct GNUNET_CRYPTO_AesInitializationVector iv;
2565 struct GNUNET_CRYPTO_AuthKey auth_key;
2567 if (n->retry_plaintext_task != GNUNET_SCHEDULER_NO_TASK)
2569 GNUNET_SCHEDULER_cancel (n->retry_plaintext_task);
2570 n->retry_plaintext_task = GNUNET_SCHEDULER_NO_TASK;
2574 case PEER_STATE_DOWN:
2577 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2578 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2579 GNUNET_i2s(&n->peer));
2582 case PEER_STATE_KEY_SENT:
2583 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2584 n->retry_set_key_task
2585 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2586 &set_key_retry_task, n);
2588 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2589 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2590 GNUNET_i2s(&n->peer));
2593 case PEER_STATE_KEY_RECEIVED:
2594 if (n->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK)
2595 n->retry_set_key_task
2596 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
2597 &set_key_retry_task, n);
2599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2600 "Not yet connected to `%4s', deferring processing of plaintext messages.\n",
2601 GNUNET_i2s(&n->peer));
2604 case PEER_STATE_KEY_CONFIRMED:
2605 /* ready to continue */
2608 discard_expired_messages (n);
2609 if (n->messages == NULL)
2612 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2613 "Plaintext message queue for `%4s' is empty.\n",
2614 GNUNET_i2s(&n->peer));
2616 return; /* no pending messages */
2618 if (n->encrypted_head != NULL)
2621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2622 "Encrypted message queue for `%4s' is still full, delaying plaintext processing.\n",
2623 GNUNET_i2s(&n->peer));
2625 return; /* wait for messages already encrypted to be
2628 ph = (struct EncryptedMessage *) pbuf;
2629 deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
2631 used = sizeof (struct EncryptedMessage);
2632 used += batch_message (n,
2634 GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE,
2635 &deadline, &retry_time, &priority);
2636 if (used == sizeof (struct EncryptedMessage))
2639 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2640 "No messages selected for transmission to `%4s' at this time, will try again later.\n",
2641 GNUNET_i2s(&n->peer));
2643 /* no messages selected for sending, try again later... */
2644 n->retry_plaintext_task =
2645 GNUNET_SCHEDULER_add_delayed (retry_time,
2646 &retry_plaintext_processing, n);
2649 #if DEBUG_CORE_QUOTA
2650 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2651 "Sending %u b/s as new limit to peer `%4s'\n",
2652 (unsigned int) ntohl (n->bw_in.value__),
2653 GNUNET_i2s (&n->peer));
2655 ph->iv_seed = htonl (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
2656 ph->sequence_number = htonl (++n->last_sequence_number_sent);
2657 ph->inbound_bw_limit = n->bw_in;
2658 ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
2660 /* setup encryption message header */
2661 me = GNUNET_malloc (sizeof (struct MessageEntry) + used);
2662 me->deadline = deadline;
2663 me->priority = priority;
2665 em = (struct EncryptedMessage *) &me[1];
2666 em->header.size = htons (used);
2667 em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
2668 em->iv_seed = ph->iv_seed;
2669 derive_iv (&iv, &n->encrypt_key, ph->iv_seed, &n->peer);
2672 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2673 "Encrypting %u bytes of plaintext messages for `%4s' for transmission in %llums.\n",
2674 (unsigned int) used - ENCRYPTED_HEADER_SIZE,
2675 GNUNET_i2s(&n->peer),
2676 (unsigned long long) GNUNET_TIME_absolute_get_remaining (deadline).rel_value);
2678 GNUNET_assert (GNUNET_OK ==
2681 &ph->sequence_number,
2682 &em->sequence_number, used - ENCRYPTED_HEADER_SIZE));
2683 derive_auth_key (&auth_key,
2686 n->encrypt_key_created);
2687 GNUNET_CRYPTO_hmac (&auth_key,
2688 &em->sequence_number,
2689 used - ENCRYPTED_HEADER_SIZE,
2692 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2693 "Authenticated %u bytes of ciphertext %u: `%s'\n",
2694 used - ENCRYPTED_HEADER_SIZE,
2695 GNUNET_CRYPTO_crc32_n (&em->sequence_number,
2696 used - ENCRYPTED_HEADER_SIZE),
2697 GNUNET_h2s (&em->hmac));
2699 /* append to transmission list */
2700 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
2704 process_encrypted_neighbour_queue (n);
2705 schedule_peer_messages (n);
2710 * Function that recalculates the bandwidth quota for the
2711 * given neighbour and transmits it to the transport service.
2713 * @param cls neighbour for the quota update
2717 neighbour_quota_update (void *cls,
2718 const struct GNUNET_SCHEDULER_TaskContext *tc);
2722 * Schedule the task that will recalculate the bandwidth
2723 * quota for this peer (and possibly force a disconnect of
2724 * idle peers by calculating a bandwidth of zero).
2727 schedule_quota_update (struct Neighbour *n)
2729 GNUNET_assert (n->quota_update_task ==
2730 GNUNET_SCHEDULER_NO_TASK);
2731 n->quota_update_task
2732 = GNUNET_SCHEDULER_add_delayed (QUOTA_UPDATE_FREQUENCY,
2733 &neighbour_quota_update,
2739 * Initialize a new 'struct Neighbour'.
2741 * @param pid ID of the new neighbour
2742 * @return handle for the new neighbour
2744 static struct Neighbour *
2745 create_neighbour (const struct GNUNET_PeerIdentity *pid)
2747 struct Neighbour *n;
2748 struct GNUNET_TIME_Absolute now;
2751 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2752 "Creating neighbour entry for peer `%4s'\n",
2755 n = GNUNET_malloc (sizeof (struct Neighbour));
2757 GNUNET_CRYPTO_aes_create_session_key (&n->encrypt_key);
2758 now = GNUNET_TIME_absolute_get ();
2759 n->encrypt_key_created = now;
2760 n->last_activity = now;
2761 n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
2762 n->bw_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2763 n->bw_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2764 n->bw_out_internal_limit = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
2765 n->bw_out_external_limit = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
2766 n->ping_challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
2768 GNUNET_assert (GNUNET_OK ==
2769 GNUNET_CONTAINER_multihashmap_put (neighbours,
2770 &n->peer.hashPubKey,
2772 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2773 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"),
2774 GNUNET_CONTAINER_multihashmap_size (neighbours), GNUNET_NO);
2775 neighbour_quota_update (n, NULL);
2776 consider_free_neighbour (n);
2782 * Handle CORE_SEND request.
2785 * @param client the client issuing the request
2786 * @param message the "struct SendMessage"
2789 handle_client_send (void *cls,
2790 struct GNUNET_SERVER_Client *client,
2791 const struct GNUNET_MessageHeader *message)
2793 const struct SendMessage *sm;
2794 struct Neighbour *n;
2795 struct MessageEntry *prev;
2796 struct MessageEntry *pos;
2797 struct MessageEntry *e;
2798 struct MessageEntry *min_prio_entry;
2799 struct MessageEntry *min_prio_prev;
2800 unsigned int min_prio;
2801 unsigned int queue_size;
2804 msize = ntohs (message->size);
2806 sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
2808 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));
2811 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2814 sm = (const struct SendMessage *) message;
2815 msize -= sizeof (struct SendMessage);
2816 if (0 == memcmp (&sm->peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
2819 GNUNET_SERVER_mst_receive (mst,
2821 (const char*) &sm[1],
2826 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2829 n = find_neighbour (&sm->peer);
2831 n = create_neighbour (&sm->peer);
2833 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2834 "Core received `%s' request, queueing %u bytes of plaintext data for transmission to `%4s'.\n",
2836 (unsigned int) msize,
2837 GNUNET_i2s (&sm->peer));
2839 discard_expired_messages (n);
2840 /* bound queue size */
2841 /* NOTE: this entire block to bound the queue size should be
2842 obsolete with the new client-request code and the
2843 'schedule_peer_messages' mechanism; we still have this code in
2844 here for now as a sanity check for the new mechanmism;
2845 ultimately, we should probably simply reject SEND messages that
2846 are not 'approved' (or provide a new core API for very unreliable
2847 delivery that always sends with priority 0). Food for thought. */
2848 min_prio = UINT32_MAX;
2849 min_prio_entry = NULL;
2850 min_prio_prev = NULL;
2856 if (pos->priority <= min_prio)
2858 min_prio_entry = pos;
2859 min_prio_prev = prev;
2860 min_prio = pos->priority;
2866 if (queue_size >= MAX_PEER_QUEUE_SIZE)
2869 if (ntohl(sm->priority) <= min_prio)
2871 /* discard new entry; this should no longer happen! */
2874 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2875 "Queue full (%u/%u), discarding new request (%u bytes of type %u)\n",
2877 (unsigned int) MAX_PEER_QUEUE_SIZE,
2878 (unsigned int) msize,
2879 (unsigned int) ntohs (message->type));
2881 GNUNET_STATISTICS_update (stats,
2882 gettext_noop ("# discarded CORE_SEND requests"),
2886 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2889 GNUNET_assert (min_prio_entry != NULL);
2890 /* discard "min_prio_entry" */
2892 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2893 "Queue full, discarding existing older request\n");
2895 GNUNET_STATISTICS_update (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 1, GNUNET_NO);
2896 if (min_prio_prev == NULL)
2897 n->messages = min_prio_entry->next;
2899 min_prio_prev->next = min_prio_entry->next;
2900 GNUNET_free (min_prio_entry);
2904 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2905 "Adding transmission request for `%4s' of size %u to queue\n",
2906 GNUNET_i2s (&sm->peer),
2907 (unsigned int) msize);
2909 GNUNET_break (0 == ntohl (sm->reserved));
2910 e = GNUNET_malloc (sizeof (struct MessageEntry) + msize);
2911 e->deadline = GNUNET_TIME_absolute_ntoh (sm->deadline);
2912 e->priority = ntohl (sm->priority);
2914 if (GNUNET_YES != (int) ntohl (sm->cork))
2915 e->got_slack = GNUNET_YES;
2916 memcpy (&e[1], &sm[1], msize);
2918 /* insert, keep list sorted by deadline */
2921 while ((pos != NULL) && (pos->deadline.abs_value < e->deadline.abs_value))
2932 /* consider scheduling now */
2933 process_plaintext_neighbour_queue (n);
2935 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2940 * Handle CORE_REQUEST_CONNECT request.
2943 * @param client the client issuing the request
2944 * @param message the "struct ConnectMessage"
2947 handle_client_request_connect (void *cls,
2948 struct GNUNET_SERVER_Client *client,
2949 const struct GNUNET_MessageHeader *message)
2951 const struct ConnectMessage *cm = (const struct ConnectMessage*) message;
2952 struct Neighbour *n;
2954 if (0 == memcmp (&cm->peer,
2956 sizeof (struct GNUNET_PeerIdentity)))
2958 /* In this case a client has asked us to connect to ourselves, not really an error! */
2959 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2962 GNUNET_break (ntohl (cm->reserved) == 0);
2964 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2965 "Core received `%s' request for `%4s', will try to establish connection\n",
2967 GNUNET_i2s (&cm->peer));
2969 GNUNET_STATISTICS_update (stats,
2970 gettext_noop ("# connection requests received"),
2973 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2974 n = find_neighbour (&cm->peer);
2976 (GNUNET_YES != n->is_connected) )
2978 GNUNET_TRANSPORT_try_connect (transport,
2983 GNUNET_STATISTICS_update (stats,
2984 gettext_noop ("# connection requests ignored (already connected)"),
2992 * PEERINFO is giving us a HELLO for a peer. Add the public key to
2993 * the neighbour's struct and retry send_key. Or, if we did not get a
2994 * HELLO, just do nothing.
2996 * @param cls the 'struct Neighbour' to retry sending the key for
2997 * @param peer the peer for which this is the HELLO
2998 * @param hello HELLO message of that peer
2999 * @param err_msg NULL if successful, otherwise contains error message
3002 process_hello_retry_send_key (void *cls,
3003 const struct GNUNET_PeerIdentity *peer,
3004 const struct GNUNET_HELLO_Message *hello,
3005 const char *err_msg)
3007 struct Neighbour *n = cls;
3009 if (err_msg != NULL)
3011 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3012 _("Error in communication with PEERINFO service\n"));
3019 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3020 "Entered `%s' and `%s' is NULL!\n",
3021 "process_hello_retry_send_key",
3025 if (n->public_key != NULL)
3027 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3029 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3030 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3032 GNUNET_STATISTICS_update (stats,
3033 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3041 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3042 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
3043 GNUNET_i2s (&n->peer));
3045 GNUNET_STATISTICS_update (stats,
3046 gettext_noop ("# Delayed connecting due to lack of public key"),
3049 if (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task)
3050 n->retry_set_key_task
3051 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3052 &set_key_retry_task, n);
3058 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3059 "Entered `%s' for peer `%4s'\n",
3060 "process_hello_retry_send_key",
3063 if (n->public_key != NULL)
3065 /* already have public key, why are we here? */
3071 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3072 "Received new `%s' message for `%4s', initiating key exchange.\n",
3077 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3078 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3080 GNUNET_STATISTICS_update (stats,
3081 gettext_noop ("# Error extracting public key from HELLO"),
3084 GNUNET_free (n->public_key);
3085 n->public_key = NULL;
3087 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3088 "GNUNET_HELLO_get_key returned awfully\n");
3096 * Send our key (and encrypted PING) to the other peer.
3098 * @param n the other peer
3101 send_key (struct Neighbour *n)
3103 struct MessageEntry *pos;
3104 struct SetKeyMessage *sm;
3105 struct MessageEntry *me;
3106 struct PingMessage pp;
3107 struct PingMessage *pm;
3108 struct GNUNET_CRYPTO_AesInitializationVector iv;
3110 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3112 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3113 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3115 if (n->pitr != NULL)
3118 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3119 "Key exchange in progress with `%4s'.\n",
3120 GNUNET_i2s (&n->peer));
3122 return; /* already in progress */
3124 if (GNUNET_YES != n->is_connected)
3126 GNUNET_STATISTICS_update (stats,
3127 gettext_noop ("# Asking transport to connect (for SET_KEY)"),
3130 GNUNET_TRANSPORT_try_connect (transport,
3135 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3136 "Asked to perform key exchange with `%4s'.\n",
3137 GNUNET_i2s (&n->peer));
3139 if (n->public_key == NULL)
3141 /* lookup n's public key, then try again */
3143 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3144 "Lacking public key for `%4s', trying to obtain one (send_key).\n",
3145 GNUNET_i2s (&n->peer));
3147 GNUNET_assert (n->pitr == NULL);
3148 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3150 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20),
3151 &process_hello_retry_send_key, n);
3154 pos = n->encrypted_head;
3157 if (GNUNET_YES == pos->is_setkey)
3159 if (pos->sender_status == n->status)
3162 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3163 "`%s' message for `%4s' queued already\n",
3165 GNUNET_i2s (&n->peer));
3167 goto trigger_processing;
3169 GNUNET_CONTAINER_DLL_remove (n->encrypted_head,
3174 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3175 "Removing queued `%s' message for `%4s', will create a new one\n",
3177 GNUNET_i2s (&n->peer));
3187 case PEER_STATE_DOWN:
3188 n->status = PEER_STATE_KEY_SENT;
3190 case PEER_STATE_KEY_SENT:
3192 case PEER_STATE_KEY_RECEIVED:
3194 case PEER_STATE_KEY_CONFIRMED:
3202 /* first, set key message */
3203 me = GNUNET_malloc (sizeof (struct MessageEntry) +
3204 sizeof (struct SetKeyMessage) +
3205 sizeof (struct PingMessage));
3206 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_SET_KEY_DELAY);
3207 me->priority = SET_KEY_PRIORITY;
3208 me->size = sizeof (struct SetKeyMessage) + sizeof (struct PingMessage);
3209 me->is_setkey = GNUNET_YES;
3210 me->got_slack = GNUNET_YES; /* do not defer this one! */
3211 me->sender_status = n->status;
3212 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3216 sm = (struct SetKeyMessage *) &me[1];
3217 sm->header.size = htons (sizeof (struct SetKeyMessage));
3218 sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
3219 sm->sender_status = htonl ((int32_t) ((n->status == PEER_STATE_DOWN) ?
3220 PEER_STATE_KEY_SENT : n->status));
3222 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3223 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3224 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3225 sizeof (struct GNUNET_PeerIdentity));
3226 sm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
3227 sm->creation_time = GNUNET_TIME_absolute_hton (n->encrypt_key_created);
3228 sm->target = n->peer;
3229 GNUNET_assert (GNUNET_OK ==
3230 GNUNET_CRYPTO_rsa_encrypt (&n->encrypt_key,
3232 GNUNET_CRYPTO_AesSessionKey),
3234 &sm->encrypted_key));
3235 GNUNET_assert (GNUNET_OK ==
3236 GNUNET_CRYPTO_rsa_sign (my_private_key, &sm->purpose,
3238 pm = (struct PingMessage *) &sm[1];
3239 pm->header.size = htons (sizeof (struct PingMessage));
3240 pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
3241 pm->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3242 derive_iv (&iv, &n->encrypt_key, pm->iv_seed, &n->peer);
3243 pp.challenge = n->ping_challenge;
3244 pp.target = n->peer;
3246 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3247 "Encrypting `%s' and `%s' messages with challenge %u for `%4s' using key %u, IV %u (salt %u).\n",
3249 (unsigned int) n->ping_challenge,
3250 GNUNET_i2s (&n->peer),
3251 (unsigned int) n->encrypt_key.crc32,
3252 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3259 sizeof (struct PingMessage) -
3260 ((void *) &pm->target - (void *) pm));
3261 GNUNET_STATISTICS_update (stats,
3262 gettext_noop ("# SET_KEY and PING messages created"),
3266 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3267 "Have %llu ms left for `%s' transmission.\n",
3268 (unsigned long long) GNUNET_TIME_absolute_get_remaining (me->deadline).rel_value,
3272 /* trigger queue processing */
3273 process_encrypted_neighbour_queue (n);
3274 if ( (n->status != PEER_STATE_KEY_CONFIRMED) &&
3275 (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task) )
3276 n->retry_set_key_task
3277 = GNUNET_SCHEDULER_add_delayed (n->set_key_retry_frequency,
3278 &set_key_retry_task, n);
3283 * We received a SET_KEY message. Validate and update
3284 * our key material and status.
3286 * @param n the neighbour from which we received message m
3287 * @param m the set key message we received
3288 * @param ats performance data
3289 * @param ats_count number of entries in ats (excluding 0-termination)
3292 handle_set_key (struct Neighbour *n,
3293 const struct SetKeyMessage *m,
3294 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3295 uint32_t ats_count);
3300 * PEERINFO is giving us a HELLO for a peer. Add the public key to
3301 * the neighbour's struct and retry handling the set_key message. Or,
3302 * if we did not get a HELLO, just free the set key message.
3304 * @param cls pointer to the set key message
3305 * @param peer the peer for which this is the HELLO
3306 * @param hello HELLO message of that peer
3307 * @param err_msg NULL if successful, otherwise contains error message
3310 process_hello_retry_handle_set_key (void *cls,
3311 const struct GNUNET_PeerIdentity *peer,
3312 const struct GNUNET_HELLO_Message *hello,
3313 const char *err_msg)
3315 struct Neighbour *n = cls;
3316 struct SetKeyMessage *sm = n->skm;
3318 if (err_msg != NULL)
3320 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3321 _("Error in communication with PEERINFO service\n"));
3329 if (n->public_key != NULL)
3332 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3333 "Received `%s' for `%4s', continuing processing of `%s' message.\n",
3335 GNUNET_i2s (&n->peer),
3338 handle_set_key (n, sm, NULL, 0);
3342 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3343 _("Ignoring `%s' message due to lack of public key for peer `%4s' (failed to obtain one).\n"),
3345 GNUNET_i2s (&n->peer));
3350 if (n->public_key != NULL)
3351 return; /* multiple HELLOs match!? */
3353 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3354 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
3356 GNUNET_break_op (0);
3357 GNUNET_free (n->public_key);
3358 n->public_key = NULL;
3364 * Merge the given performance data with the data we currently
3365 * track for the given neighbour.
3367 * @param n neighbour
3368 * @param ats new performance data
3369 * @param ats_count number of records in ats
3372 update_neighbour_performance (struct Neighbour *n,
3373 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3381 for (i = 0; i < ats_count; i++)
3383 for (j=0;j < n->ats_count; j++)
3385 if (n->ats[j].type == ats[i].type)
3387 n->ats[j].value = ats[i].value;
3391 if (j == n->ats_count)
3393 GNUNET_array_append (n->ats,
3402 * We received a PING message. Validate and transmit
3405 * @param n sender of the PING
3406 * @param m the encrypted PING message itself
3407 * @param ats performance data
3408 * @param ats_count number of entries in ats (excluding 0-termination)
3411 handle_ping (struct Neighbour *n,
3412 const struct PingMessage *m,
3413 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3416 struct PingMessage t;
3417 struct PongMessage tx;
3418 struct PongMessage *tp;
3419 struct MessageEntry *me;
3420 struct GNUNET_CRYPTO_AesInitializationVector iv;
3423 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3424 "Core service receives `%s' request from `%4s'.\n",
3425 "PING", GNUNET_i2s (&n->peer));
3427 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
3433 sizeof (struct PingMessage) -
3434 ((void *) &m->target - (void *) m)))
3437 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3438 "Decrypted `%s' to `%4s' with challenge %u decrypted using key %u, IV %u (salt %u)\n",
3440 GNUNET_i2s (&t.target),
3441 (unsigned int) t.challenge,
3442 (unsigned int) n->decrypt_key.crc32,
3443 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3446 GNUNET_STATISTICS_update (stats,
3447 gettext_noop ("# PING messages decrypted"),
3450 if (0 != memcmp (&t.target,
3451 &my_identity, sizeof (struct GNUNET_PeerIdentity)))
3456 GNUNET_snprintf(sender, sizeof (sender), "%8s", GNUNET_i2s (&n->peer));
3457 GNUNET_snprintf(peer, sizeof (peer), "%8s", GNUNET_i2s (&t.target));
3458 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3459 _("Received PING from `%s' for different identity: I am `%s', PONG identity: `%s'\n"),
3461 GNUNET_i2s (&my_identity),
3463 GNUNET_break_op (0);
3466 update_neighbour_performance (n, ats, ats_count);
3467 me = GNUNET_malloc (sizeof (struct MessageEntry) +
3468 sizeof (struct PongMessage));
3469 GNUNET_CONTAINER_DLL_insert_after (n->encrypted_head,
3473 me->deadline = GNUNET_TIME_relative_to_absolute (MAX_PONG_DELAY);
3474 me->priority = PONG_PRIORITY;
3475 me->size = sizeof (struct PongMessage);
3476 tx.inbound_bw_limit = n->bw_in;
3477 tx.challenge = t.challenge;
3478 tx.target = t.target;
3479 tp = (struct PongMessage *) &me[1];
3480 tp->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
3481 tp->header.size = htons (sizeof (struct PongMessage));
3482 tp->iv_seed = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
3483 derive_pong_iv (&iv, &n->encrypt_key, tp->iv_seed, t.challenge, &n->peer);
3488 sizeof (struct PongMessage) -
3489 ((void *) &tp->challenge - (void *) tp));
3490 GNUNET_STATISTICS_update (stats,
3491 gettext_noop ("# PONG messages created"),
3495 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3496 "Encrypting `%s' with challenge %u using key %u, IV %u (salt %u)\n",
3498 (unsigned int) t.challenge,
3499 (unsigned int) n->encrypt_key.crc32,
3500 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3503 /* trigger queue processing */
3504 process_encrypted_neighbour_queue (n);
3509 * We received a PONG message. Validate and update our status.
3511 * @param n sender of the PONG
3512 * @param m the encrypted PONG message itself
3513 * @param ats performance data
3514 * @param ats_count number of entries in ats (excluding 0-termination)
3517 handle_pong (struct Neighbour *n,
3518 const struct PongMessage *m,
3519 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3522 struct PongMessage t;
3523 struct ConnectNotifyMessage *cnm;
3524 struct GNUNET_CRYPTO_AesInitializationVector iv;
3525 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
3526 struct GNUNET_TRANSPORT_ATS_Information *mats;
3530 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3531 "Core service receives `%s' response from `%4s'.\n",
3532 "PONG", GNUNET_i2s (&n->peer));
3534 /* mark as garbage, just to be sure */
3535 memset (&t, 255, sizeof (t));
3536 derive_pong_iv (&iv, &n->decrypt_key, m->iv_seed, n->ping_challenge,
3543 sizeof (struct PongMessage) -
3544 ((void *) &m->challenge - (void *) m)))
3546 GNUNET_break_op (0);
3549 GNUNET_STATISTICS_update (stats,
3550 gettext_noop ("# PONG messages decrypted"),
3554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3555 "Decrypted `%s' from `%4s' with challenge %u using key %u, IV %u (salt %u)\n",
3557 GNUNET_i2s (&t.target),
3558 (unsigned int) t.challenge,
3559 (unsigned int) n->decrypt_key.crc32,
3560 GNUNET_CRYPTO_crc32_n (&iv, sizeof(iv)),
3563 if ((0 != memcmp (&t.target,
3565 sizeof (struct GNUNET_PeerIdentity))) ||
3566 (n->ping_challenge != t.challenge))
3568 /* PONG malformed */
3570 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3571 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
3573 GNUNET_i2s (&n->peer),
3574 (unsigned int) n->ping_challenge);
3575 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3576 "Received malformed `%s' received from `%4s' with challenge %u\n",
3577 "PONG", GNUNET_i2s (&t.target),
3578 (unsigned int) t.challenge);
3580 GNUNET_break_op (n->ping_challenge != t.challenge);
3585 case PEER_STATE_DOWN:
3586 GNUNET_break (0); /* should be impossible */
3588 case PEER_STATE_KEY_SENT:
3589 GNUNET_break (0); /* should be impossible, how did we decrypt? */
3591 case PEER_STATE_KEY_RECEIVED:
3592 GNUNET_STATISTICS_update (stats,
3593 gettext_noop ("# Session keys confirmed via PONG"),
3596 n->status = PEER_STATE_KEY_CONFIRMED;
3597 if (n->bw_out_external_limit.value__ != t.inbound_bw_limit.value__)
3599 n->bw_out_external_limit = t.inbound_bw_limit;
3600 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
3601 n->bw_out_internal_limit);
3602 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
3604 GNUNET_TRANSPORT_set_quota (transport,
3610 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3611 "Confirmed key via `%s' message for peer `%4s'\n",
3612 "PONG", GNUNET_i2s (&n->peer));
3614 if (n->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
3616 GNUNET_SCHEDULER_cancel (n->retry_set_key_task);
3617 n->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
3619 update_neighbour_performance (n, ats, ats_count);
3620 size = sizeof (struct ConnectNotifyMessage) +
3621 (n->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3622 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3625 /* recovery strategy: throw away performance data */
3626 GNUNET_array_grow (n->ats,
3629 size = sizeof (struct PeerStatusNotifyMessage) +
3630 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3632 cnm = (struct ConnectNotifyMessage*) buf;
3633 cnm->header.size = htons (size);
3634 cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
3635 cnm->ats_count = htonl (n->ats_count);
3636 cnm->peer = n->peer;
3640 n->ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
3641 mats[n->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3642 mats[n->ats_count].value = htonl (0);
3643 send_to_all_clients (&cnm->header,
3645 GNUNET_CORE_OPTION_SEND_CONNECT);
3646 process_encrypted_neighbour_queue (n);
3648 case PEER_STATE_KEY_CONFIRMED:
3649 n->last_activity = GNUNET_TIME_absolute_get ();
3650 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
3651 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
3653 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
3656 handle_peer_status_change (n);
3666 * We received a SET_KEY message. Validate and update
3667 * our key material and status.
3669 * @param n the neighbour from which we received message m
3670 * @param m the set key message we received
3671 * @param ats performance data
3672 * @param ats_count number of entries in ats (excluding 0-termination)
3675 handle_set_key (struct Neighbour *n,
3676 const struct SetKeyMessage *m,
3677 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3680 struct SetKeyMessage *m_cpy;
3681 struct GNUNET_TIME_Absolute t;
3682 struct GNUNET_CRYPTO_AesSessionKey k;
3683 struct PingMessage *ping;
3684 struct PongMessage *pong;
3685 enum PeerStateMachine sender_status;
3688 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3689 "Core service receives `%s' request from `%4s'.\n",
3690 "SET_KEY", GNUNET_i2s (&n->peer));
3692 if (n->public_key == NULL)
3694 if (n->pitr != NULL)
3697 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3698 "Ignoring `%s' message due to lack of public key for peer (still trying to obtain one).\n",
3704 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3705 "Lacking public key for peer, trying to obtain one (handle_set_key).\n");
3707 m_cpy = GNUNET_malloc (sizeof (struct SetKeyMessage));
3708 memcpy (m_cpy, m, sizeof (struct SetKeyMessage));
3709 /* lookup n's public key, then try again */
3710 GNUNET_assert (n->skm == NULL);
3712 n->pitr = GNUNET_PEERINFO_iterate (peerinfo,
3714 GNUNET_TIME_UNIT_MINUTES,
3715 &process_hello_retry_handle_set_key, n);
3716 GNUNET_STATISTICS_update (stats,
3717 gettext_noop ("# SET_KEY messages deferred (need public key)"),
3722 if (0 != memcmp (&m->target,
3724 sizeof (struct GNUNET_PeerIdentity)))
3726 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3727 _("Received `%s' message that was for `%s', not for me. Ignoring.\n"),
3729 GNUNET_i2s (&m->target));
3732 if ((ntohl (m->purpose.size) !=
3733 sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3734 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3735 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
3736 sizeof (struct GNUNET_PeerIdentity)) ||
3738 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY,
3739 &m->purpose, &m->signature, n->public_key)))
3741 /* invalid signature */
3742 GNUNET_break_op (0);
3745 t = GNUNET_TIME_absolute_ntoh (m->creation_time);
3746 if (((n->status == PEER_STATE_KEY_RECEIVED) ||
3747 (n->status == PEER_STATE_KEY_CONFIRMED)) &&
3748 (t.abs_value < n->decrypt_key_created.abs_value))
3750 /* this could rarely happen due to massive re-ordering of
3751 messages on the network level, but is most likely either
3752 a bug or some adversary messing with us. Report. */
3753 GNUNET_break_op (0);
3757 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3758 "Decrypting key material.\n");
3760 if ((GNUNET_CRYPTO_rsa_decrypt (my_private_key,
3763 sizeof (struct GNUNET_CRYPTO_AesSessionKey))
3764 != sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
3765 (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
3767 /* failed to decrypt !? */
3768 GNUNET_break_op (0);
3771 GNUNET_STATISTICS_update (stats,
3772 gettext_noop ("# SET_KEY messages decrypted"),
3776 if (n->decrypt_key_created.abs_value != t.abs_value)
3778 /* fresh key, reset sequence numbers */
3779 n->last_sequence_number_received = 0;
3780 n->last_packets_bitmap = 0;
3781 n->decrypt_key_created = t;
3783 update_neighbour_performance (n, ats, ats_count);
3784 sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
3787 case PEER_STATE_DOWN:
3788 n->status = PEER_STATE_KEY_RECEIVED;
3790 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3791 "Responding to `%s' with my own key.\n", "SET_KEY");
3795 case PEER_STATE_KEY_SENT:
3796 case PEER_STATE_KEY_RECEIVED:
3797 n->status = PEER_STATE_KEY_RECEIVED;
3798 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3799 (sender_status != PEER_STATE_KEY_CONFIRMED))
3802 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3803 "Responding to `%s' with my own key (other peer has status %u).\n",
3805 (unsigned int) sender_status);
3810 case PEER_STATE_KEY_CONFIRMED:
3811 if ((sender_status != PEER_STATE_KEY_RECEIVED) &&
3812 (sender_status != PEER_STATE_KEY_CONFIRMED))
3815 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3816 "Responding to `%s' with my own key (other peer has status %u), I was already fully up.\n",
3818 (unsigned int) sender_status);
3827 if (n->pending_ping != NULL)
3829 ping = n->pending_ping;
3830 n->pending_ping = NULL;
3831 handle_ping (n, ping, NULL, 0);
3834 if (n->pending_pong != NULL)
3836 pong = n->pending_pong;
3837 n->pending_pong = NULL;
3838 handle_pong (n, pong, NULL, 0);
3845 * Send a P2P message to a client.
3847 * @param sender who sent us the message?
3848 * @param client who should we give the message to?
3849 * @param m contains the message to transmit
3850 * @param msize number of bytes in buf to transmit
3853 send_p2p_message_to_client (struct Neighbour *sender,
3854 struct Client *client,
3855 const void *m, size_t msize)
3857 size_t size = msize + sizeof (struct NotifyTrafficMessage) +
3858 (sender->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3860 struct NotifyTrafficMessage *ntm;
3861 struct GNUNET_TRANSPORT_ATS_Information *ats;
3863 if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3866 /* recovery strategy: throw performance data away... */
3867 GNUNET_array_grow (sender->ats,
3870 size = msize + sizeof (struct NotifyTrafficMessage) +
3871 (sender->ats_count) * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
3874 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3875 "Core service passes message from `%4s' of type %u to client.\n",
3876 GNUNET_i2s(&sender->peer),
3877 (unsigned int) ntohs (((const struct GNUNET_MessageHeader *) m)->type));
3879 ntm = (struct NotifyTrafficMessage *) buf;
3880 ntm->header.size = htons (size);
3881 ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
3882 ntm->ats_count = htonl (sender->ats_count);
3883 ntm->peer = sender->peer;
3887 sizeof (struct GNUNET_TRANSPORT_ATS_Information) * sender->ats_count);
3888 ats[sender->ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3889 ats[sender->ats_count].value = htonl (0);
3890 memcpy (&ats[sender->ats_count+1],
3893 send_to_client (client, &ntm->header, GNUNET_YES);
3898 * Deliver P2P message to interested clients.
3900 * @param cls always NULL
3901 * @param client who sent us the message (struct Neighbour)
3902 * @param m the message
3905 deliver_message (void *cls,
3907 const struct GNUNET_MessageHeader *m)
3909 struct Neighbour *sender = client;
3910 size_t msize = ntohs (m->size);
3912 struct Client *cpos;
3918 type = ntohs (m->type);
3920 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3921 "Received encapsulated message of type %u and size %u from `%4s'\n",
3922 (unsigned int) type,
3924 GNUNET_i2s (&sender->peer));
3926 GNUNET_snprintf (buf,
3928 gettext_noop ("# bytes of messages of type %u received"),
3929 (unsigned int) type);
3930 GNUNET_STATISTICS_set (stats,
3934 dropped = GNUNET_YES;
3936 while (cpos != NULL)
3938 deliver_full = GNUNET_NO;
3939 if (0 != (cpos->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND))
3940 deliver_full = GNUNET_YES;
3943 for (tpos = 0; tpos < cpos->tcnt; tpos++)
3945 if (type != cpos->types[tpos])
3947 deliver_full = GNUNET_YES;
3951 if (GNUNET_YES == deliver_full)
3953 send_p2p_message_to_client (sender, cpos, m, msize);
3954 dropped = GNUNET_NO;
3956 else if (cpos->options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)
3958 send_p2p_message_to_client (sender, cpos, m,
3959 sizeof (struct GNUNET_MessageHeader));
3963 if (dropped == GNUNET_YES)
3966 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3967 "Message of type %u from `%4s' not delivered to any client.\n",
3968 (unsigned int) type,
3969 GNUNET_i2s (&sender->peer));
3971 GNUNET_STATISTICS_update (stats,
3972 gettext_noop ("# messages not delivered to any client"),
3979 * We received an encrypted message. Decrypt, validate and
3980 * pass on to the appropriate clients.
3982 * @param n target of the message
3983 * @param m encrypted message
3984 * @param ats performance data
3985 * @param ats_count number of entries in ats (excluding 0-termination)
3988 handle_encrypted_message (struct Neighbour *n,
3989 const struct EncryptedMessage *m,
3990 const struct GNUNET_TRANSPORT_ATS_Information *ats,
3993 size_t size = ntohs (m->header.size);
3995 struct EncryptedMessage *pt; /* plaintext */
3998 struct GNUNET_TIME_Absolute t;
3999 struct GNUNET_CRYPTO_AesInitializationVector iv;
4000 struct GNUNET_CRYPTO_AuthKey auth_key;
4003 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4004 "Core service receives `%s' request from `%4s'.\n",
4005 "ENCRYPTED_MESSAGE", GNUNET_i2s (&n->peer));
4008 derive_auth_key (&auth_key,
4011 n->decrypt_key_created);
4012 GNUNET_CRYPTO_hmac (&auth_key,
4013 &m->sequence_number,
4014 size - ENCRYPTED_HEADER_SIZE, &ph);
4016 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4017 "Re-Authenticated %u bytes of ciphertext (`%u'): `%s'\n",
4018 (unsigned int) size - ENCRYPTED_HEADER_SIZE,
4019 GNUNET_CRYPTO_crc32_n (&m->sequence_number,
4020 size - ENCRYPTED_HEADER_SIZE),
4024 if (0 != memcmp (&ph,
4026 sizeof (GNUNET_HashCode)))
4028 /* checksum failed */
4029 GNUNET_break_op (0);
4032 derive_iv (&iv, &n->decrypt_key, m->iv_seed, &my_identity);
4037 &m->sequence_number,
4038 &buf[ENCRYPTED_HEADER_SIZE],
4039 size - ENCRYPTED_HEADER_SIZE))
4041 pt = (struct EncryptedMessage *) buf;
4043 /* validate sequence number */
4044 snum = ntohl (pt->sequence_number);
4045 if (n->last_sequence_number_received == snum)
4047 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4048 "Received duplicate message, ignoring.\n");
4049 /* duplicate, ignore */
4050 GNUNET_STATISTICS_set (stats,
4051 gettext_noop ("# bytes dropped (duplicates)"),
4056 if ((n->last_sequence_number_received > snum) &&
4057 (n->last_sequence_number_received - snum > 32))
4059 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4060 "Received ancient out of sequence message, ignoring.\n");
4061 /* ancient out of sequence, ignore */
4062 GNUNET_STATISTICS_set (stats,
4063 gettext_noop ("# bytes dropped (out of sequence)"),
4068 if (n->last_sequence_number_received > snum)
4070 unsigned int rotbit =
4071 1 << (n->last_sequence_number_received - snum - 1);
4072 if ((n->last_packets_bitmap & rotbit) != 0)
4074 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4075 "Received duplicate message, ignoring.\n");
4076 GNUNET_STATISTICS_set (stats,
4077 gettext_noop ("# bytes dropped (duplicates)"),
4080 /* duplicate, ignore */
4083 n->last_packets_bitmap |= rotbit;
4085 if (n->last_sequence_number_received < snum)
4087 int shift = (snum - n->last_sequence_number_received);
4088 if (shift >= 8 * sizeof(n->last_packets_bitmap))
4089 n->last_packets_bitmap = 0;
4091 n->last_packets_bitmap <<= shift;
4092 n->last_sequence_number_received = snum;
4095 /* check timestamp */
4096 t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
4097 if (GNUNET_TIME_absolute_get_duration (t).rel_value > MAX_MESSAGE_AGE.rel_value)
4099 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4101 ("Message received far too old (%llu ms). Content ignored.\n"),
4102 GNUNET_TIME_absolute_get_duration (t).rel_value);
4103 GNUNET_STATISTICS_set (stats,
4104 gettext_noop ("# bytes dropped (ancient message)"),
4110 /* process decrypted message(s) */
4111 if (n->bw_out_external_limit.value__ != pt->inbound_bw_limit.value__)
4113 #if DEBUG_CORE_SET_QUOTA
4114 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4115 "Received %u b/s as new inbound limit for peer `%4s'\n",
4116 (unsigned int) ntohl (pt->inbound_bw_limit.value__),
4117 GNUNET_i2s (&n->peer));
4119 n->bw_out_external_limit = pt->inbound_bw_limit;
4120 n->bw_out = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit,
4121 n->bw_out_internal_limit);
4122 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window,
4124 GNUNET_TRANSPORT_set_quota (transport,
4129 n->last_activity = GNUNET_TIME_absolute_get ();
4130 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
4131 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
4133 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
4136 GNUNET_STATISTICS_set (stats,
4137 gettext_noop ("# bytes of payload decrypted"),
4138 size - sizeof (struct EncryptedMessage),
4140 handle_peer_status_change (n);
4141 update_neighbour_performance (n, ats, ats_count);
4142 if (GNUNET_OK != GNUNET_SERVER_mst_receive (mst,
4144 &buf[sizeof (struct EncryptedMessage)],
4145 size - sizeof (struct EncryptedMessage),
4146 GNUNET_YES, GNUNET_NO))
4147 GNUNET_break_op (0);
4152 * Function called by the transport for each received message.
4154 * @param cls closure
4155 * @param peer (claimed) identity of the other peer
4156 * @param message the message
4157 * @param ats performance data
4158 * @param ats_count number of entries in ats (excluding 0-termination)
4161 handle_transport_receive (void *cls,
4162 const struct GNUNET_PeerIdentity *peer,
4163 const struct GNUNET_MessageHeader *message,
4164 const struct GNUNET_TRANSPORT_ATS_Information *ats,
4167 struct Neighbour *n;
4168 struct GNUNET_TIME_Absolute now;
4175 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4176 "Received message of type %u from `%4s', demultiplexing.\n",
4177 (unsigned int) ntohs (message->type),
4180 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4185 n = find_neighbour (peer);
4187 n = create_neighbour (peer);
4188 changed = GNUNET_NO;
4189 up = (n->status == PEER_STATE_KEY_CONFIRMED);
4190 type = ntohs (message->type);
4191 size = ntohs (message->size);
4194 case GNUNET_MESSAGE_TYPE_CORE_SET_KEY:
4195 if (size != sizeof (struct SetKeyMessage))
4197 GNUNET_break_op (0);
4200 GNUNET_STATISTICS_update (stats,
4201 gettext_noop ("# session keys received"),
4205 (const struct SetKeyMessage *) message,
4208 case GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE:
4209 if (size < sizeof (struct EncryptedMessage) +
4210 sizeof (struct GNUNET_MessageHeader))
4212 GNUNET_break_op (0);
4215 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
4216 (n->status != PEER_STATE_KEY_CONFIRMED))
4218 GNUNET_STATISTICS_update (stats,
4219 gettext_noop ("# failed to decrypt message (no session key)"),
4225 handle_encrypted_message (n,
4226 (const struct EncryptedMessage *) message,
4229 case GNUNET_MESSAGE_TYPE_CORE_PING:
4230 if (size != sizeof (struct PingMessage))
4232 GNUNET_break_op (0);
4235 GNUNET_STATISTICS_update (stats, gettext_noop ("# PING messages received"), 1, GNUNET_NO);
4236 if ((n->status != PEER_STATE_KEY_RECEIVED) &&
4237 (n->status != PEER_STATE_KEY_CONFIRMED))
4240 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4241 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
4242 "PING", GNUNET_i2s (&n->peer));
4244 GNUNET_free_non_null (n->pending_ping);
4245 n->pending_ping = GNUNET_malloc (sizeof (struct PingMessage));
4246 memcpy (n->pending_ping, message, sizeof (struct PingMessage));
4249 handle_ping (n, (const struct PingMessage *) message,
4252 case GNUNET_MESSAGE_TYPE_CORE_PONG:
4253 if (size != sizeof (struct PongMessage))
4255 GNUNET_break_op (0);
4258 GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages received"), 1, GNUNET_NO);
4259 if ( (n->status != PEER_STATE_KEY_RECEIVED) &&
4260 (n->status != PEER_STATE_KEY_CONFIRMED) )
4263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4264 "Core service receives `%s' request from `%4s' but have not processed key; marking as pending.\n",
4265 "PONG", GNUNET_i2s (&n->peer));
4267 GNUNET_free_non_null (n->pending_pong);
4268 n->pending_pong = GNUNET_malloc (sizeof (struct PongMessage));
4269 memcpy (n->pending_pong, message, sizeof (struct PongMessage));
4272 handle_pong (n, (const struct PongMessage *) message,
4276 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4277 _("Unsupported message of type %u received.\n"),
4278 (unsigned int) type);
4281 if (n->status == PEER_STATE_KEY_CONFIRMED)
4283 now = GNUNET_TIME_absolute_get ();
4284 n->last_activity = now;
4285 changed = GNUNET_YES;
4288 GNUNET_STATISTICS_update (stats,
4289 gettext_noop ("# established sessions"),
4292 n->time_established = now;
4294 if (n->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
4295 GNUNET_SCHEDULER_cancel (n->keep_alive_task);
4297 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
4302 handle_peer_status_change (n);
4307 * Function that recalculates the bandwidth quota for the
4308 * given neighbour and transmits it to the transport service.
4310 * @param cls neighbour for the quota update
4314 neighbour_quota_update (void *cls,
4315 const struct GNUNET_SCHEDULER_TaskContext *tc)
4317 struct Neighbour *n = cls;
4318 struct GNUNET_BANDWIDTH_Value32NBO q_in;
4319 struct GNUNET_BANDWIDTH_Value32NBO q_out;
4320 struct GNUNET_BANDWIDTH_Value32NBO q_out_min;
4323 unsigned long long distributable;
4324 uint64_t need_per_peer;
4325 uint64_t need_per_second;
4326 unsigned int neighbour_count;
4329 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4330 "Neighbour quota update calculation running for peer `%4s'\n",
4331 GNUNET_i2s (&n->peer));
4333 n->quota_update_task = GNUNET_SCHEDULER_NO_TASK;
4334 /* calculate relative preference among all neighbours;
4335 divides by a bit more to avoid division by zero AND to
4336 account for possibility of new neighbours joining any time
4337 AND to convert to double... */
4338 neighbour_count = GNUNET_CONTAINER_multihashmap_size (neighbours);
4339 if (neighbour_count == 0)
4341 if (preference_sum == 0)
4343 pref_rel = 1.0 / (double) neighbour_count;
4347 pref_rel = (double) n->current_preference / preference_sum;
4349 need_per_peer = GNUNET_BANDWIDTH_value_get_available_until (MIN_BANDWIDTH_PER_PEER,
4350 GNUNET_TIME_UNIT_SECONDS);
4351 need_per_second = need_per_peer * neighbour_count;
4353 /* calculate inbound bandwidth per peer */
4355 if (bandwidth_target_in_bps > need_per_second)
4356 distributable = bandwidth_target_in_bps - need_per_second;
4357 share = distributable * pref_rel;
4358 if (share + need_per_peer > UINT32_MAX)
4359 q_in = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4361 q_in = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4363 /* calculate outbound bandwidth per peer */
4365 if (bandwidth_target_out_bps > need_per_second)
4366 distributable = bandwidth_target_out_bps - need_per_second;
4367 share = distributable * pref_rel;
4368 if (share + need_per_peer > UINT32_MAX)
4369 q_out = GNUNET_BANDWIDTH_value_init (UINT32_MAX);
4371 q_out = GNUNET_BANDWIDTH_value_init (need_per_peer + (uint32_t) share);
4372 n->bw_out_internal_limit = q_out;
4374 q_out_min = GNUNET_BANDWIDTH_value_min (n->bw_out_external_limit, n->bw_out_internal_limit);
4375 GNUNET_BANDWIDTH_tracker_update_quota (&n->available_send_window, n->bw_out);
4377 /* check if we want to disconnect for good due to inactivity */
4378 if ( (GNUNET_TIME_absolute_get_duration (get_neighbour_timeout (n)).rel_value > 0) &&
4379 (GNUNET_TIME_absolute_get_duration (n->time_established).rel_value > GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) )
4382 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4383 "Forcing disconnect of `%4s' due to inactivity\n",
4384 GNUNET_i2s (&n->peer));
4386 q_in = GNUNET_BANDWIDTH_value_init (0); /* force disconnect */
4388 #if DEBUG_CORE_QUOTA
4389 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4390 "Current quota for `%4s' is %u/%llu b/s in (old: %u b/s) / %u out (%u internal)\n",
4391 GNUNET_i2s (&n->peer),
4392 (unsigned int) ntohl (q_in.value__),
4393 bandwidth_target_out_bps,
4394 (unsigned int) ntohl (n->bw_in.value__),
4395 (unsigned int) ntohl (n->bw_out.value__),
4396 (unsigned int) ntohl (n->bw_out_internal_limit.value__));
4398 if ((n->bw_in.value__ != q_in.value__) || (n->bw_out.value__ != q_out_min.value__))
4400 if (n->bw_in.value__ != q_in.value__)
4402 if (n->bw_out.value__ != q_out_min.value__)
4403 n->bw_out = q_out_min;
4404 if (GNUNET_YES == n->is_connected)
4405 GNUNET_TRANSPORT_set_quota (transport,
4409 handle_peer_status_change (n);
4411 schedule_quota_update (n);
4416 * Function called by transport to notify us that
4417 * a peer connected to us (on the network level).
4419 * @param cls closure
4420 * @param peer the peer that connected
4421 * @param ats performance data
4422 * @param ats_count number of entries in ats (excluding 0-termination)
4425 handle_transport_notify_connect (void *cls,
4426 const struct GNUNET_PeerIdentity *peer,
4427 const struct GNUNET_TRANSPORT_ATS_Information *ats,
4430 struct Neighbour *n;
4432 if (0 == memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)))
4437 n = find_neighbour (peer);
4440 if (GNUNET_YES == n->is_connected)
4442 /* duplicate connect notification!? */
4449 n = create_neighbour (peer);
4451 GNUNET_STATISTICS_update (stats,
4452 gettext_noop ("# peers connected (transport)"),
4455 n->is_connected = GNUNET_YES;
4456 update_neighbour_performance (n, ats, ats_count);
4457 GNUNET_BANDWIDTH_tracker_init (&n->available_send_window,
4460 GNUNET_BANDWIDTH_tracker_init (&n->available_recv_window,
4464 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4465 "Received connection from `%4s'.\n",
4466 GNUNET_i2s (&n->peer));
4468 GNUNET_TRANSPORT_set_quota (transport,
4477 * Function called by transport telling us that a peer
4480 * @param cls closure
4481 * @param peer the peer that disconnected
4484 handle_transport_notify_disconnect (void *cls,
4485 const struct GNUNET_PeerIdentity *peer)
4487 struct DisconnectNotifyMessage cnm;
4488 struct Neighbour *n;
4489 struct ClientActiveRequest *car;
4490 struct GNUNET_TIME_Relative left;
4493 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4494 "Peer `%4s' disconnected from us; received notification from transport.\n",
4497 n = find_neighbour (peer);
4503 GNUNET_break (n->is_connected == GNUNET_YES);
4504 if (n->status == PEER_STATE_KEY_CONFIRMED)
4506 cnm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
4507 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
4508 cnm.reserved = htonl (0);
4510 send_to_all_clients (&cnm.header, GNUNET_NO, GNUNET_CORE_OPTION_SEND_DISCONNECT);
4511 GNUNET_STATISTICS_update (stats,
4512 gettext_noop ("# established sessions"),
4517 /* On transport disconnect transport doesn't cancel requests, so must do so here. */
4520 GNUNET_TRANSPORT_notify_transmit_ready_cancel (n->th);
4523 n->is_connected = GNUNET_NO;
4524 n->status = PEER_STATE_DOWN;
4525 while (NULL != (car = n->active_client_request_head))
4527 GNUNET_CONTAINER_DLL_remove (n->active_client_request_head,
4528 n->active_client_request_tail,
4530 GNUNET_CONTAINER_multihashmap_remove (car->client->requests,
4531 &n->peer.hashPubKey,
4536 GNUNET_STATISTICS_update (stats,
4537 gettext_noop ("# peers connected (transport)"),
4540 if (n->dead_clean_task != GNUNET_SCHEDULER_NO_TASK)
4541 GNUNET_SCHEDULER_cancel (n->dead_clean_task);
4542 left = GNUNET_TIME_relative_subtract (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4543 GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT);
4544 n->last_activity = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (),
4546 n->dead_clean_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
4547 &consider_free_task,
4553 * Wrapper around 'free_neighbour'; helper for 'cleaning_task'.
4556 free_neighbour_helper (void *cls,
4557 const GNUNET_HashCode *key,
4560 struct Neighbour *n = value;
4568 * Last task run during shutdown. Disconnects us from
4572 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4577 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4578 "Core service shutting down.\n");
4580 GNUNET_assert (transport != NULL);
4581 GNUNET_TRANSPORT_disconnect (transport);
4583 GNUNET_CONTAINER_multihashmap_iterate (neighbours,
4584 &free_neighbour_helper,
4586 GNUNET_CONTAINER_multihashmap_destroy (neighbours);
4588 GNUNET_STATISTICS_set (stats, gettext_noop ("# neighbour entries allocated"), 0, GNUNET_NO);
4589 GNUNET_SERVER_notification_context_destroy (notifier);
4591 while (NULL != (c = clients))
4592 handle_client_disconnect (NULL, c->client_handle);
4593 if (my_private_key != NULL)
4594 GNUNET_CRYPTO_rsa_key_free (my_private_key);
4596 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4597 if (peerinfo != NULL)
4598 GNUNET_PEERINFO_disconnect (peerinfo);
4600 GNUNET_SERVER_mst_destroy (mst);
4605 * Initiate core service.
4607 * @param cls closure
4608 * @param server the initialized server
4609 * @param c configuration to use
4613 struct GNUNET_SERVER_Handle *server,
4614 const struct GNUNET_CONFIGURATION_Handle *c)
4616 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4617 {&handle_client_init, NULL,
4618 GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
4619 {&handle_client_iterate_peers, NULL,
4620 GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
4621 sizeof (struct GNUNET_MessageHeader)},
4622 {&handle_client_have_peer, NULL,
4623 GNUNET_MESSAGE_TYPE_CORE_PEER_CONNECTED,
4624 sizeof (struct GNUNET_MessageHeader) + sizeof(struct GNUNET_PeerIdentity)},
4625 {&handle_client_request_info, NULL,
4626 GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO,
4627 sizeof (struct RequestInfoMessage)},
4628 {&handle_client_send_request, NULL,
4629 GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST,
4630 sizeof (struct SendMessageRequest)},
4631 {&handle_client_send, NULL,
4632 GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
4633 {&handle_client_request_connect, NULL,
4634 GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT,
4635 sizeof (struct ConnectMessage)},
4641 /* parse configuration */
4644 GNUNET_CONFIGURATION_get_value_number (c,
4647 &bandwidth_target_in_bps)) ||
4649 GNUNET_CONFIGURATION_get_value_number (c,
4652 &bandwidth_target_out_bps)) ||
4654 GNUNET_CONFIGURATION_get_value_filename (c,
4656 "HOSTKEY", &keyfile)))
4658 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4660 ("Core service is lacking key configuration settings. Exiting.\n"));
4661 GNUNET_SCHEDULER_shutdown ();
4664 peerinfo = GNUNET_PEERINFO_connect (cfg);
4665 if (NULL == peerinfo)
4667 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4668 _("Could not access PEERINFO service. Exiting.\n"));
4669 GNUNET_SCHEDULER_shutdown ();
4670 GNUNET_free (keyfile);
4673 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4674 GNUNET_free (keyfile);
4675 if (my_private_key == NULL)
4677 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4678 _("Core service could not access hostkey. Exiting.\n"));
4679 GNUNET_PEERINFO_disconnect (peerinfo);
4680 GNUNET_SCHEDULER_shutdown ();
4683 neighbours = GNUNET_CONTAINER_multihashmap_create (128);
4684 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4685 GNUNET_CRYPTO_hash (&my_public_key,
4686 sizeof (my_public_key), &my_identity.hashPubKey);
4687 self.public_key = &my_public_key;
4688 self.peer = my_identity;
4689 self.last_activity = GNUNET_TIME_UNIT_FOREVER_ABS;
4690 self.status = PEER_STATE_KEY_CONFIRMED;
4691 self.is_connected = GNUNET_YES;
4692 /* setup notification */
4693 notifier = GNUNET_SERVER_notification_context_create (server,
4695 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4696 /* setup transport connection */
4697 transport = GNUNET_TRANSPORT_connect (cfg,
4700 &handle_transport_receive,
4701 &handle_transport_notify_connect,
4702 &handle_transport_notify_disconnect);
4703 GNUNET_assert (NULL != transport);
4704 stats = GNUNET_STATISTICS_create ("core", cfg);
4706 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded CORE_SEND requests"), 0, GNUNET_NO);
4707 GNUNET_STATISTICS_set (stats, gettext_noop ("# discarded lower priority CORE_SEND requests"), 0, GNUNET_NO);
4709 mst = GNUNET_SERVER_mst_create (&deliver_message,
4711 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4712 &cleaning_task, NULL);
4713 /* process client requests */
4714 GNUNET_SERVER_add_handlers (server, handlers);
4715 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4716 _("Core service of `%4s' ready.\n"), GNUNET_i2s (&my_identity));
4722 * The main function for the transport service.
4724 * @param argc number of arguments from the command line
4725 * @param argv command line arguments
4726 * @return 0 ok, 1 on error
4729 main (int argc, char *const *argv)
4731 return (GNUNET_OK ==
4732 GNUNET_SERVICE_run (argc,
4735 GNUNET_SERVICE_OPTION_NONE,
4736 &run, NULL)) ? 0 : 1;
4739 /* end of gnunet-service-core.c */