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