DragonFly has decided to depend on char being signed, use it.
[dragonfly.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  * @(#)res_init.c       8.1 (Berkeley) 6/7/93
34  * $From: Id: res_init.c,v 8.7 1996/11/18 09:10:04 vixie Exp $
35  * $FreeBSD: src/lib/libc/net/res_init.c,v 1.19.2.7 2002/02/04 18:30:55 ume Exp $
36  * $DragonFly: src/lib/libc/net/res_init.c,v 1.4 2004/10/25 19:38:01 drhodus Exp $
37  */
38
39 /*
40  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
41  * 
42  * Permission to use, copy, modify, and distribute this software for any
43  * purpose with or without fee is hereby granted, provided that the above
44  * copyright notice and this permission notice appear in all copies, and that
45  * the name of Digital Equipment Corporation not be used in advertising or
46  * publicity pertaining to distribution of the document or software without
47  * specific, written prior permission.
48  * 
49  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
50  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
51  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
52  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
53  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
54  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
55  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
56  * SOFTWARE.
57  */
58
59 /*
60  * Portions Copyright (c) 1996 by Internet Software Consortium.
61  *
62  * Permission to use, copy, modify, and distribute this software for any
63  * purpose with or without fee is hereby granted, provided that the above
64  * copyright notice and this permission notice appear in all copies.
65  *
66  * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
67  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
68  * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
69  * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
70  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
71  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
72  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
73  * SOFTWARE.
74  */
75
76 #include <sys/types.h>
77 #include <sys/param.h>
78 #include <sys/socket.h>
79 #include <sys/time.h>
80 #include <netinet/in.h>
81 #include <arpa/inet.h>
82 #include <arpa/nameser.h>
83 #include <ctype.h>
84 #include <resolv.h>
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #include <unistd.h>
89 #include <netdb.h>
90
91 #include "res_config.h"
92
93 static void res_setoptions (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 (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 struct __res_state_ext _res_ext;
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  */
138 int
139 res_init()
140 {
141         FILE *fp;
142         char *cp, **pp;
143         int n;
144         char buf[MAXDNAME];
145         int nserv = 0;    /* number of nameserver records read from file */
146         int haveenv = 0;
147         int havesearch = 0;
148 #ifdef RESOLVSORT
149         int nsort = 0;
150         char *net;
151 #endif
152 #ifndef RFC1535
153         int dots;
154 #endif
155
156         /*
157          * These three fields used to be statically initialized.  This made
158          * it hard to use this code in a shared library.  It is necessary,
159          * now that we're doing dynamic initialization here, that we preserve
160          * the old semantics: if an application modifies one of these three
161          * fields of _res before res_init() is called, res_init() will not
162          * alter them.  Of course, if an application is setting them to
163          * _zero_ before calling res_init(), hoping to override what used
164          * to be the static default, we can't detect it and unexpected results
165          * will follow.  Zero for any of these fields would make no sense,
166          * so one can safely assume that the applications were already getting
167          * unexpected results.
168          *
169          * _res.options is tricky since some apps were known to diddle the bits
170          * before res_init() was first called. We can't replicate that semantic
171          * with dynamic initialization (they may have turned bits off that are
172          * set in RES_DEFAULT).  Our solution is to declare such applications
173          * "broken".  They could fool us by setting RES_INIT but none do (yet).
174          */
175         if (!_res.retrans)
176                 _res.retrans = RES_TIMEOUT;
177         if (!_res.retry)
178                 _res.retry = 4;
179         if (!(_res.options & RES_INIT))
180                 _res.options = RES_DEFAULT;
181
182         /*
183          * This one used to initialize implicitly to zero, so unless the app
184          * has set it to something in particular, we can randomize it now.
185          */
186         if (!_res.id)
187                 _res.id = res_randomid();
188
189 #ifdef USELOOPBACK
190         _res.nsaddr.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
191 #else
192         _res.nsaddr.sin_addr.s_addr = INADDR_ANY;
193 #endif
194         _res.nsaddr.sin_family = AF_INET;
195         _res.nsaddr.sin_port = htons(NAMESERVER_PORT);
196         _res.nsaddr.sin_len = sizeof(struct sockaddr_in);
197         if (sizeof(_res_ext.nsaddr) >= _res.nsaddr.sin_len)
198                 memcpy(&_res_ext.nsaddr, &_res.nsaddr, _res.nsaddr.sin_len);
199         _res.nscount = 1;
200         _res.ndots = 1;
201         _res.pfcode = 0;
202
203         /* Allow user to override the local domain definition */
204         if (issetugid() == 0 && (cp = getenv("LOCALDOMAIN")) != NULL) {
205                 (void)strncpy(_res.defdname, cp, sizeof(_res.defdname) - 1);
206                 _res.defdname[sizeof(_res.defdname) - 1] = '\0';
207                 haveenv++;
208
209                 /*
210                  * Set search list to be blank-separated strings
211                  * from rest of env value.  Permits users of LOCALDOMAIN
212                  * to still have a search list, and anyone to set the
213                  * one that they want to use as an individual (even more
214                  * important now that the rfc1535 stuff restricts searches)
215                  */
216                 cp = _res.defdname;
217                 pp = _res.dnsrch;
218                 *pp++ = cp;
219                 for (n = 0; *cp && pp < _res.dnsrch + MAXDNSRCH; cp++) {
220                         if (*cp == '\n')        /* silly backwards compat */
221                                 break;
222                         else if (*cp == ' ' || *cp == '\t') {
223                                 *cp = 0;
224                                 n = 1;
225                         } else if (n) {
226                                 *pp++ = cp;
227                                 n = 0;
228                                 havesearch = 1;
229                         }
230                 }
231                 /* null terminate last domain if there are excess */
232                 while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
233                         cp++;
234                 *cp = '\0';
235                 *pp++ = 0;
236         }
237
238 #define MATCH(line, name) \
239         (!strncmp(line, name, sizeof(name) - 1) && \
240         (line[sizeof(name) - 1] == ' ' || \
241          line[sizeof(name) - 1] == '\t'))
242
243         if ((fp = fopen(_PATH_RESCONF, "r")) != NULL) {
244             /* read the config file */
245             while (fgets(buf, sizeof(buf), fp) != NULL) {
246                 /* skip comments */
247                 if (*buf == ';' || *buf == '#')
248                         continue;
249                 /* read default domain name */
250                 if (MATCH(buf, "domain")) {
251                     if (haveenv)        /* skip if have from environ */
252                             continue;
253                     cp = buf + sizeof("domain") - 1;
254                     while (*cp == ' ' || *cp == '\t')
255                             cp++;
256                     if ((*cp == '\0') || (*cp == '\n'))
257                             continue;
258                     strncpy(_res.defdname, cp, sizeof(_res.defdname) - 1);
259                     _res.defdname[sizeof(_res.defdname) - 1] = '\0';
260                     if ((cp = strpbrk(_res.defdname, " \t\n")) != NULL)
261                             *cp = '\0';
262                     havesearch = 0;
263                     continue;
264                 }
265                 /* set search list */
266                 if (MATCH(buf, "search")) {
267                     if (haveenv)        /* skip if have from environ */
268                             continue;
269                     cp = buf + sizeof("search") - 1;
270                     while (*cp == ' ' || *cp == '\t')
271                             cp++;
272                     if ((*cp == '\0') || (*cp == '\n'))
273                             continue;
274                     strncpy(_res.defdname, cp, sizeof(_res.defdname) - 1);
275                     _res.defdname[sizeof(_res.defdname) - 1] = '\0';
276                     if ((cp = strchr(_res.defdname, '\n')) != NULL)
277                             *cp = '\0';
278                     /*
279                      * Set search list to be blank-separated strings
280                      * on rest of line.
281                      */
282                     cp = _res.defdname;
283                     pp = _res.dnsrch;
284                     *pp++ = cp;
285                     for (n = 0; *cp && pp < _res.dnsrch + MAXDNSRCH; cp++) {
286                             if (*cp == ' ' || *cp == '\t') {
287                                     *cp = 0;
288                                     n = 1;
289                             } else if (n) {
290                                     *pp++ = cp;
291                                     n = 0;
292                             }
293                     }
294                     /* null terminate last domain if there are excess */
295                     while (*cp != '\0' && *cp != ' ' && *cp != '\t')
296                             cp++;
297                     *cp = '\0';
298                     *pp++ = 0;
299                     havesearch = 1;
300                     continue;
301                 }
302                 /* read nameservers to query */
303                 if (MATCH(buf, "nameserver") && nserv < MAXNS) {
304                     char *q;
305                     struct addrinfo hints, *res;
306                     char pbuf[NI_MAXSERV];
307
308                     cp = buf + sizeof("nameserver") - 1;
309                     while (*cp == ' ' || *cp == '\t')
310                         cp++;
311                     if ((*cp == '\0') || (*cp == '\n'))
312                         continue;
313                     for (q = cp; *q; q++) {
314                         if (isspace(*q)) {
315                             *q = '\0';
316                             break;
317                         }
318                     }
319                     memset(&hints, 0, sizeof(hints));
320                     hints.ai_flags = AI_NUMERICHOST;
321                     hints.ai_socktype = SOCK_DGRAM;
322                     snprintf(pbuf, sizeof(pbuf), "%d", NAMESERVER_PORT);
323                     if (getaddrinfo(cp, pbuf, &hints, &res) == 0 &&
324                             res->ai_next == NULL) {
325                         if (res->ai_addrlen <= sizeof(_res_ext.nsaddr_list[nserv])) {
326                             memcpy(&_res_ext.nsaddr_list[nserv], res->ai_addr,
327                                 res->ai_addrlen);
328                         } else {
329                             memset(&_res_ext.nsaddr_list[nserv], 0,
330                                 sizeof(_res_ext.nsaddr_list[nserv]));
331                         }
332                         if (res->ai_addrlen <= sizeof(_res.nsaddr_list[nserv])) {
333                             memcpy(&_res.nsaddr_list[nserv], res->ai_addr,
334                                 res->ai_addrlen);
335                         } else {
336                             memset(&_res.nsaddr_list[nserv], 0,
337                                 sizeof(_res.nsaddr_list[nserv]));
338                         }
339                         nserv++;
340                     }
341                     if (res)
342                             freeaddrinfo(res);
343                     continue;
344                 }
345 #ifdef RESOLVSORT
346                 if (MATCH(buf, "sortlist")) {
347                     struct in_addr a;
348                     struct in6_addr a6;
349                     int m, i;
350                     u_char *u;
351
352                     cp = buf + sizeof("sortlist") - 1;
353                     while (nsort < MAXRESOLVSORT) {
354                         while (*cp == ' ' || *cp == '\t')
355                             cp++;
356                         if (*cp == '\0' || *cp == '\n' || *cp == ';')
357                             break;
358                         net = cp;
359                         while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
360                                isascii(*cp) && !isspace(*cp))
361                                 cp++;
362                         n = *cp;
363                         *cp = 0;
364                         if (inet_aton(net, &a)) {
365                             _res.sort_list[nsort].addr = a;
366                             if (ISSORTMASK(n)) {
367                                 *cp++ = n;
368                                 net = cp;
369                                 while (*cp && *cp != ';' &&
370                                         isascii(*cp) && !isspace(*cp))
371                                     cp++;
372                                 n = *cp;
373                                 *cp = 0;
374                                 if (inet_aton(net, &a)) {
375                                     _res.sort_list[nsort].mask = a.s_addr;
376                                 } else {
377                                     _res.sort_list[nsort].mask = 
378                                         net_mask(_res.sort_list[nsort].addr);
379                                 }
380                             } else {
381                                 _res.sort_list[nsort].mask = 
382                                     net_mask(_res.sort_list[nsort].addr);
383                             }
384                             _res_ext.sort_list[nsort].af = AF_INET;
385                             _res_ext.sort_list[nsort].addr.ina =
386                                 _res.sort_list[nsort].addr;
387                             _res_ext.sort_list[nsort].mask.ina.s_addr =
388                                 _res.sort_list[nsort].mask;
389                             nsort++;
390                         }
391                         else if (inet_pton(AF_INET6, net, &a6) == 1) {
392
393                             _res_ext.sort_list[nsort].af = AF_INET6;
394                             _res_ext.sort_list[nsort].addr.in6a = a6;
395                             u = (u_char *)&_res_ext.sort_list[nsort].mask.in6a;
396                             *cp++ = n;
397                             net = cp;
398                             while (*cp && *cp != ';' &&
399                                     isascii(*cp) && !isspace(*cp))
400                                 cp++;
401                             m = n;
402                             n = *cp;
403                             *cp = 0;
404                             switch (m) {
405                             case '/':
406                                 m = atoi(net);
407                                 break;
408                             case '&':
409                                 if (inet_pton(AF_INET6, net, u) == 1) {
410                                     m = -1;
411                                     break;
412                                 }
413                                 /*FALLTHROUGH*/
414                             default:
415                                 m = sizeof(struct in6_addr) * NBBY;
416                                 break;
417                             }
418                             if (m >= 0) {
419                                 for (i = 0; i < sizeof(struct in6_addr); i++) {
420                                     if (m <= 0) {
421                                         *u = 0;
422                                     } else {
423                                         m -= NBBY;
424                                         *u = (u_char)~0;
425                                         if (m < 0)
426                                             *u <<= -m;
427                                     }
428                                     u++;
429                                 }
430                             }
431                             _res.sort_list[nsort].addr.s_addr =
432                                 (u_int32_t)0xffffffff;
433                             _res.sort_list[nsort].mask = (u_int32_t)0xffffffff;
434                             nsort++;
435                         }
436                         *cp = n;
437                     }
438                     continue;
439                 }
440 #endif
441                 if (MATCH(buf, "options")) {
442                     res_setoptions(buf + sizeof("options") - 1, "conf");
443                     continue;
444                 }
445             }
446             if (nserv > 1) 
447                 _res.nscount = nserv;
448 #ifdef RESOLVSORT
449             _res.nsort = nsort;
450 #endif
451             (void) fclose(fp);
452         }
453         if (_res.defdname[0] == 0 &&
454             gethostname(buf, sizeof(_res.defdname) - 1) == 0 &&
455             (cp = strchr(buf, '.')) != NULL)
456                 strcpy(_res.defdname, cp + 1);
457
458         /* find components of local domain that might be searched */
459         if (havesearch == 0) {
460                 pp = _res.dnsrch;
461                 *pp++ = _res.defdname;
462                 *pp = NULL;
463
464 #ifndef RFC1535
465                 dots = 0;
466                 for (cp = _res.defdname; *cp; cp++)
467                         dots += (*cp == '.');
468
469                 cp = _res.defdname;
470                 while (pp < _res.dnsrch + MAXDFLSRCH) {
471                         if (dots < LOCALDOMAINPARTS)
472                                 break;
473                         cp = strchr(cp, '.') + 1;    /* we know there is one */
474                         *pp++ = cp;
475                         dots--;
476                 }
477                 *pp = NULL;
478 #ifdef DEBUG
479                 if (_res.options & RES_DEBUG) {
480                         printf(";; res_init()... default dnsrch list:\n");
481                         for (pp = _res.dnsrch; *pp; pp++)
482                                 printf(";;\t%s\n", *pp);
483                         printf(";;\t..END..\n");
484                 }
485 #endif
486 #endif /* !RFC1535 */
487         }
488
489         if (issetugid())
490                 _res.options |= RES_NOALIASES;
491         else if ((cp = getenv("RES_OPTIONS")) != NULL)
492                 res_setoptions(cp, "env");
493         _res.options |= RES_INIT;
494         return (0);
495 }
496
497 static void
498 res_setoptions(options, source)
499         char *options, *source;
500 {
501         char *cp = options;
502         int i;
503
504 #ifdef DEBUG
505         if (_res.options & RES_DEBUG)
506                 printf(";; res_setoptions(\"%s\", \"%s\")...\n",
507                        options, source);
508 #endif
509         while (*cp) {
510                 /* skip leading and inner runs of spaces */
511                 while (*cp == ' ' || *cp == '\t')
512                         cp++;
513                 /* search for and process individual options */
514                 if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) {
515                         i = atoi(cp + sizeof("ndots:") - 1);
516                         if (i <= RES_MAXNDOTS)
517                                 _res.ndots = i;
518                         else
519                                 _res.ndots = RES_MAXNDOTS;
520 #ifdef DEBUG
521                         if (_res.options & RES_DEBUG)
522                                 printf(";;\tndots=%d\n", _res.ndots);
523 #endif
524                 } else if (!strncmp(cp, "debug", sizeof("debug") - 1)) {
525 #ifdef DEBUG
526                         if (!(_res.options & RES_DEBUG)) {
527                                 printf(";; res_setoptions(\"%s\", \"%s\")..\n",
528                                        options, source);
529                                 _res.options |= RES_DEBUG;
530                         }
531                         printf(";;\tdebug\n");
532 #endif
533                 } else if (!strncmp(cp, "inet6", sizeof("inet6") - 1)) {
534                         _res.options |= RES_USE_INET6;
535                 } else if (!strncmp(cp, "insecure1", sizeof("insecure1") - 1)) {
536                        _res.options |= RES_INSECURE1;
537                 } else if (!strncmp(cp, "insecure2", sizeof("insecure2") - 1)) {
538                        _res.options |= RES_INSECURE2;
539                 } else if (!strncmp(cp, "no_tld_query", sizeof("no_tld_query") - 1)) {
540                         _res.options |= RES_NOTLDQUERY;
541                 } else if (!strncmp(cp, "edns0", sizeof("edns0") - 1)) {
542                        _res.options |= RES_USE_EDNS0;
543                 } else {
544                         /* XXX - print a warning here? */
545                 }
546                 /* skip to next run of spaces */
547                 while (*cp && *cp != ' ' && *cp != '\t')
548                         cp++;
549         }
550 }
551
552 #ifdef RESOLVSORT
553 /* XXX - should really support CIDR which means explicit masks always. */
554 static u_int32_t
555 net_mask(in)            /* XXX - should really use system's version of this */
556         struct in_addr in;
557 {
558         u_int32_t i = ntohl(in.s_addr);
559
560         if (IN_CLASSA(i))
561                 return (htonl(IN_CLASSA_NET));
562         else if (IN_CLASSB(i))
563                 return (htonl(IN_CLASSB_NET));
564         return (htonl(IN_CLASSC_NET));
565 }
566 #endif
567
568 u_int
569 res_randomid()
570 {
571         struct timeval now;
572
573         gettimeofday(&now, NULL);
574         return (0xffff & (now.tv_sec ^ now.tv_usec ^ getpid()));
575 }
576
577 /*
578  * Weak aliases for applications that use certain private entry points,
579  * and fail to include <resolv.h>.
580  */
581 #undef res_init
582 __weak_reference(__res_init, res_init);