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