Initial import from FreeBSD RELENG_4:
[dragonfly.git] / contrib / isc-dhcp / minires / res_init.c
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. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
36  * 
37  * Permission to use, copy, modify, and distribute this software for any
38  * purpose with or without fee is hereby granted, provided that the above
39  * copyright notice and this permission notice appear in all copies, and that
40  * the name of Digital Equipment Corporation not be used in advertising or
41  * publicity pertaining to distribution of the document or software without
42  * specific, written prior permission.
43  * 
44  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
45  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
46  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
47  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
48  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
49  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
50  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
51  * SOFTWARE.
52  */
53
54 /*
55  * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
56  *
57  * Permission to use, copy, modify, and distribute this software for any
58  * purpose with or without fee is hereby granted, provided that the above
59  * copyright notice and this permission notice appear in all copies.
60  *
61  * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
62  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
63  * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
64  * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
65  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
66  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
67  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
68  * SOFTWARE.
69  */
70
71 #if defined(LIBC_SCCS) && !defined(lint)
72 static const char sccsid[] = "@(#)res_init.c    8.1 (Berkeley) 6/7/93";
73 static const char rcsid[] = "$Id: res_init.c,v 1.4.2.1 2001/06/22 02:57:54 mellon Exp $";
74 #endif /* LIBC_SCCS and not lint */
75
76 #include <sys/types.h>
77 #include <sys/param.h>
78 #include <sys/socket.h>
79 #include <sys/time.h>
80
81 #include <netinet/in.h>
82 #include <arpa/inet.h>
83
84 #include <ctype.h>
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #include <unistd.h>
89
90 #include "minires/minires.h"
91 #include "arpa/nameser.h"
92
93 /* Options.  Should all be left alone. */
94 #define RESOLVSORT
95 #define RFC1535
96 #define DEBUG
97
98 static void res_setoptions (res_state, const char *, const char *);
99
100 #ifdef RESOLVSORT
101 static const char sort_mask[] = "/&";
102 #define ISSORTMASK(ch) (strchr(sort_mask, ch) != NULL)
103 static u_int32_t net_mask (struct in_addr);
104 #endif
105
106 #if !defined(isascii)   /* XXX - could be a function */
107 # define isascii(c) (!(c & 0200))
108 #endif
109
110 /*
111  * Resolver state default settings.
112  */
113
114 /*
115  * Set up default settings.  If the configuration file exist, the values
116  * there will have precedence.  Otherwise, the server address is set to
117  * INADDR_ANY and the default domain name comes from the gethostname().
118  *
119  * An interrim version of this code (BIND 4.9, pre-4.4BSD) used 127.0.0.1
120  * rather than INADDR_ANY ("0.0.0.0") as the default name server address
121  * since it was noted that INADDR_ANY actually meant ``the first interface
122  * you "ifconfig"'d at boot time'' and if this was a SLIP or PPP interface,
123  * it had to be "up" in order for you to reach your own name server.  It
124  * was later decided that since the recommended practice is to always 
125  * install local static routes through 127.0.0.1 for all your network
126  * interfaces, that we could solve this problem without a code change.
127  *
128  * The configuration file should always be used, since it is the only way
129  * to specify a default domain.  If you are running a server on your local
130  * machine, you should say "nameserver 0.0.0.0" or "nameserver 127.0.0.1"
131  * in the configuration file.
132  *
133  * Return 0 if completes successfully, -1 on error
134  */
135 extern int minires_vinit(res_state, int);
136
137 #if defined (TRACING)
138 u_int trace_mr_res_randomid(u_int);
139 #endif
140
141 int
142 res_ninit(res_state statp) {
143
144         return (minires_vinit(statp, 0));
145 }
146
147 /* This function has to be reachable by res_data.c but not publically. */
148 int
149 minires_vinit(res_state statp, int preinit) {
150         register FILE *fp;
151         register char *cp, **pp;
152         register int n;
153         char buf[BUFSIZ];
154         int nserv = 0;    /* number of nameserver records read from file */
155         int haveenv = 0;
156         int havesearch = 0;
157 #ifdef RESOLVSORT
158         int nsort = 0;
159         char *net;
160 #endif
161 #ifndef RFC1535
162         int dots;
163 #endif
164
165         if (!preinit) {
166                 statp->retrans = RES_TIMEOUT;
167                 statp->retry = RES_DFLRETRY;
168                 statp->options = RES_DEFAULT;
169                 statp->id = res_randomid();
170 #if defined (TRACING)
171                 statp->id = trace_mr_res_randomid (statp -> id);
172 #endif
173         }
174
175 #ifdef USELOOPBACK
176         statp->nsaddr.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
177 #else
178         statp->nsaddr.sin_addr.s_addr = INADDR_ANY;
179 #endif
180         statp->nsaddr.sin_family = AF_INET;
181         statp->nsaddr.sin_port = htons(NAMESERVER_PORT);
182         statp->nscount = 1;
183         statp->ndots = 1;
184         statp->pfcode = 0;
185         statp->_sock = -1;
186         statp->_flags = 0;
187         statp->qhook = NULL;
188         statp->rhook = NULL;
189
190         /* Allow user to override the local domain definition */
191         if ((cp = getenv("LOCALDOMAIN")) != NULL) {
192                 (void)strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
193                 statp->defdname[sizeof(statp->defdname) - 1] = '\0';
194                 haveenv++;
195
196                 /*
197                  * Set search list to be blank-separated strings
198                  * from rest of env value.  Permits users of LOCALDOMAIN
199                  * to still have a search list, and anyone to set the
200                  * one that they want to use as an individual (even more
201                  * important now that the rfc1535 stuff restricts searches)
202                  */
203                 cp = statp->defdname;
204                 pp = statp->dnsrch;
205                 *pp++ = cp;
206                 for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
207                         if (*cp == '\n')        /* silly backwards compat */
208                                 break;
209                         else if (*cp == ' ' || *cp == '\t') {
210                                 *cp = 0;
211                                 n = 1;
212                         } else if (n) {
213                                 *pp++ = cp;
214                                 n = 0;
215                                 havesearch = 1;
216                         }
217                 }
218                 /* null terminate last domain if there are excess */
219                 while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
220                         cp++;
221                 *cp = '\0';
222                 *pp++ = 0;
223         }
224
225 #define MATCH(line, name) \
226         (!strncmp(line, name, sizeof(name) - 1) && \
227         (line[sizeof(name) - 1] == ' ' || \
228          line[sizeof(name) - 1] == '\t'))
229
230         if ((fp = fopen(_PATH_RESCONF, "r")) != NULL) {
231             /* read the config file */
232             while (fgets(buf, sizeof(buf), fp) != NULL) {
233                 /* skip comments */
234                 if (*buf == ';' || *buf == '#')
235                         continue;
236                 /* read default domain name */
237                 if (MATCH(buf, "domain")) {
238                     if (haveenv)        /* skip if have from environ */
239                             continue;
240                     cp = buf + sizeof("domain") - 1;
241                     while (*cp == ' ' || *cp == '\t')
242                             cp++;
243                     if ((*cp == '\0') || (*cp == '\n'))
244                             continue;
245                     strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
246                     statp->defdname[sizeof(statp->defdname) - 1] = '\0';
247                     if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL)
248                             *cp = '\0';
249                     havesearch = 0;
250                     continue;
251                 }
252                 /* set search list */
253                 if (MATCH(buf, "search")) {
254                     if (haveenv)        /* skip if have from environ */
255                             continue;
256                     cp = buf + sizeof("search") - 1;
257                     while (*cp == ' ' || *cp == '\t')
258                             cp++;
259                     if ((*cp == '\0') || (*cp == '\n'))
260                             continue;
261                     strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
262                     statp->defdname[sizeof(statp->defdname) - 1] = '\0';
263                     if ((cp = strchr(statp->defdname, '\n')) != NULL)
264                             *cp = '\0';
265                     /*
266                      * Set search list to be blank-separated strings
267                      * on rest of line.
268                      */
269                     cp = statp->defdname;
270                     pp = statp->dnsrch;
271                     *pp++ = cp;
272                     for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
273                             if (*cp == ' ' || *cp == '\t') {
274                                     *cp = 0;
275                                     n = 1;
276                             } else if (n) {
277                                     *pp++ = cp;
278                                     n = 0;
279                             }
280                     }
281                     /* null terminate last domain if there are excess */
282                     while (*cp != '\0' && *cp != ' ' && *cp != '\t')
283                             cp++;
284                     *cp = '\0';
285                     *pp++ = 0;
286                     havesearch = 1;
287                     continue;
288                 }
289                 /* read nameservers to query */
290                 if (MATCH(buf, "nameserver") && nserv < MAXNS) {
291                     struct in_addr a;
292
293                     cp = buf + sizeof("nameserver") - 1;
294                     while (*cp == ' ' || *cp == '\t')
295                         cp++;
296                     if ((*cp != '\0') && (*cp != '\n') && inet_aton(cp, &a)) {
297                         statp->nsaddr_list[nserv].sin_addr = a;
298                         statp->nsaddr_list[nserv].sin_family = AF_INET;
299                         statp->nsaddr_list[nserv].sin_port =
300                                 htons(NAMESERVER_PORT);
301                         nserv++;
302                     }
303                     continue;
304                 }
305 #ifdef RESOLVSORT
306                 if (MATCH(buf, "sortlist")) {
307                     struct in_addr a;
308
309                     cp = buf + sizeof("sortlist") - 1;
310                     while (nsort < MAXRESOLVSORT) {
311                         while (*cp == ' ' || *cp == '\t')
312                             cp++;
313                         if (*cp == '\0' || *cp == '\n' || *cp == ';')
314                             break;
315                         net = cp;
316                         while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
317                                isascii(*cp) && !isspace(*cp))
318                                 cp++;
319                         n = *cp;
320                         *cp = 0;
321                         if (inet_aton(net, &a)) {
322                             statp->sort_list[nsort].addr = a;
323                             if (ISSORTMASK(n)) {
324                                 *cp++ = n;
325                                 net = cp;
326                                 while (*cp && *cp != ';' &&
327                                         isascii(*cp) && !isspace(*cp))
328                                     cp++;
329                                 n = *cp;
330                                 *cp = 0;
331                                 if (inet_aton(net, &a)) {
332                                     statp->sort_list[nsort].mask = a.s_addr;
333                                 } else {
334                                     statp->sort_list[nsort].mask = 
335                                         net_mask(statp->sort_list[nsort].addr);
336                                 }
337                             } else {
338                                 statp->sort_list[nsort].mask = 
339                                     net_mask(statp->sort_list[nsort].addr);
340                             }
341                             nsort++;
342                         }
343                         *cp = n;
344                     }
345                     continue;
346                 }
347 #endif
348                 if (MATCH(buf, "options")) {
349                     res_setoptions(statp, buf + sizeof("options") - 1, "conf");
350                     continue;
351                 }
352             }
353             if (nserv > 1) 
354                 statp->nscount = nserv;
355 #ifdef RESOLVSORT
356             statp->nsort = nsort;
357 #endif
358             (void) fclose(fp);
359         }
360         if (statp->defdname[0] == 0 &&
361             gethostname(buf, sizeof(statp->defdname) - 1) == 0 &&
362             (cp = strchr(buf, '.')) != NULL)
363                 strcpy(statp->defdname, cp + 1);
364
365         /* find components of local domain that might be searched */
366         if (havesearch == 0) {
367                 pp = statp->dnsrch;
368                 *pp++ = statp->defdname;
369                 *pp = NULL;
370
371 #ifndef RFC1535
372                 dots = 0;
373                 for (cp = statp->defdname; *cp; cp++)
374                         dots += (*cp == '.');
375
376                 cp = statp->defdname;
377                 while (pp < statp->dnsrch + MAXDFLSRCH) {
378                         if (dots < LOCALDOMAINPARTS)
379                                 break;
380                         cp = strchr(cp, '.') + 1;    /* we know there is one */
381                         *pp++ = cp;
382                         dots--;
383                 }
384                 *pp = NULL;
385 #ifdef DEBUG
386                 if (statp->options & RES_DEBUG) {
387                         printf(";; res_init()... default dnsrch list:\n");
388                         for (pp = statp->dnsrch; *pp; pp++)
389                                 printf(";;\t%s\n", *pp);
390                         printf(";;\t..END..\n");
391                 }
392 #endif
393 #endif /* !RFC1535 */
394         }
395
396         if ((cp = getenv("RES_OPTIONS")) != NULL)
397                 res_setoptions(statp, cp, "env");
398         statp->options |= RES_INIT;
399         return (0);
400 }
401
402 static void
403 res_setoptions(res_state statp, const char *options, const char *source) {
404         const char *cp = options;
405         int i;
406
407 #ifdef DEBUG
408         if (statp->options & RES_DEBUG)
409                 printf(";; res_setoptions(\"%s\", \"%s\")...\n",
410                        options, source);
411 #endif
412         while (*cp) {
413                 /* skip leading and inner runs of spaces */
414                 while (*cp == ' ' || *cp == '\t')
415                         cp++;
416                 /* search for and process individual options */
417                 if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) {
418                         i = atoi(cp + sizeof("ndots:") - 1);
419                         if (i <= RES_MAXNDOTS)
420                                 statp->ndots = i;
421                         else
422                                 statp->ndots = RES_MAXNDOTS;
423 #ifdef DEBUG
424                         if (statp->options & RES_DEBUG)
425                                 printf(";;\tndots=%d\n", statp->ndots);
426 #endif
427                 } else if (!strncmp(cp, "timeout:", sizeof("timeout:") - 1)) {
428                         i = atoi(cp + sizeof("timeout:") - 1);
429                         if (i <= RES_MAXRETRANS)
430                                 statp->retrans = i;
431                         else
432                                 statp->retrans = RES_MAXRETRANS;
433                 } else if (!strncmp(cp, "attempts:", sizeof("attempts:") - 1)){
434                         i = atoi(cp + sizeof("attempts:") - 1);
435                         if (i <= RES_MAXRETRY)
436                                 statp->retry = i;
437                         else
438                                 statp->retry = RES_MAXRETRY;
439                 } else if (!strncmp(cp, "debug", sizeof("debug") - 1)) {
440 #ifdef DEBUG
441                         if (!(statp->options & RES_DEBUG)) {
442                                 printf(";; res_setoptions(\"%s\", \"%s\")..\n",
443                                        options, source);
444                                 statp->options |= RES_DEBUG;
445                         }
446                         printf(";;\tdebug\n");
447 #endif
448                 } else if (!strncmp(cp, "inet6", sizeof("inet6") - 1)) {
449                         statp->options |= RES_USE_INET6;
450                 } else if (!strncmp(cp, "rotate", sizeof("rotate") - 1)) {
451                         statp->options |= RES_ROTATE;
452                 } else if (!strncmp(cp, "no-check-names",
453                                     sizeof("no-check-names") - 1)) {
454                         statp->options |= RES_NOCHECKNAME;
455                 } else {
456                         /* XXX - print a warning here? */
457                 }
458                 /* skip to next run of spaces */
459                 while (*cp && *cp != ' ' && *cp != '\t')
460                         cp++;
461         }
462 }
463
464 #ifdef RESOLVSORT
465 /* XXX - should really support CIDR which means explicit masks always. */
466 static u_int32_t
467 net_mask(in)            /* XXX - should really use system's version of this */
468         struct in_addr in;
469 {
470         register u_int32_t i = ntohl(in.s_addr);
471
472         if (IN_CLASSA(i))
473                 return (htonl(IN_CLASSA_NET));
474         else if (IN_CLASSB(i))
475                 return (htonl(IN_CLASSB_NET));
476         return (htonl(IN_CLASSC_NET));
477 }
478 #endif
479
480 u_int
481 res_randomid(void) {
482         struct timeval now;
483
484         gettimeofday(&now, NULL);
485         return (0xffff & (now.tv_sec ^ now.tv_usec ^ getpid()));
486 }