2 This file is part of GNUnet
3 Copyright (C) 2010-2014, 2018, 2019 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @file transport/gnunet-communicator-udp.c
23 * @brief Transport plugin using UDP.
24 * @author Christian Grothoff
27 * - consider imposing transmission limits in the absence
28 * of ACKs; or: maybe this should be done at TNG service level?
29 * (at least the receiver might want to enforce limits on
30 * KX/DH operations per sender in here) (#5552)
31 * - overall, we should look more into flow control support
32 * (either in backchannel, or general solution in TNG service)
33 * - handle addresses discovered from broadcasts (#5551)
34 * (think: what was the story again on address validation?
35 * where is the API for that!?!)
36 * - support DNS names in BINDTO option (#5528)
37 * - support NAT connection reversal method (#5529)
38 * - support other UDP-specific NAT traversal methods (#)
41 #include "gnunet_util_lib.h"
42 #include "gnunet_protocols.h"
43 #include "gnunet_signatures.h"
44 #include "gnunet_constants.h"
45 #include "gnunet_nt_lib.h"
46 #include "gnunet_nat_service.h"
47 #include "gnunet_statistics_service.h"
48 #include "gnunet_transport_communication_service.h"
51 * How often do we rekey based on time (at least)
53 #define REKEY_TIME_INTERVAL GNUNET_TIME_UNIT_DAYS
56 * How long do we wait until we must have received the initial KX?
58 #define PROTO_QUEUE_TIMEOUT GNUNET_TIME_UNIT_MINUTES
61 * How often do we broadcast our presence on the LAN?
63 #define BROADCAST_FREQUENCY GNUNET_TIME_UNIT_MINUTES
66 * How often do we scan for changes to our network interfaces?
68 #define INTERFACE_SCAN_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
73 #define AES_KEY_SIZE (256/8)
78 #define AES_IV_SIZE (96/8)
81 * Size of the GCM tag.
83 #define GCM_TAG_SIZE (128/8)
86 * If we fall below this number of available KCNs,
87 * we generate additional ACKs until we reach
89 * Should be large enough that we don't generate ACKs all
90 * the time and still have enough time for the ACK to
91 * arrive before the sender runs out. So really this
92 * should ideally be based on the RTT.
94 #define KCN_THRESHOLD 92
97 * How many KCNs do we keep around *after* we hit
98 * the #KCN_THRESHOLD? Should be larger than
99 * #KCN_THRESHOLD so we do not generate just one
102 #define KCN_TARGET 128
105 * What is the maximum delta between KCN sequence numbers
106 * that we allow. Used to expire 'ancient' KCNs that likely
107 * were dropped by the network. Must be larger than
108 * KCN_TARGET (otherwise we generate new KCNs all the time),
109 * but not too large (otherwise packet loss may cause
110 * sender to fall back to KX needlessly when sender runs
111 * out of ACK'ed KCNs due to losses).
113 #define MAX_SQN_DELTA 160
116 * How many shared master secrets do we keep around
117 * at most per sender? Should be large enough so
118 * that we generally have a chance of sending an ACK
119 * before the sender already rotated out the master
120 * secret. Generally values around #KCN_TARGET make
121 * sense. Might make sense to adapt to RTT if we had
122 * a good measurement...
124 #define MAX_SECRETS 128
127 * How often do we rekey based on number of bytes transmitted?
128 * (additionally randomized).
130 #define REKEY_MAX_BYTES (1024LLU * 1024 * 1024 * 4LLU)
133 * Address prefix used by the communicator.
136 #define COMMUNICATOR_ADDRESS_PREFIX "udp"
139 * Configuration section used by the communicator.
141 #define COMMUNICATOR_CONFIG_SECTION "communicator-udp"
143 GNUNET_NETWORK_STRUCT_BEGIN
147 * Signature we use to verify that the ephemeral key was really chosen by
148 * the specified sender. If possible, the receiver should respond with
149 * a `struct UDPAck` (possibly via backchannel).
151 struct UdpHandshakeSignature
154 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
156 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
159 * Identity of the inititor of the UDP connection (UDP client).
161 struct GNUNET_PeerIdentity sender;
164 * Presumed identity of the target of the UDP connection (UDP server)
166 struct GNUNET_PeerIdentity receiver;
169 * Ephemeral key used by the @e sender.
171 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
174 * Monotonic time of @e sender, to possibly help detect replay attacks
175 * (if receiver persists times by sender).
177 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
182 * "Plaintext" header at beginning of KX message. Followed
183 * by encrypted `struct UDPConfirmation`.
189 * Ephemeral key for KX.
191 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
194 * HMAC for the following encrypted message, using GCM. HMAC uses
195 * key derived from the handshake with sequence number zero.
197 char gcm_tag[GCM_TAG_SIZE];
203 * Encrypted continuation of UDP initial handshake, followed
204 * by message header with payload.
206 struct UDPConfirmation
211 struct GNUNET_PeerIdentity sender;
214 * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
216 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
219 * Monotonic time of @e sender, to possibly help detect replay attacks
220 * (if receiver persists times by sender).
222 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
224 /* followed by messages */
226 /* padding may follow actual messages */
231 * UDP key acknowledgement. May be sent via backchannel. Allows the
232 * sender to use `struct UDPBox` with the acknowledge key henceforth.
238 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK.
240 struct GNUNET_MessageHeader header;
243 * Sequence acknowledgement limit. Specifies current maximum sequence
244 * number supported by receiver.
246 uint32_t sequence_max GNUNET_PACKED;
249 * CMAC of the base key being acknowledged.
251 struct GNUNET_HashCode cmac;
257 * Signature we use to verify that the broadcast was really made by
258 * the peer that claims to have made it. Basically, affirms that the
259 * peer is really using this IP address (albeit possibly not in _our_
260 * LAN). Makes it difficult for peers in the LAN to claim to
261 * be just any global peer -- an attacker must have at least
262 * shared a LAN with the peer they're pretending to be here.
264 struct UdpBroadcastSignature
267 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
269 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
272 * Identity of the inititor of the UDP broadcast.
274 struct GNUNET_PeerIdentity sender;
277 * Hash of the sender's UDP address.
279 struct GNUNET_HashCode h_address;
284 * Broadcast by peer in LAN announcing its presence. Unusual in that
285 * we don't pad these to full MTU, as we cannot prevent being
286 * recognized in LAN as GNUnet peers if this feature is enabled
287 * anyway. Also, the entire message is in cleartext.
293 * Sender's peer identity.
295 struct GNUNET_PeerIdentity sender;
298 * Sender's signature of type
299 * #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
301 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
307 * UDP message box. Always sent encrypted, only allowed after
308 * the receiver sent a `struct UDPAck` for the base key!
314 * Key and IV identification code. KDF applied to an acknowledged
315 * base key and a sequence number. Sequence numbers must be used
316 * monotonically increasing up to the maximum specified in
317 * `struct UDPAck`. Without further `struct UDPAck`s, the sender
318 * must fall back to sending handshakes!
320 struct GNUNET_ShortHashCode kid;
323 * 128-bit authentication tag for the following encrypted message,
324 * from GCM. MAC starts at the @e body_start that follows and
325 * extends until the end of the UDP payload. If the @e hmac is
326 * wrong, the receiver should check if the message might be a
327 * `struct UdpHandshakeSignature`.
329 char gcm_tag[GCM_TAG_SIZE];
334 GNUNET_NETWORK_STRUCT_END
337 * Shared secret we generated for a particular sender or receiver.
343 * Pre-generated "kid" code (key and IV identification code) to
344 * quickly derive master key for a `struct UDPBox`.
352 struct KeyCacheEntry *next;
357 struct KeyCacheEntry *prev;
360 * Key and IV identification code. KDF applied to an acknowledged
361 * base key and a sequence number. Sequence numbers must be used
362 * monotonically increasing up to the maximum specified in
363 * `struct UDPAck`. Without further `struct UDPAck`s, the sender
364 * must fall back to sending handshakes!
366 struct GNUNET_ShortHashCode kid;
369 * Corresponding shared secret.
371 struct SharedSecret *ss;
374 * Sequence number used to derive this entry from master key.
376 uint32_t sequence_number;
381 * Information we track per sender address we have recently been
382 * in contact with (decryption from sender).
384 struct SenderAddress;
387 * Information we track per receiving address we have recently been
388 * in contact with (encryption to receiver).
390 struct ReceiverAddress;
393 * Shared secret we generated for a particular sender or receiver.
400 struct SharedSecret *next;
405 struct SharedSecret *prev;
408 * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
410 struct KeyCacheEntry *kce_head;
413 * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
415 struct KeyCacheEntry *kce_tail;
418 * Sender we use this shared secret with, or NULL.
420 struct SenderAddress *sender;
423 * Receiver we use this shared secret with, or NULL.
425 struct ReceiverAddress *receiver;
428 * Master shared secret.
430 struct GNUNET_HashCode master;
433 * CMAC is used to identify @e master in ACKs.
435 struct GNUNET_HashCode cmac;
438 * Up to which sequence number did we use this @e master already?
439 * (for encrypting only)
441 uint32_t sequence_used;
444 * Up to which sequence number did the other peer allow us to use
445 * this key, or up to which number did we allow the other peer to
448 uint32_t sequence_allowed;
451 * Number of active KCN entries.
453 unsigned int active_kce_count;
458 * Information we track per sender address we have recently been
459 * in contact with (we decrypt messages from the sender).
465 * To whom are we talking to.
467 struct GNUNET_PeerIdentity target;
470 * Entry in sender expiration heap.
472 struct GNUNET_CONTAINER_HeapNode *hn;
475 * Shared secrets we used with @e target, first used is head.
477 struct SharedSecret *ss_head;
480 * Shared secrets we used with @e target, last used is tail.
482 struct SharedSecret *ss_tail;
485 * Address of the other peer.
487 struct sockaddr *address;
490 * Length of the address.
492 socklen_t address_len;
495 * Timeout for this sender.
497 struct GNUNET_TIME_Absolute timeout;
500 * Length of the DLL at @a ss_head.
502 unsigned int num_secrets;
505 * Which network type does this queue use?
507 enum GNUNET_NetworkType nt;
513 * Information we track per receiving address we have recently been
514 * in contact with (encryption to receiver).
516 struct ReceiverAddress
520 * To whom are we talking to.
522 struct GNUNET_PeerIdentity target;
525 * Shared secrets we received from @e target, first used is head.
527 struct SharedSecret *ss_head;
530 * Shared secrets we received with @e target, last used is tail.
532 struct SharedSecret *ss_tail;
535 * Address of the receiver in the human-readable format
536 * with the #COMMUNICATOR_ADDRESS_PREFIX.
541 * Address of the other peer.
543 struct sockaddr *address;
546 * Length of the address.
548 socklen_t address_len;
551 * Entry in sender expiration heap.
553 struct GNUNET_CONTAINER_HeapNode *hn;
556 * Message queue we are providing for the #ch.
558 struct GNUNET_MQ_Handle *mq;
561 * handle for this queue with the #ch.
563 struct GNUNET_TRANSPORT_QueueHandle *qh;
566 * Timeout for this receiver address.
568 struct GNUNET_TIME_Absolute timeout;
571 * MTU we allowed transport for this receiver right now.
576 * Length of the DLL at @a ss_head.
578 unsigned int num_secrets;
581 * Number of BOX keys from ACKs we have currently
582 * available for this receiver.
584 unsigned int acks_available;
587 * Which network type does this queue use?
589 enum GNUNET_NetworkType nt;
595 * Interface we broadcast our presence on.
597 struct BroadcastInterface
603 struct BroadcastInterface *next;
608 struct BroadcastInterface *prev;
611 * Task for this broadcast interface.
613 struct GNUNET_SCHEDULER_Task *broadcast_task;
616 * Sender's address of the interface.
621 * Broadcast address to use on the interface.
626 * Message we broadcast on this interface.
628 struct UDPBroadcast bcm;
631 * If this is an IPv6 interface, this is the request
632 * we use to join/leave the group.
634 struct ipv6_mreq mcreq;
637 * Number of bytes in @e sa.
642 * Was this interface found in the last #iface_proc() scan?
649 * Cache of pre-generated key IDs.
651 static struct GNUNET_CONTAINER_MultiShortmap *key_cache;
656 static struct GNUNET_SCHEDULER_Task *read_task;
661 static struct GNUNET_SCHEDULER_Task *timeout_task;
664 * ID of master broadcast task
666 static struct GNUNET_SCHEDULER_Task *broadcast_task;
669 * For logging statistics.
671 static struct GNUNET_STATISTICS_Handle *stats;
676 static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
679 * Receivers (map from peer identity to `struct ReceiverAddress`)
681 static struct GNUNET_CONTAINER_MultiPeerMap *receivers;
684 * Senders (map from peer identity to `struct SenderAddress`)
686 static struct GNUNET_CONTAINER_MultiPeerMap *senders;
689 * Expiration heap for senders (contains `struct SenderAddress`)
691 static struct GNUNET_CONTAINER_Heap *senders_heap;
694 * Expiration heap for receivers (contains `struct ReceiverAddress`)
696 static struct GNUNET_CONTAINER_Heap *receivers_heap;
699 * Broadcast interface tasks. Kept in a DLL.
701 static struct BroadcastInterface *bi_head;
704 * Broadcast interface tasks. Kept in a DLL.
706 static struct BroadcastInterface *bi_tail;
711 static struct GNUNET_NETWORK_Handle *udp_sock;
714 * #GNUNET_YES if #udp_sock supports IPv6.
716 static int have_v6_socket;
721 static struct GNUNET_PeerIdentity my_identity;
726 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
731 static const struct GNUNET_CONFIGURATION_Handle *cfg;
734 * Network scanner to determine network types.
736 static struct GNUNET_NT_InterfaceScanner *is;
739 * Connection to NAT service.
741 static struct GNUNET_NAT_Handle *nat;
744 * Port number to which we are actually bound.
746 static uint16_t my_port;
750 * An interface went away, stop broadcasting on it.
752 * @param bi entity to close down
755 bi_destroy (struct BroadcastInterface *bi)
757 if (AF_INET6 == bi->sa->sa_family)
759 /* Leave the multicast group */
761 GNUNET_NETWORK_socket_setsockopt
768 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
772 GNUNET_CONTAINER_DLL_remove (bi_head,
775 GNUNET_SCHEDULER_cancel (bi->broadcast_task);
776 GNUNET_free (bi->sa);
777 GNUNET_free_non_null (bi->ba);
783 * Destroys a receiving state due to timeout or shutdown.
785 * @param receiver entity to close down
788 receiver_destroy (struct ReceiverAddress *receiver)
790 struct GNUNET_MQ_Handle *mq;
792 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
793 "Disconnecting receiver for peer `%s'\n",
794 GNUNET_i2s (&receiver->target));
795 if (NULL != (mq = receiver->mq))
798 GNUNET_MQ_destroy (mq);
800 if (NULL != receiver->qh)
802 GNUNET_TRANSPORT_communicator_mq_del (receiver->qh);
805 GNUNET_assert (GNUNET_YES ==
806 GNUNET_CONTAINER_multipeermap_remove (receivers,
809 GNUNET_assert (receiver ==
810 GNUNET_CONTAINER_heap_remove_node (receiver->hn));
811 GNUNET_STATISTICS_set (stats,
812 "# receivers active",
813 GNUNET_CONTAINER_multipeermap_size (receivers),
815 GNUNET_free (receiver->address);
816 GNUNET_free (receiver->foreign_addr);
817 GNUNET_free (receiver);
822 * Free memory used by key cache entry.
824 * @param kce the key cache entry
827 kce_destroy (struct KeyCacheEntry *kce)
829 struct SharedSecret *ss = kce->ss;
831 ss->active_kce_count--;
832 GNUNET_CONTAINER_DLL_remove (ss->kce_head,
835 GNUNET_assert (GNUNET_YES ==
836 GNUNET_CONTAINER_multishortmap_remove (key_cache,
846 * @param msec master secret for HMAC calculation
847 * @param serial number for the @a smac calculation
848 * @param kid[out] where to write the key ID
851 get_kid (const struct GNUNET_HashCode *msec,
853 struct GNUNET_ShortHashCode *kid)
855 uint32_t sid = htonl (serial);
857 GNUNET_CRYPTO_hkdf (kid,
872 * Setup key cache entry for sequence number @a seq and shared secret @a ss.
874 * @param ss shared secret
875 * @param seq sequence number for the key cache entry
878 kce_generate (struct SharedSecret *ss,
881 struct KeyCacheEntry *kce;
883 GNUNET_assert (0 < seq);
884 kce = GNUNET_new (struct KeyCacheEntry);
886 kce->sequence_number = seq;
887 get_kid (&ss->master,
890 GNUNET_CONTAINER_DLL_insert (ss->kce_head,
893 ss->active_kce_count++;
894 (void) GNUNET_CONTAINER_multishortmap_put (key_cache,
897 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
898 GNUNET_STATISTICS_set (stats,
900 GNUNET_CONTAINER_multishortmap_size (key_cache),
906 * Destroy @a ss and associated key cache entries.
908 * @param ss shared secret to destroy
911 secret_destroy (struct SharedSecret *ss)
913 struct SenderAddress *sender;
914 struct ReceiverAddress *receiver;
915 struct KeyCacheEntry *kce;
917 if (NULL != (sender = ss->sender))
919 GNUNET_CONTAINER_DLL_remove (sender->ss_head,
922 sender->num_secrets--;
924 if (NULL != (receiver = ss->receiver))
926 GNUNET_CONTAINER_DLL_remove (receiver->ss_head,
929 receiver->num_secrets--;
930 receiver->acks_available
931 -= (ss->sequence_allowed - ss->sequence_used);
933 while (NULL != (kce = ss->kce_head))
935 GNUNET_STATISTICS_update (stats,
939 GNUNET_STATISTICS_set (stats,
941 GNUNET_CONTAINER_multishortmap_size (key_cache),
948 * Functions with this signature are called whenever we need
949 * to close a sender's state due to timeout.
951 * @param sender entity to close down
954 sender_destroy (struct SenderAddress *sender)
956 GNUNET_assert (GNUNET_YES ==
957 GNUNET_CONTAINER_multipeermap_remove (senders,
960 GNUNET_assert (sender ==
961 GNUNET_CONTAINER_heap_remove_node (sender->hn));
962 GNUNET_STATISTICS_set (stats,
964 GNUNET_CONTAINER_multipeermap_size (senders),
966 GNUNET_free (sender->address);
967 GNUNET_free (sender);
972 * Compute @a key and @a iv.
974 * @param msec master secret for calculation
975 * @param serial number for the @a smac calculation
976 * @param key[out] where to write the decrption key
977 * @param iv[out] where to write the IV
980 get_iv_key (const struct GNUNET_HashCode *msec,
982 char key[AES_KEY_SIZE],
983 char iv[AES_IV_SIZE])
985 uint32_t sid = htonl (serial);
986 char res[AES_KEY_SIZE + AES_IV_SIZE];
988 GNUNET_CRYPTO_hkdf (res,
997 strlen ("UDP-IV-KEY"),
1009 * Increment sender timeout due to activity.
1011 * @param sender address for which the timeout should be rescheduled
1014 reschedule_sender_timeout (struct SenderAddress *sender)
1017 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1018 GNUNET_CONTAINER_heap_update_cost (sender->hn,
1019 sender->timeout.abs_value_us);
1024 * Increment receiver timeout due to activity.
1026 * @param receiver address for which the timeout should be rescheduled
1029 reschedule_receiver_timeout (struct ReceiverAddress *receiver)
1032 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1033 GNUNET_CONTAINER_heap_update_cost (receiver->hn,
1034 receiver->timeout.abs_value_us);
1039 * Task run to check #receiver_heap and #sender_heap for timeouts.
1041 * @param cls unused, NULL
1044 check_timeouts (void *cls)
1046 struct GNUNET_TIME_Relative st;
1047 struct GNUNET_TIME_Relative rt;
1048 struct GNUNET_TIME_Relative delay;
1049 struct ReceiverAddress *receiver;
1050 struct SenderAddress *sender;
1053 timeout_task = NULL;
1054 rt = GNUNET_TIME_UNIT_FOREVER_REL;
1055 while (NULL != (receiver = GNUNET_CONTAINER_heap_peek (receivers_heap)))
1057 rt = GNUNET_TIME_absolute_get_remaining (receiver->timeout);
1058 if (0 != rt.rel_value_us)
1060 receiver_destroy (receiver);
1062 st = GNUNET_TIME_UNIT_FOREVER_REL;
1063 while (NULL != (sender = GNUNET_CONTAINER_heap_peek (senders_heap)))
1065 st = GNUNET_TIME_absolute_get_remaining (receiver->timeout);
1066 if (0 != st.rel_value_us)
1068 sender_destroy (sender);
1070 delay = GNUNET_TIME_relative_min (rt,
1072 if (delay.rel_value_us < GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
1073 timeout_task = GNUNET_SCHEDULER_add_delayed (delay,
1080 * Calcualte cmac from master in @a ss.
1082 * @param ss[in,out] data structure to complete
1085 calculate_cmac (struct SharedSecret *ss)
1087 GNUNET_CRYPTO_hkdf (&ss->cmac,
1094 sizeof (ss->master),
1096 strlen ("UDP-CMAC"),
1102 * We received @a plaintext_len bytes of @a plaintext from a @a sender.
1103 * Pass it on to CORE.
1105 * @param queue the queue that received the plaintext
1106 * @param plaintext the plaintext that was received
1107 * @param plaintext_len number of bytes of plaintext received
1110 pass_plaintext_to_core (struct SenderAddress *sender,
1111 const void *plaintext,
1112 size_t plaintext_len)
1114 const struct GNUNET_MessageHeader *hdr = plaintext;
1116 while (ntohs (hdr->size) < plaintext_len)
1118 GNUNET_STATISTICS_update (stats,
1119 "# bytes given to core",
1122 (void) GNUNET_TRANSPORT_communicator_receive (ch,
1125 NULL /* no flow control possible */,
1127 /* move on to next message, if any */
1128 plaintext_len -= ntohs (hdr->size);
1129 if (plaintext_len < sizeof (*hdr))
1131 hdr = plaintext + ntohs (hdr->size);
1133 GNUNET_STATISTICS_update (stats,
1134 "# bytes padding discarded",
1141 * Setup @a cipher based on shared secret @a msec and
1142 * serial number @a serial.
1144 * @param msec master shared secret
1145 * @param serial serial number of cipher to set up
1146 * @param cipher[out] cipher to initialize
1149 setup_cipher (const struct GNUNET_HashCode *msec,
1151 gcry_cipher_hd_t *cipher)
1153 char key[AES_KEY_SIZE];
1154 char iv[AES_IV_SIZE];
1156 gcry_cipher_open (cipher,
1157 GCRY_CIPHER_AES256 /* low level: go for speed */,
1158 GCRY_CIPHER_MODE_GCM,
1164 gcry_cipher_setkey (*cipher,
1167 gcry_cipher_setiv (*cipher,
1174 * Try to decrypt @a buf using shared secret @a ss and key/iv
1175 * derived using @a serial.
1177 * @param ss shared secret
1178 * @param tag GCM authentication tag
1179 * @param serial serial number to use
1180 * @param in_buf input buffer to decrypt
1181 * @param in_buf_size number of bytes in @a in_buf and available in @a out_buf
1182 * @param out_buf where to write the result
1183 * @return #GNUNET_OK on success
1186 try_decrypt (const struct SharedSecret *ss,
1187 const char tag[GCM_TAG_SIZE],
1193 gcry_cipher_hd_t cipher;
1195 setup_cipher (&ss->master,
1199 gcry_cipher_decrypt (cipher,
1205 gcry_cipher_checktag (cipher,
1209 gcry_cipher_close (cipher);
1210 GNUNET_STATISTICS_update (stats,
1211 "# AEAD authentication failures",
1214 return GNUNET_SYSERR;
1216 gcry_cipher_close (cipher);
1222 * Setup shared secret for decryption.
1224 * @param ephemeral ephemeral key we received from the other peer
1225 * @return new shared secret
1227 static struct SharedSecret *
1228 setup_shared_secret_dec (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1230 struct SharedSecret *ss;
1232 ss = GNUNET_new (struct SharedSecret);
1233 GNUNET_CRYPTO_eddsa_ecdh (my_private_key,
1241 * Setup shared secret for encryption.
1243 * @param ephemeral ephemeral key we are sending to the other peer
1244 * @param receiver[in,out] queue to initialize encryption key for
1245 * @return new shared secret
1247 static struct SharedSecret *
1248 setup_shared_secret_enc (const struct GNUNET_CRYPTO_EcdhePrivateKey *ephemeral,
1249 struct ReceiverAddress *receiver)
1251 struct SharedSecret *ss;
1253 ss = GNUNET_new (struct SharedSecret);
1254 GNUNET_CRYPTO_ecdh_eddsa (ephemeral,
1255 &receiver->target.public_key,
1257 calculate_cmac (ss);
1258 ss->receiver = receiver;
1259 GNUNET_CONTAINER_DLL_insert (receiver->ss_head,
1262 receiver->num_secrets++;
1263 GNUNET_STATISTICS_update (stats,
1272 * Setup the MQ for the @a receiver. If a queue exists,
1273 * the existing one is destroyed. Then the MTU is
1274 * recalculated and a fresh queue is initialized.
1276 * @param receiver receiver to setup MQ for
1279 setup_receiver_mq (struct ReceiverAddress *receiver);
1283 * We received an ACK for @a pid. Check if it is for
1284 * the receiver in @a value and if so, handle it and
1285 * return #GNUNET_NO. Otherwise, return #GNUNET_YES.
1287 * @param cls a `const struct UDPAck`
1288 * @param pid peer the ACK is from
1289 * @param value a `struct ReceiverAddress`
1290 * @return #GNUNET_YES to continue to iterate
1293 handle_ack (void *cls,
1294 const struct GNUNET_PeerIdentity *pid,
1297 const struct UDPAck *ack = cls;
1298 struct ReceiverAddress *receiver = value;
1301 for (struct SharedSecret *ss = receiver->ss_head;
1305 if (0 == memcmp (&ack->cmac,
1307 sizeof (struct GNUNET_HashCode)))
1311 allowed = ntohl (ack->sequence_max);
1313 if (allowed > ss->sequence_allowed)
1315 receiver->acks_available += (allowed - ss->sequence_allowed);
1316 if ((allowed - ss->sequence_allowed)
1317 == receiver->acks_available)
1319 /* we just incremented from zero => MTU change! */
1320 setup_receiver_mq (receiver);
1322 ss->sequence_allowed = allowed;
1323 /* move ss to head to avoid discarding it anytime soon! */
1324 GNUNET_CONTAINER_DLL_remove (receiver->ss_head,
1327 GNUNET_CONTAINER_DLL_insert (receiver->ss_head,
1339 * Test if we have received a valid message in plaintext.
1342 * @param sender peer to process inbound plaintext for
1343 * @param buf buffer we received
1344 * @param buf_size number of bytes in @a buf
1347 try_handle_plaintext (struct SenderAddress *sender,
1351 const struct GNUNET_MessageHeader *hdr
1352 = (const struct GNUNET_MessageHeader *) buf;
1353 const struct UDPAck *ack
1354 = (const struct UDPAck *) buf;
1357 if (sizeof (*hdr) > buf_size)
1358 return; /* not even a header */
1359 if (ntohs (hdr->size) > buf_size)
1360 return; /* not even a header */
1361 type = ntohs (hdr->type);
1364 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK:
1365 /* lookup master secret by 'cmac', then update sequence_max */
1366 GNUNET_CONTAINER_multipeermap_get_multiple (receivers,
1370 /* There could be more messages after the ACK, handle those as well */
1371 buf += ntohs (hdr->size);
1372 buf_size -= ntohs (hdr->size);
1373 pass_plaintext_to_core (sender,
1377 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD:
1381 pass_plaintext_to_core (sender,
1389 * We established a shared secret with a sender. We should try to send
1390 * the sender an `struct UDPAck` at the next opportunity to allow the
1391 * sender to use @a ss longer (assuming we did not yet already
1394 * @param ss shared secret to generate ACKs for
1397 consider_ss_ack (struct SharedSecret *ss)
1399 GNUNET_assert (NULL != ss->sender);
1400 /* drop ancient KeyCacheEntries */
1401 while ( (NULL != ss->kce_head) &&
1402 (MAX_SQN_DELTA < ss->kce_head->sequence_number - ss->kce_tail->sequence_number) )
1403 kce_destroy (ss->kce_tail);
1404 if (ss->active_kce_count < KCN_THRESHOLD)
1408 while (ss->active_kce_count < KCN_TARGET)
1410 ++ss->sequence_allowed);
1411 ack.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK);
1412 ack.header.size = htons (sizeof (ack));
1413 ack.sequence_max = htonl (ss->sequence_allowed);
1414 ack.cmac = ss->cmac;
1415 GNUNET_TRANSPORT_communicator_notify (ch,
1416 &ss->sender->target,
1417 COMMUNICATOR_ADDRESS_PREFIX,
1424 * We received a @a box with matching @a kce. Decrypt and process it.
1426 * @param box the data we received
1427 * @param box_len number of bytes in @a box
1428 * @param kce key index to decrypt @a box
1431 decrypt_box (const struct UDPBox *box,
1433 struct KeyCacheEntry *kce)
1435 struct SharedSecret *ss = kce->ss;
1436 char out_buf[box_len - sizeof (*box)];
1438 GNUNET_assert (NULL != ss->sender);
1442 kce->sequence_number,
1443 (const char *) &box[1],
1447 GNUNET_STATISTICS_update (stats,
1448 "# Decryption failures with valid KCE",
1455 GNUNET_STATISTICS_update (stats,
1456 "# bytes decrypted with BOX",
1459 try_handle_plaintext (ss->sender,
1462 consider_ss_ack (ss);
1467 * Closure for #find_sender_by_address()
1469 struct SearchContext
1472 * Address we are looking for.
1474 const struct sockaddr *address;
1477 * Number of bytes in @e address.
1479 socklen_t address_len;
1482 * Return value to set if we found a match.
1484 struct SenderAddress *sender;
1489 * Find existing `struct SenderAddress` by matching addresses.
1491 * @param cls a `struct SearchContext`
1492 * @param key ignored, must match already
1493 * @param value a `struct SenderAddress`
1494 * @return #GNUNET_YES if not found (continue to search), #GNUNET_NO if found
1497 find_sender_by_address (void *cls,
1498 const struct GNUNET_PeerIdentity *key,
1501 struct SearchContext *sc = cls;
1502 struct SenderAddress *sender = value;
1504 if ( (sender->address_len == sc->address_len) &&
1505 (0 == memcmp (sender->address,
1507 sender->address_len)) )
1509 sc->sender = sender;
1510 return GNUNET_NO; /* stop iterating! */
1517 * Create sender address for @a target. Note that we
1518 * might already have one, so a fresh one is only allocated
1519 * if one does not yet exist for @a address.
1521 * @param target peer to generate address for
1522 * @param address target address
1523 * @param address_len number of bytes in @a address
1524 * @return data structure to keep track of key material for
1525 * decrypting data from @a target
1527 static struct SenderAddress *
1528 setup_sender (const struct GNUNET_PeerIdentity *target,
1529 const struct sockaddr *address,
1530 socklen_t address_len)
1532 struct SenderAddress *sender;
1533 struct SearchContext sc = {
1535 .address_len = address_len,
1539 GNUNET_CONTAINER_multipeermap_get_multiple (senders,
1541 &find_sender_by_address,
1543 if (NULL != sc.sender)
1545 reschedule_sender_timeout (sc.sender);
1548 sender = GNUNET_new (struct SenderAddress);
1549 sender->target = *target;
1550 sender->address = GNUNET_memdup (address,
1552 sender->address_len = address_len;
1553 (void) GNUNET_CONTAINER_multipeermap_put (senders,
1556 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1557 GNUNET_STATISTICS_set (stats,
1559 GNUNET_CONTAINER_multipeermap_size (receivers),
1562 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1563 sender->hn = GNUNET_CONTAINER_heap_insert (senders_heap,
1565 sender->timeout.abs_value_us);
1566 sender->nt = GNUNET_NT_scanner_get_type (is,
1569 if (NULL == timeout_task)
1570 timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts,
1577 * Check signature from @a uc against @a ephemeral.
1579 * @param ephermal key that is signed
1580 * @param uc signature of claimant
1581 * @return #GNUNET_OK if signature is valid
1584 verify_confirmation (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral,
1585 const struct UDPConfirmation *uc)
1587 struct UdpHandshakeSignature uhs;
1589 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
1590 uhs.purpose.size = htonl (sizeof (uhs));
1591 uhs.sender = uc->sender;
1592 uhs.receiver = my_identity;
1593 uhs.ephemeral = *ephemeral;
1594 uhs.monotonic_time = uc->monotonic_time;
1595 return GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE,
1598 &uc->sender.public_key);
1608 sock_read (void *cls)
1610 struct sockaddr_storage sa;
1611 socklen_t salen = sizeof (sa);
1612 char buf[UINT16_MAX];
1617 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1621 rcvd = GNUNET_NETWORK_socket_recvfrom (udp_sock,
1624 (struct sockaddr *) &sa,
1628 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1633 /* first, see if it is a UDPBox */
1634 if (rcvd > sizeof (struct UDPBox))
1636 const struct UDPBox *box;
1637 struct KeyCacheEntry *kce;
1639 box = (const struct UDPBox *) buf;
1640 kce = GNUNET_CONTAINER_multishortmap_get (key_cache,
1651 /* next, check if it is a broadcast */
1652 if (sizeof (struct UDPBroadcast) == rcvd)
1654 const struct UDPBroadcast *ub;
1655 struct UdpBroadcastSignature uhs;
1657 ub = (const struct UDPBroadcast *) buf;
1658 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
1659 uhs.purpose.size = htonl (sizeof (uhs));
1660 uhs.sender = ub->sender;
1661 GNUNET_CRYPTO_hash (&sa,
1665 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST,
1668 &ub->sender.public_key))
1670 GNUNET_STATISTICS_update (stats,
1671 "# broadcasts received",
1674 // FIXME #5551: we effectively just got a HELLO!
1675 // trigger verification NOW!
1678 /* continue with KX, mostly for statistics... */
1682 /* finally, test if it is a KX */
1683 if (rcvd < sizeof (struct UDPConfirmation) + sizeof (struct InitialKX))
1685 GNUNET_STATISTICS_update (stats,
1686 "# messages dropped (no kid, too small for KX)",
1693 const struct InitialKX *kx;
1694 struct SharedSecret *ss;
1695 char pbuf[rcvd - sizeof (struct InitialKX)];
1696 const struct UDPConfirmation *uc;
1697 struct SenderAddress *sender;
1699 kx = (const struct InitialKX *) buf;
1700 ss = setup_shared_secret_dec (&kx->ephemeral);
1710 GNUNET_STATISTICS_update (stats,
1711 "# messages dropped (no kid, AEAD decryption failed)",
1716 uc = (const struct UDPConfirmation *) pbuf;
1718 verify_confirmation (&kx->ephemeral,
1721 GNUNET_break_op (0);
1723 GNUNET_STATISTICS_update (stats,
1724 "# messages dropped (sender signature invalid)",
1729 calculate_cmac (ss);
1730 sender = setup_sender (&uc->sender,
1731 (const struct sockaddr *) &sa,
1733 ss->sender = sender;
1734 GNUNET_CONTAINER_DLL_insert (sender->ss_head,
1737 sender->num_secrets++;
1738 GNUNET_STATISTICS_update (stats,
1742 GNUNET_STATISTICS_update (stats,
1743 "# messages decrypted without BOX",
1746 try_handle_plaintext (sender,
1748 sizeof (pbuf) - sizeof (*uc));
1749 consider_ss_ack (ss);
1750 if (sender->num_secrets > MAX_SECRETS)
1751 secret_destroy (sender->ss_tail);
1757 * Convert UDP bind specification to a `struct sockaddr *`
1759 * @param bindto bind specification to convert
1760 * @param[out] sock_len set to the length of the address
1761 * @return converted bindto specification
1763 static struct sockaddr *
1764 udp_address_to_sockaddr (const char *bindto,
1765 socklen_t *sock_len)
1767 struct sockaddr *in;
1773 if (1 == SSCANF (bindto,
1778 /* interpreting value as just a PORT number */
1779 if (port > UINT16_MAX)
1781 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1782 "BINDTO specification `%s' invalid: value too large for port\n",
1787 GNUNET_NETWORK_test_pf (PF_INET6)) ||
1789 GNUNET_CONFIGURATION_get_value_yesno (cfg,
1790 COMMUNICATOR_CONFIG_SECTION,
1793 struct sockaddr_in *i4;
1795 i4 = GNUNET_malloc (sizeof (struct sockaddr_in));
1796 i4->sin_family = AF_INET;
1797 i4->sin_port = htons ((uint16_t) port);
1798 *sock_len = sizeof (struct sockaddr_in);
1799 in = (struct sockaddr *) i4;
1803 struct sockaddr_in6 *i6;
1805 i6 = GNUNET_malloc (sizeof (struct sockaddr_in6));
1806 i6->sin6_family = AF_INET6;
1807 i6->sin6_port = htons ((uint16_t) port);
1808 *sock_len = sizeof (struct sockaddr_in6);
1809 in = (struct sockaddr *) i6;
1813 cp = GNUNET_strdup (bindto);
1814 colon = strrchr (cp, ':');
1817 /* interpet value after colon as port */
1820 if (1 == SSCANF (colon,
1825 /* interpreting value as just a PORT number */
1826 if (port > UINT16_MAX)
1828 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1829 "BINDTO specification `%s' invalid: value too large for port\n",
1837 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1838 "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1846 /* interpret missing port as 0, aka pick any free one */
1851 struct sockaddr_in v4;
1853 if (1 == inet_pton (AF_INET,
1857 v4.sin_port = htons ((uint16_t) port);
1858 in = GNUNET_memdup (&v4,
1860 *sock_len = sizeof (v4);
1867 struct sockaddr_in6 v6;
1871 if ( ('[' == *cp) &&
1872 (']' == cp[strlen (cp)-1]) )
1874 start++; /* skip over '[' */
1875 cp[strlen (cp) -1] = '\0'; /* eat ']' */
1877 if (1 == inet_pton (AF_INET6,
1881 v6.sin6_port = htons ((uint16_t) port);
1882 in = GNUNET_memdup (&v6,
1884 *sock_len = sizeof (v6);
1889 /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1896 * Pad @a dgram by @a pad_size using @a out_cipher.
1898 * @param out_cipher cipher to use
1899 * @param dgram datagram to pad
1900 * @param pad_size number of bytes of padding to append
1903 do_pad (gcry_cipher_hd_t out_cipher,
1909 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
1912 if (sizeof (pad) > sizeof (struct GNUNET_MessageHeader))
1914 struct GNUNET_MessageHeader hdr = {
1915 .size = htons (sizeof (pad)),
1916 .type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD)
1924 gcry_cipher_encrypt (out_cipher,
1933 * Signature of functions implementing the sending functionality of a
1936 * @param mq the message queue
1937 * @param msg the message to send
1938 * @param impl_state our `struct ReceiverAddress`
1941 mq_send (struct GNUNET_MQ_Handle *mq,
1942 const struct GNUNET_MessageHeader *msg,
1945 struct ReceiverAddress *receiver = impl_state;
1946 uint16_t msize = ntohs (msg->size);
1948 GNUNET_assert (mq == receiver->mq);
1949 if (msize > receiver->mtu)
1952 receiver_destroy (receiver);
1955 reschedule_receiver_timeout (receiver);
1957 if (0 == receiver->acks_available)
1959 /* use KX encryption method */
1960 struct UdpHandshakeSignature uhs;
1961 struct UDPConfirmation uc;
1962 struct InitialKX kx;
1963 struct GNUNET_CRYPTO_EcdhePrivateKey epriv;
1964 char dgram[receiver->mtu +
1968 gcry_cipher_hd_t out_cipher;
1969 struct SharedSecret *ss;
1971 /* setup key material */
1972 GNUNET_assert (GNUNET_OK ==
1973 GNUNET_CRYPTO_ecdhe_key_create2 (&epriv));
1975 ss = setup_shared_secret_enc (&epriv,
1977 setup_cipher (&ss->master,
1981 uc.sender = my_identity;
1982 uc.monotonic_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1983 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
1984 uhs.purpose.size = htonl (sizeof (uhs));
1985 uhs.sender = my_identity;
1986 uhs.receiver = receiver->target;
1987 GNUNET_CRYPTO_ecdhe_key_get_public (&epriv,
1989 uhs.monotonic_time = uc.monotonic_time;
1990 GNUNET_assert (GNUNET_OK ==
1991 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1994 /* Leave space for kx */
1995 dpos = sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
1996 /* Append encrypted uc to dgram */
1998 gcry_cipher_encrypt (out_cipher,
2003 dpos += sizeof (uc);
2004 /* Append encrypted payload to dgram */
2006 gcry_cipher_encrypt (out_cipher,
2014 sizeof (dgram) - dpos);
2015 /* Datagram starts with kx */
2016 kx.ephemeral = uhs.ephemeral;
2018 gcry_cipher_gettag (out_cipher,
2020 sizeof (kx.gcm_tag)));
2021 gcry_cipher_close (out_cipher);
2026 GNUNET_NETWORK_socket_sendto (udp_sock,
2030 receiver->address_len))
2031 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2033 GNUNET_MQ_impl_send_continue (mq);
2035 } /* End of KX encryption method */
2037 /* begin "BOX" encryption method, scan for ACKs from tail! */
2038 for (struct SharedSecret *ss = receiver->ss_tail;
2042 if (ss->sequence_used < ss->sequence_allowed)
2044 char dgram[sizeof (struct UDPBox) + receiver->mtu];
2046 gcry_cipher_hd_t out_cipher;
2049 box = (struct UDPBox *) dgram;
2050 ss->sequence_used++;
2051 get_kid (&ss->master,
2054 setup_cipher (&ss->master,
2057 /* Append encrypted payload to dgram */
2058 dpos = sizeof (struct UDPBox);
2060 gcry_cipher_encrypt (out_cipher,
2068 sizeof (dgram) - dpos);
2070 gcry_cipher_gettag (out_cipher,
2072 sizeof (box->gcm_tag)));
2073 gcry_cipher_close (out_cipher);
2075 GNUNET_NETWORK_socket_sendto (udp_sock,
2079 receiver->address_len))
2080 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2082 GNUNET_MQ_impl_send_continue (mq);
2083 receiver->acks_available--;
2084 if (0 == receiver->acks_available)
2086 /* We have no more ACKs => MTU change! */
2087 setup_receiver_mq (receiver);
2097 * Signature of functions implementing the destruction of a message
2098 * queue. Implementations must not free @a mq, but should take care
2101 * @param mq the message queue to destroy
2102 * @param impl_state our `struct ReceiverAddress`
2105 mq_destroy (struct GNUNET_MQ_Handle *mq,
2108 struct ReceiverAddress *receiver = impl_state;
2110 if (mq == receiver->mq)
2112 receiver->mq = NULL;
2113 receiver_destroy (receiver);
2119 * Implementation function that cancels the currently sent message.
2121 * @param mq message queue
2122 * @param impl_state our `struct RecvierAddress`
2125 mq_cancel (struct GNUNET_MQ_Handle *mq,
2128 /* Cancellation is impossible with UDP; bail */
2134 * Generic error handler, called with the appropriate
2135 * error code and the same closure specified at the creation of
2136 * the message queue.
2137 * Not every message queue implementation supports an error handler.
2139 * @param cls our `struct ReceiverAddress`
2140 * @param error error code
2143 mq_error (void *cls,
2144 enum GNUNET_MQ_Error error)
2146 struct ReceiverAddress *receiver = cls;
2148 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2149 "MQ error in queue to %s: %d\n",
2150 GNUNET_i2s (&receiver->target),
2152 receiver_destroy (receiver);
2157 * Setup the MQ for the @a receiver. If a queue exists,
2158 * the existing one is destroyed. Then the MTU is
2159 * recalculated and a fresh queue is initialized.
2161 * @param receiver receiver to setup MQ for
2164 setup_receiver_mq (struct ReceiverAddress *receiver)
2168 if (NULL != receiver->qh)
2170 GNUNET_TRANSPORT_communicator_mq_del (receiver->qh);
2171 receiver->qh = NULL;
2173 GNUNET_assert (NULL == receiver->mq);
2174 switch (receiver->address->sa_family)
2178 = 1480 /* Ethernet MTU, 1500 - Ethernet header - VLAN tag */
2179 - sizeof (struct GNUNET_TUN_IPv4Header) /* 20 */
2180 - sizeof (struct GNUNET_TUN_UdpHeader) /* 8 */;
2184 = 1280 /* Minimum MTU required by IPv6 */
2185 - sizeof (struct GNUNET_TUN_IPv6Header) /* 40 */
2186 - sizeof (struct GNUNET_TUN_UdpHeader) /* 8 */;
2192 if (0 == receiver->acks_available)
2194 /* MTU based on full KX messages */
2197 - sizeof (struct InitialKX) /* 48 */
2198 - sizeof (struct UDPConfirmation); /* 104 */
2202 /* MTU based on BOXed messages */
2204 = base_mtu - sizeof (struct UDPBox);
2206 /* => Effective MTU for CORE will range from 1080 (IPv6 + KX) to
2207 1404 (IPv4 + Box) bytes, depending on circumstances... */
2209 = GNUNET_MQ_queue_for_callbacks (&mq_send,
2217 = GNUNET_TRANSPORT_communicator_mq_add (ch,
2219 receiver->foreign_addr,
2222 GNUNET_TRANSPORT_CS_OUTBOUND,
2228 * Setup a receiver for transmission. Setup the MQ processing and
2229 * inform transport that the queue is ready.
2233 static struct ReceiverAddress *
2234 receiver_setup (const struct GNUNET_PeerIdentity *target,
2235 const struct sockaddr *address,
2236 socklen_t address_len)
2238 struct ReceiverAddress *receiver;
2240 receiver = GNUNET_new (struct ReceiverAddress);
2241 receiver->address = GNUNET_memdup (address,
2243 receiver->address_len = address_len;
2244 receiver->target = *target;
2245 receiver->nt = GNUNET_NT_scanner_get_type (is,
2248 (void) GNUNET_CONTAINER_multipeermap_put (receivers,
2251 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2253 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2254 receiver->hn = GNUNET_CONTAINER_heap_insert (receivers_heap,
2256 receiver->timeout.abs_value_us);
2257 GNUNET_STATISTICS_set (stats,
2258 "# receivers active",
2259 GNUNET_CONTAINER_multipeermap_size (receivers),
2261 switch (address->sa_family)
2264 GNUNET_asprintf (&receiver->foreign_addr,
2266 COMMUNICATOR_ADDRESS_PREFIX,
2267 GNUNET_a2s (receiver->address,
2268 receiver->address_len));
2271 GNUNET_asprintf (&receiver->foreign_addr,
2273 COMMUNICATOR_ADDRESS_PREFIX,
2274 GNUNET_a2s (receiver->address,
2275 receiver->address_len));
2281 setup_receiver_mq (receiver);
2283 if (NULL == timeout_task)
2284 timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts,
2291 * Function called by the transport service to initialize a
2292 * message queue given address information about another peer.
2293 * If and when the communication channel is established, the
2294 * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
2295 * to notify the service that the channel is now up. It is
2296 * the responsibility of the communicator to manage sane
2297 * retries and timeouts for any @a peer/@a address combination
2298 * provided by the transport service. Timeouts and retries
2299 * do not need to be signalled to the transport service.
2301 * @param cls closure
2302 * @param peer identity of the other peer
2303 * @param address where to send the message, human-readable
2304 * communicator-specific format, 0-terminated, UTF-8
2305 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is invalid
2309 const struct GNUNET_PeerIdentity *peer,
2310 const char *address)
2312 struct ReceiverAddress *receiver;
2314 struct sockaddr *in;
2317 if (0 != strncmp (address,
2318 COMMUNICATOR_ADDRESS_PREFIX "-",
2319 strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
2321 GNUNET_break_op (0);
2322 return GNUNET_SYSERR;
2324 path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
2325 in = udp_address_to_sockaddr (path,
2327 receiver = receiver_setup (peer,
2336 * Iterator over all receivers to clean up.
2339 * @param target unused
2340 * @param value the queue to destroy
2341 * @return #GNUNET_OK to continue to iterate
2344 get_receiver_delete_it (void *cls,
2345 const struct GNUNET_PeerIdentity *target,
2348 struct ReceiverAddress *receiver = value;
2352 receiver_destroy (receiver);
2358 * Iterator over all senders to clean up.
2361 * @param target unused
2362 * @param value the queue to destroy
2363 * @return #GNUNET_OK to continue to iterate
2366 get_sender_delete_it (void *cls,
2367 const struct GNUNET_PeerIdentity *target,
2370 struct SenderAddress *sender = value;
2374 sender_destroy (sender);
2380 * Shutdown the UNIX communicator.
2382 * @param cls NULL (always)
2385 do_shutdown (void *cls)
2389 GNUNET_NAT_unregister (nat);
2392 while (NULL != bi_head)
2393 bi_destroy (bi_head);
2394 if (NULL != broadcast_task)
2396 GNUNET_SCHEDULER_cancel (broadcast_task);
2397 broadcast_task = NULL;
2399 if (NULL != read_task)
2401 GNUNET_SCHEDULER_cancel (read_task);
2404 if (NULL != udp_sock)
2406 GNUNET_break (GNUNET_OK ==
2407 GNUNET_NETWORK_socket_close (udp_sock));
2410 GNUNET_CONTAINER_multipeermap_iterate (receivers,
2411 &get_receiver_delete_it,
2413 GNUNET_CONTAINER_multipeermap_destroy (receivers);
2414 GNUNET_CONTAINER_multipeermap_iterate (senders,
2415 &get_sender_delete_it,
2417 GNUNET_CONTAINER_multipeermap_destroy (senders);
2418 GNUNET_CONTAINER_multishortmap_destroy (key_cache);
2419 GNUNET_CONTAINER_heap_destroy (senders_heap);
2420 GNUNET_CONTAINER_heap_destroy (receivers_heap);
2423 GNUNET_TRANSPORT_communicator_disconnect (ch);
2428 GNUNET_STATISTICS_destroy (stats,
2432 if (NULL != my_private_key)
2434 GNUNET_free (my_private_key);
2435 my_private_key = NULL;
2439 GNUNET_NT_scanner_done (is);
2446 * Function called when the transport service has received a
2447 * backchannel message for this communicator (!) via a different return
2448 * path. Should be an acknowledgement.
2450 * @param cls closure, NULL
2451 * @param sender which peer sent the notification
2452 * @param msg payload
2455 enc_notify_cb (void *cls,
2456 const struct GNUNET_PeerIdentity *sender,
2457 const struct GNUNET_MessageHeader *msg)
2459 const struct UDPAck *ack;
2462 if ( (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK) ||
2463 (ntohs (msg->size) != sizeof (struct UDPAck)) )
2465 GNUNET_break_op (0);
2468 ack = (const struct UDPAck *) msg;
2469 GNUNET_CONTAINER_multipeermap_get_multiple (receivers,
2477 * Signature of the callback passed to #GNUNET_NAT_register() for
2478 * a function to call whenever our set of 'valid' addresses changes.
2480 * @param cls closure
2481 * @param app_ctx[in,out] location where the app can store stuff
2482 * on add and retrieve it on remove
2483 * @param add_remove #GNUNET_YES to add a new public IP address,
2484 * #GNUNET_NO to remove a previous (now invalid) one
2485 * @param ac address class the address belongs to
2486 * @param addr either the previous or the new public IP address
2487 * @param addrlen actual length of the @a addr
2490 nat_address_cb (void *cls,
2493 enum GNUNET_NAT_AddressClass ac,
2494 const struct sockaddr *addr,
2498 struct GNUNET_TRANSPORT_AddressIdentifier *ai;
2500 if (GNUNET_YES == add_remove)
2502 enum GNUNET_NetworkType nt;
2504 GNUNET_asprintf (&my_addr,
2506 COMMUNICATOR_ADDRESS_PREFIX,
2509 nt = GNUNET_NT_scanner_get_type (is,
2512 ai = GNUNET_TRANSPORT_communicator_address_add (ch,
2515 GNUNET_TIME_UNIT_FOREVER_REL);
2516 GNUNET_free (my_addr);
2522 GNUNET_TRANSPORT_communicator_address_remove (ai);
2529 * Broadcast our presence on one of our interfaces.
2531 * @param cls a `struct BroadcastInterface`
2534 ifc_broadcast (void *cls)
2536 struct BroadcastInterface *bi = cls;
2537 struct GNUNET_TIME_Relative delay;
2539 delay = BROADCAST_FREQUENCY;
2540 delay.rel_value_us = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
2541 delay.rel_value_us);
2543 = GNUNET_SCHEDULER_add_delayed (INTERFACE_SCAN_FREQUENCY,
2547 switch (bi->sa->sa_family) {
2555 GNUNET_NETWORK_socket_setsockopt (udp_sock,
2560 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2562 sent = GNUNET_NETWORK_socket_sendto (udp_sock,
2568 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2571 GNUNET_NETWORK_socket_setsockopt (udp_sock,
2576 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2583 struct sockaddr_in6 dst;
2585 dst.sin6_family = AF_INET6;
2586 dst.sin6_port = htons (my_port);
2587 dst.sin6_addr = bi->mcreq.ipv6mr_multiaddr;
2588 dst.sin6_scope_id = ((struct sockaddr_in6*) bi->ba)->sin6_scope_id;
2590 sent = GNUNET_NETWORK_socket_sendto (udp_sock,
2593 (const struct sockaddr *)
2597 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2609 * Callback function invoked for each interface found.
2610 * Activates/deactivates broadcast interfaces.
2613 * @param name name of the interface (can be NULL for unknown)
2614 * @param isDefault is this presumably the default interface
2615 * @param addr address of this interface (can be NULL for unknown or unassigned)
2616 * @param broadcast_addr the broadcast address (can be NULL for unknown or unassigned)
2617 * @param netmask the network mask (can be NULL for unknown or unassigned)
2618 * @param addrlen length of the address
2619 * @return #GNUNET_OK to continue iteration, #GNUNET_SYSERR to abort
2622 iface_proc (void *cls,
2625 const struct sockaddr *addr,
2626 const struct sockaddr *broadcast_addr,
2627 const struct sockaddr *netmask, socklen_t addrlen)
2629 struct BroadcastInterface *bi;
2630 enum GNUNET_NetworkType network;
2631 struct UdpBroadcastSignature ubs;
2635 network = GNUNET_NT_scanner_get_type (is,
2638 if (GNUNET_NT_LOOPBACK == network)
2640 /* Broadcasting on loopback does not make sense */
2644 return GNUNET_YES; /* need to know our address! */
2645 for (bi = bi_head; NULL != bi; bi = bi->next)
2647 if ( (bi->salen == addrlen) &&
2652 bi->found = GNUNET_YES;
2657 if ( (AF_INET6 == addr->sa_family) &&
2658 (NULL == broadcast_addr) )
2659 return GNUNET_OK; /* broadcast_addr is required for IPv6! */
2660 if ( (AF_INET6 == addr->sa_family) &&
2661 (GNUNET_YES != have_v6_socket) )
2662 return GNUNET_OK; /* not using IPv6 */
2664 bi = GNUNET_new (struct BroadcastInterface);
2665 bi->sa = GNUNET_memdup (addr,
2667 if (NULL != broadcast_addr)
2668 bi->ba = GNUNET_memdup (broadcast_addr,
2670 bi->salen = addrlen;
2671 bi->found = GNUNET_YES;
2672 bi->bcm.sender = my_identity;
2673 ubs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
2674 ubs.purpose.size = htonl (sizeof (ubs));
2675 ubs.sender = my_identity;
2676 GNUNET_CRYPTO_hash (addr,
2679 GNUNET_assert (GNUNET_OK ==
2680 GNUNET_CRYPTO_eddsa_sign (my_private_key,
2682 &bi->bcm.sender_sig));
2683 bi->broadcast_task = GNUNET_SCHEDULER_add_now (&ifc_broadcast,
2685 GNUNET_CONTAINER_DLL_insert (bi_head,
2688 if ( (AF_INET6 == addr->sa_family) &&
2689 (NULL != broadcast_addr) )
2691 /* Create IPv6 multicast request */
2692 const struct sockaddr_in6 *s6
2693 = (const struct sockaddr_in6 *) broadcast_addr;
2696 inet_pton (AF_INET6,
2698 &bi->mcreq.ipv6mr_multiaddr));
2700 /* http://tools.ietf.org/html/rfc2553#section-5.2:
2704 * Join a multicast group on a specified local interface. If the
2705 * interface index is specified as 0, the kernel chooses the local
2706 * interface. For example, some kernels look up the multicast
2707 * group in the normal IPv6 routing table and using the resulting
2708 * interface; we do this for each interface, so no need to use
2709 * zero (anymore...).
2711 bi->mcreq.ipv6mr_interface = s6->sin6_scope_id;
2713 /* Join the multicast group */
2715 GNUNET_NETWORK_socket_setsockopt
2720 sizeof (bi->mcreq)))
2722 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2731 * Scan interfaces to broadcast our presence on the LAN.
2733 * @param cls NULL, unused
2736 do_broadcast (void *cls)
2738 struct BroadcastInterface *bin;
2741 for (struct BroadcastInterface *bi = bi_head;
2744 bi->found = GNUNET_NO;
2745 GNUNET_OS_network_interfaces_list (&iface_proc,
2747 for (struct BroadcastInterface *bi = bi_head;
2752 if (GNUNET_NO == bi->found)
2756 = GNUNET_SCHEDULER_add_delayed (INTERFACE_SCAN_FREQUENCY,
2763 * Setup communicator and launch network interactions.
2765 * @param cls NULL (always)
2766 * @param args remaining command-line arguments
2767 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2768 * @param c configuration
2773 const char *cfgfile,
2774 const struct GNUNET_CONFIGURATION_Handle *c)
2777 struct sockaddr *in;
2779 struct sockaddr_storage in_sto;
2785 GNUNET_CONFIGURATION_get_value_filename (cfg,
2786 COMMUNICATOR_CONFIG_SECTION,
2790 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2791 COMMUNICATOR_CONFIG_SECTION,
2796 in = udp_address_to_sockaddr (bindto,
2800 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2801 "Failed to setup UDP socket address with path `%s'\n",
2803 GNUNET_free (bindto);
2806 udp_sock = GNUNET_NETWORK_socket_create (in->sa_family,
2809 if (NULL == udp_sock)
2811 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
2814 GNUNET_free (bindto);
2817 if (AF_INET6 == in->sa_family)
2818 have_v6_socket = GNUNET_YES;
2820 GNUNET_NETWORK_socket_bind (udp_sock,
2824 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
2827 GNUNET_NETWORK_socket_close (udp_sock);
2830 GNUNET_free (bindto);
2833 /* We might have bound to port 0, allowing the OS to figure it out;
2834 thus, get the real IN-address from the socket */
2835 sto_len = sizeof (in_sto);
2836 if (0 != getsockname (GNUNET_NETWORK_get_fd (udp_sock),
2837 (struct sockaddr *) &in_sto,
2846 GNUNET_free (bindto);
2847 in = (struct sockaddr *) &in_sto;
2849 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2851 GNUNET_a2s ((const struct sockaddr *) &in_sto,
2853 switch (in->sa_family)
2856 my_port = ntohs (((struct sockaddr_in *) in)->sin_port);
2859 my_port = ntohs (((struct sockaddr_in6 *) in)->sin6_port);
2865 stats = GNUNET_STATISTICS_create ("C-UDP",
2867 senders = GNUNET_CONTAINER_multipeermap_create (32,
2869 receivers = GNUNET_CONTAINER_multipeermap_create (32,
2871 senders_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2872 receivers_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2873 key_cache = GNUNET_CONTAINER_multishortmap_create (1024,
2875 GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
2877 is = GNUNET_NT_scanner_init ();
2878 my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
2879 if (NULL == my_private_key)
2881 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2882 _("Transport service is lacking key configuration settings. Exiting.\n"));
2883 GNUNET_SCHEDULER_shutdown ();
2886 GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
2887 &my_identity.public_key);
2889 read_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2893 ch = GNUNET_TRANSPORT_communicator_connect (cfg,
2894 COMMUNICATOR_CONFIG_SECTION,
2895 COMMUNICATOR_ADDRESS_PREFIX,
2896 GNUNET_TRANSPORT_CC_UNRELIABLE,
2904 GNUNET_SCHEDULER_shutdown ();
2907 /* start broadcasting */
2909 GNUNET_CONFIGURATION_get_value_yesno (cfg,
2910 COMMUNICATOR_CONFIG_SECTION,
2911 "DISABLE_BROADCAST"))
2913 broadcast_task = GNUNET_SCHEDULER_add_now (&do_broadcast,
2916 nat = GNUNET_NAT_register (cfg,
2917 COMMUNICATOR_CONFIG_SECTION,
2919 1 /* one address */,
2920 (const struct sockaddr **) &in,
2923 NULL /* FIXME: support reversal: #5529 */,
2924 NULL /* closure */);
2929 * The main function for the UNIX communicator.
2931 * @param argc number of arguments from the command line
2932 * @param argv command line arguments
2933 * @return 0 ok, 1 on error
2939 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2940 GNUNET_GETOPT_OPTION_END
2945 GNUNET_STRINGS_get_utf8_args (argc, argv,
2951 GNUNET_PROGRAM_run (argc, argv,
2952 "gnunet-communicator-udp",
2953 _("GNUnet UDP communicator"),
2957 GNUNET_free ((void*) argv);
2962 /* end of gnunet-communicator-udp.c */