xref: /netbsd-src/lib/libc/resolv/res_init.c (revision 76c7fc5f6b13ed0b1508e6b313e88e59977ed78e)
1 /*	$NetBSD: res_init.c,v 1.31 2017/04/19 22:21:07 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.31 2017/04/19 22:21:07 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
189 res_ninit(res_state statp) {
190 	return (__res_vinit(statp, 0));
191 }
192 
193 /*% This function has to be reachable by res_data.c but not publically. */
194 int
195 __res_vinit(res_state statp, int preinit) {
196 	register FILE *fp;
197 	register char *cp, **pp;
198 	register int n;
199 	char buf[BUFSIZ];
200 	int nserv = 0;    /*%< number of nameserver records read from file */
201 	int haveenv = 0;
202 	int havesearch = 0;
203 #ifdef RESOLVSORT
204 	int nsort = 0;
205 	char *net;
206 #endif
207 	int dots;
208 	union res_sockaddr_union u[2];
209 	int maxns = MAXNS;
210 
211 	RES_SET_H_ERRNO(statp, 0);
212 
213 	if ((statp->options & RES_INIT) != 0U)
214 		res_ndestroy(statp);
215 
216 	if (!preinit) {
217 		statp->retrans = RES_TIMEOUT;
218 		statp->retry = RES_DFLRETRY;
219 		statp->options = RES_DEFAULT;
220 	}
221 	statp->_rnd = malloc(16);
222 	res_rndinit(statp);
223 	statp->id = res_nrandomid(statp);
224 
225 	memset(u, 0, sizeof(u));
226 #ifdef USELOOPBACK
227 	u[nserv].sin.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
228 #else
229 	u[nserv].sin.sin_addr.s_addr = INADDR_ANY;
230 #endif
231 	u[nserv].sin.sin_family = AF_INET;
232 	u[nserv].sin.sin_port = htons(NAMESERVER_PORT);
233 #ifdef HAVE_SA_LEN
234 	u[nserv].sin.sin_len = sizeof(struct sockaddr_in);
235 #endif
236 	nserv++;
237 #ifdef HAS_INET6_STRUCTS
238 #ifdef USELOOPBACK
239 	u[nserv].sin6.sin6_addr = in6addr_loopback;
240 #else
241 	u[nserv].sin6.sin6_addr = in6addr_any;
242 #endif
243 	u[nserv].sin6.sin6_family = AF_INET6;
244 	u[nserv].sin6.sin6_port = htons(NAMESERVER_PORT);
245 #ifdef HAVE_SA_LEN
246 	u[nserv].sin6.sin6_len = sizeof(struct sockaddr_in6);
247 #endif
248 	nserv++;
249 #endif
250 	statp->nscount = 0;
251 	statp->ndots = 1;
252 	statp->pfcode = 0;
253 	statp->_vcsock = -1;
254 	statp->_flags = 0;
255 	statp->qhook = NULL;
256 	statp->rhook = NULL;
257 	statp->_u._ext.nscount = 0;
258 	statp->_u._ext.ext = malloc(sizeof(*statp->_u._ext.ext));
259 	if (statp->_u._ext.ext != NULL) {
260 	        memset(statp->_u._ext.ext, 0, sizeof(*statp->_u._ext.ext));
261 		statp->_u._ext.ext->nsaddrs[0].sin = statp->nsaddr;
262 		strcpy(statp->_u._ext.ext->nsuffix, "ip6.arpa");
263 		strcpy(statp->_u._ext.ext->nsuffix2, "ip6.int");
264 	} else {
265 		/*
266 		 * Historically res_init() rarely, if at all, failed.
267 		 * Examples and applications exist which do not check
268 		 * our return code.  Furthermore several applications
269 		 * simply call us to get the systems domainname.  So
270 		 * rather than immediately fail here we store the
271 		 * failure, which is returned later, in h_errno.  And
272 		 * prevent the collection of 'nameserver' information
273 		 * by setting maxns to 0.  Thus applications that fail
274 		 * to check our return code wont be able to make
275 		 * queries anyhow.
276 		 */
277 		RES_SET_H_ERRNO(statp, NETDB_INTERNAL);
278 		maxns = 0;
279 	}
280 #ifdef RESOLVSORT
281 	statp->nsort = 0;
282 #endif
283 	res_setservers(statp, u, nserv);
284 
285 #ifdef	SOLARIS2
286 	/*
287 	 * The old libresolv derived the defaultdomain from NIS/NIS+.
288 	 * We want to keep this behaviour
289 	 */
290 	{
291 		char buf[sizeof(statp->defdname)], *cp;
292 		int ret;
293 
294 		if ((ret = sysinfo(SI_SRPC_DOMAIN, buf, sizeof(buf))) > 0 &&
295 			(unsigned int)ret <= sizeof(buf)) {
296 			if (buf[0] == '+')
297 				buf[0] = '.';
298 			cp = strchr(buf, '.');
299 			cp = (cp == NULL) ? buf : (cp + 1);
300 			(void)strlcpy(statp->defdname, cp,
301 			    sizeof(statp->defdname));
302 		}
303 	}
304 #endif	/* SOLARIS2 */
305 
306 	/* Allow user to override the local domain definition */
307 	if ((cp = getenv("LOCALDOMAIN")) != NULL) {
308 		(void)strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
309 		statp->defdname[sizeof(statp->defdname) - 1] = '\0';
310 		haveenv++;
311 
312 		/*
313 		 * Set search list to be blank-separated strings
314 		 * from rest of env value.  Permits users of LOCALDOMAIN
315 		 * to still have a search list, and anyone to set the
316 		 * one that they want to use as an individual (even more
317 		 * important now that the rfc1535 stuff restricts searches)
318 		 */
319 		cp = statp->defdname;
320 		pp = statp->dnsrch;
321 		*pp++ = cp;
322 		for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
323 			if (*cp == '\n')	/*%< silly backwards compat */
324 				break;
325 			else if (*cp == ' ' || *cp == '\t') {
326 				*cp = 0;
327 				n = 1;
328 			} else if (n) {
329 				*pp++ = cp;
330 				n = 0;
331 				havesearch = 1;
332 			}
333 		}
334 		/* null terminate last domain if there are excess */
335 		while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
336 			cp++;
337 		*cp = '\0';
338 		*pp++ = 0;
339 	}
340 
341 #define	MATCH(line, name) \
342 	(!strncmp(line, name, sizeof(name) - 1) && \
343 	(line[sizeof(name) - 1] == ' ' || \
344 	 line[sizeof(name) - 1] == '\t'))
345 
346 	nserv = 0;
347 	if ((fp = fopen(__res_conf_name, "re")) != NULL) {
348 	    struct stat st;
349 	    struct kevent kc;
350 
351 	    /* read the config file */
352 	    while (fgets(buf, (int)sizeof(buf), fp) != NULL) {
353 		/* skip comments */
354 		if (*buf == ';' || *buf == '#')
355 			continue;
356 		/* read default domain name */
357 		if (MATCH(buf, "domain")) {
358 		    if (haveenv)	/*%< skip if have from environ */
359 			    continue;
360 		    cp = buf + sizeof("domain") - 1;
361 		    while (*cp == ' ' || *cp == '\t')
362 			    cp++;
363 		    if ((*cp == '\0') || (*cp == '\n'))
364 			    continue;
365 		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
366 		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
367 		    if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL)
368 			    *cp = '\0';
369 		    havesearch = 0;
370 		    continue;
371 		}
372 		/* set search list */
373 		if (MATCH(buf, "search")) {
374 		    if (haveenv)	/*%< skip if have from environ */
375 			    continue;
376 		    cp = buf + sizeof("search") - 1;
377 		    while (*cp == ' ' || *cp == '\t')
378 			    cp++;
379 		    if ((*cp == '\0') || (*cp == '\n'))
380 			    continue;
381 		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
382 		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
383 		    if ((cp = strchr(statp->defdname, '\n')) != NULL)
384 			    *cp = '\0';
385 		    /*
386 		     * Set search list to be blank-separated strings
387 		     * on rest of line.
388 		     */
389 		    cp = statp->defdname;
390 		    pp = statp->dnsrch;
391 		    *pp++ = cp;
392 		    for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
393 			    if (*cp == ' ' || *cp == '\t') {
394 				    *cp = 0;
395 				    n = 1;
396 			    } else if (n) {
397 				    *pp++ = cp;
398 				    n = 0;
399 			    }
400 		    }
401 		    /* null terminate last domain if there are excess */
402 		    while (*cp != '\0' && *cp != ' ' && *cp != '\t')
403 			    cp++;
404 		    *cp = '\0';
405 		    *pp++ = 0;
406 		    havesearch = 1;
407 		    continue;
408 		}
409 		/* read nameservers to query */
410 		if (MATCH(buf, "nameserver") && nserv < maxns) {
411 		    struct addrinfo hints, *ai;
412 		    char sbuf[NI_MAXSERV];
413 		    const size_t minsiz =
414 		        sizeof(statp->_u._ext.ext->nsaddrs[0]);
415 
416 		    cp = buf + sizeof("nameserver") - 1;
417 		    while (*cp == ' ' || *cp == '\t')
418 			cp++;
419 		    cp[strcspn(cp, ";# \t\n")] = '\0';
420 		    if ((*cp != '\0') && (*cp != '\n')) {
421 			memset(&hints, 0, sizeof(hints));
422 			hints.ai_family = PF_UNSPEC;
423 			hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
424 			hints.ai_flags = AI_NUMERICHOST;
425 			sprintf(sbuf, "%u", NAMESERVER_PORT);
426 			if (getaddrinfo(cp, sbuf, &hints, &ai) == 0 &&
427 			    ai->ai_addrlen <= minsiz) {
428 			    if (statp->_u._ext.ext != NULL) {
429 				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
430 				    ai->ai_addr, ai->ai_addrlen);
431 			    }
432 			    if (ai->ai_addrlen <=
433 			        sizeof(statp->nsaddr_list[nserv])) {
434 				memcpy(&statp->nsaddr_list[nserv],
435 				    ai->ai_addr, ai->ai_addrlen);
436 			    } else
437 				statp->nsaddr_list[nserv].sin_family = 0;
438 			    freeaddrinfo(ai);
439 			    nserv++;
440 			}
441 		    }
442 		    continue;
443 		}
444 #ifdef RESOLVSORT
445 		if (MATCH(buf, "sortlist")) {
446 		    struct in_addr a;
447 
448 		    cp = buf + sizeof("sortlist") - 1;
449 		    while (nsort < MAXRESOLVSORT) {
450 			while (*cp == ' ' || *cp == '\t')
451 			    cp++;
452 			if (*cp == '\0' || *cp == '\n' || *cp == ';')
453 			    break;
454 			net = cp;
455 			while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
456 			       isascii(*cp) && !isspace((unsigned char)*cp))
457 				cp++;
458 			n = *cp;
459 			*cp = 0;
460 			if (inet_aton(net, &a)) {
461 			    statp->sort_list[nsort].addr = a;
462 			    if (ISSORTMASK(n)) {
463 				*cp++ = n;
464 				net = cp;
465 				while (*cp && *cp != ';' &&
466 					isascii(*cp) &&
467 					!isspace((unsigned char)*cp))
468 				    cp++;
469 				n = *cp;
470 				*cp = 0;
471 				if (inet_aton(net, &a)) {
472 				    statp->sort_list[nsort].mask = a.s_addr;
473 				} else {
474 				    statp->sort_list[nsort].mask =
475 					net_mask(statp->sort_list[nsort].addr);
476 				}
477 			    } else {
478 				statp->sort_list[nsort].mask =
479 				    net_mask(statp->sort_list[nsort].addr);
480 			    }
481 			    nsort++;
482 			}
483 			*cp = n;
484 		    }
485 		    continue;
486 		}
487 #endif
488 		if (MATCH(buf, "options")) {
489 		    res_setoptions(statp, buf + sizeof("options") - 1, "conf");
490 		    continue;
491 		}
492 	    }
493 	    if (nserv > 0)
494 		statp->nscount = nserv;
495 #ifdef RESOLVSORT
496 	    statp->nsort = nsort;
497 #endif
498 	    statp->_u._ext.ext->resfd = fcntl(fileno(fp), F_DUPFD_CLOEXEC, 0);
499 	    (void) fclose(fp);
500 	    if (fstat(statp->_u._ext.ext->resfd, &st) != -1)
501 		    __res_conf_time = statp->_u._ext.ext->res_conf_time =
502 			st.st_mtimespec;
503 	    statp->_u._ext.ext->kq = kqueue1(O_CLOEXEC);
504 	    EV_SET(&kc, statp->_u._ext.ext->resfd, EVFILT_VNODE,
505 		EV_ADD|EV_ENABLE|EV_CLEAR, NOTE_DELETE|NOTE_WRITE| NOTE_EXTEND|
506 		NOTE_ATTRIB|NOTE_LINK|NOTE_RENAME|NOTE_REVOKE, 0, 0);
507 	    (void)kevent(statp->_u._ext.ext->kq, &kc, 1, NULL, 0, &ts);
508 	} else {
509 	    statp->_u._ext.ext->kq = -1;
510 	    statp->_u._ext.ext->resfd = -1;
511 	}
512 /*
513  * Last chance to get a nameserver.  This should not normally
514  * be necessary
515  */
516 #ifdef NO_RESOLV_CONF
517 	if(nserv == 0)
518 		nserv = get_nameservers(statp);
519 #endif
520 
521 	if (statp->defdname[0] == 0 &&
522 	    gethostname(buf, sizeof(statp->defdname) - 1) == 0 &&
523 	    (cp = strchr(buf, '.')) != NULL)
524 		strcpy(statp->defdname, cp + 1);
525 
526 	/* find components of local domain that might be searched */
527 	if (havesearch == 0) {
528 		pp = statp->dnsrch;
529 		*pp++ = statp->defdname;
530 		*pp = NULL;
531 
532 		dots = 0;
533 		for (cp = statp->defdname; *cp; cp++)
534 			dots += (*cp == '.');
535 
536 		cp = statp->defdname;
537 		while (pp < statp->dnsrch + MAXDFLSRCH) {
538 			if (dots < LOCALDOMAINPARTS)
539 				break;
540 			cp = strchr(cp, '.') + 1;    /*%< we know there is one */
541 			*pp++ = cp;
542 			dots--;
543 		}
544 		*pp = NULL;
545 #ifdef DEBUG
546 		if (statp->options & RES_DEBUG) {
547 			printf(";; res_init()... default dnsrch list:\n");
548 			for (pp = statp->dnsrch; *pp; pp++)
549 				printf(";;\t%s\n", *pp);
550 			printf(";;\t..END..\n");
551 		}
552 #endif
553 	}
554 
555 	if ((cp = getenv("RES_OPTIONS")) != NULL)
556 		res_setoptions(statp, cp, "env");
557 	statp->options |= RES_INIT;
558 	return (statp->res_h_errno);
559 }
560 
561 int
562 res_check(res_state statp, struct timespec *mtime)
563 {
564 	/*
565 	 * If the times are equal, then we check if there
566 	 * was a kevent related to resolv.conf and reload.
567 	 * If the times are not equal, then we don't bother
568 	 * to check the kevent, because another thread already
569 	 * did, loaded and changed the time.
570 	 */
571 	if (timespeccmp(&statp->_u._ext.ext->res_conf_time,
572 	    &__res_conf_time, ==)) {
573 		struct kevent ke;
574 		if (statp->_u._ext.ext->kq == -1)
575 			goto out;
576 
577 		switch (kevent(statp->_u._ext.ext->kq, NULL, 0, &ke, 1, &ts)) {
578 		case 0:
579 		case -1:
580 out:
581 			if (mtime)
582 				*mtime = __res_conf_time;
583 			return 0;
584 		default:
585 			break;
586 		}
587 	}
588 	(void)__res_vinit(statp, 0);
589 	if (mtime)
590 		*mtime = __res_conf_time;
591 	return 1;
592 }
593 
594 static void
595 res_setoptions(res_state statp, const char *options, const char *source)
596 {
597 	const char *cp = options;
598 	int i;
599 	size_t j;
600 	struct __res_state_ext *ext = statp->_u._ext.ext;
601 
602 #ifdef DEBUG
603 	if (statp->options & RES_DEBUG)
604 		printf(";; res_setoptions(\"%s\", \"%s\")...\n",
605 		       options, source);
606 #endif
607 	while (*cp) {
608 		/* skip leading and inner runs of spaces */
609 		while (*cp == ' ' || *cp == '\t')
610 			cp++;
611 		/* search for and process individual options */
612 		if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) {
613 			i = atoi(cp + sizeof("ndots:") - 1);
614 			if (i <= RES_MAXNDOTS)
615 				statp->ndots = i;
616 			else
617 				statp->ndots = RES_MAXNDOTS;
618 #ifdef DEBUG
619 			if (statp->options & RES_DEBUG)
620 				printf(";;\tndots=%d\n", statp->ndots);
621 #endif
622 		} else if (!strncmp(cp, "timeout:", sizeof("timeout:") - 1)) {
623 			i = atoi(cp + sizeof("timeout:") - 1);
624 			if (i <= RES_MAXRETRANS)
625 				statp->retrans = i;
626 			else
627 				statp->retrans = RES_MAXRETRANS;
628 #ifdef DEBUG
629 			if (statp->options & RES_DEBUG)
630 				printf(";;\ttimeout=%d\n", statp->retrans);
631 #endif
632 #ifdef	SOLARIS2
633 		} else if (!strncmp(cp, "retrans:", sizeof("retrans:") - 1)) {
634 			/*
635 		 	 * For backward compatibility, 'retrans' is
636 		 	 * supported as an alias for 'timeout', though
637 		 	 * without an imposed maximum.
638 		 	 */
639 			statp->retrans = atoi(cp + sizeof("retrans:") - 1);
640 		} else if (!strncmp(cp, "retry:", sizeof("retry:") - 1)){
641 			/*
642 			 * For backward compatibility, 'retry' is
643 			 * supported as an alias for 'attempts', though
644 			 * without an imposed maximum.
645 			 */
646 			statp->retry = atoi(cp + sizeof("retry:") - 1);
647 #endif	/* SOLARIS2 */
648 		} else if (!strncmp(cp, "attempts:", sizeof("attempts:") - 1)){
649 			i = atoi(cp + sizeof("attempts:") - 1);
650 			if (i <= RES_MAXRETRY)
651 				statp->retry = i;
652 			else
653 				statp->retry = RES_MAXRETRY;
654 #ifdef DEBUG
655 			if (statp->options & RES_DEBUG)
656 				printf(";;\tattempts=%d\n", statp->retry);
657 #endif
658 		} else if (!strncmp(cp, "debug", sizeof("debug") - 1)) {
659 #ifdef DEBUG
660 			if (!(statp->options & RES_DEBUG)) {
661 				printf(";; res_setoptions(\"%s\", \"%s\")..\n",
662 				       options, source);
663 				statp->options |= RES_DEBUG;
664 			}
665 			printf(";;\tdebug\n");
666 #endif
667 		} else if (!strncmp(cp, "no_tld_query",
668 				    sizeof("no_tld_query") - 1) ||
669 			   !strncmp(cp, "no-tld-query",
670 				    sizeof("no-tld-query") - 1)) {
671 			statp->options |= RES_NOTLDQUERY;
672 		} else if (!strncmp(cp, "inet6", sizeof("inet6") - 1)) {
673 			statp->options |= RES_USE_INET6;
674 		} else if (!strncmp(cp, "rotate", sizeof("rotate") - 1)) {
675 			statp->options |= RES_ROTATE;
676 		} else if (!strncmp(cp, "no-check-names",
677 				    sizeof("no-check-names") - 1)) {
678 			statp->options |= RES_NOCHECKNAME;
679 		} else if (!strncmp(cp, "check-names",
680 				    sizeof("check-names") - 1)) {
681 			statp->options &= ~RES_NOCHECKNAME;
682 		}
683 #ifdef RES_USE_EDNS0
684 		else if (!strncmp(cp, "edns0", sizeof("edns0") - 1)) {
685 			statp->options |= RES_USE_EDNS0;
686 		}
687 #endif
688 		else if (!strncmp(cp, "dname", sizeof("dname") - 1)) {
689 			statp->options |= RES_USE_DNAME;
690 		}
691 		else if (!strncmp(cp, "nibble:", sizeof("nibble:") - 1)) {
692 			if (ext == NULL)
693 				goto skip;
694 			cp += sizeof("nibble:") - 1;
695 			j = MIN(strcspn(cp, " \t"), sizeof(ext->nsuffix) - 1);
696 			strncpy(ext->nsuffix, cp, j);
697 			ext->nsuffix[j] = '\0';
698 		}
699 		else if (!strncmp(cp, "nibble2:", sizeof("nibble2:") - 1)) {
700 			if (ext == NULL)
701 				goto skip;
702 			cp += sizeof("nibble2:") - 1;
703 			j = MIN(strcspn(cp, " \t"), sizeof(ext->nsuffix2) - 1);
704 			strncpy(ext->nsuffix2, cp, j);
705 			ext->nsuffix2[j] = '\0';
706 		}
707 		else if (!strncmp(cp, "v6revmode:", sizeof("v6revmode:") - 1)) {
708 			cp += sizeof("v6revmode:") - 1;
709 			/* "nibble" and "bitstring" used to be valid */
710 			if (!strncmp(cp, "single", sizeof("single") - 1)) {
711 				statp->options |= RES_NO_NIBBLE2;
712 			} else if (!strncmp(cp, "both", sizeof("both") - 1)) {
713 				statp->options &=
714 					 ~RES_NO_NIBBLE2;
715 			}
716 		}
717 		else {
718 			/* XXX - print a warning here? */
719 		}
720    skip:
721 		/* skip to next run of spaces */
722 		while (*cp && *cp != ' ' && *cp != '\t')
723 			cp++;
724 	}
725 }
726 
727 #ifdef RESOLVSORT
728 /* XXX - should really support CIDR which means explicit masks always. */
729 static uint32_t
730 net_mask(struct in_addr in) /*!< XXX - should really use system's version of this  */
731 {
732 	register uint32_t i = ntohl(in.s_addr);
733 
734 	if (IN_CLASSA(i))
735 		return (htonl(IN_CLASSA_NET));
736 	else if (IN_CLASSB(i))
737 		return (htonl(IN_CLASSB_NET));
738 	return (htonl(IN_CLASSC_NET));
739 }
740 #endif
741 
742 static u_char srnd[16];
743 
744 void
745 res_rndinit(res_state statp)
746 {
747 	struct timeval now;
748 	uint32_t u32;
749 	uint16_t u16;
750 	u_char *rnd = statp->_rnd == NULL ? srnd : statp->_rnd;
751 
752 	gettimeofday(&now, NULL);
753 	u32 = (uint32_t)now.tv_sec;
754 	memcpy(rnd, &u32, 4);
755 	u32 = now.tv_usec;
756 	memcpy(rnd + 4, &u32, 4);
757 	u32 += (uint32_t)now.tv_sec;
758 	memcpy(rnd + 8, &u32, 4);
759 	u16 = getpid();
760 	memcpy(rnd + 12, &u16, 2);
761 }
762 
763 u_int
764 res_nrandomid(res_state statp)
765 {
766 	struct timeval now;
767 	uint16_t u16;
768 	MD5_CTX ctx;
769 	u_char *rnd = statp->_rnd == NULL ? srnd : statp->_rnd;
770 
771 	gettimeofday(&now, NULL);
772 	u16 = (uint16_t) (now.tv_sec ^ now.tv_usec);
773 	memcpy(rnd + 14, &u16, 2);
774 #ifndef HAVE_MD5
775 	MD5_Init(&ctx);
776 	MD5_Update(&ctx, rnd, 16);
777 	MD5_Final(rnd, &ctx);
778 #else
779 	MD5Init(&ctx);
780 	MD5Update(&ctx, rnd, 16);
781 	MD5Final(rnd, &ctx);
782 #endif
783 	memcpy(&u16, rnd + 14, 2);
784 	return ((u_int) u16);
785 }
786 
787 /*%
788  * This routine is for closing the socket if a virtual circuit is used and
789  * the program wants to close it.  This provides support for endhostent()
790  * which expects to close the socket.
791  *
792  * This routine is not expected to be user visible.
793  */
794 void
795 res_nclose(res_state statp)
796 {
797 	int ns;
798 
799 	if (statp->_vcsock >= 0) {
800 		(void) close(statp->_vcsock);
801 		statp->_vcsock = -1;
802 		statp->_flags &= ~(RES_F_VC | RES_F_CONN);
803 	}
804 	for (ns = 0; ns < statp->_u._ext.nscount; ns++) {
805 		if (statp->_u._ext.nssocks[ns] != -1) {
806 			(void) close(statp->_u._ext.nssocks[ns]);
807 			statp->_u._ext.nssocks[ns] = -1;
808 		}
809 	}
810 }
811 
812 void
813 res_ndestroy(res_state statp)
814 {
815 	res_nclose(statp);
816 	if (statp->_u._ext.ext != NULL) {
817 		if (statp->_u._ext.ext->kq != -1)
818 			(void)close(statp->_u._ext.ext->kq);
819 		if (statp->_u._ext.ext->resfd != -1)
820 			(void)close(statp->_u._ext.ext->resfd);
821 		free(statp->_u._ext.ext);
822 		statp->_u._ext.ext = NULL;
823 	}
824 	if (statp->_rnd != NULL) {
825 		free(statp->_rnd);
826 		statp->_rnd = NULL;
827 	}
828 	statp->options &= ~RES_INIT;
829 }
830 
831 const char *
832 res_get_nibblesuffix(res_state statp)
833 {
834 	if (statp->_u._ext.ext)
835 		return (statp->_u._ext.ext->nsuffix);
836 	return ("ip6.arpa");
837 }
838 
839 const char *
840 res_get_nibblesuffix2(res_state statp)
841 {
842 	if (statp->_u._ext.ext)
843 		return (statp->_u._ext.ext->nsuffix2);
844 	return ("ip6.int");
845 }
846 
847 void
848 res_setservers(res_state statp, const union res_sockaddr_union *set, int cnt)
849 {
850 	int i, nserv;
851 	size_t size;
852 
853 	/* close open servers */
854 	res_nclose(statp);
855 
856 	/* cause rtt times to be forgotten */
857 	statp->_u._ext.nscount = 0;
858 
859 	nserv = 0;
860 	for (i = 0; i < cnt && nserv < MAXNS; i++) {
861 		switch (set->sin.sin_family) {
862 		case AF_INET:
863 			size = sizeof(set->sin);
864 			if (statp->_u._ext.ext)
865 				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
866 					&set->sin, size);
867 			if (size <= sizeof(statp->nsaddr_list[nserv]))
868 				memcpy(&statp->nsaddr_list[nserv],
869 					&set->sin, size);
870 			else
871 				statp->nsaddr_list[nserv].sin_family = 0;
872 			nserv++;
873 			break;
874 
875 #ifdef HAS_INET6_STRUCTS
876 		case AF_INET6:
877 			size = sizeof(set->sin6);
878 			if (statp->_u._ext.ext)
879 				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
880 					&set->sin6, size);
881 			if (size <= sizeof(statp->nsaddr_list[nserv]))
882 				memcpy(&statp->nsaddr_list[nserv],
883 					&set->sin6, size);
884 			else
885 				statp->nsaddr_list[nserv].sin_family = 0;
886 			nserv++;
887 			break;
888 #endif
889 
890 		default:
891 			break;
892 		}
893 		set++;
894 	}
895 	statp->nscount = nserv;
896 
897 }
898 
899 int
900 res_getservers(res_state statp, union res_sockaddr_union *set, int cnt)
901 {
902 	int i;
903 	size_t size;
904 	uint16_t family;
905 
906 	for (i = 0; i < statp->nscount && i < cnt; i++) {
907 		if (statp->_u._ext.ext)
908 			family = statp->_u._ext.ext->nsaddrs[i].sin.sin_family;
909 		else
910 			family = statp->nsaddr_list[i].sin_family;
911 
912 		switch (family) {
913 		case AF_INET:
914 			size = sizeof(set->sin);
915 			if (statp->_u._ext.ext)
916 				memcpy(&set->sin,
917 				       &statp->_u._ext.ext->nsaddrs[i],
918 				       size);
919 			else
920 				memcpy(&set->sin, &statp->nsaddr_list[i],
921 				       size);
922 			break;
923 
924 #ifdef HAS_INET6_STRUCTS
925 		case AF_INET6:
926 			size = sizeof(set->sin6);
927 			if (statp->_u._ext.ext)
928 				memcpy(&set->sin6,
929 				       &statp->_u._ext.ext->nsaddrs[i],
930 				       size);
931 			else
932 				memcpy(&set->sin6, &statp->nsaddr_list[i],
933 				       size);
934 			break;
935 #endif
936 
937 		default:
938 			set->sin.sin_family = 0;
939 			break;
940 		}
941 		set++;
942 	}
943 	return (statp->nscount);
944 }
945 
946 /*! \file */
947