DESTDIR fix in Makefiles needed by distro packagers
[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 we 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
1113 stun_request_callback(void *cls,
1114                                   enum GNUNET_NAT_StatusCode result)
1115 {
1116
1117   struct GNUNET_NAT_Handle *h = cls;
1118
1119   if(NULL == cls)
1120     return;
1121
1122   h->waiting_stun = GNUNET_NO;
1123
1124   if(result != GNUNET_OK)
1125   {
1126     LOG (GNUNET_ERROR_TYPE_WARNING,
1127        "Error processing a STUN request");
1128   }
1129
1130 };
1131
1132 /**
1133  * CHECK if is a valid STUN packet sending to GNUNET_NAT_stun_handle_packet.
1134  * It also check if it can handle the packet based on the NAT handler.
1135  * You don't need to call anything else to check if the packet is valid,
1136  *
1137  * @param cls the NAT handle
1138  * @param data, packet
1139  * @param len, packet length
1140  *
1141  * @return #GNUNET_NO if it can't decode, #GNUNET_YES if is a packet
1142  */
1143 int
1144 GNUNET_NAT_is_valid_stun_packet(void *cls, const void *data, size_t len)
1145 {
1146   struct GNUNET_NAT_Handle *h = cls;
1147   struct sockaddr_in answer;
1148
1149   /* We are not expecting a STUN message*/
1150   if(!h->waiting_stun)
1151     return GNUNET_NO;
1152
1153   /*We dont have STUN installed*/
1154   if(!h->use_stun)
1155     return GNUNET_NO;
1156
1157   /* Empty the answer structure */
1158   memset(&answer, 0, sizeof(struct sockaddr_in));
1159
1160   /*Lets handle the packet*/
1161   int valid = GNUNET_NAT_stun_handle_packet(data,len, &answer);
1162   if(valid)
1163   {
1164     LOG (GNUNET_ERROR_TYPE_INFO,
1165          "Stun server returned IP %s , with port %d \n", inet_ntoa(answer.sin_addr), ntohs(answer.sin_port));
1166     /* ADD IP AS VALID*/
1167     add_to_address_list (h, LAL_EXTERNAL_IP, (const struct sockaddr *) &answer,
1168                          sizeof (struct sockaddr_in));
1169     h->waiting_stun = GNUNET_NO;
1170     return GNUNET_YES;
1171   }
1172   else
1173   {
1174     return GNUNET_NO;
1175   }
1176
1177
1178
1179 }
1180
1181 /**
1182  * Task to do a STUN request
1183  *
1184  * @param cls the NAT handle
1185  * @param tc scheduler context
1186  */
1187 static void
1188 process_stun (void *cls,
1189                  const struct GNUNET_SCHEDULER_TaskContext *tc)
1190 {
1191   struct GNUNET_NAT_Handle *h = cls;
1192
1193   h->stun_task = NULL;
1194
1195
1196
1197   struct StunServerList* elem = h->actual_stun_server;
1198
1199   /* Make the request */
1200   LOG (GNUNET_ERROR_TYPE_INFO,
1201        "I will request the stun server %s:%i !\n", elem->address, elem->port);
1202
1203   if(GNUNET_OK == GNUNET_NAT_stun_make_request(elem->address, elem->port, h->socket, &stun_request_callback, NULL))
1204   {
1205     h->waiting_stun = GNUNET_YES;
1206   }
1207   else
1208   {
1209     LOG (GNUNET_ERROR_TYPE_ERROR,
1210          "STUN request failed %s:%i !\n", elem->address, elem->port);
1211   }
1212
1213   h->stun_task =
1214           GNUNET_SCHEDULER_add_delayed (h->stun_frequency,
1215                                         &process_stun, h);
1216
1217   /* Set actual Server*/
1218   if(elem->next)
1219   {
1220     h->actual_stun_server = elem->next;
1221   }
1222   else
1223   {
1224     h->actual_stun_server = h->stun_servers_head;
1225   }
1226
1227 }
1228
1229
1230
1231 /**
1232  * Task to do a lookup on our hostname for IP addresses.
1233  *
1234  * @param cls the NAT handle
1235  * @param tc scheduler context
1236  */
1237 static void
1238 resolve_hostname (void *cls,
1239                   const struct GNUNET_SCHEDULER_TaskContext *tc)
1240 {
1241   struct GNUNET_NAT_Handle *h = cls;
1242
1243   h->hostname_task = NULL;
1244   remove_from_address_list_by_source (h, LAL_HOSTNAME_DNS);
1245   h->hostname_dns =
1246       GNUNET_RESOLVER_hostname_resolve (AF_UNSPEC, HOSTNAME_RESOLVE_TIMEOUT,
1247                                         &process_hostname_ip, h);
1248 }
1249
1250
1251 /**
1252  * Task to do DNS lookup on our external hostname to
1253  * get DynDNS-IP addresses.
1254  *
1255  * @param cls the NAT handle
1256  * @param tc scheduler context
1257  */
1258 static void
1259 resolve_dns (void *cls,
1260              const struct GNUNET_SCHEDULER_TaskContext *tc)
1261 {
1262   struct GNUNET_NAT_Handle *h = cls;
1263   struct LocalAddressList *pos;
1264
1265   h->dns_task = NULL;
1266   for (pos = h->lal_head; NULL != pos; pos = pos->next)
1267     if (pos->source == LAL_EXTERNAL_IP)
1268       pos->source = LAL_EXTERNAL_IP_OLD;
1269   LOG (GNUNET_ERROR_TYPE_DEBUG,
1270        "Resolving external address `%s'\n",
1271        h->external_address);
1272   h->ext_dns =
1273       GNUNET_RESOLVER_ip_get (h->external_address, AF_INET,
1274                               GNUNET_TIME_UNIT_MINUTES,
1275                               &process_external_ip, h);
1276 }
1277
1278
1279 /**
1280  * Add or remove UPnP-mapped addresses.
1281  *
1282  * @param cls the `struct GNUNET_NAT_Handle`
1283  * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
1284  *     the previous (now invalid) one
1285  * @param addr either the previous or the new public IP address
1286  * @param addrlen actual lenght of @a addr
1287  * @param ret GNUNET_NAT_ERROR_SUCCESS on success, otherwise an error code
1288  */
1289 static void
1290 upnp_add (void *cls,
1291           int add_remove,
1292           const struct sockaddr *addr,
1293           socklen_t addrlen,
1294           enum GNUNET_NAT_StatusCode ret)
1295 {
1296   struct GNUNET_NAT_Handle *h = cls;
1297   struct LocalAddressList *pos;
1298   struct LocalAddressList *next;
1299
1300
1301   if (GNUNET_NAT_ERROR_SUCCESS != ret)
1302   {
1303     /* Error while running upnp client */
1304     LOG (GNUNET_ERROR_TYPE_ERROR,
1305           _("Error while running upnp client:\n"));
1306
1307     //FIXME: convert error code to string
1308
1309     return;
1310   }
1311
1312   if (GNUNET_YES == add_remove)
1313   {
1314     add_to_address_list (h, LAL_UPNP, addr, addrlen);
1315     return;
1316   }
1317   else if (GNUNET_NO == add_remove)
1318   {
1319     /* remove address */
1320     next = h->lal_head;
1321     while (NULL != (pos = next))
1322     {
1323       next = pos->next;
1324       if ((pos->source != LAL_UPNP) || (pos->addrlen != addrlen) ||
1325           (0 != memcmp (&pos[1], addr, addrlen)))
1326         continue;
1327       GNUNET_CONTAINER_DLL_remove (h->lal_head, h->lal_tail, pos);
1328       if (NULL != h->address_callback)
1329         h->address_callback (h->callback_cls, GNUNET_NO,
1330                              (const struct sockaddr *) &pos[1], pos->addrlen);
1331       GNUNET_free (pos);
1332       return;                     /* only remove once */
1333     }
1334     /* asked to remove address that does not exist */
1335     LOG (GNUNET_ERROR_TYPE_ERROR,
1336          "Asked to remove unkown address `%s'\n",
1337          GNUNET_a2s(addr, addrlen));
1338     GNUNET_break (0);
1339   }
1340   else
1341   {
1342
1343     GNUNET_break (0);
1344   }
1345 }
1346
1347
1348 /**
1349  * Try to add a port mapping using UPnP.
1350  *
1351  * @param h overall NAT handle
1352  * @param port port to map with UPnP
1353  */
1354 static void
1355 add_minis (struct GNUNET_NAT_Handle *h,
1356            uint16_t port)
1357 {
1358   struct MiniList *ml;
1359
1360   ml = h->mini_head;
1361   while (NULL != ml)
1362   {
1363     if (port == ml->port)
1364       return;                   /* already got this port */
1365     ml = ml->next;
1366   }
1367
1368   ml = GNUNET_new (struct MiniList);
1369   ml->port = port;
1370   ml->mini = GNUNET_NAT_mini_map_start (port, h->is_tcp, &upnp_add, h);
1371
1372   if (NULL == ml->mini)
1373   {
1374     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1375         _("Failed to run upnp client for port %u\n"), ml->port);
1376     GNUNET_free (ml);
1377     return;
1378   }
1379
1380   GNUNET_CONTAINER_DLL_insert (h->mini_head, h->mini_tail, ml);
1381 }
1382
1383
1384 /**
1385  * Task to add addresses from original bind to set of valid addrs.
1386  *
1387  * @param h the NAT handle
1388  */
1389 static void
1390 add_from_bind (struct GNUNET_NAT_Handle *h)
1391 {
1392   static struct in6_addr any = IN6ADDR_ANY_INIT;
1393
1394   unsigned int i;
1395   struct sockaddr *sa;
1396   const struct sockaddr_in *v4;
1397
1398   for (i = 0; i < h->num_local_addrs; i++)
1399   {
1400     sa = h->local_addrs[i];
1401     switch (sa->sa_family)
1402     {
1403     case AF_INET:
1404       if (sizeof (struct sockaddr_in) != h->local_addrlens[i])
1405       {
1406         GNUNET_break (0);
1407         break;
1408       }
1409       v4 = (const struct sockaddr_in *) sa;
1410       if (0 != v4->sin_addr.s_addr)
1411         add_to_address_list (h,
1412                              LAL_BINDTO_ADDRESS, sa,
1413                              sizeof (struct sockaddr_in));
1414       if (h->enable_upnp)
1415       {
1416         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1417                     "Running upnp client for address `%s'\n",
1418                     GNUNET_a2s (sa,sizeof (struct sockaddr_in)));
1419         add_minis (h, ntohs (v4->sin_port));
1420       }
1421       break;
1422     case AF_INET6:
1423       if (sizeof (struct sockaddr_in6) != h->local_addrlens[i])
1424       {
1425         GNUNET_break (0);
1426         break;
1427       }
1428       if (0 !=
1429           memcmp (&((const struct sockaddr_in6 *) sa)->sin6_addr,
1430                   &any,
1431                   sizeof (struct in6_addr)))
1432         add_to_address_list (h,
1433                              LAL_BINDTO_ADDRESS,
1434                              sa,
1435                              sizeof (struct sockaddr_in6));
1436       break;
1437     default:
1438       break;
1439     }
1440   }
1441 }
1442
1443
1444 /**
1445  * Attempt to enable port redirection and detect public IP address contacting
1446  * UPnP or NAT-PMP routers on the local network. Use addr to specify to which
1447  * of the local host's addresses should the external port be mapped. The port
1448  * is taken from the corresponding sockaddr_in[6] field.
1449  *
1450  * @param cfg configuration to use
1451  * @param is_tcp #GNUNET_YES for TCP, #GNUNET_NO for UDP
1452  * @param adv_port advertised port (port we are either bound to or that our OS
1453  *                 locally performs redirection from to our bound port).
1454  * @param num_addrs number of addresses in @a addrs
1455  * @param addrs the local addresses packets should be redirected to
1456  * @param addrlens actual lengths of the addresses
1457  * @param address_callback function to call everytime the public IP address changes
1458  * @param reversal_callback function to call if someone wants connection reversal from us
1459  * @param callback_cls closure for callbacks
1460  * @param sock used socket
1461  * @return NULL on error, otherwise handle that can be used to unregister
1462  */
1463 struct GNUNET_NAT_Handle *
1464 GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg,
1465                      int is_tcp,
1466                      uint16_t adv_port,
1467                      unsigned int num_addrs,
1468                      const struct sockaddr **addrs,
1469                      const socklen_t *addrlens,
1470                      GNUNET_NAT_AddressCallback address_callback,
1471                      GNUNET_NAT_ReversalCallback reversal_callback,
1472                      void *callback_cls,
1473                      struct GNUNET_NETWORK_Handle* sock )
1474 {
1475   struct GNUNET_NAT_Handle *h;
1476   struct in_addr in_addr;
1477   unsigned int i;
1478   char *binary;
1479
1480   LOG (GNUNET_ERROR_TYPE_DEBUG,
1481        "Registered with NAT service at port %u with %u IP bound local addresses\n",
1482        (unsigned int) adv_port, num_addrs);
1483   h = GNUNET_new (struct GNUNET_NAT_Handle);
1484   h->server_retry_delay = GNUNET_TIME_UNIT_SECONDS;
1485   h->cfg = cfg;
1486   h->is_tcp = is_tcp;
1487   h->address_callback = address_callback;
1488   h->reversal_callback = reversal_callback;
1489   h->callback_cls = callback_cls;
1490   h->num_local_addrs = num_addrs;
1491   h->adv_port = adv_port;
1492   if (num_addrs != 0)
1493   {
1494     h->local_addrs = GNUNET_malloc (num_addrs * sizeof (struct sockaddr *));
1495     h->local_addrlens = GNUNET_malloc (num_addrs * sizeof (socklen_t));
1496     for (i = 0; i < num_addrs; i++)
1497     {
1498       GNUNET_assert (addrlens[i] > 0);
1499       GNUNET_assert (addrs[i] != NULL);
1500       h->local_addrlens[i] = addrlens[i];
1501       h->local_addrs[i] = GNUNET_malloc (addrlens[i]);
1502       memcpy (h->local_addrs[i], addrs[i], addrlens[i]);
1503     }
1504   }
1505   if (GNUNET_OK ==
1506       GNUNET_CONFIGURATION_have_value (cfg, "nat", "INTERNAL_ADDRESS"))
1507   {
1508     (void) GNUNET_CONFIGURATION_get_value_string (cfg, "nat",
1509                                                   "INTERNAL_ADDRESS",
1510                                                   &h->internal_address);
1511   }
1512   if ((h->internal_address != NULL) &&
1513       (inet_pton (AF_INET, h->internal_address, &in_addr) != 1))
1514   {
1515     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1516                                "nat", "INTERNAL_ADDRESS",
1517                                _("malformed"));
1518     GNUNET_free (h->internal_address);
1519     h->internal_address = NULL;
1520   }
1521
1522   if (GNUNET_OK ==
1523       GNUNET_CONFIGURATION_have_value (cfg, "nat", "EXTERNAL_ADDRESS"))
1524   {
1525     (void) GNUNET_CONFIGURATION_get_value_string (cfg, "nat",
1526                                                   "EXTERNAL_ADDRESS",
1527                                                   &h->external_address);
1528   }
1529   h->behind_nat =
1530       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "BEHIND_NAT");
1531   h->nat_punched =
1532       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "PUNCHED_NAT");
1533   h->enable_nat_client =
1534       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "ENABLE_ICMP_CLIENT");
1535   h->enable_nat_server =
1536       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "ENABLE_ICMP_SERVER");
1537   h->enable_upnp =
1538       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "ENABLE_UPNP");
1539   h->use_localaddresses =
1540       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "USE_LOCALADDR");
1541   h->return_localaddress =
1542       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat",
1543                                             "RETURN_LOCAL_ADDRESSES");
1544
1545   h->use_hostname =
1546       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "USE_HOSTNAME");
1547   h->disable_ipv6 =
1548       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "DISABLEV6");
1549   if (GNUNET_OK !=
1550       GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "DYNDNS_FREQUENCY",
1551                                            &h->dyndns_frequency))
1552     h->dyndns_frequency = DYNDNS_FREQUENCY;
1553   if (GNUNET_OK !=
1554       GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "IFC_SCAN_FREQUENCY",
1555                                            &h->ifc_scan_frequency))
1556     h->ifc_scan_frequency = IFC_SCAN_FREQUENCY;
1557   if (GNUNET_OK !=
1558       GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "HOSTNAME_DNS_FREQUENCY",
1559                                            &h->hostname_dns_frequency))
1560     h->hostname_dns_frequency = HOSTNAME_DNS_FREQUENCY;
1561
1562   if (NULL == reversal_callback)
1563     h->enable_nat_server = GNUNET_NO;
1564
1565   /* Check for UPnP client, disable immediately if not available */
1566   if ( (GNUNET_YES == h->enable_upnp) &&
1567        (GNUNET_SYSERR ==
1568         GNUNET_OS_check_helper_binary ("upnpc", GNUNET_NO, NULL)) )
1569   {
1570     LOG (GNUNET_ERROR_TYPE_ERROR,
1571         _("UPnP enabled in configuration, but UPnP client `upnpc` command not found, disabling UPnP \n"));
1572     h->enable_upnp = GNUNET_NO;
1573   }
1574
1575   /* STUN */
1576   h->use_stun =
1577           GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat",
1578                                                 "USE_STUN");
1579
1580   if (GNUNET_OK !=
1581       GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "STUN_FREQUENCY",
1582                                            &h->stun_frequency))
1583     h->stun_frequency = STUN_FREQUENCY;
1584
1585
1586   /* Check if NAT was hole-punched */
1587   if ((NULL != h->address_callback) &&
1588       (NULL != h->external_address) &&
1589       (GNUNET_YES == h->nat_punched))
1590   {
1591     h->dns_task = GNUNET_SCHEDULER_add_now (&resolve_dns, h);
1592     h->enable_nat_server = GNUNET_NO;
1593     h->enable_upnp = GNUNET_NO;
1594     h->use_stun = GNUNET_NO;
1595   }
1596   else
1597   {
1598     LOG (GNUNET_ERROR_TYPE_DEBUG,
1599          "No external IP address given to add to our list of addresses\n");
1600   }
1601
1602   /* ENABLE STUN ONLY ON UDP*/
1603   if(!is_tcp && (NULL != sock) && h->use_stun  )
1604   {
1605     h->socket = sock;
1606     h->actual_stun_server = NULL;
1607
1608     /* Lets process the servers*/
1609     char *stun_servers;
1610
1611     size_t urls;
1612     int pos;
1613     size_t pos_port;
1614
1615     if (GNUNET_OK !=
1616         GNUNET_CONFIGURATION_get_value_string (cfg, "nat", "STUN_SERVERS",
1617                                                &stun_servers))
1618     {
1619       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_WARNING,
1620                                  "nat", "STUN_SERVERS");
1621     }
1622
1623     urls = 0;
1624     h->stun_servers_head = NULL;
1625     h->stun_servers_tail = NULL;
1626     h->actual_stun_server = NULL;
1627     if (strlen (stun_servers) > 0)
1628     {
1629       pos = strlen (stun_servers) - 1;
1630       pos_port = 0;
1631       while (pos >= 0)
1632       {
1633         if (stun_servers[pos] == ':')
1634         {
1635           pos_port = pos + 1;
1636         }
1637         if ((stun_servers[pos] == ' ') || (0 == pos))
1638         {
1639
1640           /*Check if we do have a port*/
1641           if((0 == pos_port) || (pos_port <= pos))
1642           {
1643             LOG (GNUNET_ERROR_TYPE_WARNING,
1644                  "STUN server format mistake\n");
1645             break;
1646           }
1647
1648           urls++;
1649
1650           struct StunServerList* ml = GNUNET_new (struct StunServerList);
1651
1652           ml->next = NULL;
1653           ml->prev = NULL;
1654
1655           ml->port = atoi(&stun_servers[pos_port]);
1656           stun_servers[pos_port-1] = '\0';
1657
1658           /* Remove trailing space */
1659           if(stun_servers[pos] == ' ')
1660             ml->address = GNUNET_strdup (&stun_servers[pos + 1]);
1661           else
1662             ml->address = GNUNET_strdup (&stun_servers[pos]);
1663
1664           LOG (GNUNET_ERROR_TYPE_DEBUG,
1665                "Found STUN server %s port %i !!!\n", ml->address, ml->port);
1666
1667           GNUNET_CONTAINER_DLL_insert (h->stun_servers_head, h->stun_servers_tail, ml);
1668           /* Make sure that we STOP if is the last one*/
1669           if(0== pos)
1670             break;
1671         }
1672
1673         pos--;
1674       }
1675     }
1676     if (urls == 0)
1677     {
1678       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_WARNING,
1679                                  "nat", "STUN_SERVERS");
1680     }
1681     else
1682     {
1683       /* Set the actual STUN server*/
1684       h->actual_stun_server = h->stun_servers_head;
1685     }
1686
1687     h->stun_task = GNUNET_SCHEDULER_add_now(&process_stun,
1688                                             h);
1689   }
1690
1691
1692   /* Test for SUID binaries */
1693   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-server");
1694   if ((h->behind_nat == GNUNET_YES) && (GNUNET_YES == h->enable_nat_server) &&
1695       (GNUNET_YES !=
1696        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
1697   {
1698     h->enable_nat_server = GNUNET_NO;
1699     LOG (GNUNET_ERROR_TYPE_WARNING,
1700          _("Configuration requires `%s', but binary is not installed properly (SUID bit not set).  Option disabled.\n"),
1701          "gnunet-helper-nat-server");
1702   }
1703   GNUNET_free (binary);
1704   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-client");
1705   if ((GNUNET_YES == h->enable_nat_client) &&
1706       (GNUNET_YES !=
1707        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
1708   {
1709     h->enable_nat_client = GNUNET_NO;
1710     LOG (GNUNET_ERROR_TYPE_WARNING,
1711          _
1712          ("Configuration requires `%s', but binary is not installed properly (SUID bit not set).  Option disabled.\n"),
1713          "gnunet-helper-nat-client");
1714   }
1715   GNUNET_free (binary);
1716   start_gnunet_nat_server (h);
1717
1718   /* FIXME: add support for UPnP, etc */
1719
1720   if (NULL != h->address_callback)
1721   {
1722     h->ifc_task = GNUNET_SCHEDULER_add_now (&list_interfaces,
1723                                             h);
1724     if (GNUNET_YES == h->use_hostname)
1725       h->hostname_task = GNUNET_SCHEDULER_add_now (&resolve_hostname,
1726                                                    h);
1727   }
1728   add_from_bind (h);
1729
1730   return h;
1731 }
1732
1733
1734 /**
1735  * Stop port redirection and public IP address detection for the given handle.
1736  * This frees the handle, after having sent the needed commands to close open ports.
1737  *
1738  * @param h the handle to stop
1739  */
1740 void
1741 GNUNET_NAT_unregister (struct GNUNET_NAT_Handle *h)
1742 {
1743   unsigned int i;
1744   struct LocalAddressList *lal;
1745   struct MiniList *ml;
1746
1747   LOG (GNUNET_ERROR_TYPE_DEBUG,
1748        "NAT unregister called\n");
1749   while (NULL != (ml = h->mini_head))
1750   {
1751     GNUNET_CONTAINER_DLL_remove (h->mini_head,
1752                                  h->mini_tail,
1753                                  ml);
1754     if (NULL != ml->mini)
1755       GNUNET_NAT_mini_map_stop (ml->mini);
1756     GNUNET_free (ml);
1757   }
1758   if (NULL != h->ext_dns)
1759   {
1760     GNUNET_RESOLVER_request_cancel (h->ext_dns);
1761     h->ext_dns = NULL;
1762   }
1763   if (NULL != h->hostname_dns)
1764   {
1765     GNUNET_RESOLVER_request_cancel (h->hostname_dns);
1766     h->hostname_dns = NULL;
1767   }
1768   if (NULL != h->server_read_task)
1769   {
1770     GNUNET_SCHEDULER_cancel (h->server_read_task);
1771     h->server_read_task = NULL;
1772   }
1773   if (NULL != h->ifc_task)
1774   {
1775     GNUNET_SCHEDULER_cancel (h->ifc_task);
1776     h->ifc_task = NULL;
1777   }
1778   if (NULL != h->hostname_task)
1779   {
1780     GNUNET_SCHEDULER_cancel (h->hostname_task);
1781     h->hostname_task = NULL;
1782   }
1783   if (NULL != h->dns_task)
1784   {
1785     GNUNET_SCHEDULER_cancel (h->dns_task);
1786     h->dns_task = NULL;
1787   }
1788   if (NULL !=   h->stun_task)
1789   {
1790     GNUNET_SCHEDULER_cancel (h->stun_task);
1791     h->stun_task = NULL;
1792   }
1793   if (NULL != h->server_proc)
1794   {
1795     if (0 != GNUNET_OS_process_kill (h->server_proc, GNUNET_TERM_SIG))
1796       GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING, "nat", "kill");
1797     GNUNET_OS_process_wait (h->server_proc);
1798     GNUNET_OS_process_destroy (h->server_proc);
1799     h->server_proc = NULL;
1800     GNUNET_DISK_pipe_close (h->server_stdout);
1801     h->server_stdout = NULL;
1802     h->server_stdout_handle = NULL;
1803   }
1804   if (NULL != h->server_stdout)
1805   {
1806     GNUNET_DISK_pipe_close (h->server_stdout);
1807     h->server_stdout = NULL;
1808     h->server_stdout_handle = NULL;
1809   }
1810   while (NULL != (lal = h->lal_head))
1811   {
1812     GNUNET_CONTAINER_DLL_remove (h->lal_head, h->lal_tail, lal);
1813     if (NULL != h->address_callback)
1814       h->address_callback (h->callback_cls, GNUNET_NO,
1815                            (const struct sockaddr *) &lal[1], lal->addrlen);
1816     GNUNET_free (lal);
1817   }
1818   for (i = 0; i < h->num_local_addrs; i++)
1819     GNUNET_free (h->local_addrs[i]);
1820   GNUNET_free_non_null (h->local_addrs);
1821   GNUNET_free_non_null (h->local_addrlens);
1822   GNUNET_free_non_null (h->external_address);
1823   GNUNET_free_non_null (h->internal_address);
1824   GNUNET_free (h);
1825 }
1826
1827
1828 /**
1829  * We learned about a peer (possibly behind NAT) so run the
1830  * gnunet-helper-nat-client to send dummy ICMP responses to cause
1831  * that peer to connect to us (connection reversal).
1832  *
1833  * @param h handle (used for configuration)
1834  * @param sa the address of the peer (IPv4-only)
1835  * @return #GNUNET_SYSERR on error, #GNUNET_NO if nat client is disabled,
1836  *         #GNUNET_OK otherwise
1837  */
1838 int
1839 GNUNET_NAT_run_client (struct GNUNET_NAT_Handle *h,
1840                        const struct sockaddr_in *sa)
1841
1842
1843 {
1844   char inet4[INET_ADDRSTRLEN];
1845   char port_as_string[6];
1846   struct GNUNET_OS_Process *proc;
1847   char *binary;
1848
1849   if (GNUNET_YES != h->enable_nat_client)
1850     return GNUNET_NO;                     /* not permitted / possible */
1851
1852   if (h->internal_address == NULL)
1853   {
1854     LOG (GNUNET_ERROR_TYPE_WARNING, "nat",
1855          _("Internal IP address not known, cannot use ICMP NAT traversal method\n"));
1856     return GNUNET_SYSERR;
1857   }
1858   GNUNET_assert (sa->sin_family == AF_INET);
1859   if (NULL == inet_ntop (AF_INET, &sa->sin_addr, inet4, INET_ADDRSTRLEN))
1860   {
1861     GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING,
1862                               "nat",
1863                               "inet_ntop");
1864     return GNUNET_SYSERR;
1865   }
1866   GNUNET_snprintf (port_as_string,
1867                    sizeof (port_as_string),
1868                    "%d",
1869                    h->adv_port);
1870   LOG (GNUNET_ERROR_TYPE_DEBUG,
1871        _("Running gnunet-helper-nat-client %s %s %u\n"),
1872        h->internal_address,
1873        inet4,
1874        (unsigned int) h->adv_port);
1875   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-client");
1876   proc =
1877       GNUNET_OS_start_process (GNUNET_NO, 0, NULL, NULL, NULL,
1878                                binary,
1879                                "gnunet-helper-nat-client",
1880                                h->internal_address,
1881                                inet4, port_as_string, NULL);
1882   GNUNET_free (binary);
1883   if (NULL == proc)
1884     return GNUNET_SYSERR;
1885   /* we know that the gnunet-helper-nat-client will terminate virtually
1886    * instantly */
1887   GNUNET_OS_process_wait (proc);
1888   GNUNET_OS_process_destroy (proc);
1889   return GNUNET_OK;
1890 }
1891
1892
1893 /**
1894  * Test if the given address is (currently) a plausible IP address for this peer.
1895  *
1896  * @param h the handle returned by register
1897  * @param addr IP address to test (IPv4 or IPv6)
1898  * @param addrlen number of bytes in @a addr
1899  * @return #GNUNET_YES if the address is plausible,
1900  *         #GNUNET_NO if the address is not plausible,
1901  *         #GNUNET_SYSERR if the address is malformed
1902  */
1903 int
1904 GNUNET_NAT_test_address (struct GNUNET_NAT_Handle *h,
1905                          const void *addr,
1906                          socklen_t addrlen)
1907 {
1908   struct LocalAddressList *pos;
1909   const struct sockaddr_in *in4;
1910   const struct sockaddr_in6 *in6;
1911
1912   if ((addrlen != sizeof (struct in_addr)) &&
1913       (addrlen != sizeof (struct in6_addr)))
1914   {
1915     GNUNET_break (0);
1916     return GNUNET_SYSERR;
1917   }
1918   for (pos = h->lal_head; NULL != pos; pos = pos->next)
1919   {
1920     if (pos->addrlen == sizeof (struct sockaddr_in))
1921     {
1922       in4 = (struct sockaddr_in *) &pos[1];
1923       if ((addrlen == sizeof (struct in_addr)) &&
1924           (0 == memcmp (&in4->sin_addr, addr, sizeof (struct in_addr))))
1925         return GNUNET_YES;
1926     }
1927     else if (pos->addrlen == sizeof (struct sockaddr_in6))
1928     {
1929       in6 = (struct sockaddr_in6 *) &pos[1];
1930       if ((addrlen == sizeof (struct in6_addr)) &&
1931           (0 == memcmp (&in6->sin6_addr, addr, sizeof (struct in6_addr))))
1932         return GNUNET_YES;
1933     }
1934     else
1935     {
1936       GNUNET_assert (0);
1937     }
1938   }
1939   LOG (GNUNET_ERROR_TYPE_WARNING,
1940        "Asked to validate one of my addresses (%s) and validation failed!\n",
1941        GNUNET_a2s (addr,
1942                    addrlen));
1943   return GNUNET_NO;
1944 }
1945
1946 /**
1947  * Converts enum GNUNET_NAT_StatusCode to a string
1948  *
1949  * @param err error code to resolve to a string
1950  * @return pointer to a static string containing the error code
1951  */
1952 const char *
1953 GNUNET_NAT_status2string (enum GNUNET_NAT_StatusCode err)
1954 {
1955   switch (err)
1956   {
1957   case GNUNET_NAT_ERROR_SUCCESS:
1958     return _ ("Operation Successful");
1959   case GNUNET_NAT_ERROR_IPC_FAILURE:
1960     return _ ("Internal Failure (IPC, ...)");
1961   case GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR:
1962     return _ ("Failure in network subsystem, check permissions.");
1963   case GNUNET_NAT_ERROR_TIMEOUT:
1964     return _ ("Encountered timeout while performing operation");
1965   case GNUNET_NAT_ERROR_NOT_ONLINE:
1966     return _ ("detected that we are offline");
1967   case GNUNET_NAT_ERROR_UPNPC_NOT_FOUND:
1968     return _ ("`upnpc` command not found");
1969   case GNUNET_NAT_ERROR_UPNPC_FAILED:
1970     return _ ("Failed to run `upnpc` command");
1971   case GNUNET_NAT_ERROR_UPNPC_TIMEOUT:
1972     return _ ("`upnpc' command took too long, process killed");
1973   case GNUNET_NAT_ERROR_UPNPC_PORTMAP_FAILED:
1974     return _ ("`upnpc' command failed to establish port mapping");
1975   case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_NOT_FOUND:
1976     return _ ("`external-ip' command not found");
1977   case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_FAILED:
1978     return _ ("Failed to run `external-ip` command");
1979   case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_OUTPUT_INVALID:
1980     return _ ("`external-ip' command output invalid");
1981   case GNUNET_NAT_ERROR_EXTERNAL_IP_ADDRESS_INVALID:
1982     return _ ("no valid address was returned by `external-ip'");
1983   case GNUNET_NAT_ERROR_NO_VALID_IF_IP_COMBO:
1984     return _ ("Could not determine interface with internal/local network address");
1985   case GNUNET_NAT_ERROR_HELPER_NAT_SERVER_NOT_FOUND:
1986     return _ ("No functioning gnunet-helper-nat-server installation found");
1987   case GNUNET_NAT_ERROR_NAT_TEST_START_FAILED:
1988     return _ ("NAT test could not be initialized");
1989   case GNUNET_NAT_ERROR_NAT_TEST_TIMEOUT:
1990     return _ ("NAT test timeout reached");
1991   case GNUNET_NAT_ERROR_NAT_REGISTER_FAILED:
1992     return _ ("could not register NAT");
1993   case GNUNET_NAT_ERROR_HELPER_NAT_CLIENT_NOT_FOUND:
1994     return _ ("No working gnunet-helper-nat-client installation found");
1995 /*  case:
1996     return _ ("");*/
1997   default:
1998     return "unknown status code";
1999   }
2000 }
2001
2002 /* end of nat.c */