resolv: Move res_randomid to its own file
[glibc.git] / resolv / res_init.c
blobef2e7c0db465dba67ea0954b66bd6fa89e74f3f2
1 /*
2 * Copyright (c) 1985, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
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.
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.
31 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
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.
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.
51 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
53 * Permission to use, copy, modify, and distribute this software for any
54 * purpose with or without fee is hereby granted, provided that the above
55 * copyright notice and this permission notice appear in all copies.
57 * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
58 * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
59 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
60 * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
61 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
62 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
63 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
64 * SOFTWARE.
67 #include <ctype.h>
68 #include <netdb.h>
69 #include <resolv/resolv-internal.h>
70 #include <stdio.h>
71 #include <stdio_ext.h>
72 #include <stdlib.h>
73 #include <string.h>
74 #include <unistd.h>
75 #include <stdint.h>
76 #include <arpa/inet.h>
77 #include <arpa/nameser.h>
78 #include <net/if.h>
79 #include <netinet/in.h>
80 #include <sys/param.h>
81 #include <sys/socket.h>
82 #include <sys/time.h>
83 #include <sys/types.h>
84 #include <inet/net-internal.h>
86 #include <not-cancel.h>
88 /* Options. Should all be left alone. */
89 /* #undef DEBUG */
91 static void res_setoptions (res_state, const char *, const char *)
92 internal_function;
94 static const char sort_mask_chars[] = "/&";
95 #define ISSORTMASK(ch) (strchr(sort_mask_chars, ch) != NULL)
96 static u_int32_t net_mask (struct in_addr) __THROW;
98 unsigned long long int __res_initstamp attribute_hidden;
101 * Resolver state default settings.
105 * Set up default settings. If the configuration file exist, the values
106 * there will have precedence. Otherwise, the server address is set to
107 * INADDR_LOOPBACK and the default domain name comes from gethostname.
109 * Return 0 if completes successfully, -1 on error
112 res_ninit(res_state statp) {
113 return (__res_vinit(statp, 0));
115 libc_hidden_def (__res_ninit)
117 /* This function has to be reachable by res_data.c but not publically. */
119 __res_vinit(res_state statp, int preinit) {
120 FILE *fp;
121 char *cp, **pp;
122 int n;
123 char buf[BUFSIZ];
124 int nserv = 0; /* number of nameservers read from file */
125 int have_serv6 = 0;
126 int haveenv = 0;
127 int havesearch = 0;
128 int nsort = 0;
129 char *net;
130 statp->_u._ext.initstamp = __res_initstamp;
132 if (!preinit) {
133 statp->retrans = RES_TIMEOUT;
134 statp->retry = RES_DFLRETRY;
135 statp->options = RES_DEFAULT;
136 statp->id = res_randomid();
139 statp->nscount = 0;
140 statp->defdname[0] = '\0';
141 statp->ndots = 1;
142 statp->pfcode = 0;
143 statp->_vcsock = -1;
144 statp->_flags = 0;
145 statp->__glibc_unused_qhook = NULL;
146 statp->__glibc_unused_rhook = NULL;
147 statp->_u._ext.nscount = 0;
148 for (n = 0; n < MAXNS; n++)
149 statp->_u._ext.nsaddrs[n] = NULL;
151 /* Allow user to override the local domain definition */
152 if ((cp = getenv("LOCALDOMAIN")) != NULL) {
153 (void)strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
154 statp->defdname[sizeof(statp->defdname) - 1] = '\0';
155 haveenv++;
158 * Set search list to be blank-separated strings
159 * from rest of env value. Permits users of LOCALDOMAIN
160 * to still have a search list, and anyone to set the
161 * one that they want to use as an individual (even more
162 * important now that the rfc1535 stuff restricts searches)
164 cp = statp->defdname;
165 pp = statp->dnsrch;
166 *pp++ = cp;
167 for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
168 if (*cp == '\n') /* silly backwards compat */
169 break;
170 else if (*cp == ' ' || *cp == '\t') {
171 *cp = 0;
172 n = 1;
173 } else if (n) {
174 *pp++ = cp;
175 n = 0;
176 havesearch = 1;
179 /* null terminate last domain if there are excess */
180 while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
181 cp++;
182 *cp = '\0';
183 *pp++ = 0;
186 #define MATCH(line, name) \
187 (!strncmp(line, name, sizeof(name) - 1) && \
188 (line[sizeof(name) - 1] == ' ' || \
189 line[sizeof(name) - 1] == '\t'))
191 if ((fp = fopen(_PATH_RESCONF, "rce")) != NULL) {
192 /* No threads use this stream. */
193 __fsetlocking (fp, FSETLOCKING_BYCALLER);
194 /* read the config file */
195 while (__fgets_unlocked(buf, sizeof(buf), fp) != NULL) {
196 /* skip comments */
197 if (*buf == ';' || *buf == '#')
198 continue;
199 /* read default domain name */
200 if (MATCH(buf, "domain")) {
201 if (haveenv) /* skip if have from environ */
202 continue;
203 cp = buf + sizeof("domain") - 1;
204 while (*cp == ' ' || *cp == '\t')
205 cp++;
206 if ((*cp == '\0') || (*cp == '\n'))
207 continue;
208 strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
209 statp->defdname[sizeof(statp->defdname) - 1] = '\0';
210 if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL)
211 *cp = '\0';
212 havesearch = 0;
213 continue;
215 /* set search list */
216 if (MATCH(buf, "search")) {
217 if (haveenv) /* skip if have from environ */
218 continue;
219 cp = buf + sizeof("search") - 1;
220 while (*cp == ' ' || *cp == '\t')
221 cp++;
222 if ((*cp == '\0') || (*cp == '\n'))
223 continue;
224 strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
225 statp->defdname[sizeof(statp->defdname) - 1] = '\0';
226 if ((cp = strchr(statp->defdname, '\n')) != NULL)
227 *cp = '\0';
229 * Set search list to be blank-separated strings
230 * on rest of line.
232 cp = statp->defdname;
233 pp = statp->dnsrch;
234 *pp++ = cp;
235 for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
236 if (*cp == ' ' || *cp == '\t') {
237 *cp = 0;
238 n = 1;
239 } else if (n) {
240 *pp++ = cp;
241 n = 0;
244 /* null terminate last domain if there are excess */
245 while (*cp != '\0' && *cp != ' ' && *cp != '\t')
246 cp++;
247 *cp = '\0';
248 *pp++ = 0;
249 havesearch = 1;
250 continue;
252 /* read nameservers to query */
253 if (MATCH(buf, "nameserver") && nserv < MAXNS) {
254 struct in_addr a;
256 cp = buf + sizeof("nameserver") - 1;
257 while (*cp == ' ' || *cp == '\t')
258 cp++;
259 if ((*cp != '\0') && (*cp != '\n')
260 && __inet_aton(cp, &a)) {
261 statp->nsaddr_list[nserv].sin_addr = a;
262 statp->nsaddr_list[nserv].sin_family = AF_INET;
263 statp->nsaddr_list[nserv].sin_port =
264 htons(NAMESERVER_PORT);
265 nserv++;
266 } else {
267 struct in6_addr a6;
268 char *el;
270 if ((el = strpbrk(cp, " \t\n")) != NULL)
271 *el = '\0';
272 if ((el = strchr(cp, SCOPE_DELIMITER)) != NULL)
273 *el = '\0';
274 if ((*cp != '\0') &&
275 (__inet_pton(AF_INET6, cp, &a6) > 0)) {
276 struct sockaddr_in6 *sa6;
278 sa6 = malloc(sizeof(*sa6));
279 if (sa6 != NULL) {
280 sa6->sin6_family = AF_INET6;
281 sa6->sin6_port = htons(NAMESERVER_PORT);
282 sa6->sin6_flowinfo = 0;
283 sa6->sin6_addr = a6;
285 sa6->sin6_scope_id = 0;
286 if (__glibc_likely (el != NULL)) {
287 /* Ignore errors, for backwards
288 compatibility. */
289 (void) __inet6_scopeid_pton
290 (&a6, el + 1, &sa6->sin6_scope_id);
293 statp->nsaddr_list[nserv].sin_family = 0;
294 statp->_u._ext.nsaddrs[nserv] = sa6;
295 statp->_u._ext.nssocks[nserv] = -1;
296 have_serv6 = 1;
297 nserv++;
301 continue;
303 if (MATCH(buf, "sortlist")) {
304 struct in_addr a;
306 cp = buf + sizeof("sortlist") - 1;
307 while (nsort < MAXRESOLVSORT) {
308 while (*cp == ' ' || *cp == '\t')
309 cp++;
310 if (*cp == '\0' || *cp == '\n' || *cp == ';')
311 break;
312 net = cp;
313 while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
314 isascii(*cp) && !isspace(*cp))
315 cp++;
316 n = *cp;
317 *cp = 0;
318 if (__inet_aton(net, &a)) {
319 statp->sort_list[nsort].addr = a;
320 if (ISSORTMASK(n)) {
321 *cp++ = n;
322 net = cp;
323 while (*cp && *cp != ';' &&
324 isascii(*cp) && !isspace(*cp))
325 cp++;
326 n = *cp;
327 *cp = 0;
328 if (__inet_aton(net, &a)) {
329 statp->sort_list[nsort].mask = a.s_addr;
330 } else {
331 statp->sort_list[nsort].mask =
332 net_mask(statp->sort_list[nsort].addr);
334 } else {
335 statp->sort_list[nsort].mask =
336 net_mask(statp->sort_list[nsort].addr);
338 nsort++;
340 *cp = n;
342 continue;
344 if (MATCH(buf, "options")) {
345 res_setoptions(statp, buf + sizeof("options") - 1, "conf");
346 continue;
349 statp->nscount = nserv;
350 if (have_serv6) {
351 /* We try IPv6 servers again. */
352 statp->ipv6_unavail = false;
354 statp->nsort = nsort;
355 (void) fclose(fp);
357 if (__glibc_unlikely (statp->nscount == 0)) {
358 statp->nsaddr.sin_addr = __inet_makeaddr(IN_LOOPBACKNET, 1);
359 statp->nsaddr.sin_family = AF_INET;
360 statp->nsaddr.sin_port = htons(NAMESERVER_PORT);
361 statp->nscount = 1;
363 if (statp->defdname[0] == 0 &&
364 __gethostname(buf, sizeof(statp->defdname) - 1) == 0 &&
365 (cp = strchr(buf, '.')) != NULL)
366 strcpy(statp->defdname, cp + 1);
368 /* find components of local domain that might be searched */
369 if (havesearch == 0) {
370 pp = statp->dnsrch;
371 *pp++ = statp->defdname;
372 *pp = NULL;
376 if ((cp = getenv("RES_OPTIONS")) != NULL)
377 res_setoptions(statp, cp, "env");
378 statp->options |= RES_INIT;
379 return (0);
382 static void
383 internal_function
384 res_setoptions(res_state statp, const char *options, const char *source) {
385 const char *cp = options;
386 int i;
388 #ifdef DEBUG
389 if (statp->options & RES_DEBUG)
390 printf(";; res_setoptions(\"%s\", \"%s\")...\n",
391 options, source);
392 #endif
393 while (*cp) {
394 /* skip leading and inner runs of spaces */
395 while (*cp == ' ' || *cp == '\t')
396 cp++;
397 /* search for and process individual options */
398 if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) {
399 i = atoi(cp + sizeof("ndots:") - 1);
400 if (i <= RES_MAXNDOTS)
401 statp->ndots = i;
402 else
403 statp->ndots = RES_MAXNDOTS;
404 #ifdef DEBUG
405 if (statp->options & RES_DEBUG)
406 printf(";;\tndots=%d\n", statp->ndots);
407 #endif
408 } else if (!strncmp(cp, "timeout:", sizeof("timeout:") - 1)) {
409 i = atoi(cp + sizeof("timeout:") - 1);
410 if (i <= RES_MAXRETRANS)
411 statp->retrans = i;
412 else
413 statp->retrans = RES_MAXRETRANS;
414 } else if (!strncmp(cp, "attempts:", sizeof("attempts:") - 1)){
415 i = atoi(cp + sizeof("attempts:") - 1);
416 if (i <= RES_MAXRETRY)
417 statp->retry = i;
418 else
419 statp->retry = RES_MAXRETRY;
420 } else if (!strncmp(cp, "debug", sizeof("debug") - 1)) {
421 #ifdef DEBUG
422 if (!(statp->options & RES_DEBUG)) {
423 printf(";; res_setoptions(\"%s\", \"%s\")..\n",
424 options, source);
425 statp->options |= RES_DEBUG;
427 printf(";;\tdebug\n");
428 #endif
429 } else {
430 static const struct
432 char str[22];
433 uint8_t len;
434 uint8_t clear;
435 unsigned long int flag;
436 } options[] = {
437 #define STRnLEN(str) str, sizeof (str) - 1
438 { STRnLEN ("inet6"), 0, DEPRECATED_RES_USE_INET6 },
439 { STRnLEN ("rotate"), 0, RES_ROTATE },
440 { STRnLEN ("edns0"), 0, RES_USE_EDNS0 },
441 { STRnLEN ("single-request-reopen"), 0, RES_SNGLKUPREOP },
442 { STRnLEN ("single-request"), 0, RES_SNGLKUP },
443 { STRnLEN ("no_tld_query"), 0, RES_NOTLDQUERY },
444 { STRnLEN ("no-tld-query"), 0, RES_NOTLDQUERY },
445 { STRnLEN ("use-vc"), 0, RES_USEVC }
447 #define noptions (sizeof (options) / sizeof (options[0]))
448 int i;
449 for (i = 0; i < noptions; ++i)
450 if (strncmp (cp, options[i].str, options[i].len) == 0)
452 if (options[i].clear)
453 statp->options &= options[i].flag;
454 else
455 statp->options |= options[i].flag;
456 break;
458 if (i == noptions) {
459 /* XXX - print a warning here? */
462 /* skip to next run of spaces */
463 while (*cp && *cp != ' ' && *cp != '\t')
464 cp++;
468 /* XXX - should really support CIDR which means explicit masks always. */
469 /* XXX - should really use system's version of this */
470 static u_int32_t
471 net_mask (struct in_addr in)
473 u_int32_t i = ntohl(in.s_addr);
475 if (IN_CLASSA(i))
476 return (htonl(IN_CLASSA_NET));
477 else if (IN_CLASSB(i))
478 return (htonl(IN_CLASSB_NET));
479 return (htonl(IN_CLASSC_NET));
483 * This routine is for closing the socket if a virtual circuit is used and
484 * the program wants to close it. This provides support for endhostent()
485 * which expects to close the socket.
487 * This routine is not expected to be user visible.
489 void
490 __res_iclose(res_state statp, bool free_addr) {
491 int ns;
493 if (statp->_vcsock >= 0) {
494 close_not_cancel_no_status(statp->_vcsock);
495 statp->_vcsock = -1;
496 statp->_flags &= ~(RES_F_VC | RES_F_CONN);
498 for (ns = 0; ns < statp->nscount; ns++)
499 if (statp->_u._ext.nsaddrs[ns]) {
500 if (statp->_u._ext.nssocks[ns] != -1) {
501 close_not_cancel_no_status(statp->_u._ext.nssocks[ns]);
502 statp->_u._ext.nssocks[ns] = -1;
504 if (free_addr) {
505 free (statp->_u._ext.nsaddrs[ns]);
506 statp->_u._ext.nsaddrs[ns] = NULL;
510 libc_hidden_def (__res_iclose)
512 void
513 res_nclose(res_state statp)
515 __res_iclose (statp, true);
517 libc_hidden_def (__res_nclose)
519 /* This is called when a thread is exiting to free resources held in _res. */
520 static void __attribute__ ((section ("__libc_thread_freeres_fn")))
521 res_thread_freeres (void)
523 if (_res.nscount == 0)
524 /* Never called res_ninit. */
525 return;
527 __res_iclose (&_res, true); /* Close any VC sockets. */
529 /* Make sure we do a full re-initialization the next time. */
530 _res.options = 0;
532 text_set_element (__libc_thread_subfreeres, res_thread_freeres);
533 text_set_element (__libc_subfreeres, res_thread_freeres);