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