]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libc/resolv/res_init.c
Update to ELF Tool Chain r3475
[FreeBSD/FreeBSD.git] / lib / libc / resolv / 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  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  * 
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 /*
31  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
32  * 
33  * Permission to use, copy, modify, and distribute this software for any
34  * purpose with or without fee is hereby granted, provided that the above
35  * copyright notice and this permission notice appear in all copies, and that
36  * the name of Digital Equipment Corporation not be used in advertising or
37  * publicity pertaining to distribution of the document or software without
38  * specific, written prior permission.
39  * 
40  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
41  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
43  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
44  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
45  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
46  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
47  * SOFTWARE.
48  */
49
50 /*
51  * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
52  * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
53  *
54  * Permission to use, copy, modify, and distribute this software for any
55  * purpose with or without fee is hereby granted, provided that the above
56  * copyright notice and this permission notice appear in all copies.
57  *
58  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
59  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
60  * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
61  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
62  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
63  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
64  * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
65  */
66
67 #if defined(LIBC_SCCS) && !defined(lint)
68 static const char sccsid[] = "@(#)res_init.c    8.1 (Berkeley) 6/7/93";
69 static const char rcsid[] = "$Id: res_init.c,v 1.26 2008/12/11 09:59:00 marka Exp $";
70 #endif /* LIBC_SCCS and not lint */
71 #include <sys/cdefs.h>
72 __FBSDID("$FreeBSD$");
73
74 #include "port_before.h"
75
76 #include "namespace.h"
77
78 #include <sys/param.h>
79 #include <sys/socket.h>
80 #include <sys/stat.h>
81 #include <sys/time.h>
82
83 #include <netinet/in.h>
84 #include <arpa/inet.h>
85 #include <arpa/nameser.h>
86
87 #include <ctype.h>
88 #include <stdio.h>
89 #include <stdlib.h>
90 #include <string.h>
91 #include <unistd.h>
92 #include <netdb.h>
93
94 #ifndef HAVE_MD5
95 # include "../dst/md5.h"
96 #else
97 # ifdef SOLARIS2
98 #  include <sys/md5.h>
99 # elif _LIBC
100 # include <md5.h>
101 # endif
102 #endif
103 #ifndef _MD5_H_
104 # define _MD5_H_ 1      /*%< make sure we do not include rsaref md5.h file */
105 #endif
106
107 #include "un-namespace.h"
108
109 #include "port_after.h"
110
111 /* ensure that sockaddr_in6 and IN6ADDR_ANY_INIT are declared / defined */
112 #include <resolv.h>
113
114 #include "res_private.h"
115
116 /*% Options.  Should all be left alone. */
117 #define RESOLVSORT
118 #ifndef DEBUG
119 #define DEBUG
120 #endif
121
122 #ifdef SOLARIS2
123 #include <sys/systeminfo.h>
124 #endif
125
126 static void res_setoptions(res_state, const char *, const char *);
127
128 #ifdef RESOLVSORT
129 static const char sort_mask[] = "/&";
130 #define ISSORTMASK(ch) (strchr(sort_mask, ch) != NULL)
131 static u_int32_t net_mask(struct in_addr);
132 #endif
133
134 #if !defined(isascii)   /*%< XXX - could be a function */
135 # define isascii(c) (!(c & 0200))
136 #endif
137
138 /*
139  * Resolver state default settings.
140  */
141
142 /*%
143  * Set up default settings.  If the configuration file exist, the values
144  * there will have precedence.  Otherwise, the server address is set to
145  * INADDR_ANY and the default domain name comes from the gethostname().
146  *
147  * An interim version of this code (BIND 4.9, pre-4.4BSD) used 127.0.0.1
148  * rather than INADDR_ANY ("0.0.0.0") as the default name server address
149  * since it was noted that INADDR_ANY actually meant ``the first interface
150  * you "ifconfig"'d at boot time'' and if this was a SLIP or PPP interface,
151  * it had to be "up" in order for you to reach your own name server.  It
152  * was later decided that since the recommended practice is to always 
153  * install local static routes through 127.0.0.1 for all your network
154  * interfaces, that we could solve this problem without a code change.
155  *
156  * The configuration file should always be used, since it is the only way
157  * to specify a default domain.  If you are running a server on your local
158  * machine, you should say "nameserver 0.0.0.0" or "nameserver 127.0.0.1"
159  * in the configuration file.
160  *
161  * Return 0 if completes successfully, -1 on error
162  */
163 int
164 res_ninit(res_state statp) {
165         extern int __res_vinit(res_state, int);
166
167         return (__res_vinit(statp, 0));
168 }
169
170 /*% This function has to be reachable by res_data.c but not publicly. */
171 int
172 __res_vinit(res_state statp, int preinit) {
173         FILE *fp;
174         char *cp, **pp;
175         int n;
176         char buf[BUFSIZ];
177         int nserv = 0;    /*%< number of nameserver records read from file */
178         int haveenv = 0;
179         int havesearch = 0;
180 #ifdef RESOLVSORT
181         int nsort = 0;
182         char *net;
183 #endif
184         int dots;
185         union res_sockaddr_union u[2];
186         int maxns = MAXNS;
187
188         RES_SET_H_ERRNO(statp, 0);
189         if (statp->_u._ext.ext != NULL)
190                 res_ndestroy(statp);
191
192         if (!preinit) {
193                 statp->retrans = RES_TIMEOUT;
194                 statp->retry = RES_DFLRETRY;
195                 statp->options = RES_DEFAULT;
196         }
197
198         statp->_rnd = malloc(16);
199         res_rndinit(statp);
200         statp->id = res_nrandomid(statp);
201
202         memset(u, 0, sizeof(u));
203 #ifdef USELOOPBACK
204         u[nserv].sin.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
205 #else
206         u[nserv].sin.sin_addr.s_addr = INADDR_ANY;
207 #endif
208         u[nserv].sin.sin_family = AF_INET;
209         u[nserv].sin.sin_port = htons(NAMESERVER_PORT);
210 #ifdef HAVE_SA_LEN
211         u[nserv].sin.sin_len = sizeof(struct sockaddr_in);
212 #endif
213         nserv++;
214 #ifdef HAS_INET6_STRUCTS
215 #ifdef USELOOPBACK
216         u[nserv].sin6.sin6_addr = in6addr_loopback;
217 #else
218         u[nserv].sin6.sin6_addr = in6addr_any;
219 #endif
220         u[nserv].sin6.sin6_family = AF_INET6;
221         u[nserv].sin6.sin6_port = htons(NAMESERVER_PORT);
222 #ifdef HAVE_SA_LEN
223         u[nserv].sin6.sin6_len = sizeof(struct sockaddr_in6);
224 #endif
225         nserv++;
226 #endif
227         statp->nscount = 0;
228         statp->ndots = 1;
229         statp->pfcode = 0;
230         statp->_vcsock = -1;
231         statp->_flags = 0;
232         statp->qhook = NULL;
233         statp->rhook = NULL;
234         statp->_u._ext.nscount = 0;
235         statp->_u._ext.ext = malloc(sizeof(*statp->_u._ext.ext));
236         if (statp->_u._ext.ext != NULL) {
237                 memset(statp->_u._ext.ext, 0, sizeof(*statp->_u._ext.ext));
238                 statp->_u._ext.ext->nsaddrs[0].sin = statp->nsaddr;
239                 strcpy(statp->_u._ext.ext->nsuffix, "ip6.arpa");
240                 strcpy(statp->_u._ext.ext->nsuffix2, "ip6.int");
241                 statp->_u._ext.ext->reload_period = 2;
242         } else {
243                 /*
244                  * Historically res_init() rarely, if at all, failed.
245                  * Examples and applications exist which do not check
246                  * our return code.  Furthermore several applications
247                  * simply call us to get the systems domainname.  So
248                  * rather then immediately fail here we store the
249                  * failure, which is returned later, in h_errno.  And
250                  * prevent the collection of 'nameserver' information
251                  * by setting maxns to 0.  Thus applications that fail
252                  * to check our return code wont be able to make
253                  * queries anyhow.
254                  */
255                 RES_SET_H_ERRNO(statp, NETDB_INTERNAL);
256                 maxns = 0;
257         }
258 #ifdef RESOLVSORT
259         statp->nsort = 0;
260 #endif
261         res_setservers(statp, u, nserv);
262
263 #ifdef  SOLARIS2
264         /*
265          * The old libresolv derived the defaultdomain from NIS/NIS+.
266          * We want to keep this behaviour
267          */
268         {
269                 char buf[sizeof(statp->defdname)], *cp;
270                 int ret;
271
272                 if ((ret = sysinfo(SI_SRPC_DOMAIN, buf, sizeof(buf))) > 0 &&
273                         (unsigned int)ret <= sizeof(buf)) {
274                         if (buf[0] == '+')
275                                 buf[0] = '.';
276                         cp = strchr(buf, '.');
277                         cp = (cp == NULL) ? buf : (cp + 1);
278                         strncpy(statp->defdname, cp,
279                                 sizeof(statp->defdname) - 1);
280                         statp->defdname[sizeof(statp->defdname) - 1] = '\0';
281                 }
282         }
283 #endif  /* SOLARIS2 */
284
285         /* Allow user to override the local domain definition */
286         if (issetugid() == 0 && (cp = getenv("LOCALDOMAIN")) != NULL) {
287                 (void)strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
288                 statp->defdname[sizeof(statp->defdname) - 1] = '\0';
289                 haveenv++;
290
291                 /*
292                  * Set search list to be blank-separated strings
293                  * from rest of env value.  Permits users of LOCALDOMAIN
294                  * to still have a search list, and anyone to set the
295                  * one that they want to use as an individual (even more
296                  * important now that the rfc1535 stuff restricts searches)
297                  */
298                 cp = statp->defdname;
299                 pp = statp->dnsrch;
300                 *pp++ = cp;
301                 for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
302                         if (*cp == '\n')        /*%< silly backwards compat */
303                                 break;
304                         else if (*cp == ' ' || *cp == '\t') {
305                                 *cp = 0;
306                                 n = 1;
307                         } else if (n) {
308                                 *pp++ = cp;
309                                 n = 0;
310                                 havesearch = 1;
311                         }
312                 }
313                 /* null terminate last domain if there are excess */
314                 while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
315                         cp++;
316                 *cp = '\0';
317                 *pp++ = NULL;
318         }
319
320 #define MATCH(line, name) \
321         (!strncmp(line, name, sizeof(name) - 1) && \
322         (line[sizeof(name) - 1] == ' ' || \
323          line[sizeof(name) - 1] == '\t'))
324
325         nserv = 0;
326         if ((fp = fopen(_PATH_RESCONF, "re")) != NULL) {
327             struct stat sb;
328             struct timespec now;
329
330             if (statp->_u._ext.ext != NULL) {
331                 if (_fstat(fileno(fp), &sb) == 0) {
332                     statp->_u._ext.ext->conf_mtim = sb.st_mtim;
333                     if (clock_gettime(CLOCK_MONOTONIC_FAST, &now) == 0) {
334                         statp->_u._ext.ext->conf_stat = now.tv_sec;
335                     }
336                 }
337             }
338
339             /* read the config file */
340             while (fgets(buf, sizeof(buf), fp) != NULL) {
341                 /* skip comments */
342                 if (*buf == ';' || *buf == '#')
343                         continue;
344                 /* read default domain name */
345                 if (MATCH(buf, "domain")) {
346                     if (haveenv)        /*%< skip if have from environ */
347                             continue;
348                     cp = buf + sizeof("domain") - 1;
349                     while (*cp == ' ' || *cp == '\t')
350                             cp++;
351                     if ((*cp == '\0') || (*cp == '\n'))
352                             continue;
353                     strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
354                     statp->defdname[sizeof(statp->defdname) - 1] = '\0';
355                     if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL)
356                             *cp = '\0';
357                     havesearch = 0;
358                     continue;
359                 }
360                 /* set search list */
361                 if (MATCH(buf, "search")) {
362                     if (haveenv)        /*%< skip if have from environ */
363                             continue;
364                     cp = buf + sizeof("search") - 1;
365                     while (*cp == ' ' || *cp == '\t')
366                             cp++;
367                     if ((*cp == '\0') || (*cp == '\n'))
368                             continue;
369                     strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
370                     statp->defdname[sizeof(statp->defdname) - 1] = '\0';
371                     if ((cp = strchr(statp->defdname, '\n')) != NULL)
372                             *cp = '\0';
373                     /*
374                      * Set search list to be blank-separated strings
375                      * on rest of line.
376                      */
377                     cp = statp->defdname;
378                     pp = statp->dnsrch;
379                     *pp++ = cp;
380                     for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
381                             if (*cp == ' ' || *cp == '\t') {
382                                     *cp = 0;
383                                     n = 1;
384                             } else if (n) {
385                                     *pp++ = cp;
386                                     n = 0;
387                             }
388                     }
389                     /* null terminate last domain if there are excess */
390                     while (*cp != '\0' && *cp != ' ' && *cp != '\t')
391                             cp++;
392                     *cp = '\0';
393                     *pp++ = NULL;
394                     havesearch = 1;
395                     continue;
396                 }
397                 /* read nameservers to query */
398                 if (MATCH(buf, "nameserver") && nserv < maxns) {
399                     struct addrinfo hints, *ai;
400                     char sbuf[NI_MAXSERV];
401                     const size_t minsiz =
402                         sizeof(statp->_u._ext.ext->nsaddrs[0]);
403
404                     cp = buf + sizeof("nameserver") - 1;
405                     while (*cp == ' ' || *cp == '\t')
406                         cp++;
407                     cp[strcspn(cp, ";# \t\n")] = '\0';
408                     if ((*cp != '\0') && (*cp != '\n')) {
409                         memset(&hints, 0, sizeof(hints));
410                         hints.ai_family = PF_UNSPEC;
411                         hints.ai_socktype = SOCK_DGRAM; /*dummy*/
412                         hints.ai_flags = AI_NUMERICHOST;
413                         sprintf(sbuf, "%u", NAMESERVER_PORT);
414                         if (getaddrinfo(cp, sbuf, &hints, &ai) == 0 &&
415                             ai->ai_addrlen <= minsiz) {
416                             if (statp->_u._ext.ext != NULL) {
417                                 memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
418                                     ai->ai_addr, ai->ai_addrlen);
419                             }
420                             if (ai->ai_addrlen <=
421                                 sizeof(statp->nsaddr_list[nserv])) {
422                                 memcpy(&statp->nsaddr_list[nserv],
423                                     ai->ai_addr, ai->ai_addrlen);
424                             } else
425                                 statp->nsaddr_list[nserv].sin_family = 0;
426                             freeaddrinfo(ai);
427                             nserv++;
428                         }
429                     }
430                     continue;
431                 }
432 #ifdef RESOLVSORT
433                 if (MATCH(buf, "sortlist")) {
434                     struct in_addr a;
435                     struct in6_addr a6;
436                     int m, i;
437                     u_char *u;
438                     struct __res_state_ext *ext = statp->_u._ext.ext;
439
440                     cp = buf + sizeof("sortlist") - 1;
441                     while (nsort < MAXRESOLVSORT) {
442                         while (*cp == ' ' || *cp == '\t')
443                             cp++;
444                         if (*cp == '\0' || *cp == '\n' || *cp == ';')
445                             break;
446                         net = cp;
447                         while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
448                                isascii(*cp) && !isspace((unsigned char)*cp))
449                                 cp++;
450                         n = *cp;
451                         *cp = 0;
452                         if (inet_aton(net, &a)) {
453                             statp->sort_list[nsort].addr = a;
454                             if (ISSORTMASK(n)) {
455                                 *cp++ = n;
456                                 net = cp;
457                                 while (*cp && *cp != ';' &&
458                                         isascii(*cp) &&
459                                         !isspace((unsigned char)*cp))
460                                     cp++;
461                                 n = *cp;
462                                 *cp = 0;
463                                 if (inet_aton(net, &a)) {
464                                     statp->sort_list[nsort].mask = a.s_addr;
465                                 } else {
466                                     statp->sort_list[nsort].mask = 
467                                         net_mask(statp->sort_list[nsort].addr);
468                                 }
469                             } else {
470                                 statp->sort_list[nsort].mask = 
471                                     net_mask(statp->sort_list[nsort].addr);
472                             }
473                             ext->sort_list[nsort].af = AF_INET;
474                             ext->sort_list[nsort].addr.ina =
475                                 statp->sort_list[nsort].addr;
476                             ext->sort_list[nsort].mask.ina.s_addr =
477                                 statp->sort_list[nsort].mask;
478                             nsort++;
479                         }
480                         else if (inet_pton(AF_INET6, net, &a6) == 1) {
481
482                             ext->sort_list[nsort].af = AF_INET6;
483                             ext->sort_list[nsort].addr.in6a = a6;
484                             u = (u_char *)&ext->sort_list[nsort].mask.in6a;
485                             *cp++ = n;
486                             net = cp;
487                             while (*cp && *cp != ';' &&
488                                     isascii(*cp) && !isspace(*cp))
489                                 cp++;
490                             m = n;
491                             n = *cp;
492                             *cp = 0;
493                             switch (m) {
494                             case '/':
495                                 m = atoi(net);
496                                 break;
497                             case '&':
498                                 if (inet_pton(AF_INET6, net, u) == 1) {
499                                     m = -1;
500                                     break;
501                                 }
502                                 /*FALLTHROUGH*/
503                             default:
504                                 m = sizeof(struct in6_addr) * CHAR_BIT;
505                                 break;
506                             }
507                             if (m >= 0) {
508                                 for (i = 0; i < sizeof(struct in6_addr); i++) {
509                                     if (m <= 0) {
510                                         *u = 0;
511                                     } else {
512                                         m -= CHAR_BIT;
513                                         *u = (u_char)~0;
514                                         if (m < 0)
515                                             *u <<= -m;
516                                     }
517                                     u++;
518                                 }
519                             }
520                             statp->sort_list[nsort].addr.s_addr =
521                                 (u_int32_t)0xffffffff;
522                             statp->sort_list[nsort].mask =
523                                 (u_int32_t)0xffffffff;
524                             nsort++;
525                         }
526                         *cp = n;
527                     }
528                     continue;
529                 }
530 #endif
531                 if (MATCH(buf, "options")) {
532                     res_setoptions(statp, buf + sizeof("options") - 1, "conf");
533                     continue;
534                 }
535             }
536             if (nserv > 0) 
537                 statp->nscount = nserv;
538 #ifdef RESOLVSORT
539             statp->nsort = nsort;
540 #endif
541             (void) fclose(fp);
542         }
543 /*
544  * Last chance to get a nameserver.  This should not normally
545  * be necessary
546  */
547 #ifdef NO_RESOLV_CONF
548         if(nserv == 0)
549                 nserv = get_nameservers(statp);
550 #endif
551
552         if (statp->defdname[0] == 0 &&
553             gethostname(buf, sizeof(statp->defdname) - 1) == 0 &&
554             (cp = strchr(buf, '.')) != NULL)
555                 strcpy(statp->defdname, cp + 1);
556
557         /* find components of local domain that might be searched */
558         if (havesearch == 0) {
559                 pp = statp->dnsrch;
560                 *pp++ = statp->defdname;
561                 *pp = NULL;
562
563                 dots = 0;
564                 for (cp = statp->defdname; *cp; cp++)
565                         dots += (*cp == '.');
566
567                 cp = statp->defdname;
568                 while (pp < statp->dnsrch + MAXDFLSRCH) {
569                         if (dots < LOCALDOMAINPARTS)
570                                 break;
571                         cp = strchr(cp, '.') + 1;    /*%< we know there is one */
572                         *pp++ = cp;
573                         dots--;
574                 }
575                 *pp = NULL;
576 #ifdef DEBUG
577                 if (statp->options & RES_DEBUG) {
578                         printf(";; res_init()... default dnsrch list:\n");
579                         for (pp = statp->dnsrch; *pp; pp++)
580                                 printf(";;\t%s\n", *pp);
581                         printf(";;\t..END..\n");
582                 }
583 #endif
584         }
585
586         if (issetugid())
587                 statp->options |= RES_NOALIASES;
588         else if ((cp = getenv("RES_OPTIONS")) != NULL)
589                 res_setoptions(statp, cp, "env");
590         statp->options |= RES_INIT;
591         return (statp->res_h_errno);
592 }
593
594 static void
595 res_setoptions(res_state statp, const char *options, const char *source)
596 {
597         const char *cp = options;
598         int i;
599         struct __res_state_ext *ext = statp->_u._ext.ext;
600
601 #ifdef DEBUG
602         if (statp->options & RES_DEBUG)
603                 printf(";; res_setoptions(\"%s\", \"%s\")...\n",
604                        options, source);
605 #endif
606         while (*cp) {
607                 /* skip leading and inner runs of spaces */
608                 while (*cp == ' ' || *cp == '\t')
609                         cp++;
610                 /* search for and process individual options */
611                 if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) {
612                         i = atoi(cp + sizeof("ndots:") - 1);
613                         if (i <= RES_MAXNDOTS)
614                                 statp->ndots = i;
615                         else
616                                 statp->ndots = RES_MAXNDOTS;
617 #ifdef DEBUG
618                         if (statp->options & RES_DEBUG)
619                                 printf(";;\tndots=%d\n", statp->ndots);
620 #endif
621                 } else if (!strncmp(cp, "timeout:", sizeof("timeout:") - 1)) {
622                         i = atoi(cp + sizeof("timeout:") - 1);
623                         if (i <= RES_MAXRETRANS)
624                                 statp->retrans = i;
625                         else
626                                 statp->retrans = RES_MAXRETRANS;
627 #ifdef DEBUG
628                         if (statp->options & RES_DEBUG)
629                                 printf(";;\ttimeout=%d\n", statp->retrans);
630 #endif
631 #ifdef  SOLARIS2
632                 } else if (!strncmp(cp, "retrans:", sizeof("retrans:") - 1)) {
633                         /*
634                          * For backward compatibility, 'retrans' is
635                          * supported as an alias for 'timeout', though
636                          * without an imposed maximum.
637                          */
638                         statp->retrans = atoi(cp + sizeof("retrans:") - 1);
639                 } else if (!strncmp(cp, "retry:", sizeof("retry:") - 1)){
640                         /*
641                          * For backward compatibility, 'retry' is
642                          * supported as an alias for 'attempts', though
643                          * without an imposed maximum.
644                          */
645                         statp->retry = atoi(cp + sizeof("retry:") - 1);
646 #endif  /* SOLARIS2 */
647                 } else if (!strncmp(cp, "attempts:", sizeof("attempts:") - 1)){
648                         i = atoi(cp + sizeof("attempts:") - 1);
649                         if (i <= RES_MAXRETRY)
650                                 statp->retry = i;
651                         else
652                                 statp->retry = RES_MAXRETRY;
653 #ifdef DEBUG
654                         if (statp->options & RES_DEBUG)
655                                 printf(";;\tattempts=%d\n", statp->retry);
656 #endif
657                 } else if (!strncmp(cp, "debug", sizeof("debug") - 1)) {
658 #ifdef DEBUG
659                         if (!(statp->options & RES_DEBUG)) {
660                                 printf(";; res_setoptions(\"%s\", \"%s\")..\n",
661                                        options, source);
662                                 statp->options |= RES_DEBUG;
663                         }
664                         printf(";;\tdebug\n");
665 #endif
666                 } else if (!strncmp(cp, "no_tld_query",
667                                     sizeof("no_tld_query") - 1) ||
668                            !strncmp(cp, "no-tld-query",
669                                     sizeof("no-tld-query") - 1)) {
670                         statp->options |= RES_NOTLDQUERY;
671                 } else if (!strncmp(cp, "inet6", sizeof("inet6") - 1)) {
672                         statp->options |= RES_USE_INET6;
673                 } else if (!strncmp(cp, "insecure1", sizeof("insecure1") - 1)) {
674                        statp->options |= RES_INSECURE1;
675                 } else if (!strncmp(cp, "insecure2", sizeof("insecure2") - 1)) {
676                        statp->options |= RES_INSECURE2;
677                 } else if (!strncmp(cp, "rotate", sizeof("rotate") - 1)) {
678                         statp->options |= RES_ROTATE;
679                 } else if (!strncmp(cp, "no-check-names",
680                                     sizeof("no-check-names") - 1)) {
681                         statp->options |= RES_NOCHECKNAME;
682                 } else if (!strncmp(cp, "reload-period:",
683                                     sizeof("reload-period:") - 1)) {
684                         if (ext != NULL) {
685                                 ext->reload_period = (u_short)
686                                     atoi(cp + sizeof("reload-period:") - 1);
687                         }
688                 }
689 #ifdef RES_USE_EDNS0
690                 else if (!strncmp(cp, "edns0", sizeof("edns0") - 1)) {
691                         statp->options |= RES_USE_EDNS0;
692                 }
693 #endif
694 #ifndef _LIBC
695                 else if (!strncmp(cp, "dname", sizeof("dname") - 1)) {
696                         statp->options |= RES_USE_DNAME;
697                 }
698                 else if (!strncmp(cp, "nibble:", sizeof("nibble:") - 1)) {
699                         if (ext == NULL)
700                                 goto skip;
701                         cp += sizeof("nibble:") - 1;
702                         i = MIN(strcspn(cp, " \t"), sizeof(ext->nsuffix) - 1);
703                         strncpy(ext->nsuffix, cp, i);
704                         ext->nsuffix[i] = '\0';
705                 }
706                 else if (!strncmp(cp, "nibble2:", sizeof("nibble2:") - 1)) {
707                         if (ext == NULL)
708                                 goto skip;
709                         cp += sizeof("nibble2:") - 1;
710                         i = MIN(strcspn(cp, " \t"), sizeof(ext->nsuffix2) - 1);
711                         strncpy(ext->nsuffix2, cp, i);
712                         ext->nsuffix2[i] = '\0';
713                 }
714                 else if (!strncmp(cp, "v6revmode:", sizeof("v6revmode:") - 1)) {
715                         cp += sizeof("v6revmode:") - 1;
716                         /* "nibble" and "bitstring" used to be valid */
717                         if (!strncmp(cp, "single", sizeof("single") - 1)) {
718                                 statp->options |= RES_NO_NIBBLE2;
719                         } else if (!strncmp(cp, "both", sizeof("both") - 1)) {
720                                 statp->options &=
721                                          ~RES_NO_NIBBLE2;
722                         }
723                 }
724 #endif
725                 else {
726                         /* XXX - print a warning here? */
727                 }
728 #ifndef _LIBC
729    skip:
730 #endif
731                 /* skip to next run of spaces */
732                 while (*cp && *cp != ' ' && *cp != '\t')
733                         cp++;
734         }
735 }
736
737 #ifdef RESOLVSORT
738 /* XXX - should really support CIDR which means explicit masks always. */
739 static u_int32_t
740 net_mask(struct in_addr in)             /*!< XXX - should really use system's version of this  */
741 {
742         u_int32_t i = ntohl(in.s_addr);
743
744         if (IN_CLASSA(i))
745                 return (htonl(IN_CLASSA_NET));
746         else if (IN_CLASSB(i))
747                 return (htonl(IN_CLASSB_NET));
748         return (htonl(IN_CLASSC_NET));
749 }
750 #endif
751
752 static u_char srnd[16];
753
754 void
755 res_rndinit(res_state statp)
756 {
757         struct timeval now;
758         u_int32_t u32;
759         u_int16_t u16;
760         u_char *rnd = statp->_rnd == NULL ? srnd : statp->_rnd;
761
762         gettimeofday(&now, NULL);
763         u32 = now.tv_sec;
764         memcpy(rnd, &u32, 4);
765         u32 = now.tv_usec;
766         memcpy(rnd + 4, &u32, 4);
767         u32 += now.tv_sec;
768         memcpy(rnd + 8, &u32, 4);
769         u16 = getpid();
770         memcpy(rnd + 12, &u16, 2);
771 }
772
773 u_int
774 res_nrandomid(res_state statp) {
775         struct timeval now;
776         u_int16_t u16;
777         MD5_CTX ctx;
778         u_char *rnd = statp->_rnd == NULL ? srnd : statp->_rnd;
779
780         gettimeofday(&now, NULL);
781         u16 = (u_int16_t) (now.tv_sec ^ now.tv_usec);
782         memcpy(rnd + 14, &u16, 2);
783 #ifndef HAVE_MD5
784         MD5_Init(&ctx);
785         MD5_Update(&ctx, rnd, 16);
786         MD5_Final(rnd, &ctx);
787 #else
788         MD5Init(&ctx);
789         MD5Update(&ctx, rnd, 16);
790         MD5Final(rnd, &ctx);
791 #endif
792         memcpy(&u16, rnd + 14, 2);
793         return ((u_int) u16);
794 }
795
796 /*%
797  * This routine is for closing the socket if a virtual circuit is used and
798  * the program wants to close it.  This provides support for endhostent()
799  * which expects to close the socket.
800  *
801  * This routine is not expected to be user visible.
802  */
803 void
804 res_nclose(res_state statp) {
805         int ns;
806
807         if (statp->_vcsock >= 0) { 
808                 (void) _close(statp->_vcsock);
809                 statp->_vcsock = -1;
810                 statp->_flags &= ~(RES_F_VC | RES_F_CONN);
811         }
812         for (ns = 0; ns < statp->_u._ext.nscount; ns++) {
813                 if (statp->_u._ext.nssocks[ns] != -1) {
814                         (void) _close(statp->_u._ext.nssocks[ns]);
815                         statp->_u._ext.nssocks[ns] = -1;
816                 }
817         }
818 }
819
820 void
821 res_ndestroy(res_state statp) {
822         res_nclose(statp);
823         if (statp->_u._ext.ext != NULL) {
824                 free(statp->_u._ext.ext);
825                 statp->_u._ext.ext = NULL;
826         }
827         if (statp->_rnd != NULL) {
828                 free(statp->_rnd);
829                 statp->_rnd = NULL;
830         }
831         statp->options &= ~RES_INIT;
832 }
833
834 #ifndef _LIBC
835 const char *
836 res_get_nibblesuffix(res_state statp) {
837         if (statp->_u._ext.ext)
838                 return (statp->_u._ext.ext->nsuffix);
839         return ("ip6.arpa");
840 }
841
842 const char *
843 res_get_nibblesuffix2(res_state statp) {
844         if (statp->_u._ext.ext)
845                 return (statp->_u._ext.ext->nsuffix2);
846         return ("ip6.int");
847 }
848 #endif
849
850 void
851 res_setservers(res_state statp, const union res_sockaddr_union *set, int cnt) {
852         int i, nserv;
853         size_t size;
854
855         /* close open servers */
856         res_nclose(statp);
857
858         /* cause rtt times to be forgotten */
859         statp->_u._ext.nscount = 0;
860
861         nserv = 0;
862         for (i = 0; i < cnt && nserv < MAXNS; i++) {
863                 switch (set->sin.sin_family) {
864                 case AF_INET:
865                         size = sizeof(set->sin);
866                         if (statp->_u._ext.ext)
867                                 memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
868                                         &set->sin, size);
869                         if (size <= sizeof(statp->nsaddr_list[nserv]))
870                                 memcpy(&statp->nsaddr_list[nserv],
871                                         &set->sin, size);
872                         else
873                                 statp->nsaddr_list[nserv].sin_family = 0;
874                         nserv++;
875                         break;
876
877 #ifdef HAS_INET6_STRUCTS
878                 case AF_INET6:
879                         size = sizeof(set->sin6);
880                         if (statp->_u._ext.ext)
881                                 memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
882                                         &set->sin6, size);
883                         if (size <= sizeof(statp->nsaddr_list[nserv]))
884                                 memcpy(&statp->nsaddr_list[nserv],
885                                         &set->sin6, size);
886                         else
887                                 statp->nsaddr_list[nserv].sin_family = 0;
888                         nserv++;
889                         break;
890 #endif
891
892                 default:
893                         break;
894                 }
895                 set++;
896         }
897         statp->nscount = nserv;
898         
899 }
900
901 int
902 res_getservers(res_state statp, union res_sockaddr_union *set, int cnt) {
903         int i;
904         size_t size;
905         u_int16_t family;
906
907         for (i = 0; i < statp->nscount && i < cnt; i++) {
908                 if (statp->_u._ext.ext)
909                         family = statp->_u._ext.ext->nsaddrs[i].sin.sin_family;
910                 else 
911                         family = statp->nsaddr_list[i].sin_family;
912
913                 switch (family) {
914                 case AF_INET:
915                         size = sizeof(set->sin);
916                         if (statp->_u._ext.ext)
917                                 memcpy(&set->sin,
918                                        &statp->_u._ext.ext->nsaddrs[i],
919                                        size);
920                         else
921                                 memcpy(&set->sin, &statp->nsaddr_list[i],
922                                        size);
923                         break;
924
925 #ifdef HAS_INET6_STRUCTS
926                 case AF_INET6:
927                         size = sizeof(set->sin6);
928                         if (statp->_u._ext.ext)
929                                 memcpy(&set->sin6,
930                                        &statp->_u._ext.ext->nsaddrs[i],
931                                        size);
932                         else
933                                 memcpy(&set->sin6, &statp->nsaddr_list[i],
934                                        size);
935                         break;
936 #endif
937
938                 default:
939                         set->sin.sin_family = 0;
940                         break;
941                 }
942                 set++;
943         }
944         return (statp->nscount);
945 }
946
947 /*! \file */