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