1 /* dns-stuff.c - DNS related code including CERT RR (rfc-4398)
2 * Copyright (C) 2003, 2005, 2006, 2009 Free Software Foundation, Inc.
3 * Copyright (C) 2005, 2006, 2009, 2015. 2016 Werner Koch
5 * This file is part of GnuPG.
7 * This file is free software; you can redistribute it and/or modify
8 * it under the terms of either
10 * - the GNU Lesser General Public License as published by the Free
11 * Software Foundation; either version 3 of the License, or (at
12 * your option) any later version.
16 * - the GNU General Public License as published by the Free
17 * Software Foundation; either version 2 of the License, or (at
18 * your option) any later version.
20 * or both in parallel, as here.
22 * This file is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, see <https://www.gnu.org/licenses/>.
32 #include <sys/types.h>
33 #ifdef HAVE_W32_SYSTEM
34 # define WIN32_LEAN_AND_MEAN
35 # ifdef HAVE_WINSOCK2_H
36 # include <winsock2.h>
39 # include <iphlpapi.h>
41 # if HAVE_SYSTEM_RESOLVER
42 # include <netinet/in.h>
43 # include <arpa/nameser.h>
49 # include <sys/stat.h>
55 /* William Ahern's DNS library, included as a source copy. */
60 /* dns.c has a dns_p_free but it is not exported. We use our own
61 * wrapper here so that we do not accidentally use xfree which would
62 * be wrong for dns.c allocated data. */
63 #define dns_free(a) free ((a))
66 #ifdef WITHOUT_NPTH /* Give the Makefile a chance to build without Pth. */
73 #include "./dirmngr-err.h"
74 #include "../common/util.h"
75 #include "../common/host2net.h"
76 #include "dirmngr-status.h"
77 #include "dns-stuff.h"
80 # define my_unprotect() npth_unprotect ()
81 # define my_protect() npth_protect ()
83 # define my_unprotect() do { } while(0)
84 # define my_protect() do { } while(0)
87 /* We allow the use of 0 instead of AF_UNSPEC - check this assumption. */
89 # error AF_UNSPEC does not have the value 0
92 /* Windows does not support the AI_ADDRCONFIG flag - use zero instead. */
94 # define AI_ADDRCONFIG 0
97 /* Not every installation has gotten around to supporting SRVs or
105 /* The standard SOCKS and TOR ports. */
106 #define SOCKS_PORT 1080
107 #define TOR_PORT 9050
108 #define TOR_PORT2 9150 /* (Used by the Tor browser) */
111 /* The default nameserver used in Tor mode. */
112 #define DEFAULT_NAMESERVER "8.8.8.8"
114 /* The default timeout in seconds for libdns requests. */
115 #define DEFAULT_TIMEOUT 30
118 #define RESOLV_CONF_NAME "/etc/resolv.conf"
120 /* Two flags to enable verbose and debug mode. */
121 static int opt_verbose;
122 static int opt_debug;
124 /* The timeout in seconds for libdns requests. */
125 static int opt_timeout;
127 /* The flag to disable IPv4 access - right now this only skips
128 * returned A records. */
129 static int opt_disable_ipv4;
131 /* The flag to disable IPv6 access - right now this only skips
132 * returned AAAA records. */
133 static int opt_disable_ipv6;
135 /* If set force the use of the standard resolver. */
136 static int standard_resolver;
138 /* If set use recursive resolver when available. */
139 static int recursive_resolver;
141 /* If set Tor mode shall be used. */
144 /* A string with the nameserver IP address used with Tor.
145 (40 should be sufficient for v6 but we add some extra for a scope.) */
146 static char tor_nameserver[40+20];
148 /* Two strings to hold the credentials presented to Tor. */
149 static char tor_socks_user[30];
150 static char tor_socks_password[20];
152 /* To avoid checking the interface too often we cache the result. */
155 unsigned int valid:1;
158 } cached_inet_support;
163 /* Libdns global data. */
166 struct dns_resolv_conf *resolv_conf;
167 struct dns_hosts *hosts;
168 struct dns_hints *hints;
170 struct sockaddr_storage socks_host;
173 /* If this flag is set, libdns shall be reinited for the next use. */
174 static int libdns_reinit_pending;
176 /* The Tor port to be used. */
177 static int libdns_tor_port;
179 #endif /*USE_LIBDNS*/
182 /* Calling this function with YES set to True forces the use of the
183 * standard resolver even if dirmngr has been built with support for
184 * an alternative resolver. */
186 enable_standard_resolver (int yes)
188 standard_resolver = yes;
192 /* Return true if the standard resolver is used. */
194 standard_resolver_p (void)
196 return standard_resolver;
200 /* Calling this function with YES switches libdns into recursive mode.
201 * It has no effect on the standard resolver. */
203 enable_recursive_resolver (int yes)
205 recursive_resolver = yes;
207 libdns_reinit_pending = 1;
212 /* Return true iff the recursive resolver is used. */
214 recursive_resolver_p (void)
217 return !standard_resolver && recursive_resolver;
224 /* Puts this module eternally into Tor mode. When called agained with
225 * NEW_CIRCUIT request a new TOR circuit for the next DNS query. */
227 enable_dns_tormode (int new_circuit)
229 if (!*tor_socks_user || new_circuit)
231 static unsigned int counter;
233 gpgrt_snprintf (tor_socks_user, sizeof tor_socks_user,
234 "dirmngr-%lu", (unsigned long)getpid ());
235 gpgrt_snprintf (tor_socks_password, sizeof tor_socks_password,
243 /* Disable tor mode. */
245 disable_dns_tormode (void)
251 /* Set verbosity and debug mode for this module. */
253 set_dns_verbose (int verbose, int debug)
255 opt_verbose = verbose;
260 /* Set the Disable-IPv4 flag so that the name resolver does not return
263 set_dns_disable_ipv4 (int yes)
265 opt_disable_ipv4 = !!yes;
269 /* Set the Disable-IPv6 flag so that the name resolver does not return
272 set_dns_disable_ipv6 (int yes)
274 opt_disable_ipv6 = !!yes;
278 /* Set the timeout for libdns requests to SECONDS. A value of 0 sets
279 * the default timeout and values are capped at 10 minutes. */
281 set_dns_timeout (int seconds)
284 seconds = DEFAULT_TIMEOUT;
285 else if (seconds < 1)
287 else if (seconds > 600)
290 opt_timeout = seconds;
294 /* Change the default IP address of the nameserver to IPADDR. The
295 address needs to be a numerical IP address and will be used for the
296 next DNS query. Note that this is only used in Tor mode. */
298 set_dns_nameserver (const char *ipaddr)
300 strncpy (tor_nameserver, ipaddr? ipaddr : DEFAULT_NAMESERVER,
301 sizeof tor_nameserver -1);
302 tor_nameserver[sizeof tor_nameserver -1] = 0;
304 libdns_reinit_pending = 1;
305 libdns_tor_port = 0; /* Start again with the default port. */
310 /* Free an addressinfo linked list as returned by resolve_dns_name. */
312 free_dns_addrinfo (dns_addrinfo_t ai)
316 dns_addrinfo_t next = ai->next;
323 #ifndef HAVE_W32_SYSTEM
324 /* Return H_ERRNO mapped to a gpg-error code. Will never return 0. */
326 get_h_errno_as_gpg_error (void)
332 case HOST_NOT_FOUND: ec = GPG_ERR_NO_NAME; break;
333 case TRY_AGAIN: ec = GPG_ERR_TRY_LATER; break;
334 case NO_RECOVERY: ec = GPG_ERR_SERVER_FAILED; break;
335 case NO_DATA: ec = GPG_ERR_NO_DATA; break;
336 default: ec = GPG_ERR_UNKNOWN_ERRNO; break;
338 return gpg_error (ec);
340 #endif /*!HAVE_W32_SYSTEM*/
343 map_eai_to_gpg_error (int ec)
349 case EAI_AGAIN: err = gpg_error (GPG_ERR_EAGAIN); break;
350 case EAI_BADFLAGS: err = gpg_error (GPG_ERR_INV_FLAG); break;
351 case EAI_FAIL: err = gpg_error (GPG_ERR_SERVER_FAILED); break;
352 case EAI_MEMORY: err = gpg_error (GPG_ERR_ENOMEM); break;
354 case EAI_NODATA: err = gpg_error (GPG_ERR_NO_DATA); break;
356 case EAI_NONAME: err = gpg_error (GPG_ERR_NO_NAME); break;
357 case EAI_SERVICE: err = gpg_error (GPG_ERR_NOT_SUPPORTED); break;
358 case EAI_FAMILY: err = gpg_error (GPG_ERR_EAFNOSUPPORT); break;
359 case EAI_SOCKTYPE: err = gpg_error (GPG_ERR_ESOCKTNOSUPPORT); break;
360 #ifndef HAVE_W32_SYSTEM
361 # ifdef EAI_ADDRFAMILY
362 case EAI_ADDRFAMILY:err = gpg_error (GPG_ERR_EADDRNOTAVAIL); break;
364 case EAI_SYSTEM: err = gpg_error_from_syserror (); break;
366 default: err = gpg_error (GPG_ERR_UNKNOWN_ERRNO); break;
374 libdns_error_to_gpg_error (int serr)
380 case 0: ec = 0; break;
382 case DNS_ENOBUFS: ec = GPG_ERR_BUFFER_TOO_SHORT; break;
383 case DNS_EILLEGAL: ec = GPG_ERR_INV_OBJ; break;
384 case DNS_EORDER: ec = GPG_ERR_INV_ORDER; break;
385 case DNS_ESECTION: ec = GPG_ERR_DNS_SECTION; break;
386 case DNS_EUNKNOWN: ec = GPG_ERR_DNS_UNKNOWN; break;
387 case DNS_EADDRESS: ec = GPG_ERR_DNS_ADDRESS; break;
388 case DNS_ENOQUERY: ec = GPG_ERR_DNS_NO_QUERY; break;
389 case DNS_ENOANSWER:ec = GPG_ERR_DNS_NO_ANSWER; break;
390 case DNS_EFETCHED: ec = GPG_ERR_ALREADY_FETCHED; break;
391 case DNS_ESERVICE: ec = GPG_ERR_NOT_SUPPORTED; break;
392 case DNS_ENONAME: ec = GPG_ERR_NO_NAME; break;
393 case DNS_EFAIL: ec = GPG_ERR_SERVER_FAILED; break;
394 case DNS_ECONNFIN: ec = GPG_ERR_DNS_CLOSED; break;
395 case DNS_EVERIFY: ec = GPG_ERR_DNS_VERIFY; break;
399 ec = gpg_err_code_from_errno (serr);
401 ec = GPG_ERR_DNS_UNKNOWN;
404 return gpg_error (ec);
406 #endif /*USE_LIBDNS*/
409 /* Return true if resolve.conf changed since it was last loaded. */
412 resolv_conf_changed_p (void)
414 #if defined(HAVE_W32_SYSTEM) || !defined(HAVE_STAT)
417 static time_t last_mtime;
418 const char *fname = RESOLV_CONF_NAME;
422 if (stat (fname, &statbuf))
424 log_error ("stat'ing '%s' failed: %s\n",
425 fname, gpg_strerror (gpg_error_from_syserror ()));
426 last_mtime = 1; /* Force a "changed" result the next time stat
429 else if (!last_mtime)
430 last_mtime = statbuf.st_mtime;
431 else if (last_mtime != statbuf.st_mtime)
434 last_mtime = statbuf.st_mtime;
440 #endif /*USE_LIBDNS*/
443 /* Initialize libdns. Returns 0 on success; prints a diagnostic and
444 * returns an error code on failure. */
446 libdns_init (ctrl_t ctrl)
452 const char *fname = NULL;
454 if (libdns.resolv_conf)
455 return 0; /* Already initialized. */
457 memset (&ld, 0, sizeof ld);
459 ld.resolv_conf = dns_resconf_open (&derr);
462 err = libdns_error_to_gpg_error (derr);
463 log_error ("failed to allocate DNS resconf object: %s\n",
470 if (!*tor_nameserver)
471 set_dns_nameserver (NULL);
473 if (!libdns_tor_port)
474 libdns_tor_port = TOR_PORT;
476 cfgstr = xtryasprintf ("[%s]:53", tor_nameserver);
478 err = gpg_error_from_syserror ();
480 err = libdns_error_to_gpg_error
481 (dns_resconf_pton (&ld.resolv_conf->nameserver[0], cfgstr));
483 log_error ("failed to set nameserver '%s': %s\n",
484 cfgstr, gpg_strerror (err));
488 ld.resolv_conf->options.tcp = DNS_RESCONF_TCP_SOCKS;
491 cfgstr = xtryasprintf ("[%s]:%d", "127.0.0.1", libdns_tor_port);
493 err = gpg_error_from_syserror ();
495 err = libdns_error_to_gpg_error
496 (dns_resconf_pton (&ld.socks_host, cfgstr));
499 log_error ("failed to set socks server '%s': %s\n",
500 cfgstr, gpg_strerror (err));
506 #ifdef HAVE_W32_SYSTEM
513 ninfo = xtrymalloc (ninfo_len);
516 err = gpg_error_from_syserror ();
520 if (GetNetworkParams (ninfo, &ninfo_len))
522 log_error ("GetNetworkParms failed: %s\n", w32_strerror (-1));
523 err = gpg_error (GPG_ERR_GENERAL);
528 for (idx=0, pip = &(ninfo->DnsServerList);
529 pip && idx < DIM (ld.resolv_conf->nameserver);
533 log_debug ("dns: dnsserver[%d] '%s'\n", idx, pip->IpAddress.String);
534 err = libdns_error_to_gpg_error
535 (dns_resconf_pton (&ld.resolv_conf->nameserver[idx],
536 pip->IpAddress.String));
538 log_error ("failed to set nameserver[%d] '%s': %s\n",
539 idx, pip->IpAddress.String, gpg_strerror (err));
547 fname = RESOLV_CONF_NAME;
548 resolv_conf_changed_p (); /* Reset timestamp. */
549 err = libdns_error_to_gpg_error
550 (dns_resconf_loadpath (ld.resolv_conf, fname));
553 log_error ("failed to load '%s': %s\n", fname, gpg_strerror (err));
557 fname = "/etc/nsswitch.conf";
558 err = libdns_error_to_gpg_error
559 (dns_nssconf_loadpath (ld.resolv_conf, fname));
562 /* This is not a fatal error: nsswitch.conf is not used on
563 * all systems; assume classic behavior instead. */
564 if (gpg_err_code (err) != GPG_ERR_ENOENT)
565 log_error ("failed to load '%s': %s\n", fname, gpg_strerror (err));
567 log_debug ("dns: fallback resolution order, files then DNS\n");
568 ld.resolv_conf->lookup[0] = 'f';
569 ld.resolv_conf->lookup[1] = 'b';
570 ld.resolv_conf->lookup[2] = '\0';
571 err = GPG_ERR_NO_ERROR;
573 else if (!strchr (ld.resolv_conf->lookup, 'b'))
575 /* No DNS resolution type found in the list. This might be
576 * due to systemd based systems which allow for custom
577 * keywords which are not known to us and thus we do not
578 * know whether DNS is wanted or not. Because DNS is
579 * important for our infrastructure, we forcefully append
580 * DNS to the end of the list. */
581 if (strlen (ld.resolv_conf->lookup)+2 < sizeof ld.resolv_conf->lookup)
584 log_debug ("dns: appending DNS to resolution order\n");
585 strcat (ld.resolv_conf->lookup, "b");
588 log_error ("failed to append DNS to resolution order\n");
594 ld.hosts = dns_hosts_open (&derr);
597 err = libdns_error_to_gpg_error (derr);
598 log_error ("failed to initialize hosts file: %s\n", gpg_strerror (err));
604 char *hosts_path = xtryasprintf ("%s\\System32\\drivers\\etc\\hosts",
605 getenv ("SystemRoot"));
608 err = gpg_error_from_syserror ();
612 derr = dns_hosts_loadpath (ld.hosts, hosts_path);
615 derr = dns_hosts_loadpath (ld.hosts, "/etc/hosts");
619 err = libdns_error_to_gpg_error (derr);
620 log_error ("failed to load hosts file: %s\n", gpg_strerror (err));
621 err = 0; /* Do not bail out - having no /etc/hosts is legal. */
625 ld.resolv_conf->options.recurse = recursive_resolver_p ();
627 /* dns_hints_local for stub mode, dns_hints_root for recursive. */
628 ld.hints = (recursive_resolver
629 ? dns_hints_root (ld.resolv_conf, &derr)
630 : dns_hints_local (ld.resolv_conf, &derr));
633 err = libdns_error_to_gpg_error (derr);
634 log_error ("failed to load DNS hints: %s\n", gpg_strerror (err));
635 fname = "[dns hints]";
639 /* All fine. Make the data global. */
643 log_debug ("dns: libdns initialized%s\n", tor_mode?" (tor mode)":"");
649 dirmngr_status_printf (ctrl, "WARNING",
650 "dns_config_problem %u"
651 " error accessing '%s': %s <%s>",
652 err, fname, gpg_strerror (err), gpg_strsource (err));
657 #endif /*USE_LIBDNS*/
661 /* Deinitialize libdns. */
667 if (!libdns.resolv_conf)
668 return; /* Not initialized. */
671 memset (&libdns, 0, sizeof libdns);
672 dns_hints_close (ld.hints);
673 dns_hosts_close (ld.hosts);
674 dns_resconf_close (ld.resolv_conf);
676 #endif /*USE_LIBDNS*/
679 /* SIGHUP action handler for this module. With FORCE set objects are
680 * all immediately released. */
682 reload_dns_stuff (int force)
688 libdns_reinit_pending = 0;
692 libdns_reinit_pending = 1;
693 libdns_tor_port = 0; /* Start again with the default port. */
699 /* We also flush the IPv4/v6 support flag cache. */
700 cached_inet_support.valid = 0;
704 /* Called from time to time from the housekeeping thread. */
706 dns_stuff_housekeeping (void)
708 /* With the current housekeeping interval of 10 minutes we flush
709 * that case so that a new or removed interface will be detected not
710 * later than 10 minutes after it changed. This way the user does
711 * not need a reload. */
712 cached_inet_support.valid = 0;
718 * Initialize libdns if needed and open a dns_resolver context.
719 * Returns 0 on success and stores the new context at R_RES. On
720 * failure an error code is returned and NULL stored at R_RES.
723 libdns_res_open (ctrl_t ctrl, struct dns_resolver **r_res)
726 struct dns_resolver *res;
728 struct dns_options opts = { 0 };
730 opts.socks_host = &libdns.socks_host;
731 opts.socks_user = tor_socks_user;
732 opts.socks_password = tor_socks_password;
736 /* Force a reload if resolv.conf has changed. */
737 if (resolv_conf_changed_p ())
740 log_debug ("dns: resolv.conf changed - forcing reload\n");
741 libdns_reinit_pending = 1;
744 if (libdns_reinit_pending)
746 libdns_reinit_pending = 0;
750 err = libdns_init (ctrl);
757 res = dns_res_open (libdns.resolv_conf, libdns.hosts, libdns.hints, NULL,
760 return libdns_error_to_gpg_error (derr);
765 #endif /*USE_LIBDNS*/
769 /* Helper to test whether we need to try again after having switched
772 libdns_switch_port_p (gpg_error_t err)
774 if (tor_mode && gpg_err_code (err) == GPG_ERR_ECONNREFUSED
775 && libdns_tor_port == TOR_PORT)
777 /* Switch port and try again. */
779 log_debug ("dns: switching from SOCKS port %d to %d\n",
780 TOR_PORT, TOR_PORT2);
781 libdns_tor_port = TOR_PORT2;
782 libdns_reinit_pending = 1;
787 #endif /*USE_LIBDNS*/
791 /* Wrapper around dns_res_submit. */
793 libdns_res_submit (struct dns_resolver *res, const char *qname,
794 enum dns_type qtype, enum dns_class qclass)
796 return libdns_error_to_gpg_error (dns_res_submit (res, qname, qtype, qclass));
798 #endif /*USE_LIBDNS*/
802 /* Standard event handling loop. */
804 libdns_res_wait (struct dns_resolver *res)
808 while ((err = libdns_error_to_gpg_error (dns_res_check (res)))
809 && gpg_err_code (err) == GPG_ERR_EAGAIN)
811 if (dns_res_elapsed (res) > opt_timeout)
813 err = gpg_error (GPG_ERR_DNS_TIMEOUT);
818 dns_res_poll (res, 1);
824 #endif /*USE_LIBDNS*/
829 resolve_name_libdns (ctrl_t ctrl, const char *name, unsigned short port,
830 int want_family, int want_socktype,
831 dns_addrinfo_t *r_dai, char **r_canonname)
834 dns_addrinfo_t daihead = NULL;
836 struct dns_resolver *res = NULL;
837 struct dns_addrinfo *ai = NULL;
838 struct addrinfo hints;
839 struct addrinfo *ent;
841 char *portstr = NULL;
842 char *namebuf = NULL;
849 memset (&hints, 0, sizeof hints);
850 hints.ai_family = want_family;
851 hints.ai_socktype = want_socktype;
852 hints.ai_flags = AI_ADDRCONFIG;
854 hints.ai_flags |= AI_CANONNAME;
858 snprintf (portstr_, sizeof portstr_, "%hu", port);
862 err = libdns_res_open (ctrl, &res);
867 if (is_ip_address (name))
869 hints.ai_flags |= AI_NUMERICHOST;
870 /* libdns does not grok brackets - remove them. */
871 if (*name == '[' && name[strlen(name)-1] == ']')
873 namebuf = xtrymalloc (strlen (name));
876 err = gpg_error_from_syserror ();
879 strcpy (namebuf, name+1);
880 namebuf[strlen (namebuf)-1] = 0;
885 ai = dns_ai_open (name, portstr, 0, &hints, res, &derr);
888 err = libdns_error_to_gpg_error (derr);
892 /* Loop over all records. */
895 err = libdns_error_to_gpg_error (dns_ai_nextent (&ent, ai));
896 if (gpg_err_code (err) == GPG_ERR_ENOENT)
899 err = 0; /* We got some results, we're good. */
902 if (gpg_err_code (err) == GPG_ERR_EAGAIN)
904 if (dns_ai_elapsed (ai) > opt_timeout)
906 err = gpg_error (GPG_ERR_DNS_TIMEOUT);
918 if (r_canonname && ! *r_canonname && ent && ent->ai_canonname)
920 *r_canonname = xtrystrdup (ent->ai_canonname);
923 err = gpg_error_from_syserror ();
926 /* Libdns appends the root zone part which is problematic
927 * for most other functions - strip it. */
928 if (**r_canonname && (*r_canonname)[strlen (*r_canonname)-1] == '.')
929 (*r_canonname)[strlen (*r_canonname)-1] = 0;
932 dai = xtrymalloc (sizeof *dai);
935 err = gpg_error_from_syserror ();
939 dai->family = ent->ai_family;
940 dai->socktype = ent->ai_socktype;
941 dai->protocol = ent->ai_protocol;
942 dai->addrlen = ent->ai_addrlen;
943 memcpy (dai->addr, ent->ai_addr, ent->ai_addrlen);
958 xfree (*r_canonname);
961 free_dns_addrinfo (daihead);
969 #endif /*USE_LIBDNS*/
972 /* Resolve a name using the standard system function. */
974 resolve_name_standard (ctrl_t ctrl, const char *name, unsigned short port,
975 int want_family, int want_socktype,
976 dns_addrinfo_t *r_dai, char **r_canonname)
979 dns_addrinfo_t daihead = NULL;
981 struct addrinfo *aibuf = NULL;
982 struct addrinfo hints, *ai;
990 memset (&hints, 0, sizeof hints);
991 hints.ai_family = want_family;
992 hints.ai_socktype = want_socktype;
993 hints.ai_flags = AI_ADDRCONFIG;
995 hints.ai_flags |= AI_CANONNAME;
996 if (is_ip_address (name))
997 hints.ai_flags |= AI_NUMERICHOST;
1000 snprintf (portstr, sizeof portstr, "%hu", port);
1004 /* We can't use the AI_IDN flag because that does the conversion
1005 using the current locale. However, GnuPG always used UTF-8. To
1006 support IDN we would need to make use of the libidn API. */
1007 ret = getaddrinfo (name, *portstr? portstr : NULL, &hints, &aibuf);
1011 err = map_eai_to_gpg_error (ret);
1012 if (gpg_err_code (err) == GPG_ERR_NO_NAME)
1014 /* There seems to be a bug in the glibc getaddrinfo function
1015 if the CNAME points to a long list of A and AAAA records
1016 in which case the function return NO_NAME. Let's do the
1017 CNAME redirection again. */
1020 if (get_dns_cname (ctrl, name, &cname))
1021 goto leave; /* Still no success. */
1023 ret = getaddrinfo (cname, *portstr? portstr : NULL, &hints, &aibuf);
1028 err = map_eai_to_gpg_error (ret);
1031 err = 0; /* Yep, now it worked. */
1037 if (r_canonname && aibuf && aibuf->ai_canonname)
1039 *r_canonname = xtrystrdup (aibuf->ai_canonname);
1042 err = gpg_error_from_syserror ();
1047 for (ai = aibuf; ai; ai = ai->ai_next)
1049 if (ai->ai_family != AF_INET6 && ai->ai_family != AF_INET)
1051 if (opt_disable_ipv4 && ai->ai_family == AF_INET)
1053 if (opt_disable_ipv6 && ai->ai_family == AF_INET6)
1056 dai = xtrymalloc (sizeof *dai);
1057 dai->family = ai->ai_family;
1058 dai->socktype = ai->ai_socktype;
1059 dai->protocol = ai->ai_protocol;
1060 dai->addrlen = ai->ai_addrlen;
1061 memcpy (dai->addr, ai->ai_addr, ai->ai_addrlen);
1062 dai->next = daihead;
1068 freeaddrinfo (aibuf);
1073 xfree (*r_canonname);
1074 *r_canonname = NULL;
1076 free_dns_addrinfo (daihead);
1084 /* This a wrapper around getaddrinfo with slightly different semantics.
1085 * NAME is the name to resolve.
1086 * PORT is the requested port or 0.
1087 * WANT_FAMILY is either 0 (AF_UNSPEC), AF_INET6, or AF_INET4.
1088 * WANT_SOCKETTYPE is either 0 for any socket type
1089 * or SOCK_STREAM or SOCK_DGRAM.
1091 * On success the result is stored in a linked list with the head
1092 * stored at the address R_AI; the caller must call free_dns_addrinfo
1093 * on this. If R_CANONNAME is not NULL the official name of the host
1094 * is stored there as a malloced string; if that name is not available
1095 * NULL is stored. */
1097 resolve_dns_name (ctrl_t ctrl, const char *name, unsigned short port,
1098 int want_family, int want_socktype,
1099 dns_addrinfo_t *r_ai, char **r_canonname)
1104 if (!standard_resolver)
1106 err = resolve_name_libdns (ctrl, name, port, want_family, want_socktype,
1108 if (err && libdns_switch_port_p (err))
1109 err = resolve_name_libdns (ctrl, name, port, want_family, want_socktype,
1113 #endif /*USE_LIBDNS*/
1114 err = resolve_name_standard (ctrl, name, port, want_family, want_socktype,
1117 log_debug ("dns: resolve_dns_name(%s): %s\n", name, gpg_strerror (err));
1123 /* Resolve an address using libdns. */
1125 resolve_addr_libdns (ctrl_t ctrl,
1126 const struct sockaddr_storage *addr, int addrlen,
1127 unsigned int flags, char **r_name)
1130 char host[DNS_D_MAXNAME + 1];
1131 struct dns_resolver *res = NULL;
1132 struct dns_packet *ans = NULL;
1138 /* First we turn ADDR into a DNS name (with ".arpa" suffix). */
1140 if (addr->ss_family == AF_INET6)
1142 const struct sockaddr_in6 *a6 = (const struct sockaddr_in6 *)addr;
1143 if (!dns_aaaa_arpa (host, sizeof host, (void*)&a6->sin6_addr))
1144 err = gpg_error (GPG_ERR_INV_OBJ);
1146 else if (addr->ss_family == AF_INET)
1148 const struct sockaddr_in *a4 = (const struct sockaddr_in *)addr;
1149 if (!dns_a_arpa (host, sizeof host, (void*)&a4->sin_addr))
1150 err = gpg_error (GPG_ERR_INV_OBJ);
1153 err = gpg_error (GPG_ERR_EAFNOSUPPORT);
1158 err = libdns_res_open (ctrl, &res);
1162 err = libdns_res_submit (res, host, DNS_T_PTR, DNS_C_IN);
1166 err = libdns_res_wait (res);
1170 ans = dns_res_fetch (res, &derr);
1173 err = libdns_error_to_gpg_error (derr);
1177 /* Check the rcode. */
1178 switch (dns_p_rcode (ans))
1180 case DNS_RC_NOERROR:
1182 case DNS_RC_NXDOMAIN:
1183 err = gpg_error (GPG_ERR_NO_NAME);
1186 err = GPG_ERR_SERVER_FAILED;
1190 /* Parse the result. */
1194 struct dns_rr_i rri;
1196 memset (&rri, 0, sizeof rri);
1197 dns_rr_i_init (&rri);
1198 rri.section = DNS_S_ALL & ~DNS_S_QD;
1200 rri.type = DNS_T_PTR;
1202 if (!dns_rr_grep (&rr, 1, &rri, ans, &derr))
1204 err = gpg_error (GPG_ERR_NOT_FOUND);
1208 err = libdns_error_to_gpg_error (dns_ptr_parse (&ptr, &rr, ans));
1213 *r_name = xtrystrdup (ptr.host);
1216 err = gpg_error_from_syserror ();
1219 /* Libdns appends the root zone part which is problematic
1220 * for most other functions - strip it. */
1221 if (**r_name && (*r_name)[strlen (*r_name)-1] == '.')
1222 (*r_name)[strlen (*r_name)-1] = 0;
1224 else /* GPG_ERR_NO_NAME */
1231 buflen = sizeof ptr.host;
1234 if (addr->ss_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1239 ec = getnameinfo ((const struct sockaddr *)addr,
1240 addrlen, p, buflen, NULL, 0, NI_NUMERICHOST);
1243 err = map_eai_to_gpg_error (ec);
1246 if (addr->ss_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1247 strcat (buffer, "]");
1252 dns_res_close (res);
1255 #endif /*USE_LIBDNS*/
1258 /* Resolve an address using the standard system function. */
1260 resolve_addr_standard (const struct sockaddr_storage *addr, int addrlen,
1261 unsigned int flags, char **r_name)
1270 buflen = NI_MAXHOST;
1271 buffer = xtrymalloc (buflen + 2 + 1);
1273 return gpg_error_from_syserror ();
1275 if ((flags & DNS_NUMERICHOST) || tor_mode)
1278 ec = getnameinfo ((const struct sockaddr *)addr,
1279 addrlen, buffer, buflen, NULL, 0, NI_NAMEREQD);
1281 if (!ec && *buffer == '[')
1282 ec = EAI_FAIL; /* A name may never start with a bracket. */
1283 else if (ec == EAI_NONAME)
1286 if (addr->ss_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1291 ec = getnameinfo ((const struct sockaddr *)addr,
1292 addrlen, p, buflen, NULL, 0, NI_NUMERICHOST);
1293 if (!ec && addr->ss_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1294 strcat (buffer, "]");
1298 err = map_eai_to_gpg_error (ec);
1301 p = xtryrealloc (buffer, strlen (buffer)+1);
1303 err = gpg_error_from_syserror ();
1320 /* A wrapper around getnameinfo. */
1322 resolve_dns_addr (ctrl_t ctrl,
1323 const struct sockaddr_storage *addr, int addrlen,
1324 unsigned int flags, char **r_name)
1329 /* Note that we divert to the standard resolver for NUMERICHOST. */
1330 if (!standard_resolver && !(flags & DNS_NUMERICHOST))
1332 err = resolve_addr_libdns (ctrl, addr, addrlen, flags, r_name);
1333 if (err && libdns_switch_port_p (err))
1334 err = resolve_addr_libdns (ctrl, addr, addrlen, flags, r_name);
1337 #endif /*USE_LIBDNS*/
1338 err = resolve_addr_standard (addr, addrlen, flags, r_name);
1341 log_debug ("dns: resolve_dns_addr(): %s\n", gpg_strerror (err));
1346 /* Check whether NAME is an IP address. Returns a true if it is
1347 * either an IPv6 or a IPv4 numerical address. The actual return
1348 * values can also be used to identify whether it is v4 or v6: The
1349 * true value will surprisingly be 4 for IPv4 and 6 for IPv6. */
1351 is_ip_address (const char *name)
1354 int ndots, dblcol, n;
1357 return 6; /* yes: A legal DNS name may not contain this character;
1358 this must be bracketed v6 address. */
1360 return 0; /* No. A leading dot is not a valid IP address. */
1362 /* Check whether this is a v6 address. */
1363 ndots = n = dblcol = 0;
1364 for (s=name; *s; s++)
1373 return 0; /* No: Only one "::" allowed. */
1382 else if (!strchr ("0123456789abcdefABCDEF", *s))
1383 return 0; /* No: Not a hex digit. */
1385 return 0; /* To many digits in a group. */
1388 return 0; /* No: Too many colons. */
1390 return 6; /* Yes: At least 2 colons indicate an v6 address. */
1393 /* Check whether it is legacy IP address. */
1395 for (s=name; *s; s++)
1400 return 0; /* No: Double dot. */
1401 if (atoi (s+1) > 255)
1402 return 0; /* No: Ipv4 byte value too large. */
1406 else if (!strchr ("0123456789", *s))
1407 return 0; /* No: Not a digit. */
1409 return 0; /* No: More than 3 digits. */
1411 return (ndots == 3)? 4 : 0;
1415 /* Return true if NAME is an onion address. */
1417 is_onion_address (const char *name)
1421 len = name? strlen (name) : 0;
1422 if (len < 8 || strcmp (name + len - 6, ".onion"))
1424 /* Note that we require at least 2 characters before the suffix. */
1425 return 1; /* Yes. */
1429 /* libdns version of get_dns_cert. */
1432 get_dns_cert_libdns (ctrl_t ctrl, const char *name, int want_certtype,
1433 void **r_key, size_t *r_keylen,
1434 unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1437 struct dns_resolver *res = NULL;
1438 struct dns_packet *ans = NULL;
1440 struct dns_rr_i rri;
1441 char host[DNS_D_MAXNAME + 1];
1445 /* Get the query type from WANT_CERTTYPE (which in general indicates
1446 * the subtype we want). */
1447 qtype = (want_certtype < DNS_CERTTYPE_RRBASE
1449 : (want_certtype - DNS_CERTTYPE_RRBASE));
1452 err = libdns_res_open (ctrl, &res);
1456 if (dns_d_anchor (host, sizeof host, name, strlen (name)) >= sizeof host)
1458 err = gpg_error (GPG_ERR_ENAMETOOLONG);
1462 err = libdns_res_submit (res, name, qtype, DNS_C_IN);
1466 err = libdns_res_wait (res);
1470 ans = dns_res_fetch (res, &derr);
1473 err = libdns_error_to_gpg_error (derr);
1477 /* Check the rcode. */
1478 switch (dns_p_rcode (ans))
1480 case DNS_RC_NOERROR: break;
1481 case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
1482 default: err = GPG_ERR_SERVER_FAILED; break;
1487 memset (&rri, 0, sizeof rri);
1488 dns_rr_i_init (&rri);
1489 rri.section = DNS_S_ALL & ~DNS_S_QD;
1493 err = gpg_error (GPG_ERR_NOT_FOUND);
1494 while (dns_rr_grep (&rr, 1, &rri, ans, &derr))
1496 unsigned char *rp = ans->data + rr.rd.p;
1497 unsigned short len = rr.rd.len;
1502 /* Definitely too short - skip. */
1504 else if (want_certtype >= DNS_CERTTYPE_RRBASE
1505 && rr.type == (want_certtype - DNS_CERTTYPE_RRBASE)
1508 *r_key = xtrymalloc (len);
1510 err = gpg_error_from_syserror ();
1513 memcpy (*r_key, rp, len);
1519 else if (want_certtype >= DNS_CERTTYPE_RRBASE)
1521 /* We did not found the requested RR - skip. */
1523 else if (rr.type == T_CERT && len > 5)
1525 /* We got a CERT type. */
1526 subtype = buf16_to_u16 (rp);
1529 /* Skip the CERT key tag and algo which we don't need. */
1532 if (want_certtype && want_certtype != subtype)
1533 ; /* Not the requested subtype - skip. */
1534 else if (subtype == DNS_CERTTYPE_PGP && len && r_key && r_keylen)
1537 *r_key = xtrymalloc (len);
1539 err = gpg_error_from_syserror ();
1542 memcpy (*r_key, rp, len);
1548 else if (subtype == DNS_CERTTYPE_IPGP
1549 && len && len < 1023 && len >= rp[0] + 1)
1555 *r_fpr = xtrymalloc (*r_fprlen);
1558 err = gpg_error_from_syserror ();
1561 memcpy (*r_fpr, rp+1, *r_fprlen);
1566 if (len > *r_fprlen + 1)
1568 *r_url = xtrymalloc (len - (*r_fprlen + 1) + 1);
1571 err = gpg_error_from_syserror ();
1576 memcpy (*r_url, rp + *r_fprlen + 1, len - (*r_fprlen + 1));
1577 (*r_url)[len - (*r_fprlen + 1)] = 0;
1587 /* Unknown subtype or record too short - skip. */
1592 /* Not a requested type - skip. */
1598 dns_res_close (res);
1601 #endif /*USE_LIBDNS*/
1604 /* Standard resolver version of get_dns_cert. */
1606 get_dns_cert_standard (const char *name, int want_certtype,
1607 void **r_key, size_t *r_keylen,
1608 unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1610 #ifdef HAVE_SYSTEM_RESOLVER
1612 unsigned char *answer;
1616 /* Allocate a 64k buffer which is the limit for an DNS response. */
1617 answer = xtrymalloc (65536);
1619 return gpg_error_from_syserror ();
1621 err = gpg_error (GPG_ERR_NOT_FOUND);
1622 r = res_query (name, C_IN,
1623 (want_certtype < DNS_CERTTYPE_RRBASE
1625 : (want_certtype - DNS_CERTTYPE_RRBASE)),
1627 /* Not too big, not too small, no errors and at least 1 answer. */
1628 if (r >= sizeof (HEADER) && r <= 65536
1629 && (((HEADER *)(void *) answer)->rcode) == NOERROR
1630 && (count = ntohs (((HEADER *)(void *) answer)->ancount)))
1633 unsigned char *pt, *emsg;
1637 pt = &answer[sizeof (HEADER)];
1639 /* Skip over the query */
1641 rc = dn_skipname (pt, emsg);
1644 err = gpg_error (GPG_ERR_INV_OBJ);
1647 pt += rc + QFIXEDSZ;
1649 /* There are several possible response types for a CERT request.
1650 We're interested in the PGP (a key) and IPGP (a URI) types.
1651 Skip all others. TODO: A key is better than a URI since
1652 we've gone through all this bother to fetch it, so favor that
1653 if we have both PGP and IPGP? */
1655 while (count-- > 0 && pt < emsg)
1657 u16 type, class, dlen, ctype;
1659 rc = dn_skipname (pt, emsg); /* the name we just queried for */
1662 err = gpg_error (GPG_ERR_INV_OBJ);
1668 /* Truncated message? 15 bytes takes us to the point where
1669 we start looking at the ctype. */
1670 if ((emsg - pt) < 15)
1673 type = buf16_to_u16 (pt);
1676 class = buf16_to_u16 (pt);
1686 dlen = buf16_to_u16 (pt);
1689 /* Check the type and parse. */
1690 if (want_certtype >= DNS_CERTTYPE_RRBASE
1691 && type == (want_certtype - DNS_CERTTYPE_RRBASE)
1694 *r_key = xtrymalloc (dlen);
1696 err = gpg_error_from_syserror ();
1699 memcpy (*r_key, pt, dlen);
1705 else if (want_certtype >= DNS_CERTTYPE_RRBASE)
1707 /* We did not found the requested RR. */
1710 else if (type == T_CERT)
1712 /* We got a CERT type. */
1713 ctype = buf16_to_u16 (pt);
1716 /* Skip the CERT key tag and algo which we don't need. */
1721 /* 15 bytes takes us to here */
1722 if (want_certtype && want_certtype != ctype)
1723 ; /* Not of the requested certtype. */
1724 else if (ctype == DNS_CERTTYPE_PGP && dlen && r_key && r_keylen)
1727 *r_key = xtrymalloc (dlen);
1729 err = gpg_error_from_syserror ();
1732 memcpy (*r_key, pt, dlen);
1738 else if (ctype == DNS_CERTTYPE_IPGP
1739 && dlen && dlen < 1023 && dlen >= pt[0] + 1)
1745 *r_fpr = xtrymalloc (*r_fprlen);
1748 err = gpg_error_from_syserror ();
1751 memcpy (*r_fpr, &pt[1], *r_fprlen);
1756 if (dlen > *r_fprlen + 1)
1758 *r_url = xtrymalloc (dlen - (*r_fprlen + 1) + 1);
1761 err = gpg_error_from_syserror ();
1766 memcpy (*r_url, &pt[*r_fprlen + 1],
1767 dlen - (*r_fprlen + 1));
1768 (*r_url)[dlen - (*r_fprlen + 1)] = '\0';
1777 /* No subtype matches, so continue with the next answer. */
1782 /* Not a requested type - might be a CNAME. Try next item. */
1792 #else /*!HAVE_SYSTEM_RESOLVER*/
1795 (void)want_certtype;
1801 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1803 #endif /*!HAVE_SYSTEM_RESOLVER*/
1807 /* Returns 0 on success or an error code. If a PGP CERT record was
1808 found, the malloced data is returned at (R_KEY, R_KEYLEN) and
1809 the other return parameters are set to NULL/0. If an IPGP CERT
1810 record was found the fingerprint is stored as an allocated block at
1811 R_FPR and its length at R_FPRLEN; an URL is allocated as a
1812 string and returned at R_URL. If WANT_CERTTYPE is 0 this function
1813 returns the first CERT found with a supported type; it is expected
1814 that only one CERT record is used. If WANT_CERTTYPE is one of the
1815 supported certtypes only records with this certtype are considered
1816 and the first found is returned. (R_KEY,R_KEYLEN) are optional. */
1818 get_dns_cert (ctrl_t ctrl, const char *name, int want_certtype,
1819 void **r_key, size_t *r_keylen,
1820 unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1833 if (!standard_resolver)
1835 err = get_dns_cert_libdns (ctrl, name, want_certtype, r_key, r_keylen,
1836 r_fpr, r_fprlen, r_url);
1837 if (err && libdns_switch_port_p (err))
1838 err = get_dns_cert_libdns (ctrl, name, want_certtype, r_key, r_keylen,
1839 r_fpr, r_fprlen, r_url);
1842 #endif /*USE_LIBDNS*/
1843 err = get_dns_cert_standard (name, want_certtype, r_key, r_keylen,
1844 r_fpr, r_fprlen, r_url);
1847 log_debug ("dns: get_dns_cert(%s): %s\n", name, gpg_strerror (err));
1853 priosort(const void *a,const void *b)
1855 const struct srventry *sa=a,*sb=b;
1856 if(sa->priority>sb->priority)
1858 else if(sa->priority<sb->priority)
1865 /* Libdns based helper for getsrv. Note that it is expected that NULL
1866 * is stored at the address of LIST and 0 is stored at the address of
1870 getsrv_libdns (ctrl_t ctrl,
1871 const char *name, struct srventry **list, unsigned int *r_count)
1874 struct dns_resolver *res = NULL;
1875 struct dns_packet *ans = NULL;
1877 struct dns_rr_i rri;
1878 char host[DNS_D_MAXNAME + 1];
1880 unsigned int srvcount = 0;
1882 err = libdns_res_open (ctrl, &res);
1886 if (dns_d_anchor (host, sizeof host, name, strlen (name)) >= sizeof host)
1888 err = gpg_error (GPG_ERR_ENAMETOOLONG);
1892 err = libdns_res_submit (res, name, DNS_T_SRV, DNS_C_IN);
1896 err = libdns_res_wait (res);
1900 ans = dns_res_fetch (res, &derr);
1903 err = libdns_error_to_gpg_error (derr);
1907 /* Check the rcode. */
1908 switch (dns_p_rcode (ans))
1910 case DNS_RC_NOERROR: break;
1911 case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
1912 default: err = GPG_ERR_SERVER_FAILED; break;
1917 memset (&rri, 0, sizeof rri);
1918 dns_rr_i_init (&rri);
1919 rri.section = DNS_S_ALL & ~DNS_S_QD;
1921 rri.type = DNS_T_SRV;
1923 while (dns_rr_grep (&rr, 1, &rri, ans, &derr))
1925 struct dns_srv dsrv;
1926 struct srventry *srv;
1927 struct srventry *newlist;
1929 err = libdns_error_to_gpg_error (dns_srv_parse(&dsrv, &rr, ans));
1933 newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));
1936 err = gpg_error_from_syserror ();
1940 memset (&(*list)[srvcount], 0, sizeof(struct srventry));
1941 srv = &(*list)[srvcount];
1943 srv->priority = dsrv.priority;
1944 srv->weight = dsrv.weight;
1945 srv->port = dsrv.port;
1946 mem2str (srv->target, dsrv.target, sizeof srv->target);
1947 /* Libdns appends the root zone part which is problematic for
1948 * most other functions - strip it. */
1949 if (*srv->target && (srv->target)[strlen (srv->target)-1] == '.')
1950 (srv->target)[strlen (srv->target)-1] = 0;
1953 *r_count = srvcount;
1962 dns_res_close (res);
1965 #endif /*USE_LIBDNS*/
1968 /* Standard resolver based helper for getsrv. Note that it is
1969 * expected that NULL is stored at the address of LIST and 0 is stored
1970 * at the address of R_COUNT. */
1972 getsrv_standard (const char *name,
1973 struct srventry **list, unsigned int *r_count)
1975 #ifdef HAVE_SYSTEM_RESOLVER
1977 unsigned char ans[2048];
1980 unsigned char *answer = res.ans;
1981 HEADER *header = res.header;
1982 unsigned char *pt, *emsg;
1985 unsigned int srvcount = 0;
1988 /* Do not allow a query using the standard resolver in Tor mode. */
1990 return gpg_error (GPG_ERR_NOT_ENABLED);
1993 r = res_query (name, C_IN, T_SRV, answer, sizeof res.ans);
1996 return get_h_errno_as_gpg_error ();
1997 if (r < sizeof (HEADER))
1998 return gpg_error (GPG_ERR_SERVER_FAILED);
1999 if (r > sizeof res.ans)
2000 return gpg_error (GPG_ERR_SYSTEM_BUG);
2001 if (header->rcode != NOERROR || !(count=ntohs (header->ancount)))
2002 return gpg_error (GPG_ERR_NO_NAME); /* Error or no record found. */
2005 pt = &answer[sizeof(HEADER)];
2007 /* Skip over the query */
2008 rc = dn_skipname (pt, emsg);
2012 pt += rc + QFIXEDSZ;
2014 while (count-- > 0 && pt < emsg)
2016 struct srventry *srv;
2018 struct srventry *newlist;
2020 newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));
2024 memset (&(*list)[srvcount], 0, sizeof(struct srventry));
2025 srv = &(*list)[srvcount];
2028 rc = dn_skipname (pt, emsg); /* The name we just queried for. */
2033 /* Truncated message? */
2037 type = buf16_to_u16 (pt);
2039 /* We asked for SRV and got something else !? */
2043 class = buf16_to_u16 (pt);
2045 /* We asked for IN and got something else !? */
2050 dlen = buf16_to_u16 (pt);
2053 srv->priority = buf16_to_ushort (pt);
2055 srv->weight = buf16_to_ushort (pt);
2057 srv->port = buf16_to_ushort (pt);
2060 /* Get the name. 2782 doesn't allow name compression, but
2061 * dn_expand still works to pull the name out of the packet. */
2062 rc = dn_expand (answer, emsg, pt, srv->target, sizeof srv->target);
2063 if (rc == 1 && srv->target[0] == 0) /* "." */
2072 /* Corrupt packet? */
2077 *r_count = srvcount;
2083 return gpg_error (GPG_ERR_GENERAL);
2085 #else /*!HAVE_SYSTEM_RESOLVER*/
2090 return gpg_error (GPG_ERR_NOT_SUPPORTED);
2092 #endif /*!HAVE_SYSTEM_RESOLVER*/
2096 /* Query a SRV record for SERVICE and PROTO for NAME. If SERVICE is
2097 * NULL, NAME is expected to contain the full query name. Note that
2098 * we do not return NONAME but simply store 0 at R_COUNT. On error an
2099 * error code is returned and 0 stored at R_COUNT. */
2101 get_dns_srv (ctrl_t ctrl,
2102 const char *name, const char *service, const char *proto,
2103 struct srventry **list, unsigned int *r_count)
2106 char *namebuffer = NULL;
2107 unsigned int srvcount;
2114 /* If SERVICE is given construct the query from it and PROTO. */
2117 namebuffer = xtryasprintf ("_%s._%s.%s",
2118 service, proto? proto:"tcp", name);
2121 err = gpg_error_from_syserror ();
2129 if (!standard_resolver)
2131 err = getsrv_libdns (ctrl, name, list, &srvcount);
2132 if (err && libdns_switch_port_p (err))
2133 err = getsrv_libdns (ctrl, name, list, &srvcount);
2136 #endif /*USE_LIBDNS*/
2137 err = getsrv_standard (name, list, &srvcount);
2141 if (gpg_err_code (err) == GPG_ERR_NO_NAME)
2146 /* Now we have an array of all the srv records. */
2148 /* Order by priority */
2149 qsort(*list,srvcount,sizeof(struct srventry),priosort);
2151 /* For each priority, move the zero-weighted items first. */
2152 for (i=0; i < srvcount; i++)
2156 for (j=i;j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)
2158 if((*list)[j].weight==0)
2163 struct srventry temp;
2165 memcpy (&temp,&(*list)[j],sizeof(struct srventry));
2166 memcpy (&(*list)[j],&(*list)[i],sizeof(struct srventry));
2167 memcpy (&(*list)[i],&temp,sizeof(struct srventry));
2175 /* Run the RFC-2782 weighting algorithm. We don't need very high
2176 quality randomness for this, so regular libc srand/rand is
2184 srand (time (NULL)*getpid());
2188 for (i=0; i < srvcount; i++)
2191 float prio_count=0,chose;
2193 for (j=i; j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)
2195 prio_count+=(*list)[j].weight;
2196 (*list)[j].run_count=prio_count;
2199 chose=prio_count*rand()/(float)RAND_MAX;
2201 for (j=i;j<srvcount && (*list)[i].priority==(*list)[j].priority;j++)
2203 if (chose<=(*list)[j].run_count)
2208 struct srventry temp;
2210 memcpy(&temp,&(*list)[j],sizeof(struct srventry));
2211 memcpy(&(*list)[j],&(*list)[i],sizeof(struct srventry));
2212 memcpy(&(*list)[i],&temp,sizeof(struct srventry));
2223 log_debug ("dns: getsrv(%s): %s\n", name, gpg_strerror (err));
2225 log_debug ("dns: getsrv(%s) -> %u records\n", name, srvcount);
2228 *r_count = srvcount;
2236 /* libdns version of get_dns_cname. */
2238 get_dns_cname_libdns (ctrl_t ctrl, const char *name, char **r_cname)
2241 struct dns_resolver *res;
2242 struct dns_packet *ans = NULL;
2243 struct dns_cname cname;
2246 err = libdns_res_open (ctrl, &res);
2250 err = libdns_res_submit (res, name, DNS_T_CNAME, DNS_C_IN);
2254 err = libdns_res_wait (res);
2258 ans = dns_res_fetch (res, &derr);
2261 err = libdns_error_to_gpg_error (derr);
2265 /* Check the rcode. */
2266 switch (dns_p_rcode (ans))
2268 case DNS_RC_NOERROR: break;
2269 case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
2270 default: err = GPG_ERR_SERVER_FAILED; break;
2275 /* Parse the result into CNAME. */
2276 err = libdns_error_to_gpg_error (dns_p_study (ans));
2280 if (!dns_d_cname (&cname, sizeof cname, name, strlen (name), ans, &derr))
2282 err = libdns_error_to_gpg_error (derr);
2287 *r_cname = xtrystrdup (cname.host);
2289 err = gpg_error_from_syserror ();
2292 /* Libdns appends the root zone part which is problematic
2293 * for most other functions - strip it. */
2294 if (**r_cname && (*r_cname)[strlen (*r_cname)-1] == '.')
2295 (*r_cname)[strlen (*r_cname)-1] = 0;
2300 dns_res_close (res);
2303 #endif /*USE_LIBDNS*/
2306 /* Standard resolver version of get_dns_cname. */
2308 get_dns_cname_standard (const char *name, char **r_cname)
2310 #ifdef HAVE_SYSTEM_RESOLVER
2314 unsigned char ans[2048];
2317 unsigned char *answer = res.ans;
2318 HEADER *header = res.header;
2319 unsigned char *pt, *emsg;
2322 int cnamesize = 1025;
2325 /* Do not allow a query using the standard resolver in Tor mode. */
2330 r = res_query (name, C_IN, T_CERT, answer, sizeof res.ans);
2333 return get_h_errno_as_gpg_error ();
2334 if (r < sizeof (HEADER))
2335 return gpg_error (GPG_ERR_SERVER_FAILED);
2336 if (r > sizeof res.ans)
2337 return gpg_error (GPG_ERR_SYSTEM_BUG);
2338 if (header->rcode != NOERROR || !(count=ntohs (header->ancount)))
2339 return gpg_error (GPG_ERR_NO_NAME); /* Error or no record found. */
2341 return gpg_error (GPG_ERR_SERVER_FAILED);
2344 pt = &answer[sizeof(HEADER)];
2345 rc = dn_skipname (pt, emsg);
2347 return gpg_error (GPG_ERR_SERVER_FAILED);
2349 pt += rc + QFIXEDSZ;
2351 return gpg_error (GPG_ERR_SERVER_FAILED);
2353 rc = dn_skipname (pt, emsg);
2355 return gpg_error (GPG_ERR_SERVER_FAILED);
2356 pt += rc + 2 + 2 + 4;
2358 return gpg_error (GPG_ERR_SERVER_FAILED);
2359 pt += 2; /* Skip rdlen */
2361 cname = xtrymalloc (cnamesize);
2363 return gpg_error_from_syserror ();
2365 rc = dn_expand (answer, emsg, pt, cname, cnamesize -1);
2369 return gpg_error (GPG_ERR_SERVER_FAILED);
2371 *r_cname = xtryrealloc (cname, strlen (cname)+1);
2374 err = gpg_error_from_syserror ();
2380 #else /*!HAVE_SYSTEM_RESOLVER*/
2384 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
2386 #endif /*!HAVE_SYSTEM_RESOLVER*/
2391 get_dns_cname (ctrl_t ctrl, const char *name, char **r_cname)
2398 if (!standard_resolver)
2400 err = get_dns_cname_libdns (ctrl, name, r_cname);
2401 if (err && libdns_switch_port_p (err))
2402 err = get_dns_cname_libdns (ctrl, name, r_cname);
2405 #endif /*USE_LIBDNS*/
2407 err = get_dns_cname_standard (name, r_cname);
2409 log_debug ("get_dns_cname(%s)%s%s\n", name,
2410 err ? ": " : " -> ",
2411 err ? gpg_strerror (err) : *r_cname);
2416 /* Check whether the machine has any usable inet devices up and
2417 * running. We put this into dns because on Windows this is
2418 * implemented using getaddrinfo and thus easiest done here. */
2420 check_inet_support (int *r_v4, int *r_v6)
2422 if (cached_inet_support.valid)
2424 *r_v4 = cached_inet_support.v4;
2425 *r_v6 = cached_inet_support.v6;
2431 #ifdef HAVE_W32_SYSTEM
2435 struct addrinfo *aibuf = NULL;
2436 struct addrinfo *ai;
2438 ret = getaddrinfo ("..localmachine", NULL, NULL, &aibuf);
2441 err = map_eai_to_gpg_error (ret);
2442 log_error ("%s: getaddrinfo failed: %s\n",__func__, gpg_strerror (err));
2446 for (ai = aibuf; ai; ai = ai->ai_next)
2450 log_debug ("%s: family: %d\n", __func__, ai->ai_family);
2451 if (ai->ai_family == AF_INET6 || ai->ai_family == AF_INET)
2455 buflen = sizeof buffer;
2456 if (WSAAddressToString (ai->ai_addr, (DWORD)ai->ai_addrlen,
2457 NULL, buffer, &buflen))
2458 log_debug ("%s: WSAAddressToString failed: ec=%u\n",
2459 __func__, (unsigned int)WSAGetLastError ());
2461 log_debug ("%s: addr: %s\n", __func__, buffer);
2466 for (ai = aibuf; ai; ai = ai->ai_next)
2468 if (ai->ai_family == AF_INET)
2471 for (ai = aibuf; ai; ai = ai->ai_next)
2473 if (ai->ai_family == AF_INET6)
2475 struct sockaddr_in6 *v6addr = (struct sockaddr_in6 *)ai->ai_addr;
2476 if (!IN6_IS_ADDR_LINKLOCAL (&v6addr->sin6_addr)
2477 && (!*r_v4 || !IN6_IS_ADDR_LOOPBACK (&v6addr->sin6_addr)))
2479 /* We only assume v6 if we do not have a v4 address or
2480 * if the address is not ::1. Linklocal never
2481 * indicates v6 support. */
2489 freeaddrinfo (aibuf);
2491 #else /*!HAVE_W32_SYSTEM*/
2493 /* For now we assume that we have both protocols. */
2496 #endif /*!HAVE_W32_SYSTEM*/
2499 log_info ("detected interfaces:%s%s\n",
2500 *r_v4? " IPv4":"", *r_v6? " IPv6":"");
2502 cached_inet_support.valid = 1;
2503 cached_inet_support.v4 = *r_v4;
2504 cached_inet_support.v6 = *r_v6;