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