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