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