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