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 // FIXME: remove from receiver_heap
552 GNUNET_STATISTICS_set (stats,
553 "# receivers active",
554 GNUNET_CONTAINER_multipeermap_size (receivers),
556 GNUNET_free (receiver->address);
557 GNUNET_free (receiver);
562 * Free memory used by key cache entry.
564 * @param kce the key cache entry
567 kce_destroy (struct KeyCacheEntry *kce)
569 struct SharedSecret *ss = kce->ss;
571 GNUNET_CONTAINER_DLL_remove (ss->kce_head,
574 GNUNET_assert (GNUNET_YES ==
575 GNUNET_CONTAINER_multishortmap_remove (key_cache,
585 * @param msec master secret for HMAC calculation
586 * @param serial number for the @a smac calculation
587 * @param kid[out] where to write the key ID
590 get_kid (const struct GNUNET_HashCode *msec,
592 struct GNUNET_ShortHashCode *kid)
594 uint32_t sid = htonl (serial);
596 GNUNET_CRYPTO_hkdf (kid,
611 * Setup key cache entry for sequence number @a seq and shared secret @a ss.
613 * @param ss shared secret
614 * @param seq sequence number for the key cache entry
617 kce_generate (struct SharedSecret *ss,
620 struct KeyCacheEntry *kce;
622 GNUNET_assert (0 < seq);
623 kce = GNUNET_new (struct KeyCacheEntry);
625 kce->sequence_number = seq;
626 get_kid (&ss->master,
629 GNUNET_CONTAINER_DLL_insert (ss->kce_head,
632 (void) GNUNET_CONTAINER_multishortmap_put (key_cache,
635 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
636 GNUNET_STATISTICS_set (stats,
638 GNUNET_CONTAINER_multipeermap_size (key_cache),
644 * Destroy @a ss and associated key cache entries.
646 * @param ss shared secret to destroy
649 secret_destroy (struct SharedSecret *ss)
651 struct SenderAddress *sender;
652 struct ReceiverAddress *receiver;
653 struct KeyCacheEntry *kce;
655 if (NULL != (sender = ss->sender))
657 GNUNET_CONTAINER_DLL_remove (sender->ss_head,
660 sender->num_secrets--;
662 if (NULL != (receiver = ss->receiver))
664 GNUNET_CONTAINER_DLL_remove (receiver->ss_head,
667 receiver->num_secrets--;
669 while (NULL != (kce = ss->kce_head))
671 GNUNET_STATISTICS_update (stats,
675 GNUNET_STATISTICS_set (stats,
677 GNUNET_CONTAINER_multipeermap_size (key_cache),
684 * Functions with this signature are called whenever we need
685 * to close a sender's state due to timeout.
687 * @param sender entity to close down
690 sender_destroy (struct SenderAddress *sender)
692 GNUNET_assert (GNUNET_YES ==
693 GNUNET_CONTAINER_multipeermap_remove (senders,
696 // FIXME: remove from sender_heap
697 GNUNET_STATISTICS_set (stats,
699 GNUNET_CONTAINER_multipeermap_size (senders),
701 GNUNET_free (sender->address);
702 GNUNET_free (sender);
707 * Compute @a smac over @a buf.
709 * @param msec master secret for HMAC calculation
710 * @param serial number for the @a smac calculation
711 * @param buf buffer to MAC
712 * @param buf_size number of bytes in @a buf
713 * @param smac[out] where to write the HMAC
716 get_hmac (const struct GNUNET_HashCode *msec,
720 struct GNUNET_ShortHashCode *smac)
722 uint32_t sid = htonl (serial);
724 GNUNET_CRYPTO_hkdf (smac,
739 * Compute @a key and @a iv.
741 * @param msec master secret for calculation
742 * @param serial number for the @a smac calculation
743 * @param key[out] where to write the decrption key
744 * @param iv[out] where to write the IV
747 get_iv_key (const struct GNUNET_HashCode *msec,
752 uint32_t sid = htonl (serial);
753 char res[sizeof(key) + sizeof (iv)];
755 GNUNET_CRYPTO_hkdf (res,
764 strlen ("UDP-IV-KEY"),
776 * Increment sender timeout due to activity.
778 * @param sender address for which the timeout should be rescheduled
781 reschedule_sender_timeout (struct SenderAddress *sender)
784 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
785 // FIXME: update heap!
790 * Increment receiver timeout due to activity.
792 * @param receiver address for which the timeout should be rescheduled
795 reschedule_receiver_timeout (struct ReceiverAddress *receiver)
798 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
799 // FIXME: update heap!
804 * Calcualte cmac from master in @a ss.
806 * @param ss[in,out] data structure to complete
809 calculate_cmac (struct SharedSecret *ss)
811 GNUNET_CRYPTO_hkdf (&ss->cmac,
826 * We received @a plaintext_len bytes of @a plaintext from a @a sender.
827 * Pass it on to CORE.
829 * @param queue the queue that received the plaintext
830 * @param plaintext the plaintext that was received
831 * @param plaintext_len number of bytes of plaintext received
834 pass_plaintext_to_core (struct SenderAddress *sender,
835 const void *plaintext,
836 size_t plaintext_len)
838 const struct GNUNET_MessageHeader *hdr = plaintext;
840 while (ntohs (hdr->size) < plaintext_len)
842 GNUNET_STATISTICS_update (stats,
843 "# bytes given to core",
846 (void) GNUNET_TRANSPORT_communicator_receive (ch,
849 NULL /* no flow control possible */,
851 /* move on to next message, if any */
852 plaintext_len -= ntohs (hdr->size);
853 if (plaintext_len < sizeof (*hdr))
855 hdr = plaintext + ntohs (hdr->size);
857 GNUNET_STATISTICS_update (stats,
858 "# bytes padding discarded",
865 * Setup @a cipher based on shared secret @a msec and
866 * serial number @a serial.
868 * @param msec master shared secret
869 * @param serial serial number of cipher to set up
870 * @param cipher[out] cipher to initialize
873 setup_cipher (const struct GNUNET_HashCode *msec,
875 gcry_cipher_hd_t *cipher)
880 gcry_cipher_open (cipher,
881 GCRY_CIPHER_AES256 /* low level: go for speed */,
882 GCRY_CIPHER_MODE_GCM,
888 gcry_cipher_setkey (*cipher,
891 gcry_cipher_setiv (*cipher,
898 * Try to decrypt @a buf using shared secret @a ss and key/iv
899 * derived using @a serial.
901 * @param ss shared secret
902 * @param tag GCM authentication tag
903 * @param serial serial number to use
904 * @param in_buf input buffer to decrypt
905 * @param in_buf_size number of bytes in @a in_buf and available in @a out_buf
906 * @param out_buf where to write the result
907 * @return #GNUNET_OK on success
910 try_decrypt (const struct SharedSecret *ss,
917 gcry_cipher_hd_t cipher;
919 setup_cipher (&ss->master,
923 gcry_cipher_decrypt (cipher,
929 gcry_cipher_checktag (cipher,
933 gcry_cipher_close (cipher);
934 GNUNET_STATISTICS_update (stats,
935 "# AEAD authentication failures",
938 return GNUNET_SYSERR;
940 gcry_cipher_close (cipher);
946 * Setup shared secret for decryption.
948 * @param ephemeral ephemeral key we received from the other peer
949 * @return new shared secret
951 static struct SharedSecret *
952 setup_shared_secret_dec (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
954 struct SharedSecret *ss;
956 ss = GNUNET_new (struct SharedSecret);
957 GNUNET_CRYPTO_eddsa_ecdh (my_private_key,
965 * Setup shared secret for encryption.
967 * @param ephemeral ephemeral key we are sending to the other peer
968 * @param receiver[in,out] queue to initialize encryption key for
969 * @return new shared secret
971 static struct SharedSecret *
972 setup_shared_secret_enc (const struct GNUNET_CRYPTO_EcdhePrivateKey *ephemeral,
973 struct ReceiverAddress *receiver)
975 struct SharedSecret *ss;
977 ss = GNUNET_new (struct SharedSecret);
978 GNUNET_CRYPTO_ecdh_eddsa (ephemeral,
979 &receiver->target.public_key,
981 calculcate_cmac (ss);
982 ss->receiver = receiver;
983 GNUNET_CONTAINER_DLL_insert (receiver->ss_head,
986 receiver->num_secrets++;
987 GNUNET_STATISTICS_update (stats,
996 * Test if we have received a valid message in plaintext.
999 * @param sender peer to process inbound plaintext for
1000 * @param buf buffer we received
1001 * @param buf_size number of bytes in @a buf
1004 try_handle_plaintext (struct SenderAddress *sender,
1008 const struct GNUNET_MessageHeader *hdr
1009 = (const struct GNUNET_MessageHeader *) queue->pread_buf;
1010 const struct UDPAck *ack
1011 = (const struct UDPAck *) queue->pread_buf;
1014 if (sizeof (*hdr) > buf_size)
1015 return; /* not even a header */
1016 if (ntohs (hdr->size) > buf_size)
1017 return 0; /* not even a header */
1018 type = ntohs (hdr->type);
1021 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK:
1022 /* lookup master secret by 'cmac', then update sequence_max */
1023 for (struct SharedSecret *ss = sender->ss_head;
1027 if (0 == memcmp (&ack->cmac,
1031 ss->sequence_allowed = GNUNET_MAX (ss->sequence_allowed,
1032 ntohl (ack->sequence_max));
1033 /* move ss to head to avoid discarding it anytime soon! */
1034 GNUNET_CONTAINER_DLL_remove (sender->ss_head,
1037 GNUNET_CONTAINER_DLL_insert (sender->ss_head,
1043 /* There could be more messages after the ACK, handle those as well */
1044 buf += ntohs (hdr->size);
1045 buf_size -= ntohs (hdr->size);
1046 pass_plaintext_to_core (sender,
1051 pass_plaintext_to_core (sender,
1059 * We established a shared secret with a sender. We should try to send
1060 * the sender an `struct UDPAck` at the next opportunity to allow the
1061 * sender to use @a ss longer (assuming we did not yet already
1065 consider_ss_ack (struct SharedSecret *ss)
1067 GNUNET_assert (NULL != ss->sender);
1068 for (uint32_t i=1;i<0 /* FIXME: ack-based! */;i++)
1071 // FIXME: consider generating ACK and more KCEs for ss!
1076 * We received a @a box with matching @a kce. Decrypt and process it.
1078 * @param box the data we received
1079 * @param box_len number of bytes in @a box
1080 * @param kce key index to decrypt @a box
1083 decrypt_box (const struct UDPBox *box,
1085 struct KeyCacheEntry *kce)
1087 struct SharedSecret *ss = kce->ss;
1088 gcry_cipher_hd_t cipher;
1089 char out_buf[box_len - sizeof (*box)];
1091 GNUNET_assert (NULL != ss->sender);
1095 kce->sequence_number,
1096 box_len - sizeof (*box),
1100 GNUNET_STATISTICS_update (stats,
1101 "# Decryption failures with valid KCE",
1108 GNUNET_STATISTICS_update (stats,
1109 "# bytes decrypted with BOX",
1112 try_handle_plaintext (ss->sender,
1115 consider_ss_ack (ss);
1125 sock_read (void *cls)
1127 struct sockaddr_storage sa;
1128 socklen_t salen = sizeof (sa);
1129 char buf[UINT16_MAX];
1134 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1138 rcvd = GNUNET_NETWORK_socket_recvfrom (udp_sock,
1141 (struct sockaddr *) &sa,
1145 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1149 /* first, see if it is a UDPBox */
1150 if (rcvd > sizeof (struct UDPBox))
1152 const struct UDPBox *box;
1153 struct KeyCacheEntry *kce;
1155 box = (const struct UDPBox *) buf;
1156 kce = GNUNET_CONTAINER_multihashmap_get (key_cache,
1166 /* next, test if it is a KX */
1167 if (rcvd < sizeof (struct UDPConfirmation) + sizeof (struct InitialKX))
1169 GNUNET_STATISTICS_update (stats,
1170 "# messages dropped (no kid, too small for KX)",
1177 const struct InitialKX *kx;
1178 struct SharedSecret *ss;
1179 char pbuf[rcvd - sizeof (struct InitialKX)];
1180 const struct UDPConfirmation *uc;
1181 struct SenderAddress *sender;
1183 kx = (const struct InitialKX *) buf;
1184 ss = setup_shared_secret_dec (&kx->ephemral);
1190 (const struct GNUNET_CRYPTO_EcdhePublicKey *) buf,
1194 GNUNET_STATISTICS_update (stats,
1195 "# messages dropped (no kid, AEAD decryption failed)",
1200 uc = (const struct UDPConfirmation *) pbuf;
1202 verify_confirmation (&kx->ephemeral,
1205 GNUNET_break_op (0);
1207 GNUNET_STATISTICS_update (stats,
1208 "# messages dropped (sender signature invalid)",
1213 calculcate_cmac (ss);
1214 sender = setup_sender (&uc->sender,
1215 (const struct sockaddr *) &sa,
1217 ss->sender = sender;
1218 GNUNET_CONTAINER_DLL_insert (sender->ss_head,
1221 sender->num_secrets++;
1222 GNUNET_STATISTICS_update (stats,
1226 GNUNET_STATISTICS_update (stats,
1227 "# bytes decrypted without BOX",
1228 sizeof (pbuf) - sizeof (*uc),
1230 try_handle_plaintext (sender,
1232 sizeof (pbuf) - sizeof (*uc));
1233 consider_ss_ack (ss);
1234 if (sender->num_secrets > MAX_SECRETS)
1235 secret_destroy (sender->ss_tail);
1241 * Convert UDP bind specification to a `struct sockaddr *`
1243 * @param bindto bind specification to convert
1244 * @param[out] sock_len set to the length of the address
1245 * @return converted bindto specification
1247 static struct sockaddr *
1248 udp_address_to_sockaddr (const char *bindto,
1249 socklen_t *sock_len)
1251 struct sockaddr *in;
1257 if (1 == SSCANF (bindto,
1262 /* interpreting value as just a PORT number */
1263 if (port > UINT16_MAX)
1265 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1266 "BINDTO specification `%s' invalid: value too large for port\n",
1271 GNUNET_CONFIGURATION_get_value_yesno (cfg,
1272 COMMUNICATOR_CONFIG_SECTION,
1275 struct sockaddr_in *i4;
1277 i4 = GNUNET_malloc (sizeof (struct sockaddr_in));
1278 i4->sin_family = AF_INET;
1279 i4->sin_port = htons ((uint16_t) port);
1280 *sock_len = sizeof (struct sockaddr_in);
1281 in = (struct sockaddr *) i4;
1285 struct sockaddr_in6 *i6;
1287 i6 = GNUNET_malloc (sizeof (struct sockaddr_in6));
1288 i6->sin6_family = AF_INET6;
1289 i6->sin6_port = htons ((uint16_t) port);
1290 *sock_len = sizeof (struct sockaddr_in6);
1291 in = (struct sockaddr *) i6;
1295 cp = GNUNET_strdup (bindto);
1296 colon = strrchr (cp, ':');
1299 /* interpet value after colon as port */
1302 if (1 == SSCANF (colon,
1307 /* interpreting value as just a PORT number */
1308 if (port > UINT16_MAX)
1310 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1311 "BINDTO specification `%s' invalid: value too large for port\n",
1319 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1320 "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1328 /* interpret missing port as 0, aka pick any free one */
1333 struct sockaddr_in v4;
1335 if (1 == inet_pton (AF_INET,
1339 v4.sin_port = htons ((uint16_t) port);
1340 in = GNUNET_memdup (&v4,
1342 *sock_len = sizeof (v4);
1349 struct sockaddr_in6 v6;
1353 if ( ('[' == *cp) &&
1354 (']' == cp[strlen (cp)-1]) )
1356 start++; /* skip over '[' */
1357 cp[strlen (cp) -1] = '\0'; /* eat ']' */
1359 if (1 == inet_pton (AF_INET6,
1363 v6.sin6_port = htons ((uint16_t) port);
1364 in = GNUNET_memdup (&v6,
1366 *sock_len = sizeof (v6);
1371 /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1383 XXX_write (void *cls)
1387 sent = GNUNET_NETWORK_socket_sendto (udp_sock,
1391 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1400 * Signature of functions implementing the sending functionality of a
1403 * @param mq the message queue
1404 * @param msg the message to send
1405 * @param impl_state our `struct ReceiverAddress`
1408 mq_send (struct GNUNET_MQ_Handle *mq,
1409 const struct GNUNET_MessageHeader *msg,
1412 struct ReceiverAddress *receiver = impl_state;
1413 uint16_t msize = ntohs (msg->size);
1415 GNUNET_assert (mq == receiver->mq);
1416 // FIXME: pick encryption method, encrypt and transmit and call MQ-send-contiue!!
1419 /* compute 'tc' and append in encrypted format to cwrite_buf */
1420 tc.sender = my_identity;
1421 tc.monotonic_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1422 ths.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
1423 ths.purpose.size = htonl (sizeof (ths));
1424 ths.sender = my_identity;
1425 ths.receiver = queue->target;
1426 ths.ephemeral = *epub;
1427 ths.monotonic_time = tc.monotonic_time;
1428 GNUNET_assert (GNUNET_OK ==
1429 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1433 gcry_cipher_encrypt (queue->out_cipher,
1434 &queue->cwrite_buf[queue->cwrite_off],
1445 * Signature of functions implementing the destruction of a message
1446 * queue. Implementations must not free @a mq, but should take care
1449 * @param mq the message queue to destroy
1450 * @param impl_state our `struct ReceiverAddress`
1453 mq_destroy (struct GNUNET_MQ_Handle *mq,
1456 struct ReceiverAddress *receiver = impl_state;
1458 if (mq == receiver->mq)
1460 receiver->mq = NULL;
1461 receiver_destroy (receiver);
1467 * Implementation function that cancels the currently sent message.
1469 * @param mq message queue
1470 * @param impl_state our `struct RecvierAddress`
1473 mq_cancel (struct GNUNET_MQ_Handle *mq,
1476 /* Cancellation is impossible with UDP; bail */
1482 * Generic error handler, called with the appropriate
1483 * error code and the same closure specified at the creation of
1484 * the message queue.
1485 * Not every message queue implementation supports an error handler.
1487 * @param cls our `struct ReceiverAddress`
1488 * @param error error code
1491 mq_error (void *cls,
1492 enum GNUNET_MQ_Error error)
1494 struct ReceiverAddress *receiver = cls;
1496 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1497 "MQ error in queue to %s: %d\n",
1498 GNUNET_i2s (&receiver->target),
1500 receiver_destroy (receiver);
1505 * Setup a receiver for transmission. Setup the MQ processing and
1506 * inform transport that the queue is ready.
1510 static struct ReceiverAddress *
1511 receiver_setup (const struct GNUNET_PeerIdentity *target,
1512 const struct sockddr *address,
1513 socklen_t address_len)
1515 struct ReceiverAddress *receiver;
1517 receiver = GNUNET_new (struct ReceiverAddress);
1518 receiver->address = GNUNET_memdup (address,
1520 receiver->address_len = address_len;
1521 receiver->target = *target;
1522 receiver->nt = GNUNET_NT_scanner_get_type (is,
1525 (void) GNUNET_CONTAINER_multipeermap_put (receivers,
1528 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1529 // FIXME: add to receiver heap!
1530 GNUNET_STATISTICS_set (stats,
1531 "# receivers active",
1532 GNUNET_CONTAINER_multipeermap_size (receivers),
1535 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1537 = GNUNET_MQ_queue_for_callbacks (&mq_send,
1547 switch (address->sa_family)
1550 GNUNET_asprintf (&foreign_addr,
1552 COMMUNICATOR_ADDRESS_PREFIX,
1553 GNUNET_a2s(queue->address,
1554 queue->address_len));
1557 GNUNET_asprintf (&foreign_addr,
1559 COMMUNICATOR_ADDRESS_PREFIX,
1560 GNUNET_a2s(queue->address,
1561 queue->address_len));
1567 = GNUNET_TRANSPORT_communicator_mq_add (ch,
1570 1200 /* FIXME: MTU OK? */,
1572 GNUNET_TRANSPORT_CS_OUTBOUND,
1574 GNUNET_free (foreign_addr);
1580 * Function called by the transport service to initialize a
1581 * message queue given address information about another peer.
1582 * If and when the communication channel is established, the
1583 * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
1584 * to notify the service that the channel is now up. It is
1585 * the responsibility of the communicator to manage sane
1586 * retries and timeouts for any @a peer/@a address combination
1587 * provided by the transport service. Timeouts and retries
1588 * do not need to be signalled to the transport service.
1590 * @param cls closure
1591 * @param peer identity of the other peer
1592 * @param address where to send the message, human-readable
1593 * communicator-specific format, 0-terminated, UTF-8
1594 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is invalid
1598 const struct GNUNET_PeerIdentity *peer,
1599 const char *address)
1601 struct ReceiverAddress *receiver;
1603 struct sockaddr *in;
1606 if (0 != strncmp (address,
1607 COMMUNICATOR_ADDRESS_PREFIX "-",
1608 strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
1610 GNUNET_break_op (0);
1611 return GNUNET_SYSERR;
1613 path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
1614 in = udp_address_to_sockaddr (path,
1616 receiver = receiver_setup (peer,
1624 * Iterator over all receivers to clean up.
1627 * @param target unused
1628 * @param value the queue to destroy
1629 * @return #GNUNET_OK to continue to iterate
1632 get_receiver_delete_it (void *cls,
1633 const struct GNUNET_PeerIdentity *target,
1636 struct ReceiverAddress *receiver = value;
1640 receiver_destroy (receiver);
1646 * Iterator over all senders to clean up.
1649 * @param target unused
1650 * @param value the queue to destroy
1651 * @return #GNUNET_OK to continue to iterate
1654 get_receiver_delete_it (void *cls,
1655 const struct GNUNET_PeerIdentity *target,
1658 struct SenderAddress *sender = value;
1662 sender_destroy (sender);
1668 * Shutdown the UNIX communicator.
1670 * @param cls NULL (always)
1673 do_shutdown (void *cls)
1677 GNUNET_NAT_unregister (nat);
1680 if (NULL != read_task)
1682 GNUNET_SCHEDULER_cancel (read_task);
1685 if (NULL != udp_sock)
1687 GNUNET_break (GNUNET_OK ==
1688 GNUNET_NETWORK_socket_close (udp_sock));
1691 GNUNET_CONTAINER_multipeermap_iterate (receivers,
1692 &get_receiver_delete_it,
1694 GNUNET_CONTAINER_multipeermap_destroy (receivers);
1695 GNUNET_CONTAINER_multipeermap_iterate (senders,
1696 &get_sender_delete_it,
1698 GNUNET_CONTAINER_multipeermap_destroy (senders);
1699 GNUNET_CONTAINER_multishortmap_destroy (key_cache);
1700 GNUNET_CONTAINER_heap_destroy (senders_heap);
1701 GNUNET_CONTAINER_heap_destroy (receivers_heap);
1704 GNUNET_TRANSPORT_communicator_disconnect (ch);
1709 GNUNET_STATISTICS_destroy (stats,
1713 if (NULL != my_private_key)
1715 GNUNET_free (my_private_key);
1716 my_private_key = NULL;
1720 GNUNET_NT_scanner_done (is);
1727 * Function called when the transport service has received an
1728 * acknowledgement for this communicator (!) via a different return
1731 * Not applicable for UDP.
1733 * @param cls closure
1734 * @param sender which peer sent the notification
1735 * @param msg payload
1738 enc_notify_cb (void *cls,
1739 const struct GNUNET_PeerIdentity *sender,
1740 const struct GNUNET_MessageHeader *msg)
1745 GNUNET_break_op (0);
1750 * Signature of the callback passed to #GNUNET_NAT_register() for
1751 * a function to call whenever our set of 'valid' addresses changes.
1753 * @param cls closure
1754 * @param app_ctx[in,out] location where the app can store stuff
1755 * on add and retrieve it on remove
1756 * @param add_remove #GNUNET_YES to add a new public IP address,
1757 * #GNUNET_NO to remove a previous (now invalid) one
1758 * @param ac address class the address belongs to
1759 * @param addr either the previous or the new public IP address
1760 * @param addrlen actual length of the @a addr
1763 nat_address_cb (void *cls,
1766 enum GNUNET_NAT_AddressClass ac,
1767 const struct sockaddr *addr,
1771 struct GNUNET_TRANSPORT_AddressIdentifier *ai;
1773 if (GNUNET_YES == add_remove)
1775 enum GNUNET_NetworkType nt;
1777 GNUNET_asprintf (&my_addr,
1779 COMMUNICATOR_ADDRESS_PREFIX,
1782 nt = GNUNET_NT_scanner_get_type (is,
1785 ai = GNUNET_TRANSPORT_communicator_address_add (ch,
1788 GNUNET_TIME_UNIT_FOREVER_REL);
1789 GNUNET_free (my_addr);
1795 GNUNET_TRANSPORT_communicator_address_remove (ai);
1802 * Setup communicator and launch network interactions.
1804 * @param cls NULL (always)
1805 * @param args remaining command-line arguments
1806 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1807 * @param c configuration
1812 const char *cfgfile,
1813 const struct GNUNET_CONFIGURATION_Handle *c)
1816 struct sockaddr *in;
1818 struct sockaddr_storage in_sto;
1824 GNUNET_CONFIGURATION_get_value_filename (cfg,
1825 COMMUNICATOR_CONFIG_SECTION,
1829 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
1830 COMMUNICATOR_CONFIG_SECTION,
1835 GNUNET_CONFIGURATION_get_value_number (cfg,
1836 COMMUNICATOR_CONFIG_SECTION,
1839 max_queue_length = DEFAULT_MAX_QUEUE_LENGTH;
1841 in = udp_address_to_sockaddr (bindto,
1845 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1846 "Failed to setup UDP socket address with path `%s'\n",
1848 GNUNET_free (bindto);
1851 udp_sock = GNUNET_NETWORK_socket_create (in->sa_family,
1854 if (NULL == udp_sock)
1856 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
1859 GNUNET_free (bindto);
1863 GNUNET_NETWORK_socket_bind (udp_sock,
1867 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1870 GNUNET_NETWORK_socket_close (udp_sock);
1873 GNUNET_free (bindto);
1876 /* We might have bound to port 0, allowing the OS to figure it out;
1877 thus, get the real IN-address from the socket */
1878 sto_len = sizeof (in_sto);
1879 if (0 != getsockname (GNUNET_NETWORK_get_fd (udp_sock),
1880 (struct sockaddr *) &in_sto,
1889 GNUNET_free (bindto);
1890 in = (struct sockaddr *) &in_sto;
1892 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1894 GNUNET_a2s ((const struct sockaddr *) &in_sto,
1896 stats = GNUNET_STATISTICS_create ("C-UDP",
1898 GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
1900 is = GNUNET_NT_scanner_init ();
1901 my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
1902 if (NULL == my_private_key)
1904 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1905 _("Transport service is lacking key configuration settings. Exiting.\n"));
1906 GNUNET_SCHEDULER_shutdown ();
1909 GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
1910 &my_identity.public_key);
1911 /* start listening */
1912 read_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1916 senders = GNUNET_CONTAINER_multipeermap_create (32,
1918 receivers = GNUNET_CONTAINER_multipeermap_create (32,
1920 key_cache = GNUNET_CONTAINER_multishortmap_create (1024,
1922 ch = GNUNET_TRANSPORT_communicator_connect (cfg,
1923 COMMUNICATOR_CONFIG_SECTION,
1924 COMMUNICATOR_ADDRESS_PREFIX,
1925 GNUNET_TRANSPORT_CC_UNRELIABLE,
1933 GNUNET_SCHEDULER_shutdown ();
1936 nat = GNUNET_NAT_register (cfg,
1937 COMMUNICATOR_CONFIG_SECTION,
1939 1 /* one address */,
1940 (const struct sockaddr **) &in,
1943 NULL /* FIXME: support reversal: #5529 */,
1944 NULL /* closure */);
1949 * The main function for the UNIX communicator.
1951 * @param argc number of arguments from the command line
1952 * @param argv command line arguments
1953 * @return 0 ok, 1 on error
1959 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1960 GNUNET_GETOPT_OPTION_END
1965 GNUNET_STRINGS_get_utf8_args (argc, argv,
1971 GNUNET_PROGRAM_run (argc, argv,
1972 "gnunet-communicator-udp",
1973 _("GNUnet UDP communicator"),
1977 GNUNET_free ((void*) argv);
1982 /* end of gnunet-communicator-udp.c */