res_init.c revision 292216
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 * 4. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30/*
31 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
32 *
33 * Permission to use, copy, modify, and distribute this software for any
34 * purpose with or without fee is hereby granted, provided that the above
35 * copyright notice and this permission notice appear in all copies, and that
36 * the name of Digital Equipment Corporation not be used in advertising or
37 * publicity pertaining to distribution of the document or software without
38 * specific, written prior permission.
39 *
40 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
41 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
42 * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
43 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
44 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
45 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
46 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
47 * SOFTWARE.
48 */
49
50/*
51 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
52 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
53 *
54 * Permission to use, copy, modify, and distribute this software for any
55 * purpose with or without fee is hereby granted, provided that the above
56 * copyright notice and this permission notice appear in all copies.
57 *
58 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
59 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
60 * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
61 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
62 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
63 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
64 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
65 */
66
67#if defined(LIBC_SCCS) && !defined(lint)
68static const char sccsid[] = "@(#)res_init.c	8.1 (Berkeley) 6/7/93";
69static const char rcsid[] = "$Id: res_init.c,v 1.26 2008/12/11 09:59:00 marka Exp $";
70#endif /* LIBC_SCCS and not lint */
71#include <sys/cdefs.h>
72__FBSDID("$FreeBSD: head/lib/libc/resolv/res_init.c 292216 2015-12-14 17:21:06Z vangyzen $");
73
74#include "port_before.h"
75
76#include "namespace.h"
77
78#include <sys/types.h>
79#include <sys/param.h>
80#include <sys/socket.h>
81#include <sys/stat.h>
82#include <sys/time.h>
83
84#include <netinet/in.h>
85#include <arpa/inet.h>
86#include <arpa/nameser.h>
87
88#include <ctype.h>
89#include <stdio.h>
90#include <stdlib.h>
91#include <string.h>
92#include <unistd.h>
93#include <netdb.h>
94
95#ifndef HAVE_MD5
96# include "../dst/md5.h"
97#else
98# ifdef SOLARIS2
99#  include <sys/md5.h>
100# elif _LIBC
101# include <md5.h>
102# endif
103#endif
104#ifndef _MD5_H_
105# define _MD5_H_ 1	/*%< make sure we do not include rsaref md5.h file */
106#endif
107
108#include "un-namespace.h"
109
110#include "port_after.h"
111
112/* ensure that sockaddr_in6 and IN6ADDR_ANY_INIT are declared / defined */
113#include <resolv.h>
114
115#include "res_private.h"
116
117/*% Options.  Should all be left alone. */
118#define RESOLVSORT
119#define DEBUG
120
121#ifdef SOLARIS2
122#include <sys/systeminfo.h>
123#endif
124
125static void res_setoptions(res_state, const char *, const char *);
126
127#ifdef RESOLVSORT
128static const char sort_mask[] = "/&";
129#define ISSORTMASK(ch) (strchr(sort_mask, ch) != NULL)
130static u_int32_t net_mask(struct in_addr);
131#endif
132
133#if !defined(isascii)	/*%< XXX - could be a function */
134# define isascii(c) (!(c & 0200))
135#endif
136
137/*
138 * Resolver state default settings.
139 */
140
141/*%
142 * Set up default settings.  If the configuration file exist, the values
143 * there will have precedence.  Otherwise, the server address is set to
144 * INADDR_ANY and the default domain name comes from the gethostname().
145 *
146 * An interrim version of this code (BIND 4.9, pre-4.4BSD) used 127.0.0.1
147 * rather than INADDR_ANY ("0.0.0.0") as the default name server address
148 * since it was noted that INADDR_ANY actually meant ``the first interface
149 * you "ifconfig"'d at boot time'' and if this was a SLIP or PPP interface,
150 * it had to be "up" in order for you to reach your own name server.  It
151 * was later decided that since the recommended practice is to always
152 * install local static routes through 127.0.0.1 for all your network
153 * interfaces, that we could solve this problem without a code change.
154 *
155 * The configuration file should always be used, since it is the only way
156 * to specify a default domain.  If you are running a server on your local
157 * machine, you should say "nameserver 0.0.0.0" or "nameserver 127.0.0.1"
158 * in the configuration file.
159 *
160 * Return 0 if completes successfully, -1 on error
161 */
162int
163res_ninit(res_state statp) {
164	extern int __res_vinit(res_state, int);
165
166	return (__res_vinit(statp, 0));
167}
168
169/*% This function has to be reachable by res_data.c but not publically. */
170int
171__res_vinit(res_state statp, int preinit) {
172	FILE *fp;
173	char *cp, **pp;
174	int n;
175	char buf[BUFSIZ];
176	int nserv = 0;    /*%< number of nameserver records read from file */
177	int haveenv = 0;
178	int havesearch = 0;
179#ifdef RESOLVSORT
180	int nsort = 0;
181	char *net;
182#endif
183	int dots;
184	union res_sockaddr_union u[2];
185	int maxns = MAXNS;
186
187	RES_SET_H_ERRNO(statp, 0);
188	if (statp->_u._ext.ext != NULL)
189		res_ndestroy(statp);
190
191	if (!preinit) {
192		statp->retrans = RES_TIMEOUT;
193		statp->retry = RES_DFLRETRY;
194		statp->options = RES_DEFAULT;
195	}
196
197	statp->_rnd = malloc(16);
198	res_rndinit(statp);
199	statp->id = res_nrandomid(statp);
200
201	memset(u, 0, sizeof(u));
202#ifdef USELOOPBACK
203	u[nserv].sin.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
204#else
205	u[nserv].sin.sin_addr.s_addr = INADDR_ANY;
206#endif
207	u[nserv].sin.sin_family = AF_INET;
208	u[nserv].sin.sin_port = htons(NAMESERVER_PORT);
209#ifdef HAVE_SA_LEN
210	u[nserv].sin.sin_len = sizeof(struct sockaddr_in);
211#endif
212	nserv++;
213#ifdef HAS_INET6_STRUCTS
214#ifdef USELOOPBACK
215	u[nserv].sin6.sin6_addr = in6addr_loopback;
216#else
217	u[nserv].sin6.sin6_addr = in6addr_any;
218#endif
219	u[nserv].sin6.sin6_family = AF_INET6;
220	u[nserv].sin6.sin6_port = htons(NAMESERVER_PORT);
221#ifdef HAVE_SA_LEN
222	u[nserv].sin6.sin6_len = sizeof(struct sockaddr_in6);
223#endif
224	nserv++;
225#endif
226	statp->nscount = 0;
227	statp->ndots = 1;
228	statp->pfcode = 0;
229	statp->_vcsock = -1;
230	statp->_flags = 0;
231	statp->qhook = NULL;
232	statp->rhook = NULL;
233	statp->_u._ext.nscount = 0;
234	statp->_u._ext.ext = malloc(sizeof(*statp->_u._ext.ext));
235	if (statp->_u._ext.ext != NULL) {
236	        memset(statp->_u._ext.ext, 0, sizeof(*statp->_u._ext.ext));
237		statp->_u._ext.ext->nsaddrs[0].sin = statp->nsaddr;
238		strcpy(statp->_u._ext.ext->nsuffix, "ip6.arpa");
239		strcpy(statp->_u._ext.ext->nsuffix2, "ip6.int");
240		statp->_u._ext.ext->reload_period = 2;
241	} else {
242		/*
243		 * Historically res_init() rarely, if at all, failed.
244		 * Examples and applications exist which do not check
245		 * our return code.  Furthermore several applications
246		 * simply call us to get the systems domainname.  So
247		 * rather then immediately fail here we store the
248		 * failure, which is returned later, in h_errno.  And
249		 * prevent the collection of 'nameserver' information
250		 * by setting maxns to 0.  Thus applications that fail
251		 * to check our return code wont be able to make
252		 * queries anyhow.
253		 */
254		RES_SET_H_ERRNO(statp, NETDB_INTERNAL);
255		maxns = 0;
256	}
257#ifdef RESOLVSORT
258	statp->nsort = 0;
259#endif
260	res_setservers(statp, u, nserv);
261
262#ifdef	SOLARIS2
263	/*
264	 * The old libresolv derived the defaultdomain from NIS/NIS+.
265	 * We want to keep this behaviour
266	 */
267	{
268		char buf[sizeof(statp->defdname)], *cp;
269		int ret;
270
271		if ((ret = sysinfo(SI_SRPC_DOMAIN, buf, sizeof(buf))) > 0 &&
272			(unsigned int)ret <= sizeof(buf)) {
273			if (buf[0] == '+')
274				buf[0] = '.';
275			cp = strchr(buf, '.');
276			cp = (cp == NULL) ? buf : (cp + 1);
277			strncpy(statp->defdname, cp,
278				sizeof(statp->defdname) - 1);
279			statp->defdname[sizeof(statp->defdname) - 1] = '\0';
280		}
281	}
282#endif	/* SOLARIS2 */
283
284	/* Allow user to override the local domain definition */
285	if (issetugid() == 0 && (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
319#define	MATCH(line, name) \
320	(!strncmp(line, name, sizeof(name) - 1) && \
321	(line[sizeof(name) - 1] == ' ' || \
322	 line[sizeof(name) - 1] == '\t'))
323
324	nserv = 0;
325	if ((fp = fopen(_PATH_RESCONF, "re")) != NULL) {
326	    struct stat sb;
327	    struct timespec now;
328
329	    if (statp->_u._ext.ext != NULL) {
330		if (_fstat(fileno(fp), &sb) == 0) {
331		    statp->_u._ext.ext->conf_mtim = sb.st_mtim;
332		    if (clock_gettime(CLOCK_MONOTONIC_FAST, &now) == 0) {
333			statp->_u._ext.ext->conf_stat = now.tv_sec;
334		    }
335		}
336	    }
337
338	    /* read the config file */
339	    while (fgets(buf, sizeof(buf), fp) != NULL) {
340		/* skip comments */
341		if (*buf == ';' || *buf == '#')
342			continue;
343		/* read default domain name */
344		if (MATCH(buf, "domain")) {
345		    if (haveenv)	/*%< skip if have from environ */
346			    continue;
347		    cp = buf + sizeof("domain") - 1;
348		    while (*cp == ' ' || *cp == '\t')
349			    cp++;
350		    if ((*cp == '\0') || (*cp == '\n'))
351			    continue;
352		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
353		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
354		    if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL)
355			    *cp = '\0';
356		    havesearch = 0;
357		    continue;
358		}
359		/* set search list */
360		if (MATCH(buf, "search")) {
361		    if (haveenv)	/*%< skip if have from environ */
362			    continue;
363		    cp = buf + sizeof("search") - 1;
364		    while (*cp == ' ' || *cp == '\t')
365			    cp++;
366		    if ((*cp == '\0') || (*cp == '\n'))
367			    continue;
368		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
369		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
370		    if ((cp = strchr(statp->defdname, '\n')) != NULL)
371			    *cp = '\0';
372		    /*
373		     * Set search list to be blank-separated strings
374		     * on rest of line.
375		     */
376		    cp = statp->defdname;
377		    pp = statp->dnsrch;
378		    *pp++ = cp;
379		    for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
380			    if (*cp == ' ' || *cp == '\t') {
381				    *cp = 0;
382				    n = 1;
383			    } else if (n) {
384				    *pp++ = cp;
385				    n = 0;
386			    }
387		    }
388		    /* null terminate last domain if there are excess */
389		    while (*cp != '\0' && *cp != ' ' && *cp != '\t')
390			    cp++;
391		    *cp = '\0';
392		    *pp++ = 0;
393		    havesearch = 1;
394		    continue;
395		}
396		/* read nameservers to query */
397		if (MATCH(buf, "nameserver") && nserv < maxns) {
398		    struct addrinfo hints, *ai;
399		    char sbuf[NI_MAXSERV];
400		    const size_t minsiz =
401		        sizeof(statp->_u._ext.ext->nsaddrs[0]);
402
403		    cp = buf + sizeof("nameserver") - 1;
404		    while (*cp == ' ' || *cp == '\t')
405			cp++;
406		    cp[strcspn(cp, ";# \t\n")] = '\0';
407		    if ((*cp != '\0') && (*cp != '\n')) {
408			memset(&hints, 0, sizeof(hints));
409			hints.ai_family = PF_UNSPEC;
410			hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
411			hints.ai_flags = AI_NUMERICHOST;
412			sprintf(sbuf, "%u", NAMESERVER_PORT);
413			if (getaddrinfo(cp, sbuf, &hints, &ai) == 0 &&
414			    ai->ai_addrlen <= minsiz) {
415			    if (statp->_u._ext.ext != NULL) {
416				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
417				    ai->ai_addr, ai->ai_addrlen);
418			    }
419			    if (ai->ai_addrlen <=
420			        sizeof(statp->nsaddr_list[nserv])) {
421				memcpy(&statp->nsaddr_list[nserv],
422				    ai->ai_addr, ai->ai_addrlen);
423			    } else
424				statp->nsaddr_list[nserv].sin_family = 0;
425			    freeaddrinfo(ai);
426			    nserv++;
427			}
428		    }
429		    continue;
430		}
431#ifdef RESOLVSORT
432		if (MATCH(buf, "sortlist")) {
433		    struct in_addr a;
434		    struct in6_addr a6;
435		    int m, i;
436		    u_char *u;
437		    struct __res_state_ext *ext = statp->_u._ext.ext;
438
439		    cp = buf + sizeof("sortlist") - 1;
440		    while (nsort < MAXRESOLVSORT) {
441			while (*cp == ' ' || *cp == '\t')
442			    cp++;
443			if (*cp == '\0' || *cp == '\n' || *cp == ';')
444			    break;
445			net = cp;
446			while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
447			       isascii(*cp) && !isspace((unsigned char)*cp))
448				cp++;
449			n = *cp;
450			*cp = 0;
451			if (inet_aton(net, &a)) {
452			    statp->sort_list[nsort].addr = a;
453			    if (ISSORTMASK(n)) {
454				*cp++ = n;
455				net = cp;
456				while (*cp && *cp != ';' &&
457					isascii(*cp) &&
458					!isspace((unsigned char)*cp))
459				    cp++;
460				n = *cp;
461				*cp = 0;
462				if (inet_aton(net, &a)) {
463				    statp->sort_list[nsort].mask = a.s_addr;
464				} else {
465				    statp->sort_list[nsort].mask =
466					net_mask(statp->sort_list[nsort].addr);
467				}
468			    } else {
469				statp->sort_list[nsort].mask =
470				    net_mask(statp->sort_list[nsort].addr);
471			    }
472			    ext->sort_list[nsort].af = AF_INET;
473			    ext->sort_list[nsort].addr.ina =
474				statp->sort_list[nsort].addr;
475			    ext->sort_list[nsort].mask.ina.s_addr =
476				statp->sort_list[nsort].mask;
477			    nsort++;
478			}
479			else if (inet_pton(AF_INET6, net, &a6) == 1) {
480
481			    ext->sort_list[nsort].af = AF_INET6;
482			    ext->sort_list[nsort].addr.in6a = a6;
483			    u = (u_char *)&ext->sort_list[nsort].mask.in6a;
484			    *cp++ = n;
485			    net = cp;
486			    while (*cp && *cp != ';' &&
487				    isascii(*cp) && !isspace(*cp))
488				cp++;
489			    m = n;
490			    n = *cp;
491			    *cp = 0;
492			    switch (m) {
493			    case '/':
494				m = atoi(net);
495				break;
496			    case '&':
497				if (inet_pton(AF_INET6, net, u) == 1) {
498				    m = -1;
499				    break;
500				}
501				/*FALLTHROUGH*/
502			    default:
503				m = sizeof(struct in6_addr) * CHAR_BIT;
504				break;
505			    }
506			    if (m >= 0) {
507				for (i = 0; i < sizeof(struct in6_addr); i++) {
508				    if (m <= 0) {
509					*u = 0;
510				    } else {
511					m -= CHAR_BIT;
512					*u = (u_char)~0;
513					if (m < 0)
514					    *u <<= -m;
515				    }
516				    u++;
517				}
518			    }
519			    statp->sort_list[nsort].addr.s_addr =
520				(u_int32_t)0xffffffff;
521			    statp->sort_list[nsort].mask =
522				(u_int32_t)0xffffffff;
523			    nsort++;
524			}
525			*cp = n;
526		    }
527		    continue;
528		}
529#endif
530		if (MATCH(buf, "options")) {
531		    res_setoptions(statp, buf + sizeof("options") - 1, "conf");
532		    continue;
533		}
534	    }
535	    if (nserv > 0)
536		statp->nscount = nserv;
537#ifdef RESOLVSORT
538	    statp->nsort = nsort;
539#endif
540	    (void) fclose(fp);
541	}
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 (issetugid())
586		statp->options |= RES_NOALIASES;
587	else if ((cp = getenv("RES_OPTIONS")) != NULL)
588		res_setoptions(statp, cp, "env");
589	statp->options |= RES_INIT;
590	return (statp->res_h_errno);
591}
592
593static void
594res_setoptions(res_state statp, const char *options, const char *source)
595{
596	const char *cp = options;
597	int i;
598	struct __res_state_ext *ext = statp->_u._ext.ext;
599
600#ifdef DEBUG
601	if (statp->options & RES_DEBUG)
602		printf(";; res_setoptions(\"%s\", \"%s\")...\n",
603		       options, source);
604#endif
605	while (*cp) {
606		/* skip leading and inner runs of spaces */
607		while (*cp == ' ' || *cp == '\t')
608			cp++;
609		/* search for and process individual options */
610		if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) {
611			i = atoi(cp + sizeof("ndots:") - 1);
612			if (i <= RES_MAXNDOTS)
613				statp->ndots = i;
614			else
615				statp->ndots = RES_MAXNDOTS;
616#ifdef DEBUG
617			if (statp->options & RES_DEBUG)
618				printf(";;\tndots=%d\n", statp->ndots);
619#endif
620		} else if (!strncmp(cp, "timeout:", sizeof("timeout:") - 1)) {
621			i = atoi(cp + sizeof("timeout:") - 1);
622			if (i <= RES_MAXRETRANS)
623				statp->retrans = i;
624			else
625				statp->retrans = RES_MAXRETRANS;
626#ifdef DEBUG
627			if (statp->options & RES_DEBUG)
628				printf(";;\ttimeout=%d\n", statp->retrans);
629#endif
630#ifdef	SOLARIS2
631		} else if (!strncmp(cp, "retrans:", sizeof("retrans:") - 1)) {
632			/*
633		 	 * For backward compatibility, 'retrans' is
634		 	 * supported as an alias for 'timeout', though
635		 	 * without an imposed maximum.
636		 	 */
637			statp->retrans = atoi(cp + sizeof("retrans:") - 1);
638		} else if (!strncmp(cp, "retry:", sizeof("retry:") - 1)){
639			/*
640			 * For backward compatibility, 'retry' is
641			 * supported as an alias for 'attempts', though
642			 * without an imposed maximum.
643			 */
644			statp->retry = atoi(cp + sizeof("retry:") - 1);
645#endif	/* SOLARIS2 */
646		} else if (!strncmp(cp, "attempts:", sizeof("attempts:") - 1)){
647			i = atoi(cp + sizeof("attempts:") - 1);
648			if (i <= RES_MAXRETRY)
649				statp->retry = i;
650			else
651				statp->retry = RES_MAXRETRY;
652#ifdef DEBUG
653			if (statp->options & RES_DEBUG)
654				printf(";;\tattempts=%d\n", statp->retry);
655#endif
656		} else if (!strncmp(cp, "debug", sizeof("debug") - 1)) {
657#ifdef DEBUG
658			if (!(statp->options & RES_DEBUG)) {
659				printf(";; res_setoptions(\"%s\", \"%s\")..\n",
660				       options, source);
661				statp->options |= RES_DEBUG;
662			}
663			printf(";;\tdebug\n");
664#endif
665		} else if (!strncmp(cp, "no_tld_query",
666				    sizeof("no_tld_query") - 1) ||
667			   !strncmp(cp, "no-tld-query",
668				    sizeof("no-tld-query") - 1)) {
669			statp->options |= RES_NOTLDQUERY;
670		} else if (!strncmp(cp, "inet6", sizeof("inet6") - 1)) {
671			statp->options |= RES_USE_INET6;
672		} else if (!strncmp(cp, "insecure1", sizeof("insecure1") - 1)) {
673		       statp->options |= RES_INSECURE1;
674		} else if (!strncmp(cp, "insecure2", sizeof("insecure2") - 1)) {
675		       statp->options |= RES_INSECURE2;
676		} else if (!strncmp(cp, "rotate", sizeof("rotate") - 1)) {
677			statp->options |= RES_ROTATE;
678		} else if (!strncmp(cp, "no-check-names",
679				    sizeof("no-check-names") - 1)) {
680			statp->options |= RES_NOCHECKNAME;
681		} else if (!strncmp(cp, "reload-period:",
682				    sizeof("reload-period:") - 1)) {
683			if (ext != NULL) {
684				ext->reload_period = (u_short)
685				    atoi(cp + sizeof("reload-period:") - 1);
686			}
687		}
688#ifdef RES_USE_EDNS0
689		else if (!strncmp(cp, "edns0", sizeof("edns0") - 1)) {
690			statp->options |= RES_USE_EDNS0;
691		}
692#endif
693#ifndef _LIBC
694		else if (!strncmp(cp, "dname", sizeof("dname") - 1)) {
695			statp->options |= RES_USE_DNAME;
696		}
697		else if (!strncmp(cp, "nibble:", sizeof("nibble:") - 1)) {
698			if (ext == NULL)
699				goto skip;
700			cp += sizeof("nibble:") - 1;
701			i = MIN(strcspn(cp, " \t"), sizeof(ext->nsuffix) - 1);
702			strncpy(ext->nsuffix, cp, i);
703			ext->nsuffix[i] = '\0';
704		}
705		else if (!strncmp(cp, "nibble2:", sizeof("nibble2:") - 1)) {
706			if (ext == NULL)
707				goto skip;
708			cp += sizeof("nibble2:") - 1;
709			i = MIN(strcspn(cp, " \t"), sizeof(ext->nsuffix2) - 1);
710			strncpy(ext->nsuffix2, cp, i);
711			ext->nsuffix2[i] = '\0';
712		}
713		else if (!strncmp(cp, "v6revmode:", sizeof("v6revmode:") - 1)) {
714			cp += sizeof("v6revmode:") - 1;
715			/* "nibble" and "bitstring" used to be valid */
716			if (!strncmp(cp, "single", sizeof("single") - 1)) {
717				statp->options |= RES_NO_NIBBLE2;
718			} else if (!strncmp(cp, "both", sizeof("both") - 1)) {
719				statp->options &=
720					 ~RES_NO_NIBBLE2;
721			}
722		}
723#endif
724		else {
725			/* XXX - print a warning here? */
726		}
727#ifndef _LIBC
728   skip:
729#endif
730		/* skip to next run of spaces */
731		while (*cp && *cp != ' ' && *cp != '\t')
732			cp++;
733	}
734}
735
736#ifdef RESOLVSORT
737/* XXX - should really support CIDR which means explicit masks always. */
738static u_int32_t
739net_mask(struct in_addr in)		/*!< XXX - should really use system's version of this  */
740{
741	u_int32_t i = ntohl(in.s_addr);
742
743	if (IN_CLASSA(i))
744		return (htonl(IN_CLASSA_NET));
745	else if (IN_CLASSB(i))
746		return (htonl(IN_CLASSB_NET));
747	return (htonl(IN_CLASSC_NET));
748}
749#endif
750
751static u_char srnd[16];
752
753void
754res_rndinit(res_state statp)
755{
756	struct timeval now;
757	u_int32_t u32;
758	u_int16_t u16;
759	u_char *rnd = statp->_rnd == NULL ? srnd : statp->_rnd;
760
761	gettimeofday(&now, NULL);
762	u32 = now.tv_sec;
763	memcpy(rnd, &u32, 4);
764	u32 = now.tv_usec;
765	memcpy(rnd + 4, &u32, 4);
766	u32 += now.tv_sec;
767	memcpy(rnd + 8, &u32, 4);
768	u16 = getpid();
769	memcpy(rnd + 12, &u16, 2);
770}
771
772u_int
773res_nrandomid(res_state statp) {
774	struct timeval now;
775	u_int16_t u16;
776	MD5_CTX ctx;
777	u_char *rnd = statp->_rnd == NULL ? srnd : statp->_rnd;
778
779	gettimeofday(&now, NULL);
780	u16 = (u_int16_t) (now.tv_sec ^ now.tv_usec);
781	memcpy(rnd + 14, &u16, 2);
782#ifndef HAVE_MD5
783	MD5_Init(&ctx);
784	MD5_Update(&ctx, rnd, 16);
785	MD5_Final(rnd, &ctx);
786#else
787	MD5Init(&ctx);
788	MD5Update(&ctx, rnd, 16);
789	MD5Final(rnd, &ctx);
790#endif
791	memcpy(&u16, rnd + 14, 2);
792	return ((u_int) u16);
793}
794
795/*%
796 * This routine is for closing the socket if a virtual circuit is used and
797 * the program wants to close it.  This provides support for endhostent()
798 * which expects to close the socket.
799 *
800 * This routine is not expected to be user visible.
801 */
802void
803res_nclose(res_state statp) {
804	int ns;
805
806	if (statp->_vcsock >= 0) {
807		(void) _close(statp->_vcsock);
808		statp->_vcsock = -1;
809		statp->_flags &= ~(RES_F_VC | RES_F_CONN);
810	}
811	for (ns = 0; ns < statp->_u._ext.nscount; ns++) {
812		if (statp->_u._ext.nssocks[ns] != -1) {
813			(void) _close(statp->_u._ext.nssocks[ns]);
814			statp->_u._ext.nssocks[ns] = -1;
815		}
816	}
817}
818
819void
820res_ndestroy(res_state statp) {
821	res_nclose(statp);
822	if (statp->_u._ext.ext != NULL) {
823		free(statp->_u._ext.ext);
824		statp->_u._ext.ext = NULL;
825	}
826	if (statp->_rnd != NULL) {
827		free(statp->_rnd);
828		statp->_rnd = NULL;
829	}
830	statp->options &= ~RES_INIT;
831}
832
833#ifndef _LIBC
834const char *
835res_get_nibblesuffix(res_state statp) {
836	if (statp->_u._ext.ext)
837		return (statp->_u._ext.ext->nsuffix);
838	return ("ip6.arpa");
839}
840
841const char *
842res_get_nibblesuffix2(res_state statp) {
843	if (statp->_u._ext.ext)
844		return (statp->_u._ext.ext->nsuffix2);
845	return ("ip6.int");
846}
847#endif
848
849void
850res_setservers(res_state statp, const union res_sockaddr_union *set, int cnt) {
851	int i, nserv;
852	size_t size;
853
854	/* close open servers */
855	res_nclose(statp);
856
857	/* cause rtt times to be forgotten */
858	statp->_u._ext.nscount = 0;
859
860	nserv = 0;
861	for (i = 0; i < cnt && nserv < MAXNS; i++) {
862		switch (set->sin.sin_family) {
863		case AF_INET:
864			size = sizeof(set->sin);
865			if (statp->_u._ext.ext)
866				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
867					&set->sin, size);
868			if (size <= sizeof(statp->nsaddr_list[nserv]))
869				memcpy(&statp->nsaddr_list[nserv],
870					&set->sin, size);
871			else
872				statp->nsaddr_list[nserv].sin_family = 0;
873			nserv++;
874			break;
875
876#ifdef HAS_INET6_STRUCTS
877		case AF_INET6:
878			size = sizeof(set->sin6);
879			if (statp->_u._ext.ext)
880				memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
881					&set->sin6, size);
882			if (size <= sizeof(statp->nsaddr_list[nserv]))
883				memcpy(&statp->nsaddr_list[nserv],
884					&set->sin6, size);
885			else
886				statp->nsaddr_list[nserv].sin_family = 0;
887			nserv++;
888			break;
889#endif
890
891		default:
892			break;
893		}
894		set++;
895	}
896	statp->nscount = nserv;
897
898}
899
900int
901res_getservers(res_state statp, union res_sockaddr_union *set, int cnt) {
902	int i;
903	size_t size;
904	u_int16_t family;
905
906	for (i = 0; i < statp->nscount && i < cnt; i++) {
907		if (statp->_u._ext.ext)
908			family = statp->_u._ext.ext->nsaddrs[i].sin.sin_family;
909		else
910			family = statp->nsaddr_list[i].sin_family;
911
912		switch (family) {
913		case AF_INET:
914			size = sizeof(set->sin);
915			if (statp->_u._ext.ext)
916				memcpy(&set->sin,
917				       &statp->_u._ext.ext->nsaddrs[i],
918				       size);
919			else
920				memcpy(&set->sin, &statp->nsaddr_list[i],
921				       size);
922			break;
923
924#ifdef HAS_INET6_STRUCTS
925		case AF_INET6:
926			size = sizeof(set->sin6);
927			if (statp->_u._ext.ext)
928				memcpy(&set->sin6,
929				       &statp->_u._ext.ext->nsaddrs[i],
930				       size);
931			else
932				memcpy(&set->sin6, &statp->nsaddr_list[i],
933				       size);
934			break;
935#endif
936
937		default:
938			set->sin.sin_family = 0;
939			break;
940		}
941		set++;
942	}
943	return (statp->nscount);
944}
945
946/*! \file */
947