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 * - add and use util/ check for IPv6 availability (#5553)
28 * - consider imposing transmission limits in the absence
29 * of ACKs; or: maybe this should be done at TNG service level?
30 * (at least the receiver might want to enforce limits on
31 * KX/DH operations per sender in here) (#5552)
32 * - overall, we should look more into flow control support
33 * (either in backchannel, or general solution in TNG service)
34 * - handle addresses discovered from broadcasts (#5551)
35 * (think: what was the story again on address validation?
36 * where is the API for that!?!)
37 * - support DNS names in BINDTO option (#5528)
38 * - support NAT connection reversal method (#5529)
39 * - support other UDP-specific NAT traversal methods (#)
42 #include "gnunet_util_lib.h"
43 #include "gnunet_protocols.h"
44 #include "gnunet_signatures.h"
45 #include "gnunet_constants.h"
46 #include "gnunet_nt_lib.h"
47 #include "gnunet_nat_service.h"
48 #include "gnunet_statistics_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)
74 #define AES_KEY_SIZE (256/8)
79 #define AES_IV_SIZE (96/8)
82 * Size of the GCM tag.
84 #define GCM_TAG_SIZE (128/8)
87 * If we fall below this number of available KCNs,
88 * we generate additional ACKs until we reach
90 * Should be large enough that we don't generate ACKs all
91 * the time and still have enough time for the ACK to
92 * arrive before the sender runs out. So really this
93 * should ideally be based on the RTT.
95 #define KCN_THRESHOLD 92
98 * How many KCNs do we keep around *after* we hit
99 * the #KCN_THRESHOLD? Should be larger than
100 * #KCN_THRESHOLD so we do not generate just one
103 #define KCN_TARGET 128
106 * What is the maximum delta between KCN sequence numbers
107 * that we allow. Used to expire 'ancient' KCNs that likely
108 * were dropped by the network. Must be larger than
109 * KCN_TARGET (otherwise we generate new KCNs all the time),
110 * but not too large (otherwise packet loss may cause
111 * sender to fall back to KX needlessly when sender runs
112 * out of ACK'ed KCNs due to losses).
114 #define MAX_SQN_DELTA 160
117 * How many shared master secrets do we keep around
118 * at most per sender? Should be large enough so
119 * that we generally have a chance of sending an ACK
120 * before the sender already rotated out the master
121 * secret. Generally values around #KCN_TARGET make
122 * sense. Might make sense to adapt to RTT if we had
123 * a good measurement...
125 #define MAX_SECRETS 128
128 * How often do we rekey based on number of bytes transmitted?
129 * (additionally randomized).
131 #define REKEY_MAX_BYTES (1024LLU * 1024 * 1024 * 4LLU)
134 * Address prefix used by the communicator.
137 #define COMMUNICATOR_ADDRESS_PREFIX "udp"
140 * Configuration section used by the communicator.
142 #define COMMUNICATOR_CONFIG_SECTION "communicator-udp"
144 GNUNET_NETWORK_STRUCT_BEGIN
148 * Signature we use to verify that the ephemeral key was really chosen by
149 * the specified sender. If possible, the receiver should respond with
150 * a `struct UDPAck` (possibly via backchannel).
152 struct UdpHandshakeSignature
155 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
157 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
160 * Identity of the inititor of the UDP connection (UDP client).
162 struct GNUNET_PeerIdentity sender;
165 * Presumed identity of the target of the UDP connection (UDP server)
167 struct GNUNET_PeerIdentity receiver;
170 * Ephemeral key used by the @e sender.
172 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
175 * Monotonic time of @e sender, to possibly help detect replay attacks
176 * (if receiver persists times by sender).
178 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
183 * "Plaintext" header at beginning of KX message. Followed
184 * by encrypted `struct UDPConfirmation`.
190 * Ephemeral key for KX.
192 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
195 * HMAC for the following encrypted message, using GCM. HMAC uses
196 * key derived from the handshake with sequence number zero.
198 char gcm_tag[GCM_TAG_SIZE];
204 * Encrypted continuation of UDP initial handshake, followed
205 * by message header with payload.
207 struct UDPConfirmation
212 struct GNUNET_PeerIdentity sender;
215 * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
217 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
220 * Monotonic time of @e sender, to possibly help detect replay attacks
221 * (if receiver persists times by sender).
223 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
225 /* followed by messages */
227 /* padding may follow actual messages */
232 * UDP key acknowledgement. May be sent via backchannel. Allows the
233 * sender to use `struct UDPBox` with the acknowledge key henceforth.
239 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK.
241 struct GNUNET_MessageHeader header;
244 * Sequence acknowledgement limit. Specifies current maximum sequence
245 * number supported by receiver.
247 uint32_t sequence_max GNUNET_PACKED;
250 * CMAC of the base key being acknowledged.
252 struct GNUNET_HashCode cmac;
258 * Signature we use to verify that the broadcast was really made by
259 * the peer that claims to have made it. Basically, affirms that the
260 * peer is really using this IP address (albeit possibly not in _our_
261 * LAN). Makes it difficult for peers in the LAN to claim to
262 * be just any global peer -- an attacker must have at least
263 * shared a LAN with the peer they're pretending to be here.
265 struct UdpBroadcastSignature
268 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
270 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
273 * Identity of the inititor of the UDP broadcast.
275 struct GNUNET_PeerIdentity sender;
278 * Hash of the sender's UDP address.
280 struct GNUNET_HashCode h_address;
285 * Broadcast by peer in LAN announcing its presence. Unusual in that
286 * we don't pad these to full MTU, as we cannot prevent being
287 * recognized in LAN as GNUnet peers if this feature is enabled
288 * anyway. Also, the entire message is in cleartext.
294 * Sender's peer identity.
296 struct GNUNET_PeerIdentity sender;
299 * Sender's signature of type
300 * #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
302 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
308 * UDP message box. Always sent encrypted, only allowed after
309 * the receiver sent a `struct UDPAck` for the base key!
315 * Key and IV identification code. KDF applied to an acknowledged
316 * base key and a sequence number. Sequence numbers must be used
317 * monotonically increasing up to the maximum specified in
318 * `struct UDPAck`. Without further `struct UDPAck`s, the sender
319 * must fall back to sending handshakes!
321 struct GNUNET_ShortHashCode kid;
324 * 128-bit authentication tag for the following encrypted message,
325 * from GCM. MAC starts at the @e body_start that follows and
326 * extends until the end of the UDP payload. If the @e hmac is
327 * wrong, the receiver should check if the message might be a
328 * `struct UdpHandshakeSignature`.
330 char gcm_tag[GCM_TAG_SIZE];
335 GNUNET_NETWORK_STRUCT_END
338 * Shared secret we generated for a particular sender or receiver.
344 * Pre-generated "kid" code (key and IV identification code) to
345 * quickly derive master key for a `struct UDPBox`.
353 struct KeyCacheEntry *next;
358 struct KeyCacheEntry *prev;
361 * Key and IV identification code. KDF applied to an acknowledged
362 * base key and a sequence number. Sequence numbers must be used
363 * monotonically increasing up to the maximum specified in
364 * `struct UDPAck`. Without further `struct UDPAck`s, the sender
365 * must fall back to sending handshakes!
367 struct GNUNET_ShortHashCode kid;
370 * Corresponding shared secret.
372 struct SharedSecret *ss;
375 * Sequence number used to derive this entry from master key.
377 uint32_t sequence_number;
382 * Information we track per sender address we have recently been
383 * in contact with (decryption from sender).
385 struct SenderAddress;
388 * Information we track per receiving address we have recently been
389 * in contact with (encryption to receiver).
391 struct ReceiverAddress;
394 * Shared secret we generated for a particular sender or receiver.
401 struct SharedSecret *next;
406 struct SharedSecret *prev;
409 * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
411 struct KeyCacheEntry *kce_head;
414 * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
416 struct KeyCacheEntry *kce_tail;
419 * Sender we use this shared secret with, or NULL.
421 struct SenderAddress *sender;
424 * Receiver we use this shared secret with, or NULL.
426 struct ReceiverAddress *receiver;
429 * Master shared secret.
431 struct GNUNET_HashCode master;
434 * CMAC is used to identify @e master in ACKs.
436 struct GNUNET_HashCode cmac;
439 * Up to which sequence number did we use this @e master already?
440 * (for encrypting only)
442 uint32_t sequence_used;
445 * Up to which sequence number did the other peer allow us to use
446 * this key, or up to which number did we allow the other peer to
449 uint32_t sequence_allowed;
452 * Number of active KCN entries.
454 unsigned int active_kce_count;
459 * Information we track per sender address we have recently been
460 * in contact with (we decrypt messages from the sender).
466 * To whom are we talking to.
468 struct GNUNET_PeerIdentity target;
471 * Entry in sender expiration heap.
473 struct GNUNET_CONTAINER_HeapNode *hn;
476 * Shared secrets we used with @e target, first used is head.
478 struct SharedSecret *ss_head;
481 * Shared secrets we used with @e target, last used is tail.
483 struct SharedSecret *ss_tail;
486 * Address of the other peer.
488 struct sockaddr *address;
491 * Length of the address.
493 socklen_t address_len;
496 * Timeout for this sender.
498 struct GNUNET_TIME_Absolute timeout;
501 * Length of the DLL at @a ss_head.
503 unsigned int num_secrets;
506 * Which network type does this queue use?
508 enum GNUNET_NetworkType nt;
514 * Information we track per receiving address we have recently been
515 * in contact with (encryption to receiver).
517 struct ReceiverAddress
521 * To whom are we talking to.
523 struct GNUNET_PeerIdentity target;
526 * Shared secrets we received from @e target, first used is head.
528 struct SharedSecret *ss_head;
531 * Shared secrets we received with @e target, last used is tail.
533 struct SharedSecret *ss_tail;
536 * Address of the receiver in the human-readable format
537 * with the #COMMUNICATOR_ADDRESS_PREFIX.
542 * Address of the other peer.
544 struct sockaddr *address;
547 * Length of the address.
549 socklen_t address_len;
552 * Entry in sender expiration heap.
554 struct GNUNET_CONTAINER_HeapNode *hn;
557 * Message queue we are providing for the #ch.
559 struct GNUNET_MQ_Handle *mq;
562 * handle for this queue with the #ch.
564 struct GNUNET_TRANSPORT_QueueHandle *qh;
567 * Timeout for this receiver address.
569 struct GNUNET_TIME_Absolute timeout;
572 * MTU we allowed transport for this receiver right now.
577 * Length of the DLL at @a ss_head.
579 unsigned int num_secrets;
582 * Number of BOX keys from ACKs we have currently
583 * available for this receiver.
585 unsigned int acks_available;
588 * Which network type does this queue use?
590 enum GNUNET_NetworkType nt;
596 * Interface we broadcast our presence on.
598 struct BroadcastInterface
604 struct BroadcastInterface *next;
609 struct BroadcastInterface *prev;
612 * Task for this broadcast interface.
614 struct GNUNET_SCHEDULER_Task *broadcast_task;
617 * Sender's address of the interface.
622 * Broadcast address to use on the interface.
627 * Message we broadcast on this interface.
629 struct UDPBroadcast bcm;
632 * If this is an IPv6 interface, this is the request
633 * we use to join/leave the group.
635 struct ipv6_mreq mcreq;
638 * Number of bytes in @e sa.
643 * Was this interface found in the last #iface_proc() scan?
650 * Cache of pre-generated key IDs.
652 static struct GNUNET_CONTAINER_MultiShortmap *key_cache;
657 static struct GNUNET_SCHEDULER_Task *read_task;
662 static struct GNUNET_SCHEDULER_Task *timeout_task;
665 * ID of master broadcast task
667 static struct GNUNET_SCHEDULER_Task *broadcast_task;
670 * For logging statistics.
672 static struct GNUNET_STATISTICS_Handle *stats;
677 static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
680 * Receivers (map from peer identity to `struct ReceiverAddress`)
682 static struct GNUNET_CONTAINER_MultiPeerMap *receivers;
685 * Senders (map from peer identity to `struct SenderAddress`)
687 static struct GNUNET_CONTAINER_MultiPeerMap *senders;
690 * Expiration heap for senders (contains `struct SenderAddress`)
692 static struct GNUNET_CONTAINER_Heap *senders_heap;
695 * Expiration heap for receivers (contains `struct ReceiverAddress`)
697 static struct GNUNET_CONTAINER_Heap *receivers_heap;
700 * Broadcast interface tasks. Kept in a DLL.
702 static struct BroadcastInterface *bi_head;
705 * Broadcast interface tasks. Kept in a DLL.
707 static struct BroadcastInterface *bi_tail;
712 static struct GNUNET_NETWORK_Handle *udp_sock;
715 * #GNUNET_YES if #udp_sock supports IPv6.
717 static int have_v6_socket;
722 static struct GNUNET_PeerIdentity my_identity;
727 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
732 static const struct GNUNET_CONFIGURATION_Handle *cfg;
735 * Network scanner to determine network types.
737 static struct GNUNET_NT_InterfaceScanner *is;
740 * Connection to NAT service.
742 static struct GNUNET_NAT_Handle *nat;
745 * Port number to which we are actually bound.
747 static uint16_t my_port;
751 * An interface went away, stop broadcasting on it.
753 * @param bi entity to close down
756 bi_destroy (struct BroadcastInterface *bi)
758 if (AF_INET6 == bi->sa->sa_family)
760 /* Leave the multicast group */
762 GNUNET_NETWORK_socket_setsockopt
769 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
773 GNUNET_CONTAINER_DLL_remove (bi_head,
776 GNUNET_SCHEDULER_cancel (bi->broadcast_task);
777 GNUNET_free (bi->sa);
778 GNUNET_free_non_null (bi->ba);
784 * Destroys a receiving state due to timeout or shutdown.
786 * @param receiver entity to close down
789 receiver_destroy (struct ReceiverAddress *receiver)
791 struct GNUNET_MQ_Handle *mq;
793 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
794 "Disconnecting receiver for peer `%s'\n",
795 GNUNET_i2s (&receiver->target));
796 if (NULL != (mq = receiver->mq))
799 GNUNET_MQ_destroy (mq);
801 if (NULL != receiver->qh)
803 GNUNET_TRANSPORT_communicator_mq_del (receiver->qh);
806 GNUNET_assert (GNUNET_YES ==
807 GNUNET_CONTAINER_multipeermap_remove (receivers,
810 GNUNET_assert (receiver ==
811 GNUNET_CONTAINER_heap_remove_node (receiver->hn));
812 GNUNET_STATISTICS_set (stats,
813 "# receivers active",
814 GNUNET_CONTAINER_multipeermap_size (receivers),
816 GNUNET_free (receiver->address);
817 GNUNET_free (receiver->foreign_addr);
818 GNUNET_free (receiver);
823 * Free memory used by key cache entry.
825 * @param kce the key cache entry
828 kce_destroy (struct KeyCacheEntry *kce)
830 struct SharedSecret *ss = kce->ss;
832 ss->active_kce_count--;
833 GNUNET_CONTAINER_DLL_remove (ss->kce_head,
836 GNUNET_assert (GNUNET_YES ==
837 GNUNET_CONTAINER_multishortmap_remove (key_cache,
847 * @param msec master secret for HMAC calculation
848 * @param serial number for the @a smac calculation
849 * @param kid[out] where to write the key ID
852 get_kid (const struct GNUNET_HashCode *msec,
854 struct GNUNET_ShortHashCode *kid)
856 uint32_t sid = htonl (serial);
858 GNUNET_CRYPTO_hkdf (kid,
873 * Setup key cache entry for sequence number @a seq and shared secret @a ss.
875 * @param ss shared secret
876 * @param seq sequence number for the key cache entry
879 kce_generate (struct SharedSecret *ss,
882 struct KeyCacheEntry *kce;
884 GNUNET_assert (0 < seq);
885 kce = GNUNET_new (struct KeyCacheEntry);
887 kce->sequence_number = seq;
888 get_kid (&ss->master,
891 GNUNET_CONTAINER_DLL_insert (ss->kce_head,
894 ss->active_kce_count++;
895 (void) GNUNET_CONTAINER_multishortmap_put (key_cache,
898 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
899 GNUNET_STATISTICS_set (stats,
901 GNUNET_CONTAINER_multishortmap_size (key_cache),
907 * Destroy @a ss and associated key cache entries.
909 * @param ss shared secret to destroy
912 secret_destroy (struct SharedSecret *ss)
914 struct SenderAddress *sender;
915 struct ReceiverAddress *receiver;
916 struct KeyCacheEntry *kce;
918 if (NULL != (sender = ss->sender))
920 GNUNET_CONTAINER_DLL_remove (sender->ss_head,
923 sender->num_secrets--;
925 if (NULL != (receiver = ss->receiver))
927 GNUNET_CONTAINER_DLL_remove (receiver->ss_head,
930 receiver->num_secrets--;
931 receiver->acks_available
932 -= (ss->sequence_allowed - ss->sequence_used);
934 while (NULL != (kce = ss->kce_head))
936 GNUNET_STATISTICS_update (stats,
940 GNUNET_STATISTICS_set (stats,
942 GNUNET_CONTAINER_multishortmap_size (key_cache),
949 * Functions with this signature are called whenever we need
950 * to close a sender's state due to timeout.
952 * @param sender entity to close down
955 sender_destroy (struct SenderAddress *sender)
957 GNUNET_assert (GNUNET_YES ==
958 GNUNET_CONTAINER_multipeermap_remove (senders,
961 GNUNET_assert (sender ==
962 GNUNET_CONTAINER_heap_remove_node (sender->hn));
963 GNUNET_STATISTICS_set (stats,
965 GNUNET_CONTAINER_multipeermap_size (senders),
967 GNUNET_free (sender->address);
968 GNUNET_free (sender);
973 * Compute @a key and @a iv.
975 * @param msec master secret for calculation
976 * @param serial number for the @a smac calculation
977 * @param key[out] where to write the decrption key
978 * @param iv[out] where to write the IV
981 get_iv_key (const struct GNUNET_HashCode *msec,
983 char key[AES_KEY_SIZE],
984 char iv[AES_IV_SIZE])
986 uint32_t sid = htonl (serial);
987 char res[AES_KEY_SIZE + AES_IV_SIZE];
989 GNUNET_CRYPTO_hkdf (res,
998 strlen ("UDP-IV-KEY"),
1010 * Increment sender timeout due to activity.
1012 * @param sender address for which the timeout should be rescheduled
1015 reschedule_sender_timeout (struct SenderAddress *sender)
1018 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1019 GNUNET_CONTAINER_heap_update_cost (sender->hn,
1020 sender->timeout.abs_value_us);
1025 * Increment receiver timeout due to activity.
1027 * @param receiver address for which the timeout should be rescheduled
1030 reschedule_receiver_timeout (struct ReceiverAddress *receiver)
1033 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1034 GNUNET_CONTAINER_heap_update_cost (receiver->hn,
1035 receiver->timeout.abs_value_us);
1040 * Task run to check #receiver_heap and #sender_heap for timeouts.
1042 * @param cls unused, NULL
1045 check_timeouts (void *cls)
1047 struct GNUNET_TIME_Relative st;
1048 struct GNUNET_TIME_Relative rt;
1049 struct GNUNET_TIME_Relative delay;
1050 struct ReceiverAddress *receiver;
1051 struct SenderAddress *sender;
1054 timeout_task = NULL;
1055 rt = GNUNET_TIME_UNIT_FOREVER_REL;
1056 while (NULL != (receiver = GNUNET_CONTAINER_heap_peek (receivers_heap)))
1058 rt = GNUNET_TIME_absolute_get_remaining (receiver->timeout);
1059 if (0 != rt.rel_value_us)
1061 receiver_destroy (receiver);
1063 st = GNUNET_TIME_UNIT_FOREVER_REL;
1064 while (NULL != (sender = GNUNET_CONTAINER_heap_peek (senders_heap)))
1066 st = GNUNET_TIME_absolute_get_remaining (receiver->timeout);
1067 if (0 != st.rel_value_us)
1069 sender_destroy (sender);
1071 delay = GNUNET_TIME_relative_min (rt,
1073 if (delay.rel_value_us < GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
1074 timeout_task = GNUNET_SCHEDULER_add_delayed (delay,
1081 * Calcualte cmac from master in @a ss.
1083 * @param ss[in,out] data structure to complete
1086 calculate_cmac (struct SharedSecret *ss)
1088 GNUNET_CRYPTO_hkdf (&ss->cmac,
1095 sizeof (ss->master),
1097 strlen ("UDP-CMAC"),
1103 * We received @a plaintext_len bytes of @a plaintext from a @a sender.
1104 * Pass it on to CORE.
1106 * @param queue the queue that received the plaintext
1107 * @param plaintext the plaintext that was received
1108 * @param plaintext_len number of bytes of plaintext received
1111 pass_plaintext_to_core (struct SenderAddress *sender,
1112 const void *plaintext,
1113 size_t plaintext_len)
1115 const struct GNUNET_MessageHeader *hdr = plaintext;
1117 while (ntohs (hdr->size) < plaintext_len)
1119 GNUNET_STATISTICS_update (stats,
1120 "# bytes given to core",
1123 (void) GNUNET_TRANSPORT_communicator_receive (ch,
1126 NULL /* no flow control possible */,
1128 /* move on to next message, if any */
1129 plaintext_len -= ntohs (hdr->size);
1130 if (plaintext_len < sizeof (*hdr))
1132 hdr = plaintext + ntohs (hdr->size);
1134 GNUNET_STATISTICS_update (stats,
1135 "# bytes padding discarded",
1142 * Setup @a cipher based on shared secret @a msec and
1143 * serial number @a serial.
1145 * @param msec master shared secret
1146 * @param serial serial number of cipher to set up
1147 * @param cipher[out] cipher to initialize
1150 setup_cipher (const struct GNUNET_HashCode *msec,
1152 gcry_cipher_hd_t *cipher)
1154 char key[AES_KEY_SIZE];
1155 char iv[AES_IV_SIZE];
1157 gcry_cipher_open (cipher,
1158 GCRY_CIPHER_AES256 /* low level: go for speed */,
1159 GCRY_CIPHER_MODE_GCM,
1165 gcry_cipher_setkey (*cipher,
1168 gcry_cipher_setiv (*cipher,
1175 * Try to decrypt @a buf using shared secret @a ss and key/iv
1176 * derived using @a serial.
1178 * @param ss shared secret
1179 * @param tag GCM authentication tag
1180 * @param serial serial number to use
1181 * @param in_buf input buffer to decrypt
1182 * @param in_buf_size number of bytes in @a in_buf and available in @a out_buf
1183 * @param out_buf where to write the result
1184 * @return #GNUNET_OK on success
1187 try_decrypt (const struct SharedSecret *ss,
1188 const char tag[GCM_TAG_SIZE],
1194 gcry_cipher_hd_t cipher;
1196 setup_cipher (&ss->master,
1200 gcry_cipher_decrypt (cipher,
1206 gcry_cipher_checktag (cipher,
1210 gcry_cipher_close (cipher);
1211 GNUNET_STATISTICS_update (stats,
1212 "# AEAD authentication failures",
1215 return GNUNET_SYSERR;
1217 gcry_cipher_close (cipher);
1223 * Setup shared secret for decryption.
1225 * @param ephemeral ephemeral key we received from the other peer
1226 * @return new shared secret
1228 static struct SharedSecret *
1229 setup_shared_secret_dec (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1231 struct SharedSecret *ss;
1233 ss = GNUNET_new (struct SharedSecret);
1234 GNUNET_CRYPTO_eddsa_ecdh (my_private_key,
1242 * Setup shared secret for encryption.
1244 * @param ephemeral ephemeral key we are sending to the other peer
1245 * @param receiver[in,out] queue to initialize encryption key for
1246 * @return new shared secret
1248 static struct SharedSecret *
1249 setup_shared_secret_enc (const struct GNUNET_CRYPTO_EcdhePrivateKey *ephemeral,
1250 struct ReceiverAddress *receiver)
1252 struct SharedSecret *ss;
1254 ss = GNUNET_new (struct SharedSecret);
1255 GNUNET_CRYPTO_ecdh_eddsa (ephemeral,
1256 &receiver->target.public_key,
1258 calculate_cmac (ss);
1259 ss->receiver = receiver;
1260 GNUNET_CONTAINER_DLL_insert (receiver->ss_head,
1263 receiver->num_secrets++;
1264 GNUNET_STATISTICS_update (stats,
1273 * Setup the MQ for the @a receiver. If a queue exists,
1274 * the existing one is destroyed. Then the MTU is
1275 * recalculated and a fresh queue is initialized.
1277 * @param receiver receiver to setup MQ for
1280 setup_receiver_mq (struct ReceiverAddress *receiver);
1284 * We received an ACK for @a pid. Check if it is for
1285 * the receiver in @a value and if so, handle it and
1286 * return #GNUNET_NO. Otherwise, return #GNUNET_YES.
1288 * @param cls a `const struct UDPAck`
1289 * @param pid peer the ACK is from
1290 * @param value a `struct ReceiverAddress`
1291 * @return #GNUNET_YES to continue to iterate
1294 handle_ack (void *cls,
1295 const struct GNUNET_PeerIdentity *pid,
1298 const struct UDPAck *ack = cls;
1299 struct ReceiverAddress *receiver = value;
1302 for (struct SharedSecret *ss = receiver->ss_head;
1306 if (0 == memcmp (&ack->cmac,
1308 sizeof (struct GNUNET_HashCode)))
1312 allowed = ntohl (ack->sequence_max);
1314 if (allowed > ss->sequence_allowed)
1316 receiver->acks_available += (allowed - ss->sequence_allowed);
1317 if ((allowed - ss->sequence_allowed)
1318 == receiver->acks_available)
1320 /* we just incremented from zero => MTU change! */
1321 setup_receiver_mq (receiver);
1323 ss->sequence_allowed = allowed;
1324 /* move ss to head to avoid discarding it anytime soon! */
1325 GNUNET_CONTAINER_DLL_remove (receiver->ss_head,
1328 GNUNET_CONTAINER_DLL_insert (receiver->ss_head,
1340 * Test if we have received a valid message in plaintext.
1343 * @param sender peer to process inbound plaintext for
1344 * @param buf buffer we received
1345 * @param buf_size number of bytes in @a buf
1348 try_handle_plaintext (struct SenderAddress *sender,
1352 const struct GNUNET_MessageHeader *hdr
1353 = (const struct GNUNET_MessageHeader *) buf;
1354 const struct UDPAck *ack
1355 = (const struct UDPAck *) buf;
1358 if (sizeof (*hdr) > buf_size)
1359 return; /* not even a header */
1360 if (ntohs (hdr->size) > buf_size)
1361 return; /* not even a header */
1362 type = ntohs (hdr->type);
1365 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK:
1366 /* lookup master secret by 'cmac', then update sequence_max */
1367 GNUNET_CONTAINER_multipeermap_get_multiple (receivers,
1371 /* There could be more messages after the ACK, handle those as well */
1372 buf += ntohs (hdr->size);
1373 buf_size -= ntohs (hdr->size);
1374 pass_plaintext_to_core (sender,
1378 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD:
1382 pass_plaintext_to_core (sender,
1390 * We established a shared secret with a sender. We should try to send
1391 * the sender an `struct UDPAck` at the next opportunity to allow the
1392 * sender to use @a ss longer (assuming we did not yet already
1395 * @param ss shared secret to generate ACKs for
1398 consider_ss_ack (struct SharedSecret *ss)
1400 GNUNET_assert (NULL != ss->sender);
1401 /* drop ancient KeyCacheEntries */
1402 while ( (NULL != ss->kce_head) &&
1403 (MAX_SQN_DELTA < ss->kce_head->sequence_number - ss->kce_tail->sequence_number) )
1404 kce_destroy (ss->kce_tail);
1405 if (ss->active_kce_count < KCN_THRESHOLD)
1409 while (ss->active_kce_count < KCN_TARGET)
1411 ++ss->sequence_allowed);
1412 ack.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK);
1413 ack.header.size = htons (sizeof (ack));
1414 ack.sequence_max = htonl (ss->sequence_allowed);
1415 ack.cmac = ss->cmac;
1416 GNUNET_TRANSPORT_communicator_notify (ch,
1417 &ss->sender->target,
1418 COMMUNICATOR_ADDRESS_PREFIX,
1425 * We received a @a box with matching @a kce. Decrypt and process it.
1427 * @param box the data we received
1428 * @param box_len number of bytes in @a box
1429 * @param kce key index to decrypt @a box
1432 decrypt_box (const struct UDPBox *box,
1434 struct KeyCacheEntry *kce)
1436 struct SharedSecret *ss = kce->ss;
1437 char out_buf[box_len - sizeof (*box)];
1439 GNUNET_assert (NULL != ss->sender);
1443 kce->sequence_number,
1444 (const char *) &box[1],
1448 GNUNET_STATISTICS_update (stats,
1449 "# Decryption failures with valid KCE",
1456 GNUNET_STATISTICS_update (stats,
1457 "# bytes decrypted with BOX",
1460 try_handle_plaintext (ss->sender,
1463 consider_ss_ack (ss);
1468 * Closure for #find_sender_by_address()
1470 struct SearchContext
1473 * Address we are looking for.
1475 const struct sockaddr *address;
1478 * Number of bytes in @e address.
1480 socklen_t address_len;
1483 * Return value to set if we found a match.
1485 struct SenderAddress *sender;
1490 * Find existing `struct SenderAddress` by matching addresses.
1492 * @param cls a `struct SearchContext`
1493 * @param key ignored, must match already
1494 * @param value a `struct SenderAddress`
1495 * @return #GNUNET_YES if not found (continue to search), #GNUNET_NO if found
1498 find_sender_by_address (void *cls,
1499 const struct GNUNET_PeerIdentity *key,
1502 struct SearchContext *sc = cls;
1503 struct SenderAddress *sender = value;
1505 if ( (sender->address_len == sc->address_len) &&
1506 (0 == memcmp (sender->address,
1508 sender->address_len)) )
1510 sc->sender = sender;
1511 return GNUNET_NO; /* stop iterating! */
1518 * Create sender address for @a target. Note that we
1519 * might already have one, so a fresh one is only allocated
1520 * if one does not yet exist for @a address.
1522 * @param target peer to generate address for
1523 * @param address target address
1524 * @param address_len number of bytes in @a address
1525 * @return data structure to keep track of key material for
1526 * decrypting data from @a target
1528 static struct SenderAddress *
1529 setup_sender (const struct GNUNET_PeerIdentity *target,
1530 const struct sockaddr *address,
1531 socklen_t address_len)
1533 struct SenderAddress *sender;
1534 struct SearchContext sc = {
1536 .address_len = address_len,
1540 GNUNET_CONTAINER_multipeermap_get_multiple (senders,
1542 &find_sender_by_address,
1544 if (NULL != sc.sender)
1546 reschedule_sender_timeout (sc.sender);
1549 sender = GNUNET_new (struct SenderAddress);
1550 sender->target = *target;
1551 sender->address = GNUNET_memdup (address,
1553 sender->address_len = address_len;
1554 (void) GNUNET_CONTAINER_multipeermap_put (senders,
1557 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1558 GNUNET_STATISTICS_set (stats,
1560 GNUNET_CONTAINER_multipeermap_size (receivers),
1563 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1564 sender->hn = GNUNET_CONTAINER_heap_insert (senders_heap,
1566 sender->timeout.abs_value_us);
1567 sender->nt = GNUNET_NT_scanner_get_type (is,
1570 if (NULL == timeout_task)
1571 timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts,
1578 * Check signature from @a uc against @a ephemeral.
1580 * @param ephermal key that is signed
1581 * @param uc signature of claimant
1582 * @return #GNUNET_OK if signature is valid
1585 verify_confirmation (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral,
1586 const struct UDPConfirmation *uc)
1588 struct UdpHandshakeSignature uhs;
1590 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
1591 uhs.purpose.size = htonl (sizeof (uhs));
1592 uhs.sender = uc->sender;
1593 uhs.receiver = my_identity;
1594 uhs.ephemeral = *ephemeral;
1595 uhs.monotonic_time = uc->monotonic_time;
1596 return GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE,
1599 &uc->sender.public_key);
1609 sock_read (void *cls)
1611 struct sockaddr_storage sa;
1612 socklen_t salen = sizeof (sa);
1613 char buf[UINT16_MAX];
1618 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1622 rcvd = GNUNET_NETWORK_socket_recvfrom (udp_sock,
1625 (struct sockaddr *) &sa,
1629 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1634 /* first, see if it is a UDPBox */
1635 if (rcvd > sizeof (struct UDPBox))
1637 const struct UDPBox *box;
1638 struct KeyCacheEntry *kce;
1640 box = (const struct UDPBox *) buf;
1641 kce = GNUNET_CONTAINER_multishortmap_get (key_cache,
1652 /* next, check if it is a broadcast */
1653 if (sizeof (struct UDPBroadcast) == rcvd)
1655 const struct UDPBroadcast *ub;
1656 struct UdpBroadcastSignature uhs;
1658 ub = (const struct UDPBroadcast *) buf;
1659 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
1660 uhs.purpose.size = htonl (sizeof (uhs));
1661 uhs.sender = ub->sender;
1662 GNUNET_CRYPTO_hash (&sa,
1666 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST,
1669 &ub->sender.public_key))
1671 GNUNET_STATISTICS_update (stats,
1672 "# broadcasts received",
1675 // FIXME #5551: we effectively just got a HELLO!
1676 // trigger verification NOW!
1679 /* continue with KX, mostly for statistics... */
1683 /* finally, test if it is a KX */
1684 if (rcvd < sizeof (struct UDPConfirmation) + sizeof (struct InitialKX))
1686 GNUNET_STATISTICS_update (stats,
1687 "# messages dropped (no kid, too small for KX)",
1694 const struct InitialKX *kx;
1695 struct SharedSecret *ss;
1696 char pbuf[rcvd - sizeof (struct InitialKX)];
1697 const struct UDPConfirmation *uc;
1698 struct SenderAddress *sender;
1700 kx = (const struct InitialKX *) buf;
1701 ss = setup_shared_secret_dec (&kx->ephemeral);
1711 GNUNET_STATISTICS_update (stats,
1712 "# messages dropped (no kid, AEAD decryption failed)",
1717 uc = (const struct UDPConfirmation *) pbuf;
1719 verify_confirmation (&kx->ephemeral,
1722 GNUNET_break_op (0);
1724 GNUNET_STATISTICS_update (stats,
1725 "# messages dropped (sender signature invalid)",
1730 calculate_cmac (ss);
1731 sender = setup_sender (&uc->sender,
1732 (const struct sockaddr *) &sa,
1734 ss->sender = sender;
1735 GNUNET_CONTAINER_DLL_insert (sender->ss_head,
1738 sender->num_secrets++;
1739 GNUNET_STATISTICS_update (stats,
1743 GNUNET_STATISTICS_update (stats,
1744 "# messages decrypted without BOX",
1747 try_handle_plaintext (sender,
1749 sizeof (pbuf) - sizeof (*uc));
1750 consider_ss_ack (ss);
1751 if (sender->num_secrets > MAX_SECRETS)
1752 secret_destroy (sender->ss_tail);
1758 * Convert UDP bind specification to a `struct sockaddr *`
1760 * @param bindto bind specification to convert
1761 * @param[out] sock_len set to the length of the address
1762 * @return converted bindto specification
1764 static struct sockaddr *
1765 udp_address_to_sockaddr (const char *bindto,
1766 socklen_t *sock_len)
1768 struct sockaddr *in;
1774 if (1 == SSCANF (bindto,
1779 /* interpreting value as just a PORT number */
1780 if (port > UINT16_MAX)
1782 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1783 "BINDTO specification `%s' invalid: value too large for port\n",
1787 /* FIXME #V6: add test to util/ for IPv6 availability,
1788 and depending on the result, go directly for v4-only */
1790 GNUNET_CONFIGURATION_get_value_yesno (cfg,
1791 COMMUNICATOR_CONFIG_SECTION,
1794 struct sockaddr_in *i4;
1796 i4 = GNUNET_malloc (sizeof (struct sockaddr_in));
1797 i4->sin_family = AF_INET;
1798 i4->sin_port = htons ((uint16_t) port);
1799 *sock_len = sizeof (struct sockaddr_in);
1800 in = (struct sockaddr *) i4;
1804 struct sockaddr_in6 *i6;
1806 i6 = GNUNET_malloc (sizeof (struct sockaddr_in6));
1807 i6->sin6_family = AF_INET6;
1808 i6->sin6_port = htons ((uint16_t) port);
1809 *sock_len = sizeof (struct sockaddr_in6);
1810 in = (struct sockaddr *) i6;
1814 cp = GNUNET_strdup (bindto);
1815 colon = strrchr (cp, ':');
1818 /* interpet value after colon as port */
1821 if (1 == SSCANF (colon,
1826 /* interpreting value as just a PORT number */
1827 if (port > UINT16_MAX)
1829 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1830 "BINDTO specification `%s' invalid: value too large for port\n",
1838 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1839 "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1847 /* interpret missing port as 0, aka pick any free one */
1852 struct sockaddr_in v4;
1854 if (1 == inet_pton (AF_INET,
1858 v4.sin_port = htons ((uint16_t) port);
1859 in = GNUNET_memdup (&v4,
1861 *sock_len = sizeof (v4);
1868 struct sockaddr_in6 v6;
1872 if ( ('[' == *cp) &&
1873 (']' == cp[strlen (cp)-1]) )
1875 start++; /* skip over '[' */
1876 cp[strlen (cp) -1] = '\0'; /* eat ']' */
1878 if (1 == inet_pton (AF_INET6,
1882 v6.sin6_port = htons ((uint16_t) port);
1883 in = GNUNET_memdup (&v6,
1885 *sock_len = sizeof (v6);
1890 /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1897 * Pad @a dgram by @a pad_size using @a out_cipher.
1899 * @param out_cipher cipher to use
1900 * @param dgram datagram to pad
1901 * @param pad_size number of bytes of padding to append
1904 do_pad (gcry_cipher_hd_t out_cipher,
1910 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
1913 if (sizeof (pad) > sizeof (struct GNUNET_MessageHeader))
1915 struct GNUNET_MessageHeader hdr = {
1916 .size = htons (sizeof (pad)),
1917 .type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD)
1925 gcry_cipher_encrypt (out_cipher,
1934 * Signature of functions implementing the sending functionality of a
1937 * @param mq the message queue
1938 * @param msg the message to send
1939 * @param impl_state our `struct ReceiverAddress`
1942 mq_send (struct GNUNET_MQ_Handle *mq,
1943 const struct GNUNET_MessageHeader *msg,
1946 struct ReceiverAddress *receiver = impl_state;
1947 uint16_t msize = ntohs (msg->size);
1949 GNUNET_assert (mq == receiver->mq);
1950 if (msize > receiver->mtu)
1953 receiver_destroy (receiver);
1956 reschedule_receiver_timeout (receiver);
1958 if (0 == receiver->acks_available)
1960 /* use KX encryption method */
1961 struct UdpHandshakeSignature uhs;
1962 struct UDPConfirmation uc;
1963 struct InitialKX kx;
1964 struct GNUNET_CRYPTO_EcdhePrivateKey epriv;
1965 char dgram[receiver->mtu +
1969 gcry_cipher_hd_t out_cipher;
1970 struct SharedSecret *ss;
1972 /* setup key material */
1973 GNUNET_assert (GNUNET_OK ==
1974 GNUNET_CRYPTO_ecdhe_key_create2 (&epriv));
1976 ss = setup_shared_secret_enc (&epriv,
1978 setup_cipher (&ss->master,
1982 uc.sender = my_identity;
1983 uc.monotonic_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1984 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
1985 uhs.purpose.size = htonl (sizeof (uhs));
1986 uhs.sender = my_identity;
1987 uhs.receiver = receiver->target;
1988 GNUNET_CRYPTO_ecdhe_key_get_public (&epriv,
1990 uhs.monotonic_time = uc.monotonic_time;
1991 GNUNET_assert (GNUNET_OK ==
1992 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1995 /* Leave space for kx */
1996 dpos = sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
1997 /* Append encrypted uc to dgram */
1999 gcry_cipher_encrypt (out_cipher,
2004 dpos += sizeof (uc);
2005 /* Append encrypted payload to dgram */
2007 gcry_cipher_encrypt (out_cipher,
2015 sizeof (dgram) - dpos);
2016 /* Datagram starts with kx */
2017 kx.ephemeral = uhs.ephemeral;
2019 gcry_cipher_gettag (out_cipher,
2021 sizeof (kx.gcm_tag)));
2022 gcry_cipher_close (out_cipher);
2027 GNUNET_NETWORK_socket_sendto (udp_sock,
2031 receiver->address_len))
2032 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2034 GNUNET_MQ_impl_send_continue (mq);
2036 } /* End of KX encryption method */
2038 /* begin "BOX" encryption method, scan for ACKs from tail! */
2039 for (struct SharedSecret *ss = receiver->ss_tail;
2043 if (ss->sequence_used < ss->sequence_allowed)
2045 char dgram[sizeof (struct UDPBox) + receiver->mtu];
2047 gcry_cipher_hd_t out_cipher;
2050 box = (struct UDPBox *) dgram;
2051 ss->sequence_used++;
2052 get_kid (&ss->master,
2055 setup_cipher (&ss->master,
2058 /* Append encrypted payload to dgram */
2059 dpos = sizeof (struct UDPBox);
2061 gcry_cipher_encrypt (out_cipher,
2069 sizeof (dgram) - dpos);
2071 gcry_cipher_gettag (out_cipher,
2073 sizeof (box->gcm_tag)));
2074 gcry_cipher_close (out_cipher);
2076 GNUNET_NETWORK_socket_sendto (udp_sock,
2080 receiver->address_len))
2081 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2083 GNUNET_MQ_impl_send_continue (mq);
2084 receiver->acks_available--;
2085 if (0 == receiver->acks_available)
2087 /* We have no more ACKs => MTU change! */
2088 setup_receiver_mq (receiver);
2098 * Signature of functions implementing the destruction of a message
2099 * queue. Implementations must not free @a mq, but should take care
2102 * @param mq the message queue to destroy
2103 * @param impl_state our `struct ReceiverAddress`
2106 mq_destroy (struct GNUNET_MQ_Handle *mq,
2109 struct ReceiverAddress *receiver = impl_state;
2111 if (mq == receiver->mq)
2113 receiver->mq = NULL;
2114 receiver_destroy (receiver);
2120 * Implementation function that cancels the currently sent message.
2122 * @param mq message queue
2123 * @param impl_state our `struct RecvierAddress`
2126 mq_cancel (struct GNUNET_MQ_Handle *mq,
2129 /* Cancellation is impossible with UDP; bail */
2135 * Generic error handler, called with the appropriate
2136 * error code and the same closure specified at the creation of
2137 * the message queue.
2138 * Not every message queue implementation supports an error handler.
2140 * @param cls our `struct ReceiverAddress`
2141 * @param error error code
2144 mq_error (void *cls,
2145 enum GNUNET_MQ_Error error)
2147 struct ReceiverAddress *receiver = cls;
2149 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2150 "MQ error in queue to %s: %d\n",
2151 GNUNET_i2s (&receiver->target),
2153 receiver_destroy (receiver);
2158 * Setup the MQ for the @a receiver. If a queue exists,
2159 * the existing one is destroyed. Then the MTU is
2160 * recalculated and a fresh queue is initialized.
2162 * @param receiver receiver to setup MQ for
2165 setup_receiver_mq (struct ReceiverAddress *receiver)
2169 if (NULL != receiver->qh)
2171 GNUNET_TRANSPORT_communicator_mq_del (receiver->qh);
2172 receiver->qh = NULL;
2174 GNUNET_assert (NULL == receiver->mq);
2175 switch (receiver->address->sa_family)
2179 = 1480 /* Ethernet MTU, 1500 - Ethernet header - VLAN tag */
2180 - sizeof (struct GNUNET_TUN_IPv4Header) /* 20 */
2181 - sizeof (struct GNUNET_TUN_UdpHeader) /* 8 */;
2185 = 1280 /* Minimum MTU required by IPv6 */
2186 - sizeof (struct GNUNET_TUN_IPv6Header) /* 40 */
2187 - sizeof (struct GNUNET_TUN_UdpHeader) /* 8 */;
2193 if (0 == receiver->acks_available)
2195 /* MTU based on full KX messages */
2198 - sizeof (struct InitialKX) /* 48 */
2199 - sizeof (struct UDPConfirmation); /* 104 */
2203 /* MTU based on BOXed messages */
2205 = base_mtu - sizeof (struct UDPBox);
2207 /* => Effective MTU for CORE will range from 1080 (IPv6 + KX) to
2208 1404 (IPv4 + Box) bytes, depending on circumstances... */
2210 = GNUNET_MQ_queue_for_callbacks (&mq_send,
2218 = GNUNET_TRANSPORT_communicator_mq_add (ch,
2220 receiver->foreign_addr,
2223 GNUNET_TRANSPORT_CS_OUTBOUND,
2229 * Setup a receiver for transmission. Setup the MQ processing and
2230 * inform transport that the queue is ready.
2234 static struct ReceiverAddress *
2235 receiver_setup (const struct GNUNET_PeerIdentity *target,
2236 const struct sockaddr *address,
2237 socklen_t address_len)
2239 struct ReceiverAddress *receiver;
2241 receiver = GNUNET_new (struct ReceiverAddress);
2242 receiver->address = GNUNET_memdup (address,
2244 receiver->address_len = address_len;
2245 receiver->target = *target;
2246 receiver->nt = GNUNET_NT_scanner_get_type (is,
2249 (void) GNUNET_CONTAINER_multipeermap_put (receivers,
2252 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2254 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2255 receiver->hn = GNUNET_CONTAINER_heap_insert (receivers_heap,
2257 receiver->timeout.abs_value_us);
2258 GNUNET_STATISTICS_set (stats,
2259 "# receivers active",
2260 GNUNET_CONTAINER_multipeermap_size (receivers),
2262 switch (address->sa_family)
2265 GNUNET_asprintf (&receiver->foreign_addr,
2267 COMMUNICATOR_ADDRESS_PREFIX,
2268 GNUNET_a2s (receiver->address,
2269 receiver->address_len));
2272 GNUNET_asprintf (&receiver->foreign_addr,
2274 COMMUNICATOR_ADDRESS_PREFIX,
2275 GNUNET_a2s (receiver->address,
2276 receiver->address_len));
2282 setup_receiver_mq (receiver);
2284 if (NULL == timeout_task)
2285 timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts,
2292 * Function called by the transport service to initialize a
2293 * message queue given address information about another peer.
2294 * If and when the communication channel is established, the
2295 * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
2296 * to notify the service that the channel is now up. It is
2297 * the responsibility of the communicator to manage sane
2298 * retries and timeouts for any @a peer/@a address combination
2299 * provided by the transport service. Timeouts and retries
2300 * do not need to be signalled to the transport service.
2302 * @param cls closure
2303 * @param peer identity of the other peer
2304 * @param address where to send the message, human-readable
2305 * communicator-specific format, 0-terminated, UTF-8
2306 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is invalid
2310 const struct GNUNET_PeerIdentity *peer,
2311 const char *address)
2313 struct ReceiverAddress *receiver;
2315 struct sockaddr *in;
2318 if (0 != strncmp (address,
2319 COMMUNICATOR_ADDRESS_PREFIX "-",
2320 strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
2322 GNUNET_break_op (0);
2323 return GNUNET_SYSERR;
2325 path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
2326 in = udp_address_to_sockaddr (path,
2328 receiver = receiver_setup (peer,
2337 * Iterator over all receivers to clean up.
2340 * @param target unused
2341 * @param value the queue to destroy
2342 * @return #GNUNET_OK to continue to iterate
2345 get_receiver_delete_it (void *cls,
2346 const struct GNUNET_PeerIdentity *target,
2349 struct ReceiverAddress *receiver = value;
2353 receiver_destroy (receiver);
2359 * Iterator over all senders to clean up.
2362 * @param target unused
2363 * @param value the queue to destroy
2364 * @return #GNUNET_OK to continue to iterate
2367 get_sender_delete_it (void *cls,
2368 const struct GNUNET_PeerIdentity *target,
2371 struct SenderAddress *sender = value;
2375 sender_destroy (sender);
2381 * Shutdown the UNIX communicator.
2383 * @param cls NULL (always)
2386 do_shutdown (void *cls)
2390 GNUNET_NAT_unregister (nat);
2393 while (NULL != bi_head)
2394 bi_destroy (bi_head);
2395 if (NULL != broadcast_task)
2397 GNUNET_SCHEDULER_cancel (broadcast_task);
2398 broadcast_task = NULL;
2400 if (NULL != read_task)
2402 GNUNET_SCHEDULER_cancel (read_task);
2405 if (NULL != udp_sock)
2407 GNUNET_break (GNUNET_OK ==
2408 GNUNET_NETWORK_socket_close (udp_sock));
2411 GNUNET_CONTAINER_multipeermap_iterate (receivers,
2412 &get_receiver_delete_it,
2414 GNUNET_CONTAINER_multipeermap_destroy (receivers);
2415 GNUNET_CONTAINER_multipeermap_iterate (senders,
2416 &get_sender_delete_it,
2418 GNUNET_CONTAINER_multipeermap_destroy (senders);
2419 GNUNET_CONTAINER_multishortmap_destroy (key_cache);
2420 GNUNET_CONTAINER_heap_destroy (senders_heap);
2421 GNUNET_CONTAINER_heap_destroy (receivers_heap);
2424 GNUNET_TRANSPORT_communicator_disconnect (ch);
2429 GNUNET_STATISTICS_destroy (stats,
2433 if (NULL != my_private_key)
2435 GNUNET_free (my_private_key);
2436 my_private_key = NULL;
2440 GNUNET_NT_scanner_done (is);
2447 * Function called when the transport service has received a
2448 * backchannel message for this communicator (!) via a different return
2449 * path. Should be an acknowledgement.
2451 * @param cls closure, NULL
2452 * @param sender which peer sent the notification
2453 * @param msg payload
2456 enc_notify_cb (void *cls,
2457 const struct GNUNET_PeerIdentity *sender,
2458 const struct GNUNET_MessageHeader *msg)
2460 const struct UDPAck *ack;
2463 if ( (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK) ||
2464 (ntohs (msg->size) != sizeof (struct UDPAck)) )
2466 GNUNET_break_op (0);
2469 ack = (const struct UDPAck *) msg;
2470 GNUNET_CONTAINER_multipeermap_get_multiple (receivers,
2478 * Signature of the callback passed to #GNUNET_NAT_register() for
2479 * a function to call whenever our set of 'valid' addresses changes.
2481 * @param cls closure
2482 * @param app_ctx[in,out] location where the app can store stuff
2483 * on add and retrieve it on remove
2484 * @param add_remove #GNUNET_YES to add a new public IP address,
2485 * #GNUNET_NO to remove a previous (now invalid) one
2486 * @param ac address class the address belongs to
2487 * @param addr either the previous or the new public IP address
2488 * @param addrlen actual length of the @a addr
2491 nat_address_cb (void *cls,
2494 enum GNUNET_NAT_AddressClass ac,
2495 const struct sockaddr *addr,
2499 struct GNUNET_TRANSPORT_AddressIdentifier *ai;
2501 if (GNUNET_YES == add_remove)
2503 enum GNUNET_NetworkType nt;
2505 GNUNET_asprintf (&my_addr,
2507 COMMUNICATOR_ADDRESS_PREFIX,
2510 nt = GNUNET_NT_scanner_get_type (is,
2513 ai = GNUNET_TRANSPORT_communicator_address_add (ch,
2516 GNUNET_TIME_UNIT_FOREVER_REL);
2517 GNUNET_free (my_addr);
2523 GNUNET_TRANSPORT_communicator_address_remove (ai);
2530 * Broadcast our presence on one of our interfaces.
2532 * @param cls a `struct BroadcastInterface`
2535 ifc_broadcast (void *cls)
2537 struct BroadcastInterface *bi = cls;
2538 struct GNUNET_TIME_Relative delay;
2540 delay = BROADCAST_FREQUENCY;
2541 delay.rel_value_us = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
2542 delay.rel_value_us);
2544 = GNUNET_SCHEDULER_add_delayed (INTERFACE_SCAN_FREQUENCY,
2548 switch (bi->sa->sa_family) {
2556 GNUNET_NETWORK_socket_setsockopt (udp_sock,
2561 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2563 sent = GNUNET_NETWORK_socket_sendto (udp_sock,
2569 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2572 GNUNET_NETWORK_socket_setsockopt (udp_sock,
2577 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2584 struct sockaddr_in6 dst;
2586 dst.sin6_family = AF_INET6;
2587 dst.sin6_port = htons (my_port);
2588 dst.sin6_addr = bi->mcreq.ipv6mr_multiaddr;
2589 dst.sin6_scope_id = ((struct sockaddr_in6*) bi->ba)->sin6_scope_id;
2591 sent = GNUNET_NETWORK_socket_sendto (udp_sock,
2594 (const struct sockaddr *)
2598 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2610 * Callback function invoked for each interface found.
2611 * Activates/deactivates broadcast interfaces.
2614 * @param name name of the interface (can be NULL for unknown)
2615 * @param isDefault is this presumably the default interface
2616 * @param addr address of this interface (can be NULL for unknown or unassigned)
2617 * @param broadcast_addr the broadcast address (can be NULL for unknown or unassigned)
2618 * @param netmask the network mask (can be NULL for unknown or unassigned)
2619 * @param addrlen length of the address
2620 * @return #GNUNET_OK to continue iteration, #GNUNET_SYSERR to abort
2623 iface_proc (void *cls,
2626 const struct sockaddr *addr,
2627 const struct sockaddr *broadcast_addr,
2628 const struct sockaddr *netmask, socklen_t addrlen)
2630 struct BroadcastInterface *bi;
2631 enum GNUNET_NetworkType network;
2632 struct UdpBroadcastSignature ubs;
2636 network = GNUNET_NT_scanner_get_type (is,
2639 if (GNUNET_NT_LOOPBACK == network)
2641 /* Broadcasting on loopback does not make sense */
2645 return GNUNET_YES; /* need to know our address! */
2646 for (bi = bi_head; NULL != bi; bi = bi->next)
2648 if ( (bi->salen == addrlen) &&
2653 bi->found = GNUNET_YES;
2658 if ( (AF_INET6 == addr->sa_family) &&
2659 (NULL == broadcast_addr) )
2660 return GNUNET_OK; /* broadcast_addr is required for IPv6! */
2661 if ( (AF_INET6 == addr->sa_family) &&
2662 (GNUNET_YES != have_v6_socket) )
2663 return GNUNET_OK; /* not using IPv6 */
2665 bi = GNUNET_new (struct BroadcastInterface);
2666 bi->sa = GNUNET_memdup (addr,
2668 if (NULL != broadcast_addr)
2669 bi->ba = GNUNET_memdup (broadcast_addr,
2671 bi->salen = addrlen;
2672 bi->found = GNUNET_YES;
2673 bi->bcm.sender = my_identity;
2674 ubs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
2675 ubs.purpose.size = htonl (sizeof (ubs));
2676 ubs.sender = my_identity;
2677 GNUNET_CRYPTO_hash (addr,
2680 GNUNET_assert (GNUNET_OK ==
2681 GNUNET_CRYPTO_eddsa_sign (my_private_key,
2683 &bi->bcm.sender_sig));
2684 bi->broadcast_task = GNUNET_SCHEDULER_add_now (&ifc_broadcast,
2686 GNUNET_CONTAINER_DLL_insert (bi_head,
2689 if ( (AF_INET6 == addr->sa_family) &&
2690 (NULL != broadcast_addr) )
2692 /* Create IPv6 multicast request */
2693 const struct sockaddr_in6 *s6
2694 = (const struct sockaddr_in6 *) broadcast_addr;
2697 inet_pton (AF_INET6,
2699 &bi->mcreq.ipv6mr_multiaddr));
2701 /* http://tools.ietf.org/html/rfc2553#section-5.2:
2705 * Join a multicast group on a specified local interface. If the
2706 * interface index is specified as 0, the kernel chooses the local
2707 * interface. For example, some kernels look up the multicast
2708 * group in the normal IPv6 routing table and using the resulting
2709 * interface; we do this for each interface, so no need to use
2710 * zero (anymore...).
2712 bi->mcreq.ipv6mr_interface = s6->sin6_scope_id;
2714 /* Join the multicast group */
2716 GNUNET_NETWORK_socket_setsockopt
2721 sizeof (bi->mcreq)))
2723 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2732 * Scan interfaces to broadcast our presence on the LAN.
2734 * @param cls NULL, unused
2737 do_broadcast (void *cls)
2739 struct BroadcastInterface *bin;
2742 for (struct BroadcastInterface *bi = bi_head;
2745 bi->found = GNUNET_NO;
2746 GNUNET_OS_network_interfaces_list (&iface_proc,
2748 for (struct BroadcastInterface *bi = bi_head;
2753 if (GNUNET_NO == bi->found)
2757 = GNUNET_SCHEDULER_add_delayed (INTERFACE_SCAN_FREQUENCY,
2764 * Setup communicator and launch network interactions.
2766 * @param cls NULL (always)
2767 * @param args remaining command-line arguments
2768 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2769 * @param c configuration
2774 const char *cfgfile,
2775 const struct GNUNET_CONFIGURATION_Handle *c)
2778 struct sockaddr *in;
2780 struct sockaddr_storage in_sto;
2786 GNUNET_CONFIGURATION_get_value_filename (cfg,
2787 COMMUNICATOR_CONFIG_SECTION,
2791 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2792 COMMUNICATOR_CONFIG_SECTION,
2797 in = udp_address_to_sockaddr (bindto,
2801 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2802 "Failed to setup UDP socket address with path `%s'\n",
2804 GNUNET_free (bindto);
2807 udp_sock = GNUNET_NETWORK_socket_create (in->sa_family,
2810 if (NULL == udp_sock)
2812 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
2815 GNUNET_free (bindto);
2818 if (AF_INET6 == in->sa_family)
2819 have_v6_socket = GNUNET_YES;
2821 GNUNET_NETWORK_socket_bind (udp_sock,
2825 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
2828 GNUNET_NETWORK_socket_close (udp_sock);
2831 GNUNET_free (bindto);
2834 /* We might have bound to port 0, allowing the OS to figure it out;
2835 thus, get the real IN-address from the socket */
2836 sto_len = sizeof (in_sto);
2837 if (0 != getsockname (GNUNET_NETWORK_get_fd (udp_sock),
2838 (struct sockaddr *) &in_sto,
2847 GNUNET_free (bindto);
2848 in = (struct sockaddr *) &in_sto;
2850 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2852 GNUNET_a2s ((const struct sockaddr *) &in_sto,
2854 switch (in->sa_family)
2857 my_port = ntohs (((struct sockaddr_in *) in)->sin_port);
2860 my_port = ntohs (((struct sockaddr_in6 *) in)->sin6_port);
2866 stats = GNUNET_STATISTICS_create ("C-UDP",
2868 senders = GNUNET_CONTAINER_multipeermap_create (32,
2870 receivers = GNUNET_CONTAINER_multipeermap_create (32,
2872 senders_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2873 receivers_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2874 key_cache = GNUNET_CONTAINER_multishortmap_create (1024,
2876 GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
2878 is = GNUNET_NT_scanner_init ();
2879 my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
2880 if (NULL == my_private_key)
2882 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2883 _("Transport service is lacking key configuration settings. Exiting.\n"));
2884 GNUNET_SCHEDULER_shutdown ();
2887 GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
2888 &my_identity.public_key);
2890 read_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2894 ch = GNUNET_TRANSPORT_communicator_connect (cfg,
2895 COMMUNICATOR_CONFIG_SECTION,
2896 COMMUNICATOR_ADDRESS_PREFIX,
2897 GNUNET_TRANSPORT_CC_UNRELIABLE,
2905 GNUNET_SCHEDULER_shutdown ();
2908 /* start broadcasting */
2910 GNUNET_CONFIGURATION_get_value_yesno (cfg,
2911 COMMUNICATOR_CONFIG_SECTION,
2912 "DISABLE_BROADCAST"))
2914 broadcast_task = GNUNET_SCHEDULER_add_now (&do_broadcast,
2917 nat = GNUNET_NAT_register (cfg,
2918 COMMUNICATOR_CONFIG_SECTION,
2920 1 /* one address */,
2921 (const struct sockaddr **) &in,
2924 NULL /* FIXME: support reversal: #5529 */,
2925 NULL /* closure */);
2930 * The main function for the UNIX communicator.
2932 * @param argc number of arguments from the command line
2933 * @param argv command line arguments
2934 * @return 0 ok, 1 on error
2940 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2941 GNUNET_GETOPT_OPTION_END
2946 GNUNET_STRINGS_get_utf8_args (argc, argv,
2952 GNUNET_PROGRAM_run (argc, argv,
2953 "gnunet-communicator-udp",
2954 _("GNUnet UDP communicator"),
2958 GNUNET_free ((void*) argv);
2963 /* end of gnunet-communicator-udp.c */