- debug info
[oweals/gnunet.git] / src / nat / nat.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009, 2010, 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      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      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file nat/nat.c
23  * @brief Library handling UPnP and NAT-PMP port forwarding and
24  *     external IP address retrieval
25  * @author Milan Bouchet-Valat
26  * @author Christian Grothoff
27  */
28 #include "platform.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet_resolver_service.h"
31 #include "gnunet_nat_lib.h"
32 #include "nat.h"
33
34 #define LOG(kind,...) GNUNET_log_from (kind, "nat", __VA_ARGS__)
35
36 /**
37  * How often do we scan for changes in our IP address from our local
38  * interfaces?
39  */
40 #define IFC_SCAN_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
41
42 /**
43  * How often do we scan for changes in how our hostname resolves?
44  */
45 #define HOSTNAME_DNS_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 20)
46
47
48 /**
49  * How often do we scan for changes in how our external (dyndns) hostname resolves?
50  */
51 #define DYNDNS_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 7)
52
53 /**
54  * How long until we give up trying to resolve our own hostname?
55  */
56 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
57
58
59 /**
60  * Where did the given local address originate from?
61  * To be used for debugging as well as in the future
62  * to remove all addresses from a certain source when
63  * we reevaluate the source.
64  */
65 enum LocalAddressSource
66 {
67   /**
68    * Address was obtained by DNS resolution of the external hostname
69    * given in the configuration (i.e. hole-punched DynDNS setup).
70    */
71   LAL_EXTERNAL_IP,
72
73    /**
74    * Address was obtained by an external STUN server
75    */
76   LAL_EXTERNAL_STUN_IP,
77
78   /**
79    * Address was obtained by DNS resolution of the external hostname
80    * given in the configuration (i.e. hole-punched DynDNS setup)
81    * during the previous iteration (see #3213).
82    */
83   LAL_EXTERNAL_IP_OLD,
84
85   /**
86    * Address was obtained by looking up our own hostname in DNS.
87    */
88   LAL_HOSTNAME_DNS,
89
90   /**
91    * Address was obtained by scanning our hosts's network interfaces
92    * and taking their address (no DNS involved).
93    */
94   LAL_INTERFACE_ADDRESS,
95
96   /**
97    * Addresses we were explicitly bound to.
98    */
99   LAL_BINDTO_ADDRESS,
100
101   /**
102    * Addresses from UPnP or PMP
103    */
104   LAL_UPNP,
105
106   /**
107    * End of the list.
108    */
109   LAL_END
110 };
111
112
113 /**
114  * List of local addresses that we currently deem valid.  Actual
115  * struct is followed by the 'struct sockaddr'.  Note that the code
116  * intentionally makes no attempt to ensure that a particular address
117  * is only listed once (especially since it may come from different
118  * sources, and the source is an "internal" construct).
119  */
120 struct LocalAddressList
121 {
122   /**
123    * This is a linked list.
124    */
125   struct LocalAddressList *next;
126
127   /**
128    * Previous entry.
129    */
130   struct LocalAddressList *prev;
131
132   /**
133    * Number of bytes of address that follow.
134    */
135   socklen_t addrlen;
136
137   /**
138    * Origin of the local address.
139    */
140   enum LocalAddressSource source;
141 };
142
143
144 /**
145  * Handle for miniupnp-based NAT traversal actions.
146  */
147 struct MiniList
148 {
149
150   /**
151    * Doubly-linked list.
152    */
153   struct MiniList *next;
154
155   /**
156    * Doubly-linked list.
157    */
158   struct MiniList *prev;
159
160   /**
161    * Handle to mini-action.
162    */
163   struct GNUNET_NAT_MiniHandle *mini;
164
165   /**
166    * Local port number that was mapped.
167    */
168   uint16_t port;
169
170 };
171
172
173 /**
174  * Handle for active NAT registrations.
175  */
176 struct GNUNET_NAT_Handle
177 {
178
179   /**
180    * Configuration to use.
181    */
182   const struct GNUNET_CONFIGURATION_Handle *cfg;
183
184   /**
185    * Function to call when we learn about a new address.
186    */
187   GNUNET_NAT_AddressCallback address_callback;
188
189   /**
190    * Function to call when we notice another peer asking for
191    * connection reversal.
192    */
193   GNUNET_NAT_ReversalCallback reversal_callback;
194
195   /**
196    * Closure for callbacks (@e address_callback and @e reversal_callback)
197    */
198   void *callback_cls;
199
200   /**
201    * Handle for (DYN)DNS lookup of our external IP.
202    */
203   struct GNUNET_RESOLVER_RequestHandle *ext_dns;
204
205   /**
206    * Handle for request of hostname resolution, non-NULL if pending.
207    */
208   struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
209
210   /**
211    * stdout pipe handle for the gnunet-helper-nat-server process
212    */
213   struct GNUNET_DISK_PipeHandle *server_stdout;
214
215   /**
216    * stdout file handle (for reading) for the gnunet-helper-nat-server process
217    */
218   const struct GNUNET_DISK_FileHandle *server_stdout_handle;
219
220   /**
221    * Linked list of currently valid addresses (head).
222    */
223   struct LocalAddressList *lal_head;
224
225   /**
226    * Linked list of currently valid addresses (tail).
227    */
228   struct LocalAddressList *lal_tail;
229
230   /**
231    * How long do we wait for restarting a crashed gnunet-helper-nat-server?
232    */
233   struct GNUNET_TIME_Relative server_retry_delay;
234
235   /**
236    * ID of select gnunet-helper-nat-server stdout read task
237    */
238   struct GNUNET_SCHEDULER_Task * server_read_task;
239
240   /**
241    * ID of interface IP-scan task
242    */
243   struct GNUNET_SCHEDULER_Task * ifc_task;
244
245   /**
246    * ID of hostname DNS lookup task
247    */
248   struct GNUNET_SCHEDULER_Task * hostname_task;
249
250   /**
251    * ID of DynDNS lookup task
252    */
253   struct GNUNET_SCHEDULER_Task *dns_task;
254
255   /**
256    * How often do we scan for changes in our IP address from our local
257    * interfaces?
258    */
259   struct GNUNET_TIME_Relative ifc_scan_frequency;
260
261   /**
262    * How often do we scan for changes in how our hostname resolves?
263    */
264   struct GNUNET_TIME_Relative hostname_dns_frequency;
265
266   /**
267    * How often do we scan for changes in how our external (dyndns) hostname resolves?
268    */
269   struct GNUNET_TIME_Relative dyndns_frequency;
270
271   /**
272    * The process id of the server process (if behind NAT)
273    */
274   struct GNUNET_OS_Process *server_proc;
275
276   /**
277    * LAN address as passed by the caller (array).
278    */
279   struct sockaddr **local_addrs;
280
281   /**
282    * Length of the @e local_addrs.
283    */
284   socklen_t *local_addrlens;
285
286   /**
287    * List of handles for UPnP-traversal, one per local port (if
288    * not IPv6-only).
289    */
290   struct MiniList *mini_head;
291
292   /**
293    * List of handles for UPnP-traversal, one per local port (if
294    * not IPv6-only).
295    */
296   struct MiniList *mini_tail;
297
298   /**
299    * Number of entries in 'local_addrs' array.
300    */
301   unsigned int num_local_addrs;
302
303   /**
304    * Our external address (according to config, UPnP may disagree...),
305    * in dotted decimal notation, IPv4-only. Or NULL if not known.
306    */
307   char *external_address;
308
309   /**
310    * Presumably our internal address (according to config)
311    */
312   char *internal_address;
313
314   /**
315    * Is this transport configured to be behind a NAT?
316    */
317   int behind_nat;
318
319   /**
320    * Has the NAT been punched? (according to config)
321    */
322   int nat_punched;
323
324   /**
325    * Is this transport configured to allow connections to NAT'd peers?
326    */
327   int enable_nat_client;
328
329   /**
330    * Should we run the gnunet-helper-nat-server?
331    */
332   int enable_nat_server;
333
334   /**
335    * Are we allowed to try UPnP/PMP for NAT traversal?
336    */
337   int enable_upnp;
338
339   /**
340    * Should we use local addresses (loopback)? (according to config)
341    */
342   int use_localaddresses;
343
344   /**
345    * Should we return local addresses to clients
346    */
347   int return_localaddress;
348
349   /**
350    * Should we do a DNS lookup of our hostname to find out our own IP?
351    */
352   int use_hostname;
353
354   /**
355    * Is using IPv6 disabled?
356    */
357   int disable_ipv6;
358
359   /**
360    * Is this TCP or UDP?
361    */
362   int is_tcp;
363
364   /**
365    * Port we advertise to the outside.
366    */
367   uint16_t adv_port;
368
369 };
370
371
372 /**
373  * Try to start the gnunet-helper-nat-server (if it is not
374  * already running).
375  *
376  * @param h handle to NAT
377  */
378 static void
379 start_gnunet_nat_server (struct GNUNET_NAT_Handle *h);
380
381
382 /**
383  * Remove all addresses from the list of 'local' addresses
384  * that originated from the given source.
385  *
386  * @param h handle to NAT
387  * @param src source that identifies addresses to remove
388  */
389 static void
390 remove_from_address_list_by_source (struct GNUNET_NAT_Handle *h,
391                                     enum LocalAddressSource src)
392 {
393   struct LocalAddressList *pos;
394   struct LocalAddressList *next;
395
396   next = h->lal_head;
397   while (NULL != (pos = next))
398   {
399     next = pos->next;
400     if (pos->source != src)
401       continue;
402     GNUNET_CONTAINER_DLL_remove (h->lal_head, h->lal_tail, pos);
403     if (NULL != h->address_callback)
404       h->address_callback (h->callback_cls, GNUNET_NO,
405                            (const struct sockaddr *) &pos[1], pos->addrlen);
406     GNUNET_free (pos);
407   }
408 }
409
410
411 /**
412  * Add the given address to the list of 'local' addresses, thereby
413  * making it a 'legal' address for this peer to have.
414  *
415  * @param h handle to NAT
416  * @param src where did the local address originate from?
417  * @param arg the address, some `struct sockaddr`
418  * @param arg_size number of bytes in @a arg
419  */
420 static void
421 add_to_address_list_as_is (struct GNUNET_NAT_Handle *h,
422                            enum LocalAddressSource src,
423                            const struct sockaddr *arg, socklen_t arg_size)
424 {
425   struct LocalAddressList *lal;
426
427   lal = GNUNET_malloc (sizeof (struct LocalAddressList) + arg_size);
428   memcpy (&lal[1], arg, arg_size);
429   lal->addrlen = arg_size;
430   lal->source = src;
431   GNUNET_CONTAINER_DLL_insert (h->lal_head, h->lal_tail, lal);
432   LOG (GNUNET_ERROR_TYPE_DEBUG,
433        "Adding address `%s' from source %d\n",
434        GNUNET_a2s (arg, arg_size),
435        src);
436   if (NULL != h->address_callback)
437     h->address_callback (h->callback_cls, GNUNET_YES, arg, arg_size);
438 }
439
440
441 /**
442  * Add the given address to the list of 'local' addresses, thereby
443  * making it a 'legal' address for this peer to have.   Set the
444  * port number in the process to the advertised port and possibly
445  * also to zero (if we have the gnunet-helper-nat-server).
446  *
447  * @param h handle to NAT
448  * @param src where did the local address originate from?
449  * @param arg the address, some `struct sockaddr`
450  * @param arg_size number of bytes in @a arg
451  */
452 static void
453 add_to_address_list (struct GNUNET_NAT_Handle *h,
454                      enum LocalAddressSource src,
455                      const struct sockaddr *arg,
456                      socklen_t arg_size)
457 {
458   struct sockaddr_in s4;
459   const struct sockaddr_in *in4;
460   struct sockaddr_in6 s6;
461   const struct sockaddr_in6 *in6;
462
463   if (arg_size == sizeof (struct sockaddr_in))
464   {
465     in4 = (const struct sockaddr_in *) arg;
466     s4 = *in4;
467     s4.sin_port = htons (h->adv_port);
468     add_to_address_list_as_is (h, src, (const struct sockaddr *) &s4,
469                                sizeof (struct sockaddr_in));
470     if (GNUNET_YES == h->enable_nat_server)
471     {
472       /* also add with PORT = 0 to indicate NAT server is enabled */
473       s4.sin_port = htons (0);
474       add_to_address_list_as_is (h, src, (const struct sockaddr *) &s4,
475                                  sizeof (struct sockaddr_in));
476     }
477   }
478   else if (arg_size == sizeof (struct sockaddr_in6))
479   {
480     if (GNUNET_YES != h->disable_ipv6)
481     {
482       in6 = (const struct sockaddr_in6 *) arg;
483       s6 = *in6;
484       s6.sin6_port = htons (h->adv_port);
485       add_to_address_list_as_is (h, src, (const struct sockaddr *) &s6,
486                                  sizeof (struct sockaddr_in6));
487     }
488   }
489   else
490   {
491     GNUNET_assert (0);
492   }
493 }
494
495
496 /**
497  * Add the given IP address to the list of 'local' addresses, thereby
498  * making it a 'legal' address for this peer to have.
499  *
500  * @param h handle to NAT
501  * @param src where did the local address originate from?
502  * @param addr the address, some `struct in_addr` or `struct in6_addr`
503  * @param addrlen number of bytes in addr
504  */
505 static void
506 add_ip_to_address_list (struct GNUNET_NAT_Handle *h,
507                         enum LocalAddressSource src, const void *addr,
508                         socklen_t addrlen)
509 {
510   struct sockaddr_in s4;
511   const struct in_addr *in4;
512   struct sockaddr_in6 s6;
513   const struct in6_addr *in6;
514
515   if (addrlen == sizeof (struct in_addr))
516   {
517     in4 = (const struct in_addr *) addr;
518     memset (&s4, 0, sizeof (s4));
519     s4.sin_family = AF_INET;
520     s4.sin_port = 0;
521 #if HAVE_SOCKADDR_IN_SIN_LEN
522     s4.sin_len = (u_char) sizeof (struct sockaddr_in);
523 #endif
524     s4.sin_addr = *in4;
525     add_to_address_list (h, src, (const struct sockaddr *) &s4,
526                          sizeof (struct sockaddr_in));
527     if (GNUNET_YES == h->enable_nat_server)
528     {
529       /* also add with PORT = 0 to indicate NAT server is enabled */
530       s4.sin_port = htons (0);
531       add_to_address_list (h, src, (const struct sockaddr *) &s4,
532                            sizeof (struct sockaddr_in));
533
534     }
535   }
536   else if (addrlen == sizeof (struct in6_addr))
537   {
538     if (GNUNET_YES != h->disable_ipv6)
539     {
540       in6 = (const struct in6_addr *) addr;
541       memset (&s6, 0, sizeof (s6));
542       s6.sin6_family = AF_INET6;
543       s6.sin6_port = htons (h->adv_port);
544 #if HAVE_SOCKADDR_IN_SIN_LEN
545       s6.sin6_len = (u_char) sizeof (struct sockaddr_in6);
546 #endif
547       s6.sin6_addr = *in6;
548       add_to_address_list (h, src, (const struct sockaddr *) &s6,
549                            sizeof (struct sockaddr_in6));
550     }
551   }
552   else
553   {
554     GNUNET_assert (0);
555   }
556 }
557
558
559 /**
560  * Task to do DNS lookup on our external hostname to
561  * get DynDNS-IP addresses.
562  *
563  * @param cls the NAT handle
564  * @param tc scheduler context
565  */
566 static void
567 resolve_dns (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
568
569
570 /**
571  * Our (external) hostname was resolved and the configuration says that
572  * the NAT was hole-punched.
573  *
574  * @param cls the `struct GNUNET_NAT_Handle`
575  * @param addr NULL on error, otherwise result of DNS lookup
576  * @param addrlen number of bytes in @a addr
577  */
578 static void
579 process_external_ip (void *cls,
580                      const struct sockaddr *addr,
581                      socklen_t addrlen)
582 {
583   struct GNUNET_NAT_Handle *h = cls;
584   struct in_addr dummy;
585
586   if (NULL == addr)
587   {
588     h->ext_dns = NULL;
589     /* Current iteration is over, remove 'old' IPs now */
590     LOG (GNUNET_ERROR_TYPE_DEBUG,
591          "Purging old IPs for external address\n");
592     remove_from_address_list_by_source (h, LAL_EXTERNAL_IP_OLD);
593     if (1 == inet_pton (AF_INET,
594                         h->external_address,
595                         &dummy))
596     {
597       LOG (GNUNET_ERROR_TYPE_DEBUG,
598            "Got numeric IP for external address, not repeating lookup\n");
599       return;                   /* repated lookup pointless: was numeric! */
600     }
601     h->dns_task =
602       GNUNET_SCHEDULER_add_delayed (h->dyndns_frequency,
603                                     &resolve_dns, h);
604     return;
605   }
606   LOG (GNUNET_ERROR_TYPE_DEBUG,
607        "Got IP `%s' for external address `%s'\n",
608        GNUNET_a2s (addr, addrlen),
609        h->external_address);
610   add_to_address_list (h, LAL_EXTERNAL_IP, addr, addrlen);
611 }
612
613
614 /**
615  * Task to do a lookup on our hostname for IP addresses.
616  *
617  * @param cls the NAT handle
618  * @param tc scheduler context
619  */
620 static void
621 resolve_hostname (void *cls,
622                   const struct GNUNET_SCHEDULER_TaskContext *tc);
623
624
625 /**
626  * Function called by the resolver for each address obtained from DNS
627  * for our own hostname.  Add the addresses to the list of our IP
628  * addresses.
629  *
630  * @param cls closure
631  * @param addr one of the addresses of the host, NULL for the last address
632  * @param addrlen length of the @a addr
633  */
634 static void
635 process_hostname_ip (void *cls,
636                      const struct sockaddr *addr,
637                      socklen_t addrlen)
638 {
639   struct GNUNET_NAT_Handle *h = cls;
640
641   if (NULL == addr)
642   {
643     h->hostname_dns = NULL;
644     h->hostname_task =
645         GNUNET_SCHEDULER_add_delayed (h->hostname_dns_frequency,
646                                       &resolve_hostname, h);
647     return;
648   }
649   add_to_address_list (h, LAL_HOSTNAME_DNS, addr, addrlen);
650 }
651
652
653 /**
654  * Length of the interface names returned from os_network.c.
655  * (in that file, hardcoded at 11).
656  */
657 #define IF_NAME_LEN 11
658
659
660 /**
661  * Add the IP of our network interface to the list of
662  * our IP addresses.
663  *
664  * @param cls the `struct GNUNET_NAT_Handle`
665  * @param name name of the interface
666  * @param isDefault do we think this may be our default interface
667  * @param addr address of the interface
668  * @param broadcast_addr the broadcast address (can be NULL for unknown or unassigned)
669  * @param netmask the network mask (can be NULL for unknown or unassigned))
670  * @param addrlen number of bytes in @a addr and @a broadcast_addr
671  * @return #GNUNET_OK to continue iterating
672  */
673 static int
674 process_interfaces (void *cls,
675                     const char *name,
676                     int isDefault,
677                     const struct sockaddr *addr,
678                     const struct sockaddr *broadcast_addr,
679                     const struct sockaddr *netmask,
680                     socklen_t addrlen)
681 {
682   const static struct in6_addr any6 = IN6ADDR_ANY_INIT;
683   struct GNUNET_NAT_Handle *h = cls;
684   const struct sockaddr_in *s4;
685   const struct sockaddr_in6 *s6;
686   const void *ip;
687   char buf[INET6_ADDRSTRLEN];
688   unsigned int i;
689   int have_any;
690   char *tun_if;
691
692   /* skip virtual interfaces created by GNUnet-vpn */
693   if (GNUNET_OK ==
694       GNUNET_CONFIGURATION_get_value_string (h->cfg,
695                                              "vpn",
696                                              "IFNAME",
697                                              &tun_if))
698   {
699     if (0 == strncasecmp (name,
700                           tun_if,
701                           IF_NAME_LEN))
702     {
703       GNUNET_free (tun_if);
704       return GNUNET_OK;
705     }
706   }
707   /* skip virtual interfaces created by GNUnet-dns */
708   if (GNUNET_OK ==
709       GNUNET_CONFIGURATION_get_value_string (h->cfg,
710                                              "dns",
711                                              "IFNAME",
712                                              &tun_if))
713   {
714     if (0 == strncasecmp (name,
715                           tun_if,
716                           IF_NAME_LEN))
717     {
718       GNUNET_free (tun_if);
719       return GNUNET_OK;
720     }
721   }
722   /* skip virtual interfaces created by GNUnet-exit */
723   if (GNUNET_OK ==
724       GNUNET_CONFIGURATION_get_value_string (h->cfg,
725                                              "exit",
726                                              "EXIT_IFNAME",
727                                              &tun_if))
728   {
729     if (0 == strncasecmp (name,
730                           tun_if,
731                           IF_NAME_LEN))
732     {
733       GNUNET_free (tun_if);
734       return GNUNET_OK;
735     }
736   }
737
738
739   switch (addr->sa_family)
740   {
741   case AF_INET:
742     /* check if we're bound to the "ANY" IP address */
743     have_any = GNUNET_NO;
744     for (i=0;i<h->num_local_addrs;i++)
745       {
746         if (h->local_addrs[i]->sa_family != AF_INET)
747           continue;
748 #ifndef INADDR_ANY
749 #define INADDR_ANY 0
750 #endif
751         if (INADDR_ANY == ((struct sockaddr_in*) h->local_addrs[i])->sin_addr.s_addr)
752           {
753             have_any = GNUNET_YES;
754             break;
755           }
756       }
757     if (GNUNET_NO == have_any)
758       return GNUNET_OK; /* not bound to IP 0.0.0.0 but to specific IP addresses,
759                            do not use those from interfaces */
760     s4 = (struct sockaddr_in *) addr;
761     ip = &s4->sin_addr;
762
763     /* Check if address is in 127.0.0.0/8 */
764     uint32_t address = ntohl ((uint32_t) (s4->sin_addr.s_addr));
765     uint32_t value = (address & 0xFF000000) ^ 0x7F000000;
766
767     if ((h->return_localaddress == GNUNET_NO) && (value == 0))
768     {
769       return GNUNET_OK;
770     }
771     if ((GNUNET_YES == h->use_localaddresses) || (value != 0))
772     {
773       add_ip_to_address_list (h, LAL_INTERFACE_ADDRESS, &s4->sin_addr,
774                               sizeof (struct in_addr));
775     }
776     break;
777   case AF_INET6:
778     /* check if we're bound to the "ANY" IP address */
779     have_any = GNUNET_NO;
780     for (i=0;i<h->num_local_addrs;i++)
781       {
782         if (h->local_addrs[i]->sa_family != AF_INET6)
783           continue;
784         if (0 == memcmp (&any6,
785                          &((struct sockaddr_in6*) h->local_addrs[i])->sin6_addr,
786                          sizeof (struct in6_addr)))
787           {
788             have_any = GNUNET_YES;
789             break;
790           }
791       }
792     if (GNUNET_NO == have_any)
793       return GNUNET_OK; /* not bound to "ANY" IP (::0) but to specific IP addresses,
794                            do not use those from interfaces */
795
796     s6 = (struct sockaddr_in6 *) addr;
797     if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
798     {
799       /* skip link local addresses */
800       return GNUNET_OK;
801     }
802     if ((h->return_localaddress == GNUNET_NO) &&
803         (IN6_IS_ADDR_LOOPBACK (&((struct sockaddr_in6 *) addr)->sin6_addr)))
804     {
805       return GNUNET_OK;
806     }
807     ip = &s6->sin6_addr;
808     if (GNUNET_YES == h->use_localaddresses)
809     {
810       add_ip_to_address_list (h, LAL_INTERFACE_ADDRESS, &s6->sin6_addr,
811                               sizeof (struct in6_addr));
812     }
813     break;
814   default:
815     GNUNET_break (0);
816     return GNUNET_OK;
817   }
818   if ((h->internal_address == NULL) && (h->server_proc == NULL) &&
819       (h->server_read_task == NULL) &&
820       (GNUNET_YES == isDefault) && ((addr->sa_family == AF_INET) ||
821                                     (addr->sa_family == AF_INET6)))
822   {
823     /* no internal address configured, but we found a "default"
824      * interface, try using that as our 'internal' address */
825     h->internal_address =
826         GNUNET_strdup (inet_ntop (addr->sa_family, ip, buf, sizeof (buf)));
827     start_gnunet_nat_server (h);
828   }
829   return GNUNET_OK;
830 }
831
832
833 /**
834  * Task that restarts the gnunet-helper-nat-server process after a crash
835  * after a certain delay.
836  *
837  * @param cls the `struct GNUNET_NAT_Handle`
838  * @param tc scheduler context
839  */
840 static void
841 restart_nat_server (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
842 {
843   struct GNUNET_NAT_Handle *h = cls;
844
845   h->server_read_task = NULL;
846   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
847     return;
848   start_gnunet_nat_server (h);
849 }
850
851
852 /**
853  * We have been notified that gnunet-helper-nat-server has written
854  * something to stdout.  Handle the output, then reschedule this
855  * function to be called again once more is available.
856  *
857  * @param cls the NAT handle
858  * @param tc the scheduling context
859  */
860 static void
861 nat_server_read (void *cls,
862                  const struct GNUNET_SCHEDULER_TaskContext *tc)
863 {
864   struct GNUNET_NAT_Handle *h = cls;
865   char mybuf[40];
866   ssize_t bytes;
867   size_t i;
868   int port;
869   const char *port_start;
870   struct sockaddr_in sin_addr;
871
872   h->server_read_task = NULL;
873   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
874     return;
875   memset (mybuf, 0, sizeof (mybuf));
876   bytes =
877     GNUNET_DISK_file_read (h->server_stdout_handle, mybuf, sizeof (mybuf));
878   if (bytes < 1)
879   {
880     LOG (GNUNET_ERROR_TYPE_DEBUG,
881          "Finished reading from server stdout with code: %d\n",
882          bytes);
883     if (0 != GNUNET_OS_process_kill (h->server_proc, GNUNET_TERM_SIG))
884       GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING, "nat", "kill");
885     GNUNET_OS_process_wait (h->server_proc);
886     GNUNET_OS_process_destroy (h->server_proc);
887     h->server_proc = NULL;
888     GNUNET_DISK_pipe_close (h->server_stdout);
889     h->server_stdout = NULL;
890     h->server_stdout_handle = NULL;
891     /* now try to restart it */
892     h->server_retry_delay = GNUNET_TIME_STD_BACKOFF (h->server_retry_delay);
893     h->server_read_task =
894         GNUNET_SCHEDULER_add_delayed (h->server_retry_delay,
895                                       &restart_nat_server, h);
896     return;
897   }
898
899   port_start = NULL;
900   for (i = 0; i < sizeof (mybuf); i++)
901   {
902     if (mybuf[i] == '\n')
903     {
904       mybuf[i] = '\0';
905       break;
906     }
907     if ((mybuf[i] == ':') && (i + 1 < sizeof (mybuf)))
908     {
909       mybuf[i] = '\0';
910       port_start = &mybuf[i + 1];
911     }
912   }
913
914   /* construct socket address of sender */
915   memset (&sin_addr, 0, sizeof (sin_addr));
916   sin_addr.sin_family = AF_INET;
917 #if HAVE_SOCKADDR_IN_SIN_LEN
918   sin_addr.sin_len = sizeof (sin_addr);
919 #endif
920   if ((NULL == port_start) || (1 != SSCANF (port_start, "%d", &port)) ||
921       (-1 == inet_pton (AF_INET, mybuf, &sin_addr.sin_addr)))
922   {
923     /* should we restart gnunet-helper-nat-server? */
924     LOG (GNUNET_ERROR_TYPE_WARNING, "nat",
925          _("gnunet-helper-nat-server generated malformed address `%s'\n"),
926          mybuf);
927     h->server_read_task =
928         GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
929                                         h->server_stdout_handle,
930                                         &nat_server_read, h);
931     return;
932   }
933   sin_addr.sin_port = htons ((uint16_t) port);
934   LOG (GNUNET_ERROR_TYPE_DEBUG, "gnunet-helper-nat-server read: %s:%d\n", mybuf,
935        port);
936   h->reversal_callback (h->callback_cls, (const struct sockaddr *) &sin_addr,
937                         sizeof (sin_addr));
938   h->server_read_task =
939       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
940                                       h->server_stdout_handle, &nat_server_read,
941                                       h);
942 }
943
944
945 /**
946  * Try to start the gnunet-helper-nat-server (if it is not
947  * already running).
948  *
949  * @param h handle to NAT
950  */
951 static void
952 start_gnunet_nat_server (struct GNUNET_NAT_Handle *h)
953 {
954   char *binary;
955
956   if ((h->behind_nat == GNUNET_YES) && (h->enable_nat_server == GNUNET_YES) &&
957       (h->internal_address != NULL) &&
958       (NULL !=
959        (h->server_stdout =
960         GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES))))
961   {
962     LOG (GNUNET_ERROR_TYPE_DEBUG,
963          "Starting `%s' at `%s'\n",
964          "gnunet-helper-nat-server", h->internal_address);
965     /* Start the server process */
966     binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-server");
967     h->server_proc =
968         GNUNET_OS_start_process (GNUNET_NO, 0, NULL, h->server_stdout, NULL,
969                                  binary,
970                                  "gnunet-helper-nat-server",
971                                  h->internal_address, NULL);
972     GNUNET_free (binary);
973     if (h->server_proc == NULL)
974     {
975       LOG (GNUNET_ERROR_TYPE_WARNING, "nat", _("Failed to start %s\n"),
976            "gnunet-helper-nat-server");
977       GNUNET_DISK_pipe_close (h->server_stdout);
978       h->server_stdout = NULL;
979     }
980     else
981     {
982       /* Close the write end of the read pipe */
983       GNUNET_DISK_pipe_close_end (h->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
984       h->server_stdout_handle =
985           GNUNET_DISK_pipe_handle (h->server_stdout, GNUNET_DISK_PIPE_END_READ);
986       h->server_read_task =
987           GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
988                                           h->server_stdout_handle,
989                                           &nat_server_read, h);
990     }
991   }
992 }
993
994
995 /**
996  * Task to scan the local network interfaces for IP addresses.
997  *
998  * @param cls the NAT handle
999  * @param tc scheduler context
1000  */
1001 static void
1002 list_interfaces (void *cls,
1003                  const struct GNUNET_SCHEDULER_TaskContext *tc)
1004 {
1005   struct GNUNET_NAT_Handle *h = cls;
1006
1007   h->ifc_task = NULL;
1008   remove_from_address_list_by_source (h, LAL_INTERFACE_ADDRESS);
1009   GNUNET_OS_network_interfaces_list (&process_interfaces, h);
1010   h->ifc_task =
1011     GNUNET_SCHEDULER_add_delayed (h->ifc_scan_frequency,
1012                                   &list_interfaces, h);
1013 }
1014
1015
1016 /**
1017  * Task to do a lookup on our hostname for IP addresses.
1018  *
1019  * @param cls the NAT handle
1020  * @param tc scheduler context
1021  */
1022 static void
1023 resolve_hostname (void *cls,
1024                   const struct GNUNET_SCHEDULER_TaskContext *tc)
1025 {
1026   struct GNUNET_NAT_Handle *h = cls;
1027
1028   h->hostname_task = NULL;
1029   remove_from_address_list_by_source (h, LAL_HOSTNAME_DNS);
1030   h->hostname_dns =
1031       GNUNET_RESOLVER_hostname_resolve (AF_UNSPEC, HOSTNAME_RESOLVE_TIMEOUT,
1032                                         &process_hostname_ip, h);
1033 }
1034
1035
1036 /**
1037  * Task to do DNS lookup on our external hostname to
1038  * get DynDNS-IP addresses.
1039  *
1040  * @param cls the NAT handle
1041  * @param tc scheduler context
1042  */
1043 static void
1044 resolve_dns (void *cls,
1045              const struct GNUNET_SCHEDULER_TaskContext *tc)
1046 {
1047   struct GNUNET_NAT_Handle *h = cls;
1048   struct LocalAddressList *pos;
1049
1050   h->dns_task = NULL;
1051   for (pos = h->lal_head; NULL != pos; pos = pos->next)
1052     if (pos->source == LAL_EXTERNAL_IP)
1053       pos->source = LAL_EXTERNAL_IP_OLD;
1054   LOG (GNUNET_ERROR_TYPE_DEBUG,
1055        "Resolving external address `%s'\n",
1056        h->external_address);
1057   h->ext_dns =
1058       GNUNET_RESOLVER_ip_get (h->external_address, AF_INET,
1059                               GNUNET_TIME_UNIT_MINUTES,
1060                               &process_external_ip, h);
1061 }
1062
1063
1064 /**
1065  * Add or remove UPnP-mapped addresses.
1066  *
1067  * @param cls the `struct GNUNET_NAT_Handle`
1068  * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
1069  *     the previous (now invalid) one
1070  * @param addr either the previous or the new public IP address
1071  * @param addrlen actual lenght of @a addr
1072  * @param ret GNUNET_NAT_ERROR_SUCCESS on success, otherwise an error code
1073  */
1074 static void
1075 upnp_add (void *cls,
1076           int add_remove,
1077           const struct sockaddr *addr,
1078           socklen_t addrlen,
1079           enum GNUNET_NAT_StatusCode ret)
1080 {
1081   struct GNUNET_NAT_Handle *h = cls;
1082   struct LocalAddressList *pos;
1083   struct LocalAddressList *next;
1084
1085
1086   if (GNUNET_NAT_ERROR_SUCCESS != ret)
1087   {
1088     /* Error while running upnp client */
1089     LOG (GNUNET_ERROR_TYPE_ERROR,
1090           _("Error while running upnp client:\n"));
1091
1092     //FIXME: convert error code to string
1093
1094     return;
1095   }
1096
1097   if (GNUNET_YES == add_remove)
1098   {
1099     add_to_address_list (h, LAL_UPNP, addr, addrlen);
1100     return;
1101   }
1102   else if (GNUNET_NO == add_remove)
1103   {
1104     /* remove address */
1105     next = h->lal_head;
1106     while (NULL != (pos = next))
1107     {
1108       next = pos->next;
1109       if ((pos->source != LAL_UPNP) || (pos->addrlen != addrlen) ||
1110           (0 != memcmp (&pos[1], addr, addrlen)))
1111         continue;
1112       GNUNET_CONTAINER_DLL_remove (h->lal_head, h->lal_tail, pos);
1113       if (NULL != h->address_callback)
1114         h->address_callback (h->callback_cls, GNUNET_NO,
1115                              (const struct sockaddr *) &pos[1], pos->addrlen);
1116       GNUNET_free (pos);
1117       return;                     /* only remove once */
1118     }
1119     /* asked to remove address that does not exist */
1120     LOG (GNUNET_ERROR_TYPE_ERROR,
1121          "Asked to remove unkown address `%s'\n",
1122          GNUNET_a2s(addr, addrlen));
1123     GNUNET_break (0);
1124   }
1125   else
1126   {
1127
1128     GNUNET_break (0);
1129   }
1130 }
1131
1132
1133 /**
1134  * Try to add a port mapping using UPnP.
1135  *
1136  * @param h overall NAT handle
1137  * @param port port to map with UPnP
1138  */
1139 static void
1140 add_minis (struct GNUNET_NAT_Handle *h,
1141            uint16_t port)
1142 {
1143   struct MiniList *ml;
1144
1145   ml = h->mini_head;
1146   while (NULL != ml)
1147   {
1148     if (port == ml->port)
1149       return;                   /* already got this port */
1150     ml = ml->next;
1151   }
1152
1153   ml = GNUNET_new (struct MiniList);
1154   ml->port = port;
1155   ml->mini = GNUNET_NAT_mini_map_start (port, h->is_tcp, &upnp_add, h);
1156
1157   if (NULL == ml->mini)
1158   {
1159     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1160         _("Failed to run upnp client for port %u\n"), ml->port);
1161     GNUNET_free (ml);
1162     return;
1163   }
1164
1165   GNUNET_CONTAINER_DLL_insert (h->mini_head, h->mini_tail, ml);
1166 }
1167
1168
1169 /**
1170  * Task to add addresses from original bind to set of valid addrs.
1171  *
1172  * @param h the NAT handle
1173  */
1174 static void
1175 add_from_bind (struct GNUNET_NAT_Handle *h)
1176 {
1177   static struct in6_addr any = IN6ADDR_ANY_INIT;
1178
1179   unsigned int i;
1180   struct sockaddr *sa;
1181   const struct sockaddr_in *v4;
1182
1183   for (i = 0; i < h->num_local_addrs; i++)
1184   {
1185     sa = h->local_addrs[i];
1186     switch (sa->sa_family)
1187     {
1188     case AF_INET:
1189       if (sizeof (struct sockaddr_in) != h->local_addrlens[i])
1190       {
1191         GNUNET_break (0);
1192         break;
1193       }
1194       v4 = (const struct sockaddr_in *) sa;
1195       if (0 != v4->sin_addr.s_addr)
1196         add_to_address_list (h,
1197                              LAL_BINDTO_ADDRESS, sa,
1198                              sizeof (struct sockaddr_in));
1199       if (h->enable_upnp)
1200       {
1201         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1202                     "Running upnp client for address `%s'\n",
1203                     GNUNET_a2s (sa,sizeof (struct sockaddr_in)));
1204         add_minis (h, ntohs (v4->sin_port));
1205       }
1206       break;
1207     case AF_INET6:
1208       if (sizeof (struct sockaddr_in6) != h->local_addrlens[i])
1209       {
1210         GNUNET_break (0);
1211         break;
1212       }
1213       if (0 !=
1214           memcmp (&((const struct sockaddr_in6 *) sa)->sin6_addr,
1215                   &any,
1216                   sizeof (struct in6_addr)))
1217         add_to_address_list (h,
1218                              LAL_BINDTO_ADDRESS,
1219                              sa,
1220                              sizeof (struct sockaddr_in6));
1221       break;
1222     default:
1223       break;
1224     }
1225   }
1226 }
1227
1228
1229 /**
1230  * Attempt to enable port redirection and detect public IP address contacting
1231  * UPnP or NAT-PMP routers on the local network. Use addr to specify to which
1232  * of the local host's addresses should the external port be mapped. The port
1233  * is taken from the corresponding sockaddr_in[6] field.
1234  *
1235  * @param cfg configuration to use
1236  * @param is_tcp #GNUNET_YES for TCP, #GNUNET_NO for UDP
1237  * @param adv_port advertised port (port we are either bound to or that our OS
1238  *                 locally performs redirection from to our bound port).
1239  * @param num_addrs number of addresses in @a addrs
1240  * @param addrs the local addresses packets should be redirected to
1241  * @param addrlens actual lengths of the addresses
1242  * @param address_callback function to call everytime the public IP address changes
1243  * @param reversal_callback function to call if someone wants connection reversal from us
1244  * @param callback_cls closure for callbacks
1245  * @return NULL on error, otherwise handle that can be used to unregister
1246  */
1247 struct GNUNET_NAT_Handle *
1248 GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg,
1249                      int is_tcp,
1250                      uint16_t adv_port,
1251                      unsigned int num_addrs,
1252                      const struct sockaddr **addrs,
1253                      const socklen_t *addrlens,
1254                      GNUNET_NAT_AddressCallback address_callback,
1255                      GNUNET_NAT_ReversalCallback reversal_callback,
1256                      void *callback_cls)
1257 {
1258   struct GNUNET_NAT_Handle *h;
1259   struct in_addr in_addr;
1260   unsigned int i;
1261   char *binary;
1262
1263   LOG (GNUNET_ERROR_TYPE_DEBUG,
1264        "Registered with NAT service at port %u with %u IP bound local addresses\n",
1265        (unsigned int) adv_port, num_addrs);
1266   h = GNUNET_new (struct GNUNET_NAT_Handle);
1267   h->server_retry_delay = GNUNET_TIME_UNIT_SECONDS;
1268   h->cfg = cfg;
1269   h->is_tcp = is_tcp;
1270   h->address_callback = address_callback;
1271   h->reversal_callback = reversal_callback;
1272   h->callback_cls = callback_cls;
1273   h->num_local_addrs = num_addrs;
1274   h->adv_port = adv_port;
1275   if (num_addrs != 0)
1276   {
1277     h->local_addrs = GNUNET_malloc (num_addrs * sizeof (struct sockaddr *));
1278     h->local_addrlens = GNUNET_malloc (num_addrs * sizeof (socklen_t));
1279     for (i = 0; i < num_addrs; i++)
1280     {
1281       GNUNET_assert (addrlens[i] > 0);
1282       GNUNET_assert (addrs[i] != NULL);
1283       h->local_addrlens[i] = addrlens[i];
1284       h->local_addrs[i] = GNUNET_malloc (addrlens[i]);
1285       memcpy (h->local_addrs[i], addrs[i], addrlens[i]);
1286     }
1287   }
1288   if (GNUNET_OK ==
1289       GNUNET_CONFIGURATION_have_value (cfg, "nat", "INTERNAL_ADDRESS"))
1290   {
1291     (void) GNUNET_CONFIGURATION_get_value_string (cfg, "nat",
1292                                                   "INTERNAL_ADDRESS",
1293                                                   &h->internal_address);
1294   }
1295   if ((h->internal_address != NULL) &&
1296       (inet_pton (AF_INET, h->internal_address, &in_addr) != 1))
1297   {
1298     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1299                                "nat", "INTERNAL_ADDRESS",
1300                                _("malformed"));
1301     GNUNET_free (h->internal_address);
1302     h->internal_address = NULL;
1303   }
1304
1305   if (GNUNET_OK ==
1306       GNUNET_CONFIGURATION_have_value (cfg, "nat", "EXTERNAL_ADDRESS"))
1307   {
1308     (void) GNUNET_CONFIGURATION_get_value_string (cfg, "nat",
1309                                                   "EXTERNAL_ADDRESS",
1310                                                   &h->external_address);
1311   }
1312   h->behind_nat =
1313       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "BEHIND_NAT");
1314   h->nat_punched =
1315       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "PUNCHED_NAT");
1316   h->enable_nat_client =
1317       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "ENABLE_ICMP_CLIENT");
1318   h->enable_nat_server =
1319       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "ENABLE_ICMP_SERVER");
1320   h->enable_upnp =
1321       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "ENABLE_UPNP");
1322   h->use_localaddresses =
1323       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "USE_LOCALADDR");
1324   h->return_localaddress =
1325       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat",
1326                                             "RETURN_LOCAL_ADDRESSES");
1327
1328   h->use_hostname =
1329       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "USE_HOSTNAME");
1330   h->disable_ipv6 =
1331       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "DISABLEV6");
1332   if (GNUNET_OK !=
1333       GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "DYNDNS_FREQUENCY",
1334                                            &h->dyndns_frequency))
1335     h->dyndns_frequency = DYNDNS_FREQUENCY;
1336   if (GNUNET_OK !=
1337       GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "IFC_SCAN_FREQUENCY",
1338                                            &h->ifc_scan_frequency))
1339     h->ifc_scan_frequency = IFC_SCAN_FREQUENCY;
1340   if (GNUNET_OK !=
1341       GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "HOSTNAME_DNS_FREQUENCY",
1342                                            &h->hostname_dns_frequency))
1343     h->hostname_dns_frequency = HOSTNAME_DNS_FREQUENCY;
1344
1345   if (NULL == reversal_callback)
1346     h->enable_nat_server = GNUNET_NO;
1347
1348   /* Check for UPnP client, disable immediately if not available */
1349   if ( (GNUNET_YES == h->enable_upnp) &&
1350        (GNUNET_SYSERR ==
1351         GNUNET_OS_check_helper_binary ("upnpc", GNUNET_NO, NULL)) )
1352   {
1353     LOG (GNUNET_ERROR_TYPE_ERROR,
1354         _("UPnP enabled in configuration, but UPnP client `upnpc` command not found, disabling UPnP \n"));
1355     h->enable_upnp = GNUNET_NO;
1356   }
1357
1358   /* Check if NAT was hole-punched */
1359   if ((NULL != h->address_callback) &&
1360       (NULL != h->external_address) &&
1361       (GNUNET_YES == h->nat_punched))
1362   {
1363     h->dns_task = GNUNET_SCHEDULER_add_now (&resolve_dns, h);
1364     h->enable_nat_server = GNUNET_NO;
1365     h->enable_upnp = GNUNET_NO;
1366   }
1367   else
1368   {
1369     LOG (GNUNET_ERROR_TYPE_DEBUG,
1370          "No external IP address given to add to our list of addresses\n");
1371   }
1372
1373   /* Test for SUID binaries */
1374   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-server");
1375   if ((h->behind_nat == GNUNET_YES) && (GNUNET_YES == h->enable_nat_server) &&
1376       (GNUNET_YES !=
1377        GNUNET_OS_check_helper_binary (binary, GNUNET_YES, "-d 127.0.0.1" ))) // use localhost as source for that one udp-port, ok for testing
1378   {
1379     h->enable_nat_server = GNUNET_NO;
1380     LOG (GNUNET_ERROR_TYPE_WARNING,
1381          _("Configuration requires `%s', but binary is not installed properly (SUID bit not set).  Option disabled.\n"),
1382          "gnunet-helper-nat-server");
1383   }
1384   GNUNET_free (binary);
1385   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-client");
1386   if ((GNUNET_YES == h->enable_nat_client) &&
1387       (GNUNET_YES !=
1388        GNUNET_OS_check_helper_binary (binary, GNUNET_YES, "-d 127.0.0.1 127.0.0.2 42"))) // none of these parameters are actually used in privilege testing mode
1389   {
1390     h->enable_nat_client = GNUNET_NO;
1391     LOG (GNUNET_ERROR_TYPE_WARNING,
1392          _
1393          ("Configuration requires `%s', but binary is not installed properly (SUID bit not set).  Option disabled.\n"),
1394          "gnunet-helper-nat-client");
1395   }
1396   GNUNET_free (binary);
1397   start_gnunet_nat_server (h);
1398
1399   /* FIXME: add support for UPnP, etc */
1400
1401   if (NULL != h->address_callback)
1402   {
1403     h->ifc_task = GNUNET_SCHEDULER_add_now (&list_interfaces,
1404                                             h);
1405     if (GNUNET_YES == h->use_hostname)
1406       h->hostname_task = GNUNET_SCHEDULER_add_now (&resolve_hostname,
1407                                                    h);
1408   }
1409   add_from_bind (h);
1410
1411   return h;
1412 }
1413
1414
1415 /**
1416  * Stop port redirection and public IP address detection for the given handle.
1417  * This frees the handle, after having sent the needed commands to close open ports.
1418  *
1419  * @param h the handle to stop
1420  */
1421 void
1422 GNUNET_NAT_unregister (struct GNUNET_NAT_Handle *h)
1423 {
1424   unsigned int i;
1425   struct LocalAddressList *lal;
1426   struct MiniList *ml;
1427
1428   LOG (GNUNET_ERROR_TYPE_DEBUG,
1429        "NAT unregister called\n");
1430   while (NULL != (ml = h->mini_head))
1431   {
1432     GNUNET_CONTAINER_DLL_remove (h->mini_head,
1433                                  h->mini_tail,
1434                                  ml);
1435     if (NULL != ml->mini)
1436       GNUNET_NAT_mini_map_stop (ml->mini);
1437     GNUNET_free (ml);
1438   }
1439   if (NULL != h->ext_dns)
1440   {
1441     GNUNET_RESOLVER_request_cancel (h->ext_dns);
1442     h->ext_dns = NULL;
1443   }
1444   if (NULL != h->hostname_dns)
1445   {
1446     GNUNET_RESOLVER_request_cancel (h->hostname_dns);
1447     h->hostname_dns = NULL;
1448   }
1449   if (NULL != h->server_read_task)
1450   {
1451     GNUNET_SCHEDULER_cancel (h->server_read_task);
1452     h->server_read_task = NULL;
1453   }
1454   if (NULL != h->ifc_task)
1455   {
1456     GNUNET_SCHEDULER_cancel (h->ifc_task);
1457     h->ifc_task = NULL;
1458   }
1459   if (NULL != h->hostname_task)
1460   {
1461     GNUNET_SCHEDULER_cancel (h->hostname_task);
1462     h->hostname_task = NULL;
1463   }
1464   if (NULL != h->dns_task)
1465   {
1466     GNUNET_SCHEDULER_cancel (h->dns_task);
1467     h->dns_task = NULL;
1468   }
1469   if (NULL != h->server_proc)
1470   {
1471     if (0 != GNUNET_OS_process_kill (h->server_proc, GNUNET_TERM_SIG))
1472       GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING, "nat", "kill");
1473     GNUNET_OS_process_wait (h->server_proc);
1474     GNUNET_OS_process_destroy (h->server_proc);
1475     h->server_proc = NULL;
1476     GNUNET_DISK_pipe_close (h->server_stdout);
1477     h->server_stdout = NULL;
1478     h->server_stdout_handle = NULL;
1479   }
1480   if (NULL != h->server_stdout)
1481   {
1482     GNUNET_DISK_pipe_close (h->server_stdout);
1483     h->server_stdout = NULL;
1484     h->server_stdout_handle = NULL;
1485   }
1486   while (NULL != (lal = h->lal_head))
1487   {
1488     GNUNET_CONTAINER_DLL_remove (h->lal_head, h->lal_tail, lal);
1489     if (NULL != h->address_callback)
1490       h->address_callback (h->callback_cls, GNUNET_NO,
1491                            (const struct sockaddr *) &lal[1], lal->addrlen);
1492     GNUNET_free (lal);
1493   }
1494   for (i = 0; i < h->num_local_addrs; i++)
1495     GNUNET_free (h->local_addrs[i]);
1496   GNUNET_free_non_null (h->local_addrs);
1497   GNUNET_free_non_null (h->local_addrlens);
1498   GNUNET_free_non_null (h->external_address);
1499   GNUNET_free_non_null (h->internal_address);
1500   GNUNET_free (h);
1501 }
1502
1503
1504 /**
1505  * We learned about a peer (possibly behind NAT) so run the
1506  * gnunet-helper-nat-client to send dummy ICMP responses to cause
1507  * that peer to connect to us (connection reversal).
1508  *
1509  * @param h handle (used for configuration)
1510  * @param sa the address of the peer (IPv4-only)
1511  * @return #GNUNET_SYSERR on error, #GNUNET_NO if nat client is disabled,
1512  *         #GNUNET_OK otherwise
1513  */
1514 int
1515 GNUNET_NAT_run_client (struct GNUNET_NAT_Handle *h,
1516                        const struct sockaddr_in *sa)
1517
1518
1519 {
1520   char inet4[INET_ADDRSTRLEN];
1521   char port_as_string[6];
1522   struct GNUNET_OS_Process *proc;
1523   char *binary;
1524
1525   if (GNUNET_YES != h->enable_nat_client)
1526     return GNUNET_NO;                     /* not permitted / possible */
1527
1528   if (h->internal_address == NULL)
1529   {
1530     LOG (GNUNET_ERROR_TYPE_WARNING, "nat",
1531          _("Internal IP address not known, cannot use ICMP NAT traversal method\n"));
1532     return GNUNET_SYSERR;
1533   }
1534   GNUNET_assert (sa->sin_family == AF_INET);
1535   if (NULL == inet_ntop (AF_INET, &sa->sin_addr, inet4, INET_ADDRSTRLEN))
1536   {
1537     GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING,
1538                               "nat",
1539                               "inet_ntop");
1540     return GNUNET_SYSERR;
1541   }
1542   GNUNET_snprintf (port_as_string,
1543                    sizeof (port_as_string),
1544                    "%d",
1545                    h->adv_port);
1546   LOG (GNUNET_ERROR_TYPE_DEBUG,
1547        _("Running gnunet-helper-nat-client %s %s %u\n"),
1548        h->internal_address,
1549        inet4,
1550        (unsigned int) h->adv_port);
1551   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-client");
1552   proc =
1553       GNUNET_OS_start_process (GNUNET_NO, 0, NULL, NULL, NULL,
1554                                binary,
1555                                "gnunet-helper-nat-client",
1556                                h->internal_address,
1557                                inet4, port_as_string, NULL);
1558   GNUNET_free (binary);
1559   if (NULL == proc)
1560     return GNUNET_SYSERR;
1561   /* we know that the gnunet-helper-nat-client will terminate virtually
1562    * instantly */
1563   GNUNET_OS_process_wait (proc);
1564   GNUNET_OS_process_destroy (proc);
1565   return GNUNET_OK;
1566 }
1567
1568
1569 /**
1570  * Test if the given address is (currently) a plausible IP address for this peer.
1571  *
1572  * @param h the handle returned by register
1573  * @param addr IP address to test (IPv4 or IPv6)
1574  * @param addrlen number of bytes in @a addr
1575  * @return #GNUNET_YES if the address is plausible,
1576  *         #GNUNET_NO if the address is not plausible,
1577  *         #GNUNET_SYSERR if the address is malformed
1578  */
1579 int
1580 GNUNET_NAT_test_address (struct GNUNET_NAT_Handle *h,
1581                          const void *addr,
1582                          socklen_t addrlen)
1583 {
1584   struct LocalAddressList *pos;
1585   const struct sockaddr_in *in4;
1586   const struct sockaddr_in6 *in6;
1587
1588   if ((addrlen != sizeof (struct in_addr)) &&
1589       (addrlen != sizeof (struct in6_addr)))
1590   {
1591     GNUNET_break (0);
1592     return GNUNET_SYSERR;
1593   }
1594   for (pos = h->lal_head; NULL != pos; pos = pos->next)
1595   {
1596     if (pos->addrlen == sizeof (struct sockaddr_in))
1597     {
1598       in4 = (struct sockaddr_in *) &pos[1];
1599       if ((addrlen == sizeof (struct in_addr)) &&
1600           (0 == memcmp (&in4->sin_addr, addr, sizeof (struct in_addr))))
1601         return GNUNET_YES;
1602     }
1603     else if (pos->addrlen == sizeof (struct sockaddr_in6))
1604     {
1605       in6 = (struct sockaddr_in6 *) &pos[1];
1606       if ((addrlen == sizeof (struct in6_addr)) &&
1607           (0 == memcmp (&in6->sin6_addr, addr, sizeof (struct in6_addr))))
1608         return GNUNET_YES;
1609     }
1610     else
1611     {
1612       GNUNET_assert (0);
1613     }
1614   }
1615   LOG (GNUNET_ERROR_TYPE_WARNING,
1616        "Asked to validate one of my addresses and validation failed!\n");
1617   return GNUNET_NO;
1618 }
1619
1620 /**
1621  * Converts enum GNUNET_NAT_StatusCode to a string
1622  *
1623  * @param err error code to resolve to a string
1624  * @return pointer to a static string containing the error code
1625  */
1626 const char *
1627 GNUNET_NAT_status2string (enum GNUNET_NAT_StatusCode err)
1628 {
1629   switch (err)
1630   {
1631   case GNUNET_NAT_ERROR_SUCCESS:
1632     return _ ("Operation Successful");
1633   case GNUNET_NAT_ERROR_IPC_FAILURE:
1634     return _ ("Internal Failure (IPC, ...)");
1635   case GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR:
1636     return _ ("Failure in network subsystem, check permissions.");
1637   case GNUNET_NAT_ERROR_TIMEOUT:
1638     return _ ("Encountered timeout while performing operation");
1639   case GNUNET_NAT_ERROR_NOT_ONLINE:
1640     return _ ("detected that we are offline");
1641   case GNUNET_NAT_ERROR_UPNPC_NOT_FOUND:
1642     return _ ("`upnpc` command not found");
1643   case GNUNET_NAT_ERROR_UPNPC_FAILED:
1644     return _ ("Failed to run `upnpc` command");
1645   case GNUNET_NAT_ERROR_UPNPC_TIMEOUT:
1646     return _ ("`upnpc' command took too long, process killed");
1647   case GNUNET_NAT_ERROR_UPNPC_PORTMAP_FAILED:
1648     return _ ("`upnpc' command failed to establish port mapping");
1649   case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_NOT_FOUND:
1650     return _ ("`external-ip' command not found");
1651   case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_FAILED:
1652     return _ ("Failed to run `external-ip` command");
1653   case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_OUTPUT_INVALID:
1654     return _ ("`external-ip' command output invalid");
1655   case GNUNET_NAT_ERROR_EXTERNAL_IP_ADDRESS_INVALID:
1656     return _ ("no valid address was returned by `external-ip'");
1657   case GNUNET_NAT_ERROR_NO_VALID_IF_IP_COMBO:
1658     return _ ("Could not determine interface with internal/local network address");
1659   case GNUNET_NAT_ERROR_HELPER_NAT_SERVER_NOT_FOUND:
1660     return _ ("No functioning gnunet-helper-nat-server installation found");
1661   case GNUNET_NAT_ERROR_NAT_TEST_START_FAILED:
1662     return _ ("NAT test could not be initialized");
1663   case GNUNET_NAT_ERROR_NAT_TEST_TIMEOUT:
1664     return _ ("NAT test timeout reached");
1665   case GNUNET_NAT_ERROR_NAT_REGISTER_FAILED:
1666     return _ ("could not register NAT");
1667   case GNUNET_NAT_ERROR_HELPER_NAT_CLIENT_NOT_FOUND:
1668     return _ ("No working gnunet-helper-nat-client installation found");
1669 /*  case:
1670     return _ ("");*/
1671   default:
1672     return "unknown status code";
1673   }
1674 }
1675
1676 /* end of nat.c */