xref: /titanic_52/usr/src/lib/libresolv2/common/resolv/res_init.c (revision fd845fc0cb4fbc8e85f974e2e4eaacca1cc26e81)
1 /*
2  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 
6 /*
7  * Copyright (c) 1985, 1989, 1993
8  *    The Regents of the University of California.  All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  * 	This product includes software developed by the University of
21  * 	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 /*
40  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
41  *
42  * Permission to use, copy, modify, and distribute this software for any
43  * purpose with or without fee is hereby granted, provided that the above
44  * copyright notice and this permission notice appear in all copies, and that
45  * the name of Digital Equipment Corporation not be used in advertising or
46  * publicity pertaining to distribution of the document or software without
47  * specific, written prior permission.
48  *
49  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
50  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
51  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
52  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
53  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
54  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
55  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
56  * SOFTWARE.
57  */
58 
59 /*
60  * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
61  *
62  * Permission to use, copy, modify, and distribute this software for any
63  * purpose with or without fee is hereby granted, provided that the above
64  * copyright notice and this permission notice appear in all copies.
65  *
66  * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
67  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
68  * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
69  * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
70  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
71  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
72  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
73  * SOFTWARE.
74  */
75 
76 #pragma ident	"%Z%%M%	%I%	%E% SMI"
77 
78 #if defined(LIBC_SCCS) && !defined(lint)
79 static const char sccsid[] = "@(#)res_init.c	8.1 (Berkeley) 6/7/93";
80 static const char rcsid[] = "$Id: res_init.c,v 8.32 2003/04/03 06:31:10 marka Exp $";
81 #endif /* LIBC_SCCS and not lint */
82 
83 #include "port_before.h"
84 
85 #include <sys/types.h>
86 #include <sys/param.h>
87 #include <sys/socket.h>
88 #include <sys/time.h>
89 
90 #include <netinet/in.h>
91 #include <arpa/inet.h>
92 #include <arpa/nameser.h>
93 
94 #include <ctype.h>
95 #include <stdio.h>
96 #include <stdlib.h>
97 #include <string.h>
98 #include <unistd.h>
99 #include <netdb.h>
100 
101 #include "port_after.h"
102 
103 /* ensure that sockaddr_in6 and IN6ADDR_ANY_INIT are declared / defined */
104 #include <resolv.h>
105 
106 #include "res_private.h"
107 
108 /* Options.  Should all be left alone. */
109 #define RESOLVSORT
110 #define DEBUG
111 
112 #ifdef  SUNW_INITCHKIF
113 #include <net/if.h>
114 #include <netinet/if_ether.h>
115 #include <sys/sockio.h>
116 #define MAXIFS  8192
117 #endif  /* SUNW_INITCHKIF */
118 
119 #ifdef  SUNW_DOMAINFROMNIS
120 #include <sys/systeminfo.h>
121 #include <string.h>
122 #endif  /* SUNW_DOMAINFROMNIS */
123 
124 #ifdef	ORIGINAL_ISC_CODE
125 #else
126 #pragma weak	__res_randomid	=	res_randomid
127 #endif	/* ORIGINAL_ISC_CODE */
128 
129 static void res_setoptions __P((res_state, const char *, const char *));
130 
131 #ifdef RESOLVSORT
132 static const char sort_mask[] = "/&";
133 #define ISSORTMASK(ch) (strchr(sort_mask, ch) != NULL)
134 static u_int32_t net_mask __P((struct in_addr));
135 #endif
136 
137 #if !defined(isascii)	/* XXX - could be a function */
138 # define isascii(c) (!(c & 0200))
139 #endif
140 
141 /*
142  * Resolver state default settings.
143  */
144 
145 /*
146  * Set up default settings.  If the configuration file exist, the values
147  * there will have precedence.  Otherwise, the server address is set to
148  * INADDR_ANY and the default domain name comes from the gethostname().
149  *
150  * An interrim version of this code (BIND 4.9, pre-4.4BSD) used 127.0.0.1
151  * rather than INADDR_ANY ("0.0.0.0") as the default name server address
152  * since it was noted that INADDR_ANY actually meant ``the first interface
153  * you "ifconfig"'d at boot time'' and if this was a SLIP or PPP interface,
154  * it had to be "up" in order for you to reach your own name server.  It
155  * was later decided that since the recommended practice is to always
156  * install local static routes through 127.0.0.1 for all your network
157  * interfaces, that we could solve this problem without a code change.
158  *
159  * The configuration file should always be used, since it is the only way
160  * to specify a default domain.  If you are running a server on your local
161  * machine, you should say "nameserver 0.0.0.0" or "nameserver 127.0.0.1"
162  * in the configuration file.
163  *
164  * Return 0 if completes successfully, -1 on error
165  */
166 int
167 res_ninit(res_state statp) {
168 	extern int __res_vinit(res_state, int);
169 
170 	return (__res_vinit(statp, 0));
171 }
172 
173 /* This function has to be reachable by res_data.c but not publically. */
174 int
175 __res_vinit(res_state statp, int preinit) {
176 	register FILE *fp;
177 	register char *cp, **pp;
178 	register int n;
179 	char buf[BUFSIZ];
180 	int nserv = 0;    /* number of nameserver records read from file */
181 	int haveenv = 0;
182 	int havesearch = 0;
183 #ifdef RESOLVSORT
184 	int nsort = 0;
185 	char *net;
186 #endif
187 	int dots;
188 	union res_sockaddr_union u[2];
189 
190 	if (!preinit) {
191 		statp->retrans = RES_TIMEOUT;
192 		statp->retry = RES_DFLRETRY;
193 		statp->options = RES_DEFAULT;
194 		statp->id = res_randomid();
195 	}
196 
197 	if ((statp->options & RES_INIT) != 0)
198 		res_ndestroy(statp);
199 
200 	memset(u, 0, sizeof(u));
201 #ifdef USELOOPBACK
202 	u[nserv].sin.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
203 #else
204 	u[nserv].sin.sin_addr.s_addr = INADDR_ANY;
205 #endif
206 	u[nserv].sin.sin_family = AF_INET;
207 	u[nserv].sin.sin_port = htons(NAMESERVER_PORT);
208 #ifdef HAVE_SA_LEN
209 	u[nserv].sin.sin_len = sizeof(struct sockaddr_in);
210 #endif
211 	nserv++;
212 #ifdef HAS_INET6_STRUCTS
213 #ifdef USELOOPBACK
214 	u[nserv].sin6.sin6_addr = in6addr_loopback;
215 #else
216 	u[nserv].sin6.sin6_addr = in6addr_any;
217 #endif
218 	u[nserv].sin6.sin6_family = AF_INET6;
219 	u[nserv].sin6.sin6_port = htons(NAMESERVER_PORT);
220 #ifdef HAVE_SA_LEN
221 	u[nserv].sin6.sin6_len = sizeof(struct sockaddr_in6);
222 #endif
223 	nserv++;
224 #endif
225 	statp->nscount = 0;
226 	statp->ndots = 1;
227 	statp->pfcode = 0;
228 	statp->_vcsock = -1;
229 	statp->_flags = 0;
230 	statp->qhook = NULL;
231 	statp->rhook = NULL;
232 	statp->_u._ext.nscount = 0;
233 	statp->_u._ext.ext = malloc(sizeof(*statp->_u._ext.ext));
234 	if (statp->_u._ext.ext != NULL) {
235 	        memset(statp->_u._ext.ext, 0, sizeof(*statp->_u._ext.ext));
236 		statp->_u._ext.ext->nsaddrs[0].sin = statp->nsaddr;
237 		strcpy(statp->_u._ext.ext->nsuffix, "ip6.arpa");
238 		strcpy(statp->_u._ext.ext->nsuffix2, "ip6.int");
239 	}
240 #ifdef RESOLVSORT
241 	statp->nsort = 0;
242 #endif
243 	res_setservers(statp, u, nserv);
244 
245 #ifdef  SUNW_INITCHKIF
246 /*
247  * Short circuit res_init() if no non-loopback interfaces are up. This is
248  * done to avoid boot delays if "dns" comes before "files" in nsswitch.conf.
249  * An additional fix has been added to this code, to count all external
250  * interfaces, which includes the IPv6 interfaces. If no external interfaces
251  * are found, an additional check is carried out to determine if any deprecated
252  * interfaces are up.
253  */
254 	{
255 		int s;
256 		struct lifnum lifn;
257 
258 		if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
259 			perror("res_init: socket");
260 			return (-1);
261 		}
262 		lifn.lifn_family = AF_UNSPEC;
263 		lifn.lifn_flags = LIFC_EXTERNAL_SOURCE;
264 		if (ioctl(s, SIOCGLIFNUM, (char *)&lifn) < 0) {
265 			close(s);
266 			return (-1);
267 		}
268 		if (lifn.lifn_count == 0) {
269 			/*
270 			 * Check if there are any deprecated interfaces up
271 			 */
272 			struct lifconf lifc;
273 			uchar_t *buf;
274 			int buflen, i, int_up = 0;
275 
276 			lifn.lifn_flags = 0;
277 			if ((ioctl(s, SIOCGLIFNUM, (char *)&lifn) < 0) ||
278 					(lifn.lifn_count < 1)) {
279 				close(s);
280 				return (-1);
281 			}
282 
283 			buflen = lifn.lifn_count * sizeof (struct lifreq);
284 			buf = (uchar_t *)malloc(buflen);
285 			if (buf == NULL) {
286 				close(s);
287 				return (-1);
288 			}
289 
290 			lifc.lifc_family = AF_UNSPEC;
291 			lifc.lifc_flags = 0;
292 			lifc.lifc_len = buflen;
293 			lifc.lifc_lifcu.lifcu_buf = (caddr_t)buf;
294 			if (ioctl(s, SIOCGLIFCONF, (char *)&lifc) < 0) {
295 				close(s);
296 				free(buf);
297 				return (-1);
298 			}
299 
300 			for (i = 0; i < lifn.lifn_count; ++i) {
301 				struct lifreq *lreqp, lreq;
302 
303 				lreqp = (struct lifreq *)&lifc.lifc_req[i];
304 				strlcpy(lreq.lifr_name, lreqp->lifr_name,
305 						sizeof (lreq.lifr_name));
306 				if (ioctl(s, SIOCGLIFFLAGS, &lreq) < 0) {
307 					close(s);
308 					free(buf);
309 					return (-1);
310 				}
311 				if ((lreq.lifr_flags & IFF_UP) &&
312 					!(lreq.lifr_flags & IFF_NOLOCAL) &&
313 					!(lreq.lifr_flags & IFF_NOXMIT) &&
314 					!(lreq.lifr_flags & IFF_LOOPBACK)) {
315 					int_up = 1;
316 					break;
317 				}
318 			}
319 			free(buf);
320 
321 			if (!int_up) {
322 				close(s);
323 				return (-1);
324 			}
325 		}
326 		close(s);
327 	}
328 #endif  /* SUNW_INITCHKIF */
329 
330 #ifdef  SUNW_DOMAINFROMNIS
331 /*
332  * The old (4.8.3) libresolv derived the default domainname from NIS/NIS+.
333  */
334         {
335                 char buf[sizeof(statp->defdname)], *cp;
336                 int  ret;
337                 if ((ret = sysinfo(SI_SRPC_DOMAIN, buf, sizeof(buf))) > 0 &&
338                     ret <= sizeof(buf)) {
339                         if (buf[0] == '+')
340                                 buf[0] = '.';
341                         cp = strchr(buf, '.');
342                         if (cp == 0)
343                                 strcpy(statp->defdname, buf);
344                         else
345                                 strcpy(statp->defdname, cp+1);
346                 }
347         }
348 #endif  /* SUNW_DOMAINFROMNIS */
349 
350 	/* Allow user to override the local domain definition */
351 	if ((cp = getenv("LOCALDOMAIN")) != NULL) {
352 		(void)strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
353 		statp->defdname[sizeof(statp->defdname) - 1] = '\0';
354 		haveenv++;
355 
356 		/*
357 		 * Set search list to be blank-separated strings
358 		 * from rest of env value.  Permits users of LOCALDOMAIN
359 		 * to still have a search list, and anyone to set the
360 		 * one that they want to use as an individual (even more
361 		 * important now that the rfc1535 stuff restricts searches)
362 		 */
363 		cp = statp->defdname;
364 		pp = statp->dnsrch;
365 		*pp++ = cp;
366 		for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
367 			if (*cp == '\n')	/* silly backwards compat */
368 				break;
369 			else if (*cp == ' ' || *cp == '\t') {
370 				*cp = 0;
371 				n = 1;
372 			} else if (n) {
373 				*pp++ = cp;
374 				n = 0;
375 				havesearch = 1;
376 			}
377 		}
378 		/* null terminate last domain if there are excess */
379 		while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
380 			cp++;
381 		*cp = '\0';
382 		*pp++ = 0;
383 	}
384 
385 #define	MATCH(line, name) \
386 	(!strncmp(line, name, sizeof(name) - 1) && \
387 	(line[sizeof(name) - 1] == ' ' || \
388 	 line[sizeof(name) - 1] == '\t'))
389 
390 	nserv = 0;
391 
392 #ifdef SUNW_AVOIDSTDIO_FDLIMIT
393 	if ((fp = fopen(_PATH_RESCONF, "rF")) != NULL) {
394 #else
395 	if ((fp = fopen(_PATH_RESCONF, "r")) != NULL) {
396 #endif
397 	    /* read the config file */
398 	    while (fgets(buf, sizeof(buf), fp) != NULL) {
399 		/* skip comments */
400 		if (*buf == ';' || *buf == '#')
401 			continue;
402 		/* read default domain name */
403 		if (MATCH(buf, "domain")) {
404 		    if (haveenv)	/* skip if have from environ */
405 			    continue;
406 		    cp = buf + sizeof("domain") - 1;
407 		    while (*cp == ' ' || *cp == '\t')
408 			    cp++;
409 		    if ((*cp == '\0') || (*cp == '\n'))
410 			    continue;
411 		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
412 		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
413 		    if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL)
414 			    *cp = '\0';
415 		    havesearch = 0;
416 		    continue;
417 		}
418 		/* set search list */
419 		if (MATCH(buf, "search")) {
420 		    if (haveenv)	/* skip if have from environ */
421 			    continue;
422 		    cp = buf + sizeof("search") - 1;
423 		    while (*cp == ' ' || *cp == '\t')
424 			    cp++;
425 		    if ((*cp == '\0') || (*cp == '\n'))
426 			    continue;
427 		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
428 		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
429 		    if ((cp = strchr(statp->defdname, '\n')) != NULL)
430 			    *cp = '\0';
431 		    /*
432 		     * Set search list to be blank-separated strings
433 		     * on rest of line.
434 		     */
435 		    cp = statp->defdname;
436 		    pp = statp->dnsrch;
437 		    *pp++ = cp;
438 		    for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
439 			    if (*cp == ' ' || *cp == '\t') {
440 				    *cp = 0;
441 				    n = 1;
442 			    } else if (n) {
443 				    *pp++ = cp;
444 				    n = 0;
445 			    }
446 		    }
447 		    /* null terminate last domain if there are excess */
448 		    while (*cp != '\0' && *cp != ' ' && *cp != '\t')
449 			    cp++;
450 		    *cp = '\0';
451 		    *pp++ = 0;
452 		    havesearch = 1;
453 		    continue;
454 		}
455 		/* read nameservers to query */
456 		if (MATCH(buf, "nameserver") && nserv < MAXNS) {
457 		    struct addrinfo hints, *ai;
458 		    char sbuf[NI_MAXSERV];
459 		    const size_t minsiz =
460 		        sizeof(statp->_u._ext.ext->nsaddrs[0]);
461 
462 		    cp = buf + sizeof("nameserver") - 1;
463 		    while (*cp == ' ' || *cp == '\t')
464 			cp++;
465 		    cp[strcspn(cp, ";# \t\n")] = '\0';
466 		    if ((*cp != '\0') && (*cp != '\n')) {
467 			memset(&hints, 0, sizeof(hints));
468 			hints.ai_family = PF_UNSPEC;
469 			hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
470 			hints.ai_flags = AI_NUMERICHOST;
471 			sprintf(sbuf, "%u", NAMESERVER_PORT);
472 			if (getaddrinfo(cp, sbuf, &hints, &ai) == 0 &&
473 			    ai->ai_addrlen <= minsiz) {
474 			    if (statp->_u._ext.ext != NULL) {
475 				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
476 				    ai->ai_addr, ai->ai_addrlen);
477 			    }
478 			    if (ai->ai_addrlen <=
479 			        sizeof(statp->nsaddr_list[nserv])) {
480 				memcpy(&statp->nsaddr_list[nserv],
481 				    ai->ai_addr, ai->ai_addrlen);
482 			    } else
483 				statp->nsaddr_list[nserv].sin_family = 0;
484 			    freeaddrinfo(ai);
485 			    nserv++;
486 			}
487 		    }
488 		    continue;
489 		}
490 #ifdef RESOLVSORT
491 		if (MATCH(buf, "sortlist")) {
492 		    struct in_addr a;
493 
494 		    cp = buf + sizeof("sortlist") - 1;
495 		    while (nsort < MAXRESOLVSORT) {
496 			while (*cp == ' ' || *cp == '\t')
497 			    cp++;
498 			if (*cp == '\0' || *cp == '\n' || *cp == ';')
499 			    break;
500 			net = cp;
501 			while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
502 			       isascii(*cp) && !isspace((unsigned char)*cp))
503 				cp++;
504 			n = *cp;
505 			*cp = 0;
506 			if (inet_aton(net, &a)) {
507 			    statp->sort_list[nsort].addr = a;
508 			    if (ISSORTMASK(n)) {
509 				*cp++ = n;
510 				net = cp;
511 				while (*cp && *cp != ';' &&
512 					isascii(*cp) &&
513 					!isspace((unsigned char)*cp))
514 				    cp++;
515 				n = *cp;
516 				*cp = 0;
517 				if (inet_aton(net, &a)) {
518 				    statp->sort_list[nsort].mask = a.s_addr;
519 				} else {
520 				    statp->sort_list[nsort].mask =
521 					net_mask(statp->sort_list[nsort].addr);
522 				}
523 			    } else {
524 				statp->sort_list[nsort].mask =
525 				    net_mask(statp->sort_list[nsort].addr);
526 			    }
527 			    nsort++;
528 			}
529 			*cp = n;
530 		    }
531 		    continue;
532 		}
533 #endif
534 		if (MATCH(buf, "options")) {
535 		    res_setoptions(statp, buf + sizeof("options") - 1, "conf");
536 		    continue;
537 		}
538 	    }
539 	    if (nserv > 0)
540 		statp->nscount = nserv;
541 #ifdef RESOLVSORT
542 	    statp->nsort = nsort;
543 #endif
544 		(void) fclose(fp);
545 	}
546 /*
547  * Last chance to get a nameserver.  This should not normally
548  * be necessary
549  */
550 #ifdef NO_RESOLV_CONF
551 	if(nserv == 0)
552 		nserv = get_nameservers(statp);
553 #endif
554 
555 	if (statp->defdname[0] == 0 &&
556 	    gethostname(buf, sizeof(statp->defdname) - 1) == 0 &&
557 	    (cp = strchr(buf, '.')) != NULL)
558 		strcpy(statp->defdname, cp + 1);
559 
560 	/* find components of local domain that might be searched */
561 	if (havesearch == 0) {
562 		pp = statp->dnsrch;
563 		*pp++ = statp->defdname;
564 		*pp = NULL;
565 
566 		dots = 0;
567 		for (cp = statp->defdname; *cp; cp++)
568 			dots += (*cp == '.');
569 
570 		cp = statp->defdname;
571 		while (pp < statp->dnsrch + MAXDFLSRCH) {
572 			if (dots < LOCALDOMAINPARTS)
573 				break;
574 			cp = strchr(cp, '.') + 1;    /* we know there is one */
575 			*pp++ = cp;
576 			dots--;
577 		}
578 		*pp = NULL;
579 #ifdef DEBUG
580 		if (statp->options & RES_DEBUG) {
581 			printf(";; res_init()... default dnsrch list:\n");
582 			for (pp = statp->dnsrch; *pp; pp++)
583 				printf(";;\t%s\n", *pp);
584 			printf(";;\t..END..\n");
585 		}
586 #endif
587 	}
588 
589 	if ((cp = getenv("RES_OPTIONS")) != NULL)
590 		res_setoptions(statp, cp, "env");
591 	statp->options |= RES_INIT;
592 	return (0);
593 }
594 
595 static void
596 res_setoptions(res_state statp, const char *options, const char *source)
597 {
598 	const char *cp = options;
599 	int i;
600 	struct __res_state_ext *ext = statp->_u._ext.ext;
601 
602 #ifdef DEBUG
603 	if (statp->options & RES_DEBUG)
604 		printf(";; res_setoptions(\"%s\", \"%s\")...\n",
605 		       options, source);
606 #endif
607 	while (*cp) {
608 		/* skip leading and inner runs of spaces */
609 		while (*cp == ' ' || *cp == '\t')
610 			cp++;
611 		/* search for and process individual options */
612 		if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) {
613 			i = atoi(cp + sizeof("ndots:") - 1);
614 			if (i <= RES_MAXNDOTS)
615 				statp->ndots = i;
616 			else
617 				statp->ndots = RES_MAXNDOTS;
618 #ifdef DEBUG
619 			if (statp->options & RES_DEBUG)
620 				printf(";;\tndots=%d\n", statp->ndots);
621 #endif
622 		} else if (!strncmp(cp, "timeout:", sizeof("timeout:") - 1)) {
623 			i = atoi(cp + sizeof("timeout:") - 1);
624 			if (i <= RES_MAXRETRANS)
625 				statp->retrans = i;
626 			else
627 				statp->retrans = RES_MAXRETRANS;
628 		} else if (!strncmp(cp, "attempts:", sizeof("attempts:") - 1)){
629 			i = atoi(cp + sizeof("attempts:") - 1);
630 			if (i <= RES_MAXRETRY)
631 				statp->retry = i;
632 			else
633 				statp->retry = RES_MAXRETRY;
634 #ifdef	ORIGINAL_ISC_CODE
635 #else
636 		} else if (!strncmp(cp, "retrans:", sizeof("retrans:") - 1)) {
637 			/*
638 			 * For backward compatibility, 'retrans' is
639 			 * supported as an alias for 'timeout', though
640 			 * without an imposed maximum.
641 			 */
642 			statp->retrans = atoi(cp + sizeof("retrans:") - 1);
643 		} else if (!strncmp(cp, "retry:", sizeof("retry:") - 1)){
644 			/*
645 			 * For backward compatibility, 'retry' is
646 			 * supported as an alias for 'attempts', though
647 			 * without an imposed maximum.
648 			 */
649 			statp->retry = atoi(cp + sizeof("retry:") - 1);
650 #endif	/* ORIGINAL_ISC_CODE */
651 		} else if (!strncmp(cp, "debug", sizeof("debug") - 1)) {
652 #ifdef DEBUG
653 			if (!(statp->options & RES_DEBUG)) {
654 				printf(";; res_setoptions(\"%s\", \"%s\")..\n",
655 				       options, source);
656 				statp->options |= RES_DEBUG;
657 			}
658 			printf(";;\tdebug\n");
659 #endif
660 		} else if (!strncmp(cp, "no_tld_query",
661 				    sizeof("no_tld_query") - 1) ||
662 			   !strncmp(cp, "no-tld-query",
663 				    sizeof("no-tld-query") - 1)) {
664 			statp->options |= RES_NOTLDQUERY;
665 		} else if (!strncmp(cp, "inet6", sizeof("inet6") - 1)) {
666 			statp->options |= RES_USE_INET6;
667 		} else if (!strncmp(cp, "rotate", sizeof("rotate") - 1)) {
668 			statp->options |= RES_ROTATE;
669 		} else if (!strncmp(cp, "no-check-names",
670 				    sizeof("no-check-names") - 1)) {
671 			statp->options |= RES_NOCHECKNAME;
672 		}
673 #ifdef RES_USE_EDNS0
674 		else if (!strncmp(cp, "edns0", sizeof("edns0") - 1)) {
675 			statp->options |= RES_USE_EDNS0;
676 		}
677 #endif
678 		else if (!strncmp(cp, "dname", sizeof("dname") - 1)) {
679 			statp->options |= RES_USE_DNAME;
680 		}
681 		else if (!strncmp(cp, "nibble:", sizeof("nibble:") - 1)) {
682 			if (ext == NULL)
683 				goto skip;
684 			cp += sizeof("nibble:") - 1;
685 			i = MIN(strcspn(cp, " \t"), sizeof(ext->nsuffix) - 1);
686 			strncpy(ext->nsuffix, cp, i);
687 			ext->nsuffix[i] = '\0';
688 		}
689 		else if (!strncmp(cp, "nibble2:", sizeof("nibble2:") - 1)) {
690 			if (ext == NULL)
691 				goto skip;
692 			cp += sizeof("nibble2:") - 1;
693 			i = MIN(strcspn(cp, " \t"), sizeof(ext->nsuffix2) - 1);
694 			strncpy(ext->nsuffix2, cp, i);
695 			ext->nsuffix2[i] = '\0';
696 		}
697 		else if (!strncmp(cp, "v6revmode:", sizeof("v6revmode:") - 1)) {
698 			cp += sizeof("v6revmode:") - 1;
699 			/* "nibble" and "bitstring" used to be valid */
700 			if (!strncmp(cp, "single", sizeof("single") - 1)) {
701 				statp->options |= RES_NO_NIBBLE2;
702 			} else if (!strncmp(cp, "both", sizeof("both") - 1)) {
703 				statp->options &=
704 					 ~RES_NO_NIBBLE2;
705 			}
706 		}
707 		else {
708 			/* XXX - print a warning here? */
709 		}
710    skip:
711 		/* skip to next run of spaces */
712 		while (*cp && *cp != ' ' && *cp != '\t')
713 			cp++;
714 	}
715 }
716 
717 #ifdef RESOLVSORT
718 /* XXX - should really support CIDR which means explicit masks always. */
719 static u_int32_t
720 net_mask(in)		/* XXX - should really use system's version of this */
721 	struct in_addr in;
722 {
723 	register u_int32_t i = ntohl(in.s_addr);
724 
725 	if (IN_CLASSA(i))
726 		return (htonl(IN_CLASSA_NET));
727 	else if (IN_CLASSB(i))
728 		return (htonl(IN_CLASSB_NET));
729 	return (htonl(IN_CLASSC_NET));
730 }
731 #endif
732 
733 u_int
734 res_randomid(void) {
735 	struct timeval now;
736 
737 	gettimeofday(&now, NULL);
738 	return (0xffff & (now.tv_sec ^ now.tv_usec ^ getpid()));
739 }
740 
741 /*
742  * This routine is for closing the socket if a virtual circuit is used and
743  * the program wants to close it.  This provides support for endhostent()
744  * which expects to close the socket.
745  *
746  * This routine is not expected to be user visible.
747  */
748 void
749 res_nclose(res_state statp) {
750 	int ns;
751 
752 	if (statp->_vcsock >= 0) {
753 		(void) close(statp->_vcsock);
754 		statp->_vcsock = -1;
755 		statp->_flags &= ~(RES_F_VC | RES_F_CONN);
756 	}
757 	for (ns = 0; ns < statp->_u._ext.nscount; ns++) {
758 		if (statp->_u._ext.nssocks[ns] != -1) {
759 			(void) close(statp->_u._ext.nssocks[ns]);
760 			statp->_u._ext.nssocks[ns] = -1;
761 		}
762 	}
763 }
764 
765 void
766 res_ndestroy(res_state statp) {
767 	res_nclose(statp);
768 	if (statp->_u._ext.ext != NULL)
769 		free(statp->_u._ext.ext);
770 	statp->options &= ~RES_INIT;
771 	statp->_u._ext.ext = NULL;
772 }
773 
774 const char *
775 res_get_nibblesuffix(res_state statp) {
776 	if (statp->_u._ext.ext)
777 		return (statp->_u._ext.ext->nsuffix);
778 	return ("ip6.arpa");
779 }
780 
781 const char *
782 res_get_nibblesuffix2(res_state statp) {
783 	if (statp->_u._ext.ext)
784 		return (statp->_u._ext.ext->nsuffix2);
785 	return ("ip6.int");
786 }
787 
788 void
789 res_setservers(res_state statp, const union res_sockaddr_union *set, int cnt) {
790 	int i, nserv;
791 	size_t size;
792 
793 	/* close open servers */
794 	res_nclose(statp);
795 
796 	/* cause rtt times to be forgotten */
797 	statp->_u._ext.nscount = 0;
798 
799 	nserv = 0;
800 	for (i = 0; i < cnt && nserv < MAXNS; i++) {
801 		switch (set->sin.sin_family) {
802 		case AF_INET:
803 			size = sizeof(set->sin);
804 			if (statp->_u._ext.ext)
805 				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
806 					&set->sin, size);
807 			if (size <= sizeof(statp->nsaddr_list[nserv]))
808 				memcpy(&statp->nsaddr_list[nserv],
809 					&set->sin, size);
810 			else
811 				statp->nsaddr_list[nserv].sin_family = 0;
812 			nserv++;
813 			break;
814 
815 #ifdef HAS_INET6_STRUCTS
816 		case AF_INET6:
817 			size = sizeof(set->sin6);
818 			if (statp->_u._ext.ext)
819 				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
820 					&set->sin6, size);
821 			if (size <= sizeof(statp->nsaddr_list[nserv]))
822 				memcpy(&statp->nsaddr_list[nserv],
823 					&set->sin6, size);
824 			else
825 				statp->nsaddr_list[nserv].sin_family = 0;
826 			nserv++;
827 			break;
828 #endif
829 
830 		default:
831 			break;
832 		}
833 		set++;
834 	}
835 	statp->nscount = nserv;
836 
837 }
838 
839 int
840 res_getservers(res_state statp, union res_sockaddr_union *set, int cnt) {
841 	int i;
842 	size_t size;
843 	u_int16_t family;
844 
845 	for (i = 0; i < statp->nscount && i < cnt; i++) {
846 		if (statp->_u._ext.ext)
847 			family = statp->_u._ext.ext->nsaddrs[i].sin.sin_family;
848 		else
849 			family = statp->nsaddr_list[i].sin_family;
850 
851 		switch (family) {
852 		case AF_INET:
853 			size = sizeof(set->sin);
854 			if (statp->_u._ext.ext)
855 				memcpy(&set->sin,
856 				       &statp->_u._ext.ext->nsaddrs[i],
857 				       size);
858 			else
859 				memcpy(&set->sin, &statp->nsaddr_list[i],
860 				       size);
861 			break;
862 
863 #ifdef HAS_INET6_STRUCTS
864 		case AF_INET6:
865 			size = sizeof(set->sin6);
866 			if (statp->_u._ext.ext)
867 				memcpy(&set->sin6,
868 				       &statp->_u._ext.ext->nsaddrs[i],
869 				       size);
870 			else
871 				memcpy(&set->sin6, &statp->nsaddr_list[i],
872 				       size);
873 			break;
874 #endif
875 
876 		default:
877 			set->sin.sin_family = 0;
878 			break;
879 		}
880 		set++;
881 	}
882 	return (statp->nscount);
883 }
884