xref: /netbsd-src/lib/libc/resolv/res_init.c (revision 30d43af96b5d3eb9983c28c54dedd408d2fb277c)
1 /*	$NetBSD: res_init.c,v 1.32 2021/09/30 12:35:55 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 1985, 1989, 1993
5  *    The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*
33  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
34  *
35  * Permission to use, copy, modify, and distribute this software for any
36  * purpose with or without fee is hereby granted, provided that the above
37  * copyright notice and this permission notice appear in all copies, and that
38  * the name of Digital Equipment Corporation not be used in advertising or
39  * publicity pertaining to distribution of the document or software without
40  * specific, written prior permission.
41  *
42  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
43  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
44  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
45  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
46  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
47  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
48  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
49  * SOFTWARE.
50  */
51 
52 /*
53  * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
54  * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
55  *
56  * Permission to use, copy, modify, and distribute this software for any
57  * purpose with or without fee is hereby granted, provided that the above
58  * copyright notice and this permission notice appear in all copies.
59  *
60  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
61  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
62  * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
63  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
64  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
65  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
66  * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
67  */
68 
69 #include <sys/cdefs.h>
70 #if defined(LIBC_SCCS) && !defined(lint)
71 #ifdef notdef
72 static const char sccsid[] = "@(#)res_init.c	8.1 (Berkeley) 6/7/93";
73 static const char rcsid[] = "Id: res_init.c,v 1.26 2008/12/11 09:59:00 marka Exp";
74 #else
75 __RCSID("$NetBSD: res_init.c,v 1.32 2021/09/30 12:35:55 christos Exp $");
76 #endif
77 #endif /* LIBC_SCCS and not lint */
78 
79 #include "port_before.h"
80 
81 #include "namespace.h"
82 #include <sys/types.h>
83 #include <sys/param.h>
84 #include <sys/socket.h>
85 #include <sys/stat.h>
86 #include <sys/time.h>
87 #include <sys/event.h>
88 
89 #include <netinet/in.h>
90 #include <arpa/inet.h>
91 #include <arpa/nameser.h>
92 
93 #include <ctype.h>
94 #include <stdio.h>
95 #include <stdlib.h>
96 #include <string.h>
97 #include <unistd.h>
98 #include <fcntl.h>
99 #include <netdb.h>
100 
101 #define HAVE_MD5
102 #include <md5.h>
103 
104 #ifndef HAVE_MD5
105 # include "../dst/md5.h"
106 #else
107 # ifdef SOLARIS2
108 #  include <sys/md5.h>
109 # endif
110 #endif
111 #ifndef _MD5_H_
112 # define _MD5_H_ 1	/*%< make sure we do not include rsaref md5.h file */
113 #endif
114 
115 #include "port_after.h"
116 
117 #if 0
118 #ifdef __weak_alias
119 __weak_alias(res_ninit,_res_ninit)
120 __weak_alias(res_randomid,__res_randomid)
121 __weak_alias(res_nclose,_res_nclose)
122 __weak_alias(res_ndestroy,_res_ndestroy)
123 __weak_alias(res_get_nibblesuffix,__res_get_nibblesuffix)
124 __weak_alias(res_get_nibblesuffix2,__res_get_nibblesuffix2)
125 __weak_alias(res_getservers,__res_getservers)
126 __weak_alias(res_setservers,__res_setservers)
127 #endif
128 #endif
129 
130 
131 /* ensure that sockaddr_in6 and IN6ADDR_ANY_INIT are declared / defined */
132 #include <resolv.h>
133 
134 #include "res_private.h"
135 
136 #define RESOLVSORT
137 /*% Options.  Should all be left alone. */
138 #ifndef DEBUG
139 #define DEBUG
140 #endif
141 
142 #ifdef SOLARIS2
143 #include <sys/systeminfo.h>
144 #endif
145 
146 static void res_setoptions(res_state, const char *, const char *);
147 
148 #ifdef RESOLVSORT
149 static const char sort_mask[] = "/&";
150 #define ISSORTMASK(ch) (strchr(sort_mask, ch) != NULL)
151 static uint32_t net_mask(struct in_addr);
152 #endif
153 
154 #if !defined(isascii)	/*%< XXX - could be a function */
155 # define isascii(c) (!(c & 0200))
156 #endif
157 
158 static struct timespec __res_conf_time;
159 static const struct timespec ts = { 0, 0 };
160 
161 const char *__res_conf_name = _PATH_RESCONF;
162 
163 /*
164  * Resolver state default settings.
165  */
166 
167 /*%
168  * Set up default settings.  If the configuration file exist, the values
169  * there will have precedence.  Otherwise, the server address is set to
170  * INADDR_ANY and the default domain name comes from the gethostname().
171  *
172  * An interrim version of this code (BIND 4.9, pre-4.4BSD) used 127.0.0.1
173  * rather than INADDR_ANY ("0.0.0.0") as the default name server address
174  * since it was noted that INADDR_ANY actually meant ``the first interface
175  * you "ifconfig"'d at boot time'' and if this was a SLIP or PPP interface,
176  * it had to be "up" in order for you to reach your own name server.  It
177  * was later decided that since the recommended practice is to always
178  * install local static routes through 127.0.0.1 for all your network
179  * interfaces, that we could solve this problem without a code change.
180  *
181  * The configuration file should always be used, since it is the only way
182  * to specify a default domain.  If you are running a server on your local
183  * machine, you should say "nameserver 0.0.0.0" or "nameserver 127.0.0.1"
184  * in the configuration file.
185  *
186  * Return 0 if completes successfully, -1 on error
187  */
188 int
res_ninit(res_state statp)189 res_ninit(res_state statp) {
190 	return (__res_vinit(statp, 0));
191 }
192 
193 static int
__res_kqinit(res_state statp)194 __res_kqinit(res_state statp)
195 {
196 	struct kevent kc;
197 	struct __res_state_ext *ext = statp->_u._ext.ext;
198 
199 	ext->kq = kqueue1(O_CLOEXEC);
200 	ext->kqpid = getpid();
201 	EV_SET(&kc, ext->resfd, EVFILT_VNODE,
202 	    EV_ADD|EV_ENABLE|EV_CLEAR, NOTE_DELETE|NOTE_WRITE| NOTE_EXTEND|
203 	    NOTE_ATTRIB|NOTE_LINK|NOTE_RENAME|NOTE_REVOKE, 0, 0);
204 	(void)kevent(ext->kq, &kc, 1, NULL, 0, &ts);
205 	return ext->kq;
206 }
207 
208 /*% This function has to be reachable by res_data.c but not publically. */
209 int
__res_vinit(res_state statp,int preinit)210 __res_vinit(res_state statp, int preinit) {
211 	register FILE *fp;
212 	register char *cp, **pp;
213 	register int n;
214 	char buf[BUFSIZ];
215 	int nserv = 0;    /*%< number of nameserver records read from file */
216 	int haveenv = 0;
217 	int havesearch = 0;
218 #ifdef RESOLVSORT
219 	int nsort = 0;
220 	char *net;
221 #endif
222 	int dots;
223 	union res_sockaddr_union u[2];
224 	int maxns = MAXNS;
225 
226 	RES_SET_H_ERRNO(statp, 0);
227 
228 	if ((statp->options & RES_INIT) != 0U)
229 		res_ndestroy(statp);
230 
231 	if (!preinit) {
232 		statp->retrans = RES_TIMEOUT;
233 		statp->retry = RES_DFLRETRY;
234 		statp->options = RES_DEFAULT;
235 	}
236 	statp->_rnd = malloc(16);
237 	res_rndinit(statp);
238 	statp->id = res_nrandomid(statp);
239 
240 	memset(u, 0, sizeof(u));
241 #ifdef USELOOPBACK
242 	u[nserv].sin.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
243 #else
244 	u[nserv].sin.sin_addr.s_addr = INADDR_ANY;
245 #endif
246 	u[nserv].sin.sin_family = AF_INET;
247 	u[nserv].sin.sin_port = htons(NAMESERVER_PORT);
248 #ifdef HAVE_SA_LEN
249 	u[nserv].sin.sin_len = sizeof(struct sockaddr_in);
250 #endif
251 	nserv++;
252 #ifdef HAS_INET6_STRUCTS
253 #ifdef USELOOPBACK
254 	u[nserv].sin6.sin6_addr = in6addr_loopback;
255 #else
256 	u[nserv].sin6.sin6_addr = in6addr_any;
257 #endif
258 	u[nserv].sin6.sin6_family = AF_INET6;
259 	u[nserv].sin6.sin6_port = htons(NAMESERVER_PORT);
260 #ifdef HAVE_SA_LEN
261 	u[nserv].sin6.sin6_len = sizeof(struct sockaddr_in6);
262 #endif
263 	nserv++;
264 #endif
265 	statp->nscount = 0;
266 	statp->ndots = 1;
267 	statp->pfcode = 0;
268 	statp->_vcsock = -1;
269 	statp->_flags = 0;
270 	statp->qhook = NULL;
271 	statp->rhook = NULL;
272 	statp->_u._ext.nscount = 0;
273 	statp->_u._ext.ext = malloc(sizeof(*statp->_u._ext.ext));
274 	if (statp->_u._ext.ext != NULL) {
275 	        memset(statp->_u._ext.ext, 0, sizeof(*statp->_u._ext.ext));
276 		statp->_u._ext.ext->nsaddrs[0].sin = statp->nsaddr;
277 		strcpy(statp->_u._ext.ext->nsuffix, "ip6.arpa");
278 		strcpy(statp->_u._ext.ext->nsuffix2, "ip6.int");
279 	} else {
280 		/*
281 		 * Historically res_init() rarely, if at all, failed.
282 		 * Examples and applications exist which do not check
283 		 * our return code.  Furthermore several applications
284 		 * simply call us to get the systems domainname.  So
285 		 * rather than immediately fail here we store the
286 		 * failure, which is returned later, in h_errno.  And
287 		 * prevent the collection of 'nameserver' information
288 		 * by setting maxns to 0.  Thus applications that fail
289 		 * to check our return code wont be able to make
290 		 * queries anyhow.
291 		 */
292 		RES_SET_H_ERRNO(statp, NETDB_INTERNAL);
293 		maxns = 0;
294 	}
295 #ifdef RESOLVSORT
296 	statp->nsort = 0;
297 #endif
298 	res_setservers(statp, u, nserv);
299 
300 #ifdef	SOLARIS2
301 	/*
302 	 * The old libresolv derived the defaultdomain from NIS/NIS+.
303 	 * We want to keep this behaviour
304 	 */
305 	{
306 		char buf[sizeof(statp->defdname)], *cp;
307 		int ret;
308 
309 		if ((ret = sysinfo(SI_SRPC_DOMAIN, buf, sizeof(buf))) > 0 &&
310 			(unsigned int)ret <= sizeof(buf)) {
311 			if (buf[0] == '+')
312 				buf[0] = '.';
313 			cp = strchr(buf, '.');
314 			cp = (cp == NULL) ? buf : (cp + 1);
315 			(void)strlcpy(statp->defdname, cp,
316 			    sizeof(statp->defdname));
317 		}
318 	}
319 #endif	/* SOLARIS2 */
320 
321 	/* Allow user to override the local domain definition */
322 	if ((cp = getenv("LOCALDOMAIN")) != NULL) {
323 		(void)strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
324 		statp->defdname[sizeof(statp->defdname) - 1] = '\0';
325 		haveenv++;
326 
327 		/*
328 		 * Set search list to be blank-separated strings
329 		 * from rest of env value.  Permits users of LOCALDOMAIN
330 		 * to still have a search list, and anyone to set the
331 		 * one that they want to use as an individual (even more
332 		 * important now that the rfc1535 stuff restricts searches)
333 		 */
334 		cp = statp->defdname;
335 		pp = statp->dnsrch;
336 		*pp++ = cp;
337 		for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
338 			if (*cp == '\n')	/*%< silly backwards compat */
339 				break;
340 			else if (*cp == ' ' || *cp == '\t') {
341 				*cp = 0;
342 				n = 1;
343 			} else if (n) {
344 				*pp++ = cp;
345 				n = 0;
346 				havesearch = 1;
347 			}
348 		}
349 		/* null terminate last domain if there are excess */
350 		while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
351 			cp++;
352 		*cp = '\0';
353 		*pp++ = 0;
354 	}
355 
356 #define	MATCH(line, name) \
357 	(!strncmp(line, name, sizeof(name) - 1) && \
358 	(line[sizeof(name) - 1] == ' ' || \
359 	 line[sizeof(name) - 1] == '\t'))
360 
361 	nserv = 0;
362 	if ((fp = fopen(__res_conf_name, "re")) != NULL) {
363 	    struct stat st;
364 
365 	    /* read the config file */
366 	    while (fgets(buf, (int)sizeof(buf), fp) != NULL) {
367 		/* skip comments */
368 		if (*buf == ';' || *buf == '#')
369 			continue;
370 		/* read default domain name */
371 		if (MATCH(buf, "domain")) {
372 		    if (haveenv)	/*%< skip if have from environ */
373 			    continue;
374 		    cp = buf + sizeof("domain") - 1;
375 		    while (*cp == ' ' || *cp == '\t')
376 			    cp++;
377 		    if ((*cp == '\0') || (*cp == '\n'))
378 			    continue;
379 		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
380 		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
381 		    if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL)
382 			    *cp = '\0';
383 		    havesearch = 0;
384 		    continue;
385 		}
386 		/* set search list */
387 		if (MATCH(buf, "search")) {
388 		    if (haveenv)	/*%< skip if have from environ */
389 			    continue;
390 		    cp = buf + sizeof("search") - 1;
391 		    while (*cp == ' ' || *cp == '\t')
392 			    cp++;
393 		    if ((*cp == '\0') || (*cp == '\n'))
394 			    continue;
395 		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
396 		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
397 		    if ((cp = strchr(statp->defdname, '\n')) != NULL)
398 			    *cp = '\0';
399 		    /*
400 		     * Set search list to be blank-separated strings
401 		     * on rest of line.
402 		     */
403 		    cp = statp->defdname;
404 		    pp = statp->dnsrch;
405 		    *pp++ = cp;
406 		    for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
407 			    if (*cp == ' ' || *cp == '\t') {
408 				    *cp = 0;
409 				    n = 1;
410 			    } else if (n) {
411 				    *pp++ = cp;
412 				    n = 0;
413 			    }
414 		    }
415 		    /* null terminate last domain if there are excess */
416 		    while (*cp != '\0' && *cp != ' ' && *cp != '\t')
417 			    cp++;
418 		    *cp = '\0';
419 		    *pp++ = 0;
420 		    havesearch = 1;
421 		    continue;
422 		}
423 		/* read nameservers to query */
424 		if (MATCH(buf, "nameserver") && nserv < maxns) {
425 		    struct addrinfo hints, *ai;
426 		    char sbuf[NI_MAXSERV];
427 		    const size_t minsiz =
428 		        sizeof(statp->_u._ext.ext->nsaddrs[0]);
429 
430 		    cp = buf + sizeof("nameserver") - 1;
431 		    while (*cp == ' ' || *cp == '\t')
432 			cp++;
433 		    cp[strcspn(cp, ";# \t\n")] = '\0';
434 		    if ((*cp != '\0') && (*cp != '\n')) {
435 			memset(&hints, 0, sizeof(hints));
436 			hints.ai_family = PF_UNSPEC;
437 			hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
438 			hints.ai_flags = AI_NUMERICHOST;
439 			sprintf(sbuf, "%u", NAMESERVER_PORT);
440 			if (getaddrinfo(cp, sbuf, &hints, &ai) == 0 &&
441 			    ai->ai_addrlen <= minsiz) {
442 			    if (statp->_u._ext.ext != NULL) {
443 				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
444 				    ai->ai_addr, ai->ai_addrlen);
445 			    }
446 			    if (ai->ai_addrlen <=
447 			        sizeof(statp->nsaddr_list[nserv])) {
448 				memcpy(&statp->nsaddr_list[nserv],
449 				    ai->ai_addr, ai->ai_addrlen);
450 			    } else
451 				statp->nsaddr_list[nserv].sin_family = 0;
452 			    freeaddrinfo(ai);
453 			    nserv++;
454 			}
455 		    }
456 		    continue;
457 		}
458 #ifdef RESOLVSORT
459 		if (MATCH(buf, "sortlist")) {
460 		    struct in_addr a;
461 
462 		    cp = buf + sizeof("sortlist") - 1;
463 		    while (nsort < MAXRESOLVSORT) {
464 			while (*cp == ' ' || *cp == '\t')
465 			    cp++;
466 			if (*cp == '\0' || *cp == '\n' || *cp == ';')
467 			    break;
468 			net = cp;
469 			while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
470 			       isascii(*cp) && !isspace((unsigned char)*cp))
471 				cp++;
472 			n = *cp;
473 			*cp = 0;
474 			if (inet_aton(net, &a)) {
475 			    statp->sort_list[nsort].addr = a;
476 			    if (ISSORTMASK(n)) {
477 				*cp++ = n;
478 				net = cp;
479 				while (*cp && *cp != ';' &&
480 					isascii(*cp) &&
481 					!isspace((unsigned char)*cp))
482 				    cp++;
483 				n = *cp;
484 				*cp = 0;
485 				if (inet_aton(net, &a)) {
486 				    statp->sort_list[nsort].mask = a.s_addr;
487 				} else {
488 				    statp->sort_list[nsort].mask =
489 					net_mask(statp->sort_list[nsort].addr);
490 				}
491 			    } else {
492 				statp->sort_list[nsort].mask =
493 				    net_mask(statp->sort_list[nsort].addr);
494 			    }
495 			    nsort++;
496 			}
497 			*cp = n;
498 		    }
499 		    continue;
500 		}
501 #endif
502 		if (MATCH(buf, "options")) {
503 		    res_setoptions(statp, buf + sizeof("options") - 1, "conf");
504 		    continue;
505 		}
506 	    }
507 	    if (nserv > 0)
508 		statp->nscount = nserv;
509 #ifdef RESOLVSORT
510 	    statp->nsort = nsort;
511 #endif
512 	    statp->_u._ext.ext->resfd = fcntl(fileno(fp), F_DUPFD_CLOEXEC, 0);
513 	    (void) fclose(fp);
514 	    if (fstat(statp->_u._ext.ext->resfd, &st) != -1)
515 		    __res_conf_time = statp->_u._ext.ext->res_conf_time =
516 			st.st_mtimespec;
517 	    __res_kqinit(statp);
518 	} else {
519 	    statp->_u._ext.ext->kq = -1;
520 	    statp->_u._ext.ext->resfd = -1;
521 	}
522 /*
523  * Last chance to get a nameserver.  This should not normally
524  * be necessary
525  */
526 #ifdef NO_RESOLV_CONF
527 	if(nserv == 0)
528 		nserv = get_nameservers(statp);
529 #endif
530 
531 	if (statp->defdname[0] == 0 &&
532 	    gethostname(buf, sizeof(statp->defdname) - 1) == 0 &&
533 	    (cp = strchr(buf, '.')) != NULL)
534 		strcpy(statp->defdname, cp + 1);
535 
536 	/* find components of local domain that might be searched */
537 	if (havesearch == 0) {
538 		pp = statp->dnsrch;
539 		*pp++ = statp->defdname;
540 		*pp = NULL;
541 
542 		dots = 0;
543 		for (cp = statp->defdname; *cp; cp++)
544 			dots += (*cp == '.');
545 
546 		cp = statp->defdname;
547 		while (pp < statp->dnsrch + MAXDFLSRCH) {
548 			if (dots < LOCALDOMAINPARTS)
549 				break;
550 			cp = strchr(cp, '.') + 1;    /*%< we know there is one */
551 			*pp++ = cp;
552 			dots--;
553 		}
554 		*pp = NULL;
555 #ifdef DEBUG
556 		if (statp->options & RES_DEBUG) {
557 			printf(";; res_init()... default dnsrch list:\n");
558 			for (pp = statp->dnsrch; *pp; pp++)
559 				printf(";;\t%s\n", *pp);
560 			printf(";;\t..END..\n");
561 		}
562 #endif
563 	}
564 
565 	if ((cp = getenv("RES_OPTIONS")) != NULL)
566 		res_setoptions(statp, cp, "env");
567 	statp->options |= RES_INIT;
568 	return (statp->res_h_errno);
569 }
570 
571 int
res_check(res_state statp,struct timespec * mtime)572 res_check(res_state statp, struct timespec *mtime)
573 {
574 	/*
575 	 * If the times are equal, then we check if there
576 	 * was a kevent related to resolv.conf and reload.
577 	 * If the times are not equal, then we don't bother
578 	 * to check the kevent, because another thread already
579 	 * did, loaded and changed the time.
580 	 */
581 	if (timespeccmp(&statp->_u._ext.ext->res_conf_time,
582 	    &__res_conf_time, ==)) {
583 		struct kevent ke;
584 		if (statp->_u._ext.ext->kq == -1)
585 			goto out;
586 		if (statp->_u._ext.ext->kqpid != getpid() &&
587 		    __res_kqinit(statp) == -1)
588 			goto out;
589 
590 		switch (kevent(statp->_u._ext.ext->kq, NULL, 0, &ke, 1, &ts)) {
591 		case 0:
592 		case -1:
593 out:
594 			if (mtime)
595 				*mtime = __res_conf_time;
596 			return 0;
597 		default:
598 			break;
599 		}
600 	}
601 	(void)__res_vinit(statp, 0);
602 	if (mtime)
603 		*mtime = __res_conf_time;
604 	return 1;
605 }
606 
607 static void
res_setoptions(res_state statp,const char * options,const char * source)608 res_setoptions(res_state statp, const char *options, const char *source)
609 {
610 	const char *cp = options;
611 	int i;
612 	size_t j;
613 	struct __res_state_ext *ext = statp->_u._ext.ext;
614 
615 #ifdef DEBUG
616 	if (statp->options & RES_DEBUG)
617 		printf(";; res_setoptions(\"%s\", \"%s\")...\n",
618 		       options, source);
619 #endif
620 	while (*cp) {
621 		/* skip leading and inner runs of spaces */
622 		while (*cp == ' ' || *cp == '\t')
623 			cp++;
624 		/* search for and process individual options */
625 		if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) {
626 			i = atoi(cp + sizeof("ndots:") - 1);
627 			if (i <= RES_MAXNDOTS)
628 				statp->ndots = i;
629 			else
630 				statp->ndots = RES_MAXNDOTS;
631 #ifdef DEBUG
632 			if (statp->options & RES_DEBUG)
633 				printf(";;\tndots=%d\n", statp->ndots);
634 #endif
635 		} else if (!strncmp(cp, "timeout:", sizeof("timeout:") - 1)) {
636 			i = atoi(cp + sizeof("timeout:") - 1);
637 			if (i <= RES_MAXRETRANS)
638 				statp->retrans = i;
639 			else
640 				statp->retrans = RES_MAXRETRANS;
641 #ifdef DEBUG
642 			if (statp->options & RES_DEBUG)
643 				printf(";;\ttimeout=%d\n", statp->retrans);
644 #endif
645 #ifdef	SOLARIS2
646 		} else if (!strncmp(cp, "retrans:", sizeof("retrans:") - 1)) {
647 			/*
648 		 	 * For backward compatibility, 'retrans' is
649 		 	 * supported as an alias for 'timeout', though
650 		 	 * without an imposed maximum.
651 		 	 */
652 			statp->retrans = atoi(cp + sizeof("retrans:") - 1);
653 		} else if (!strncmp(cp, "retry:", sizeof("retry:") - 1)){
654 			/*
655 			 * For backward compatibility, 'retry' is
656 			 * supported as an alias for 'attempts', though
657 			 * without an imposed maximum.
658 			 */
659 			statp->retry = atoi(cp + sizeof("retry:") - 1);
660 #endif	/* SOLARIS2 */
661 		} else if (!strncmp(cp, "attempts:", sizeof("attempts:") - 1)){
662 			i = atoi(cp + sizeof("attempts:") - 1);
663 			if (i <= RES_MAXRETRY)
664 				statp->retry = i;
665 			else
666 				statp->retry = RES_MAXRETRY;
667 #ifdef DEBUG
668 			if (statp->options & RES_DEBUG)
669 				printf(";;\tattempts=%d\n", statp->retry);
670 #endif
671 		} else if (!strncmp(cp, "debug", sizeof("debug") - 1)) {
672 #ifdef DEBUG
673 			if (!(statp->options & RES_DEBUG)) {
674 				printf(";; res_setoptions(\"%s\", \"%s\")..\n",
675 				       options, source);
676 				statp->options |= RES_DEBUG;
677 			}
678 			printf(";;\tdebug\n");
679 #endif
680 		} else if (!strncmp(cp, "no_tld_query",
681 				    sizeof("no_tld_query") - 1) ||
682 			   !strncmp(cp, "no-tld-query",
683 				    sizeof("no-tld-query") - 1)) {
684 			statp->options |= RES_NOTLDQUERY;
685 		} else if (!strncmp(cp, "inet6", sizeof("inet6") - 1)) {
686 			statp->options |= RES_USE_INET6;
687 		} else if (!strncmp(cp, "rotate", sizeof("rotate") - 1)) {
688 			statp->options |= RES_ROTATE;
689 		} else if (!strncmp(cp, "no-check-names",
690 				    sizeof("no-check-names") - 1)) {
691 			statp->options |= RES_NOCHECKNAME;
692 		} else if (!strncmp(cp, "check-names",
693 				    sizeof("check-names") - 1)) {
694 			statp->options &= ~RES_NOCHECKNAME;
695 		}
696 #ifdef RES_USE_EDNS0
697 		else if (!strncmp(cp, "edns0", sizeof("edns0") - 1)) {
698 			statp->options |= RES_USE_EDNS0;
699 		}
700 #endif
701 		else if (!strncmp(cp, "dname", sizeof("dname") - 1)) {
702 			statp->options |= RES_USE_DNAME;
703 		}
704 		else if (!strncmp(cp, "nibble:", sizeof("nibble:") - 1)) {
705 			if (ext == NULL)
706 				goto skip;
707 			cp += sizeof("nibble:") - 1;
708 			j = MIN(strcspn(cp, " \t"), sizeof(ext->nsuffix) - 1);
709 			strncpy(ext->nsuffix, cp, j);
710 			ext->nsuffix[j] = '\0';
711 		}
712 		else if (!strncmp(cp, "nibble2:", sizeof("nibble2:") - 1)) {
713 			if (ext == NULL)
714 				goto skip;
715 			cp += sizeof("nibble2:") - 1;
716 			j = MIN(strcspn(cp, " \t"), sizeof(ext->nsuffix2) - 1);
717 			strncpy(ext->nsuffix2, cp, j);
718 			ext->nsuffix2[j] = '\0';
719 		}
720 		else if (!strncmp(cp, "v6revmode:", sizeof("v6revmode:") - 1)) {
721 			cp += sizeof("v6revmode:") - 1;
722 			/* "nibble" and "bitstring" used to be valid */
723 			if (!strncmp(cp, "single", sizeof("single") - 1)) {
724 				statp->options |= RES_NO_NIBBLE2;
725 			} else if (!strncmp(cp, "both", sizeof("both") - 1)) {
726 				statp->options &=
727 					 ~RES_NO_NIBBLE2;
728 			}
729 		}
730 		else {
731 			/* XXX - print a warning here? */
732 		}
733    skip:
734 		/* skip to next run of spaces */
735 		while (*cp && *cp != ' ' && *cp != '\t')
736 			cp++;
737 	}
738 }
739 
740 #ifdef RESOLVSORT
741 /* XXX - should really support CIDR which means explicit masks always. */
742 static uint32_t
net_mask(struct in_addr in)743 net_mask(struct in_addr in) /*!< XXX - should really use system's version of this  */
744 {
745 	register uint32_t i = ntohl(in.s_addr);
746 
747 	if (IN_CLASSA(i))
748 		return (htonl(IN_CLASSA_NET));
749 	else if (IN_CLASSB(i))
750 		return (htonl(IN_CLASSB_NET));
751 	return (htonl(IN_CLASSC_NET));
752 }
753 #endif
754 
755 static u_char srnd[16];
756 
757 void
res_rndinit(res_state statp)758 res_rndinit(res_state statp)
759 {
760 	struct timeval now;
761 	uint32_t u32;
762 	uint16_t u16;
763 	u_char *rnd = statp->_rnd == NULL ? srnd : statp->_rnd;
764 
765 	gettimeofday(&now, NULL);
766 	u32 = (uint32_t)now.tv_sec;
767 	memcpy(rnd, &u32, 4);
768 	u32 = now.tv_usec;
769 	memcpy(rnd + 4, &u32, 4);
770 	u32 += (uint32_t)now.tv_sec;
771 	memcpy(rnd + 8, &u32, 4);
772 	u16 = getpid();
773 	memcpy(rnd + 12, &u16, 2);
774 }
775 
776 u_int
res_nrandomid(res_state statp)777 res_nrandomid(res_state statp)
778 {
779 	struct timeval now;
780 	uint16_t u16;
781 	MD5_CTX ctx;
782 	u_char *rnd = statp->_rnd == NULL ? srnd : statp->_rnd;
783 
784 	gettimeofday(&now, NULL);
785 	u16 = (uint16_t) (now.tv_sec ^ now.tv_usec);
786 	memcpy(rnd + 14, &u16, 2);
787 #ifndef HAVE_MD5
788 	MD5_Init(&ctx);
789 	MD5_Update(&ctx, rnd, 16);
790 	MD5_Final(rnd, &ctx);
791 #else
792 	MD5Init(&ctx);
793 	MD5Update(&ctx, rnd, 16);
794 	MD5Final(rnd, &ctx);
795 #endif
796 	memcpy(&u16, rnd + 14, 2);
797 	return ((u_int) u16);
798 }
799 
800 /*%
801  * This routine is for closing the socket if a virtual circuit is used and
802  * the program wants to close it.  This provides support for endhostent()
803  * which expects to close the socket.
804  *
805  * This routine is not expected to be user visible.
806  */
807 void
res_nclose(res_state statp)808 res_nclose(res_state statp)
809 {
810 	int ns;
811 
812 	if (statp->_vcsock >= 0) {
813 		(void) close(statp->_vcsock);
814 		statp->_vcsock = -1;
815 		statp->_flags &= ~(RES_F_VC | RES_F_CONN);
816 	}
817 	for (ns = 0; ns < statp->_u._ext.nscount; ns++) {
818 		if (statp->_u._ext.nssocks[ns] != -1) {
819 			(void) close(statp->_u._ext.nssocks[ns]);
820 			statp->_u._ext.nssocks[ns] = -1;
821 		}
822 	}
823 }
824 
825 void
res_ndestroy(res_state statp)826 res_ndestroy(res_state statp)
827 {
828 	struct __res_state_ext *ext = statp->_u._ext.ext;
829 	res_nclose(statp);
830 	if (ext != NULL) {
831 		if (ext->kq != -1 && ext->kqpid == getpid())
832 			(void)close(ext->kq);
833 		if (ext->resfd != -1)
834 			(void)close(ext->resfd);
835 		free(ext);
836 		statp->_u._ext.ext = NULL;
837 	}
838 	if (statp->_rnd != NULL) {
839 		free(statp->_rnd);
840 		statp->_rnd = NULL;
841 	}
842 	statp->options &= ~RES_INIT;
843 }
844 
845 const char *
res_get_nibblesuffix(res_state statp)846 res_get_nibblesuffix(res_state statp)
847 {
848 	if (statp->_u._ext.ext)
849 		return (statp->_u._ext.ext->nsuffix);
850 	return ("ip6.arpa");
851 }
852 
853 const char *
res_get_nibblesuffix2(res_state statp)854 res_get_nibblesuffix2(res_state statp)
855 {
856 	if (statp->_u._ext.ext)
857 		return (statp->_u._ext.ext->nsuffix2);
858 	return ("ip6.int");
859 }
860 
861 void
res_setservers(res_state statp,const union res_sockaddr_union * set,int cnt)862 res_setservers(res_state statp, const union res_sockaddr_union *set, int cnt)
863 {
864 	int i, nserv;
865 	size_t size;
866 
867 	/* close open servers */
868 	res_nclose(statp);
869 
870 	/* cause rtt times to be forgotten */
871 	statp->_u._ext.nscount = 0;
872 
873 	nserv = 0;
874 	for (i = 0; i < cnt && nserv < MAXNS; i++) {
875 		switch (set->sin.sin_family) {
876 		case AF_INET:
877 			size = sizeof(set->sin);
878 			if (statp->_u._ext.ext)
879 				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
880 					&set->sin, size);
881 			if (size <= sizeof(statp->nsaddr_list[nserv]))
882 				memcpy(&statp->nsaddr_list[nserv],
883 					&set->sin, size);
884 			else
885 				statp->nsaddr_list[nserv].sin_family = 0;
886 			nserv++;
887 			break;
888 
889 #ifdef HAS_INET6_STRUCTS
890 		case AF_INET6:
891 			size = sizeof(set->sin6);
892 			if (statp->_u._ext.ext)
893 				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
894 					&set->sin6, size);
895 			if (size <= sizeof(statp->nsaddr_list[nserv]))
896 				memcpy(&statp->nsaddr_list[nserv],
897 					&set->sin6, size);
898 			else
899 				statp->nsaddr_list[nserv].sin_family = 0;
900 			nserv++;
901 			break;
902 #endif
903 
904 		default:
905 			break;
906 		}
907 		set++;
908 	}
909 	statp->nscount = nserv;
910 
911 }
912 
913 int
res_getservers(res_state statp,union res_sockaddr_union * set,int cnt)914 res_getservers(res_state statp, union res_sockaddr_union *set, int cnt)
915 {
916 	int i;
917 	size_t size;
918 	uint16_t family;
919 
920 	for (i = 0; i < statp->nscount && i < cnt; i++) {
921 		if (statp->_u._ext.ext)
922 			family = statp->_u._ext.ext->nsaddrs[i].sin.sin_family;
923 		else
924 			family = statp->nsaddr_list[i].sin_family;
925 
926 		switch (family) {
927 		case AF_INET:
928 			size = sizeof(set->sin);
929 			if (statp->_u._ext.ext)
930 				memcpy(&set->sin,
931 				       &statp->_u._ext.ext->nsaddrs[i],
932 				       size);
933 			else
934 				memcpy(&set->sin, &statp->nsaddr_list[i],
935 				       size);
936 			break;
937 
938 #ifdef HAS_INET6_STRUCTS
939 		case AF_INET6:
940 			size = sizeof(set->sin6);
941 			if (statp->_u._ext.ext)
942 				memcpy(&set->sin6,
943 				       &statp->_u._ext.ext->nsaddrs[i],
944 				       size);
945 			else
946 				memcpy(&set->sin6, &statp->nsaddr_list[i],
947 				       size);
948 			break;
949 #endif
950 
951 		default:
952 			set->sin.sin_family = 0;
953 			break;
954 		}
955 		set++;
956 	}
957 	return (statp->nscount);
958 }
959 
960 /*! \file */
961