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 * - support DNS names in BINDTO option (#5528)
28 * - support NAT connection reversal method (#5529)
29 * - support other UDP-specific NAT traversal methods
32 #include "gnunet_util_lib.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_signatures.h"
35 #include "gnunet_constants.h"
36 #include "gnunet_nt_lib.h"
37 #include "gnunet_nat_service.h"
38 #include "gnunet_statistics_service.h"
39 #include "gnunet_transport_communication_service.h"
42 * How many messages do we keep at most in the queue to the
43 * transport service before we start to drop (default,
44 * can be changed via the configuration file).
45 * Should be _below_ the level of the communicator API, as
46 * otherwise we may read messages just to have them dropped
47 * by the communicator API.
49 #define DEFAULT_MAX_QUEUE_LENGTH 8
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 rekey based on number of bytes transmitted?
63 * (additionally randomized).
65 #define REKEY_MAX_BYTES (1024LLU * 1024 * 1024 * 4LLU)
68 * Address prefix used by the communicator.
70 #define COMMUNICATOR_ADDRESS_PREFIX "udp"
73 * Configuration section used by the communicator.
75 #define COMMUNICATOR_CONFIG_SECTION "communicator-udp"
77 GNUNET_NETWORK_STRUCT_BEGIN
81 * Signature we use to verify that the ephemeral key was really chosen by
82 * the specified sender. If possible, the receiver should respond with
83 * a `struct UDPAck` (possibly via backchannel).
85 struct UdpHandshakeSignature
88 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
90 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
93 * Identity of the inititor of the UDP connection (UDP client).
95 struct GNUNET_PeerIdentity sender;
98 * Presumed identity of the target of the UDP connection (UDP server)
100 struct GNUNET_PeerIdentity receiver;
103 * Ephemeral key used by the @e sender.
105 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
108 * Monotonic time of @e sender, to possibly help detect replay attacks
109 * (if receiver persists times by sender).
111 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
116 * "Plaintext" header at beginning of KX message. Followed
117 * by encrypted `struct UDPConfirmation`.
123 * Ephemeral key for KX.
125 struct GNUNET_CRYPT_EddsaPublicKey ephemeral;
128 * HMAC for the following encrypted message, using GCM. HMAC uses
129 * key derived from the handshake with sequence number zero.
131 uint8_t gcm_tag[128/8];
137 * Encrypted continuation of UDP initial handshake, followed
138 * by message header with payload.
140 struct UDPConfirmation
145 struct GNUNET_PeerIdentity sender;
148 * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
150 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
153 * Monotonic time of @e sender, to possibly help detect replay attacks
154 * (if receiver persists times by sender).
156 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
158 /* followed by messages */
160 /* padding may follow actual messages */
165 * UDP key acknowledgement. May be sent via backchannel. Allows the
166 * sender to use `struct UDPBox` with the acknowledge key henceforth.
172 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK.
174 struct GNUNET_MessageHeader header;
177 * Sequence acknowledgement limit. Specifies current maximum sequence
178 * number supported by receiver.
180 uint32_t sequence_max GNUNET_PACKED;
183 * CMAC of the base key being acknowledged.
185 struct GNUNET_HashCode cmac;
191 * UDP message box. Always sent encrypted, only allowed after
192 * the receiver sent a `struct UDPAck` for the base key!
198 * Key and IV identification code. KDF applied to an acknowledged
199 * base key and a sequence number. Sequence numbers must be used
200 * monotonically increasing up to the maximum specified in
201 * `struct UDPAck`. Without further `struct UDPAck`s, the sender
202 * must fall back to sending handshakes!
204 struct GNUNET_ShortHashCode kid;
207 * 128-bit authentication tag for the following encrypted message,
208 * from GCM. MAC starts at the @e body_start that follows and
209 * extends until the end of the UDP payload. If the @e hmac is
210 * wrong, the receiver should check if the message might be a
211 * `struct UdpHandshakeSignature`.
213 uint8_t gcm_tag[128/8];
219 GNUNET_NETWORK_STRUCT_END
222 * Shared secret we generated for a particular sender or receiver.
228 * Pre-generated "kid" code (key and IV identification code) to
229 * quickly derive master key for a `struct UDPBox`.
237 struct KeyCacheEntry *next;
242 struct KeyCacheEntry *prev;
245 * Key and IV identification code. KDF applied to an acknowledged
246 * base key and a sequence number. Sequence numbers must be used
247 * monotonically increasing up to the maximum specified in
248 * `struct UDPAck`. Without further `struct UDPAck`s, the sender
249 * must fall back to sending handshakes!
251 struct GNUNET_ShortHashCode kid;
254 * Corresponding shared secret.
256 struct SharedSecret *ss;
259 * Sequence number used to derive this entry from master key.
261 uint32_t sequence_number;
266 * Information we track per sender address we have recently been
267 * in contact with (decryption from sender).
269 struct SenderAddress;
272 * Information we track per receiving address we have recently been
273 * in contact with (encryption to receiver).
275 struct ReceiverAddress;
278 * Shared secret we generated for a particular sender or receiver.
285 struct SharedSecret *next;
290 struct SharedSecret *prev;
293 * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
295 struct KeyCacheEntry *kce_head;
298 * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
300 struct KeyCacheEntry *kce_tail;
303 * Sender we use this shared secret with, or NULL.
305 struct SenderAddress *sender;
308 * Receiver we use this shared secret with, or NULL.
310 struct ReceiverAddress *receiver;
313 * Master shared secret.
315 struct GNUNET_HashCode master;
318 * CMAC is used to identify @e master in ACKs.
320 struct GNUNET_HashCode cmac;
323 * Up to which sequence number did we use this @e master already?
324 * (for sending or receiving)
326 uint32_t sequence_used;
329 * Up to which sequence number did the other peer allow us to use
330 * this key, or up to which number did we allow the other peer to
333 uint32_t sequence_allowed;
338 * Information we track per sender address we have recently been
339 * in contact with (we decrypt messages from the sender).
345 * To whom are we talking to.
347 struct GNUNET_PeerIdentity target;
350 * Entry in sender expiration heap.
352 struct GNUNET_CONTAINER_HeapNode *hn;
355 * Shared secrets we used with @e target, first used is head.
357 struct SharedSecret *ss_head;
360 * Shared secrets we used with @e target, last used is tail.
362 struct SharedSecret *ss_tail;
365 * Address of the other peer.
367 struct sockaddr *address;
370 * Length of the address.
372 socklen_t address_len;
375 * Timeout for this sender.
377 struct GNUNET_TIME_Absolute timeout;
380 * Length of the DLL at @a ss_head.
382 unsigned int num_secrets;
385 * Which network type does this queue use?
387 enum GNUNET_NetworkType nt;
393 * Information we track per receiving address we have recently been
394 * in contact with (encryption to receiver).
396 struct ReceiverAddress
400 * To whom are we talking to.
402 struct GNUNET_PeerIdentity target;
405 * Shared secrets we received from @e target, first used is head.
407 struct SharedSecret *ss_head;
410 * Shared secrets we received with @e target, last used is tail.
412 struct SharedSecret *ss_tail;
415 * Address of the other peer.
417 struct sockaddr *address;
420 * Length of the address.
422 socklen_t address_len;
425 * Message queue we are providing for the #ch.
427 struct GNUNET_MQ_Handle *mq;
430 * handle for this queue with the #ch.
432 struct GNUNET_TRANSPORT_QueueHandle *qh;
435 * Timeout for this receiver address.
437 struct GNUNET_TIME_Absolute timeout;
440 * Length of the DLL at @a ss_head.
442 unsigned int num_secrets;
445 * Which network type does this queue use?
447 enum GNUNET_NetworkType nt;
453 * Cache of pre-generated key IDs.
455 static struct GNUNET_CONTINER_MultiShortMap *key_cache;
460 static struct GNUNET_SCHEDULER_Task *read_task;
465 static struct GNUNET_SCHEDULER_Task *timeout_task;
468 * For logging statistics.
470 static struct GNUNET_STATISTICS_Handle *stats;
475 static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
478 * Receivers (map from peer identity to `struct ReceiverAddress`)
480 static struct GNUNET_CONTAINER_MultiPeerMap *receivers;
483 * Senders (map from peer identity to `struct SenderAddress`)
485 static struct GNUNET_CONTAINER_MultiPeerMap *senders;
488 * Expiration heap for senders (contains `struct SenderAddress`)
490 static struct GNUNET_CONTAINER_Heap *senders_heap;
493 * Expiration heap for receivers (contains `struct ReceiverAddress`)
495 static struct GNUNET_CONTAINER_Heap *receivers_heap;
500 static struct GNUNET_NETWORK_Handle *udp_sock;
505 static struct GNUNET_PeerIdentity my_identity;
510 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
515 static const struct GNUNET_CONFIGURATION_Handle *cfg;
518 * Network scanner to determine network types.
520 static struct GNUNET_NT_InterfaceScanner *is;
523 * Connection to NAT service.
525 static struct GNUNET_NAT_Handle *nat;
529 * Functions with this signature are called whenever we need
530 * to close a receiving state due to timeout.
532 * @param receiver entity to close down
535 receiver_destroy (struct ReceiverAddress *receiver)
537 struct GNUNET_MQ_Handle *mq;
539 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
540 "Disconnecting receiver for peer `%s'\n",
541 GNUNET_i2s (&receiver->target));
542 if (NULL != (mq = receiver->mq))
545 GNUNET_MQ_destroy (mq);
547 GNUNET_assert (GNUNET_YES ==
548 GNUNET_CONTAINER_multipeermap_remove (receivers,
551 GNUNET_assert (sender ==
552 GNUNET_CONTAINER_heap_remove_node (receivers_heap,
554 GNUNET_STATISTICS_set (stats,
555 "# receivers active",
556 GNUNET_CONTAINER_multipeermap_size (receivers),
558 GNUNET_free (receiver->address);
559 GNUNET_free (receiver);
564 * Free memory used by key cache entry.
566 * @param kce the key cache entry
569 kce_destroy (struct KeyCacheEntry *kce)
571 struct SharedSecret *ss = kce->ss;
573 GNUNET_CONTAINER_DLL_remove (ss->kce_head,
576 GNUNET_assert (GNUNET_YES ==
577 GNUNET_CONTAINER_multishortmap_remove (key_cache,
587 * @param msec master secret for HMAC calculation
588 * @param serial number for the @a smac calculation
589 * @param kid[out] where to write the key ID
592 get_kid (const struct GNUNET_HashCode *msec,
594 struct GNUNET_ShortHashCode *kid)
596 uint32_t sid = htonl (serial);
598 GNUNET_CRYPTO_hkdf (kid,
613 * Setup key cache entry for sequence number @a seq and shared secret @a ss.
615 * @param ss shared secret
616 * @param seq sequence number for the key cache entry
619 kce_generate (struct SharedSecret *ss,
622 struct KeyCacheEntry *kce;
624 GNUNET_assert (0 < seq);
625 kce = GNUNET_new (struct KeyCacheEntry);
627 kce->sequence_number = seq;
628 get_kid (&ss->master,
631 GNUNET_CONTAINER_DLL_insert (ss->kce_head,
634 (void) GNUNET_CONTAINER_multishortmap_put (key_cache,
637 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
638 GNUNET_STATISTICS_set (stats,
640 GNUNET_CONTAINER_multipeermap_size (key_cache),
646 * Destroy @a ss and associated key cache entries.
648 * @param ss shared secret to destroy
651 secret_destroy (struct SharedSecret *ss)
653 struct SenderAddress *sender;
654 struct ReceiverAddress *receiver;
655 struct KeyCacheEntry *kce;
657 if (NULL != (sender = ss->sender))
659 GNUNET_CONTAINER_DLL_remove (sender->ss_head,
662 sender->num_secrets--;
664 if (NULL != (receiver = ss->receiver))
666 GNUNET_CONTAINER_DLL_remove (receiver->ss_head,
669 receiver->num_secrets--;
671 while (NULL != (kce = ss->kce_head))
673 GNUNET_STATISTICS_update (stats,
677 GNUNET_STATISTICS_set (stats,
679 GNUNET_CONTAINER_multipeermap_size (key_cache),
686 * Functions with this signature are called whenever we need
687 * to close a sender's state due to timeout.
689 * @param sender entity to close down
692 sender_destroy (struct SenderAddress *sender)
694 GNUNET_assert (GNUNET_YES ==
695 GNUNET_CONTAINER_multipeermap_remove (senders,
698 GNUNET_assert (sender ==
699 GNUNET_CONTAINER_heap_remove_node (senders_heap,
701 GNUNET_STATISTICS_set (stats,
703 GNUNET_CONTAINER_multipeermap_size (senders),
705 GNUNET_free (sender->address);
706 GNUNET_free (sender);
711 * Compute @a smac over @a buf.
713 * @param msec master secret for HMAC calculation
714 * @param serial number for the @a smac calculation
715 * @param buf buffer to MAC
716 * @param buf_size number of bytes in @a buf
717 * @param smac[out] where to write the HMAC
720 get_hmac (const struct GNUNET_HashCode *msec,
724 struct GNUNET_ShortHashCode *smac)
726 uint32_t sid = htonl (serial);
728 GNUNET_CRYPTO_hkdf (smac,
743 * Compute @a key and @a iv.
745 * @param msec master secret for calculation
746 * @param serial number for the @a smac calculation
747 * @param key[out] where to write the decrption key
748 * @param iv[out] where to write the IV
751 get_iv_key (const struct GNUNET_HashCode *msec,
756 uint32_t sid = htonl (serial);
757 char res[sizeof(key) + sizeof (iv)];
759 GNUNET_CRYPTO_hkdf (res,
768 strlen ("UDP-IV-KEY"),
780 * Increment sender timeout due to activity.
782 * @param sender address for which the timeout should be rescheduled
785 reschedule_sender_timeout (struct SenderAddress *sender)
788 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
789 GNUNET_CONTAINER_heap_update_cost (sender->hn,
790 sender.timeout.abs_value_us);
795 * Increment receiver timeout due to activity.
797 * @param receiver address for which the timeout should be rescheduled
800 reschedule_receiver_timeout (struct ReceiverAddress *receiver)
803 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
804 GNUNET_CONTAINER_heap_update_cost (receiver->hn,
805 receiver.timeout.abs_value_us);
810 * Calcualte cmac from master in @a ss.
812 * @param ss[in,out] data structure to complete
815 calculate_cmac (struct SharedSecret *ss)
817 GNUNET_CRYPTO_hkdf (&ss->cmac,
832 * We received @a plaintext_len bytes of @a plaintext from a @a sender.
833 * Pass it on to CORE.
835 * @param queue the queue that received the plaintext
836 * @param plaintext the plaintext that was received
837 * @param plaintext_len number of bytes of plaintext received
840 pass_plaintext_to_core (struct SenderAddress *sender,
841 const void *plaintext,
842 size_t plaintext_len)
844 const struct GNUNET_MessageHeader *hdr = plaintext;
846 while (ntohs (hdr->size) < plaintext_len)
848 GNUNET_STATISTICS_update (stats,
849 "# bytes given to core",
852 (void) GNUNET_TRANSPORT_communicator_receive (ch,
855 NULL /* no flow control possible */,
857 /* move on to next message, if any */
858 plaintext_len -= ntohs (hdr->size);
859 if (plaintext_len < sizeof (*hdr))
861 hdr = plaintext + ntohs (hdr->size);
863 GNUNET_STATISTICS_update (stats,
864 "# bytes padding discarded",
871 * Setup @a cipher based on shared secret @a msec and
872 * serial number @a serial.
874 * @param msec master shared secret
875 * @param serial serial number of cipher to set up
876 * @param cipher[out] cipher to initialize
879 setup_cipher (const struct GNUNET_HashCode *msec,
881 gcry_cipher_hd_t *cipher)
886 gcry_cipher_open (cipher,
887 GCRY_CIPHER_AES256 /* low level: go for speed */,
888 GCRY_CIPHER_MODE_GCM,
894 gcry_cipher_setkey (*cipher,
897 gcry_cipher_setiv (*cipher,
904 * Try to decrypt @a buf using shared secret @a ss and key/iv
905 * derived using @a serial.
907 * @param ss shared secret
908 * @param tag GCM authentication tag
909 * @param serial serial number to use
910 * @param in_buf input buffer to decrypt
911 * @param in_buf_size number of bytes in @a in_buf and available in @a out_buf
912 * @param out_buf where to write the result
913 * @return #GNUNET_OK on success
916 try_decrypt (const struct SharedSecret *ss,
923 gcry_cipher_hd_t cipher;
925 setup_cipher (&ss->master,
929 gcry_cipher_decrypt (cipher,
935 gcry_cipher_checktag (cipher,
939 gcry_cipher_close (cipher);
940 GNUNET_STATISTICS_update (stats,
941 "# AEAD authentication failures",
944 return GNUNET_SYSERR;
946 gcry_cipher_close (cipher);
952 * Setup shared secret for decryption.
954 * @param ephemeral ephemeral key we received from the other peer
955 * @return new shared secret
957 static struct SharedSecret *
958 setup_shared_secret_dec (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
960 struct SharedSecret *ss;
962 ss = GNUNET_new (struct SharedSecret);
963 GNUNET_CRYPTO_eddsa_ecdh (my_private_key,
971 * Setup shared secret for encryption.
973 * @param ephemeral ephemeral key we are sending to the other peer
974 * @param receiver[in,out] queue to initialize encryption key for
975 * @return new shared secret
977 static struct SharedSecret *
978 setup_shared_secret_enc (const struct GNUNET_CRYPTO_EcdhePrivateKey *ephemeral,
979 struct ReceiverAddress *receiver)
981 struct SharedSecret *ss;
983 ss = GNUNET_new (struct SharedSecret);
984 GNUNET_CRYPTO_ecdh_eddsa (ephemeral,
985 &receiver->target.public_key,
987 calculcate_cmac (ss);
988 ss->receiver = receiver;
989 GNUNET_CONTAINER_DLL_insert (receiver->ss_head,
992 receiver->num_secrets++;
993 GNUNET_STATISTICS_update (stats,
1002 * Test if we have received a valid message in plaintext.
1005 * @param sender peer to process inbound plaintext for
1006 * @param buf buffer we received
1007 * @param buf_size number of bytes in @a buf
1010 try_handle_plaintext (struct SenderAddress *sender,
1014 const struct GNUNET_MessageHeader *hdr
1015 = (const struct GNUNET_MessageHeader *) queue->pread_buf;
1016 const struct UDPAck *ack
1017 = (const struct UDPAck *) queue->pread_buf;
1020 if (sizeof (*hdr) > buf_size)
1021 return; /* not even a header */
1022 if (ntohs (hdr->size) > buf_size)
1023 return 0; /* not even a header */
1024 type = ntohs (hdr->type);
1027 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK:
1028 /* lookup master secret by 'cmac', then update sequence_max */
1029 for (struct SharedSecret *ss = sender->ss_head;
1033 if (0 == memcmp (&ack->cmac,
1037 ss->sequence_allowed = GNUNET_MAX (ss->sequence_allowed,
1038 ntohl (ack->sequence_max));
1039 /* move ss to head to avoid discarding it anytime soon! */
1040 GNUNET_CONTAINER_DLL_remove (sender->ss_head,
1043 GNUNET_CONTAINER_DLL_insert (sender->ss_head,
1049 /* There could be more messages after the ACK, handle those as well */
1050 buf += ntohs (hdr->size);
1051 buf_size -= ntohs (hdr->size);
1052 pass_plaintext_to_core (sender,
1057 pass_plaintext_to_core (sender,
1065 * We established a shared secret with a sender. We should try to send
1066 * the sender an `struct UDPAck` at the next opportunity to allow the
1067 * sender to use @a ss longer (assuming we did not yet already
1071 consider_ss_ack (struct SharedSecret *ss)
1073 GNUNET_assert (NULL != ss->sender);
1074 for (uint32_t i=1;i<0 /* FIXME: ack-based! */;i++)
1077 // FIXME: consider generating ACK and more KCEs for ss!
1082 * We received a @a box with matching @a kce. Decrypt and process it.
1084 * @param box the data we received
1085 * @param box_len number of bytes in @a box
1086 * @param kce key index to decrypt @a box
1089 decrypt_box (const struct UDPBox *box,
1091 struct KeyCacheEntry *kce)
1093 struct SharedSecret *ss = kce->ss;
1094 gcry_cipher_hd_t cipher;
1095 char out_buf[box_len - sizeof (*box)];
1097 GNUNET_assert (NULL != ss->sender);
1101 kce->sequence_number,
1102 box_len - sizeof (*box),
1106 GNUNET_STATISTICS_update (stats,
1107 "# Decryption failures with valid KCE",
1114 GNUNET_STATISTICS_update (stats,
1115 "# bytes decrypted with BOX",
1118 try_handle_plaintext (ss->sender,
1121 consider_ss_ack (ss);
1126 * Closure for #find_sender_by_address()
1128 struct SearchContext
1131 * Address we are looking for.
1133 const struct sockaddr *address;
1136 * Number of bytes in @e address.
1138 socklen_t address_len;
1141 * Return value to set if we found a match.
1143 struct SenderAddress *sender;
1148 * Find existing `struct SenderAddress` by matching addresses.
1150 * @param cls a `struct SearchContext`
1151 * @param key ignored, must match already
1152 * @param value a `struct SenderAddress`
1153 * @return #GNUNET_YES if not found (continue to search), #GNUNET_NO if found
1156 find_sender_by_address (void *cls,
1157 const struct GNUNET_PeerIdentity *key,
1160 struct SearchContext *sc = cls;
1161 struct SenderAddress *sender = value;
1163 if ( (sender->address_len == sc->address_len) &&
1164 (0 == memcmp (sender->address,
1166 sender->address_len)) )
1168 sc->sender = sender;
1169 return GNUNET_NO; /* stop iterating! */
1176 * Create sender address for @a target. Note that we
1177 * might already have one, so a fresh one is only allocated
1178 * if one does not yet exist for @a address.
1180 * @param target peer to generate address for
1181 * @param address target address
1182 * @param address_len number of bytes in @a address
1183 * @return data structure to keep track of key material for
1184 * decrypting data from @a target
1186 static struct SenderAddress *
1187 setup_sender (const struct GNUNET_PeerIdentity *target,
1188 const struct sockaddr *address,
1189 socklen_t address_len)
1191 struct SenderAddress *sender;
1192 struct SearchContext sc = {
1194 .address_len = address_len,
1198 GNUNET_CONTAINER_multihashmap_get_multiple (senders,
1200 &find_sender_by_address,
1202 if (NULL != sc.sender)
1204 sender = GNUNET_new (struct SenderAddress);
1205 sender->target = *target;
1206 sender->address = GNUNET_memdup (address,
1208 sender->address_len = address_len;
1209 (void) GNUNET_CONTAINER_multihashmap_put (senders,
1212 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1213 GNUNET_STATISTICS_set (stats,
1215 GNUNET_CONTAINER_multipeermap_size (receivers),
1218 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1219 sender->hn = GNUNET_CONTAINER_heap_insert (senders_heap,
1221 sender.timeout.abs_value_us);
1222 sender->nt = GNUNET_NT_scanner_get_type (is,
1235 sock_read (void *cls)
1237 struct sockaddr_storage sa;
1238 socklen_t salen = sizeof (sa);
1239 char buf[UINT16_MAX];
1244 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1248 rcvd = GNUNET_NETWORK_socket_recvfrom (udp_sock,
1251 (struct sockaddr *) &sa,
1255 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1259 /* first, see if it is a UDPBox */
1260 if (rcvd > sizeof (struct UDPBox))
1262 const struct UDPBox *box;
1263 struct KeyCacheEntry *kce;
1265 box = (const struct UDPBox *) buf;
1266 kce = GNUNET_CONTAINER_multihashmap_get (key_cache,
1276 /* next, test if it is a KX */
1277 if (rcvd < sizeof (struct UDPConfirmation) + sizeof (struct InitialKX))
1279 GNUNET_STATISTICS_update (stats,
1280 "# messages dropped (no kid, too small for KX)",
1287 const struct InitialKX *kx;
1288 struct SharedSecret *ss;
1289 char pbuf[rcvd - sizeof (struct InitialKX)];
1290 const struct UDPConfirmation *uc;
1291 struct SenderAddress *sender;
1293 kx = (const struct InitialKX *) buf;
1294 ss = setup_shared_secret_dec (&kx->ephemral);
1300 (const struct GNUNET_CRYPTO_EcdhePublicKey *) buf,
1304 GNUNET_STATISTICS_update (stats,
1305 "# messages dropped (no kid, AEAD decryption failed)",
1310 uc = (const struct UDPConfirmation *) pbuf;
1312 verify_confirmation (&kx->ephemeral,
1315 GNUNET_break_op (0);
1317 GNUNET_STATISTICS_update (stats,
1318 "# messages dropped (sender signature invalid)",
1323 calculcate_cmac (ss);
1324 sender = setup_sender (&uc->sender,
1325 (const struct sockaddr *) &sa,
1327 ss->sender = sender;
1328 GNUNET_CONTAINER_DLL_insert (sender->ss_head,
1331 sender->num_secrets++;
1332 GNUNET_STATISTICS_update (stats,
1336 GNUNET_STATISTICS_update (stats,
1337 "# bytes decrypted without BOX",
1338 sizeof (pbuf) - sizeof (*uc),
1340 try_handle_plaintext (sender,
1342 sizeof (pbuf) - sizeof (*uc));
1343 consider_ss_ack (ss);
1344 if (sender->num_secrets > MAX_SECRETS)
1345 secret_destroy (sender->ss_tail);
1351 * Convert UDP bind specification to a `struct sockaddr *`
1353 * @param bindto bind specification to convert
1354 * @param[out] sock_len set to the length of the address
1355 * @return converted bindto specification
1357 static struct sockaddr *
1358 udp_address_to_sockaddr (const char *bindto,
1359 socklen_t *sock_len)
1361 struct sockaddr *in;
1367 if (1 == SSCANF (bindto,
1372 /* interpreting value as just a PORT number */
1373 if (port > UINT16_MAX)
1375 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1376 "BINDTO specification `%s' invalid: value too large for port\n",
1381 GNUNET_CONFIGURATION_get_value_yesno (cfg,
1382 COMMUNICATOR_CONFIG_SECTION,
1385 struct sockaddr_in *i4;
1387 i4 = GNUNET_malloc (sizeof (struct sockaddr_in));
1388 i4->sin_family = AF_INET;
1389 i4->sin_port = htons ((uint16_t) port);
1390 *sock_len = sizeof (struct sockaddr_in);
1391 in = (struct sockaddr *) i4;
1395 struct sockaddr_in6 *i6;
1397 i6 = GNUNET_malloc (sizeof (struct sockaddr_in6));
1398 i6->sin6_family = AF_INET6;
1399 i6->sin6_port = htons ((uint16_t) port);
1400 *sock_len = sizeof (struct sockaddr_in6);
1401 in = (struct sockaddr *) i6;
1405 cp = GNUNET_strdup (bindto);
1406 colon = strrchr (cp, ':');
1409 /* interpet value after colon as port */
1412 if (1 == SSCANF (colon,
1417 /* interpreting value as just a PORT number */
1418 if (port > UINT16_MAX)
1420 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1421 "BINDTO specification `%s' invalid: value too large for port\n",
1429 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1430 "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1438 /* interpret missing port as 0, aka pick any free one */
1443 struct sockaddr_in v4;
1445 if (1 == inet_pton (AF_INET,
1449 v4.sin_port = htons ((uint16_t) port);
1450 in = GNUNET_memdup (&v4,
1452 *sock_len = sizeof (v4);
1459 struct sockaddr_in6 v6;
1463 if ( ('[' == *cp) &&
1464 (']' == cp[strlen (cp)-1]) )
1466 start++; /* skip over '[' */
1467 cp[strlen (cp) -1] = '\0'; /* eat ']' */
1469 if (1 == inet_pton (AF_INET6,
1473 v6.sin6_port = htons ((uint16_t) port);
1474 in = GNUNET_memdup (&v6,
1476 *sock_len = sizeof (v6);
1481 /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1493 XXX_write (void *cls)
1497 sent = GNUNET_NETWORK_socket_sendto (udp_sock,
1501 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1510 * Signature of functions implementing the sending functionality of a
1513 * @param mq the message queue
1514 * @param msg the message to send
1515 * @param impl_state our `struct ReceiverAddress`
1518 mq_send (struct GNUNET_MQ_Handle *mq,
1519 const struct GNUNET_MessageHeader *msg,
1522 struct ReceiverAddress *receiver = impl_state;
1523 uint16_t msize = ntohs (msg->size);
1525 GNUNET_assert (mq == receiver->mq);
1526 // FIXME: pick encryption method, encrypt and transmit and call MQ-send-contiue!!
1529 /* compute 'tc' and append in encrypted format to cwrite_buf */
1530 tc.sender = my_identity;
1531 tc.monotonic_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1532 ths.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
1533 ths.purpose.size = htonl (sizeof (ths));
1534 ths.sender = my_identity;
1535 ths.receiver = queue->target;
1536 ths.ephemeral = *epub;
1537 ths.monotonic_time = tc.monotonic_time;
1538 GNUNET_assert (GNUNET_OK ==
1539 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1543 gcry_cipher_encrypt (queue->out_cipher,
1544 &queue->cwrite_buf[queue->cwrite_off],
1555 * Signature of functions implementing the destruction of a message
1556 * queue. Implementations must not free @a mq, but should take care
1559 * @param mq the message queue to destroy
1560 * @param impl_state our `struct ReceiverAddress`
1563 mq_destroy (struct GNUNET_MQ_Handle *mq,
1566 struct ReceiverAddress *receiver = impl_state;
1568 if (mq == receiver->mq)
1570 receiver->mq = NULL;
1571 receiver_destroy (receiver);
1577 * Implementation function that cancels the currently sent message.
1579 * @param mq message queue
1580 * @param impl_state our `struct RecvierAddress`
1583 mq_cancel (struct GNUNET_MQ_Handle *mq,
1586 /* Cancellation is impossible with UDP; bail */
1592 * Generic error handler, called with the appropriate
1593 * error code and the same closure specified at the creation of
1594 * the message queue.
1595 * Not every message queue implementation supports an error handler.
1597 * @param cls our `struct ReceiverAddress`
1598 * @param error error code
1601 mq_error (void *cls,
1602 enum GNUNET_MQ_Error error)
1604 struct ReceiverAddress *receiver = cls;
1606 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1607 "MQ error in queue to %s: %d\n",
1608 GNUNET_i2s (&receiver->target),
1610 receiver_destroy (receiver);
1615 * Setup a receiver for transmission. Setup the MQ processing and
1616 * inform transport that the queue is ready.
1620 static struct ReceiverAddress *
1621 receiver_setup (const struct GNUNET_PeerIdentity *target,
1622 const struct sockddr *address,
1623 socklen_t address_len)
1625 struct ReceiverAddress *receiver;
1627 receiver = GNUNET_new (struct ReceiverAddress);
1628 receiver->address = GNUNET_memdup (address,
1630 receiver->address_len = address_len;
1631 receiver->target = *target;
1632 receiver->nt = GNUNET_NT_scanner_get_type (is,
1635 (void) GNUNET_CONTAINER_multipeermap_put (receivers,
1638 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1640 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1641 receiver->hn = GNUNET_CONTAINER_heap_insert (receivers_heap,
1643 receiver.timeout.abs_value_us);
1645 = GNUNET_MQ_queue_for_callbacks (&mq_send,
1652 GNUNET_STATISTICS_set (stats,
1653 "# receivers active",
1654 GNUNET_CONTAINER_multipeermap_size (receivers),
1659 switch (address->sa_family)
1662 GNUNET_asprintf (&foreign_addr,
1664 COMMUNICATOR_ADDRESS_PREFIX,
1665 GNUNET_a2s(queue->address,
1666 queue->address_len));
1669 GNUNET_asprintf (&foreign_addr,
1671 COMMUNICATOR_ADDRESS_PREFIX,
1672 GNUNET_a2s(queue->address,
1673 queue->address_len));
1679 = GNUNET_TRANSPORT_communicator_mq_add (ch,
1682 1200 /* FIXME: MTU OK? */,
1684 GNUNET_TRANSPORT_CS_OUTBOUND,
1686 GNUNET_free (foreign_addr);
1692 * Function called by the transport service to initialize a
1693 * message queue given address information about another peer.
1694 * If and when the communication channel is established, the
1695 * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
1696 * to notify the service that the channel is now up. It is
1697 * the responsibility of the communicator to manage sane
1698 * retries and timeouts for any @a peer/@a address combination
1699 * provided by the transport service. Timeouts and retries
1700 * do not need to be signalled to the transport service.
1702 * @param cls closure
1703 * @param peer identity of the other peer
1704 * @param address where to send the message, human-readable
1705 * communicator-specific format, 0-terminated, UTF-8
1706 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is invalid
1710 const struct GNUNET_PeerIdentity *peer,
1711 const char *address)
1713 struct ReceiverAddress *receiver;
1715 struct sockaddr *in;
1718 if (0 != strncmp (address,
1719 COMMUNICATOR_ADDRESS_PREFIX "-",
1720 strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
1722 GNUNET_break_op (0);
1723 return GNUNET_SYSERR;
1725 path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
1726 in = udp_address_to_sockaddr (path,
1728 receiver = receiver_setup (peer,
1736 * Iterator over all receivers to clean up.
1739 * @param target unused
1740 * @param value the queue to destroy
1741 * @return #GNUNET_OK to continue to iterate
1744 get_receiver_delete_it (void *cls,
1745 const struct GNUNET_PeerIdentity *target,
1748 struct ReceiverAddress *receiver = value;
1752 receiver_destroy (receiver);
1758 * Iterator over all senders to clean up.
1761 * @param target unused
1762 * @param value the queue to destroy
1763 * @return #GNUNET_OK to continue to iterate
1766 get_receiver_delete_it (void *cls,
1767 const struct GNUNET_PeerIdentity *target,
1770 struct SenderAddress *sender = value;
1774 sender_destroy (sender);
1780 * Shutdown the UNIX communicator.
1782 * @param cls NULL (always)
1785 do_shutdown (void *cls)
1789 GNUNET_NAT_unregister (nat);
1792 if (NULL != read_task)
1794 GNUNET_SCHEDULER_cancel (read_task);
1797 if (NULL != udp_sock)
1799 GNUNET_break (GNUNET_OK ==
1800 GNUNET_NETWORK_socket_close (udp_sock));
1803 GNUNET_CONTAINER_multipeermap_iterate (receivers,
1804 &get_receiver_delete_it,
1806 GNUNET_CONTAINER_multipeermap_destroy (receivers);
1807 GNUNET_CONTAINER_multipeermap_iterate (senders,
1808 &get_sender_delete_it,
1810 GNUNET_CONTAINER_multipeermap_destroy (senders);
1811 GNUNET_CONTAINER_multishortmap_destroy (key_cache);
1812 GNUNET_CONTAINER_heap_destroy (senders_heap);
1813 GNUNET_CONTAINER_heap_destroy (receivers_heap);
1816 GNUNET_TRANSPORT_communicator_disconnect (ch);
1821 GNUNET_STATISTICS_destroy (stats,
1825 if (NULL != my_private_key)
1827 GNUNET_free (my_private_key);
1828 my_private_key = NULL;
1832 GNUNET_NT_scanner_done (is);
1839 * Function called when the transport service has received an
1840 * acknowledgement for this communicator (!) via a different return
1843 * Not applicable for UDP.
1845 * @param cls closure
1846 * @param sender which peer sent the notification
1847 * @param msg payload
1850 enc_notify_cb (void *cls,
1851 const struct GNUNET_PeerIdentity *sender,
1852 const struct GNUNET_MessageHeader *msg)
1857 GNUNET_break_op (0);
1862 * Signature of the callback passed to #GNUNET_NAT_register() for
1863 * a function to call whenever our set of 'valid' addresses changes.
1865 * @param cls closure
1866 * @param app_ctx[in,out] location where the app can store stuff
1867 * on add and retrieve it on remove
1868 * @param add_remove #GNUNET_YES to add a new public IP address,
1869 * #GNUNET_NO to remove a previous (now invalid) one
1870 * @param ac address class the address belongs to
1871 * @param addr either the previous or the new public IP address
1872 * @param addrlen actual length of the @a addr
1875 nat_address_cb (void *cls,
1878 enum GNUNET_NAT_AddressClass ac,
1879 const struct sockaddr *addr,
1883 struct GNUNET_TRANSPORT_AddressIdentifier *ai;
1885 if (GNUNET_YES == add_remove)
1887 enum GNUNET_NetworkType nt;
1889 GNUNET_asprintf (&my_addr,
1891 COMMUNICATOR_ADDRESS_PREFIX,
1894 nt = GNUNET_NT_scanner_get_type (is,
1897 ai = GNUNET_TRANSPORT_communicator_address_add (ch,
1900 GNUNET_TIME_UNIT_FOREVER_REL);
1901 GNUNET_free (my_addr);
1907 GNUNET_TRANSPORT_communicator_address_remove (ai);
1914 * Setup communicator and launch network interactions.
1916 * @param cls NULL (always)
1917 * @param args remaining command-line arguments
1918 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1919 * @param c configuration
1924 const char *cfgfile,
1925 const struct GNUNET_CONFIGURATION_Handle *c)
1928 struct sockaddr *in;
1930 struct sockaddr_storage in_sto;
1936 GNUNET_CONFIGURATION_get_value_filename (cfg,
1937 COMMUNICATOR_CONFIG_SECTION,
1941 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
1942 COMMUNICATOR_CONFIG_SECTION,
1947 GNUNET_CONFIGURATION_get_value_number (cfg,
1948 COMMUNICATOR_CONFIG_SECTION,
1951 max_queue_length = DEFAULT_MAX_QUEUE_LENGTH;
1953 in = udp_address_to_sockaddr (bindto,
1957 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1958 "Failed to setup UDP socket address with path `%s'\n",
1960 GNUNET_free (bindto);
1963 udp_sock = GNUNET_NETWORK_socket_create (in->sa_family,
1966 if (NULL == udp_sock)
1968 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
1971 GNUNET_free (bindto);
1975 GNUNET_NETWORK_socket_bind (udp_sock,
1979 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1982 GNUNET_NETWORK_socket_close (udp_sock);
1985 GNUNET_free (bindto);
1988 /* We might have bound to port 0, allowing the OS to figure it out;
1989 thus, get the real IN-address from the socket */
1990 sto_len = sizeof (in_sto);
1991 if (0 != getsockname (GNUNET_NETWORK_get_fd (udp_sock),
1992 (struct sockaddr *) &in_sto,
2001 GNUNET_free (bindto);
2002 in = (struct sockaddr *) &in_sto;
2004 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2006 GNUNET_a2s ((const struct sockaddr *) &in_sto,
2008 stats = GNUNET_STATISTICS_create ("C-UDP",
2010 senders = GNUNET_CONTAINER_multipeermap_create (32,
2012 receivers = GNUNET_CONTAINER_multipeermap_create (32,
2014 senders_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2015 receivers_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2016 key_cache = GNUNET_CONTAINER_multishortmap_create (1024,
2018 GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
2020 is = GNUNET_NT_scanner_init ();
2021 my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
2022 if (NULL == my_private_key)
2024 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2025 _("Transport service is lacking key configuration settings. Exiting.\n"));
2026 GNUNET_SCHEDULER_shutdown ();
2029 GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
2030 &my_identity.public_key);
2031 /* start listening */
2032 read_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2036 ch = GNUNET_TRANSPORT_communicator_connect (cfg,
2037 COMMUNICATOR_CONFIG_SECTION,
2038 COMMUNICATOR_ADDRESS_PREFIX,
2039 GNUNET_TRANSPORT_CC_UNRELIABLE,
2047 GNUNET_SCHEDULER_shutdown ();
2050 nat = GNUNET_NAT_register (cfg,
2051 COMMUNICATOR_CONFIG_SECTION,
2053 1 /* one address */,
2054 (const struct sockaddr **) &in,
2057 NULL /* FIXME: support reversal: #5529 */,
2058 NULL /* closure */);
2063 * The main function for the UNIX communicator.
2065 * @param argc number of arguments from the command line
2066 * @param argv command line arguments
2067 * @return 0 ok, 1 on error
2073 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2074 GNUNET_GETOPT_OPTION_END
2079 GNUNET_STRINGS_get_utf8_args (argc, argv,
2085 GNUNET_PROGRAM_run (argc, argv,
2086 "gnunet-communicator-udp",
2087 _("GNUnet UDP communicator"),
2091 GNUNET_free ((void*) argv);
2096 /* end of gnunet-communicator-udp.c */