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