chiark / gitweb /
dirmngr: New option --no-use-tor and internal changes.
[gnupg2.git] / dirmngr / dns-stuff.c
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
4  *
5  * This file is part of GnuPG.
6  *
7  * This file is free software; you can redistribute it and/or modify
8  * it under the terms of either
9  *
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.
13  *
14  * or
15  *
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.
19  *
20  * or both in parallel, as here.
21  *
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.
26  *
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/>.
29  */
30
31 #include <config.h>
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>
37 # endif
38 # include <windows.h>
39 # include <iphlpapi.h>
40 #else
41 # if HAVE_SYSTEM_RESOLVER
42 #  include <netinet/in.h>
43 #  include <arpa/nameser.h>
44 #  include <resolv.h>
45 # endif
46 # include <netdb.h>
47 #endif
48 #include <string.h>
49 #include <unistd.h>
50
51
52 /* William Ahern's DNS library, included as a source copy.  */
53 #ifdef USE_LIBDNS
54 # include "dns.h"
55 #endif
56
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))
61
62
63 #ifdef WITHOUT_NPTH /* Give the Makefile a chance to build without Pth.  */
64 # undef USE_NPTH
65 #endif
66 #ifdef USE_NPTH
67 # include <npth.h>
68 #endif
69
70 #include "./dirmngr-err.h"
71 #include "util.h"
72 #include "host2net.h"
73 #include "dns-stuff.h"
74
75 #ifdef USE_NPTH
76 # define my_unprotect()        npth_unprotect ()
77 # define my_protect()          npth_protect ()
78 #else
79 # define my_unprotect()        do { } while(0)
80 # define my_protect()          do { } while(0)
81 #endif
82
83 /* We allow the use of 0 instead of AF_UNSPEC - check this assumption.  */
84 #if AF_UNSPEC != 0
85 # error AF_UNSPEC does not have the value 0
86 #endif
87
88 /* Windows does not support the AI_ADDRCONFIG flag - use zero instead.  */
89 #ifndef AI_ADDRCONFIG
90 # define AI_ADDRCONFIG 0
91 #endif
92
93 /* Not every installation has gotten around to supporting SRVs or
94    CERTs yet... */
95 #ifndef T_SRV
96 #define T_SRV 33
97 #endif
98 #ifndef T_CERT
99 # define T_CERT 37
100 #endif
101
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) */
106
107
108 /* The default nameserver used in Tor mode.  */
109 #define DEFAULT_NAMESERVER "8.8.8.8"
110
111 /* The default timeout in seconds for libdns requests.  */
112 #define DEFAULT_TIMEOUT 30
113
114
115 /* Two flags to enable verbose and debug mode.  */
116 static int opt_verbose;
117 static int opt_debug;
118
119 /* The timeout in seconds for libdns requests.  */
120 static int opt_timeout;
121
122 /* The flag to disable IPv4 access - right now this only skips
123  * returned A records.  */
124 static int opt_disable_ipv4;
125
126 /* If set force the use of the standard resolver.  */
127 static int standard_resolver;
128
129 /* If set use recursive resolver when available. */
130 static int recursive_resolver;
131
132 /* If set Tor mode shall be used.  */
133 static int tor_mode;
134
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];
138
139 /* Two strings to hold the credentials presented to Tor.  */
140 static char tor_socks_user[30];
141 static char tor_socks_password[20];
142
143
144 #ifdef USE_LIBDNS
145 /* Libdns gobal data.  */
146 struct libdns_s
147 {
148   struct dns_resolv_conf *resolv_conf;
149   struct dns_hosts *hosts;
150   struct dns_hints *hints;
151
152   struct sockaddr_storage socks_host;
153 } libdns;
154
155 /* If this flag is set, libdns shall be reinited for the next use.  */
156 static int libdns_reinit_pending;
157
158 /* The Tor port to be used.  */
159 static int libdns_tor_port;
160
161 #endif /*USE_LIBDNS*/
162
163
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.  */
167 void
168 enable_standard_resolver (int yes)
169 {
170   standard_resolver = yes;
171 }
172
173
174 /* Return true if the standard resolver is used.  */
175 int
176 standard_resolver_p (void)
177 {
178   return standard_resolver;
179 }
180
181
182 /* Calling this function with YES switches libdns into recursive mode.
183  * It has no effect on the standard resolver.  */
184 void
185 enable_recursive_resolver (int yes)
186 {
187   recursive_resolver = yes;
188 #ifdef USE_LIBDNS
189   libdns_reinit_pending = 1;
190 #endif
191 }
192
193
194 /* Return true iff the recursive resolver is used.  */
195 int
196 recursive_resolver_p (void)
197 {
198 #if USE_LIBDNS
199   return !standard_resolver && recursive_resolver;
200 #else
201   return 0;
202 #endif
203 }
204
205
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.  */
208 void
209 enable_dns_tormode (int new_circuit)
210 {
211   if (!*tor_socks_user || new_circuit)
212     {
213       static unsigned int counter;
214
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,
218                       "p%u", counter);
219       counter++;
220     }
221   tor_mode = 1;
222 }
223
224
225 /* Disable tor mode.  */
226 void
227 disable_dns_tormode (void)
228 {
229   tor_mode = 0;
230 }
231
232
233 /* Set verbosity and debug mode for this module. */
234 void
235 set_dns_verbose (int verbose, int debug)
236 {
237   opt_verbose = verbose;
238   opt_debug = debug;
239 }
240
241
242 /* Set the Disable-IPv4 flag so that the name resolver does not return
243  * A addresses.  */
244 void
245 set_dns_disable_ipv4 (int yes)
246 {
247   opt_disable_ipv4 = !!yes;
248 }
249
250
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.  */
253 void
254 set_dns_timeout (int seconds)
255 {
256   if (!seconds)
257     seconds = DEFAULT_TIMEOUT;
258   else if (seconds < 1)
259     seconds = 1;
260   else if (seconds > 600)
261     seconds = 600;
262
263   opt_timeout = seconds;
264 }
265
266
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.  */
270 void
271 set_dns_nameserver (const char *ipaddr)
272 {
273   strncpy (tor_nameserver, ipaddr? ipaddr : DEFAULT_NAMESERVER,
274            sizeof tor_nameserver -1);
275   tor_nameserver[sizeof tor_nameserver -1] = 0;
276 #ifdef USE_LIBDNS
277   libdns_reinit_pending = 1;
278   libdns_tor_port = 0;  /* Start again with the default port.  */
279 #endif
280 }
281
282
283 /* Free an addressinfo linked list as returned by resolve_dns_name.  */
284 void
285 free_dns_addrinfo (dns_addrinfo_t ai)
286 {
287   while (ai)
288     {
289       dns_addrinfo_t next = ai->next;
290       xfree (ai);
291       ai = next;
292     }
293 }
294
295
296 #ifndef HAVE_W32_SYSTEM
297 /* Return H_ERRNO mapped to a gpg-error code.  Will never return 0. */
298 static gpg_error_t
299 get_h_errno_as_gpg_error (void)
300 {
301   gpg_err_code_t ec;
302
303   switch (h_errno)
304     {
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;
310     }
311   return gpg_error (ec);
312 }
313 #endif /*!HAVE_W32_SYSTEM*/
314
315 static gpg_error_t
316 map_eai_to_gpg_error (int ec)
317 {
318   gpg_error_t err;
319
320   switch (ec)
321     {
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;
326 #ifdef EAI_NODATA
327     case EAI_NODATA:    err = gpg_error (GPG_ERR_NO_DATA); break;
328 #endif
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;
336 # endif
337     case EAI_SYSTEM:    err = gpg_error_from_syserror (); break;
338 #endif
339     default:            err = gpg_error (GPG_ERR_UNKNOWN_ERRNO); break;
340     }
341   return err;
342 }
343
344
345 #ifdef USE_LIBDNS
346 static gpg_error_t
347 libdns_error_to_gpg_error (int serr)
348 {
349   gpg_err_code_t ec;
350
351   switch (serr)
352     {
353     case 0: ec = 0; break;
354
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;
369
370     default:
371       if (serr >= 0)
372         ec = gpg_err_code_from_errno (serr);
373       else
374         ec = GPG_ERR_DNS_UNKNOWN;
375       break;
376     }
377   return gpg_error (ec);
378 }
379 #endif /*USE_LIBDNS*/
380
381
382 #ifdef USE_LIBDNS
383 /* Initialize libdns.  Returns 0 on success; prints a diagnostic and
384  * returns an error code on failure.  */
385 static gpg_error_t
386 libdns_init (void)
387 {
388   gpg_error_t err;
389   struct libdns_s ld;
390   int derr;
391   char *cfgstr = NULL;
392
393   if (libdns.resolv_conf)
394     return 0; /* Already initialized.  */
395
396   memset (&ld, 0, sizeof ld);
397
398   ld.resolv_conf = dns_resconf_open (&derr);
399   if (!ld.resolv_conf)
400     {
401       err = libdns_error_to_gpg_error (derr);
402       log_error ("failed to allocate DNS resconf object: %s\n",
403                  gpg_strerror (err));
404       goto leave;
405     }
406
407   if (tor_mode)
408     {
409       if (!*tor_nameserver)
410         set_dns_nameserver (NULL);
411
412       if (!libdns_tor_port)
413         libdns_tor_port = TOR_PORT;
414
415       cfgstr = xtryasprintf ("[%s]:53", tor_nameserver);
416       if (!cfgstr)
417         err = gpg_error_from_syserror ();
418       else
419         err = libdns_error_to_gpg_error
420           (dns_resconf_pton (&ld.resolv_conf->nameserver[0], cfgstr));
421       if (err)
422         log_error ("failed to set nameserver '%s': %s\n",
423                    cfgstr, gpg_strerror (err));
424       if (err)
425         goto leave;
426
427       ld.resolv_conf->options.tcp = DNS_RESCONF_TCP_SOCKS;
428
429       xfree (cfgstr);
430       cfgstr = xtryasprintf ("[%s]:%d", "127.0.0.1", libdns_tor_port);
431       if (!cfgstr)
432         err = gpg_error_from_syserror ();
433       else
434         err = libdns_error_to_gpg_error
435           (dns_resconf_pton (&ld.socks_host, cfgstr));
436       if (err)
437         {
438           log_error ("failed to set socks server '%s': %s\n",
439                      cfgstr, gpg_strerror (err));
440           goto leave;
441         }
442     }
443   else
444     {
445 #ifdef HAVE_W32_SYSTEM
446       ULONG ninfo_len;
447       PFIXED_INFO ninfo;
448       PIP_ADDR_STRING pip;
449       int idx;
450
451       ninfo_len = 2048;
452       ninfo = xtrymalloc (ninfo_len);
453       if (!ninfo)
454         {
455           err = gpg_error_from_syserror ();
456           goto leave;
457         }
458
459       if (GetNetworkParams (ninfo, &ninfo_len))
460         {
461           log_error ("GetNetworkParms failed: %s\n", w32_strerror (-1));
462           err = gpg_error (GPG_ERR_GENERAL);
463           xfree (ninfo);
464           goto leave;
465         }
466
467       for (idx=0, pip = &(ninfo->DnsServerList);
468            pip && idx < DIM (ld.resolv_conf->nameserver);
469            pip = pip->Next)
470         {
471           if (opt_debug)
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));
476           if (err)
477             log_error ("failed to set nameserver[%d] '%s': %s\n",
478                        idx, pip->IpAddress.String, gpg_strerror (err));
479           else
480             idx++;
481         }
482       xfree (ninfo);
483
484 #else /* Unix */
485       const char *fname;
486
487       fname = "/etc/resolv.conf";
488       err = libdns_error_to_gpg_error
489         (dns_resconf_loadpath (ld.resolv_conf, fname));
490       if (err)
491         {
492           log_error ("failed to load '%s': %s\n", fname, gpg_strerror (err));
493           goto leave;
494         }
495
496       fname = "/etc/nsswitch.conf";
497       err = libdns_error_to_gpg_error
498         (dns_nssconf_loadpath (ld.resolv_conf, fname));
499       if (err)
500         {
501           log_error ("failed to load '%s': %s\n", fname, gpg_strerror (err));
502           /* not fatal, nsswitch.conf is not used on all systems; assume
503            * classic behavior instead.  Our dns library states "bf" which tries
504            * DNS then Files, which is not classic; FreeBSD
505            * /usr/src/lib/libc/net/gethostnamadr.c defines default_src[] which
506            * is Files then DNS, which is. */
507           if (opt_debug)
508             log_debug ("dns: fallback resolution order, files then DNS\n");
509           ld.resolv_conf->lookup[0] = 'f';
510           ld.resolv_conf->lookup[1] = 'b';
511           ld.resolv_conf->lookup[2] = '\0';
512           err = GPG_ERR_NO_ERROR;
513         }
514
515 #endif /* Unix */
516     }
517
518   ld.hosts = dns_hosts_open (&derr);
519   if (!ld.hosts)
520     {
521       log_error ("failed to load hosts file: %s\n", gpg_strerror (err));
522       err = libdns_error_to_gpg_error (derr);
523       goto leave;
524     }
525
526   /* dns_hints_local for stub mode, dns_hints_root for recursive.  */
527   ld.hints = (recursive_resolver
528               ? dns_hints_root  (ld.resolv_conf, &derr)
529               : dns_hints_local (ld.resolv_conf, &derr));
530   if (!ld.hints)
531     {
532       log_error ("failed to load DNS hints: %s\n", gpg_strerror (err));
533       err = libdns_error_to_gpg_error (derr);
534       goto leave;
535     }
536
537   /* All fine.  Make the data global.  */
538   libdns = ld;
539
540   if (opt_debug)
541     log_debug ("dns: libdns initialized%s\n", tor_mode?" (tor mode)":"");
542
543  leave:
544   xfree (cfgstr);
545   return err;
546 }
547 #endif /*USE_LIBDNS*/
548
549
550 #ifdef USE_LIBDNS
551 /* Deinitialize libdns.  */
552 static void
553 libdns_deinit (void)
554 {
555   struct libdns_s ld;
556
557   if (!libdns.resolv_conf)
558     return; /* Not initialized.  */
559
560   ld = libdns;
561   memset (&libdns, 0, sizeof libdns);
562   dns_hints_close (ld.hints);
563   dns_hosts_close (ld.hosts);
564   dns_resconf_close (ld.resolv_conf);
565 }
566 #endif /*USE_LIBDNS*/
567
568
569 /* SIGHUP action handler for this module.  With FORCE set objects are
570  * all immediately released. */
571 void
572 reload_dns_stuff (int force)
573 {
574 #ifdef USE_LIBDNS
575   if (force)
576     {
577       libdns_deinit ();
578       libdns_reinit_pending = 0;
579     }
580   else
581     {
582       libdns_reinit_pending = 1;
583       libdns_tor_port = 0;  /* Start again with the default port.  */
584     }
585 #else
586   (void)force;
587 #endif
588 }
589
590
591 #ifdef USE_LIBDNS
592 /*
593  * Initialize libdns if needed and open a dns_resolver context.
594  * Returns 0 on success and stores the new context at R_RES.  On
595  * failure an error code is returned and NULL stored at R_RES.
596  */
597 static gpg_error_t
598 libdns_res_open (struct dns_resolver **r_res)
599 {
600   gpg_error_t err;
601   struct dns_resolver *res;
602   int derr;
603
604   *r_res = NULL;
605
606   if (libdns_reinit_pending)
607     {
608       libdns_reinit_pending = 0;
609       libdns_deinit ();
610     }
611
612   err = libdns_init ();
613   if (err)
614     return err;
615
616   if (!opt_timeout)
617     set_dns_timeout (0);
618
619   res = dns_res_open (libdns.resolv_conf, libdns.hosts, libdns.hints, NULL,
620                       dns_opts (.socks_host     = &libdns.socks_host,
621                                 .socks_user     = tor_socks_user,
622                                 .socks_password = tor_socks_password ),
623                       &derr);
624   if (!res)
625     return libdns_error_to_gpg_error (derr);
626
627   *r_res = res;
628   return 0;
629 }
630 #endif /*USE_LIBDNS*/
631
632
633 #ifdef USE_LIBDNS
634 /* Helper to test whether we need to try again after having switched
635  * the Tor port.  */
636 static int
637 libdns_switch_port_p (gpg_error_t err)
638 {
639   if (tor_mode && gpg_err_code (err) == GPG_ERR_ECONNREFUSED
640       && libdns_tor_port == TOR_PORT)
641     {
642       /* Switch port and try again.  */
643       if (opt_debug)
644         log_debug ("dns: switching from SOCKS port %d to %d\n",
645                    TOR_PORT, TOR_PORT2);
646       libdns_tor_port = TOR_PORT2;
647       libdns_reinit_pending = 1;
648       return 1;
649     }
650   return 0;
651 }
652 #endif /*USE_LIBDNS*/
653
654
655 #ifdef USE_LIBDNS
656 /* Wrapper around dns_res_submit.  */
657 static gpg_error_t
658 libdns_res_submit (struct dns_resolver *res, const char *qname,
659                    enum dns_type qtype, enum dns_class qclass)
660 {
661   return libdns_error_to_gpg_error (dns_res_submit (res, qname, qtype, qclass));
662 }
663 #endif /*USE_LIBDNS*/
664
665
666 #ifdef USE_LIBDNS
667 /* Standard event handling loop.  */
668 gpg_error_t
669 libdns_res_wait (struct dns_resolver *res)
670 {
671   gpg_error_t err;
672
673   while ((err = libdns_error_to_gpg_error (dns_res_check (res)))
674          && gpg_err_code (err) == GPG_ERR_EAGAIN)
675     {
676       if (dns_res_elapsed (res) > opt_timeout)
677         {
678           err = gpg_error (GPG_ERR_DNS_TIMEOUT);
679           break;
680         }
681
682       my_unprotect ();
683       dns_res_poll (res, 1);
684       my_protect ();
685     }
686
687   return err;
688 }
689 #endif /*USE_LIBDNS*/
690
691
692 #ifdef USE_LIBDNS
693 static gpg_error_t
694 resolve_name_libdns (const char *name, unsigned short port,
695                      int want_family, int want_socktype,
696                      dns_addrinfo_t *r_dai, char **r_canonname)
697 {
698   gpg_error_t err;
699   dns_addrinfo_t daihead = NULL;
700   dns_addrinfo_t dai;
701   struct dns_resolver *res = NULL;
702   struct dns_addrinfo *ai = NULL;
703   struct addrinfo hints;
704   struct addrinfo *ent;
705   char portstr_[21];
706   char *portstr = NULL;
707   int derr;
708
709   *r_dai = NULL;
710   if (r_canonname)
711     *r_canonname = NULL;
712
713   memset (&hints, 0, sizeof hints);
714   hints.ai_family = want_family;
715   hints.ai_socktype = want_socktype;
716   hints.ai_flags = AI_ADDRCONFIG;
717   if (r_canonname)
718     hints.ai_flags |= AI_CANONNAME;
719   if (is_ip_address (name))
720     hints.ai_flags |= AI_NUMERICHOST;
721
722   if (port)
723     {
724       snprintf (portstr_, sizeof portstr_, "%hu", port);
725       portstr = portstr_;
726     }
727
728   err = libdns_res_open (&res);
729   if (err)
730     goto leave;
731
732   ai = dns_ai_open (name, portstr, 0, &hints, res, &derr);
733   if (!ai)
734     {
735       err = libdns_error_to_gpg_error (derr);
736       goto leave;
737     }
738
739   /* Loop over all records.  */
740   for (;;)
741     {
742       err = libdns_error_to_gpg_error (dns_ai_nextent (&ent, ai));
743       if (gpg_err_code (err) == GPG_ERR_ENOENT)
744         {
745           if (daihead)
746             err = 0; /* We got some results, we're good.  */
747           break; /* Ready.  */
748         }
749       if (gpg_err_code (err) == GPG_ERR_EAGAIN)
750         {
751           if (dns_ai_elapsed (ai) > opt_timeout)
752             {
753               err = gpg_error (GPG_ERR_DNS_TIMEOUT);
754               goto leave;
755             }
756
757           my_unprotect ();
758           dns_ai_poll (ai, 1);
759           my_protect ();
760           continue;
761         }
762       if (err)
763         goto leave;
764
765       if (r_canonname && ! *r_canonname && ent && ent->ai_canonname)
766         {
767           *r_canonname = xtrystrdup (ent->ai_canonname);
768           if (!*r_canonname)
769             {
770               err = gpg_error_from_syserror ();
771               goto leave;
772             }
773           /* Libdns appends the root zone part which is problematic
774            * for most other functions - strip it.  */
775           if (**r_canonname && (*r_canonname)[strlen (*r_canonname)-1] == '.')
776             (*r_canonname)[strlen (*r_canonname)-1] = 0;
777         }
778
779       dai = xtrymalloc (sizeof *dai + ent->ai_addrlen -1);
780       if (dai == NULL)
781         {
782           err = gpg_error_from_syserror ();
783           goto leave;
784         }
785
786       dai->family = ent->ai_family;
787       dai->socktype = ent->ai_socktype;
788       dai->protocol = ent->ai_protocol;
789       dai->addrlen = ent->ai_addrlen;
790       memcpy (dai->addr, ent->ai_addr, ent->ai_addrlen);
791       dai->next = daihead;
792       daihead = dai;
793
794       xfree (ent);
795   }
796
797  leave:
798   dns_ai_close (ai);
799   dns_res_close (res);
800
801   if (err)
802     {
803       if (r_canonname)
804         {
805           xfree (*r_canonname);
806           *r_canonname = NULL;
807         }
808       free_dns_addrinfo (daihead);
809     }
810   else
811     *r_dai = daihead;
812
813   return err;
814 }
815 #endif /*USE_LIBDNS*/
816
817
818 /* Resolve a name using the standard system function.  */
819 static gpg_error_t
820 resolve_name_standard (const char *name, unsigned short port,
821                        int want_family, int want_socktype,
822                        dns_addrinfo_t *r_dai, char **r_canonname)
823 {
824   gpg_error_t err = 0;
825   dns_addrinfo_t daihead = NULL;
826   dns_addrinfo_t dai;
827   struct addrinfo *aibuf = NULL;
828   struct addrinfo hints, *ai;
829   char portstr[21];
830   int ret;
831
832   *r_dai = NULL;
833   if (r_canonname)
834     *r_canonname = NULL;
835
836   memset (&hints, 0, sizeof hints);
837   hints.ai_family = want_family;
838   hints.ai_socktype = want_socktype;
839   hints.ai_flags = AI_ADDRCONFIG;
840   if (r_canonname)
841     hints.ai_flags |= AI_CANONNAME;
842   if (is_ip_address (name))
843     hints.ai_flags |= AI_NUMERICHOST;
844
845   if (port)
846     snprintf (portstr, sizeof portstr, "%hu", port);
847   else
848     *portstr = 0;
849
850   /* We can't use the the AI_IDN flag because that does the conversion
851      using the current locale.  However, GnuPG always used UTF-8.  To
852      support IDN we would need to make use of the libidn API.  */
853   ret = getaddrinfo (name, *portstr? portstr : NULL, &hints, &aibuf);
854   if (ret)
855     {
856       aibuf = NULL;
857       err = map_eai_to_gpg_error (ret);
858       if (gpg_err_code (err) == GPG_ERR_NO_NAME)
859         {
860           /* There seems to be a bug in the glibc getaddrinfo function
861              if the CNAME points to a long list of A and AAAA records
862              in which case the function return NO_NAME.  Let's do the
863              CNAME redirection again.  */
864           char *cname;
865
866           if (get_dns_cname (name, &cname))
867             goto leave; /* Still no success.  */
868
869           ret = getaddrinfo (cname, *portstr? portstr : NULL, &hints, &aibuf);
870           xfree (cname);
871           if (ret)
872             {
873               aibuf = NULL;
874               err = map_eai_to_gpg_error (ret);
875               goto leave;
876             }
877           err = 0; /* Yep, now it worked.  */
878         }
879       else
880         goto leave;
881     }
882
883   if (r_canonname && aibuf && aibuf->ai_canonname)
884     {
885       *r_canonname = xtrystrdup (aibuf->ai_canonname);
886       if (!*r_canonname)
887         {
888           err = gpg_error_from_syserror ();
889           goto leave;
890         }
891     }
892
893   for (ai = aibuf; ai; ai = ai->ai_next)
894     {
895       if (ai->ai_family != AF_INET6 && ai->ai_family != AF_INET)
896         continue;
897       if (opt_disable_ipv4 && ai->ai_family == AF_INET)
898         continue;
899
900       dai = xtrymalloc (sizeof *dai + ai->ai_addrlen - 1);
901       dai->family = ai->ai_family;
902       dai->socktype = ai->ai_socktype;
903       dai->protocol = ai->ai_protocol;
904       dai->addrlen = ai->ai_addrlen;
905       memcpy (dai->addr, ai->ai_addr, ai->ai_addrlen);
906       dai->next = daihead;
907       daihead = dai;
908     }
909
910  leave:
911   if (aibuf)
912     freeaddrinfo (aibuf);
913   if (err)
914     {
915       if (r_canonname)
916         {
917           xfree (*r_canonname);
918           *r_canonname = NULL;
919         }
920       free_dns_addrinfo (daihead);
921     }
922   else
923     *r_dai = daihead;
924   return err;
925 }
926
927
928 /* This a wrapper around getaddrinfo with slightly different semantics.
929    NAME is the name to resolve.
930    PORT is the requested port or 0.
931    WANT_FAMILY is either 0 (AF_UNSPEC), AF_INET6, or AF_INET4.
932    WANT_SOCKETTYPE is either SOCK_STREAM or SOCK_DGRAM.
933
934    On success the result is stored in a linked list with the head
935    stored at the address R_AI; the caller must call gpg_addrinfo_free
936    on this.  If R_CANONNAME is not NULL the official name of the host
937    is stored there as a malloced string; if that name is not available
938    NULL is stored.  */
939 gpg_error_t
940 resolve_dns_name (const char *name, unsigned short port,
941                   int want_family, int want_socktype,
942                   dns_addrinfo_t *r_ai, char **r_canonname)
943 {
944   gpg_error_t err;
945
946 #ifdef USE_LIBDNS
947   if (!standard_resolver)
948     {
949       err = resolve_name_libdns (name, port, want_family, want_socktype,
950                                   r_ai, r_canonname);
951       if (err && libdns_switch_port_p (err))
952         err = resolve_name_libdns (name, port, want_family, want_socktype,
953                                    r_ai, r_canonname);
954     }
955   else
956 #endif /*USE_LIBDNS*/
957     err = resolve_name_standard (name, port, want_family, want_socktype,
958                                  r_ai, r_canonname);
959   if (opt_debug)
960     log_debug ("dns: resolve_dns_name(%s): %s\n", name, gpg_strerror (err));
961   return err;
962 }
963
964
965 #ifdef USE_LIBDNS
966 /* Resolve an address using libdns.  */
967 static gpg_error_t
968 resolve_addr_libdns (const struct sockaddr *addr, int addrlen,
969                      unsigned int flags, char **r_name)
970 {
971   gpg_error_t err;
972   char host[DNS_D_MAXNAME + 1];
973   struct dns_resolver *res = NULL;
974   struct dns_packet *ans = NULL;
975   struct dns_ptr ptr;
976   int derr;
977
978   *r_name = NULL;
979
980   /* First we turn ADDR into a DNS name (with ".arpa" suffix).  */
981   err = 0;
982   if (addr->sa_family == AF_INET6)
983     {
984       const struct sockaddr_in6 *a6 = (const struct sockaddr_in6 *)addr;
985       if (!dns_aaaa_arpa (host, sizeof host, (void*)&a6->sin6_addr))
986         err = gpg_error (GPG_ERR_INV_OBJ);
987     }
988   else if (addr->sa_family == AF_INET)
989     {
990       const struct sockaddr_in *a4 = (const struct sockaddr_in *)addr;
991       if (!dns_a_arpa (host, sizeof host, (void*)&a4->sin_addr))
992         err = gpg_error (GPG_ERR_INV_OBJ);
993     }
994   else
995     err = gpg_error (GPG_ERR_EAFNOSUPPORT);
996   if (err)
997     goto leave;
998
999
1000   err = libdns_res_open (&res);
1001   if (err)
1002     goto leave;
1003
1004   err = libdns_res_submit (res, host, DNS_T_PTR, DNS_C_IN);
1005   if (err)
1006     goto leave;
1007
1008   err = libdns_res_wait (res);
1009   if (err)
1010     goto leave;
1011
1012   ans = dns_res_fetch (res, &derr);
1013   if (!ans)
1014     {
1015       err = libdns_error_to_gpg_error (derr);
1016       goto leave;
1017     }
1018
1019   /* Check the rcode.  */
1020   switch (dns_p_rcode (ans))
1021     {
1022     case DNS_RC_NOERROR:
1023       break;
1024     case DNS_RC_NXDOMAIN:
1025       err = gpg_error (GPG_ERR_NO_NAME);
1026       break;
1027     default:
1028       err = GPG_ERR_SERVER_FAILED;
1029       goto leave;
1030     }
1031
1032   /* Parse the result.  */
1033   if (!err)
1034     {
1035       struct dns_rr rr;
1036       struct dns_rr_i rri;
1037
1038       memset (&rri, 0, sizeof rri);
1039       dns_rr_i_init (&rri, ans);
1040       rri.section = DNS_S_ALL & ~DNS_S_QD;
1041       rri.name    = host;
1042       rri.type    = DNS_T_PTR;
1043
1044       if (!dns_rr_grep (&rr, 1, &rri, ans, &derr))
1045         {
1046           err = gpg_error (GPG_ERR_NOT_FOUND);
1047           goto leave;
1048         }
1049
1050       err = libdns_error_to_gpg_error (dns_ptr_parse (&ptr, &rr, ans));
1051       if (err)
1052         goto leave;
1053
1054       /* Copy result.  */
1055       *r_name = xtrystrdup (ptr.host);
1056       if (!*r_name)
1057         {
1058           err = gpg_error_from_syserror ();
1059           goto leave;
1060         }
1061       /* Libdns appends the root zone part which is problematic
1062        * for most other functions - strip it.  */
1063       if (**r_name && (*r_name)[strlen (*r_name)-1] == '.')
1064         (*r_name)[strlen (*r_name)-1] = 0;
1065     }
1066   else /* GPG_ERR_NO_NAME */
1067     {
1068       char *buffer, *p;
1069       int buflen;
1070       int ec;
1071
1072       buffer = ptr.host;
1073       buflen = sizeof ptr.host;
1074
1075       p = buffer;
1076       if (addr->sa_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1077         {
1078           *p++ = '[';
1079           buflen -= 2;
1080         }
1081       ec = getnameinfo (addr, addrlen, p, buflen, NULL, 0, NI_NUMERICHOST);
1082       if (ec)
1083         {
1084           err = map_eai_to_gpg_error (ec);
1085           goto leave;
1086         }
1087       if (addr->sa_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1088         strcat (buffer, "]");
1089     }
1090
1091  leave:
1092   dns_free (ans);
1093   dns_res_close (res);
1094   return err;
1095 }
1096 #endif /*USE_LIBDNS*/
1097
1098
1099 /* Resolve an address using the standard system function.  */
1100 static gpg_error_t
1101 resolve_addr_standard (const struct sockaddr *addr, int addrlen,
1102                        unsigned int flags, char **r_name)
1103 {
1104   gpg_error_t err;
1105   int ec;
1106   char *buffer, *p;
1107   int buflen;
1108
1109   *r_name = NULL;
1110
1111   buflen = NI_MAXHOST;
1112   buffer = xtrymalloc (buflen + 2 + 1);
1113   if (!buffer)
1114     return gpg_error_from_syserror ();
1115
1116   if ((flags & DNS_NUMERICHOST) || tor_mode)
1117     ec = EAI_NONAME;
1118   else
1119     ec = getnameinfo (addr, addrlen, buffer, buflen, NULL, 0, NI_NAMEREQD);
1120
1121   if (!ec && *buffer == '[')
1122     ec = EAI_FAIL;  /* A name may never start with a bracket.  */
1123   else if (ec == EAI_NONAME)
1124     {
1125       p = buffer;
1126       if (addr->sa_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1127         {
1128           *p++ = '[';
1129           buflen -= 2;
1130         }
1131       ec = getnameinfo (addr, addrlen, p, buflen, NULL, 0, NI_NUMERICHOST);
1132       if (!ec && addr->sa_family == AF_INET6 && (flags & DNS_WITHBRACKET))
1133         strcat (buffer, "]");
1134     }
1135
1136   if (ec)
1137     err = map_eai_to_gpg_error (ec);
1138   else
1139     {
1140       p = xtryrealloc (buffer, strlen (buffer)+1);
1141       if (!p)
1142         err = gpg_error_from_syserror ();
1143       else
1144         {
1145           buffer = p;
1146           err = 0;
1147         }
1148     }
1149
1150   if (err)
1151     xfree (buffer);
1152   else
1153     *r_name = buffer;
1154
1155   return err;
1156 }
1157
1158
1159 /* A wrapper around getnameinfo.  */
1160 gpg_error_t
1161 resolve_dns_addr (const struct sockaddr *addr, int addrlen,
1162                   unsigned int flags, char **r_name)
1163 {
1164   gpg_error_t err;
1165
1166 #ifdef USE_LIBDNS
1167   /* Note that we divert to the standard resolver for NUMERICHOST.  */
1168   if (!standard_resolver && !(flags & DNS_NUMERICHOST))
1169     {
1170       err = resolve_addr_libdns (addr, addrlen, flags, r_name);
1171       if (err && libdns_switch_port_p (err))
1172         err = resolve_addr_libdns (addr, addrlen, flags, r_name);
1173     }
1174   else
1175 #endif /*USE_LIBDNS*/
1176     err = resolve_addr_standard (addr, addrlen, flags, r_name);
1177
1178   if (opt_debug)
1179     log_debug ("dns: resolve_dns_addr(): %s\n", gpg_strerror (err));
1180   return err;
1181 }
1182
1183
1184 /* Check whether NAME is an IP address.  Returns a true if it is
1185  * either an IPv6 or a IPv4 numerical address.  The actual return
1186  * values can also be used to identify whether it is v4 or v6: The
1187  * true value will surprisingly be 4 for IPv4 and 6 for IPv6.  */
1188 int
1189 is_ip_address (const char *name)
1190 {
1191   const char *s;
1192   int ndots, dblcol, n;
1193
1194   if (*name == '[')
1195     return 6; /* yes: A legal DNS name may not contain this character;
1196                  this mut be bracketed v6 address.  */
1197   if (*name == '.')
1198     return 0; /* No.  A leading dot is not a valid IP address.  */
1199
1200   /* Check whether this is a v6 address.  */
1201   ndots = n = dblcol = 0;
1202   for (s=name; *s; s++)
1203     {
1204       if (*s == ':')
1205         {
1206           ndots++;
1207           if (s[1] == ':')
1208             {
1209               ndots++;
1210               if (dblcol)
1211                 return 0; /* No: Only one "::" allowed.  */
1212               dblcol++;
1213               if (s[1])
1214                 s++;
1215             }
1216           n = 0;
1217         }
1218       else if (*s == '.')
1219         goto legacy;
1220       else if (!strchr ("0123456789abcdefABCDEF", *s))
1221         return 0; /* No: Not a hex digit.  */
1222       else if (++n > 4)
1223         return 0; /* To many digits in a group.  */
1224     }
1225   if (ndots > 7)
1226     return 0; /* No: Too many colons.  */
1227   else if (ndots > 1)
1228     return 6; /* Yes: At least 2 colons indicate an v6 address.  */
1229
1230  legacy:
1231   /* Check whether it is legacy IP address.  */
1232   ndots = n = 0;
1233   for (s=name; *s; s++)
1234     {
1235       if (*s == '.')
1236         {
1237           if (s[1] == '.')
1238             return 0; /* No:  Douple dot. */
1239           if (atoi (s+1) > 255)
1240             return 0; /* No:  Ipv4 byte value too large.  */
1241           ndots++;
1242           n = 0;
1243         }
1244       else if (!strchr ("0123456789", *s))
1245         return 0; /* No: Not a digit.  */
1246       else if (++n > 3)
1247         return 0; /* No: More than 3 digits.  */
1248     }
1249   return (ndots == 3)? 4 : 0;
1250 }
1251
1252
1253 /* Return true if NAME is an onion address.  */
1254 int
1255 is_onion_address (const char *name)
1256 {
1257   size_t len;
1258
1259   len = name? strlen (name) : 0;
1260   if (len < 8 || strcmp (name + len - 6, ".onion"))
1261     return 0;
1262   /* Note that we require at least 2 characters before the suffix.  */
1263   return 1;  /* Yes.  */
1264 }
1265
1266
1267 /* libdns version of get_dns_cert.  */
1268 #ifdef USE_LIBDNS
1269 static gpg_error_t
1270 get_dns_cert_libdns (const char *name, int want_certtype,
1271                      void **r_key, size_t *r_keylen,
1272                      unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1273 {
1274   gpg_error_t err;
1275   struct dns_resolver *res = NULL;
1276   struct dns_packet *ans = NULL;
1277   struct dns_rr rr;
1278   struct dns_rr_i rri;
1279   char host[DNS_D_MAXNAME + 1];
1280   int derr;
1281   int qtype;
1282
1283   /* Get the query type from WANT_CERTTYPE (which in general indicates
1284    * the subtype we want). */
1285   qtype = (want_certtype < DNS_CERTTYPE_RRBASE
1286            ? T_CERT
1287            : (want_certtype - DNS_CERTTYPE_RRBASE));
1288
1289
1290   err = libdns_res_open (&res);
1291   if (err)
1292     goto leave;
1293
1294   if (dns_d_anchor (host, sizeof host, name, strlen (name)) >= sizeof host)
1295     {
1296       err = gpg_error (GPG_ERR_ENAMETOOLONG);
1297       goto leave;
1298     }
1299
1300   err = libdns_res_submit (res, name, qtype, DNS_C_IN);
1301   if (err)
1302     goto leave;
1303
1304   err = libdns_res_wait (res);
1305   if (err)
1306     goto leave;
1307
1308   ans = dns_res_fetch (res, &derr);
1309   if (!ans)
1310     {
1311       err = libdns_error_to_gpg_error (derr);
1312       goto leave;
1313     }
1314
1315   /* Check the rcode.  */
1316   switch (dns_p_rcode (ans))
1317     {
1318     case DNS_RC_NOERROR: break;
1319     case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
1320     default: err = GPG_ERR_SERVER_FAILED; break;
1321     }
1322   if (err)
1323     goto leave;
1324
1325   memset (&rri, 0, sizeof rri);
1326   dns_rr_i_init (&rri, ans);
1327   rri.section = DNS_S_ALL & ~DNS_S_QD;
1328   rri.name    = host;
1329   rri.type    = qtype;
1330
1331   err = gpg_error (GPG_ERR_NOT_FOUND);
1332   while (dns_rr_grep (&rr, 1, &rri, ans, &derr))
1333     {
1334       unsigned char *rp  = ans->data + rr.rd.p;
1335       unsigned short len = rr.rd.len;
1336       u16 subtype;
1337
1338        if (!len)
1339         {
1340           /* Definitely too short - skip.  */
1341         }
1342       else if (want_certtype >= DNS_CERTTYPE_RRBASE
1343           && rr.type == (want_certtype - DNS_CERTTYPE_RRBASE)
1344           && r_key)
1345         {
1346           *r_key = xtrymalloc (len);
1347           if (!*r_key)
1348             err = gpg_error_from_syserror ();
1349           else
1350             {
1351               memcpy (*r_key, rp, len);
1352               *r_keylen = len;
1353               err = 0;
1354             }
1355           goto leave;
1356         }
1357       else if (want_certtype >= DNS_CERTTYPE_RRBASE)
1358         {
1359           /* We did not found the requested RR - skip. */
1360         }
1361       else if (rr.type == T_CERT && len > 5)
1362         {
1363           /* We got a CERT type.   */
1364           subtype = buf16_to_u16 (rp);
1365           rp += 2; len -= 2;
1366
1367           /* Skip the CERT key tag and algo which we don't need.  */
1368           rp += 3; len -= 3;
1369
1370           if (want_certtype && want_certtype != subtype)
1371             ; /* Not the requested subtype - skip.  */
1372           else if (subtype == DNS_CERTTYPE_PGP && len && r_key && r_keylen)
1373             {
1374               /* PGP subtype */
1375               *r_key = xtrymalloc (len);
1376               if (!*r_key)
1377                 err = gpg_error_from_syserror ();
1378               else
1379                 {
1380                   memcpy (*r_key, rp, len);
1381                   *r_keylen = len;
1382                   err = 0;
1383                 }
1384               goto leave;
1385             }
1386           else if (subtype == DNS_CERTTYPE_IPGP
1387                    && len && len < 1023 && len >= rp[0] + 1)
1388             {
1389               /* IPGP type */
1390               *r_fprlen = rp[0];
1391               if (*r_fprlen)
1392                 {
1393                   *r_fpr = xtrymalloc (*r_fprlen);
1394                   if (!*r_fpr)
1395                     {
1396                       err = gpg_error_from_syserror ();
1397                       goto leave;
1398                     }
1399                   memcpy (*r_fpr, rp+1, *r_fprlen);
1400                 }
1401               else
1402                 *r_fpr = NULL;
1403
1404               if (len > *r_fprlen + 1)
1405                 {
1406                   *r_url = xtrymalloc (len - (*r_fprlen + 1) + 1);
1407                   if (!*r_url)
1408                     {
1409                       err = gpg_error_from_syserror ();
1410                       xfree (*r_fpr);
1411                       *r_fpr = NULL;
1412                       goto leave;
1413                     }
1414                   memcpy (*r_url, rp + *r_fprlen + 1, len - (*r_fprlen + 1));
1415                   (*r_url)[len - (*r_fprlen + 1)] = 0;
1416                 }
1417               else
1418                 *r_url = NULL;
1419
1420               err = 0;
1421               goto leave;
1422             }
1423           else
1424             {
1425               /* Unknown subtype or record too short - skip.  */
1426             }
1427         }
1428       else
1429         {
1430           /* Not a requested type - skip.  */
1431         }
1432     }
1433
1434  leave:
1435   dns_free (ans);
1436   dns_res_close (res);
1437   return err;
1438 }
1439 #endif /*USE_LIBDNS*/
1440
1441
1442 /* Standard resolver version of get_dns_cert.  */
1443 static gpg_error_t
1444 get_dns_cert_standard (const char *name, int want_certtype,
1445                        void **r_key, size_t *r_keylen,
1446                        unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1447 {
1448 #ifdef HAVE_SYSTEM_RESOLVER
1449   gpg_error_t err;
1450   unsigned char *answer;
1451   int r;
1452   u16 count;
1453
1454   /* Allocate a 64k buffer which is the limit for an DNS response.  */
1455   answer = xtrymalloc (65536);
1456   if (!answer)
1457     return gpg_error_from_syserror ();
1458
1459   err = gpg_error (GPG_ERR_NOT_FOUND);
1460   r = res_query (name, C_IN,
1461                  (want_certtype < DNS_CERTTYPE_RRBASE
1462                   ? T_CERT
1463                   : (want_certtype - DNS_CERTTYPE_RRBASE)),
1464                  answer, 65536);
1465   /* Not too big, not too small, no errors and at least 1 answer. */
1466   if (r >= sizeof (HEADER) && r <= 65536
1467       && (((HEADER *)(void *) answer)->rcode) == NOERROR
1468       && (count = ntohs (((HEADER *)(void *) answer)->ancount)))
1469     {
1470       int rc;
1471       unsigned char *pt, *emsg;
1472
1473       emsg = &answer[r];
1474
1475       pt = &answer[sizeof (HEADER)];
1476
1477       /* Skip over the query */
1478
1479       rc = dn_skipname (pt, emsg);
1480       if (rc == -1)
1481         {
1482           err = gpg_error (GPG_ERR_INV_OBJ);
1483           goto leave;
1484         }
1485       pt += rc + QFIXEDSZ;
1486
1487       /* There are several possible response types for a CERT request.
1488          We're interested in the PGP (a key) and IPGP (a URI) types.
1489          Skip all others.  TODO: A key is better than a URI since
1490          we've gone through all this bother to fetch it, so favor that
1491          if we have both PGP and IPGP? */
1492
1493       while (count-- > 0 && pt < emsg)
1494         {
1495           u16 type, class, dlen, ctype;
1496
1497           rc = dn_skipname (pt, emsg);  /* the name we just queried for */
1498           if (rc == -1)
1499             {
1500               err = gpg_error (GPG_ERR_INV_OBJ);
1501               goto leave;
1502             }
1503
1504           pt += rc;
1505
1506           /* Truncated message? 15 bytes takes us to the point where
1507              we start looking at the ctype. */
1508           if ((emsg - pt) < 15)
1509             break;
1510
1511           type = buf16_to_u16 (pt);
1512           pt += 2;
1513
1514           class = buf16_to_u16 (pt);
1515           pt += 2;
1516
1517           if (class != C_IN)
1518             break;
1519
1520           /* ttl */
1521           pt += 4;
1522
1523           /* data length */
1524           dlen = buf16_to_u16 (pt);
1525           pt += 2;
1526
1527           /* Check the type and parse.  */
1528           if (want_certtype >= DNS_CERTTYPE_RRBASE
1529               && type == (want_certtype - DNS_CERTTYPE_RRBASE)
1530               && r_key)
1531             {
1532               *r_key = xtrymalloc (dlen);
1533               if (!*r_key)
1534                 err = gpg_error_from_syserror ();
1535               else
1536                 {
1537                   memcpy (*r_key, pt, dlen);
1538                   *r_keylen = dlen;
1539                   err = 0;
1540                 }
1541               goto leave;
1542             }
1543           else if (want_certtype >= DNS_CERTTYPE_RRBASE)
1544             {
1545               /* We did not found the requested RR.  */
1546               pt += dlen;
1547             }
1548           else if (type == T_CERT)
1549             {
1550               /* We got a CERT type.   */
1551               ctype = buf16_to_u16 (pt);
1552               pt += 2;
1553
1554               /* Skip the CERT key tag and algo which we don't need. */
1555               pt += 3;
1556
1557               dlen -= 5;
1558
1559               /* 15 bytes takes us to here */
1560               if (want_certtype && want_certtype != ctype)
1561                 ; /* Not of the requested certtype.  */
1562               else if (ctype == DNS_CERTTYPE_PGP && dlen && r_key && r_keylen)
1563                 {
1564                   /* PGP type */
1565                   *r_key = xtrymalloc (dlen);
1566                   if (!*r_key)
1567                     err = gpg_error_from_syserror ();
1568                   else
1569                     {
1570                       memcpy (*r_key, pt, dlen);
1571                       *r_keylen = dlen;
1572                       err = 0;
1573                     }
1574                   goto leave;
1575                 }
1576               else if (ctype == DNS_CERTTYPE_IPGP
1577                        && dlen && dlen < 1023 && dlen >= pt[0] + 1)
1578                 {
1579                   /* IPGP type */
1580                   *r_fprlen = pt[0];
1581                   if (*r_fprlen)
1582                     {
1583                       *r_fpr = xtrymalloc (*r_fprlen);
1584                       if (!*r_fpr)
1585                         {
1586                           err = gpg_error_from_syserror ();
1587                           goto leave;
1588                         }
1589                       memcpy (*r_fpr, &pt[1], *r_fprlen);
1590                     }
1591                   else
1592                     *r_fpr = NULL;
1593
1594                   if (dlen > *r_fprlen + 1)
1595                     {
1596                       *r_url = xtrymalloc (dlen - (*r_fprlen + 1) + 1);
1597                       if (!*r_url)
1598                         {
1599                           err = gpg_error_from_syserror ();
1600                           xfree (*r_fpr);
1601                           *r_fpr = NULL;
1602                           goto leave;
1603                         }
1604                       memcpy (*r_url, &pt[*r_fprlen + 1],
1605                               dlen - (*r_fprlen + 1));
1606                       (*r_url)[dlen - (*r_fprlen + 1)] = '\0';
1607                     }
1608                   else
1609                     *r_url = NULL;
1610
1611                   err = 0;
1612                   goto leave;
1613                 }
1614
1615               /* No subtype matches, so continue with the next answer. */
1616               pt += dlen;
1617             }
1618           else
1619             {
1620               /* Not a requested type - might be a CNAME. Try next item.  */
1621               pt += dlen;
1622             }
1623         }
1624     }
1625
1626  leave:
1627   xfree (answer);
1628   return err;
1629
1630 #else /*!HAVE_SYSTEM_RESOLVER*/
1631
1632   (void)name;
1633   (void)want_certtype;
1634   (void)r_key;
1635   (void)r_keylen;
1636   (void)r_fpr;
1637   (void)r_fprlen;
1638   (void)r_url;
1639   return gpg_error (GPG_ERR_NOT_SUPPORTED);
1640
1641 #endif /*!HAVE_SYSTEM_RESOLVER*/
1642 }
1643
1644
1645 /* Returns 0 on success or an error code.  If a PGP CERT record was
1646    found, the malloced data is returned at (R_KEY, R_KEYLEN) and
1647    the other return parameters are set to NULL/0.  If an IPGP CERT
1648    record was found the fingerprint is stored as an allocated block at
1649    R_FPR and its length at R_FPRLEN; an URL is is allocated as a
1650    string and returned at R_URL.  If WANT_CERTTYPE is 0 this function
1651    returns the first CERT found with a supported type; it is expected
1652    that only one CERT record is used.  If WANT_CERTTYPE is one of the
1653    supported certtypes only records with this certtype are considered
1654    and the first found is returned.  (R_KEY,R_KEYLEN) are optional. */
1655 gpg_error_t
1656 get_dns_cert (const char *name, int want_certtype,
1657               void **r_key, size_t *r_keylen,
1658               unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
1659 {
1660   gpg_error_t err;
1661
1662   if (r_key)
1663     *r_key = NULL;
1664   if (r_keylen)
1665     *r_keylen = 0;
1666   *r_fpr = NULL;
1667   *r_fprlen = 0;
1668   *r_url = NULL;
1669
1670 #ifdef USE_LIBDNS
1671   if (!standard_resolver)
1672     {
1673       err = get_dns_cert_libdns (name, want_certtype, r_key, r_keylen,
1674                                  r_fpr, r_fprlen, r_url);
1675       if (err && libdns_switch_port_p (err))
1676         err = get_dns_cert_libdns (name, want_certtype, r_key, r_keylen,
1677                                    r_fpr, r_fprlen, r_url);
1678     }
1679   else
1680 #endif /*USE_LIBDNS*/
1681     err = get_dns_cert_standard (name, want_certtype, r_key, r_keylen,
1682                                  r_fpr, r_fprlen, r_url);
1683
1684   if (opt_debug)
1685     log_debug ("dns: get_dns_cert(%s): %s\n", name, gpg_strerror (err));
1686   return err;
1687 }
1688
1689
1690 static int
1691 priosort(const void *a,const void *b)
1692 {
1693   const struct srventry *sa=a,*sb=b;
1694   if(sa->priority>sb->priority)
1695     return 1;
1696   else if(sa->priority<sb->priority)
1697     return -1;
1698   else
1699     return 0;
1700 }
1701
1702
1703 /* Libdns based helper for getsrv.  Note that it is expected that NULL
1704  * is stored at the address of LIST and 0 is stored at the address of
1705  * R_COUNT.  */
1706 #ifdef USE_LIBDNS
1707 static gpg_error_t
1708 getsrv_libdns (const char *name, struct srventry **list, unsigned int *r_count)
1709 {
1710   gpg_error_t err;
1711   struct dns_resolver *res = NULL;
1712   struct dns_packet *ans = NULL;
1713   struct dns_rr rr;
1714   struct dns_rr_i rri;
1715   char host[DNS_D_MAXNAME + 1];
1716   int derr;
1717   unsigned int srvcount = 0;
1718
1719   err = libdns_res_open (&res);
1720   if (err)
1721     goto leave;
1722
1723   if (dns_d_anchor (host, sizeof host, name, strlen (name)) >= sizeof host)
1724     {
1725       err = gpg_error (GPG_ERR_ENAMETOOLONG);
1726       goto leave;
1727     }
1728
1729   err = libdns_res_submit (res, name, DNS_T_SRV, DNS_C_IN);
1730   if (err)
1731     goto leave;
1732
1733   err = libdns_res_wait (res);
1734   if (err)
1735     goto leave;
1736
1737   ans = dns_res_fetch (res, &derr);
1738   if (!ans)
1739     {
1740       err = libdns_error_to_gpg_error (derr);
1741       goto leave;
1742     }
1743
1744   /* Check the rcode.  */
1745   switch (dns_p_rcode (ans))
1746     {
1747     case DNS_RC_NOERROR: break;
1748     case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
1749     default: err = GPG_ERR_SERVER_FAILED; break;
1750     }
1751   if (err)
1752     goto leave;
1753
1754   memset (&rri, 0, sizeof rri);
1755   dns_rr_i_init (&rri, ans);
1756   rri.section = DNS_S_ALL & ~DNS_S_QD;
1757   rri.name        = host;
1758   rri.type        = DNS_T_SRV;
1759
1760   while (dns_rr_grep (&rr, 1, &rri, ans, &derr))
1761     {
1762       struct dns_srv dsrv;
1763       struct srventry *srv;
1764       struct srventry *newlist;
1765
1766       err = libdns_error_to_gpg_error (dns_srv_parse(&dsrv, &rr, ans));
1767       if (err)
1768         goto leave;
1769
1770       newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));
1771       if (!newlist)
1772         {
1773           err = gpg_error_from_syserror ();
1774           goto leave;
1775         }
1776       *list = newlist;
1777       memset (&(*list)[srvcount], 0, sizeof(struct srventry));
1778       srv = &(*list)[srvcount];
1779       srvcount++;
1780       srv->priority = dsrv.priority;
1781       srv->weight   = dsrv.weight;
1782       srv->port     = dsrv.port;
1783       mem2str (srv->target, dsrv.target, sizeof srv->target);
1784       /* Libdns appends the root zone part which is problematic for
1785        * most other functions - strip it.  */
1786       if (*srv->target && (srv->target)[strlen (srv->target)-1] == '.')
1787         (srv->target)[strlen (srv->target)-1] = 0;
1788     }
1789
1790   *r_count = srvcount;
1791
1792  leave:
1793   if (err)
1794     {
1795       xfree (*list);
1796       *list = NULL;
1797     }
1798   dns_free (ans);
1799   dns_res_close (res);
1800   return err;
1801 }
1802 #endif /*USE_LIBDNS*/
1803
1804
1805 /* Standard resolver based helper for getsrv.  Note that it is
1806  * expected that NULL is stored at the address of LIST and 0 is stored
1807  * at the address of R_COUNT.  */
1808 static gpg_error_t
1809 getsrv_standard (const char *name,
1810                  struct srventry **list, unsigned int *r_count)
1811 {
1812 #ifdef HAVE_SYSTEM_RESOLVER
1813   union {
1814     unsigned char ans[2048];
1815     HEADER header[1];
1816   } res;
1817   unsigned char *answer = res.ans;
1818   HEADER *header = res.header;
1819   unsigned char *pt, *emsg;
1820   int r, rc;
1821   u16 dlen;
1822   unsigned int srvcount = 0;
1823   u16 count;
1824
1825   /* Do not allow a query using the standard resolver in Tor mode.  */
1826   if (tor_mode)
1827     return gpg_error (GPG_ERR_NOT_ENABLED);
1828
1829   my_unprotect ();
1830   r = res_query (name, C_IN, T_SRV, answer, sizeof res.ans);
1831   my_protect ();
1832   if (r < 0)
1833     return get_h_errno_as_gpg_error ();
1834   if (r < sizeof (HEADER))
1835     return gpg_error (GPG_ERR_SERVER_FAILED);
1836   if (r > sizeof res.ans)
1837     return gpg_error (GPG_ERR_SYSTEM_BUG);
1838   if (header->rcode != NOERROR || !(count=ntohs (header->ancount)))
1839     return gpg_error (GPG_ERR_NO_NAME); /* Error or no record found.  */
1840
1841   emsg = &answer[r];
1842   pt = &answer[sizeof(HEADER)];
1843
1844   /* Skip over the query */
1845   rc = dn_skipname (pt, emsg);
1846   if (rc == -1)
1847     goto fail;
1848
1849   pt += rc + QFIXEDSZ;
1850
1851   while (count-- > 0 && pt < emsg)
1852     {
1853       struct srventry *srv;
1854       u16 type, class;
1855       struct srventry *newlist;
1856
1857       newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));
1858       if (!newlist)
1859         goto fail;
1860       *list = newlist;
1861       memset (&(*list)[srvcount], 0, sizeof(struct srventry));
1862       srv = &(*list)[srvcount];
1863       srvcount++;
1864
1865       rc = dn_skipname (pt, emsg); /* The name we just queried for.  */
1866       if (rc == -1)
1867         goto fail;
1868       pt += rc;
1869
1870       /* Truncated message? */
1871       if ((emsg-pt) < 16)
1872         goto fail;
1873
1874       type = buf16_to_u16 (pt);
1875       pt += 2;
1876       /* We asked for SRV and got something else !? */
1877       if (type != T_SRV)
1878         goto fail;
1879
1880       class = buf16_to_u16 (pt);
1881       pt += 2;
1882       /* We asked for IN and got something else !? */
1883       if (class != C_IN)
1884         goto fail;
1885
1886       pt += 4; /* ttl */
1887       dlen = buf16_to_u16 (pt);
1888       pt += 2;
1889
1890       srv->priority = buf16_to_ushort (pt);
1891       pt += 2;
1892       srv->weight = buf16_to_ushort (pt);
1893       pt += 2;
1894       srv->port = buf16_to_ushort (pt);
1895       pt += 2;
1896
1897       /* Get the name.  2782 doesn't allow name compression, but
1898        * dn_expand still works to pull the name out of the packet. */
1899       rc = dn_expand (answer, emsg, pt, srv->target, sizeof srv->target);
1900       if (rc == 1 && srv->target[0] == 0) /* "." */
1901         {
1902           xfree(*list);
1903           *list = NULL;
1904           return 0;
1905         }
1906       if (rc == -1)
1907         goto fail;
1908       pt += rc;
1909       /* Corrupt packet? */
1910       if (dlen != rc+6)
1911         goto fail;
1912     }
1913
1914   *r_count = srvcount;
1915   return 0;
1916
1917  fail:
1918   xfree (*list);
1919   *list = NULL;
1920   return gpg_error (GPG_ERR_GENERAL);
1921
1922 #else /*!HAVE_SYSTEM_RESOLVER*/
1923
1924   (void)name;
1925   (void)list;
1926   (void)r_count;
1927   return gpg_error (GPG_ERR_NOT_SUPPORTED);
1928
1929 #endif /*!HAVE_SYSTEM_RESOLVER*/
1930 }
1931
1932
1933 /* Query a SRV record for SERVICE and PROTO for NAME.  If SERVICE is
1934  * NULL, NAME is expected to contain the full query name.  Note that
1935  * we do not return NONAME but simply store 0 at R_COUNT.  On error an
1936  * error code is returned and 0 stored at R_COUNT.  */
1937 gpg_error_t
1938 get_dns_srv (const char *name, const char *service, const char *proto,
1939              struct srventry **list, unsigned int *r_count)
1940 {
1941   gpg_error_t err;
1942   char *namebuffer = NULL;
1943   unsigned int srvcount;
1944   int i;
1945
1946   *list = NULL;
1947   *r_count = 0;
1948   srvcount = 0;
1949
1950   /* If SERVICE is given construct the query from it and PROTO.  */
1951   if (service)
1952     {
1953       namebuffer = xtryasprintf ("_%s._%s.%s",
1954                                  service, proto? proto:"tcp", name);
1955       if (!namebuffer)
1956         {
1957           err = gpg_error_from_syserror ();
1958           goto leave;
1959         }
1960       name = namebuffer;
1961     }
1962
1963
1964 #ifdef USE_LIBDNS
1965   if (!standard_resolver)
1966     {
1967       err = getsrv_libdns (name, list, &srvcount);
1968       if (err && libdns_switch_port_p (err))
1969         err = getsrv_libdns (name, list, &srvcount);
1970     }
1971   else
1972 #endif /*USE_LIBDNS*/
1973     err = getsrv_standard (name, list, &srvcount);
1974
1975   if (err)
1976     {
1977       if (gpg_err_code (err) == GPG_ERR_NO_NAME)
1978         err = 0;
1979       goto leave;
1980     }
1981
1982   /* Now we have an array of all the srv records. */
1983
1984   /* Order by priority */
1985   qsort(*list,srvcount,sizeof(struct srventry),priosort);
1986
1987   /* For each priority, move the zero-weighted items first. */
1988   for (i=0; i < srvcount; i++)
1989     {
1990       int j;
1991
1992       for (j=i;j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)
1993         {
1994           if((*list)[j].weight==0)
1995             {
1996               /* Swap j with i */
1997               if(j!=i)
1998                 {
1999                   struct srventry temp;
2000
2001                   memcpy (&temp,&(*list)[j],sizeof(struct srventry));
2002                   memcpy (&(*list)[j],&(*list)[i],sizeof(struct srventry));
2003                   memcpy (&(*list)[i],&temp,sizeof(struct srventry));
2004                 }
2005
2006               break;
2007             }
2008         }
2009     }
2010
2011   /* Run the RFC-2782 weighting algorithm.  We don't need very high
2012      quality randomness for this, so regular libc srand/rand is
2013      sufficient.  */
2014
2015   {
2016     static int done;
2017     if (!done)
2018       {
2019         done = 1;
2020         srand (time (NULL)*getpid());
2021       }
2022   }
2023
2024   for (i=0; i < srvcount; i++)
2025     {
2026       int j;
2027       float prio_count=0,chose;
2028
2029       for (j=i; j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)
2030         {
2031           prio_count+=(*list)[j].weight;
2032           (*list)[j].run_count=prio_count;
2033         }
2034
2035       chose=prio_count*rand()/RAND_MAX;
2036
2037       for (j=i;j<srvcount && (*list)[i].priority==(*list)[j].priority;j++)
2038         {
2039           if (chose<=(*list)[j].run_count)
2040             {
2041               /* Swap j with i */
2042               if(j!=i)
2043                 {
2044                   struct srventry temp;
2045
2046                   memcpy(&temp,&(*list)[j],sizeof(struct srventry));
2047                   memcpy(&(*list)[j],&(*list)[i],sizeof(struct srventry));
2048                   memcpy(&(*list)[i],&temp,sizeof(struct srventry));
2049                 }
2050               break;
2051             }
2052         }
2053     }
2054
2055  leave:
2056   if (opt_debug)
2057     {
2058       if (err)
2059         log_debug ("dns: getsrv(%s): %s\n", name, gpg_strerror (err));
2060       else
2061         log_debug ("dns: getsrv(%s) -> %u records\n", name, srvcount);
2062     }
2063   if (!err)
2064     *r_count = srvcount;
2065   xfree (namebuffer);
2066   return err;
2067 }
2068
2069
2070 \f
2071 #ifdef USE_LIBDNS
2072 /* libdns version of get_dns_cname.  */
2073 gpg_error_t
2074 get_dns_cname_libdns (const char *name, char **r_cname)
2075 {
2076   gpg_error_t err;
2077   struct dns_resolver *res;
2078   struct dns_packet *ans = NULL;
2079   struct dns_cname cname;
2080   int derr;
2081
2082   err = libdns_res_open (&res);
2083   if (err)
2084     goto leave;
2085
2086   err = libdns_res_submit (res, name, DNS_T_CNAME, DNS_C_IN);
2087   if (err)
2088     goto leave;
2089
2090   err = libdns_res_wait (res);
2091   if (err)
2092     goto leave;
2093
2094   ans = dns_res_fetch (res, &derr);
2095   if (!ans)
2096     {
2097       err = libdns_error_to_gpg_error (derr);
2098       goto leave;
2099     }
2100
2101   /* Check the rcode.  */
2102   switch (dns_p_rcode (ans))
2103     {
2104     case DNS_RC_NOERROR: break;
2105     case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
2106     default: err = GPG_ERR_SERVER_FAILED; break;
2107     }
2108   if (err)
2109     goto leave;
2110
2111   /* Parse the result into CNAME.  */
2112   err = libdns_error_to_gpg_error (dns_p_study (ans));
2113   if (err)
2114     goto leave;
2115
2116   if (!dns_d_cname (&cname, sizeof cname, name, strlen (name), ans, &derr))
2117     {
2118       err = libdns_error_to_gpg_error (derr);
2119       goto leave;
2120     }
2121
2122   /* Copy result.  */
2123   *r_cname = xtrystrdup (cname.host);
2124   if (!*r_cname)
2125     err = gpg_error_from_syserror ();
2126   else
2127     {
2128       /* Libdns appends the root zone part which is problematic
2129        * for most other functions - strip it.  */
2130       if (**r_cname && (*r_cname)[strlen (*r_cname)-1] == '.')
2131         (*r_cname)[strlen (*r_cname)-1] = 0;
2132     }
2133
2134  leave:
2135   dns_free (ans);
2136   dns_res_close (res);
2137   return err;
2138 }
2139 #endif /*USE_LIBDNS*/
2140
2141
2142 /* Standard resolver version of get_dns_cname.  */
2143 gpg_error_t
2144 get_dns_cname_standard (const char *name, char **r_cname)
2145 {
2146 #ifdef HAVE_SYSTEM_RESOLVER
2147   gpg_error_t err;
2148   int rc;
2149   union {
2150     unsigned char ans[2048];
2151     HEADER header[1];
2152   } res;
2153   unsigned char *answer = res.ans;
2154   HEADER *header = res.header;
2155   unsigned char *pt, *emsg;
2156   int r;
2157   char *cname;
2158   int cnamesize = 1025;
2159   u16 count;
2160
2161   /* Do not allow a query using the standard resolver in Tor mode.  */
2162   if (tor_mode)
2163     return -1;
2164
2165   my_unprotect ();
2166   r = res_query (name, C_IN, T_CERT, answer, sizeof res.ans);
2167   my_protect ();
2168   if (r < 0)
2169     return get_h_errno_as_gpg_error ();
2170   if (r < sizeof (HEADER))
2171     return gpg_error (GPG_ERR_SERVER_FAILED);
2172   if (r > sizeof res.ans)
2173     return gpg_error (GPG_ERR_SYSTEM_BUG);
2174   if (header->rcode != NOERROR || !(count=ntohs (header->ancount)))
2175     return gpg_error (GPG_ERR_NO_NAME); /* Error or no record found.  */
2176   if (count != 1)
2177     return gpg_error (GPG_ERR_SERVER_FAILED);
2178
2179   emsg = &answer[r];
2180   pt = &answer[sizeof(HEADER)];
2181   rc = dn_skipname (pt, emsg);
2182   if (rc == -1)
2183     return gpg_error (GPG_ERR_SERVER_FAILED);
2184
2185   pt += rc + QFIXEDSZ;
2186   if (pt >= emsg)
2187     return gpg_error (GPG_ERR_SERVER_FAILED);
2188
2189   rc = dn_skipname (pt, emsg);
2190   if (rc == -1)
2191     return gpg_error (GPG_ERR_SERVER_FAILED);
2192   pt += rc + 2 + 2 + 4;
2193   if (pt+2 >= emsg)
2194     return gpg_error (GPG_ERR_SERVER_FAILED);
2195   pt += 2;  /* Skip rdlen */
2196
2197   cname = xtrymalloc (cnamesize);
2198   if (!cname)
2199     return gpg_error_from_syserror ();
2200
2201   rc = dn_expand (answer, emsg, pt, cname, cnamesize -1);
2202   if (rc == -1)
2203     {
2204       xfree (cname);
2205       return gpg_error (GPG_ERR_SERVER_FAILED);
2206     }
2207   *r_cname = xtryrealloc (cname, strlen (cname)+1);
2208   if (!*r_cname)
2209     {
2210       err = gpg_error_from_syserror ();
2211       xfree (cname);
2212       return err;
2213     }
2214   return 0;
2215
2216 #else /*!HAVE_SYSTEM_RESOLVER*/
2217
2218   (void)name;
2219   (void)r_cname;
2220   return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
2221
2222 #endif /*!HAVE_SYSTEM_RESOLVER*/
2223 }
2224
2225
2226 gpg_error_t
2227 get_dns_cname (const char *name, char **r_cname)
2228 {
2229   gpg_error_t err;
2230
2231   *r_cname = NULL;
2232
2233 #ifdef USE_LIBDNS
2234   if (!standard_resolver)
2235     {
2236       err = get_dns_cname_libdns (name, r_cname);
2237       if (err && libdns_switch_port_p (err))
2238         err = get_dns_cname_libdns (name, r_cname);
2239       return err;
2240     }
2241 #endif /*USE_LIBDNS*/
2242
2243   err = get_dns_cname_standard (name, r_cname);
2244   if (opt_debug)
2245     log_debug ("get_dns_cname(%s)%s%s\n", name,
2246                err ? ": " : " -> ",
2247                err ? gpg_strerror (err) : *r_cname);
2248   return err;
2249 }