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 log_error ("failed to load hosts file: %s\n", gpg_strerror (err));
537 err = libdns_error_to_gpg_error (derr);
541 /* dns_hints_local for stub mode, dns_hints_root for recursive. */
542 ld.hints = (recursive_resolver
543 ? dns_hints_root (ld.resolv_conf, &derr)
544 : dns_hints_local (ld.resolv_conf, &derr));
547 log_error ("failed to load DNS hints: %s\n", gpg_strerror (err));
548 err = libdns_error_to_gpg_error (derr);
552 /* All fine. Make the data global. */
556 log_debug ("dns: libdns initialized%s\n", tor_mode?" (tor mode)":"");
562 #endif /*USE_LIBDNS*/
566 /* Deinitialize libdns. */
572 if (!libdns.resolv_conf)
573 return; /* Not initialized. */
576 memset (&libdns, 0, sizeof libdns);
577 dns_hints_close (ld.hints);
578 dns_hosts_close (ld.hosts);
579 dns_resconf_close (ld.resolv_conf);
581 #endif /*USE_LIBDNS*/
584 /* SIGHUP action handler for this module. With FORCE set objects are
585 * all immediately released. */
587 reload_dns_stuff (int force)
593 libdns_reinit_pending = 0;
597 libdns_reinit_pending = 1;
598 libdns_tor_port = 0; /* Start again with the default port. */
608 * Initialize libdns if needed and open a dns_resolver context.
609 * Returns 0 on success and stores the new context at R_RES. On
610 * failure an error code is returned and NULL stored at R_RES.
613 libdns_res_open (struct dns_resolver **r_res)
616 struct dns_resolver *res;
621 if (libdns_reinit_pending)
623 libdns_reinit_pending = 0;
627 err = libdns_init ();
634 res = dns_res_open (libdns.resolv_conf, libdns.hosts, libdns.hints, NULL,
635 dns_opts (.socks_host = &libdns.socks_host,
636 .socks_user = tor_socks_user,
637 .socks_password = tor_socks_password ),
640 return libdns_error_to_gpg_error (derr);
645 #endif /*USE_LIBDNS*/
649 /* Helper to test whether we need to try again after having switched
652 libdns_switch_port_p (gpg_error_t err)
654 if (tor_mode && gpg_err_code (err) == GPG_ERR_ECONNREFUSED
655 && libdns_tor_port == TOR_PORT)
657 /* Switch port and try again. */
659 log_debug ("dns: switching from SOCKS port %d to %d\n",
660 TOR_PORT, TOR_PORT2);
661 libdns_tor_port = TOR_PORT2;
662 libdns_reinit_pending = 1;
667 #endif /*USE_LIBDNS*/
671 /* Wrapper around dns_res_submit. */
673 libdns_res_submit (struct dns_resolver *res, const char *qname,
674 enum dns_type qtype, enum dns_class qclass)
676 return libdns_error_to_gpg_error (dns_res_submit (res, qname, qtype, qclass));
678 #endif /*USE_LIBDNS*/
682 /* Standard event handling loop. */
684 libdns_res_wait (struct dns_resolver *res)
688 while ((err = libdns_error_to_gpg_error (dns_res_check (res)))
689 && gpg_err_code (err) == GPG_ERR_EAGAIN)
691 if (dns_res_elapsed (res) > opt_timeout)
693 err = gpg_error (GPG_ERR_DNS_TIMEOUT);
698 dns_res_poll (res, 1);
704 #endif /*USE_LIBDNS*/
709 resolve_name_libdns (const char *name, unsigned short port,
710 int want_family, int want_socktype,
711 dns_addrinfo_t *r_dai, char **r_canonname)
714 dns_addrinfo_t daihead = NULL;
716 struct dns_resolver *res = NULL;
717 struct dns_addrinfo *ai = NULL;
718 struct addrinfo hints;
719 struct addrinfo *ent;
721 char *portstr = NULL;
728 memset (&hints, 0, sizeof hints);
729 hints.ai_family = want_family;
730 hints.ai_socktype = want_socktype;
731 hints.ai_flags = AI_ADDRCONFIG;
733 hints.ai_flags |= AI_CANONNAME;
734 if (is_ip_address (name))
735 hints.ai_flags |= AI_NUMERICHOST;
739 snprintf (portstr_, sizeof portstr_, "%hu", port);
743 err = libdns_res_open (&res);
747 ai = dns_ai_open (name, portstr, 0, &hints, res, &derr);
750 err = libdns_error_to_gpg_error (derr);
754 /* Loop over all records. */
757 err = libdns_error_to_gpg_error (dns_ai_nextent (&ent, ai));
758 if (gpg_err_code (err) == GPG_ERR_ENOENT)
761 err = 0; /* We got some results, we're good. */
764 if (gpg_err_code (err) == GPG_ERR_EAGAIN)
766 if (dns_ai_elapsed (ai) > opt_timeout)
768 err = gpg_error (GPG_ERR_DNS_TIMEOUT);
780 if (r_canonname && ! *r_canonname && ent && ent->ai_canonname)
782 *r_canonname = xtrystrdup (ent->ai_canonname);
785 err = gpg_error_from_syserror ();
788 /* Libdns appends the root zone part which is problematic
789 * for most other functions - strip it. */
790 if (**r_canonname && (*r_canonname)[strlen (*r_canonname)-1] == '.')
791 (*r_canonname)[strlen (*r_canonname)-1] = 0;
794 dai = xtrymalloc (sizeof *dai + ent->ai_addrlen -1);
797 err = gpg_error_from_syserror ();
801 dai->family = ent->ai_family;
802 dai->socktype = ent->ai_socktype;
803 dai->protocol = ent->ai_protocol;
804 dai->addrlen = ent->ai_addrlen;
805 memcpy (dai->addr, ent->ai_addr, ent->ai_addrlen);
820 xfree (*r_canonname);
823 free_dns_addrinfo (daihead);
830 #endif /*USE_LIBDNS*/
833 /* Resolve a name using the standard system function. */
835 resolve_name_standard (const char *name, unsigned short port,
836 int want_family, int want_socktype,
837 dns_addrinfo_t *r_dai, char **r_canonname)
840 dns_addrinfo_t daihead = NULL;
842 struct addrinfo *aibuf = NULL;
843 struct addrinfo hints, *ai;
851 memset (&hints, 0, sizeof hints);
852 hints.ai_family = want_family;
853 hints.ai_socktype = want_socktype;
854 hints.ai_flags = AI_ADDRCONFIG;
856 hints.ai_flags |= AI_CANONNAME;
857 if (is_ip_address (name))
858 hints.ai_flags |= AI_NUMERICHOST;
861 snprintf (portstr, sizeof portstr, "%hu", port);
865 /* We can't use the the AI_IDN flag because that does the conversion
866 using the current locale. However, GnuPG always used UTF-8. To
867 support IDN we would need to make use of the libidn API. */
868 ret = getaddrinfo (name, *portstr? portstr : NULL, &hints, &aibuf);
872 err = map_eai_to_gpg_error (ret);
873 if (gpg_err_code (err) == GPG_ERR_NO_NAME)
875 /* There seems to be a bug in the glibc getaddrinfo function
876 if the CNAME points to a long list of A and AAAA records
877 in which case the function return NO_NAME. Let's do the
878 CNAME redirection again. */
881 if (get_dns_cname (name, &cname))
882 goto leave; /* Still no success. */
884 ret = getaddrinfo (cname, *portstr? portstr : NULL, &hints, &aibuf);
889 err = map_eai_to_gpg_error (ret);
892 err = 0; /* Yep, now it worked. */
898 if (r_canonname && aibuf && aibuf->ai_canonname)
900 *r_canonname = xtrystrdup (aibuf->ai_canonname);
903 err = gpg_error_from_syserror ();
908 for (ai = aibuf; ai; ai = ai->ai_next)
910 if (ai->ai_family != AF_INET6 && ai->ai_family != AF_INET)
912 if (opt_disable_ipv4 && ai->ai_family == AF_INET)
915 dai = xtrymalloc (sizeof *dai + ai->ai_addrlen - 1);
916 dai->family = ai->ai_family;
917 dai->socktype = ai->ai_socktype;
918 dai->protocol = ai->ai_protocol;
919 dai->addrlen = ai->ai_addrlen;
920 memcpy (dai->addr, ai->ai_addr, ai->ai_addrlen);
927 freeaddrinfo (aibuf);
932 xfree (*r_canonname);
935 free_dns_addrinfo (daihead);
943 /* This a wrapper around getaddrinfo with slightly different semantics.
944 NAME is the name to resolve.
945 PORT is the requested port or 0.
946 WANT_FAMILY is either 0 (AF_UNSPEC), AF_INET6, or AF_INET4.
947 WANT_SOCKETTYPE is either SOCK_STREAM or SOCK_DGRAM.
949 On success the result is stored in a linked list with the head
950 stored at the address R_AI; the caller must call gpg_addrinfo_free
951 on this. If R_CANONNAME is not NULL the official name of the host
952 is stored there as a malloced string; if that name is not available
955 resolve_dns_name (const char *name, unsigned short port,
956 int want_family, int want_socktype,
957 dns_addrinfo_t *r_ai, char **r_canonname)
962 if (!standard_resolver)
964 err = resolve_name_libdns (name, port, want_family, want_socktype,
966 if (err && libdns_switch_port_p (err))
967 err = resolve_name_libdns (name, port, want_family, want_socktype,
971 #endif /*USE_LIBDNS*/
972 err = resolve_name_standard (name, port, want_family, want_socktype,
975 log_debug ("dns: resolve_dns_name(%s): %s\n", name, gpg_strerror (err));
981 /* Resolve an address using libdns. */
983 resolve_addr_libdns (const struct sockaddr *addr, int addrlen,
984 unsigned int flags, char **r_name)
987 char host[DNS_D_MAXNAME + 1];
988 struct dns_resolver *res = NULL;
989 struct dns_packet *ans = NULL;
995 /* First we turn ADDR into a DNS name (with ".arpa" suffix). */
997 if (addr->sa_family == AF_INET6)
999 const struct sockaddr_in6 *a6 = (const struct sockaddr_in6 *)addr;
1000 if (!dns_aaaa_arpa (host, sizeof host, (void*)&a6->sin6_addr))
1001 err = gpg_error (GPG_ERR_INV_OBJ);
1003 else if (addr->sa_family == AF_INET)
1005 const struct sockaddr_in *a4 = (const struct sockaddr_in *)addr;
1006 if (!dns_a_arpa (host, sizeof host, (void*)&a4->sin_addr))
1007 err = gpg_error (GPG_ERR_INV_OBJ);
1010 err = gpg_error (GPG_ERR_EAFNOSUPPORT);
1015 err = libdns_res_open (&res);
1019 err = libdns_res_submit (res, host, DNS_T_PTR, DNS_C_IN);
1023 err = libdns_res_wait (res);
1027 ans = dns_res_fetch (res, &derr);
1030 err = libdns_error_to_gpg_error (derr);
1034 /* Check the rcode. */
1035 switch (dns_p_rcode (ans))
1037 case DNS_RC_NOERROR:
1039 case DNS_RC_NXDOMAIN:
1040 err = gpg_error (GPG_ERR_NO_NAME);
1043 err = GPG_ERR_SERVER_FAILED;
1047 /* Parse the result. */
1051 struct dns_rr_i rri;
1053 memset (&rri, 0, sizeof rri);
1054 dns_rr_i_init (&rri, ans);
1055 rri.section = DNS_S_ALL & ~DNS_S_QD;
1057 rri.type = DNS_T_PTR;
1059 if (!dns_rr_grep (&rr, 1, &rri, ans, &derr))
1061 err = gpg_error (GPG_ERR_NOT_FOUND);
1065 err = libdns_error_to_gpg_error (dns_ptr_parse (&ptr, &rr, ans));
1070 *r_name = xtrystrdup (ptr.host);
1073 err = gpg_error_from_syserror ();
1076 /* Libdns appends the root zone part which is problematic
1077 * for most other functions - strip it. */
1078 if (**r_name && (*r_name)[strlen (*r_name)-1] == '.')
1079 (*r_name)[strlen (*r_name)-1] = 0;
1081 else /* GPG_ERR_NO_NAME */
1088 buflen = sizeof ptr.host;
1091 if (addr->sa_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1096 ec = getnameinfo (addr, addrlen, p, buflen, NULL, 0, NI_NUMERICHOST);
1099 err = map_eai_to_gpg_error (ec);
1102 if (addr->sa_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1103 strcat (buffer, "]");
1108 dns_res_close (res);
1111 #endif /*USE_LIBDNS*/
1114 /* Resolve an address using the standard system function. */
1116 resolve_addr_standard (const struct sockaddr *addr, int addrlen,
1117 unsigned int flags, char **r_name)
1126 buflen = NI_MAXHOST;
1127 buffer = xtrymalloc (buflen + 2 + 1);
1129 return gpg_error_from_syserror ();
1131 if ((flags & DNS_NUMERICHOST) || tor_mode)
1134 ec = getnameinfo (addr, addrlen, buffer, buflen, NULL, 0, NI_NAMEREQD);
1136 if (!ec && *buffer == '[')
1137 ec = EAI_FAIL; /* A name may never start with a bracket. */
1138 else if (ec == EAI_NONAME)
1141 if (addr->sa_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1146 ec = getnameinfo (addr, addrlen, p, buflen, NULL, 0, NI_NUMERICHOST);
1147 if (!ec && addr->sa_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1148 strcat (buffer, "]");
1152 err = map_eai_to_gpg_error (ec);
1155 p = xtryrealloc (buffer, strlen (buffer)+1);
1157 err = gpg_error_from_syserror ();
1174 /* A wrapper around getnameinfo. */
1176 resolve_dns_addr (const struct sockaddr *addr, int addrlen,
1177 unsigned int flags, char **r_name)
1182 /* Note that we divert to the standard resolver for NUMERICHOST. */
1183 if (!standard_resolver && !(flags & DNS_NUMERICHOST))
1185 err = resolve_addr_libdns (addr, addrlen, flags, r_name);
1186 if (err && libdns_switch_port_p (err))
1187 err = resolve_addr_libdns (addr, addrlen, flags, r_name);
1190 #endif /*USE_LIBDNS*/
1191 err = resolve_addr_standard (addr, addrlen, flags, r_name);
1194 log_debug ("dns: resolve_dns_addr(): %s\n", gpg_strerror (err));
1199 /* Check whether NAME is an IP address. Returns a true if it is
1200 * either an IPv6 or a IPv4 numerical address. The actual return
1201 * values can also be used to identify whether it is v4 or v6: The
1202 * true value will surprisingly be 4 for IPv4 and 6 for IPv6. */
1204 is_ip_address (const char *name)
1207 int ndots, dblcol, n;
1210 return 6; /* yes: A legal DNS name may not contain this character;
1211 this mut be bracketed v6 address. */
1213 return 0; /* No. A leading dot is not a valid IP address. */
1215 /* Check whether this is a v6 address. */
1216 ndots = n = dblcol = 0;
1217 for (s=name; *s; s++)
1226 return 0; /* No: Only one "::" allowed. */
1235 else if (!strchr ("0123456789abcdefABCDEF", *s))
1236 return 0; /* No: Not a hex digit. */
1238 return 0; /* To many digits in a group. */
1241 return 0; /* No: Too many colons. */
1243 return 6; /* Yes: At least 2 colons indicate an v6 address. */
1246 /* Check whether it is legacy IP address. */
1248 for (s=name; *s; s++)
1253 return 0; /* No: Douple dot. */
1254 if (atoi (s+1) > 255)
1255 return 0; /* No: Ipv4 byte value too large. */
1259 else if (!strchr ("0123456789", *s))
1260 return 0; /* No: Not a digit. */
1262 return 0; /* No: More than 3 digits. */
1264 return (ndots == 3)? 4 : 0;
1268 /* Return true if NAME is an onion address. */
1270 is_onion_address (const char *name)
1274 len = name? strlen (name) : 0;
1275 if (len < 8 || strcmp (name + len - 6, ".onion"))
1277 /* Note that we require at least 2 characters before the suffix. */
1278 return 1; /* Yes. */
1282 /* libdns version of get_dns_cert. */
1285 get_dns_cert_libdns (const char *name, int want_certtype,
1286 void **r_key, size_t *r_keylen,
1287 unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1290 struct dns_resolver *res = NULL;
1291 struct dns_packet *ans = NULL;
1293 struct dns_rr_i rri;
1294 char host[DNS_D_MAXNAME + 1];
1298 /* Get the query type from WANT_CERTTYPE (which in general indicates
1299 * the subtype we want). */
1300 qtype = (want_certtype < DNS_CERTTYPE_RRBASE
1302 : (want_certtype - DNS_CERTTYPE_RRBASE));
1305 err = libdns_res_open (&res);
1309 if (dns_d_anchor (host, sizeof host, name, strlen (name)) >= sizeof host)
1311 err = gpg_error (GPG_ERR_ENAMETOOLONG);
1315 err = libdns_res_submit (res, name, qtype, DNS_C_IN);
1319 err = libdns_res_wait (res);
1323 ans = dns_res_fetch (res, &derr);
1326 err = libdns_error_to_gpg_error (derr);
1330 /* Check the rcode. */
1331 switch (dns_p_rcode (ans))
1333 case DNS_RC_NOERROR: break;
1334 case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
1335 default: err = GPG_ERR_SERVER_FAILED; break;
1340 memset (&rri, 0, sizeof rri);
1341 dns_rr_i_init (&rri, ans);
1342 rri.section = DNS_S_ALL & ~DNS_S_QD;
1346 err = gpg_error (GPG_ERR_NOT_FOUND);
1347 while (dns_rr_grep (&rr, 1, &rri, ans, &derr))
1349 unsigned char *rp = ans->data + rr.rd.p;
1350 unsigned short len = rr.rd.len;
1355 /* Definitely too short - skip. */
1357 else if (want_certtype >= DNS_CERTTYPE_RRBASE
1358 && rr.type == (want_certtype - DNS_CERTTYPE_RRBASE)
1361 *r_key = xtrymalloc (len);
1363 err = gpg_error_from_syserror ();
1366 memcpy (*r_key, rp, len);
1372 else if (want_certtype >= DNS_CERTTYPE_RRBASE)
1374 /* We did not found the requested RR - skip. */
1376 else if (rr.type == T_CERT && len > 5)
1378 /* We got a CERT type. */
1379 subtype = buf16_to_u16 (rp);
1382 /* Skip the CERT key tag and algo which we don't need. */
1385 if (want_certtype && want_certtype != subtype)
1386 ; /* Not the requested subtype - skip. */
1387 else if (subtype == DNS_CERTTYPE_PGP && len && r_key && r_keylen)
1390 *r_key = xtrymalloc (len);
1392 err = gpg_error_from_syserror ();
1395 memcpy (*r_key, rp, len);
1401 else if (subtype == DNS_CERTTYPE_IPGP
1402 && len && len < 1023 && len >= rp[0] + 1)
1408 *r_fpr = xtrymalloc (*r_fprlen);
1411 err = gpg_error_from_syserror ();
1414 memcpy (*r_fpr, rp+1, *r_fprlen);
1419 if (len > *r_fprlen + 1)
1421 *r_url = xtrymalloc (len - (*r_fprlen + 1) + 1);
1424 err = gpg_error_from_syserror ();
1429 memcpy (*r_url, rp + *r_fprlen + 1, len - (*r_fprlen + 1));
1430 (*r_url)[len - (*r_fprlen + 1)] = 0;
1440 /* Unknown subtype or record too short - skip. */
1445 /* Not a requested type - skip. */
1451 dns_res_close (res);
1454 #endif /*USE_LIBDNS*/
1457 /* Standard resolver version of get_dns_cert. */
1459 get_dns_cert_standard (const char *name, int want_certtype,
1460 void **r_key, size_t *r_keylen,
1461 unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1463 #ifdef HAVE_SYSTEM_RESOLVER
1465 unsigned char *answer;
1469 /* Allocate a 64k buffer which is the limit for an DNS response. */
1470 answer = xtrymalloc (65536);
1472 return gpg_error_from_syserror ();
1474 err = gpg_error (GPG_ERR_NOT_FOUND);
1475 r = res_query (name, C_IN,
1476 (want_certtype < DNS_CERTTYPE_RRBASE
1478 : (want_certtype - DNS_CERTTYPE_RRBASE)),
1480 /* Not too big, not too small, no errors and at least 1 answer. */
1481 if (r >= sizeof (HEADER) && r <= 65536
1482 && (((HEADER *)(void *) answer)->rcode) == NOERROR
1483 && (count = ntohs (((HEADER *)(void *) answer)->ancount)))
1486 unsigned char *pt, *emsg;
1490 pt = &answer[sizeof (HEADER)];
1492 /* Skip over the query */
1494 rc = dn_skipname (pt, emsg);
1497 err = gpg_error (GPG_ERR_INV_OBJ);
1500 pt += rc + QFIXEDSZ;
1502 /* There are several possible response types for a CERT request.
1503 We're interested in the PGP (a key) and IPGP (a URI) types.
1504 Skip all others. TODO: A key is better than a URI since
1505 we've gone through all this bother to fetch it, so favor that
1506 if we have both PGP and IPGP? */
1508 while (count-- > 0 && pt < emsg)
1510 u16 type, class, dlen, ctype;
1512 rc = dn_skipname (pt, emsg); /* the name we just queried for */
1515 err = gpg_error (GPG_ERR_INV_OBJ);
1521 /* Truncated message? 15 bytes takes us to the point where
1522 we start looking at the ctype. */
1523 if ((emsg - pt) < 15)
1526 type = buf16_to_u16 (pt);
1529 class = buf16_to_u16 (pt);
1539 dlen = buf16_to_u16 (pt);
1542 /* Check the type and parse. */
1543 if (want_certtype >= DNS_CERTTYPE_RRBASE
1544 && type == (want_certtype - DNS_CERTTYPE_RRBASE)
1547 *r_key = xtrymalloc (dlen);
1549 err = gpg_error_from_syserror ();
1552 memcpy (*r_key, pt, dlen);
1558 else if (want_certtype >= DNS_CERTTYPE_RRBASE)
1560 /* We did not found the requested RR. */
1563 else if (type == T_CERT)
1565 /* We got a CERT type. */
1566 ctype = buf16_to_u16 (pt);
1569 /* Skip the CERT key tag and algo which we don't need. */
1574 /* 15 bytes takes us to here */
1575 if (want_certtype && want_certtype != ctype)
1576 ; /* Not of the requested certtype. */
1577 else if (ctype == DNS_CERTTYPE_PGP && dlen && r_key && r_keylen)
1580 *r_key = xtrymalloc (dlen);
1582 err = gpg_error_from_syserror ();
1585 memcpy (*r_key, pt, dlen);
1591 else if (ctype == DNS_CERTTYPE_IPGP
1592 && dlen && dlen < 1023 && dlen >= pt[0] + 1)
1598 *r_fpr = xtrymalloc (*r_fprlen);
1601 err = gpg_error_from_syserror ();
1604 memcpy (*r_fpr, &pt[1], *r_fprlen);
1609 if (dlen > *r_fprlen + 1)
1611 *r_url = xtrymalloc (dlen - (*r_fprlen + 1) + 1);
1614 err = gpg_error_from_syserror ();
1619 memcpy (*r_url, &pt[*r_fprlen + 1],
1620 dlen - (*r_fprlen + 1));
1621 (*r_url)[dlen - (*r_fprlen + 1)] = '\0';
1630 /* No subtype matches, so continue with the next answer. */
1635 /* Not a requested type - might be a CNAME. Try next item. */
1645 #else /*!HAVE_SYSTEM_RESOLVER*/
1648 (void)want_certtype;
1654 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1656 #endif /*!HAVE_SYSTEM_RESOLVER*/
1660 /* Returns 0 on success or an error code. If a PGP CERT record was
1661 found, the malloced data is returned at (R_KEY, R_KEYLEN) and
1662 the other return parameters are set to NULL/0. If an IPGP CERT
1663 record was found the fingerprint is stored as an allocated block at
1664 R_FPR and its length at R_FPRLEN; an URL is is allocated as a
1665 string and returned at R_URL. If WANT_CERTTYPE is 0 this function
1666 returns the first CERT found with a supported type; it is expected
1667 that only one CERT record is used. If WANT_CERTTYPE is one of the
1668 supported certtypes only records with this certtype are considered
1669 and the first found is returned. (R_KEY,R_KEYLEN) are optional. */
1671 get_dns_cert (const char *name, int want_certtype,
1672 void **r_key, size_t *r_keylen,
1673 unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1686 if (!standard_resolver)
1688 err = get_dns_cert_libdns (name, want_certtype, r_key, r_keylen,
1689 r_fpr, r_fprlen, r_url);
1690 if (err && libdns_switch_port_p (err))
1691 err = get_dns_cert_libdns (name, want_certtype, r_key, r_keylen,
1692 r_fpr, r_fprlen, r_url);
1695 #endif /*USE_LIBDNS*/
1696 err = get_dns_cert_standard (name, want_certtype, r_key, r_keylen,
1697 r_fpr, r_fprlen, r_url);
1700 log_debug ("dns: get_dns_cert(%s): %s\n", name, gpg_strerror (err));
1706 priosort(const void *a,const void *b)
1708 const struct srventry *sa=a,*sb=b;
1709 if(sa->priority>sb->priority)
1711 else if(sa->priority<sb->priority)
1718 /* Libdns based helper for getsrv. Note that it is expected that NULL
1719 * is stored at the address of LIST and 0 is stored at the address of
1723 getsrv_libdns (const char *name, struct srventry **list, unsigned int *r_count)
1726 struct dns_resolver *res = NULL;
1727 struct dns_packet *ans = NULL;
1729 struct dns_rr_i rri;
1730 char host[DNS_D_MAXNAME + 1];
1732 unsigned int srvcount = 0;
1734 err = libdns_res_open (&res);
1738 if (dns_d_anchor (host, sizeof host, name, strlen (name)) >= sizeof host)
1740 err = gpg_error (GPG_ERR_ENAMETOOLONG);
1744 err = libdns_res_submit (res, name, DNS_T_SRV, DNS_C_IN);
1748 err = libdns_res_wait (res);
1752 ans = dns_res_fetch (res, &derr);
1755 err = libdns_error_to_gpg_error (derr);
1759 /* Check the rcode. */
1760 switch (dns_p_rcode (ans))
1762 case DNS_RC_NOERROR: break;
1763 case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
1764 default: err = GPG_ERR_SERVER_FAILED; break;
1769 memset (&rri, 0, sizeof rri);
1770 dns_rr_i_init (&rri, ans);
1771 rri.section = DNS_S_ALL & ~DNS_S_QD;
1773 rri.type = DNS_T_SRV;
1775 while (dns_rr_grep (&rr, 1, &rri, ans, &derr))
1777 struct dns_srv dsrv;
1778 struct srventry *srv;
1779 struct srventry *newlist;
1781 err = libdns_error_to_gpg_error (dns_srv_parse(&dsrv, &rr, ans));
1785 newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));
1788 err = gpg_error_from_syserror ();
1792 memset (&(*list)[srvcount], 0, sizeof(struct srventry));
1793 srv = &(*list)[srvcount];
1795 srv->priority = dsrv.priority;
1796 srv->weight = dsrv.weight;
1797 srv->port = dsrv.port;
1798 mem2str (srv->target, dsrv.target, sizeof srv->target);
1799 /* Libdns appends the root zone part which is problematic for
1800 * most other functions - strip it. */
1801 if (*srv->target && (srv->target)[strlen (srv->target)-1] == '.')
1802 (srv->target)[strlen (srv->target)-1] = 0;
1805 *r_count = srvcount;
1814 dns_res_close (res);
1817 #endif /*USE_LIBDNS*/
1820 /* Standard resolver based helper for getsrv. Note that it is
1821 * expected that NULL is stored at the address of LIST and 0 is stored
1822 * at the address of R_COUNT. */
1824 getsrv_standard (const char *name,
1825 struct srventry **list, unsigned int *r_count)
1827 #ifdef HAVE_SYSTEM_RESOLVER
1829 unsigned char ans[2048];
1832 unsigned char *answer = res.ans;
1833 HEADER *header = res.header;
1834 unsigned char *pt, *emsg;
1837 unsigned int srvcount = 0;
1840 /* Do not allow a query using the standard resolver in Tor mode. */
1842 return gpg_error (GPG_ERR_NOT_ENABLED);
1845 r = res_query (name, C_IN, T_SRV, answer, sizeof res.ans);
1848 return get_h_errno_as_gpg_error ();
1849 if (r < sizeof (HEADER))
1850 return gpg_error (GPG_ERR_SERVER_FAILED);
1851 if (r > sizeof res.ans)
1852 return gpg_error (GPG_ERR_SYSTEM_BUG);
1853 if (header->rcode != NOERROR || !(count=ntohs (header->ancount)))
1854 return gpg_error (GPG_ERR_NO_NAME); /* Error or no record found. */
1857 pt = &answer[sizeof(HEADER)];
1859 /* Skip over the query */
1860 rc = dn_skipname (pt, emsg);
1864 pt += rc + QFIXEDSZ;
1866 while (count-- > 0 && pt < emsg)
1868 struct srventry *srv;
1870 struct srventry *newlist;
1872 newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));
1876 memset (&(*list)[srvcount], 0, sizeof(struct srventry));
1877 srv = &(*list)[srvcount];
1880 rc = dn_skipname (pt, emsg); /* The name we just queried for. */
1885 /* Truncated message? */
1889 type = buf16_to_u16 (pt);
1891 /* We asked for SRV and got something else !? */
1895 class = buf16_to_u16 (pt);
1897 /* We asked for IN and got something else !? */
1902 dlen = buf16_to_u16 (pt);
1905 srv->priority = buf16_to_ushort (pt);
1907 srv->weight = buf16_to_ushort (pt);
1909 srv->port = buf16_to_ushort (pt);
1912 /* Get the name. 2782 doesn't allow name compression, but
1913 * dn_expand still works to pull the name out of the packet. */
1914 rc = dn_expand (answer, emsg, pt, srv->target, sizeof srv->target);
1915 if (rc == 1 && srv->target[0] == 0) /* "." */
1924 /* Corrupt packet? */
1929 *r_count = srvcount;
1935 return gpg_error (GPG_ERR_GENERAL);
1937 #else /*!HAVE_SYSTEM_RESOLVER*/
1942 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1944 #endif /*!HAVE_SYSTEM_RESOLVER*/
1948 /* Query a SRV record for SERVICE and PROTO for NAME. If SERVICE is
1949 * NULL, NAME is expected to contain the full query name. Note that
1950 * we do not return NONAME but simply store 0 at R_COUNT. On error an
1951 * error code is returned and 0 stored at R_COUNT. */
1953 get_dns_srv (const char *name, const char *service, const char *proto,
1954 struct srventry **list, unsigned int *r_count)
1957 char *namebuffer = NULL;
1958 unsigned int srvcount;
1965 /* If SERVICE is given construct the query from it and PROTO. */
1968 namebuffer = xtryasprintf ("_%s._%s.%s",
1969 service, proto? proto:"tcp", name);
1972 err = gpg_error_from_syserror ();
1980 if (!standard_resolver)
1982 err = getsrv_libdns (name, list, &srvcount);
1983 if (err && libdns_switch_port_p (err))
1984 err = getsrv_libdns (name, list, &srvcount);
1987 #endif /*USE_LIBDNS*/
1988 err = getsrv_standard (name, list, &srvcount);
1992 if (gpg_err_code (err) == GPG_ERR_NO_NAME)
1997 /* Now we have an array of all the srv records. */
1999 /* Order by priority */
2000 qsort(*list,srvcount,sizeof(struct srventry),priosort);
2002 /* For each priority, move the zero-weighted items first. */
2003 for (i=0; i < srvcount; i++)
2007 for (j=i;j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)
2009 if((*list)[j].weight==0)
2014 struct srventry temp;
2016 memcpy (&temp,&(*list)[j],sizeof(struct srventry));
2017 memcpy (&(*list)[j],&(*list)[i],sizeof(struct srventry));
2018 memcpy (&(*list)[i],&temp,sizeof(struct srventry));
2026 /* Run the RFC-2782 weighting algorithm. We don't need very high
2027 quality randomness for this, so regular libc srand/rand is
2035 srand (time (NULL)*getpid());
2039 for (i=0; i < srvcount; i++)
2042 float prio_count=0,chose;
2044 for (j=i; j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)
2046 prio_count+=(*list)[j].weight;
2047 (*list)[j].run_count=prio_count;
2050 chose=prio_count*rand()/RAND_MAX;
2052 for (j=i;j<srvcount && (*list)[i].priority==(*list)[j].priority;j++)
2054 if (chose<=(*list)[j].run_count)
2059 struct srventry temp;
2061 memcpy(&temp,&(*list)[j],sizeof(struct srventry));
2062 memcpy(&(*list)[j],&(*list)[i],sizeof(struct srventry));
2063 memcpy(&(*list)[i],&temp,sizeof(struct srventry));
2074 log_debug ("dns: getsrv(%s): %s\n", name, gpg_strerror (err));
2076 log_debug ("dns: getsrv(%s) -> %u records\n", name, srvcount);
2079 *r_count = srvcount;
2087 /* libdns version of get_dns_cname. */
2089 get_dns_cname_libdns (const char *name, char **r_cname)
2092 struct dns_resolver *res;
2093 struct dns_packet *ans = NULL;
2094 struct dns_cname cname;
2097 err = libdns_res_open (&res);
2101 err = libdns_res_submit (res, name, DNS_T_CNAME, DNS_C_IN);
2105 err = libdns_res_wait (res);
2109 ans = dns_res_fetch (res, &derr);
2112 err = libdns_error_to_gpg_error (derr);
2116 /* Check the rcode. */
2117 switch (dns_p_rcode (ans))
2119 case DNS_RC_NOERROR: break;
2120 case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
2121 default: err = GPG_ERR_SERVER_FAILED; break;
2126 /* Parse the result into CNAME. */
2127 err = libdns_error_to_gpg_error (dns_p_study (ans));
2131 if (!dns_d_cname (&cname, sizeof cname, name, strlen (name), ans, &derr))
2133 err = libdns_error_to_gpg_error (derr);
2138 *r_cname = xtrystrdup (cname.host);
2140 err = gpg_error_from_syserror ();
2143 /* Libdns appends the root zone part which is problematic
2144 * for most other functions - strip it. */
2145 if (**r_cname && (*r_cname)[strlen (*r_cname)-1] == '.')
2146 (*r_cname)[strlen (*r_cname)-1] = 0;
2151 dns_res_close (res);
2154 #endif /*USE_LIBDNS*/
2157 /* Standard resolver version of get_dns_cname. */
2159 get_dns_cname_standard (const char *name, char **r_cname)
2161 #ifdef HAVE_SYSTEM_RESOLVER
2165 unsigned char ans[2048];
2168 unsigned char *answer = res.ans;
2169 HEADER *header = res.header;
2170 unsigned char *pt, *emsg;
2173 int cnamesize = 1025;
2176 /* Do not allow a query using the standard resolver in Tor mode. */
2181 r = res_query (name, C_IN, T_CERT, answer, sizeof res.ans);
2184 return get_h_errno_as_gpg_error ();
2185 if (r < sizeof (HEADER))
2186 return gpg_error (GPG_ERR_SERVER_FAILED);
2187 if (r > sizeof res.ans)
2188 return gpg_error (GPG_ERR_SYSTEM_BUG);
2189 if (header->rcode != NOERROR || !(count=ntohs (header->ancount)))
2190 return gpg_error (GPG_ERR_NO_NAME); /* Error or no record found. */
2192 return gpg_error (GPG_ERR_SERVER_FAILED);
2195 pt = &answer[sizeof(HEADER)];
2196 rc = dn_skipname (pt, emsg);
2198 return gpg_error (GPG_ERR_SERVER_FAILED);
2200 pt += rc + QFIXEDSZ;
2202 return gpg_error (GPG_ERR_SERVER_FAILED);
2204 rc = dn_skipname (pt, emsg);
2206 return gpg_error (GPG_ERR_SERVER_FAILED);
2207 pt += rc + 2 + 2 + 4;
2209 return gpg_error (GPG_ERR_SERVER_FAILED);
2210 pt += 2; /* Skip rdlen */
2212 cname = xtrymalloc (cnamesize);
2214 return gpg_error_from_syserror ();
2216 rc = dn_expand (answer, emsg, pt, cname, cnamesize -1);
2220 return gpg_error (GPG_ERR_SERVER_FAILED);
2222 *r_cname = xtryrealloc (cname, strlen (cname)+1);
2225 err = gpg_error_from_syserror ();
2231 #else /*!HAVE_SYSTEM_RESOLVER*/
2235 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
2237 #endif /*!HAVE_SYSTEM_RESOLVER*/
2242 get_dns_cname (const char *name, char **r_cname)
2249 if (!standard_resolver)
2251 err = get_dns_cname_libdns (name, r_cname);
2252 if (err && libdns_switch_port_p (err))
2253 err = get_dns_cname_libdns (name, r_cname);
2256 #endif /*USE_LIBDNS*/
2258 err = get_dns_cname_standard (name, r_cname);
2260 log_debug ("get_dns_cname(%s)%s%s\n", name,
2261 err ? ": " : " -> ",
2262 err ? gpg_strerror (err) : *r_cname);