generate ACKs for backchannel
[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  * - main BOXed sending logic
28  * - figure out what to do with MTU: 1280 for IPv6 is obvious;
29  *   what for IPv4? 1500? Also, consider differences in 
30  *   headers for with/without box: need to give MIN of both
31  *   to TNG (as TNG expects a fixed MTU!), or maybe
32  *   we create a FRESH MQ while we have available BOXes SQNs?
33  *   (otherwise padding will REALLY hurt)
34  * - support DNS names in BINDTO option (#5528)
35  * - support NAT connection reversal method (#5529)
36  * - support other UDP-specific NAT traversal methods 
37  */
38 #include "platform.h"
39 #include "gnunet_util_lib.h"
40 #include "gnunet_protocols.h"
41 #include "gnunet_signatures.h"
42 #include "gnunet_constants.h"
43 #include "gnunet_nt_lib.h"
44 #include "gnunet_nat_service.h"
45 #include "gnunet_statistics_service.h"
46 #include "gnunet_transport_communication_service.h"
47
48 /**
49  * How many messages do we keep at most in the queue to the
50  * transport service before we start to drop (default,
51  * can be changed via the configuration file).
52  * Should be _below_ the level of the communicator API, as
53  * otherwise we may read messages just to have them dropped
54  * by the communicator API.
55  */
56 #define DEFAULT_MAX_QUEUE_LENGTH 8
57
58 /**
59  * How often do we rekey based on time (at least)
60  */ 
61 #define REKEY_TIME_INTERVAL GNUNET_TIME_UNIT_DAYS
62
63 /**
64  * How long do we wait until we must have received the initial KX?
65  */ 
66 #define PROTO_QUEUE_TIMEOUT GNUNET_TIME_UNIT_MINUTES
67
68 /**
69  * If we fall below this number of available KCNs,
70  * we generate additional ACKs until we reach
71  * #KCN_TARGET.
72  * Should be large enough that we don't generate ACKs all
73  * the time and still have enough time for the ACK to
74  * arrive before the sender runs out. So really this 
75  * should ideally be based on the RTT.
76  */
77 #define KCN_THRESHOLD 92
78
79 /**
80  * How many KCNs do we keep around *after* we hit
81  * the #KCN_THRESHOLD? Should be larger than
82  * #KCN_THRESHOLD so we do not generate just one
83  * ACK at the time.
84  */
85 #define KCN_TARGET 128
86
87 /**
88  * What is the maximum delta between KCN sequence numbers
89  * that we allow. Used to expire 'ancient' KCNs that likely
90  * were dropped by the network.  Must be larger than
91  * KCN_TARGET (otherwise we generate new KCNs all the time),
92  * but not too large (otherwise packet loss may cause
93  * sender to fall back to KX needlessly when sender runs
94  * out of ACK'ed KCNs due to losses).
95  */
96 #define MAX_SQN_DELTA 160
97
98 /**
99  * How often do we rekey based on number of bytes transmitted?
100  * (additionally randomized).
101  */ 
102 #define REKEY_MAX_BYTES (1024LLU * 1024 * 1024 * 4LLU)
103
104 /**
105  * Address prefix used by the communicator.
106  */
107 #define COMMUNICATOR_ADDRESS_PREFIX "udp"
108
109 /**
110  * Configuration section used by the communicator.
111  */
112 #define COMMUNICATOR_CONFIG_SECTION "communicator-udp"
113
114 GNUNET_NETWORK_STRUCT_BEGIN
115
116
117 /**
118  * Signature we use to verify that the ephemeral key was really chosen by
119  * the specified sender.  If possible, the receiver should respond with
120  * a `struct UDPAck` (possibly via backchannel).
121  */
122 struct UdpHandshakeSignature
123 {
124   /**
125    * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
126    */
127   struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
128
129   /**
130    * Identity of the inititor of the UDP connection (UDP client).
131    */ 
132   struct GNUNET_PeerIdentity sender;
133
134   /**
135    * Presumed identity of the target of the UDP connection (UDP server)
136    */ 
137   struct GNUNET_PeerIdentity receiver;
138
139   /**
140    * Ephemeral key used by the @e sender.
141    */ 
142   struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
143
144   /**
145    * Monotonic time of @e sender, to possibly help detect replay attacks
146    * (if receiver persists times by sender).
147    */ 
148   struct GNUNET_TIME_AbsoluteNBO monotonic_time;
149 };
150
151
152 /**
153  * "Plaintext" header at beginning of KX message. Followed
154  * by encrypted `struct UDPConfirmation`.
155  */
156 struct InitialKX
157 {
158
159   /**
160    * Ephemeral key for KX.
161    */ 
162   struct GNUNET_CRYPT_EddsaPublicKey ephemeral;
163
164   /**
165    * HMAC for the following encrypted message, using GCM.  HMAC uses
166    * key derived from the handshake with sequence number zero.
167    */ 
168   uint8_t gcm_tag[128/8];
169
170 };
171
172
173 /**
174  * Encrypted continuation of UDP initial handshake, followed
175  * by message header with payload.
176  */
177 struct UDPConfirmation
178 {
179   /**
180    * Sender's identity
181    */
182   struct GNUNET_PeerIdentity sender;
183
184   /**
185    * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
186    */
187   struct GNUNET_CRYPTO_EddsaSignature sender_sig;
188
189   /**
190    * Monotonic time of @e sender, to possibly help detect replay attacks
191    * (if receiver persists times by sender).
192    */ 
193   struct GNUNET_TIME_AbsoluteNBO monotonic_time;
194
195   /* followed by messages */
196
197   /* padding may follow actual messages */
198 };
199
200
201 /**
202  * UDP key acknowledgement.  May be sent via backchannel. Allows the
203  * sender to use `struct UDPBox` with the acknowledge key henceforth.
204  */ 
205 struct UDPAck
206 {
207
208   /**
209    * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK.
210    */ 
211   struct GNUNET_MessageHeader header;
212
213   /**
214    * Sequence acknowledgement limit. Specifies current maximum sequence
215    * number supported by receiver.
216    */ 
217   uint32_t sequence_max GNUNET_PACKED;
218   
219   /**
220    * CMAC of the base key being acknowledged.
221    */ 
222   struct GNUNET_HashCode cmac;
223
224 };
225
226
227 /**
228  * UDP message box.  Always sent encrypted, only allowed after
229  * the receiver sent a `struct UDPAck` for the base key!
230  */ 
231 struct UDPBox
232 {
233
234   /**
235    * Key and IV identification code. KDF applied to an acknowledged
236    * base key and a sequence number.  Sequence numbers must be used
237    * monotonically increasing up to the maximum specified in 
238    * `struct UDPAck`. Without further `struct UDPAck`s, the sender
239    * must fall back to sending handshakes!
240    */
241   struct GNUNET_ShortHashCode kid;
242
243   /**
244    * 128-bit authentication tag for the following encrypted message,
245    * from GCM.  MAC starts at the @e body_start that follows and
246    * extends until the end of the UDP payload.  If the @e hmac is
247    * wrong, the receiver should check if the message might be a
248    * `struct UdpHandshakeSignature`.
249    */ 
250   uint8_t gcm_tag[128/8];
251
252   
253 };
254
255
256 GNUNET_NETWORK_STRUCT_END
257
258 /**
259  * Shared secret we generated for a particular sender or receiver.
260  */
261 struct SharedSecret;
262
263
264 /**
265  * Pre-generated "kid" code (key and IV identification code) to
266  * quickly derive master key for a `struct UDPBox`.
267  */
268 struct KeyCacheEntry
269 {
270
271   /**
272    * Kept in a DLL.
273    */
274   struct KeyCacheEntry *next;
275   
276   /**
277    * Kept in a DLL.
278    */
279   struct KeyCacheEntry *prev;
280
281   /**
282    * Key and IV identification code. KDF applied to an acknowledged
283    * base key and a sequence number.  Sequence numbers must be used
284    * monotonically increasing up to the maximum specified in 
285    * `struct UDPAck`. Without further `struct UDPAck`s, the sender
286    * must fall back to sending handshakes!
287    */
288   struct GNUNET_ShortHashCode kid;
289
290   /**
291    * Corresponding shared secret.
292    */
293   struct SharedSecret *ss;
294
295   /**
296    * Sequence number used to derive this entry from master key.
297    */ 
298   uint32_t sequence_number;
299 };
300
301
302 /**
303  * Information we track per sender address we have recently been
304  * in contact with (decryption from sender).
305  */
306 struct SenderAddress;
307
308 /**
309  * Information we track per receiving address we have recently been
310  * in contact with (encryption to receiver).
311  */
312 struct ReceiverAddress;
313
314 /**
315  * Shared secret we generated for a particular sender or receiver.
316  */
317 struct SharedSecret
318 {
319   /**
320    * Kept in a DLL.
321    */
322   struct SharedSecret *next;
323
324   /**
325    * Kept in a DLL.
326    */
327   struct SharedSecret *prev;
328
329   /**
330    * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
331    */
332   struct KeyCacheEntry *kce_head;
333   
334   /**
335    * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
336    */
337   struct KeyCacheEntry *kce_tail;
338
339   /**
340    * Sender we use this shared secret with, or NULL.
341    */
342   struct SenderAddress *sender;
343
344   /**
345    * Receiver we use this shared secret with, or NULL.
346    */
347   struct ReceiverAddress *receiver;
348   
349   /**
350    * Master shared secret.
351    */ 
352   struct GNUNET_HashCode master;
353
354   /**
355    * CMAC is used to identify @e master in ACKs.
356    */ 
357   struct GNUNET_HashCode cmac;
358
359   /**
360    * Up to which sequence number did we use this @e master already?
361    * (for sending or receiving)
362    */ 
363   uint32_t sequence_used;
364
365   /**
366    * Up to which sequence number did the other peer allow us to use
367    * this key, or up to which number did we allow the other peer to
368    * use this key?
369    */
370   uint32_t sequence_allowed;
371
372   /**
373    * Number of active KCN entries.
374    */ 
375   unsigned int active_kce_count;
376 };
377
378
379 /**
380  * Information we track per sender address we have recently been
381  * in contact with (we decrypt messages from the sender).
382  */
383 struct SenderAddress
384 {
385
386   /**
387    * To whom are we talking to.
388    */
389   struct GNUNET_PeerIdentity target;  
390
391   /**
392    * Entry in sender expiration heap.
393    */ 
394   struct GNUNET_CONTAINER_HeapNode *hn;
395
396   /**
397    * Shared secrets we used with @e target, first used is head.
398    */
399   struct SharedSecret *ss_head;
400
401   /**
402    * Shared secrets we used with @e target, last used is tail.
403    */
404   struct SharedSecret *ss_tail;
405   
406   /**
407    * Address of the other peer.
408    */
409   struct sockaddr *address;
410   
411   /**
412    * Length of the address.
413    */
414   socklen_t address_len;
415
416   /**
417    * Timeout for this sender.
418    */
419   struct GNUNET_TIME_Absolute timeout;
420
421   /**
422    * Length of the DLL at @a ss_head.
423    */ 
424   unsigned int num_secrets;
425   
426   /**
427    * Which network type does this queue use?
428    */
429   enum GNUNET_NetworkType nt;
430   
431 };
432
433
434 /**
435  * Information we track per receiving address we have recently been
436  * in contact with (encryption to receiver).
437  */
438 struct ReceiverAddress
439 {
440
441   /**
442    * To whom are we talking to.
443    */
444   struct GNUNET_PeerIdentity target;  
445   
446   /**
447    * Shared secrets we received from @e target, first used is head.
448    */
449   struct SharedSecret *ss_head;
450
451   /**
452    * Shared secrets we received with @e target, last used is tail.
453    */
454   struct SharedSecret *ss_tail;
455
456   /**
457    * Address of the other peer.
458    */
459   struct sockaddr *address;
460   
461   /**
462    * Length of the address.
463    */
464   socklen_t address_len;
465
466   /**
467    * Message queue we are providing for the #ch.
468    */
469   struct GNUNET_MQ_Handle *mq;
470
471   /**
472    * handle for this queue with the #ch.
473    */
474   struct GNUNET_TRANSPORT_QueueHandle *qh;
475
476   /**
477    * Timeout for this receiver address.
478    */
479   struct GNUNET_TIME_Absolute timeout;
480
481   /**
482    * Length of the DLL at @a ss_head.
483    */ 
484   unsigned int num_secrets;
485   
486   /**
487    * Which network type does this queue use?
488    */
489   enum GNUNET_NetworkType nt;
490   
491 };
492
493
494 /**
495  * Cache of pre-generated key IDs.
496  */
497 static struct GNUNET_CONTINER_MultiShortMap *key_cache;
498
499 /**
500  * ID of read task
501  */
502 static struct GNUNET_SCHEDULER_Task *read_task;
503
504 /**
505  * ID of timeout task
506  */
507 static struct GNUNET_SCHEDULER_Task *timeout_task;
508
509 /**
510  * For logging statistics.
511  */
512 static struct GNUNET_STATISTICS_Handle *stats;
513
514 /**
515  * Our environment.
516  */
517 static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
518
519 /**
520  * Receivers (map from peer identity to `struct ReceiverAddress`)
521  */
522 static struct GNUNET_CONTAINER_MultiPeerMap *receivers;
523
524 /**
525  * Senders (map from peer identity to `struct SenderAddress`)
526  */
527 static struct GNUNET_CONTAINER_MultiPeerMap *senders;
528
529 /**
530  * Expiration heap for senders (contains `struct SenderAddress`)
531  */
532 static struct GNUNET_CONTAINER_Heap *senders_heap;
533
534 /**
535  * Expiration heap for receivers (contains `struct ReceiverAddress`)
536  */
537 static struct GNUNET_CONTAINER_Heap *receivers_heap;
538
539 /**
540  * Our socket.
541  */
542 static struct GNUNET_NETWORK_Handle *udp_sock;
543
544 /**
545  * Our public key.
546  */
547 static struct GNUNET_PeerIdentity my_identity;
548
549 /**
550  * Our private key.
551  */
552 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
553
554 /**
555  * Our configuration.
556  */
557 static const struct GNUNET_CONFIGURATION_Handle *cfg;
558
559 /**
560  * Network scanner to determine network types.
561  */
562 static struct GNUNET_NT_InterfaceScanner *is;
563
564 /**
565  * Connection to NAT service.
566  */
567 static struct GNUNET_NAT_Handle *nat;
568
569
570 /**
571  * Functions with this signature are called whenever we need
572  * to close a receiving state due to timeout.
573  *
574  * @param receiver entity to close down
575  */
576 static void
577 receiver_destroy (struct ReceiverAddress *receiver)
578 {
579   struct GNUNET_MQ_Handle *mq;
580   
581   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
582               "Disconnecting receiver for peer `%s'\n",
583               GNUNET_i2s (&receiver->target));
584   if (NULL != (mq = receiver->mq))
585   {
586     receiver->mq = NULL;
587     GNUNET_MQ_destroy (mq);
588   }
589   GNUNET_assert (GNUNET_YES ==
590                  GNUNET_CONTAINER_multipeermap_remove (receivers,
591                                                        &receiver->target,
592                                                        receiver));
593   GNUNET_assert (sender ==
594                  GNUNET_CONTAINER_heap_remove_node (receivers_heap,
595                                                     receiver->hn));
596   GNUNET_STATISTICS_set (stats,
597                          "# receivers active",
598                          GNUNET_CONTAINER_multipeermap_size (receivers),
599                          GNUNET_NO);
600   GNUNET_free (receiver->address);
601   GNUNET_free (receiver);
602 }
603
604
605 /**
606  * Free memory used by key cache entry.
607  *
608  * @param kce the key cache entry
609  */ 
610 static void
611 kce_destroy (struct KeyCacheEntry *kce)
612 {
613   struct SharedSecret *ss = kce->ss;
614
615   ss->active_kce_count--;
616   GNUNET_CONTAINER_DLL_remove (ss->kce_head,
617                                ss->kce_tail,
618                                kce);
619   GNUNET_assert (GNUNET_YES ==
620                  GNUNET_CONTAINER_multishortmap_remove (key_cache,
621                                                         &kce->kid,
622                                                         kce));
623   GNUNET_free (kce);
624 }
625
626
627 /**
628  * Compute @a kid.
629  *
630  * @param msec master secret for HMAC calculation
631  * @param serial number for the @a smac calculation
632  * @param kid[out] where to write the key ID
633  */
634 static void
635 get_kid (const struct GNUNET_HashCode *msec,
636          uint32_t serial,
637          struct GNUNET_ShortHashCode *kid)
638 {
639   uint32_t sid = htonl (serial);
640
641   GNUNET_CRYPTO_hkdf (kid,
642                       sizeof (*kid),
643                       GCRY_MD_SHA512,
644                       GCRY_MD_SHA256,
645                       &sid,
646                       sizeof (sid),
647                       msec,
648                       sizeof (*msec),
649                       "UDP-KID",
650                       strlen ("UDP-KID"),
651                       NULL, 0);
652 }
653
654
655 /**
656  * Setup key cache entry for sequence number @a seq and shared secret @a ss.
657  *
658  * @param ss shared secret
659  * @param seq sequence number for the key cache entry
660  */
661 static void
662 kce_generate (struct SharedSecret *ss,
663               uint32_t seq)
664 {
665   struct KeyCacheEntry *kce;
666
667   GNUNET_assert (0 < seq);
668   kce = GNUNET_new (struct KeyCacheEntry);
669   kce->ss = ss;
670   kce->sequence_number = seq;
671   get_kid (&ss->master,
672            seq,
673            &kce->kid);
674   GNUNET_CONTAINER_DLL_insert (ss->kce_head,
675                                ss->kce_tail,
676                                kce);
677   ss->active_kce_count++;
678   (void) GNUNET_CONTAINER_multishortmap_put (key_cache,
679                                              &kce->kid,
680                                              kce,
681                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
682   GNUNET_STATISTICS_set (stats,
683                          "# KIDs active",
684                          GNUNET_CONTAINER_multipeermap_size (key_cache),
685                          GNUNET_NO);
686 }
687
688
689 /**
690  * Destroy @a ss and associated key cache entries.
691  *
692  * @param ss shared secret to destroy
693  */
694 static void
695 secret_destroy (struct SharedSecret *ss)
696 {
697   struct SenderAddress *sender;
698   struct ReceiverAddress *receiver;
699   struct KeyCacheEntry *kce;
700
701   if (NULL != (sender = ss->sender))
702   {
703     GNUNET_CONTAINER_DLL_remove (sender->ss_head,
704                                  sender->ss_tail,
705                                  ss);
706     sender->num_secrets--;
707   }
708   if (NULL != (receiver = ss->receiver))
709   {
710     GNUNET_CONTAINER_DLL_remove (receiver->ss_head,
711                                  receiver->ss_tail,
712                                  ss);
713     receiver->num_secrets--;
714   }
715   while (NULL != (kce = ss->kce_head))
716     kce_destroy (kce);
717   GNUNET_STATISTICS_update (stats,
718                             "# Secrets active",
719                             -1,
720                             GNUNET_NO);
721   GNUNET_STATISTICS_set (stats,
722                          "# KIDs active",
723                          GNUNET_CONTAINER_multipeermap_size (key_cache),
724                          GNUNET_NO);
725   GNUNET_free (ss);
726 }
727
728
729 /**
730  * Functions with this signature are called whenever we need
731  * to close a sender's state due to timeout.
732  *
733  * @param sender entity to close down
734  */
735 static void
736 sender_destroy (struct SenderAddress *sender)
737 {
738   GNUNET_assert (GNUNET_YES ==
739                  GNUNET_CONTAINER_multipeermap_remove (senders,
740                                                        &sender->target,
741                                                        sender));
742   GNUNET_assert (sender ==
743                  GNUNET_CONTAINER_heap_remove_node (senders_heap,
744                                                     sender->hn));
745   GNUNET_STATISTICS_set (stats,
746                          "# senders active",
747                          GNUNET_CONTAINER_multipeermap_size (senders),
748                          GNUNET_NO);
749   GNUNET_free (sender->address);
750   GNUNET_free (sender);
751 }
752
753
754 /**
755  * Compute @a smac over @a buf.
756  *
757  * @param msec master secret for HMAC calculation
758  * @param serial number for the @a smac calculation
759  * @param buf buffer to MAC
760  * @param buf_size number of bytes in @a buf
761  * @param smac[out] where to write the HMAC
762  */
763 static void
764 get_hmac (const struct GNUNET_HashCode *msec,
765           uint32_t serial,
766           const void *buf,
767           size_t buf_size,
768           struct GNUNET_ShortHashCode *smac)
769 {
770   uint32_t sid = htonl (serial);
771
772   GNUNET_CRYPTO_hkdf (smac,
773                       sizeof (*smac),
774                       GCRY_MD_SHA512,
775                       GCRY_MD_SHA256,
776                       &sid,
777                       sizeof (sid),
778                       msec,
779                       sizeof (*msec),
780                       "UDP-HMAC",
781                       strlen ("UDP-HMAC"),
782                       NULL, 0);
783 }
784
785
786 /**
787  * Compute @a key and @a iv.
788  *
789  * @param msec master secret for calculation
790  * @param serial number for the @a smac calculation
791  * @param key[out] where to write the decrption key
792  * @param iv[out] where to write the IV
793  */
794 static void
795 get_iv_key (const struct GNUNET_HashCode *msec,
796             uint32_t serial,
797             char key[256/8],
798             char iv[96/8])
799 {
800   uint32_t sid = htonl (serial);
801   char res[sizeof(key) + sizeof (iv)];
802
803   GNUNET_CRYPTO_hkdf (res,
804                       sizeof (res),
805                       GCRY_MD_SHA512,
806                       GCRY_MD_SHA256,
807                       &sid,
808                       sizeof (sid),
809                       msec,
810                       sizeof (*msec),
811                       "UDP-IV-KEY",
812                       strlen ("UDP-IV-KEY"),
813                       NULL, 0);
814   memcpy (key,
815           sid,
816           sizeof (key));
817   memcpy (iv,
818           &sid[sizeof(key)],
819           sizeof (iv));
820 }
821
822
823 /**
824  * Increment sender timeout due to activity.
825  *
826  * @param sender address for which the timeout should be rescheduled
827  */
828 static void
829 reschedule_sender_timeout (struct SenderAddress *sender)
830 {
831   sender->timeout
832     = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
833   GNUNET_CONTAINER_heap_update_cost (sender->hn,
834                                      sender.timeout.abs_value_us);
835 }
836
837
838 /**
839  * Increment receiver timeout due to activity.
840  *
841  * @param receiver address for which the timeout should be rescheduled
842  */
843 static void
844 reschedule_receiver_timeout (struct ReceiverAddress *receiver)
845 {
846   receiver->timeout
847     = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
848   GNUNET_CONTAINER_heap_update_cost (receiver->hn,
849                                      receiver.timeout.abs_value_us);
850 }
851
852
853 /**
854  * Task run to check #receiver_heap and #sender_heap for timeouts.
855  *
856  * @param cls unused, NULL
857  */
858 static void
859 check_timeouts (void *cls)
860 {
861   struct GNUNET_TIME_Relative st;
862   struct GNUNET_TIME_Relative rt;
863   struct GNUNET_TIME_Relative delay;
864   struct ReceiverAddress *receiver;
865   struct SenderAddress *sender;
866   
867   (void) cls;
868   timeout_task = NULL;
869   rt = GNUNET_TIME_UNIT_FOREVER_REL;
870   while (NULL != (receiver = GNUNET_CONTAINER_heap_peek (receivers_heap)))
871   {
872     rt = GNUNET_TIME_absolute_get_remaining (receiver->timeout);
873     if (0 != rt.rel_value_us)
874       break;
875     receiver_destroy (receiver);
876   }
877   st = GNUNET_TIME_UNIT_FOREVER_REL;
878   while (NULL != (sender = GNUNET_CONTAINER_heap_peek (senders_heap)))
879   {
880     st = GNUNET_TIME_absolute_get_remaining (receiver->timeout);
881     if (0 != st.rel_value_us)
882       break;
883     sender_destroy (sender);
884   }
885   delay = GNUNET_TIME_relative_min (rt,
886                                     st);
887   if (delay.rel_value_us < GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
888     timeout_task = GNUNET_SCHEDULER_add_delayed (delay,
889                                                  &check_timeouts,
890                                                  NULL);  
891 }
892                           
893
894 /**
895  * Calcualte cmac from master in @a ss.
896  *
897  * @param ss[in,out] data structure to complete
898  */
899 static void
900 calculate_cmac (struct SharedSecret *ss)
901 {
902   GNUNET_CRYPTO_hkdf (&ss->cmac,
903                       sizeof (ss->cmac),
904                       GCRY_MD_SHA512,
905                       GCRY_MD_SHA256,
906                       "CMAC",
907                       strlen ("CMAC"),
908                       &ss->master,
909                       sizeof (ss->master),
910                       "UDP-CMAC",
911                       strlen ("UDP-CMAC"),
912                       NULL, 0);
913 }
914
915
916 /**
917  * We received @a plaintext_len bytes of @a plaintext from a @a sender.
918  * Pass it on to CORE.  
919  *
920  * @param queue the queue that received the plaintext
921  * @param plaintext the plaintext that was received
922  * @param plaintext_len number of bytes of plaintext received
923  */ 
924 static void
925 pass_plaintext_to_core (struct SenderAddress *sender,
926                         const void *plaintext,
927                         size_t plaintext_len)
928 {
929   const struct GNUNET_MessageHeader *hdr = plaintext;
930
931   while (ntohs (hdr->size) < plaintext_len)
932   {
933     GNUNET_STATISTICS_update (stats,
934                               "# bytes given to core",
935                               ntohs (hdr->size),
936                               GNUNET_NO);
937     (void) GNUNET_TRANSPORT_communicator_receive (ch,
938                                                   &queue->target,
939                                                   hdr,
940                                                   NULL /* no flow control possible */,
941                                                   NULL);
942     /* move on to next message, if any */
943     plaintext_len -= ntohs (hdr->size);
944     if (plaintext_len < sizeof (*hdr))
945       break;
946     hdr = plaintext + ntohs (hdr->size);
947   }
948   GNUNET_STATISTICS_update (stats,
949                             "# bytes padding discarded",
950                             plaintext_len,
951                             GNUNET_NO);
952 }
953
954
955 /**
956  * Setup @a cipher based on shared secret @a msec and
957  * serial number @a serial.
958  *
959  * @param msec master shared secret
960  * @param serial serial number of cipher to set up
961  * @param cipher[out] cipher to initialize
962  */
963 static void
964 setup_cipher (const struct GNUNET_HashCode *msec,
965               uint32_t serial,
966               gcry_cipher_hd_t *cipher)
967 {
968   char key[256/8];
969   char iv[96/8];
970
971   gcry_cipher_open (cipher,
972                     GCRY_CIPHER_AES256 /* low level: go for speed */,
973                     GCRY_CIPHER_MODE_GCM,
974                     0 /* flags */);
975   get_iv_key (msec,
976               serial,
977               key,
978               iv);
979   gcry_cipher_setkey (*cipher,
980                       key,
981                       sizeof (key));
982   gcry_cipher_setiv (*cipher,
983                      iv,
984                      sizeof (iv));
985 }
986
987
988 /**
989  * Try to decrypt @a buf using shared secret @a ss and key/iv 
990  * derived using @a serial.
991  *
992  * @param ss shared secret
993  * @param tag GCM authentication tag
994  * @param serial serial number to use
995  * @param in_buf input buffer to decrypt
996  * @param in_buf_size number of bytes in @a in_buf and available in @a out_buf
997  * @param out_buf where to write the result
998  * @return #GNUNET_OK on success
999  */
1000 static int
1001 try_decrypt (const struct SharedSecret *ss,
1002              char tag[128/8],
1003              uint32_t serial,
1004              const char *in_buf,
1005              size_t in_buf_size,
1006              char *out_buf)
1007 {
1008   gcry_cipher_hd_t cipher;
1009
1010   setup_cipher (&ss->master,
1011                 serial,
1012                 &cipher);
1013   GNUNET_assert (0 ==
1014                  gcry_cipher_decrypt (cipher,
1015                                       in_buf,
1016                                       in_buf_size,
1017                                       out_buf,
1018                                       in_buf_size));
1019   if (0 !=
1020       gcry_cipher_checktag (cipher,
1021                             tag,
1022                             sizeof (tag)))
1023   {
1024     gcry_cipher_close (cipher);
1025     GNUNET_STATISTICS_update (stats,
1026                               "# AEAD authentication failures",
1027                               1,
1028                               GNUNET_NO);
1029     return GNUNET_SYSERR;
1030   }
1031   gcry_cipher_close (cipher);
1032   return GNUNET_OK;
1033 }
1034
1035
1036 /**
1037  * Setup shared secret for decryption.
1038  *
1039  * @param ephemeral ephemeral key we received from the other peer
1040  * @return new shared secret
1041  */
1042 static struct SharedSecret *
1043 setup_shared_secret_dec (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1044 {
1045   struct SharedSecret *ss;
1046
1047   ss = GNUNET_new (struct SharedSecret);
1048   GNUNET_CRYPTO_eddsa_ecdh (my_private_key,
1049                             ephemeral,
1050                             &ss->master);
1051   return ss;
1052 }
1053
1054
1055 /**
1056  * Setup shared secret for encryption.
1057  *
1058  * @param ephemeral ephemeral key we are sending to the other peer
1059  * @param receiver[in,out] queue to initialize encryption key for
1060  * @return new shared secret
1061  */
1062 static struct SharedSecret *
1063 setup_shared_secret_enc (const struct GNUNET_CRYPTO_EcdhePrivateKey *ephemeral,
1064                          struct ReceiverAddress *receiver)
1065 {
1066   struct SharedSecret *ss;
1067
1068   ss = GNUNET_new (struct SharedSecret);
1069   GNUNET_CRYPTO_ecdh_eddsa (ephemeral,
1070                             &receiver->target.public_key,
1071                             &ss->master);
1072   calculcate_cmac (ss);
1073   ss->receiver = receiver;
1074   GNUNET_CONTAINER_DLL_insert (receiver->ss_head,
1075                                receiver->ss_tail,
1076                                ss);
1077   receiver->num_secrets++;
1078   GNUNET_STATISTICS_update (stats,
1079                             "# Secrets active",
1080                             1,
1081                             GNUNET_NO);
1082   return ss;
1083 }
1084
1085
1086 /**
1087  * We received an ACK for @a pid. Check if it is for
1088  * the receiver in @a value and if so, handle it and
1089  * return #GNUNET_NO. Otherwise, return #GNUNET_YES.
1090  *
1091  * @param cls a `const struct UDPAck`
1092  * @param pid peer the ACK is from
1093  * @param value a `struct ReceiverAddress`
1094  * @return #GNUNET_YES to continue to iterate
1095  */
1096 static int
1097 handle_ack (void *cls,
1098             const struct GNUNET_PeerIdentity *pid,
1099             void *value)
1100 {
1101   const struct UDPAck *ack = cls;
1102   struct ReceiverAddress *receiver = value;
1103
1104   (void) pid;
1105   for (struct SharedSecret *ss = receiver->ss_head;
1106        NULL != ss;
1107        ss = ss->next)
1108   {
1109     if (0 == memcmp (&ack->cmac,
1110                      &ss->cmac,
1111                      sizeof (struct GNUNET_HashCode)))
1112     {
1113       ss->sequence_allowed = GNUNET_MAX (ss->sequence_allowed,
1114                                          ntohl (ack->sequence_max));
1115       /* move ss to head to avoid discarding it anytime soon! */
1116       GNUNET_CONTAINER_DLL_remove (sender->ss_head,
1117                                    sender->ss_tail,
1118                                    ss);
1119       GNUNET_CONTAINER_DLL_insert (sender->ss_head,
1120                                    sender->ss_tail,
1121                                    ss);
1122       /* FIXME: if this changed sequence_allowed,
1123          update MTU / MQ of 'receiver'! */
1124       return GNUNET_NO;
1125     }
1126   }
1127   return GNUNET_YES;
1128 }
1129
1130
1131 /**
1132  * Test if we have received a valid message in plaintext.
1133  * If so, handle it.
1134  *
1135  * @param sender peer to process inbound plaintext for
1136  * @param buf buffer we received
1137  * @param buf_size number of bytes in @a buf
1138  */ 
1139 static void
1140 try_handle_plaintext (struct SenderAddress *sender,
1141                       const void *buf,
1142                       size_t buf_size)
1143 {
1144   const struct GNUNET_MessageHeader *hdr
1145     = (const struct GNUNET_MessageHeader *) queue->pread_buf;
1146   const struct UDPAck *ack
1147     = (const struct UDPAck *) queue->pread_buf;
1148   uint16_t type;
1149
1150   if (sizeof (*hdr) > buf_size)
1151     return; /* not even a header */
1152   if (ntohs (hdr->size) > buf_size)
1153     return 0; /* not even a header */
1154   type = ntohs (hdr->type);
1155   switch (type)
1156   {
1157   case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK:
1158     /* lookup master secret by 'cmac', then update sequence_max */
1159     GNUNET_CONTAINER_multihashmap_get_multiple (receivers,
1160                                                 &sender->target,
1161                                                 &handle_ack,
1162                                                 (void *) ack);
1163     /* There could be more messages after the ACK, handle those as well */
1164     buf += ntohs (hdr->size);
1165     buf_size -= ntohs (hdr->size);
1166     pass_plaintext_to_core (sender,
1167                             buf,
1168                             buf_size);
1169     break;
1170   case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD:
1171     /* skip padding */
1172     break;
1173   default:
1174     pass_plaintext_to_core (sender,
1175                             buf,
1176                             buf_size);
1177   }
1178 }
1179
1180
1181 /**
1182  * We established a shared secret with a sender. We should try to send
1183  * the sender an `struct UDPAck` at the next opportunity to allow the
1184  * sender to use @a ss longer (assuming we did not yet already
1185  * recently).
1186  *
1187  * @param ss shared secret to generate ACKs for
1188  */
1189 static void
1190 consider_ss_ack (struct SharedSecret *ss)
1191 {
1192   GNUNET_assert (NULL != ss->sender);
1193   /* drop ancient KeyCacheEntries */
1194   while ( (NULL != ss->kce_head) &&
1195           (MAX_SQN_DELTA < ss->kce_head->sequence_number - ss->kce_tail->sequence_number) )
1196     kce_destroy (ss->kce_tail);
1197   if (ss->active_kce_count < KCN_THRESHOLD)
1198   {
1199     struct UDPAck ack;
1200
1201     while (ss->active_kce_count < KCN_TARGET)
1202       kce_generate (ss,
1203                     ++ss->sequence_used);
1204     ack.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK);
1205     ack.header.size = htons (sizeof (ack));
1206     ack.sequence_max = htonl (ss->sequence_max);
1207     ack.cmac = ss->cmac;
1208     GNUNET_TRANSPORT_communicator_notify (ch,
1209                                           &ss->sender->target,
1210                                           COMMUNICATOR_ADDRESS_PREFIX,
1211                                           &ack.header);
1212   }
1213 }
1214
1215
1216 /**
1217  * We received a @a box with matching @a kce.  Decrypt and process it.
1218  *
1219  * @param box the data we received
1220  * @param box_len number of bytes in @a box
1221  * @param kce key index to decrypt @a box
1222  */ 
1223 static void
1224 decrypt_box (const struct UDPBox *box,
1225              size_t box_len,
1226              struct KeyCacheEntry *kce)
1227 {
1228   struct SharedSecret *ss = kce->ss;
1229   gcry_cipher_hd_t cipher;
1230   char out_buf[box_len - sizeof (*box)];
1231
1232   GNUNET_assert (NULL != ss->sender);
1233   if (GNUNET_OK !=
1234       try_decrypt (ss,
1235                    box->gcm_tag,
1236                    kce->sequence_number,
1237                    box_len - sizeof (*box),
1238                    out_buf,
1239                    sizeof (out_buf)))
1240   {
1241     GNUNET_STATISTICS_update (stats,
1242                               "# Decryption failures with valid KCE",
1243                               1,
1244                               GNUNET_NO);
1245     kce_destroy (kce);
1246     return;
1247   }
1248   kce_destroy (kce);
1249   GNUNET_STATISTICS_update (stats,
1250                             "# bytes decrypted with BOX",
1251                             sizeof (out_buf),
1252                             GNUNET_NO);
1253   try_handle_plaintext (ss->sender,
1254                         out_buf,
1255                         sizeof (out_buf));
1256   consider_ss_ack (ss);
1257 }
1258
1259
1260 /**
1261  * Closure for #find_sender_by_address()
1262  */
1263 struct SearchContext
1264 {
1265   /**
1266    * Address we are looking for.
1267    */
1268   const struct sockaddr *address;
1269
1270   /**
1271    * Number of bytes in @e address.
1272    */
1273   socklen_t address_len;
1274
1275   /**
1276    * Return value to set if we found a match.
1277    */
1278   struct SenderAddress *sender;
1279 };
1280
1281
1282 /**
1283  * Find existing `struct SenderAddress` by matching addresses.
1284  *
1285  * @param cls a `struct SearchContext`
1286  * @param key ignored, must match already
1287  * @param value a `struct SenderAddress`
1288  * @return #GNUNET_YES if not found (continue to search), #GNUNET_NO if found
1289  */
1290 static int
1291 find_sender_by_address (void *cls,
1292                         const struct GNUNET_PeerIdentity *key,
1293                         void *value)
1294 {
1295   struct SearchContext *sc = cls;
1296   struct SenderAddress *sender = value;
1297
1298   if ( (sender->address_len == sc->address_len) &&
1299        (0 == memcmp (sender->address,
1300                      sc->address,
1301                      sender->address_len)) )
1302   {
1303     sc->sender = sender;
1304     return GNUNET_NO; /* stop iterating! */
1305   }
1306   return GNUNET_YES;
1307 }
1308
1309
1310 /**
1311  * Create sender address for @a target.  Note that we
1312  * might already have one, so a fresh one is only allocated
1313  * if one does not yet exist for @a address.
1314  *
1315  * @param target peer to generate address for
1316  * @param address target address 
1317  * @param address_len number of bytes in @a address
1318  * @return data structure to keep track of key material for
1319  *         decrypting data from @a target
1320  */
1321 static struct SenderAddress *
1322 setup_sender (const struct GNUNET_PeerIdentity *target,
1323               const struct sockaddr *address,
1324               socklen_t address_len)
1325 {
1326   struct SenderAddress *sender;
1327   struct SearchContext sc = {
1328     .address = address,
1329     .address_len = address_len,
1330     .sender = NULL
1331   };
1332
1333   GNUNET_CONTAINER_multihashmap_get_multiple (senders,
1334                                               target,
1335                                               &find_sender_by_address,
1336                                               &sc);
1337   if (NULL != sc.sender)
1338   {
1339     reschedule_sender_timeout (sc.sender);
1340     return sc.sender;
1341   }
1342   sender = GNUNET_new (struct SenderAddress);
1343   sender->target = *target;
1344   sender->address = GNUNET_memdup (address,
1345                                    address_len);
1346   sender->address_len = address_len;
1347   (void) GNUNET_CONTAINER_multihashmap_put (senders,
1348                                             &sender->target,
1349                                             sender,
1350                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1351   GNUNET_STATISTICS_set (stats,
1352                          "# senders active",
1353                          GNUNET_CONTAINER_multipeermap_size (receivers),
1354                          GNUNET_NO);
1355   sender->timeout
1356     = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1357   sender->hn = GNUNET_CONTAINER_heap_insert (senders_heap,
1358                                              sender,
1359                                              sender.timeout.abs_value_us);
1360   sender->nt = GNUNET_NT_scanner_get_type (is,
1361                                            address,
1362                                            address_len);
1363   if (NULL == timeout_task)
1364     timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts,
1365                                              NULL);
1366   return sender;
1367 }
1368
1369
1370 /**
1371  * Socket read task. 
1372  *
1373  * @param cls NULL
1374  */
1375 static void
1376 sock_read (void *cls)
1377 {
1378   struct sockaddr_storage sa;
1379   socklen_t salen = sizeof (sa);
1380   char buf[UINT16_MAX];
1381   ssize_t rcvd;
1382
1383   (void) cls;
1384   read_task
1385       = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1386                                        udp_sock,
1387                                        &sock_read,
1388                                        NULL);
1389   rcvd = GNUNET_NETWORK_socket_recvfrom (udp_sock,
1390                                          buf,
1391                                          sizeof (buf),
1392                                          (struct sockaddr *) &sa,
1393                                          &salen);
1394   if (-1 == rcvd)
1395   {
1396     GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1397                          "recv");
1398     return;
1399   }
1400   /* first, see if it is a UDPBox */
1401   if (rcvd > sizeof (struct UDPBox))
1402   {
1403     const struct UDPBox *box;
1404     struct KeyCacheEntry *kce;
1405
1406     box = (const struct UDPBox *) buf;
1407     kce = GNUNET_CONTAINER_multihashmap_get (key_cache,
1408                                              &box->kid);
1409     if (NULL != kce)
1410     {
1411       decrypt_box (box,
1412                    (size_t) rcvd,
1413                    kce);
1414       return;
1415     }
1416   }
1417   /* next, test if it is a KX */
1418   if (rcvd < sizeof (struct UDPConfirmation) + sizeof (struct InitialKX))
1419   {
1420     GNUNET_STATISTICS_update (stats,
1421                               "# messages dropped (no kid, too small for KX)",
1422                               1,
1423                               GNUNET_NO);
1424     return;
1425   }
1426
1427   {
1428     const struct InitialKX *kx;
1429     struct SharedSecret *ss;
1430     char pbuf[rcvd - sizeof (struct InitialKX)];
1431     const struct UDPConfirmation *uc;
1432     struct SenderAddress *sender;
1433
1434     kx = (const struct InitialKX *) buf;
1435     ss = setup_shared_secret_dec (&kx->ephemral);
1436     if (GNUNET_OK !=
1437         try_decrypt (ss,
1438                      0,
1439                      kx->gcm_tag,
1440                      &buf[sizeof (*kx)],
1441                      (const struct GNUNET_CRYPTO_EcdhePublicKey *) buf,
1442                      pbuf))
1443     {
1444       GNUNET_free (ss);
1445       GNUNET_STATISTICS_update (stats,
1446                                 "# messages dropped (no kid, AEAD decryption failed)",
1447                                 1,
1448                                 GNUNET_NO);
1449       return;
1450     }
1451     uc = (const struct UDPConfirmation *) pbuf;
1452     if (GNUNET_OK !=
1453         verify_confirmation (&kx->ephemeral,
1454                              uc))
1455     {
1456       GNUNET_break_op (0);
1457       GNUNET_free (ss);
1458       GNUNET_STATISTICS_update (stats,
1459                                 "# messages dropped (sender signature invalid)",
1460                                 1,
1461                                 GNUNET_NO);
1462       return;
1463     }
1464     calculcate_cmac (ss);
1465     sender = setup_sender (&uc->sender,
1466                            (const struct sockaddr *) &sa,
1467                            salen);
1468     ss->sender = sender;
1469     GNUNET_CONTAINER_DLL_insert (sender->ss_head,
1470                                  sender->ss_tail,
1471                                  ss);
1472     sender->num_secrets++;
1473     GNUNET_STATISTICS_update (stats,
1474                               "# Secrets active",
1475                               1,
1476                               GNUNET_NO);
1477     GNUNET_STATISTICS_update (stats,
1478                               "# messages decrypted without BOX",
1479                               1,
1480                               GNUNET_NO);
1481     try_handle_plaintext (sender,
1482                           &uc[1],
1483                           sizeof (pbuf) - sizeof (*uc));
1484     consider_ss_ack (ss);
1485     if (sender->num_secrets > MAX_SECRETS)
1486       secret_destroy (sender->ss_tail);
1487   }
1488 }
1489
1490
1491 /**
1492  * Convert UDP bind specification to a `struct sockaddr *`
1493  *
1494  * @param bindto bind specification to convert
1495  * @param[out] sock_len set to the length of the address
1496  * @return converted bindto specification
1497  */
1498 static struct sockaddr *
1499 udp_address_to_sockaddr (const char *bindto,
1500                          socklen_t *sock_len)
1501 {
1502   struct sockaddr *in;
1503   unsigned int port;
1504   char dummy[2];
1505   char *colon;
1506   char *cp;
1507   
1508   if (1 == SSCANF (bindto,
1509                    "%u%1s",
1510                    &port,
1511                    dummy))
1512   {
1513     /* interpreting value as just a PORT number */
1514     if (port > UINT16_MAX)
1515     {
1516       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1517                   "BINDTO specification `%s' invalid: value too large for port\n",
1518                   bindto);
1519       return NULL;
1520     }
1521     if (GNUNET_YES ==
1522         GNUNET_CONFIGURATION_get_value_yesno (cfg,
1523                                               COMMUNICATOR_CONFIG_SECTION,
1524                                               "DISABLE_V6"))
1525     {
1526       struct sockaddr_in *i4;
1527       
1528       i4 = GNUNET_malloc (sizeof (struct sockaddr_in));
1529       i4->sin_family = AF_INET;
1530       i4->sin_port = htons ((uint16_t) port);
1531       *sock_len = sizeof (struct sockaddr_in);
1532       in = (struct sockaddr *) i4;
1533     }
1534     else
1535     {
1536       struct sockaddr_in6 *i6;
1537       
1538       i6 = GNUNET_malloc (sizeof (struct sockaddr_in6));
1539       i6->sin6_family = AF_INET6;
1540       i6->sin6_port = htons ((uint16_t) port);
1541       *sock_len = sizeof (struct sockaddr_in6);
1542       in = (struct sockaddr *) i6;
1543     }
1544     return in;
1545   }
1546   cp = GNUNET_strdup (bindto);
1547   colon = strrchr (cp, ':');
1548   if (NULL != colon)
1549   {
1550     /* interpet value after colon as port */
1551     *colon = '\0';
1552     colon++;
1553     if (1 == SSCANF (colon,
1554                      "%u%1s",
1555                      &port,
1556                      dummy))
1557     {
1558       /* interpreting value as just a PORT number */
1559       if (port > UINT16_MAX)
1560       {
1561         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1562                     "BINDTO specification `%s' invalid: value too large for port\n",
1563                     bindto);
1564         GNUNET_free (cp);
1565         return NULL;
1566       }
1567     }
1568     else
1569     {
1570       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1571                   "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1572                   bindto);
1573       GNUNET_free (cp);
1574       return NULL;
1575     }
1576   }
1577   else
1578   {
1579     /* interpret missing port as 0, aka pick any free one */
1580     port = 0;
1581   }
1582   {
1583     /* try IPv4 */
1584     struct sockaddr_in v4;
1585
1586     if (1 == inet_pton (AF_INET,
1587                         cp,
1588                         &v4))
1589     {
1590       v4.sin_port = htons ((uint16_t) port);
1591       in = GNUNET_memdup (&v4,
1592                           sizeof (v4));
1593       *sock_len = sizeof (v4);
1594       GNUNET_free (cp);
1595       return in;
1596     }
1597   }
1598   {
1599     /* try IPv6 */
1600     struct sockaddr_in6 v6;
1601     const char *start;
1602
1603     start = cp;
1604     if ( ('[' == *cp) &&
1605          (']' == cp[strlen (cp)-1]) )
1606     {
1607       start++; /* skip over '[' */
1608       cp[strlen (cp) -1] = '\0'; /* eat ']' */
1609     }
1610     if (1 == inet_pton (AF_INET6,
1611                         start,
1612                         &v6))
1613     {
1614       v6.sin6_port = htons ((uint16_t) port);
1615       in = GNUNET_memdup (&v6,
1616                           sizeof (v6));
1617       *sock_len = sizeof (v6);
1618       GNUNET_free (cp);
1619       return in;
1620     }
1621   }
1622   /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1623   GNUNET_free (cp);
1624   return NULL;
1625 }
1626
1627
1628 /**
1629  * Signature of functions implementing the sending functionality of a
1630  * message queue.
1631  *
1632  * @param mq the message queue
1633  * @param msg the message to send
1634  * @param impl_state our `struct ReceiverAddress`
1635  */
1636 static void
1637 mq_send (struct GNUNET_MQ_Handle *mq,
1638          const struct GNUNET_MessageHeader *msg,
1639          void *impl_state)
1640 {
1641   struct ReceiverAddress *receiver = impl_state;
1642   uint16_t msize = ntohs (msg->size);
1643
1644   GNUNET_assert (mq == receiver->mq);
1645   if (msize > receiver->mtu)
1646   {
1647     GNUNET_break (0);
1648     receiver_destroy (receiver);
1649     return;
1650   }
1651   
1652   // FIXME: add support for BOX encryption method!
1653
1654   /* KX encryption method */
1655   {
1656     struct UdpHandshakeSignature uhs;
1657     struct UdpConfirmation uc;
1658     struct InitialKX kx;
1659     struct GNUNET_CRYPTO_EcdhePrivateKey epriv;
1660     char dgram[receiver->mtu +
1661                sizeof (uc) +
1662                sizeof (kx)];
1663     size_t dpos;
1664
1665     GNUNET_assert (GNUNET_OK ==
1666                    GNUNET_CRYPTO_ecdhe_key_create2 (&epriv)); 
1667     /* compute 'uc' */
1668     uc.sender = my_identity;
1669     uc.monotonic_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1670     uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
1671     uhs.purpose.size = htonl (sizeof (uhs));
1672     uhs.sender = my_identity;
1673     uhs.receiver = receiver->target;
1674     GNUNET_CRYPTO_ecdhe_key_get_public (&epriv,
1675                                         &uhs.ephemeral);
1676     uhs.monotonic_time = uc.monotonic_time;
1677     GNUNET_assert (GNUNET_OK ==
1678                    GNUNET_CRYPTO_eddsa_sign (my_private_key,
1679                                              &uhs.purpose,
1680                                              &uc.sender_sig));
1681     /* Leave space for kx */
1682     dpos = sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
1683     /* Append encrypted uc to dgram */
1684     GNUNET_assert (0 ==
1685                    gcry_cipher_encrypt (out_cipher,
1686                                         &dgram[dpos],
1687                                         sizeof (uc),
1688                                         &uc,
1689                                         sizeof (uc)));
1690     dpos += sizeof (uc);
1691     /* Append encrypted payload to dgram */
1692     GNUNET_assert (0 ==
1693                    gcry_cipher_encrypt (out_cipher,
1694                                         &dgram[dpos],
1695                                         msize,
1696                                         msg,
1697                                         msize));
1698     dpos += msize;
1699     /* Pad to MTU */
1700     {
1701       char pad[sizeof (dgram) - pos];
1702
1703       GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
1704                                   pad,
1705                                   sizeof (pad));
1706       if (sizeof (pad) > sizeof (struct GNUNET_MessageHeader))
1707       {
1708         struct GNUNET_MessageHeader hdr = {
1709           .size = htons (sizeof (pad)),
1710           .type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD)
1711         };
1712         
1713         memcpy (pad,
1714                 &hdr,
1715                 sizeof (hdr));
1716         GNUNET_assert (0 ==
1717                        gcry_cipher_encrypt (out_cipher,
1718                                             &dgram[dpos],
1719                                             sizeof (pad),
1720                                             pad,
1721                                             sizeof (pad)));
1722       }
1723     }
1724     /* Datagram starts with kx */
1725     kx.ephemeral = uhs.ephemeral;
1726     GNUNET_assert (0 ==
1727                    gcry_cipher_gettag (out_cipher,
1728                                        kx.gcm_tag,
1729                                        sizeof (kx.gcm_tag)));
1730     memcpy (dgram,
1731             &kx,
1732             sizeof (kx));
1733     if (-1 ==
1734         GNUNET_NETWORK_socket_sendto (udp_sock,
1735                                       dgram,
1736                                       sizeof (dgram),
1737                                       receiver->address,
1738                                       receiver->address_len))
1739       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1740                            "send");
1741     GNUNET_MQ_impl_send_continue (mq);
1742   } /* End of KX encryption method */
1743 }
1744
1745
1746 /**
1747  * Signature of functions implementing the destruction of a message
1748  * queue.  Implementations must not free @a mq, but should take care
1749  * of @a impl_state.
1750  *
1751  * @param mq the message queue to destroy
1752  * @param impl_state our `struct ReceiverAddress`
1753  */
1754 static void
1755 mq_destroy (struct GNUNET_MQ_Handle *mq,
1756             void *impl_state)
1757 {
1758   struct ReceiverAddress *receiver = impl_state;
1759
1760   if (mq == receiver->mq)
1761   {
1762     receiver->mq = NULL;
1763     receiver_destroy (receiver);
1764   }
1765 }
1766
1767
1768 /**
1769  * Implementation function that cancels the currently sent message.
1770  *
1771  * @param mq message queue
1772  * @param impl_state our `struct RecvierAddress`
1773  */
1774 static void
1775 mq_cancel (struct GNUNET_MQ_Handle *mq,
1776            void *impl_state)
1777 {
1778   /* Cancellation is impossible with UDP; bail */
1779   GNUNET_assert (0);
1780 }
1781
1782
1783 /**
1784  * Generic error handler, called with the appropriate
1785  * error code and the same closure specified at the creation of
1786  * the message queue.
1787  * Not every message queue implementation supports an error handler.
1788  *
1789  * @param cls our `struct ReceiverAddress`
1790  * @param error error code
1791  */
1792 static void
1793 mq_error (void *cls,
1794           enum GNUNET_MQ_Error error)
1795 {
1796   struct ReceiverAddress *receiver = cls;
1797
1798   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1799               "MQ error in queue to %s: %d\n",
1800               GNUNET_i2s (&receiver->target),
1801               (int) error);
1802   receiver_destroy (receiver);
1803 }
1804
1805
1806 /**
1807  * Setup a receiver for transmission.  Setup the MQ processing and
1808  * inform transport that the queue is ready. 
1809  *
1810  * @param 
1811  */ 
1812 static struct ReceiverAddress *
1813 receiver_setup (const struct GNUNET_PeerIdentity *target,
1814                 const struct sockddr *address,
1815                 socklen_t address_len)
1816 {
1817   struct ReceiverAddress *receiver;
1818
1819   receiver = GNUNET_new (struct ReceiverAddress);
1820   receiver->address = GNUNET_memdup (address,
1821                                      address_len);
1822   receiver->address_len = address_len;
1823   receiver->target = *target;
1824   receiver->nt = GNUNET_NT_scanner_get_type (is,
1825                                              address,
1826                                              address_len);
1827   (void) GNUNET_CONTAINER_multipeermap_put (receivers,
1828                                             &receiver->target,
1829                                             receiver,
1830                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1831   receiver->timeout
1832     = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1833   receiver->hn = GNUNET_CONTAINER_heap_insert (receivers_heap,
1834                                                receiver,
1835                                                receiver.timeout.abs_value_us);
1836   receiver->mq
1837     = GNUNET_MQ_queue_for_callbacks (&mq_send,
1838                                      &mq_destroy,
1839                                      &mq_cancel,
1840                                      receiver,
1841                                      NULL,
1842                                      &mq_error,
1843                                      receiver);
1844   receiver->mtu = 1200 /* FIXME: MTU OK? */;
1845   if (NULL == timeout_task)
1846     timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts,
1847                                              NULL);
1848   GNUNET_STATISTICS_set (stats,
1849                          "# receivers active",
1850                          GNUNET_CONTAINER_multipeermap_size (receivers),
1851                          GNUNET_NO);
1852   {
1853     char *foreign_addr;
1854
1855     switch (address->sa_family)
1856     {
1857     case AF_INET:
1858       GNUNET_asprintf (&foreign_addr,
1859                        "%s-%s",
1860                        COMMUNICATOR_ADDRESS_PREFIX,
1861                        GNUNET_a2s(queue->address,
1862                                   queue->address_len));
1863       break;
1864     case AF_INET6:
1865       GNUNET_asprintf (&foreign_addr,
1866                        "%s-%s",
1867                        COMMUNICATOR_ADDRESS_PREFIX,
1868                        GNUNET_a2s(queue->address,
1869                                   queue->address_len));
1870       break;
1871     default:
1872       GNUNET_assert (0);
1873     }
1874     receiver->qh
1875       = GNUNET_TRANSPORT_communicator_mq_add (ch,
1876                                               &receiver->target,
1877                                               foreign_addr,
1878                                               receiver->mtu,
1879                                               receiver->nt,
1880                                               GNUNET_TRANSPORT_CS_OUTBOUND,
1881                                               receiver->mq);
1882     GNUNET_free (foreign_addr);
1883   }
1884 }
1885
1886
1887 /**
1888  * Function called by the transport service to initialize a
1889  * message queue given address information about another peer.
1890  * If and when the communication channel is established, the
1891  * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
1892  * to notify the service that the channel is now up.  It is
1893  * the responsibility of the communicator to manage sane
1894  * retries and timeouts for any @a peer/@a address combination
1895  * provided by the transport service.  Timeouts and retries
1896  * do not need to be signalled to the transport service.
1897  *
1898  * @param cls closure
1899  * @param peer identity of the other peer
1900  * @param address where to send the message, human-readable
1901  *        communicator-specific format, 0-terminated, UTF-8
1902  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is invalid
1903  */
1904 static int
1905 mq_init (void *cls,
1906          const struct GNUNET_PeerIdentity *peer,
1907          const char *address)
1908 {
1909   struct ReceiverAddress *receiver;
1910   const char *path;
1911   struct sockaddr *in;
1912   socklen_t in_len;
1913   
1914   if (0 != strncmp (address,
1915                     COMMUNICATOR_ADDRESS_PREFIX "-",
1916                     strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
1917   {
1918     GNUNET_break_op (0);
1919     return GNUNET_SYSERR;
1920   }
1921   path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
1922   in = udp_address_to_sockaddr (path,
1923                                 &in_len);  
1924   receiver = receiver_setup (peer,
1925                              in,
1926                              in_len);
1927   return GNUNET_OK;  
1928 }
1929
1930
1931 /**
1932  * Iterator over all receivers to clean up.
1933  *
1934  * @param cls NULL
1935  * @param target unused
1936  * @param value the queue to destroy
1937  * @return #GNUNET_OK to continue to iterate
1938  */
1939 static int
1940 get_receiver_delete_it (void *cls,
1941                         const struct GNUNET_PeerIdentity *target,
1942                         void *value)
1943 {
1944   struct ReceiverAddress *receiver = value;
1945
1946   (void) cls;
1947   (void) target;
1948   receiver_destroy (receiver);
1949   return GNUNET_OK;
1950 }
1951
1952
1953 /**
1954  * Iterator over all senders to clean up.
1955  *
1956  * @param cls NULL
1957  * @param target unused
1958  * @param value the queue to destroy
1959  * @return #GNUNET_OK to continue to iterate
1960  */
1961 static int
1962 get_receiver_delete_it (void *cls,
1963                         const struct GNUNET_PeerIdentity *target,
1964                         void *value)
1965 {
1966   struct SenderAddress *sender = value;
1967
1968   (void) cls;
1969   (void) target;
1970   sender_destroy (sender);
1971   return GNUNET_OK;
1972 }
1973
1974
1975 /**
1976  * Shutdown the UNIX communicator.
1977  *
1978  * @param cls NULL (always)
1979  */
1980 static void
1981 do_shutdown (void *cls)
1982 {
1983   if (NULL != nat)
1984   {
1985      GNUNET_NAT_unregister (nat);
1986      nat = NULL;
1987   }
1988   if (NULL != read_task)
1989   {
1990     GNUNET_SCHEDULER_cancel (read_task);
1991     read_task = NULL;
1992   }
1993   if (NULL != udp_sock)
1994   {
1995     GNUNET_break (GNUNET_OK ==
1996                   GNUNET_NETWORK_socket_close (udp_sock));
1997     udp_sock = NULL;
1998   }
1999   GNUNET_CONTAINER_multipeermap_iterate (receivers,
2000                                          &get_receiver_delete_it,
2001                                          NULL);
2002   GNUNET_CONTAINER_multipeermap_destroy (receivers);
2003   GNUNET_CONTAINER_multipeermap_iterate (senders,
2004                                          &get_sender_delete_it,
2005                                          NULL);
2006   GNUNET_CONTAINER_multipeermap_destroy (senders);
2007   GNUNET_CONTAINER_multishortmap_destroy (key_cache);
2008   GNUNET_CONTAINER_heap_destroy (senders_heap);
2009   GNUNET_CONTAINER_heap_destroy (receivers_heap);
2010   if (NULL != ch)
2011   {
2012     GNUNET_TRANSPORT_communicator_disconnect (ch);
2013     ch = NULL;
2014   }
2015   if (NULL != stats)
2016   {
2017     GNUNET_STATISTICS_destroy (stats,
2018                                GNUNET_NO);
2019     stats = NULL;
2020   }
2021   if (NULL != my_private_key)
2022   {
2023     GNUNET_free (my_private_key);
2024     my_private_key = NULL;
2025   }
2026   if (NULL != is)
2027   {
2028      GNUNET_NT_scanner_done (is);
2029      is = NULL;
2030   }
2031 }
2032
2033
2034 /**
2035  * Function called when the transport service has received a
2036  * backchannel message for this communicator (!) via a different return
2037  * path. Should be an acknowledgement.
2038  *
2039  * @param cls closure, NULL
2040  * @param sender which peer sent the notification
2041  * @param msg payload
2042  */
2043 static void
2044 enc_notify_cb (void *cls,
2045                const struct GNUNET_PeerIdentity *sender,
2046                const struct GNUNET_MessageHeader *msg)
2047 {
2048   const struct UDPAck *ack;
2049   
2050   (void) cls;
2051   if ( (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK) ||
2052        (ntohs (msg->size) != sizeof (struct UDPAck)) )
2053   {
2054     GNUNET_break_op (0);
2055     return;
2056   }
2057   ack = (const struct UDPAck *) msg;
2058   GNUNET_CONTAINER_multihashmap_get_multiple (receivers,
2059                                               sender,
2060                                               &handle_ack,
2061                                               (void *) ack);
2062 }
2063
2064
2065 /**
2066  * Signature of the callback passed to #GNUNET_NAT_register() for
2067  * a function to call whenever our set of 'valid' addresses changes.
2068  *
2069  * @param cls closure
2070  * @param app_ctx[in,out] location where the app can store stuff
2071  *                  on add and retrieve it on remove
2072  * @param add_remove #GNUNET_YES to add a new public IP address, 
2073  *                   #GNUNET_NO to remove a previous (now invalid) one
2074  * @param ac address class the address belongs to
2075  * @param addr either the previous or the new public IP address
2076  * @param addrlen actual length of the @a addr
2077  */
2078 static void
2079 nat_address_cb (void *cls,
2080                 void **app_ctx,
2081                 int add_remove,
2082                 enum GNUNET_NAT_AddressClass ac,
2083                 const struct sockaddr *addr,
2084                 socklen_t addrlen)
2085 {
2086   char *my_addr;
2087   struct GNUNET_TRANSPORT_AddressIdentifier *ai;
2088
2089   if (GNUNET_YES == add_remove)
2090   {
2091     enum GNUNET_NetworkType nt;
2092
2093     GNUNET_asprintf (&my_addr,
2094                      "%s-%s",
2095                      COMMUNICATOR_ADDRESS_PREFIX,
2096                      GNUNET_a2s (addr,
2097                                  addrlen));
2098     nt = GNUNET_NT_scanner_get_type (is,
2099                                      addr,
2100                                      addrlen); 
2101     ai = GNUNET_TRANSPORT_communicator_address_add (ch,
2102                                                     my_addr,
2103                                                     nt,
2104                                                     GNUNET_TIME_UNIT_FOREVER_REL);
2105     GNUNET_free (my_addr);
2106     *app_ctx = ai;
2107   }
2108   else
2109   {
2110     ai = *app_ctx;
2111     GNUNET_TRANSPORT_communicator_address_remove (ai);
2112     *app_ctx = NULL;
2113   }
2114 }
2115
2116
2117 /**
2118  * Setup communicator and launch network interactions.
2119  *
2120  * @param cls NULL (always)
2121  * @param args remaining command-line arguments
2122  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2123  * @param c configuration
2124  */
2125 static void
2126 run (void *cls,
2127      char *const *args,
2128      const char *cfgfile,
2129      const struct GNUNET_CONFIGURATION_Handle *c)
2130 {
2131   char *bindto;
2132   struct sockaddr *in;
2133   socklen_t in_len;
2134   struct sockaddr_storage in_sto;
2135   socklen_t sto_len;
2136   
2137   (void) cls;
2138   cfg = c;
2139   if (GNUNET_OK !=
2140       GNUNET_CONFIGURATION_get_value_filename (cfg,
2141                                                COMMUNICATOR_CONFIG_SECTION,
2142                                                "BINDTO",
2143                                                &bindto))
2144   {
2145     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2146                                COMMUNICATOR_CONFIG_SECTION,
2147                                "BINDTO");
2148     return;
2149   }
2150   if (GNUNET_OK !=
2151       GNUNET_CONFIGURATION_get_value_number (cfg,
2152                                              COMMUNICATOR_CONFIG_SECTION,
2153                                              "MAX_QUEUE_LENGTH",
2154                                              &max_queue_length))
2155     max_queue_length = DEFAULT_MAX_QUEUE_LENGTH;
2156
2157   in = udp_address_to_sockaddr (bindto,
2158                                 &in_len);
2159   if (NULL == in)
2160   {
2161     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2162                 "Failed to setup UDP socket address with path `%s'\n",
2163                 bindto);
2164     GNUNET_free (bindto);
2165     return;
2166   }
2167   udp_sock = GNUNET_NETWORK_socket_create (in->sa_family,
2168                                            SOCK_DGRAM,
2169                                            IPPROTO_UDP);
2170   if (NULL == udp_sock)
2171   {
2172     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
2173                          "socket");
2174     GNUNET_free (in);
2175     GNUNET_free (bindto);
2176     return;
2177   }
2178   if (GNUNET_OK !=
2179       GNUNET_NETWORK_socket_bind (udp_sock,
2180                                   in,
2181                                   in_len))
2182   {
2183     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
2184                               "bind",
2185                               bindto);
2186     GNUNET_NETWORK_socket_close (udp_sock);
2187     listen_sock = NULL;
2188     GNUNET_free (in);
2189     GNUNET_free (bindto);
2190     return;
2191   }
2192   /* We might have bound to port 0, allowing the OS to figure it out;
2193      thus, get the real IN-address from the socket */
2194   sto_len = sizeof (in_sto);
2195   if (0 != getsockname (GNUNET_NETWORK_get_fd (udp_sock),
2196                         (struct sockaddr *) &in_sto,
2197                         &sto_len))
2198   {
2199     memcpy (&in_sto,
2200             in,
2201             in_len);
2202     sto_len = in_len;
2203   }
2204   GNUNET_free (in);
2205   GNUNET_free (bindto);
2206   in = (struct sockaddr *) &in_sto;
2207   in_len = sto_len;
2208   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2209               "Bound to `%s'\n",
2210               GNUNET_a2s ((const struct sockaddr *) &in_sto,
2211                           sto_len));
2212   stats = GNUNET_STATISTICS_create ("C-UDP",
2213                                     cfg);
2214   senders = GNUNET_CONTAINER_multipeermap_create (32,
2215                                                   GNUNET_YES);
2216   receivers = GNUNET_CONTAINER_multipeermap_create (32,
2217                                                     GNUNET_YES);
2218   senders_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2219   receivers_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2220   key_cache = GNUNET_CONTAINER_multishortmap_create (1024,
2221                                                      GNUNET_YES);
2222   GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
2223                                  NULL);
2224   is = GNUNET_NT_scanner_init ();
2225   my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
2226   if (NULL == my_private_key)
2227   {
2228     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2229                 _("Transport service is lacking key configuration settings. Exiting.\n"));
2230     GNUNET_SCHEDULER_shutdown ();
2231     return;
2232   }
2233   GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
2234                                       &my_identity.public_key);
2235   /* start listening */
2236   read_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2237                                              udp_sock,
2238                                              &sock_read,
2239                                              NULL);
2240   ch = GNUNET_TRANSPORT_communicator_connect (cfg,
2241                                               COMMUNICATOR_CONFIG_SECTION,
2242                                               COMMUNICATOR_ADDRESS_PREFIX,
2243                                               GNUNET_TRANSPORT_CC_UNRELIABLE,
2244                                               &mq_init,
2245                                               NULL,
2246                                               &enc_notify_cb,
2247                                               NULL);
2248   if (NULL == ch)
2249   {
2250     GNUNET_break (0);
2251     GNUNET_SCHEDULER_shutdown ();
2252     return;
2253   }
2254   nat = GNUNET_NAT_register (cfg,
2255                              COMMUNICATOR_CONFIG_SECTION,
2256                              IPPROTO_UDP,
2257                              1 /* one address */,
2258                              (const struct sockaddr **) &in,
2259                              &in_len,
2260                              &nat_address_cb,
2261                              NULL /* FIXME: support reversal: #5529 */,
2262                              NULL /* closure */);
2263 }
2264
2265
2266 /**
2267  * The main function for the UNIX communicator.
2268  *
2269  * @param argc number of arguments from the command line
2270  * @param argv command line arguments
2271  * @return 0 ok, 1 on error
2272  */
2273 int
2274 main (int argc,
2275       char *const *argv)
2276 {
2277   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2278     GNUNET_GETOPT_OPTION_END
2279   };
2280   int ret;
2281
2282   if (GNUNET_OK !=
2283       GNUNET_STRINGS_get_utf8_args (argc, argv,
2284                                     &argc, &argv))
2285     return 2;
2286
2287   ret =
2288       (GNUNET_OK ==
2289        GNUNET_PROGRAM_run (argc, argv,
2290                            "gnunet-communicator-udp",
2291                            _("GNUnet UDP communicator"),
2292                            options,
2293                            &run,
2294                            NULL)) ? 0 : 1;
2295   GNUNET_free ((void*) argv);
2296   return ret;
2297 }
2298
2299
2300 /* end of gnunet-communicator-udp.c */