2 This file is part of GNUnet.
3 Copyright (C) 2009, 2010, 2011 Christian Grothoff (and other contributing authors)
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.
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.
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.
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
29 #include "gnunet_util_lib.h"
30 #include "gnunet_resolver_service.h"
31 #include "gnunet_nat_lib.h"
34 #define LOG(kind,...) GNUNET_log_from (kind, "nat", __VA_ARGS__)
37 * How often do we scan for changes in our IP address from our local
40 #define IFC_SCAN_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
43 * How often do we scan for changes in how our hostname resolves?
45 #define HOSTNAME_DNS_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 20)
49 * How often do we scan for changes in how our external (dyndns) hostname resolves?
51 #define DYNDNS_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 7)
54 * How long until we give up trying to resolve our own hostname?
56 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
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.
65 enum LocalAddressSource
68 * Address was obtained by DNS resolution of the external hostname
69 * given in the configuration (i.e. hole-punched DynDNS setup).
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).
81 * Address was obtained by looking up our own hostname in DNS.
86 * Address was obtained by scanning our hosts's network interfaces
87 * and taking their address (no DNS involved).
89 LAL_INTERFACE_ADDRESS,
92 * Addresses we were explicitly bound to.
97 * Addresses from UPnP or PMP
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).
115 struct LocalAddressList
118 * This is a linked list.
120 struct LocalAddressList *next;
125 struct LocalAddressList *prev;
128 * Number of bytes of address that follow.
133 * Origin of the local address.
135 enum LocalAddressSource source;
140 * Handle for miniupnp-based NAT traversal actions.
146 * Doubly-linked list.
148 struct MiniList *next;
151 * Doubly-linked list.
153 struct MiniList *prev;
156 * Handle to mini-action.
158 struct GNUNET_NAT_MiniHandle *mini;
161 * Local port number that was mapped.
169 * Handle for active NAT registrations.
171 struct GNUNET_NAT_Handle
175 * Configuration to use.
177 const struct GNUNET_CONFIGURATION_Handle *cfg;
180 * Function to call when we learn about a new address.
182 GNUNET_NAT_AddressCallback address_callback;
185 * Function to call when we notice another peer asking for
186 * connection reversal.
188 GNUNET_NAT_ReversalCallback reversal_callback;
191 * Closure for callbacks (@e address_callback and @e reversal_callback)
196 * Handle for (DYN)DNS lookup of our external IP.
198 struct GNUNET_RESOLVER_RequestHandle *ext_dns;
201 * Handle for request of hostname resolution, non-NULL if pending.
203 struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
206 * stdout pipe handle for the gnunet-helper-nat-server process
208 struct GNUNET_DISK_PipeHandle *server_stdout;
211 * stdout file handle (for reading) for the gnunet-helper-nat-server process
213 const struct GNUNET_DISK_FileHandle *server_stdout_handle;
216 * Linked list of currently valid addresses (head).
218 struct LocalAddressList *lal_head;
221 * Linked list of currently valid addresses (tail).
223 struct LocalAddressList *lal_tail;
226 * How long do we wait for restarting a crashed gnunet-helper-nat-server?
228 struct GNUNET_TIME_Relative server_retry_delay;
231 * ID of select gnunet-helper-nat-server stdout read task
233 struct GNUNET_SCHEDULER_Task * server_read_task;
236 * ID of interface IP-scan task
238 struct GNUNET_SCHEDULER_Task * ifc_task;
241 * ID of hostname DNS lookup task
243 struct GNUNET_SCHEDULER_Task * hostname_task;
246 * ID of DynDNS lookup task
248 struct GNUNET_SCHEDULER_Task *dns_task;
251 * How often do we scan for changes in our IP address from our local
254 struct GNUNET_TIME_Relative ifc_scan_frequency;
257 * How often do we scan for changes in how our hostname resolves?
259 struct GNUNET_TIME_Relative hostname_dns_frequency;
262 * How often do we scan for changes in how our external (dyndns) hostname resolves?
264 struct GNUNET_TIME_Relative dyndns_frequency;
267 * The process id of the server process (if behind NAT)
269 struct GNUNET_OS_Process *server_proc;
272 * LAN address as passed by the caller (array).
274 struct sockaddr **local_addrs;
277 * Length of the @e local_addrs.
279 socklen_t *local_addrlens;
282 * List of handles for UPnP-traversal, one per local port (if
285 struct MiniList *mini_head;
288 * List of handles for UPnP-traversal, one per local port (if
291 struct MiniList *mini_tail;
294 * Number of entries in 'local_addrs' array.
296 unsigned int num_local_addrs;
299 * Our external address (according to config, UPnP may disagree...),
300 * in dotted decimal notation, IPv4-only. Or NULL if not known.
302 char *external_address;
305 * Presumably our internal address (according to config)
307 char *internal_address;
310 * Is this transport configured to be behind a NAT?
315 * Has the NAT been punched? (according to config)
320 * Is this transport configured to allow connections to NAT'd peers?
322 int enable_nat_client;
325 * Should we run the gnunet-helper-nat-server?
327 int enable_nat_server;
330 * Are we allowed to try UPnP/PMP for NAT traversal?
335 * Should we use local addresses (loopback)? (according to config)
337 int use_localaddresses;
340 * Should we return local addresses to clients
342 int return_localaddress;
345 * Should we do a DNS lookup of our hostname to find out our own IP?
350 * Is using IPv6 disabled?
355 * Is this TCP or UDP?
360 * Port we advertise to the outside.
368 * Try to start the gnunet-helper-nat-server (if it is not
371 * @param h handle to NAT
374 start_gnunet_nat_server (struct GNUNET_NAT_Handle *h);
378 * Remove all addresses from the list of 'local' addresses
379 * that originated from the given source.
381 * @param h handle to NAT
382 * @param src source that identifies addresses to remove
385 remove_from_address_list_by_source (struct GNUNET_NAT_Handle *h,
386 enum LocalAddressSource src)
388 struct LocalAddressList *pos;
389 struct LocalAddressList *next;
392 while (NULL != (pos = next))
395 if (pos->source != src)
397 GNUNET_CONTAINER_DLL_remove (h->lal_head, h->lal_tail, pos);
398 if (NULL != h->address_callback)
399 h->address_callback (h->callback_cls, GNUNET_NO,
400 (const struct sockaddr *) &pos[1], pos->addrlen);
407 * Add the given address to the list of 'local' addresses, thereby
408 * making it a 'legal' address for this peer to have.
410 * @param h handle to NAT
411 * @param src where did the local address originate from?
412 * @param arg the address, some `struct sockaddr`
413 * @param arg_size number of bytes in @a arg
416 add_to_address_list_as_is (struct GNUNET_NAT_Handle *h,
417 enum LocalAddressSource src,
418 const struct sockaddr *arg, socklen_t arg_size)
420 struct LocalAddressList *lal;
422 lal = GNUNET_malloc (sizeof (struct LocalAddressList) + arg_size);
423 memcpy (&lal[1], arg, arg_size);
424 lal->addrlen = arg_size;
426 GNUNET_CONTAINER_DLL_insert (h->lal_head, h->lal_tail, lal);
427 LOG (GNUNET_ERROR_TYPE_DEBUG,
428 "Adding address `%s' from source %d\n",
429 GNUNET_a2s (arg, arg_size),
431 if (NULL != h->address_callback)
432 h->address_callback (h->callback_cls, GNUNET_YES, arg, arg_size);
437 * Add the given address to the list of 'local' addresses, thereby
438 * making it a 'legal' address for this peer to have. Set the
439 * port number in the process to the advertised port and possibly
440 * also to zero (if we have the gnunet-helper-nat-server).
442 * @param h handle to NAT
443 * @param src where did the local address originate from?
444 * @param arg the address, some `struct sockaddr`
445 * @param arg_size number of bytes in @a arg
448 add_to_address_list (struct GNUNET_NAT_Handle *h,
449 enum LocalAddressSource src,
450 const struct sockaddr *arg,
453 struct sockaddr_in s4;
454 const struct sockaddr_in *in4;
455 struct sockaddr_in6 s6;
456 const struct sockaddr_in6 *in6;
458 if (arg_size == sizeof (struct sockaddr_in))
460 in4 = (const struct sockaddr_in *) arg;
462 s4.sin_port = htons (h->adv_port);
463 add_to_address_list_as_is (h, src, (const struct sockaddr *) &s4,
464 sizeof (struct sockaddr_in));
465 if (GNUNET_YES == h->enable_nat_server)
467 /* also add with PORT = 0 to indicate NAT server is enabled */
468 s4.sin_port = htons (0);
469 add_to_address_list_as_is (h, src, (const struct sockaddr *) &s4,
470 sizeof (struct sockaddr_in));
473 else if (arg_size == sizeof (struct sockaddr_in6))
475 if (GNUNET_YES != h->disable_ipv6)
477 in6 = (const struct sockaddr_in6 *) arg;
479 s6.sin6_port = htons (h->adv_port);
480 add_to_address_list_as_is (h, src, (const struct sockaddr *) &s6,
481 sizeof (struct sockaddr_in6));
492 * Add the given IP address to the list of 'local' addresses, thereby
493 * making it a 'legal' address for this peer to have.
495 * @param h handle to NAT
496 * @param src where did the local address originate from?
497 * @param addr the address, some `struct in_addr` or `struct in6_addr`
498 * @param addrlen number of bytes in addr
501 add_ip_to_address_list (struct GNUNET_NAT_Handle *h,
502 enum LocalAddressSource src, const void *addr,
505 struct sockaddr_in s4;
506 const struct in_addr *in4;
507 struct sockaddr_in6 s6;
508 const struct in6_addr *in6;
510 if (addrlen == sizeof (struct in_addr))
512 in4 = (const struct in_addr *) addr;
513 memset (&s4, 0, sizeof (s4));
514 s4.sin_family = AF_INET;
516 #if HAVE_SOCKADDR_IN_SIN_LEN
517 s4.sin_len = (u_char) sizeof (struct sockaddr_in);
520 add_to_address_list (h, src, (const struct sockaddr *) &s4,
521 sizeof (struct sockaddr_in));
522 if (GNUNET_YES == h->enable_nat_server)
524 /* also add with PORT = 0 to indicate NAT server is enabled */
525 s4.sin_port = htons (0);
526 add_to_address_list (h, src, (const struct sockaddr *) &s4,
527 sizeof (struct sockaddr_in));
531 else if (addrlen == sizeof (struct in6_addr))
533 if (GNUNET_YES != h->disable_ipv6)
535 in6 = (const struct in6_addr *) addr;
536 memset (&s6, 0, sizeof (s6));
537 s6.sin6_family = AF_INET6;
538 s6.sin6_port = htons (h->adv_port);
539 #if HAVE_SOCKADDR_IN_SIN_LEN
540 s6.sin6_len = (u_char) sizeof (struct sockaddr_in6);
543 add_to_address_list (h, src, (const struct sockaddr *) &s6,
544 sizeof (struct sockaddr_in6));
555 * Task to do DNS lookup on our external hostname to
556 * get DynDNS-IP addresses.
558 * @param cls the NAT handle
559 * @param tc scheduler context
562 resolve_dns (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
566 * Our (external) hostname was resolved and the configuration says that
567 * the NAT was hole-punched.
569 * @param cls the `struct GNUNET_NAT_Handle`
570 * @param addr NULL on error, otherwise result of DNS lookup
571 * @param addrlen number of bytes in @a addr
574 process_external_ip (void *cls,
575 const struct sockaddr *addr,
578 struct GNUNET_NAT_Handle *h = cls;
579 struct in_addr dummy;
584 /* Current iteration is over, remove 'old' IPs now */
585 LOG (GNUNET_ERROR_TYPE_DEBUG,
586 "Purging old IPs for external address\n");
587 remove_from_address_list_by_source (h, LAL_EXTERNAL_IP_OLD);
588 if (1 == inet_pton (AF_INET,
592 LOG (GNUNET_ERROR_TYPE_DEBUG,
593 "Got numeric IP for external address, not repeating lookup\n");
594 return; /* repated lookup pointless: was numeric! */
597 GNUNET_SCHEDULER_add_delayed (h->dyndns_frequency,
601 LOG (GNUNET_ERROR_TYPE_DEBUG,
602 "Got IP `%s' for external address `%s'\n",
603 GNUNET_a2s (addr, addrlen),
604 h->external_address);
605 add_to_address_list (h, LAL_EXTERNAL_IP, addr, addrlen);
610 * Task to do a lookup on our hostname for IP addresses.
612 * @param cls the NAT handle
613 * @param tc scheduler context
616 resolve_hostname (void *cls,
617 const struct GNUNET_SCHEDULER_TaskContext *tc);
621 * Function called by the resolver for each address obtained from DNS
622 * for our own hostname. Add the addresses to the list of our IP
626 * @param addr one of the addresses of the host, NULL for the last address
627 * @param addrlen length of the @a addr
630 process_hostname_ip (void *cls,
631 const struct sockaddr *addr,
634 struct GNUNET_NAT_Handle *h = cls;
638 h->hostname_dns = NULL;
640 GNUNET_SCHEDULER_add_delayed (h->hostname_dns_frequency,
641 &resolve_hostname, h);
644 add_to_address_list (h, LAL_HOSTNAME_DNS, addr, addrlen);
649 * Add the IP of our network interface to the list of
652 * @param cls the `struct GNUNET_NAT_Handle`
653 * @param name name of the interface
654 * @param isDefault do we think this may be our default interface
655 * @param addr address of the interface
656 * @param broadcast_addr the broadcast address (can be NULL for unknown or unassigned)
657 * @param netmask the network mask (can be NULL for unknown or unassigned))
658 * @param addrlen number of bytes in @a addr and @a broadcast_addr
659 * @return #GNUNET_OK to continue iterating
662 process_interfaces (void *cls, const char *name, int isDefault,
663 const struct sockaddr *addr,
664 const struct sockaddr *broadcast_addr,
665 const struct sockaddr *netmask, socklen_t addrlen)
667 const static struct in6_addr any6 = IN6ADDR_ANY_INIT;
668 struct GNUNET_NAT_Handle *h = cls;
669 const struct sockaddr_in *s4;
670 const struct sockaddr_in6 *s6;
672 char buf[INET6_ADDRSTRLEN];
676 switch (addr->sa_family)
679 /* check if we're bound to the "ANY" IP address */
680 have_any = GNUNET_NO;
681 for (i=0;i<h->num_local_addrs;i++)
683 if (h->local_addrs[i]->sa_family != AF_INET)
688 if (INADDR_ANY == ((struct sockaddr_in*) h->local_addrs[i])->sin_addr.s_addr)
690 have_any = GNUNET_YES;
694 if (GNUNET_NO == have_any)
695 return GNUNET_OK; /* not bound to IP 0.0.0.0 but to specific IP addresses,
696 do not use those from interfaces */
697 s4 = (struct sockaddr_in *) addr;
700 /* Check if address is in 127.0.0.0/8 */
701 uint32_t address = ntohl ((uint32_t) (s4->sin_addr.s_addr));
702 uint32_t value = (address & 0xFF000000) ^ 0x7F000000;
704 if ((h->return_localaddress == GNUNET_NO) && (value == 0))
708 if ((GNUNET_YES == h->use_localaddresses) || (value != 0))
710 add_ip_to_address_list (h, LAL_INTERFACE_ADDRESS, &s4->sin_addr,
711 sizeof (struct in_addr));
715 /* check if we're bound to the "ANY" IP address */
716 have_any = GNUNET_NO;
717 for (i=0;i<h->num_local_addrs;i++)
719 if (h->local_addrs[i]->sa_family != AF_INET6)
721 if (0 == memcmp (&any6,
722 &((struct sockaddr_in6*) h->local_addrs[i])->sin6_addr,
723 sizeof (struct in6_addr)))
725 have_any = GNUNET_YES;
729 if (GNUNET_NO == have_any)
730 return GNUNET_OK; /* not bound to "ANY" IP (::0) but to specific IP addresses,
731 do not use those from interfaces */
733 s6 = (struct sockaddr_in6 *) addr;
734 if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
736 /* skip link local addresses */
739 if ((h->return_localaddress == GNUNET_NO) &&
740 (IN6_IS_ADDR_LOOPBACK (&((struct sockaddr_in6 *) addr)->sin6_addr)))
745 if (GNUNET_YES == h->use_localaddresses)
747 add_ip_to_address_list (h, LAL_INTERFACE_ADDRESS, &s6->sin6_addr,
748 sizeof (struct in6_addr));
755 if ((h->internal_address == NULL) && (h->server_proc == NULL) &&
756 (h->server_read_task == NULL) &&
757 (GNUNET_YES == isDefault) && ((addr->sa_family == AF_INET) ||
758 (addr->sa_family == AF_INET6)))
760 /* no internal address configured, but we found a "default"
761 * interface, try using that as our 'internal' address */
762 h->internal_address =
763 GNUNET_strdup (inet_ntop (addr->sa_family, ip, buf, sizeof (buf)));
764 start_gnunet_nat_server (h);
771 * Task that restarts the gnunet-helper-nat-server process after a crash
772 * after a certain delay.
774 * @param cls the `struct GNUNET_NAT_Handle`
775 * @param tc scheduler context
778 restart_nat_server (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
780 struct GNUNET_NAT_Handle *h = cls;
782 h->server_read_task = NULL;
783 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
785 start_gnunet_nat_server (h);
790 * We have been notified that gnunet-helper-nat-server has written
791 * something to stdout. Handle the output, then reschedule this
792 * function to be called again once more is available.
794 * @param cls the NAT handle
795 * @param tc the scheduling context
798 nat_server_read (void *cls,
799 const struct GNUNET_SCHEDULER_TaskContext *tc)
801 struct GNUNET_NAT_Handle *h = cls;
806 const char *port_start;
807 struct sockaddr_in sin_addr;
809 h->server_read_task = NULL;
810 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
812 memset (mybuf, 0, sizeof (mybuf));
814 GNUNET_DISK_file_read (h->server_stdout_handle, mybuf, sizeof (mybuf));
817 LOG (GNUNET_ERROR_TYPE_DEBUG,
818 "Finished reading from server stdout with code: %d\n",
820 if (0 != GNUNET_OS_process_kill (h->server_proc, GNUNET_TERM_SIG))
821 GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING, "nat", "kill");
822 GNUNET_OS_process_wait (h->server_proc);
823 GNUNET_OS_process_destroy (h->server_proc);
824 h->server_proc = NULL;
825 GNUNET_DISK_pipe_close (h->server_stdout);
826 h->server_stdout = NULL;
827 h->server_stdout_handle = NULL;
828 /* now try to restart it */
829 h->server_retry_delay = GNUNET_TIME_STD_BACKOFF (h->server_retry_delay);
830 h->server_read_task =
831 GNUNET_SCHEDULER_add_delayed (h->server_retry_delay,
832 &restart_nat_server, h);
837 for (i = 0; i < sizeof (mybuf); i++)
839 if (mybuf[i] == '\n')
844 if ((mybuf[i] == ':') && (i + 1 < sizeof (mybuf)))
847 port_start = &mybuf[i + 1];
851 /* construct socket address of sender */
852 memset (&sin_addr, 0, sizeof (sin_addr));
853 sin_addr.sin_family = AF_INET;
854 #if HAVE_SOCKADDR_IN_SIN_LEN
855 sin_addr.sin_len = sizeof (sin_addr);
857 if ((NULL == port_start) || (1 != SSCANF (port_start, "%d", &port)) ||
858 (-1 == inet_pton (AF_INET, mybuf, &sin_addr.sin_addr)))
860 /* should we restart gnunet-helper-nat-server? */
861 LOG (GNUNET_ERROR_TYPE_WARNING, "nat",
862 _("gnunet-helper-nat-server generated malformed address `%s'\n"),
864 h->server_read_task =
865 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
866 h->server_stdout_handle,
867 &nat_server_read, h);
870 sin_addr.sin_port = htons ((uint16_t) port);
871 LOG (GNUNET_ERROR_TYPE_DEBUG, "gnunet-helper-nat-server read: %s:%d\n", mybuf,
873 h->reversal_callback (h->callback_cls, (const struct sockaddr *) &sin_addr,
875 h->server_read_task =
876 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
877 h->server_stdout_handle, &nat_server_read,
883 * Try to start the gnunet-helper-nat-server (if it is not
886 * @param h handle to NAT
889 start_gnunet_nat_server (struct GNUNET_NAT_Handle *h)
893 if ((h->behind_nat == GNUNET_YES) && (h->enable_nat_server == GNUNET_YES) &&
894 (h->internal_address != NULL) &&
897 GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES))))
899 LOG (GNUNET_ERROR_TYPE_DEBUG,
900 "Starting `%s' at `%s'\n",
901 "gnunet-helper-nat-server", h->internal_address);
902 /* Start the server process */
903 binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-server");
905 GNUNET_OS_start_process (GNUNET_NO, 0, NULL, h->server_stdout, NULL,
907 "gnunet-helper-nat-server",
908 h->internal_address, NULL);
909 GNUNET_free (binary);
910 if (h->server_proc == NULL)
912 LOG (GNUNET_ERROR_TYPE_WARNING, "nat", _("Failed to start %s\n"),
913 "gnunet-helper-nat-server");
914 GNUNET_DISK_pipe_close (h->server_stdout);
915 h->server_stdout = NULL;
919 /* Close the write end of the read pipe */
920 GNUNET_DISK_pipe_close_end (h->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
921 h->server_stdout_handle =
922 GNUNET_DISK_pipe_handle (h->server_stdout, GNUNET_DISK_PIPE_END_READ);
923 h->server_read_task =
924 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
925 h->server_stdout_handle,
926 &nat_server_read, h);
933 * Task to scan the local network interfaces for IP addresses.
935 * @param cls the NAT handle
936 * @param tc scheduler context
939 list_interfaces (void *cls,
940 const struct GNUNET_SCHEDULER_TaskContext *tc)
942 struct GNUNET_NAT_Handle *h = cls;
945 remove_from_address_list_by_source (h, LAL_INTERFACE_ADDRESS);
946 GNUNET_OS_network_interfaces_list (&process_interfaces, h);
948 GNUNET_SCHEDULER_add_delayed (h->ifc_scan_frequency,
949 &list_interfaces, h);
954 * Task to do a lookup on our hostname for IP addresses.
956 * @param cls the NAT handle
957 * @param tc scheduler context
960 resolve_hostname (void *cls,
961 const struct GNUNET_SCHEDULER_TaskContext *tc)
963 struct GNUNET_NAT_Handle *h = cls;
965 h->hostname_task = NULL;
966 remove_from_address_list_by_source (h, LAL_HOSTNAME_DNS);
968 GNUNET_RESOLVER_hostname_resolve (AF_UNSPEC, HOSTNAME_RESOLVE_TIMEOUT,
969 &process_hostname_ip, h);
974 * Task to do DNS lookup on our external hostname to
975 * get DynDNS-IP addresses.
977 * @param cls the NAT handle
978 * @param tc scheduler context
981 resolve_dns (void *cls,
982 const struct GNUNET_SCHEDULER_TaskContext *tc)
984 struct GNUNET_NAT_Handle *h = cls;
985 struct LocalAddressList *pos;
988 for (pos = h->lal_head; NULL != pos; pos = pos->next)
989 if (pos->source == LAL_EXTERNAL_IP)
990 pos->source = LAL_EXTERNAL_IP_OLD;
991 LOG (GNUNET_ERROR_TYPE_DEBUG,
992 "Resolving external address `%s'\n",
993 h->external_address);
995 GNUNET_RESOLVER_ip_get (h->external_address, AF_INET,
996 GNUNET_TIME_UNIT_MINUTES,
997 &process_external_ip, h);
1002 * Add or remove UPnP-mapped addresses.
1004 * @param cls the `struct GNUNET_NAT_Handle`
1005 * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
1006 * the previous (now invalid) one
1007 * @param addr either the previous or the new public IP address
1008 * @param addrlen actual lenght of @a addr
1009 * @param ret GNUNET_NAT_ERROR_SUCCESS on success, otherwise an error code
1012 upnp_add (void *cls,
1014 const struct sockaddr *addr,
1016 enum GNUNET_NAT_StatusCode ret)
1018 struct GNUNET_NAT_Handle *h = cls;
1019 struct LocalAddressList *pos;
1020 struct LocalAddressList *next;
1023 if (GNUNET_NAT_ERROR_SUCCESS != ret)
1025 /* Error while running upnp client */
1026 LOG (GNUNET_ERROR_TYPE_ERROR,
1027 _("Error while running upnp client:\n"));
1029 //FIXME: convert error code to string
1034 if (GNUNET_YES == add_remove)
1036 add_to_address_list (h, LAL_UPNP, addr, addrlen);
1039 else if (GNUNET_NO == add_remove)
1041 /* remove address */
1043 while (NULL != (pos = next))
1046 if ((pos->source != LAL_UPNP) || (pos->addrlen != addrlen) ||
1047 (0 != memcmp (&pos[1], addr, addrlen)))
1049 GNUNET_CONTAINER_DLL_remove (h->lal_head, h->lal_tail, pos);
1050 if (NULL != h->address_callback)
1051 h->address_callback (h->callback_cls, GNUNET_NO,
1052 (const struct sockaddr *) &pos[1], pos->addrlen);
1054 return; /* only remove once */
1056 /* asked to remove address that does not exist */
1057 LOG (GNUNET_ERROR_TYPE_ERROR,
1058 "Asked to remove unkown address `%s'\n",
1059 GNUNET_a2s(addr, addrlen));
1071 * Try to add a port mapping using UPnP.
1073 * @param h overall NAT handle
1074 * @param port port to map with UPnP
1077 add_minis (struct GNUNET_NAT_Handle *h,
1080 struct MiniList *ml;
1085 if (port == ml->port)
1086 return; /* already got this port */
1090 ml = GNUNET_new (struct MiniList);
1092 ml->mini = GNUNET_NAT_mini_map_start (port, h->is_tcp, &upnp_add, h);
1094 if (NULL == ml->mini)
1096 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1097 _("Failed to run upnp client for port %u\n"), ml->port);
1102 GNUNET_CONTAINER_DLL_insert (h->mini_head, h->mini_tail, ml);
1107 * Task to add addresses from original bind to set of valid addrs.
1109 * @param h the NAT handle
1112 add_from_bind (struct GNUNET_NAT_Handle *h)
1114 static struct in6_addr any = IN6ADDR_ANY_INIT;
1117 struct sockaddr *sa;
1118 const struct sockaddr_in *v4;
1120 for (i = 0; i < h->num_local_addrs; i++)
1122 sa = h->local_addrs[i];
1123 switch (sa->sa_family)
1126 if (sizeof (struct sockaddr_in) != h->local_addrlens[i])
1131 v4 = (const struct sockaddr_in *) sa;
1132 if (0 != v4->sin_addr.s_addr)
1133 add_to_address_list (h,
1134 LAL_BINDTO_ADDRESS, sa,
1135 sizeof (struct sockaddr_in));
1138 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1139 "Running upnp client for address `%s'\n",
1140 GNUNET_a2s (sa,sizeof (struct sockaddr_in)));
1141 add_minis (h, ntohs (v4->sin_port));
1145 if (sizeof (struct sockaddr_in6) != h->local_addrlens[i])
1151 memcmp (&((const struct sockaddr_in6 *) sa)->sin6_addr,
1153 sizeof (struct in6_addr)))
1154 add_to_address_list (h,
1157 sizeof (struct sockaddr_in6));
1167 * Attempt to enable port redirection and detect public IP address contacting
1168 * UPnP or NAT-PMP routers on the local network. Use addr to specify to which
1169 * of the local host's addresses should the external port be mapped. The port
1170 * is taken from the corresponding sockaddr_in[6] field.
1172 * @param cfg configuration to use
1173 * @param is_tcp #GNUNET_YES for TCP, #GNUNET_NO for UDP
1174 * @param adv_port advertised port (port we are either bound to or that our OS
1175 * locally performs redirection from to our bound port).
1176 * @param num_addrs number of addresses in @a addrs
1177 * @param addrs the local addresses packets should be redirected to
1178 * @param addrlens actual lengths of the addresses
1179 * @param address_callback function to call everytime the public IP address changes
1180 * @param reversal_callback function to call if someone wants connection reversal from us
1181 * @param callback_cls closure for callbacks
1182 * @return NULL on error, otherwise handle that can be used to unregister
1184 struct GNUNET_NAT_Handle *
1185 GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg,
1188 unsigned int num_addrs,
1189 const struct sockaddr **addrs,
1190 const socklen_t *addrlens,
1191 GNUNET_NAT_AddressCallback address_callback,
1192 GNUNET_NAT_ReversalCallback reversal_callback,
1195 struct GNUNET_NAT_Handle *h;
1196 struct in_addr in_addr;
1200 LOG (GNUNET_ERROR_TYPE_DEBUG,
1201 "Registered with NAT service at port %u with %u IP bound local addresses\n",
1202 (unsigned int) adv_port, num_addrs);
1203 h = GNUNET_new (struct GNUNET_NAT_Handle);
1204 h->server_retry_delay = GNUNET_TIME_UNIT_SECONDS;
1207 h->address_callback = address_callback;
1208 h->reversal_callback = reversal_callback;
1209 h->callback_cls = callback_cls;
1210 h->num_local_addrs = num_addrs;
1211 h->adv_port = adv_port;
1214 h->local_addrs = GNUNET_malloc (num_addrs * sizeof (struct sockaddr *));
1215 h->local_addrlens = GNUNET_malloc (num_addrs * sizeof (socklen_t));
1216 for (i = 0; i < num_addrs; i++)
1218 GNUNET_assert (addrlens[i] > 0);
1219 GNUNET_assert (addrs[i] != NULL);
1220 h->local_addrlens[i] = addrlens[i];
1221 h->local_addrs[i] = GNUNET_malloc (addrlens[i]);
1222 memcpy (h->local_addrs[i], addrs[i], addrlens[i]);
1226 GNUNET_CONFIGURATION_have_value (cfg, "nat", "INTERNAL_ADDRESS"))
1228 (void) GNUNET_CONFIGURATION_get_value_string (cfg, "nat",
1230 &h->internal_address);
1232 if ((h->internal_address != NULL) &&
1233 (inet_pton (AF_INET, h->internal_address, &in_addr) != 1))
1235 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1236 "nat", "INTERNAL_ADDRESS",
1238 GNUNET_free (h->internal_address);
1239 h->internal_address = NULL;
1243 GNUNET_CONFIGURATION_have_value (cfg, "nat", "EXTERNAL_ADDRESS"))
1245 (void) GNUNET_CONFIGURATION_get_value_string (cfg, "nat",
1247 &h->external_address);
1250 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "BEHIND_NAT");
1252 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "PUNCHED_NAT");
1253 h->enable_nat_client =
1254 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "ENABLE_ICMP_CLIENT");
1255 h->enable_nat_server =
1256 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "ENABLE_ICMP_SERVER");
1258 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "ENABLE_UPNP");
1259 h->use_localaddresses =
1260 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "USE_LOCALADDR");
1261 h->return_localaddress =
1262 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat",
1263 "RETURN_LOCAL_ADDRESSES");
1266 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "USE_HOSTNAME");
1268 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "DISABLEV6");
1270 GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "DYNDNS_FREQUENCY",
1271 &h->dyndns_frequency))
1272 h->dyndns_frequency = DYNDNS_FREQUENCY;
1274 GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "IFC_SCAN_FREQUENCY",
1275 &h->ifc_scan_frequency))
1276 h->ifc_scan_frequency = IFC_SCAN_FREQUENCY;
1278 GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "HOSTNAME_DNS_FREQUENCY",
1279 &h->hostname_dns_frequency))
1280 h->hostname_dns_frequency = HOSTNAME_DNS_FREQUENCY;
1282 if (NULL == reversal_callback)
1283 h->enable_nat_server = GNUNET_NO;
1285 /* Check for UPnP client, disable immediately if not available */
1286 if ( (GNUNET_YES == h->enable_upnp) &&
1288 GNUNET_OS_check_helper_binary ("upnpc", GNUNET_NO, NULL)) )
1290 LOG (GNUNET_ERROR_TYPE_ERROR,
1291 _("UPnP enabled in configuration, but UPnP client `upnpc` command not found, disabling UPnP \n"));
1292 h->enable_upnp = GNUNET_NO;
1295 /* Check if NAT was hole-punched */
1296 if ((NULL != h->address_callback) &&
1297 (NULL != h->external_address) &&
1298 (GNUNET_YES == h->nat_punched))
1300 h->dns_task = GNUNET_SCHEDULER_add_now (&resolve_dns, h);
1301 h->enable_nat_server = GNUNET_NO;
1302 h->enable_upnp = GNUNET_NO;
1306 LOG (GNUNET_ERROR_TYPE_DEBUG,
1307 "No external IP address given to add to our list of addresses\n");
1310 /* Test for SUID binaries */
1311 binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-server");
1312 if ((h->behind_nat == GNUNET_YES) && (GNUNET_YES == h->enable_nat_server) &&
1314 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
1316 h->enable_nat_server = GNUNET_NO;
1317 LOG (GNUNET_ERROR_TYPE_WARNING,
1318 _("Configuration requires `%s', but binary is not installed properly (SUID bit not set). Option disabled.\n"),
1319 "gnunet-helper-nat-server");
1321 GNUNET_free (binary);
1322 binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-client");
1323 if ((GNUNET_YES == h->enable_nat_client) &&
1325 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
1327 h->enable_nat_client = GNUNET_NO;
1328 LOG (GNUNET_ERROR_TYPE_WARNING,
1330 ("Configuration requires `%s', but binary is not installed properly (SUID bit not set). Option disabled.\n"),
1331 "gnunet-helper-nat-client");
1333 GNUNET_free (binary);
1334 start_gnunet_nat_server (h);
1336 /* FIXME: add support for UPnP, etc */
1338 if (NULL != h->address_callback)
1342 if (GNUNET_YES == h->use_hostname)
1343 h->hostname_task = GNUNET_SCHEDULER_add_now (&resolve_hostname,
1353 * Stop port redirection and public IP address detection for the given handle.
1354 * This frees the handle, after having sent the needed commands to close open ports.
1356 * @param h the handle to stop
1359 GNUNET_NAT_unregister (struct GNUNET_NAT_Handle *h)
1362 struct LocalAddressList *lal;
1363 struct MiniList *ml;
1365 LOG (GNUNET_ERROR_TYPE_DEBUG,
1366 "NAT unregister called\n");
1367 while (NULL != (ml = h->mini_head))
1369 GNUNET_CONTAINER_DLL_remove (h->mini_head, h->mini_tail, ml);
1370 if (NULL != ml->mini)
1371 GNUNET_NAT_mini_map_stop (ml->mini);
1374 if (NULL != h->ext_dns)
1376 GNUNET_RESOLVER_request_cancel (h->ext_dns);
1379 if (NULL != h->hostname_dns)
1381 GNUNET_RESOLVER_request_cancel (h->hostname_dns);
1382 h->hostname_dns = NULL;
1384 if (NULL != h->server_read_task)
1386 GNUNET_SCHEDULER_cancel (h->server_read_task);
1387 h->server_read_task = NULL;
1389 if (NULL != h->ifc_task)
1391 GNUNET_SCHEDULER_cancel (h->ifc_task);
1394 if (NULL != h->hostname_task)
1396 GNUNET_SCHEDULER_cancel (h->hostname_task);
1397 h->hostname_task = NULL;
1399 if (NULL != h->dns_task)
1401 GNUNET_SCHEDULER_cancel (h->dns_task);
1404 if (NULL != h->server_proc)
1406 if (0 != GNUNET_OS_process_kill (h->server_proc, GNUNET_TERM_SIG))
1407 GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING, "nat", "kill");
1408 GNUNET_OS_process_wait (h->server_proc);
1409 GNUNET_OS_process_destroy (h->server_proc);
1410 h->server_proc = NULL;
1411 GNUNET_DISK_pipe_close (h->server_stdout);
1412 h->server_stdout = NULL;
1413 h->server_stdout_handle = NULL;
1415 if (NULL != h->server_stdout)
1417 GNUNET_DISK_pipe_close (h->server_stdout);
1418 h->server_stdout = NULL;
1419 h->server_stdout_handle = NULL;
1421 while (NULL != (lal = h->lal_head))
1423 GNUNET_CONTAINER_DLL_remove (h->lal_head, h->lal_tail, lal);
1424 if (NULL != h->address_callback)
1425 h->address_callback (h->callback_cls, GNUNET_NO,
1426 (const struct sockaddr *) &lal[1], lal->addrlen);
1429 for (i = 0; i < h->num_local_addrs; i++)
1430 GNUNET_free (h->local_addrs[i]);
1431 GNUNET_free_non_null (h->local_addrs);
1432 GNUNET_free_non_null (h->local_addrlens);
1433 GNUNET_free_non_null (h->external_address);
1434 GNUNET_free_non_null (h->internal_address);
1440 * We learned about a peer (possibly behind NAT) so run the
1441 * gnunet-helper-nat-client to send dummy ICMP responses to cause
1442 * that peer to connect to us (connection reversal).
1444 * @param h handle (used for configuration)
1445 * @param sa the address of the peer (IPv4-only)
1446 * @return #GNUNET_SYSERR on error, #GNUNET_NO if nat client is disabled,
1447 * #GNUNET_OK otherwise
1450 GNUNET_NAT_run_client (struct GNUNET_NAT_Handle *h,
1451 const struct sockaddr_in *sa)
1455 char inet4[INET_ADDRSTRLEN];
1456 char port_as_string[6];
1457 struct GNUNET_OS_Process *proc;
1460 if (GNUNET_YES != h->enable_nat_client)
1461 return GNUNET_NO; /* not permitted / possible */
1463 if (h->internal_address == NULL)
1465 LOG (GNUNET_ERROR_TYPE_WARNING, "nat",
1466 _("Internal IP address not known, cannot use ICMP NAT traversal method\n"));
1467 return GNUNET_SYSERR;
1469 GNUNET_assert (sa->sin_family == AF_INET);
1470 if (NULL == inet_ntop (AF_INET, &sa->sin_addr, inet4, INET_ADDRSTRLEN))
1472 GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING,
1475 return GNUNET_SYSERR;
1477 GNUNET_snprintf (port_as_string,
1478 sizeof (port_as_string),
1481 LOG (GNUNET_ERROR_TYPE_DEBUG,
1482 _("Running gnunet-helper-nat-client %s %s %u\n"),
1483 h->internal_address,
1485 (unsigned int) h->adv_port);
1486 binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-client");
1488 GNUNET_OS_start_process (GNUNET_NO, 0, NULL, NULL, NULL,
1490 "gnunet-helper-nat-client",
1491 h->internal_address,
1492 inet4, port_as_string, NULL);
1493 GNUNET_free (binary);
1495 return GNUNET_SYSERR;
1496 /* we know that the gnunet-helper-nat-client will terminate virtually
1498 GNUNET_OS_process_wait (proc);
1499 GNUNET_OS_process_destroy (proc);
1505 * Test if the given address is (currently) a plausible IP address for this peer.
1507 * @param h the handle returned by register
1508 * @param addr IP address to test (IPv4 or IPv6)
1509 * @param addrlen number of bytes in @a addr
1510 * @return #GNUNET_YES if the address is plausible,
1511 * #GNUNET_NO if the address is not plausible,
1512 * #GNUNET_SYSERR if the address is malformed
1515 GNUNET_NAT_test_address (struct GNUNET_NAT_Handle *h,
1519 struct LocalAddressList *pos;
1520 const struct sockaddr_in *in4;
1521 const struct sockaddr_in6 *in6;
1523 if ((addrlen != sizeof (struct in_addr)) &&
1524 (addrlen != sizeof (struct in6_addr)))
1527 return GNUNET_SYSERR;
1529 for (pos = h->lal_head; NULL != pos; pos = pos->next)
1531 if (pos->addrlen == sizeof (struct sockaddr_in))
1533 in4 = (struct sockaddr_in *) &pos[1];
1534 if ((addrlen == sizeof (struct in_addr)) &&
1535 (0 == memcmp (&in4->sin_addr, addr, sizeof (struct in_addr))))
1538 else if (pos->addrlen == sizeof (struct sockaddr_in6))
1540 in6 = (struct sockaddr_in6 *) &pos[1];
1541 if ((addrlen == sizeof (struct in6_addr)) &&
1542 (0 == memcmp (&in6->sin6_addr, addr, sizeof (struct in6_addr))))
1550 LOG (GNUNET_ERROR_TYPE_WARNING,
1551 "Asked to validate one of my addresses and validation failed!\n");
1556 * Converts enum GNUNET_NAT_StatusCode to a string
1558 * @param err error code to resolve to a string
1559 * @return pointer to a static string containing the error code
1562 GNUNET_NAT_status2string (enum GNUNET_NAT_StatusCode err)
1566 case GNUNET_NAT_ERROR_SUCCESS:
1567 return _ ("Operation Successful");
1568 case GNUNET_NAT_ERROR_IPC_FAILURE:
1569 return _ ("Internal Failure (IPC, ...)");
1570 case GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR:
1571 return _ ("Failure in network subsystem, check permissions.");
1572 case GNUNET_NAT_ERROR_TIMEOUT:
1573 return _ ("Encountered timeout while performing operation");
1574 case GNUNET_NAT_ERROR_NOT_ONLINE:
1575 return _ ("detected that we are offline");
1576 case GNUNET_NAT_ERROR_UPNPC_NOT_FOUND:
1577 return _ ("`upnpc` command not found");
1578 case GNUNET_NAT_ERROR_UPNPC_FAILED:
1579 return _ ("Failed to run `upnpc` command");
1580 case GNUNET_NAT_ERROR_UPNPC_TIMEOUT:
1581 return _ ("`upnpc' command took too long, process killed");
1582 case GNUNET_NAT_ERROR_UPNPC_PORTMAP_FAILED:
1583 return _ ("`upnpc' command failed to establish port mapping");
1584 case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_NOT_FOUND:
1585 return _ ("`external-ip' command not found");
1586 case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_FAILED:
1587 return _ ("Failed to run `external-ip` command");
1588 case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_OUTPUT_INVALID:
1589 return _ ("`external-ip' command output invalid");
1590 case GNUNET_NAT_ERROR_EXTERNAL_IP_ADDRESS_INVALID:
1591 return _ ("no valid address was returned by `external-ip'");
1592 case GNUNET_NAT_ERROR_NO_VALID_IF_IP_COMBO:
1593 return _ ("Could not determine interface with internal/local network address");
1594 case GNUNET_NAT_ERROR_HELPER_NAT_SERVER_NOT_FOUND:
1595 return _ ("No functioning gnunet-helper-nat-server installation found");
1596 case GNUNET_NAT_ERROR_NAT_TEST_START_FAILED:
1597 return _ ("NAT test could not be initialized");
1598 case GNUNET_NAT_ERROR_NAT_TEST_TIMEOUT:
1599 return _ ("NAT test timeout reached");
1600 case GNUNET_NAT_ERROR_NAT_REGISTER_FAILED:
1601 return _ ("could not register NAT");
1602 case GNUNET_NAT_ERROR_HELPER_NAT_CLIENT_NOT_FOUND:
1603 return _ ("No working gnunet-helper-nat-client installation found");
1607 return "unknown status code";