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 \
70 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
73 * How long do we believe our addresses to remain up (before
74 * the other peer should revalidate).
76 #define ADDRESS_VALIDITY_PERIOD GNUNET_TIME_UNIT_HOURS
81 #define AES_KEY_SIZE (256 / 8)
86 #define AES_IV_SIZE (96 / 8)
89 * Size of the GCM tag.
91 #define GCM_TAG_SIZE (128 / 8)
94 * If we fall below this number of available KCNs,
95 * we generate additional ACKs until we reach
97 * Should be large enough that we don't generate ACKs all
98 * the time and still have enough time for the ACK to
99 * arrive before the sender runs out. So really this
100 * should ideally be based on the RTT.
102 #define KCN_THRESHOLD 92
105 * How many KCNs do we keep around *after* we hit
106 * the #KCN_THRESHOLD? Should be larger than
107 * #KCN_THRESHOLD so we do not generate just one
110 #define KCN_TARGET 128
113 * What is the maximum delta between KCN sequence numbers
114 * that we allow. Used to expire 'ancient' KCNs that likely
115 * were dropped by the network. Must be larger than
116 * KCN_TARGET (otherwise we generate new KCNs all the time),
117 * but not too large (otherwise packet loss may cause
118 * sender to fall back to KX needlessly when sender runs
119 * out of ACK'ed KCNs due to losses).
121 #define MAX_SQN_DELTA 160
124 * How many shared master secrets do we keep around
125 * at most per sender? Should be large enough so
126 * that we generally have a chance of sending an ACK
127 * before the sender already rotated out the master
128 * secret. Generally values around #KCN_TARGET make
129 * sense. Might make sense to adapt to RTT if we had
130 * a good measurement...
132 #define MAX_SECRETS 128
135 * How often do we rekey based on number of bytes transmitted?
136 * (additionally randomized).
138 #define REKEY_MAX_BYTES (1024LLU * 1024 * 1024 * 4LLU)
141 * Address prefix used by the communicator.
144 #define COMMUNICATOR_ADDRESS_PREFIX "udp"
147 * Configuration section used by the communicator.
149 #define COMMUNICATOR_CONFIG_SECTION "communicator-udp"
151 GNUNET_NETWORK_STRUCT_BEGIN
155 * Signature we use to verify that the ephemeral key was really chosen by
156 * the specified sender. If possible, the receiver should respond with
157 * a `struct UDPAck` (possibly via backchannel).
159 struct UdpHandshakeSignature
162 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
164 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
167 * Identity of the inititor of the UDP connection (UDP client).
169 struct GNUNET_PeerIdentity sender;
172 * Presumed identity of the target of the UDP connection (UDP server)
174 struct GNUNET_PeerIdentity receiver;
177 * Ephemeral key used by the @e sender.
179 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
182 * Monotonic time of @e sender, to possibly help detect replay attacks
183 * (if receiver persists times by sender).
185 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
190 * "Plaintext" header at beginning of KX message. Followed
191 * by encrypted `struct UDPConfirmation`.
197 * Ephemeral key for KX.
199 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
202 * HMAC for the following encrypted message, using GCM. HMAC uses
203 * key derived from the handshake with sequence number zero.
205 char gcm_tag[GCM_TAG_SIZE];
210 * Encrypted continuation of UDP initial handshake, followed
211 * by message header with payload.
213 struct UDPConfirmation
218 struct GNUNET_PeerIdentity sender;
221 * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
223 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
226 * Monotonic time of @e sender, to possibly help detect replay attacks
227 * (if receiver persists times by sender).
229 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
231 /* followed by messages */
233 /* padding may follow actual messages */
238 * UDP key acknowledgement. May be sent via backchannel. Allows the
239 * sender to use `struct UDPBox` with the acknowledge key henceforth.
245 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK.
247 struct GNUNET_MessageHeader header;
250 * Sequence acknowledgement limit. Specifies current maximum sequence
251 * number supported by receiver.
253 uint32_t sequence_max GNUNET_PACKED;
256 * CMAC of the base key being acknowledged.
258 struct GNUNET_HashCode cmac;
263 * Signature we use to verify that the broadcast was really made by
264 * the peer that claims to have made it. Basically, affirms that the
265 * peer is really using this IP address (albeit possibly not in _our_
266 * LAN). Makes it difficult for peers in the LAN to claim to
267 * be just any global peer -- an attacker must have at least
268 * shared a LAN with the peer they're pretending to be here.
270 struct UdpBroadcastSignature
273 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
275 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
278 * Identity of the inititor of the UDP broadcast.
280 struct GNUNET_PeerIdentity sender;
283 * Hash of the sender's UDP address.
285 struct GNUNET_HashCode h_address;
290 * Broadcast by peer in LAN announcing its presence. Unusual in that
291 * we don't pad these to full MTU, as we cannot prevent being
292 * recognized in LAN as GNUnet peers if this feature is enabled
293 * anyway. Also, the entire message is in cleartext.
299 * Sender's peer identity.
301 struct GNUNET_PeerIdentity sender;
304 * Sender's signature of type
305 * #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
307 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
312 * UDP message box. Always sent encrypted, only allowed after
313 * the receiver sent a `struct UDPAck` for the base key!
319 * Key and IV identification code. KDF applied to an acknowledged
320 * base key and a sequence number. Sequence numbers must be used
321 * monotonically increasing up to the maximum specified in
322 * `struct UDPAck`. Without further `struct UDPAck`s, the sender
323 * must fall back to sending handshakes!
325 struct GNUNET_ShortHashCode kid;
328 * 128-bit authentication tag for the following encrypted message,
329 * from GCM. MAC starts at the @e body_start that follows and
330 * extends until the end of the UDP payload. If the @e hmac is
331 * wrong, the receiver should check if the message might be a
332 * `struct UdpHandshakeSignature`.
334 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;
516 * Information we track per receiving address we have recently been
517 * in contact with (encryption to receiver).
519 struct ReceiverAddress
523 * To whom are we talking to.
525 struct GNUNET_PeerIdentity target;
528 * Shared secrets we received from @e target, first used is head.
530 struct SharedSecret *ss_head;
533 * Shared secrets we received with @e target, last used is tail.
535 struct SharedSecret *ss_tail;
538 * Address of the receiver in the human-readable format
539 * with the #COMMUNICATOR_ADDRESS_PREFIX.
544 * Address of the other peer.
546 struct sockaddr *address;
549 * Length of the address.
551 socklen_t address_len;
554 * Entry in sender expiration heap.
556 struct GNUNET_CONTAINER_HeapNode *hn;
559 * Message queue we are providing for the #ch.
561 struct GNUNET_MQ_Handle *mq;
564 * handle for this queue with the #ch.
566 struct GNUNET_TRANSPORT_QueueHandle *qh;
569 * Timeout for this receiver address.
571 struct GNUNET_TIME_Absolute timeout;
574 * MTU we allowed transport for this receiver right now.
579 * Length of the DLL at @a ss_head.
581 unsigned int num_secrets;
584 * Number of BOX keys from ACKs we have currently
585 * available for this receiver.
587 unsigned int acks_available;
590 * Which network type does this queue use?
592 enum GNUNET_NetworkType nt;
597 * Interface we broadcast our presence on.
599 struct BroadcastInterface
605 struct BroadcastInterface *next;
610 struct BroadcastInterface *prev;
613 * Task for this broadcast interface.
615 struct GNUNET_SCHEDULER_Task *broadcast_task;
618 * Sender's address of the interface.
623 * Broadcast address to use on the interface.
628 * Message we broadcast on this interface.
630 struct UDPBroadcast bcm;
633 * If this is an IPv6 interface, this is the request
634 * we use to join/leave the group.
636 struct ipv6_mreq mcreq;
639 * Number of bytes in @e sa.
644 * Was this interface found in the last #iface_proc() scan?
651 * Cache of pre-generated key IDs.
653 static struct GNUNET_CONTAINER_MultiShortmap *key_cache;
658 static struct GNUNET_SCHEDULER_Task *read_task;
663 static struct GNUNET_SCHEDULER_Task *timeout_task;
666 * ID of master broadcast task
668 static struct GNUNET_SCHEDULER_Task *broadcast_task;
671 * For logging statistics.
673 static struct GNUNET_STATISTICS_Handle *stats;
678 static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
681 * Receivers (map from peer identity to `struct ReceiverAddress`)
683 static struct GNUNET_CONTAINER_MultiPeerMap *receivers;
686 * Senders (map from peer identity to `struct SenderAddress`)
688 static struct GNUNET_CONTAINER_MultiPeerMap *senders;
691 * Expiration heap for senders (contains `struct SenderAddress`)
693 static struct GNUNET_CONTAINER_Heap *senders_heap;
696 * Expiration heap for receivers (contains `struct ReceiverAddress`)
698 static struct GNUNET_CONTAINER_Heap *receivers_heap;
701 * Broadcast interface tasks. Kept in a DLL.
703 static struct BroadcastInterface *bi_head;
706 * Broadcast interface tasks. Kept in a DLL.
708 static struct BroadcastInterface *bi_tail;
713 static struct GNUNET_NETWORK_Handle *udp_sock;
716 * #GNUNET_YES if #udp_sock supports IPv6.
718 static int have_v6_socket;
723 static struct GNUNET_PeerIdentity my_identity;
728 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
733 static const struct GNUNET_CONFIGURATION_Handle *cfg;
736 * Our handle to report addresses for validation to TRANSPORT.
738 static struct GNUNET_TRANSPORT_ApplicationHandle *ah;
741 * Network scanner to determine network types.
743 static struct GNUNET_NT_InterfaceScanner *is;
746 * Connection to NAT service.
748 static struct GNUNET_NAT_Handle *nat;
751 * Port number to which we are actually bound.
753 static uint16_t my_port;
757 * An interface went away, stop broadcasting on it.
759 * @param bi entity to close down
762 bi_destroy (struct BroadcastInterface *bi)
764 if (AF_INET6 == bi->sa->sa_family)
766 /* Leave the multicast group */
767 if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt (udp_sock,
773 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
776 GNUNET_CONTAINER_DLL_remove (bi_head, bi_tail, bi);
777 GNUNET_SCHEDULER_cancel (bi->broadcast_task);
778 GNUNET_free (bi->sa);
779 GNUNET_free_non_null (bi->ba);
785 * Destroys a receiving state due to timeout or shutdown.
787 * @param receiver entity to close down
790 receiver_destroy (struct ReceiverAddress *receiver)
792 struct GNUNET_MQ_Handle *mq;
794 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
795 "Disconnecting receiver for peer `%s'\n",
796 GNUNET_i2s (&receiver->target));
797 if (NULL != (mq = receiver->mq))
800 GNUNET_MQ_destroy (mq);
802 if (NULL != receiver->qh)
804 GNUNET_TRANSPORT_communicator_mq_del (receiver->qh);
807 GNUNET_assert (GNUNET_YES ==
808 GNUNET_CONTAINER_multipeermap_remove (receivers,
811 GNUNET_assert (receiver == GNUNET_CONTAINER_heap_remove_node (receiver->hn));
812 GNUNET_STATISTICS_set (stats,
813 "# receivers active",
814 GNUNET_CONTAINER_multipeermap_size (receivers),
816 GNUNET_free (receiver->address);
817 GNUNET_free (receiver->foreign_addr);
818 GNUNET_free (receiver);
823 * Free memory used by key cache entry.
825 * @param kce the key cache entry
828 kce_destroy (struct KeyCacheEntry *kce)
830 struct SharedSecret *ss = kce->ss;
832 ss->active_kce_count--;
833 GNUNET_CONTAINER_DLL_remove (ss->kce_head, ss->kce_tail, kce);
834 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multishortmap_remove (key_cache,
844 * @param msec master secret for HMAC calculation
845 * @param serial number for the @a smac calculation
846 * @param kid[out] where to write the key ID
849 get_kid (const struct GNUNET_HashCode *msec,
851 struct GNUNET_ShortHashCode *kid)
853 uint32_t sid = htonl (serial);
855 GNUNET_CRYPTO_hkdf (kid,
871 * Setup key cache entry for sequence number @a seq and shared secret @a ss.
873 * @param ss shared secret
874 * @param seq sequence number for the key cache entry
877 kce_generate (struct SharedSecret *ss, uint32_t seq)
879 struct KeyCacheEntry *kce;
881 GNUNET_assert (0 < seq);
882 kce = GNUNET_new (struct KeyCacheEntry);
884 kce->sequence_number = seq;
885 get_kid (&ss->master, seq, &kce->kid);
886 GNUNET_CONTAINER_DLL_insert (ss->kce_head, ss->kce_tail, kce);
887 ss->active_kce_count++;
888 (void) GNUNET_CONTAINER_multishortmap_put (
892 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
893 GNUNET_STATISTICS_set (stats,
895 GNUNET_CONTAINER_multishortmap_size (key_cache),
901 * Destroy @a ss and associated key cache entries.
903 * @param ss shared secret to destroy
906 secret_destroy (struct SharedSecret *ss)
908 struct SenderAddress *sender;
909 struct ReceiverAddress *receiver;
910 struct KeyCacheEntry *kce;
912 if (NULL != (sender = ss->sender))
914 GNUNET_CONTAINER_DLL_remove (sender->ss_head, sender->ss_tail, ss);
915 sender->num_secrets--;
917 if (NULL != (receiver = ss->receiver))
919 GNUNET_CONTAINER_DLL_remove (receiver->ss_head, receiver->ss_tail, ss);
920 receiver->num_secrets--;
921 receiver->acks_available -= (ss->sequence_allowed - ss->sequence_used);
923 while (NULL != (kce = ss->kce_head))
925 GNUNET_STATISTICS_update (stats, "# Secrets active", -1, GNUNET_NO);
926 GNUNET_STATISTICS_set (stats,
928 GNUNET_CONTAINER_multishortmap_size (key_cache),
935 * Functions with this signature are called whenever we need
936 * to close a sender's state due to timeout.
938 * @param sender entity to close down
941 sender_destroy (struct SenderAddress *sender)
945 GNUNET_CONTAINER_multipeermap_remove (senders, &sender->target, sender));
946 GNUNET_assert (sender == GNUNET_CONTAINER_heap_remove_node (sender->hn));
947 GNUNET_STATISTICS_set (stats,
949 GNUNET_CONTAINER_multipeermap_size (senders),
951 GNUNET_free (sender->address);
952 GNUNET_free (sender);
957 * Compute @a key and @a iv.
959 * @param msec master secret for calculation
960 * @param serial number for the @a smac calculation
961 * @param key[out] where to write the decrption key
962 * @param iv[out] where to write the IV
965 get_iv_key (const struct GNUNET_HashCode *msec,
967 char key[AES_KEY_SIZE],
968 char iv[AES_IV_SIZE])
970 uint32_t sid = htonl (serial);
971 char res[AES_KEY_SIZE + AES_IV_SIZE];
973 GNUNET_CRYPTO_hkdf (res,
982 strlen ("UDP-IV-KEY"),
985 memcpy (key, res, AES_KEY_SIZE);
986 memcpy (iv, &res[AES_KEY_SIZE], AES_IV_SIZE);
991 * Increment sender timeout due to activity.
993 * @param sender address for which the timeout should be rescheduled
996 reschedule_sender_timeout (struct SenderAddress *sender)
999 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1000 GNUNET_CONTAINER_heap_update_cost (sender->hn, sender->timeout.abs_value_us);
1005 * Increment receiver timeout due to activity.
1007 * @param receiver address for which the timeout should be rescheduled
1010 reschedule_receiver_timeout (struct ReceiverAddress *receiver)
1013 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1014 GNUNET_CONTAINER_heap_update_cost (receiver->hn,
1015 receiver->timeout.abs_value_us);
1020 * Task run to check #receiver_heap and #sender_heap for timeouts.
1022 * @param cls unused, NULL
1025 check_timeouts (void *cls)
1027 struct GNUNET_TIME_Relative st;
1028 struct GNUNET_TIME_Relative rt;
1029 struct GNUNET_TIME_Relative delay;
1030 struct ReceiverAddress *receiver;
1031 struct SenderAddress *sender;
1034 timeout_task = NULL;
1035 rt = GNUNET_TIME_UNIT_FOREVER_REL;
1036 while (NULL != (receiver = GNUNET_CONTAINER_heap_peek (receivers_heap)))
1038 rt = GNUNET_TIME_absolute_get_remaining (receiver->timeout);
1039 if (0 != rt.rel_value_us)
1041 receiver_destroy (receiver);
1043 st = GNUNET_TIME_UNIT_FOREVER_REL;
1044 while (NULL != (sender = GNUNET_CONTAINER_heap_peek (senders_heap)))
1046 st = GNUNET_TIME_absolute_get_remaining (sender->timeout);
1047 if (0 != st.rel_value_us)
1049 sender_destroy (sender);
1051 delay = GNUNET_TIME_relative_min (rt, st);
1052 if (delay.rel_value_us < GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
1053 timeout_task = GNUNET_SCHEDULER_add_delayed (delay, &check_timeouts, NULL);
1058 * Calcualte cmac from master in @a ss.
1060 * @param ss[in,out] data structure to complete
1063 calculate_cmac (struct SharedSecret *ss)
1065 GNUNET_CRYPTO_hkdf (&ss->cmac,
1072 sizeof (ss->master),
1074 strlen ("UDP-CMAC"),
1081 * We received @a plaintext_len bytes of @a plaintext from a @a sender.
1082 * Pass it on to CORE.
1084 * @param queue the queue that received the plaintext
1085 * @param plaintext the plaintext that was received
1086 * @param plaintext_len number of bytes of plaintext received
1089 pass_plaintext_to_core (struct SenderAddress *sender,
1090 const void *plaintext,
1091 size_t plaintext_len)
1093 const struct GNUNET_MessageHeader *hdr = plaintext;
1095 while (ntohs (hdr->size) < plaintext_len)
1097 GNUNET_STATISTICS_update (stats,
1098 "# bytes given to core",
1102 GNUNET_TRANSPORT_communicator_receive (ch,
1105 ADDRESS_VALIDITY_PERIOD,
1106 NULL /* no flow control possible */
1109 /* move on to next message, if any */
1110 plaintext_len -= ntohs (hdr->size);
1111 if (plaintext_len < sizeof (*hdr))
1113 hdr = plaintext + ntohs (hdr->size);
1115 GNUNET_STATISTICS_update (stats,
1116 "# bytes padding discarded",
1123 * Setup @a cipher based on shared secret @a msec and
1124 * serial number @a serial.
1126 * @param msec master shared secret
1127 * @param serial serial number of cipher to set up
1128 * @param cipher[out] cipher to initialize
1131 setup_cipher (const struct GNUNET_HashCode *msec,
1133 gcry_cipher_hd_t *cipher)
1135 char key[AES_KEY_SIZE];
1136 char iv[AES_IV_SIZE];
1138 gcry_cipher_open (cipher,
1139 GCRY_CIPHER_AES256 /* low level: go for speed */,
1140 GCRY_CIPHER_MODE_GCM,
1142 get_iv_key (msec, serial, key, iv);
1143 gcry_cipher_setkey (*cipher, key, sizeof (key));
1144 gcry_cipher_setiv (*cipher, iv, sizeof (iv));
1149 * Try to decrypt @a buf using shared secret @a ss and key/iv
1150 * derived using @a serial.
1152 * @param ss shared secret
1153 * @param tag GCM authentication tag
1154 * @param serial serial number to use
1155 * @param in_buf input buffer to decrypt
1156 * @param in_buf_size number of bytes in @a in_buf and available in @a out_buf
1157 * @param out_buf where to write the result
1158 * @return #GNUNET_OK on success
1161 try_decrypt (const struct SharedSecret *ss,
1162 const char tag[GCM_TAG_SIZE],
1168 gcry_cipher_hd_t cipher;
1170 setup_cipher (&ss->master, serial, &cipher);
1173 gcry_cipher_decrypt (cipher, out_buf, in_buf_size, in_buf, in_buf_size));
1174 if (0 != gcry_cipher_checktag (cipher, tag, GCM_TAG_SIZE))
1176 gcry_cipher_close (cipher);
1177 GNUNET_STATISTICS_update (stats,
1178 "# AEAD authentication failures",
1181 return GNUNET_SYSERR;
1183 gcry_cipher_close (cipher);
1189 * Setup shared secret for decryption.
1191 * @param ephemeral ephemeral key we received from the other peer
1192 * @return new shared secret
1194 static struct SharedSecret *
1195 setup_shared_secret_dec (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1197 struct SharedSecret *ss;
1199 ss = GNUNET_new (struct SharedSecret);
1200 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, ephemeral, &ss->master);
1206 * Setup shared secret for encryption.
1208 * @param ephemeral ephemeral key we are sending to the other peer
1209 * @param receiver[in,out] queue to initialize encryption key for
1210 * @return new shared secret
1212 static struct SharedSecret *
1213 setup_shared_secret_enc (const struct GNUNET_CRYPTO_EcdhePrivateKey *ephemeral,
1214 struct ReceiverAddress *receiver)
1216 struct SharedSecret *ss;
1218 ss = GNUNET_new (struct SharedSecret);
1219 GNUNET_CRYPTO_ecdh_eddsa (ephemeral,
1220 &receiver->target.public_key,
1222 calculate_cmac (ss);
1223 ss->receiver = receiver;
1224 GNUNET_CONTAINER_DLL_insert (receiver->ss_head, receiver->ss_tail, ss);
1225 receiver->num_secrets++;
1226 GNUNET_STATISTICS_update (stats, "# Secrets active", 1, GNUNET_NO);
1232 * Setup the MQ for the @a receiver. If a queue exists,
1233 * the existing one is destroyed. Then the MTU is
1234 * recalculated and a fresh queue is initialized.
1236 * @param receiver receiver to setup MQ for
1239 setup_receiver_mq (struct ReceiverAddress *receiver);
1243 * We received an ACK for @a pid. Check if it is for
1244 * the receiver in @a value and if so, handle it and
1245 * return #GNUNET_NO. Otherwise, return #GNUNET_YES.
1247 * @param cls a `const struct UDPAck`
1248 * @param pid peer the ACK is from
1249 * @param value a `struct ReceiverAddress`
1250 * @return #GNUNET_YES to continue to iterate
1253 handle_ack (void *cls, const struct GNUNET_PeerIdentity *pid, void *value)
1255 const struct UDPAck *ack = cls;
1256 struct ReceiverAddress *receiver = value;
1259 for (struct SharedSecret *ss = receiver->ss_head; NULL != ss; ss = ss->next)
1261 if (0 == memcmp (&ack->cmac, &ss->cmac, sizeof (struct GNUNET_HashCode)))
1265 allowed = ntohl (ack->sequence_max);
1267 if (allowed > ss->sequence_allowed)
1269 receiver->acks_available += (allowed - ss->sequence_allowed);
1270 if ((allowed - ss->sequence_allowed) == receiver->acks_available)
1272 /* we just incremented from zero => MTU change! */
1273 setup_receiver_mq (receiver);
1275 ss->sequence_allowed = allowed;
1276 /* move ss to head to avoid discarding it anytime soon! */
1277 GNUNET_CONTAINER_DLL_remove (receiver->ss_head, receiver->ss_tail, ss);
1278 GNUNET_CONTAINER_DLL_insert (receiver->ss_head, receiver->ss_tail, ss);
1288 * Test if we have received a valid message in plaintext.
1291 * @param sender peer to process inbound plaintext for
1292 * @param buf buffer we received
1293 * @param buf_size number of bytes in @a buf
1296 try_handle_plaintext (struct SenderAddress *sender,
1300 const struct GNUNET_MessageHeader *hdr =
1301 (const struct GNUNET_MessageHeader *) buf;
1302 const struct UDPAck *ack = (const struct UDPAck *) buf;
1305 if (sizeof (*hdr) > buf_size)
1306 return; /* not even a header */
1307 if (ntohs (hdr->size) > buf_size)
1308 return; /* not even a header */
1309 type = ntohs (hdr->type);
1312 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK:
1313 /* lookup master secret by 'cmac', then update sequence_max */
1314 GNUNET_CONTAINER_multipeermap_get_multiple (receivers,
1318 /* There could be more messages after the ACK, handle those as well */
1319 buf += ntohs (hdr->size);
1320 buf_size -= ntohs (hdr->size);
1321 pass_plaintext_to_core (sender, buf, buf_size);
1323 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD:
1327 pass_plaintext_to_core (sender, buf, buf_size);
1333 * We established a shared secret with a sender. We should try to send
1334 * the sender an `struct UDPAck` at the next opportunity to allow the
1335 * sender to use @a ss longer (assuming we did not yet already
1338 * @param ss shared secret to generate ACKs for
1341 consider_ss_ack (struct SharedSecret *ss)
1343 GNUNET_assert (NULL != ss->sender);
1344 /* drop ancient KeyCacheEntries */
1345 while ((NULL != ss->kce_head) &&
1347 ss->kce_head->sequence_number - ss->kce_tail->sequence_number))
1348 kce_destroy (ss->kce_tail);
1349 if (ss->active_kce_count < KCN_THRESHOLD)
1353 while (ss->active_kce_count < KCN_TARGET)
1354 kce_generate (ss, ++ss->sequence_allowed);
1355 ack.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK);
1356 ack.header.size = htons (sizeof (ack));
1357 ack.sequence_max = htonl (ss->sequence_allowed);
1358 ack.cmac = ss->cmac;
1359 GNUNET_TRANSPORT_communicator_notify (ch,
1360 &ss->sender->target,
1361 COMMUNICATOR_ADDRESS_PREFIX,
1368 * We received a @a box with matching @a kce. Decrypt and process it.
1370 * @param box the data we received
1371 * @param box_len number of bytes in @a box
1372 * @param kce key index to decrypt @a box
1375 decrypt_box (const struct UDPBox *box,
1377 struct KeyCacheEntry *kce)
1379 struct SharedSecret *ss = kce->ss;
1380 char out_buf[box_len - sizeof (*box)];
1382 GNUNET_assert (NULL != ss->sender);
1383 if (GNUNET_OK != try_decrypt (ss,
1385 kce->sequence_number,
1386 (const char *) &box[1],
1390 GNUNET_STATISTICS_update (stats,
1391 "# Decryption failures with valid KCE",
1398 GNUNET_STATISTICS_update (stats,
1399 "# bytes decrypted with BOX",
1402 try_handle_plaintext (ss->sender, out_buf, sizeof (out_buf));
1403 consider_ss_ack (ss);
1408 * Closure for #find_sender_by_address()
1410 struct SearchContext
1413 * Address we are looking for.
1415 const struct sockaddr *address;
1418 * Number of bytes in @e address.
1420 socklen_t address_len;
1423 * Return value to set if we found a match.
1425 struct SenderAddress *sender;
1430 * Find existing `struct SenderAddress` by matching addresses.
1432 * @param cls a `struct SearchContext`
1433 * @param key ignored, must match already
1434 * @param value a `struct SenderAddress`
1435 * @return #GNUNET_YES if not found (continue to search), #GNUNET_NO if found
1438 find_sender_by_address (void *cls,
1439 const struct GNUNET_PeerIdentity *key,
1442 struct SearchContext *sc = cls;
1443 struct SenderAddress *sender = value;
1445 if ((sender->address_len == sc->address_len) &&
1446 (0 == memcmp (sender->address, sc->address, sender->address_len)))
1448 sc->sender = sender;
1449 return GNUNET_NO; /* stop iterating! */
1456 * Create sender address for @a target. Note that we
1457 * might already have one, so a fresh one is only allocated
1458 * if one does not yet exist for @a address.
1460 * @param target peer to generate address for
1461 * @param address target address
1462 * @param address_len number of bytes in @a address
1463 * @return data structure to keep track of key material for
1464 * decrypting data from @a target
1466 static struct SenderAddress *
1467 setup_sender (const struct GNUNET_PeerIdentity *target,
1468 const struct sockaddr *address,
1469 socklen_t address_len)
1471 struct SenderAddress *sender;
1472 struct SearchContext sc = {.address = address,
1473 .address_len = address_len,
1476 GNUNET_CONTAINER_multipeermap_get_multiple (senders,
1478 &find_sender_by_address,
1480 if (NULL != sc.sender)
1482 reschedule_sender_timeout (sc.sender);
1485 sender = GNUNET_new (struct SenderAddress);
1486 sender->target = *target;
1487 sender->address = GNUNET_memdup (address, address_len);
1488 sender->address_len = address_len;
1489 (void) GNUNET_CONTAINER_multipeermap_put (
1493 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1494 GNUNET_STATISTICS_set (stats,
1496 GNUNET_CONTAINER_multipeermap_size (receivers),
1499 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1500 sender->hn = GNUNET_CONTAINER_heap_insert (senders_heap,
1502 sender->timeout.abs_value_us);
1503 sender->nt = GNUNET_NT_scanner_get_type (is, address, address_len);
1504 if (NULL == timeout_task)
1505 timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts, NULL);
1511 * Check signature from @a uc against @a ephemeral.
1513 * @param ephermal key that is signed
1514 * @param uc signature of claimant
1515 * @return #GNUNET_OK if signature is valid
1518 verify_confirmation (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral,
1519 const struct UDPConfirmation *uc)
1521 struct UdpHandshakeSignature uhs;
1523 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
1524 uhs.purpose.size = htonl (sizeof (uhs));
1525 uhs.sender = uc->sender;
1526 uhs.receiver = my_identity;
1527 uhs.ephemeral = *ephemeral;
1528 uhs.monotonic_time = uc->monotonic_time;
1529 return GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE,
1532 &uc->sender.public_key);
1537 * Converts @a address to the address string format used by this
1538 * communicator in HELLOs.
1540 * @param address the address to convert, must be AF_INET or AF_INET6.
1541 * @param address_len number of bytes in @a address
1542 * @return string representation of @a address
1545 sockaddr_to_udpaddr_string (const struct sockaddr *address,
1546 socklen_t address_len)
1550 switch (address->sa_family)
1553 GNUNET_asprintf (&ret,
1555 COMMUNICATOR_ADDRESS_PREFIX,
1556 GNUNET_a2s (address, address_len));
1559 GNUNET_asprintf (&ret,
1561 COMMUNICATOR_ADDRESS_PREFIX,
1562 GNUNET_a2s (address, address_len));
1577 sock_read (void *cls)
1579 struct sockaddr_storage sa;
1580 socklen_t salen = sizeof (sa);
1581 char buf[UINT16_MAX];
1585 read_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1589 rcvd = GNUNET_NETWORK_socket_recvfrom (udp_sock,
1592 (struct sockaddr *) &sa,
1596 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "recv");
1600 /* first, see if it is a UDPBox */
1601 if (rcvd > sizeof (struct UDPBox))
1603 const struct UDPBox *box;
1604 struct KeyCacheEntry *kce;
1606 box = (const struct UDPBox *) buf;
1607 kce = GNUNET_CONTAINER_multishortmap_get (key_cache, &box->kid);
1610 decrypt_box (box, (size_t) rcvd, kce);
1615 /* next, check if it is a broadcast */
1616 if (sizeof (struct UDPBroadcast) == rcvd)
1618 const struct UDPBroadcast *ub;
1619 struct UdpBroadcastSignature uhs;
1621 ub = (const struct UDPBroadcast *) buf;
1622 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
1623 uhs.purpose.size = htonl (sizeof (uhs));
1624 uhs.sender = ub->sender;
1625 GNUNET_CRYPTO_hash (&sa, salen, &uhs.h_address);
1627 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST,
1630 &ub->sender.public_key))
1633 enum GNUNET_NetworkType nt;
1636 sockaddr_to_udpaddr_string ((const struct sockaddr *) &sa, salen);
1637 GNUNET_STATISTICS_update (stats, "# broadcasts received", 1, GNUNET_NO);
1638 /* use our own mechanism to determine network type */
1640 GNUNET_NT_scanner_get_type (is, (const struct sockaddr *) &sa, salen);
1641 GNUNET_TRANSPORT_application_validate (ah, &ub->sender, nt, addr_s);
1642 GNUNET_free (addr_s);
1645 /* continue with KX, mostly for statistics... */
1649 /* finally, test if it is a KX */
1650 if (rcvd < sizeof (struct UDPConfirmation) + sizeof (struct InitialKX))
1652 GNUNET_STATISTICS_update (stats,
1653 "# messages dropped (no kid, too small for KX)",
1660 const struct InitialKX *kx;
1661 struct SharedSecret *ss;
1662 char pbuf[rcvd - sizeof (struct InitialKX)];
1663 const struct UDPConfirmation *uc;
1664 struct SenderAddress *sender;
1666 kx = (const struct InitialKX *) buf;
1667 ss = setup_shared_secret_dec (&kx->ephemeral);
1668 if (GNUNET_OK != try_decrypt (ss,
1676 GNUNET_STATISTICS_update (
1678 "# messages dropped (no kid, AEAD decryption failed)",
1683 uc = (const struct UDPConfirmation *) pbuf;
1684 if (GNUNET_OK != verify_confirmation (&kx->ephemeral, uc))
1686 GNUNET_break_op (0);
1688 GNUNET_STATISTICS_update (stats,
1689 "# messages dropped (sender signature invalid)",
1694 calculate_cmac (ss);
1695 sender = setup_sender (&uc->sender, (const struct sockaddr *) &sa, salen);
1696 ss->sender = sender;
1697 GNUNET_CONTAINER_DLL_insert (sender->ss_head, sender->ss_tail, ss);
1698 sender->num_secrets++;
1699 GNUNET_STATISTICS_update (stats, "# Secrets active", 1, GNUNET_NO);
1700 GNUNET_STATISTICS_update (stats,
1701 "# messages decrypted without BOX",
1704 try_handle_plaintext (sender, &uc[1], sizeof (pbuf) - sizeof (*uc));
1705 consider_ss_ack (ss);
1706 if (sender->num_secrets > MAX_SECRETS)
1707 secret_destroy (sender->ss_tail);
1713 * Convert UDP bind specification to a `struct sockaddr *`
1715 * @param bindto bind specification to convert
1716 * @param[out] sock_len set to the length of the address
1717 * @return converted bindto specification
1719 static struct sockaddr *
1720 udp_address_to_sockaddr (const char *bindto, socklen_t *sock_len)
1722 struct sockaddr *in;
1728 if (1 == sscanf (bindto, "%u%1s", &port, dummy))
1730 /* interpreting value as just a PORT number */
1731 if (port > UINT16_MAX)
1733 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1734 "BINDTO specification `%s' invalid: value too large for port\n",
1738 if ((GNUNET_NO == GNUNET_NETWORK_test_pf (PF_INET6)) ||
1740 GNUNET_CONFIGURATION_get_value_yesno (cfg,
1741 COMMUNICATOR_CONFIG_SECTION,
1744 struct sockaddr_in *i4;
1746 i4 = GNUNET_malloc (sizeof (struct sockaddr_in));
1747 i4->sin_family = AF_INET;
1748 i4->sin_port = htons ((uint16_t) port);
1749 *sock_len = sizeof (struct sockaddr_in);
1750 in = (struct sockaddr *) i4;
1754 struct sockaddr_in6 *i6;
1756 i6 = GNUNET_malloc (sizeof (struct sockaddr_in6));
1757 i6->sin6_family = AF_INET6;
1758 i6->sin6_port = htons ((uint16_t) port);
1759 *sock_len = sizeof (struct sockaddr_in6);
1760 in = (struct sockaddr *) i6;
1764 cp = GNUNET_strdup (bindto);
1765 colon = strrchr (cp, ':');
1768 /* interpet value after colon as port */
1771 if (1 == sscanf (colon, "%u%1s", &port, dummy))
1773 /* interpreting value as just a PORT number */
1774 if (port > UINT16_MAX)
1776 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1777 "BINDTO specification `%s' invalid: value too large for port\n",
1786 GNUNET_ERROR_TYPE_ERROR,
1787 "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1795 /* interpret missing port as 0, aka pick any free one */
1800 struct sockaddr_in v4;
1802 if (1 == inet_pton (AF_INET, cp, &v4))
1804 v4.sin_port = htons ((uint16_t) port);
1805 in = GNUNET_memdup (&v4, sizeof (v4));
1806 *sock_len = sizeof (v4);
1813 struct sockaddr_in6 v6;
1817 if (('[' == *cp) && (']' == cp[strlen (cp) - 1]))
1819 start++; /* skip over '[' */
1820 cp[strlen (cp) - 1] = '\0'; /* eat ']' */
1822 if (1 == inet_pton (AF_INET6, start, &v6))
1824 v6.sin6_port = htons ((uint16_t) port);
1825 in = GNUNET_memdup (&v6, sizeof (v6));
1826 *sock_len = sizeof (v6);
1831 /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1838 * Pad @a dgram by @a pad_size using @a out_cipher.
1840 * @param out_cipher cipher to use
1841 * @param dgram datagram to pad
1842 * @param pad_size number of bytes of padding to append
1845 do_pad (gcry_cipher_hd_t out_cipher, char *dgram, size_t pad_size)
1849 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, pad, sizeof (pad));
1850 if (sizeof (pad) > sizeof (struct GNUNET_MessageHeader))
1852 struct GNUNET_MessageHeader hdr =
1853 {.size = htons (sizeof (pad)),
1854 .type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD)};
1856 memcpy (pad, &hdr, sizeof (hdr));
1860 gcry_cipher_encrypt (out_cipher, dgram, sizeof (pad), pad, sizeof (pad)));
1865 * Signature of functions implementing the sending functionality of a
1868 * @param mq the message queue
1869 * @param msg the message to send
1870 * @param impl_state our `struct ReceiverAddress`
1873 mq_send (struct GNUNET_MQ_Handle *mq,
1874 const struct GNUNET_MessageHeader *msg,
1877 struct ReceiverAddress *receiver = impl_state;
1878 uint16_t msize = ntohs (msg->size);
1880 GNUNET_assert (mq == receiver->mq);
1881 if (msize > receiver->mtu)
1884 receiver_destroy (receiver);
1887 reschedule_receiver_timeout (receiver);
1889 if (0 == receiver->acks_available)
1891 /* use KX encryption method */
1892 struct UdpHandshakeSignature uhs;
1893 struct UDPConfirmation uc;
1894 struct InitialKX kx;
1895 struct GNUNET_CRYPTO_EcdhePrivateKey epriv;
1896 char dgram[receiver->mtu + sizeof (uc) + sizeof (kx)];
1898 gcry_cipher_hd_t out_cipher;
1899 struct SharedSecret *ss;
1901 /* setup key material */
1902 GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_ecdhe_key_create2 (&epriv));
1904 ss = setup_shared_secret_enc (&epriv, receiver);
1905 setup_cipher (&ss->master, 0, &out_cipher);
1907 uc.sender = my_identity;
1909 GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1910 uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
1911 uhs.purpose.size = htonl (sizeof (uhs));
1912 uhs.sender = my_identity;
1913 uhs.receiver = receiver->target;
1914 GNUNET_CRYPTO_ecdhe_key_get_public (&epriv, &uhs.ephemeral);
1915 uhs.monotonic_time = uc.monotonic_time;
1916 GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_eddsa_sign (my_private_key,
1919 /* Leave space for kx */
1920 dpos = sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
1921 /* Append encrypted uc to dgram */
1922 GNUNET_assert (0 == gcry_cipher_encrypt (out_cipher,
1927 dpos += sizeof (uc);
1928 /* Append encrypted payload to dgram */
1930 0 == gcry_cipher_encrypt (out_cipher, &dgram[dpos], msize, msg, msize));
1932 do_pad (out_cipher, &dgram[dpos], sizeof (dgram) - dpos);
1933 /* Datagram starts with kx */
1934 kx.ephemeral = uhs.ephemeral;
1936 0 == gcry_cipher_gettag (out_cipher, kx.gcm_tag, sizeof (kx.gcm_tag)));
1937 gcry_cipher_close (out_cipher);
1938 memcpy (dgram, &kx, sizeof (kx));
1939 if (-1 == GNUNET_NETWORK_socket_sendto (udp_sock,
1943 receiver->address_len))
1944 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "send");
1945 GNUNET_MQ_impl_send_continue (mq);
1947 } /* End of KX encryption method */
1949 /* begin "BOX" encryption method, scan for ACKs from tail! */
1950 for (struct SharedSecret *ss = receiver->ss_tail; NULL != ss; ss = ss->prev)
1952 if (ss->sequence_used < ss->sequence_allowed)
1954 char dgram[sizeof (struct UDPBox) + receiver->mtu];
1956 gcry_cipher_hd_t out_cipher;
1959 box = (struct UDPBox *) dgram;
1960 ss->sequence_used++;
1961 get_kid (&ss->master, ss->sequence_used, &box->kid);
1962 setup_cipher (&ss->master, ss->sequence_used, &out_cipher);
1963 /* Append encrypted payload to dgram */
1964 dpos = sizeof (struct UDPBox);
1966 0 == gcry_cipher_encrypt (out_cipher, &dgram[dpos], msize, msg, msize));
1968 do_pad (out_cipher, &dgram[dpos], sizeof (dgram) - dpos);
1969 GNUNET_assert (0 == gcry_cipher_gettag (out_cipher,
1971 sizeof (box->gcm_tag)));
1972 gcry_cipher_close (out_cipher);
1973 if (-1 == GNUNET_NETWORK_socket_sendto (udp_sock,
1977 receiver->address_len))
1978 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "send");
1979 GNUNET_MQ_impl_send_continue (mq);
1980 receiver->acks_available--;
1981 if (0 == receiver->acks_available)
1983 /* We have no more ACKs => MTU change! */
1984 setup_receiver_mq (receiver);
1994 * Signature of functions implementing the destruction of a message
1995 * queue. Implementations must not free @a mq, but should take care
1998 * @param mq the message queue to destroy
1999 * @param impl_state our `struct ReceiverAddress`
2002 mq_destroy (struct GNUNET_MQ_Handle *mq, void *impl_state)
2004 struct ReceiverAddress *receiver = impl_state;
2006 if (mq == receiver->mq)
2008 receiver->mq = NULL;
2009 receiver_destroy (receiver);
2015 * Implementation function that cancels the currently sent message.
2017 * @param mq message queue
2018 * @param impl_state our `struct RecvierAddress`
2021 mq_cancel (struct GNUNET_MQ_Handle *mq, void *impl_state)
2023 /* Cancellation is impossible with UDP; bail */
2029 * Generic error handler, called with the appropriate
2030 * error code and the same closure specified at the creation of
2031 * the message queue.
2032 * Not every message queue implementation supports an error handler.
2034 * @param cls our `struct ReceiverAddress`
2035 * @param error error code
2038 mq_error (void *cls, enum GNUNET_MQ_Error error)
2040 struct ReceiverAddress *receiver = cls;
2042 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2043 "MQ error in queue to %s: %d\n",
2044 GNUNET_i2s (&receiver->target),
2046 receiver_destroy (receiver);
2051 * Setup the MQ for the @a receiver. If a queue exists,
2052 * the existing one is destroyed. Then the MTU is
2053 * recalculated and a fresh queue is initialized.
2055 * @param receiver receiver to setup MQ for
2058 setup_receiver_mq (struct ReceiverAddress *receiver)
2062 if (NULL != receiver->qh)
2064 GNUNET_TRANSPORT_communicator_mq_del (receiver->qh);
2065 receiver->qh = NULL;
2067 GNUNET_assert (NULL == receiver->mq);
2068 switch (receiver->address->sa_family)
2071 base_mtu = 1480 /* Ethernet MTU, 1500 - Ethernet header - VLAN tag */
2072 - sizeof (struct GNUNET_TUN_IPv4Header) /* 20 */
2073 - sizeof (struct GNUNET_TUN_UdpHeader) /* 8 */;
2076 base_mtu = 1280 /* Minimum MTU required by IPv6 */
2077 - sizeof (struct GNUNET_TUN_IPv6Header) /* 40 */
2078 - sizeof (struct GNUNET_TUN_UdpHeader) /* 8 */;
2084 if (0 == receiver->acks_available)
2086 /* MTU based on full KX messages */
2087 receiver->mtu = base_mtu - sizeof (struct InitialKX) /* 48 */
2088 - sizeof (struct UDPConfirmation); /* 104 */
2092 /* MTU based on BOXed messages */
2093 receiver->mtu = base_mtu - sizeof (struct UDPBox);
2095 /* => Effective MTU for CORE will range from 1080 (IPv6 + KX) to
2096 1404 (IPv4 + Box) bytes, depending on circumstances... */
2097 if (NULL == receiver->mq)
2098 receiver->mq = GNUNET_MQ_queue_for_callbacks (&mq_send,
2106 GNUNET_TRANSPORT_communicator_mq_add (ch,
2108 receiver->foreign_addr,
2111 GNUNET_TRANSPORT_CS_OUTBOUND,
2117 * Function called by the transport service to initialize a
2118 * message queue given address information about another peer.
2119 * If and when the communication channel is established, the
2120 * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
2121 * to notify the service that the channel is now up. It is
2122 * the responsibility of the communicator to manage sane
2123 * retries and timeouts for any @a peer/@a address combination
2124 * provided by the transport service. Timeouts and retries
2125 * do not need to be signalled to the transport service.
2127 * @param cls closure
2128 * @param peer identity of the other peer
2129 * @param address where to send the message, human-readable
2130 * communicator-specific format, 0-terminated, UTF-8
2131 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is
2135 mq_init (void *cls, const struct GNUNET_PeerIdentity *peer, const char *address)
2137 struct ReceiverAddress *receiver;
2139 struct sockaddr *in;
2142 if (0 != strncmp (address,
2143 COMMUNICATOR_ADDRESS_PREFIX "-",
2144 strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
2146 GNUNET_break_op (0);
2147 return GNUNET_SYSERR;
2149 path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
2150 in = udp_address_to_sockaddr (path, &in_len);
2152 receiver = GNUNET_new (struct ReceiverAddress);
2153 receiver->address = in;
2154 receiver->address_len = in_len;
2155 receiver->target = *peer;
2156 receiver->nt = GNUNET_NT_scanner_get_type (is, in, in_len);
2157 (void) GNUNET_CONTAINER_multipeermap_put (
2161 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2163 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2164 receiver->hn = GNUNET_CONTAINER_heap_insert (receivers_heap,
2166 receiver->timeout.abs_value_us);
2167 GNUNET_STATISTICS_set (stats,
2168 "# receivers active",
2169 GNUNET_CONTAINER_multipeermap_size (receivers),
2171 receiver->foreign_addr =
2172 sockaddr_to_udpaddr_string (receiver->address, receiver->address_len);
2173 setup_receiver_mq (receiver);
2174 if (NULL == timeout_task)
2175 timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts, NULL);
2181 * Iterator over all receivers to clean up.
2184 * @param target unused
2185 * @param value the queue to destroy
2186 * @return #GNUNET_OK to continue to iterate
2189 get_receiver_delete_it (void *cls,
2190 const struct GNUNET_PeerIdentity *target,
2193 struct ReceiverAddress *receiver = value;
2197 receiver_destroy (receiver);
2203 * Iterator over all senders to clean up.
2206 * @param target unused
2207 * @param value the queue to destroy
2208 * @return #GNUNET_OK to continue to iterate
2211 get_sender_delete_it (void *cls,
2212 const struct GNUNET_PeerIdentity *target,
2215 struct SenderAddress *sender = value;
2219 sender_destroy (sender);
2225 * Shutdown the UNIX communicator.
2227 * @param cls NULL (always)
2230 do_shutdown (void *cls)
2234 GNUNET_NAT_unregister (nat);
2237 while (NULL != bi_head)
2238 bi_destroy (bi_head);
2239 if (NULL != broadcast_task)
2241 GNUNET_SCHEDULER_cancel (broadcast_task);
2242 broadcast_task = NULL;
2244 if (NULL != read_task)
2246 GNUNET_SCHEDULER_cancel (read_task);
2249 if (NULL != udp_sock)
2251 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (udp_sock));
2254 GNUNET_CONTAINER_multipeermap_iterate (receivers,
2255 &get_receiver_delete_it,
2257 GNUNET_CONTAINER_multipeermap_destroy (receivers);
2258 GNUNET_CONTAINER_multipeermap_iterate (senders, &get_sender_delete_it, NULL);
2259 GNUNET_CONTAINER_multipeermap_destroy (senders);
2260 GNUNET_CONTAINER_multishortmap_destroy (key_cache);
2261 GNUNET_CONTAINER_heap_destroy (senders_heap);
2262 GNUNET_CONTAINER_heap_destroy (receivers_heap);
2265 GNUNET_TRANSPORT_communicator_disconnect (ch);
2270 GNUNET_TRANSPORT_application_done (ah);
2275 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
2278 if (NULL != my_private_key)
2280 GNUNET_free (my_private_key);
2281 my_private_key = NULL;
2285 GNUNET_NT_scanner_done (is);
2292 * Function called when the transport service has received a
2293 * backchannel message for this communicator (!) via a different return
2294 * path. Should be an acknowledgement.
2296 * @param cls closure, NULL
2297 * @param sender which peer sent the notification
2298 * @param msg payload
2301 enc_notify_cb (void *cls,
2302 const struct GNUNET_PeerIdentity *sender,
2303 const struct GNUNET_MessageHeader *msg)
2305 const struct UDPAck *ack;
2308 if ((ntohs (msg->type) != GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK) ||
2309 (ntohs (msg->size) != sizeof (struct UDPAck)))
2311 GNUNET_break_op (0);
2314 ack = (const struct UDPAck *) msg;
2315 GNUNET_CONTAINER_multipeermap_get_multiple (receivers,
2323 * Signature of the callback passed to #GNUNET_NAT_register() for
2324 * a function to call whenever our set of 'valid' addresses changes.
2326 * @param cls closure
2327 * @param app_ctx[in,out] location where the app can store stuff
2328 * on add and retrieve it on remove
2329 * @param add_remove #GNUNET_YES to add a new public IP address,
2330 * #GNUNET_NO to remove a previous (now invalid) one
2331 * @param ac address class the address belongs to
2332 * @param addr either the previous or the new public IP address
2333 * @param addrlen actual length of the @a addr
2336 nat_address_cb (void *cls,
2339 enum GNUNET_NAT_AddressClass ac,
2340 const struct sockaddr *addr,
2344 struct GNUNET_TRANSPORT_AddressIdentifier *ai;
2346 if (GNUNET_YES == add_remove)
2348 enum GNUNET_NetworkType nt;
2350 GNUNET_asprintf (&my_addr,
2352 COMMUNICATOR_ADDRESS_PREFIX,
2353 GNUNET_a2s (addr, addrlen));
2354 nt = GNUNET_NT_scanner_get_type (is, addr, addrlen);
2356 GNUNET_TRANSPORT_communicator_address_add (ch,
2359 GNUNET_TIME_UNIT_FOREVER_REL);
2360 GNUNET_free (my_addr);
2366 GNUNET_TRANSPORT_communicator_address_remove (ai);
2373 * Broadcast our presence on one of our interfaces.
2375 * @param cls a `struct BroadcastInterface`
2378 ifc_broadcast (void *cls)
2380 struct BroadcastInterface *bi = cls;
2381 struct GNUNET_TIME_Relative delay;
2383 delay = BROADCAST_FREQUENCY;
2384 delay.rel_value_us =
2385 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, delay.rel_value_us);
2386 bi->broadcast_task =
2387 GNUNET_SCHEDULER_add_delayed (INTERFACE_SCAN_FREQUENCY, &ifc_broadcast, bi);
2389 switch (bi->sa->sa_family)
2396 if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt (udp_sock,
2401 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
2402 sent = GNUNET_NETWORK_socket_sendto (udp_sock,
2408 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "sendto");
2409 if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt (udp_sock,
2414 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
2419 struct sockaddr_in6 dst;
2421 dst.sin6_family = AF_INET6;
2422 dst.sin6_port = htons (my_port);
2423 dst.sin6_addr = bi->mcreq.ipv6mr_multiaddr;
2424 dst.sin6_scope_id = ((struct sockaddr_in6 *) bi->ba)->sin6_scope_id;
2426 sent = GNUNET_NETWORK_socket_sendto (udp_sock,
2429 (const struct sockaddr *) &dst,
2432 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "sendto");
2443 * Callback function invoked for each interface found.
2444 * Activates/deactivates broadcast interfaces.
2447 * @param name name of the interface (can be NULL for unknown)
2448 * @param isDefault is this presumably the default interface
2449 * @param addr address of this interface (can be NULL for unknown or unassigned)
2450 * @param broadcast_addr the broadcast address (can be NULL for unknown or
2452 * @param netmask the network mask (can be NULL for unknown or unassigned)
2453 * @param addrlen length of the address
2454 * @return #GNUNET_OK to continue iteration, #GNUNET_SYSERR to abort
2457 iface_proc (void *cls,
2460 const struct sockaddr *addr,
2461 const struct sockaddr *broadcast_addr,
2462 const struct sockaddr *netmask,
2465 struct BroadcastInterface *bi;
2466 enum GNUNET_NetworkType network;
2467 struct UdpBroadcastSignature ubs;
2472 return GNUNET_YES; /* need to know our address! */
2473 network = GNUNET_NT_scanner_get_type (is, addr, addrlen);
2474 if (GNUNET_NT_LOOPBACK == network)
2476 /* Broadcasting on loopback does not make sense */
2479 for (bi = bi_head; NULL != bi; bi = bi->next)
2481 if ((bi->salen == addrlen) && (0 == memcmp (addr, bi->sa, addrlen)))
2483 bi->found = GNUNET_YES;
2488 if ((AF_INET6 == addr->sa_family) && (NULL == broadcast_addr))
2489 return GNUNET_OK; /* broadcast_addr is required for IPv6! */
2490 if ((AF_INET6 == addr->sa_family) && (GNUNET_YES != have_v6_socket))
2491 return GNUNET_OK; /* not using IPv6 */
2493 bi = GNUNET_new (struct BroadcastInterface);
2494 bi->sa = GNUNET_memdup (addr, addrlen);
2495 if (NULL != broadcast_addr)
2496 bi->ba = GNUNET_memdup (broadcast_addr, addrlen);
2497 bi->salen = addrlen;
2498 bi->found = GNUNET_YES;
2499 bi->bcm.sender = my_identity;
2500 ubs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
2501 ubs.purpose.size = htonl (sizeof (ubs));
2502 ubs.sender = my_identity;
2503 GNUNET_CRYPTO_hash (addr, addrlen, &ubs.h_address);
2504 GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_eddsa_sign (my_private_key,
2506 &bi->bcm.sender_sig));
2507 bi->broadcast_task = GNUNET_SCHEDULER_add_now (&ifc_broadcast, bi);
2508 GNUNET_CONTAINER_DLL_insert (bi_head, bi_tail, bi);
2509 if ((AF_INET6 == addr->sa_family) && (NULL != broadcast_addr))
2511 /* Create IPv6 multicast request */
2512 const struct sockaddr_in6 *s6 =
2513 (const struct sockaddr_in6 *) broadcast_addr;
2516 1 == inet_pton (AF_INET6, "FF05::13B", &bi->mcreq.ipv6mr_multiaddr));
2518 /* http://tools.ietf.org/html/rfc2553#section-5.2:
2522 * Join a multicast group on a specified local interface. If the
2523 * interface index is specified as 0, the kernel chooses the local
2524 * interface. For example, some kernels look up the multicast
2525 * group in the normal IPv6 routing table and using the resulting
2526 * interface; we do this for each interface, so no need to use
2527 * zero (anymore...).
2529 bi->mcreq.ipv6mr_interface = s6->sin6_scope_id;
2531 /* Join the multicast group */
2532 if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt (udp_sock,
2536 sizeof (bi->mcreq)))
2538 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
2546 * Scan interfaces to broadcast our presence on the LAN.
2548 * @param cls NULL, unused
2551 do_broadcast (void *cls)
2553 struct BroadcastInterface *bin;
2556 for (struct BroadcastInterface *bi = bi_head; NULL != bi; bi = bi->next)
2557 bi->found = GNUNET_NO;
2558 GNUNET_OS_network_interfaces_list (&iface_proc, NULL);
2559 for (struct BroadcastInterface *bi = bi_head; NULL != bi; bi = bin)
2562 if (GNUNET_NO == bi->found)
2565 broadcast_task = GNUNET_SCHEDULER_add_delayed (INTERFACE_SCAN_FREQUENCY,
2572 * Setup communicator and launch network interactions.
2574 * @param cls NULL (always)
2575 * @param args remaining command-line arguments
2576 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2577 * @param c configuration
2582 const char *cfgfile,
2583 const struct GNUNET_CONFIGURATION_Handle *c)
2586 struct sockaddr *in;
2588 struct sockaddr_storage in_sto;
2594 GNUNET_CONFIGURATION_get_value_filename (cfg,
2595 COMMUNICATOR_CONFIG_SECTION,
2599 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2600 COMMUNICATOR_CONFIG_SECTION,
2605 in = udp_address_to_sockaddr (bindto, &in_len);
2608 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2609 "Failed to setup UDP socket address with path `%s'\n",
2611 GNUNET_free (bindto);
2615 GNUNET_NETWORK_socket_create (in->sa_family, SOCK_DGRAM, IPPROTO_UDP);
2616 if (NULL == udp_sock)
2618 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
2620 GNUNET_free (bindto);
2623 if (AF_INET6 == in->sa_family)
2624 have_v6_socket = GNUNET_YES;
2625 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (udp_sock, in, in_len))
2627 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "bind", bindto);
2628 GNUNET_NETWORK_socket_close (udp_sock);
2631 GNUNET_free (bindto);
2634 /* We might have bound to port 0, allowing the OS to figure it out;
2635 thus, get the real IN-address from the socket */
2636 sto_len = sizeof (in_sto);
2637 if (0 != getsockname (GNUNET_NETWORK_get_fd (udp_sock),
2638 (struct sockaddr *) &in_sto,
2641 memcpy (&in_sto, in, in_len);
2645 GNUNET_free (bindto);
2646 in = (struct sockaddr *) &in_sto;
2648 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2650 GNUNET_a2s ((const struct sockaddr *) &in_sto, sto_len));
2651 switch (in->sa_family)
2654 my_port = ntohs (((struct sockaddr_in *) in)->sin_port);
2657 my_port = ntohs (((struct sockaddr_in6 *) in)->sin6_port);
2663 stats = GNUNET_STATISTICS_create ("C-UDP", cfg);
2664 senders = GNUNET_CONTAINER_multipeermap_create (32, GNUNET_YES);
2665 receivers = GNUNET_CONTAINER_multipeermap_create (32, GNUNET_YES);
2666 senders_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2668 GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2669 key_cache = GNUNET_CONTAINER_multishortmap_create (1024, GNUNET_YES);
2670 GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
2671 is = GNUNET_NT_scanner_init ();
2672 my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
2673 if (NULL == my_private_key)
2676 GNUNET_ERROR_TYPE_ERROR,
2678 "Transport service is lacking key configuration settings. Exiting.\n"));
2679 GNUNET_SCHEDULER_shutdown ();
2682 GNUNET_CRYPTO_eddsa_key_get_public (my_private_key, &my_identity.public_key);
2684 read_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2688 ch = GNUNET_TRANSPORT_communicator_connect (cfg,
2689 COMMUNICATOR_CONFIG_SECTION,
2690 COMMUNICATOR_ADDRESS_PREFIX,
2691 GNUNET_TRANSPORT_CC_UNRELIABLE,
2699 GNUNET_SCHEDULER_shutdown ();
2702 ah = GNUNET_TRANSPORT_application_init (cfg);
2706 GNUNET_SCHEDULER_shutdown ();
2709 /* start broadcasting */
2711 GNUNET_CONFIGURATION_get_value_yesno (cfg,
2712 COMMUNICATOR_CONFIG_SECTION,
2713 "DISABLE_BROADCAST"))
2715 broadcast_task = GNUNET_SCHEDULER_add_now (&do_broadcast, NULL);
2717 nat = GNUNET_NAT_register (cfg,
2718 COMMUNICATOR_CONFIG_SECTION,
2720 1 /* one address */,
2721 (const struct sockaddr **) &in,
2724 NULL /* FIXME: support reversal: #5529 */,
2725 NULL /* closure */);
2730 * The main function for the UNIX communicator.
2732 * @param argc number of arguments from the command line
2733 * @param argv command line arguments
2734 * @return 0 ok, 1 on error
2737 main (int argc, char *const *argv)
2739 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2740 GNUNET_GETOPT_OPTION_END};
2743 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
2746 ret = (GNUNET_OK == GNUNET_PROGRAM_run (argc,
2748 "gnunet-communicator-udp",
2749 _ ("GNUnet UDP communicator"),
2755 GNUNET_free ((void *) argv);
2760 /* end of gnunet-communicator-udp.c */