2 This file is part of GNUnet
3 Copyright (C) 2010-2014, 2018, 2019 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your 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 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @file transport/gnunet-communicator-udp.c
23 * @brief Transport plugin using UDP.
24 * @author Christian Grothoff
27 * - consider imposing transmission limits in the absence
28 * of ACKs; or: maybe this should be done at TNG service level?
29 * (at least the receiver might want to enforce limits on
30 * KX/DH operations per sender in here) (#5552)
31 * - overall, we should look more into flow control support
32 * (either in backchannel, or general solution in TNG service)
33 * - handle addresses discovered from broadcasts (#5551)
34 * (think: what was the story again on address validation?
35 * where is the API for that!?!)
36 * - support DNS names in BINDTO option (#5528)
37 * - support NAT connection reversal method (#5529)
38 * - support other UDP-specific NAT traversal methods (#)
41 #include "gnunet_util_lib.h"
42 #include "gnunet_protocols.h"
43 #include "gnunet_signatures.h"
44 #include "gnunet_constants.h"
45 #include "gnunet_nt_lib.h"
46 #include "gnunet_nat_service.h"
47 #include "gnunet_statistics_service.h"
48 #include "gnunet_transport_application_service.h"
49 #include "gnunet_transport_communication_service.h"
52 * How often do we rekey based on time (at least)
54 #define REKEY_TIME_INTERVAL GNUNET_TIME_UNIT_DAYS
57 * How long do we wait until we must have received the initial KX?
59 #define PROTO_QUEUE_TIMEOUT GNUNET_TIME_UNIT_MINUTES
62 * How often do we broadcast our presence on the LAN?
64 #define BROADCAST_FREQUENCY GNUNET_TIME_UNIT_MINUTES
67 * How often do we scan for changes to our network interfaces?
69 #define INTERFACE_SCAN_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
72 * How long do we believe our addresses to remain up (before
73 * the other peer should revalidate).
75 #define ADDRESS_VALIDITY_PERIOD GNUNET_TIME_UNIT_HOURS
80 #define AES_KEY_SIZE (256/8)
85 #define AES_IV_SIZE (96/8)
88 * Size of the GCM tag.
90 #define GCM_TAG_SIZE (128/8)
93 * If we fall below this number of available KCNs,
94 * we generate additional ACKs until we reach
96 * Should be large enough that we don't generate ACKs all
97 * the time and still have enough time for the ACK to
98 * arrive before the sender runs out. So really this
99 * should ideally be based on the RTT.
101 #define KCN_THRESHOLD 92
104 * How many KCNs do we keep around *after* we hit
105 * the #KCN_THRESHOLD? Should be larger than
106 * #KCN_THRESHOLD so we do not generate just one
109 #define KCN_TARGET 128
112 * What is the maximum delta between KCN sequence numbers
113 * that we allow. Used to expire 'ancient' KCNs that likely
114 * were dropped by the network. Must be larger than
115 * KCN_TARGET (otherwise we generate new KCNs all the time),
116 * but not too large (otherwise packet loss may cause
117 * sender to fall back to KX needlessly when sender runs
118 * out of ACK'ed KCNs due to losses).
120 #define MAX_SQN_DELTA 160
123 * How many shared master secrets do we keep around
124 * at most per sender? Should be large enough so
125 * that we generally have a chance of sending an ACK
126 * before the sender already rotated out the master
127 * secret. Generally values around #KCN_TARGET make
128 * sense. Might make sense to adapt to RTT if we had
129 * a good measurement...
131 #define MAX_SECRETS 128
134 * How often do we rekey based on number of bytes transmitted?
135 * (additionally randomized).
137 #define REKEY_MAX_BYTES (1024LLU * 1024 * 1024 * 4LLU)
140 * Address prefix used by the communicator.
143 #define COMMUNICATOR_ADDRESS_PREFIX "udp"
146 * Configuration section used by the communicator.
148 #define COMMUNICATOR_CONFIG_SECTION "communicator-udp"
150 GNUNET_NETWORK_STRUCT_BEGIN
154 * Signature we use to verify that the ephemeral key was really chosen by
155 * the specified sender. If possible, the receiver should respond with
156 * a `struct UDPAck` (possibly via backchannel).
158 struct UdpHandshakeSignature
161 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
163 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
166 * Identity of the inititor of the UDP connection (UDP client).
168 struct GNUNET_PeerIdentity sender;
171 * Presumed identity of the target of the UDP connection (UDP server)
173 struct GNUNET_PeerIdentity receiver;
176 * Ephemeral key used by the @e sender.
178 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
181 * Monotonic time of @e sender, to possibly help detect replay attacks
182 * (if receiver persists times by sender).
184 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
189 * "Plaintext" header at beginning of KX message. Followed
190 * by encrypted `struct UDPConfirmation`.
196 * Ephemeral key for KX.
198 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
201 * HMAC for the following encrypted message, using GCM. HMAC uses
202 * key derived from the handshake with sequence number zero.
204 char gcm_tag[GCM_TAG_SIZE];
210 * Encrypted continuation of UDP initial handshake, followed
211 * by message header with payload.
213 struct UDPConfirmation
218 struct GNUNET_PeerIdentity sender;
221 * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
223 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
226 * Monotonic time of @e sender, to possibly help detect replay attacks
227 * (if receiver persists times by sender).
229 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
231 /* followed by messages */
233 /* padding may follow actual messages */
238 * UDP key acknowledgement. May be sent via backchannel. Allows the
239 * sender to use `struct UDPBox` with the acknowledge key henceforth.
245 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK.
247 struct GNUNET_MessageHeader header;
250 * Sequence acknowledgement limit. Specifies current maximum sequence
251 * number supported by receiver.
253 uint32_t sequence_max GNUNET_PACKED;
256 * CMAC of the base key being acknowledged.
258 struct GNUNET_HashCode cmac;
264 * Signature we use to verify that the broadcast was really made by
265 * the peer that claims to have made it. Basically, affirms that the
266 * peer is really using this IP address (albeit possibly not in _our_
267 * LAN). Makes it difficult for peers in the LAN to claim to
268 * be just any global peer -- an attacker must have at least
269 * shared a LAN with the peer they're pretending to be here.
271 struct UdpBroadcastSignature
274 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
276 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
279 * Identity of the inititor of the UDP broadcast.
281 struct GNUNET_PeerIdentity sender;
284 * Hash of the sender's UDP address.
286 struct GNUNET_HashCode h_address;
291 * Broadcast by peer in LAN announcing its presence. Unusual in that
292 * we don't pad these to full MTU, as we cannot prevent being
293 * recognized in LAN as GNUnet peers if this feature is enabled
294 * anyway. Also, the entire message is in cleartext.
300 * Sender's peer identity.
302 struct GNUNET_PeerIdentity sender;
305 * Sender's signature of type
306 * #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
308 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
314 * UDP message box. Always sent encrypted, only allowed after
315 * the receiver sent a `struct UDPAck` for the base key!
321 * Key and IV identification code. KDF applied to an acknowledged
322 * base key and a sequence number. Sequence numbers must be used
323 * monotonically increasing up to the maximum specified in
324 * `struct UDPAck`. Without further `struct UDPAck`s, the sender
325 * must fall back to sending handshakes!
327 struct GNUNET_ShortHashCode kid;
330 * 128-bit authentication tag for the following encrypted message,
331 * from GCM. MAC starts at the @e body_start that follows and
332 * extends until the end of the UDP payload. If the @e hmac is
333 * wrong, the receiver should check if the message might be a
334 * `struct UdpHandshakeSignature`.
336 char gcm_tag[GCM_TAG_SIZE];
341 GNUNET_NETWORK_STRUCT_END
344 * Shared secret we generated for a particular sender or receiver.
350 * Pre-generated "kid" code (key and IV identification code) to
351 * quickly derive master key for a `struct UDPBox`.
359 struct KeyCacheEntry *next;
364 struct KeyCacheEntry *prev;
367 * Key and IV identification code. KDF applied to an acknowledged
368 * base key and a sequence number. Sequence numbers must be used
369 * monotonically increasing up to the maximum specified in
370 * `struct UDPAck`. Without further `struct UDPAck`s, the sender
371 * must fall back to sending handshakes!
373 struct GNUNET_ShortHashCode kid;
376 * Corresponding shared secret.
378 struct SharedSecret *ss;
381 * Sequence number used to derive this entry from master key.
383 uint32_t sequence_number;
388 * Information we track per sender address we have recently been
389 * in contact with (decryption from sender).
391 struct SenderAddress;
394 * Information we track per receiving address we have recently been
395 * in contact with (encryption to receiver).
397 struct ReceiverAddress;
400 * Shared secret we generated for a particular sender or receiver.
407 struct SharedSecret *next;
412 struct SharedSecret *prev;
415 * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
417 struct KeyCacheEntry *kce_head;
420 * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
422 struct KeyCacheEntry *kce_tail;
425 * Sender we use this shared secret with, or NULL.
427 struct SenderAddress *sender;
430 * Receiver we use this shared secret with, or NULL.
432 struct ReceiverAddress *receiver;
435 * Master shared secret.
437 struct GNUNET_HashCode master;
440 * CMAC is used to identify @e master in ACKs.
442 struct GNUNET_HashCode cmac;
445 * Up to which sequence number did we use this @e master already?
446 * (for encrypting only)
448 uint32_t sequence_used;
451 * Up to which sequence number did the other peer allow us to use
452 * this key, or up to which number did we allow the other peer to
455 uint32_t sequence_allowed;
458 * Number of active KCN entries.
460 unsigned int active_kce_count;
465 * Information we track per sender address we have recently been
466 * in contact with (we decrypt messages from the sender).
472 * To whom are we talking to.
474 struct GNUNET_PeerIdentity target;
477 * Entry in sender expiration heap.
479 struct GNUNET_CONTAINER_HeapNode *hn;
482 * Shared secrets we used with @e target, first used is head.
484 struct SharedSecret *ss_head;
487 * Shared secrets we used with @e target, last used is tail.
489 struct SharedSecret *ss_tail;
492 * Address of the other peer.
494 struct sockaddr *address;
497 * Length of the address.
499 socklen_t address_len;
502 * Timeout for this sender.
504 struct GNUNET_TIME_Absolute timeout;
507 * Length of the DLL at @a ss_head.
509 unsigned int num_secrets;
512 * Which network type does this queue use?
514 enum GNUNET_NetworkType nt;
520 * Information we track per receiving address we have recently been
521 * in contact with (encryption to receiver).
523 struct ReceiverAddress
527 * To whom are we talking to.
529 struct GNUNET_PeerIdentity target;
532 * Shared secrets we received from @e target, first used is head.
534 struct SharedSecret *ss_head;
537 * Shared secrets we received with @e target, last used is tail.
539 struct SharedSecret *ss_tail;
542 * Address of the receiver in the human-readable format
543 * with the #COMMUNICATOR_ADDRESS_PREFIX.
548 * Address of the other peer.
550 struct sockaddr *address;
553 * Length of the address.
555 socklen_t address_len;
558 * Entry in sender expiration heap.
560 struct GNUNET_CONTAINER_HeapNode *hn;
563 * Message queue we are providing for the #ch.
565 struct GNUNET_MQ_Handle *mq;
568 * handle for this queue with the #ch.
570 struct GNUNET_TRANSPORT_QueueHandle *qh;
573 * Timeout for this receiver address.
575 struct GNUNET_TIME_Absolute timeout;
578 * MTU we allowed transport for this receiver right now.
583 * Length of the DLL at @a ss_head.
585 unsigned int num_secrets;
588 * Number of BOX keys from ACKs we have currently
589 * available for this receiver.
591 unsigned int acks_available;
594 * Which network type does this queue use?
596 enum GNUNET_NetworkType nt;
602 * Interface we broadcast our presence on.
604 struct BroadcastInterface
610 struct BroadcastInterface *next;
615 struct BroadcastInterface *prev;
618 * Task for this broadcast interface.
620 struct GNUNET_SCHEDULER_Task *broadcast_task;
623 * Sender's address of the interface.
628 * Broadcast address to use on the interface.
633 * Message we broadcast on this interface.
635 struct UDPBroadcast bcm;
638 * If this is an IPv6 interface, this is the request
639 * we use to join/leave the group.
641 struct ipv6_mreq mcreq;
644 * Number of bytes in @e sa.
649 * Was this interface found in the last #iface_proc() scan?
656 * Cache of pre-generated key IDs.
658 static struct GNUNET_CONTAINER_MultiShortmap *key_cache;
663 static struct GNUNET_SCHEDULER_Task *read_task;
668 static struct GNUNET_SCHEDULER_Task *timeout_task;
671 * ID of master broadcast task
673 static struct GNUNET_SCHEDULER_Task *broadcast_task;
676 * For logging statistics.
678 static struct GNUNET_STATISTICS_Handle *stats;
683 static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
686 * Receivers (map from peer identity to `struct ReceiverAddress`)
688 static struct GNUNET_CONTAINER_MultiPeerMap *receivers;
691 * Senders (map from peer identity to `struct SenderAddress`)
693 static struct GNUNET_CONTAINER_MultiPeerMap *senders;
696 * Expiration heap for senders (contains `struct SenderAddress`)
698 static struct GNUNET_CONTAINER_Heap *senders_heap;
701 * Expiration heap for receivers (contains `struct ReceiverAddress`)
703 static struct GNUNET_CONTAINER_Heap *receivers_heap;
706 * Broadcast interface tasks. Kept in a DLL.
708 static struct BroadcastInterface *bi_head;
711 * Broadcast interface tasks. Kept in a DLL.
713 static struct BroadcastInterface *bi_tail;
718 static struct GNUNET_NETWORK_Handle *udp_sock;
721 * #GNUNET_YES if #udp_sock supports IPv6.
723 static int have_v6_socket;
728 static struct GNUNET_PeerIdentity my_identity;
733 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
738 static const struct GNUNET_CONFIGURATION_Handle *cfg;
741 * Our handle to report addresses for validation to TRANSPORT.
743 static struct GNUNET_TRANSPORT_ApplicationHandle *ah;
746 * Network scanner to determine network types.
748 static struct GNUNET_NT_InterfaceScanner *is;
751 * Connection to NAT service.
753 static struct GNUNET_NAT_Handle *nat;
756 * Port number to which we are actually bound.
758 static uint16_t my_port;
762 * An interface went away, stop broadcasting on it.
764 * @param bi entity to close down
767 bi_destroy (struct BroadcastInterface *bi)
769 if (AF_INET6 == bi->sa->sa_family)
771 /* Leave the multicast group */
773 GNUNET_NETWORK_socket_setsockopt
780 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
784 GNUNET_CONTAINER_DLL_remove (bi_head,
787 GNUNET_SCHEDULER_cancel (bi->broadcast_task);
788 GNUNET_free (bi->sa);
789 GNUNET_free_non_null (bi->ba);
795 * Destroys a receiving state due to timeout or shutdown.
797 * @param receiver entity to close down
800 receiver_destroy (struct ReceiverAddress *receiver)
802 struct GNUNET_MQ_Handle *mq;
804 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
805 "Disconnecting receiver for peer `%s'\n",
806 GNUNET_i2s (&receiver->target));
807 if (NULL != (mq = receiver->mq))
810 GNUNET_MQ_destroy (mq);
812 if (NULL != receiver->qh)
814 GNUNET_TRANSPORT_communicator_mq_del (receiver->qh);
817 GNUNET_assert (GNUNET_YES ==
818 GNUNET_CONTAINER_multipeermap_remove (receivers,
821 GNUNET_assert (receiver ==
822 GNUNET_CONTAINER_heap_remove_node (receiver->hn));
823 GNUNET_STATISTICS_set (stats,
824 "# receivers active",
825 GNUNET_CONTAINER_multipeermap_size (receivers),
827 GNUNET_free (receiver->address);
828 GNUNET_free (receiver->foreign_addr);
829 GNUNET_free (receiver);
834 * Free memory used by key cache entry.
836 * @param kce the key cache entry
839 kce_destroy (struct KeyCacheEntry *kce)
841 struct SharedSecret *ss = kce->ss;
843 ss->active_kce_count--;
844 GNUNET_CONTAINER_DLL_remove (ss->kce_head,
847 GNUNET_assert (GNUNET_YES ==
848 GNUNET_CONTAINER_multishortmap_remove (key_cache,
858 * @param msec master secret for HMAC calculation
859 * @param serial number for the @a smac calculation
860 * @param kid[out] where to write the key ID
863 get_kid (const struct GNUNET_HashCode *msec,
865 struct GNUNET_ShortHashCode *kid)
867 uint32_t sid = htonl (serial);
869 GNUNET_CRYPTO_hkdf (kid,
884 * Setup key cache entry for sequence number @a seq and shared secret @a ss.
886 * @param ss shared secret
887 * @param seq sequence number for the key cache entry
890 kce_generate (struct SharedSecret *ss,
893 struct KeyCacheEntry *kce;
895 GNUNET_assert (0 < seq);
896 kce = GNUNET_new (struct KeyCacheEntry);
898 kce->sequence_number = seq;
899 get_kid (&ss->master,
902 GNUNET_CONTAINER_DLL_insert (ss->kce_head,
905 ss->active_kce_count++;
906 (void) GNUNET_CONTAINER_multishortmap_put (key_cache,
909 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
910 GNUNET_STATISTICS_set (stats,
912 GNUNET_CONTAINER_multishortmap_size (key_cache),
918 * Destroy @a ss and associated key cache entries.
920 * @param ss shared secret to destroy
923 secret_destroy (struct SharedSecret *ss)
925 struct SenderAddress *sender;
926 struct ReceiverAddress *receiver;
927 struct KeyCacheEntry *kce;
929 if (NULL != (sender = ss->sender))
931 GNUNET_CONTAINER_DLL_remove (sender->ss_head,
934 sender->num_secrets--;
936 if (NULL != (receiver = ss->receiver))
938 GNUNET_CONTAINER_DLL_remove (receiver->ss_head,
941 receiver->num_secrets--;
942 receiver->acks_available
943 -= (ss->sequence_allowed - ss->sequence_used);
945 while (NULL != (kce = ss->kce_head))
947 GNUNET_STATISTICS_update (stats,
951 GNUNET_STATISTICS_set (stats,
953 GNUNET_CONTAINER_multishortmap_size (key_cache),
960 * Functions with this signature are called whenever we need
961 * to close a sender's state due to timeout.
963 * @param sender entity to close down
966 sender_destroy (struct SenderAddress *sender)
968 GNUNET_assert (GNUNET_YES ==
969 GNUNET_CONTAINER_multipeermap_remove (senders,
972 GNUNET_assert (sender ==
973 GNUNET_CONTAINER_heap_remove_node (sender->hn));
974 GNUNET_STATISTICS_set (stats,
976 GNUNET_CONTAINER_multipeermap_size (senders),
978 GNUNET_free (sender->address);
979 GNUNET_free (sender);
984 * Compute @a key and @a iv.
986 * @param msec master secret for calculation
987 * @param serial number for the @a smac calculation
988 * @param key[out] where to write the decrption key
989 * @param iv[out] where to write the IV
992 get_iv_key (const struct GNUNET_HashCode *msec,
994 char key[AES_KEY_SIZE],
995 char iv[AES_IV_SIZE])
997 uint32_t sid = htonl (serial);
998 char res[AES_KEY_SIZE + AES_IV_SIZE];
1000 GNUNET_CRYPTO_hkdf (res,
1009 strlen ("UDP-IV-KEY"),
1021 * Increment sender timeout due to activity.
1023 * @param sender address for which the timeout should be rescheduled
1026 reschedule_sender_timeout (struct SenderAddress *sender)
1029 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1030 GNUNET_CONTAINER_heap_update_cost (sender->hn,
1031 sender->timeout.abs_value_us);
1036 * Increment receiver timeout due to activity.
1038 * @param receiver address for which the timeout should be rescheduled
1041 reschedule_receiver_timeout (struct ReceiverAddress *receiver)
1044 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1045 GNUNET_CONTAINER_heap_update_cost (receiver->hn,
1046 receiver->timeout.abs_value_us);
1051 * Task run to check #receiver_heap and #sender_heap for timeouts.
1053 * @param cls unused, NULL
1056 check_timeouts (void *cls)
1058 struct GNUNET_TIME_Relative st;
1059 struct GNUNET_TIME_Relative rt;
1060 struct GNUNET_TIME_Relative delay;
1061 struct ReceiverAddress *receiver;
1062 struct SenderAddress *sender;
1065 timeout_task = NULL;
1066 rt = GNUNET_TIME_UNIT_FOREVER_REL;
1067 while (NULL != (receiver = GNUNET_CONTAINER_heap_peek (receivers_heap)))
1069 rt = GNUNET_TIME_absolute_get_remaining (receiver->timeout);
1070 if (0 != rt.rel_value_us)
1072 receiver_destroy (receiver);
1074 st = GNUNET_TIME_UNIT_FOREVER_REL;
1075 while (NULL != (sender = GNUNET_CONTAINER_heap_peek (senders_heap)))
1077 st = GNUNET_TIME_absolute_get_remaining (receiver->timeout);
1078 if (0 != st.rel_value_us)
1080 sender_destroy (sender);
1082 delay = GNUNET_TIME_relative_min (rt,
1084 if (delay.rel_value_us < GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
1085 timeout_task = GNUNET_SCHEDULER_add_delayed (delay,
1092 * Calcualte cmac from master in @a ss.
1094 * @param ss[in,out] data structure to complete
1097 calculate_cmac (struct SharedSecret *ss)
1099 GNUNET_CRYPTO_hkdf (&ss->cmac,
1106 sizeof (ss->master),
1108 strlen ("UDP-CMAC"),
1114 * We received @a plaintext_len bytes of @a plaintext from a @a sender.
1115 * Pass it on to CORE.
1117 * @param queue the queue that received the plaintext
1118 * @param plaintext the plaintext that was received
1119 * @param plaintext_len number of bytes of plaintext received
1122 pass_plaintext_to_core (struct SenderAddress *sender,
1123 const void *plaintext,
1124 size_t plaintext_len)
1126 const struct GNUNET_MessageHeader *hdr = plaintext;
1128 while (ntohs (hdr->size) < plaintext_len)
1130 GNUNET_STATISTICS_update (stats,
1131 "# bytes given to core",
1134 (void) GNUNET_TRANSPORT_communicator_receive (ch,
1137 ADDRESS_VALIDITY_PERIOD,
1138 NULL /* no flow control possible */,
1140 /* move on to next message, if any */
1141 plaintext_len -= ntohs (hdr->size);
1142 if (plaintext_len < sizeof (*hdr))
1144 hdr = plaintext + ntohs (hdr->size);
1146 GNUNET_STATISTICS_update (stats,
1147 "# bytes padding discarded",
1154 * Setup @a cipher based on shared secret @a msec and
1155 * serial number @a serial.
1157 * @param msec master shared secret
1158 * @param serial serial number of cipher to set up
1159 * @param cipher[out] cipher to initialize
1162 setup_cipher (const struct GNUNET_HashCode *msec,
1164 gcry_cipher_hd_t *cipher)
1166 char key[AES_KEY_SIZE];
1167 char iv[AES_IV_SIZE];
1169 gcry_cipher_open (cipher,
1170 GCRY_CIPHER_AES256 /* low level: go for speed */,
1171 GCRY_CIPHER_MODE_GCM,
1177 gcry_cipher_setkey (*cipher,
1180 gcry_cipher_setiv (*cipher,
1187 * Try to decrypt @a buf using shared secret @a ss and key/iv
1188 * derived using @a serial.
1190 * @param ss shared secret
1191 * @param tag GCM authentication tag
1192 * @param serial serial number to use
1193 * @param in_buf input buffer to decrypt
1194 * @param in_buf_size number of bytes in @a in_buf and available in @a out_buf
1195 * @param out_buf where to write the result
1196 * @return #GNUNET_OK on success
1199 try_decrypt (const struct SharedSecret *ss,
1200 const char tag[GCM_TAG_SIZE],
1206 gcry_cipher_hd_t cipher;
1208 setup_cipher (&ss->master,
1212 gcry_cipher_decrypt (cipher,
1218 gcry_cipher_checktag (cipher,
1222 gcry_cipher_close (cipher);
1223 GNUNET_STATISTICS_update (stats,
1224 "# AEAD authentication failures",
1227 return GNUNET_SYSERR;
1229 gcry_cipher_close (cipher);
1235 * Setup shared secret for decryption.
1237 * @param ephemeral ephemeral key we received from the other peer
1238 * @return new shared secret
1240 static struct SharedSecret *
1241 setup_shared_secret_dec (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1243 struct SharedSecret *ss;
1245 ss = GNUNET_new (struct SharedSecret);
1246 GNUNET_CRYPTO_eddsa_ecdh (my_private_key,
1254 * Setup shared secret for encryption.
1256 * @param ephemeral ephemeral key we are sending to the other peer
1257 * @param receiver[in,out] queue to initialize encryption key for
1258 * @return new shared secret
1260 static struct SharedSecret *
1261 setup_shared_secret_enc (const struct GNUNET_CRYPTO_EcdhePrivateKey *ephemeral,
1262 struct ReceiverAddress *receiver)
1264 struct SharedSecret *ss;
1266 ss = GNUNET_new (struct SharedSecret);
1267 GNUNET_CRYPTO_ecdh_eddsa (ephemeral,
1268 &receiver->target.public_key,
1270 calculate_cmac (ss);
1271 ss->receiver = receiver;
1272 GNUNET_CONTAINER_DLL_insert (receiver->ss_head,
1275 receiver->num_secrets++;
1276 GNUNET_STATISTICS_update (stats,
1285 * Setup the MQ for the @a receiver. If a queue exists,
1286 * the existing one is destroyed. Then the MTU is
1287 * recalculated and a fresh queue is initialized.
1289 * @param receiver receiver to setup MQ for
1292 setup_receiver_mq (struct ReceiverAddress *receiver);
1296 * We received an ACK for @a pid. Check if it is for
1297 * the receiver in @a value and if so, handle it and
1298 * return #GNUNET_NO. Otherwise, return #GNUNET_YES.
1300 * @param cls a `const struct UDPAck`
1301 * @param pid peer the ACK is from
1302 * @param value a `struct ReceiverAddress`
1303 * @return #GNUNET_YES to continue to iterate
1306 handle_ack (void *cls,
1307 const struct GNUNET_PeerIdentity *pid,
1310 const struct UDPAck *ack = cls;
1311 struct ReceiverAddress *receiver = value;
1314 for (struct SharedSecret *ss = receiver->ss_head;
1318 if (0 == memcmp (&ack->cmac,
1320 sizeof (struct GNUNET_HashCode)))
1324 allowed = ntohl (ack->sequence_max);
1326 if (allowed > ss->sequence_allowed)
1328 receiver->acks_available += (allowed - ss->sequence_allowed);
1329 if ((allowed - ss->sequence_allowed)
1330 == receiver->acks_available)
1332 /* we just incremented from zero => MTU change! */
1333 setup_receiver_mq (receiver);
1335 ss->sequence_allowed = allowed;
1336 /* move ss to head to avoid discarding it anytime soon! */
1337 GNUNET_CONTAINER_DLL_remove (receiver->ss_head,
1340 GNUNET_CONTAINER_DLL_insert (receiver->ss_head,
1352 * Test if we have received a valid message in plaintext.
1355 * @param sender peer to process inbound plaintext for
1356 * @param buf buffer we received
1357 * @param buf_size number of bytes in @a buf
1360 try_handle_plaintext (struct SenderAddress *sender,
1364 const struct GNUNET_MessageHeader *hdr
1365 = (const struct GNUNET_MessageHeader *) buf;
1366 const struct UDPAck *ack
1367 = (const struct UDPAck *) buf;
1370 if (sizeof (*hdr) > buf_size)
1371 return; /* not even a header */
1372 if (ntohs (hdr->size) > buf_size)
1373 return; /* not even a header */
1374 type = ntohs (hdr->type);
1377 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK:
1378 /* lookup master secret by 'cmac', then update sequence_max */
1379 GNUNET_CONTAINER_multipeermap_get_multiple (receivers,
1383 /* There could be more messages after the ACK, handle those as well */
1384 buf += ntohs (hdr->size);
1385 buf_size -= ntohs (hdr->size);
1386 pass_plaintext_to_core (sender,
1390 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD:
1394 pass_plaintext_to_core (sender,
1402 * We established a shared secret with a sender. We should try to send
1403 * the sender an `struct UDPAck` at the next opportunity to allow the
1404 * sender to use @a ss longer (assuming we did not yet already
1407 * @param ss shared secret to generate ACKs for
1410 consider_ss_ack (struct SharedSecret *ss)
1412 GNUNET_assert (NULL != ss->sender);
1413 /* drop ancient KeyCacheEntries */
1414 while ( (NULL != ss->kce_head) &&
1415 (MAX_SQN_DELTA < ss->kce_head->sequence_number - ss->kce_tail->sequence_number) )
1416 kce_destroy (ss->kce_tail);
1417 if (ss->active_kce_count < KCN_THRESHOLD)
1421 while (ss->active_kce_count < KCN_TARGET)
1423 ++ss->sequence_allowed);
1424 ack.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK);
1425 ack.header.size = htons (sizeof (ack));
1426 ack.sequence_max = htonl (ss->sequence_allowed);
1427 ack.cmac = ss->cmac;
1428 GNUNET_TRANSPORT_communicator_notify (ch,
1429 &ss->sender->target,
1430 COMMUNICATOR_ADDRESS_PREFIX,
1437 * We received a @a box with matching @a kce. Decrypt and process it.
1439 * @param box the data we received
1440 * @param box_len number of bytes in @a box
1441 * @param kce key index to decrypt @a box
1444 decrypt_box (const struct UDPBox *box,
1446 struct KeyCacheEntry *kce)
1448 struct SharedSecret *ss = kce->ss;
1449 char out_buf[box_len - sizeof (*box)];
1451 GNUNET_assert (NULL != ss->sender);
1455 kce->sequence_number,
1456 (const char *) &box[1],
1460 GNUNET_STATISTICS_update (stats,
1461 "# Decryption failures with valid KCE",
1468 GNUNET_STATISTICS_update (stats,
1469 "# bytes decrypted with BOX",
1472 try_handle_plaintext (ss->sender,
1475 consider_ss_ack (ss);
1480 * Closure for #find_sender_by_address()
1482 struct SearchContext
1485 * Address we are looking for.
1487 const struct sockaddr *address;
1490 * Number of bytes in @e address.
1492 socklen_t address_len;
1495 * Return value to set if we found a match.
1497 struct SenderAddress *sender;
1502 * Find existing `struct SenderAddress` by matching addresses.
1504 * @param cls a `struct SearchContext`
1505 * @param key ignored, must match already
1506 * @param value a `struct SenderAddress`
1507 * @return #GNUNET_YES if not found (continue to search), #GNUNET_NO if found
1510 find_sender_by_address (void *cls,
1511 const struct GNUNET_PeerIdentity *key,
1514 struct SearchContext *sc = cls;
1515 struct SenderAddress *sender = value;
1517 if ( (sender->address_len == sc->address_len) &&
1518 (0 == memcmp (sender->address,
1520 sender->address_len)) )
1522 sc->sender = sender;
1523 return GNUNET_NO; /* stop iterating! */
1530 * Create sender address for @a target. Note that we
1531 * might already have one, so a fresh one is only allocated
1532 * if one does not yet exist for @a address.
1534 * @param target peer to generate address for
1535 * @param address target address
1536 * @param address_len number of bytes in @a address
1537 * @return data structure to keep track of key material for
1538 * decrypting data from @a target
1540 static struct SenderAddress *
1541 setup_sender (const struct GNUNET_PeerIdentity *target,
1542 const struct sockaddr *address,
1543 socklen_t address_len)
1545 struct SenderAddress *sender;
1546 struct SearchContext sc = {
1548 .address_len = address_len,
1552 GNUNET_CONTAINER_multipeermap_get_multiple (senders,
1554 &find_sender_by_address,
1556 if (NULL != sc.sender)
1558 reschedule_sender_timeout (sc.sender);
1561 sender = GNUNET_new (struct SenderAddress);
1562 sender->target = *target;
1563 sender->address = GNUNET_memdup (address,
1565 sender->address_len = address_len;
1566 (void) GNUNET_CONTAINER_multipeermap_put (senders,
1569 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1570 GNUNET_STATISTICS_set (stats,
1572 GNUNET_CONTAINER_multipeermap_size (receivers),
1575 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1576 sender->hn = GNUNET_CONTAINER_heap_insert (senders_heap,
1578 sender->timeout.abs_value_us);
1579 sender->nt = GNUNET_NT_scanner_get_type (is,
1582 if (NULL == timeout_task)
1583 timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts,
1590 * Check signature from @a uc against @a ephemeral.
1592 * @param ephermal key that is signed
1593 * @param uc signature of claimant
1594 * @return #GNUNET_OK if signature is valid
1597 verify_confirmation (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral,
1598 const struct UDPConfirmation *uc)
1600 struct UdpHandshakeSignature uhs;
1602 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
1603 uhs.purpose.size = htonl (sizeof (uhs));
1604 uhs.sender = uc->sender;
1605 uhs.receiver = my_identity;
1606 uhs.ephemeral = *ephemeral;
1607 uhs.monotonic_time = uc->monotonic_time;
1608 return GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE,
1611 &uc->sender.public_key);
1616 * Converts @a address to the address string format used by this
1617 * communicator in HELLOs.
1619 * @param address the address to convert, must be AF_INET or AF_INET6.
1620 * @param address_len number of bytes in @a address
1621 * @return string representation of @a address
1624 sockaddr_to_udpaddr_string (const struct sockaddr *address,
1625 socklen_t address_len)
1629 switch (address->sa_family)
1632 GNUNET_asprintf (&ret,
1634 COMMUNICATOR_ADDRESS_PREFIX,
1635 GNUNET_a2s (address,
1639 GNUNET_asprintf (&ret,
1641 COMMUNICATOR_ADDRESS_PREFIX,
1642 GNUNET_a2s (address,
1658 sock_read (void *cls)
1660 struct sockaddr_storage sa;
1661 socklen_t salen = sizeof (sa);
1662 char buf[UINT16_MAX];
1667 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1671 rcvd = GNUNET_NETWORK_socket_recvfrom (udp_sock,
1674 (struct sockaddr *) &sa,
1678 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1683 /* first, see if it is a UDPBox */
1684 if (rcvd > sizeof (struct UDPBox))
1686 const struct UDPBox *box;
1687 struct KeyCacheEntry *kce;
1689 box = (const struct UDPBox *) buf;
1690 kce = GNUNET_CONTAINER_multishortmap_get (key_cache,
1701 /* next, check if it is a broadcast */
1702 if (sizeof (struct UDPBroadcast) == rcvd)
1704 const struct UDPBroadcast *ub;
1705 struct UdpBroadcastSignature uhs;
1707 ub = (const struct UDPBroadcast *) buf;
1708 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
1709 uhs.purpose.size = htonl (sizeof (uhs));
1710 uhs.sender = ub->sender;
1711 GNUNET_CRYPTO_hash (&sa,
1715 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST,
1718 &ub->sender.public_key))
1721 struct GNUNET_TIME_Absolute expiration;
1722 enum GNUNET_NetworkType nt;
1724 addr_s = sockaddr_to_udpaddr_string ((const struct sockaddr *) &sa,
1726 GNUNET_STATISTICS_update (stats,
1727 "# broadcasts received",
1730 /* expire at the broadcast frequency, as then we'll get the next one anyway */
1731 expiration = GNUNET_TIME_relative_to_absolute (BROADCAST_FREQUENCY);
1732 /* use our own mechanism to determine network type */
1733 nt = GNUNET_NT_scanner_get_type (is,
1734 (const struct sockaddr *) &sa,
1736 GNUNET_TRANSPORT_application_validate (ah,
1741 GNUNET_free (addr_s);
1744 /* continue with KX, mostly for statistics... */
1748 /* finally, test if it is a KX */
1749 if (rcvd < sizeof (struct UDPConfirmation) + sizeof (struct InitialKX))
1751 GNUNET_STATISTICS_update (stats,
1752 "# messages dropped (no kid, too small for KX)",
1759 const struct InitialKX *kx;
1760 struct SharedSecret *ss;
1761 char pbuf[rcvd - sizeof (struct InitialKX)];
1762 const struct UDPConfirmation *uc;
1763 struct SenderAddress *sender;
1765 kx = (const struct InitialKX *) buf;
1766 ss = setup_shared_secret_dec (&kx->ephemeral);
1776 GNUNET_STATISTICS_update (stats,
1777 "# messages dropped (no kid, AEAD decryption failed)",
1782 uc = (const struct UDPConfirmation *) pbuf;
1784 verify_confirmation (&kx->ephemeral,
1787 GNUNET_break_op (0);
1789 GNUNET_STATISTICS_update (stats,
1790 "# messages dropped (sender signature invalid)",
1795 calculate_cmac (ss);
1796 sender = setup_sender (&uc->sender,
1797 (const struct sockaddr *) &sa,
1799 ss->sender = sender;
1800 GNUNET_CONTAINER_DLL_insert (sender->ss_head,
1803 sender->num_secrets++;
1804 GNUNET_STATISTICS_update (stats,
1808 GNUNET_STATISTICS_update (stats,
1809 "# messages decrypted without BOX",
1812 try_handle_plaintext (sender,
1814 sizeof (pbuf) - sizeof (*uc));
1815 consider_ss_ack (ss);
1816 if (sender->num_secrets > MAX_SECRETS)
1817 secret_destroy (sender->ss_tail);
1823 * Convert UDP bind specification to a `struct sockaddr *`
1825 * @param bindto bind specification to convert
1826 * @param[out] sock_len set to the length of the address
1827 * @return converted bindto specification
1829 static struct sockaddr *
1830 udp_address_to_sockaddr (const char *bindto,
1831 socklen_t *sock_len)
1833 struct sockaddr *in;
1839 if (1 == SSCANF (bindto,
1844 /* interpreting value as just a PORT number */
1845 if (port > UINT16_MAX)
1847 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1848 "BINDTO specification `%s' invalid: value too large for port\n",
1853 GNUNET_NETWORK_test_pf (PF_INET6)) ||
1855 GNUNET_CONFIGURATION_get_value_yesno (cfg,
1856 COMMUNICATOR_CONFIG_SECTION,
1859 struct sockaddr_in *i4;
1861 i4 = GNUNET_malloc (sizeof (struct sockaddr_in));
1862 i4->sin_family = AF_INET;
1863 i4->sin_port = htons ((uint16_t) port);
1864 *sock_len = sizeof (struct sockaddr_in);
1865 in = (struct sockaddr *) i4;
1869 struct sockaddr_in6 *i6;
1871 i6 = GNUNET_malloc (sizeof (struct sockaddr_in6));
1872 i6->sin6_family = AF_INET6;
1873 i6->sin6_port = htons ((uint16_t) port);
1874 *sock_len = sizeof (struct sockaddr_in6);
1875 in = (struct sockaddr *) i6;
1879 cp = GNUNET_strdup (bindto);
1880 colon = strrchr (cp, ':');
1883 /* interpet value after colon as port */
1886 if (1 == SSCANF (colon,
1891 /* interpreting value as just a PORT number */
1892 if (port > UINT16_MAX)
1894 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1895 "BINDTO specification `%s' invalid: value too large for port\n",
1903 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1904 "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1912 /* interpret missing port as 0, aka pick any free one */
1917 struct sockaddr_in v4;
1919 if (1 == inet_pton (AF_INET,
1923 v4.sin_port = htons ((uint16_t) port);
1924 in = GNUNET_memdup (&v4,
1926 *sock_len = sizeof (v4);
1933 struct sockaddr_in6 v6;
1937 if ( ('[' == *cp) &&
1938 (']' == cp[strlen (cp)-1]) )
1940 start++; /* skip over '[' */
1941 cp[strlen (cp) -1] = '\0'; /* eat ']' */
1943 if (1 == inet_pton (AF_INET6,
1947 v6.sin6_port = htons ((uint16_t) port);
1948 in = GNUNET_memdup (&v6,
1950 *sock_len = sizeof (v6);
1955 /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1962 * Pad @a dgram by @a pad_size using @a out_cipher.
1964 * @param out_cipher cipher to use
1965 * @param dgram datagram to pad
1966 * @param pad_size number of bytes of padding to append
1969 do_pad (gcry_cipher_hd_t out_cipher,
1975 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
1978 if (sizeof (pad) > sizeof (struct GNUNET_MessageHeader))
1980 struct GNUNET_MessageHeader hdr = {
1981 .size = htons (sizeof (pad)),
1982 .type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD)
1990 gcry_cipher_encrypt (out_cipher,
1999 * Signature of functions implementing the sending functionality of a
2002 * @param mq the message queue
2003 * @param msg the message to send
2004 * @param impl_state our `struct ReceiverAddress`
2007 mq_send (struct GNUNET_MQ_Handle *mq,
2008 const struct GNUNET_MessageHeader *msg,
2011 struct ReceiverAddress *receiver = impl_state;
2012 uint16_t msize = ntohs (msg->size);
2014 GNUNET_assert (mq == receiver->mq);
2015 if (msize > receiver->mtu)
2018 receiver_destroy (receiver);
2021 reschedule_receiver_timeout (receiver);
2023 if (0 == receiver->acks_available)
2025 /* use KX encryption method */
2026 struct UdpHandshakeSignature uhs;
2027 struct UDPConfirmation uc;
2028 struct InitialKX kx;
2029 struct GNUNET_CRYPTO_EcdhePrivateKey epriv;
2030 char dgram[receiver->mtu +
2034 gcry_cipher_hd_t out_cipher;
2035 struct SharedSecret *ss;
2037 /* setup key material */
2038 GNUNET_assert (GNUNET_OK ==
2039 GNUNET_CRYPTO_ecdhe_key_create2 (&epriv));
2041 ss = setup_shared_secret_enc (&epriv,
2043 setup_cipher (&ss->master,
2047 uc.sender = my_identity;
2048 uc.monotonic_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
2049 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
2050 uhs.purpose.size = htonl (sizeof (uhs));
2051 uhs.sender = my_identity;
2052 uhs.receiver = receiver->target;
2053 GNUNET_CRYPTO_ecdhe_key_get_public (&epriv,
2055 uhs.monotonic_time = uc.monotonic_time;
2056 GNUNET_assert (GNUNET_OK ==
2057 GNUNET_CRYPTO_eddsa_sign (my_private_key,
2060 /* Leave space for kx */
2061 dpos = sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
2062 /* Append encrypted uc to dgram */
2064 gcry_cipher_encrypt (out_cipher,
2069 dpos += sizeof (uc);
2070 /* Append encrypted payload to dgram */
2072 gcry_cipher_encrypt (out_cipher,
2080 sizeof (dgram) - dpos);
2081 /* Datagram starts with kx */
2082 kx.ephemeral = uhs.ephemeral;
2084 gcry_cipher_gettag (out_cipher,
2086 sizeof (kx.gcm_tag)));
2087 gcry_cipher_close (out_cipher);
2092 GNUNET_NETWORK_socket_sendto (udp_sock,
2096 receiver->address_len))
2097 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2099 GNUNET_MQ_impl_send_continue (mq);
2101 } /* End of KX encryption method */
2103 /* begin "BOX" encryption method, scan for ACKs from tail! */
2104 for (struct SharedSecret *ss = receiver->ss_tail;
2108 if (ss->sequence_used < ss->sequence_allowed)
2110 char dgram[sizeof (struct UDPBox) + receiver->mtu];
2112 gcry_cipher_hd_t out_cipher;
2115 box = (struct UDPBox *) dgram;
2116 ss->sequence_used++;
2117 get_kid (&ss->master,
2120 setup_cipher (&ss->master,
2123 /* Append encrypted payload to dgram */
2124 dpos = sizeof (struct UDPBox);
2126 gcry_cipher_encrypt (out_cipher,
2134 sizeof (dgram) - dpos);
2136 gcry_cipher_gettag (out_cipher,
2138 sizeof (box->gcm_tag)));
2139 gcry_cipher_close (out_cipher);
2141 GNUNET_NETWORK_socket_sendto (udp_sock,
2145 receiver->address_len))
2146 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2148 GNUNET_MQ_impl_send_continue (mq);
2149 receiver->acks_available--;
2150 if (0 == receiver->acks_available)
2152 /* We have no more ACKs => MTU change! */
2153 setup_receiver_mq (receiver);
2163 * Signature of functions implementing the destruction of a message
2164 * queue. Implementations must not free @a mq, but should take care
2167 * @param mq the message queue to destroy
2168 * @param impl_state our `struct ReceiverAddress`
2171 mq_destroy (struct GNUNET_MQ_Handle *mq,
2174 struct ReceiverAddress *receiver = impl_state;
2176 if (mq == receiver->mq)
2178 receiver->mq = NULL;
2179 receiver_destroy (receiver);
2185 * Implementation function that cancels the currently sent message.
2187 * @param mq message queue
2188 * @param impl_state our `struct RecvierAddress`
2191 mq_cancel (struct GNUNET_MQ_Handle *mq,
2194 /* Cancellation is impossible with UDP; bail */
2200 * Generic error handler, called with the appropriate
2201 * error code and the same closure specified at the creation of
2202 * the message queue.
2203 * Not every message queue implementation supports an error handler.
2205 * @param cls our `struct ReceiverAddress`
2206 * @param error error code
2209 mq_error (void *cls,
2210 enum GNUNET_MQ_Error error)
2212 struct ReceiverAddress *receiver = cls;
2214 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2215 "MQ error in queue to %s: %d\n",
2216 GNUNET_i2s (&receiver->target),
2218 receiver_destroy (receiver);
2223 * Setup the MQ for the @a receiver. If a queue exists,
2224 * the existing one is destroyed. Then the MTU is
2225 * recalculated and a fresh queue is initialized.
2227 * @param receiver receiver to setup MQ for
2230 setup_receiver_mq (struct ReceiverAddress *receiver)
2234 if (NULL != receiver->qh)
2236 GNUNET_TRANSPORT_communicator_mq_del (receiver->qh);
2237 receiver->qh = NULL;
2239 GNUNET_assert (NULL == receiver->mq);
2240 switch (receiver->address->sa_family)
2244 = 1480 /* Ethernet MTU, 1500 - Ethernet header - VLAN tag */
2245 - sizeof (struct GNUNET_TUN_IPv4Header) /* 20 */
2246 - sizeof (struct GNUNET_TUN_UdpHeader) /* 8 */;
2250 = 1280 /* Minimum MTU required by IPv6 */
2251 - sizeof (struct GNUNET_TUN_IPv6Header) /* 40 */
2252 - sizeof (struct GNUNET_TUN_UdpHeader) /* 8 */;
2258 if (0 == receiver->acks_available)
2260 /* MTU based on full KX messages */
2263 - sizeof (struct InitialKX) /* 48 */
2264 - sizeof (struct UDPConfirmation); /* 104 */
2268 /* MTU based on BOXed messages */
2270 = base_mtu - sizeof (struct UDPBox);
2272 /* => Effective MTU for CORE will range from 1080 (IPv6 + KX) to
2273 1404 (IPv4 + Box) bytes, depending on circumstances... */
2275 = GNUNET_MQ_queue_for_callbacks (&mq_send,
2283 = GNUNET_TRANSPORT_communicator_mq_add (ch,
2285 receiver->foreign_addr,
2288 GNUNET_TRANSPORT_CS_OUTBOUND,
2294 * Setup a receiver for transmission. Setup the MQ processing and
2295 * inform transport that the queue is ready.
2297 * @param target which peer are we talking to
2298 * @param address address of the peer
2299 * @param address_len number of bytes in @a address
2300 * @return handle for the address
2302 static struct ReceiverAddress *
2303 receiver_setup (const struct GNUNET_PeerIdentity *target,
2304 const struct sockaddr *address,
2305 socklen_t address_len)
2307 struct ReceiverAddress *receiver;
2309 receiver = GNUNET_new (struct ReceiverAddress);
2310 receiver->address = GNUNET_memdup (address,
2312 receiver->address_len = address_len;
2313 receiver->target = *target;
2314 receiver->nt = GNUNET_NT_scanner_get_type (is,
2317 (void) GNUNET_CONTAINER_multipeermap_put (receivers,
2320 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2322 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2323 receiver->hn = GNUNET_CONTAINER_heap_insert (receivers_heap,
2325 receiver->timeout.abs_value_us);
2326 GNUNET_STATISTICS_set (stats,
2327 "# receivers active",
2328 GNUNET_CONTAINER_multipeermap_size (receivers),
2330 receiver->foreign_addr = sockaddr_to_udpaddr_string (receiver->address,
2331 receiver->address_len);
2332 setup_receiver_mq (receiver);
2334 if (NULL == timeout_task)
2335 timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts,
2342 * Function called by the transport service to initialize a
2343 * message queue given address information about another peer.
2344 * If and when the communication channel is established, the
2345 * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
2346 * to notify the service that the channel is now up. It is
2347 * the responsibility of the communicator to manage sane
2348 * retries and timeouts for any @a peer/@a address combination
2349 * provided by the transport service. Timeouts and retries
2350 * do not need to be signalled to the transport service.
2352 * @param cls closure
2353 * @param peer identity of the other peer
2354 * @param address where to send the message, human-readable
2355 * communicator-specific format, 0-terminated, UTF-8
2356 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is invalid
2360 const struct GNUNET_PeerIdentity *peer,
2361 const char *address)
2363 struct ReceiverAddress *receiver;
2365 struct sockaddr *in;
2368 if (0 != strncmp (address,
2369 COMMUNICATOR_ADDRESS_PREFIX "-",
2370 strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
2372 GNUNET_break_op (0);
2373 return GNUNET_SYSERR;
2375 path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
2376 in = udp_address_to_sockaddr (path,
2378 receiver = receiver_setup (peer,
2387 * Iterator over all receivers to clean up.
2390 * @param target unused
2391 * @param value the queue to destroy
2392 * @return #GNUNET_OK to continue to iterate
2395 get_receiver_delete_it (void *cls,
2396 const struct GNUNET_PeerIdentity *target,
2399 struct ReceiverAddress *receiver = value;
2403 receiver_destroy (receiver);
2409 * Iterator over all senders to clean up.
2412 * @param target unused
2413 * @param value the queue to destroy
2414 * @return #GNUNET_OK to continue to iterate
2417 get_sender_delete_it (void *cls,
2418 const struct GNUNET_PeerIdentity *target,
2421 struct SenderAddress *sender = value;
2425 sender_destroy (sender);
2431 * Shutdown the UNIX communicator.
2433 * @param cls NULL (always)
2436 do_shutdown (void *cls)
2440 GNUNET_NAT_unregister (nat);
2443 while (NULL != bi_head)
2444 bi_destroy (bi_head);
2445 if (NULL != broadcast_task)
2447 GNUNET_SCHEDULER_cancel (broadcast_task);
2448 broadcast_task = NULL;
2450 if (NULL != read_task)
2452 GNUNET_SCHEDULER_cancel (read_task);
2455 if (NULL != udp_sock)
2457 GNUNET_break (GNUNET_OK ==
2458 GNUNET_NETWORK_socket_close (udp_sock));
2461 GNUNET_CONTAINER_multipeermap_iterate (receivers,
2462 &get_receiver_delete_it,
2464 GNUNET_CONTAINER_multipeermap_destroy (receivers);
2465 GNUNET_CONTAINER_multipeermap_iterate (senders,
2466 &get_sender_delete_it,
2468 GNUNET_CONTAINER_multipeermap_destroy (senders);
2469 GNUNET_CONTAINER_multishortmap_destroy (key_cache);
2470 GNUNET_CONTAINER_heap_destroy (senders_heap);
2471 GNUNET_CONTAINER_heap_destroy (receivers_heap);
2474 GNUNET_TRANSPORT_communicator_disconnect (ch);
2479 GNUNET_TRANSPORT_application_done (ah);
2484 GNUNET_STATISTICS_destroy (stats,
2488 if (NULL != my_private_key)
2490 GNUNET_free (my_private_key);
2491 my_private_key = NULL;
2495 GNUNET_NT_scanner_done (is);
2502 * Function called when the transport service has received a
2503 * backchannel message for this communicator (!) via a different return
2504 * path. Should be an acknowledgement.
2506 * @param cls closure, NULL
2507 * @param sender which peer sent the notification
2508 * @param msg payload
2511 enc_notify_cb (void *cls,
2512 const struct GNUNET_PeerIdentity *sender,
2513 const struct GNUNET_MessageHeader *msg)
2515 const struct UDPAck *ack;
2518 if ( (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK) ||
2519 (ntohs (msg->size) != sizeof (struct UDPAck)) )
2521 GNUNET_break_op (0);
2524 ack = (const struct UDPAck *) msg;
2525 GNUNET_CONTAINER_multipeermap_get_multiple (receivers,
2533 * Signature of the callback passed to #GNUNET_NAT_register() for
2534 * a function to call whenever our set of 'valid' addresses changes.
2536 * @param cls closure
2537 * @param app_ctx[in,out] location where the app can store stuff
2538 * on add and retrieve it on remove
2539 * @param add_remove #GNUNET_YES to add a new public IP address,
2540 * #GNUNET_NO to remove a previous (now invalid) one
2541 * @param ac address class the address belongs to
2542 * @param addr either the previous or the new public IP address
2543 * @param addrlen actual length of the @a addr
2546 nat_address_cb (void *cls,
2549 enum GNUNET_NAT_AddressClass ac,
2550 const struct sockaddr *addr,
2554 struct GNUNET_TRANSPORT_AddressIdentifier *ai;
2556 if (GNUNET_YES == add_remove)
2558 enum GNUNET_NetworkType nt;
2560 GNUNET_asprintf (&my_addr,
2562 COMMUNICATOR_ADDRESS_PREFIX,
2565 nt = GNUNET_NT_scanner_get_type (is,
2568 ai = GNUNET_TRANSPORT_communicator_address_add (ch,
2571 GNUNET_TIME_UNIT_FOREVER_REL);
2572 GNUNET_free (my_addr);
2578 GNUNET_TRANSPORT_communicator_address_remove (ai);
2585 * Broadcast our presence on one of our interfaces.
2587 * @param cls a `struct BroadcastInterface`
2590 ifc_broadcast (void *cls)
2592 struct BroadcastInterface *bi = cls;
2593 struct GNUNET_TIME_Relative delay;
2595 delay = BROADCAST_FREQUENCY;
2596 delay.rel_value_us = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
2597 delay.rel_value_us);
2599 = GNUNET_SCHEDULER_add_delayed (INTERFACE_SCAN_FREQUENCY,
2603 switch (bi->sa->sa_family) {
2611 GNUNET_NETWORK_socket_setsockopt (udp_sock,
2616 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2618 sent = GNUNET_NETWORK_socket_sendto (udp_sock,
2624 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2627 GNUNET_NETWORK_socket_setsockopt (udp_sock,
2632 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2639 struct sockaddr_in6 dst;
2641 dst.sin6_family = AF_INET6;
2642 dst.sin6_port = htons (my_port);
2643 dst.sin6_addr = bi->mcreq.ipv6mr_multiaddr;
2644 dst.sin6_scope_id = ((struct sockaddr_in6*) bi->ba)->sin6_scope_id;
2646 sent = GNUNET_NETWORK_socket_sendto (udp_sock,
2649 (const struct sockaddr *)
2653 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2665 * Callback function invoked for each interface found.
2666 * Activates/deactivates broadcast interfaces.
2669 * @param name name of the interface (can be NULL for unknown)
2670 * @param isDefault is this presumably the default interface
2671 * @param addr address of this interface (can be NULL for unknown or unassigned)
2672 * @param broadcast_addr the broadcast address (can be NULL for unknown or unassigned)
2673 * @param netmask the network mask (can be NULL for unknown or unassigned)
2674 * @param addrlen length of the address
2675 * @return #GNUNET_OK to continue iteration, #GNUNET_SYSERR to abort
2678 iface_proc (void *cls,
2681 const struct sockaddr *addr,
2682 const struct sockaddr *broadcast_addr,
2683 const struct sockaddr *netmask, socklen_t addrlen)
2685 struct BroadcastInterface *bi;
2686 enum GNUNET_NetworkType network;
2687 struct UdpBroadcastSignature ubs;
2691 network = GNUNET_NT_scanner_get_type (is,
2694 if (GNUNET_NT_LOOPBACK == network)
2696 /* Broadcasting on loopback does not make sense */
2700 return GNUNET_YES; /* need to know our address! */
2701 for (bi = bi_head; NULL != bi; bi = bi->next)
2703 if ( (bi->salen == addrlen) &&
2708 bi->found = GNUNET_YES;
2713 if ( (AF_INET6 == addr->sa_family) &&
2714 (NULL == broadcast_addr) )
2715 return GNUNET_OK; /* broadcast_addr is required for IPv6! */
2716 if ( (AF_INET6 == addr->sa_family) &&
2717 (GNUNET_YES != have_v6_socket) )
2718 return GNUNET_OK; /* not using IPv6 */
2720 bi = GNUNET_new (struct BroadcastInterface);
2721 bi->sa = GNUNET_memdup (addr,
2723 if (NULL != broadcast_addr)
2724 bi->ba = GNUNET_memdup (broadcast_addr,
2726 bi->salen = addrlen;
2727 bi->found = GNUNET_YES;
2728 bi->bcm.sender = my_identity;
2729 ubs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
2730 ubs.purpose.size = htonl (sizeof (ubs));
2731 ubs.sender = my_identity;
2732 GNUNET_CRYPTO_hash (addr,
2735 GNUNET_assert (GNUNET_OK ==
2736 GNUNET_CRYPTO_eddsa_sign (my_private_key,
2738 &bi->bcm.sender_sig));
2739 bi->broadcast_task = GNUNET_SCHEDULER_add_now (&ifc_broadcast,
2741 GNUNET_CONTAINER_DLL_insert (bi_head,
2744 if ( (AF_INET6 == addr->sa_family) &&
2745 (NULL != broadcast_addr) )
2747 /* Create IPv6 multicast request */
2748 const struct sockaddr_in6 *s6
2749 = (const struct sockaddr_in6 *) broadcast_addr;
2752 inet_pton (AF_INET6,
2754 &bi->mcreq.ipv6mr_multiaddr));
2756 /* http://tools.ietf.org/html/rfc2553#section-5.2:
2760 * Join a multicast group on a specified local interface. If the
2761 * interface index is specified as 0, the kernel chooses the local
2762 * interface. For example, some kernels look up the multicast
2763 * group in the normal IPv6 routing table and using the resulting
2764 * interface; we do this for each interface, so no need to use
2765 * zero (anymore...).
2767 bi->mcreq.ipv6mr_interface = s6->sin6_scope_id;
2769 /* Join the multicast group */
2771 GNUNET_NETWORK_socket_setsockopt
2776 sizeof (bi->mcreq)))
2778 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2787 * Scan interfaces to broadcast our presence on the LAN.
2789 * @param cls NULL, unused
2792 do_broadcast (void *cls)
2794 struct BroadcastInterface *bin;
2797 for (struct BroadcastInterface *bi = bi_head;
2800 bi->found = GNUNET_NO;
2801 GNUNET_OS_network_interfaces_list (&iface_proc,
2803 for (struct BroadcastInterface *bi = bi_head;
2808 if (GNUNET_NO == bi->found)
2812 = GNUNET_SCHEDULER_add_delayed (INTERFACE_SCAN_FREQUENCY,
2819 * Setup communicator and launch network interactions.
2821 * @param cls NULL (always)
2822 * @param args remaining command-line arguments
2823 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2824 * @param c configuration
2829 const char *cfgfile,
2830 const struct GNUNET_CONFIGURATION_Handle *c)
2833 struct sockaddr *in;
2835 struct sockaddr_storage in_sto;
2841 GNUNET_CONFIGURATION_get_value_filename (cfg,
2842 COMMUNICATOR_CONFIG_SECTION,
2846 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2847 COMMUNICATOR_CONFIG_SECTION,
2852 in = udp_address_to_sockaddr (bindto,
2856 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2857 "Failed to setup UDP socket address with path `%s'\n",
2859 GNUNET_free (bindto);
2862 udp_sock = GNUNET_NETWORK_socket_create (in->sa_family,
2865 if (NULL == udp_sock)
2867 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
2870 GNUNET_free (bindto);
2873 if (AF_INET6 == in->sa_family)
2874 have_v6_socket = GNUNET_YES;
2876 GNUNET_NETWORK_socket_bind (udp_sock,
2880 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
2883 GNUNET_NETWORK_socket_close (udp_sock);
2886 GNUNET_free (bindto);
2889 /* We might have bound to port 0, allowing the OS to figure it out;
2890 thus, get the real IN-address from the socket */
2891 sto_len = sizeof (in_sto);
2892 if (0 != getsockname (GNUNET_NETWORK_get_fd (udp_sock),
2893 (struct sockaddr *) &in_sto,
2902 GNUNET_free (bindto);
2903 in = (struct sockaddr *) &in_sto;
2905 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2907 GNUNET_a2s ((const struct sockaddr *) &in_sto,
2909 switch (in->sa_family)
2912 my_port = ntohs (((struct sockaddr_in *) in)->sin_port);
2915 my_port = ntohs (((struct sockaddr_in6 *) in)->sin6_port);
2921 stats = GNUNET_STATISTICS_create ("C-UDP",
2923 senders = GNUNET_CONTAINER_multipeermap_create (32,
2925 receivers = GNUNET_CONTAINER_multipeermap_create (32,
2927 senders_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2928 receivers_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2929 key_cache = GNUNET_CONTAINER_multishortmap_create (1024,
2931 GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
2933 is = GNUNET_NT_scanner_init ();
2934 my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
2935 if (NULL == my_private_key)
2937 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2938 _("Transport service is lacking key configuration settings. Exiting.\n"));
2939 GNUNET_SCHEDULER_shutdown ();
2942 GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
2943 &my_identity.public_key);
2945 read_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2949 ch = GNUNET_TRANSPORT_communicator_connect (cfg,
2950 COMMUNICATOR_CONFIG_SECTION,
2951 COMMUNICATOR_ADDRESS_PREFIX,
2952 GNUNET_TRANSPORT_CC_UNRELIABLE,
2960 GNUNET_SCHEDULER_shutdown ();
2963 ah = GNUNET_TRANSPORT_application_init (cfg);
2967 GNUNET_SCHEDULER_shutdown ();
2970 /* start broadcasting */
2972 GNUNET_CONFIGURATION_get_value_yesno (cfg,
2973 COMMUNICATOR_CONFIG_SECTION,
2974 "DISABLE_BROADCAST"))
2976 broadcast_task = GNUNET_SCHEDULER_add_now (&do_broadcast,
2979 nat = GNUNET_NAT_register (cfg,
2980 COMMUNICATOR_CONFIG_SECTION,
2982 1 /* one address */,
2983 (const struct sockaddr **) &in,
2986 NULL /* FIXME: support reversal: #5529 */,
2987 NULL /* closure */);
2992 * The main function for the UNIX communicator.
2994 * @param argc number of arguments from the command line
2995 * @param argv command line arguments
2996 * @return 0 ok, 1 on error
3002 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
3003 GNUNET_GETOPT_OPTION_END
3008 GNUNET_STRINGS_get_utf8_args (argc, argv,
3014 GNUNET_PROGRAM_run (argc, argv,
3015 "gnunet-communicator-udp",
3016 _("GNUnet UDP communicator"),
3020 GNUNET_free ((void*) argv);
3025 /* end of gnunet-communicator-udp.c */