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