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