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>
52 /* William Ahern's DNS library, included as a source copy. */
57 /* dns.c has a dns_p_free but it is not exported. We use our own
58 * wrapper here so that we do not accidentally use xfree which would
59 * be wrong for dns.c allocated data. */
60 #define dns_free(a) free ((a))
63 #ifdef WITHOUT_NPTH /* Give the Makefile a chance to build without Pth. */
70 #include "./dirmngr-err.h"
73 #include "dns-stuff.h"
76 # define my_unprotect() npth_unprotect ()
77 # define my_protect() npth_protect ()
79 # define my_unprotect() do { } while(0)
80 # define my_protect() do { } while(0)
83 /* We allow the use of 0 instead of AF_UNSPEC - check this assumption. */
85 # error AF_UNSPEC does not have the value 0
88 /* Windows does not support the AI_ADDRCONFIG flag - use zero instead. */
90 # define AI_ADDRCONFIG 0
93 /* Not every installation has gotten around to supporting SRVs or
102 /* The standard SOCKS and TOR ports. */
103 #define SOCKS_PORT 1080
104 #define TOR_PORT 9050
105 #define TOR_PORT2 9150 /* (Used by the Tor browser) */
108 /* The default nameserver used in Tor mode. */
109 #define DEFAULT_NAMESERVER "8.8.8.8"
111 /* The default timeout in seconds for libdns requests. */
112 #define DEFAULT_TIMEOUT 30
115 /* Two flags to enable verbose and debug mode. */
116 static int opt_verbose;
117 static int opt_debug;
119 /* The timeout in seconds for libdns requests. */
120 static int opt_timeout;
122 /* The flag to disable IPv4 access - right now this only skips
123 * returned A records. */
124 static int opt_disable_ipv4;
126 /* If set force the use of the standard resolver. */
127 static int standard_resolver;
129 /* If set use recursive resolver when available. */
130 static int recursive_resolver;
132 /* If set Tor mode shall be used. */
135 /* A string with the nameserver IP address used with Tor.
136 (40 should be sufficient for v6 but we add some extra for a scope.) */
137 static char tor_nameserver[40+20];
139 /* Two strings to hold the credentials presented to Tor. */
140 static char tor_socks_user[30];
141 static char tor_socks_password[20];
145 /* Libdns gobal data. */
148 struct dns_resolv_conf *resolv_conf;
149 struct dns_hosts *hosts;
150 struct dns_hints *hints;
152 struct sockaddr_storage socks_host;
155 /* If this flag is set, libdns shall be reinited for the next use. */
156 static int libdns_reinit_pending;
158 /* The Tor port to be used. */
159 static int libdns_tor_port;
161 #endif /*USE_LIBDNS*/
164 /* Calling this function with YES set to True forces the use of the
165 * standard resolver even if dirmngr has been built with support for
166 * an alternative resolver. */
168 enable_standard_resolver (int yes)
170 standard_resolver = yes;
174 /* Return true if the standard resolver is used. */
176 standard_resolver_p (void)
178 return standard_resolver;
182 /* Calling this function with YES switches libdns into recursive mode.
183 * It has no effect on the standard resolver. */
185 enable_recursive_resolver (int yes)
187 recursive_resolver = yes;
189 libdns_reinit_pending = 1;
194 /* Return true iff the recursive resolver is used. */
196 recursive_resolver_p (void)
199 return !standard_resolver && recursive_resolver;
206 /* Puts this module eternally into Tor mode. When called agained with
207 * NEW_CIRCUIT request a new TOR circuit for the next DNS query. */
209 enable_dns_tormode (int new_circuit)
211 if (!*tor_socks_user || new_circuit)
213 static unsigned int counter;
215 gpgrt_snprintf (tor_socks_user, sizeof tor_socks_user,
216 "dirmngr-%lu", (unsigned long)getpid ());
217 gpgrt_snprintf (tor_socks_password, sizeof tor_socks_password,
225 /* Disable tor mode. */
227 disable_dns_tormode (void)
233 /* Set verbosity and debug mode for this module. */
235 set_dns_verbose (int verbose, int debug)
237 opt_verbose = verbose;
242 /* Set the Disable-IPv4 flag so that the name resolver does not return
245 set_dns_disable_ipv4 (int yes)
247 opt_disable_ipv4 = !!yes;
251 /* Set the timeout for libdns requests to SECONDS. A value of 0 sets
252 * the default timeout and values are capped at 10 minutes. */
254 set_dns_timeout (int seconds)
257 seconds = DEFAULT_TIMEOUT;
258 else if (seconds < 1)
260 else if (seconds > 600)
263 opt_timeout = seconds;
267 /* Change the default IP address of the nameserver to IPADDR. The
268 address needs to be a numerical IP address and will be used for the
269 next DNS query. Note that this is only used in Tor mode. */
271 set_dns_nameserver (const char *ipaddr)
273 strncpy (tor_nameserver, ipaddr? ipaddr : DEFAULT_NAMESERVER,
274 sizeof tor_nameserver -1);
275 tor_nameserver[sizeof tor_nameserver -1] = 0;
277 libdns_reinit_pending = 1;
278 libdns_tor_port = 0; /* Start again with the default port. */
283 /* Free an addressinfo linked list as returned by resolve_dns_name. */
285 free_dns_addrinfo (dns_addrinfo_t ai)
289 dns_addrinfo_t next = ai->next;
296 #ifndef HAVE_W32_SYSTEM
297 /* Return H_ERRNO mapped to a gpg-error code. Will never return 0. */
299 get_h_errno_as_gpg_error (void)
305 case HOST_NOT_FOUND: ec = GPG_ERR_NO_NAME; break;
306 case TRY_AGAIN: ec = GPG_ERR_TRY_LATER; break;
307 case NO_RECOVERY: ec = GPG_ERR_SERVER_FAILED; break;
308 case NO_DATA: ec = GPG_ERR_NO_DATA; break;
309 default: ec = GPG_ERR_UNKNOWN_ERRNO; break;
311 return gpg_error (ec);
313 #endif /*!HAVE_W32_SYSTEM*/
316 map_eai_to_gpg_error (int ec)
322 case EAI_AGAIN: err = gpg_error (GPG_ERR_EAGAIN); break;
323 case EAI_BADFLAGS: err = gpg_error (GPG_ERR_INV_FLAG); break;
324 case EAI_FAIL: err = gpg_error (GPG_ERR_SERVER_FAILED); break;
325 case EAI_MEMORY: err = gpg_error (GPG_ERR_ENOMEM); break;
327 case EAI_NODATA: err = gpg_error (GPG_ERR_NO_DATA); break;
329 case EAI_NONAME: err = gpg_error (GPG_ERR_NO_NAME); break;
330 case EAI_SERVICE: err = gpg_error (GPG_ERR_NOT_SUPPORTED); break;
331 case EAI_FAMILY: err = gpg_error (GPG_ERR_EAFNOSUPPORT); break;
332 case EAI_SOCKTYPE: err = gpg_error (GPG_ERR_ESOCKTNOSUPPORT); break;
333 #ifndef HAVE_W32_SYSTEM
334 # ifdef EAI_ADDRFAMILY
335 case EAI_ADDRFAMILY:err = gpg_error (GPG_ERR_EADDRNOTAVAIL); break;
337 case EAI_SYSTEM: err = gpg_error_from_syserror (); break;
339 default: err = gpg_error (GPG_ERR_UNKNOWN_ERRNO); break;
347 libdns_error_to_gpg_error (int serr)
353 case 0: ec = 0; break;
355 case DNS_ENOBUFS: ec = GPG_ERR_BUFFER_TOO_SHORT; break;
356 case DNS_EILLEGAL: ec = GPG_ERR_INV_OBJ; break;
357 case DNS_EORDER: ec = GPG_ERR_INV_ORDER; break;
358 case DNS_ESECTION: ec = GPG_ERR_DNS_SECTION; break;
359 case DNS_EUNKNOWN: ec = GPG_ERR_DNS_UNKNOWN; break;
360 case DNS_EADDRESS: ec = GPG_ERR_DNS_ADDRESS; break;
361 case DNS_ENOQUERY: ec = GPG_ERR_DNS_NO_QUERY; break;
362 case DNS_ENOANSWER:ec = GPG_ERR_DNS_NO_ANSWER; break;
363 case DNS_EFETCHED: ec = GPG_ERR_ALREADY_FETCHED; break;
364 case DNS_ESERVICE: ec = GPG_ERR_NOT_SUPPORTED; break;
365 case DNS_ENONAME: ec = GPG_ERR_NO_NAME; break;
366 case DNS_EFAIL: ec = GPG_ERR_SERVER_FAILED; break;
367 case DNS_ECONNFIN: ec = GPG_ERR_DNS_CLOSED; break;
368 case DNS_EVERIFY: ec = GPG_ERR_DNS_VERIFY; break;
372 ec = gpg_err_code_from_errno (serr);
374 ec = GPG_ERR_DNS_UNKNOWN;
377 return gpg_error (ec);
379 #endif /*USE_LIBDNS*/
383 /* Initialize libdns. Returns 0 on success; prints a diagnostic and
384 * returns an error code on failure. */
393 if (libdns.resolv_conf)
394 return 0; /* Already initialized. */
396 memset (&ld, 0, sizeof ld);
398 ld.resolv_conf = dns_resconf_open (&derr);
401 err = libdns_error_to_gpg_error (derr);
402 log_error ("failed to allocate DNS resconf object: %s\n",
409 if (!*tor_nameserver)
410 set_dns_nameserver (NULL);
412 if (!libdns_tor_port)
413 libdns_tor_port = TOR_PORT;
415 cfgstr = xtryasprintf ("[%s]:53", tor_nameserver);
417 err = gpg_error_from_syserror ();
419 err = libdns_error_to_gpg_error
420 (dns_resconf_pton (&ld.resolv_conf->nameserver[0], cfgstr));
422 log_error ("failed to set nameserver '%s': %s\n",
423 cfgstr, gpg_strerror (err));
427 ld.resolv_conf->options.tcp = DNS_RESCONF_TCP_SOCKS;
430 cfgstr = xtryasprintf ("[%s]:%d", "127.0.0.1", libdns_tor_port);
432 err = gpg_error_from_syserror ();
434 err = libdns_error_to_gpg_error
435 (dns_resconf_pton (&ld.socks_host, cfgstr));
438 log_error ("failed to set socks server '%s': %s\n",
439 cfgstr, gpg_strerror (err));
445 #ifdef HAVE_W32_SYSTEM
452 ninfo = xtrymalloc (ninfo_len);
455 err = gpg_error_from_syserror ();
459 if (GetNetworkParams (ninfo, &ninfo_len))
461 log_error ("GetNetworkParms failed: %s\n", w32_strerror (-1));
462 err = gpg_error (GPG_ERR_GENERAL);
467 for (idx=0, pip = &(ninfo->DnsServerList);
468 pip && idx < DIM (ld.resolv_conf->nameserver);
472 log_debug ("dns: dnsserver[%d] '%s'\n", idx, pip->IpAddress.String);
473 err = libdns_error_to_gpg_error
474 (dns_resconf_pton (&ld.resolv_conf->nameserver[idx],
475 pip->IpAddress.String));
477 log_error ("failed to set nameserver[%d] '%s': %s\n",
478 idx, pip->IpAddress.String, gpg_strerror (err));
487 fname = "/etc/resolv.conf";
488 err = libdns_error_to_gpg_error
489 (dns_resconf_loadpath (ld.resolv_conf, fname));
492 log_error ("failed to load '%s': %s\n", fname, gpg_strerror (err));
496 fname = "/etc/nsswitch.conf";
497 err = libdns_error_to_gpg_error
498 (dns_nssconf_loadpath (ld.resolv_conf, fname));
501 /* This is not a fatal error: nsswitch.conf is not used on
502 * all systems; assume classic behavior instead. */
503 if (gpg_err_code (err) != GPG_ERR_ENOENT)
504 log_error ("failed to load '%s': %s\n", fname, gpg_strerror (err));
506 log_debug ("dns: fallback resolution order, files then DNS\n");
507 ld.resolv_conf->lookup[0] = 'f';
508 ld.resolv_conf->lookup[1] = 'b';
509 ld.resolv_conf->lookup[2] = '\0';
510 err = GPG_ERR_NO_ERROR;
512 else if (!strchr (ld.resolv_conf->lookup, 'b'))
514 /* No DNS resulution type found in the list. This might be
515 * due to systemd based systems which allow for custom
516 * keywords which are not known to us and thus we do not
517 * know whether DNS is wanted or not. Becuase DNS is
518 * important for our infrastructure, we forcefully append
519 * DNS to the end of the list. */
520 if (strlen (ld.resolv_conf->lookup)+2 < sizeof ld.resolv_conf->lookup)
523 log_debug ("dns: appending DNS to resolution order\n");
524 strcat (ld.resolv_conf->lookup, "b");
527 log_error ("failed to append DNS to resolution order\n");
533 ld.hosts = dns_hosts_open (&derr);
536 err = libdns_error_to_gpg_error (derr);
537 log_error ("failed to initialize hosts file: %s\n", gpg_strerror (err));
544 char *hosts_path = xtryasprintf ("%s\System32\drivers\etc\hosts",
545 getenv ("SystemRoot"));
548 err = gpg_error_from_syserror ();
552 derr = dns_hosts_loadpath (ld.hosts, hosts_path);
555 derr = dns_hosts_loadpath (ld.hosts, "/etc/hosts");
559 err = libdns_error_to_gpg_error (derr);
560 log_error ("failed to load hosts file: %s\n", gpg_strerror (err));
565 /* dns_hints_local for stub mode, dns_hints_root for recursive. */
566 ld.hints = (recursive_resolver
567 ? dns_hints_root (ld.resolv_conf, &derr)
568 : dns_hints_local (ld.resolv_conf, &derr));
571 log_error ("failed to load DNS hints: %s\n", gpg_strerror (err));
572 err = libdns_error_to_gpg_error (derr);
576 /* All fine. Make the data global. */
580 log_debug ("dns: libdns initialized%s\n", tor_mode?" (tor mode)":"");
586 #endif /*USE_LIBDNS*/
590 /* Deinitialize libdns. */
596 if (!libdns.resolv_conf)
597 return; /* Not initialized. */
600 memset (&libdns, 0, sizeof libdns);
601 dns_hints_close (ld.hints);
602 dns_hosts_close (ld.hosts);
603 dns_resconf_close (ld.resolv_conf);
605 #endif /*USE_LIBDNS*/
608 /* SIGHUP action handler for this module. With FORCE set objects are
609 * all immediately released. */
611 reload_dns_stuff (int force)
617 libdns_reinit_pending = 0;
621 libdns_reinit_pending = 1;
622 libdns_tor_port = 0; /* Start again with the default port. */
632 * Initialize libdns if needed and open a dns_resolver context.
633 * Returns 0 on success and stores the new context at R_RES. On
634 * failure an error code is returned and NULL stored at R_RES.
637 libdns_res_open (struct dns_resolver **r_res)
640 struct dns_resolver *res;
645 if (libdns_reinit_pending)
647 libdns_reinit_pending = 0;
651 err = libdns_init ();
658 res = dns_res_open (libdns.resolv_conf, libdns.hosts, libdns.hints, NULL,
659 dns_opts (.socks_host = &libdns.socks_host,
660 .socks_user = tor_socks_user,
661 .socks_password = tor_socks_password ),
664 return libdns_error_to_gpg_error (derr);
669 #endif /*USE_LIBDNS*/
673 /* Helper to test whether we need to try again after having switched
676 libdns_switch_port_p (gpg_error_t err)
678 if (tor_mode && gpg_err_code (err) == GPG_ERR_ECONNREFUSED
679 && libdns_tor_port == TOR_PORT)
681 /* Switch port and try again. */
683 log_debug ("dns: switching from SOCKS port %d to %d\n",
684 TOR_PORT, TOR_PORT2);
685 libdns_tor_port = TOR_PORT2;
686 libdns_reinit_pending = 1;
691 #endif /*USE_LIBDNS*/
695 /* Wrapper around dns_res_submit. */
697 libdns_res_submit (struct dns_resolver *res, const char *qname,
698 enum dns_type qtype, enum dns_class qclass)
700 return libdns_error_to_gpg_error (dns_res_submit (res, qname, qtype, qclass));
702 #endif /*USE_LIBDNS*/
706 /* Standard event handling loop. */
708 libdns_res_wait (struct dns_resolver *res)
712 while ((err = libdns_error_to_gpg_error (dns_res_check (res)))
713 && gpg_err_code (err) == GPG_ERR_EAGAIN)
715 if (dns_res_elapsed (res) > opt_timeout)
717 err = gpg_error (GPG_ERR_DNS_TIMEOUT);
722 dns_res_poll (res, 1);
728 #endif /*USE_LIBDNS*/
733 resolve_name_libdns (const char *name, unsigned short port,
734 int want_family, int want_socktype,
735 dns_addrinfo_t *r_dai, char **r_canonname)
738 dns_addrinfo_t daihead = NULL;
740 struct dns_resolver *res = NULL;
741 struct dns_addrinfo *ai = NULL;
742 struct addrinfo hints;
743 struct addrinfo *ent;
745 char *portstr = NULL;
752 memset (&hints, 0, sizeof hints);
753 hints.ai_family = want_family;
754 hints.ai_socktype = want_socktype;
755 hints.ai_flags = AI_ADDRCONFIG;
757 hints.ai_flags |= AI_CANONNAME;
758 if (is_ip_address (name))
759 hints.ai_flags |= AI_NUMERICHOST;
763 snprintf (portstr_, sizeof portstr_, "%hu", port);
767 err = libdns_res_open (&res);
771 ai = dns_ai_open (name, portstr, 0, &hints, res, &derr);
774 err = libdns_error_to_gpg_error (derr);
778 /* Loop over all records. */
781 err = libdns_error_to_gpg_error (dns_ai_nextent (&ent, ai));
782 if (gpg_err_code (err) == GPG_ERR_ENOENT)
785 err = 0; /* We got some results, we're good. */
788 if (gpg_err_code (err) == GPG_ERR_EAGAIN)
790 if (dns_ai_elapsed (ai) > opt_timeout)
792 err = gpg_error (GPG_ERR_DNS_TIMEOUT);
804 if (r_canonname && ! *r_canonname && ent && ent->ai_canonname)
806 *r_canonname = xtrystrdup (ent->ai_canonname);
809 err = gpg_error_from_syserror ();
812 /* Libdns appends the root zone part which is problematic
813 * for most other functions - strip it. */
814 if (**r_canonname && (*r_canonname)[strlen (*r_canonname)-1] == '.')
815 (*r_canonname)[strlen (*r_canonname)-1] = 0;
818 dai = xtrymalloc (sizeof *dai + ent->ai_addrlen -1);
821 err = gpg_error_from_syserror ();
825 dai->family = ent->ai_family;
826 dai->socktype = ent->ai_socktype;
827 dai->protocol = ent->ai_protocol;
828 dai->addrlen = ent->ai_addrlen;
829 memcpy (dai->addr, ent->ai_addr, ent->ai_addrlen);
844 xfree (*r_canonname);
847 free_dns_addrinfo (daihead);
854 #endif /*USE_LIBDNS*/
857 /* Resolve a name using the standard system function. */
859 resolve_name_standard (const char *name, unsigned short port,
860 int want_family, int want_socktype,
861 dns_addrinfo_t *r_dai, char **r_canonname)
864 dns_addrinfo_t daihead = NULL;
866 struct addrinfo *aibuf = NULL;
867 struct addrinfo hints, *ai;
875 memset (&hints, 0, sizeof hints);
876 hints.ai_family = want_family;
877 hints.ai_socktype = want_socktype;
878 hints.ai_flags = AI_ADDRCONFIG;
880 hints.ai_flags |= AI_CANONNAME;
881 if (is_ip_address (name))
882 hints.ai_flags |= AI_NUMERICHOST;
885 snprintf (portstr, sizeof portstr, "%hu", port);
889 /* We can't use the the AI_IDN flag because that does the conversion
890 using the current locale. However, GnuPG always used UTF-8. To
891 support IDN we would need to make use of the libidn API. */
892 ret = getaddrinfo (name, *portstr? portstr : NULL, &hints, &aibuf);
896 err = map_eai_to_gpg_error (ret);
897 if (gpg_err_code (err) == GPG_ERR_NO_NAME)
899 /* There seems to be a bug in the glibc getaddrinfo function
900 if the CNAME points to a long list of A and AAAA records
901 in which case the function return NO_NAME. Let's do the
902 CNAME redirection again. */
905 if (get_dns_cname (name, &cname))
906 goto leave; /* Still no success. */
908 ret = getaddrinfo (cname, *portstr? portstr : NULL, &hints, &aibuf);
913 err = map_eai_to_gpg_error (ret);
916 err = 0; /* Yep, now it worked. */
922 if (r_canonname && aibuf && aibuf->ai_canonname)
924 *r_canonname = xtrystrdup (aibuf->ai_canonname);
927 err = gpg_error_from_syserror ();
932 for (ai = aibuf; ai; ai = ai->ai_next)
934 if (ai->ai_family != AF_INET6 && ai->ai_family != AF_INET)
936 if (opt_disable_ipv4 && ai->ai_family == AF_INET)
939 dai = xtrymalloc (sizeof *dai + ai->ai_addrlen - 1);
940 dai->family = ai->ai_family;
941 dai->socktype = ai->ai_socktype;
942 dai->protocol = ai->ai_protocol;
943 dai->addrlen = ai->ai_addrlen;
944 memcpy (dai->addr, ai->ai_addr, ai->ai_addrlen);
951 freeaddrinfo (aibuf);
956 xfree (*r_canonname);
959 free_dns_addrinfo (daihead);
967 /* This a wrapper around getaddrinfo with slightly different semantics.
968 NAME is the name to resolve.
969 PORT is the requested port or 0.
970 WANT_FAMILY is either 0 (AF_UNSPEC), AF_INET6, or AF_INET4.
971 WANT_SOCKETTYPE is either SOCK_STREAM or SOCK_DGRAM.
973 On success the result is stored in a linked list with the head
974 stored at the address R_AI; the caller must call gpg_addrinfo_free
975 on this. If R_CANONNAME is not NULL the official name of the host
976 is stored there as a malloced string; if that name is not available
979 resolve_dns_name (const char *name, unsigned short port,
980 int want_family, int want_socktype,
981 dns_addrinfo_t *r_ai, char **r_canonname)
986 if (!standard_resolver)
988 err = resolve_name_libdns (name, port, want_family, want_socktype,
990 if (err && libdns_switch_port_p (err))
991 err = resolve_name_libdns (name, port, want_family, want_socktype,
995 #endif /*USE_LIBDNS*/
996 err = resolve_name_standard (name, port, want_family, want_socktype,
999 log_debug ("dns: resolve_dns_name(%s): %s\n", name, gpg_strerror (err));
1005 /* Resolve an address using libdns. */
1007 resolve_addr_libdns (const struct sockaddr *addr, int addrlen,
1008 unsigned int flags, char **r_name)
1011 char host[DNS_D_MAXNAME + 1];
1012 struct dns_resolver *res = NULL;
1013 struct dns_packet *ans = NULL;
1019 /* First we turn ADDR into a DNS name (with ".arpa" suffix). */
1021 if (addr->sa_family == AF_INET6)
1023 const struct sockaddr_in6 *a6 = (const struct sockaddr_in6 *)addr;
1024 if (!dns_aaaa_arpa (host, sizeof host, (void*)&a6->sin6_addr))
1025 err = gpg_error (GPG_ERR_INV_OBJ);
1027 else if (addr->sa_family == AF_INET)
1029 const struct sockaddr_in *a4 = (const struct sockaddr_in *)addr;
1030 if (!dns_a_arpa (host, sizeof host, (void*)&a4->sin_addr))
1031 err = gpg_error (GPG_ERR_INV_OBJ);
1034 err = gpg_error (GPG_ERR_EAFNOSUPPORT);
1039 err = libdns_res_open (&res);
1043 err = libdns_res_submit (res, host, DNS_T_PTR, DNS_C_IN);
1047 err = libdns_res_wait (res);
1051 ans = dns_res_fetch (res, &derr);
1054 err = libdns_error_to_gpg_error (derr);
1058 /* Check the rcode. */
1059 switch (dns_p_rcode (ans))
1061 case DNS_RC_NOERROR:
1063 case DNS_RC_NXDOMAIN:
1064 err = gpg_error (GPG_ERR_NO_NAME);
1067 err = GPG_ERR_SERVER_FAILED;
1071 /* Parse the result. */
1075 struct dns_rr_i rri;
1077 memset (&rri, 0, sizeof rri);
1078 dns_rr_i_init (&rri, ans);
1079 rri.section = DNS_S_ALL & ~DNS_S_QD;
1081 rri.type = DNS_T_PTR;
1083 if (!dns_rr_grep (&rr, 1, &rri, ans, &derr))
1085 err = gpg_error (GPG_ERR_NOT_FOUND);
1089 err = libdns_error_to_gpg_error (dns_ptr_parse (&ptr, &rr, ans));
1094 *r_name = xtrystrdup (ptr.host);
1097 err = gpg_error_from_syserror ();
1100 /* Libdns appends the root zone part which is problematic
1101 * for most other functions - strip it. */
1102 if (**r_name && (*r_name)[strlen (*r_name)-1] == '.')
1103 (*r_name)[strlen (*r_name)-1] = 0;
1105 else /* GPG_ERR_NO_NAME */
1112 buflen = sizeof ptr.host;
1115 if (addr->sa_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1120 ec = getnameinfo (addr, addrlen, p, buflen, NULL, 0, NI_NUMERICHOST);
1123 err = map_eai_to_gpg_error (ec);
1126 if (addr->sa_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1127 strcat (buffer, "]");
1132 dns_res_close (res);
1135 #endif /*USE_LIBDNS*/
1138 /* Resolve an address using the standard system function. */
1140 resolve_addr_standard (const struct sockaddr *addr, int addrlen,
1141 unsigned int flags, char **r_name)
1150 buflen = NI_MAXHOST;
1151 buffer = xtrymalloc (buflen + 2 + 1);
1153 return gpg_error_from_syserror ();
1155 if ((flags & DNS_NUMERICHOST) || tor_mode)
1158 ec = getnameinfo (addr, addrlen, buffer, buflen, NULL, 0, NI_NAMEREQD);
1160 if (!ec && *buffer == '[')
1161 ec = EAI_FAIL; /* A name may never start with a bracket. */
1162 else if (ec == EAI_NONAME)
1165 if (addr->sa_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1170 ec = getnameinfo (addr, addrlen, p, buflen, NULL, 0, NI_NUMERICHOST);
1171 if (!ec && addr->sa_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1172 strcat (buffer, "]");
1176 err = map_eai_to_gpg_error (ec);
1179 p = xtryrealloc (buffer, strlen (buffer)+1);
1181 err = gpg_error_from_syserror ();
1198 /* A wrapper around getnameinfo. */
1200 resolve_dns_addr (const struct sockaddr *addr, int addrlen,
1201 unsigned int flags, char **r_name)
1206 /* Note that we divert to the standard resolver for NUMERICHOST. */
1207 if (!standard_resolver && !(flags & DNS_NUMERICHOST))
1209 err = resolve_addr_libdns (addr, addrlen, flags, r_name);
1210 if (err && libdns_switch_port_p (err))
1211 err = resolve_addr_libdns (addr, addrlen, flags, r_name);
1214 #endif /*USE_LIBDNS*/
1215 err = resolve_addr_standard (addr, addrlen, flags, r_name);
1218 log_debug ("dns: resolve_dns_addr(): %s\n", gpg_strerror (err));
1223 /* Check whether NAME is an IP address. Returns a true if it is
1224 * either an IPv6 or a IPv4 numerical address. The actual return
1225 * values can also be used to identify whether it is v4 or v6: The
1226 * true value will surprisingly be 4 for IPv4 and 6 for IPv6. */
1228 is_ip_address (const char *name)
1231 int ndots, dblcol, n;
1234 return 6; /* yes: A legal DNS name may not contain this character;
1235 this mut be bracketed v6 address. */
1237 return 0; /* No. A leading dot is not a valid IP address. */
1239 /* Check whether this is a v6 address. */
1240 ndots = n = dblcol = 0;
1241 for (s=name; *s; s++)
1250 return 0; /* No: Only one "::" allowed. */
1259 else if (!strchr ("0123456789abcdefABCDEF", *s))
1260 return 0; /* No: Not a hex digit. */
1262 return 0; /* To many digits in a group. */
1265 return 0; /* No: Too many colons. */
1267 return 6; /* Yes: At least 2 colons indicate an v6 address. */
1270 /* Check whether it is legacy IP address. */
1272 for (s=name; *s; s++)
1277 return 0; /* No: Douple dot. */
1278 if (atoi (s+1) > 255)
1279 return 0; /* No: Ipv4 byte value too large. */
1283 else if (!strchr ("0123456789", *s))
1284 return 0; /* No: Not a digit. */
1286 return 0; /* No: More than 3 digits. */
1288 return (ndots == 3)? 4 : 0;
1292 /* Return true if NAME is an onion address. */
1294 is_onion_address (const char *name)
1298 len = name? strlen (name) : 0;
1299 if (len < 8 || strcmp (name + len - 6, ".onion"))
1301 /* Note that we require at least 2 characters before the suffix. */
1302 return 1; /* Yes. */
1306 /* libdns version of get_dns_cert. */
1309 get_dns_cert_libdns (const char *name, int want_certtype,
1310 void **r_key, size_t *r_keylen,
1311 unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1314 struct dns_resolver *res = NULL;
1315 struct dns_packet *ans = NULL;
1317 struct dns_rr_i rri;
1318 char host[DNS_D_MAXNAME + 1];
1322 /* Get the query type from WANT_CERTTYPE (which in general indicates
1323 * the subtype we want). */
1324 qtype = (want_certtype < DNS_CERTTYPE_RRBASE
1326 : (want_certtype - DNS_CERTTYPE_RRBASE));
1329 err = libdns_res_open (&res);
1333 if (dns_d_anchor (host, sizeof host, name, strlen (name)) >= sizeof host)
1335 err = gpg_error (GPG_ERR_ENAMETOOLONG);
1339 err = libdns_res_submit (res, name, qtype, DNS_C_IN);
1343 err = libdns_res_wait (res);
1347 ans = dns_res_fetch (res, &derr);
1350 err = libdns_error_to_gpg_error (derr);
1354 /* Check the rcode. */
1355 switch (dns_p_rcode (ans))
1357 case DNS_RC_NOERROR: break;
1358 case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
1359 default: err = GPG_ERR_SERVER_FAILED; break;
1364 memset (&rri, 0, sizeof rri);
1365 dns_rr_i_init (&rri, ans);
1366 rri.section = DNS_S_ALL & ~DNS_S_QD;
1370 err = gpg_error (GPG_ERR_NOT_FOUND);
1371 while (dns_rr_grep (&rr, 1, &rri, ans, &derr))
1373 unsigned char *rp = ans->data + rr.rd.p;
1374 unsigned short len = rr.rd.len;
1379 /* Definitely too short - skip. */
1381 else if (want_certtype >= DNS_CERTTYPE_RRBASE
1382 && rr.type == (want_certtype - DNS_CERTTYPE_RRBASE)
1385 *r_key = xtrymalloc (len);
1387 err = gpg_error_from_syserror ();
1390 memcpy (*r_key, rp, len);
1396 else if (want_certtype >= DNS_CERTTYPE_RRBASE)
1398 /* We did not found the requested RR - skip. */
1400 else if (rr.type == T_CERT && len > 5)
1402 /* We got a CERT type. */
1403 subtype = buf16_to_u16 (rp);
1406 /* Skip the CERT key tag and algo which we don't need. */
1409 if (want_certtype && want_certtype != subtype)
1410 ; /* Not the requested subtype - skip. */
1411 else if (subtype == DNS_CERTTYPE_PGP && len && r_key && r_keylen)
1414 *r_key = xtrymalloc (len);
1416 err = gpg_error_from_syserror ();
1419 memcpy (*r_key, rp, len);
1425 else if (subtype == DNS_CERTTYPE_IPGP
1426 && len && len < 1023 && len >= rp[0] + 1)
1432 *r_fpr = xtrymalloc (*r_fprlen);
1435 err = gpg_error_from_syserror ();
1438 memcpy (*r_fpr, rp+1, *r_fprlen);
1443 if (len > *r_fprlen + 1)
1445 *r_url = xtrymalloc (len - (*r_fprlen + 1) + 1);
1448 err = gpg_error_from_syserror ();
1453 memcpy (*r_url, rp + *r_fprlen + 1, len - (*r_fprlen + 1));
1454 (*r_url)[len - (*r_fprlen + 1)] = 0;
1464 /* Unknown subtype or record too short - skip. */
1469 /* Not a requested type - skip. */
1475 dns_res_close (res);
1478 #endif /*USE_LIBDNS*/
1481 /* Standard resolver version of get_dns_cert. */
1483 get_dns_cert_standard (const char *name, int want_certtype,
1484 void **r_key, size_t *r_keylen,
1485 unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1487 #ifdef HAVE_SYSTEM_RESOLVER
1489 unsigned char *answer;
1493 /* Allocate a 64k buffer which is the limit for an DNS response. */
1494 answer = xtrymalloc (65536);
1496 return gpg_error_from_syserror ();
1498 err = gpg_error (GPG_ERR_NOT_FOUND);
1499 r = res_query (name, C_IN,
1500 (want_certtype < DNS_CERTTYPE_RRBASE
1502 : (want_certtype - DNS_CERTTYPE_RRBASE)),
1504 /* Not too big, not too small, no errors and at least 1 answer. */
1505 if (r >= sizeof (HEADER) && r <= 65536
1506 && (((HEADER *)(void *) answer)->rcode) == NOERROR
1507 && (count = ntohs (((HEADER *)(void *) answer)->ancount)))
1510 unsigned char *pt, *emsg;
1514 pt = &answer[sizeof (HEADER)];
1516 /* Skip over the query */
1518 rc = dn_skipname (pt, emsg);
1521 err = gpg_error (GPG_ERR_INV_OBJ);
1524 pt += rc + QFIXEDSZ;
1526 /* There are several possible response types for a CERT request.
1527 We're interested in the PGP (a key) and IPGP (a URI) types.
1528 Skip all others. TODO: A key is better than a URI since
1529 we've gone through all this bother to fetch it, so favor that
1530 if we have both PGP and IPGP? */
1532 while (count-- > 0 && pt < emsg)
1534 u16 type, class, dlen, ctype;
1536 rc = dn_skipname (pt, emsg); /* the name we just queried for */
1539 err = gpg_error (GPG_ERR_INV_OBJ);
1545 /* Truncated message? 15 bytes takes us to the point where
1546 we start looking at the ctype. */
1547 if ((emsg - pt) < 15)
1550 type = buf16_to_u16 (pt);
1553 class = buf16_to_u16 (pt);
1563 dlen = buf16_to_u16 (pt);
1566 /* Check the type and parse. */
1567 if (want_certtype >= DNS_CERTTYPE_RRBASE
1568 && type == (want_certtype - DNS_CERTTYPE_RRBASE)
1571 *r_key = xtrymalloc (dlen);
1573 err = gpg_error_from_syserror ();
1576 memcpy (*r_key, pt, dlen);
1582 else if (want_certtype >= DNS_CERTTYPE_RRBASE)
1584 /* We did not found the requested RR. */
1587 else if (type == T_CERT)
1589 /* We got a CERT type. */
1590 ctype = buf16_to_u16 (pt);
1593 /* Skip the CERT key tag and algo which we don't need. */
1598 /* 15 bytes takes us to here */
1599 if (want_certtype && want_certtype != ctype)
1600 ; /* Not of the requested certtype. */
1601 else if (ctype == DNS_CERTTYPE_PGP && dlen && r_key && r_keylen)
1604 *r_key = xtrymalloc (dlen);
1606 err = gpg_error_from_syserror ();
1609 memcpy (*r_key, pt, dlen);
1615 else if (ctype == DNS_CERTTYPE_IPGP
1616 && dlen && dlen < 1023 && dlen >= pt[0] + 1)
1622 *r_fpr = xtrymalloc (*r_fprlen);
1625 err = gpg_error_from_syserror ();
1628 memcpy (*r_fpr, &pt[1], *r_fprlen);
1633 if (dlen > *r_fprlen + 1)
1635 *r_url = xtrymalloc (dlen - (*r_fprlen + 1) + 1);
1638 err = gpg_error_from_syserror ();
1643 memcpy (*r_url, &pt[*r_fprlen + 1],
1644 dlen - (*r_fprlen + 1));
1645 (*r_url)[dlen - (*r_fprlen + 1)] = '\0';
1654 /* No subtype matches, so continue with the next answer. */
1659 /* Not a requested type - might be a CNAME. Try next item. */
1669 #else /*!HAVE_SYSTEM_RESOLVER*/
1672 (void)want_certtype;
1678 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1680 #endif /*!HAVE_SYSTEM_RESOLVER*/
1684 /* Returns 0 on success or an error code. If a PGP CERT record was
1685 found, the malloced data is returned at (R_KEY, R_KEYLEN) and
1686 the other return parameters are set to NULL/0. If an IPGP CERT
1687 record was found the fingerprint is stored as an allocated block at
1688 R_FPR and its length at R_FPRLEN; an URL is is allocated as a
1689 string and returned at R_URL. If WANT_CERTTYPE is 0 this function
1690 returns the first CERT found with a supported type; it is expected
1691 that only one CERT record is used. If WANT_CERTTYPE is one of the
1692 supported certtypes only records with this certtype are considered
1693 and the first found is returned. (R_KEY,R_KEYLEN) are optional. */
1695 get_dns_cert (const char *name, int want_certtype,
1696 void **r_key, size_t *r_keylen,
1697 unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1710 if (!standard_resolver)
1712 err = get_dns_cert_libdns (name, want_certtype, r_key, r_keylen,
1713 r_fpr, r_fprlen, r_url);
1714 if (err && libdns_switch_port_p (err))
1715 err = get_dns_cert_libdns (name, want_certtype, r_key, r_keylen,
1716 r_fpr, r_fprlen, r_url);
1719 #endif /*USE_LIBDNS*/
1720 err = get_dns_cert_standard (name, want_certtype, r_key, r_keylen,
1721 r_fpr, r_fprlen, r_url);
1724 log_debug ("dns: get_dns_cert(%s): %s\n", name, gpg_strerror (err));
1730 priosort(const void *a,const void *b)
1732 const struct srventry *sa=a,*sb=b;
1733 if(sa->priority>sb->priority)
1735 else if(sa->priority<sb->priority)
1742 /* Libdns based helper for getsrv. Note that it is expected that NULL
1743 * is stored at the address of LIST and 0 is stored at the address of
1747 getsrv_libdns (const char *name, struct srventry **list, unsigned int *r_count)
1750 struct dns_resolver *res = NULL;
1751 struct dns_packet *ans = NULL;
1753 struct dns_rr_i rri;
1754 char host[DNS_D_MAXNAME + 1];
1756 unsigned int srvcount = 0;
1758 err = libdns_res_open (&res);
1762 if (dns_d_anchor (host, sizeof host, name, strlen (name)) >= sizeof host)
1764 err = gpg_error (GPG_ERR_ENAMETOOLONG);
1768 err = libdns_res_submit (res, name, DNS_T_SRV, DNS_C_IN);
1772 err = libdns_res_wait (res);
1776 ans = dns_res_fetch (res, &derr);
1779 err = libdns_error_to_gpg_error (derr);
1783 /* Check the rcode. */
1784 switch (dns_p_rcode (ans))
1786 case DNS_RC_NOERROR: break;
1787 case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
1788 default: err = GPG_ERR_SERVER_FAILED; break;
1793 memset (&rri, 0, sizeof rri);
1794 dns_rr_i_init (&rri, ans);
1795 rri.section = DNS_S_ALL & ~DNS_S_QD;
1797 rri.type = DNS_T_SRV;
1799 while (dns_rr_grep (&rr, 1, &rri, ans, &derr))
1801 struct dns_srv dsrv;
1802 struct srventry *srv;
1803 struct srventry *newlist;
1805 err = libdns_error_to_gpg_error (dns_srv_parse(&dsrv, &rr, ans));
1809 newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));
1812 err = gpg_error_from_syserror ();
1816 memset (&(*list)[srvcount], 0, sizeof(struct srventry));
1817 srv = &(*list)[srvcount];
1819 srv->priority = dsrv.priority;
1820 srv->weight = dsrv.weight;
1821 srv->port = dsrv.port;
1822 mem2str (srv->target, dsrv.target, sizeof srv->target);
1823 /* Libdns appends the root zone part which is problematic for
1824 * most other functions - strip it. */
1825 if (*srv->target && (srv->target)[strlen (srv->target)-1] == '.')
1826 (srv->target)[strlen (srv->target)-1] = 0;
1829 *r_count = srvcount;
1838 dns_res_close (res);
1841 #endif /*USE_LIBDNS*/
1844 /* Standard resolver based helper for getsrv. Note that it is
1845 * expected that NULL is stored at the address of LIST and 0 is stored
1846 * at the address of R_COUNT. */
1848 getsrv_standard (const char *name,
1849 struct srventry **list, unsigned int *r_count)
1851 #ifdef HAVE_SYSTEM_RESOLVER
1853 unsigned char ans[2048];
1856 unsigned char *answer = res.ans;
1857 HEADER *header = res.header;
1858 unsigned char *pt, *emsg;
1861 unsigned int srvcount = 0;
1864 /* Do not allow a query using the standard resolver in Tor mode. */
1866 return gpg_error (GPG_ERR_NOT_ENABLED);
1869 r = res_query (name, C_IN, T_SRV, answer, sizeof res.ans);
1872 return get_h_errno_as_gpg_error ();
1873 if (r < sizeof (HEADER))
1874 return gpg_error (GPG_ERR_SERVER_FAILED);
1875 if (r > sizeof res.ans)
1876 return gpg_error (GPG_ERR_SYSTEM_BUG);
1877 if (header->rcode != NOERROR || !(count=ntohs (header->ancount)))
1878 return gpg_error (GPG_ERR_NO_NAME); /* Error or no record found. */
1881 pt = &answer[sizeof(HEADER)];
1883 /* Skip over the query */
1884 rc = dn_skipname (pt, emsg);
1888 pt += rc + QFIXEDSZ;
1890 while (count-- > 0 && pt < emsg)
1892 struct srventry *srv;
1894 struct srventry *newlist;
1896 newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));
1900 memset (&(*list)[srvcount], 0, sizeof(struct srventry));
1901 srv = &(*list)[srvcount];
1904 rc = dn_skipname (pt, emsg); /* The name we just queried for. */
1909 /* Truncated message? */
1913 type = buf16_to_u16 (pt);
1915 /* We asked for SRV and got something else !? */
1919 class = buf16_to_u16 (pt);
1921 /* We asked for IN and got something else !? */
1926 dlen = buf16_to_u16 (pt);
1929 srv->priority = buf16_to_ushort (pt);
1931 srv->weight = buf16_to_ushort (pt);
1933 srv->port = buf16_to_ushort (pt);
1936 /* Get the name. 2782 doesn't allow name compression, but
1937 * dn_expand still works to pull the name out of the packet. */
1938 rc = dn_expand (answer, emsg, pt, srv->target, sizeof srv->target);
1939 if (rc == 1 && srv->target[0] == 0) /* "." */
1948 /* Corrupt packet? */
1953 *r_count = srvcount;
1959 return gpg_error (GPG_ERR_GENERAL);
1961 #else /*!HAVE_SYSTEM_RESOLVER*/
1966 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1968 #endif /*!HAVE_SYSTEM_RESOLVER*/
1972 /* Query a SRV record for SERVICE and PROTO for NAME. If SERVICE is
1973 * NULL, NAME is expected to contain the full query name. Note that
1974 * we do not return NONAME but simply store 0 at R_COUNT. On error an
1975 * error code is returned and 0 stored at R_COUNT. */
1977 get_dns_srv (const char *name, const char *service, const char *proto,
1978 struct srventry **list, unsigned int *r_count)
1981 char *namebuffer = NULL;
1982 unsigned int srvcount;
1989 /* If SERVICE is given construct the query from it and PROTO. */
1992 namebuffer = xtryasprintf ("_%s._%s.%s",
1993 service, proto? proto:"tcp", name);
1996 err = gpg_error_from_syserror ();
2004 if (!standard_resolver)
2006 err = getsrv_libdns (name, list, &srvcount);
2007 if (err && libdns_switch_port_p (err))
2008 err = getsrv_libdns (name, list, &srvcount);
2011 #endif /*USE_LIBDNS*/
2012 err = getsrv_standard (name, list, &srvcount);
2016 if (gpg_err_code (err) == GPG_ERR_NO_NAME)
2021 /* Now we have an array of all the srv records. */
2023 /* Order by priority */
2024 qsort(*list,srvcount,sizeof(struct srventry),priosort);
2026 /* For each priority, move the zero-weighted items first. */
2027 for (i=0; i < srvcount; i++)
2031 for (j=i;j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)
2033 if((*list)[j].weight==0)
2038 struct srventry temp;
2040 memcpy (&temp,&(*list)[j],sizeof(struct srventry));
2041 memcpy (&(*list)[j],&(*list)[i],sizeof(struct srventry));
2042 memcpy (&(*list)[i],&temp,sizeof(struct srventry));
2050 /* Run the RFC-2782 weighting algorithm. We don't need very high
2051 quality randomness for this, so regular libc srand/rand is
2059 srand (time (NULL)*getpid());
2063 for (i=0; i < srvcount; i++)
2066 float prio_count=0,chose;
2068 for (j=i; j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)
2070 prio_count+=(*list)[j].weight;
2071 (*list)[j].run_count=prio_count;
2074 chose=prio_count*rand()/RAND_MAX;
2076 for (j=i;j<srvcount && (*list)[i].priority==(*list)[j].priority;j++)
2078 if (chose<=(*list)[j].run_count)
2083 struct srventry temp;
2085 memcpy(&temp,&(*list)[j],sizeof(struct srventry));
2086 memcpy(&(*list)[j],&(*list)[i],sizeof(struct srventry));
2087 memcpy(&(*list)[i],&temp,sizeof(struct srventry));
2098 log_debug ("dns: getsrv(%s): %s\n", name, gpg_strerror (err));
2100 log_debug ("dns: getsrv(%s) -> %u records\n", name, srvcount);
2103 *r_count = srvcount;
2111 /* libdns version of get_dns_cname. */
2113 get_dns_cname_libdns (const char *name, char **r_cname)
2116 struct dns_resolver *res;
2117 struct dns_packet *ans = NULL;
2118 struct dns_cname cname;
2121 err = libdns_res_open (&res);
2125 err = libdns_res_submit (res, name, DNS_T_CNAME, DNS_C_IN);
2129 err = libdns_res_wait (res);
2133 ans = dns_res_fetch (res, &derr);
2136 err = libdns_error_to_gpg_error (derr);
2140 /* Check the rcode. */
2141 switch (dns_p_rcode (ans))
2143 case DNS_RC_NOERROR: break;
2144 case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
2145 default: err = GPG_ERR_SERVER_FAILED; break;
2150 /* Parse the result into CNAME. */
2151 err = libdns_error_to_gpg_error (dns_p_study (ans));
2155 if (!dns_d_cname (&cname, sizeof cname, name, strlen (name), ans, &derr))
2157 err = libdns_error_to_gpg_error (derr);
2162 *r_cname = xtrystrdup (cname.host);
2164 err = gpg_error_from_syserror ();
2167 /* Libdns appends the root zone part which is problematic
2168 * for most other functions - strip it. */
2169 if (**r_cname && (*r_cname)[strlen (*r_cname)-1] == '.')
2170 (*r_cname)[strlen (*r_cname)-1] = 0;
2175 dns_res_close (res);
2178 #endif /*USE_LIBDNS*/
2181 /* Standard resolver version of get_dns_cname. */
2183 get_dns_cname_standard (const char *name, char **r_cname)
2185 #ifdef HAVE_SYSTEM_RESOLVER
2189 unsigned char ans[2048];
2192 unsigned char *answer = res.ans;
2193 HEADER *header = res.header;
2194 unsigned char *pt, *emsg;
2197 int cnamesize = 1025;
2200 /* Do not allow a query using the standard resolver in Tor mode. */
2205 r = res_query (name, C_IN, T_CERT, answer, sizeof res.ans);
2208 return get_h_errno_as_gpg_error ();
2209 if (r < sizeof (HEADER))
2210 return gpg_error (GPG_ERR_SERVER_FAILED);
2211 if (r > sizeof res.ans)
2212 return gpg_error (GPG_ERR_SYSTEM_BUG);
2213 if (header->rcode != NOERROR || !(count=ntohs (header->ancount)))
2214 return gpg_error (GPG_ERR_NO_NAME); /* Error or no record found. */
2216 return gpg_error (GPG_ERR_SERVER_FAILED);
2219 pt = &answer[sizeof(HEADER)];
2220 rc = dn_skipname (pt, emsg);
2222 return gpg_error (GPG_ERR_SERVER_FAILED);
2224 pt += rc + QFIXEDSZ;
2226 return gpg_error (GPG_ERR_SERVER_FAILED);
2228 rc = dn_skipname (pt, emsg);
2230 return gpg_error (GPG_ERR_SERVER_FAILED);
2231 pt += rc + 2 + 2 + 4;
2233 return gpg_error (GPG_ERR_SERVER_FAILED);
2234 pt += 2; /* Skip rdlen */
2236 cname = xtrymalloc (cnamesize);
2238 return gpg_error_from_syserror ();
2240 rc = dn_expand (answer, emsg, pt, cname, cnamesize -1);
2244 return gpg_error (GPG_ERR_SERVER_FAILED);
2246 *r_cname = xtryrealloc (cname, strlen (cname)+1);
2249 err = gpg_error_from_syserror ();
2255 #else /*!HAVE_SYSTEM_RESOLVER*/
2259 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
2261 #endif /*!HAVE_SYSTEM_RESOLVER*/
2266 get_dns_cname (const char *name, char **r_cname)
2273 if (!standard_resolver)
2275 err = get_dns_cname_libdns (name, r_cname);
2276 if (err && libdns_switch_port_p (err))
2277 err = get_dns_cname_libdns (name, r_cname);
2280 #endif /*USE_LIBDNS*/
2282 err = get_dns_cname_standard (name, r_cname);
2284 log_debug ("get_dns_cname(%s)%s%s\n", name,
2285 err ? ": " : " -> ",
2286 err ? gpg_strerror (err) : *r_cname);