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 /* If set force the use of the standard resolver. */
123 static int standard_resolver;
125 /* If set use recursive resolver when available. */
126 static int recursive_resolver;
128 /* If set Tor mode shall be used. */
131 /* A string with the nameserver IP address used with Tor.
132 (40 should be sufficient for v6 but we add some extra for a scope.) */
133 static char tor_nameserver[40+20];
135 /* Two strings to hold the credentials presented to Tor. */
136 static char tor_socks_user[30];
137 static char tor_socks_password[20];
141 /* Libdns gobal data. */
144 struct dns_resolv_conf *resolv_conf;
145 struct dns_hosts *hosts;
146 struct dns_hints *hints;
148 struct sockaddr_storage socks_host;
151 /* If this flag is set, libdns shall be reinited for the next use. */
152 static int libdns_reinit_pending;
154 /* The Tor port to be used. */
155 static int libdns_tor_port;
157 #endif /*USE_LIBDNS*/
160 /* Calling this function with YES set to True forces the use of the
161 * standard resolver even if dirmngr has been built with support for
162 * an alternative resolver. */
164 enable_standard_resolver (int yes)
166 standard_resolver = yes;
170 /* Return true if the standard resolver is used. */
172 standard_resolver_p (void)
174 return standard_resolver;
178 /* Calling this function with YES switches libdns into recursive mode.
179 * It has no effect on the standard resolver. */
181 enable_recursive_resolver (int yes)
183 recursive_resolver = yes;
185 libdns_reinit_pending = 1;
190 /* Return true iff the recursive resolver is used. */
192 recursive_resolver_p (void)
195 return !standard_resolver && recursive_resolver;
202 /* Sets the module in Tor mode. Returns 0 is this is possible or an
205 enable_dns_tormode (int new_circuit)
207 if (!*tor_socks_user || new_circuit)
209 static unsigned int counter;
211 gpgrt_snprintf (tor_socks_user, sizeof tor_socks_user,
212 "dirmngr-%lu", (unsigned long)getpid ());
213 gpgrt_snprintf (tor_socks_password, sizeof tor_socks_password,
222 /* Set verbosity and debug mode for this module. */
224 set_dns_verbose (int verbose, int debug)
226 opt_verbose = verbose;
231 /* Set the timeout for libdns requests to SECONDS. A value of 0 sets
232 * the default timeout and values are capped at 10 minutes. */
234 set_dns_timeout (int seconds)
237 seconds = DEFAULT_TIMEOUT;
238 else if (seconds < 1)
240 else if (seconds > 600)
243 opt_timeout = seconds;
247 /* Change the default IP address of the nameserver to IPADDR. The
248 address needs to be a numerical IP address and will be used for the
249 next DNS query. Note that this is only used in Tor mode. */
251 set_dns_nameserver (const char *ipaddr)
253 strncpy (tor_nameserver, ipaddr? ipaddr : DEFAULT_NAMESERVER,
254 sizeof tor_nameserver -1);
255 tor_nameserver[sizeof tor_nameserver -1] = 0;
257 libdns_reinit_pending = 1;
258 libdns_tor_port = 0; /* Start again with the default port. */
263 /* Free an addressinfo linked list as returned by resolve_dns_name. */
265 free_dns_addrinfo (dns_addrinfo_t ai)
269 dns_addrinfo_t next = ai->next;
276 #ifndef HAVE_W32_SYSTEM
277 /* Return H_ERRNO mapped to a gpg-error code. Will never return 0. */
279 get_h_errno_as_gpg_error (void)
285 case HOST_NOT_FOUND: ec = GPG_ERR_NO_NAME; break;
286 case TRY_AGAIN: ec = GPG_ERR_TRY_LATER; break;
287 case NO_RECOVERY: ec = GPG_ERR_SERVER_FAILED; break;
288 case NO_DATA: ec = GPG_ERR_NO_DATA; break;
289 default: ec = GPG_ERR_UNKNOWN_ERRNO; break;
291 return gpg_error (ec);
293 #endif /*!HAVE_W32_SYSTEM*/
296 map_eai_to_gpg_error (int ec)
302 case EAI_AGAIN: err = gpg_error (GPG_ERR_EAGAIN); break;
303 case EAI_BADFLAGS: err = gpg_error (GPG_ERR_INV_FLAG); break;
304 case EAI_FAIL: err = gpg_error (GPG_ERR_SERVER_FAILED); break;
305 case EAI_MEMORY: err = gpg_error (GPG_ERR_ENOMEM); break;
307 case EAI_NODATA: err = gpg_error (GPG_ERR_NO_DATA); break;
309 case EAI_NONAME: err = gpg_error (GPG_ERR_NO_NAME); break;
310 case EAI_SERVICE: err = gpg_error (GPG_ERR_NOT_SUPPORTED); break;
311 case EAI_FAMILY: err = gpg_error (GPG_ERR_EAFNOSUPPORT); break;
312 case EAI_SOCKTYPE: err = gpg_error (GPG_ERR_ESOCKTNOSUPPORT); break;
313 #ifndef HAVE_W32_SYSTEM
314 # ifdef EAI_ADDRFAMILY
315 case EAI_ADDRFAMILY:err = gpg_error (GPG_ERR_EADDRNOTAVAIL); break;
317 case EAI_SYSTEM: err = gpg_error_from_syserror (); break;
319 default: err = gpg_error (GPG_ERR_UNKNOWN_ERRNO); break;
327 libdns_error_to_gpg_error (int serr)
333 case 0: ec = 0; break;
335 case DNS_ENOBUFS: ec = GPG_ERR_BUFFER_TOO_SHORT; break;
336 case DNS_EILLEGAL: ec = GPG_ERR_INV_OBJ; break;
337 case DNS_EORDER: ec = GPG_ERR_INV_ORDER; break;
338 case DNS_ESECTION: ec = GPG_ERR_DNS_SECTION; break;
339 case DNS_EUNKNOWN: ec = GPG_ERR_DNS_UNKNOWN; break;
340 case DNS_EADDRESS: ec = GPG_ERR_DNS_ADDRESS; break;
341 case DNS_ENOQUERY: ec = GPG_ERR_DNS_NO_QUERY; break;
342 case DNS_ENOANSWER:ec = GPG_ERR_DNS_NO_ANSWER; break;
343 case DNS_EFETCHED: ec = GPG_ERR_ALREADY_FETCHED; break;
344 case DNS_ESERVICE: ec = GPG_ERR_NOT_SUPPORTED; break;
345 case DNS_ENONAME: ec = GPG_ERR_NO_NAME; break;
346 case DNS_EFAIL: ec = GPG_ERR_SERVER_FAILED; break;
347 case DNS_ECONNFIN: ec = GPG_ERR_DNS_CLOSED; break;
348 case DNS_EVERIFY: ec = GPG_ERR_DNS_VERIFY; break;
352 ec = gpg_err_code_from_errno (serr);
354 ec = GPG_ERR_DNS_UNKNOWN;
357 return gpg_error (ec);
359 #endif /*USE_LIBDNS*/
363 /* Initialize libdns. Returns 0 on success; prints a diagnostic and
364 * returns an error code on failure. */
373 if (libdns.resolv_conf)
374 return 0; /* Already initialized. */
376 memset (&ld, 0, sizeof ld);
378 ld.resolv_conf = dns_resconf_open (&derr);
381 err = libdns_error_to_gpg_error (derr);
382 log_error ("failed to allocate DNS resconf object: %s\n",
389 if (!*tor_nameserver)
390 set_dns_nameserver (NULL);
392 if (!libdns_tor_port)
393 libdns_tor_port = TOR_PORT;
395 cfgstr = xtryasprintf ("[%s]:53", tor_nameserver);
397 err = gpg_error_from_syserror ();
399 err = libdns_error_to_gpg_error
400 (dns_resconf_pton (&ld.resolv_conf->nameserver[0], cfgstr));
402 log_error ("failed to set nameserver '%s': %s\n",
403 cfgstr, gpg_strerror (err));
407 ld.resolv_conf->options.tcp = DNS_RESCONF_TCP_SOCKS;
410 cfgstr = xtryasprintf ("[%s]:%d", "127.0.0.1", libdns_tor_port);
412 err = gpg_error_from_syserror ();
414 err = libdns_error_to_gpg_error
415 (dns_resconf_pton (&ld.socks_host, cfgstr));
418 log_error ("failed to set socks server '%s': %s\n",
419 cfgstr, gpg_strerror (err));
425 #ifdef HAVE_W32_SYSTEM
432 ninfo = xtrymalloc (ninfo_len);
435 err = gpg_error_from_syserror ();
439 if (GetNetworkParams (ninfo, &ninfo_len))
441 log_error ("GetNetworkParms failed: %s\n", w32_strerror (-1));
442 err = gpg_error (GPG_ERR_GENERAL);
447 for (idx=0, pip = &(ninfo->DnsServerList);
448 pip && idx < DIM (ld.resolv_conf->nameserver);
452 log_debug ("dns: dnsserver[%d] '%s'\n", idx, pip->IpAddress.String);
453 err = libdns_error_to_gpg_error
454 (dns_resconf_pton (&ld.resolv_conf->nameserver[idx],
455 pip->IpAddress.String));
457 log_error ("failed to set nameserver[%d] '%s': %s\n",
458 idx, pip->IpAddress.String, gpg_strerror (err));
467 fname = "/etc/resolv.conf";
468 err = libdns_error_to_gpg_error
469 (dns_resconf_loadpath (ld.resolv_conf, fname));
472 log_error ("failed to load '%s': %s\n", fname, gpg_strerror (err));
476 fname = "/etc/nsswitch.conf";
477 err = libdns_error_to_gpg_error
478 (dns_nssconf_loadpath (ld.resolv_conf, fname));
481 log_error ("failed to load '%s': %s\n", fname, gpg_strerror (err));
488 ld.hosts = dns_hosts_open (&derr);
491 log_error ("failed to load hosts file: %s\n", gpg_strerror (err));
492 err = libdns_error_to_gpg_error (derr);
496 /* dns_hints_local for stub mode, dns_hints_root for recursive. */
497 ld.hints = (recursive_resolver
498 ? dns_hints_root (ld.resolv_conf, &derr)
499 : dns_hints_local (ld.resolv_conf, &derr));
502 log_error ("failed to load DNS hints: %s\n", gpg_strerror (err));
503 err = libdns_error_to_gpg_error (derr);
507 /* All fine. Make the data global. */
514 #endif /*USE_LIBDNS*/
518 /* Deinitialize libdns. */
524 if (!libdns.resolv_conf)
525 return; /* Not initialized. */
528 memset (&libdns, 0, sizeof libdns);
529 dns_hints_close (ld.hints);
530 dns_hosts_close (ld.hosts);
531 dns_resconf_close (ld.resolv_conf);
533 #endif /*USE_LIBDNS*/
536 /* SIGHUP action handler for this module. With FORCE set objects are
537 * all immediately released. */
539 reload_dns_stuff (int force)
545 libdns_reinit_pending = 0;
548 libdns_reinit_pending = 1;
557 * Initialize libdns if needed and open a dns_resolver context.
558 * Returns 0 on success and stores the new context at R_RES. On
559 * failure an error code is returned and NULL stored at R_RES.
562 libdns_res_open (struct dns_resolver **r_res)
565 struct dns_resolver *res;
570 if (libdns_reinit_pending)
572 libdns_reinit_pending = 0;
576 err = libdns_init ();
583 res = dns_res_open (libdns.resolv_conf, libdns.hosts, libdns.hints, NULL,
584 dns_opts (.socks_host = &libdns.socks_host,
585 .socks_user = tor_socks_user,
586 .socks_password = tor_socks_password ),
589 return libdns_error_to_gpg_error (derr);
594 #endif /*USE_LIBDNS*/
598 /* Helper to test whether we need totry again after having swicthed
601 libdns_switch_port_p (gpg_error_t err)
603 if (tor_mode && gpg_err_code (err) == GPG_ERR_ECONNREFUSED
604 && libdns_tor_port == TOR_PORT)
606 /* Switch port and try again. */
608 log_debug ("dns: switching from SOCKS port %d to %d\n",
609 TOR_PORT, TOR_PORT2);
610 libdns_tor_port = TOR_PORT2;
611 libdns_reinit_pending = 1;
616 #endif /*USE_LIBDNS*/
620 /* Wrapper around dns_res_submit. */
622 libdns_res_submit (struct dns_resolver *res, const char *qname,
623 enum dns_type qtype, enum dns_class qclass)
625 return libdns_error_to_gpg_error (dns_res_submit (res, qname, qtype, qclass));
627 #endif /*USE_LIBDNS*/
631 /* Standard event handling loop. */
633 libdns_res_wait (struct dns_resolver *res)
637 while ((err = libdns_error_to_gpg_error (dns_res_check (res)))
638 && gpg_err_code (err) == GPG_ERR_EAGAIN)
640 if (dns_res_elapsed (res) > opt_timeout)
642 err = gpg_error (GPG_ERR_DNS_TIMEOUT);
647 dns_res_poll (res, 1);
653 #endif /*USE_LIBDNS*/
658 resolve_name_libdns (const char *name, unsigned short port,
659 int want_family, int want_socktype,
660 dns_addrinfo_t *r_dai, char **r_canonname)
663 dns_addrinfo_t daihead = NULL;
665 struct dns_resolver *res = NULL;
666 struct dns_addrinfo *ai = NULL;
667 struct addrinfo hints;
668 struct addrinfo *ent;
670 char *portstr = NULL;
677 memset (&hints, 0, sizeof hints);
678 hints.ai_family = want_family;
679 hints.ai_socktype = want_socktype;
680 hints.ai_flags = AI_ADDRCONFIG;
682 hints.ai_flags |= AI_CANONNAME;
686 snprintf (portstr_, sizeof portstr_, "%hu", port);
690 err = libdns_res_open (&res);
694 ai = dns_ai_open (name, portstr, 0, &hints, res, &derr);
697 err = libdns_error_to_gpg_error (derr);
701 /* Loop over all records. */
704 err = libdns_error_to_gpg_error (dns_ai_nextent (&ent, ai));
705 if (gpg_err_code (err) == GPG_ERR_ENOENT)
708 err = 0; /* We got some results, we're good. */
711 if (gpg_err_code (err) == GPG_ERR_EAGAIN)
713 if (dns_ai_elapsed (ai) > opt_timeout)
715 err = gpg_error (GPG_ERR_DNS_TIMEOUT);
727 if (r_canonname && ! *r_canonname && ent && ent->ai_canonname)
729 *r_canonname = xtrystrdup (ent->ai_canonname);
732 err = gpg_error_from_syserror ();
737 dai = xtrymalloc (sizeof *dai + ent->ai_addrlen -1);
740 err = gpg_error_from_syserror ();
744 dai->family = ent->ai_family;
745 dai->socktype = ent->ai_socktype;
746 dai->protocol = ent->ai_protocol;
747 dai->addrlen = ent->ai_addrlen;
748 memcpy (dai->addr, ent->ai_addr, ent->ai_addrlen);
763 xfree (*r_canonname);
766 free_dns_addrinfo (daihead);
773 #endif /*USE_LIBDNS*/
776 /* Resolve a name using the standard system function. */
778 resolve_name_standard (const char *name, unsigned short port,
779 int want_family, int want_socktype,
780 dns_addrinfo_t *r_dai, char **r_canonname)
783 dns_addrinfo_t daihead = NULL;
785 struct addrinfo *aibuf = NULL;
786 struct addrinfo hints, *ai;
794 memset (&hints, 0, sizeof hints);
795 hints.ai_family = want_family;
796 hints.ai_socktype = want_socktype;
797 hints.ai_flags = AI_ADDRCONFIG;
799 hints.ai_flags |= AI_CANONNAME;
802 snprintf (portstr, sizeof portstr, "%hu", port);
806 /* We can't use the the AI_IDN flag because that does the conversion
807 using the current locale. However, GnuPG always used UTF-8. To
808 support IDN we would need to make use of the libidn API. */
809 ret = getaddrinfo (name, *portstr? portstr : NULL, &hints, &aibuf);
813 err = map_eai_to_gpg_error (ret);
814 if (gpg_err_code (err) == GPG_ERR_NO_NAME)
816 /* There seems to be a bug in the glibc getaddrinfo function
817 if the CNAME points to a long list of A and AAAA records
818 in which case the function return NO_NAME. Let's do the
819 CNAME redirection again. */
822 if (get_dns_cname (name, &cname))
823 goto leave; /* Still no success. */
825 ret = getaddrinfo (cname, *portstr? portstr : NULL, &hints, &aibuf);
830 err = map_eai_to_gpg_error (ret);
833 err = 0; /* Yep, now it worked. */
839 if (r_canonname && aibuf && aibuf->ai_canonname)
841 *r_canonname = xtrystrdup (aibuf->ai_canonname);
844 err = gpg_error_from_syserror ();
849 for (ai = aibuf; ai; ai = ai->ai_next)
851 if (ai->ai_family != AF_INET6 && ai->ai_family != AF_INET)
854 dai = xtrymalloc (sizeof *dai + ai->ai_addrlen - 1);
855 dai->family = ai->ai_family;
856 dai->socktype = ai->ai_socktype;
857 dai->protocol = ai->ai_protocol;
858 dai->addrlen = ai->ai_addrlen;
859 memcpy (dai->addr, ai->ai_addr, ai->ai_addrlen);
866 freeaddrinfo (aibuf);
871 xfree (*r_canonname);
874 free_dns_addrinfo (daihead);
882 /* Resolve an address using the standard system function. */
884 resolve_addr_standard (const struct sockaddr *addr, int addrlen,
885 unsigned int flags, char **r_name)
895 buffer = xtrymalloc (buflen + 2 + 1);
897 return gpg_error_from_syserror ();
899 if ((flags & DNS_NUMERICHOST) || tor_mode)
902 ec = getnameinfo (addr, addrlen, buffer, buflen, NULL, 0, NI_NAMEREQD);
904 if (!ec && *buffer == '[')
905 ec = EAI_FAIL; /* A name may never start with a bracket. */
906 else if (ec == EAI_NONAME)
909 if (addr->sa_family == AF_INET6 && (flags & DNS_WITHBRACKET))
914 ec = getnameinfo (addr, addrlen, p, buflen, NULL, 0, NI_NUMERICHOST);
915 if (!ec && addr->sa_family == AF_INET6 && (flags & DNS_WITHBRACKET))
916 strcat (buffer, "]");
920 err = map_eai_to_gpg_error (ec);
923 p = xtryrealloc (buffer, strlen (buffer)+1);
925 err = gpg_error_from_syserror ();
942 /* This a wrapper around getaddrinfo with slightly different semantics.
943 NAME is the name to resolve.
944 PORT is the requested port or 0.
945 WANT_FAMILY is either 0 (AF_UNSPEC), AF_INET6, or AF_INET4.
946 WANT_SOCKETTYPE is either SOCK_STREAM or SOCK_DGRAM.
948 On success the result is stored in a linked list with the head
949 stored at the address R_AI; the caller must call gpg_addrinfo_free
950 on this. If R_CANONNAME is not NULL the official name of the host
951 is stored there as a malloced string; if that name is not available
954 resolve_dns_name (const char *name, unsigned short port,
955 int want_family, int want_socktype,
956 dns_addrinfo_t *r_ai, char **r_canonname)
961 if (!standard_resolver)
963 err = resolve_name_libdns (name, port, want_family, want_socktype,
965 if (err && libdns_switch_port_p (err))
966 err = resolve_name_libdns (name, port, want_family, want_socktype,
970 #endif /*USE_LIBDNS*/
971 err = resolve_name_standard (name, port, want_family, want_socktype,
974 log_debug ("dns: resolve_dns_name(%s): %s\n", name, gpg_strerror (err));
980 resolve_dns_addr (const struct sockaddr *addr, int addrlen,
981 unsigned int flags, char **r_name)
983 return resolve_addr_standard (addr, addrlen, flags, r_name);
987 /* Check whether NAME is an IP address. Returns true if it is either
988 an IPv6 or IPv4 numerical address. */
990 is_ip_address (const char *name)
993 int ndots, dblcol, n;
996 return 1; /* yes: A legal DNS name may not contain this character;
997 this mut be bracketed v6 address. */
999 return 0; /* No. A leading dot is not a valid IP address. */
1001 /* Check whether this is a v6 address. */
1002 ndots = n = dblcol = 0;
1003 for (s=name; *s; s++)
1012 return 0; /* No: Only one "::" allowed. */
1021 else if (!strchr ("0123456789abcdefABCDEF", *s))
1022 return 0; /* No: Not a hex digit. */
1024 return 0; /* To many digits in a group. */
1027 return 0; /* No: Too many colons. */
1029 return 1; /* Yes: At least 2 colons indicate an v6 address. */
1032 /* Check whether it is legacy IP address. */
1034 for (s=name; *s; s++)
1039 return 0; /* No: Douple dot. */
1040 if (atoi (s+1) > 255)
1041 return 0; /* No: Ipv4 byte value too large. */
1045 else if (!strchr ("0123456789", *s))
1046 return 0; /* No: Not a digit. */
1048 return 0; /* No: More than 3 digits. */
1050 return !!(ndots == 3);
1054 /* Return true if NAME is an onion address. */
1056 is_onion_address (const char *name)
1060 len = name? strlen (name) : 0;
1061 if (len < 8 || strcmp (name + len - 6, ".onion"))
1063 /* Note that we require at least 2 characters before the suffix. */
1064 return 1; /* Yes. */
1068 /* libdns version of get_dns_cert. */
1071 get_dns_cert_libdns (const char *name, int want_certtype,
1072 void **r_key, size_t *r_keylen,
1073 unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1076 struct dns_resolver *res = NULL;
1077 struct dns_packet *ans = NULL;
1079 struct dns_rr_i rri;
1080 char host[DNS_D_MAXNAME + 1];
1084 /* Gte the query type from WANT_CERTTYPE (which in general indicates
1085 * the subtype we want). */
1086 qtype = (want_certtype < DNS_CERTTYPE_RRBASE
1088 : (want_certtype - DNS_CERTTYPE_RRBASE));
1091 err = libdns_res_open (&res);
1095 if (dns_d_anchor (host, sizeof host, name, strlen (name)) >= sizeof host)
1097 err = gpg_error (GPG_ERR_ENAMETOOLONG);
1101 err = libdns_res_submit (res, name, qtype, DNS_C_IN);
1105 err = libdns_res_wait (res);
1109 ans = dns_res_fetch (res, &derr);
1112 err = libdns_error_to_gpg_error (derr);
1116 /* Check the rcode. */
1117 switch (dns_p_rcode (ans))
1119 case DNS_RC_NOERROR: break;
1120 case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
1121 default: err = GPG_ERR_SERVER_FAILED; break;
1126 memset (&rri, 0, sizeof rri);
1127 dns_rr_i_init (&rri, ans);
1128 rri.section = DNS_S_ALL & ~DNS_S_QD;
1132 err = gpg_error (GPG_ERR_NOT_FOUND);
1133 while (dns_rr_grep (&rr, 1, &rri, ans, &derr))
1135 unsigned char *rp = ans->data + rr.rd.p;
1136 unsigned short len = rr.rd.len;
1141 /* Definitely too short - skip. */
1143 else if (want_certtype >= DNS_CERTTYPE_RRBASE
1144 && rr.type == (want_certtype - DNS_CERTTYPE_RRBASE)
1147 *r_key = xtrymalloc (len);
1149 err = gpg_error_from_syserror ();
1152 memcpy (*r_key, rp, len);
1158 else if (want_certtype >= DNS_CERTTYPE_RRBASE)
1160 /* We did not found the requested RR - skip. */
1162 else if (rr.type == T_CERT && len > 5)
1164 /* We got a CERT type. */
1165 subtype = buf16_to_u16 (rp);
1168 /* Skip the CERT key tag and algo which we don't need. */
1171 if (want_certtype && want_certtype != subtype)
1172 ; /* Not the requested subtype - skip. */
1173 else if (subtype == DNS_CERTTYPE_PGP && len && r_key && r_keylen)
1176 *r_key = xtrymalloc (len);
1178 err = gpg_error_from_syserror ();
1181 memcpy (*r_key, rp, len);
1187 else if (subtype == DNS_CERTTYPE_IPGP
1188 && len && len < 1023 && len >= rp[0] + 1)
1194 *r_fpr = xtrymalloc (*r_fprlen);
1197 err = gpg_error_from_syserror ();
1200 memcpy (*r_fpr, rp+1, *r_fprlen);
1205 if (len > *r_fprlen + 1)
1207 *r_url = xtrymalloc (len - (*r_fprlen + 1) + 1);
1210 err = gpg_error_from_syserror ();
1215 memcpy (*r_url, rp + *r_fprlen + 1, len - (*r_fprlen + 1));
1216 (*r_url)[len - (*r_fprlen + 1)] = 0;
1226 /* Unknown subtype or record too short - skip. */
1231 /* Not a requested type - skip. */
1237 dns_res_close (res);
1240 #endif /*USE_LIBDNS*/
1243 /* Standard resolver version of get_dns_cert. */
1245 get_dns_cert_standard (const char *name, int want_certtype,
1246 void **r_key, size_t *r_keylen,
1247 unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1249 #ifdef HAVE_SYSTEM_RESOLVER
1251 unsigned char *answer;
1255 /* Allocate a 64k buffer which is the limit for an DNS response. */
1256 answer = xtrymalloc (65536);
1258 return gpg_error_from_syserror ();
1260 err = gpg_error (GPG_ERR_NOT_FOUND);
1261 r = res_query (name, C_IN,
1262 (want_certtype < DNS_CERTTYPE_RRBASE
1264 : (want_certtype - DNS_CERTTYPE_RRBASE)),
1266 /* Not too big, not too small, no errors and at least 1 answer. */
1267 if (r >= sizeof (HEADER) && r <= 65536
1268 && (((HEADER *)(void *) answer)->rcode) == NOERROR
1269 && (count = ntohs (((HEADER *)(void *) answer)->ancount)))
1272 unsigned char *pt, *emsg;
1276 pt = &answer[sizeof (HEADER)];
1278 /* Skip over the query */
1280 rc = dn_skipname (pt, emsg);
1283 err = gpg_error (GPG_ERR_INV_OBJ);
1286 pt += rc + QFIXEDSZ;
1288 /* There are several possible response types for a CERT request.
1289 We're interested in the PGP (a key) and IPGP (a URI) types.
1290 Skip all others. TODO: A key is better than a URI since
1291 we've gone through all this bother to fetch it, so favor that
1292 if we have both PGP and IPGP? */
1294 while (count-- > 0 && pt < emsg)
1296 u16 type, class, dlen, ctype;
1298 rc = dn_skipname (pt, emsg); /* the name we just queried for */
1301 err = gpg_error (GPG_ERR_INV_OBJ);
1307 /* Truncated message? 15 bytes takes us to the point where
1308 we start looking at the ctype. */
1309 if ((emsg - pt) < 15)
1312 type = buf16_to_u16 (pt);
1315 class = buf16_to_u16 (pt);
1325 dlen = buf16_to_u16 (pt);
1328 /* Check the type and parse. */
1329 if (want_certtype >= DNS_CERTTYPE_RRBASE
1330 && type == (want_certtype - DNS_CERTTYPE_RRBASE)
1333 *r_key = xtrymalloc (dlen);
1335 err = gpg_error_from_syserror ();
1338 memcpy (*r_key, pt, dlen);
1344 else if (want_certtype >= DNS_CERTTYPE_RRBASE)
1346 /* We did not found the requested RR. */
1349 else if (type == T_CERT)
1351 /* We got a CERT type. */
1352 ctype = buf16_to_u16 (pt);
1355 /* Skip the CERT key tag and algo which we don't need. */
1360 /* 15 bytes takes us to here */
1361 if (want_certtype && want_certtype != ctype)
1362 ; /* Not of the requested certtype. */
1363 else if (ctype == DNS_CERTTYPE_PGP && dlen && r_key && r_keylen)
1366 *r_key = xtrymalloc (dlen);
1368 err = gpg_error_from_syserror ();
1371 memcpy (*r_key, pt, dlen);
1377 else if (ctype == DNS_CERTTYPE_IPGP
1378 && dlen && dlen < 1023 && dlen >= pt[0] + 1)
1384 *r_fpr = xtrymalloc (*r_fprlen);
1387 err = gpg_error_from_syserror ();
1390 memcpy (*r_fpr, &pt[1], *r_fprlen);
1395 if (dlen > *r_fprlen + 1)
1397 *r_url = xtrymalloc (dlen - (*r_fprlen + 1) + 1);
1400 err = gpg_error_from_syserror ();
1405 memcpy (*r_url, &pt[*r_fprlen + 1],
1406 dlen - (*r_fprlen + 1));
1407 (*r_url)[dlen - (*r_fprlen + 1)] = '\0';
1416 /* No subtype matches, so continue with the next answer. */
1421 /* Not a requested type - might be a CNAME. Try next item. */
1431 #else /*!HAVE_SYSTEM_RESOLVER*/
1434 (void)want_certtype;
1440 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1442 #endif /*!HAVE_SYSTEM_RESOLVER*/
1446 /* Returns 0 on success or an error code. If a PGP CERT record was
1447 found, the malloced data is returned at (R_KEY, R_KEYLEN) and
1448 the other return parameters are set to NULL/0. If an IPGP CERT
1449 record was found the fingerprint is stored as an allocated block at
1450 R_FPR and its length at R_FPRLEN; an URL is is allocated as a
1451 string and returned at R_URL. If WANT_CERTTYPE is 0 this function
1452 returns the first CERT found with a supported type; it is expected
1453 that only one CERT record is used. If WANT_CERTTYPE is one of the
1454 supported certtypes only records with this certtype are considered
1455 and the first found is returned. (R_KEY,R_KEYLEN) are optional. */
1457 get_dns_cert (const char *name, int want_certtype,
1458 void **r_key, size_t *r_keylen,
1459 unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1472 if (!standard_resolver)
1474 err = get_dns_cert_libdns (name, want_certtype, r_key, r_keylen,
1475 r_fpr, r_fprlen, r_url);
1476 if (err && libdns_switch_port_p (err))
1477 err = get_dns_cert_libdns (name, want_certtype, r_key, r_keylen,
1478 r_fpr, r_fprlen, r_url);
1481 #endif /*USE_LIBDNS*/
1482 err = get_dns_cert_standard (name, want_certtype, r_key, r_keylen,
1483 r_fpr, r_fprlen, r_url);
1486 log_debug ("dns: get_dns_cert(%s): %s\n", name, gpg_strerror (err));
1492 priosort(const void *a,const void *b)
1494 const struct srventry *sa=a,*sb=b;
1495 if(sa->priority>sb->priority)
1497 else if(sa->priority<sb->priority)
1504 /* Libdns based helper for getsrv. Note that it is expected that NULL
1505 * is stored at the address of LIST and 0 is stored at the address of
1509 getsrv_libdns (const char *name, struct srventry **list, unsigned int *r_count)
1512 struct dns_resolver *res = NULL;
1513 struct dns_packet *ans = NULL;
1515 struct dns_rr_i rri;
1516 char host[DNS_D_MAXNAME + 1];
1518 unsigned int srvcount = 0;
1520 err = libdns_res_open (&res);
1524 if (dns_d_anchor (host, sizeof host, name, strlen (name)) >= sizeof host)
1526 err = gpg_error (GPG_ERR_ENAMETOOLONG);
1530 err = libdns_res_submit (res, name, DNS_T_SRV, DNS_C_IN);
1534 err = libdns_res_wait (res);
1538 ans = dns_res_fetch (res, &derr);
1541 err = libdns_error_to_gpg_error (derr);
1545 /* Check the rcode. */
1546 switch (dns_p_rcode (ans))
1548 case DNS_RC_NOERROR: break;
1549 case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
1550 default: err = GPG_ERR_SERVER_FAILED; break;
1555 memset (&rri, 0, sizeof rri);
1556 dns_rr_i_init (&rri, ans);
1557 rri.section = DNS_S_ALL & ~DNS_S_QD;
1559 rri.type = DNS_T_SRV;
1561 while (dns_rr_grep (&rr, 1, &rri, ans, &derr))
1563 struct dns_srv dsrv;
1564 struct srventry *srv;
1565 struct srventry *newlist;
1567 err = libdns_error_to_gpg_error (dns_srv_parse(&dsrv, &rr, ans));
1571 newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));
1574 err = gpg_error_from_syserror ();
1578 memset (&(*list)[srvcount], 0, sizeof(struct srventry));
1579 srv = &(*list)[srvcount];
1581 srv->priority = dsrv.priority;
1582 srv->weight = dsrv.weight;
1583 srv->port = dsrv.port;
1584 mem2str (srv->target, dsrv.target, sizeof srv->target);
1587 *r_count = srvcount;
1596 dns_res_close (res);
1599 #endif /*USE_LIBDNS*/
1602 /* Standard resolver based helper for getsrv. Note that it is
1603 * expected that NULL is stored at the address of LIST and 0 is stored
1604 * at the address of R_COUNT. */
1606 getsrv_standard (const char *name,
1607 struct srventry **list, unsigned int *r_count)
1609 #ifdef HAVE_SYSTEM_RESOLVER
1611 unsigned char ans[2048];
1614 unsigned char *answer = res.ans;
1615 HEADER *header = res.header;
1616 unsigned char *pt, *emsg;
1619 unsigned int srvcount = 0;
1622 /* Do not allow a query using the standard resolver in Tor mode. */
1624 return gpg_error (GPG_ERR_NOT_ENABLED);
1627 r = res_query (name, C_IN, T_SRV, answer, sizeof res.ans);
1630 return get_h_errno_as_gpg_error ();
1631 if (r < sizeof (HEADER))
1632 return gpg_error (GPG_ERR_SERVER_FAILED);
1633 if (r > sizeof res.ans)
1634 return gpg_error (GPG_ERR_SYSTEM_BUG);
1635 if (header->rcode != NOERROR || !(count=ntohs (header->ancount)))
1636 return gpg_error (GPG_ERR_NO_NAME); /* Error or no record found. */
1639 pt = &answer[sizeof(HEADER)];
1641 /* Skip over the query */
1642 rc = dn_skipname (pt, emsg);
1646 pt += rc + QFIXEDSZ;
1648 while (count-- > 0 && pt < emsg)
1650 struct srventry *srv;
1652 struct srventry *newlist;
1654 newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));
1658 memset (&(*list)[srvcount], 0, sizeof(struct srventry));
1659 srv = &(*list)[srvcount];
1662 rc = dn_skipname (pt, emsg); /* The name we just queried for. */
1667 /* Truncated message? */
1671 type = buf16_to_u16 (pt);
1673 /* We asked for SRV and got something else !? */
1677 class = buf16_to_u16 (pt);
1679 /* We asked for IN and got something else !? */
1684 dlen = buf16_to_u16 (pt);
1687 srv->priority = buf16_to_ushort (pt);
1689 srv->weight = buf16_to_ushort (pt);
1691 srv->port = buf16_to_ushort (pt);
1694 /* Get the name. 2782 doesn't allow name compression, but
1695 * dn_expand still works to pull the name out of the packet. */
1696 rc = dn_expand (answer, emsg, pt, srv->target, sizeof srv->target);
1697 if (rc == 1 && srv->target[0] == 0) /* "." */
1706 /* Corrupt packet? */
1711 *r_count = srvcount;
1717 return gpg_error (GPG_ERR_GENERAL);
1719 #else /*!HAVE_SYSTEM_RESOLVER*/
1724 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1726 #endif /*!HAVE_SYSTEM_RESOLVER*/
1730 /* Note that we do not return NONAME but simply store 0 at R_COUNT. */
1732 get_dns_srv (const char *name, struct srventry **list, unsigned int *r_count)
1735 unsigned int srvcount;
1742 if (!standard_resolver)
1744 err = getsrv_libdns (name, list, &srvcount);
1745 if (err && libdns_switch_port_p (err))
1746 err = getsrv_libdns (name, list, &srvcount);
1749 #endif /*USE_LIBDNS*/
1750 err = getsrv_standard (name, list, &srvcount);
1754 if (gpg_err_code (err) == GPG_ERR_NO_NAME)
1759 /* Now we have an array of all the srv records. */
1761 /* Order by priority */
1762 qsort(*list,srvcount,sizeof(struct srventry),priosort);
1764 /* For each priority, move the zero-weighted items first. */
1765 for (i=0; i < srvcount; i++)
1769 for (j=i;j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)
1771 if((*list)[j].weight==0)
1776 struct srventry temp;
1778 memcpy (&temp,&(*list)[j],sizeof(struct srventry));
1779 memcpy (&(*list)[j],&(*list)[i],sizeof(struct srventry));
1780 memcpy (&(*list)[i],&temp,sizeof(struct srventry));
1788 /* Run the RFC-2782 weighting algorithm. We don't need very high
1789 quality randomness for this, so regular libc srand/rand is
1797 srand (time (NULL)*getpid());
1801 for (i=0; i < srvcount; i++)
1804 float prio_count=0,chose;
1806 for (j=i; j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)
1808 prio_count+=(*list)[j].weight;
1809 (*list)[j].run_count=prio_count;
1812 chose=prio_count*rand()/RAND_MAX;
1814 for (j=i;j<srvcount && (*list)[i].priority==(*list)[j].priority;j++)
1816 if (chose<=(*list)[j].run_count)
1821 struct srventry temp;
1823 memcpy(&temp,&(*list)[j],sizeof(struct srventry));
1824 memcpy(&(*list)[j],&(*list)[i],sizeof(struct srventry));
1825 memcpy(&(*list)[i],&temp,sizeof(struct srventry));
1836 log_debug ("dns: getsrv(%s): %s\n", name, gpg_strerror (err));
1838 log_debug ("dns: getsrv(%s) -> %u records\n", name, srvcount);
1841 *r_count = srvcount;
1848 /* libdns version of get_dns_cname. */
1850 get_dns_cname_libdns (const char *name, char **r_cname)
1853 struct dns_resolver *res;
1854 struct dns_packet *ans = NULL;
1855 struct dns_cname cname;
1858 err = libdns_res_open (&res);
1862 err = libdns_res_submit (res, name, DNS_T_CNAME, DNS_C_IN);
1866 err = libdns_res_wait (res);
1870 ans = dns_res_fetch (res, &derr);
1873 err = libdns_error_to_gpg_error (derr);
1877 /* Check the rcode. */
1878 switch (dns_p_rcode (ans))
1880 case DNS_RC_NOERROR: break;
1881 case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
1882 default: err = GPG_ERR_SERVER_FAILED; break;
1887 /* Parse the result into CNAME. */
1888 err = libdns_error_to_gpg_error (dns_p_study (ans));
1892 if (!dns_d_cname (&cname, sizeof cname, name, strlen (name), ans, &derr))
1894 err = libdns_error_to_gpg_error (derr);
1899 *r_cname = xtrystrdup (cname.host);
1901 err = gpg_error_from_syserror ();
1905 dns_res_close (res);
1908 #endif /*USE_LIBDNS*/
1911 /* Standard resolver version of get_dns_cname. */
1913 get_dns_cname_standard (const char *name, char **r_cname)
1915 #ifdef HAVE_SYSTEM_RESOLVER
1919 unsigned char ans[2048];
1922 unsigned char *answer = res.ans;
1923 HEADER *header = res.header;
1924 unsigned char *pt, *emsg;
1927 int cnamesize = 1025;
1930 /* Do not allow a query using the standard resolver in Tor mode. */
1935 r = res_query (name, C_IN, T_CERT, answer, sizeof res.ans);
1938 return get_h_errno_as_gpg_error ();
1939 if (r < sizeof (HEADER))
1940 return gpg_error (GPG_ERR_SERVER_FAILED);
1941 if (r > sizeof res.ans)
1942 return gpg_error (GPG_ERR_SYSTEM_BUG);
1943 if (header->rcode != NOERROR || !(count=ntohs (header->ancount)))
1944 return gpg_error (GPG_ERR_NO_NAME); /* Error or no record found. */
1946 return gpg_error (GPG_ERR_SERVER_FAILED);
1949 pt = &answer[sizeof(HEADER)];
1950 rc = dn_skipname (pt, emsg);
1952 return gpg_error (GPG_ERR_SERVER_FAILED);
1954 pt += rc + QFIXEDSZ;
1956 return gpg_error (GPG_ERR_SERVER_FAILED);
1958 rc = dn_skipname (pt, emsg);
1960 return gpg_error (GPG_ERR_SERVER_FAILED);
1961 pt += rc + 2 + 2 + 4;
1963 return gpg_error (GPG_ERR_SERVER_FAILED);
1964 pt += 2; /* Skip rdlen */
1966 cname = xtrymalloc (cnamesize);
1968 return gpg_error_from_syserror ();
1970 rc = dn_expand (answer, emsg, pt, cname, cnamesize -1);
1974 return gpg_error (GPG_ERR_SERVER_FAILED);
1976 *r_cname = xtryrealloc (cname, strlen (cname)+1);
1979 err = gpg_error_from_syserror ();
1985 #else /*!HAVE_SYSTEM_RESOLVER*/
1989 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1991 #endif /*!HAVE_SYSTEM_RESOLVER*/
1996 get_dns_cname (const char *name, char **r_cname)
2003 if (!standard_resolver)
2005 err = get_dns_cname_libdns (name, r_cname);
2006 if (err && libdns_switch_port_p (err))
2007 err = get_dns_cname_libdns (name, r_cname);
2010 #endif /*USE_LIBDNS*/
2012 err = get_dns_cname_standard (name, r_cname);
2014 log_debug ("get_dns_cname(%s)%s%s\n", name,
2015 err ? ": " : " -> ",
2016 err ? gpg_strerror (err) : *r_cname);