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