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