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