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