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