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