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