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