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