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