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