1 /*	$NetBSD: res_init.c,v 1.8 2006/03/19 03:10:08 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.8 2006/03/19 03:10:08 christos Exp $");
80 #endif
81 #endif /* LIBC_SCCS and not lint */
82 
83 
84 
85 #include <sys/types.h>
86 #include <sys/param.h>
87 #include <sys/socket.h>
88 #include <sys/time.h>
89 
90 #include <netinet/in.h>
91 #include <arpa/inet.h>
92 #include <arpa/nameser.h>
93 
94 #include <ctype.h>
95 #include <stdio.h>
96 #include <stdlib.h>
97 #include <string.h>
98 #include <unistd.h>
99 #include <netdb.h>
100 
101 #ifdef ANDROID_CHANGES
102 #include <errno.h>
103 #include <fcntl.h>
104 #endif /* ANDROID_CHANGES */
105 
106 /* ensure that sockaddr_in6 and IN6ADDR_ANY_INIT are declared / defined */
107 #ifdef ANDROID_CHANGES
108 #include "resolv_netid.h"
109 #include "resolv_private.h"
110 #else
111 #include <resolv.h>
112 #endif
113 
114 #include "res_private.h"
115 
116 /* Options.  Should all be left alone. */
117 #ifndef DEBUG
118 #define DEBUG
119 #endif
120 
121 static void res_setoptions __P((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 uint32_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 interrim 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
res_ninit(res_state statp)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
__res_vinit(res_state statp,int preinit)167 __res_vinit(res_state statp, int preinit) {
168 #if !defined(__BIONIC__)
169 	register FILE *fp;
170 #endif
171 	register char *cp, **pp;
172 #if !defined(__BIONIC__)
173 	register int n;
174 #endif
175 	char buf[BUFSIZ];
176 	int nserv = 0;    /* number of nameserver records read from file */
177 #if !defined(__BIONIC__)
178 	int haveenv = 0;
179 #endif
180 	int havesearch = 0;
181 #ifdef RESOLVSORT
182 	int nsort = 0;
183 #endif
184 #if !defined(__BIONIC__)
185 	char *net;
186 #endif
187 	int dots;
188 	union res_sockaddr_union u[2];
189 
190         if ((statp->options & RES_INIT) != 0U)
191                 res_ndestroy(statp);
192 
193 	if (!preinit) {
194 		statp->netid = NETID_UNSET;
195 		statp->retrans = RES_TIMEOUT;
196 		statp->retry = RES_DFLRETRY;
197 		statp->options = RES_DEFAULT;
198 		statp->id = res_randomid();
199 		statp->_mark = MARK_UNSET;
200 	}
201 
202 	memset(u, 0, sizeof(u));
203 #ifdef USELOOPBACK
204 	u[nserv].sin.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
205 #else
206 	u[nserv].sin.sin_addr.s_addr = INADDR_ANY;
207 #endif
208 	u[nserv].sin.sin_family = AF_INET;
209 	u[nserv].sin.sin_port = htons(NAMESERVER_PORT);
210 #ifdef HAVE_SA_LEN
211 	u[nserv].sin.sin_len = sizeof(struct sockaddr_in);
212 #endif
213 	nserv++;
214 #ifdef HAS_INET6_STRUCTS
215 #ifdef USELOOPBACK
216 	u[nserv].sin6.sin6_addr = in6addr_loopback;
217 #else
218 	u[nserv].sin6.sin6_addr = in6addr_any;
219 #endif
220 	u[nserv].sin6.sin6_family = AF_INET6;
221 	u[nserv].sin6.sin6_port = htons(NAMESERVER_PORT);
222 #ifdef HAVE_SA_LEN
223 	u[nserv].sin6.sin6_len = sizeof(struct sockaddr_in6);
224 #endif
225 	nserv++;
226 #endif
227 	statp->nscount = 0;
228 	statp->ndots = 1;
229 	statp->pfcode = 0;
230 	statp->_vcsock = -1;
231 	statp->_flags = 0;
232 	statp->qhook = NULL;
233 	statp->rhook = NULL;
234 	statp->_u._ext.nscount = 0;
235 	statp->_u._ext.ext = malloc(sizeof(*statp->_u._ext.ext));
236 	if (statp->_u._ext.ext != NULL) {
237 	        memset(statp->_u._ext.ext, 0, sizeof(*statp->_u._ext.ext));
238 		statp->_u._ext.ext->nsaddrs[0].sin = statp->nsaddr;
239 		strcpy(statp->_u._ext.ext->nsuffix, "ip6.arpa");
240 		strcpy(statp->_u._ext.ext->nsuffix2, "ip6.int");
241 	}
242 	statp->nsort = 0;
243 	res_setservers(statp, u, nserv);
244 
245 #if defined(__BIONIC__)
246 	/* Ignore the environment. */
247 #else
248 	/* Allow user to override the local domain definition */
249 	if ((cp = getenv("LOCALDOMAIN")) != NULL) {
250 		(void)strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
251 		statp->defdname[sizeof(statp->defdname) - 1] = '\0';
252 		haveenv++;
253 
254 		/*
255 		 * Set search list to be blank-separated strings
256 		 * from rest of env value.  Permits users of LOCALDOMAIN
257 		 * to still have a search list, and anyone to set the
258 		 * one that they want to use as an individual (even more
259 		 * important now that the rfc1535 stuff restricts searches)
260 		 */
261 		cp = statp->defdname;
262 		pp = statp->dnsrch;
263 		*pp++ = cp;
264 		for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
265 			if (*cp == '\n')	/* silly backwards compat */
266 				break;
267 			else if (*cp == ' ' || *cp == '\t') {
268 				*cp = 0;
269 				n = 1;
270 			} else if (n) {
271 				*pp++ = cp;
272 				n = 0;
273 				havesearch = 1;
274 			}
275 		}
276 		/* null terminate last domain if there are excess */
277 		while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
278 			cp++;
279 		*cp = '\0';
280 		*pp++ = 0;
281 	}
282 	if (nserv > 0)
283 		statp->nscount = nserv;
284 #endif
285 
286 #ifndef ANDROID_CHANGES /* !ANDROID_CHANGES - IGNORE resolv.conf in Android */
287 #define	MATCH(line, name) \
288 	(!strncmp(line, name, sizeof(name) - 1) && \
289 	(line[sizeof(name) - 1] == ' ' || \
290 	 line[sizeof(name) - 1] == '\t'))
291 
292 	nserv = 0;
293 	if ((fp = fopen(_PATH_RESCONF, "re")) != NULL) {
294 	    /* read the config file */
295 	    while (fgets(buf, sizeof(buf), fp) != NULL) {
296 		/* skip comments */
297 		if (*buf == ';' || *buf == '#')
298 			continue;
299 		/* read default domain name */
300 		if (MATCH(buf, "domain")) {
301 		    if (haveenv)	/* skip if have from environ */
302 			    continue;
303 		    cp = buf + sizeof("domain") - 1;
304 		    while (*cp == ' ' || *cp == '\t')
305 			    cp++;
306 		    if ((*cp == '\0') || (*cp == '\n'))
307 			    continue;
308 		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
309 		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
310 		    if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL)
311 			    *cp = '\0';
312 		    havesearch = 0;
313 		    continue;
314 		}
315 		/* set search list */
316 		if (MATCH(buf, "search")) {
317 		    if (haveenv)	/* skip if have from environ */
318 			    continue;
319 		    cp = buf + sizeof("search") - 1;
320 		    while (*cp == ' ' || *cp == '\t')
321 			    cp++;
322 		    if ((*cp == '\0') || (*cp == '\n'))
323 			    continue;
324 		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
325 		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
326 		    if ((cp = strchr(statp->defdname, '\n')) != NULL)
327 			    *cp = '\0';
328 		    /*
329 		     * Set search list to be blank-separated strings
330 		     * on rest of line.
331 		     */
332 		    cp = statp->defdname;
333 		    pp = statp->dnsrch;
334 		    *pp++ = cp;
335 		    for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
336 			    if (*cp == ' ' || *cp == '\t') {
337 				    *cp = 0;
338 				    n = 1;
339 			    } else if (n) {
340 				    *pp++ = cp;
341 				    n = 0;
342 			    }
343 		    }
344 		    /* null terminate last domain if there are excess */
345 		    while (*cp != '\0' && *cp != ' ' && *cp != '\t')
346 			    cp++;
347 		    *cp = '\0';
348 		    *pp++ = 0;
349 		    havesearch = 1;
350 		    continue;
351 		}
352 		/* read nameservers to query */
353 		if (MATCH(buf, "nameserver") && nserv < MAXNS) {
354 		    struct addrinfo hints, *ai;
355 		    char sbuf[NI_MAXSERV];
356 		    const size_t minsiz =
357 		        sizeof(statp->_u._ext.ext->nsaddrs[0]);
358 
359 		    cp = buf + sizeof("nameserver") - 1;
360 		    while (*cp == ' ' || *cp == '\t')
361 			cp++;
362 		    cp[strcspn(cp, ";# \t\n")] = '\0';
363 		    if ((*cp != '\0') && (*cp != '\n')) {
364 			memset(&hints, 0, sizeof(hints));
365 			hints.ai_family = PF_UNSPEC;
366 			hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
367 			hints.ai_flags = AI_NUMERICHOST;
368 			sprintf(sbuf, "%u", NAMESERVER_PORT);
369 			if (getaddrinfo(cp, sbuf, &hints, &ai) == 0 &&
370 			    ai->ai_addrlen <= minsiz) {
371 			    if (statp->_u._ext.ext != NULL) {
372 				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
373 				    ai->ai_addr, ai->ai_addrlen);
374 			    }
375 			    if (ai->ai_addrlen <=
376 			        sizeof(statp->nsaddr_list[nserv])) {
377 				memcpy(&statp->nsaddr_list[nserv],
378 				    ai->ai_addr, ai->ai_addrlen);
379 			    } else
380 				statp->nsaddr_list[nserv].sin_family = 0;
381 			    freeaddrinfo(ai);
382 			    nserv++;
383 			}
384 		    }
385 		    continue;
386 		}
387 		if (MATCH(buf, "sortlist")) {
388 		    struct in_addr a;
389 
390 		    cp = buf + sizeof("sortlist") - 1;
391 		    while (nsort < MAXRESOLVSORT) {
392 			while (*cp == ' ' || *cp == '\t')
393 			    cp++;
394 			if (*cp == '\0' || *cp == '\n' || *cp == ';')
395 			    break;
396 			net = cp;
397 			while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
398 			       isascii(*cp) && !isspace((unsigned char)*cp))
399 				cp++;
400 			n = *cp;
401 			*cp = 0;
402 			if (inet_aton(net, &a)) {
403 			    statp->sort_list[nsort].addr = a;
404 			    if (ISSORTMASK(n)) {
405 				*cp++ = n;
406 				net = cp;
407 				while (*cp && *cp != ';' &&
408 					isascii(*cp) &&
409 					!isspace((unsigned char)*cp))
410 				    cp++;
411 				n = *cp;
412 				*cp = 0;
413 				if (inet_aton(net, &a)) {
414 				    statp->sort_list[nsort].mask = a.s_addr;
415 				} else {
416 				    statp->sort_list[nsort].mask =
417 					net_mask(statp->sort_list[nsort].addr);
418 				}
419 			    } else {
420 				statp->sort_list[nsort].mask =
421 				    net_mask(statp->sort_list[nsort].addr);
422 			    }
423 			    nsort++;
424 			}
425 			*cp = n;
426 		    }
427 		    continue;
428 		}
429 		if (MATCH(buf, "options")) {
430 		    res_setoptions(statp, buf + sizeof("options") - 1, "conf");
431 		    continue;
432 		}
433 	    }
434 	    if (nserv > 0)
435 		statp->nscount = nserv;
436 	    statp->nsort = nsort;
437 	    (void) fclose(fp);
438 	}
439 #endif /* !ANDROID_CHANGES */
440 /*
441  * Last chance to get a nameserver.  This should not normally
442  * be necessary
443  */
444 #ifdef NO_RESOLV_CONF
445 	if(nserv == 0)
446 		nserv = get_nameservers(statp);
447 #endif
448 
449 	if (statp->defdname[0] == 0 &&
450 	    gethostname(buf, sizeof(statp->defdname) - 1) == 0 &&
451 	    (cp = strchr(buf, '.')) != NULL)
452 		strcpy(statp->defdname, cp + 1);
453 
454 	/* find components of local domain that might be searched */
455 	if (havesearch == 0) {
456 		pp = statp->dnsrch;
457 		*pp++ = statp->defdname;
458 		*pp = NULL;
459 
460 		dots = 0;
461 		for (cp = statp->defdname; *cp; cp++)
462 			dots += (*cp == '.');
463 
464 		cp = statp->defdname;
465 		while (pp < statp->dnsrch + MAXDFLSRCH) {
466 			if (dots < LOCALDOMAINPARTS)
467 				break;
468 			cp = strchr(cp, '.') + 1;    /* we know there is one */
469 			*pp++ = cp;
470 			dots--;
471 		}
472 		*pp = NULL;
473 #ifdef DEBUG
474 		if (statp->options & RES_DEBUG) {
475 			printf(";; res_init()... default dnsrch list:\n");
476 			for (pp = statp->dnsrch; *pp; pp++)
477 				printf(";;\t%s\n", *pp);
478 			printf(";;\t..END..\n");
479 		}
480 #endif
481 	}
482 
483 	if ((cp = getenv("RES_OPTIONS")) != NULL)
484 		res_setoptions(statp, cp, "env");
485 	if (nserv > 0) {
486 		statp->nscount = nserv;
487 		statp->options |= RES_INIT;
488 	}
489 	return (0);
490 }
491 
492 static void
res_setoptions(res_state statp,const char * options,const char * source)493 res_setoptions(res_state statp, const char *options, const char *source)
494 {
495 	const char *cp = options;
496 	int i;
497 	struct __res_state_ext *ext = statp->_u._ext.ext;
498 
499 #ifdef DEBUG
500 	if (statp->options & RES_DEBUG)
501 		printf(";; res_setoptions(\"%s\", \"%s\")...\n",
502 		       options, source);
503 #endif
504 	while (*cp) {
505 		/* skip leading and inner runs of spaces */
506 		while (*cp == ' ' || *cp == '\t')
507 			cp++;
508 		/* search for and process individual options */
509 		if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) {
510 			i = atoi(cp + sizeof("ndots:") - 1);
511 			if (i <= RES_MAXNDOTS)
512 				statp->ndots = i;
513 			else
514 				statp->ndots = RES_MAXNDOTS;
515 #ifdef DEBUG
516 			if (statp->options & RES_DEBUG)
517 				printf(";;\tndots=%d\n", statp->ndots);
518 #endif
519 		} else if (!strncmp(cp, "timeout:", sizeof("timeout:") - 1)) {
520 			i = atoi(cp + sizeof("timeout:") - 1);
521 			if (i <= RES_MAXRETRANS)
522 				statp->retrans = i;
523 			else
524 				statp->retrans = RES_MAXRETRANS;
525 #ifdef DEBUG
526 			if (statp->options & RES_DEBUG)
527 				printf(";;\ttimeout=%d\n", statp->retrans);
528 #endif
529 		} else if (!strncmp(cp, "attempts:", sizeof("attempts:") - 1)){
530 			i = atoi(cp + sizeof("attempts:") - 1);
531 			if (i <= RES_MAXRETRY)
532 				statp->retry = i;
533 			else
534 				statp->retry = RES_MAXRETRY;
535 #ifdef DEBUG
536 			if (statp->options & RES_DEBUG)
537 				printf(";;\tattempts=%d\n", statp->retry);
538 #endif
539 		} else if (!strncmp(cp, "debug", sizeof("debug") - 1)) {
540 #ifdef DEBUG
541 			if (!(statp->options & RES_DEBUG)) {
542 				printf(";; res_setoptions(\"%s\", \"%s\")..\n",
543 				       options, source);
544 				statp->options |= RES_DEBUG;
545 			}
546 			printf(";;\tdebug\n");
547 #endif
548 		} else if (!strncmp(cp, "no_tld_query",
549 				    sizeof("no_tld_query") - 1) ||
550 			   !strncmp(cp, "no-tld-query",
551 				    sizeof("no-tld-query") - 1)) {
552 			statp->options |= RES_NOTLDQUERY;
553 		} else if (!strncmp(cp, "inet6", sizeof("inet6") - 1)) {
554 			statp->options |= RES_USE_INET6;
555 		} else if (!strncmp(cp, "rotate", sizeof("rotate") - 1)) {
556 			statp->options |= RES_ROTATE;
557 		} else if (!strncmp(cp, "no-check-names",
558 				    sizeof("no-check-names") - 1)) {
559 			statp->options |= RES_NOCHECKNAME;
560 		}
561 #ifdef RES_USE_EDNS0
562 		else if (!strncmp(cp, "edns0", sizeof("edns0") - 1)) {
563 			statp->options |= RES_USE_EDNS0;
564 		}
565 #endif
566 		else if (!strncmp(cp, "dname", sizeof("dname") - 1)) {
567 			statp->options |= RES_USE_DNAME;
568 		}
569 		else if (!strncmp(cp, "nibble:", sizeof("nibble:") - 1)) {
570 			if (ext == NULL)
571 				goto skip;
572 			cp += sizeof("nibble:") - 1;
573 			i = MIN(strcspn(cp, " \t"), sizeof(ext->nsuffix) - 1);
574 			strncpy(ext->nsuffix, cp, (size_t)i);
575 			ext->nsuffix[i] = '\0';
576 		}
577 		else if (!strncmp(cp, "nibble2:", sizeof("nibble2:") - 1)) {
578 			if (ext == NULL)
579 				goto skip;
580 			cp += sizeof("nibble2:") - 1;
581 			i = MIN(strcspn(cp, " \t"), sizeof(ext->nsuffix2) - 1);
582 			strncpy(ext->nsuffix2, cp, (size_t)i);
583 			ext->nsuffix2[i] = '\0';
584 		}
585 		else if (!strncmp(cp, "v6revmode:", sizeof("v6revmode:") - 1)) {
586 			cp += sizeof("v6revmode:") - 1;
587 			/* "nibble" and "bitstring" used to be valid */
588 			if (!strncmp(cp, "single", sizeof("single") - 1)) {
589 				statp->options |= RES_NO_NIBBLE2;
590 			} else if (!strncmp(cp, "both", sizeof("both") - 1)) {
591 				statp->options &=
592 					 ~RES_NO_NIBBLE2;
593 			}
594 		}
595 		else {
596 			/* XXX - print a warning here? */
597 		}
598    skip:
599 		/* skip to next run of spaces */
600 		while (*cp && *cp != ' ' && *cp != '\t')
601 			cp++;
602 	}
603 }
604 
605 #ifdef RESOLVSORT
606 /* XXX - should really support CIDR which means explicit masks always. */
607 static uint32_t
net_mask(struct in_addr in)608 net_mask(struct in_addr in)	/*!< XXX - should really use system's version of this */
609 {
610 	register uint32_t i = ntohl(in.s_addr);
611 
612 	if (IN_CLASSA(i))
613 		return (htonl(IN_CLASSA_NET));
614 	else if (IN_CLASSB(i))
615 		return (htonl(IN_CLASSB_NET));
616 	return (htonl(IN_CLASSC_NET));
617 }
618 #endif
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
res_nclose(res_state statp)628 res_nclose(res_state statp)
629 {
630 	int ns;
631 
632 	if (statp->_vcsock >= 0) {
633 		(void) close(statp->_vcsock);
634 		statp->_vcsock = -1;
635 		statp->_flags &= ~(RES_F_VC | RES_F_CONN);
636 	}
637 	for (ns = 0; ns < statp->_u._ext.nscount; ns++) {
638 		if (statp->_u._ext.nssocks[ns] != -1) {
639 			(void) close(statp->_u._ext.nssocks[ns]);
640 			statp->_u._ext.nssocks[ns] = -1;
641 		}
642 	}
643 }
644 
645 void
res_ndestroy(res_state statp)646 res_ndestroy(res_state statp)
647 {
648 	res_nclose(statp);
649 	if (statp->_u._ext.ext != NULL)
650 		free(statp->_u._ext.ext);
651 	statp->options &= ~RES_INIT;
652 	statp->_u._ext.ext = NULL;
653 }
654 
655 const char *
res_get_nibblesuffix(res_state statp)656 res_get_nibblesuffix(res_state statp)
657 {
658 	if (statp->_u._ext.ext)
659 		return (statp->_u._ext.ext->nsuffix);
660 	return ("ip6.arpa");
661 }
662 
663 const char *
res_get_nibblesuffix2(res_state statp)664 res_get_nibblesuffix2(res_state statp)
665 {
666 	if (statp->_u._ext.ext)
667 		return (statp->_u._ext.ext->nsuffix2);
668 	return ("ip6.int");
669 }
670 
671 void
res_setservers(res_state statp,const union res_sockaddr_union * set,int cnt)672 res_setservers(res_state statp, const union res_sockaddr_union *set, int cnt)
673 {
674 	int i, nserv;
675 	size_t size;
676 
677 	/* close open servers */
678 	res_nclose(statp);
679 
680 	/* cause rtt times to be forgotten */
681 	statp->_u._ext.nscount = 0;
682 
683 	nserv = 0;
684 	for (i = 0; i < cnt && nserv < MAXNS; i++) {
685 		switch (set->sin.sin_family) {
686 		case AF_INET:
687 			size = sizeof(set->sin);
688 			if (statp->_u._ext.ext)
689 				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
690 					&set->sin, size);
691 			if (size <= sizeof(statp->nsaddr_list[nserv]))
692 				memcpy(&statp->nsaddr_list[nserv],
693 					&set->sin, size);
694 			else
695 				statp->nsaddr_list[nserv].sin_family = 0;
696 			nserv++;
697 			break;
698 
699 #ifdef HAS_INET6_STRUCTS
700 		case AF_INET6:
701 			size = sizeof(set->sin6);
702 			if (statp->_u._ext.ext)
703 				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
704 					&set->sin6, size);
705 			if (size <= sizeof(statp->nsaddr_list[nserv]))
706 				memcpy(&statp->nsaddr_list[nserv],
707 					&set->sin6, size);
708 			else
709 				statp->nsaddr_list[nserv].sin_family = 0;
710 			nserv++;
711 			break;
712 #endif
713 
714 		default:
715 			break;
716 		}
717 		set++;
718 	}
719 	statp->nscount = nserv;
720 
721 }
722 
723 int
res_getservers(res_state statp,union res_sockaddr_union * set,int cnt)724 res_getservers(res_state statp, union res_sockaddr_union *set, int cnt)
725 {
726 	int i;
727 	size_t size;
728 	uint16_t family;
729 
730 	for (i = 0; i < statp->nscount && i < cnt; i++) {
731 		if (statp->_u._ext.ext)
732 			family = statp->_u._ext.ext->nsaddrs[i].sin.sin_family;
733 		else
734 			family = statp->nsaddr_list[i].sin_family;
735 
736 		switch (family) {
737 		case AF_INET:
738 			size = sizeof(set->sin);
739 			if (statp->_u._ext.ext)
740 				memcpy(&set->sin,
741 				       &statp->_u._ext.ext->nsaddrs[i],
742 				       size);
743 			else
744 				memcpy(&set->sin, &statp->nsaddr_list[i],
745 				       size);
746 			break;
747 
748 #ifdef HAS_INET6_STRUCTS
749 		case AF_INET6:
750 			size = sizeof(set->sin6);
751 			if (statp->_u._ext.ext)
752 				memcpy(&set->sin6,
753 				       &statp->_u._ext.ext->nsaddrs[i],
754 				       size);
755 			else
756 				memcpy(&set->sin6, &statp->nsaddr_list[i],
757 				       size);
758 			break;
759 #endif
760 
761 		default:
762 			set->sin.sin_family = 0;
763 			break;
764 		}
765 		set++;
766 	}
767 	return (statp->nscount);
768 }
769 
770 #ifdef ANDROID_CHANGES
res_setnetcontext(res_state statp,const struct android_net_context * netcontext)771 void res_setnetcontext(res_state statp, const struct android_net_context *netcontext)
772 {
773 	if (statp != NULL) {
774 		statp->netid = netcontext->dns_netid;
775 		statp->_mark = netcontext->dns_mark;
776 		statp->qhook = netcontext->qhook;
777 		if (netcontext->flags & NET_CONTEXT_FLAG_USE_EDNS) {
778 			statp->options |= RES_USE_EDNS0 | RES_USE_DNSSEC;
779 		}
780 	}
781 }
782 
783 #endif /* ANDROID_CHANGES */
784