-ensure external symbols have proper prefix for conversation service
[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 looking up our own hostname in DNS.
75      */
76   LAL_HOSTNAME_DNS,
77
78     /**
79      * Address was obtained by scanning our hosts's network interfaces
80      * and taking their address (no DNS involved).
81      */
82   LAL_INTERFACE_ADDRESS,
83
84     /**
85      * Addresses we were explicitly bound to.
86      */
87   LAL_BINDTO_ADDRESS,
88
89     /**
90      * Addresses from UPnP or PMP
91      */
92   LAL_UPNP,
93
94     /**
95      * End of the list.
96      */
97   LAL_END
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    * Our external address (according to config, UPnP may disagree...),
298    * in dotted decimal notation, IPv4-only. Or NULL if not known.
299    */
300   char *external_address;
301
302   /**
303    * Presumably our internal address (according to config)
304    */
305   char *internal_address;
306
307   /**
308    * Is this transport configured to be behind a NAT?
309    */
310   int behind_nat;
311
312   /**
313    * Has the NAT been punched? (according to config)
314    */
315   int nat_punched;
316
317   /**
318    * Is this transport configured to allow connections to NAT'd peers?
319    */
320   int enable_nat_client;
321
322   /**
323    * Should we run the gnunet-helper-nat-server?
324    */
325   int enable_nat_server;
326
327   /**
328    * Are we allowed to try UPnP/PMP for NAT traversal?
329    */
330   int enable_upnp;
331
332   /**
333    * Should we use local addresses (loopback)? (according to config)
334    */
335   int use_localaddresses;
336
337   /**
338    * Should we return local addresses to clients
339    */
340   int return_localaddress;
341
342   /**
343    * Should we do a DNS lookup of our hostname to find out our own IP?
344    */
345   int use_hostname;
346
347   /**
348    * Is using IPv6 disabled?
349    */
350   int disable_ipv6;
351
352   /**
353    * Is this TCP or UDP?
354    */
355   int is_tcp;
356
357   /**
358    * Port we advertise to the outside.
359    */
360   uint16_t adv_port;
361
362 };
363
364
365 /**
366  * Try to start the gnunet-helper-nat-server (if it is not
367  * already running).
368  *
369  * @param h handle to NAT
370  */
371 static void
372 start_gnunet_nat_server (struct GNUNET_NAT_Handle *h);
373
374
375 /**
376  * Remove all addresses from the list of 'local' addresses
377  * that originated from the given source.
378  *
379  * @param h handle to NAT
380  * @param src source that identifies addresses to remove
381  */
382 static void
383 remove_from_address_list_by_source (struct GNUNET_NAT_Handle *h,
384                                     enum LocalAddressSource src)
385 {
386   struct LocalAddressList *pos;
387   struct LocalAddressList *next;
388
389   next = h->lal_head;
390   while (NULL != (pos = next))
391   {
392     next = pos->next;
393     if (pos->source != src)
394       continue;
395     GNUNET_CONTAINER_DLL_remove (h->lal_head, h->lal_tail, pos);
396     if (NULL != h->address_callback)
397       h->address_callback (h->callback_cls, GNUNET_NO,
398                            (const struct sockaddr *) &pos[1], pos->addrlen);
399     GNUNET_free (pos);
400   }
401 }
402
403
404 /**
405  * Add the given address to the list of 'local' addresses, thereby
406  * making it a 'legal' address for this peer to have.
407  *
408  * @param h handle to NAT
409  * @param src where did the local address originate from?
410  * @param arg the address, some 'struct sockaddr'
411  * @param arg_size number of bytes in arg
412  */
413 static void
414 add_to_address_list_as_is (struct GNUNET_NAT_Handle *h,
415                            enum LocalAddressSource src,
416                            const struct sockaddr *arg, socklen_t arg_size)
417 {
418   struct LocalAddressList *lal;
419
420   lal = GNUNET_malloc (sizeof (struct LocalAddressList) + arg_size);
421   memcpy (&lal[1], arg, arg_size);
422   lal->addrlen = arg_size;
423   lal->source = src;
424   GNUNET_CONTAINER_DLL_insert (h->lal_head, h->lal_tail, lal);
425   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding address `%s' from source %d\n",
426        GNUNET_a2s (arg, arg_size), src);
427   if (NULL != h->address_callback)
428     h->address_callback (h->callback_cls, GNUNET_YES, arg, arg_size);
429 }
430
431
432 /**
433  * Add the given address to the list of 'local' addresses, thereby
434  * making it a 'legal' address for this peer to have.   Set the
435  * port number in the process to the advertised port and possibly
436  * also to zero (if we have the gnunet-helper-nat-server).
437  *
438  * @param h handle to NAT
439  * @param src where did the local address originate from?
440  * @param arg the address, some 'struct sockaddr'
441  * @param arg_size number of bytes in arg
442  */
443 static void
444 add_to_address_list (struct GNUNET_NAT_Handle *h, enum LocalAddressSource src,
445                      const struct sockaddr *arg, socklen_t arg_size)
446 {
447   struct sockaddr_in s4;
448   const struct sockaddr_in *in4;
449   struct sockaddr_in6 s6;
450   const struct sockaddr_in6 *in6;
451
452   if (arg_size == sizeof (struct sockaddr_in))
453   {
454     in4 = (const struct sockaddr_in *) arg;
455     s4 = *in4;
456     s4.sin_port = htons (h->adv_port);
457     add_to_address_list_as_is (h, src, (const struct sockaddr *) &s4,
458                                sizeof (struct sockaddr_in));
459     if (GNUNET_YES == h->enable_nat_server)
460     {
461       /* also add with PORT = 0 to indicate NAT server is enabled */
462       s4.sin_port = htons (0);
463       add_to_address_list_as_is (h, src, (const struct sockaddr *) &s4,
464                                  sizeof (struct sockaddr_in));
465     }
466   }
467   else if (arg_size == sizeof (struct sockaddr_in6))
468   {
469     if (GNUNET_YES != h->disable_ipv6)
470     {
471       in6 = (const struct sockaddr_in6 *) arg;
472       s6 = *in6;
473       s6.sin6_port = htons (h->adv_port);
474       add_to_address_list_as_is (h, src, (const struct sockaddr *) &s6,
475                                  sizeof (struct sockaddr_in6));
476     }
477   }
478   else
479   {
480     GNUNET_assert (0);
481   }
482 }
483
484
485 /**
486  * Add the given IP address to the list of 'local' addresses, thereby
487  * making it a 'legal' address for this peer to have.
488  *
489  * @param h handle to NAT
490  * @param src where did the local address originate from?
491  * @param addr the address, some 'struct in_addr' or 'struct in6_addr'
492  * @param addrlen number of bytes in addr
493  */
494 static void
495 add_ip_to_address_list (struct GNUNET_NAT_Handle *h,
496                         enum LocalAddressSource src, const void *addr,
497                         socklen_t addrlen)
498 {
499   struct sockaddr_in s4;
500   const struct in_addr *in4;
501   struct sockaddr_in6 s6;
502   const struct in6_addr *in6;
503
504   if (addrlen == sizeof (struct in_addr))
505   {
506     in4 = (const struct in_addr *) addr;
507     memset (&s4, 0, sizeof (s4));
508     s4.sin_family = AF_INET;
509     s4.sin_port = 0;
510 #if HAVE_SOCKADDR_IN_SIN_LEN
511     s4.sin_len = (u_char) sizeof (struct sockaddr_in);
512 #endif
513     s4.sin_addr = *in4;
514     add_to_address_list (h, src, (const struct sockaddr *) &s4,
515                          sizeof (struct sockaddr_in));
516     if (GNUNET_YES == h->enable_nat_server)
517     {
518       /* also add with PORT = 0 to indicate NAT server is enabled */
519       s4.sin_port = htons (0);
520       add_to_address_list (h, src, (const struct sockaddr *) &s4,
521                            sizeof (struct sockaddr_in));
522
523     }
524   }
525   else if (addrlen == sizeof (struct in6_addr))
526   {
527     if (GNUNET_YES != h->disable_ipv6)
528     {
529       in6 = (const struct in6_addr *) addr;
530       memset (&s6, 0, sizeof (s6));
531       s6.sin6_family = AF_INET6;
532       s6.sin6_port = htons (h->adv_port);
533 #if HAVE_SOCKADDR_IN_SIN_LEN
534       s6.sin6_len = (u_char) sizeof (struct sockaddr_in6);
535 #endif
536       s6.sin6_addr = *in6;
537       add_to_address_list (h, src, (const struct sockaddr *) &s6,
538                            sizeof (struct sockaddr_in6));
539     }
540   }
541   else
542   {
543     GNUNET_assert (0);
544   }
545 }
546
547
548 /**
549  * Task to do DNS lookup on our external hostname to
550  * get DynDNS-IP addresses.
551  *
552  * @param cls the NAT handle
553  * @param tc scheduler context
554  */
555 static void
556 resolve_dns (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
557
558
559 /**
560  * Our (external) hostname was resolved and the configuration says that
561  * the NAT was hole-punched.
562  *
563  * @param cls the 'struct Plugin'
564  * @param addr NULL on error, otherwise result of DNS lookup
565  * @param addrlen number of bytes in addr
566  */
567 static void
568 process_external_ip (void *cls, const struct sockaddr *addr, socklen_t addrlen)
569 {
570   struct GNUNET_NAT_Handle *h = cls;
571   struct in_addr dummy;
572
573   if (addr == NULL)
574   {
575     h->ext_dns = NULL;
576     if (1 == inet_pton (AF_INET, h->external_address, &dummy))
577       return;                   /* repated lookup pointless: was numeric! */
578     h->dns_task =
579         GNUNET_SCHEDULER_add_delayed (h->dyndns_frequency, &resolve_dns, h);
580     return;
581   }
582   add_to_address_list (h, LAL_EXTERNAL_IP, addr, addrlen);
583 }
584
585
586 /**
587  * Task to do a lookup on our hostname for IP addresses.
588  *
589  * @param cls the NAT handle
590  * @param tc scheduler context
591  */
592 static void
593 resolve_hostname (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
594
595
596 /**
597  * Function called by the resolver for each address obtained from DNS
598  * for our own hostname.  Add the addresses to the list of our IP
599  * addresses.
600  *
601  * @param cls closure
602  * @param addr one of the addresses of the host, NULL for the last address
603  * @param addrlen length of the address
604  */
605 static void
606 process_hostname_ip (void *cls, const struct sockaddr *addr, socklen_t addrlen)
607 {
608   struct GNUNET_NAT_Handle *h = cls;
609
610   if (addr == NULL)
611   {
612     h->hostname_dns = NULL;
613     h->hostname_task =
614         GNUNET_SCHEDULER_add_delayed (h->hostname_dns_frequency,
615                                       &resolve_hostname, h);
616     return;
617   }
618   add_to_address_list (h, LAL_HOSTNAME_DNS, addr, addrlen);
619 }
620
621
622 /**
623  * Add the IP of our network interface to the list of
624  * our IP addresses.
625  *
626  * @param cls the 'struct GNUNET_NAT_Handle'
627  * @param name name of the interface
628  * @param isDefault do we think this may be our default interface
629  * @param addr address of the interface
630  * @param broadcast_addr the broadcast address (can be NULL for unknown or unassigned)
631  * @param netmask the network mask (can be NULL for unknown or unassigned))
632  * @param addrlen number of bytes in addr
633  * @return GNUNET_OK to continue iterating
634  */
635 static int
636 process_interfaces (void *cls, const char *name, int isDefault,
637                     const struct sockaddr *addr,
638                     const struct sockaddr *broadcast_addr,
639                     const struct sockaddr *netmask, socklen_t addrlen)
640 {
641   const static struct in6_addr any6 = IN6ADDR_ANY_INIT;
642   struct GNUNET_NAT_Handle *h = cls;
643   const struct sockaddr_in *s4;
644   const struct sockaddr_in6 *s6;
645   const void *ip;
646   char buf[INET6_ADDRSTRLEN];
647   unsigned int i;
648   int have_any;
649
650   switch (addr->sa_family)
651   {
652   case AF_INET:
653     /* check if we're bound to the "ANY" IP address */
654     have_any = GNUNET_NO;
655     for (i=0;i<h->num_local_addrs;i++)
656       {
657         if (h->local_addrs[i]->sa_family != AF_INET)
658           continue;
659 #ifndef INADDR_ANY
660 #define INADDR_ANY 0
661 #endif
662         if (INADDR_ANY == ((struct sockaddr_in*) h->local_addrs[i])->sin_addr.s_addr)
663           {
664             have_any = GNUNET_YES;
665             break;
666           }
667       }
668     if (GNUNET_NO == have_any)
669       return GNUNET_OK; /* not bound to IP 0.0.0.0 but to specific IP addresses,
670                            do not use those from interfaces */
671     s4 = (struct sockaddr_in *) addr;
672     ip = &s4->sin_addr;
673
674     /* Check if address is in 127.0.0.0/8 */
675     uint32_t address = ntohl ((uint32_t) (s4->sin_addr.s_addr));
676     uint32_t value = (address & 0xFF000000) ^ 0x7F000000;
677
678     if ((h->return_localaddress == GNUNET_NO) && (value == 0))
679     {
680       return GNUNET_OK;
681     }
682     if (GNUNET_YES == h->use_localaddresses)
683     {
684       add_ip_to_address_list (h, LAL_INTERFACE_ADDRESS, &s4->sin_addr,
685                               sizeof (struct in_addr));
686     }
687     break;
688   case AF_INET6:
689     /* check if we're bound to the "ANY" IP address */
690     have_any = GNUNET_NO;
691     for (i=0;i<h->num_local_addrs;i++)
692       {
693         if (h->local_addrs[i]->sa_family != AF_INET6)
694           continue;
695         if (0 == memcmp (&any6,
696                          &((struct sockaddr_in6*) h->local_addrs[i])->sin6_addr,
697                          sizeof (struct in6_addr)))
698           {
699             have_any = GNUNET_YES;
700             break;
701           }
702       }
703     if (GNUNET_NO == have_any)
704       return GNUNET_OK; /* not bound to "ANY" IP (::0) but to specific IP addresses,
705                            do not use those from interfaces */
706
707     s6 = (struct sockaddr_in6 *) addr;
708     if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
709     {
710       /* skip link local addresses */
711       return GNUNET_OK;
712     }
713     if ((h->return_localaddress == GNUNET_NO) &&
714         (IN6_IS_ADDR_LOOPBACK (&((struct sockaddr_in6 *) addr)->sin6_addr)))
715     {
716       return GNUNET_OK;
717     }
718     ip = &s6->sin6_addr;
719     if (GNUNET_YES == h->use_localaddresses)
720     {
721       add_ip_to_address_list (h, LAL_INTERFACE_ADDRESS, &s6->sin6_addr,
722                               sizeof (struct in6_addr));
723     }
724     break;
725   default:
726     GNUNET_break (0);
727     return GNUNET_OK;
728   }
729   if ((h->internal_address == NULL) && (h->server_proc == NULL) &&
730       (h->server_read_task == GNUNET_SCHEDULER_NO_TASK) &&
731       (GNUNET_YES == isDefault) && ((addr->sa_family == AF_INET) ||
732                                     (addr->sa_family == AF_INET6)))
733   {
734     /* no internal address configured, but we found a "default"
735      * interface, try using that as our 'internal' address */
736     h->internal_address =
737         GNUNET_strdup (inet_ntop (addr->sa_family, ip, buf, sizeof (buf)));
738     start_gnunet_nat_server (h);
739   }
740   return GNUNET_OK;
741 }
742
743
744 /**
745  * Task that restarts the gnunet-helper-nat-server process after a crash
746  * after a certain delay.
747  *
748  * @param cls the 'struct GNUNET_NAT_Handle'
749  * @param tc scheduler context
750  */
751 static void
752 restart_nat_server (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
753 {
754   struct GNUNET_NAT_Handle *h = cls;
755
756   h->server_read_task = GNUNET_SCHEDULER_NO_TASK;
757   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
758     return;
759   start_gnunet_nat_server (h);
760 }
761
762
763 /**
764  * We have been notified that gnunet-helper-nat-server has written something to stdout.
765  * Handle the output, then reschedule this function to be called again once
766  * more is available.
767  *
768  * @param cls the NAT handle
769  * @param tc the scheduling context
770  */
771 static void
772 nat_server_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
773 {
774   struct GNUNET_NAT_Handle *h = cls;
775   char mybuf[40];
776   ssize_t bytes;
777   size_t i;
778   int port;
779   const char *port_start;
780   struct sockaddr_in sin_addr;
781
782   h->server_read_task = GNUNET_SCHEDULER_NO_TASK;
783   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
784     return;
785   memset (mybuf, 0, sizeof (mybuf));
786   bytes =
787       GNUNET_DISK_file_read (h->server_stdout_handle, mybuf, sizeof (mybuf));
788   if (bytes < 1)
789   {
790     LOG (GNUNET_ERROR_TYPE_DEBUG,
791          "Finished reading from server stdout with code: %d\n", bytes);
792     if (0 != GNUNET_OS_process_kill (h->server_proc, SIGTERM))
793       GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING, "nat", "kill");
794     GNUNET_OS_process_wait (h->server_proc);
795     GNUNET_OS_process_destroy (h->server_proc);
796     h->server_proc = NULL;
797     GNUNET_DISK_pipe_close (h->server_stdout);
798     h->server_stdout = NULL;
799     h->server_stdout_handle = NULL;
800     /* now try to restart it */
801     h->server_retry_delay = GNUNET_TIME_STD_BACKOFF (h->server_retry_delay);
802     h->server_read_task =
803         GNUNET_SCHEDULER_add_delayed (h->server_retry_delay,
804                                       &restart_nat_server, h);
805     return;
806   }
807
808   port_start = NULL;
809   for (i = 0; i < sizeof (mybuf); i++)
810   {
811     if (mybuf[i] == '\n')
812     {
813       mybuf[i] = '\0';
814       break;
815     }
816     if ((mybuf[i] == ':') && (i + 1 < sizeof (mybuf)))
817     {
818       mybuf[i] = '\0';
819       port_start = &mybuf[i + 1];
820     }
821   }
822
823   /* construct socket address of sender */
824   memset (&sin_addr, 0, sizeof (sin_addr));
825   sin_addr.sin_family = AF_INET;
826 #if HAVE_SOCKADDR_IN_SIN_LEN
827   sin_addr.sin_len = sizeof (sin_addr);
828 #endif
829   if ((NULL == port_start) || (1 != SSCANF (port_start, "%d", &port)) ||
830       (-1 == inet_pton (AF_INET, mybuf, &sin_addr.sin_addr)))
831   {
832     /* should we restart gnunet-helper-nat-server? */
833     LOG (GNUNET_ERROR_TYPE_WARNING, "nat",
834          _("gnunet-helper-nat-server generated malformed address `%s'\n"),
835          mybuf);
836     h->server_read_task =
837         GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
838                                         h->server_stdout_handle,
839                                         &nat_server_read, h);
840     return;
841   }
842   sin_addr.sin_port = htons ((uint16_t) port);
843   LOG (GNUNET_ERROR_TYPE_DEBUG, "gnunet-helper-nat-server read: %s:%d\n", mybuf,
844        port);
845   h->reversal_callback (h->callback_cls, (const struct sockaddr *) &sin_addr,
846                         sizeof (sin_addr));
847   h->server_read_task =
848       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
849                                       h->server_stdout_handle, &nat_server_read,
850                                       h);
851 }
852
853
854 /**
855  * Try to start the gnunet-helper-nat-server (if it is not
856  * already running).
857  *
858  * @param h handle to NAT
859  */
860 static void
861 start_gnunet_nat_server (struct GNUNET_NAT_Handle *h)
862 {
863   char *binary;
864
865   if ((h->behind_nat == GNUNET_YES) && (h->enable_nat_server == GNUNET_YES) &&
866       (h->internal_address != NULL) &&
867       (NULL !=
868        (h->server_stdout =
869         GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES))))
870   {
871     LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting `%s' at `%s'\n",
872          "gnunet-helper-nat-server", h->internal_address);
873     /* Start the server process */
874     binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-server");
875     h->server_proc =
876         GNUNET_OS_start_process (GNUNET_NO, 0, NULL, h->server_stdout,
877                                  binary,
878                                  "gnunet-helper-nat-server",
879                                  h->internal_address, NULL);
880     GNUNET_free (binary);
881     if (h->server_proc == NULL)
882     {
883       LOG (GNUNET_ERROR_TYPE_WARNING, "nat", _("Failed to start %s\n"),
884            "gnunet-helper-nat-server");
885       GNUNET_DISK_pipe_close (h->server_stdout);
886       h->server_stdout = NULL;
887     }
888     else
889     {
890       /* Close the write end of the read pipe */
891       GNUNET_DISK_pipe_close_end (h->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
892       h->server_stdout_handle =
893           GNUNET_DISK_pipe_handle (h->server_stdout, GNUNET_DISK_PIPE_END_READ);
894       h->server_read_task =
895           GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
896                                           h->server_stdout_handle,
897                                           &nat_server_read, h);
898     }
899   }
900 }
901
902
903 /**
904  * Task to scan the local network interfaces for IP addresses.
905  *
906  * @param cls the NAT handle
907  * @param tc scheduler context
908  */
909 static void
910 list_interfaces (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
911 {
912   struct GNUNET_NAT_Handle *h = cls;
913
914   h->ifc_task = GNUNET_SCHEDULER_NO_TASK;
915   remove_from_address_list_by_source (h, LAL_INTERFACE_ADDRESS);
916   GNUNET_OS_network_interfaces_list (&process_interfaces, h);
917   h->ifc_task =
918       GNUNET_SCHEDULER_add_delayed (h->ifc_scan_frequency, &list_interfaces, h);
919 }
920
921
922 /**
923  * Task to do a lookup on our hostname for IP addresses.
924  *
925  * @param cls the NAT handle
926  * @param tc scheduler context
927  */
928 static void
929 resolve_hostname (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
930 {
931   struct GNUNET_NAT_Handle *h = cls;
932
933   h->hostname_task = GNUNET_SCHEDULER_NO_TASK;
934   remove_from_address_list_by_source (h, LAL_HOSTNAME_DNS);
935   h->hostname_dns =
936       GNUNET_RESOLVER_hostname_resolve (AF_UNSPEC, HOSTNAME_RESOLVE_TIMEOUT,
937                                         &process_hostname_ip, h);
938 }
939
940
941 /**
942  * Task to do DNS lookup on our external hostname to
943  * get DynDNS-IP addresses.
944  *
945  * @param cls the NAT handle
946  * @param tc scheduler context
947  */
948 static void
949 resolve_dns (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
950 {
951   struct GNUNET_NAT_Handle *h = cls;
952
953   h->dns_task = GNUNET_SCHEDULER_NO_TASK;
954   remove_from_address_list_by_source (h, LAL_EXTERNAL_IP);
955   h->ext_dns =
956       GNUNET_RESOLVER_ip_get (h->external_address, AF_INET,
957                               GNUNET_TIME_UNIT_MINUTES, &process_external_ip,
958                               h);
959 }
960
961
962 /**
963  * Add or remove UPnP-mapped addresses.
964  *
965  * @param cls the GNUNET_NAT_Handle
966  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
967  *     the previous (now invalid) one
968  * @param addr either the previous or the new public IP address
969  * @param addrlen actual lenght of the address
970  */
971 static void
972 upnp_add (void *cls, int add_remove, const struct sockaddr *addr,
973           socklen_t addrlen)
974 {
975   struct GNUNET_NAT_Handle *h = cls;
976   struct LocalAddressList *pos;
977   struct LocalAddressList *next;
978
979   if (GNUNET_YES == add_remove)
980   {
981     add_to_address_list (h, LAL_UPNP, addr, addrlen);
982     return;
983   }
984   /* remove address */
985   next = h->lal_head;
986   while (NULL != (pos = next))
987   {
988     next = pos->next;
989     if ((pos->source != LAL_UPNP) || (pos->addrlen != addrlen) ||
990         (0 != memcmp (&pos[1], addr, addrlen)))
991       continue;
992     GNUNET_CONTAINER_DLL_remove (h->lal_head, h->lal_tail, pos);
993     if (NULL != h->address_callback)
994       h->address_callback (h->callback_cls, GNUNET_NO,
995                            (const struct sockaddr *) &pos[1], pos->addrlen);
996     GNUNET_free (pos);
997     return;                     /* only remove once */
998   }
999   /* asked to remove address that does not exist */
1000   GNUNET_break (0);
1001 }
1002
1003
1004 /**
1005  * Try to add a port mapping using UPnP.
1006  *
1007  * @param h overall NAT handle
1008  * @param port port to map with UPnP
1009  */
1010 static void
1011 add_minis (struct GNUNET_NAT_Handle *h, uint16_t port)
1012 {
1013   struct MiniList *ml;
1014
1015   ml = h->mini_head;
1016   while (NULL != ml)
1017   {
1018     if (port == ml->port)
1019       return;                   /* already got this port */
1020     ml = ml->next;
1021   }
1022   ml = GNUNET_malloc (sizeof (struct MiniList));
1023   ml->port = port;
1024   ml->mini = GNUNET_NAT_mini_map_start (port, h->is_tcp, &upnp_add, h);
1025   GNUNET_CONTAINER_DLL_insert (h->mini_head, h->mini_tail, ml);
1026 }
1027
1028
1029 /**
1030  * Task to add addresses from original bind to set of valid addrs.
1031  *
1032  * @param cls the NAT handle
1033  * @param tc scheduler context
1034  */
1035 static void
1036 add_from_bind (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1037 {
1038   static struct in6_addr any = IN6ADDR_ANY_INIT;
1039   struct GNUNET_NAT_Handle *h = cls;
1040   unsigned int i;
1041   struct sockaddr *sa;
1042   const struct sockaddr_in *v4;
1043
1044   h->bind_task = GNUNET_SCHEDULER_NO_TASK;
1045   for (i = 0; i < h->num_local_addrs; i++)
1046   {
1047     sa = h->local_addrs[i];
1048     switch (sa->sa_family)
1049     {
1050     case AF_INET:
1051       if (sizeof (struct sockaddr_in) != h->local_addrlens[i])
1052       {
1053         GNUNET_break (0);
1054         break;
1055       }
1056       v4 = (const struct sockaddr_in *) sa;
1057       if (0 != v4->sin_addr.s_addr)
1058         add_to_address_list (h, LAL_BINDTO_ADDRESS, sa,
1059                              sizeof (struct sockaddr_in));
1060       if (h->enable_upnp)
1061         add_minis (h, ntohs (v4->sin_port));
1062       break;
1063     case AF_INET6:
1064       if (sizeof (struct sockaddr_in6) != h->local_addrlens[i])
1065       {
1066         GNUNET_break (0);
1067         break;
1068       }
1069       if (0 !=
1070           memcmp (&((const struct sockaddr_in6 *) sa)->sin6_addr, &any,
1071                   sizeof (struct in6_addr)))
1072         add_to_address_list (h, LAL_BINDTO_ADDRESS, sa,
1073                              sizeof (struct sockaddr_in6));
1074       break;
1075     default:
1076       break;
1077     }
1078   }
1079 }
1080
1081
1082
1083 /**
1084  * Attempt to enable port redirection and detect public IP address contacting
1085  * UPnP or NAT-PMP routers on the local network. Use addr to specify to which
1086  * of the local host's addresses should the external port be mapped. The port
1087  * is taken from the corresponding sockaddr_in[6] field.
1088  *
1089  * @param cfg configuration to use
1090  * @param is_tcp GNUNET_YES for TCP, GNUNET_NO for UDP
1091  * @param adv_port advertised port (port we are either bound to or that our OS
1092  *                 locally performs redirection from to our bound port).
1093  * @param num_addrs number of addresses in 'addrs'
1094  * @param addrs the local addresses packets should be redirected to
1095  * @param addrlens actual lengths of the addresses
1096  * @param address_callback function to call everytime the public IP address changes
1097  * @param reversal_callback function to call if someone wants connection reversal from us
1098  * @param callback_cls closure for callbacks
1099  * @return NULL on error, otherwise handle that can be used to unregister
1100  */
1101 struct GNUNET_NAT_Handle *
1102 GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg, int is_tcp,
1103                      uint16_t adv_port, unsigned int num_addrs,
1104                      const struct sockaddr **addrs, const socklen_t * addrlens,
1105                      GNUNET_NAT_AddressCallback address_callback,
1106                      GNUNET_NAT_ReversalCallback reversal_callback,
1107                      void *callback_cls)
1108 {
1109   struct GNUNET_NAT_Handle *h;
1110   struct in_addr in_addr;
1111   unsigned int i;
1112   char *binary;
1113
1114   LOG (GNUNET_ERROR_TYPE_DEBUG,
1115        "Registered with NAT service at port %u with %u IP bound local addresses\n",
1116        (unsigned int) adv_port, num_addrs);
1117   h = GNUNET_malloc (sizeof (struct GNUNET_NAT_Handle));
1118   h->server_retry_delay = GNUNET_TIME_UNIT_SECONDS;
1119   h->cfg = cfg;
1120   h->is_tcp = is_tcp;
1121   h->address_callback = address_callback;
1122   h->reversal_callback = reversal_callback;
1123   h->callback_cls = callback_cls;
1124   h->num_local_addrs = num_addrs;
1125   h->adv_port = adv_port;
1126   if (num_addrs != 0)
1127   {
1128     h->local_addrs = GNUNET_malloc (num_addrs * sizeof (struct sockaddr *));
1129     h->local_addrlens = GNUNET_malloc (num_addrs * sizeof (socklen_t));
1130     for (i = 0; i < num_addrs; i++)
1131     {
1132       GNUNET_assert (addrlens[i] > 0);
1133       GNUNET_assert (addrs[i] != NULL);
1134       h->local_addrlens[i] = addrlens[i];
1135       h->local_addrs[i] = GNUNET_malloc (addrlens[i]);
1136       memcpy (h->local_addrs[i], addrs[i], addrlens[i]);
1137     }
1138   }
1139   h->bind_task = GNUNET_SCHEDULER_add_now (&add_from_bind, h);
1140   if (GNUNET_OK ==
1141       GNUNET_CONFIGURATION_have_value (cfg, "nat", "INTERNAL_ADDRESS"))
1142   {
1143     (void) GNUNET_CONFIGURATION_get_value_string (cfg, "nat",
1144                                                   "INTERNAL_ADDRESS",
1145                                                   &h->internal_address);
1146   }
1147   if ((h->internal_address != NULL) &&
1148       (inet_pton (AF_INET, h->internal_address, &in_addr) != 1))
1149   {
1150     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING, 
1151                                "nat", "INTERNAL_ADDRESS",
1152                                _("malformed"));
1153     GNUNET_free (h->internal_address);
1154     h->internal_address = NULL;
1155   }
1156
1157   if (GNUNET_OK ==
1158       GNUNET_CONFIGURATION_have_value (cfg, "nat", "EXTERNAL_ADDRESS"))
1159   {
1160     (void) GNUNET_CONFIGURATION_get_value_string (cfg, "nat",
1161                                                   "EXTERNAL_ADDRESS",
1162                                                   &h->external_address);
1163   }
1164   h->behind_nat =
1165       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "BEHIND_NAT");
1166   h->nat_punched =
1167       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "PUNCHED_NAT");
1168   h->enable_nat_client =
1169       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "ENABLE_ICMP_CLIENT");
1170   h->enable_nat_server =
1171       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "ENABLE_ICMP_SERVER");
1172   h->enable_upnp =
1173       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "ENABLE_UPNP");
1174   h->use_localaddresses =
1175       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "USE_LOCALADDR");
1176   h->return_localaddress =
1177       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat",
1178                                             "RETURN_LOCAL_ADDRESSES");
1179
1180   h->use_hostname =
1181       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "USE_HOSTNAME");
1182   h->disable_ipv6 =
1183       GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "DISABLEV6");
1184   if (GNUNET_OK !=
1185       GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "DYNDNS_FREQUENCY",
1186                                            &h->dyndns_frequency))
1187     h->dyndns_frequency = DYNDNS_FREQUENCY;
1188   if (GNUNET_OK !=
1189       GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "IFC_SCAN_FREQUENCY",
1190                                            &h->ifc_scan_frequency))
1191     h->ifc_scan_frequency = IFC_SCAN_FREQUENCY;
1192   if (GNUNET_OK !=
1193       GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "HOSTNAME_DNS_FREQUENCY",
1194                                            &h->hostname_dns_frequency))
1195     h->hostname_dns_frequency = HOSTNAME_DNS_FREQUENCY;
1196
1197   if (NULL == reversal_callback)
1198     h->enable_nat_server = GNUNET_NO;
1199
1200   /* Check if NAT was hole-punched */
1201   if ((NULL != h->address_callback) && (h->external_address != NULL) &&
1202       (h->nat_punched == GNUNET_YES))
1203   {
1204     h->dns_task = GNUNET_SCHEDULER_add_now (&resolve_dns, h);
1205     h->enable_nat_server = GNUNET_NO;
1206     h->enable_upnp = GNUNET_NO;
1207   }
1208
1209   /* Test for SUID binaries */
1210   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-server");
1211   if ((h->behind_nat == GNUNET_YES) && (GNUNET_YES == h->enable_nat_server) &&
1212       (GNUNET_YES !=
1213        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
1214   {
1215     h->enable_nat_server = GNUNET_NO;
1216     LOG (GNUNET_ERROR_TYPE_WARNING,
1217          _
1218          ("Configuration requires `%s', but binary is not installed properly (SUID bit not set).  Option disabled.\n"),
1219          "gnunet-helper-nat-server");
1220   }
1221   GNUNET_free (binary);
1222   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-client");
1223   if ((GNUNET_YES == h->enable_nat_client) &&
1224       (GNUNET_YES !=
1225        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
1226   {
1227     h->enable_nat_client = GNUNET_NO;
1228     LOG (GNUNET_ERROR_TYPE_WARNING,
1229          _
1230          ("Configuration requires `%s', but binary is not installed properly (SUID bit not set).  Option disabled.\n"),
1231          "gnunet-helper-nat-client");
1232   }
1233   GNUNET_free (binary);
1234   start_gnunet_nat_server (h);
1235
1236   /* FIXME: add support for UPnP, etc */
1237
1238   if (NULL != h->address_callback)
1239   {
1240     h->ifc_task = GNUNET_SCHEDULER_add_now (&list_interfaces, h);
1241     if (GNUNET_YES == h->use_hostname)
1242       h->hostname_task = GNUNET_SCHEDULER_add_now (&resolve_hostname, h);
1243   }
1244
1245   return h;
1246 }
1247
1248
1249 /**
1250  * Stop port redirection and public IP address detection for the given handle.
1251  * This frees the handle, after having sent the needed commands to close open ports.
1252  *
1253  * @param h the handle to stop
1254  */
1255 void
1256 GNUNET_NAT_unregister (struct GNUNET_NAT_Handle *h)
1257 {
1258   unsigned int i;
1259   struct LocalAddressList *lal;
1260   struct MiniList *ml;
1261
1262   while (NULL != (ml = h->mini_head))
1263   {
1264     GNUNET_CONTAINER_DLL_remove (h->mini_head, h->mini_tail, ml);
1265     if (NULL != ml->mini)
1266       GNUNET_NAT_mini_map_stop (ml->mini);
1267     GNUNET_free (ml);
1268   }
1269   if (h->ext_dns != NULL)
1270   {
1271     GNUNET_RESOLVER_request_cancel (h->ext_dns);
1272     h->ext_dns = NULL;
1273   }
1274   if (NULL != h->hostname_dns)
1275   {
1276     GNUNET_RESOLVER_request_cancel (h->hostname_dns);
1277     h->hostname_dns = NULL;
1278   }
1279   if (GNUNET_SCHEDULER_NO_TASK != h->server_read_task)
1280   {
1281     GNUNET_SCHEDULER_cancel (h->server_read_task);
1282     h->server_read_task = GNUNET_SCHEDULER_NO_TASK;
1283   }
1284   if (GNUNET_SCHEDULER_NO_TASK != h->bind_task)
1285   {
1286     GNUNET_SCHEDULER_cancel (h->bind_task);
1287     h->bind_task = GNUNET_SCHEDULER_NO_TASK;
1288   }
1289   if (GNUNET_SCHEDULER_NO_TASK != h->ifc_task)
1290   {
1291     GNUNET_SCHEDULER_cancel (h->ifc_task);
1292     h->ifc_task = GNUNET_SCHEDULER_NO_TASK;
1293   }
1294   if (GNUNET_SCHEDULER_NO_TASK != h->hostname_task)
1295   {
1296     GNUNET_SCHEDULER_cancel (h->hostname_task);
1297     h->hostname_task = GNUNET_SCHEDULER_NO_TASK;
1298   }
1299   if (GNUNET_SCHEDULER_NO_TASK != h->dns_task)
1300   {
1301     GNUNET_SCHEDULER_cancel (h->dns_task);
1302     h->dns_task = GNUNET_SCHEDULER_NO_TASK;
1303   }
1304   if (NULL != h->server_proc)
1305   {
1306     if (0 != GNUNET_OS_process_kill (h->server_proc, SIGTERM))
1307       GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING, "nat", "kill");
1308     GNUNET_OS_process_wait (h->server_proc);
1309     GNUNET_OS_process_destroy (h->server_proc);
1310     h->server_proc = NULL;
1311     GNUNET_DISK_pipe_close (h->server_stdout);
1312     h->server_stdout = NULL;
1313     h->server_stdout_handle = NULL;
1314   }
1315   if (NULL != h->server_stdout)
1316   {
1317     GNUNET_DISK_pipe_close (h->server_stdout);
1318     h->server_stdout = NULL;
1319     h->server_stdout_handle = NULL;
1320   }
1321   while (NULL != (lal = h->lal_head))
1322   {
1323     GNUNET_CONTAINER_DLL_remove (h->lal_head, h->lal_tail, lal);
1324     if (NULL != h->address_callback)
1325       h->address_callback (h->callback_cls, GNUNET_NO,
1326                            (const struct sockaddr *) &lal[1], lal->addrlen);
1327     GNUNET_free (lal);
1328   }
1329   for (i = 0; i < h->num_local_addrs; i++)
1330     GNUNET_free (h->local_addrs[i]);
1331   GNUNET_free_non_null (h->local_addrs);
1332   GNUNET_free_non_null (h->local_addrlens);
1333   GNUNET_free_non_null (h->external_address);
1334   GNUNET_free_non_null (h->internal_address);
1335   GNUNET_free (h);
1336 }
1337
1338
1339 /**
1340  * We learned about a peer (possibly behind NAT) so run the
1341  * gnunet-helper-nat-client to send dummy ICMP responses to cause
1342  * that peer to connect to us (connection reversal).
1343  *
1344  * @return GNUNET_SYSERR on error, GNUNET_NO if nat client is disabled,
1345  *         GNUNET_OK otherwise
1346  */
1347 int
1348 GNUNET_NAT_run_client (struct GNUNET_NAT_Handle *h,
1349                        const struct sockaddr_in *sa)
1350
1351
1352 {
1353   char inet4[INET_ADDRSTRLEN];
1354   char port_as_string[6];
1355   struct GNUNET_OS_Process *proc;
1356   char *binary;
1357
1358   if (GNUNET_YES != h->enable_nat_client)
1359     return GNUNET_NO;                     /* not permitted / possible */
1360
1361   if (h->internal_address == NULL)
1362   {
1363     LOG (GNUNET_ERROR_TYPE_WARNING, "nat",
1364          _
1365          ("Internal IP address not known, cannot use ICMP NAT traversal method\n"));
1366     return GNUNET_SYSERR;
1367   }
1368   GNUNET_assert (sa->sin_family == AF_INET);
1369   if (NULL == inet_ntop (AF_INET, &sa->sin_addr, inet4, INET_ADDRSTRLEN))
1370   {
1371     GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING, "nat", "inet_ntop");
1372     return GNUNET_SYSERR;
1373   }
1374   GNUNET_snprintf (port_as_string, sizeof (port_as_string), "%d", h->adv_port);
1375   LOG (GNUNET_ERROR_TYPE_DEBUG,
1376        _("Running gnunet-helper-nat-client %s %s %u\n"), h->internal_address,
1377        inet4, (unsigned int) h->adv_port);
1378   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-client");
1379   proc =
1380       GNUNET_OS_start_process (GNUNET_NO, 0, NULL, NULL,
1381                                binary,
1382                                "gnunet-helper-nat-client", h->internal_address,
1383                                inet4, port_as_string, NULL);
1384   GNUNET_free (binary);
1385   if (NULL == proc)
1386     return GNUNET_SYSERR;
1387   /* we know that the gnunet-helper-nat-client will terminate virtually
1388    * instantly */
1389   GNUNET_OS_process_wait (proc);
1390   GNUNET_OS_process_destroy (proc);
1391   return GNUNET_OK;
1392 }
1393
1394
1395 /**
1396  * Test if the given address is (currently) a plausible IP address for this peer.
1397  *
1398  * @param h the handle returned by register
1399  * @param addr IP address to test (IPv4 or IPv6)
1400  * @param addrlen number of bytes in addr
1401  * @return GNUNET_YES if the address is plausible,
1402  *         GNUNET_NO if the address is not plausible,
1403  *         GNUNET_SYSERR if the address is malformed
1404  */
1405 int
1406 GNUNET_NAT_test_address (struct GNUNET_NAT_Handle *h, const void *addr,
1407                          socklen_t addrlen)
1408 {
1409   struct LocalAddressList *pos;
1410   const struct sockaddr_in *in4;
1411   const struct sockaddr_in6 *in6;
1412
1413   if ((addrlen != sizeof (struct in_addr)) &&
1414       (addrlen != sizeof (struct in6_addr)))
1415   {
1416     GNUNET_break (0);
1417     return GNUNET_SYSERR;
1418   }
1419   pos = h->lal_head;
1420   while (NULL != pos)
1421   {
1422     if (pos->addrlen == sizeof (struct sockaddr_in))
1423     {
1424       in4 = (struct sockaddr_in *) &pos[1];
1425       if ((addrlen == sizeof (struct in_addr)) &&
1426           (0 == memcmp (&in4->sin_addr, addr, sizeof (struct in_addr))))
1427         return GNUNET_YES;
1428     }
1429     else if (pos->addrlen == sizeof (struct sockaddr_in6))
1430     {
1431       in6 = (struct sockaddr_in6 *) &pos[1];
1432       if ((addrlen == sizeof (struct in6_addr)) &&
1433           (0 == memcmp (&in6->sin6_addr, addr, sizeof (struct in6_addr))))
1434         return GNUNET_YES;
1435     }
1436     else
1437     {
1438       GNUNET_assert (0);
1439     }
1440     pos = pos->next;
1441   }
1442   LOG (GNUNET_ERROR_TYPE_WARNING,
1443        "Asked to validate one of my addresses and validation failed!\n");
1444   return GNUNET_NO;
1445 }
1446
1447
1448 /* end of nat.c */