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