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