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