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