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