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