tolerate additional IPv4 address now available for gnunet.org
[oweals/gnunet.git] / src / transport / gnunet-communicator-udp.c
1 /*
2      This file is part of GNUnet
3      Copyright (C) 2010-2014, 2018, 2019 GNUnet e.V.
4
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.
9
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.
14
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/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
19 */
20
21 /**
22  * @file transport/gnunet-communicator-udp.c
23  * @brief Transport plugin using UDP.
24  * @author Christian Grothoff
25  *
26  * TODO:
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 (#)
39  */
40 #include "platform.h"
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"
50
51 /**
52  * How often do we rekey based on time (at least)
53  */
54 #define REKEY_TIME_INTERVAL GNUNET_TIME_UNIT_DAYS
55
56 /**
57  * How long do we wait until we must have received the initial KX?
58  */
59 #define PROTO_QUEUE_TIMEOUT GNUNET_TIME_UNIT_MINUTES
60
61 /**
62  * How often do we broadcast our presence on the LAN?
63  */
64 #define BROADCAST_FREQUENCY GNUNET_TIME_UNIT_MINUTES
65
66 /**
67  * How often do we scan for changes to our network interfaces?
68  */
69 #define INTERFACE_SCAN_FREQUENCY \
70   GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
71
72 /**
73  * How long do we believe our addresses to remain up (before
74  * the other peer should revalidate).
75  */
76 #define ADDRESS_VALIDITY_PERIOD GNUNET_TIME_UNIT_HOURS
77
78 /**
79  * AES key size.
80  */
81 #define AES_KEY_SIZE (256 / 8)
82
83 /**
84  * AES (GCM) IV size.
85  */
86 #define AES_IV_SIZE (96 / 8)
87
88 /**
89  * Size of the GCM tag.
90  */
91 #define GCM_TAG_SIZE (128 / 8)
92
93 /**
94  * If we fall below this number of available KCNs,
95  * we generate additional ACKs until we reach
96  * #KCN_TARGET.
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.
101  */
102 #define KCN_THRESHOLD 92
103
104 /**
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
108  * ACK at the time.
109  */
110 #define KCN_TARGET 128
111
112 /**
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).
120  */
121 #define MAX_SQN_DELTA 160
122
123 /**
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...
131  */
132 #define MAX_SECRETS 128
133
134 /**
135  * How often do we rekey based on number of bytes transmitted?
136  * (additionally randomized).
137  */
138 #define REKEY_MAX_BYTES (1024LLU * 1024 * 1024 * 4LLU)
139
140 /**
141  * Address prefix used by the communicator.
142  */
143
144 #define COMMUNICATOR_ADDRESS_PREFIX "udp"
145
146 /**
147  * Configuration section used by the communicator.
148  */
149 #define COMMUNICATOR_CONFIG_SECTION "communicator-udp"
150
151 GNUNET_NETWORK_STRUCT_BEGIN
152
153
154 /**
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).
158  */
159 struct UdpHandshakeSignature
160 {
161   /**
162    * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
163    */
164   struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
165
166   /**
167    * Identity of the inititor of the UDP connection (UDP client).
168    */
169   struct GNUNET_PeerIdentity sender;
170
171   /**
172    * Presumed identity of the target of the UDP connection (UDP server)
173    */
174   struct GNUNET_PeerIdentity receiver;
175
176   /**
177    * Ephemeral key used by the @e sender.
178    */
179   struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
180
181   /**
182    * Monotonic time of @e sender, to possibly help detect replay attacks
183    * (if receiver persists times by sender).
184    */
185   struct GNUNET_TIME_AbsoluteNBO monotonic_time;
186 };
187
188
189 /**
190  * "Plaintext" header at beginning of KX message. Followed
191  * by encrypted `struct UDPConfirmation`.
192  */
193 struct InitialKX
194 {
195
196   /**
197    * Ephemeral key for KX.
198    */
199   struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
200
201   /**
202    * HMAC for the following encrypted message, using GCM.  HMAC uses
203    * key derived from the handshake with sequence number zero.
204    */
205   char gcm_tag[GCM_TAG_SIZE];
206 };
207
208
209 /**
210  * Encrypted continuation of UDP initial handshake, followed
211  * by message header with payload.
212  */
213 struct UDPConfirmation
214 {
215   /**
216    * Sender's identity
217    */
218   struct GNUNET_PeerIdentity sender;
219
220   /**
221    * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
222    */
223   struct GNUNET_CRYPTO_EddsaSignature sender_sig;
224
225   /**
226    * Monotonic time of @e sender, to possibly help detect replay attacks
227    * (if receiver persists times by sender).
228    */
229   struct GNUNET_TIME_AbsoluteNBO monotonic_time;
230
231   /* followed by messages */
232
233   /* padding may follow actual messages */
234 };
235
236
237 /**
238  * UDP key acknowledgement.  May be sent via backchannel. Allows the
239  * sender to use `struct UDPBox` with the acknowledge key henceforth.
240  */
241 struct UDPAck
242 {
243
244   /**
245    * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK.
246    */
247   struct GNUNET_MessageHeader header;
248
249   /**
250    * Sequence acknowledgement limit. Specifies current maximum sequence
251    * number supported by receiver.
252    */
253   uint32_t sequence_max GNUNET_PACKED;
254
255   /**
256    * CMAC of the base key being acknowledged.
257    */
258   struct GNUNET_HashCode cmac;
259 };
260
261
262 /**
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.
269  */
270 struct UdpBroadcastSignature
271 {
272   /**
273    * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
274    */
275   struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
276
277   /**
278    * Identity of the inititor of the UDP broadcast.
279    */
280   struct GNUNET_PeerIdentity sender;
281
282   /**
283    * Hash of the sender's UDP address.
284    */
285   struct GNUNET_HashCode h_address;
286 };
287
288
289 /**
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.
294  */
295 struct UDPBroadcast
296 {
297
298   /**
299    * Sender's peer identity.
300    */
301   struct GNUNET_PeerIdentity sender;
302
303   /**
304    * Sender's signature of type
305    * #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
306    */
307   struct GNUNET_CRYPTO_EddsaSignature sender_sig;
308 };
309
310
311 /**
312  * UDP message box.  Always sent encrypted, only allowed after
313  * the receiver sent a `struct UDPAck` for the base key!
314  */
315 struct UDPBox
316 {
317
318   /**
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!
324    */
325   struct GNUNET_ShortHashCode kid;
326
327   /**
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`.
333    */
334   char gcm_tag[GCM_TAG_SIZE];
335 };
336
337
338 GNUNET_NETWORK_STRUCT_END
339
340 /**
341  * Shared secret we generated for a particular sender or receiver.
342  */
343 struct SharedSecret;
344
345
346 /**
347  * Pre-generated "kid" code (key and IV identification code) to
348  * quickly derive master key for a `struct UDPBox`.
349  */
350 struct KeyCacheEntry
351 {
352
353   /**
354    * Kept in a DLL.
355    */
356   struct KeyCacheEntry *next;
357
358   /**
359    * Kept in a DLL.
360    */
361   struct KeyCacheEntry *prev;
362
363   /**
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!
369    */
370   struct GNUNET_ShortHashCode kid;
371
372   /**
373    * Corresponding shared secret.
374    */
375   struct SharedSecret *ss;
376
377   /**
378    * Sequence number used to derive this entry from master key.
379    */
380   uint32_t sequence_number;
381 };
382
383
384 /**
385  * Information we track per sender address we have recently been
386  * in contact with (decryption from sender).
387  */
388 struct SenderAddress;
389
390 /**
391  * Information we track per receiving address we have recently been
392  * in contact with (encryption to receiver).
393  */
394 struct ReceiverAddress;
395
396 /**
397  * Shared secret we generated for a particular sender or receiver.
398  */
399 struct SharedSecret
400 {
401   /**
402    * Kept in a DLL.
403    */
404   struct SharedSecret *next;
405
406   /**
407    * Kept in a DLL.
408    */
409   struct SharedSecret *prev;
410
411   /**
412    * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
413    */
414   struct KeyCacheEntry *kce_head;
415
416   /**
417    * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
418    */
419   struct KeyCacheEntry *kce_tail;
420
421   /**
422    * Sender we use this shared secret with, or NULL.
423    */
424   struct SenderAddress *sender;
425
426   /**
427    * Receiver we use this shared secret with, or NULL.
428    */
429   struct ReceiverAddress *receiver;
430
431   /**
432    * Master shared secret.
433    */
434   struct GNUNET_HashCode master;
435
436   /**
437    * CMAC is used to identify @e master in ACKs.
438    */
439   struct GNUNET_HashCode cmac;
440
441   /**
442    * Up to which sequence number did we use this @e master already?
443    * (for encrypting only)
444    */
445   uint32_t sequence_used;
446
447   /**
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
450    * use this key?
451    */
452   uint32_t sequence_allowed;
453
454   /**
455    * Number of active KCN entries.
456    */
457   unsigned int active_kce_count;
458 };
459
460
461 /**
462  * Information we track per sender address we have recently been
463  * in contact with (we decrypt messages from the sender).
464  */
465 struct SenderAddress
466 {
467
468   /**
469    * To whom are we talking to.
470    */
471   struct GNUNET_PeerIdentity target;
472
473   /**
474    * Entry in sender expiration heap.
475    */
476   struct GNUNET_CONTAINER_HeapNode *hn;
477
478   /**
479    * Shared secrets we used with @e target, first used is head.
480    */
481   struct SharedSecret *ss_head;
482
483   /**
484    * Shared secrets we used with @e target, last used is tail.
485    */
486   struct SharedSecret *ss_tail;
487
488   /**
489    * Address of the other peer.
490    */
491   struct sockaddr *address;
492
493   /**
494    * Length of the address.
495    */
496   socklen_t address_len;
497
498   /**
499    * Timeout for this sender.
500    */
501   struct GNUNET_TIME_Absolute timeout;
502
503   /**
504    * Length of the DLL at @a ss_head.
505    */
506   unsigned int num_secrets;
507
508   /**
509    * Which network type does this queue use?
510    */
511   enum GNUNET_NetworkType nt;
512 };
513
514
515 /**
516  * Information we track per receiving address we have recently been
517  * in contact with (encryption to receiver).
518  */
519 struct ReceiverAddress
520 {
521
522   /**
523    * To whom are we talking to.
524    */
525   struct GNUNET_PeerIdentity target;
526
527   /**
528    * Shared secrets we received from @e target, first used is head.
529    */
530   struct SharedSecret *ss_head;
531
532   /**
533    * Shared secrets we received with @e target, last used is tail.
534    */
535   struct SharedSecret *ss_tail;
536
537   /**
538    * Address of the receiver in the human-readable format
539    * with the #COMMUNICATOR_ADDRESS_PREFIX.
540    */
541   char *foreign_addr;
542
543   /**
544    * Address of the other peer.
545    */
546   struct sockaddr *address;
547
548   /**
549    * Length of the address.
550    */
551   socklen_t address_len;
552
553   /**
554    * Entry in sender expiration heap.
555    */
556   struct GNUNET_CONTAINER_HeapNode *hn;
557
558   /**
559    * Message queue we are providing for the #ch.
560    */
561   struct GNUNET_MQ_Handle *mq;
562
563   /**
564    * handle for this queue with the #ch.
565    */
566   struct GNUNET_TRANSPORT_QueueHandle *qh;
567
568   /**
569    * Timeout for this receiver address.
570    */
571   struct GNUNET_TIME_Absolute timeout;
572
573   /**
574    * MTU we allowed transport for this receiver right now.
575    */
576   size_t mtu;
577
578   /**
579    * Length of the DLL at @a ss_head.
580    */
581   unsigned int num_secrets;
582
583   /**
584    * Number of BOX keys from ACKs we have currently
585    * available for this receiver.
586    */
587   unsigned int acks_available;
588
589   /**
590    * Which network type does this queue use?
591    */
592   enum GNUNET_NetworkType nt;
593 };
594
595
596 /**
597  * Interface we broadcast our presence on.
598  */
599 struct BroadcastInterface
600 {
601
602   /**
603    * Kept in a DLL.
604    */
605   struct BroadcastInterface *next;
606
607   /**
608    * Kept in a DLL.
609    */
610   struct BroadcastInterface *prev;
611
612   /**
613    * Task for this broadcast interface.
614    */
615   struct GNUNET_SCHEDULER_Task *broadcast_task;
616
617   /**
618    * Sender's address of the interface.
619    */
620   struct sockaddr *sa;
621
622   /**
623    * Broadcast address to use on the interface.
624    */
625   struct sockaddr *ba;
626
627   /**
628    * Message we broadcast on this interface.
629    */
630   struct UDPBroadcast bcm;
631
632   /**
633    * If this is an IPv6 interface, this is the request
634    * we use to join/leave the group.
635    */
636   struct ipv6_mreq mcreq;
637
638   /**
639    * Number of bytes in @e sa.
640    */
641   socklen_t salen;
642
643   /**
644    * Was this interface found in the last #iface_proc() scan?
645    */
646   int found;
647 };
648
649
650 /**
651  * Cache of pre-generated key IDs.
652  */
653 static struct GNUNET_CONTAINER_MultiShortmap *key_cache;
654
655 /**
656  * ID of read task
657  */
658 static struct GNUNET_SCHEDULER_Task *read_task;
659
660 /**
661  * ID of timeout task
662  */
663 static struct GNUNET_SCHEDULER_Task *timeout_task;
664
665 /**
666  * ID of master broadcast task
667  */
668 static struct GNUNET_SCHEDULER_Task *broadcast_task;
669
670 /**
671  * For logging statistics.
672  */
673 static struct GNUNET_STATISTICS_Handle *stats;
674
675 /**
676  * Our environment.
677  */
678 static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
679
680 /**
681  * Receivers (map from peer identity to `struct ReceiverAddress`)
682  */
683 static struct GNUNET_CONTAINER_MultiPeerMap *receivers;
684
685 /**
686  * Senders (map from peer identity to `struct SenderAddress`)
687  */
688 static struct GNUNET_CONTAINER_MultiPeerMap *senders;
689
690 /**
691  * Expiration heap for senders (contains `struct SenderAddress`)
692  */
693 static struct GNUNET_CONTAINER_Heap *senders_heap;
694
695 /**
696  * Expiration heap for receivers (contains `struct ReceiverAddress`)
697  */
698 static struct GNUNET_CONTAINER_Heap *receivers_heap;
699
700 /**
701  * Broadcast interface tasks. Kept in a DLL.
702  */
703 static struct BroadcastInterface *bi_head;
704
705 /**
706  * Broadcast interface tasks. Kept in a DLL.
707  */
708 static struct BroadcastInterface *bi_tail;
709
710 /**
711  * Our socket.
712  */
713 static struct GNUNET_NETWORK_Handle *udp_sock;
714
715 /**
716  * #GNUNET_YES if #udp_sock supports IPv6.
717  */
718 static int have_v6_socket;
719
720 /**
721  * Our public key.
722  */
723 static struct GNUNET_PeerIdentity my_identity;
724
725 /**
726  * Our private key.
727  */
728 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
729
730 /**
731  * Our configuration.
732  */
733 static const struct GNUNET_CONFIGURATION_Handle *cfg;
734
735 /**
736  * Our handle to report addresses for validation to TRANSPORT.
737  */
738 static struct GNUNET_TRANSPORT_ApplicationHandle *ah;
739
740 /**
741  * Network scanner to determine network types.
742  */
743 static struct GNUNET_NT_InterfaceScanner *is;
744
745 /**
746  * Connection to NAT service.
747  */
748 static struct GNUNET_NAT_Handle *nat;
749
750 /**
751  * Port number to which we are actually bound.
752  */
753 static uint16_t my_port;
754
755
756 /**
757  * An interface went away, stop broadcasting on it.
758  *
759  * @param bi entity to close down
760  */
761 static void
762 bi_destroy (struct BroadcastInterface *bi)
763 {
764   if (AF_INET6 == bi->sa->sa_family)
765   {
766     /* Leave the multicast group */
767     if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt (udp_sock,
768                                                        IPPROTO_IPV6,
769                                                        IPV6_LEAVE_GROUP,
770                                                        &bi->mcreq,
771                                                        sizeof (bi->mcreq)))
772     {
773       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
774     }
775   }
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);
780   GNUNET_free (bi);
781 }
782
783
784 /**
785  * Destroys a receiving state due to timeout or shutdown.
786  *
787  * @param receiver entity to close down
788  */
789 static void
790 receiver_destroy (struct ReceiverAddress *receiver)
791 {
792   struct GNUNET_MQ_Handle *mq;
793
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))
798   {
799     receiver->mq = NULL;
800     GNUNET_MQ_destroy (mq);
801   }
802   if (NULL != receiver->qh)
803   {
804     GNUNET_TRANSPORT_communicator_mq_del (receiver->qh);
805     receiver->qh = NULL;
806   }
807   GNUNET_assert (GNUNET_YES ==
808                  GNUNET_CONTAINER_multipeermap_remove (receivers,
809                                                        &receiver->target,
810                                                        receiver));
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),
815                          GNUNET_NO);
816   GNUNET_free (receiver->address);
817   GNUNET_free (receiver->foreign_addr);
818   GNUNET_free (receiver);
819 }
820
821
822 /**
823  * Free memory used by key cache entry.
824  *
825  * @param kce the key cache entry
826  */
827 static void
828 kce_destroy (struct KeyCacheEntry *kce)
829 {
830   struct SharedSecret *ss = kce->ss;
831
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,
835                                                                       &kce->kid,
836                                                                       kce));
837   GNUNET_free (kce);
838 }
839
840
841 /**
842  * Compute @a kid.
843  *
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
847  */
848 static void
849 get_kid (const struct GNUNET_HashCode *msec,
850          uint32_t serial,
851          struct GNUNET_ShortHashCode *kid)
852 {
853   uint32_t sid = htonl (serial);
854
855   GNUNET_CRYPTO_hkdf (kid,
856                       sizeof (*kid),
857                       GCRY_MD_SHA512,
858                       GCRY_MD_SHA256,
859                       &sid,
860                       sizeof (sid),
861                       msec,
862                       sizeof (*msec),
863                       "UDP-KID",
864                       strlen ("UDP-KID"),
865                       NULL,
866                       0);
867 }
868
869
870 /**
871  * Setup key cache entry for sequence number @a seq and shared secret @a ss.
872  *
873  * @param ss shared secret
874  * @param seq sequence number for the key cache entry
875  */
876 static void
877 kce_generate (struct SharedSecret *ss, uint32_t seq)
878 {
879   struct KeyCacheEntry *kce;
880
881   GNUNET_assert (0 < seq);
882   kce = GNUNET_new (struct KeyCacheEntry);
883   kce->ss = ss;
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 (
889     key_cache,
890     &kce->kid,
891     kce,
892     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
893   GNUNET_STATISTICS_set (stats,
894                          "# KIDs active",
895                          GNUNET_CONTAINER_multishortmap_size (key_cache),
896                          GNUNET_NO);
897 }
898
899
900 /**
901  * Destroy @a ss and associated key cache entries.
902  *
903  * @param ss shared secret to destroy
904  */
905 static void
906 secret_destroy (struct SharedSecret *ss)
907 {
908   struct SenderAddress *sender;
909   struct ReceiverAddress *receiver;
910   struct KeyCacheEntry *kce;
911
912   if (NULL != (sender = ss->sender))
913   {
914     GNUNET_CONTAINER_DLL_remove (sender->ss_head, sender->ss_tail, ss);
915     sender->num_secrets--;
916   }
917   if (NULL != (receiver = ss->receiver))
918   {
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);
922   }
923   while (NULL != (kce = ss->kce_head))
924     kce_destroy (kce);
925   GNUNET_STATISTICS_update (stats, "# Secrets active", -1, GNUNET_NO);
926   GNUNET_STATISTICS_set (stats,
927                          "# KIDs active",
928                          GNUNET_CONTAINER_multishortmap_size (key_cache),
929                          GNUNET_NO);
930   GNUNET_free (ss);
931 }
932
933
934 /**
935  * Functions with this signature are called whenever we need
936  * to close a sender's state due to timeout.
937  *
938  * @param sender entity to close down
939  */
940 static void
941 sender_destroy (struct SenderAddress *sender)
942 {
943   GNUNET_assert (
944     GNUNET_YES ==
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,
948                          "# senders active",
949                          GNUNET_CONTAINER_multipeermap_size (senders),
950                          GNUNET_NO);
951   GNUNET_free (sender->address);
952   GNUNET_free (sender);
953 }
954
955
956 /**
957  * Compute @a key and @a iv.
958  *
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
963  */
964 static void
965 get_iv_key (const struct GNUNET_HashCode *msec,
966             uint32_t serial,
967             char key[AES_KEY_SIZE],
968             char iv[AES_IV_SIZE])
969 {
970   uint32_t sid = htonl (serial);
971   char res[AES_KEY_SIZE + AES_IV_SIZE];
972
973   GNUNET_CRYPTO_hkdf (res,
974                       sizeof (res),
975                       GCRY_MD_SHA512,
976                       GCRY_MD_SHA256,
977                       &sid,
978                       sizeof (sid),
979                       msec,
980                       sizeof (*msec),
981                       "UDP-IV-KEY",
982                       strlen ("UDP-IV-KEY"),
983                       NULL,
984                       0);
985   memcpy (key, res, AES_KEY_SIZE);
986   memcpy (iv, &res[AES_KEY_SIZE], AES_IV_SIZE);
987 }
988
989
990 /**
991  * Increment sender timeout due to activity.
992  *
993  * @param sender address for which the timeout should be rescheduled
994  */
995 static void
996 reschedule_sender_timeout (struct SenderAddress *sender)
997 {
998   sender->timeout =
999     GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1000   GNUNET_CONTAINER_heap_update_cost (sender->hn, sender->timeout.abs_value_us);
1001 }
1002
1003
1004 /**
1005  * Increment receiver timeout due to activity.
1006  *
1007  * @param receiver address for which the timeout should be rescheduled
1008  */
1009 static void
1010 reschedule_receiver_timeout (struct ReceiverAddress *receiver)
1011 {
1012   receiver->timeout =
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);
1016 }
1017
1018
1019 /**
1020  * Task run to check #receiver_heap and #sender_heap for timeouts.
1021  *
1022  * @param cls unused, NULL
1023  */
1024 static void
1025 check_timeouts (void *cls)
1026 {
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;
1032
1033   (void) cls;
1034   timeout_task = NULL;
1035   rt = GNUNET_TIME_UNIT_FOREVER_REL;
1036   while (NULL != (receiver = GNUNET_CONTAINER_heap_peek (receivers_heap)))
1037   {
1038     rt = GNUNET_TIME_absolute_get_remaining (receiver->timeout);
1039     if (0 != rt.rel_value_us)
1040       break;
1041     receiver_destroy (receiver);
1042   }
1043   st = GNUNET_TIME_UNIT_FOREVER_REL;
1044   while (NULL != (sender = GNUNET_CONTAINER_heap_peek (senders_heap)))
1045   {
1046     st = GNUNET_TIME_absolute_get_remaining (receiver->timeout);
1047     if (0 != st.rel_value_us)
1048       break;
1049     sender_destroy (sender);
1050   }
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);
1054 }
1055
1056
1057 /**
1058  * Calcualte cmac from master in @a ss.
1059  *
1060  * @param ss[in,out] data structure to complete
1061  */
1062 static void
1063 calculate_cmac (struct SharedSecret *ss)
1064 {
1065   GNUNET_CRYPTO_hkdf (&ss->cmac,
1066                       sizeof (ss->cmac),
1067                       GCRY_MD_SHA512,
1068                       GCRY_MD_SHA256,
1069                       "CMAC",
1070                       strlen ("CMAC"),
1071                       &ss->master,
1072                       sizeof (ss->master),
1073                       "UDP-CMAC",
1074                       strlen ("UDP-CMAC"),
1075                       NULL,
1076                       0);
1077 }
1078
1079
1080 /**
1081  * We received @a plaintext_len bytes of @a plaintext from a @a sender.
1082  * Pass it on to CORE.
1083  *
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
1087  */
1088 static void
1089 pass_plaintext_to_core (struct SenderAddress *sender,
1090                         const void *plaintext,
1091                         size_t plaintext_len)
1092 {
1093   const struct GNUNET_MessageHeader *hdr = plaintext;
1094
1095   while (ntohs (hdr->size) < plaintext_len)
1096   {
1097     GNUNET_STATISTICS_update (stats,
1098                               "# bytes given to core",
1099                               ntohs (hdr->size),
1100                               GNUNET_NO);
1101     (void)
1102       GNUNET_TRANSPORT_communicator_receive (ch,
1103                                              &sender->target,
1104                                              hdr,
1105                                              ADDRESS_VALIDITY_PERIOD,
1106                                              NULL /* no flow control possible */
1107                                              ,
1108                                              NULL);
1109     /* move on to next message, if any */
1110     plaintext_len -= ntohs (hdr->size);
1111     if (plaintext_len < sizeof (*hdr))
1112       break;
1113     hdr = plaintext + ntohs (hdr->size);
1114   }
1115   GNUNET_STATISTICS_update (stats,
1116                             "# bytes padding discarded",
1117                             plaintext_len,
1118                             GNUNET_NO);
1119 }
1120
1121
1122 /**
1123  * Setup @a cipher based on shared secret @a msec and
1124  * serial number @a serial.
1125  *
1126  * @param msec master shared secret
1127  * @param serial serial number of cipher to set up
1128  * @param cipher[out] cipher to initialize
1129  */
1130 static void
1131 setup_cipher (const struct GNUNET_HashCode *msec,
1132               uint32_t serial,
1133               gcry_cipher_hd_t *cipher)
1134 {
1135   char key[AES_KEY_SIZE];
1136   char iv[AES_IV_SIZE];
1137
1138   gcry_cipher_open (cipher,
1139                     GCRY_CIPHER_AES256 /* low level: go for speed */,
1140                     GCRY_CIPHER_MODE_GCM,
1141                     0 /* flags */);
1142   get_iv_key (msec, serial, key, iv);
1143   gcry_cipher_setkey (*cipher, key, sizeof (key));
1144   gcry_cipher_setiv (*cipher, iv, sizeof (iv));
1145 }
1146
1147
1148 /**
1149  * Try to decrypt @a buf using shared secret @a ss and key/iv
1150  * derived using @a serial.
1151  *
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
1159  */
1160 static int
1161 try_decrypt (const struct SharedSecret *ss,
1162              const char tag[GCM_TAG_SIZE],
1163              uint32_t serial,
1164              const char *in_buf,
1165              size_t in_buf_size,
1166              char *out_buf)
1167 {
1168   gcry_cipher_hd_t cipher;
1169
1170   setup_cipher (&ss->master, serial, &cipher);
1171   GNUNET_assert (
1172     0 ==
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))
1175   {
1176     gcry_cipher_close (cipher);
1177     GNUNET_STATISTICS_update (stats,
1178                               "# AEAD authentication failures",
1179                               1,
1180                               GNUNET_NO);
1181     return GNUNET_SYSERR;
1182   }
1183   gcry_cipher_close (cipher);
1184   return GNUNET_OK;
1185 }
1186
1187
1188 /**
1189  * Setup shared secret for decryption.
1190  *
1191  * @param ephemeral ephemeral key we received from the other peer
1192  * @return new shared secret
1193  */
1194 static struct SharedSecret *
1195 setup_shared_secret_dec (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1196 {
1197   struct SharedSecret *ss;
1198
1199   ss = GNUNET_new (struct SharedSecret);
1200   GNUNET_CRYPTO_eddsa_ecdh (my_private_key, ephemeral, &ss->master);
1201   return ss;
1202 }
1203
1204
1205 /**
1206  * Setup shared secret for encryption.
1207  *
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
1211  */
1212 static struct SharedSecret *
1213 setup_shared_secret_enc (const struct GNUNET_CRYPTO_EcdhePrivateKey *ephemeral,
1214                          struct ReceiverAddress *receiver)
1215 {
1216   struct SharedSecret *ss;
1217
1218   ss = GNUNET_new (struct SharedSecret);
1219   GNUNET_CRYPTO_ecdh_eddsa (ephemeral,
1220                             &receiver->target.public_key,
1221                             &ss->master);
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);
1227   return ss;
1228 }
1229
1230
1231 /**
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.
1235  *
1236  * @param receiver receiver to setup MQ for
1237  */
1238 static void
1239 setup_receiver_mq (struct ReceiverAddress *receiver);
1240
1241
1242 /**
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.
1246  *
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
1251  */
1252 static int
1253 handle_ack (void *cls, const struct GNUNET_PeerIdentity *pid, void *value)
1254 {
1255   const struct UDPAck *ack = cls;
1256   struct ReceiverAddress *receiver = value;
1257
1258   (void) pid;
1259   for (struct SharedSecret *ss = receiver->ss_head; NULL != ss; ss = ss->next)
1260   {
1261     if (0 == memcmp (&ack->cmac, &ss->cmac, sizeof (struct GNUNET_HashCode)))
1262     {
1263       uint32_t allowed;
1264
1265       allowed = ntohl (ack->sequence_max);
1266
1267       if (allowed > ss->sequence_allowed)
1268       {
1269         receiver->acks_available += (allowed - ss->sequence_allowed);
1270         if ((allowed - ss->sequence_allowed) == receiver->acks_available)
1271         {
1272           /* we just incremented from zero => MTU change! */
1273           setup_receiver_mq (receiver);
1274         }
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);
1279       }
1280       return GNUNET_NO;
1281     }
1282   }
1283   return GNUNET_YES;
1284 }
1285
1286
1287 /**
1288  * Test if we have received a valid message in plaintext.
1289  * If so, handle it.
1290  *
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
1294  */
1295 static void
1296 try_handle_plaintext (struct SenderAddress *sender,
1297                       const void *buf,
1298                       size_t buf_size)
1299 {
1300   const struct GNUNET_MessageHeader *hdr =
1301     (const struct GNUNET_MessageHeader *) buf;
1302   const struct UDPAck *ack = (const struct UDPAck *) buf;
1303   uint16_t type;
1304
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);
1310   switch (type)
1311   {
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,
1315                                                 &sender->target,
1316                                                 &handle_ack,
1317                                                 (void *) ack);
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);
1322     break;
1323   case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD:
1324     /* skip padding */
1325     break;
1326   default:
1327     pass_plaintext_to_core (sender, buf, buf_size);
1328   }
1329 }
1330
1331
1332 /**
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
1336  * recently).
1337  *
1338  * @param ss shared secret to generate ACKs for
1339  */
1340 static void
1341 consider_ss_ack (struct SharedSecret *ss)
1342 {
1343   GNUNET_assert (NULL != ss->sender);
1344   /* drop ancient KeyCacheEntries */
1345   while ((NULL != ss->kce_head) &&
1346          (MAX_SQN_DELTA <
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)
1350   {
1351     struct UDPAck ack;
1352
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,
1362                                           &ack.header);
1363   }
1364 }
1365
1366
1367 /**
1368  * We received a @a box with matching @a kce.  Decrypt and process it.
1369  *
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
1373  */
1374 static void
1375 decrypt_box (const struct UDPBox *box,
1376              size_t box_len,
1377              struct KeyCacheEntry *kce)
1378 {
1379   struct SharedSecret *ss = kce->ss;
1380   char out_buf[box_len - sizeof (*box)];
1381
1382   GNUNET_assert (NULL != ss->sender);
1383   if (GNUNET_OK != try_decrypt (ss,
1384                                 box->gcm_tag,
1385                                 kce->sequence_number,
1386                                 (const char *) &box[1],
1387                                 sizeof (out_buf),
1388                                 out_buf))
1389   {
1390     GNUNET_STATISTICS_update (stats,
1391                               "# Decryption failures with valid KCE",
1392                               1,
1393                               GNUNET_NO);
1394     kce_destroy (kce);
1395     return;
1396   }
1397   kce_destroy (kce);
1398   GNUNET_STATISTICS_update (stats,
1399                             "# bytes decrypted with BOX",
1400                             sizeof (out_buf),
1401                             GNUNET_NO);
1402   try_handle_plaintext (ss->sender, out_buf, sizeof (out_buf));
1403   consider_ss_ack (ss);
1404 }
1405
1406
1407 /**
1408  * Closure for #find_sender_by_address()
1409  */
1410 struct SearchContext
1411 {
1412   /**
1413    * Address we are looking for.
1414    */
1415   const struct sockaddr *address;
1416
1417   /**
1418    * Number of bytes in @e address.
1419    */
1420   socklen_t address_len;
1421
1422   /**
1423    * Return value to set if we found a match.
1424    */
1425   struct SenderAddress *sender;
1426 };
1427
1428
1429 /**
1430  * Find existing `struct SenderAddress` by matching addresses.
1431  *
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
1436  */
1437 static int
1438 find_sender_by_address (void *cls,
1439                         const struct GNUNET_PeerIdentity *key,
1440                         void *value)
1441 {
1442   struct SearchContext *sc = cls;
1443   struct SenderAddress *sender = value;
1444
1445   if ((sender->address_len == sc->address_len) &&
1446       (0 == memcmp (sender->address, sc->address, sender->address_len)))
1447   {
1448     sc->sender = sender;
1449     return GNUNET_NO; /* stop iterating! */
1450   }
1451   return GNUNET_YES;
1452 }
1453
1454
1455 /**
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.
1459  *
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
1465  */
1466 static struct SenderAddress *
1467 setup_sender (const struct GNUNET_PeerIdentity *target,
1468               const struct sockaddr *address,
1469               socklen_t address_len)
1470 {
1471   struct SenderAddress *sender;
1472   struct SearchContext sc = {.address = address,
1473                              .address_len = address_len,
1474                              .sender = NULL};
1475
1476   GNUNET_CONTAINER_multipeermap_get_multiple (senders,
1477                                               target,
1478                                               &find_sender_by_address,
1479                                               &sc);
1480   if (NULL != sc.sender)
1481   {
1482     reschedule_sender_timeout (sc.sender);
1483     return sc.sender;
1484   }
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 (
1490     senders,
1491     &sender->target,
1492     sender,
1493     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1494   GNUNET_STATISTICS_set (stats,
1495                          "# senders active",
1496                          GNUNET_CONTAINER_multipeermap_size (receivers),
1497                          GNUNET_NO);
1498   sender->timeout =
1499     GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1500   sender->hn = GNUNET_CONTAINER_heap_insert (senders_heap,
1501                                              sender,
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);
1506   return sender;
1507 }
1508
1509
1510 /**
1511  * Check signature from @a uc against @a ephemeral.
1512  *
1513  * @param ephermal key that is signed
1514  * @param uc signature of claimant
1515  * @return #GNUNET_OK if signature is valid
1516  */
1517 static int
1518 verify_confirmation (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral,
1519                      const struct UDPConfirmation *uc)
1520 {
1521   struct UdpHandshakeSignature uhs;
1522
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,
1530                                      &uhs.purpose,
1531                                      &uc->sender_sig,
1532                                      &uc->sender.public_key);
1533 }
1534
1535
1536 /**
1537  * Converts @a address to the address string format used by this
1538  * communicator in HELLOs.
1539  *
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
1543  */
1544 static char *
1545 sockaddr_to_udpaddr_string (const struct sockaddr *address,
1546                             socklen_t address_len)
1547 {
1548   char *ret;
1549
1550   switch (address->sa_family)
1551   {
1552   case AF_INET:
1553     GNUNET_asprintf (&ret,
1554                      "%s-%s",
1555                      COMMUNICATOR_ADDRESS_PREFIX,
1556                      GNUNET_a2s (address, address_len));
1557     break;
1558   case AF_INET6:
1559     GNUNET_asprintf (&ret,
1560                      "%s-%s",
1561                      COMMUNICATOR_ADDRESS_PREFIX,
1562                      GNUNET_a2s (address, address_len));
1563     break;
1564   default:
1565     GNUNET_assert (0);
1566   }
1567   return ret;
1568 }
1569
1570
1571 /**
1572  * Socket read task.
1573  *
1574  * @param cls NULL
1575  */
1576 static void
1577 sock_read (void *cls)
1578 {
1579   struct sockaddr_storage sa;
1580   socklen_t salen = sizeof (sa);
1581   char buf[UINT16_MAX];
1582   ssize_t rcvd;
1583
1584   (void) cls;
1585   read_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1586                                              udp_sock,
1587                                              &sock_read,
1588                                              NULL);
1589   rcvd = GNUNET_NETWORK_socket_recvfrom (udp_sock,
1590                                          buf,
1591                                          sizeof (buf),
1592                                          (struct sockaddr *) &sa,
1593                                          &salen);
1594   if (-1 == rcvd)
1595   {
1596     GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "recv");
1597     return;
1598   }
1599
1600   /* first, see if it is a UDPBox */
1601   if (rcvd > sizeof (struct UDPBox))
1602   {
1603     const struct UDPBox *box;
1604     struct KeyCacheEntry *kce;
1605
1606     box = (const struct UDPBox *) buf;
1607     kce = GNUNET_CONTAINER_multishortmap_get (key_cache, &box->kid);
1608     if (NULL != kce)
1609     {
1610       decrypt_box (box, (size_t) rcvd, kce);
1611       return;
1612     }
1613   }
1614
1615   /* next, check if it is a broadcast */
1616   if (sizeof (struct UDPBroadcast) == rcvd)
1617   {
1618     const struct UDPBroadcast *ub;
1619     struct UdpBroadcastSignature uhs;
1620
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);
1626     if (GNUNET_OK ==
1627         GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST,
1628                                     &uhs.purpose,
1629                                     &ub->sender_sig,
1630                                     &ub->sender.public_key))
1631     {
1632       char *addr_s;
1633       struct GNUNET_TIME_Absolute expiration;
1634       enum GNUNET_NetworkType nt;
1635
1636       addr_s =
1637         sockaddr_to_udpaddr_string ((const struct sockaddr *) &sa, salen);
1638       GNUNET_STATISTICS_update (stats, "# broadcasts received", 1, GNUNET_NO);
1639       /* expire at the broadcast frequency, as then we'll get the next one
1640        * anyway */
1641       expiration = GNUNET_TIME_relative_to_absolute (BROADCAST_FREQUENCY);
1642       /* use our own mechanism to determine network type */
1643       nt =
1644         GNUNET_NT_scanner_get_type (is, (const struct sockaddr *) &sa, salen);
1645       GNUNET_TRANSPORT_application_validate (ah,
1646                                              &ub->sender,
1647                                              expiration,
1648                                              nt,
1649                                              addr_s);
1650       GNUNET_free (addr_s);
1651       return;
1652     }
1653     /* continue with KX, mostly for statistics... */
1654   }
1655
1656
1657   /* finally, test if it is a KX */
1658   if (rcvd < sizeof (struct UDPConfirmation) + sizeof (struct InitialKX))
1659   {
1660     GNUNET_STATISTICS_update (stats,
1661                               "# messages dropped (no kid, too small for KX)",
1662                               1,
1663                               GNUNET_NO);
1664     return;
1665   }
1666
1667   {
1668     const struct InitialKX *kx;
1669     struct SharedSecret *ss;
1670     char pbuf[rcvd - sizeof (struct InitialKX)];
1671     const struct UDPConfirmation *uc;
1672     struct SenderAddress *sender;
1673
1674     kx = (const struct InitialKX *) buf;
1675     ss = setup_shared_secret_dec (&kx->ephemeral);
1676     if (GNUNET_OK != try_decrypt (ss,
1677                                   kx->gcm_tag,
1678                                   0,
1679                                   &buf[sizeof (*kx)],
1680                                   sizeof (pbuf),
1681                                   pbuf))
1682     {
1683       GNUNET_free (ss);
1684       GNUNET_STATISTICS_update (
1685         stats,
1686         "# messages dropped (no kid, AEAD decryption failed)",
1687         1,
1688         GNUNET_NO);
1689       return;
1690     }
1691     uc = (const struct UDPConfirmation *) pbuf;
1692     if (GNUNET_OK != verify_confirmation (&kx->ephemeral, uc))
1693     {
1694       GNUNET_break_op (0);
1695       GNUNET_free (ss);
1696       GNUNET_STATISTICS_update (stats,
1697                                 "# messages dropped (sender signature invalid)",
1698                                 1,
1699                                 GNUNET_NO);
1700       return;
1701     }
1702     calculate_cmac (ss);
1703     sender = setup_sender (&uc->sender, (const struct sockaddr *) &sa, salen);
1704     ss->sender = sender;
1705     GNUNET_CONTAINER_DLL_insert (sender->ss_head, sender->ss_tail, ss);
1706     sender->num_secrets++;
1707     GNUNET_STATISTICS_update (stats, "# Secrets active", 1, GNUNET_NO);
1708     GNUNET_STATISTICS_update (stats,
1709                               "# messages decrypted without BOX",
1710                               1,
1711                               GNUNET_NO);
1712     try_handle_plaintext (sender, &uc[1], sizeof (pbuf) - sizeof (*uc));
1713     consider_ss_ack (ss);
1714     if (sender->num_secrets > MAX_SECRETS)
1715       secret_destroy (sender->ss_tail);
1716   }
1717 }
1718
1719
1720 /**
1721  * Convert UDP bind specification to a `struct sockaddr *`
1722  *
1723  * @param bindto bind specification to convert
1724  * @param[out] sock_len set to the length of the address
1725  * @return converted bindto specification
1726  */
1727 static struct sockaddr *
1728 udp_address_to_sockaddr (const char *bindto, socklen_t *sock_len)
1729 {
1730   struct sockaddr *in;
1731   unsigned int port;
1732   char dummy[2];
1733   char *colon;
1734   char *cp;
1735
1736   if (1 == SSCANF (bindto, "%u%1s", &port, dummy))
1737   {
1738     /* interpreting value as just a PORT number */
1739     if (port > UINT16_MAX)
1740     {
1741       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1742                   "BINDTO specification `%s' invalid: value too large for port\n",
1743                   bindto);
1744       return NULL;
1745     }
1746     if ((GNUNET_NO == GNUNET_NETWORK_test_pf (PF_INET6)) ||
1747         (GNUNET_YES ==
1748          GNUNET_CONFIGURATION_get_value_yesno (cfg,
1749                                                COMMUNICATOR_CONFIG_SECTION,
1750                                                "DISABLE_V6")))
1751     {
1752       struct sockaddr_in *i4;
1753
1754       i4 = GNUNET_malloc (sizeof (struct sockaddr_in));
1755       i4->sin_family = AF_INET;
1756       i4->sin_port = htons ((uint16_t) port);
1757       *sock_len = sizeof (struct sockaddr_in);
1758       in = (struct sockaddr *) i4;
1759     }
1760     else
1761     {
1762       struct sockaddr_in6 *i6;
1763
1764       i6 = GNUNET_malloc (sizeof (struct sockaddr_in6));
1765       i6->sin6_family = AF_INET6;
1766       i6->sin6_port = htons ((uint16_t) port);
1767       *sock_len = sizeof (struct sockaddr_in6);
1768       in = (struct sockaddr *) i6;
1769     }
1770     return in;
1771   }
1772   cp = GNUNET_strdup (bindto);
1773   colon = strrchr (cp, ':');
1774   if (NULL != colon)
1775   {
1776     /* interpet value after colon as port */
1777     *colon = '\0';
1778     colon++;
1779     if (1 == SSCANF (colon, "%u%1s", &port, dummy))
1780     {
1781       /* interpreting value as just a PORT number */
1782       if (port > UINT16_MAX)
1783       {
1784         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1785                     "BINDTO specification `%s' invalid: value too large for port\n",
1786                     bindto);
1787         GNUNET_free (cp);
1788         return NULL;
1789       }
1790     }
1791     else
1792     {
1793       GNUNET_log (
1794         GNUNET_ERROR_TYPE_ERROR,
1795         "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1796         bindto);
1797       GNUNET_free (cp);
1798       return NULL;
1799     }
1800   }
1801   else
1802   {
1803     /* interpret missing port as 0, aka pick any free one */
1804     port = 0;
1805   }
1806   {
1807     /* try IPv4 */
1808     struct sockaddr_in v4;
1809
1810     if (1 == inet_pton (AF_INET, cp, &v4))
1811     {
1812       v4.sin_port = htons ((uint16_t) port);
1813       in = GNUNET_memdup (&v4, sizeof (v4));
1814       *sock_len = sizeof (v4);
1815       GNUNET_free (cp);
1816       return in;
1817     }
1818   }
1819   {
1820     /* try IPv6 */
1821     struct sockaddr_in6 v6;
1822     const char *start;
1823
1824     start = cp;
1825     if (('[' == *cp) && (']' == cp[strlen (cp) - 1]))
1826     {
1827       start++; /* skip over '[' */
1828       cp[strlen (cp) - 1] = '\0'; /* eat ']' */
1829     }
1830     if (1 == inet_pton (AF_INET6, start, &v6))
1831     {
1832       v6.sin6_port = htons ((uint16_t) port);
1833       in = GNUNET_memdup (&v6, sizeof (v6));
1834       *sock_len = sizeof (v6);
1835       GNUNET_free (cp);
1836       return in;
1837     }
1838   }
1839   /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1840   GNUNET_free (cp);
1841   return NULL;
1842 }
1843
1844
1845 /**
1846  * Pad @a dgram by @a pad_size using @a out_cipher.
1847  *
1848  * @param out_cipher cipher to use
1849  * @param dgram datagram to pad
1850  * @param pad_size number of bytes of padding to append
1851  */
1852 static void
1853 do_pad (gcry_cipher_hd_t out_cipher, char *dgram, size_t pad_size)
1854 {
1855   char pad[pad_size];
1856
1857   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, pad, sizeof (pad));
1858   if (sizeof (pad) > sizeof (struct GNUNET_MessageHeader))
1859   {
1860     struct GNUNET_MessageHeader hdr =
1861       {.size = htons (sizeof (pad)),
1862        .type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD)};
1863
1864     memcpy (pad, &hdr, sizeof (hdr));
1865   }
1866   GNUNET_assert (
1867     0 ==
1868     gcry_cipher_encrypt (out_cipher, dgram, sizeof (pad), pad, sizeof (pad)));
1869 }
1870
1871
1872 /**
1873  * Signature of functions implementing the sending functionality of a
1874  * message queue.
1875  *
1876  * @param mq the message queue
1877  * @param msg the message to send
1878  * @param impl_state our `struct ReceiverAddress`
1879  */
1880 static void
1881 mq_send (struct GNUNET_MQ_Handle *mq,
1882          const struct GNUNET_MessageHeader *msg,
1883          void *impl_state)
1884 {
1885   struct ReceiverAddress *receiver = impl_state;
1886   uint16_t msize = ntohs (msg->size);
1887
1888   GNUNET_assert (mq == receiver->mq);
1889   if (msize > receiver->mtu)
1890   {
1891     GNUNET_break (0);
1892     receiver_destroy (receiver);
1893     return;
1894   }
1895   reschedule_receiver_timeout (receiver);
1896
1897   if (0 == receiver->acks_available)
1898   {
1899     /* use KX encryption method */
1900     struct UdpHandshakeSignature uhs;
1901     struct UDPConfirmation uc;
1902     struct InitialKX kx;
1903     struct GNUNET_CRYPTO_EcdhePrivateKey epriv;
1904     char dgram[receiver->mtu + sizeof (uc) + sizeof (kx)];
1905     size_t dpos;
1906     gcry_cipher_hd_t out_cipher;
1907     struct SharedSecret *ss;
1908
1909     /* setup key material */
1910     GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_ecdhe_key_create2 (&epriv));
1911
1912     ss = setup_shared_secret_enc (&epriv, receiver);
1913     setup_cipher (&ss->master, 0, &out_cipher);
1914     /* compute 'uc' */
1915     uc.sender = my_identity;
1916     uc.monotonic_time =
1917       GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1918     uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
1919     uhs.purpose.size = htonl (sizeof (uhs));
1920     uhs.sender = my_identity;
1921     uhs.receiver = receiver->target;
1922     GNUNET_CRYPTO_ecdhe_key_get_public (&epriv, &uhs.ephemeral);
1923     uhs.monotonic_time = uc.monotonic_time;
1924     GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_eddsa_sign (my_private_key,
1925                                                           &uhs.purpose,
1926                                                           &uc.sender_sig));
1927     /* Leave space for kx */
1928     dpos = sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
1929     /* Append encrypted uc to dgram */
1930     GNUNET_assert (0 == gcry_cipher_encrypt (out_cipher,
1931                                              &dgram[dpos],
1932                                              sizeof (uc),
1933                                              &uc,
1934                                              sizeof (uc)));
1935     dpos += sizeof (uc);
1936     /* Append encrypted payload to dgram */
1937     GNUNET_assert (
1938       0 == gcry_cipher_encrypt (out_cipher, &dgram[dpos], msize, msg, msize));
1939     dpos += msize;
1940     do_pad (out_cipher, &dgram[dpos], sizeof (dgram) - dpos);
1941     /* Datagram starts with kx */
1942     kx.ephemeral = uhs.ephemeral;
1943     GNUNET_assert (
1944       0 == gcry_cipher_gettag (out_cipher, kx.gcm_tag, sizeof (kx.gcm_tag)));
1945     gcry_cipher_close (out_cipher);
1946     memcpy (dgram, &kx, sizeof (kx));
1947     if (-1 == GNUNET_NETWORK_socket_sendto (udp_sock,
1948                                             dgram,
1949                                             sizeof (dgram),
1950                                             receiver->address,
1951                                             receiver->address_len))
1952       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "send");
1953     GNUNET_MQ_impl_send_continue (mq);
1954     return;
1955   } /* End of KX encryption method */
1956
1957   /* begin "BOX" encryption method, scan for ACKs from tail! */
1958   for (struct SharedSecret *ss = receiver->ss_tail; NULL != ss; ss = ss->prev)
1959   {
1960     if (ss->sequence_used < ss->sequence_allowed)
1961     {
1962       char dgram[sizeof (struct UDPBox) + receiver->mtu];
1963       struct UDPBox *box;
1964       gcry_cipher_hd_t out_cipher;
1965       size_t dpos;
1966
1967       box = (struct UDPBox *) dgram;
1968       ss->sequence_used++;
1969       get_kid (&ss->master, ss->sequence_used, &box->kid);
1970       setup_cipher (&ss->master, ss->sequence_used, &out_cipher);
1971       /* Append encrypted payload to dgram */
1972       dpos = sizeof (struct UDPBox);
1973       GNUNET_assert (
1974         0 == gcry_cipher_encrypt (out_cipher, &dgram[dpos], msize, msg, msize));
1975       dpos += msize;
1976       do_pad (out_cipher, &dgram[dpos], sizeof (dgram) - dpos);
1977       GNUNET_assert (0 == gcry_cipher_gettag (out_cipher,
1978                                               box->gcm_tag,
1979                                               sizeof (box->gcm_tag)));
1980       gcry_cipher_close (out_cipher);
1981       if (-1 == GNUNET_NETWORK_socket_sendto (udp_sock,
1982                                               dgram,
1983                                               sizeof (dgram),
1984                                               receiver->address,
1985                                               receiver->address_len))
1986         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "send");
1987       GNUNET_MQ_impl_send_continue (mq);
1988       receiver->acks_available--;
1989       if (0 == receiver->acks_available)
1990       {
1991         /* We have no more ACKs => MTU change! */
1992         setup_receiver_mq (receiver);
1993       }
1994       return;
1995     }
1996   }
1997   GNUNET_assert (0);
1998 }
1999
2000
2001 /**
2002  * Signature of functions implementing the destruction of a message
2003  * queue.  Implementations must not free @a mq, but should take care
2004  * of @a impl_state.
2005  *
2006  * @param mq the message queue to destroy
2007  * @param impl_state our `struct ReceiverAddress`
2008  */
2009 static void
2010 mq_destroy (struct GNUNET_MQ_Handle *mq, void *impl_state)
2011 {
2012   struct ReceiverAddress *receiver = impl_state;
2013
2014   if (mq == receiver->mq)
2015   {
2016     receiver->mq = NULL;
2017     receiver_destroy (receiver);
2018   }
2019 }
2020
2021
2022 /**
2023  * Implementation function that cancels the currently sent message.
2024  *
2025  * @param mq message queue
2026  * @param impl_state our `struct RecvierAddress`
2027  */
2028 static void
2029 mq_cancel (struct GNUNET_MQ_Handle *mq, void *impl_state)
2030 {
2031   /* Cancellation is impossible with UDP; bail */
2032   GNUNET_assert (0);
2033 }
2034
2035
2036 /**
2037  * Generic error handler, called with the appropriate
2038  * error code and the same closure specified at the creation of
2039  * the message queue.
2040  * Not every message queue implementation supports an error handler.
2041  *
2042  * @param cls our `struct ReceiverAddress`
2043  * @param error error code
2044  */
2045 static void
2046 mq_error (void *cls, enum GNUNET_MQ_Error error)
2047 {
2048   struct ReceiverAddress *receiver = cls;
2049
2050   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2051               "MQ error in queue to %s: %d\n",
2052               GNUNET_i2s (&receiver->target),
2053               (int) error);
2054   receiver_destroy (receiver);
2055 }
2056
2057
2058 /**
2059  * Setup the MQ for the @a receiver.  If a queue exists,
2060  * the existing one is destroyed.  Then the MTU is
2061  * recalculated and a fresh queue is initialized.
2062  *
2063  * @param receiver receiver to setup MQ for
2064  */
2065 static void
2066 setup_receiver_mq (struct ReceiverAddress *receiver)
2067 {
2068   size_t base_mtu;
2069
2070   if (NULL != receiver->qh)
2071   {
2072     GNUNET_TRANSPORT_communicator_mq_del (receiver->qh);
2073     receiver->qh = NULL;
2074   }
2075   GNUNET_assert (NULL == receiver->mq);
2076   switch (receiver->address->sa_family)
2077   {
2078   case AF_INET:
2079     base_mtu = 1480 /* Ethernet MTU, 1500 - Ethernet header - VLAN tag */
2080                - sizeof (struct GNUNET_TUN_IPv4Header) /* 20 */
2081                - sizeof (struct GNUNET_TUN_UdpHeader) /* 8 */;
2082     break;
2083   case AF_INET6:
2084     base_mtu = 1280 /* Minimum MTU required by IPv6 */
2085                - sizeof (struct GNUNET_TUN_IPv6Header) /* 40 */
2086                - sizeof (struct GNUNET_TUN_UdpHeader) /* 8 */;
2087     break;
2088   default:
2089     GNUNET_assert (0);
2090     break;
2091   }
2092   if (0 == receiver->acks_available)
2093   {
2094     /* MTU based on full KX messages */
2095     receiver->mtu = base_mtu - sizeof (struct InitialKX) /* 48 */
2096                     - sizeof (struct UDPConfirmation); /* 104 */
2097   }
2098   else
2099   {
2100     /* MTU based on BOXed messages */
2101     receiver->mtu = base_mtu - sizeof (struct UDPBox);
2102   }
2103   /* => Effective MTU for CORE will range from 1080 (IPv6 + KX) to
2104      1404 (IPv4 + Box) bytes, depending on circumstances... */
2105   receiver->mq = GNUNET_MQ_queue_for_callbacks (&mq_send,
2106                                                 &mq_destroy,
2107                                                 &mq_cancel,
2108                                                 receiver,
2109                                                 NULL,
2110                                                 &mq_error,
2111                                                 receiver);
2112   receiver->qh =
2113     GNUNET_TRANSPORT_communicator_mq_add (ch,
2114                                           &receiver->target,
2115                                           receiver->foreign_addr,
2116                                           receiver->mtu,
2117                                           receiver->nt,
2118                                           GNUNET_TRANSPORT_CS_OUTBOUND,
2119                                           receiver->mq);
2120 }
2121
2122
2123 /**
2124  * Setup a receiver for transmission.  Setup the MQ processing and
2125  * inform transport that the queue is ready.
2126  *
2127  * @param target which peer are we talking to
2128  * @param address address of the peer
2129  * @param address_len number of bytes in @a address
2130  * @return handle for the address
2131  */
2132 static struct ReceiverAddress *
2133 receiver_setup (const struct GNUNET_PeerIdentity *target,
2134                 const struct sockaddr *address,
2135                 socklen_t address_len)
2136 {
2137   struct ReceiverAddress *receiver;
2138
2139   receiver = GNUNET_new (struct ReceiverAddress);
2140   receiver->address = GNUNET_memdup (address, address_len);
2141   receiver->address_len = address_len;
2142   receiver->target = *target;
2143   receiver->nt = GNUNET_NT_scanner_get_type (is, address, address_len);
2144   (void) GNUNET_CONTAINER_multipeermap_put (
2145     receivers,
2146     &receiver->target,
2147     receiver,
2148     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2149   receiver->timeout =
2150     GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2151   receiver->hn = GNUNET_CONTAINER_heap_insert (receivers_heap,
2152                                                receiver,
2153                                                receiver->timeout.abs_value_us);
2154   GNUNET_STATISTICS_set (stats,
2155                          "# receivers active",
2156                          GNUNET_CONTAINER_multipeermap_size (receivers),
2157                          GNUNET_NO);
2158   receiver->foreign_addr =
2159     sockaddr_to_udpaddr_string (receiver->address, receiver->address_len);
2160   setup_receiver_mq (receiver);
2161
2162   if (NULL == timeout_task)
2163     timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts, NULL);
2164   return receiver;
2165 }
2166
2167
2168 /**
2169  * Function called by the transport service to initialize a
2170  * message queue given address information about another peer.
2171  * If and when the communication channel is established, the
2172  * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
2173  * to notify the service that the channel is now up.  It is
2174  * the responsibility of the communicator to manage sane
2175  * retries and timeouts for any @a peer/@a address combination
2176  * provided by the transport service.  Timeouts and retries
2177  * do not need to be signalled to the transport service.
2178  *
2179  * @param cls closure
2180  * @param peer identity of the other peer
2181  * @param address where to send the message, human-readable
2182  *        communicator-specific format, 0-terminated, UTF-8
2183  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is
2184  * invalid
2185  */
2186 static int
2187 mq_init (void *cls, const struct GNUNET_PeerIdentity *peer, const char *address)
2188 {
2189   struct ReceiverAddress *receiver;
2190   const char *path;
2191   struct sockaddr *in;
2192   socklen_t in_len;
2193
2194   if (0 != strncmp (address,
2195                     COMMUNICATOR_ADDRESS_PREFIX "-",
2196                     strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
2197   {
2198     GNUNET_break_op (0);
2199     return GNUNET_SYSERR;
2200   }
2201   path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
2202   in = udp_address_to_sockaddr (path, &in_len);
2203   receiver = receiver_setup (peer, in, in_len);
2204   (void) receiver;
2205   return GNUNET_OK;
2206 }
2207
2208
2209 /**
2210  * Iterator over all receivers to clean up.
2211  *
2212  * @param cls NULL
2213  * @param target unused
2214  * @param value the queue to destroy
2215  * @return #GNUNET_OK to continue to iterate
2216  */
2217 static int
2218 get_receiver_delete_it (void *cls,
2219                         const struct GNUNET_PeerIdentity *target,
2220                         void *value)
2221 {
2222   struct ReceiverAddress *receiver = value;
2223
2224   (void) cls;
2225   (void) target;
2226   receiver_destroy (receiver);
2227   return GNUNET_OK;
2228 }
2229
2230
2231 /**
2232  * Iterator over all senders to clean up.
2233  *
2234  * @param cls NULL
2235  * @param target unused
2236  * @param value the queue to destroy
2237  * @return #GNUNET_OK to continue to iterate
2238  */
2239 static int
2240 get_sender_delete_it (void *cls,
2241                       const struct GNUNET_PeerIdentity *target,
2242                       void *value)
2243 {
2244   struct SenderAddress *sender = value;
2245
2246   (void) cls;
2247   (void) target;
2248   sender_destroy (sender);
2249   return GNUNET_OK;
2250 }
2251
2252
2253 /**
2254  * Shutdown the UNIX communicator.
2255  *
2256  * @param cls NULL (always)
2257  */
2258 static void
2259 do_shutdown (void *cls)
2260 {
2261   if (NULL != nat)
2262   {
2263     GNUNET_NAT_unregister (nat);
2264     nat = NULL;
2265   }
2266   while (NULL != bi_head)
2267     bi_destroy (bi_head);
2268   if (NULL != broadcast_task)
2269   {
2270     GNUNET_SCHEDULER_cancel (broadcast_task);
2271     broadcast_task = NULL;
2272   }
2273   if (NULL != read_task)
2274   {
2275     GNUNET_SCHEDULER_cancel (read_task);
2276     read_task = NULL;
2277   }
2278   if (NULL != udp_sock)
2279   {
2280     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (udp_sock));
2281     udp_sock = NULL;
2282   }
2283   GNUNET_CONTAINER_multipeermap_iterate (receivers,
2284                                          &get_receiver_delete_it,
2285                                          NULL);
2286   GNUNET_CONTAINER_multipeermap_destroy (receivers);
2287   GNUNET_CONTAINER_multipeermap_iterate (senders, &get_sender_delete_it, NULL);
2288   GNUNET_CONTAINER_multipeermap_destroy (senders);
2289   GNUNET_CONTAINER_multishortmap_destroy (key_cache);
2290   GNUNET_CONTAINER_heap_destroy (senders_heap);
2291   GNUNET_CONTAINER_heap_destroy (receivers_heap);
2292   if (NULL != ch)
2293   {
2294     GNUNET_TRANSPORT_communicator_disconnect (ch);
2295     ch = NULL;
2296   }
2297   if (NULL != ah)
2298   {
2299     GNUNET_TRANSPORT_application_done (ah);
2300     ah = NULL;
2301   }
2302   if (NULL != stats)
2303   {
2304     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
2305     stats = NULL;
2306   }
2307   if (NULL != my_private_key)
2308   {
2309     GNUNET_free (my_private_key);
2310     my_private_key = NULL;
2311   }
2312   if (NULL != is)
2313   {
2314     GNUNET_NT_scanner_done (is);
2315     is = NULL;
2316   }
2317 }
2318
2319
2320 /**
2321  * Function called when the transport service has received a
2322  * backchannel message for this communicator (!) via a different return
2323  * path. Should be an acknowledgement.
2324  *
2325  * @param cls closure, NULL
2326  * @param sender which peer sent the notification
2327  * @param msg payload
2328  */
2329 static void
2330 enc_notify_cb (void *cls,
2331                const struct GNUNET_PeerIdentity *sender,
2332                const struct GNUNET_MessageHeader *msg)
2333 {
2334   const struct UDPAck *ack;
2335
2336   (void) cls;
2337   if ((ntohs (msg->type) != GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK) ||
2338       (ntohs (msg->size) != sizeof (struct UDPAck)))
2339   {
2340     GNUNET_break_op (0);
2341     return;
2342   }
2343   ack = (const struct UDPAck *) msg;
2344   GNUNET_CONTAINER_multipeermap_get_multiple (receivers,
2345                                               sender,
2346                                               &handle_ack,
2347                                               (void *) ack);
2348 }
2349
2350
2351 /**
2352  * Signature of the callback passed to #GNUNET_NAT_register() for
2353  * a function to call whenever our set of 'valid' addresses changes.
2354  *
2355  * @param cls closure
2356  * @param app_ctx[in,out] location where the app can store stuff
2357  *                  on add and retrieve it on remove
2358  * @param add_remove #GNUNET_YES to add a new public IP address,
2359  *                   #GNUNET_NO to remove a previous (now invalid) one
2360  * @param ac address class the address belongs to
2361  * @param addr either the previous or the new public IP address
2362  * @param addrlen actual length of the @a addr
2363  */
2364 static void
2365 nat_address_cb (void *cls,
2366                 void **app_ctx,
2367                 int add_remove,
2368                 enum GNUNET_NAT_AddressClass ac,
2369                 const struct sockaddr *addr,
2370                 socklen_t addrlen)
2371 {
2372   char *my_addr;
2373   struct GNUNET_TRANSPORT_AddressIdentifier *ai;
2374
2375   if (GNUNET_YES == add_remove)
2376   {
2377     enum GNUNET_NetworkType nt;
2378
2379     GNUNET_asprintf (&my_addr,
2380                      "%s-%s",
2381                      COMMUNICATOR_ADDRESS_PREFIX,
2382                      GNUNET_a2s (addr, addrlen));
2383     nt = GNUNET_NT_scanner_get_type (is, addr, addrlen);
2384     ai =
2385       GNUNET_TRANSPORT_communicator_address_add (ch,
2386                                                  my_addr,
2387                                                  nt,
2388                                                  GNUNET_TIME_UNIT_FOREVER_REL);
2389     GNUNET_free (my_addr);
2390     *app_ctx = ai;
2391   }
2392   else
2393   {
2394     ai = *app_ctx;
2395     GNUNET_TRANSPORT_communicator_address_remove (ai);
2396     *app_ctx = NULL;
2397   }
2398 }
2399
2400
2401 /**
2402  * Broadcast our presence on one of our interfaces.
2403  *
2404  * @param cls a `struct BroadcastInterface`
2405  */
2406 static void
2407 ifc_broadcast (void *cls)
2408 {
2409   struct BroadcastInterface *bi = cls;
2410   struct GNUNET_TIME_Relative delay;
2411
2412   delay = BROADCAST_FREQUENCY;
2413   delay.rel_value_us =
2414     GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, delay.rel_value_us);
2415   bi->broadcast_task =
2416     GNUNET_SCHEDULER_add_delayed (INTERFACE_SCAN_FREQUENCY, &ifc_broadcast, bi);
2417
2418   switch (bi->sa->sa_family)
2419   {
2420   case AF_INET: {
2421     static int yes = 1;
2422     static int no = 0;
2423     ssize_t sent;
2424
2425     if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt (udp_sock,
2426                                                        SOL_SOCKET,
2427                                                        SO_BROADCAST,
2428                                                        &yes,
2429                                                        sizeof (int)))
2430       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
2431     sent = GNUNET_NETWORK_socket_sendto (udp_sock,
2432                                          &bi->bcm,
2433                                          sizeof (bi->bcm),
2434                                          bi->ba,
2435                                          bi->salen);
2436     if (-1 == sent)
2437       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "sendto");
2438     if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt (udp_sock,
2439                                                        SOL_SOCKET,
2440                                                        SO_BROADCAST,
2441                                                        &no,
2442                                                        sizeof (int)))
2443       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
2444     break;
2445   }
2446   case AF_INET6: {
2447     ssize_t sent;
2448     struct sockaddr_in6 dst;
2449
2450     dst.sin6_family = AF_INET6;
2451     dst.sin6_port = htons (my_port);
2452     dst.sin6_addr = bi->mcreq.ipv6mr_multiaddr;
2453     dst.sin6_scope_id = ((struct sockaddr_in6 *) bi->ba)->sin6_scope_id;
2454
2455     sent = GNUNET_NETWORK_socket_sendto (udp_sock,
2456                                          &bi->bcm,
2457                                          sizeof (bi->bcm),
2458                                          (const struct sockaddr *) &dst,
2459                                          sizeof (dst));
2460     if (-1 == sent)
2461       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "sendto");
2462     break;
2463   }
2464   default:
2465     GNUNET_break (0);
2466     break;
2467   }
2468 }
2469
2470
2471 /**
2472  * Callback function invoked for each interface found.
2473  * Activates/deactivates broadcast interfaces.
2474  *
2475  * @param cls NULL
2476  * @param name name of the interface (can be NULL for unknown)
2477  * @param isDefault is this presumably the default interface
2478  * @param addr address of this interface (can be NULL for unknown or unassigned)
2479  * @param broadcast_addr the broadcast address (can be NULL for unknown or
2480  * unassigned)
2481  * @param netmask the network mask (can be NULL for unknown or unassigned)
2482  * @param addrlen length of the address
2483  * @return #GNUNET_OK to continue iteration, #GNUNET_SYSERR to abort
2484  */
2485 static int
2486 iface_proc (void *cls,
2487             const char *name,
2488             int isDefault,
2489             const struct sockaddr *addr,
2490             const struct sockaddr *broadcast_addr,
2491             const struct sockaddr *netmask,
2492             socklen_t addrlen)
2493 {
2494   struct BroadcastInterface *bi;
2495   enum GNUNET_NetworkType network;
2496   struct UdpBroadcastSignature ubs;
2497
2498   (void) cls;
2499   (void) netmask;
2500   network = GNUNET_NT_scanner_get_type (is, addr, addrlen);
2501   if (GNUNET_NT_LOOPBACK == network)
2502   {
2503     /* Broadcasting on loopback does not make sense */
2504     return GNUNET_YES;
2505   }
2506   if (NULL == addr)
2507     return GNUNET_YES; /* need to know our address! */
2508   for (bi = bi_head; NULL != bi; bi = bi->next)
2509   {
2510     if ((bi->salen == addrlen) && (0 == memcmp (addr, bi->sa, addrlen)))
2511     {
2512       bi->found = GNUNET_YES;
2513       return GNUNET_OK;
2514     }
2515   }
2516
2517   if ((AF_INET6 == addr->sa_family) && (NULL == broadcast_addr))
2518     return GNUNET_OK; /* broadcast_addr is required for IPv6! */
2519   if ((AF_INET6 == addr->sa_family) && (GNUNET_YES != have_v6_socket))
2520     return GNUNET_OK; /* not using IPv6 */
2521
2522   bi = GNUNET_new (struct BroadcastInterface);
2523   bi->sa = GNUNET_memdup (addr, addrlen);
2524   if (NULL != broadcast_addr)
2525     bi->ba = GNUNET_memdup (broadcast_addr, addrlen);
2526   bi->salen = addrlen;
2527   bi->found = GNUNET_YES;
2528   bi->bcm.sender = my_identity;
2529   ubs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
2530   ubs.purpose.size = htonl (sizeof (ubs));
2531   ubs.sender = my_identity;
2532   GNUNET_CRYPTO_hash (addr, addrlen, &ubs.h_address);
2533   GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_eddsa_sign (my_private_key,
2534                                                         &ubs.purpose,
2535                                                         &bi->bcm.sender_sig));
2536   bi->broadcast_task = GNUNET_SCHEDULER_add_now (&ifc_broadcast, bi);
2537   GNUNET_CONTAINER_DLL_insert (bi_head, bi_tail, bi);
2538   if ((AF_INET6 == addr->sa_family) && (NULL != broadcast_addr))
2539   {
2540     /* Create IPv6 multicast request */
2541     const struct sockaddr_in6 *s6 =
2542       (const struct sockaddr_in6 *) broadcast_addr;
2543
2544     GNUNET_assert (
2545       1 == inet_pton (AF_INET6, "FF05::13B", &bi->mcreq.ipv6mr_multiaddr));
2546
2547     /* http://tools.ietf.org/html/rfc2553#section-5.2:
2548      *
2549      * IPV6_JOIN_GROUP
2550      *
2551      * Join a multicast group on a specified local interface.  If the
2552      * interface index is specified as 0, the kernel chooses the local
2553      * interface.  For example, some kernels look up the multicast
2554      * group in the normal IPv6 routing table and using the resulting
2555      * interface; we do this for each interface, so no need to use
2556      * zero (anymore...).
2557      */
2558     bi->mcreq.ipv6mr_interface = s6->sin6_scope_id;
2559
2560     /* Join the multicast group */
2561     if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt (udp_sock,
2562                                                        IPPROTO_IPV6,
2563                                                        IPV6_JOIN_GROUP,
2564                                                        &bi->mcreq,
2565                                                        sizeof (bi->mcreq)))
2566     {
2567       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
2568     }
2569   }
2570   return GNUNET_OK;
2571 }
2572
2573
2574 /**
2575  * Scan interfaces to broadcast our presence on the LAN.
2576  *
2577  * @param cls NULL, unused
2578  */
2579 static void
2580 do_broadcast (void *cls)
2581 {
2582   struct BroadcastInterface *bin;
2583
2584   (void) cls;
2585   for (struct BroadcastInterface *bi = bi_head; NULL != bi; bi = bi->next)
2586     bi->found = GNUNET_NO;
2587   GNUNET_OS_network_interfaces_list (&iface_proc, NULL);
2588   for (struct BroadcastInterface *bi = bi_head; NULL != bi; bi = bin)
2589   {
2590     bin = bi->next;
2591     if (GNUNET_NO == bi->found)
2592       bi_destroy (bi);
2593   }
2594   broadcast_task = GNUNET_SCHEDULER_add_delayed (INTERFACE_SCAN_FREQUENCY,
2595                                                  &do_broadcast,
2596                                                  NULL);
2597 }
2598
2599
2600 /**
2601  * Setup communicator and launch network interactions.
2602  *
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
2607  */
2608 static void
2609 run (void *cls,
2610      char *const *args,
2611      const char *cfgfile,
2612      const struct GNUNET_CONFIGURATION_Handle *c)
2613 {
2614   char *bindto;
2615   struct sockaddr *in;
2616   socklen_t in_len;
2617   struct sockaddr_storage in_sto;
2618   socklen_t sto_len;
2619
2620   (void) cls;
2621   cfg = c;
2622   if (GNUNET_OK !=
2623       GNUNET_CONFIGURATION_get_value_filename (cfg,
2624                                                COMMUNICATOR_CONFIG_SECTION,
2625                                                "BINDTO",
2626                                                &bindto))
2627   {
2628     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2629                                COMMUNICATOR_CONFIG_SECTION,
2630                                "BINDTO");
2631     return;
2632   }
2633
2634   in = udp_address_to_sockaddr (bindto, &in_len);
2635   if (NULL == in)
2636   {
2637     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2638                 "Failed to setup UDP socket address with path `%s'\n",
2639                 bindto);
2640     GNUNET_free (bindto);
2641     return;
2642   }
2643   udp_sock =
2644     GNUNET_NETWORK_socket_create (in->sa_family, SOCK_DGRAM, IPPROTO_UDP);
2645   if (NULL == udp_sock)
2646   {
2647     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
2648     GNUNET_free (in);
2649     GNUNET_free (bindto);
2650     return;
2651   }
2652   if (AF_INET6 == in->sa_family)
2653     have_v6_socket = GNUNET_YES;
2654   if (GNUNET_OK != GNUNET_NETWORK_socket_bind (udp_sock, in, in_len))
2655   {
2656     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "bind", bindto);
2657     GNUNET_NETWORK_socket_close (udp_sock);
2658     udp_sock = NULL;
2659     GNUNET_free (in);
2660     GNUNET_free (bindto);
2661     return;
2662   }
2663   /* We might have bound to port 0, allowing the OS to figure it out;
2664      thus, get the real IN-address from the socket */
2665   sto_len = sizeof (in_sto);
2666   if (0 != getsockname (GNUNET_NETWORK_get_fd (udp_sock),
2667                         (struct sockaddr *) &in_sto,
2668                         &sto_len))
2669   {
2670     memcpy (&in_sto, in, in_len);
2671     sto_len = in_len;
2672   }
2673   GNUNET_free (in);
2674   GNUNET_free (bindto);
2675   in = (struct sockaddr *) &in_sto;
2676   in_len = sto_len;
2677   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2678               "Bound to `%s'\n",
2679               GNUNET_a2s ((const struct sockaddr *) &in_sto, sto_len));
2680   switch (in->sa_family)
2681   {
2682   case AF_INET:
2683     my_port = ntohs (((struct sockaddr_in *) in)->sin_port);
2684     break;
2685   case AF_INET6:
2686     my_port = ntohs (((struct sockaddr_in6 *) in)->sin6_port);
2687     break;
2688   default:
2689     GNUNET_break (0);
2690     my_port = 0;
2691   }
2692   stats = GNUNET_STATISTICS_create ("C-UDP", cfg);
2693   senders = GNUNET_CONTAINER_multipeermap_create (32, GNUNET_YES);
2694   receivers = GNUNET_CONTAINER_multipeermap_create (32, GNUNET_YES);
2695   senders_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2696   receivers_heap =
2697     GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2698   key_cache = GNUNET_CONTAINER_multishortmap_create (1024, GNUNET_YES);
2699   GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
2700   is = GNUNET_NT_scanner_init ();
2701   my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
2702   if (NULL == my_private_key)
2703   {
2704     GNUNET_log (
2705       GNUNET_ERROR_TYPE_ERROR,
2706       _ (
2707         "Transport service is lacking key configuration settings. Exiting.\n"));
2708     GNUNET_SCHEDULER_shutdown ();
2709     return;
2710   }
2711   GNUNET_CRYPTO_eddsa_key_get_public (my_private_key, &my_identity.public_key);
2712   /* start reading */
2713   read_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2714                                              udp_sock,
2715                                              &sock_read,
2716                                              NULL);
2717   ch = GNUNET_TRANSPORT_communicator_connect (cfg,
2718                                               COMMUNICATOR_CONFIG_SECTION,
2719                                               COMMUNICATOR_ADDRESS_PREFIX,
2720                                               GNUNET_TRANSPORT_CC_UNRELIABLE,
2721                                               &mq_init,
2722                                               NULL,
2723                                               &enc_notify_cb,
2724                                               NULL);
2725   if (NULL == ch)
2726   {
2727     GNUNET_break (0);
2728     GNUNET_SCHEDULER_shutdown ();
2729     return;
2730   }
2731   ah = GNUNET_TRANSPORT_application_init (cfg);
2732   if (NULL == ah)
2733   {
2734     GNUNET_break (0);
2735     GNUNET_SCHEDULER_shutdown ();
2736     return;
2737   }
2738   /* start broadcasting */
2739   if (GNUNET_YES !=
2740       GNUNET_CONFIGURATION_get_value_yesno (cfg,
2741                                             COMMUNICATOR_CONFIG_SECTION,
2742                                             "DISABLE_BROADCAST"))
2743   {
2744     broadcast_task = GNUNET_SCHEDULER_add_now (&do_broadcast, NULL);
2745   }
2746   nat = GNUNET_NAT_register (cfg,
2747                              COMMUNICATOR_CONFIG_SECTION,
2748                              IPPROTO_UDP,
2749                              1 /* one address */,
2750                              (const struct sockaddr **) &in,
2751                              &in_len,
2752                              &nat_address_cb,
2753                              NULL /* FIXME: support reversal: #5529 */,
2754                              NULL /* closure */);
2755 }
2756
2757
2758 /**
2759  * The main function for the UNIX communicator.
2760  *
2761  * @param argc number of arguments from the command line
2762  * @param argv command line arguments
2763  * @return 0 ok, 1 on error
2764  */
2765 int
2766 main (int argc, char *const *argv)
2767 {
2768   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2769     GNUNET_GETOPT_OPTION_END};
2770   int ret;
2771
2772   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
2773     return 2;
2774
2775   ret = (GNUNET_OK == GNUNET_PROGRAM_run (argc,
2776                                           argv,
2777                                           "gnunet-communicator-udp",
2778                                           _ ("GNUnet UDP communicator"),
2779                                           options,
2780                                           &run,
2781                                           NULL))
2782           ? 0
2783           : 1;
2784   GNUNET_free ((void *) argv);
2785   return ret;
2786 }
2787
2788
2789 /* end of gnunet-communicator-udp.c */