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