Libinfo-406.17.tar.gz
[apple/libinfo.git] / dns.subproj / res_init.c
1 /*
2 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * Portions Copyright (c) 1999 Apple Computer, Inc. All Rights
7 * Reserved. This file contains Original Code and/or Modifications of
8 * Original Code as defined in and that are subject to the Apple Public
9 * Source License Version 1.1 (the "License"). You may not use this file
10 * except in compliance with the License. Please obtain a copy of the
11 * License at http://www.apple.com/publicsource and read it before using
12 * this file.
13 *
14 * The Original Code and all software distributed under the License are
15 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE OR NON- INFRINGEMENT. Please see the
19 * License for the specific language governing rights and limitations
20 * under the License.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24 /*
25 * ++Copyright++ 1985, 1989, 1993
26 * -
27 * Copyright (c) 1985, 1989, 1993
28 * The Regents of the University of California. All rights reserved.
29 *
30 * Redistribution and use in source and binary forms, with or without
31 * modification, are permitted provided that the following conditions
32 * are met:
33 * 1. Redistributions of source code must retain the above copyright
34 * notice, this list of conditions and the following disclaimer.
35 * 2. Redistributions in binary form must reproduce the above copyright
36 * notice, this list of conditions and the following disclaimer in the
37 * documentation and/or other materials provided with the distribution.
38 * 3. All advertising materials mentioning features or use of this software
39 * must display the following acknowledgement:
40 * This product includes software developed by the University of
41 * California, Berkeley and its contributors.
42 * 4. Neither the name of the University nor the names of its contributors
43 * may be used to endorse or promote products derived from this software
44 * without specific prior written permission.
45 *
46 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
47 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
50 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
51 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
52 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
53 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
54 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
55 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
56 * SUCH DAMAGE.
57 * -
58 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
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, and that
63 * the name of Digital Equipment Corporation not be used in advertising or
64 * publicity pertaining to distribution of the document or software without
65 * specific, written prior permission.
66 *
67 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
68 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
69 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
70 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
71 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
72 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
73 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
74 * SOFTWARE.
75 * -
76 * --Copyright--
77 */
78
79 #if defined(LIBC_SCCS) && !defined(lint)
80 static char sccsid[] = "@(#)res_init.c 8.1 (Berkeley) 6/7/93";
81 static char rcsid[] = "$Id: res_init.c,v 1.8 2003/02/18 17:29:24 majka Exp $";
82 #endif /* LIBC_SCCS and not lint */
83
84 #include <sys/param.h>
85 #include <sys/socket.h>
86 #include <sys/time.h>
87 #include <netinet/in.h>
88 #include <arpa/inet.h>
89
90 #include <stdio.h>
91 #include <ctype.h>
92
93 #include "nameser8_compat.h"
94 #include "resolv8_compat.h"
95
96 #if defined(BSD) && (BSD >= 199103)
97 # include <unistd.h>
98 # include <stdlib.h>
99 # include <string.h>
100 #else
101 # include "portability.h"
102 #endif
103
104 #if defined(USE_OPTIONS_H)
105 # include "options.h"
106 #endif
107
108 static void res_setoptions __P((char *, char *));
109
110 #ifdef RESOLVSORT
111 static const char sort_mask[] = "/&";
112 #define ISSORTMASK(ch) (strchr(sort_mask, ch) != NULL)
113 static u_int32_t net_mask __P((struct in_addr));
114 #endif
115
116 #if !defined(isascii) /* XXX - could be a function */
117 # define isascii(c) (!(c & 0200))
118 #endif
119
120 /*
121 * Resolver state default settings.
122 */
123
124 #if defined(__APPLE__)
125 extern
126 #endif /* NeXT */
127 struct __res_state _res;
128
129 /*
130 * Set up default settings. If the configuration file exist, the values
131 * there will have precedence. Otherwise, the server address is set to
132 * INADDR_ANY and the default domain name comes from the gethostname().
133 *
134 * An interrim version of this code (BIND 4.9, pre-4.4BSD) used 127.0.0.1
135 * rather than INADDR_ANY ("0.0.0.0") as the default name server address
136 * since it was noted that INADDR_ANY actually meant ``the first interface
137 * you "ifconfig"'d at boot time'' and if this was a SLIP or PPP interface,
138 * it had to be "up" in order for you to reach your own name server. It
139 * was later decided that since the recommended practice is to always
140 * install local static routes through 127.0.0.1 for all your network
141 * interfaces, that we could solve this problem without a code change.
142 *
143 * The configuration file should always be used, since it is the only way
144 * to specify a default domain. If you are running a server on your local
145 * machine, you should say "nameserver 0.0.0.0" or "nameserver 127.0.0.1"
146 * in the configuration file.
147 *
148 * Return 0 if completes successfully, -1 on error
149 */
150 int
151 res_init()
152 {
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 /*
169 * These three fields used to be statically initialized. This made
170 * it hard to use this code in a shared library. It is necessary,
171 * now that we're doing dynamic initialization here, that we preserve
172 * the old semantics: if an application modifies one of these three
173 * fields of _res before res_init() is called, res_init() will not
174 * alter them. Of course, if an application is setting them to
175 * _zero_ before calling res_init(), hoping to override what used
176 * to be the static default, we can't detect it and unexpected results
177 * will follow. Zero for any of these fields would make no sense,
178 * so one can safely assume that the applications were already getting
179 * unexpected results.
180 *
181 * _res.options is tricky since some apps were known to diddle the bits
182 * before res_init() was first called. We can't replicate that semantic
183 * with dynamic initialization (they may have turned bits off that are
184 * set in RES_DEFAULT). Our solution is to declare such applications
185 * "broken". They could fool us by setting RES_INIT but none do (yet).
186 */
187 if (!_res.retrans)
188 _res.retrans = RES_TIMEOUT;
189 if (!_res.retry)
190 _res.retry = 4;
191 if (!(_res.options & RES_INIT))
192 _res.options = RES_DEFAULT;
193
194 /*
195 * This one used to initialize implicitly to zero, so unless the app
196 * has set it to something in particular, we can randomize it now.
197 */
198 if (!_res.id)
199 _res.id = res_randomid();
200
201 #ifdef USELOOPBACK
202 _res.nsaddr.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
203 #else
204 _res.nsaddr.sin_addr.s_addr = INADDR_ANY;
205 #endif
206 _res.nsaddr.sin_family = AF_INET;
207 _res.nsaddr.sin_port = htons(NAMESERVER_PORT);
208 _res.nscount = 1;
209 _res.ndots = 1;
210 _res.pfcode = 0;
211
212 /* Allow user to override the local domain definition */
213 if ((cp = getenv("LOCALDOMAIN")) != NULL) {
214 (void)strncpy(_res.defdname, cp, sizeof(_res.defdname) - 1);
215 haveenv++;
216
217 /*
218 * Set search list to be blank-separated strings
219 * from rest of env value. Permits users of LOCALDOMAIN
220 * to still have a search list, and anyone to set the
221 * one that they want to use as an individual (even more
222 * important now that the rfc1535 stuff restricts searches)
223 */
224 cp = _res.defdname;
225 pp = _res.dnsrch;
226 *pp++ = cp;
227 for (n = 0; *cp && pp < _res.dnsrch + MAXDNSRCH; cp++) {
228 if (*cp == '\n') /* silly backwards compat */
229 break;
230 else if (*cp == ' ' || *cp == '\t') {
231 *cp = 0;
232 n = 1;
233 } else if (n) {
234 *pp++ = cp;
235 n = 0;
236 havesearch = 1;
237 }
238 }
239 /* null terminate last domain if there are excess */
240 while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
241 cp++;
242 *cp = '\0';
243 *pp++ = 0;
244 }
245
246 #define MATCH(line, name) \
247 (!strncmp(line, name, sizeof(name) - 1) && \
248 (line[sizeof(name) - 1] == ' ' || \
249 line[sizeof(name) - 1] == '\t'))
250
251 if ((fp = fopen(_PATH_RESCONF, "r")) != NULL) {
252 /* read the config file */
253 while (fgets(buf, sizeof(buf), fp) != NULL) {
254 /* skip comments */
255 if (*buf == ';' || *buf == '#')
256 continue;
257 /* read default domain name */
258 if (MATCH(buf, "domain")) {
259 if (haveenv) /* skip if have from environ */
260 continue;
261 cp = buf + sizeof("domain") - 1;
262 while (*cp == ' ' || *cp == '\t')
263 cp++;
264 if ((*cp == '\0') || (*cp == '\n'))
265 continue;
266 strncpy(_res.defdname, cp, sizeof(_res.defdname) - 1);
267 if ((cp = strpbrk(_res.defdname, " \t\n")) != NULL)
268 *cp = '\0';
269 havesearch = 0;
270 continue;
271 }
272 /* set search list */
273 if (MATCH(buf, "search")) {
274 if (haveenv) /* skip if have from environ */
275 continue;
276 cp = buf + sizeof("search") - 1;
277 while (*cp == ' ' || *cp == '\t')
278 cp++;
279 if ((*cp == '\0') || (*cp == '\n'))
280 continue;
281 strncpy(_res.defdname, cp, sizeof(_res.defdname) - 1);
282 if ((cp = strchr(_res.defdname, '\n')) != NULL)
283 *cp = '\0';
284 /*
285 * Set search list to be blank-separated strings
286 * on rest of line.
287 */
288 cp = _res.defdname;
289 pp = _res.dnsrch;
290 *pp++ = cp;
291 for (n = 0; *cp && pp < _res.dnsrch + MAXDNSRCH; cp++) {
292 if (*cp == ' ' || *cp == '\t') {
293 *cp = 0;
294 n = 1;
295 } else if (n) {
296 *pp++ = cp;
297 n = 0;
298 }
299 }
300 /* null terminate last domain if there are excess */
301 while (*cp != '\0' && *cp != ' ' && *cp != '\t')
302 cp++;
303 *cp = '\0';
304 *pp++ = 0;
305 havesearch = 1;
306 continue;
307 }
308 /* read nameservers to query */
309 if (MATCH(buf, "nameserver") && nserv < MAXNS) {
310 struct in_addr a;
311
312 cp = buf + sizeof("nameserver") - 1;
313 while (*cp == ' ' || *cp == '\t')
314 cp++;
315 if ((*cp != '\0') && (*cp != '\n') && inet_aton(cp, &a)) {
316 _res.nsaddr_list[nserv].sin_addr = a;
317 _res.nsaddr_list[nserv].sin_family = AF_INET;
318 _res.nsaddr_list[nserv].sin_port =
319 htons(NAMESERVER_PORT);
320 nserv++;
321 }
322 continue;
323 }
324 #ifdef RESOLVSORT
325 if (MATCH(buf, "sortlist")) {
326 struct in_addr a;
327
328 cp = buf + sizeof("sortlist") - 1;
329 while (nsort < MAXRESOLVSORT) {
330 while (*cp == ' ' || *cp == '\t')
331 cp++;
332 if (*cp == '\0' || *cp == '\n' || *cp == ';')
333 break;
334 net = cp;
335 while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
336 isascii(*cp) && !isspace(*cp))
337 cp++;
338 n = *cp;
339 *cp = 0;
340 if (inet_aton(net, &a)) {
341 _res.sort_list[nsort].addr = a;
342 if (ISSORTMASK(n)) {
343 *cp++ = n;
344 net = cp;
345 while (*cp && *cp != ';' &&
346 isascii(*cp) && !isspace(*cp))
347 cp++;
348 n = *cp;
349 *cp = 0;
350 if (inet_aton(net, &a)) {
351 _res.sort_list[nsort].mask = a.s_addr;
352 } else {
353 _res.sort_list[nsort].mask =
354 net_mask(_res.sort_list[nsort].addr);
355 }
356 } else {
357 _res.sort_list[nsort].mask =
358 net_mask(_res.sort_list[nsort].addr);
359 }
360 nsort++;
361 }
362 *cp = n;
363 }
364 continue;
365 }
366 #endif
367 if (MATCH(buf, "options")) {
368 res_setoptions(buf + sizeof("options") - 1, "conf");
369 continue;
370 }
371 }
372 if (nserv > 1)
373 _res.nscount = nserv;
374 #ifdef RESOLVSORT
375 _res.nsort = nsort;
376 #endif
377 (void) fclose(fp);
378 }
379
380 if (_res.defdname[0] == 0 &&
381 gethostname(buf, sizeof(_res.defdname) - 1) == 0 &&
382 (cp = strchr(buf, '.')) != NULL)
383 strcpy(_res.defdname, cp + 1);
384
385 /* find components of local domain that might be searched */
386 if (havesearch == 0) {
387 pp = _res.dnsrch;
388 *pp++ = _res.defdname;
389 *pp = NULL;
390
391 #ifndef RFC1535
392 dots = 0;
393 for (cp = _res.defdname; *cp; cp++)
394 dots += (*cp == '.');
395
396 cp = _res.defdname;
397 while (pp < _res.dnsrch + MAXDFLSRCH) {
398 if (dots < LOCALDOMAINPARTS)
399 break;
400 cp = strchr(cp, '.') + 1; /* we know there is one */
401 *pp++ = cp;
402 dots--;
403 }
404 *pp = NULL;
405 #ifdef DEBUG
406 if (_res.options & RES_DEBUG) {
407 printf(";; res_init()... default dnsrch list:\n");
408 for (pp = _res.dnsrch; *pp; pp++)
409 printf(";;\t%s\n", *pp);
410 printf(";;\t..END..\n");
411 }
412 #endif /* DEBUG */
413 #endif /* !RFC1535 */
414 }
415
416 if ((cp = getenv("RES_OPTIONS")) != NULL)
417 res_setoptions(cp, "env");
418 _res.options |= RES_INIT;
419 return (0);
420 }
421
422 static void
423 res_setoptions(options, source)
424 char *options, *source;
425 {
426 char *cp = options;
427 int i;
428
429 #ifdef DEBUG
430 if (_res.options & RES_DEBUG)
431 printf(";; res_setoptions(\"%s\", \"%s\")...\n",
432 options, source);
433 #endif
434 while (*cp) {
435 /* skip leading and inner runs of spaces */
436 while (*cp == ' ' || *cp == '\t')
437 cp++;
438 /* search for and process individual options */
439 if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) {
440 i = atoi(cp + sizeof("ndots:") - 1);
441 if (i <= RES_MAXNDOTS)
442 _res.ndots = i;
443 else
444 _res.ndots = RES_MAXNDOTS;
445 #ifdef DEBUG
446 if (_res.options & RES_DEBUG)
447 printf(";;\tndots=%d\n", _res.ndots);
448 #endif
449 } else if (!strncmp(cp, "debug", sizeof("debug") - 1)) {
450 #ifdef DEBUG
451 if (!(_res.options & RES_DEBUG)) {
452 printf(";; res_setoptions(\"%s\", \"%s\")..\n",
453 options, source);
454 _res.options |= RES_DEBUG;
455 }
456 printf(";;\tdebug\n");
457 #endif
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. */
469 static u_int32_t
470 net_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
483 u_int16_t
484 res_randomid()
485 {
486 struct timeval now;
487
488 gettimeofday(&now, NULL);
489 return (0xffff & (now.tv_sec ^ now.tv_usec ^ getpid()));
490 }