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