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