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