1 /* dns-stuff.c - DNS related code including CERT RR (rfc-4398)
2 * Copyright (C) 2003, 2005, 2006, 2009 Free Software Foundation, Inc.
3 * Copyright (C) 2005, 2006, 2009, 2015. 2016 Werner Koch
5 * This file is part of GnuPG.
7 * This file is free software; you can redistribute it and/or modify
8 * it under the terms of either
10 * - the GNU Lesser General Public License as published by the Free
11 * Software Foundation; either version 3 of the License, or (at
12 * your option) any later version.
16 * - the GNU General Public License as published by the Free
17 * Software Foundation; either version 2 of the License, or (at
18 * your option) any later version.
20 * or both in parallel, as here.
22 * This file is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, see <https://www.gnu.org/licenses/>.
32 #include <sys/types.h>
33 #ifdef HAVE_W32_SYSTEM
34 # define WIN32_LEAN_AND_MEAN
35 # ifdef HAVE_WINSOCK2_H
36 # include <winsock2.h>
39 # include <iphlpapi.h>
41 # if HAVE_SYSTEM_RESOLVER
42 # include <netinet/in.h>
43 # include <arpa/nameser.h>
49 # include <sys/stat.h>
55 /* William Ahern's DNS library, included as a source copy. */
60 /* dns.c has a dns_p_free but it is not exported. We use our own
61 * wrapper here so that we do not accidentally use xfree which would
62 * be wrong for dns.c allocated data. */
63 #define dns_free(a) free ((a))
66 #ifdef WITHOUT_NPTH /* Give the Makefile a chance to build without Pth. */
73 #include "./dirmngr-err.h"
74 #include "../common/util.h"
75 #include "../common/host2net.h"
76 #include "dns-stuff.h"
79 # define my_unprotect() npth_unprotect ()
80 # define my_protect() npth_protect ()
82 # define my_unprotect() do { } while(0)
83 # define my_protect() do { } while(0)
86 /* We allow the use of 0 instead of AF_UNSPEC - check this assumption. */
88 # error AF_UNSPEC does not have the value 0
91 /* Windows does not support the AI_ADDRCONFIG flag - use zero instead. */
93 # define AI_ADDRCONFIG 0
96 /* Not every installation has gotten around to supporting SRVs or
104 /* The standard SOCKS and TOR ports. */
105 #define SOCKS_PORT 1080
106 #define TOR_PORT 9050
107 #define TOR_PORT2 9150 /* (Used by the Tor browser) */
110 /* The default nameserver used in Tor mode. */
111 #define DEFAULT_NAMESERVER "8.8.8.8"
113 /* The default timeout in seconds for libdns requests. */
114 #define DEFAULT_TIMEOUT 30
117 #define RESOLV_CONF_NAME "/etc/resolv.conf"
119 /* Two flags to enable verbose and debug mode. */
120 static int opt_verbose;
121 static int opt_debug;
123 /* The timeout in seconds for libdns requests. */
124 static int opt_timeout;
126 /* The flag to disable IPv4 access - right now this only skips
127 * returned A records. */
128 static int opt_disable_ipv4;
130 /* The flag to disable IPv6 access - right now this only skips
131 * returned AAAA records. */
132 static int opt_disable_ipv6;
134 /* If set force the use of the standard resolver. */
135 static int standard_resolver;
137 /* If set use recursive resolver when available. */
138 static int recursive_resolver;
140 /* If set Tor mode shall be used. */
143 /* A string with the nameserver IP address used with Tor.
144 (40 should be sufficient for v6 but we add some extra for a scope.) */
145 static char tor_nameserver[40+20];
147 /* Two strings to hold the credentials presented to Tor. */
148 static char tor_socks_user[30];
149 static char tor_socks_password[20];
153 /* Libdns gobal data. */
156 struct dns_resolv_conf *resolv_conf;
157 struct dns_hosts *hosts;
158 struct dns_hints *hints;
160 struct sockaddr_storage socks_host;
163 /* If this flag is set, libdns shall be reinited for the next use. */
164 static int libdns_reinit_pending;
166 /* The Tor port to be used. */
167 static int libdns_tor_port;
169 #endif /*USE_LIBDNS*/
172 /* Calling this function with YES set to True forces the use of the
173 * standard resolver even if dirmngr has been built with support for
174 * an alternative resolver. */
176 enable_standard_resolver (int yes)
178 standard_resolver = yes;
182 /* Return true if the standard resolver is used. */
184 standard_resolver_p (void)
186 return standard_resolver;
190 /* Calling this function with YES switches libdns into recursive mode.
191 * It has no effect on the standard resolver. */
193 enable_recursive_resolver (int yes)
195 recursive_resolver = yes;
197 libdns_reinit_pending = 1;
202 /* Return true iff the recursive resolver is used. */
204 recursive_resolver_p (void)
207 return !standard_resolver && recursive_resolver;
214 /* Puts this module eternally into Tor mode. When called agained with
215 * NEW_CIRCUIT request a new TOR circuit for the next DNS query. */
217 enable_dns_tormode (int new_circuit)
219 if (!*tor_socks_user || new_circuit)
221 static unsigned int counter;
223 gpgrt_snprintf (tor_socks_user, sizeof tor_socks_user,
224 "dirmngr-%lu", (unsigned long)getpid ());
225 gpgrt_snprintf (tor_socks_password, sizeof tor_socks_password,
233 /* Disable tor mode. */
235 disable_dns_tormode (void)
241 /* Set verbosity and debug mode for this module. */
243 set_dns_verbose (int verbose, int debug)
245 opt_verbose = verbose;
250 /* Set the Disable-IPv4 flag so that the name resolver does not return
253 set_dns_disable_ipv4 (int yes)
255 opt_disable_ipv4 = !!yes;
259 /* Set the Disable-IPv6 flag so that the name resolver does not return
262 set_dns_disable_ipv6 (int yes)
264 opt_disable_ipv6 = !!yes;
268 /* Set the timeout for libdns requests to SECONDS. A value of 0 sets
269 * the default timeout and values are capped at 10 minutes. */
271 set_dns_timeout (int seconds)
274 seconds = DEFAULT_TIMEOUT;
275 else if (seconds < 1)
277 else if (seconds > 600)
280 opt_timeout = seconds;
284 /* Change the default IP address of the nameserver to IPADDR. The
285 address needs to be a numerical IP address and will be used for the
286 next DNS query. Note that this is only used in Tor mode. */
288 set_dns_nameserver (const char *ipaddr)
290 strncpy (tor_nameserver, ipaddr? ipaddr : DEFAULT_NAMESERVER,
291 sizeof tor_nameserver -1);
292 tor_nameserver[sizeof tor_nameserver -1] = 0;
294 libdns_reinit_pending = 1;
295 libdns_tor_port = 0; /* Start again with the default port. */
300 /* Free an addressinfo linked list as returned by resolve_dns_name. */
302 free_dns_addrinfo (dns_addrinfo_t ai)
306 dns_addrinfo_t next = ai->next;
313 #ifndef HAVE_W32_SYSTEM
314 /* Return H_ERRNO mapped to a gpg-error code. Will never return 0. */
316 get_h_errno_as_gpg_error (void)
322 case HOST_NOT_FOUND: ec = GPG_ERR_NO_NAME; break;
323 case TRY_AGAIN: ec = GPG_ERR_TRY_LATER; break;
324 case NO_RECOVERY: ec = GPG_ERR_SERVER_FAILED; break;
325 case NO_DATA: ec = GPG_ERR_NO_DATA; break;
326 default: ec = GPG_ERR_UNKNOWN_ERRNO; break;
328 return gpg_error (ec);
330 #endif /*!HAVE_W32_SYSTEM*/
333 map_eai_to_gpg_error (int ec)
339 case EAI_AGAIN: err = gpg_error (GPG_ERR_EAGAIN); break;
340 case EAI_BADFLAGS: err = gpg_error (GPG_ERR_INV_FLAG); break;
341 case EAI_FAIL: err = gpg_error (GPG_ERR_SERVER_FAILED); break;
342 case EAI_MEMORY: err = gpg_error (GPG_ERR_ENOMEM); break;
344 case EAI_NODATA: err = gpg_error (GPG_ERR_NO_DATA); break;
346 case EAI_NONAME: err = gpg_error (GPG_ERR_NO_NAME); break;
347 case EAI_SERVICE: err = gpg_error (GPG_ERR_NOT_SUPPORTED); break;
348 case EAI_FAMILY: err = gpg_error (GPG_ERR_EAFNOSUPPORT); break;
349 case EAI_SOCKTYPE: err = gpg_error (GPG_ERR_ESOCKTNOSUPPORT); break;
350 #ifndef HAVE_W32_SYSTEM
351 # ifdef EAI_ADDRFAMILY
352 case EAI_ADDRFAMILY:err = gpg_error (GPG_ERR_EADDRNOTAVAIL); break;
354 case EAI_SYSTEM: err = gpg_error_from_syserror (); break;
356 default: err = gpg_error (GPG_ERR_UNKNOWN_ERRNO); break;
364 libdns_error_to_gpg_error (int serr)
370 case 0: ec = 0; break;
372 case DNS_ENOBUFS: ec = GPG_ERR_BUFFER_TOO_SHORT; break;
373 case DNS_EILLEGAL: ec = GPG_ERR_INV_OBJ; break;
374 case DNS_EORDER: ec = GPG_ERR_INV_ORDER; break;
375 case DNS_ESECTION: ec = GPG_ERR_DNS_SECTION; break;
376 case DNS_EUNKNOWN: ec = GPG_ERR_DNS_UNKNOWN; break;
377 case DNS_EADDRESS: ec = GPG_ERR_DNS_ADDRESS; break;
378 case DNS_ENOQUERY: ec = GPG_ERR_DNS_NO_QUERY; break;
379 case DNS_ENOANSWER:ec = GPG_ERR_DNS_NO_ANSWER; break;
380 case DNS_EFETCHED: ec = GPG_ERR_ALREADY_FETCHED; break;
381 case DNS_ESERVICE: ec = GPG_ERR_NOT_SUPPORTED; break;
382 case DNS_ENONAME: ec = GPG_ERR_NO_NAME; break;
383 case DNS_EFAIL: ec = GPG_ERR_SERVER_FAILED; break;
384 case DNS_ECONNFIN: ec = GPG_ERR_DNS_CLOSED; break;
385 case DNS_EVERIFY: ec = GPG_ERR_DNS_VERIFY; break;
389 ec = gpg_err_code_from_errno (serr);
391 ec = GPG_ERR_DNS_UNKNOWN;
394 return gpg_error (ec);
396 #endif /*USE_LIBDNS*/
399 /* Return true if resolve.conf changed since it was last loaded. */
402 resolv_conf_changed_p (void)
404 #if defined(HAVE_W32_SYSTEM) || !defined(HAVE_STAT)
407 static time_t last_mtime;
408 const char *fname = RESOLV_CONF_NAME;
412 if (stat (fname, &statbuf))
414 log_error ("stat'ing '%s' failed: %s\n",
415 fname, gpg_strerror (gpg_error_from_syserror ()));
416 last_mtime = 1; /* Force a "changed" result the next time stat
419 else if (!last_mtime)
420 last_mtime = statbuf.st_mtime;
421 else if (last_mtime != statbuf.st_mtime)
424 last_mtime = statbuf.st_mtime;
430 #endif /*USE_LIBDNS*/
433 /* Initialize libdns. Returns 0 on success; prints a diagnostic and
434 * returns an error code on failure. */
443 if (libdns.resolv_conf)
444 return 0; /* Already initialized. */
446 memset (&ld, 0, sizeof ld);
448 ld.resolv_conf = dns_resconf_open (&derr);
451 err = libdns_error_to_gpg_error (derr);
452 log_error ("failed to allocate DNS resconf object: %s\n",
459 if (!*tor_nameserver)
460 set_dns_nameserver (NULL);
462 if (!libdns_tor_port)
463 libdns_tor_port = TOR_PORT;
465 cfgstr = xtryasprintf ("[%s]:53", tor_nameserver);
467 err = gpg_error_from_syserror ();
469 err = libdns_error_to_gpg_error
470 (dns_resconf_pton (&ld.resolv_conf->nameserver[0], cfgstr));
472 log_error ("failed to set nameserver '%s': %s\n",
473 cfgstr, gpg_strerror (err));
477 ld.resolv_conf->options.tcp = DNS_RESCONF_TCP_SOCKS;
480 cfgstr = xtryasprintf ("[%s]:%d", "127.0.0.1", libdns_tor_port);
482 err = gpg_error_from_syserror ();
484 err = libdns_error_to_gpg_error
485 (dns_resconf_pton (&ld.socks_host, cfgstr));
488 log_error ("failed to set socks server '%s': %s\n",
489 cfgstr, gpg_strerror (err));
495 #ifdef HAVE_W32_SYSTEM
502 ninfo = xtrymalloc (ninfo_len);
505 err = gpg_error_from_syserror ();
509 if (GetNetworkParams (ninfo, &ninfo_len))
511 log_error ("GetNetworkParms failed: %s\n", w32_strerror (-1));
512 err = gpg_error (GPG_ERR_GENERAL);
517 for (idx=0, pip = &(ninfo->DnsServerList);
518 pip && idx < DIM (ld.resolv_conf->nameserver);
522 log_debug ("dns: dnsserver[%d] '%s'\n", idx, pip->IpAddress.String);
523 err = libdns_error_to_gpg_error
524 (dns_resconf_pton (&ld.resolv_conf->nameserver[idx],
525 pip->IpAddress.String));
527 log_error ("failed to set nameserver[%d] '%s': %s\n",
528 idx, pip->IpAddress.String, gpg_strerror (err));
537 fname = RESOLV_CONF_NAME;
538 resolv_conf_changed_p (); /* Reset timestamp. */
539 err = libdns_error_to_gpg_error
540 (dns_resconf_loadpath (ld.resolv_conf, fname));
543 log_error ("failed to load '%s': %s\n", fname, gpg_strerror (err));
547 fname = "/etc/nsswitch.conf";
548 err = libdns_error_to_gpg_error
549 (dns_nssconf_loadpath (ld.resolv_conf, fname));
552 /* This is not a fatal error: nsswitch.conf is not used on
553 * all systems; assume classic behavior instead. */
554 if (gpg_err_code (err) != GPG_ERR_ENOENT)
555 log_error ("failed to load '%s': %s\n", fname, gpg_strerror (err));
557 log_debug ("dns: fallback resolution order, files then DNS\n");
558 ld.resolv_conf->lookup[0] = 'f';
559 ld.resolv_conf->lookup[1] = 'b';
560 ld.resolv_conf->lookup[2] = '\0';
561 err = GPG_ERR_NO_ERROR;
563 else if (!strchr (ld.resolv_conf->lookup, 'b'))
565 /* No DNS resolution type found in the list. This might be
566 * due to systemd based systems which allow for custom
567 * keywords which are not known to us and thus we do not
568 * know whether DNS is wanted or not. Because DNS is
569 * important for our infrastructure, we forcefully append
570 * DNS to the end of the list. */
571 if (strlen (ld.resolv_conf->lookup)+2 < sizeof ld.resolv_conf->lookup)
574 log_debug ("dns: appending DNS to resolution order\n");
575 strcat (ld.resolv_conf->lookup, "b");
578 log_error ("failed to append DNS to resolution order\n");
584 ld.hosts = dns_hosts_open (&derr);
587 err = libdns_error_to_gpg_error (derr);
588 log_error ("failed to initialize hosts file: %s\n", gpg_strerror (err));
594 char *hosts_path = xtryasprintf ("%s\\System32\\drivers\\etc\\hosts",
595 getenv ("SystemRoot"));
598 err = gpg_error_from_syserror ();
602 derr = dns_hosts_loadpath (ld.hosts, hosts_path);
605 derr = dns_hosts_loadpath (ld.hosts, "/etc/hosts");
609 err = libdns_error_to_gpg_error (derr);
610 log_error ("failed to load hosts file: %s\n", gpg_strerror (err));
611 err = 0; /* Do not bail out - having no /etc/hosts is legal. */
615 /* dns_hints_local for stub mode, dns_hints_root for recursive. */
616 ld.hints = (recursive_resolver
617 ? dns_hints_root (ld.resolv_conf, &derr)
618 : dns_hints_local (ld.resolv_conf, &derr));
621 err = libdns_error_to_gpg_error (derr);
622 log_error ("failed to load DNS hints: %s\n", gpg_strerror (err));
626 /* All fine. Make the data global. */
630 log_debug ("dns: libdns initialized%s\n", tor_mode?" (tor mode)":"");
636 #endif /*USE_LIBDNS*/
640 /* Deinitialize libdns. */
646 if (!libdns.resolv_conf)
647 return; /* Not initialized. */
650 memset (&libdns, 0, sizeof libdns);
651 dns_hints_close (ld.hints);
652 dns_hosts_close (ld.hosts);
653 dns_resconf_close (ld.resolv_conf);
655 #endif /*USE_LIBDNS*/
658 /* SIGHUP action handler for this module. With FORCE set objects are
659 * all immediately released. */
661 reload_dns_stuff (int force)
667 libdns_reinit_pending = 0;
671 libdns_reinit_pending = 1;
672 libdns_tor_port = 0; /* Start again with the default port. */
682 * Initialize libdns if needed and open a dns_resolver context.
683 * Returns 0 on success and stores the new context at R_RES. On
684 * failure an error code is returned and NULL stored at R_RES.
687 libdns_res_open (struct dns_resolver **r_res)
690 struct dns_resolver *res;
695 /* Force a reload if resolv.conf has changed. */
696 if (resolv_conf_changed_p ())
699 log_debug ("dns: resolv.conf changed - forcing reload\n");
700 libdns_reinit_pending = 1;
703 if (libdns_reinit_pending)
705 libdns_reinit_pending = 0;
709 err = libdns_init ();
716 res = dns_res_open (libdns.resolv_conf, libdns.hosts, libdns.hints, NULL,
717 dns_opts (.socks_host = &libdns.socks_host,
718 .socks_user = tor_socks_user,
719 .socks_password = tor_socks_password ),
722 return libdns_error_to_gpg_error (derr);
727 #endif /*USE_LIBDNS*/
731 /* Helper to test whether we need to try again after having switched
734 libdns_switch_port_p (gpg_error_t err)
736 if (tor_mode && gpg_err_code (err) == GPG_ERR_ECONNREFUSED
737 && libdns_tor_port == TOR_PORT)
739 /* Switch port and try again. */
741 log_debug ("dns: switching from SOCKS port %d to %d\n",
742 TOR_PORT, TOR_PORT2);
743 libdns_tor_port = TOR_PORT2;
744 libdns_reinit_pending = 1;
749 #endif /*USE_LIBDNS*/
753 /* Wrapper around dns_res_submit. */
755 libdns_res_submit (struct dns_resolver *res, const char *qname,
756 enum dns_type qtype, enum dns_class qclass)
758 return libdns_error_to_gpg_error (dns_res_submit (res, qname, qtype, qclass));
760 #endif /*USE_LIBDNS*/
764 /* Standard event handling loop. */
766 libdns_res_wait (struct dns_resolver *res)
770 while ((err = libdns_error_to_gpg_error (dns_res_check (res)))
771 && gpg_err_code (err) == GPG_ERR_EAGAIN)
773 if (dns_res_elapsed (res) > opt_timeout)
775 err = gpg_error (GPG_ERR_DNS_TIMEOUT);
780 dns_res_poll (res, 1);
786 #endif /*USE_LIBDNS*/
791 resolve_name_libdns (const char *name, unsigned short port,
792 int want_family, int want_socktype,
793 dns_addrinfo_t *r_dai, char **r_canonname)
796 dns_addrinfo_t daihead = NULL;
798 struct dns_resolver *res = NULL;
799 struct dns_addrinfo *ai = NULL;
800 struct addrinfo hints;
801 struct addrinfo *ent;
803 char *portstr = NULL;
804 char *namebuf = NULL;
811 memset (&hints, 0, sizeof hints);
812 hints.ai_family = want_family;
813 hints.ai_socktype = want_socktype;
814 hints.ai_flags = AI_ADDRCONFIG;
816 hints.ai_flags |= AI_CANONNAME;
820 snprintf (portstr_, sizeof portstr_, "%hu", port);
824 err = libdns_res_open (&res);
829 if (is_ip_address (name))
831 hints.ai_flags |= AI_NUMERICHOST;
832 /* libdns does not grok brackets - remove them. */
833 if (*name == '[' && name[strlen(name)-1] == ']')
835 namebuf = xtrymalloc (strlen (name));
838 err = gpg_error_from_syserror ();
841 strcpy (namebuf, name+1);
842 namebuf[strlen (namebuf)-1] = 0;
847 ai = dns_ai_open (name, portstr, 0, &hints, res, &derr);
850 err = libdns_error_to_gpg_error (derr);
854 /* Loop over all records. */
857 err = libdns_error_to_gpg_error (dns_ai_nextent (&ent, ai));
858 if (gpg_err_code (err) == GPG_ERR_ENOENT)
861 err = 0; /* We got some results, we're good. */
864 if (gpg_err_code (err) == GPG_ERR_EAGAIN)
866 if (dns_ai_elapsed (ai) > opt_timeout)
868 err = gpg_error (GPG_ERR_DNS_TIMEOUT);
880 if (r_canonname && ! *r_canonname && ent && ent->ai_canonname)
882 *r_canonname = xtrystrdup (ent->ai_canonname);
885 err = gpg_error_from_syserror ();
888 /* Libdns appends the root zone part which is problematic
889 * for most other functions - strip it. */
890 if (**r_canonname && (*r_canonname)[strlen (*r_canonname)-1] == '.')
891 (*r_canonname)[strlen (*r_canonname)-1] = 0;
894 dai = xtrymalloc (sizeof *dai);
897 err = gpg_error_from_syserror ();
901 dai->family = ent->ai_family;
902 dai->socktype = ent->ai_socktype;
903 dai->protocol = ent->ai_protocol;
904 dai->addrlen = ent->ai_addrlen;
905 memcpy (dai->addr, ent->ai_addr, ent->ai_addrlen);
920 xfree (*r_canonname);
923 free_dns_addrinfo (daihead);
931 #endif /*USE_LIBDNS*/
934 /* Resolve a name using the standard system function. */
936 resolve_name_standard (const char *name, unsigned short port,
937 int want_family, int want_socktype,
938 dns_addrinfo_t *r_dai, char **r_canonname)
941 dns_addrinfo_t daihead = NULL;
943 struct addrinfo *aibuf = NULL;
944 struct addrinfo hints, *ai;
952 memset (&hints, 0, sizeof hints);
953 hints.ai_family = want_family;
954 hints.ai_socktype = want_socktype;
955 hints.ai_flags = AI_ADDRCONFIG;
957 hints.ai_flags |= AI_CANONNAME;
958 if (is_ip_address (name))
959 hints.ai_flags |= AI_NUMERICHOST;
962 snprintf (portstr, sizeof portstr, "%hu", port);
966 /* We can't use the AI_IDN flag because that does the conversion
967 using the current locale. However, GnuPG always used UTF-8. To
968 support IDN we would need to make use of the libidn API. */
969 ret = getaddrinfo (name, *portstr? portstr : NULL, &hints, &aibuf);
973 err = map_eai_to_gpg_error (ret);
974 if (gpg_err_code (err) == GPG_ERR_NO_NAME)
976 /* There seems to be a bug in the glibc getaddrinfo function
977 if the CNAME points to a long list of A and AAAA records
978 in which case the function return NO_NAME. Let's do the
979 CNAME redirection again. */
982 if (get_dns_cname (name, &cname))
983 goto leave; /* Still no success. */
985 ret = getaddrinfo (cname, *portstr? portstr : NULL, &hints, &aibuf);
990 err = map_eai_to_gpg_error (ret);
993 err = 0; /* Yep, now it worked. */
999 if (r_canonname && aibuf && aibuf->ai_canonname)
1001 *r_canonname = xtrystrdup (aibuf->ai_canonname);
1004 err = gpg_error_from_syserror ();
1009 for (ai = aibuf; ai; ai = ai->ai_next)
1011 if (ai->ai_family != AF_INET6 && ai->ai_family != AF_INET)
1013 if (opt_disable_ipv4 && ai->ai_family == AF_INET)
1015 if (opt_disable_ipv6 && ai->ai_family == AF_INET6)
1018 dai = xtrymalloc (sizeof *dai);
1019 dai->family = ai->ai_family;
1020 dai->socktype = ai->ai_socktype;
1021 dai->protocol = ai->ai_protocol;
1022 dai->addrlen = ai->ai_addrlen;
1023 memcpy (dai->addr, ai->ai_addr, ai->ai_addrlen);
1024 dai->next = daihead;
1030 freeaddrinfo (aibuf);
1035 xfree (*r_canonname);
1036 *r_canonname = NULL;
1038 free_dns_addrinfo (daihead);
1046 /* This a wrapper around getaddrinfo with slightly different semantics.
1047 NAME is the name to resolve.
1048 PORT is the requested port or 0.
1049 WANT_FAMILY is either 0 (AF_UNSPEC), AF_INET6, or AF_INET4.
1050 WANT_SOCKETTYPE is either SOCK_STREAM or SOCK_DGRAM.
1052 On success the result is stored in a linked list with the head
1053 stored at the address R_AI; the caller must call gpg_addrinfo_free
1054 on this. If R_CANONNAME is not NULL the official name of the host
1055 is stored there as a malloced string; if that name is not available
1058 resolve_dns_name (const char *name, unsigned short port,
1059 int want_family, int want_socktype,
1060 dns_addrinfo_t *r_ai, char **r_canonname)
1065 if (!standard_resolver)
1067 err = resolve_name_libdns (name, port, want_family, want_socktype,
1069 if (err && libdns_switch_port_p (err))
1070 err = resolve_name_libdns (name, port, want_family, want_socktype,
1074 #endif /*USE_LIBDNS*/
1075 err = resolve_name_standard (name, port, want_family, want_socktype,
1078 log_debug ("dns: resolve_dns_name(%s): %s\n", name, gpg_strerror (err));
1084 /* Resolve an address using libdns. */
1086 resolve_addr_libdns (const struct sockaddr_storage *addr, int addrlen,
1087 unsigned int flags, char **r_name)
1090 char host[DNS_D_MAXNAME + 1];
1091 struct dns_resolver *res = NULL;
1092 struct dns_packet *ans = NULL;
1098 /* First we turn ADDR into a DNS name (with ".arpa" suffix). */
1100 if (addr->ss_family == AF_INET6)
1102 const struct sockaddr_in6 *a6 = (const struct sockaddr_in6 *)addr;
1103 if (!dns_aaaa_arpa (host, sizeof host, (void*)&a6->sin6_addr))
1104 err = gpg_error (GPG_ERR_INV_OBJ);
1106 else if (addr->ss_family == AF_INET)
1108 const struct sockaddr_in *a4 = (const struct sockaddr_in *)addr;
1109 if (!dns_a_arpa (host, sizeof host, (void*)&a4->sin_addr))
1110 err = gpg_error (GPG_ERR_INV_OBJ);
1113 err = gpg_error (GPG_ERR_EAFNOSUPPORT);
1118 err = libdns_res_open (&res);
1122 err = libdns_res_submit (res, host, DNS_T_PTR, DNS_C_IN);
1126 err = libdns_res_wait (res);
1130 ans = dns_res_fetch (res, &derr);
1133 err = libdns_error_to_gpg_error (derr);
1137 /* Check the rcode. */
1138 switch (dns_p_rcode (ans))
1140 case DNS_RC_NOERROR:
1142 case DNS_RC_NXDOMAIN:
1143 err = gpg_error (GPG_ERR_NO_NAME);
1146 err = GPG_ERR_SERVER_FAILED;
1150 /* Parse the result. */
1154 struct dns_rr_i rri;
1156 memset (&rri, 0, sizeof rri);
1157 dns_rr_i_init (&rri, ans);
1158 rri.section = DNS_S_ALL & ~DNS_S_QD;
1160 rri.type = DNS_T_PTR;
1162 if (!dns_rr_grep (&rr, 1, &rri, ans, &derr))
1164 err = gpg_error (GPG_ERR_NOT_FOUND);
1168 err = libdns_error_to_gpg_error (dns_ptr_parse (&ptr, &rr, ans));
1173 *r_name = xtrystrdup (ptr.host);
1176 err = gpg_error_from_syserror ();
1179 /* Libdns appends the root zone part which is problematic
1180 * for most other functions - strip it. */
1181 if (**r_name && (*r_name)[strlen (*r_name)-1] == '.')
1182 (*r_name)[strlen (*r_name)-1] = 0;
1184 else /* GPG_ERR_NO_NAME */
1191 buflen = sizeof ptr.host;
1194 if (addr->ss_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1199 ec = getnameinfo ((const struct sockaddr *)addr,
1200 addrlen, p, buflen, NULL, 0, NI_NUMERICHOST);
1203 err = map_eai_to_gpg_error (ec);
1206 if (addr->ss_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1207 strcat (buffer, "]");
1212 dns_res_close (res);
1215 #endif /*USE_LIBDNS*/
1218 /* Resolve an address using the standard system function. */
1220 resolve_addr_standard (const struct sockaddr_storage *addr, int addrlen,
1221 unsigned int flags, char **r_name)
1230 buflen = NI_MAXHOST;
1231 buffer = xtrymalloc (buflen + 2 + 1);
1233 return gpg_error_from_syserror ();
1235 if ((flags & DNS_NUMERICHOST) || tor_mode)
1238 ec = getnameinfo ((const struct sockaddr *)addr,
1239 addrlen, buffer, buflen, NULL, 0, NI_NAMEREQD);
1241 if (!ec && *buffer == '[')
1242 ec = EAI_FAIL; /* A name may never start with a bracket. */
1243 else if (ec == EAI_NONAME)
1246 if (addr->ss_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1251 ec = getnameinfo ((const struct sockaddr *)addr,
1252 addrlen, p, buflen, NULL, 0, NI_NUMERICHOST);
1253 if (!ec && addr->ss_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1254 strcat (buffer, "]");
1258 err = map_eai_to_gpg_error (ec);
1261 p = xtryrealloc (buffer, strlen (buffer)+1);
1263 err = gpg_error_from_syserror ();
1280 /* A wrapper around getnameinfo. */
1282 resolve_dns_addr (const struct sockaddr_storage *addr, int addrlen,
1283 unsigned int flags, char **r_name)
1288 /* Note that we divert to the standard resolver for NUMERICHOST. */
1289 if (!standard_resolver && !(flags & DNS_NUMERICHOST))
1291 err = resolve_addr_libdns (addr, addrlen, flags, r_name);
1292 if (err && libdns_switch_port_p (err))
1293 err = resolve_addr_libdns (addr, addrlen, flags, r_name);
1296 #endif /*USE_LIBDNS*/
1297 err = resolve_addr_standard (addr, addrlen, flags, r_name);
1300 log_debug ("dns: resolve_dns_addr(): %s\n", gpg_strerror (err));
1305 /* Check whether NAME is an IP address. Returns a true if it is
1306 * either an IPv6 or a IPv4 numerical address. The actual return
1307 * values can also be used to identify whether it is v4 or v6: The
1308 * true value will surprisingly be 4 for IPv4 and 6 for IPv6. */
1310 is_ip_address (const char *name)
1313 int ndots, dblcol, n;
1316 return 6; /* yes: A legal DNS name may not contain this character;
1317 this must be bracketed v6 address. */
1319 return 0; /* No. A leading dot is not a valid IP address. */
1321 /* Check whether this is a v6 address. */
1322 ndots = n = dblcol = 0;
1323 for (s=name; *s; s++)
1332 return 0; /* No: Only one "::" allowed. */
1341 else if (!strchr ("0123456789abcdefABCDEF", *s))
1342 return 0; /* No: Not a hex digit. */
1344 return 0; /* To many digits in a group. */
1347 return 0; /* No: Too many colons. */
1349 return 6; /* Yes: At least 2 colons indicate an v6 address. */
1352 /* Check whether it is legacy IP address. */
1354 for (s=name; *s; s++)
1359 return 0; /* No: Double dot. */
1360 if (atoi (s+1) > 255)
1361 return 0; /* No: Ipv4 byte value too large. */
1365 else if (!strchr ("0123456789", *s))
1366 return 0; /* No: Not a digit. */
1368 return 0; /* No: More than 3 digits. */
1370 return (ndots == 3)? 4 : 0;
1374 /* Return true if NAME is an onion address. */
1376 is_onion_address (const char *name)
1380 len = name? strlen (name) : 0;
1381 if (len < 8 || strcmp (name + len - 6, ".onion"))
1383 /* Note that we require at least 2 characters before the suffix. */
1384 return 1; /* Yes. */
1388 /* libdns version of get_dns_cert. */
1391 get_dns_cert_libdns (const char *name, int want_certtype,
1392 void **r_key, size_t *r_keylen,
1393 unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1396 struct dns_resolver *res = NULL;
1397 struct dns_packet *ans = NULL;
1399 struct dns_rr_i rri;
1400 char host[DNS_D_MAXNAME + 1];
1404 /* Get the query type from WANT_CERTTYPE (which in general indicates
1405 * the subtype we want). */
1406 qtype = (want_certtype < DNS_CERTTYPE_RRBASE
1408 : (want_certtype - DNS_CERTTYPE_RRBASE));
1411 err = libdns_res_open (&res);
1415 if (dns_d_anchor (host, sizeof host, name, strlen (name)) >= sizeof host)
1417 err = gpg_error (GPG_ERR_ENAMETOOLONG);
1421 err = libdns_res_submit (res, name, qtype, DNS_C_IN);
1425 err = libdns_res_wait (res);
1429 ans = dns_res_fetch (res, &derr);
1432 err = libdns_error_to_gpg_error (derr);
1436 /* Check the rcode. */
1437 switch (dns_p_rcode (ans))
1439 case DNS_RC_NOERROR: break;
1440 case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
1441 default: err = GPG_ERR_SERVER_FAILED; break;
1446 memset (&rri, 0, sizeof rri);
1447 dns_rr_i_init (&rri, ans);
1448 rri.section = DNS_S_ALL & ~DNS_S_QD;
1452 err = gpg_error (GPG_ERR_NOT_FOUND);
1453 while (dns_rr_grep (&rr, 1, &rri, ans, &derr))
1455 unsigned char *rp = ans->data + rr.rd.p;
1456 unsigned short len = rr.rd.len;
1461 /* Definitely too short - skip. */
1463 else if (want_certtype >= DNS_CERTTYPE_RRBASE
1464 && rr.type == (want_certtype - DNS_CERTTYPE_RRBASE)
1467 *r_key = xtrymalloc (len);
1469 err = gpg_error_from_syserror ();
1472 memcpy (*r_key, rp, len);
1478 else if (want_certtype >= DNS_CERTTYPE_RRBASE)
1480 /* We did not found the requested RR - skip. */
1482 else if (rr.type == T_CERT && len > 5)
1484 /* We got a CERT type. */
1485 subtype = buf16_to_u16 (rp);
1488 /* Skip the CERT key tag and algo which we don't need. */
1491 if (want_certtype && want_certtype != subtype)
1492 ; /* Not the requested subtype - skip. */
1493 else if (subtype == DNS_CERTTYPE_PGP && len && r_key && r_keylen)
1496 *r_key = xtrymalloc (len);
1498 err = gpg_error_from_syserror ();
1501 memcpy (*r_key, rp, len);
1507 else if (subtype == DNS_CERTTYPE_IPGP
1508 && len && len < 1023 && len >= rp[0] + 1)
1514 *r_fpr = xtrymalloc (*r_fprlen);
1517 err = gpg_error_from_syserror ();
1520 memcpy (*r_fpr, rp+1, *r_fprlen);
1525 if (len > *r_fprlen + 1)
1527 *r_url = xtrymalloc (len - (*r_fprlen + 1) + 1);
1530 err = gpg_error_from_syserror ();
1535 memcpy (*r_url, rp + *r_fprlen + 1, len - (*r_fprlen + 1));
1536 (*r_url)[len - (*r_fprlen + 1)] = 0;
1546 /* Unknown subtype or record too short - skip. */
1551 /* Not a requested type - skip. */
1557 dns_res_close (res);
1560 #endif /*USE_LIBDNS*/
1563 /* Standard resolver version of get_dns_cert. */
1565 get_dns_cert_standard (const char *name, int want_certtype,
1566 void **r_key, size_t *r_keylen,
1567 unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1569 #ifdef HAVE_SYSTEM_RESOLVER
1571 unsigned char *answer;
1575 /* Allocate a 64k buffer which is the limit for an DNS response. */
1576 answer = xtrymalloc (65536);
1578 return gpg_error_from_syserror ();
1580 err = gpg_error (GPG_ERR_NOT_FOUND);
1581 r = res_query (name, C_IN,
1582 (want_certtype < DNS_CERTTYPE_RRBASE
1584 : (want_certtype - DNS_CERTTYPE_RRBASE)),
1586 /* Not too big, not too small, no errors and at least 1 answer. */
1587 if (r >= sizeof (HEADER) && r <= 65536
1588 && (((HEADER *)(void *) answer)->rcode) == NOERROR
1589 && (count = ntohs (((HEADER *)(void *) answer)->ancount)))
1592 unsigned char *pt, *emsg;
1596 pt = &answer[sizeof (HEADER)];
1598 /* Skip over the query */
1600 rc = dn_skipname (pt, emsg);
1603 err = gpg_error (GPG_ERR_INV_OBJ);
1606 pt += rc + QFIXEDSZ;
1608 /* There are several possible response types for a CERT request.
1609 We're interested in the PGP (a key) and IPGP (a URI) types.
1610 Skip all others. TODO: A key is better than a URI since
1611 we've gone through all this bother to fetch it, so favor that
1612 if we have both PGP and IPGP? */
1614 while (count-- > 0 && pt < emsg)
1616 u16 type, class, dlen, ctype;
1618 rc = dn_skipname (pt, emsg); /* the name we just queried for */
1621 err = gpg_error (GPG_ERR_INV_OBJ);
1627 /* Truncated message? 15 bytes takes us to the point where
1628 we start looking at the ctype. */
1629 if ((emsg - pt) < 15)
1632 type = buf16_to_u16 (pt);
1635 class = buf16_to_u16 (pt);
1645 dlen = buf16_to_u16 (pt);
1648 /* Check the type and parse. */
1649 if (want_certtype >= DNS_CERTTYPE_RRBASE
1650 && type == (want_certtype - DNS_CERTTYPE_RRBASE)
1653 *r_key = xtrymalloc (dlen);
1655 err = gpg_error_from_syserror ();
1658 memcpy (*r_key, pt, dlen);
1664 else if (want_certtype >= DNS_CERTTYPE_RRBASE)
1666 /* We did not found the requested RR. */
1669 else if (type == T_CERT)
1671 /* We got a CERT type. */
1672 ctype = buf16_to_u16 (pt);
1675 /* Skip the CERT key tag and algo which we don't need. */
1680 /* 15 bytes takes us to here */
1681 if (want_certtype && want_certtype != ctype)
1682 ; /* Not of the requested certtype. */
1683 else if (ctype == DNS_CERTTYPE_PGP && dlen && r_key && r_keylen)
1686 *r_key = xtrymalloc (dlen);
1688 err = gpg_error_from_syserror ();
1691 memcpy (*r_key, pt, dlen);
1697 else if (ctype == DNS_CERTTYPE_IPGP
1698 && dlen && dlen < 1023 && dlen >= pt[0] + 1)
1704 *r_fpr = xtrymalloc (*r_fprlen);
1707 err = gpg_error_from_syserror ();
1710 memcpy (*r_fpr, &pt[1], *r_fprlen);
1715 if (dlen > *r_fprlen + 1)
1717 *r_url = xtrymalloc (dlen - (*r_fprlen + 1) + 1);
1720 err = gpg_error_from_syserror ();
1725 memcpy (*r_url, &pt[*r_fprlen + 1],
1726 dlen - (*r_fprlen + 1));
1727 (*r_url)[dlen - (*r_fprlen + 1)] = '\0';
1736 /* No subtype matches, so continue with the next answer. */
1741 /* Not a requested type - might be a CNAME. Try next item. */
1751 #else /*!HAVE_SYSTEM_RESOLVER*/
1754 (void)want_certtype;
1760 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1762 #endif /*!HAVE_SYSTEM_RESOLVER*/
1766 /* Returns 0 on success or an error code. If a PGP CERT record was
1767 found, the malloced data is returned at (R_KEY, R_KEYLEN) and
1768 the other return parameters are set to NULL/0. If an IPGP CERT
1769 record was found the fingerprint is stored as an allocated block at
1770 R_FPR and its length at R_FPRLEN; an URL is allocated as a
1771 string and returned at R_URL. If WANT_CERTTYPE is 0 this function
1772 returns the first CERT found with a supported type; it is expected
1773 that only one CERT record is used. If WANT_CERTTYPE is one of the
1774 supported certtypes only records with this certtype are considered
1775 and the first found is returned. (R_KEY,R_KEYLEN) are optional. */
1777 get_dns_cert (const char *name, int want_certtype,
1778 void **r_key, size_t *r_keylen,
1779 unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1792 if (!standard_resolver)
1794 err = get_dns_cert_libdns (name, want_certtype, r_key, r_keylen,
1795 r_fpr, r_fprlen, r_url);
1796 if (err && libdns_switch_port_p (err))
1797 err = get_dns_cert_libdns (name, want_certtype, r_key, r_keylen,
1798 r_fpr, r_fprlen, r_url);
1801 #endif /*USE_LIBDNS*/
1802 err = get_dns_cert_standard (name, want_certtype, r_key, r_keylen,
1803 r_fpr, r_fprlen, r_url);
1806 log_debug ("dns: get_dns_cert(%s): %s\n", name, gpg_strerror (err));
1812 priosort(const void *a,const void *b)
1814 const struct srventry *sa=a,*sb=b;
1815 if(sa->priority>sb->priority)
1817 else if(sa->priority<sb->priority)
1824 /* Libdns based helper for getsrv. Note that it is expected that NULL
1825 * is stored at the address of LIST and 0 is stored at the address of
1829 getsrv_libdns (const char *name, struct srventry **list, unsigned int *r_count)
1832 struct dns_resolver *res = NULL;
1833 struct dns_packet *ans = NULL;
1835 struct dns_rr_i rri;
1836 char host[DNS_D_MAXNAME + 1];
1838 unsigned int srvcount = 0;
1840 err = libdns_res_open (&res);
1844 if (dns_d_anchor (host, sizeof host, name, strlen (name)) >= sizeof host)
1846 err = gpg_error (GPG_ERR_ENAMETOOLONG);
1850 err = libdns_res_submit (res, name, DNS_T_SRV, DNS_C_IN);
1854 err = libdns_res_wait (res);
1858 ans = dns_res_fetch (res, &derr);
1861 err = libdns_error_to_gpg_error (derr);
1865 /* Check the rcode. */
1866 switch (dns_p_rcode (ans))
1868 case DNS_RC_NOERROR: break;
1869 case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
1870 default: err = GPG_ERR_SERVER_FAILED; break;
1875 memset (&rri, 0, sizeof rri);
1876 dns_rr_i_init (&rri, ans);
1877 rri.section = DNS_S_ALL & ~DNS_S_QD;
1879 rri.type = DNS_T_SRV;
1881 while (dns_rr_grep (&rr, 1, &rri, ans, &derr))
1883 struct dns_srv dsrv;
1884 struct srventry *srv;
1885 struct srventry *newlist;
1887 err = libdns_error_to_gpg_error (dns_srv_parse(&dsrv, &rr, ans));
1891 newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));
1894 err = gpg_error_from_syserror ();
1898 memset (&(*list)[srvcount], 0, sizeof(struct srventry));
1899 srv = &(*list)[srvcount];
1901 srv->priority = dsrv.priority;
1902 srv->weight = dsrv.weight;
1903 srv->port = dsrv.port;
1904 mem2str (srv->target, dsrv.target, sizeof srv->target);
1905 /* Libdns appends the root zone part which is problematic for
1906 * most other functions - strip it. */
1907 if (*srv->target && (srv->target)[strlen (srv->target)-1] == '.')
1908 (srv->target)[strlen (srv->target)-1] = 0;
1911 *r_count = srvcount;
1920 dns_res_close (res);
1923 #endif /*USE_LIBDNS*/
1926 /* Standard resolver based helper for getsrv. Note that it is
1927 * expected that NULL is stored at the address of LIST and 0 is stored
1928 * at the address of R_COUNT. */
1930 getsrv_standard (const char *name,
1931 struct srventry **list, unsigned int *r_count)
1933 #ifdef HAVE_SYSTEM_RESOLVER
1935 unsigned char ans[2048];
1938 unsigned char *answer = res.ans;
1939 HEADER *header = res.header;
1940 unsigned char *pt, *emsg;
1943 unsigned int srvcount = 0;
1946 /* Do not allow a query using the standard resolver in Tor mode. */
1948 return gpg_error (GPG_ERR_NOT_ENABLED);
1951 r = res_query (name, C_IN, T_SRV, answer, sizeof res.ans);
1954 return get_h_errno_as_gpg_error ();
1955 if (r < sizeof (HEADER))
1956 return gpg_error (GPG_ERR_SERVER_FAILED);
1957 if (r > sizeof res.ans)
1958 return gpg_error (GPG_ERR_SYSTEM_BUG);
1959 if (header->rcode != NOERROR || !(count=ntohs (header->ancount)))
1960 return gpg_error (GPG_ERR_NO_NAME); /* Error or no record found. */
1963 pt = &answer[sizeof(HEADER)];
1965 /* Skip over the query */
1966 rc = dn_skipname (pt, emsg);
1970 pt += rc + QFIXEDSZ;
1972 while (count-- > 0 && pt < emsg)
1974 struct srventry *srv;
1976 struct srventry *newlist;
1978 newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));
1982 memset (&(*list)[srvcount], 0, sizeof(struct srventry));
1983 srv = &(*list)[srvcount];
1986 rc = dn_skipname (pt, emsg); /* The name we just queried for. */
1991 /* Truncated message? */
1995 type = buf16_to_u16 (pt);
1997 /* We asked for SRV and got something else !? */
2001 class = buf16_to_u16 (pt);
2003 /* We asked for IN and got something else !? */
2008 dlen = buf16_to_u16 (pt);
2011 srv->priority = buf16_to_ushort (pt);
2013 srv->weight = buf16_to_ushort (pt);
2015 srv->port = buf16_to_ushort (pt);
2018 /* Get the name. 2782 doesn't allow name compression, but
2019 * dn_expand still works to pull the name out of the packet. */
2020 rc = dn_expand (answer, emsg, pt, srv->target, sizeof srv->target);
2021 if (rc == 1 && srv->target[0] == 0) /* "." */
2030 /* Corrupt packet? */
2035 *r_count = srvcount;
2041 return gpg_error (GPG_ERR_GENERAL);
2043 #else /*!HAVE_SYSTEM_RESOLVER*/
2048 return gpg_error (GPG_ERR_NOT_SUPPORTED);
2050 #endif /*!HAVE_SYSTEM_RESOLVER*/
2054 /* Query a SRV record for SERVICE and PROTO for NAME. If SERVICE is
2055 * NULL, NAME is expected to contain the full query name. Note that
2056 * we do not return NONAME but simply store 0 at R_COUNT. On error an
2057 * error code is returned and 0 stored at R_COUNT. */
2059 get_dns_srv (const char *name, const char *service, const char *proto,
2060 struct srventry **list, unsigned int *r_count)
2063 char *namebuffer = NULL;
2064 unsigned int srvcount;
2071 /* If SERVICE is given construct the query from it and PROTO. */
2074 namebuffer = xtryasprintf ("_%s._%s.%s",
2075 service, proto? proto:"tcp", name);
2078 err = gpg_error_from_syserror ();
2086 if (!standard_resolver)
2088 err = getsrv_libdns (name, list, &srvcount);
2089 if (err && libdns_switch_port_p (err))
2090 err = getsrv_libdns (name, list, &srvcount);
2093 #endif /*USE_LIBDNS*/
2094 err = getsrv_standard (name, list, &srvcount);
2098 if (gpg_err_code (err) == GPG_ERR_NO_NAME)
2103 /* Now we have an array of all the srv records. */
2105 /* Order by priority */
2106 qsort(*list,srvcount,sizeof(struct srventry),priosort);
2108 /* For each priority, move the zero-weighted items first. */
2109 for (i=0; i < srvcount; i++)
2113 for (j=i;j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)
2115 if((*list)[j].weight==0)
2120 struct srventry temp;
2122 memcpy (&temp,&(*list)[j],sizeof(struct srventry));
2123 memcpy (&(*list)[j],&(*list)[i],sizeof(struct srventry));
2124 memcpy (&(*list)[i],&temp,sizeof(struct srventry));
2132 /* Run the RFC-2782 weighting algorithm. We don't need very high
2133 quality randomness for this, so regular libc srand/rand is
2141 srand (time (NULL)*getpid());
2145 for (i=0; i < srvcount; i++)
2148 float prio_count=0,chose;
2150 for (j=i; j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)
2152 prio_count+=(*list)[j].weight;
2153 (*list)[j].run_count=prio_count;
2156 chose=prio_count*rand()/RAND_MAX;
2158 for (j=i;j<srvcount && (*list)[i].priority==(*list)[j].priority;j++)
2160 if (chose<=(*list)[j].run_count)
2165 struct srventry temp;
2167 memcpy(&temp,&(*list)[j],sizeof(struct srventry));
2168 memcpy(&(*list)[j],&(*list)[i],sizeof(struct srventry));
2169 memcpy(&(*list)[i],&temp,sizeof(struct srventry));
2180 log_debug ("dns: getsrv(%s): %s\n", name, gpg_strerror (err));
2182 log_debug ("dns: getsrv(%s) -> %u records\n", name, srvcount);
2185 *r_count = srvcount;
2193 /* libdns version of get_dns_cname. */
2195 get_dns_cname_libdns (const char *name, char **r_cname)
2198 struct dns_resolver *res;
2199 struct dns_packet *ans = NULL;
2200 struct dns_cname cname;
2203 err = libdns_res_open (&res);
2207 err = libdns_res_submit (res, name, DNS_T_CNAME, DNS_C_IN);
2211 err = libdns_res_wait (res);
2215 ans = dns_res_fetch (res, &derr);
2218 err = libdns_error_to_gpg_error (derr);
2222 /* Check the rcode. */
2223 switch (dns_p_rcode (ans))
2225 case DNS_RC_NOERROR: break;
2226 case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
2227 default: err = GPG_ERR_SERVER_FAILED; break;
2232 /* Parse the result into CNAME. */
2233 err = libdns_error_to_gpg_error (dns_p_study (ans));
2237 if (!dns_d_cname (&cname, sizeof cname, name, strlen (name), ans, &derr))
2239 err = libdns_error_to_gpg_error (derr);
2244 *r_cname = xtrystrdup (cname.host);
2246 err = gpg_error_from_syserror ();
2249 /* Libdns appends the root zone part which is problematic
2250 * for most other functions - strip it. */
2251 if (**r_cname && (*r_cname)[strlen (*r_cname)-1] == '.')
2252 (*r_cname)[strlen (*r_cname)-1] = 0;
2257 dns_res_close (res);
2260 #endif /*USE_LIBDNS*/
2263 /* Standard resolver version of get_dns_cname. */
2265 get_dns_cname_standard (const char *name, char **r_cname)
2267 #ifdef HAVE_SYSTEM_RESOLVER
2271 unsigned char ans[2048];
2274 unsigned char *answer = res.ans;
2275 HEADER *header = res.header;
2276 unsigned char *pt, *emsg;
2279 int cnamesize = 1025;
2282 /* Do not allow a query using the standard resolver in Tor mode. */
2287 r = res_query (name, C_IN, T_CERT, answer, sizeof res.ans);
2290 return get_h_errno_as_gpg_error ();
2291 if (r < sizeof (HEADER))
2292 return gpg_error (GPG_ERR_SERVER_FAILED);
2293 if (r > sizeof res.ans)
2294 return gpg_error (GPG_ERR_SYSTEM_BUG);
2295 if (header->rcode != NOERROR || !(count=ntohs (header->ancount)))
2296 return gpg_error (GPG_ERR_NO_NAME); /* Error or no record found. */
2298 return gpg_error (GPG_ERR_SERVER_FAILED);
2301 pt = &answer[sizeof(HEADER)];
2302 rc = dn_skipname (pt, emsg);
2304 return gpg_error (GPG_ERR_SERVER_FAILED);
2306 pt += rc + QFIXEDSZ;
2308 return gpg_error (GPG_ERR_SERVER_FAILED);
2310 rc = dn_skipname (pt, emsg);
2312 return gpg_error (GPG_ERR_SERVER_FAILED);
2313 pt += rc + 2 + 2 + 4;
2315 return gpg_error (GPG_ERR_SERVER_FAILED);
2316 pt += 2; /* Skip rdlen */
2318 cname = xtrymalloc (cnamesize);
2320 return gpg_error_from_syserror ();
2322 rc = dn_expand (answer, emsg, pt, cname, cnamesize -1);
2326 return gpg_error (GPG_ERR_SERVER_FAILED);
2328 *r_cname = xtryrealloc (cname, strlen (cname)+1);
2331 err = gpg_error_from_syserror ();
2337 #else /*!HAVE_SYSTEM_RESOLVER*/
2341 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
2343 #endif /*!HAVE_SYSTEM_RESOLVER*/
2348 get_dns_cname (const char *name, char **r_cname)
2355 if (!standard_resolver)
2357 err = get_dns_cname_libdns (name, r_cname);
2358 if (err && libdns_switch_port_p (err))
2359 err = get_dns_cname_libdns (name, r_cname);
2362 #endif /*USE_LIBDNS*/
2364 err = get_dns_cname_standard (name, r_cname);
2366 log_debug ("get_dns_cname(%s)%s%s\n", name,
2367 err ? ": " : " -> ",
2368 err ? gpg_strerror (err) : *r_cname);