Home | History | Annotate | Line # | Download | only in resolv
res_init.c revision 1.29
      1 /*	$NetBSD: res_init.c,v 1.29 2014/09/16 01:29:48 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.29 2014/09/16 01:29:48 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 #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 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 	    struct kevent kc;
    354 
    355 	    /* read the config file */
    356 	    while (fgets(buf, (int)sizeof(buf), fp) != NULL) {
    357 		/* skip comments */
    358 		if (*buf == ';' || *buf == '#')
    359 			continue;
    360 		/* read default domain name */
    361 		if (MATCH(buf, "domain")) {
    362 		    if (haveenv)	/*%< skip if have from environ */
    363 			    continue;
    364 		    cp = buf + sizeof("domain") - 1;
    365 		    while (*cp == ' ' || *cp == '\t')
    366 			    cp++;
    367 		    if ((*cp == '\0') || (*cp == '\n'))
    368 			    continue;
    369 		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
    370 		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
    371 		    if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL)
    372 			    *cp = '\0';
    373 		    havesearch = 0;
    374 		    continue;
    375 		}
    376 		/* set search list */
    377 		if (MATCH(buf, "search")) {
    378 		    if (haveenv)	/*%< skip if have from environ */
    379 			    continue;
    380 		    cp = buf + sizeof("search") - 1;
    381 		    while (*cp == ' ' || *cp == '\t')
    382 			    cp++;
    383 		    if ((*cp == '\0') || (*cp == '\n'))
    384 			    continue;
    385 		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
    386 		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
    387 		    if ((cp = strchr(statp->defdname, '\n')) != NULL)
    388 			    *cp = '\0';
    389 		    /*
    390 		     * Set search list to be blank-separated strings
    391 		     * on rest of line.
    392 		     */
    393 		    cp = statp->defdname;
    394 		    pp = statp->dnsrch;
    395 		    *pp++ = cp;
    396 		    for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
    397 			    if (*cp == ' ' || *cp == '\t') {
    398 				    *cp = 0;
    399 				    n = 1;
    400 			    } else if (n) {
    401 				    *pp++ = cp;
    402 				    n = 0;
    403 			    }
    404 		    }
    405 		    /* null terminate last domain if there are excess */
    406 		    while (*cp != '\0' && *cp != ' ' && *cp != '\t')
    407 			    cp++;
    408 		    *cp = '\0';
    409 		    *pp++ = 0;
    410 		    havesearch = 1;
    411 		    continue;
    412 		}
    413 		/* read nameservers to query */
    414 		if (MATCH(buf, "nameserver") && nserv < maxns) {
    415 		    struct addrinfo hints, *ai;
    416 		    char sbuf[NI_MAXSERV];
    417 		    const size_t minsiz =
    418 		        sizeof(statp->_u._ext.ext->nsaddrs[0]);
    419 
    420 		    cp = buf + sizeof("nameserver") - 1;
    421 		    while (*cp == ' ' || *cp == '\t')
    422 			cp++;
    423 		    cp[strcspn(cp, ";# \t\n")] = '\0';
    424 		    if ((*cp != '\0') && (*cp != '\n')) {
    425 			memset(&hints, 0, sizeof(hints));
    426 			hints.ai_family = PF_UNSPEC;
    427 			hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
    428 			hints.ai_flags = AI_NUMERICHOST;
    429 			sprintf(sbuf, "%u", NAMESERVER_PORT);
    430 			if (getaddrinfo(cp, sbuf, &hints, &ai) == 0 &&
    431 			    ai->ai_addrlen <= minsiz) {
    432 			    if (statp->_u._ext.ext != NULL) {
    433 				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
    434 				    ai->ai_addr, ai->ai_addrlen);
    435 			    }
    436 			    if (ai->ai_addrlen <=
    437 			        sizeof(statp->nsaddr_list[nserv])) {
    438 				memcpy(&statp->nsaddr_list[nserv],
    439 				    ai->ai_addr, ai->ai_addrlen);
    440 			    } else
    441 				statp->nsaddr_list[nserv].sin_family = 0;
    442 			    freeaddrinfo(ai);
    443 			    nserv++;
    444 			}
    445 		    }
    446 		    continue;
    447 		}
    448 #ifdef RESOLVSORT
    449 		if (MATCH(buf, "sortlist")) {
    450 		    struct in_addr a;
    451 
    452 		    cp = buf + sizeof("sortlist") - 1;
    453 		    while (nsort < MAXRESOLVSORT) {
    454 			while (*cp == ' ' || *cp == '\t')
    455 			    cp++;
    456 			if (*cp == '\0' || *cp == '\n' || *cp == ';')
    457 			    break;
    458 			net = cp;
    459 			while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
    460 			       isascii(*cp) && !isspace((unsigned char)*cp))
    461 				cp++;
    462 			n = *cp;
    463 			*cp = 0;
    464 			if (inet_aton(net, &a)) {
    465 			    statp->sort_list[nsort].addr = a;
    466 			    if (ISSORTMASK(n)) {
    467 				*cp++ = n;
    468 				net = cp;
    469 				while (*cp && *cp != ';' &&
    470 					isascii(*cp) &&
    471 					!isspace((unsigned char)*cp))
    472 				    cp++;
    473 				n = *cp;
    474 				*cp = 0;
    475 				if (inet_aton(net, &a)) {
    476 				    statp->sort_list[nsort].mask = a.s_addr;
    477 				} else {
    478 				    statp->sort_list[nsort].mask =
    479 					net_mask(statp->sort_list[nsort].addr);
    480 				}
    481 			    } else {
    482 				statp->sort_list[nsort].mask =
    483 				    net_mask(statp->sort_list[nsort].addr);
    484 			    }
    485 			    nsort++;
    486 			}
    487 			*cp = n;
    488 		    }
    489 		    continue;
    490 		}
    491 #endif
    492 		if (MATCH(buf, "options")) {
    493 		    res_setoptions(statp, buf + sizeof("options") - 1, "conf");
    494 		    continue;
    495 		}
    496 	    }
    497 	    if (nserv > 0)
    498 		statp->nscount = nserv;
    499 #ifdef RESOLVSORT
    500 	    statp->nsort = nsort;
    501 #endif
    502 	    statp->_u._ext.ext->resfd = fcntl(fileno(fp), F_DUPFD_CLOEXEC);
    503 	    (void) fclose(fp);
    504 	    if (fstat(statp->_u._ext.ext->resfd, &st) != -1)
    505 		    __res_conf_time = statp->_u._ext.ext->res_conf_time =
    506 			st.st_mtimespec;
    507 	    statp->_u._ext.ext->kq = kqueue1(O_CLOEXEC);
    508 	    EV_SET(&kc, statp->_u._ext.ext->resfd, EVFILT_VNODE,
    509 		EV_ADD|EV_ENABLE|EV_CLEAR, NOTE_DELETE|NOTE_WRITE| NOTE_EXTEND|
    510 		NOTE_ATTRIB|NOTE_LINK|NOTE_RENAME|NOTE_REVOKE, 0, 0);
    511 	    (void)kevent(statp->_u._ext.ext->kq, &kc, 1, NULL, 0, &ts);
    512 	} else {
    513 	    statp->_u._ext.ext->kq = -1;
    514 	    statp->_u._ext.ext->resfd = -1;
    515 	}
    516 /*
    517  * Last chance to get a nameserver.  This should not normally
    518  * be necessary
    519  */
    520 #ifdef NO_RESOLV_CONF
    521 	if(nserv == 0)
    522 		nserv = get_nameservers(statp);
    523 #endif
    524 
    525 	if (statp->defdname[0] == 0 &&
    526 	    gethostname(buf, sizeof(statp->defdname) - 1) == 0 &&
    527 	    (cp = strchr(buf, '.')) != NULL)
    528 		strcpy(statp->defdname, cp + 1);
    529 
    530 	/* find components of local domain that might be searched */
    531 	if (havesearch == 0) {
    532 		pp = statp->dnsrch;
    533 		*pp++ = statp->defdname;
    534 		*pp = NULL;
    535 
    536 		dots = 0;
    537 		for (cp = statp->defdname; *cp; cp++)
    538 			dots += (*cp == '.');
    539 
    540 		cp = statp->defdname;
    541 		while (pp < statp->dnsrch + MAXDFLSRCH) {
    542 			if (dots < LOCALDOMAINPARTS)
    543 				break;
    544 			cp = strchr(cp, '.') + 1;    /*%< we know there is one */
    545 			*pp++ = cp;
    546 			dots--;
    547 		}
    548 		*pp = NULL;
    549 #ifdef DEBUG
    550 		if (statp->options & RES_DEBUG) {
    551 			printf(";; res_init()... default dnsrch list:\n");
    552 			for (pp = statp->dnsrch; *pp; pp++)
    553 				printf(";;\t%s\n", *pp);
    554 			printf(";;\t..END..\n");
    555 		}
    556 #endif
    557 	}
    558 
    559 	if ((cp = getenv("RES_OPTIONS")) != NULL)
    560 		res_setoptions(statp, cp, "env");
    561 	statp->options |= RES_INIT;
    562 	return (statp->res_h_errno);
    563 }
    564 
    565 int
    566 res_check(res_state statp, struct timespec *mtime)
    567 {
    568 	/*
    569 	 * If the times are equal, then we check if there
    570 	 * was a kevent related to resolv.conf and reload.
    571 	 * If the times are not equal, then we don't bother
    572 	 * to check the kevent, because another thread already
    573 	 * did, loaded and changed the time.
    574 	 */
    575 	if (timespeccmp(&statp->_u._ext.ext->res_conf_time,
    576 	    &__res_conf_time, ==)) {
    577 		struct kevent ke;
    578 		if (statp->_u._ext.ext->kq == -1)
    579 			goto out;
    580 
    581 		switch (kevent(statp->_u._ext.ext->kq, NULL, 0, &ke, 1, &ts)) {
    582 		case 0:
    583 		case -1:
    584 out:
    585 			if (mtime)
    586 				*mtime = __res_conf_time;
    587 			return 0;
    588 		default:
    589 			break;
    590 		}
    591 	}
    592 	(void)__res_vinit(statp, 0);
    593 	if (mtime)
    594 		*mtime = __res_conf_time;
    595 	return 1;
    596 }
    597 
    598 static void
    599 res_setoptions(res_state statp, const char *options, const char *source)
    600 {
    601 	const char *cp = options;
    602 	int i;
    603 	size_t j;
    604 	struct __res_state_ext *ext = statp->_u._ext.ext;
    605 
    606 #ifdef DEBUG
    607 	if (statp->options & RES_DEBUG)
    608 		printf(";; res_setoptions(\"%s\", \"%s\")...\n",
    609 		       options, source);
    610 #endif
    611 	while (*cp) {
    612 		/* skip leading and inner runs of spaces */
    613 		while (*cp == ' ' || *cp == '\t')
    614 			cp++;
    615 		/* search for and process individual options */
    616 		if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) {
    617 			i = atoi(cp + sizeof("ndots:") - 1);
    618 			if (i <= RES_MAXNDOTS)
    619 				statp->ndots = i;
    620 			else
    621 				statp->ndots = RES_MAXNDOTS;
    622 #ifdef DEBUG
    623 			if (statp->options & RES_DEBUG)
    624 				printf(";;\tndots=%d\n", statp->ndots);
    625 #endif
    626 		} else if (!strncmp(cp, "timeout:", sizeof("timeout:") - 1)) {
    627 			i = atoi(cp + sizeof("timeout:") - 1);
    628 			if (i <= RES_MAXRETRANS)
    629 				statp->retrans = i;
    630 			else
    631 				statp->retrans = RES_MAXRETRANS;
    632 #ifdef DEBUG
    633 			if (statp->options & RES_DEBUG)
    634 				printf(";;\ttimeout=%d\n", statp->retrans);
    635 #endif
    636 #ifdef	SOLARIS2
    637 		} else if (!strncmp(cp, "retrans:", sizeof("retrans:") - 1)) {
    638 			/*
    639 		 	 * For backward compatibility, 'retrans' is
    640 		 	 * supported as an alias for 'timeout', though
    641 		 	 * without an imposed maximum.
    642 		 	 */
    643 			statp->retrans = atoi(cp + sizeof("retrans:") - 1);
    644 		} else if (!strncmp(cp, "retry:", sizeof("retry:") - 1)){
    645 			/*
    646 			 * For backward compatibility, 'retry' is
    647 			 * supported as an alias for 'attempts', though
    648 			 * without an imposed maximum.
    649 			 */
    650 			statp->retry = atoi(cp + sizeof("retry:") - 1);
    651 #endif	/* SOLARIS2 */
    652 		} else if (!strncmp(cp, "attempts:", sizeof("attempts:") - 1)){
    653 			i = atoi(cp + sizeof("attempts:") - 1);
    654 			if (i <= RES_MAXRETRY)
    655 				statp->retry = i;
    656 			else
    657 				statp->retry = RES_MAXRETRY;
    658 #ifdef DEBUG
    659 			if (statp->options & RES_DEBUG)
    660 				printf(";;\tattempts=%d\n", statp->retry);
    661 #endif
    662 		} else if (!strncmp(cp, "debug", sizeof("debug") - 1)) {
    663 #ifdef DEBUG
    664 			if (!(statp->options & RES_DEBUG)) {
    665 				printf(";; res_setoptions(\"%s\", \"%s\")..\n",
    666 				       options, source);
    667 				statp->options |= RES_DEBUG;
    668 			}
    669 			printf(";;\tdebug\n");
    670 #endif
    671 		} else if (!strncmp(cp, "no_tld_query",
    672 				    sizeof("no_tld_query") - 1) ||
    673 			   !strncmp(cp, "no-tld-query",
    674 				    sizeof("no-tld-query") - 1)) {
    675 			statp->options |= RES_NOTLDQUERY;
    676 		} else if (!strncmp(cp, "inet6", sizeof("inet6") - 1)) {
    677 			statp->options |= RES_USE_INET6;
    678 		} else if (!strncmp(cp, "rotate", sizeof("rotate") - 1)) {
    679 			statp->options |= RES_ROTATE;
    680 		} else if (!strncmp(cp, "no-check-names",
    681 				    sizeof("no-check-names") - 1)) {
    682 			statp->options |= RES_NOCHECKNAME;
    683 		} else if (!strncmp(cp, "check-names",
    684 				    sizeof("check-names") - 1)) {
    685 			statp->options &= ~RES_NOCHECKNAME;
    686 		}
    687 #ifdef RES_USE_EDNS0
    688 		else if (!strncmp(cp, "edns0", sizeof("edns0") - 1)) {
    689 			statp->options |= RES_USE_EDNS0;
    690 		}
    691 #endif
    692 		else if (!strncmp(cp, "dname", sizeof("dname") - 1)) {
    693 			statp->options |= RES_USE_DNAME;
    694 		}
    695 		else if (!strncmp(cp, "nibble:", sizeof("nibble:") - 1)) {
    696 			if (ext == NULL)
    697 				goto skip;
    698 			cp += sizeof("nibble:") - 1;
    699 			j = MIN(strcspn(cp, " \t"), sizeof(ext->nsuffix) - 1);
    700 			strncpy(ext->nsuffix, cp, j);
    701 			ext->nsuffix[j] = '\0';
    702 		}
    703 		else if (!strncmp(cp, "nibble2:", sizeof("nibble2:") - 1)) {
    704 			if (ext == NULL)
    705 				goto skip;
    706 			cp += sizeof("nibble2:") - 1;
    707 			j = MIN(strcspn(cp, " \t"), sizeof(ext->nsuffix2) - 1);
    708 			strncpy(ext->nsuffix2, cp, j);
    709 			ext->nsuffix2[j] = '\0';
    710 		}
    711 		else if (!strncmp(cp, "v6revmode:", sizeof("v6revmode:") - 1)) {
    712 			cp += sizeof("v6revmode:") - 1;
    713 			/* "nibble" and "bitstring" used to be valid */
    714 			if (!strncmp(cp, "single", sizeof("single") - 1)) {
    715 				statp->options |= RES_NO_NIBBLE2;
    716 			} else if (!strncmp(cp, "both", sizeof("both") - 1)) {
    717 				statp->options &=
    718 					 ~RES_NO_NIBBLE2;
    719 			}
    720 		}
    721 		else {
    722 			/* XXX - print a warning here? */
    723 		}
    724    skip:
    725 		/* skip to next run of spaces */
    726 		while (*cp && *cp != ' ' && *cp != '\t')
    727 			cp++;
    728 	}
    729 }
    730 
    731 #ifdef RESOLVSORT
    732 /* XXX - should really support CIDR which means explicit masks always. */
    733 static uint32_t
    734 net_mask(struct in_addr in) /*!< XXX - should really use system's version of this  */
    735 {
    736 	register uint32_t i = ntohl(in.s_addr);
    737 
    738 	if (IN_CLASSA(i))
    739 		return (htonl(IN_CLASSA_NET));
    740 	else if (IN_CLASSB(i))
    741 		return (htonl(IN_CLASSB_NET));
    742 	return (htonl(IN_CLASSC_NET));
    743 }
    744 #endif
    745 
    746 static u_char srnd[16];
    747 
    748 void
    749 res_rndinit(res_state statp)
    750 {
    751 	struct timeval now;
    752 	uint32_t u32;
    753 	uint16_t u16;
    754 	u_char *rnd = statp->_rnd == NULL ? srnd : statp->_rnd;
    755 
    756 	gettimeofday(&now, NULL);
    757 	u32 = (uint32_t)now.tv_sec;
    758 	memcpy(rnd, &u32, 4);
    759 	u32 = now.tv_usec;
    760 	memcpy(rnd + 4, &u32, 4);
    761 	u32 += (uint32_t)now.tv_sec;
    762 	memcpy(rnd + 8, &u32, 4);
    763 	u16 = getpid();
    764 	memcpy(rnd + 12, &u16, 2);
    765 }
    766 
    767 u_int
    768 res_nrandomid(res_state statp)
    769 {
    770 	struct timeval now;
    771 	uint16_t u16;
    772 	MD5_CTX ctx;
    773 	u_char *rnd = statp->_rnd == NULL ? srnd : statp->_rnd;
    774 
    775 	gettimeofday(&now, NULL);
    776 	u16 = (uint16_t) (now.tv_sec ^ now.tv_usec);
    777 	memcpy(rnd + 14, &u16, 2);
    778 #ifndef HAVE_MD5
    779 	MD5_Init(&ctx);
    780 	MD5_Update(&ctx, rnd, 16);
    781 	MD5_Final(rnd, &ctx);
    782 #else
    783 	MD5Init(&ctx);
    784 	MD5Update(&ctx, rnd, 16);
    785 	MD5Final(rnd, &ctx);
    786 #endif
    787 	memcpy(&u16, rnd + 14, 2);
    788 	return ((u_int) u16);
    789 }
    790 
    791 /*%
    792  * This routine is for closing the socket if a virtual circuit is used and
    793  * the program wants to close it.  This provides support for endhostent()
    794  * which expects to close the socket.
    795  *
    796  * This routine is not expected to be user visible.
    797  */
    798 void
    799 res_nclose(res_state statp)
    800 {
    801 	int ns;
    802 
    803 	if (statp->_vcsock >= 0) {
    804 		(void) close(statp->_vcsock);
    805 		statp->_vcsock = -1;
    806 		statp->_flags &= ~(RES_F_VC | RES_F_CONN);
    807 	}
    808 	for (ns = 0; ns < statp->_u._ext.nscount; ns++) {
    809 		if (statp->_u._ext.nssocks[ns] != -1) {
    810 			(void) close(statp->_u._ext.nssocks[ns]);
    811 			statp->_u._ext.nssocks[ns] = -1;
    812 		}
    813 	}
    814 }
    815 
    816 void
    817 res_ndestroy(res_state statp)
    818 {
    819 	res_nclose(statp);
    820 	if (statp->_u._ext.ext != NULL) {
    821 		if (statp->_u._ext.ext->kq != -1)
    822 			(void)close(statp->_u._ext.ext->kq);
    823 		if (statp->_u._ext.ext->resfd != -1)
    824 			(void)close(statp->_u._ext.ext->resfd);
    825 		free(statp->_u._ext.ext);
    826 		statp->_u._ext.ext = NULL;
    827 	}
    828 	if (statp->_rnd != NULL) {
    829 		free(statp->_rnd);
    830 		statp->_rnd = NULL;
    831 	}
    832 	statp->options &= ~RES_INIT;
    833 }
    834 
    835 const char *
    836 res_get_nibblesuffix(res_state statp)
    837 {
    838 	if (statp->_u._ext.ext)
    839 		return (statp->_u._ext.ext->nsuffix);
    840 	return ("ip6.arpa");
    841 }
    842 
    843 const char *
    844 res_get_nibblesuffix2(res_state statp)
    845 {
    846 	if (statp->_u._ext.ext)
    847 		return (statp->_u._ext.ext->nsuffix2);
    848 	return ("ip6.int");
    849 }
    850 
    851 void
    852 res_setservers(res_state statp, const union res_sockaddr_union *set, int cnt)
    853 {
    854 	int i, nserv;
    855 	size_t size;
    856 
    857 	/* close open servers */
    858 	res_nclose(statp);
    859 
    860 	/* cause rtt times to be forgotten */
    861 	statp->_u._ext.nscount = 0;
    862 
    863 	nserv = 0;
    864 	for (i = 0; i < cnt && nserv < MAXNS; i++) {
    865 		switch (set->sin.sin_family) {
    866 		case AF_INET:
    867 			size = sizeof(set->sin);
    868 			if (statp->_u._ext.ext)
    869 				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
    870 					&set->sin, size);
    871 			if (size <= sizeof(statp->nsaddr_list[nserv]))
    872 				memcpy(&statp->nsaddr_list[nserv],
    873 					&set->sin, size);
    874 			else
    875 				statp->nsaddr_list[nserv].sin_family = 0;
    876 			nserv++;
    877 			break;
    878 
    879 #ifdef HAS_INET6_STRUCTS
    880 		case AF_INET6:
    881 			size = sizeof(set->sin6);
    882 			if (statp->_u._ext.ext)
    883 				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
    884 					&set->sin6, size);
    885 			if (size <= sizeof(statp->nsaddr_list[nserv]))
    886 				memcpy(&statp->nsaddr_list[nserv],
    887 					&set->sin6, size);
    888 			else
    889 				statp->nsaddr_list[nserv].sin_family = 0;
    890 			nserv++;
    891 			break;
    892 #endif
    893 
    894 		default:
    895 			break;
    896 		}
    897 		set++;
    898 	}
    899 	statp->nscount = nserv;
    900 
    901 }
    902 
    903 int
    904 res_getservers(res_state statp, union res_sockaddr_union *set, int cnt)
    905 {
    906 	int i;
    907 	size_t size;
    908 	uint16_t family;
    909 
    910 	for (i = 0; i < statp->nscount && i < cnt; i++) {
    911 		if (statp->_u._ext.ext)
    912 			family = statp->_u._ext.ext->nsaddrs[i].sin.sin_family;
    913 		else
    914 			family = statp->nsaddr_list[i].sin_family;
    915 
    916 		switch (family) {
    917 		case AF_INET:
    918 			size = sizeof(set->sin);
    919 			if (statp->_u._ext.ext)
    920 				memcpy(&set->sin,
    921 				       &statp->_u._ext.ext->nsaddrs[i],
    922 				       size);
    923 			else
    924 				memcpy(&set->sin, &statp->nsaddr_list[i],
    925 				       size);
    926 			break;
    927 
    928 #ifdef HAS_INET6_STRUCTS
    929 		case AF_INET6:
    930 			size = sizeof(set->sin6);
    931 			if (statp->_u._ext.ext)
    932 				memcpy(&set->sin6,
    933 				       &statp->_u._ext.ext->nsaddrs[i],
    934 				       size);
    935 			else
    936 				memcpy(&set->sin6, &statp->nsaddr_list[i],
    937 				       size);
    938 			break;
    939 #endif
    940 
    941 		default:
    942 			set->sin.sin_family = 0;
    943 			break;
    944 		}
    945 		set++;
    946 	}
    947 	return (statp->nscount);
    948 }
    949 
    950 /*! \file */
    951