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