1/*
2 * Copyright (c) 1985, 1989, 1993
3 *    The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. 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 * Portions Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
52 * Portions Copyright (c) 1995-2003 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 *   Internet Systems Consortium, Inc.
67 *   950 Charter Street
68 *   Redwood City, CA 94063
69 *   <info@isc.org>
70 *   http://www.isc.org/
71 */
72
73#if defined(LIBC_SCCS) && !defined(lint)
74static const char sccsid[] = "@(#)res_init.c	8.1 (Berkeley) 6/7/93";
75static const char rcsid[] = "$Id: res_init.c,v 1.5 2007/05/27 16:27:57 tls Exp $";
76#endif /* LIBC_SCCS and not lint */
77
78#include <sys/types.h>
79#include <sys/param.h>
80#include <sys/socket.h>
81#include <sys/time.h>
82
83#include <netinet/in.h>
84#include <arpa/inet.h>
85
86#include <ctype.h>
87#include <stdio.h>
88#include <stdlib.h>
89#include <string.h>
90#include <unistd.h>
91
92#include "minires/minires.h"
93#include "omapip/trace_mr.h"
94#include "arpa/nameser.h"
95
96/* Options.  Should all be left alone. */
97#define RESOLVSORT
98#define RFC1535
99#define DEBUG
100
101static void res_setoptions (res_state, const char *, const char *);
102
103#ifdef RESOLVSORT
104static const char sort_mask[] = "/&";
105#define ISSORTMASK(ch) (strchr(sort_mask, ch) != NULL)
106static u_int32_t net_mask (struct in_addr);
107#endif
108
109#if !defined(isascii)	/* XXX - could be a function */
110# define isascii(c) (!(c & 0200))
111#endif
112
113/*
114 * Resolver state default settings.
115 */
116
117/*
118 * Set up default settings.  If the configuration file exist, the values
119 * there will have precedence.  Otherwise, the server address is set to
120 * INADDR_ANY and the default domain name comes from the gethostname().
121 *
122 * An interrim version of this code (BIND 4.9, pre-4.4BSD) used 127.0.0.1
123 * rather than INADDR_ANY ("0.0.0.0") as the default name server address
124 * since it was noted that INADDR_ANY actually meant ``the first interface
125 * you "ifconfig"'d at boot time'' and if this was a SLIP or PPP interface,
126 * it had to be "up" in order for you to reach your own name server.  It
127 * was later decided that since the recommended practice is to always
128 * install local static routes through 127.0.0.1 for all your network
129 * interfaces, that we could solve this problem without a code change.
130 *
131 * The configuration file should always be used, since it is the only way
132 * to specify a default domain.  If you are running a server on your local
133 * machine, you should say "nameserver 0.0.0.0" or "nameserver 127.0.0.1"
134 * in the configuration file.
135 *
136 * Return 0 if completes successfully, -1 on error
137 */
138extern int minires_vinit(res_state, int);
139
140#if defined (TRACING)
141u_int trace_mr_res_randomid(u_int);
142#endif
143
144int
145res_ninit(res_state statp) {
146
147	return (minires_vinit(statp, 0));
148}
149
150/* This function has to be reachable by res_data.c but not publically. */
151int
152minires_vinit(res_state statp, int preinit) {
153	register FILE *fp;
154	register char *cp, **pp;
155	register int n;
156	char buf[BUFSIZ];
157	int nserv = 0;    /* number of nameserver records read from file */
158	int haveenv = 0;
159	int havesearch = 0;
160#ifdef RESOLVSORT
161	int nsort = 0;
162	char *net;
163#endif
164#ifndef RFC1535
165	int dots;
166#endif
167
168	if (!preinit) {
169		statp->retrans = RES_TIMEOUT;
170		statp->retry = RES_DFLRETRY;
171		statp->options = RES_DEFAULT;
172		statp->id = res_randomid();
173#if defined (TRACING)
174		statp->id = trace_mr_res_randomid (statp -> id);
175#endif
176	}
177
178#ifdef USELOOPBACK
179	statp->nsaddr.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
180#else
181	statp->nsaddr.sin_addr.s_addr = INADDR_ANY;
182#endif
183	statp->nsaddr.sin_family = AF_INET;
184	statp->nsaddr.sin_port = htons(NAMESERVER_PORT);
185	statp->nscount = 1;
186	statp->ndots = 1;
187	statp->pfcode = 0;
188	statp->_sock = -1;
189	statp->_flags = 0;
190	statp->qhook = NULL;
191	statp->rhook = NULL;
192
193	/* Allow user to override the local domain definition */
194	if ((cp = getenv("LOCALDOMAIN")) != NULL) {
195		(void)strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
196		statp->defdname[sizeof(statp->defdname) - 1] = '\0';
197		haveenv++;
198
199		/*
200		 * Set search list to be blank-separated strings
201		 * from rest of env value.  Permits users of LOCALDOMAIN
202		 * to still have a search list, and anyone to set the
203		 * one that they want to use as an individual (even more
204		 * important now that the rfc1535 stuff restricts searches)
205		 */
206		cp = statp->defdname;
207		pp = statp->dnsrch;
208		*pp++ = cp;
209		for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
210			if (*cp == '\n')	/* silly backwards compat */
211				break;
212			else if (*cp == ' ' || *cp == '\t') {
213				*cp = 0;
214				n = 1;
215			} else if (n) {
216				*pp++ = cp;
217				n = 0;
218				havesearch = 1;
219			}
220		}
221		/* null terminate last domain if there are excess */
222		while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
223			cp++;
224		*cp = '\0';
225		*pp++ = 0;
226	}
227
228#define	MATCH(line, name) \
229	(!strncmp(line, name, sizeof(name) - 1) && \
230	(line[sizeof(name) - 1] == ' ' || \
231	 line[sizeof(name) - 1] == '\t'))
232
233	if ((fp = fopen(_PATH_RESCONF, "r")) != NULL) {
234	    /* read the config file */
235	    while (fgets(buf, sizeof(buf), fp) != NULL) {
236		/* skip comments */
237		if (*buf == ';' || *buf == '#')
238			continue;
239		/* read default domain name */
240		if (MATCH(buf, "domain")) {
241		    if (haveenv)	/* skip if have from environ */
242			    continue;
243		    cp = buf + sizeof("domain") - 1;
244		    while (*cp == ' ' || *cp == '\t')
245			    cp++;
246		    if ((*cp == '\0') || (*cp == '\n'))
247			    continue;
248		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
249		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
250		    if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL)
251			    *cp = '\0';
252		    havesearch = 0;
253		    continue;
254		}
255		/* set search list */
256		if (MATCH(buf, "search")) {
257		    if (haveenv)	/* skip if have from environ */
258			    continue;
259		    cp = buf + sizeof("search") - 1;
260		    while (*cp == ' ' || *cp == '\t')
261			    cp++;
262		    if ((*cp == '\0') || (*cp == '\n'))
263			    continue;
264		    strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
265		    statp->defdname[sizeof(statp->defdname) - 1] = '\0';
266		    if ((cp = strchr(statp->defdname, '\n')) != NULL)
267			    *cp = '\0';
268		    /*
269		     * Set search list to be blank-separated strings
270		     * on rest of line.
271		     */
272		    cp = statp->defdname;
273		    pp = statp->dnsrch;
274		    *pp++ = cp;
275		    for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
276			    if (*cp == ' ' || *cp == '\t') {
277				    *cp = 0;
278				    n = 1;
279			    } else if (n) {
280				    *pp++ = cp;
281				    n = 0;
282			    }
283		    }
284		    /* null terminate last domain if there are excess */
285		    while (*cp != '\0' && *cp != ' ' && *cp != '\t')
286			    cp++;
287		    *cp = '\0';
288		    *pp++ = 0;
289		    havesearch = 1;
290		    continue;
291		}
292		/* read nameservers to query */
293		if (MATCH(buf, "nameserver") && nserv < MAXNS) {
294		    struct in_addr a;
295
296		    cp = buf + sizeof("nameserver") - 1;
297		    while (*cp == ' ' || *cp == '\t')
298			cp++;
299		    if ((*cp != '\0') && (*cp != '\n') && inet_aton(cp, &a)) {
300			statp->nsaddr_list[nserv].sin_addr = a;
301			statp->nsaddr_list[nserv].sin_family = AF_INET;
302			statp->nsaddr_list[nserv].sin_port =
303				htons(NAMESERVER_PORT);
304			nserv++;
305		    }
306		    continue;
307		}
308#ifdef RESOLVSORT
309		if (MATCH(buf, "sortlist")) {
310		    struct in_addr a;
311
312		    cp = buf + sizeof("sortlist") - 1;
313		    while (nsort < MAXRESOLVSORT) {
314			while (*cp == ' ' || *cp == '\t')
315			    cp++;
316			if (*cp == '\0' || *cp == '\n' || *cp == ';')
317			    break;
318			net = cp;
319			while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
320			       !isspace((unsigned char)*cp))
321				cp++;
322			n = *cp;
323			*cp = 0;
324			if (inet_aton(net, &a)) {
325			    statp->sort_list[nsort].addr = a;
326			    if (ISSORTMASK(n)) {
327				*cp++ = n;
328				net = cp;
329				while (*cp && *cp != ';' &&
330					!isspace((unsigned char)*cp))
331				    cp++;
332				n = *cp;
333				*cp = 0;
334				if (inet_aton(net, &a)) {
335				    statp->sort_list[nsort].mask = a.s_addr;
336				} else {
337				    statp->sort_list[nsort].mask =
338					net_mask(statp->sort_list[nsort].addr);
339				}
340			    } else {
341				statp->sort_list[nsort].mask =
342				    net_mask(statp->sort_list[nsort].addr);
343			    }
344			    nsort++;
345			}
346			*cp = n;
347		    }
348		    continue;
349		}
350#endif
351		if (MATCH(buf, "options")) {
352		    res_setoptions(statp, buf + sizeof("options") - 1, "conf");
353		    continue;
354		}
355	    }
356	    if (nserv > 1)
357		statp->nscount = nserv;
358#ifdef RESOLVSORT
359	    statp->nsort = nsort;
360#endif
361	    (void) fclose(fp);
362	}
363	if (statp->defdname[0] == 0 &&
364	    gethostname(buf, sizeof(statp->defdname) - 1) == 0 &&
365	    (cp = strchr(buf, '.')) != NULL)
366		strcpy(statp->defdname, cp + 1);
367
368	/* find components of local domain that might be searched */
369	if (havesearch == 0) {
370		pp = statp->dnsrch;
371		*pp++ = statp->defdname;
372		*pp = NULL;
373
374#ifndef RFC1535
375		dots = 0;
376		for (cp = statp->defdname; *cp; cp++)
377			dots += (*cp == '.');
378
379		cp = statp->defdname;
380		while (pp < statp->dnsrch + MAXDFLSRCH) {
381			if (dots < LOCALDOMAINPARTS)
382				break;
383			cp = strchr(cp, '.') + 1;    /* we know there is one */
384			*pp++ = cp;
385			dots--;
386		}
387		*pp = NULL;
388#ifdef DEBUG
389		if (statp->options & RES_DEBUG) {
390			printf(";; res_init()... default dnsrch list:\n");
391			for (pp = statp->dnsrch; *pp; pp++)
392				printf(";;\t%s\n", *pp);
393			printf(";;\t..END..\n");
394		}
395#endif
396#endif /* !RFC1535 */
397	}
398
399	if ((cp = getenv("RES_OPTIONS")) != NULL)
400		res_setoptions(statp, cp, "env");
401	statp->options |= RES_INIT;
402	return (0);
403}
404
405static void
406res_setoptions(res_state statp, const char *options, const char *source) {
407	const char *cp = options;
408	int i;
409
410#ifdef DEBUG
411	if (statp->options & RES_DEBUG)
412		printf(";; res_setoptions(\"%s\", \"%s\")...\n",
413		       options, source);
414#endif
415	while (*cp) {
416		/* skip leading and inner runs of spaces */
417		while (*cp == ' ' || *cp == '\t')
418			cp++;
419		/* search for and process individual options */
420		if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) {
421			i = atoi(cp + sizeof("ndots:") - 1);
422			if (i <= RES_MAXNDOTS)
423				statp->ndots = i;
424			else
425				statp->ndots = RES_MAXNDOTS;
426#ifdef DEBUG
427			if (statp->options & RES_DEBUG)
428				printf(";;\tndots=%d\n", statp->ndots);
429#endif
430		} else if (!strncmp(cp, "timeout:", sizeof("timeout:") - 1)) {
431			i = atoi(cp + sizeof("timeout:") - 1);
432			if (i <= RES_MAXRETRANS)
433				statp->retrans = i;
434			else
435				statp->retrans = RES_MAXRETRANS;
436		} else if (!strncmp(cp, "attempts:", sizeof("attempts:") - 1)){
437			i = atoi(cp + sizeof("attempts:") - 1);
438			if (i <= RES_MAXRETRY)
439				statp->retry = i;
440			else
441				statp->retry = RES_MAXRETRY;
442		} else if (!strncmp(cp, "debug", sizeof("debug") - 1)) {
443#ifdef DEBUG
444			if (!(statp->options & RES_DEBUG)) {
445				printf(";; res_setoptions(\"%s\", \"%s\")..\n",
446				       options, source);
447				statp->options |= RES_DEBUG;
448			}
449			printf(";;\tdebug\n");
450#endif
451		} else if (!strncmp(cp, "inet6", sizeof("inet6") - 1)) {
452			statp->options |= RES_USE_INET6;
453		} else if (!strncmp(cp, "rotate", sizeof("rotate") - 1)) {
454			statp->options |= RES_ROTATE;
455		} else if (!strncmp(cp, "no-check-names",
456				    sizeof("no-check-names") - 1)) {
457			statp->options |= RES_NOCHECKNAME;
458		} else {
459			/* XXX - print a warning here? */
460		}
461		/* skip to next run of spaces */
462		while (*cp && *cp != ' ' && *cp != '\t')
463			cp++;
464	}
465}
466
467#ifdef RESOLVSORT
468/* XXX - should really support CIDR which means explicit masks always. */
469static u_int32_t
470net_mask(in)		/* XXX - should really use system's version of this */
471	struct in_addr in;
472{
473	register u_int32_t i = ntohl(in.s_addr);
474
475	if (IN_CLASSA(i))
476		return (htonl(IN_CLASSA_NET));
477	else if (IN_CLASSB(i))
478		return (htonl(IN_CLASSB_NET));
479	return (htonl(IN_CLASSC_NET));
480}
481#endif
482
483u_int
484res_randomid(void) {
485	struct timeval now;
486
487	gettimeofday(&now, NULL);
488	return (0xffff & (now.tv_sec ^ now.tv_usec ^ getpid()));
489}
490