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