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