99d2bbc7ca2b1747507da4a2d65768b6d9674de5
[oweals/gnunet.git] / src / nat / nat.c
1 /*
2      This file is part of GNUnet.
3      (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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, 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  * TODO:
29  * - implement UPnP/PMP support
30  * - repeatedly perform certain checks again to notice changes
31  */
32 #include "platform.h"
33 #include "gnunet_util_lib.h"
34 #include "gnunet_resolver_service.h"
35 #include "gnunet_nat_lib.h"
36
37
38 /**
39  * How long until we give up on transmitting the welcome message?
40  */
41 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
42
43
44 /**
45  * Where did the given local address originate from?
46  * To be used for debugging as well as in the future 
47  * to remove all addresses from a certain source when
48  * we reevaluate the source.
49  */
50 enum LocalAddressSource
51   {
52     /**
53      * Address was obtained by DNS resolution of the external hostname
54      * given in the configuration (i.e. hole-punched DynDNS setup).
55      * FIXME: repeatedly do the lookup to notice changes!
56      */
57     LAL_EXTERNAL_IP,
58
59     /**
60      * Address was obtained by looking up our own hostname in DNS.
61      * FIXME: repeatedly do the lookup to notice changes!
62      */
63     LAL_HOSTNAME_DNS,
64
65     /**
66      * Address was obtained by scanning our hosts's network interfaces
67      * and taking their address (no DNS involved).
68      * FIXME: repeatedly do the lookup to notice changes!
69      */
70     LAL_INTERFACE_ADDRESS,
71
72     /* TODO: add UPnP, etc. */
73
74     /**
75      * End of the list.
76      */
77     LAL_END
78     
79   };
80
81
82 /**
83  * List of local addresses that we currently deem valid.  Actual
84  * struct is followed by the 'struct sockaddr'.  Note that the code
85  * intentionally makes no attempt to ensure that a particular address
86  * is only listed once (especially since it may come from different
87  * sources, and the source is an "internal" construct).
88  */
89 struct LocalAddressList
90 {
91   /**
92    * This is a linked list.
93    */
94   struct LocalAddressList *next;
95
96   /**
97    * Previous entry.
98    */ 
99   struct LocalAddressList *prev;
100
101   /**
102    * Number of bytes of address that follow.
103    */
104   socklen_t addrlen;
105
106   /**
107    * Origin of the local address.
108    */
109   enum LocalAddressSource source;
110 };
111
112
113 /**
114  * Handle for active NAT registrations.
115  */
116 struct GNUNET_NAT_Handle
117 {
118
119   /**
120    * Configuration to use.
121    */
122   const struct GNUNET_CONFIGURATION_Handle *cfg;
123   
124   /**
125    * Function to call when we learn about a new address.
126    */
127   GNUNET_NAT_AddressCallback address_callback;
128
129   /**
130    * Function to call when we notice another peer asking for
131    * connection reversal.
132    */
133   GNUNET_NAT_ReversalCallback reversal_callback;
134
135   /**
136    * Closure for 'callback'.
137    */
138   void *callback_cls;
139
140   /**
141    * Handle for (DYN)DNS lookup of our external IP.
142    */
143   struct GNUNET_RESOLVER_RequestHandle *ext_dns;
144
145   /**
146    * Handle for request of hostname resolution, non-NULL if pending.
147    */
148   struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
149
150   /**
151    * stdout pipe handle for the gnunet-nat-server process
152    */
153   struct GNUNET_DISK_PipeHandle *server_stdout;
154
155   /**
156    * stdout file handle (for reading) for the gnunet-nat-server process
157    */
158   const struct GNUNET_DISK_FileHandle *server_stdout_handle;
159
160   /**
161    * Linked list of currently valid addresses (head).
162    */
163   struct LocalAddressList *lal_head;
164
165   /**
166    * Linked list of currently valid addresses (tail).
167    */
168   struct LocalAddressList *lal_tail;
169
170   /**
171    * How long do we wait for restarting a crashed gnunet-nat-server?
172    */
173   struct GNUNET_TIME_Relative server_retry_delay;
174
175   /**
176    * ID of select gnunet-nat-server stdout read task
177    */
178   GNUNET_SCHEDULER_TaskIdentifier server_read_task;
179
180   /**
181    * ID of interface IP-scan task
182    */
183   GNUNET_SCHEDULER_TaskIdentifier ifc_task;
184
185   /**
186    * The process id of the server process (if behind NAT)
187    */
188   struct GNUNET_OS_Process *server_proc;
189
190   /**
191    * LAN address as passed by the caller (array).
192    */
193   struct sockaddr **local_addrs;
194
195   /**
196    * Length of the 'local_addrs'.
197    */
198   socklen_t *local_addrlens;
199
200   /**
201    * Number of entries in 'local_addrs' array.
202    */
203   unsigned int num_local_addrs;
204
205   /**
206    * The our external address (according to config, UPnP may disagree...)
207    */
208   char *external_address;
209
210   /**
211    * Presumably our internal address (according to config)
212    */
213   char *internal_address;
214
215   /**
216    * Is this transport configured to be behind a NAT?
217    */
218   int behind_nat;
219
220   /**
221    * Has the NAT been punched? (according to config)
222    */
223   int nat_punched;
224
225   /**
226    * Is this transport configured to allow connections to NAT'd peers?
227    */
228   int enable_nat_client;
229
230   /**
231    * Should we run the gnunet-nat-server?
232    */
233   int enable_nat_server;
234
235   /**
236    * Are we allowed to try UPnP/PMP for NAT traversal?
237    */
238   int enable_upnp;
239
240   /**
241    * Should we use local addresses (loopback)? (according to config)
242    */
243   int use_localaddresses;
244
245   /**
246    * Is using IPv6 disabled?
247    */
248   int disable_ipv6;
249
250   /**
251    * Is this TCP or UDP?
252    */ 
253   int is_tcp;
254
255   /**
256    * Port we advertise to the outside.
257    */
258   uint16_t adv_port;
259
260 };
261
262
263 /**
264  * Try to start the gnunet-nat-server (if it is not
265  * already running).
266  *
267  * @param h handle to NAT
268  */
269 static void
270 start_gnunet_nat_server (struct GNUNET_NAT_Handle *h);
271
272
273 /**
274  * Add the given address to the list of 'local' addresses, thereby
275  * making it a 'legal' address for this peer to have.  
276  * 
277  * @param plugin the plugin
278  * @param src where did the local address originate from?
279  * @param arg the address, some 'struct sockaddr'
280  * @param arg_size number of bytes in arg
281  */
282 static void
283 add_to_address_list_as_is (struct GNUNET_NAT_Handle *h,
284                            enum LocalAddressSource src,
285                            const struct sockaddr *arg,
286                            socklen_t arg_size)
287 {
288   struct LocalAddressList *lal;
289
290   lal = GNUNET_malloc (sizeof (struct LocalAddressList) + arg_size);
291   memcpy (&lal[1], arg, arg_size);
292   lal->addrlen = arg_size;
293   lal->source = src;
294   GNUNET_CONTAINER_DLL_insert (h->lal_head,
295                                h->lal_tail,
296                                lal);
297   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
298                    "nat",
299                    "Adding address `%s' from source %d\n",
300                    GNUNET_a2s (arg, arg_size),
301                    src);
302   h->address_callback (h->callback_cls,
303                        GNUNET_YES,
304                        arg,
305                        arg_size);
306 }
307
308
309 /**
310  * Add the given address to the list of 'local' addresses, thereby
311  * making it a 'legal' address for this peer to have.   Set the
312  * port number in the process to the advertised port and possibly
313  * also to zero (if we have the gnunet-nat-server).
314  * 
315  * @param plugin the plugin
316  * @param src where did the local address originate from?
317  * @param arg the address, some 'struct sockaddr'
318  * @param arg_size number of bytes in arg
319  */
320 static void
321 add_to_address_list (struct GNUNET_NAT_Handle *h,
322                      enum LocalAddressSource src,
323                      const struct sockaddr *arg,
324                      socklen_t arg_size)
325 {
326   struct sockaddr_in s4;
327   const struct sockaddr_in *in4;
328   struct sockaddr_in6 s6;
329   const struct sockaddr_in6 *in6;
330
331   if (arg_size == sizeof (struct sockaddr_in))
332     {
333       in4 = (const struct sockaddr_in *) arg;
334       s4 = *in4;
335       s4.sin_port = htons (h->adv_port);
336       add_to_address_list_as_is (h, 
337                                  src,
338                                  (const struct sockaddr*) &s4,
339                                  sizeof (struct sockaddr_in));
340       if (GNUNET_YES == h->enable_nat_server)
341         {
342           /* also add with PORT = 0 to indicate NAT server is enabled */
343           s4.sin_port = htons(0);
344           add_to_address_list_as_is (h, 
345                                      src,
346                                      (const struct sockaddr*) &s4,
347                                      sizeof (struct sockaddr_in));        
348         }
349     }
350   else if (arg_size == sizeof (struct sockaddr_in6))
351     {
352       if (GNUNET_YES != h->disable_ipv6)
353         {
354           in6 = (const struct sockaddr_in6 *) arg;
355           s6 = *in6;
356           s6.sin6_port = htons(h->adv_port);
357           add_to_address_list_as_is (h, 
358                                      src,
359                                      (const struct sockaddr*) &s6,
360                                      sizeof (struct sockaddr_in6));
361         }
362     }
363   else
364     {
365       GNUNET_assert (0);
366     }
367 }
368
369
370 /**
371  * Add the given IP address to the list of 'local' addresses, thereby
372  * making it a 'legal' address for this peer to have.  
373  * 
374  * @param plugin the plugin
375  * @param src where did the local address originate from?
376  * @param arg the address, some 'struct in_addr' or 'struct in6_addr'
377  * @param arg_size number of bytes in arg
378  */
379 static void
380 add_ip_to_address_list (struct GNUNET_NAT_Handle *h,
381                         enum LocalAddressSource src,
382                         const void *addr,
383                         socklen_t addrlen)
384 {
385   struct sockaddr_in s4;
386   const struct in_addr *in4;
387   struct sockaddr_in6 s6;
388   const struct in6_addr *in6;
389
390   if (addrlen == sizeof (struct in_addr))
391     {
392       in4 = (const struct in_addr *) addr;
393       memset (&s4, 0, sizeof (s4));
394       s4.sin_family = AF_INET;
395       s4.sin_port = 0;
396 #if HAVE_SOCKADDR_IN_SIN_LEN
397       s4.sin_len = (u_char) sizeof (struct sockaddr_in);
398 #endif
399       s4.sin_addr = *in4;
400       add_to_address_list (h, 
401                            src,
402                            (const struct sockaddr*) &s4,
403                            sizeof (struct sockaddr_in));
404       if (GNUNET_YES == h->enable_nat_server)
405         {
406           /* also add with PORT = 0 to indicate NAT server is enabled */
407           s4.sin_port = htons(0);
408           add_to_address_list (h, 
409                                src,
410                                (const struct sockaddr*) &s4,
411                                sizeof (struct sockaddr_in));
412
413         }
414     }
415   else if (addrlen == sizeof (struct in6_addr))
416     {
417       if (GNUNET_YES != h->disable_ipv6)
418         {
419           in6 = (const struct in6_addr *) addr;
420           memset (&s6, 0, sizeof (s6));
421           s6.sin6_family = AF_INET6;
422           s6.sin6_port = htons(h->adv_port);
423 #if HAVE_SOCKADDR_IN_SIN_LEN
424           s6.sin6_len = (u_char) sizeof (struct sockaddr_in6);
425 #endif
426           s6.sin6_addr = *in6;
427           add_to_address_list (h, 
428                                src,
429                                (const struct sockaddr*) &s6,
430                                sizeof (struct sockaddr_in6));
431         }
432     }
433   else
434     {
435       GNUNET_assert (0);
436     }
437 }
438
439
440 /**
441  * Our (external) hostname was resolved and the configuration says that
442  * the NAT was hole-punched.
443  *
444  * @param cls the 'struct Plugin'
445  * @param addr NULL on error, otherwise result of DNS lookup
446  * @param addrlen number of bytes in addr
447  */
448 static void
449 process_external_ip (void *cls,
450                      const struct sockaddr *addr,
451                      socklen_t addrlen)
452 {
453   struct GNUNET_NAT_Handle *h = cls;
454
455   if (addr == NULL)
456     {    
457       h->ext_dns = NULL;
458       /* FIXME: schedule task to resolve IP again in the
459          future, and if the result changes, update the
460          local address list accordingly */
461       return;
462     }
463   add_to_address_list (h, LAL_EXTERNAL_IP, addr, addrlen);
464 }
465
466
467 /**
468  * Function called by the resolver for each address obtained from DNS
469  * for our own hostname.  Add the addresses to the list of our IP
470  * addresses.
471  *
472  * @param cls closure
473  * @param addr one of the addresses of the host, NULL for the last address
474  * @param addrlen length of the address
475  */
476 static void
477 process_hostname_ip (void *cls,
478                       const struct sockaddr *addr, socklen_t addrlen)
479 {
480   struct GNUNET_NAT_Handle *h = cls;
481  
482   if (addr == NULL)
483     {
484       h->hostname_dns = NULL;
485       /* FIXME: schedule task to resolve IP again in the
486          future, and if the result changes, update the
487          address list accordingly */
488       return;
489     }
490   add_to_address_list (h, LAL_HOSTNAME_DNS, addr, addrlen);
491 }
492
493
494 /**
495  * Add the IP of our network interface to the list of
496  * our IP addresses.
497  *
498  * @param cls the 'struct GNUNET_NAT_Handle'
499  * @param name name of the interface
500  * @param isDefault do we think this may be our default interface
501  * @param addr address of the interface
502  * @param addrlen number of bytes in addr
503  * @return GNUNET_OK to continue iterating
504  */
505 static int
506 process_interfaces (void *cls,
507                     const char *name,
508                     int isDefault,
509                     const struct sockaddr *addr, socklen_t addrlen)
510 {
511   struct GNUNET_NAT_Handle *h = cls;
512   const struct sockaddr_in *s4;
513   const struct sockaddr_in6 *s6;
514   const void *ip;
515   char buf[INET6_ADDRSTRLEN];
516
517   switch (addr->sa_family)
518     {
519     case AF_INET:
520       s4 = (struct sockaddr_in *) addr;
521       ip = &s4->sin_addr;
522       if (GNUNET_YES == h->use_localaddresses)
523         add_ip_to_address_list (h, 
524                                 LAL_INTERFACE_ADDRESS,
525                                 &s4->sin_addr,
526                                 sizeof (struct in_addr));
527       break;
528     case AF_INET6:
529       s6 = (struct sockaddr_in6 *) addr;
530       if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
531         {
532           /* skip link local addresses */
533           return GNUNET_OK;
534         }
535       ip = &s6->sin6_addr;
536       if (GNUNET_YES == h->use_localaddresses)
537         add_ip_to_address_list (h, 
538                                 LAL_INTERFACE_ADDRESS,
539                                 &s6->sin6_addr,
540                                 sizeof (struct in6_addr));
541       break;
542     default:
543       GNUNET_break (0);
544       break;
545     }
546   if ( (h->internal_address == NULL) &&
547        (h->server_proc == NULL) &&
548        (h->server_read_task == GNUNET_SCHEDULER_NO_TASK) &&
549        (GNUNET_YES == isDefault) &&
550        ( (addr->sa_family == AF_INET) || (addr->sa_family == AF_INET6) ) )
551     {
552       /* no internal address configured, but we found a "default"
553          interface, try using that as our 'internal' address */
554       h->internal_address = GNUNET_strdup (inet_ntop (addr->sa_family,
555                                                       ip,
556                                                       buf,
557                                                       sizeof (buf)));
558       start_gnunet_nat_server (h);
559     }
560   return GNUNET_OK;
561 }
562
563
564 /**
565  * Return the actual path to a file found in the current
566  * PATH environment variable.
567  *
568  * @param binary the name of the file to find
569  * @return path to binary, NULL if not found
570  */
571 static char *
572 get_path_from_PATH (const char *binary)
573 {
574   char *path;
575   char *pos;
576   char *end;
577   char *buf;
578   const char *p;
579
580   p = getenv ("PATH");
581   if (p == NULL)
582     {
583       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
584                        "tcp",
585                        _("PATH environment variable is unset.\n"));
586       return NULL;
587     }
588   path = GNUNET_strdup (p);     /* because we write on it */
589   buf = GNUNET_malloc (strlen (path) + 20);
590   pos = path;
591
592   while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
593     {
594       *end = '\0';
595       sprintf (buf, "%s/%s", pos, binary);
596       if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
597         {
598           GNUNET_free (path);
599           return buf;
600         }
601       pos = end + 1;
602     }
603   sprintf (buf, "%s/%s", pos, binary);
604   if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
605     {
606       GNUNET_free (path);
607       return buf;
608     }
609   GNUNET_free (buf);
610   GNUNET_free (path);
611   return NULL;
612 }
613
614
615 /**
616  * Check whether the suid bit is set on a file.
617  * Attempts to find the file using the current
618  * PATH environment variable as a search path.
619  *
620  * @param binary the name of the file to check
621  * @return GNUNET_YES if the file is SUID, 
622  *         GNUNET_NO if not, 
623  *         GNUNET_SYSERR on error
624  */
625 static int
626 check_gnunet_nat_binary (const char *binary)
627 {
628   struct stat statbuf;
629   char *p;
630 #ifdef MINGW
631   SOCKET rawsock;
632   char *binaryexe;
633
634   GNUNET_asprintf (&binaryexe, "%s.exe", binary);
635   p = get_path_from_PATH (binaryexe);
636   free (binaryexe);
637 #else
638   p = get_path_from_PATH (binary);
639 #endif
640   if (p == NULL)
641     {
642       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
643                        "tcp",
644                        _("Could not find binary `%s' in PATH!\n"),
645                        binary);
646       return GNUNET_NO;
647     }
648   if (0 != STAT (p, &statbuf))
649     {
650       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 
651                   _("stat (%s) failed: %s\n"), 
652                   p,
653                   STRERROR (errno));
654       GNUNET_free (p);
655       return GNUNET_SYSERR;
656     }
657   GNUNET_free (p);
658 #ifndef MINGW
659   if ( (0 != (statbuf.st_mode & S_ISUID)) &&
660        (statbuf.st_uid == 0) )
661     return GNUNET_YES;
662   return GNUNET_NO;
663 #else
664   rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
665   if (INVALID_SOCKET == rawsock)
666     {
667       DWORD err = GetLastError ();
668       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, 
669                        "tcp",
670                        "socket (AF_INET, SOCK_RAW, IPPROTO_ICMP) failed! GLE = %d\n", err);
671       return GNUNET_NO; /* not running as administrator */
672     }
673   closesocket (rawsock);
674   return GNUNET_YES;
675 #endif
676 }
677
678
679 /**
680  * Task that restarts the gnunet-nat-server process after a crash
681  * after a certain delay.
682  *
683  * @param cls the 'struct GNUNET_NAT_Handle'
684  * @param tc scheduler context
685  */ 
686 static void
687 restart_nat_server (void *cls,
688                     const struct GNUNET_SCHEDULER_TaskContext *tc)
689 {
690   struct GNUNET_NAT_Handle *h = cls;
691
692   h->server_read_task = GNUNET_SCHEDULER_NO_TASK;
693   if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
694     return;  
695   start_gnunet_nat_server (h);
696 }
697
698
699 /**
700  * We have been notified that gnunet-nat-server has written something to stdout.
701  * Handle the output, then reschedule this function to be called again once
702  * more is available.
703  *
704  * @param cls the NAT handle
705  * @param tc the scheduling context
706  */
707 static void
708 nat_server_read (void *cls, 
709                  const struct GNUNET_SCHEDULER_TaskContext *tc)
710 {
711   struct GNUNET_NAT_Handle *h = cls;
712   char mybuf[40];
713   ssize_t bytes;
714   size_t i;
715   int port;
716   const char *port_start;
717   struct sockaddr_in sin_addr;
718
719   h->server_read_task = GNUNET_SCHEDULER_NO_TASK;
720   if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
721     return;
722   memset (mybuf, 0, sizeof(mybuf));
723   bytes = GNUNET_DISK_file_read(h->server_stdout_handle, 
724                                 mybuf,
725                                 sizeof(mybuf));
726   if (bytes < 1)
727     {
728 #if DEBUG_TCP_NAT
729       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
730                        "nat",
731                        "Finished reading from server stdout with code: %d\n", 
732                        bytes);
733 #endif
734       if (0 != GNUNET_OS_process_kill (h->server_proc, SIGTERM))
735         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
736       GNUNET_OS_process_wait (h->server_proc);
737       GNUNET_OS_process_close (h->server_proc);
738       h->server_proc = NULL;
739       GNUNET_DISK_pipe_close (h->server_stdout);
740       h->server_stdout = NULL;
741       h->server_stdout_handle = NULL;
742       /* now try to restart it */
743       h->server_retry_delay = GNUNET_TIME_relative_multiply (h->server_retry_delay, 2);
744       h->server_retry_delay = GNUNET_TIME_relative_max (GNUNET_TIME_UNIT_HOURS, 
745                                                         h->server_retry_delay);
746       h->server_read_task = GNUNET_SCHEDULER_add_delayed (h->server_retry_delay,
747                                                           &restart_nat_server,
748                                                           h);
749       return;
750     }
751
752   port_start = NULL;
753   for (i = 0; i < sizeof(mybuf); i++)
754     {
755       if (mybuf[i] == '\n')
756         {
757           mybuf[i] = '\0';
758           break;
759         }
760       if ( (mybuf[i] == ':') && (i + 1 < sizeof(mybuf)) )
761         {
762           mybuf[i] = '\0';
763           port_start = &mybuf[i + 1];
764         }
765     }
766
767   /* construct socket address of sender */
768   memset (&sin_addr, 0, sizeof (sin_addr));
769   sin_addr.sin_family = AF_INET;
770 #if HAVE_SOCKADDR_IN_SIN_LEN
771   sin_addr.sin_len = sizeof (sin_addr);
772 #endif
773   if ( (NULL == port_start) ||
774        (1 != sscanf (port_start, "%d", &port)) ||
775        (-1 == inet_pton(AF_INET, mybuf, &sin_addr.sin_addr)) )
776     {
777       /* should we restart gnunet-nat-server? */
778       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
779                        "nat",
780                        _("gnunet-nat-server generated malformed address `%s'\n"),
781                        mybuf);
782       h->server_read_task 
783         = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
784                                           h->server_stdout_handle,
785                                           &nat_server_read, 
786                                           h);
787       return;
788     }
789   sin_addr.sin_port = htons((uint16_t) port);
790 #if DEBUG_NAT
791   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
792                    "nat",
793                    "gnunet-nat-server read: %s:%d\n", 
794                    mybuf, port);
795 #endif
796   h->reversal_callback (h->callback_cls,
797                         (const struct sockaddr*) &sin_addr,
798                         sizeof (sin_addr));
799   h->server_read_task =
800     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
801                                     h->server_stdout_handle, 
802                                     &nat_server_read, 
803                                     h);
804 }
805
806
807 /**
808  * Try to start the gnunet-nat-server (if it is not
809  * already running).
810  *
811  * @param h handle to NAT
812  */
813 static void
814 start_gnunet_nat_server (struct GNUNET_NAT_Handle *h)
815 {
816   if ( (h->behind_nat == GNUNET_YES) &&
817        (h->enable_nat_server == GNUNET_YES) &&
818        (h->internal_address != NULL) &&
819        (NULL != (h->server_stdout = GNUNET_DISK_pipe (GNUNET_YES,
820                                                       GNUNET_NO,
821                                                       GNUNET_YES))) )
822     {
823 #if DEBUG_NAT
824       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
825                        "nat"
826                        "Starting %s at `%s'\n",
827                        "gnunet-nat-server", 
828                        h->internal_address);
829 #endif
830       /* Start the server process */
831       h->server_proc = GNUNET_OS_start_process (NULL,
832                                                 h->server_stdout,
833                                                 "gnunet-nat-server", 
834                                                 "gnunet-nat-server", 
835                                                 h->internal_address, 
836                                                 NULL);
837       if (h->server_proc == NULL)
838         {
839           GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
840                            "nat",
841                            _("Failed to start %s\n"),
842                            "gnunet-nat-server");
843           GNUNET_DISK_pipe_close (h->server_stdout);
844           h->server_stdout = NULL;
845         }
846       else
847         {
848           /* Close the write end of the read pipe */
849           GNUNET_DISK_pipe_close_end(h->server_stdout, 
850                                      GNUNET_DISK_PIPE_END_WRITE);
851           h->server_stdout_handle 
852             = GNUNET_DISK_pipe_handle (h->server_stdout, 
853                                        GNUNET_DISK_PIPE_END_READ);
854           h->server_read_task 
855             = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
856                                               h->server_stdout_handle,
857                                               &nat_server_read, 
858                                               h);
859         }
860     }  
861 }
862
863
864 /**
865  * Task to scan the local network interfaces for IP addresses.
866  *
867  * @param cls the NAT handle
868  * @param tc scheduler context
869  */
870 static void
871 list_interfaces (void *cls,
872                  const struct GNUNET_SCHEDULER_TaskContext *tc)
873 {
874   struct GNUNET_NAT_Handle *h = cls;
875
876   h->ifc_task = GNUNET_SCHEDULER_NO_TASK;
877   GNUNET_OS_network_interfaces_list (&process_interfaces, h); 
878 #if 0
879   h->ifc_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FIXME,
880                                               &list_interfaces, h);
881 #endif
882 }
883
884
885 /**
886  * Attempt to enable port redirection and detect public IP address contacting
887  * UPnP or NAT-PMP routers on the local network. Use addr to specify to which
888  * of the local host's addresses should the external port be mapped. The port
889  * is taken from the corresponding sockaddr_in[6] field.
890  *
891  * @param cfg configuration to use
892  * @param is_tcp GNUNET_YES for TCP, GNUNET_NO for UDP
893  * @param adv_port advertised port (port we are either bound to or that our OS
894  *                 locally performs redirection from to our bound port).
895  * @param num_addrs number of addresses in 'addrs'
896  * @param addr the local address packets should be redirected to
897  * @param addrlen actual lenght of the address
898  * @param address_callback function to call everytime the public IP address changes
899  * @param reversal_callback function to call if someone wants connection reversal from us
900  * @param callback_cls closure for callbacks
901  * @return NULL on error, otherwise handle that can be used to unregister 
902  */
903 struct GNUNET_NAT_Handle *
904 GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg,
905                      int is_tcp,
906                      uint16_t adv_port,
907                      unsigned int num_addrs,
908                      const struct sockaddr **addrs,
909                      const socklen_t *addrlens,
910                      GNUNET_NAT_AddressCallback address_callback, 
911                      GNUNET_NAT_ReversalCallback reversal_callback,
912                      void *callback_cls)
913 {
914   struct GNUNET_NAT_Handle *h;
915   struct in_addr in_addr;
916   unsigned int i;
917
918   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
919               "Registered with NAT service at port %u with %u IP bound local addresses\n",
920               (unsigned int) adv_port,
921               num_addrs);
922   h = GNUNET_malloc (sizeof (struct GNUNET_NAT_Handle));
923   h->server_retry_delay = GNUNET_TIME_UNIT_SECONDS;
924   h->cfg = cfg;
925   h->is_tcp = is_tcp;
926   h->address_callback = address_callback;
927   h->reversal_callback = reversal_callback;
928   h->callback_cls = callback_cls;
929   h->num_local_addrs = num_addrs;
930   h->adv_port = adv_port;
931   if (num_addrs != 0)
932     {
933       h->local_addrs = GNUNET_malloc (num_addrs * sizeof (struct sockaddr*));
934       h->local_addrlens = GNUNET_malloc (num_addrs * sizeof (socklen_t));
935       for (i=0;i<num_addrs;i++)
936         {
937           h->local_addrlens[i] = addrlens[i];
938           h->local_addrs[i] = GNUNET_malloc (addrlens[i]);
939           memcpy (h->local_addrs[i], addrs[i], addrlens[i]);
940         }
941     }
942
943   if (GNUNET_OK ==
944       GNUNET_CONFIGURATION_have_value (cfg,
945                                        "nat",
946                                        "INTERNAL_ADDRESS"))
947     {
948       (void) GNUNET_CONFIGURATION_get_value_string (cfg,
949                                                     "nat",
950                                                     "INTERNAL_ADDRESS",
951                                                     &h->internal_address);
952     }
953   if ( (h->internal_address != NULL) && 
954        (inet_pton(AF_INET, h->internal_address, &in_addr) != 1) )
955     {
956       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
957                        "nat",
958                        _("Malformed %s `%s' given in configuration!\n"), 
959                        "INTERNAL_ADDRESS",
960                        h->internal_address);      
961       GNUNET_free (h->internal_address);
962       h->internal_address = NULL;
963     }
964
965   if (GNUNET_OK ==
966       GNUNET_CONFIGURATION_have_value (cfg,
967                                        "nat",
968                                        "EXTERNAL_ADDRESS"))
969     {
970       (void) GNUNET_CONFIGURATION_get_value_string (cfg,
971                                                     "nat",
972                                                     "EXTERNAL_ADDRESS",
973                                                     &h->external_address);
974     }
975   if ( (h->external_address != NULL) && 
976        (inet_pton(AF_INET, h->external_address, &in_addr) != 1) ) 
977     {      
978       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
979                        "nat",
980                        _("Malformed %s `%s' given in configuration!\n"), 
981                        "EXTERNAL_ADDRESS",
982                        h->external_address);
983       GNUNET_free (h->external_address);
984       h->external_address = NULL;
985     }
986   h->behind_nat = GNUNET_CONFIGURATION_get_value_yesno (cfg,
987                                                         "nat",
988                                                         "BEHIND_NAT");
989   h->nat_punched = GNUNET_CONFIGURATION_get_value_yesno (cfg,
990                                                          "nat",
991                                                          "NAT_PUNCHED");
992   h->enable_nat_client = GNUNET_CONFIGURATION_get_value_yesno (cfg,
993                                                                "nat",
994                                                                "ENABLE_NAT_CLIENT");
995   h->enable_nat_server = GNUNET_CONFIGURATION_get_value_yesno (cfg,
996                                                                "nat",
997                                                                "ENABLE_NAT_SERVER");
998   h->enable_upnp = GNUNET_CONFIGURATION_get_value_yesno (cfg,
999                                                          "nat",
1000                                                          "ENABLE_UPNP");
1001   h->use_localaddresses = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1002                                                                 "nat",
1003                                                                 "USE_LOCALADDR");
1004   h->disable_ipv6 = GNUNET_CONFIGURATION_get_value_yesno(cfg,
1005                                                          "nat", 
1006                                                          "DISABLEV6");
1007   if (NULL == reversal_callback)
1008     h->enable_nat_server = GNUNET_NO;
1009
1010   /* Check if NAT was hole-punched */
1011   if ( (NULL != h->address_callback) &&
1012        (h->external_address != NULL) &&
1013        (h->nat_punched == GNUNET_YES) )
1014     {
1015       h->ext_dns = GNUNET_RESOLVER_ip_get (h->external_address,
1016                                            AF_INET,
1017                                            GNUNET_TIME_UNIT_MINUTES,
1018                                            &process_external_ip,
1019                                            h);
1020       h->enable_nat_server = GNUNET_NO;
1021       h->enable_upnp = GNUNET_NO;
1022     }
1023
1024   /* Test for SUID binaries */
1025   if ( (h->behind_nat == GNUNET_YES) &&
1026        (GNUNET_YES == h->enable_nat_server) &&
1027        (GNUNET_YES != check_gnunet_nat_binary("gnunet-nat-server")) )
1028     {
1029       h->enable_nat_server = GNUNET_NO;
1030       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1031                   _("Configuration requires `%s', but binary is not installed properly (SUID bit not set).  Option disabled.\n"),
1032                   "gnunet-nat-server");        
1033     }
1034   if ( (GNUNET_YES == h->enable_nat_client) &&
1035        (GNUNET_YES != check_gnunet_nat_binary("gnunet-nat-client")) )
1036     {
1037       h->enable_nat_client = GNUNET_NO;
1038       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1039                   _("Configuration requires `%s', but binary is not installed properly (SUID bit not set).  Option disabled.\n"),
1040                   "gnunet-nat-client"); 
1041     }
1042
1043   start_gnunet_nat_server (h);
1044
1045   /* FIXME: add support for UPnP, etc */
1046
1047   if (NULL != h->address_callback)
1048     {
1049       h->ifc_task = GNUNET_SCHEDULER_add_now (&list_interfaces, h);
1050       h->hostname_dns = GNUNET_RESOLVER_hostname_resolve (AF_UNSPEC,
1051                                                           HOSTNAME_RESOLVE_TIMEOUT,
1052                                                           &process_hostname_ip,
1053                                                           h);
1054     }
1055   return h;
1056 }
1057
1058
1059 /**
1060  * Stop port redirection and public IP address detection for the given handle.
1061  * This frees the handle, after having sent the needed commands to close open ports.
1062  *
1063  * @param h the handle to stop
1064  */
1065 void
1066 GNUNET_NAT_unregister (struct GNUNET_NAT_Handle *h)
1067 {
1068   unsigned int i;
1069   struct LocalAddressList *lal;
1070
1071   if (h->ext_dns != NULL)
1072     {
1073       GNUNET_RESOLVER_request_cancel (h->ext_dns);
1074       h->ext_dns = NULL;
1075     }
1076   if (NULL != h->hostname_dns)
1077     {
1078       GNUNET_RESOLVER_request_cancel (h->hostname_dns);
1079       h->hostname_dns = NULL;
1080     }
1081   if (GNUNET_SCHEDULER_NO_TASK != h->server_read_task)
1082     {
1083       GNUNET_SCHEDULER_cancel (h->server_read_task);
1084       h->server_read_task = GNUNET_SCHEDULER_NO_TASK;
1085     }
1086   if (GNUNET_SCHEDULER_NO_TASK != h->ifc_task)
1087     {
1088       GNUNET_SCHEDULER_cancel (h->ifc_task);
1089       h->ifc_task = GNUNET_SCHEDULER_NO_TASK;
1090     }
1091   if (NULL != h->server_proc)
1092     {
1093       if (0 != GNUNET_OS_process_kill (h->server_proc, SIGTERM))
1094         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
1095       GNUNET_OS_process_wait (h->server_proc);
1096       GNUNET_OS_process_close (h->server_proc);
1097       h->server_proc = NULL;
1098       GNUNET_DISK_pipe_close (h->server_stdout);
1099       h->server_stdout = NULL;
1100       h->server_stdout_handle = NULL;
1101     }
1102   if (NULL != h->server_stdout)
1103     {
1104       GNUNET_DISK_pipe_close (h->server_stdout);
1105       h->server_stdout = NULL;
1106       h->server_stdout_handle = NULL;
1107     }
1108   while (NULL != (lal = h->lal_head))
1109     {
1110       GNUNET_CONTAINER_DLL_remove (h->lal_head,
1111                                    h->lal_tail,
1112                                    lal);
1113       h->address_callback (h->callback_cls,
1114                            GNUNET_NO,
1115                            (const struct sockaddr*) &lal[1],
1116                            lal->addrlen);
1117       GNUNET_free (lal);
1118     }
1119   for (i=0;i<h->num_local_addrs;i++)   
1120     GNUNET_free (h->local_addrs[i]);
1121   GNUNET_free_non_null (h->local_addrs);
1122   GNUNET_free_non_null (h->local_addrlens);
1123   GNUNET_free_non_null (h->external_address);
1124   GNUNET_free_non_null (h->internal_address);  
1125   GNUNET_free (h);
1126 }
1127
1128
1129 /**
1130  * We learned about a peer (possibly behind NAT) so run the
1131  * gnunet-nat-client to send dummy ICMP responses to cause
1132  * that peer to connect to us (connection reversal).
1133  *
1134  * @param h NAT handle for us (largely used for configuration)
1135  * @param sa the address of the peer (IPv4-only)
1136  */
1137 void
1138 GNUNET_NAT_run_client (struct GNUNET_NAT_Handle *h,
1139                        const struct sockaddr_in *sa)
1140 {
1141   char inet4[INET_ADDRSTRLEN];
1142   char port_as_string[6];
1143   struct GNUNET_OS_Process *proc;
1144
1145   if (GNUNET_YES != h->enable_nat_client) 
1146     return; /* not permitted / possible */
1147
1148   if (h->internal_address == NULL)
1149     {
1150       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1151                        "nat",
1152                        _("Internal IP address not known, cannot use ICMP NAT traversal method\n"));
1153       return;
1154     }
1155   GNUNET_assert (sa->sin_family == AF_INET);
1156   if (NULL == inet_ntop (AF_INET,
1157                          &sa->sin_addr,
1158                          inet4, INET_ADDRSTRLEN))
1159     {
1160       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
1161       return;
1162     }
1163   GNUNET_snprintf(port_as_string, 
1164                   sizeof (port_as_string),
1165                   "%d", 
1166                   h->adv_port);
1167 #if DEBUG_TCP_NAT
1168   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1169                    "nat",
1170                    _("Running gnunet-nat-client %s %s %u\n"), 
1171                    h->internal_address,
1172                    inet4,
1173                    (unsigned int) h->adv_port);
1174 #endif
1175   proc = GNUNET_OS_start_process (NULL, 
1176                                   NULL, 
1177                                   "gnunet-nat-client",
1178                                   "gnunet-nat-client",
1179                                   h->internal_address, 
1180                                   inet4,
1181                                   port_as_string, 
1182                                   NULL);
1183   if (NULL == proc)
1184     return;
1185   /* we know that the gnunet-nat-client will terminate virtually
1186      instantly */
1187   GNUNET_OS_process_wait (proc);
1188   GNUNET_OS_process_close (proc);
1189 }
1190
1191
1192 /**
1193  * Test if the given address is (currently) a plausible IP address for this peer.
1194  *
1195  * @param h the handle returned by register
1196  * @param addr IP address to test (IPv4 or IPv6)
1197  * @param addrlen number of bytes in addr
1198  * @return GNUNET_YES if the address is plausible,
1199  *         GNUNET_NO if the address is not plausible,
1200  *         GNUNET_SYSERR if the address is malformed
1201  */
1202 int
1203 GNUNET_NAT_test_address (struct GNUNET_NAT_Handle *h,
1204                          const void *addr,
1205                          socklen_t addrlen)
1206 {
1207   struct LocalAddressList *pos;
1208   const struct sockaddr_in *in4;
1209   const struct sockaddr_in6 *in6;
1210   
1211   if ( (addrlen != sizeof (struct in_addr)) &&
1212        (addrlen != sizeof (struct in6_addr)) )
1213     {
1214       GNUNET_break (0);
1215       return GNUNET_SYSERR;
1216     }
1217   pos = h->lal_head;
1218   while (NULL != pos)
1219     {
1220       if (pos->addrlen == sizeof (struct sockaddr_in))
1221         {
1222           in4 = (struct sockaddr_in* ) &pos[1];
1223           if ( (addrlen == sizeof (struct in_addr)) &&
1224                (0 == memcmp (&in4->sin_addr, addr, sizeof (struct in_addr))) )
1225             return GNUNET_YES;
1226         }
1227       else if (pos->addrlen == sizeof (struct sockaddr_in6))
1228         {
1229           in6 = (struct sockaddr_in6* ) &pos[1];
1230           if ( (addrlen == sizeof (struct in6_addr)) &&
1231                (0 == memcmp (&in6->sin6_addr, addr, sizeof (struct in6_addr))) )
1232             return GNUNET_YES;
1233         }
1234       else
1235         {
1236           GNUNET_assert (0);      
1237         }
1238       pos = pos->next;
1239     }
1240   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1241               "Asked to validate one of my addresses and validation failed!\n");
1242   return GNUNET_NO;
1243 }
1244
1245
1246 /* end of nat.c */