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