remove send on connect
[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 #if DEBUG_NAT
427   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
428                    "nat",
429                    "Adding address `%s' from source %d\n",
430                    GNUNET_a2s (arg, arg_size),
431                    src);
432 #endif
433   if (NULL != h->address_callback)
434     h->address_callback (h->callback_cls,
435                          GNUNET_YES,
436                          arg,
437                          arg_size);
438 }
439
440
441 /**
442  * Add the given address to the list of 'local' addresses, thereby
443  * making it a 'legal' address for this peer to have.   Set the
444  * port number in the process to the advertised port and possibly
445  * also to zero (if we have the gnunet-helper-nat-server).
446  * 
447  * @param plugin the plugin
448  * @param src where did the local address originate from?
449  * @param arg the address, some 'struct sockaddr'
450  * @param arg_size number of bytes in arg
451  */
452 static void
453 add_to_address_list (struct GNUNET_NAT_Handle *h,
454                      enum LocalAddressSource src,
455                      const struct sockaddr *arg,
456                      socklen_t arg_size)
457 {
458   struct sockaddr_in s4;
459   const struct sockaddr_in *in4;
460   struct sockaddr_in6 s6;
461   const struct sockaddr_in6 *in6;
462
463   if (arg_size == sizeof (struct sockaddr_in))
464     {
465       in4 = (const struct sockaddr_in *) arg;
466       s4 = *in4;
467       s4.sin_port = htons (h->adv_port);
468       add_to_address_list_as_is (h, 
469                                  src,
470                                  (const struct sockaddr*) &s4,
471                                  sizeof (struct sockaddr_in));
472       if (GNUNET_YES == h->enable_nat_server)
473         {
474           /* also add with PORT = 0 to indicate NAT server is enabled */
475           s4.sin_port = htons(0);
476           add_to_address_list_as_is (h, 
477                                      src,
478                                      (const struct sockaddr*) &s4,
479                                      sizeof (struct sockaddr_in));        
480         }
481     }
482   else if (arg_size == sizeof (struct sockaddr_in6))
483     {
484       if (GNUNET_YES != h->disable_ipv6)
485         {
486           in6 = (const struct sockaddr_in6 *) arg;
487           s6 = *in6;
488           s6.sin6_port = htons(h->adv_port);
489           add_to_address_list_as_is (h, 
490                                      src,
491                                      (const struct sockaddr*) &s6,
492                                      sizeof (struct sockaddr_in6));
493         }
494     }
495   else
496     {
497       GNUNET_assert (0);
498     }
499 }
500
501
502 /**
503  * Add the given IP address to the list of 'local' addresses, thereby
504  * making it a 'legal' address for this peer to have.  
505  * 
506  * @param plugin the plugin
507  * @param src where did the local address originate from?
508  * @param arg the address, some 'struct in_addr' or 'struct in6_addr'
509  * @param arg_size number of bytes in arg
510  */
511 static void
512 add_ip_to_address_list (struct GNUNET_NAT_Handle *h,
513                         enum LocalAddressSource src,
514                         const void *addr,
515                         socklen_t addrlen)
516 {
517   struct sockaddr_in s4;
518   const struct in_addr *in4;
519   struct sockaddr_in6 s6;
520   const struct in6_addr *in6;
521
522   if (addrlen == sizeof (struct in_addr))
523     {
524       in4 = (const struct in_addr *) addr;
525       memset (&s4, 0, sizeof (s4));
526       s4.sin_family = AF_INET;
527       s4.sin_port = 0;
528 #if HAVE_SOCKADDR_IN_SIN_LEN
529       s4.sin_len = (u_char) sizeof (struct sockaddr_in);
530 #endif
531       s4.sin_addr = *in4;
532       add_to_address_list (h, 
533                            src,
534                            (const struct sockaddr*) &s4,
535                            sizeof (struct sockaddr_in));
536       if (GNUNET_YES == h->enable_nat_server)
537         {
538           /* also add with PORT = 0 to indicate NAT server is enabled */
539           s4.sin_port = htons(0);
540           add_to_address_list (h, 
541                                src,
542                                (const struct sockaddr*) &s4,
543                                sizeof (struct sockaddr_in));
544
545         }
546     }
547   else if (addrlen == sizeof (struct in6_addr))
548     {
549       if (GNUNET_YES != h->disable_ipv6)
550         {
551           in6 = (const struct in6_addr *) addr;
552           memset (&s6, 0, sizeof (s6));
553           s6.sin6_family = AF_INET6;
554           s6.sin6_port = htons(h->adv_port);
555 #if HAVE_SOCKADDR_IN_SIN_LEN
556           s6.sin6_len = (u_char) sizeof (struct sockaddr_in6);
557 #endif
558           s6.sin6_addr = *in6;
559           add_to_address_list (h, 
560                                src,
561                                (const struct sockaddr*) &s6,
562                                sizeof (struct sockaddr_in6));
563         }
564     }
565   else
566     {
567       GNUNET_assert (0);
568     }
569 }
570
571
572 /**
573  * Task to do DNS lookup on our external hostname to
574  * get DynDNS-IP addresses.
575  *
576  * @param cls the NAT handle
577  * @param tc scheduler context
578  */
579 static void
580 resolve_dns (void *cls,
581              const struct GNUNET_SCHEDULER_TaskContext *tc);
582
583
584 /**
585  * Our (external) hostname was resolved and the configuration says that
586  * the NAT was hole-punched.
587  *
588  * @param cls the 'struct Plugin'
589  * @param addr NULL on error, otherwise result of DNS lookup
590  * @param addrlen number of bytes in addr
591  */
592 static void
593 process_external_ip (void *cls,
594                      const struct sockaddr *addr,
595                      socklen_t addrlen)
596 {
597   struct GNUNET_NAT_Handle *h = cls;
598   struct in_addr dummy;
599
600   if (addr == NULL)
601     {    
602       h->ext_dns = NULL;
603       if (1 == inet_pton (AF_INET,
604                           h->external_address,
605                           &dummy))
606         return; /* repated lookup pointless: was numeric! */
607       h->dns_task = GNUNET_SCHEDULER_add_delayed (h->dyndns_frequency,
608                                                   &resolve_dns, h);
609       return;
610     }
611   add_to_address_list (h, LAL_EXTERNAL_IP, addr, addrlen);
612 }
613
614
615 /**
616  * Task to do a lookup on our hostname for IP addresses.
617  *
618  * @param cls the NAT handle
619  * @param tc scheduler context
620  */
621 static void
622 resolve_hostname (void *cls,
623                   const struct GNUNET_SCHEDULER_TaskContext *tc);
624
625
626 /**
627  * Function called by the resolver for each address obtained from DNS
628  * for our own hostname.  Add the addresses to the list of our IP
629  * addresses.
630  *
631  * @param cls closure
632  * @param addr one of the addresses of the host, NULL for the last address
633  * @param addrlen length of the address
634  */
635 static void
636 process_hostname_ip (void *cls,
637                       const struct sockaddr *addr, socklen_t addrlen)
638 {
639   struct GNUNET_NAT_Handle *h = cls;
640  
641   if (addr == NULL)
642     {
643       h->hostname_dns = NULL;
644       h->hostname_task = GNUNET_SCHEDULER_add_delayed (h->hostname_dns_frequency,
645                                                        &resolve_hostname, h);
646       return;
647     }
648   add_to_address_list (h, LAL_HOSTNAME_DNS, addr, addrlen);
649 }
650
651
652 /**
653  * Add the IP of our network interface to the list of
654  * our IP addresses.
655  *
656  * @param cls the 'struct GNUNET_NAT_Handle'
657  * @param name name of the interface
658  * @param isDefault do we think this may be our default interface
659  * @param addr address of the interface
660  * @param addrlen number of bytes in addr
661  * @return GNUNET_OK to continue iterating
662  */
663 static int
664 process_interfaces (void *cls,
665                     const char *name,
666                     int isDefault,
667                     const struct sockaddr *addr, socklen_t addrlen)
668 {
669   struct GNUNET_NAT_Handle *h = cls;
670   const struct sockaddr_in *s4;
671   const struct sockaddr_in6 *s6;
672   const void *ip;
673   char buf[INET6_ADDRSTRLEN];
674
675   switch (addr->sa_family)
676     {
677     case AF_INET:
678       s4 = (struct sockaddr_in *) addr;
679       ip = &s4->sin_addr;
680       if (GNUNET_YES == h->use_localaddresses)
681         add_ip_to_address_list (h, 
682                                 LAL_INTERFACE_ADDRESS,
683                                 &s4->sin_addr,
684                                 sizeof (struct in_addr));
685       break;
686     case AF_INET6:
687       s6 = (struct sockaddr_in6 *) addr;
688       if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
689         {
690           /* skip link local addresses */
691           return GNUNET_OK;
692         }
693       ip = &s6->sin6_addr;
694       if (GNUNET_YES == h->use_localaddresses)
695         add_ip_to_address_list (h, 
696                                 LAL_INTERFACE_ADDRESS,
697                                 &s6->sin6_addr,
698                                 sizeof (struct in6_addr));
699       break;
700     default:
701       GNUNET_break (0);
702       return GNUNET_OK;
703     }
704   if ( (h->internal_address == NULL) &&
705        (h->server_proc == NULL) &&
706        (h->server_read_task == GNUNET_SCHEDULER_NO_TASK) &&
707        (GNUNET_YES == isDefault) &&
708        ( (addr->sa_family == AF_INET) || (addr->sa_family == AF_INET6) ) )
709     {
710       /* no internal address configured, but we found a "default"
711          interface, try using that as our 'internal' address */
712       h->internal_address = GNUNET_strdup (inet_ntop (addr->sa_family,
713                                                       ip,
714                                                       buf,
715                                                       sizeof (buf)));
716       start_gnunet_nat_server (h);
717     }
718   return GNUNET_OK;
719 }
720
721
722 /**
723  * Task that restarts the gnunet-helper-nat-server process after a crash
724  * after a certain delay.
725  *
726  * @param cls the 'struct GNUNET_NAT_Handle'
727  * @param tc scheduler context
728  */ 
729 static void
730 restart_nat_server (void *cls,
731                     const struct GNUNET_SCHEDULER_TaskContext *tc)
732 {
733   struct GNUNET_NAT_Handle *h = cls;
734
735   h->server_read_task = GNUNET_SCHEDULER_NO_TASK;
736   if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
737     return;  
738   start_gnunet_nat_server (h);
739 }
740
741
742 /**
743  * We have been notified that gnunet-helper-nat-server has written something to stdout.
744  * Handle the output, then reschedule this function to be called again once
745  * more is available.
746  *
747  * @param cls the NAT handle
748  * @param tc the scheduling context
749  */
750 static void
751 nat_server_read (void *cls, 
752                  const struct GNUNET_SCHEDULER_TaskContext *tc)
753 {
754   struct GNUNET_NAT_Handle *h = cls;
755   char mybuf[40];
756   ssize_t bytes;
757   size_t i;
758   int port;
759   const char *port_start;
760   struct sockaddr_in sin_addr;
761
762   h->server_read_task = GNUNET_SCHEDULER_NO_TASK;
763   if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
764     return;
765   memset (mybuf, 0, sizeof(mybuf));
766   bytes = GNUNET_DISK_file_read(h->server_stdout_handle, 
767                                 mybuf,
768                                 sizeof(mybuf));
769   if (bytes < 1)
770     {
771 #if DEBUG_NAT
772       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
773                        "nat",
774                        "Finished reading from server stdout with code: %d\n", 
775                        bytes);
776 #endif
777       if (0 != GNUNET_OS_process_kill (h->server_proc, SIGTERM))
778         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
779       GNUNET_OS_process_wait (h->server_proc);
780       GNUNET_OS_process_close (h->server_proc);
781       h->server_proc = NULL;
782       GNUNET_DISK_pipe_close (h->server_stdout);
783       h->server_stdout = NULL;
784       h->server_stdout_handle = NULL;
785       /* now try to restart it */
786       h->server_retry_delay = GNUNET_TIME_relative_multiply (h->server_retry_delay, 2);
787       h->server_retry_delay = GNUNET_TIME_relative_max (GNUNET_TIME_UNIT_HOURS, 
788                                                         h->server_retry_delay);
789       h->server_read_task = GNUNET_SCHEDULER_add_delayed (h->server_retry_delay,
790                                                           &restart_nat_server,
791                                                           h);
792       return;
793     }
794
795   port_start = NULL;
796   for (i = 0; i < sizeof(mybuf); i++)
797     {
798       if (mybuf[i] == '\n')
799         {
800           mybuf[i] = '\0';
801           break;
802         }
803       if ( (mybuf[i] == ':') && (i + 1 < sizeof(mybuf)) )
804         {
805           mybuf[i] = '\0';
806           port_start = &mybuf[i + 1];
807         }
808     }
809
810   /* construct socket address of sender */
811   memset (&sin_addr, 0, sizeof (sin_addr));
812   sin_addr.sin_family = AF_INET;
813 #if HAVE_SOCKADDR_IN_SIN_LEN
814   sin_addr.sin_len = sizeof (sin_addr);
815 #endif
816   if ( (NULL == port_start) ||
817        (1 != sscanf (port_start, "%d", &port)) ||
818        (-1 == inet_pton(AF_INET, mybuf, &sin_addr.sin_addr)) )
819     {
820       /* should we restart gnunet-helper-nat-server? */
821       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
822                        "nat",
823                        _("gnunet-helper-nat-server generated malformed address `%s'\n"),
824                        mybuf);
825       h->server_read_task 
826         = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
827                                           h->server_stdout_handle,
828                                           &nat_server_read, 
829                                           h);
830       return;
831     }
832   sin_addr.sin_port = htons((uint16_t) port);
833 #if DEBUG_NAT
834   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
835                    "nat",
836                    "gnunet-helper-nat-server read: %s:%d\n", 
837                    mybuf, port);
838 #endif
839   h->reversal_callback (h->callback_cls,
840                         (const struct sockaddr*) &sin_addr,
841                         sizeof (sin_addr));
842   h->server_read_task =
843     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
844                                     h->server_stdout_handle, 
845                                     &nat_server_read, 
846                                     h);
847 }
848
849
850 /**
851  * Try to start the gnunet-helper-nat-server (if it is not
852  * already running).
853  *
854  * @param h handle to NAT
855  */
856 static void
857 start_gnunet_nat_server (struct GNUNET_NAT_Handle *h)
858 {
859   if ( (h->behind_nat == GNUNET_YES) &&
860        (h->enable_nat_server == GNUNET_YES) &&
861        (h->internal_address != NULL) &&
862        (NULL != (h->server_stdout = GNUNET_DISK_pipe (GNUNET_YES,
863                                                       GNUNET_NO,
864                                                       GNUNET_YES))) )
865     {
866 #if DEBUG_NAT
867       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
868                        "nat"
869                        "Starting %s at `%s'\n",
870                        "gnunet-helper-nat-server", 
871                        h->internal_address);
872 #endif
873       /* Start the server process */
874       h->server_proc = GNUNET_OS_start_process (NULL,
875                                                 h->server_stdout,
876                                                 "gnunet-helper-nat-server", 
877                                                 "gnunet-helper-nat-server", 
878                                                 h->internal_address, 
879                                                 NULL);
880       if (h->server_proc == NULL)
881         {
882           GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
883                            "nat",
884                            _("Failed to start %s\n"),
885                            "gnunet-helper-nat-server");
886           GNUNET_DISK_pipe_close (h->server_stdout);
887           h->server_stdout = NULL;
888         }
889       else
890         {
891           /* Close the write end of the read pipe */
892           GNUNET_DISK_pipe_close_end(h->server_stdout, 
893                                      GNUNET_DISK_PIPE_END_WRITE);
894           h->server_stdout_handle 
895             = GNUNET_DISK_pipe_handle (h->server_stdout, 
896                                        GNUNET_DISK_PIPE_END_READ);
897           h->server_read_task 
898             = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
899                                               h->server_stdout_handle,
900                                               &nat_server_read, 
901                                               h);
902         }
903     }  
904 }
905
906
907 /**
908  * Task to scan the local network interfaces for IP addresses.
909  *
910  * @param cls the NAT handle
911  * @param tc scheduler context
912  */
913 static void
914 list_interfaces (void *cls,
915                  const struct GNUNET_SCHEDULER_TaskContext *tc)
916 {
917   struct GNUNET_NAT_Handle *h = cls;
918
919   h->ifc_task = GNUNET_SCHEDULER_NO_TASK;
920   remove_from_address_list_by_source (h, LAL_INTERFACE_ADDRESS);
921   GNUNET_OS_network_interfaces_list (&process_interfaces, h); 
922   h->ifc_task = GNUNET_SCHEDULER_add_delayed (h->ifc_scan_frequency,
923                                               &list_interfaces, h);
924 }
925
926
927 /**
928  * Task to do a lookup on our hostname for IP addresses.
929  *
930  * @param cls the NAT handle
931  * @param tc scheduler context
932  */
933 static void
934 resolve_hostname (void *cls,
935                   const struct GNUNET_SCHEDULER_TaskContext *tc)
936 {
937   struct GNUNET_NAT_Handle *h = cls;
938  
939   h->hostname_task = GNUNET_SCHEDULER_NO_TASK;
940   remove_from_address_list_by_source (h, LAL_HOSTNAME_DNS);
941   h->hostname_dns = GNUNET_RESOLVER_hostname_resolve (AF_UNSPEC,
942                                                       HOSTNAME_RESOLVE_TIMEOUT,
943                                                       &process_hostname_ip,
944                                                       h);
945 }
946
947
948 /**
949  * Task to do DNS lookup on our external hostname to
950  * get DynDNS-IP addresses.
951  *
952  * @param cls the NAT handle
953  * @param tc scheduler context
954  */
955 static void
956 resolve_dns (void *cls,
957              const struct GNUNET_SCHEDULER_TaskContext *tc)
958 {
959   struct GNUNET_NAT_Handle *h = cls;
960  
961   h->dns_task = GNUNET_SCHEDULER_NO_TASK;
962   remove_from_address_list_by_source (h, LAL_EXTERNAL_IP);
963   h->ext_dns = GNUNET_RESOLVER_ip_get (h->external_address,
964                                        AF_INET,
965                                        GNUNET_TIME_UNIT_MINUTES,
966                                        &process_external_ip,
967                                        h);
968 }
969
970
971 /**
972  * Add or remove UPnP-mapped addresses.
973  *
974  * @param cls the GNUNET_NAT_Handle
975  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
976  *     the previous (now invalid) one
977  * @param addr either the previous or the new public IP address
978  * @param addrlen actual lenght of the address
979  */
980 static void 
981 upnp_add (void *cls, 
982           int add_remove,
983           const struct sockaddr *addr,
984           socklen_t addrlen)
985 {
986   struct GNUNET_NAT_Handle *h = cls;
987   struct LocalAddressList *pos;
988   struct LocalAddressList *next;
989
990   if (GNUNET_YES == add_remove)
991     {
992       add_to_address_list (h, 
993                            LAL_UPNP,
994                            addr, addrlen);
995       return;
996     }
997   /* remove address */
998   next = h->lal_head;
999   while (NULL != (pos = next))
1000     {
1001       next = pos->next;
1002       if ( (pos->source != LAL_UPNP) ||
1003            (pos->addrlen != addrlen) ||
1004            (0 != memcmp (&pos[1],
1005                          addr,
1006                          addrlen)) )
1007         continue;
1008       GNUNET_CONTAINER_DLL_remove (h->lal_head,
1009                                    h->lal_tail,
1010                                    pos);
1011       if (NULL != h->address_callback)
1012         h->address_callback (h->callback_cls,
1013                              GNUNET_NO,
1014                              (const struct sockaddr* ) &pos[1],
1015                              pos->addrlen);
1016       GNUNET_free (pos);
1017       return; /* only remove once */
1018     } 
1019   /* asked to remove address that does not exist */
1020   GNUNET_break (0);
1021 }
1022
1023
1024 /**
1025  * Try to add a port mapping using UPnP.
1026  *
1027  * @param h overall NAT handle
1028  * @param port port to map with UPnP
1029  */
1030 static void
1031 add_minis (struct GNUNET_NAT_Handle *h,
1032            uint16_t port)
1033 {
1034   struct MiniList *ml;
1035
1036   ml = h->mini_head;
1037   while (NULL != ml)
1038     {
1039       if (port == ml->port)
1040         return; /* already got this port */
1041       ml = ml->next;
1042     }
1043   ml = GNUNET_malloc (sizeof (struct MiniList));
1044   ml->port = port;
1045   ml->mini = GNUNET_NAT_mini_map_start (port,
1046                                         h->is_tcp,
1047                                         &upnp_add, h);
1048   GNUNET_CONTAINER_DLL_insert (h->mini_head,
1049                                h->mini_tail,
1050                                ml);                                     
1051 }
1052
1053
1054 /**
1055  * Task to add addresses from original bind to set of valid addrs.
1056  *
1057  * @param cls the NAT handle
1058  * @param tc scheduler context
1059  */
1060 static void
1061 add_from_bind (void *cls,
1062                const struct GNUNET_SCHEDULER_TaskContext *tc)
1063 {
1064   static struct in6_addr any = IN6ADDR_ANY_INIT;
1065   struct GNUNET_NAT_Handle *h = cls;
1066   unsigned int i;
1067   struct sockaddr *sa;
1068   const struct sockaddr_in *v4;
1069
1070   h->bind_task = GNUNET_SCHEDULER_NO_TASK;
1071   for (i=0;i<h->num_local_addrs;i++)
1072     {
1073       sa = h->local_addrs[i];
1074       switch (sa->sa_family)
1075         {
1076         case AF_INET:
1077           if (sizeof (struct sockaddr_in) != h->local_addrlens[i])
1078             {
1079               GNUNET_break (0);
1080               break;
1081             }
1082           v4 = (const struct sockaddr_in*) sa;
1083           if (0 != v4->sin_addr.s_addr)
1084             add_to_address_list (h, LAL_BINDTO_ADDRESS, sa, sizeof (struct sockaddr_in));
1085           if (h->enable_upnp)
1086             add_minis (h, ntohs (v4->sin_port));
1087           break;
1088         case AF_INET6:
1089           if (sizeof (struct sockaddr_in6) != h->local_addrlens[i])
1090             {
1091               GNUNET_break (0);
1092               break;
1093             }
1094           if (0 != memcmp (&((const struct sockaddr_in6*) sa)->sin6_addr,
1095                            &any,
1096                            sizeof (struct in6_addr)))
1097             add_to_address_list (h, LAL_BINDTO_ADDRESS, sa, sizeof (struct sockaddr_in6));
1098           break;
1099         default:
1100           break;
1101         }       
1102     }
1103 }
1104
1105
1106
1107 /**
1108  * Attempt to enable port redirection and detect public IP address contacting
1109  * UPnP or NAT-PMP routers on the local network. Use addr to specify to which
1110  * of the local host's addresses should the external port be mapped. The port
1111  * is taken from the corresponding sockaddr_in[6] field.
1112  *
1113  * @param cfg configuration to use
1114  * @param is_tcp GNUNET_YES for TCP, GNUNET_NO for UDP
1115  * @param adv_port advertised port (port we are either bound to or that our OS
1116  *                 locally performs redirection from to our bound port).
1117  * @param num_addrs number of addresses in 'addrs'
1118  * @param addr the local address packets should be redirected to
1119  * @param addrlen actual lenght of the address
1120  * @param address_callback function to call everytime the public IP address changes
1121  * @param reversal_callback function to call if someone wants connection reversal from us
1122  * @param callback_cls closure for callbacks
1123  * @return NULL on error, otherwise handle that can be used to unregister 
1124  */
1125 struct GNUNET_NAT_Handle *
1126 GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg,
1127                      int is_tcp,
1128                      uint16_t adv_port,
1129                      unsigned int num_addrs,
1130                      const struct sockaddr **addrs,
1131                      const socklen_t *addrlens,
1132                      GNUNET_NAT_AddressCallback address_callback, 
1133                      GNUNET_NAT_ReversalCallback reversal_callback,
1134                      void *callback_cls)
1135 {
1136   struct GNUNET_NAT_Handle *h;
1137   struct in_addr in_addr;
1138   unsigned int i;
1139
1140 #if DEBUG_NAT
1141   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1142                    "nat",
1143                    "Registered with NAT service at port %u with %u IP bound local addresses\n",
1144                    (unsigned int) adv_port,
1145                    num_addrs);
1146 #endif
1147   h = GNUNET_malloc (sizeof (struct GNUNET_NAT_Handle));
1148   h->server_retry_delay = GNUNET_TIME_UNIT_SECONDS;
1149   h->cfg = cfg;
1150   h->is_tcp = is_tcp;
1151   h->address_callback = address_callback;
1152   h->reversal_callback = reversal_callback;
1153   h->callback_cls = callback_cls;
1154   h->num_local_addrs = num_addrs;
1155   h->adv_port = adv_port;
1156   if (num_addrs != 0)
1157     {
1158       h->local_addrs = GNUNET_malloc (num_addrs * sizeof (struct sockaddr*));
1159       h->local_addrlens = GNUNET_malloc (num_addrs * sizeof (socklen_t));
1160       for (i=0;i<num_addrs;i++)
1161         {
1162           GNUNET_assert (addrlens[i] > 0);
1163           GNUNET_assert (addrs[i] != NULL);
1164           h->local_addrlens[i] = addrlens[i];
1165           h->local_addrs[i] = GNUNET_malloc (addrlens[i]);
1166           memcpy (h->local_addrs[i], addrs[i], addrlens[i]);
1167         }
1168     }
1169   h->bind_task = GNUNET_SCHEDULER_add_now (&add_from_bind, h);
1170   if (GNUNET_OK ==
1171       GNUNET_CONFIGURATION_have_value (cfg,
1172                                        "nat",
1173                                        "INTERNAL_ADDRESS"))
1174     {
1175       (void) GNUNET_CONFIGURATION_get_value_string (cfg,
1176                                                     "nat",
1177                                                     "INTERNAL_ADDRESS",
1178                                                     &h->internal_address);
1179     }
1180   if ( (h->internal_address != NULL) && 
1181        (inet_pton(AF_INET, h->internal_address, &in_addr) != 1) )
1182     {
1183       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1184                        "nat",
1185                        _("Malformed %s `%s' given in configuration!\n"), 
1186                        "INTERNAL_ADDRESS",
1187                        h->internal_address);      
1188       GNUNET_free (h->internal_address);
1189       h->internal_address = NULL;
1190     }
1191
1192   if (GNUNET_OK ==
1193       GNUNET_CONFIGURATION_have_value (cfg,
1194                                        "nat",
1195                                        "EXTERNAL_ADDRESS"))
1196     {
1197       (void) GNUNET_CONFIGURATION_get_value_string (cfg,
1198                                                     "nat",
1199                                                     "EXTERNAL_ADDRESS",
1200                                                     &h->external_address);
1201     }
1202   if ( (h->external_address != NULL) && 
1203        (inet_pton(AF_INET, h->external_address, &in_addr) != 1) ) 
1204     {      
1205       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1206                        "nat",
1207                        _("Malformed %s `%s' given in configuration!\n"), 
1208                        "EXTERNAL_ADDRESS",
1209                        h->external_address);
1210       GNUNET_free (h->external_address);
1211       h->external_address = NULL;
1212     }
1213   h->behind_nat = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1214                                                         "nat",
1215                                                         "BEHIND_NAT");
1216   h->nat_punched = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1217                                                          "nat",
1218                                                          "PUNCHED_NAT");
1219   h->enable_nat_client = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1220                                                                "nat",
1221                                                                "ENABLE_NAT_CLIENT");
1222   h->enable_nat_server = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1223                                                                "nat",
1224                                                                "ENABLE_NAT_SERVER");
1225   h->enable_upnp = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1226                                                          "nat",
1227                                                          "ENABLE_UPNP");
1228   h->use_localaddresses = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1229                                                                 "nat",
1230                                                                 "USE_LOCALADDR");
1231   h->use_hostname = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1232                                                           "nat",
1233                                                           "USE_HOSTNAME");
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 */