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