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 * - implement main BOXed sending logic
28 * - figure out what to do with MTU: 1280 for IPv6 is obvious;
29 * what for IPv4? 1500? Also, consider differences in
30 * headers for with/without box: need to give MIN of both
31 * to TNG (as TNG expects a fixed MTU!), or maybe
32 * we create a FRESH MQ while we have available BOXes SQNs?
33 * (otherwise padding will REALLY hurt)
34 * - add and use util/ check for IPv6 availability (#V6)
35 * - consider imposing transmission limits in the absence
36 * of ACKs; or: maybe this should be done at TNG service level?
37 * - handle addresses discovered fro broadcasts (#)
38 * (think: what was the story again on address validation?
39 * where is the API for that!?!)
40 * - support DNS names in BINDTO option (#5528)
41 * - support NAT connection reversal method (#5529)
42 * - support other UDP-specific NAT traversal methods (#)
45 #include "gnunet_util_lib.h"
46 #include "gnunet_protocols.h"
47 #include "gnunet_signatures.h"
48 #include "gnunet_constants.h"
49 #include "gnunet_nt_lib.h"
50 #include "gnunet_nat_service.h"
51 #include "gnunet_statistics_service.h"
52 #include "gnunet_transport_communication_service.h"
55 * How often do we rekey based on time (at least)
57 #define REKEY_TIME_INTERVAL GNUNET_TIME_UNIT_DAYS
60 * How long do we wait until we must have received the initial KX?
62 #define PROTO_QUEUE_TIMEOUT GNUNET_TIME_UNIT_MINUTES
65 * How often do we broadcast our presence on the LAN?
67 #define BROADCAST_FREQUENCY GNUNET_TIME_UNIT_MINUTES
70 * How often do we scan for changes to our network interfaces?
72 #define INTERFACE_SCAN_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
77 #define AES_KEY_SIZE (256/8)
82 #define AES_IV_SIZE (96/8)
85 * Size of the GCM tag.
87 #define GCM_TAG_SIZE (128/8)
90 * If we fall below this number of available KCNs,
91 * we generate additional ACKs until we reach
93 * Should be large enough that we don't generate ACKs all
94 * the time and still have enough time for the ACK to
95 * arrive before the sender runs out. So really this
96 * should ideally be based on the RTT.
98 #define KCN_THRESHOLD 92
101 * How many KCNs do we keep around *after* we hit
102 * the #KCN_THRESHOLD? Should be larger than
103 * #KCN_THRESHOLD so we do not generate just one
106 #define KCN_TARGET 128
109 * What is the maximum delta between KCN sequence numbers
110 * that we allow. Used to expire 'ancient' KCNs that likely
111 * were dropped by the network. Must be larger than
112 * KCN_TARGET (otherwise we generate new KCNs all the time),
113 * but not too large (otherwise packet loss may cause
114 * sender to fall back to KX needlessly when sender runs
115 * out of ACK'ed KCNs due to losses).
117 #define MAX_SQN_DELTA 160
120 * How many shared master secrets do we keep around
121 * at most per sender? Should be large enough so
122 * that we generally have a chance of sending an ACK
123 * before the sender already rotated out the master
124 * secret. Generally values around #KCN_TARGET make
125 * sense. Might make sense to adapt to RTT if we had
126 * a good measurement...
128 #define MAX_SECRETS 128
131 * How often do we rekey based on number of bytes transmitted?
132 * (additionally randomized).
134 #define REKEY_MAX_BYTES (1024LLU * 1024 * 1024 * 4LLU)
137 * Address prefix used by the communicator.
140 #define COMMUNICATOR_ADDRESS_PREFIX "udp"
143 * Configuration section used by the communicator.
145 #define COMMUNICATOR_CONFIG_SECTION "communicator-udp"
147 GNUNET_NETWORK_STRUCT_BEGIN
151 * Signature we use to verify that the ephemeral key was really chosen by
152 * the specified sender. If possible, the receiver should respond with
153 * a `struct UDPAck` (possibly via backchannel).
155 struct UdpHandshakeSignature
158 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
160 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
163 * Identity of the inititor of the UDP connection (UDP client).
165 struct GNUNET_PeerIdentity sender;
168 * Presumed identity of the target of the UDP connection (UDP server)
170 struct GNUNET_PeerIdentity receiver;
173 * Ephemeral key used by the @e sender.
175 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
178 * Monotonic time of @e sender, to possibly help detect replay attacks
179 * (if receiver persists times by sender).
181 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
186 * "Plaintext" header at beginning of KX message. Followed
187 * by encrypted `struct UDPConfirmation`.
193 * Ephemeral key for KX.
195 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
198 * HMAC for the following encrypted message, using GCM. HMAC uses
199 * key derived from the handshake with sequence number zero.
201 char gcm_tag[GCM_TAG_SIZE];
207 * Encrypted continuation of UDP initial handshake, followed
208 * by message header with payload.
210 struct UDPConfirmation
215 struct GNUNET_PeerIdentity sender;
218 * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
220 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
223 * Monotonic time of @e sender, to possibly help detect replay attacks
224 * (if receiver persists times by sender).
226 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
228 /* followed by messages */
230 /* padding may follow actual messages */
235 * UDP key acknowledgement. May be sent via backchannel. Allows the
236 * sender to use `struct UDPBox` with the acknowledge key henceforth.
242 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK.
244 struct GNUNET_MessageHeader header;
247 * Sequence acknowledgement limit. Specifies current maximum sequence
248 * number supported by receiver.
250 uint32_t sequence_max GNUNET_PACKED;
253 * CMAC of the base key being acknowledged.
255 struct GNUNET_HashCode cmac;
261 * Signature we use to verify that the broadcast was really made by
262 * the peer that claims to have made it. Basically, affirms that the
263 * peer is really using this IP address (albeit possibly not in _our_
264 * LAN). Makes it difficult for peers in the LAN to claim to
265 * be just any global peer -- an attacker must have at least
266 * shared a LAN with the peer they're pretending to be here.
268 struct UdpBroadcastSignature
271 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
273 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
276 * Identity of the inititor of the UDP broadcast.
278 struct GNUNET_PeerIdentity sender;
281 * Hash of the sender's UDP address.
283 struct GNUNET_HashCode h_address;
288 * Broadcast by peer in LAN announcing its presence. Unusual in that
289 * we don't pad these to full MTU, as we cannot prevent being
290 * recognized in LAN as GNUnet peers if this feature is enabled
291 * anyway. Also, the entire message is in cleartext.
297 * Sender's peer identity.
299 struct GNUNET_PeerIdentity sender;
302 * Sender's signature of type
303 * #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
305 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
311 * UDP message box. Always sent encrypted, only allowed after
312 * the receiver sent a `struct UDPAck` for the base key!
318 * Key and IV identification code. KDF applied to an acknowledged
319 * base key and a sequence number. Sequence numbers must be used
320 * monotonically increasing up to the maximum specified in
321 * `struct UDPAck`. Without further `struct UDPAck`s, the sender
322 * must fall back to sending handshakes!
324 struct GNUNET_ShortHashCode kid;
327 * 128-bit authentication tag for the following encrypted message,
328 * from GCM. MAC starts at the @e body_start that follows and
329 * extends until the end of the UDP payload. If the @e hmac is
330 * wrong, the receiver should check if the message might be a
331 * `struct UdpHandshakeSignature`.
333 char gcm_tag[GCM_TAG_SIZE];
338 GNUNET_NETWORK_STRUCT_END
341 * Shared secret we generated for a particular sender or receiver.
347 * Pre-generated "kid" code (key and IV identification code) to
348 * quickly derive master key for a `struct UDPBox`.
356 struct KeyCacheEntry *next;
361 struct KeyCacheEntry *prev;
364 * Key and IV identification code. KDF applied to an acknowledged
365 * base key and a sequence number. Sequence numbers must be used
366 * monotonically increasing up to the maximum specified in
367 * `struct UDPAck`. Without further `struct UDPAck`s, the sender
368 * must fall back to sending handshakes!
370 struct GNUNET_ShortHashCode kid;
373 * Corresponding shared secret.
375 struct SharedSecret *ss;
378 * Sequence number used to derive this entry from master key.
380 uint32_t sequence_number;
385 * Information we track per sender address we have recently been
386 * in contact with (decryption from sender).
388 struct SenderAddress;
391 * Information we track per receiving address we have recently been
392 * in contact with (encryption to receiver).
394 struct ReceiverAddress;
397 * Shared secret we generated for a particular sender or receiver.
404 struct SharedSecret *next;
409 struct SharedSecret *prev;
412 * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
414 struct KeyCacheEntry *kce_head;
417 * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
419 struct KeyCacheEntry *kce_tail;
422 * Sender we use this shared secret with, or NULL.
424 struct SenderAddress *sender;
427 * Receiver we use this shared secret with, or NULL.
429 struct ReceiverAddress *receiver;
432 * Master shared secret.
434 struct GNUNET_HashCode master;
437 * CMAC is used to identify @e master in ACKs.
439 struct GNUNET_HashCode cmac;
442 * Up to which sequence number did we use this @e master already?
443 * (for encrypting only)
445 uint32_t sequence_used;
448 * Up to which sequence number did the other peer allow us to use
449 * this key, or up to which number did we allow the other peer to
452 uint32_t sequence_allowed;
455 * Number of active KCN entries.
457 unsigned int active_kce_count;
462 * Information we track per sender address we have recently been
463 * in contact with (we decrypt messages from the sender).
469 * To whom are we talking to.
471 struct GNUNET_PeerIdentity target;
474 * Entry in sender expiration heap.
476 struct GNUNET_CONTAINER_HeapNode *hn;
479 * Shared secrets we used with @e target, first used is head.
481 struct SharedSecret *ss_head;
484 * Shared secrets we used with @e target, last used is tail.
486 struct SharedSecret *ss_tail;
489 * Address of the other peer.
491 struct sockaddr *address;
494 * Length of the address.
496 socklen_t address_len;
499 * Timeout for this sender.
501 struct GNUNET_TIME_Absolute timeout;
504 * Length of the DLL at @a ss_head.
506 unsigned int num_secrets;
509 * Which network type does this queue use?
511 enum GNUNET_NetworkType nt;
517 * Information we track per receiving address we have recently been
518 * in contact with (encryption to receiver).
520 struct ReceiverAddress
524 * To whom are we talking to.
526 struct GNUNET_PeerIdentity target;
529 * Shared secrets we received from @e target, first used is head.
531 struct SharedSecret *ss_head;
534 * Shared secrets we received with @e target, last used is tail.
536 struct SharedSecret *ss_tail;
539 * Address of the other peer.
541 struct sockaddr *address;
544 * Length of the address.
546 socklen_t address_len;
549 * Entry in sender expiration heap.
551 struct GNUNET_CONTAINER_HeapNode *hn;
554 * Message queue we are providing for the #ch.
556 struct GNUNET_MQ_Handle *mq;
559 * handle for this queue with the #ch.
561 struct GNUNET_TRANSPORT_QueueHandle *qh;
564 * Timeout for this receiver address.
566 struct GNUNET_TIME_Absolute timeout;
569 * MTU we allowed transport for this receiver right now.
574 * Length of the DLL at @a ss_head.
576 unsigned int num_secrets;
579 * Which network type does this queue use?
581 enum GNUNET_NetworkType nt;
587 * Interface we broadcast our presence on.
589 struct BroadcastInterface
595 struct BroadcastInterface *next;
600 struct BroadcastInterface *prev;
603 * Task for this broadcast interface.
605 struct GNUNET_SCHEDULER_Task *broadcast_task;
608 * Sender's address of the interface.
613 * Broadcast address to use on the interface.
618 * Message we broadcast on this interface.
620 struct UDPBroadcast bcm;
623 * If this is an IPv6 interface, this is the request
624 * we use to join/leave the group.
626 struct ipv6_mreq mcreq;
629 * Number of bytes in @e sa.
634 * Was this interface found in the last #iface_proc() scan?
641 * Cache of pre-generated key IDs.
643 static struct GNUNET_CONTAINER_MultiShortmap *key_cache;
648 static struct GNUNET_SCHEDULER_Task *read_task;
653 static struct GNUNET_SCHEDULER_Task *timeout_task;
656 * ID of master broadcast task
658 static struct GNUNET_SCHEDULER_Task *broadcast_task;
661 * For logging statistics.
663 static struct GNUNET_STATISTICS_Handle *stats;
668 static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
671 * Receivers (map from peer identity to `struct ReceiverAddress`)
673 static struct GNUNET_CONTAINER_MultiPeerMap *receivers;
676 * Senders (map from peer identity to `struct SenderAddress`)
678 static struct GNUNET_CONTAINER_MultiPeerMap *senders;
681 * Expiration heap for senders (contains `struct SenderAddress`)
683 static struct GNUNET_CONTAINER_Heap *senders_heap;
686 * Expiration heap for receivers (contains `struct ReceiverAddress`)
688 static struct GNUNET_CONTAINER_Heap *receivers_heap;
691 * Broadcast interface tasks. Kept in a DLL.
693 static struct BroadcastInterface *bi_head;
696 * Broadcast interface tasks. Kept in a DLL.
698 static struct BroadcastInterface *bi_tail;
703 static struct GNUNET_NETWORK_Handle *udp_sock;
706 * #GNUNET_YES if #udp_sock supports IPv6.
708 static int have_v6_socket;
713 static struct GNUNET_PeerIdentity my_identity;
718 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
723 static const struct GNUNET_CONFIGURATION_Handle *cfg;
726 * Network scanner to determine network types.
728 static struct GNUNET_NT_InterfaceScanner *is;
731 * Connection to NAT service.
733 static struct GNUNET_NAT_Handle *nat;
736 * Port number to which we are actually bound.
738 static uint16_t my_port;
742 * An interface went away, stop broadcasting on it.
744 * @param bi entity to close down
747 bi_destroy (struct BroadcastInterface *bi)
749 if (AF_INET6 == bi->sa->sa_family)
751 /* Leave the multicast group */
753 GNUNET_NETWORK_socket_setsockopt
760 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
764 GNUNET_CONTAINER_DLL_remove (bi_head,
767 GNUNET_SCHEDULER_cancel (bi->broadcast_task);
768 GNUNET_free (bi->sa);
769 GNUNET_free_non_null (bi->ba);
775 * Destroys a receiving state due to timeout or shutdown.
777 * @param receiver entity to close down
780 receiver_destroy (struct ReceiverAddress *receiver)
782 struct GNUNET_MQ_Handle *mq;
784 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
785 "Disconnecting receiver for peer `%s'\n",
786 GNUNET_i2s (&receiver->target));
787 if (NULL != (mq = receiver->mq))
790 GNUNET_MQ_destroy (mq);
792 GNUNET_assert (GNUNET_YES ==
793 GNUNET_CONTAINER_multipeermap_remove (receivers,
796 GNUNET_assert (receiver ==
797 GNUNET_CONTAINER_heap_remove_node (receiver->hn));
798 GNUNET_STATISTICS_set (stats,
799 "# receivers active",
800 GNUNET_CONTAINER_multipeermap_size (receivers),
802 GNUNET_free (receiver->address);
803 GNUNET_free (receiver);
808 * Free memory used by key cache entry.
810 * @param kce the key cache entry
813 kce_destroy (struct KeyCacheEntry *kce)
815 struct SharedSecret *ss = kce->ss;
817 ss->active_kce_count--;
818 GNUNET_CONTAINER_DLL_remove (ss->kce_head,
821 GNUNET_assert (GNUNET_YES ==
822 GNUNET_CONTAINER_multishortmap_remove (key_cache,
832 * @param msec master secret for HMAC calculation
833 * @param serial number for the @a smac calculation
834 * @param kid[out] where to write the key ID
837 get_kid (const struct GNUNET_HashCode *msec,
839 struct GNUNET_ShortHashCode *kid)
841 uint32_t sid = htonl (serial);
843 GNUNET_CRYPTO_hkdf (kid,
858 * Setup key cache entry for sequence number @a seq and shared secret @a ss.
860 * @param ss shared secret
861 * @param seq sequence number for the key cache entry
864 kce_generate (struct SharedSecret *ss,
867 struct KeyCacheEntry *kce;
869 GNUNET_assert (0 < seq);
870 kce = GNUNET_new (struct KeyCacheEntry);
872 kce->sequence_number = seq;
873 get_kid (&ss->master,
876 GNUNET_CONTAINER_DLL_insert (ss->kce_head,
879 ss->active_kce_count++;
880 (void) GNUNET_CONTAINER_multishortmap_put (key_cache,
883 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
884 GNUNET_STATISTICS_set (stats,
886 GNUNET_CONTAINER_multishortmap_size (key_cache),
892 * Destroy @a ss and associated key cache entries.
894 * @param ss shared secret to destroy
897 secret_destroy (struct SharedSecret *ss)
899 struct SenderAddress *sender;
900 struct ReceiverAddress *receiver;
901 struct KeyCacheEntry *kce;
903 if (NULL != (sender = ss->sender))
905 GNUNET_CONTAINER_DLL_remove (sender->ss_head,
908 sender->num_secrets--;
910 if (NULL != (receiver = ss->receiver))
912 GNUNET_CONTAINER_DLL_remove (receiver->ss_head,
915 receiver->num_secrets--;
917 while (NULL != (kce = ss->kce_head))
919 GNUNET_STATISTICS_update (stats,
923 GNUNET_STATISTICS_set (stats,
925 GNUNET_CONTAINER_multishortmap_size (key_cache),
932 * Functions with this signature are called whenever we need
933 * to close a sender's state due to timeout.
935 * @param sender entity to close down
938 sender_destroy (struct SenderAddress *sender)
940 GNUNET_assert (GNUNET_YES ==
941 GNUNET_CONTAINER_multipeermap_remove (senders,
944 GNUNET_assert (sender ==
945 GNUNET_CONTAINER_heap_remove_node (sender->hn));
946 GNUNET_STATISTICS_set (stats,
948 GNUNET_CONTAINER_multipeermap_size (senders),
950 GNUNET_free (sender->address);
951 GNUNET_free (sender);
956 * Compute @a key and @a iv.
958 * @param msec master secret for calculation
959 * @param serial number for the @a smac calculation
960 * @param key[out] where to write the decrption key
961 * @param iv[out] where to write the IV
964 get_iv_key (const struct GNUNET_HashCode *msec,
966 char key[AES_KEY_SIZE],
967 char iv[AES_IV_SIZE])
969 uint32_t sid = htonl (serial);
970 char res[AES_KEY_SIZE + AES_IV_SIZE];
972 GNUNET_CRYPTO_hkdf (res,
981 strlen ("UDP-IV-KEY"),
993 * Increment sender timeout due to activity.
995 * @param sender address for which the timeout should be rescheduled
998 reschedule_sender_timeout (struct SenderAddress *sender)
1001 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1002 GNUNET_CONTAINER_heap_update_cost (sender->hn,
1003 sender->timeout.abs_value_us);
1008 * Increment receiver timeout due to activity.
1010 * @param receiver address for which the timeout should be rescheduled
1013 reschedule_receiver_timeout (struct ReceiverAddress *receiver)
1016 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1017 GNUNET_CONTAINER_heap_update_cost (receiver->hn,
1018 receiver->timeout.abs_value_us);
1023 * Task run to check #receiver_heap and #sender_heap for timeouts.
1025 * @param cls unused, NULL
1028 check_timeouts (void *cls)
1030 struct GNUNET_TIME_Relative st;
1031 struct GNUNET_TIME_Relative rt;
1032 struct GNUNET_TIME_Relative delay;
1033 struct ReceiverAddress *receiver;
1034 struct SenderAddress *sender;
1037 timeout_task = NULL;
1038 rt = GNUNET_TIME_UNIT_FOREVER_REL;
1039 while (NULL != (receiver = GNUNET_CONTAINER_heap_peek (receivers_heap)))
1041 rt = GNUNET_TIME_absolute_get_remaining (receiver->timeout);
1042 if (0 != rt.rel_value_us)
1044 receiver_destroy (receiver);
1046 st = GNUNET_TIME_UNIT_FOREVER_REL;
1047 while (NULL != (sender = GNUNET_CONTAINER_heap_peek (senders_heap)))
1049 st = GNUNET_TIME_absolute_get_remaining (receiver->timeout);
1050 if (0 != st.rel_value_us)
1052 sender_destroy (sender);
1054 delay = GNUNET_TIME_relative_min (rt,
1056 if (delay.rel_value_us < GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
1057 timeout_task = GNUNET_SCHEDULER_add_delayed (delay,
1064 * Calcualte cmac from master in @a ss.
1066 * @param ss[in,out] data structure to complete
1069 calculate_cmac (struct SharedSecret *ss)
1071 GNUNET_CRYPTO_hkdf (&ss->cmac,
1078 sizeof (ss->master),
1080 strlen ("UDP-CMAC"),
1086 * We received @a plaintext_len bytes of @a plaintext from a @a sender.
1087 * Pass it on to CORE.
1089 * @param queue the queue that received the plaintext
1090 * @param plaintext the plaintext that was received
1091 * @param plaintext_len number of bytes of plaintext received
1094 pass_plaintext_to_core (struct SenderAddress *sender,
1095 const void *plaintext,
1096 size_t plaintext_len)
1098 const struct GNUNET_MessageHeader *hdr = plaintext;
1100 while (ntohs (hdr->size) < plaintext_len)
1102 GNUNET_STATISTICS_update (stats,
1103 "# bytes given to core",
1106 (void) GNUNET_TRANSPORT_communicator_receive (ch,
1109 NULL /* no flow control possible */,
1111 /* move on to next message, if any */
1112 plaintext_len -= ntohs (hdr->size);
1113 if (plaintext_len < sizeof (*hdr))
1115 hdr = plaintext + ntohs (hdr->size);
1117 GNUNET_STATISTICS_update (stats,
1118 "# bytes padding discarded",
1125 * Setup @a cipher based on shared secret @a msec and
1126 * serial number @a serial.
1128 * @param msec master shared secret
1129 * @param serial serial number of cipher to set up
1130 * @param cipher[out] cipher to initialize
1133 setup_cipher (const struct GNUNET_HashCode *msec,
1135 gcry_cipher_hd_t *cipher)
1137 char key[AES_KEY_SIZE];
1138 char iv[AES_IV_SIZE];
1140 gcry_cipher_open (cipher,
1141 GCRY_CIPHER_AES256 /* low level: go for speed */,
1142 GCRY_CIPHER_MODE_GCM,
1148 gcry_cipher_setkey (*cipher,
1151 gcry_cipher_setiv (*cipher,
1158 * Try to decrypt @a buf using shared secret @a ss and key/iv
1159 * derived using @a serial.
1161 * @param ss shared secret
1162 * @param tag GCM authentication tag
1163 * @param serial serial number to use
1164 * @param in_buf input buffer to decrypt
1165 * @param in_buf_size number of bytes in @a in_buf and available in @a out_buf
1166 * @param out_buf where to write the result
1167 * @return #GNUNET_OK on success
1170 try_decrypt (const struct SharedSecret *ss,
1171 const char tag[GCM_TAG_SIZE],
1177 gcry_cipher_hd_t cipher;
1179 setup_cipher (&ss->master,
1183 gcry_cipher_decrypt (cipher,
1189 gcry_cipher_checktag (cipher,
1193 gcry_cipher_close (cipher);
1194 GNUNET_STATISTICS_update (stats,
1195 "# AEAD authentication failures",
1198 return GNUNET_SYSERR;
1200 gcry_cipher_close (cipher);
1206 * Setup shared secret for decryption.
1208 * @param ephemeral ephemeral key we received from the other peer
1209 * @return new shared secret
1211 static struct SharedSecret *
1212 setup_shared_secret_dec (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1214 struct SharedSecret *ss;
1216 ss = GNUNET_new (struct SharedSecret);
1217 GNUNET_CRYPTO_eddsa_ecdh (my_private_key,
1225 * Setup shared secret for encryption.
1227 * @param ephemeral ephemeral key we are sending to the other peer
1228 * @param receiver[in,out] queue to initialize encryption key for
1229 * @return new shared secret
1231 static struct SharedSecret *
1232 setup_shared_secret_enc (const struct GNUNET_CRYPTO_EcdhePrivateKey *ephemeral,
1233 struct ReceiverAddress *receiver)
1235 struct SharedSecret *ss;
1237 ss = GNUNET_new (struct SharedSecret);
1238 GNUNET_CRYPTO_ecdh_eddsa (ephemeral,
1239 &receiver->target.public_key,
1241 calculate_cmac (ss);
1242 ss->receiver = receiver;
1243 GNUNET_CONTAINER_DLL_insert (receiver->ss_head,
1246 receiver->num_secrets++;
1247 GNUNET_STATISTICS_update (stats,
1256 * We received an ACK for @a pid. Check if it is for
1257 * the receiver in @a value and if so, handle it and
1258 * return #GNUNET_NO. Otherwise, return #GNUNET_YES.
1260 * @param cls a `const struct UDPAck`
1261 * @param pid peer the ACK is from
1262 * @param value a `struct ReceiverAddress`
1263 * @return #GNUNET_YES to continue to iterate
1266 handle_ack (void *cls,
1267 const struct GNUNET_PeerIdentity *pid,
1270 const struct UDPAck *ack = cls;
1271 struct ReceiverAddress *receiver = value;
1274 for (struct SharedSecret *ss = receiver->ss_head;
1278 if (0 == memcmp (&ack->cmac,
1280 sizeof (struct GNUNET_HashCode)))
1282 ss->sequence_allowed = GNUNET_MAX (ss->sequence_allowed,
1283 ntohl (ack->sequence_max));
1284 /* move ss to head to avoid discarding it anytime soon! */
1285 GNUNET_CONTAINER_DLL_remove (receiver->ss_head,
1288 GNUNET_CONTAINER_DLL_insert (receiver->ss_head,
1291 /* FIXME: if this changed sequence_allowed,
1292 update MTU / MQ of 'receiver'! */
1301 * Test if we have received a valid message in plaintext.
1304 * @param sender peer to process inbound plaintext for
1305 * @param buf buffer we received
1306 * @param buf_size number of bytes in @a buf
1309 try_handle_plaintext (struct SenderAddress *sender,
1313 const struct GNUNET_MessageHeader *hdr
1314 = (const struct GNUNET_MessageHeader *) buf;
1315 const struct UDPAck *ack
1316 = (const struct UDPAck *) buf;
1319 if (sizeof (*hdr) > buf_size)
1320 return; /* not even a header */
1321 if (ntohs (hdr->size) > buf_size)
1322 return; /* not even a header */
1323 type = ntohs (hdr->type);
1326 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK:
1327 /* lookup master secret by 'cmac', then update sequence_max */
1328 GNUNET_CONTAINER_multipeermap_get_multiple (receivers,
1332 /* There could be more messages after the ACK, handle those as well */
1333 buf += ntohs (hdr->size);
1334 buf_size -= ntohs (hdr->size);
1335 pass_plaintext_to_core (sender,
1339 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD:
1343 pass_plaintext_to_core (sender,
1351 * We established a shared secret with a sender. We should try to send
1352 * the sender an `struct UDPAck` at the next opportunity to allow the
1353 * sender to use @a ss longer (assuming we did not yet already
1356 * @param ss shared secret to generate ACKs for
1359 consider_ss_ack (struct SharedSecret *ss)
1361 GNUNET_assert (NULL != ss->sender);
1362 /* drop ancient KeyCacheEntries */
1363 while ( (NULL != ss->kce_head) &&
1364 (MAX_SQN_DELTA < ss->kce_head->sequence_number - ss->kce_tail->sequence_number) )
1365 kce_destroy (ss->kce_tail);
1366 if (ss->active_kce_count < KCN_THRESHOLD)
1370 while (ss->active_kce_count < KCN_TARGET)
1372 ++ss->sequence_allowed);
1373 ack.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK);
1374 ack.header.size = htons (sizeof (ack));
1375 ack.sequence_max = htonl (ss->sequence_allowed);
1376 ack.cmac = ss->cmac;
1377 GNUNET_TRANSPORT_communicator_notify (ch,
1378 &ss->sender->target,
1379 COMMUNICATOR_ADDRESS_PREFIX,
1386 * We received a @a box with matching @a kce. Decrypt and process it.
1388 * @param box the data we received
1389 * @param box_len number of bytes in @a box
1390 * @param kce key index to decrypt @a box
1393 decrypt_box (const struct UDPBox *box,
1395 struct KeyCacheEntry *kce)
1397 struct SharedSecret *ss = kce->ss;
1398 char out_buf[box_len - sizeof (*box)];
1400 GNUNET_assert (NULL != ss->sender);
1404 kce->sequence_number,
1405 (const char *) &box[1],
1409 GNUNET_STATISTICS_update (stats,
1410 "# Decryption failures with valid KCE",
1417 GNUNET_STATISTICS_update (stats,
1418 "# bytes decrypted with BOX",
1421 try_handle_plaintext (ss->sender,
1424 consider_ss_ack (ss);
1429 * Closure for #find_sender_by_address()
1431 struct SearchContext
1434 * Address we are looking for.
1436 const struct sockaddr *address;
1439 * Number of bytes in @e address.
1441 socklen_t address_len;
1444 * Return value to set if we found a match.
1446 struct SenderAddress *sender;
1451 * Find existing `struct SenderAddress` by matching addresses.
1453 * @param cls a `struct SearchContext`
1454 * @param key ignored, must match already
1455 * @param value a `struct SenderAddress`
1456 * @return #GNUNET_YES if not found (continue to search), #GNUNET_NO if found
1459 find_sender_by_address (void *cls,
1460 const struct GNUNET_PeerIdentity *key,
1463 struct SearchContext *sc = cls;
1464 struct SenderAddress *sender = value;
1466 if ( (sender->address_len == sc->address_len) &&
1467 (0 == memcmp (sender->address,
1469 sender->address_len)) )
1471 sc->sender = sender;
1472 return GNUNET_NO; /* stop iterating! */
1479 * Create sender address for @a target. Note that we
1480 * might already have one, so a fresh one is only allocated
1481 * if one does not yet exist for @a address.
1483 * @param target peer to generate address for
1484 * @param address target address
1485 * @param address_len number of bytes in @a address
1486 * @return data structure to keep track of key material for
1487 * decrypting data from @a target
1489 static struct SenderAddress *
1490 setup_sender (const struct GNUNET_PeerIdentity *target,
1491 const struct sockaddr *address,
1492 socklen_t address_len)
1494 struct SenderAddress *sender;
1495 struct SearchContext sc = {
1497 .address_len = address_len,
1501 GNUNET_CONTAINER_multipeermap_get_multiple (senders,
1503 &find_sender_by_address,
1505 if (NULL != sc.sender)
1507 reschedule_sender_timeout (sc.sender);
1510 sender = GNUNET_new (struct SenderAddress);
1511 sender->target = *target;
1512 sender->address = GNUNET_memdup (address,
1514 sender->address_len = address_len;
1515 (void) GNUNET_CONTAINER_multipeermap_put (senders,
1518 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1519 GNUNET_STATISTICS_set (stats,
1521 GNUNET_CONTAINER_multipeermap_size (receivers),
1524 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1525 sender->hn = GNUNET_CONTAINER_heap_insert (senders_heap,
1527 sender->timeout.abs_value_us);
1528 sender->nt = GNUNET_NT_scanner_get_type (is,
1531 if (NULL == timeout_task)
1532 timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts,
1539 * Check signature from @a uc against @a ephemeral.
1541 * @param ephermal key that is signed
1542 * @param uc signature of claimant
1543 * @return #GNUNET_OK if signature is valid
1546 verify_confirmation (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral,
1547 const struct UDPConfirmation *uc)
1549 struct UdpHandshakeSignature uhs;
1551 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
1552 uhs.purpose.size = htonl (sizeof (uhs));
1553 uhs.sender = uc->sender;
1554 uhs.receiver = my_identity;
1555 uhs.ephemeral = *ephemeral;
1556 uhs.monotonic_time = uc->monotonic_time;
1557 return GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE,
1560 &uc->sender.public_key);
1570 sock_read (void *cls)
1572 struct sockaddr_storage sa;
1573 socklen_t salen = sizeof (sa);
1574 char buf[UINT16_MAX];
1579 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1583 rcvd = GNUNET_NETWORK_socket_recvfrom (udp_sock,
1586 (struct sockaddr *) &sa,
1590 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1595 /* first, see if it is a UDPBox */
1596 if (rcvd > sizeof (struct UDPBox))
1598 const struct UDPBox *box;
1599 struct KeyCacheEntry *kce;
1601 box = (const struct UDPBox *) buf;
1602 kce = GNUNET_CONTAINER_multishortmap_get (key_cache,
1613 /* next, check if it is a broadcast */
1614 if (sizeof (struct UDPBroadcast) == rcvd)
1616 const struct UDPBroadcast *ub;
1617 struct UdpBroadcastSignature uhs;
1619 ub = (const struct UDPBroadcast *) buf;
1620 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
1621 uhs.purpose.size = htonl (sizeof (uhs));
1622 uhs.sender = ub->sender;
1623 GNUNET_CRYPTO_hash (&sa,
1627 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST,
1630 &ub->sender.public_key))
1632 GNUNET_STATISTICS_update (stats,
1633 "# broadcasts received",
1636 // FIXME: we effectively just got a HELLO!
1637 // trigger verification NOW!
1640 /* continue with KX, mostly for statistics... */
1644 /* finally, test if it is a KX */
1645 if (rcvd < sizeof (struct UDPConfirmation) + sizeof (struct InitialKX))
1647 GNUNET_STATISTICS_update (stats,
1648 "# messages dropped (no kid, too small for KX)",
1655 const struct InitialKX *kx;
1656 struct SharedSecret *ss;
1657 char pbuf[rcvd - sizeof (struct InitialKX)];
1658 const struct UDPConfirmation *uc;
1659 struct SenderAddress *sender;
1661 kx = (const struct InitialKX *) buf;
1662 ss = setup_shared_secret_dec (&kx->ephemeral);
1672 GNUNET_STATISTICS_update (stats,
1673 "# messages dropped (no kid, AEAD decryption failed)",
1678 uc = (const struct UDPConfirmation *) pbuf;
1680 verify_confirmation (&kx->ephemeral,
1683 GNUNET_break_op (0);
1685 GNUNET_STATISTICS_update (stats,
1686 "# messages dropped (sender signature invalid)",
1691 calculate_cmac (ss);
1692 sender = setup_sender (&uc->sender,
1693 (const struct sockaddr *) &sa,
1695 ss->sender = sender;
1696 GNUNET_CONTAINER_DLL_insert (sender->ss_head,
1699 sender->num_secrets++;
1700 GNUNET_STATISTICS_update (stats,
1704 GNUNET_STATISTICS_update (stats,
1705 "# messages decrypted without BOX",
1708 try_handle_plaintext (sender,
1710 sizeof (pbuf) - sizeof (*uc));
1711 consider_ss_ack (ss);
1712 if (sender->num_secrets > MAX_SECRETS)
1713 secret_destroy (sender->ss_tail);
1719 * Convert UDP bind specification to a `struct sockaddr *`
1721 * @param bindto bind specification to convert
1722 * @param[out] sock_len set to the length of the address
1723 * @return converted bindto specification
1725 static struct sockaddr *
1726 udp_address_to_sockaddr (const char *bindto,
1727 socklen_t *sock_len)
1729 struct sockaddr *in;
1735 if (1 == SSCANF (bindto,
1740 /* interpreting value as just a PORT number */
1741 if (port > UINT16_MAX)
1743 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1744 "BINDTO specification `%s' invalid: value too large for port\n",
1748 /* FIXME #V6: add test to util/ for IPv6 availability,
1749 and depending on the result, go directly for v4-only */
1751 GNUNET_CONFIGURATION_get_value_yesno (cfg,
1752 COMMUNICATOR_CONFIG_SECTION,
1755 struct sockaddr_in *i4;
1757 i4 = GNUNET_malloc (sizeof (struct sockaddr_in));
1758 i4->sin_family = AF_INET;
1759 i4->sin_port = htons ((uint16_t) port);
1760 *sock_len = sizeof (struct sockaddr_in);
1761 in = (struct sockaddr *) i4;
1765 struct sockaddr_in6 *i6;
1767 i6 = GNUNET_malloc (sizeof (struct sockaddr_in6));
1768 i6->sin6_family = AF_INET6;
1769 i6->sin6_port = htons ((uint16_t) port);
1770 *sock_len = sizeof (struct sockaddr_in6);
1771 in = (struct sockaddr *) i6;
1775 cp = GNUNET_strdup (bindto);
1776 colon = strrchr (cp, ':');
1779 /* interpet value after colon as port */
1782 if (1 == SSCANF (colon,
1787 /* interpreting value as just a PORT number */
1788 if (port > UINT16_MAX)
1790 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1791 "BINDTO specification `%s' invalid: value too large for port\n",
1799 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1800 "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1808 /* interpret missing port as 0, aka pick any free one */
1813 struct sockaddr_in v4;
1815 if (1 == inet_pton (AF_INET,
1819 v4.sin_port = htons ((uint16_t) port);
1820 in = GNUNET_memdup (&v4,
1822 *sock_len = sizeof (v4);
1829 struct sockaddr_in6 v6;
1833 if ( ('[' == *cp) &&
1834 (']' == cp[strlen (cp)-1]) )
1836 start++; /* skip over '[' */
1837 cp[strlen (cp) -1] = '\0'; /* eat ']' */
1839 if (1 == inet_pton (AF_INET6,
1843 v6.sin6_port = htons ((uint16_t) port);
1844 in = GNUNET_memdup (&v6,
1846 *sock_len = sizeof (v6);
1851 /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1858 * Signature of functions implementing the sending functionality of a
1861 * @param mq the message queue
1862 * @param msg the message to send
1863 * @param impl_state our `struct ReceiverAddress`
1866 mq_send (struct GNUNET_MQ_Handle *mq,
1867 const struct GNUNET_MessageHeader *msg,
1870 struct ReceiverAddress *receiver = impl_state;
1871 uint16_t msize = ntohs (msg->size);
1873 GNUNET_assert (mq == receiver->mq);
1874 if (msize > receiver->mtu)
1877 receiver_destroy (receiver);
1880 reschedule_receiver_timeout (receiver);
1882 // FIXME: add support for BOX encryption method!
1884 /* KX encryption method */
1886 struct UdpHandshakeSignature uhs;
1887 struct UDPConfirmation uc;
1888 struct InitialKX kx;
1889 struct GNUNET_CRYPTO_EcdhePrivateKey epriv;
1890 char dgram[receiver->mtu +
1894 gcry_cipher_hd_t out_cipher;
1895 struct SharedSecret *ss;
1897 /* setup key material */
1898 GNUNET_assert (GNUNET_OK ==
1899 GNUNET_CRYPTO_ecdhe_key_create2 (&epriv));
1901 ss = setup_shared_secret_enc (&epriv,
1903 setup_cipher (&ss->master,
1907 uc.sender = my_identity;
1908 uc.monotonic_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1909 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
1910 uhs.purpose.size = htonl (sizeof (uhs));
1911 uhs.sender = my_identity;
1912 uhs.receiver = receiver->target;
1913 GNUNET_CRYPTO_ecdhe_key_get_public (&epriv,
1915 uhs.monotonic_time = uc.monotonic_time;
1916 GNUNET_assert (GNUNET_OK ==
1917 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1920 /* Leave space for kx */
1921 dpos = sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
1922 /* Append encrypted uc to dgram */
1924 gcry_cipher_encrypt (out_cipher,
1929 dpos += sizeof (uc);
1930 /* Append encrypted payload to dgram */
1932 gcry_cipher_encrypt (out_cipher,
1940 char pad[sizeof (dgram) - dpos];
1942 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
1945 if (sizeof (pad) > sizeof (struct GNUNET_MessageHeader))
1947 struct GNUNET_MessageHeader hdr = {
1948 .size = htons (sizeof (pad)),
1949 .type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD)
1956 gcry_cipher_encrypt (out_cipher,
1963 /* Datagram starts with kx */
1964 kx.ephemeral = uhs.ephemeral;
1966 gcry_cipher_gettag (out_cipher,
1968 sizeof (kx.gcm_tag)));
1969 gcry_cipher_close (out_cipher);
1974 GNUNET_NETWORK_socket_sendto (udp_sock,
1978 receiver->address_len))
1979 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1981 GNUNET_MQ_impl_send_continue (mq);
1982 } /* End of KX encryption method */
1987 * Signature of functions implementing the destruction of a message
1988 * queue. Implementations must not free @a mq, but should take care
1991 * @param mq the message queue to destroy
1992 * @param impl_state our `struct ReceiverAddress`
1995 mq_destroy (struct GNUNET_MQ_Handle *mq,
1998 struct ReceiverAddress *receiver = impl_state;
2000 if (mq == receiver->mq)
2002 receiver->mq = NULL;
2003 receiver_destroy (receiver);
2009 * Implementation function that cancels the currently sent message.
2011 * @param mq message queue
2012 * @param impl_state our `struct RecvierAddress`
2015 mq_cancel (struct GNUNET_MQ_Handle *mq,
2018 /* Cancellation is impossible with UDP; bail */
2024 * Generic error handler, called with the appropriate
2025 * error code and the same closure specified at the creation of
2026 * the message queue.
2027 * Not every message queue implementation supports an error handler.
2029 * @param cls our `struct ReceiverAddress`
2030 * @param error error code
2033 mq_error (void *cls,
2034 enum GNUNET_MQ_Error error)
2036 struct ReceiverAddress *receiver = cls;
2038 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2039 "MQ error in queue to %s: %d\n",
2040 GNUNET_i2s (&receiver->target),
2042 receiver_destroy (receiver);
2047 * Setup a receiver for transmission. Setup the MQ processing and
2048 * inform transport that the queue is ready.
2052 static struct ReceiverAddress *
2053 receiver_setup (const struct GNUNET_PeerIdentity *target,
2054 const struct sockaddr *address,
2055 socklen_t address_len)
2057 struct ReceiverAddress *receiver;
2059 receiver = GNUNET_new (struct ReceiverAddress);
2060 receiver->address = GNUNET_memdup (address,
2062 receiver->address_len = address_len;
2063 receiver->target = *target;
2064 receiver->nt = GNUNET_NT_scanner_get_type (is,
2067 (void) GNUNET_CONTAINER_multipeermap_put (receivers,
2070 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2072 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2073 receiver->hn = GNUNET_CONTAINER_heap_insert (receivers_heap,
2075 receiver->timeout.abs_value_us);
2077 = GNUNET_MQ_queue_for_callbacks (&mq_send,
2084 receiver->mtu = 1200 /* FIXME: MTU OK? */;
2085 if (NULL == timeout_task)
2086 timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts,
2088 GNUNET_STATISTICS_set (stats,
2089 "# receivers active",
2090 GNUNET_CONTAINER_multipeermap_size (receivers),
2095 switch (address->sa_family)
2098 GNUNET_asprintf (&foreign_addr,
2100 COMMUNICATOR_ADDRESS_PREFIX,
2101 GNUNET_a2s (receiver->address,
2102 receiver->address_len));
2105 GNUNET_asprintf (&foreign_addr,
2107 COMMUNICATOR_ADDRESS_PREFIX,
2108 GNUNET_a2s (receiver->address,
2109 receiver->address_len));
2115 = GNUNET_TRANSPORT_communicator_mq_add (ch,
2120 GNUNET_TRANSPORT_CS_OUTBOUND,
2122 GNUNET_free (foreign_addr);
2129 * Function called by the transport service to initialize a
2130 * message queue given address information about another peer.
2131 * If and when the communication channel is established, the
2132 * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
2133 * to notify the service that the channel is now up. It is
2134 * the responsibility of the communicator to manage sane
2135 * retries and timeouts for any @a peer/@a address combination
2136 * provided by the transport service. Timeouts and retries
2137 * do not need to be signalled to the transport service.
2139 * @param cls closure
2140 * @param peer identity of the other peer
2141 * @param address where to send the message, human-readable
2142 * communicator-specific format, 0-terminated, UTF-8
2143 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is invalid
2147 const struct GNUNET_PeerIdentity *peer,
2148 const char *address)
2150 struct ReceiverAddress *receiver;
2152 struct sockaddr *in;
2155 if (0 != strncmp (address,
2156 COMMUNICATOR_ADDRESS_PREFIX "-",
2157 strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
2159 GNUNET_break_op (0);
2160 return GNUNET_SYSERR;
2162 path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
2163 in = udp_address_to_sockaddr (path,
2165 receiver = receiver_setup (peer,
2174 * Iterator over all receivers to clean up.
2177 * @param target unused
2178 * @param value the queue to destroy
2179 * @return #GNUNET_OK to continue to iterate
2182 get_receiver_delete_it (void *cls,
2183 const struct GNUNET_PeerIdentity *target,
2186 struct ReceiverAddress *receiver = value;
2190 receiver_destroy (receiver);
2196 * Iterator over all senders to clean up.
2199 * @param target unused
2200 * @param value the queue to destroy
2201 * @return #GNUNET_OK to continue to iterate
2204 get_sender_delete_it (void *cls,
2205 const struct GNUNET_PeerIdentity *target,
2208 struct SenderAddress *sender = value;
2212 sender_destroy (sender);
2218 * Shutdown the UNIX communicator.
2220 * @param cls NULL (always)
2223 do_shutdown (void *cls)
2227 GNUNET_NAT_unregister (nat);
2230 while (NULL != bi_head)
2231 bi_destroy (bi_head);
2232 if (NULL != broadcast_task)
2234 GNUNET_SCHEDULER_cancel (broadcast_task);
2235 broadcast_task = NULL;
2237 if (NULL != read_task)
2239 GNUNET_SCHEDULER_cancel (read_task);
2242 if (NULL != udp_sock)
2244 GNUNET_break (GNUNET_OK ==
2245 GNUNET_NETWORK_socket_close (udp_sock));
2248 GNUNET_CONTAINER_multipeermap_iterate (receivers,
2249 &get_receiver_delete_it,
2251 GNUNET_CONTAINER_multipeermap_destroy (receivers);
2252 GNUNET_CONTAINER_multipeermap_iterate (senders,
2253 &get_sender_delete_it,
2255 GNUNET_CONTAINER_multipeermap_destroy (senders);
2256 GNUNET_CONTAINER_multishortmap_destroy (key_cache);
2257 GNUNET_CONTAINER_heap_destroy (senders_heap);
2258 GNUNET_CONTAINER_heap_destroy (receivers_heap);
2261 GNUNET_TRANSPORT_communicator_disconnect (ch);
2266 GNUNET_STATISTICS_destroy (stats,
2270 if (NULL != my_private_key)
2272 GNUNET_free (my_private_key);
2273 my_private_key = NULL;
2277 GNUNET_NT_scanner_done (is);
2284 * Function called when the transport service has received a
2285 * backchannel message for this communicator (!) via a different return
2286 * path. Should be an acknowledgement.
2288 * @param cls closure, NULL
2289 * @param sender which peer sent the notification
2290 * @param msg payload
2293 enc_notify_cb (void *cls,
2294 const struct GNUNET_PeerIdentity *sender,
2295 const struct GNUNET_MessageHeader *msg)
2297 const struct UDPAck *ack;
2300 if ( (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK) ||
2301 (ntohs (msg->size) != sizeof (struct UDPAck)) )
2303 GNUNET_break_op (0);
2306 ack = (const struct UDPAck *) msg;
2307 GNUNET_CONTAINER_multipeermap_get_multiple (receivers,
2315 * Signature of the callback passed to #GNUNET_NAT_register() for
2316 * a function to call whenever our set of 'valid' addresses changes.
2318 * @param cls closure
2319 * @param app_ctx[in,out] location where the app can store stuff
2320 * on add and retrieve it on remove
2321 * @param add_remove #GNUNET_YES to add a new public IP address,
2322 * #GNUNET_NO to remove a previous (now invalid) one
2323 * @param ac address class the address belongs to
2324 * @param addr either the previous or the new public IP address
2325 * @param addrlen actual length of the @a addr
2328 nat_address_cb (void *cls,
2331 enum GNUNET_NAT_AddressClass ac,
2332 const struct sockaddr *addr,
2336 struct GNUNET_TRANSPORT_AddressIdentifier *ai;
2338 if (GNUNET_YES == add_remove)
2340 enum GNUNET_NetworkType nt;
2342 GNUNET_asprintf (&my_addr,
2344 COMMUNICATOR_ADDRESS_PREFIX,
2347 nt = GNUNET_NT_scanner_get_type (is,
2350 ai = GNUNET_TRANSPORT_communicator_address_add (ch,
2353 GNUNET_TIME_UNIT_FOREVER_REL);
2354 GNUNET_free (my_addr);
2360 GNUNET_TRANSPORT_communicator_address_remove (ai);
2367 * Broadcast our presence on one of our interfaces.
2369 * @param cls a `struct BroadcastInterface`
2372 ifc_broadcast (void *cls)
2374 struct BroadcastInterface *bi = cls;
2375 struct GNUNET_TIME_Relative delay;
2377 delay = BROADCAST_FREQUENCY;
2378 delay.rel_value_us = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
2379 delay.rel_value_us);
2381 = GNUNET_SCHEDULER_add_delayed (INTERFACE_SCAN_FREQUENCY,
2385 switch (bi->sa->sa_family) {
2393 GNUNET_NETWORK_socket_setsockopt (udp_sock,
2398 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2400 sent = GNUNET_NETWORK_socket_sendto (udp_sock,
2406 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2409 GNUNET_NETWORK_socket_setsockopt (udp_sock,
2414 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2421 struct sockaddr_in6 dst;
2423 dst.sin6_family = AF_INET6;
2424 dst.sin6_port = htons (my_port);
2425 dst.sin6_addr = bi->mcreq.ipv6mr_multiaddr;
2426 dst.sin6_scope_id = ((struct sockaddr_in6*) bi->ba)->sin6_scope_id;
2428 sent = GNUNET_NETWORK_socket_sendto (udp_sock,
2431 (const struct sockaddr *)
2435 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2447 * Callback function invoked for each interface found.
2448 * Activates/deactivates broadcast interfaces.
2451 * @param name name of the interface (can be NULL for unknown)
2452 * @param isDefault is this presumably the default interface
2453 * @param addr address of this interface (can be NULL for unknown or unassigned)
2454 * @param broadcast_addr the broadcast address (can be NULL for unknown or unassigned)
2455 * @param netmask the network mask (can be NULL for unknown or unassigned)
2456 * @param addrlen length of the address
2457 * @return #GNUNET_OK to continue iteration, #GNUNET_SYSERR to abort
2460 iface_proc (void *cls,
2463 const struct sockaddr *addr,
2464 const struct sockaddr *broadcast_addr,
2465 const struct sockaddr *netmask, socklen_t addrlen)
2467 struct BroadcastInterface *bi;
2468 enum GNUNET_NetworkType network;
2469 struct UdpBroadcastSignature ubs;
2473 network = GNUNET_NT_scanner_get_type (is,
2476 if (GNUNET_NT_LOOPBACK == network)
2478 /* Broadcasting on loopback does not make sense */
2482 return GNUNET_YES; /* need to know our address! */
2483 for (bi = bi_head; NULL != bi; bi = bi->next)
2485 if ( (bi->salen == addrlen) &&
2490 bi->found = GNUNET_YES;
2495 if ( (AF_INET6 == addr->sa_family) &&
2496 (NULL == broadcast_addr) )
2497 return GNUNET_OK; /* broadcast_addr is required for IPv6! */
2498 if ( (AF_INET6 == addr->sa_family) &&
2499 (GNUNET_YES != have_v6_socket) )
2500 return GNUNET_OK; /* not using IPv6 */
2502 bi = GNUNET_new (struct BroadcastInterface);
2503 bi->sa = GNUNET_memdup (addr,
2505 if (NULL != broadcast_addr)
2506 bi->ba = GNUNET_memdup (broadcast_addr,
2508 bi->salen = addrlen;
2509 bi->found = GNUNET_YES;
2510 bi->bcm.sender = my_identity;
2511 ubs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
2512 ubs.purpose.size = htonl (sizeof (ubs));
2513 ubs.sender = my_identity;
2514 GNUNET_CRYPTO_hash (addr,
2517 GNUNET_assert (GNUNET_OK ==
2518 GNUNET_CRYPTO_eddsa_sign (my_private_key,
2520 &bi->bcm.sender_sig));
2521 bi->broadcast_task = GNUNET_SCHEDULER_add_now (&ifc_broadcast,
2523 GNUNET_CONTAINER_DLL_insert (bi_head,
2526 if ( (AF_INET6 == addr->sa_family) &&
2527 (NULL != broadcast_addr) )
2529 /* Create IPv6 multicast request */
2530 const struct sockaddr_in6 *s6
2531 = (const struct sockaddr_in6 *) broadcast_addr;
2534 inet_pton (AF_INET6,
2536 &bi->mcreq.ipv6mr_multiaddr));
2538 /* http://tools.ietf.org/html/rfc2553#section-5.2:
2542 * Join a multicast group on a specified local interface. If the
2543 * interface index is specified as 0, the kernel chooses the local
2544 * interface. For example, some kernels look up the multicast
2545 * group in the normal IPv6 routing table and using the resulting
2546 * interface; we do this for each interface, so no need to use
2547 * zero (anymore...).
2549 bi->mcreq.ipv6mr_interface = s6->sin6_scope_id;
2551 /* Join the multicast group */
2553 GNUNET_NETWORK_socket_setsockopt
2558 sizeof (bi->mcreq)))
2560 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2569 * Scan interfaces to broadcast our presence on the LAN.
2571 * @param cls NULL, unused
2574 do_broadcast (void *cls)
2576 struct BroadcastInterface *bin;
2579 for (struct BroadcastInterface *bi = bi_head;
2582 bi->found = GNUNET_NO;
2583 GNUNET_OS_network_interfaces_list (&iface_proc,
2585 for (struct BroadcastInterface *bi = bi_head;
2590 if (GNUNET_NO == bi->found)
2594 = GNUNET_SCHEDULER_add_delayed (INTERFACE_SCAN_FREQUENCY,
2601 * Setup communicator and launch network interactions.
2603 * @param cls NULL (always)
2604 * @param args remaining command-line arguments
2605 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2606 * @param c configuration
2611 const char *cfgfile,
2612 const struct GNUNET_CONFIGURATION_Handle *c)
2615 struct sockaddr *in;
2617 struct sockaddr_storage in_sto;
2623 GNUNET_CONFIGURATION_get_value_filename (cfg,
2624 COMMUNICATOR_CONFIG_SECTION,
2628 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2629 COMMUNICATOR_CONFIG_SECTION,
2634 in = udp_address_to_sockaddr (bindto,
2638 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2639 "Failed to setup UDP socket address with path `%s'\n",
2641 GNUNET_free (bindto);
2644 udp_sock = GNUNET_NETWORK_socket_create (in->sa_family,
2647 if (NULL == udp_sock)
2649 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
2652 GNUNET_free (bindto);
2655 if (AF_INET6 == in->sa_family)
2656 have_v6_socket = GNUNET_YES;
2658 GNUNET_NETWORK_socket_bind (udp_sock,
2662 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
2665 GNUNET_NETWORK_socket_close (udp_sock);
2668 GNUNET_free (bindto);
2671 /* We might have bound to port 0, allowing the OS to figure it out;
2672 thus, get the real IN-address from the socket */
2673 sto_len = sizeof (in_sto);
2674 if (0 != getsockname (GNUNET_NETWORK_get_fd (udp_sock),
2675 (struct sockaddr *) &in_sto,
2684 GNUNET_free (bindto);
2685 in = (struct sockaddr *) &in_sto;
2687 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2689 GNUNET_a2s ((const struct sockaddr *) &in_sto,
2691 switch (in->sa_family)
2694 my_port = ntohs (((struct sockaddr_in *) in)->sin_port);
2697 my_port = ntohs (((struct sockaddr_in6 *) in)->sin6_port);
2703 stats = GNUNET_STATISTICS_create ("C-UDP",
2705 senders = GNUNET_CONTAINER_multipeermap_create (32,
2707 receivers = GNUNET_CONTAINER_multipeermap_create (32,
2709 senders_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2710 receivers_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2711 key_cache = GNUNET_CONTAINER_multishortmap_create (1024,
2713 GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
2715 is = GNUNET_NT_scanner_init ();
2716 my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
2717 if (NULL == my_private_key)
2719 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2720 _("Transport service is lacking key configuration settings. Exiting.\n"));
2721 GNUNET_SCHEDULER_shutdown ();
2724 GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
2725 &my_identity.public_key);
2727 read_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2731 ch = GNUNET_TRANSPORT_communicator_connect (cfg,
2732 COMMUNICATOR_CONFIG_SECTION,
2733 COMMUNICATOR_ADDRESS_PREFIX,
2734 GNUNET_TRANSPORT_CC_UNRELIABLE,
2742 GNUNET_SCHEDULER_shutdown ();
2745 /* start broadcasting */
2747 GNUNET_CONFIGURATION_get_value_yesno (cfg,
2748 COMMUNICATOR_CONFIG_SECTION,
2749 "DISABLE_BROADCAST"))
2751 broadcast_task = GNUNET_SCHEDULER_add_now (&do_broadcast,
2754 nat = GNUNET_NAT_register (cfg,
2755 COMMUNICATOR_CONFIG_SECTION,
2757 1 /* one address */,
2758 (const struct sockaddr **) &in,
2761 NULL /* FIXME: support reversal: #5529 */,
2762 NULL /* closure */);
2767 * The main function for the UNIX communicator.
2769 * @param argc number of arguments from the command line
2770 * @param argv command line arguments
2771 * @return 0 ok, 1 on error
2777 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2778 GNUNET_GETOPT_OPTION_END
2783 GNUNET_STRINGS_get_utf8_args (argc, argv,
2789 GNUNET_PROGRAM_run (argc, argv,
2790 "gnunet-communicator-udp",
2791 _("GNUnet UDP communicator"),
2795 GNUNET_free ((void*) argv);
2800 /* end of gnunet-communicator-udp.c */