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