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