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