]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libc/net/res_init.c
This commit was generated by cvs2svn to compensate for changes in r58653,
[FreeBSD/FreeBSD.git] / lib / libc / net / 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 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 char sccsid[] = "@(#)res_init.c  8.1 (Berkeley) 6/7/93";
73 static char orig_rcsid[] = "From: Id: res_init.c,v 8.7 1996/11/18 09:10:04 vixie Exp $";
74 static char rcsid[] = "$FreeBSD$";
75 #endif /* LIBC_SCCS and not lint */
76
77 #include <sys/types.h>
78 #include <sys/param.h>
79 #include <sys/socket.h>
80 #include <sys/time.h>
81 #include <netinet/in.h>
82 #include <arpa/inet.h>
83 #include <arpa/nameser.h>
84 #include <ctype.h>
85 #include <resolv.h>
86 #include <stdio.h>
87 #include <stdlib.h>
88 #include <string.h>
89 #include <unistd.h>
90
91 #include "res_config.h"
92
93 static void res_setoptions __P((char *, char *));
94
95 #ifdef RESOLVSORT
96 static const char sort_mask[] = "/&";
97 #define ISSORTMASK(ch) (strchr(sort_mask, ch) != NULL)
98 static u_int32_t net_mask __P((struct in_addr));
99 #endif
100
101 #if !defined(isascii) /* XXX - could be a function */
102 # define isascii(c) (!(c & 0200))
103 #endif
104
105 /*
106  * Resolver state default settings.
107  */
108
109 struct __res_state _res
110 # if defined(__BIND_RES_TEXT)
111         = { RES_TIMEOUT, }      /* Motorola, et al. */
112 # endif
113         ;
114
115 #ifdef INET6
116 struct __res_state_ext _res_ext;
117 #endif /* INET6 */
118
119 /*
120  * Set up default settings.  If the configuration file exist, the values
121  * there will have precedence.  Otherwise, the server address is set to
122  * INADDR_ANY and the default domain name comes from the gethostname().
123  *
124  * An interrim version of this code (BIND 4.9, pre-4.4BSD) used 127.0.0.1
125  * rather than INADDR_ANY ("0.0.0.0") as the default name server address
126  * since it was noted that INADDR_ANY actually meant ``the first interface
127  * you "ifconfig"'d at boot time'' and if this was a SLIP or PPP interface,
128  * it had to be "up" in order for you to reach your own name server.  It
129  * was later decided that since the recommended practice is to always 
130  * install local static routes through 127.0.0.1 for all your network
131  * interfaces, that we could solve this problem without a code change.
132  *
133  * The configuration file should always be used, since it is the only way
134  * to specify a default domain.  If you are running a server on your local
135  * machine, you should say "nameserver 0.0.0.0" or "nameserver 127.0.0.1"
136  * in the configuration file.
137  *
138  * Return 0 if completes successfully, -1 on error
139  */
140 int
141 res_init()
142 {
143         register FILE *fp;
144         register char *cp, **pp;
145         register int n;
146         char buf[MAXDNAME];
147         int nserv = 0;    /* number of nameserver records read from file */
148         int haveenv = 0;
149         int havesearch = 0;
150 #ifdef RESOLVSORT
151         int nsort = 0;
152         char *net;
153 #endif
154 #ifndef RFC1535
155         int dots;
156 #endif
157
158         /*
159          * These three fields used to be statically initialized.  This made
160          * it hard to use this code in a shared library.  It is necessary,
161          * now that we're doing dynamic initialization here, that we preserve
162          * the old semantics: if an application modifies one of these three
163          * fields of _res before res_init() is called, res_init() will not
164          * alter them.  Of course, if an application is setting them to
165          * _zero_ before calling res_init(), hoping to override what used
166          * to be the static default, we can't detect it and unexpected results
167          * will follow.  Zero for any of these fields would make no sense,
168          * so one can safely assume that the applications were already getting
169          * unexpected results.
170          *
171          * _res.options is tricky since some apps were known to diddle the bits
172          * before res_init() was first called. We can't replicate that semantic
173          * with dynamic initialization (they may have turned bits off that are
174          * set in RES_DEFAULT).  Our solution is to declare such applications
175          * "broken".  They could fool us by setting RES_INIT but none do (yet).
176          */
177         if (!_res.retrans)
178                 _res.retrans = RES_TIMEOUT;
179         if (!_res.retry)
180                 _res.retry = 4;
181         if (!(_res.options & RES_INIT))
182                 _res.options = RES_DEFAULT;
183
184         /*
185          * This one used to initialize implicitly to zero, so unless the app
186          * has set it to something in particular, we can randomize it now.
187          */
188         if (!_res.id)
189                 _res.id = res_randomid();
190
191 #ifdef USELOOPBACK
192         _res.nsaddr.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
193 #else
194         _res.nsaddr.sin_addr.s_addr = INADDR_ANY;
195 #endif
196         _res.nsaddr.sin_family = AF_INET;
197         _res.nsaddr.sin_port = htons(NAMESERVER_PORT);
198         _res.nscount = 1;
199         _res.ndots = 1;
200         _res.pfcode = 0;
201
202         /* Allow user to override the local domain definition */
203         if (issetugid() == 0 && (cp = getenv("LOCALDOMAIN")) != NULL) {
204                 (void)strncpy(_res.defdname, cp, sizeof(_res.defdname) - 1);
205                 _res.defdname[sizeof(_res.defdname) - 1] = '\0';
206                 haveenv++;
207
208                 /*
209                  * Set search list to be blank-separated strings
210                  * from rest of env value.  Permits users of LOCALDOMAIN
211                  * to still have a search list, and anyone to set the
212                  * one that they want to use as an individual (even more
213                  * important now that the rfc1535 stuff restricts searches)
214                  */
215                 cp = _res.defdname;
216                 pp = _res.dnsrch;
217                 *pp++ = cp;
218                 for (n = 0; *cp && pp < _res.dnsrch + MAXDNSRCH; cp++) {
219                         if (*cp == '\n')        /* silly backwards compat */
220                                 break;
221                         else if (*cp == ' ' || *cp == '\t') {
222                                 *cp = 0;
223                                 n = 1;
224                         } else if (n) {
225                                 *pp++ = cp;
226                                 n = 0;
227                                 havesearch = 1;
228                         }
229                 }
230                 /* null terminate last domain if there are excess */
231                 while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
232                         cp++;
233                 *cp = '\0';
234                 *pp++ = 0;
235         }
236
237 #define MATCH(line, name) \
238         (!strncmp(line, name, sizeof(name) - 1) && \
239         (line[sizeof(name) - 1] == ' ' || \
240          line[sizeof(name) - 1] == '\t'))
241
242         if ((fp = fopen(_PATH_RESCONF, "r")) != NULL) {
243             /* read the config file */
244             while (fgets(buf, sizeof(buf), fp) != NULL) {
245                 /* skip comments */
246                 if (*buf == ';' || *buf == '#')
247                         continue;
248                 /* read default domain name */
249                 if (MATCH(buf, "domain")) {
250                     if (haveenv)        /* skip if have from environ */
251                             continue;
252                     cp = buf + sizeof("domain") - 1;
253                     while (*cp == ' ' || *cp == '\t')
254                             cp++;
255                     if ((*cp == '\0') || (*cp == '\n'))
256                             continue;
257                     strncpy(_res.defdname, cp, sizeof(_res.defdname) - 1);
258                     _res.defdname[sizeof(_res.defdname) - 1] = '\0';
259                     if ((cp = strpbrk(_res.defdname, " \t\n")) != NULL)
260                             *cp = '\0';
261                     havesearch = 0;
262                     continue;
263                 }
264                 /* set search list */
265                 if (MATCH(buf, "search")) {
266                     if (haveenv)        /* skip if have from environ */
267                             continue;
268                     cp = buf + sizeof("search") - 1;
269                     while (*cp == ' ' || *cp == '\t')
270                             cp++;
271                     if ((*cp == '\0') || (*cp == '\n'))
272                             continue;
273                     strncpy(_res.defdname, cp, sizeof(_res.defdname) - 1);
274                     _res.defdname[sizeof(_res.defdname) - 1] = '\0';
275                     if ((cp = strchr(_res.defdname, '\n')) != NULL)
276                             *cp = '\0';
277                     /*
278                      * Set search list to be blank-separated strings
279                      * on rest of line.
280                      */
281                     cp = _res.defdname;
282                     pp = _res.dnsrch;
283                     *pp++ = cp;
284                     for (n = 0; *cp && pp < _res.dnsrch + MAXDNSRCH; cp++) {
285                             if (*cp == ' ' || *cp == '\t') {
286                                     *cp = 0;
287                                     n = 1;
288                             } else if (n) {
289                                     *pp++ = cp;
290                                     n = 0;
291                             }
292                     }
293                     /* null terminate last domain if there are excess */
294                     while (*cp != '\0' && *cp != ' ' && *cp != '\t')
295                             cp++;
296                     *cp = '\0';
297                     *pp++ = 0;
298                     havesearch = 1;
299                     continue;
300                 }
301                 /* read nameservers to query */
302                 if (MATCH(buf, "nameserver") && nserv < MAXNS) {
303                     struct in_addr a;
304
305                     cp = buf + sizeof("nameserver") - 1;
306                     while (*cp == ' ' || *cp == '\t')
307                         cp++;
308                     if ((*cp != '\0') && (*cp != '\n') && inet_aton(cp, &a)) {
309                         _res.nsaddr_list[nserv].sin_addr = a;
310                         _res.nsaddr_list[nserv].sin_family = AF_INET;
311                         _res.nsaddr_list[nserv].sin_port =
312                                 htons(NAMESERVER_PORT);
313                         nserv++;
314                     }
315                     continue;
316                 }
317 #ifdef RESOLVSORT
318                 if (MATCH(buf, "sortlist")) {
319                     struct in_addr a;
320 #ifdef INET6
321                     struct in6_addr a6;
322 #endif /* INET6 */
323
324                     cp = buf + sizeof("sortlist") - 1;
325                     while (nsort < MAXRESOLVSORT) {
326                         while (*cp == ' ' || *cp == '\t')
327                             cp++;
328                         if (*cp == '\0' || *cp == '\n' || *cp == ';')
329                             break;
330                         net = cp;
331                         while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
332                                isascii(*cp) && !isspace(*cp))
333                                 cp++;
334                         n = *cp;
335                         *cp = 0;
336                         if (inet_aton(net, &a)) {
337                             _res.sort_list[nsort].addr = a;
338                             if (ISSORTMASK(n)) {
339                                 *cp++ = n;
340                                 net = cp;
341                                 while (*cp && *cp != ';' &&
342                                         isascii(*cp) && !isspace(*cp))
343                                     cp++;
344                                 n = *cp;
345                                 *cp = 0;
346                                 if (inet_aton(net, &a)) {
347                                     _res.sort_list[nsort].mask = a.s_addr;
348                                 } else {
349                                     _res.sort_list[nsort].mask = 
350                                         net_mask(_res.sort_list[nsort].addr);
351                                 }
352                             } else {
353                                 _res.sort_list[nsort].mask = 
354                                     net_mask(_res.sort_list[nsort].addr);
355                             }
356 #ifdef INET6
357                             _res_ext.sort_list[nsort].af = AF_INET;
358                             _res_ext.sort_list[nsort].addr.ina =
359                                 _res.sort_list[nsort].addr;
360                             _res_ext.sort_list[nsort].mask.ina.s_addr =
361                                 _res.sort_list[nsort].mask;
362 #endif /* INET6 */
363                             nsort++;
364                         }
365 #ifdef INET6
366                         else if (inet_pton(AF_INET6, net, &a6) == 1) {
367                             int m, i;
368                             u_char *u;
369
370                             _res_ext.sort_list[nsort].af = AF_INET6;
371                             _res_ext.sort_list[nsort].addr.in6a = a6;
372                             u = (u_char *)&_res_ext.sort_list[nsort].mask.in6a;
373                             *cp++ = n;
374                             net = cp;
375                             while (*cp && *cp != ';' &&
376                                     isascii(*cp) && !isspace(*cp))
377                                 cp++;
378                             m = n;
379                             n = *cp;
380                             *cp = 0;
381                             switch (m) {
382                             case '/':
383                                 m = atoi(net);
384                                 break;
385                             case '&':
386                                 if (inet_pton(AF_INET6, net, u) == 1) {
387                                     m = -1;
388                                     break;
389                                 }
390                                 /*FALLTHROUGH*/
391                             default:
392                                 m = sizeof(struct in6_addr) * NBBY;
393                                 break;
394                             }
395                             if (m >= 0) {
396                                 for (i = 0; i < sizeof(struct in6_addr); i++) {
397                                     if (m <= 0) {
398                                         *u = 0;
399                                     } else {
400                                         m -= NBBY;
401                                         *u = (u_char)~0;
402                                         if (m < 0)
403                                             *u <<= -m;
404                                     }
405                                     u++;
406                                 }
407                             }
408                             nsort++;
409                         }
410 #endif /* INET6 */
411                         *cp = n;
412                     }
413                     continue;
414                 }
415 #endif
416                 if (MATCH(buf, "options")) {
417                     res_setoptions(buf + sizeof("options") - 1, "conf");
418                     continue;
419                 }
420             }
421             if (nserv > 1) 
422                 _res.nscount = nserv;
423 #ifdef RESOLVSORT
424             _res.nsort = nsort;
425 #endif
426             (void) fclose(fp);
427         }
428         if (_res.defdname[0] == 0 &&
429             gethostname(buf, sizeof(_res.defdname) - 1) == 0 &&
430             (cp = strchr(buf, '.')) != NULL)
431                 strcpy(_res.defdname, cp + 1);
432
433         /* find components of local domain that might be searched */
434         if (havesearch == 0) {
435                 pp = _res.dnsrch;
436                 *pp++ = _res.defdname;
437                 *pp = NULL;
438
439 #ifndef RFC1535
440                 dots = 0;
441                 for (cp = _res.defdname; *cp; cp++)
442                         dots += (*cp == '.');
443
444                 cp = _res.defdname;
445                 while (pp < _res.dnsrch + MAXDFLSRCH) {
446                         if (dots < LOCALDOMAINPARTS)
447                                 break;
448                         cp = strchr(cp, '.') + 1;    /* we know there is one */
449                         *pp++ = cp;
450                         dots--;
451                 }
452                 *pp = NULL;
453 #ifdef DEBUG
454                 if (_res.options & RES_DEBUG) {
455                         printf(";; res_init()... default dnsrch list:\n");
456                         for (pp = _res.dnsrch; *pp; pp++)
457                                 printf(";;\t%s\n", *pp);
458                         printf(";;\t..END..\n");
459                 }
460 #endif
461 #endif /* !RFC1535 */
462         }
463
464         if (issetugid())
465                 _res.options |= RES_NOALIASES;
466         else if ((cp = getenv("RES_OPTIONS")) != NULL)
467                 res_setoptions(cp, "env");
468         _res.options |= RES_INIT;
469         return (0);
470 }
471
472 static void
473 res_setoptions(options, source)
474         char *options, *source;
475 {
476         char *cp = options;
477         int i;
478
479 #ifdef DEBUG
480         if (_res.options & RES_DEBUG)
481                 printf(";; res_setoptions(\"%s\", \"%s\")...\n",
482                        options, source);
483 #endif
484         while (*cp) {
485                 /* skip leading and inner runs of spaces */
486                 while (*cp == ' ' || *cp == '\t')
487                         cp++;
488                 /* search for and process individual options */
489                 if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) {
490                         i = atoi(cp + sizeof("ndots:") - 1);
491                         if (i <= RES_MAXNDOTS)
492                                 _res.ndots = i;
493                         else
494                                 _res.ndots = RES_MAXNDOTS;
495 #ifdef DEBUG
496                         if (_res.options & RES_DEBUG)
497                                 printf(";;\tndots=%d\n", _res.ndots);
498 #endif
499                 } else if (!strncmp(cp, "debug", sizeof("debug") - 1)) {
500 #ifdef DEBUG
501                         if (!(_res.options & RES_DEBUG)) {
502                                 printf(";; res_setoptions(\"%s\", \"%s\")..\n",
503                                        options, source);
504                                 _res.options |= RES_DEBUG;
505                         }
506                         printf(";;\tdebug\n");
507 #endif
508                 } else if (!strncmp(cp, "inet6", sizeof("inet6") - 1)) {
509                         _res.options |= RES_USE_INET6;
510                 } else if (!strncmp(cp, "no_tld_query", sizeof("no_tld_query") - 1)) {
511                         _res.options |= RES_NOTLDQUERY;
512                 } else {
513                         /* XXX - print a warning here? */
514                 }
515                 /* skip to next run of spaces */
516                 while (*cp && *cp != ' ' && *cp != '\t')
517                         cp++;
518         }
519 }
520
521 #ifdef RESOLVSORT
522 /* XXX - should really support CIDR which means explicit masks always. */
523 static u_int32_t
524 net_mask(in)            /* XXX - should really use system's version of this */
525         struct in_addr in;
526 {
527         register u_int32_t i = ntohl(in.s_addr);
528
529         if (IN_CLASSA(i))
530                 return (htonl(IN_CLASSA_NET));
531         else if (IN_CLASSB(i))
532                 return (htonl(IN_CLASSB_NET));
533         return (htonl(IN_CLASSC_NET));
534 }
535 #endif
536
537 u_int
538 res_randomid()
539 {
540         struct timeval now;
541
542         gettimeofday(&now, NULL);
543         return (0xffff & (now.tv_sec ^ now.tv_usec ^ getpid()));
544 }
545
546 /*
547  * Weak aliases for applications that use certain private entry points,
548  * and fail to include <resolv.h>.
549  */
550 #undef res_init
551 __weak_reference(__res_init, res_init);