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