1/*
2 * Copyright (c) 1985, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30/*
31 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
32 *
33 * Permission to use, copy, modify, and distribute this software for any
34 * purpose with or without fee is hereby granted, provided that the above
35 * copyright notice and this permission notice appear in all copies, and that
36 * the name of Digital Equipment Corporation not be used in advertising or
37 * publicity pertaining to distribution of the document or software without
38 * specific, written prior permission.
39 *
40 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
41 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
42 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
43 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
44 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
45 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
46 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
47 * SOFTWARE.
48 */
49
50/*
51 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
52 *
53 * Permission to use, copy, modify, and distribute this software for any
54 * purpose with or without fee is hereby granted, provided that the above
55 * copyright notice and this permission notice appear in all copies.
56 *
57 * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
58 * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
59 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
60 * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
61 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
62 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
63 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
64 * SOFTWARE.
65 */
66
67#include <ctype.h>
68#include <netdb.h>
69#include <resolv.h>
70#include <stdio.h>
71#include <stdio_ext.h>
72#include <stdlib.h>
73#include <string.h>
74#include <unistd.h>
75#include <stdint.h>
76#include <arpa/inet.h>
77#include <arpa/nameser.h>
78#include <net/if.h>
79#include <netinet/in.h>
80#include <sys/param.h>
81#include <sys/socket.h>
82#include <sys/time.h>
83#include <sys/types.h>
84
85#include <not-cancel.h>
86
87/* Options. Should all be left alone. */
88/* #undef DEBUG */
89
90static void res_setoptions (res_state, const char *, const char *)
91 internal_function;
92
93static const char sort_mask_chars[] = "/&";
94#define ISSORTMASK(ch) (strchr(sort_mask_chars, ch) != NULL)
95static u_int32_t net_mask (struct in_addr) __THROW;
96
97unsigned long long int __res_initstamp attribute_hidden;
98
99/*
100 * Resolver state default settings.
101 */
102
103/*
104 * Set up default settings. If the configuration file exist, the values
105 * there will have precedence. Otherwise, the server address is set to
106 * INADDR_LOOPBACK and the default domain name comes from gethostname.
107 *
108 * Return 0 if completes successfully, -1 on error
109 */
110int
111res_ninit(res_state statp) {
112 extern int __res_vinit(res_state, int);
113
114 return (__res_vinit(statp, 0));
115}
116libc_hidden_def (__res_ninit)
117
118/* This function has to be reachable by res_data.c but not publically. */
119int
120__res_vinit(res_state statp, int preinit) {
121 FILE *fp;
122 char *cp, **pp;
123 int n;
124 char buf[BUFSIZ];
125 int nserv = 0; /* number of nameservers read from file */
126 int have_serv6 = 0;
127 int haveenv = 0;
128 int havesearch = 0;
129 int nsort = 0;
130 char *net;
131 statp->_u._ext.initstamp = __res_initstamp;
132
133 if (!preinit) {
134 statp->retrans = RES_TIMEOUT;
135 statp->retry = RES_DFLRETRY;
136 statp->options = RES_DEFAULT;
137 statp->id = res_randomid();
138 }
139
140 statp->nscount = 0;
141 statp->defdname[0] = '\0';
142 statp->ndots = 1;
143 statp->pfcode = 0;
144 statp->_vcsock = -1;
145 statp->_flags = 0;
146 statp->qhook = NULL;
147 statp->rhook = NULL;
148 statp->_u._ext.nscount = 0;
149 for (n = 0; n < MAXNS; n++)
150 statp->_u._ext.nsaddrs[n] = NULL;
151
152 /* Allow user to override the local domain definition */
153 if ((cp = getenv("LOCALDOMAIN")) != NULL) {
154 (void)strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
155 statp->defdname[sizeof(statp->defdname) - 1] = '\0';
156 haveenv++;
157
158 /*
159 * Set search list to be blank-separated strings
160 * from rest of env value. Permits users of LOCALDOMAIN
161 * to still have a search list, and anyone to set the
162 * one that they want to use as an individual (even more
163 * important now that the rfc1535 stuff restricts searches)
164 */
165 cp = statp->defdname;
166 pp = statp->dnsrch;
167 *pp++ = cp;
168 for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
169 if (*cp == '\n') /* silly backwards compat */
170 break;
171 else if (*cp == ' ' || *cp == '\t') {
172 *cp = 0;
173 n = 1;
174 } else if (n) {
175 *pp++ = cp;
176 n = 0;
177 havesearch = 1;
178 }
179 }
180 /* null terminate last domain if there are excess */
181 while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
182 cp++;
183 *cp = '\0';
184 *pp++ = 0;
185 }
186
187#define MATCH(line, name) \
188 (!strncmp(line, name, sizeof(name) - 1) && \
189 (line[sizeof(name) - 1] == ' ' || \
190 line[sizeof(name) - 1] == '\t'))
191
192 if ((fp = fopen(_PATH_RESCONF, "rce")) != NULL) {
193 /* No threads use this stream. */
194 __fsetlocking (fp, FSETLOCKING_BYCALLER);
195 /* read the config file */
196 while (__fgets_unlocked(buf, sizeof(buf), fp) != NULL) {
197 /* skip comments */
198 if (*buf == ';' || *buf == '#')
199 continue;
200 /* read default domain name */
201 if (MATCH(buf, "domain")) {
202 if (haveenv) /* skip if have from environ */
203 continue;
204 cp = buf + sizeof("domain") - 1;
205 while (*cp == ' ' || *cp == '\t')
206 cp++;
207 if ((*cp == '\0') || (*cp == '\n'))
208 continue;
209 strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
210 statp->defdname[sizeof(statp->defdname) - 1] = '\0';
211 if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL)
212 *cp = '\0';
213 havesearch = 0;
214 continue;
215 }
216 /* set search list */
217 if (MATCH(buf, "search")) {
218 if (haveenv) /* skip if have from environ */
219 continue;
220 cp = buf + sizeof("search") - 1;
221 while (*cp == ' ' || *cp == '\t')
222 cp++;
223 if ((*cp == '\0') || (*cp == '\n'))
224 continue;
225 strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
226 statp->defdname[sizeof(statp->defdname) - 1] = '\0';
227 if ((cp = strchr(statp->defdname, '\n')) != NULL)
228 *cp = '\0';
229 /*
230 * Set search list to be blank-separated strings
231 * on rest of line.
232 */
233 cp = statp->defdname;
234 pp = statp->dnsrch;
235 *pp++ = cp;
236 for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
237 if (*cp == ' ' || *cp == '\t') {
238 *cp = 0;
239 n = 1;
240 } else if (n) {
241 *pp++ = cp;
242 n = 0;
243 }
244 }
245 /* null terminate last domain if there are excess */
246 while (*cp != '\0' && *cp != ' ' && *cp != '\t')
247 cp++;
248 *cp = '\0';
249 *pp++ = 0;
250 havesearch = 1;
251 continue;
252 }
253 /* read nameservers to query */
254 if (MATCH(buf, "nameserver") && nserv < MAXNS) {
255 struct in_addr a;
256
257 cp = buf + sizeof("nameserver") - 1;
258 while (*cp == ' ' || *cp == '\t')
259 cp++;
260 if ((*cp != '\0') && (*cp != '\n')
261 && __inet_aton(cp, &a)) {
262 statp->nsaddr_list[nserv].sin_addr = a;
263 statp->nsaddr_list[nserv].sin_family = AF_INET;
264 statp->nsaddr_list[nserv].sin_port =
265 htons(NAMESERVER_PORT);
266 nserv++;
267 } else {
268 struct in6_addr a6;
269 char *el;
270
271 if ((el = strpbrk(cp, " \t\n")) != NULL)
272 *el = '\0';
273 if ((el = strchr(cp, SCOPE_DELIMITER)) != NULL)
274 *el = '\0';
275 if ((*cp != '\0') &&
276 (__inet_pton(AF_INET6, cp, &a6) > 0)) {
277 struct sockaddr_in6 *sa6;
278
279 sa6 = malloc(sizeof(*sa6));
280 if (sa6 != NULL) {
281 sa6->sin6_family = AF_INET6;
282 sa6->sin6_port = htons(NAMESERVER_PORT);
283 sa6->sin6_flowinfo = 0;
284 sa6->sin6_addr = a6;
285
286 if (__glibc_likely (el == NULL))
287 sa6->sin6_scope_id = 0;
288 else {
289 int try_numericscope = 1;
290 if (IN6_IS_ADDR_LINKLOCAL (&a6)
291 || IN6_IS_ADDR_MC_LINKLOCAL (&a6)) {
292 sa6->sin6_scope_id
293 = __if_nametoindex (el + 1);
294 if (sa6->sin6_scope_id != 0)
295 try_numericscope = 0;
296 }
297
298 if (try_numericscope) {
299 char *end;
300 sa6->sin6_scope_id
301 = (uint32_t) strtoul (el + 1, &end,
302 10);
303 if (*end != '\0')
304 sa6->sin6_scope_id = 0;
305 }
306 }
307
308 statp->nsaddr_list[nserv].sin_family = 0;
309 statp->_u._ext.nsaddrs[nserv] = sa6;
310 statp->_u._ext.nssocks[nserv] = -1;
311 have_serv6 = 1;
312 nserv++;
313 }
314 }
315 }
316 continue;
317 }
318 if (MATCH(buf, "sortlist")) {
319 struct in_addr a;
320
321 cp = buf + sizeof("sortlist") - 1;
322 while (nsort < MAXRESOLVSORT) {
323 while (*cp == ' ' || *cp == '\t')
324 cp++;
325 if (*cp == '\0' || *cp == '\n' || *cp == ';')
326 break;
327 net = cp;
328 while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
329 isascii(*cp) && !isspace(*cp))
330 cp++;
331 n = *cp;
332 *cp = 0;
333 if (__inet_aton(net, &a)) {
334 statp->sort_list[nsort].addr = a;
335 if (ISSORTMASK(n)) {
336 *cp++ = n;
337 net = cp;
338 while (*cp && *cp != ';' &&
339 isascii(*cp) && !isspace(*cp))
340 cp++;
341 n = *cp;
342 *cp = 0;
343 if (__inet_aton(net, &a)) {
344 statp->sort_list[nsort].mask = a.s_addr;
345 } else {
346 statp->sort_list[nsort].mask =
347 net_mask(statp->sort_list[nsort].addr);
348 }
349 } else {
350 statp->sort_list[nsort].mask =
351 net_mask(statp->sort_list[nsort].addr);
352 }
353 nsort++;
354 }
355 *cp = n;
356 }
357 continue;
358 }
359 if (MATCH(buf, "options")) {
360 res_setoptions(statp, buf + sizeof("options") - 1, "conf");
361 continue;
362 }
363 }
364 statp->nscount = nserv;
365 if (have_serv6) {
366 /* We try IPv6 servers again. */
367 statp->ipv6_unavail = false;
368 }
369 statp->nsort = nsort;
370 (void) fclose(fp);
371 }
372 if (__builtin_expect(statp->nscount == 0, 0)) {
373 statp->nsaddr.sin_addr = __inet_makeaddr(IN_LOOPBACKNET, 1);
374 statp->nsaddr.sin_family = AF_INET;
375 statp->nsaddr.sin_port = htons(NAMESERVER_PORT);
376 statp->nscount = 1;
377 }
378 if (statp->defdname[0] == 0 &&
379 __gethostname(buf, sizeof(statp->defdname) - 1) == 0 &&
380 (cp = strchr(buf, '.')) != NULL)
381 strcpy(statp->defdname, cp + 1);
382
383 /* find components of local domain that might be searched */
384 if (havesearch == 0) {
385 pp = statp->dnsrch;
386 *pp++ = statp->defdname;
387 *pp = NULL;
388
389 }
390
391 if ((cp = getenv("RES_OPTIONS")) != NULL)
392 res_setoptions(statp, cp, "env");
393 statp->options |= RES_INIT;
394 return (0);
395}
396
397static void
398internal_function
399res_setoptions(res_state statp, const char *options, const char *source) {
400 const char *cp = options;
401 int i;
402
403#ifdef DEBUG
404 if (statp->options & RES_DEBUG)
405 printf(";; res_setoptions(\"%s\", \"%s\")...\n",
406 options, source);
407#endif
408 while (*cp) {
409 /* skip leading and inner runs of spaces */
410 while (*cp == ' ' || *cp == '\t')
411 cp++;
412 /* search for and process individual options */
413 if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) {
414 i = atoi(cp + sizeof("ndots:") - 1);
415 if (i <= RES_MAXNDOTS)
416 statp->ndots = i;
417 else
418 statp->ndots = RES_MAXNDOTS;
419#ifdef DEBUG
420 if (statp->options & RES_DEBUG)
421 printf(";;\tndots=%d\n", statp->ndots);
422#endif
423 } else if (!strncmp(cp, "timeout:", sizeof("timeout:") - 1)) {
424 i = atoi(cp + sizeof("timeout:") - 1);
425 if (i <= RES_MAXRETRANS)
426 statp->retrans = i;
427 else
428 statp->retrans = RES_MAXRETRANS;
429 } else if (!strncmp(cp, "attempts:", sizeof("attempts:") - 1)){
430 i = atoi(cp + sizeof("attempts:") - 1);
431 if (i <= RES_MAXRETRY)
432 statp->retry = i;
433 else
434 statp->retry = RES_MAXRETRY;
435 } else if (!strncmp(cp, "debug", sizeof("debug") - 1)) {
436#ifdef DEBUG
437 if (!(statp->options & RES_DEBUG)) {
438 printf(";; res_setoptions(\"%s\", \"%s\")..\n",
439 options, source);
440 statp->options |= RES_DEBUG;
441 }
442 printf(";;\tdebug\n");
443#endif
444 } else {
445 static const struct
446 {
447 char str[22];
448 uint8_t len;
449 uint8_t clear;
450 unsigned long int flag;
451 } options[] = {
452#define STRnLEN(str) str, sizeof (str) - 1
453 { STRnLEN ("inet6"), 0, RES_USE_INET6 },
454 { STRnLEN ("ip6-bytestring"), 0, RES_USEBSTRING },
455 { STRnLEN ("no-ip6-dotint"), 0, RES_NOIP6DOTINT },
456 { STRnLEN ("ip6-dotint"), 1, ~RES_NOIP6DOTINT },
457 { STRnLEN ("rotate"), 0, RES_ROTATE },
458 { STRnLEN ("no-check-names"), 0, RES_NOCHECKNAME },
459 { STRnLEN ("edns0"), 0, RES_USE_EDNS0 },
460 { STRnLEN ("single-request-reopen"), 0, RES_SNGLKUPREOP },
461 { STRnLEN ("single-request"), 0, RES_SNGLKUP },
462 { STRnLEN ("no_tld_query"), 0, RES_NOTLDQUERY },
463 { STRnLEN ("no-tld-query"), 0, RES_NOTLDQUERY },
464 { STRnLEN ("use-vc"), 0, RES_USEVC }
465 };
466#define noptions (sizeof (options) / sizeof (options[0]))
467 int i;
468 for (i = 0; i < noptions; ++i)
469 if (strncmp (cp, options[i].str, options[i].len) == 0)
470 {
471 if (options[i].clear)
472 statp->options &= options[i].flag;
473 else
474 statp->options |= options[i].flag;
475 break;
476 }
477 if (i == noptions) {
478 /* XXX - print a warning here? */
479 }
480 }
481 /* skip to next run of spaces */
482 while (*cp && *cp != ' ' && *cp != '\t')
483 cp++;
484 }
485}
486
487/* XXX - should really support CIDR which means explicit masks always. */
488/* XXX - should really use system's version of this */
489static u_int32_t
490net_mask (struct in_addr in)
491{
492 u_int32_t i = ntohl(in.s_addr);
493
494 if (IN_CLASSA(i))
495 return (htonl(IN_CLASSA_NET));
496 else if (IN_CLASSB(i))
497 return (htonl(IN_CLASSB_NET));
498 return (htonl(IN_CLASSC_NET));
499}
500
501u_int
502res_randomid(void) {
503 return 0xffff & __getpid();
504}
505libc_hidden_def (__res_randomid)
506
507
508/*
509 * This routine is for closing the socket if a virtual circuit is used and
510 * the program wants to close it. This provides support for endhostent()
511 * which expects to close the socket.
512 *
513 * This routine is not expected to be user visible.
514 */
515void
516__res_iclose(res_state statp, bool free_addr) {
517 int ns;
518
519 if (statp->_vcsock >= 0) {
520 close_not_cancel_no_status(statp->_vcsock);
521 statp->_vcsock = -1;
522 statp->_flags &= ~(RES_F_VC | RES_F_CONN);
523 }
524 for (ns = 0; ns < statp->nscount; ns++)
525 if (statp->_u._ext.nsaddrs[ns]) {
526 if (statp->_u._ext.nssocks[ns] != -1) {
527 close_not_cancel_no_status(statp->_u._ext.nssocks[ns]);
528 statp->_u._ext.nssocks[ns] = -1;
529 }
530 if (free_addr) {
531 free (statp->_u._ext.nsaddrs[ns]);
532 statp->_u._ext.nsaddrs[ns] = NULL;
533 }
534 }
535}
536libc_hidden_def (__res_iclose)
537
538void
539res_nclose(res_state statp)
540{
541 __res_iclose (statp, true);
542}
543libc_hidden_def (__res_nclose)
544
545#ifdef _LIBC_REENTRANT
546/* This is called when a thread is exiting to free resources held in _res. */
547static void __attribute__ ((section ("__libc_thread_freeres_fn")))
548res_thread_freeres (void)
549{
550 if (_res.nscount == 0)
551 /* Never called res_ninit. */
552 return;
553
554 __res_iclose (&_res, true); /* Close any VC sockets. */
555
556 /* Make sure we do a full re-initialization the next time. */
557 _res.options = 0;
558}
559text_set_element (__libc_thread_subfreeres, res_thread_freeres);
560text_set_element (__libc_subfreeres, res_thread_freeres);
561#endif
562