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