2 This file is part of GNUnet
3 Copyright (C) 2010-2014, 2018, 2019 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @file transport/gnunet-communicator-udp.c
23 * @brief Transport plugin using UDP.
24 * @author Christian Grothoff
27 * - consider imposing transmission limits in the absence
28 * of ACKs; or: maybe this should be done at TNG service level?
29 * (at least the receiver might want to enforce limits on
30 * KX/DH operations per sender in here) (#5552)
31 * - overall, we should look more into flow control support
32 * (either in backchannel, or general solution in TNG service)
33 * - handle addresses discovered from broadcasts (#5551)
34 * (think: what was the story again on address validation?
35 * where is the API for that!?!)
36 * - support DNS names in BINDTO option (#5528)
37 * - support NAT connection reversal method (#5529)
38 * - support other UDP-specific NAT traversal methods (#)
41 #include "gnunet_util_lib.h"
42 #include "gnunet_protocols.h"
43 #include "gnunet_signatures.h"
44 #include "gnunet_constants.h"
45 #include "gnunet_nt_lib.h"
46 #include "gnunet_nat_service.h"
47 #include "gnunet_statistics_service.h"
48 #include "gnunet_transport_application_service.h"
49 #include "gnunet_transport_communication_service.h"
52 * How often do we rekey based on time (at least)
54 #define REKEY_TIME_INTERVAL GNUNET_TIME_UNIT_DAYS
57 * How long do we wait until we must have received the initial KX?
59 #define PROTO_QUEUE_TIMEOUT GNUNET_TIME_UNIT_MINUTES
62 * How often do we broadcast our presence on the LAN?
64 #define BROADCAST_FREQUENCY GNUNET_TIME_UNIT_MINUTES
67 * How often do we scan for changes to our network interfaces?
69 #define INTERFACE_SCAN_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
74 #define AES_KEY_SIZE (256/8)
79 #define AES_IV_SIZE (96/8)
82 * Size of the GCM tag.
84 #define GCM_TAG_SIZE (128/8)
87 * If we fall below this number of available KCNs,
88 * we generate additional ACKs until we reach
90 * Should be large enough that we don't generate ACKs all
91 * the time and still have enough time for the ACK to
92 * arrive before the sender runs out. So really this
93 * should ideally be based on the RTT.
95 #define KCN_THRESHOLD 92
98 * How many KCNs do we keep around *after* we hit
99 * the #KCN_THRESHOLD? Should be larger than
100 * #KCN_THRESHOLD so we do not generate just one
103 #define KCN_TARGET 128
106 * What is the maximum delta between KCN sequence numbers
107 * that we allow. Used to expire 'ancient' KCNs that likely
108 * were dropped by the network. Must be larger than
109 * KCN_TARGET (otherwise we generate new KCNs all the time),
110 * but not too large (otherwise packet loss may cause
111 * sender to fall back to KX needlessly when sender runs
112 * out of ACK'ed KCNs due to losses).
114 #define MAX_SQN_DELTA 160
117 * How many shared master secrets do we keep around
118 * at most per sender? Should be large enough so
119 * that we generally have a chance of sending an ACK
120 * before the sender already rotated out the master
121 * secret. Generally values around #KCN_TARGET make
122 * sense. Might make sense to adapt to RTT if we had
123 * a good measurement...
125 #define MAX_SECRETS 128
128 * How often do we rekey based on number of bytes transmitted?
129 * (additionally randomized).
131 #define REKEY_MAX_BYTES (1024LLU * 1024 * 1024 * 4LLU)
134 * Address prefix used by the communicator.
137 #define COMMUNICATOR_ADDRESS_PREFIX "udp"
140 * Configuration section used by the communicator.
142 #define COMMUNICATOR_CONFIG_SECTION "communicator-udp"
144 GNUNET_NETWORK_STRUCT_BEGIN
148 * Signature we use to verify that the ephemeral key was really chosen by
149 * the specified sender. If possible, the receiver should respond with
150 * a `struct UDPAck` (possibly via backchannel).
152 struct UdpHandshakeSignature
155 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
157 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
160 * Identity of the inititor of the UDP connection (UDP client).
162 struct GNUNET_PeerIdentity sender;
165 * Presumed identity of the target of the UDP connection (UDP server)
167 struct GNUNET_PeerIdentity receiver;
170 * Ephemeral key used by the @e sender.
172 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
175 * Monotonic time of @e sender, to possibly help detect replay attacks
176 * (if receiver persists times by sender).
178 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
183 * "Plaintext" header at beginning of KX message. Followed
184 * by encrypted `struct UDPConfirmation`.
190 * Ephemeral key for KX.
192 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
195 * HMAC for the following encrypted message, using GCM. HMAC uses
196 * key derived from the handshake with sequence number zero.
198 char gcm_tag[GCM_TAG_SIZE];
204 * Encrypted continuation of UDP initial handshake, followed
205 * by message header with payload.
207 struct UDPConfirmation
212 struct GNUNET_PeerIdentity sender;
215 * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
217 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
220 * Monotonic time of @e sender, to possibly help detect replay attacks
221 * (if receiver persists times by sender).
223 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
225 /* followed by messages */
227 /* padding may follow actual messages */
232 * UDP key acknowledgement. May be sent via backchannel. Allows the
233 * sender to use `struct UDPBox` with the acknowledge key henceforth.
239 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK.
241 struct GNUNET_MessageHeader header;
244 * Sequence acknowledgement limit. Specifies current maximum sequence
245 * number supported by receiver.
247 uint32_t sequence_max GNUNET_PACKED;
250 * CMAC of the base key being acknowledged.
252 struct GNUNET_HashCode cmac;
258 * Signature we use to verify that the broadcast was really made by
259 * the peer that claims to have made it. Basically, affirms that the
260 * peer is really using this IP address (albeit possibly not in _our_
261 * LAN). Makes it difficult for peers in the LAN to claim to
262 * be just any global peer -- an attacker must have at least
263 * shared a LAN with the peer they're pretending to be here.
265 struct UdpBroadcastSignature
268 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
270 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
273 * Identity of the inititor of the UDP broadcast.
275 struct GNUNET_PeerIdentity sender;
278 * Hash of the sender's UDP address.
280 struct GNUNET_HashCode h_address;
285 * Broadcast by peer in LAN announcing its presence. Unusual in that
286 * we don't pad these to full MTU, as we cannot prevent being
287 * recognized in LAN as GNUnet peers if this feature is enabled
288 * anyway. Also, the entire message is in cleartext.
294 * Sender's peer identity.
296 struct GNUNET_PeerIdentity sender;
299 * Sender's signature of type
300 * #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
302 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
308 * UDP message box. Always sent encrypted, only allowed after
309 * the receiver sent a `struct UDPAck` for the base key!
315 * Key and IV identification code. KDF applied to an acknowledged
316 * base key and a sequence number. Sequence numbers must be used
317 * monotonically increasing up to the maximum specified in
318 * `struct UDPAck`. Without further `struct UDPAck`s, the sender
319 * must fall back to sending handshakes!
321 struct GNUNET_ShortHashCode kid;
324 * 128-bit authentication tag for the following encrypted message,
325 * from GCM. MAC starts at the @e body_start that follows and
326 * extends until the end of the UDP payload. If the @e hmac is
327 * wrong, the receiver should check if the message might be a
328 * `struct UdpHandshakeSignature`.
330 char gcm_tag[GCM_TAG_SIZE];
335 GNUNET_NETWORK_STRUCT_END
338 * Shared secret we generated for a particular sender or receiver.
344 * Pre-generated "kid" code (key and IV identification code) to
345 * quickly derive master key for a `struct UDPBox`.
353 struct KeyCacheEntry *next;
358 struct KeyCacheEntry *prev;
361 * Key and IV identification code. KDF applied to an acknowledged
362 * base key and a sequence number. Sequence numbers must be used
363 * monotonically increasing up to the maximum specified in
364 * `struct UDPAck`. Without further `struct UDPAck`s, the sender
365 * must fall back to sending handshakes!
367 struct GNUNET_ShortHashCode kid;
370 * Corresponding shared secret.
372 struct SharedSecret *ss;
375 * Sequence number used to derive this entry from master key.
377 uint32_t sequence_number;
382 * Information we track per sender address we have recently been
383 * in contact with (decryption from sender).
385 struct SenderAddress;
388 * Information we track per receiving address we have recently been
389 * in contact with (encryption to receiver).
391 struct ReceiverAddress;
394 * Shared secret we generated for a particular sender or receiver.
401 struct SharedSecret *next;
406 struct SharedSecret *prev;
409 * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
411 struct KeyCacheEntry *kce_head;
414 * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
416 struct KeyCacheEntry *kce_tail;
419 * Sender we use this shared secret with, or NULL.
421 struct SenderAddress *sender;
424 * Receiver we use this shared secret with, or NULL.
426 struct ReceiverAddress *receiver;
429 * Master shared secret.
431 struct GNUNET_HashCode master;
434 * CMAC is used to identify @e master in ACKs.
436 struct GNUNET_HashCode cmac;
439 * Up to which sequence number did we use this @e master already?
440 * (for encrypting only)
442 uint32_t sequence_used;
445 * Up to which sequence number did the other peer allow us to use
446 * this key, or up to which number did we allow the other peer to
449 uint32_t sequence_allowed;
452 * Number of active KCN entries.
454 unsigned int active_kce_count;
459 * Information we track per sender address we have recently been
460 * in contact with (we decrypt messages from the sender).
466 * To whom are we talking to.
468 struct GNUNET_PeerIdentity target;
471 * Entry in sender expiration heap.
473 struct GNUNET_CONTAINER_HeapNode *hn;
476 * Shared secrets we used with @e target, first used is head.
478 struct SharedSecret *ss_head;
481 * Shared secrets we used with @e target, last used is tail.
483 struct SharedSecret *ss_tail;
486 * Address of the other peer.
488 struct sockaddr *address;
491 * Length of the address.
493 socklen_t address_len;
496 * Timeout for this sender.
498 struct GNUNET_TIME_Absolute timeout;
501 * Length of the DLL at @a ss_head.
503 unsigned int num_secrets;
506 * Which network type does this queue use?
508 enum GNUNET_NetworkType nt;
514 * Information we track per receiving address we have recently been
515 * in contact with (encryption to receiver).
517 struct ReceiverAddress
521 * To whom are we talking to.
523 struct GNUNET_PeerIdentity target;
526 * Shared secrets we received from @e target, first used is head.
528 struct SharedSecret *ss_head;
531 * Shared secrets we received with @e target, last used is tail.
533 struct SharedSecret *ss_tail;
536 * Address of the receiver in the human-readable format
537 * with the #COMMUNICATOR_ADDRESS_PREFIX.
542 * Address of the other peer.
544 struct sockaddr *address;
547 * Length of the address.
549 socklen_t address_len;
552 * Entry in sender expiration heap.
554 struct GNUNET_CONTAINER_HeapNode *hn;
557 * Message queue we are providing for the #ch.
559 struct GNUNET_MQ_Handle *mq;
562 * handle for this queue with the #ch.
564 struct GNUNET_TRANSPORT_QueueHandle *qh;
567 * Timeout for this receiver address.
569 struct GNUNET_TIME_Absolute timeout;
572 * MTU we allowed transport for this receiver right now.
577 * Length of the DLL at @a ss_head.
579 unsigned int num_secrets;
582 * Number of BOX keys from ACKs we have currently
583 * available for this receiver.
585 unsigned int acks_available;
588 * Which network type does this queue use?
590 enum GNUNET_NetworkType nt;
596 * Interface we broadcast our presence on.
598 struct BroadcastInterface
604 struct BroadcastInterface *next;
609 struct BroadcastInterface *prev;
612 * Task for this broadcast interface.
614 struct GNUNET_SCHEDULER_Task *broadcast_task;
617 * Sender's address of the interface.
622 * Broadcast address to use on the interface.
627 * Message we broadcast on this interface.
629 struct UDPBroadcast bcm;
632 * If this is an IPv6 interface, this is the request
633 * we use to join/leave the group.
635 struct ipv6_mreq mcreq;
638 * Number of bytes in @e sa.
643 * Was this interface found in the last #iface_proc() scan?
650 * Cache of pre-generated key IDs.
652 static struct GNUNET_CONTAINER_MultiShortmap *key_cache;
657 static struct GNUNET_SCHEDULER_Task *read_task;
662 static struct GNUNET_SCHEDULER_Task *timeout_task;
665 * ID of master broadcast task
667 static struct GNUNET_SCHEDULER_Task *broadcast_task;
670 * For logging statistics.
672 static struct GNUNET_STATISTICS_Handle *stats;
677 static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
680 * Receivers (map from peer identity to `struct ReceiverAddress`)
682 static struct GNUNET_CONTAINER_MultiPeerMap *receivers;
685 * Senders (map from peer identity to `struct SenderAddress`)
687 static struct GNUNET_CONTAINER_MultiPeerMap *senders;
690 * Expiration heap for senders (contains `struct SenderAddress`)
692 static struct GNUNET_CONTAINER_Heap *senders_heap;
695 * Expiration heap for receivers (contains `struct ReceiverAddress`)
697 static struct GNUNET_CONTAINER_Heap *receivers_heap;
700 * Broadcast interface tasks. Kept in a DLL.
702 static struct BroadcastInterface *bi_head;
705 * Broadcast interface tasks. Kept in a DLL.
707 static struct BroadcastInterface *bi_tail;
712 static struct GNUNET_NETWORK_Handle *udp_sock;
715 * #GNUNET_YES if #udp_sock supports IPv6.
717 static int have_v6_socket;
722 static struct GNUNET_PeerIdentity my_identity;
727 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
732 static const struct GNUNET_CONFIGURATION_Handle *cfg;
735 * Our handle to report addresses for validation to TRANSPORT.
737 static struct GNUNET_TRANSPORT_ApplicationHandle *ah;
740 * Network scanner to determine network types.
742 static struct GNUNET_NT_InterfaceScanner *is;
745 * Connection to NAT service.
747 static struct GNUNET_NAT_Handle *nat;
750 * Port number to which we are actually bound.
752 static uint16_t my_port;
756 * An interface went away, stop broadcasting on it.
758 * @param bi entity to close down
761 bi_destroy (struct BroadcastInterface *bi)
763 if (AF_INET6 == bi->sa->sa_family)
765 /* Leave the multicast group */
767 GNUNET_NETWORK_socket_setsockopt
774 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
778 GNUNET_CONTAINER_DLL_remove (bi_head,
781 GNUNET_SCHEDULER_cancel (bi->broadcast_task);
782 GNUNET_free (bi->sa);
783 GNUNET_free_non_null (bi->ba);
789 * Destroys a receiving state due to timeout or shutdown.
791 * @param receiver entity to close down
794 receiver_destroy (struct ReceiverAddress *receiver)
796 struct GNUNET_MQ_Handle *mq;
798 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
799 "Disconnecting receiver for peer `%s'\n",
800 GNUNET_i2s (&receiver->target));
801 if (NULL != (mq = receiver->mq))
804 GNUNET_MQ_destroy (mq);
806 if (NULL != receiver->qh)
808 GNUNET_TRANSPORT_communicator_mq_del (receiver->qh);
811 GNUNET_assert (GNUNET_YES ==
812 GNUNET_CONTAINER_multipeermap_remove (receivers,
815 GNUNET_assert (receiver ==
816 GNUNET_CONTAINER_heap_remove_node (receiver->hn));
817 GNUNET_STATISTICS_set (stats,
818 "# receivers active",
819 GNUNET_CONTAINER_multipeermap_size (receivers),
821 GNUNET_free (receiver->address);
822 GNUNET_free (receiver->foreign_addr);
823 GNUNET_free (receiver);
828 * Free memory used by key cache entry.
830 * @param kce the key cache entry
833 kce_destroy (struct KeyCacheEntry *kce)
835 struct SharedSecret *ss = kce->ss;
837 ss->active_kce_count--;
838 GNUNET_CONTAINER_DLL_remove (ss->kce_head,
841 GNUNET_assert (GNUNET_YES ==
842 GNUNET_CONTAINER_multishortmap_remove (key_cache,
852 * @param msec master secret for HMAC calculation
853 * @param serial number for the @a smac calculation
854 * @param kid[out] where to write the key ID
857 get_kid (const struct GNUNET_HashCode *msec,
859 struct GNUNET_ShortHashCode *kid)
861 uint32_t sid = htonl (serial);
863 GNUNET_CRYPTO_hkdf (kid,
878 * Setup key cache entry for sequence number @a seq and shared secret @a ss.
880 * @param ss shared secret
881 * @param seq sequence number for the key cache entry
884 kce_generate (struct SharedSecret *ss,
887 struct KeyCacheEntry *kce;
889 GNUNET_assert (0 < seq);
890 kce = GNUNET_new (struct KeyCacheEntry);
892 kce->sequence_number = seq;
893 get_kid (&ss->master,
896 GNUNET_CONTAINER_DLL_insert (ss->kce_head,
899 ss->active_kce_count++;
900 (void) GNUNET_CONTAINER_multishortmap_put (key_cache,
903 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
904 GNUNET_STATISTICS_set (stats,
906 GNUNET_CONTAINER_multishortmap_size (key_cache),
912 * Destroy @a ss and associated key cache entries.
914 * @param ss shared secret to destroy
917 secret_destroy (struct SharedSecret *ss)
919 struct SenderAddress *sender;
920 struct ReceiverAddress *receiver;
921 struct KeyCacheEntry *kce;
923 if (NULL != (sender = ss->sender))
925 GNUNET_CONTAINER_DLL_remove (sender->ss_head,
928 sender->num_secrets--;
930 if (NULL != (receiver = ss->receiver))
932 GNUNET_CONTAINER_DLL_remove (receiver->ss_head,
935 receiver->num_secrets--;
936 receiver->acks_available
937 -= (ss->sequence_allowed - ss->sequence_used);
939 while (NULL != (kce = ss->kce_head))
941 GNUNET_STATISTICS_update (stats,
945 GNUNET_STATISTICS_set (stats,
947 GNUNET_CONTAINER_multishortmap_size (key_cache),
954 * Functions with this signature are called whenever we need
955 * to close a sender's state due to timeout.
957 * @param sender entity to close down
960 sender_destroy (struct SenderAddress *sender)
962 GNUNET_assert (GNUNET_YES ==
963 GNUNET_CONTAINER_multipeermap_remove (senders,
966 GNUNET_assert (sender ==
967 GNUNET_CONTAINER_heap_remove_node (sender->hn));
968 GNUNET_STATISTICS_set (stats,
970 GNUNET_CONTAINER_multipeermap_size (senders),
972 GNUNET_free (sender->address);
973 GNUNET_free (sender);
978 * Compute @a key and @a iv.
980 * @param msec master secret for calculation
981 * @param serial number for the @a smac calculation
982 * @param key[out] where to write the decrption key
983 * @param iv[out] where to write the IV
986 get_iv_key (const struct GNUNET_HashCode *msec,
988 char key[AES_KEY_SIZE],
989 char iv[AES_IV_SIZE])
991 uint32_t sid = htonl (serial);
992 char res[AES_KEY_SIZE + AES_IV_SIZE];
994 GNUNET_CRYPTO_hkdf (res,
1003 strlen ("UDP-IV-KEY"),
1015 * Increment sender timeout due to activity.
1017 * @param sender address for which the timeout should be rescheduled
1020 reschedule_sender_timeout (struct SenderAddress *sender)
1023 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1024 GNUNET_CONTAINER_heap_update_cost (sender->hn,
1025 sender->timeout.abs_value_us);
1030 * Increment receiver timeout due to activity.
1032 * @param receiver address for which the timeout should be rescheduled
1035 reschedule_receiver_timeout (struct ReceiverAddress *receiver)
1038 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1039 GNUNET_CONTAINER_heap_update_cost (receiver->hn,
1040 receiver->timeout.abs_value_us);
1045 * Task run to check #receiver_heap and #sender_heap for timeouts.
1047 * @param cls unused, NULL
1050 check_timeouts (void *cls)
1052 struct GNUNET_TIME_Relative st;
1053 struct GNUNET_TIME_Relative rt;
1054 struct GNUNET_TIME_Relative delay;
1055 struct ReceiverAddress *receiver;
1056 struct SenderAddress *sender;
1059 timeout_task = NULL;
1060 rt = GNUNET_TIME_UNIT_FOREVER_REL;
1061 while (NULL != (receiver = GNUNET_CONTAINER_heap_peek (receivers_heap)))
1063 rt = GNUNET_TIME_absolute_get_remaining (receiver->timeout);
1064 if (0 != rt.rel_value_us)
1066 receiver_destroy (receiver);
1068 st = GNUNET_TIME_UNIT_FOREVER_REL;
1069 while (NULL != (sender = GNUNET_CONTAINER_heap_peek (senders_heap)))
1071 st = GNUNET_TIME_absolute_get_remaining (receiver->timeout);
1072 if (0 != st.rel_value_us)
1074 sender_destroy (sender);
1076 delay = GNUNET_TIME_relative_min (rt,
1078 if (delay.rel_value_us < GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
1079 timeout_task = GNUNET_SCHEDULER_add_delayed (delay,
1086 * Calcualte cmac from master in @a ss.
1088 * @param ss[in,out] data structure to complete
1091 calculate_cmac (struct SharedSecret *ss)
1093 GNUNET_CRYPTO_hkdf (&ss->cmac,
1100 sizeof (ss->master),
1102 strlen ("UDP-CMAC"),
1108 * We received @a plaintext_len bytes of @a plaintext from a @a sender.
1109 * Pass it on to CORE.
1111 * @param queue the queue that received the plaintext
1112 * @param plaintext the plaintext that was received
1113 * @param plaintext_len number of bytes of plaintext received
1116 pass_plaintext_to_core (struct SenderAddress *sender,
1117 const void *plaintext,
1118 size_t plaintext_len)
1120 const struct GNUNET_MessageHeader *hdr = plaintext;
1122 while (ntohs (hdr->size) < plaintext_len)
1124 GNUNET_STATISTICS_update (stats,
1125 "# bytes given to core",
1128 (void) GNUNET_TRANSPORT_communicator_receive (ch,
1131 NULL /* no flow control possible */,
1133 /* move on to next message, if any */
1134 plaintext_len -= ntohs (hdr->size);
1135 if (plaintext_len < sizeof (*hdr))
1137 hdr = plaintext + ntohs (hdr->size);
1139 GNUNET_STATISTICS_update (stats,
1140 "# bytes padding discarded",
1147 * Setup @a cipher based on shared secret @a msec and
1148 * serial number @a serial.
1150 * @param msec master shared secret
1151 * @param serial serial number of cipher to set up
1152 * @param cipher[out] cipher to initialize
1155 setup_cipher (const struct GNUNET_HashCode *msec,
1157 gcry_cipher_hd_t *cipher)
1159 char key[AES_KEY_SIZE];
1160 char iv[AES_IV_SIZE];
1162 gcry_cipher_open (cipher,
1163 GCRY_CIPHER_AES256 /* low level: go for speed */,
1164 GCRY_CIPHER_MODE_GCM,
1170 gcry_cipher_setkey (*cipher,
1173 gcry_cipher_setiv (*cipher,
1180 * Try to decrypt @a buf using shared secret @a ss and key/iv
1181 * derived using @a serial.
1183 * @param ss shared secret
1184 * @param tag GCM authentication tag
1185 * @param serial serial number to use
1186 * @param in_buf input buffer to decrypt
1187 * @param in_buf_size number of bytes in @a in_buf and available in @a out_buf
1188 * @param out_buf where to write the result
1189 * @return #GNUNET_OK on success
1192 try_decrypt (const struct SharedSecret *ss,
1193 const char tag[GCM_TAG_SIZE],
1199 gcry_cipher_hd_t cipher;
1201 setup_cipher (&ss->master,
1205 gcry_cipher_decrypt (cipher,
1211 gcry_cipher_checktag (cipher,
1215 gcry_cipher_close (cipher);
1216 GNUNET_STATISTICS_update (stats,
1217 "# AEAD authentication failures",
1220 return GNUNET_SYSERR;
1222 gcry_cipher_close (cipher);
1228 * Setup shared secret for decryption.
1230 * @param ephemeral ephemeral key we received from the other peer
1231 * @return new shared secret
1233 static struct SharedSecret *
1234 setup_shared_secret_dec (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1236 struct SharedSecret *ss;
1238 ss = GNUNET_new (struct SharedSecret);
1239 GNUNET_CRYPTO_eddsa_ecdh (my_private_key,
1247 * Setup shared secret for encryption.
1249 * @param ephemeral ephemeral key we are sending to the other peer
1250 * @param receiver[in,out] queue to initialize encryption key for
1251 * @return new shared secret
1253 static struct SharedSecret *
1254 setup_shared_secret_enc (const struct GNUNET_CRYPTO_EcdhePrivateKey *ephemeral,
1255 struct ReceiverAddress *receiver)
1257 struct SharedSecret *ss;
1259 ss = GNUNET_new (struct SharedSecret);
1260 GNUNET_CRYPTO_ecdh_eddsa (ephemeral,
1261 &receiver->target.public_key,
1263 calculate_cmac (ss);
1264 ss->receiver = receiver;
1265 GNUNET_CONTAINER_DLL_insert (receiver->ss_head,
1268 receiver->num_secrets++;
1269 GNUNET_STATISTICS_update (stats,
1278 * Setup the MQ for the @a receiver. If a queue exists,
1279 * the existing one is destroyed. Then the MTU is
1280 * recalculated and a fresh queue is initialized.
1282 * @param receiver receiver to setup MQ for
1285 setup_receiver_mq (struct ReceiverAddress *receiver);
1289 * We received an ACK for @a pid. Check if it is for
1290 * the receiver in @a value and if so, handle it and
1291 * return #GNUNET_NO. Otherwise, return #GNUNET_YES.
1293 * @param cls a `const struct UDPAck`
1294 * @param pid peer the ACK is from
1295 * @param value a `struct ReceiverAddress`
1296 * @return #GNUNET_YES to continue to iterate
1299 handle_ack (void *cls,
1300 const struct GNUNET_PeerIdentity *pid,
1303 const struct UDPAck *ack = cls;
1304 struct ReceiverAddress *receiver = value;
1307 for (struct SharedSecret *ss = receiver->ss_head;
1311 if (0 == memcmp (&ack->cmac,
1313 sizeof (struct GNUNET_HashCode)))
1317 allowed = ntohl (ack->sequence_max);
1319 if (allowed > ss->sequence_allowed)
1321 receiver->acks_available += (allowed - ss->sequence_allowed);
1322 if ((allowed - ss->sequence_allowed)
1323 == receiver->acks_available)
1325 /* we just incremented from zero => MTU change! */
1326 setup_receiver_mq (receiver);
1328 ss->sequence_allowed = allowed;
1329 /* move ss to head to avoid discarding it anytime soon! */
1330 GNUNET_CONTAINER_DLL_remove (receiver->ss_head,
1333 GNUNET_CONTAINER_DLL_insert (receiver->ss_head,
1345 * Test if we have received a valid message in plaintext.
1348 * @param sender peer to process inbound plaintext for
1349 * @param buf buffer we received
1350 * @param buf_size number of bytes in @a buf
1353 try_handle_plaintext (struct SenderAddress *sender,
1357 const struct GNUNET_MessageHeader *hdr
1358 = (const struct GNUNET_MessageHeader *) buf;
1359 const struct UDPAck *ack
1360 = (const struct UDPAck *) buf;
1363 if (sizeof (*hdr) > buf_size)
1364 return; /* not even a header */
1365 if (ntohs (hdr->size) > buf_size)
1366 return; /* not even a header */
1367 type = ntohs (hdr->type);
1370 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK:
1371 /* lookup master secret by 'cmac', then update sequence_max */
1372 GNUNET_CONTAINER_multipeermap_get_multiple (receivers,
1376 /* There could be more messages after the ACK, handle those as well */
1377 buf += ntohs (hdr->size);
1378 buf_size -= ntohs (hdr->size);
1379 pass_plaintext_to_core (sender,
1383 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD:
1387 pass_plaintext_to_core (sender,
1395 * We established a shared secret with a sender. We should try to send
1396 * the sender an `struct UDPAck` at the next opportunity to allow the
1397 * sender to use @a ss longer (assuming we did not yet already
1400 * @param ss shared secret to generate ACKs for
1403 consider_ss_ack (struct SharedSecret *ss)
1405 GNUNET_assert (NULL != ss->sender);
1406 /* drop ancient KeyCacheEntries */
1407 while ( (NULL != ss->kce_head) &&
1408 (MAX_SQN_DELTA < ss->kce_head->sequence_number - ss->kce_tail->sequence_number) )
1409 kce_destroy (ss->kce_tail);
1410 if (ss->active_kce_count < KCN_THRESHOLD)
1414 while (ss->active_kce_count < KCN_TARGET)
1416 ++ss->sequence_allowed);
1417 ack.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK);
1418 ack.header.size = htons (sizeof (ack));
1419 ack.sequence_max = htonl (ss->sequence_allowed);
1420 ack.cmac = ss->cmac;
1421 GNUNET_TRANSPORT_communicator_notify (ch,
1422 &ss->sender->target,
1423 COMMUNICATOR_ADDRESS_PREFIX,
1430 * We received a @a box with matching @a kce. Decrypt and process it.
1432 * @param box the data we received
1433 * @param box_len number of bytes in @a box
1434 * @param kce key index to decrypt @a box
1437 decrypt_box (const struct UDPBox *box,
1439 struct KeyCacheEntry *kce)
1441 struct SharedSecret *ss = kce->ss;
1442 char out_buf[box_len - sizeof (*box)];
1444 GNUNET_assert (NULL != ss->sender);
1448 kce->sequence_number,
1449 (const char *) &box[1],
1453 GNUNET_STATISTICS_update (stats,
1454 "# Decryption failures with valid KCE",
1461 GNUNET_STATISTICS_update (stats,
1462 "# bytes decrypted with BOX",
1465 try_handle_plaintext (ss->sender,
1468 consider_ss_ack (ss);
1473 * Closure for #find_sender_by_address()
1475 struct SearchContext
1478 * Address we are looking for.
1480 const struct sockaddr *address;
1483 * Number of bytes in @e address.
1485 socklen_t address_len;
1488 * Return value to set if we found a match.
1490 struct SenderAddress *sender;
1495 * Find existing `struct SenderAddress` by matching addresses.
1497 * @param cls a `struct SearchContext`
1498 * @param key ignored, must match already
1499 * @param value a `struct SenderAddress`
1500 * @return #GNUNET_YES if not found (continue to search), #GNUNET_NO if found
1503 find_sender_by_address (void *cls,
1504 const struct GNUNET_PeerIdentity *key,
1507 struct SearchContext *sc = cls;
1508 struct SenderAddress *sender = value;
1510 if ( (sender->address_len == sc->address_len) &&
1511 (0 == memcmp (sender->address,
1513 sender->address_len)) )
1515 sc->sender = sender;
1516 return GNUNET_NO; /* stop iterating! */
1523 * Create sender address for @a target. Note that we
1524 * might already have one, so a fresh one is only allocated
1525 * if one does not yet exist for @a address.
1527 * @param target peer to generate address for
1528 * @param address target address
1529 * @param address_len number of bytes in @a address
1530 * @return data structure to keep track of key material for
1531 * decrypting data from @a target
1533 static struct SenderAddress *
1534 setup_sender (const struct GNUNET_PeerIdentity *target,
1535 const struct sockaddr *address,
1536 socklen_t address_len)
1538 struct SenderAddress *sender;
1539 struct SearchContext sc = {
1541 .address_len = address_len,
1545 GNUNET_CONTAINER_multipeermap_get_multiple (senders,
1547 &find_sender_by_address,
1549 if (NULL != sc.sender)
1551 reschedule_sender_timeout (sc.sender);
1554 sender = GNUNET_new (struct SenderAddress);
1555 sender->target = *target;
1556 sender->address = GNUNET_memdup (address,
1558 sender->address_len = address_len;
1559 (void) GNUNET_CONTAINER_multipeermap_put (senders,
1562 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1563 GNUNET_STATISTICS_set (stats,
1565 GNUNET_CONTAINER_multipeermap_size (receivers),
1568 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1569 sender->hn = GNUNET_CONTAINER_heap_insert (senders_heap,
1571 sender->timeout.abs_value_us);
1572 sender->nt = GNUNET_NT_scanner_get_type (is,
1575 if (NULL == timeout_task)
1576 timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts,
1583 * Check signature from @a uc against @a ephemeral.
1585 * @param ephermal key that is signed
1586 * @param uc signature of claimant
1587 * @return #GNUNET_OK if signature is valid
1590 verify_confirmation (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral,
1591 const struct UDPConfirmation *uc)
1593 struct UdpHandshakeSignature uhs;
1595 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
1596 uhs.purpose.size = htonl (sizeof (uhs));
1597 uhs.sender = uc->sender;
1598 uhs.receiver = my_identity;
1599 uhs.ephemeral = *ephemeral;
1600 uhs.monotonic_time = uc->monotonic_time;
1601 return GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE,
1604 &uc->sender.public_key);
1609 * Converts @a address to the address string format used by this
1610 * communicator in HELLOs.
1612 * @param address the address to convert, must be AF_INET or AF_INET6.
1613 * @param address_len number of bytes in @a address
1614 * @return string representation of @a address
1617 sockaddr_to_udpaddr_string (const struct sockaddr *address,
1618 socklen_t address_len)
1622 switch (address->sa_family)
1625 GNUNET_asprintf (&ret,
1627 COMMUNICATOR_ADDRESS_PREFIX,
1628 GNUNET_a2s (address,
1632 GNUNET_asprintf (&ret,
1634 COMMUNICATOR_ADDRESS_PREFIX,
1635 GNUNET_a2s (address,
1651 sock_read (void *cls)
1653 struct sockaddr_storage sa;
1654 socklen_t salen = sizeof (sa);
1655 char buf[UINT16_MAX];
1660 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1664 rcvd = GNUNET_NETWORK_socket_recvfrom (udp_sock,
1667 (struct sockaddr *) &sa,
1671 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1676 /* first, see if it is a UDPBox */
1677 if (rcvd > sizeof (struct UDPBox))
1679 const struct UDPBox *box;
1680 struct KeyCacheEntry *kce;
1682 box = (const struct UDPBox *) buf;
1683 kce = GNUNET_CONTAINER_multishortmap_get (key_cache,
1694 /* next, check if it is a broadcast */
1695 if (sizeof (struct UDPBroadcast) == rcvd)
1697 const struct UDPBroadcast *ub;
1698 struct UdpBroadcastSignature uhs;
1700 ub = (const struct UDPBroadcast *) buf;
1701 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
1702 uhs.purpose.size = htonl (sizeof (uhs));
1703 uhs.sender = ub->sender;
1704 GNUNET_CRYPTO_hash (&sa,
1708 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST,
1711 &ub->sender.public_key))
1714 struct GNUNET_TIME_Absolute expiration;
1715 enum GNUNET_NetworkType nt;
1717 addr_s = sockaddr_to_udpaddr_string ((const struct sockaddr *) &sa,
1719 GNUNET_STATISTICS_update (stats,
1720 "# broadcasts received",
1723 /* expire at the broadcast frequency, as then we'll get the next one anyway */
1724 expiration = GNUNET_TIME_relative_to_absolute (BROADCAST_FREQUENCY);
1725 /* use our own mechanism to determine network type */
1726 nt = GNUNET_NT_scanner_get_type (is,
1727 (const struct sockaddr *) &sa,
1729 GNUNET_TRANSPORT_application_validate (ah,
1734 GNUNET_free (addr_s);
1737 /* continue with KX, mostly for statistics... */
1741 /* finally, test if it is a KX */
1742 if (rcvd < sizeof (struct UDPConfirmation) + sizeof (struct InitialKX))
1744 GNUNET_STATISTICS_update (stats,
1745 "# messages dropped (no kid, too small for KX)",
1752 const struct InitialKX *kx;
1753 struct SharedSecret *ss;
1754 char pbuf[rcvd - sizeof (struct InitialKX)];
1755 const struct UDPConfirmation *uc;
1756 struct SenderAddress *sender;
1758 kx = (const struct InitialKX *) buf;
1759 ss = setup_shared_secret_dec (&kx->ephemeral);
1769 GNUNET_STATISTICS_update (stats,
1770 "# messages dropped (no kid, AEAD decryption failed)",
1775 uc = (const struct UDPConfirmation *) pbuf;
1777 verify_confirmation (&kx->ephemeral,
1780 GNUNET_break_op (0);
1782 GNUNET_STATISTICS_update (stats,
1783 "# messages dropped (sender signature invalid)",
1788 calculate_cmac (ss);
1789 sender = setup_sender (&uc->sender,
1790 (const struct sockaddr *) &sa,
1792 ss->sender = sender;
1793 GNUNET_CONTAINER_DLL_insert (sender->ss_head,
1796 sender->num_secrets++;
1797 GNUNET_STATISTICS_update (stats,
1801 GNUNET_STATISTICS_update (stats,
1802 "# messages decrypted without BOX",
1805 try_handle_plaintext (sender,
1807 sizeof (pbuf) - sizeof (*uc));
1808 consider_ss_ack (ss);
1809 if (sender->num_secrets > MAX_SECRETS)
1810 secret_destroy (sender->ss_tail);
1816 * Convert UDP bind specification to a `struct sockaddr *`
1818 * @param bindto bind specification to convert
1819 * @param[out] sock_len set to the length of the address
1820 * @return converted bindto specification
1822 static struct sockaddr *
1823 udp_address_to_sockaddr (const char *bindto,
1824 socklen_t *sock_len)
1826 struct sockaddr *in;
1832 if (1 == SSCANF (bindto,
1837 /* interpreting value as just a PORT number */
1838 if (port > UINT16_MAX)
1840 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1841 "BINDTO specification `%s' invalid: value too large for port\n",
1846 GNUNET_NETWORK_test_pf (PF_INET6)) ||
1848 GNUNET_CONFIGURATION_get_value_yesno (cfg,
1849 COMMUNICATOR_CONFIG_SECTION,
1852 struct sockaddr_in *i4;
1854 i4 = GNUNET_malloc (sizeof (struct sockaddr_in));
1855 i4->sin_family = AF_INET;
1856 i4->sin_port = htons ((uint16_t) port);
1857 *sock_len = sizeof (struct sockaddr_in);
1858 in = (struct sockaddr *) i4;
1862 struct sockaddr_in6 *i6;
1864 i6 = GNUNET_malloc (sizeof (struct sockaddr_in6));
1865 i6->sin6_family = AF_INET6;
1866 i6->sin6_port = htons ((uint16_t) port);
1867 *sock_len = sizeof (struct sockaddr_in6);
1868 in = (struct sockaddr *) i6;
1872 cp = GNUNET_strdup (bindto);
1873 colon = strrchr (cp, ':');
1876 /* interpet value after colon as port */
1879 if (1 == SSCANF (colon,
1884 /* interpreting value as just a PORT number */
1885 if (port > UINT16_MAX)
1887 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1888 "BINDTO specification `%s' invalid: value too large for port\n",
1896 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1897 "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1905 /* interpret missing port as 0, aka pick any free one */
1910 struct sockaddr_in v4;
1912 if (1 == inet_pton (AF_INET,
1916 v4.sin_port = htons ((uint16_t) port);
1917 in = GNUNET_memdup (&v4,
1919 *sock_len = sizeof (v4);
1926 struct sockaddr_in6 v6;
1930 if ( ('[' == *cp) &&
1931 (']' == cp[strlen (cp)-1]) )
1933 start++; /* skip over '[' */
1934 cp[strlen (cp) -1] = '\0'; /* eat ']' */
1936 if (1 == inet_pton (AF_INET6,
1940 v6.sin6_port = htons ((uint16_t) port);
1941 in = GNUNET_memdup (&v6,
1943 *sock_len = sizeof (v6);
1948 /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1955 * Pad @a dgram by @a pad_size using @a out_cipher.
1957 * @param out_cipher cipher to use
1958 * @param dgram datagram to pad
1959 * @param pad_size number of bytes of padding to append
1962 do_pad (gcry_cipher_hd_t out_cipher,
1968 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
1971 if (sizeof (pad) > sizeof (struct GNUNET_MessageHeader))
1973 struct GNUNET_MessageHeader hdr = {
1974 .size = htons (sizeof (pad)),
1975 .type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD)
1983 gcry_cipher_encrypt (out_cipher,
1992 * Signature of functions implementing the sending functionality of a
1995 * @param mq the message queue
1996 * @param msg the message to send
1997 * @param impl_state our `struct ReceiverAddress`
2000 mq_send (struct GNUNET_MQ_Handle *mq,
2001 const struct GNUNET_MessageHeader *msg,
2004 struct ReceiverAddress *receiver = impl_state;
2005 uint16_t msize = ntohs (msg->size);
2007 GNUNET_assert (mq == receiver->mq);
2008 if (msize > receiver->mtu)
2011 receiver_destroy (receiver);
2014 reschedule_receiver_timeout (receiver);
2016 if (0 == receiver->acks_available)
2018 /* use KX encryption method */
2019 struct UdpHandshakeSignature uhs;
2020 struct UDPConfirmation uc;
2021 struct InitialKX kx;
2022 struct GNUNET_CRYPTO_EcdhePrivateKey epriv;
2023 char dgram[receiver->mtu +
2027 gcry_cipher_hd_t out_cipher;
2028 struct SharedSecret *ss;
2030 /* setup key material */
2031 GNUNET_assert (GNUNET_OK ==
2032 GNUNET_CRYPTO_ecdhe_key_create2 (&epriv));
2034 ss = setup_shared_secret_enc (&epriv,
2036 setup_cipher (&ss->master,
2040 uc.sender = my_identity;
2041 uc.monotonic_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
2042 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
2043 uhs.purpose.size = htonl (sizeof (uhs));
2044 uhs.sender = my_identity;
2045 uhs.receiver = receiver->target;
2046 GNUNET_CRYPTO_ecdhe_key_get_public (&epriv,
2048 uhs.monotonic_time = uc.monotonic_time;
2049 GNUNET_assert (GNUNET_OK ==
2050 GNUNET_CRYPTO_eddsa_sign (my_private_key,
2053 /* Leave space for kx */
2054 dpos = sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
2055 /* Append encrypted uc to dgram */
2057 gcry_cipher_encrypt (out_cipher,
2062 dpos += sizeof (uc);
2063 /* Append encrypted payload to dgram */
2065 gcry_cipher_encrypt (out_cipher,
2073 sizeof (dgram) - dpos);
2074 /* Datagram starts with kx */
2075 kx.ephemeral = uhs.ephemeral;
2077 gcry_cipher_gettag (out_cipher,
2079 sizeof (kx.gcm_tag)));
2080 gcry_cipher_close (out_cipher);
2085 GNUNET_NETWORK_socket_sendto (udp_sock,
2089 receiver->address_len))
2090 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2092 GNUNET_MQ_impl_send_continue (mq);
2094 } /* End of KX encryption method */
2096 /* begin "BOX" encryption method, scan for ACKs from tail! */
2097 for (struct SharedSecret *ss = receiver->ss_tail;
2101 if (ss->sequence_used < ss->sequence_allowed)
2103 char dgram[sizeof (struct UDPBox) + receiver->mtu];
2105 gcry_cipher_hd_t out_cipher;
2108 box = (struct UDPBox *) dgram;
2109 ss->sequence_used++;
2110 get_kid (&ss->master,
2113 setup_cipher (&ss->master,
2116 /* Append encrypted payload to dgram */
2117 dpos = sizeof (struct UDPBox);
2119 gcry_cipher_encrypt (out_cipher,
2127 sizeof (dgram) - dpos);
2129 gcry_cipher_gettag (out_cipher,
2131 sizeof (box->gcm_tag)));
2132 gcry_cipher_close (out_cipher);
2134 GNUNET_NETWORK_socket_sendto (udp_sock,
2138 receiver->address_len))
2139 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2141 GNUNET_MQ_impl_send_continue (mq);
2142 receiver->acks_available--;
2143 if (0 == receiver->acks_available)
2145 /* We have no more ACKs => MTU change! */
2146 setup_receiver_mq (receiver);
2156 * Signature of functions implementing the destruction of a message
2157 * queue. Implementations must not free @a mq, but should take care
2160 * @param mq the message queue to destroy
2161 * @param impl_state our `struct ReceiverAddress`
2164 mq_destroy (struct GNUNET_MQ_Handle *mq,
2167 struct ReceiverAddress *receiver = impl_state;
2169 if (mq == receiver->mq)
2171 receiver->mq = NULL;
2172 receiver_destroy (receiver);
2178 * Implementation function that cancels the currently sent message.
2180 * @param mq message queue
2181 * @param impl_state our `struct RecvierAddress`
2184 mq_cancel (struct GNUNET_MQ_Handle *mq,
2187 /* Cancellation is impossible with UDP; bail */
2193 * Generic error handler, called with the appropriate
2194 * error code and the same closure specified at the creation of
2195 * the message queue.
2196 * Not every message queue implementation supports an error handler.
2198 * @param cls our `struct ReceiverAddress`
2199 * @param error error code
2202 mq_error (void *cls,
2203 enum GNUNET_MQ_Error error)
2205 struct ReceiverAddress *receiver = cls;
2207 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2208 "MQ error in queue to %s: %d\n",
2209 GNUNET_i2s (&receiver->target),
2211 receiver_destroy (receiver);
2216 * Setup the MQ for the @a receiver. If a queue exists,
2217 * the existing one is destroyed. Then the MTU is
2218 * recalculated and a fresh queue is initialized.
2220 * @param receiver receiver to setup MQ for
2223 setup_receiver_mq (struct ReceiverAddress *receiver)
2227 if (NULL != receiver->qh)
2229 GNUNET_TRANSPORT_communicator_mq_del (receiver->qh);
2230 receiver->qh = NULL;
2232 GNUNET_assert (NULL == receiver->mq);
2233 switch (receiver->address->sa_family)
2237 = 1480 /* Ethernet MTU, 1500 - Ethernet header - VLAN tag */
2238 - sizeof (struct GNUNET_TUN_IPv4Header) /* 20 */
2239 - sizeof (struct GNUNET_TUN_UdpHeader) /* 8 */;
2243 = 1280 /* Minimum MTU required by IPv6 */
2244 - sizeof (struct GNUNET_TUN_IPv6Header) /* 40 */
2245 - sizeof (struct GNUNET_TUN_UdpHeader) /* 8 */;
2251 if (0 == receiver->acks_available)
2253 /* MTU based on full KX messages */
2256 - sizeof (struct InitialKX) /* 48 */
2257 - sizeof (struct UDPConfirmation); /* 104 */
2261 /* MTU based on BOXed messages */
2263 = base_mtu - sizeof (struct UDPBox);
2265 /* => Effective MTU for CORE will range from 1080 (IPv6 + KX) to
2266 1404 (IPv4 + Box) bytes, depending on circumstances... */
2268 = GNUNET_MQ_queue_for_callbacks (&mq_send,
2276 = GNUNET_TRANSPORT_communicator_mq_add (ch,
2278 receiver->foreign_addr,
2281 GNUNET_TRANSPORT_CS_OUTBOUND,
2287 * Setup a receiver for transmission. Setup the MQ processing and
2288 * inform transport that the queue is ready.
2292 static struct ReceiverAddress *
2293 receiver_setup (const struct GNUNET_PeerIdentity *target,
2294 const struct sockaddr *address,
2295 socklen_t address_len)
2297 struct ReceiverAddress *receiver;
2299 receiver = GNUNET_new (struct ReceiverAddress);
2300 receiver->address = GNUNET_memdup (address,
2302 receiver->address_len = address_len;
2303 receiver->target = *target;
2304 receiver->nt = GNUNET_NT_scanner_get_type (is,
2307 (void) GNUNET_CONTAINER_multipeermap_put (receivers,
2310 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2312 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2313 receiver->hn = GNUNET_CONTAINER_heap_insert (receivers_heap,
2315 receiver->timeout.abs_value_us);
2316 GNUNET_STATISTICS_set (stats,
2317 "# receivers active",
2318 GNUNET_CONTAINER_multipeermap_size (receivers),
2320 receiver->foreign_addr = sockaddr_to_udpaddr_string (receiver->address,
2321 receiver->address_len);
2322 setup_receiver_mq (receiver);
2324 if (NULL == timeout_task)
2325 timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts,
2332 * Function called by the transport service to initialize a
2333 * message queue given address information about another peer.
2334 * If and when the communication channel is established, the
2335 * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
2336 * to notify the service that the channel is now up. It is
2337 * the responsibility of the communicator to manage sane
2338 * retries and timeouts for any @a peer/@a address combination
2339 * provided by the transport service. Timeouts and retries
2340 * do not need to be signalled to the transport service.
2342 * @param cls closure
2343 * @param peer identity of the other peer
2344 * @param address where to send the message, human-readable
2345 * communicator-specific format, 0-terminated, UTF-8
2346 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is invalid
2350 const struct GNUNET_PeerIdentity *peer,
2351 const char *address)
2353 struct ReceiverAddress *receiver;
2355 struct sockaddr *in;
2358 if (0 != strncmp (address,
2359 COMMUNICATOR_ADDRESS_PREFIX "-",
2360 strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
2362 GNUNET_break_op (0);
2363 return GNUNET_SYSERR;
2365 path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
2366 in = udp_address_to_sockaddr (path,
2368 receiver = receiver_setup (peer,
2377 * Iterator over all receivers to clean up.
2380 * @param target unused
2381 * @param value the queue to destroy
2382 * @return #GNUNET_OK to continue to iterate
2385 get_receiver_delete_it (void *cls,
2386 const struct GNUNET_PeerIdentity *target,
2389 struct ReceiverAddress *receiver = value;
2393 receiver_destroy (receiver);
2399 * Iterator over all senders to clean up.
2402 * @param target unused
2403 * @param value the queue to destroy
2404 * @return #GNUNET_OK to continue to iterate
2407 get_sender_delete_it (void *cls,
2408 const struct GNUNET_PeerIdentity *target,
2411 struct SenderAddress *sender = value;
2415 sender_destroy (sender);
2421 * Shutdown the UNIX communicator.
2423 * @param cls NULL (always)
2426 do_shutdown (void *cls)
2430 GNUNET_NAT_unregister (nat);
2433 while (NULL != bi_head)
2434 bi_destroy (bi_head);
2435 if (NULL != broadcast_task)
2437 GNUNET_SCHEDULER_cancel (broadcast_task);
2438 broadcast_task = NULL;
2440 if (NULL != read_task)
2442 GNUNET_SCHEDULER_cancel (read_task);
2445 if (NULL != udp_sock)
2447 GNUNET_break (GNUNET_OK ==
2448 GNUNET_NETWORK_socket_close (udp_sock));
2451 GNUNET_CONTAINER_multipeermap_iterate (receivers,
2452 &get_receiver_delete_it,
2454 GNUNET_CONTAINER_multipeermap_destroy (receivers);
2455 GNUNET_CONTAINER_multipeermap_iterate (senders,
2456 &get_sender_delete_it,
2458 GNUNET_CONTAINER_multipeermap_destroy (senders);
2459 GNUNET_CONTAINER_multishortmap_destroy (key_cache);
2460 GNUNET_CONTAINER_heap_destroy (senders_heap);
2461 GNUNET_CONTAINER_heap_destroy (receivers_heap);
2464 GNUNET_TRANSPORT_communicator_disconnect (ch);
2469 GNUNET_TRANSPORT_application_done (ah);
2474 GNUNET_STATISTICS_destroy (stats,
2478 if (NULL != my_private_key)
2480 GNUNET_free (my_private_key);
2481 my_private_key = NULL;
2485 GNUNET_NT_scanner_done (is);
2492 * Function called when the transport service has received a
2493 * backchannel message for this communicator (!) via a different return
2494 * path. Should be an acknowledgement.
2496 * @param cls closure, NULL
2497 * @param sender which peer sent the notification
2498 * @param msg payload
2501 enc_notify_cb (void *cls,
2502 const struct GNUNET_PeerIdentity *sender,
2503 const struct GNUNET_MessageHeader *msg)
2505 const struct UDPAck *ack;
2508 if ( (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK) ||
2509 (ntohs (msg->size) != sizeof (struct UDPAck)) )
2511 GNUNET_break_op (0);
2514 ack = (const struct UDPAck *) msg;
2515 GNUNET_CONTAINER_multipeermap_get_multiple (receivers,
2523 * Signature of the callback passed to #GNUNET_NAT_register() for
2524 * a function to call whenever our set of 'valid' addresses changes.
2526 * @param cls closure
2527 * @param app_ctx[in,out] location where the app can store stuff
2528 * on add and retrieve it on remove
2529 * @param add_remove #GNUNET_YES to add a new public IP address,
2530 * #GNUNET_NO to remove a previous (now invalid) one
2531 * @param ac address class the address belongs to
2532 * @param addr either the previous or the new public IP address
2533 * @param addrlen actual length of the @a addr
2536 nat_address_cb (void *cls,
2539 enum GNUNET_NAT_AddressClass ac,
2540 const struct sockaddr *addr,
2544 struct GNUNET_TRANSPORT_AddressIdentifier *ai;
2546 if (GNUNET_YES == add_remove)
2548 enum GNUNET_NetworkType nt;
2550 GNUNET_asprintf (&my_addr,
2552 COMMUNICATOR_ADDRESS_PREFIX,
2555 nt = GNUNET_NT_scanner_get_type (is,
2558 ai = GNUNET_TRANSPORT_communicator_address_add (ch,
2561 GNUNET_TIME_UNIT_FOREVER_REL);
2562 GNUNET_free (my_addr);
2568 GNUNET_TRANSPORT_communicator_address_remove (ai);
2575 * Broadcast our presence on one of our interfaces.
2577 * @param cls a `struct BroadcastInterface`
2580 ifc_broadcast (void *cls)
2582 struct BroadcastInterface *bi = cls;
2583 struct GNUNET_TIME_Relative delay;
2585 delay = BROADCAST_FREQUENCY;
2586 delay.rel_value_us = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
2587 delay.rel_value_us);
2589 = GNUNET_SCHEDULER_add_delayed (INTERFACE_SCAN_FREQUENCY,
2593 switch (bi->sa->sa_family) {
2601 GNUNET_NETWORK_socket_setsockopt (udp_sock,
2606 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2608 sent = GNUNET_NETWORK_socket_sendto (udp_sock,
2614 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2617 GNUNET_NETWORK_socket_setsockopt (udp_sock,
2622 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2629 struct sockaddr_in6 dst;
2631 dst.sin6_family = AF_INET6;
2632 dst.sin6_port = htons (my_port);
2633 dst.sin6_addr = bi->mcreq.ipv6mr_multiaddr;
2634 dst.sin6_scope_id = ((struct sockaddr_in6*) bi->ba)->sin6_scope_id;
2636 sent = GNUNET_NETWORK_socket_sendto (udp_sock,
2639 (const struct sockaddr *)
2643 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2655 * Callback function invoked for each interface found.
2656 * Activates/deactivates broadcast interfaces.
2659 * @param name name of the interface (can be NULL for unknown)
2660 * @param isDefault is this presumably the default interface
2661 * @param addr address of this interface (can be NULL for unknown or unassigned)
2662 * @param broadcast_addr the broadcast address (can be NULL for unknown or unassigned)
2663 * @param netmask the network mask (can be NULL for unknown or unassigned)
2664 * @param addrlen length of the address
2665 * @return #GNUNET_OK to continue iteration, #GNUNET_SYSERR to abort
2668 iface_proc (void *cls,
2671 const struct sockaddr *addr,
2672 const struct sockaddr *broadcast_addr,
2673 const struct sockaddr *netmask, socklen_t addrlen)
2675 struct BroadcastInterface *bi;
2676 enum GNUNET_NetworkType network;
2677 struct UdpBroadcastSignature ubs;
2681 network = GNUNET_NT_scanner_get_type (is,
2684 if (GNUNET_NT_LOOPBACK == network)
2686 /* Broadcasting on loopback does not make sense */
2690 return GNUNET_YES; /* need to know our address! */
2691 for (bi = bi_head; NULL != bi; bi = bi->next)
2693 if ( (bi->salen == addrlen) &&
2698 bi->found = GNUNET_YES;
2703 if ( (AF_INET6 == addr->sa_family) &&
2704 (NULL == broadcast_addr) )
2705 return GNUNET_OK; /* broadcast_addr is required for IPv6! */
2706 if ( (AF_INET6 == addr->sa_family) &&
2707 (GNUNET_YES != have_v6_socket) )
2708 return GNUNET_OK; /* not using IPv6 */
2710 bi = GNUNET_new (struct BroadcastInterface);
2711 bi->sa = GNUNET_memdup (addr,
2713 if (NULL != broadcast_addr)
2714 bi->ba = GNUNET_memdup (broadcast_addr,
2716 bi->salen = addrlen;
2717 bi->found = GNUNET_YES;
2718 bi->bcm.sender = my_identity;
2719 ubs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
2720 ubs.purpose.size = htonl (sizeof (ubs));
2721 ubs.sender = my_identity;
2722 GNUNET_CRYPTO_hash (addr,
2725 GNUNET_assert (GNUNET_OK ==
2726 GNUNET_CRYPTO_eddsa_sign (my_private_key,
2728 &bi->bcm.sender_sig));
2729 bi->broadcast_task = GNUNET_SCHEDULER_add_now (&ifc_broadcast,
2731 GNUNET_CONTAINER_DLL_insert (bi_head,
2734 if ( (AF_INET6 == addr->sa_family) &&
2735 (NULL != broadcast_addr) )
2737 /* Create IPv6 multicast request */
2738 const struct sockaddr_in6 *s6
2739 = (const struct sockaddr_in6 *) broadcast_addr;
2742 inet_pton (AF_INET6,
2744 &bi->mcreq.ipv6mr_multiaddr));
2746 /* http://tools.ietf.org/html/rfc2553#section-5.2:
2750 * Join a multicast group on a specified local interface. If the
2751 * interface index is specified as 0, the kernel chooses the local
2752 * interface. For example, some kernels look up the multicast
2753 * group in the normal IPv6 routing table and using the resulting
2754 * interface; we do this for each interface, so no need to use
2755 * zero (anymore...).
2757 bi->mcreq.ipv6mr_interface = s6->sin6_scope_id;
2759 /* Join the multicast group */
2761 GNUNET_NETWORK_socket_setsockopt
2766 sizeof (bi->mcreq)))
2768 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2777 * Scan interfaces to broadcast our presence on the LAN.
2779 * @param cls NULL, unused
2782 do_broadcast (void *cls)
2784 struct BroadcastInterface *bin;
2787 for (struct BroadcastInterface *bi = bi_head;
2790 bi->found = GNUNET_NO;
2791 GNUNET_OS_network_interfaces_list (&iface_proc,
2793 for (struct BroadcastInterface *bi = bi_head;
2798 if (GNUNET_NO == bi->found)
2802 = GNUNET_SCHEDULER_add_delayed (INTERFACE_SCAN_FREQUENCY,
2809 * Setup communicator and launch network interactions.
2811 * @param cls NULL (always)
2812 * @param args remaining command-line arguments
2813 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2814 * @param c configuration
2819 const char *cfgfile,
2820 const struct GNUNET_CONFIGURATION_Handle *c)
2823 struct sockaddr *in;
2825 struct sockaddr_storage in_sto;
2831 GNUNET_CONFIGURATION_get_value_filename (cfg,
2832 COMMUNICATOR_CONFIG_SECTION,
2836 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2837 COMMUNICATOR_CONFIG_SECTION,
2842 in = udp_address_to_sockaddr (bindto,
2846 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2847 "Failed to setup UDP socket address with path `%s'\n",
2849 GNUNET_free (bindto);
2852 udp_sock = GNUNET_NETWORK_socket_create (in->sa_family,
2855 if (NULL == udp_sock)
2857 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
2860 GNUNET_free (bindto);
2863 if (AF_INET6 == in->sa_family)
2864 have_v6_socket = GNUNET_YES;
2866 GNUNET_NETWORK_socket_bind (udp_sock,
2870 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
2873 GNUNET_NETWORK_socket_close (udp_sock);
2876 GNUNET_free (bindto);
2879 /* We might have bound to port 0, allowing the OS to figure it out;
2880 thus, get the real IN-address from the socket */
2881 sto_len = sizeof (in_sto);
2882 if (0 != getsockname (GNUNET_NETWORK_get_fd (udp_sock),
2883 (struct sockaddr *) &in_sto,
2892 GNUNET_free (bindto);
2893 in = (struct sockaddr *) &in_sto;
2895 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2897 GNUNET_a2s ((const struct sockaddr *) &in_sto,
2899 switch (in->sa_family)
2902 my_port = ntohs (((struct sockaddr_in *) in)->sin_port);
2905 my_port = ntohs (((struct sockaddr_in6 *) in)->sin6_port);
2911 stats = GNUNET_STATISTICS_create ("C-UDP",
2913 senders = GNUNET_CONTAINER_multipeermap_create (32,
2915 receivers = GNUNET_CONTAINER_multipeermap_create (32,
2917 senders_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2918 receivers_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2919 key_cache = GNUNET_CONTAINER_multishortmap_create (1024,
2921 GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
2923 is = GNUNET_NT_scanner_init ();
2924 my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
2925 if (NULL == my_private_key)
2927 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2928 _("Transport service is lacking key configuration settings. Exiting.\n"));
2929 GNUNET_SCHEDULER_shutdown ();
2932 GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
2933 &my_identity.public_key);
2935 read_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2939 ch = GNUNET_TRANSPORT_communicator_connect (cfg,
2940 COMMUNICATOR_CONFIG_SECTION,
2941 COMMUNICATOR_ADDRESS_PREFIX,
2942 GNUNET_TRANSPORT_CC_UNRELIABLE,
2950 GNUNET_SCHEDULER_shutdown ();
2953 ah = GNUNET_TRANSPORT_application_init (cfg);
2957 GNUNET_SCHEDULER_shutdown ();
2960 /* start broadcasting */
2962 GNUNET_CONFIGURATION_get_value_yesno (cfg,
2963 COMMUNICATOR_CONFIG_SECTION,
2964 "DISABLE_BROADCAST"))
2966 broadcast_task = GNUNET_SCHEDULER_add_now (&do_broadcast,
2969 nat = GNUNET_NAT_register (cfg,
2970 COMMUNICATOR_CONFIG_SECTION,
2972 1 /* one address */,
2973 (const struct sockaddr **) &in,
2976 NULL /* FIXME: support reversal: #5529 */,
2977 NULL /* closure */);
2982 * The main function for the UNIX communicator.
2984 * @param argc number of arguments from the command line
2985 * @param argv command line arguments
2986 * @return 0 ok, 1 on error
2992 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2993 GNUNET_GETOPT_OPTION_END
2998 GNUNET_STRINGS_get_utf8_args (argc, argv,
3004 GNUNET_PROGRAM_run (argc, argv,
3005 "gnunet-communicator-udp",
3006 _("GNUnet UDP communicator"),
3010 GNUNET_free ((void*) argv);
3015 /* end of gnunet-communicator-udp.c */