xref: /openbsd-src/lib/libc/asr/asr.c (revision 43f9b9884eaec506014e68ec4f0b7b0064120d27)
1 /*	$OpenBSD: asr.c,v 1.19 2013/04/01 15:49:54 deraadt Exp $	*/
2 /*
3  * Copyright (c) 2010-2012 Eric Faurot <eric@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <netinet/in.h>
21 #include <arpa/inet.h>
22 #include <arpa/nameser.h>
23 
24 #include <err.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <netdb.h>
28 #include <resolv.h>
29 #include <poll.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34 
35 #include "asr.h"
36 #include "asr_private.h"
37 
38 #ifndef ASR_OPT_THREADSAFE
39 #define ASR_OPT_THREADSAFE 1
40 #endif
41 #ifndef ASR_OPT_HOSTALIASES
42 #define ASR_OPT_HOSTALIASES 1
43 #endif
44 #ifndef ASR_OPT_ENVOPTS
45 #define ASR_OPT_ENVOPTS 1
46 #endif
47 #ifndef ASR_OPT_RELOADCONF
48 #define ASR_OPT_RELOADCONF 1
49 #endif
50 #ifndef ASR_OPT_ALTCONF
51 #define ASR_OPT_ALTCONF 1
52 #endif
53 
54 #if ASR_OPT_THREADSAFE
55 #include "thread_private.h"
56 #endif
57 
58 #define DEFAULT_CONFFILE	"/etc/resolv.conf"
59 #define DEFAULT_HOSTFILE	"/etc/hosts"
60 #define DEFAULT_CONF		"lookup file\n"
61 #define DEFAULT_LOOKUP		"lookup bind file"
62 
63 #define RELOAD_DELAY		15 /* seconds */
64 
65 static void asr_check_reload(struct asr *);
66 static struct asr_ctx *asr_ctx_create(void);
67 static void asr_ctx_ref(struct asr_ctx *);
68 static void asr_ctx_free(struct asr_ctx *);
69 static int asr_ctx_add_searchdomain(struct asr_ctx *, const char *);
70 static int asr_ctx_from_file(struct asr_ctx *, const char *);
71 static int asr_ctx_from_string(struct asr_ctx *, const char *);
72 static int asr_ctx_parse(struct asr_ctx *, const char *);
73 static int asr_parse_nameserver(struct sockaddr *, const char *);
74 static int asr_ndots(const char *);
75 static void pass0(char **, int, struct asr_ctx *);
76 static int strsplit(char *, char **, int);
77 #if ASR_OPT_HOSTALIASES
78 static char *asr_hostalias(const char *, char *, size_t);
79 #endif
80 #if ASR_OPT_ENVOPTS
81 static void asr_ctx_envopts(struct asr_ctx *);
82 #endif
83 #if ASR_OPT_THREADSAFE
84 static void *__THREAD_NAME(_asr);
85 #else
86 #	define _THREAD_PRIVATE(a, b, c)  (c)
87 #endif
88 
89 static struct asr *_asr = NULL;
90 
91 /* Allocate and configure an async "resolver". */
92 struct asr *
93 async_resolver(const char *conf)
94 {
95 	static int	 init = 0;
96 	struct asr	*asr;
97 
98 	if (init == 0) {
99 #ifdef DEBUG
100 		if (getenv("ASR_DEBUG"))
101 			asr_debug = stderr;
102 #endif
103 		init = 1;
104 	}
105 
106 	if ((asr = calloc(1, sizeof(*asr))) == NULL)
107 		goto fail;
108 
109 #if ASR_OPT_ALTCONF
110 	/* If not setuid/setgid, allow to use an alternate config. */
111 	if (conf == NULL && !issetugid())
112 		conf = getenv("ASR_CONFIG");
113 #endif
114 
115 	if (conf == NULL)
116 		conf = DEFAULT_CONFFILE;
117 
118 	if (conf[0] == '!') {
119 		/* Use the rest of the string as config file */
120 		if ((asr->a_ctx = asr_ctx_create()) == NULL)
121 			goto fail;
122 		if (asr_ctx_from_string(asr->a_ctx, conf + 1) == -1)
123 			goto fail;
124 	} else {
125 		/* Use the given config file */
126 		asr->a_path = strdup(conf);
127 		asr_check_reload(asr);
128 		if (asr->a_ctx == NULL) {
129 			if ((asr->a_ctx = asr_ctx_create()) == NULL)
130 				goto fail;
131 			if (asr_ctx_from_string(asr->a_ctx, DEFAULT_CONF) == -1)
132 				goto fail;
133 #if ASR_OPT_ENVOPTS
134 			asr_ctx_envopts(asr->a_ctx);
135 #endif
136 		}
137 	}
138 
139 #ifdef DEBUG
140 	asr_dump_config(asr_debug, asr);
141 #endif
142 	return (asr);
143 
144     fail:
145 	if (asr) {
146 		if (asr->a_ctx)
147 			asr_ctx_free(asr->a_ctx);
148 		free(asr);
149 	}
150 
151 	return (NULL);
152 }
153 
154 /*
155  * Free the "asr" async resolver (or the thread-local resolver if NULL).
156  * Drop the reference to the current context.
157  */
158 void
159 async_resolver_done(struct asr *asr)
160 {
161 	struct asr **priv;
162 
163 	if (asr == NULL) {
164 		priv = _THREAD_PRIVATE(_asr, asr, &_asr);
165 		if (*priv == NULL)
166 			return;
167 		asr = *priv;
168 		*priv = NULL;
169 	}
170 
171 	asr_ctx_unref(asr->a_ctx);
172 	if (asr->a_path)
173 		free(asr->a_path);
174 	free(asr);
175 }
176 
177 /*
178  * Cancel an async query.
179  */
180 void
181 async_abort(struct async *as)
182 {
183 	async_free(as);
184 }
185 
186 /*
187  * Resume the "as" async query resolution.  Return one of ASYNC_COND,
188  * ASYNC_YIELD or ASYNC_DONE and put query-specific return values in
189  * the user-allocated memory at "ar".
190  */
191 int
192 async_run(struct async *as, struct async_res *ar)
193 {
194 	int	r, saved_errno = errno;
195 
196 	DPRINT("asr: async_run(%p, %p) %s ctx=[%p]\n", as, ar,
197 	    asr_querystr(as->as_type), as->as_ctx);
198 	r = as->as_run(as, ar);
199 
200 	DPRINT("asr: async_run(%p, %p) -> %s", as, ar, asr_transitionstr(r));
201 #ifdef DEBUG
202 	if (r == ASYNC_COND)
203 #endif
204 		DPRINT(" fd=%i timeout=%i", ar->ar_fd, ar->ar_timeout);
205 	DPRINT("\n");
206 	if (r == ASYNC_DONE)
207 		async_free(as);
208 
209 	errno = saved_errno;
210 
211 	return (r);
212 }
213 
214 /*
215  * Same as above, but run in a loop that handles the fd conditions result.
216  */
217 int
218 async_run_sync(struct async *as, struct async_res *ar)
219 {
220 	struct pollfd	 fds[1];
221 	int		 r, saved_errno = errno;
222 
223 	while ((r = async_run(as, ar)) == ASYNC_COND) {
224 		fds[0].fd = ar->ar_fd;
225 		fds[0].events = (ar->ar_cond == ASYNC_READ) ? POLLIN : POLLOUT;
226 	again:
227 		r = poll(fds, 1, ar->ar_timeout);
228 		if (r == -1 && errno == EINTR)
229 			goto again;
230 		/*
231 		 * Otherwise, just ignore the error and let async_run()
232 		 * catch the failure.
233 		 */
234 	}
235 
236 	errno = saved_errno;
237 
238 	return (r);
239 }
240 
241 /*
242  * Create a new async request of the given "type" on the async context "ac".
243  * Take a reference on it so it does not gets deleted while the async query
244  * is running.
245  */
246 struct async *
247 async_new(struct asr_ctx *ac, int type)
248 {
249 	struct async	*as;
250 
251 	DPRINT("asr: async_new(ctx=%p) type=%i refcount=%i\n", ac, type,
252 	    ac->ac_refcount);
253 	if ((as = calloc(1, sizeof(*as))) == NULL)
254 		return (NULL);
255 
256 	ac->ac_refcount += 1;
257 	as->as_ctx = ac;
258 	as->as_fd = -1;
259 	as->as_type = type;
260 	as->as_state = ASR_STATE_INIT;
261 
262 	return (as);
263 }
264 
265 /*
266  * Free an async query and unref the associated context.
267  */
268 void
269 async_free(struct async *as)
270 {
271 	DPRINT("asr: async_free(%p)\n", as);
272 	switch (as->as_type) {
273 	case ASR_SEND:
274 		if (as->as_fd != -1)
275 			close(as->as_fd);
276 		if (as->as.dns.obuf && !(as->as.dns.flags & ASYNC_EXTOBUF))
277 			free(as->as.dns.obuf);
278 		if (as->as.dns.ibuf && !(as->as.dns.flags & ASYNC_EXTIBUF))
279 			free(as->as.dns.ibuf);
280 		if (as->as.dns.dname)
281 			free(as->as.dns.dname);
282 		break;
283 
284 	case ASR_SEARCH:
285 		if (as->as.search.subq)
286 			async_free(as->as.search.subq);
287 		if (as->as.search.name)
288 			free(as->as.search.name);
289 		break;
290 
291 	case ASR_GETRRSETBYNAME:
292 		if (as->as.rrset.subq)
293 			async_free(as->as.rrset.subq);
294 		if (as->as.rrset.name)
295 			free(as->as.rrset.name);
296 		break;
297 
298 	case ASR_GETHOSTBYNAME:
299 	case ASR_GETHOSTBYADDR:
300 		if (as->as.hostnamadr.subq)
301 			async_free(as->as.hostnamadr.subq);
302 		if (as->as.hostnamadr.name)
303 			free(as->as.hostnamadr.name);
304 		break;
305 
306 	case ASR_GETNETBYNAME:
307 	case ASR_GETNETBYADDR:
308 		if (as->as.netnamadr.subq)
309 			async_free(as->as.netnamadr.subq);
310 		if (as->as.netnamadr.name)
311 			free(as->as.netnamadr.name);
312 		break;
313 
314 	case ASR_GETADDRINFO:
315 		if (as->as.ai.subq)
316 			async_free(as->as.ai.subq);
317 		if (as->as.ai.aifirst)
318 			freeaddrinfo(as->as.ai.aifirst);
319 		if (as->as.ai.hostname)
320 			free(as->as.ai.hostname);
321 		if (as->as.ai.servname)
322 			free(as->as.ai.servname);
323 		if (as->as.ai.fqdn)
324 			free(as->as.ai.fqdn);
325 		break;
326 
327 	case ASR_GETNAMEINFO:
328 		if (as->as.ni.subq)
329 			async_free(as->as.ni.subq);
330 		break;
331 	}
332 
333 	asr_ctx_unref(as->as_ctx);
334 	free(as);
335 }
336 
337 /*
338  * Get a context from the given resolver. This takes a new reference to
339  * the returned context, which *must* be explicitely dropped when done
340  * using this context.
341  */
342 struct asr_ctx *
343 asr_use_resolver(struct asr *asr)
344 {
345 	struct asr **priv;
346 
347 	if (asr == NULL) {
348 		DPRINT("using thread-local resolver\n");
349 		priv = _THREAD_PRIVATE(_asr, asr, &_asr);
350 		if (*priv == NULL) {
351 			DPRINT("setting up thread-local resolver\n");
352 			*priv = async_resolver(NULL);
353 		}
354 		asr = *priv;
355 	}
356 
357 	asr_check_reload(asr);
358 	asr_ctx_ref(asr->a_ctx);
359 	return (asr->a_ctx);
360 }
361 
362 static void
363 asr_ctx_ref(struct asr_ctx *ac)
364 {
365 	DPRINT("asr: asr_ctx_ref(ctx=%p) refcount=%i\n", ac, ac->ac_refcount);
366 	ac->ac_refcount += 1;
367 }
368 
369 /*
370  * Drop a reference to an async context, freeing it if the reference
371  * count drops to 0.
372  */
373 void
374 asr_ctx_unref(struct asr_ctx *ac)
375 {
376 	DPRINT("asr: asr_ctx_unref(ctx=%p) refcount=%i\n", ac, ac->ac_refcount);
377 	if (--ac->ac_refcount)
378 		return;
379 
380 	asr_ctx_free(ac);
381 }
382 
383 static void
384 asr_ctx_free(struct asr_ctx *ac)
385 {
386 	int i;
387 
388 	if (ac->ac_domain)
389 		free(ac->ac_domain);
390 	for (i = 0; i < ac->ac_nscount; i++)
391 		free(ac->ac_ns[i]);
392 	for (i = 0; i < ac->ac_domcount; i++)
393 		free(ac->ac_dom[i]);
394 
395 	free(ac);
396 }
397 
398 /*
399  * Reload the configuration file if it has changed on disk.
400  */
401 static void
402 asr_check_reload(struct asr *asr)
403 {
404 	struct asr_ctx	*ac;
405 #if ASR_OPT_RELOADCONF
406 	struct stat	 st;
407 	struct timespec	 tp;
408 #endif
409 
410 	if (asr->a_path == NULL)
411 		return;
412 
413 #if ASR_OPT_RELOADCONF
414 	if (clock_gettime(CLOCK_MONOTONIC, &tp) == -1)
415 		return;
416 
417 	if ((tp.tv_sec - asr->a_rtime) < RELOAD_DELAY && asr->a_rtime != 0)
418 		return;
419 	asr->a_rtime = tp.tv_sec;
420 
421 	DPRINT("asr: checking for update of \"%s\"\n", asr->a_path);
422 	if (stat(asr->a_path, &st) == -1 ||
423 	    asr->a_mtime == st.st_mtime ||
424 	    (ac = asr_ctx_create()) == NULL)
425 		return;
426 	asr->a_mtime = st.st_mtime;
427 #else
428 	if ((ac = asr_ctx_create()) == NULL)
429 		return;
430 #endif
431 
432 	DPRINT("asr: reloading config file\n");
433 	if (asr_ctx_from_file(ac, asr->a_path) == -1) {
434 		asr_ctx_free(ac);
435 		return;
436 	}
437 
438 #if ASR_OPT_ENVOPTS
439 	asr_ctx_envopts(ac);
440 #endif
441 	if (asr->a_ctx)
442 		asr_ctx_unref(asr->a_ctx);
443 	asr->a_ctx = ac;
444 }
445 
446 /*
447  * Construct a fully-qualified domain name for the given name and domain.
448  * If "name" ends with a '.' it is considered as a FQDN by itself.
449  * Otherwise, the domain, which must be a FQDN, is appended to "name" (it
450  * may have a leading dot which would be ignored). If the domain is null,
451  * then "." is used. Return the length of the constructed FQDN or (0) on
452  * error.
453  */
454 size_t
455 asr_make_fqdn(const char *name, const char *domain, char *buf, size_t buflen)
456 {
457 	size_t	len;
458 
459 	if (domain == NULL)
460 		domain = ".";
461 	else if ((len = strlen(domain)) == 0)
462 		return (0);
463 	else if (domain[len -1] != '.')
464 		return (0);
465 
466 	len = strlen(name);
467 	if (len == 0) {
468 		strlcpy(buf, domain, buflen);
469 	} else if (name[len - 1] !=  '.') {
470 		if (domain[0] == '.')
471 			domain += 1;
472 		strlcpy(buf, name, buflen);
473 		strlcat(buf, ".", buflen);
474 		strlcat(buf, domain, buflen);
475 	} else {
476 		strlcpy(buf, name, buflen);
477 	}
478 
479 	return (strlen(buf));
480 }
481 
482 /*
483  * Concatenate a name and a domain name. The result has no trailing dot.
484  */
485 size_t
486 asr_domcat(const char *name, const char *domain, char *buf, size_t buflen)
487 {
488 	size_t	r;
489 
490 	r = asr_make_fqdn(name, domain, buf, buflen);
491 	if (r == 0)
492 		return (0);
493 	buf[r - 1] = '\0';
494 
495 	return (r - 1);
496 }
497 
498 /*
499  * Count the dots in a string.
500  */
501 static int
502 asr_ndots(const char *s)
503 {
504 	int n;
505 
506 	for (n = 0; *s; s++)
507 		if (*s == '.')
508 			n += 1;
509 
510 	return (n);
511 }
512 
513 /*
514  * Allocate a new empty context.
515  */
516 static struct asr_ctx *
517 asr_ctx_create(void)
518 {
519 	struct asr_ctx	*ac;
520 
521 	if ((ac = calloc(1, sizeof(*ac))) == NULL)
522 		return (NULL);
523 
524 	ac->ac_options = RES_RECURSE | RES_DEFNAMES | RES_DNSRCH;
525 	ac->ac_refcount = 1;
526 	ac->ac_ndots = 1;
527 	ac->ac_family[0] = AF_INET;
528 	ac->ac_family[1] = AF_INET6;
529 	ac->ac_family[2] = -1;
530 
531 	ac->ac_hostfile = DEFAULT_HOSTFILE;
532 
533 	ac->ac_nscount = 0;
534 	ac->ac_nstimeout = 5;
535 	ac->ac_nsretries = 4;
536 
537 	return (ac);
538 }
539 
540 /*
541  * Add a search domain to the async context.
542  */
543 static int
544 asr_ctx_add_searchdomain(struct asr_ctx *ac, const char *domain)
545 {
546 	char buf[MAXDNAME];
547 
548 	if (ac->ac_domcount == ASR_MAXDOM)
549 		return (-1);
550 
551 	if (asr_make_fqdn(domain, NULL, buf, sizeof(buf)) == 0)
552 		return (-1);
553 
554 	if ((ac->ac_dom[ac->ac_domcount] = strdup(buf)) == NULL)
555 		return (0);
556 
557 	ac->ac_domcount += 1;
558 
559 	return (1);
560 }
561 
562 static int
563 strsplit(char *line, char **tokens, int ntokens)
564 {
565 	int	ntok;
566 	char	*cp, **tp;
567 
568 	for (cp = line, tp = tokens, ntok = 0;
569 	    ntok < ntokens && (*tp = strsep(&cp, " \t")) != NULL; )
570 		if (**tp != '\0') {
571 			tp++;
572 			ntok++;
573 		}
574 
575 	return (ntok);
576 }
577 
578 /*
579  * Pass on a split config line.
580  */
581 static void
582 pass0(char **tok, int n, struct asr_ctx *ac)
583 {
584 	int		 i, j, d;
585 	const char	*e;
586 	struct sockaddr_storage	ss;
587 
588 	if (!strcmp(tok[0], "nameserver")) {
589 		if (ac->ac_nscount == ASR_MAXNS)
590 			return;
591 		if (n != 2)
592 			return;
593 		if (asr_parse_nameserver((struct sockaddr *)&ss, tok[1]))
594 			return;
595 		if ((ac->ac_ns[ac->ac_nscount] = calloc(1, ss.ss_len)) == NULL)
596 			return;
597 		memmove(ac->ac_ns[ac->ac_nscount], &ss, ss.ss_len);
598 		ac->ac_nscount += 1;
599 
600 	} else if (!strcmp(tok[0], "domain")) {
601 		if (n != 2)
602 			return;
603 		if (ac->ac_domain)
604 			return;
605 		ac->ac_domain = strdup(tok[1]);
606 
607 	} else if (!strcmp(tok[0], "lookup")) {
608 		/* ignore the line if we already set lookup */
609 		if (ac->ac_dbcount != 0)
610 			return;
611 		if (n - 1 > ASR_MAXDB)
612 			return;
613 		/* ensure that each lookup is only given once */
614 		for (i = 1; i < n; i++)
615 			for (j = i + 1; j < n; j++)
616 				if (!strcmp(tok[i], tok[j]))
617 					return;
618 		for (i = 1; i < n; i++, ac->ac_dbcount++) {
619 			if (!strcmp(tok[i], "yp")) {
620 				ac->ac_db[i-1] = ASR_DB_YP;
621 			} else if (!strcmp(tok[i], "bind")) {
622 				ac->ac_db[i-1] = ASR_DB_DNS;
623 			} else if (!strcmp(tok[i], "file")) {
624 				ac->ac_db[i-1] = ASR_DB_FILE;
625 			} else {
626 				/* ignore the line */
627 				ac->ac_dbcount = 0;
628 				return;
629 			}
630 		}
631 	} else if (!strcmp(tok[0], "search")) {
632 		/* resolv.conf says the last line wins */
633 		for (i = 0; i < ac->ac_domcount; i++)
634 			free(ac->ac_dom[i]);
635 		ac->ac_domcount = 0;
636 		for (i = 1; i < n; i++)
637 			asr_ctx_add_searchdomain(ac, tok[i]);
638 
639 	} else if (!strcmp(tok[0], "family")) {
640 		if (n == 1 || n > 3)
641 			return;
642 		for (i = 1; i < n; i++)
643 			if (strcmp(tok[i], "inet4") && strcmp(tok[i], "inet6"))
644 				return;
645 		for (i = 1; i < n; i++)
646 			ac->ac_family[i - 1] = strcmp(tok[i], "inet4") ? \
647 			    AF_INET6 : AF_INET;
648 		ac->ac_family[i - 1] = -1;
649 
650 	} else if (!strcmp(tok[0], "options")) {
651 		for (i = 1; i < n; i++) {
652 			if (!strcmp(tok[i], "tcp"))
653 				ac->ac_options |= RES_USEVC;
654 			else if ((!strncmp(tok[i], "ndots:", 6))) {
655 				e = NULL;
656 				d = strtonum(tok[i] + 6, 1, 16, &e);
657 				if (e == NULL)
658 					ac->ac_ndots = d;
659 			}
660 		}
661 	}
662 }
663 
664 /*
665  * Setup an async context with the config specified in the string "str".
666  */
667 static int
668 asr_ctx_from_string(struct asr_ctx *ac, const char *str)
669 {
670 	char		 buf[512], *ch;
671 
672 	asr_ctx_parse(ac, str);
673 
674 	if (ac->ac_dbcount == 0) {
675 		/* No lookup directive */
676 		asr_ctx_parse(ac, DEFAULT_LOOKUP);
677 	}
678 
679 	if (ac->ac_nscount == 0)
680 		asr_ctx_parse(ac, "nameserver 127.0.0.1");
681 
682 	if (ac->ac_domain == NULL)
683 		if (gethostname(buf, sizeof buf) == 0) {
684 			ch = strchr(buf, '.');
685 			if (ch)
686 				ac->ac_domain = strdup(ch + 1);
687 			else /* Assume root. see resolv.conf(5) */
688 				ac->ac_domain = strdup("");
689 		}
690 
691 	/* If no search domain was specified, use the local subdomains */
692 	if (ac->ac_domcount == 0)
693 		for (ch = ac->ac_domain; ch; ) {
694 			asr_ctx_add_searchdomain(ac, ch);
695 			ch = strchr(ch, '.');
696 			if (ch && asr_ndots(++ch) == 0)
697 				break;
698 		}
699 
700 	return (0);
701 }
702 
703 /*
704  * Setup the "ac" async context from the file at location "path".
705  */
706 static int
707 asr_ctx_from_file(struct asr_ctx *ac, const char *path)
708 {
709 	FILE	*cf;
710 	char	 buf[4096];
711 	ssize_t	 r;
712 
713 	cf = fopen(path, "r");
714 	if (cf == NULL)
715 		return (-1);
716 
717 	r = fread(buf, 1, sizeof buf - 1, cf);
718 	if (feof(cf) == 0) {
719 		DPRINT("asr: config file too long: \"%s\"\n", path);
720 		r = -1;
721 	}
722 	fclose(cf);
723 	if (r == -1)
724 		return (-1);
725 	buf[r] = '\0';
726 
727 	return asr_ctx_from_string(ac, buf);
728 }
729 
730 /*
731  * Parse lines in the configuration string. For each one, split it into
732  * tokens and pass them to "pass0" for processing.
733  */
734 static int
735 asr_ctx_parse(struct asr_ctx *ac, const char *str)
736 {
737 	size_t		 len;
738 	const char	*line;
739 	char		 buf[1024];
740 	char		*tok[10];
741 	int		 ntok;
742 
743 	line = str;
744 	while (*line) {
745 		len = strcspn(line, "\n\0");
746 		if (len < sizeof buf) {
747 			memmove(buf, line, len);
748 			buf[len] = '\0';
749 		} else
750 			buf[0] = '\0';
751 		line += len;
752 		if (*line == '\n')
753 			line++;
754 		buf[strcspn(buf, ";#")] = '\0';
755 		if ((ntok = strsplit(buf, tok, 10)) == 0)
756 			continue;
757 
758 		pass0(tok, ntok, ac);
759 	}
760 
761 	return (0);
762 }
763 
764 #if ASR_OPT_ENVOPTS
765 /*
766  * Check for environment variables altering the configuration as described
767  * in resolv.conf(5).  Altough not documented there, this feature is disabled
768  * for setuid/setgid programs.
769  */
770 static void
771 asr_ctx_envopts(struct asr_ctx *ac)
772 {
773 	char	buf[4096], *e;
774 	size_t	s;
775 
776 	if (issetugid()) {
777 		ac->ac_options |= RES_NOALIASES;
778 		return;
779 	}
780 
781 	if ((e = getenv("RES_OPTIONS")) != NULL) {
782 		strlcpy(buf, "options ", sizeof buf);
783 		strlcat(buf, e, sizeof buf);
784 		s = strlcat(buf, "\n", sizeof buf);
785 		s = strlcat(buf, "\n", sizeof buf);
786 		if (s < sizeof buf)
787 			asr_ctx_parse(ac, buf);
788 	}
789 
790 	if ((e = getenv("LOCALDOMAIN")) != NULL) {
791 		strlcpy(buf, "search ", sizeof buf);
792 		strlcat(buf, e, sizeof buf);
793 		s = strlcat(buf, "\n", sizeof buf);
794 		if (s < sizeof buf)
795 			asr_ctx_parse(ac, buf);
796 	}
797 }
798 #endif
799 
800 /*
801  * Parse a resolv.conf(5) nameserver string into a sockaddr.
802  */
803 static int
804 asr_parse_nameserver(struct sockaddr *sa, const char *s)
805 {
806 	const char	*estr;
807 	char		 buf[256];
808 	char		*port = NULL;
809 	in_port_t	 portno = 53;
810 
811 	if (*s == '[') {
812 		strlcpy(buf, s + 1, sizeof buf);
813 		s = buf;
814 		port = strchr(buf, ']');
815 		if (port == NULL)
816 			return (-1);
817 		*port++ = '\0';
818 		if (*port != ':')
819 			return (-1);
820 		port++;
821 	}
822 
823 	if (port) {
824 		portno = strtonum(port, 1, USHRT_MAX, &estr);
825 		if (estr)
826 			return (-1);
827 	}
828 
829 	if (sockaddr_from_str(sa, PF_UNSPEC, s) == -1)
830 		return (-1);
831 
832 	if (sa->sa_family == PF_INET)
833 		((struct sockaddr_in *)sa)->sin_port = htons(portno);
834 	else if (sa->sa_family == PF_INET6)
835 		((struct sockaddr_in6 *)sa)->sin6_port = htons(portno);
836 
837 	return (0);
838 }
839 
840 /*
841  * Turn a (uncompressed) DNS domain name into a regular nul-terminated string
842  * where labels are separated by dots. The result is put into the "buf" buffer,
843  * truncated if it exceeds "max" chars. The function returns "buf".
844  */
845 char *
846 asr_strdname(const char *_dname, char *buf, size_t max)
847 {
848 	const unsigned char *dname = _dname;
849 	char	*res;
850 	size_t	 left, n, count;
851 
852 	if (_dname[0] == 0) {
853 		strlcpy(buf, ".", max);
854 		return buf;
855 	}
856 
857 	res = buf;
858 	left = max - 1;
859 	for (n = 0; dname[0] && left; n += dname[0]) {
860 		count = (dname[0] < (left - 1)) ? dname[0] : (left - 1);
861 		memmove(buf, dname + 1, count);
862 		dname += dname[0] + 1;
863 		left -= count;
864 		buf += count;
865 		if (left) {
866 			left -= 1;
867 			*buf++ = '.';
868 		}
869 	}
870 	buf[0] = 0;
871 
872 	return (res);
873 }
874 
875 /*
876  * Read and split the next line from the given namedb file.
877  * Return -1 on error, or put the result in the "tokens" array of
878  * size "ntoken" and returns the number of token on the line.
879  */
880 int
881 asr_parse_namedb_line(FILE *file, char **tokens, int ntoken)
882 {
883 	size_t	  len;
884 	char	 *buf;
885 	int	  ntok;
886 
887     again:
888 	if ((buf = fgetln(file, &len)) == NULL)
889 		return (-1);
890 
891 	if (buf[len - 1] == '\n')
892 		len--;
893 
894 	buf[len] = '\0';
895 	buf[strcspn(buf, "#")] = '\0';
896 	if ((ntok = strsplit(buf, tokens, ntoken)) == 0)
897 		goto again;
898 
899 	return (ntok);
900 }
901 
902 /*
903  * Update the async context so that it uses the next configured DB.
904  * Return 0 on success, or -1 if no more DBs is available.
905  */
906 int
907 asr_iter_db(struct async *as)
908 {
909 	if (as->as_db_idx >= as->as_ctx->ac_dbcount) {
910 		DPRINT("asr_iter_db: done\n");
911 		return (-1);
912 	}
913 
914 	as->as_db_idx += 1;
915 	as->as_ns_idx = 0;
916 	DPRINT("asr_iter_db: %i\n", as->as_db_idx);
917 
918 	return (0);
919 }
920 
921 /*
922  * Set the async context nameserver index to the next nameserver of the
923  * currently used DB (assuming it is DNS), cycling over the list until the
924  * maximum retry counter is reached.  Return 0 on success, or -1 if all
925  * nameservers were used.
926  */
927 int
928 asr_iter_ns(struct async *as)
929 {
930 	for (;;) {
931 		if (as->as_ns_cycles >= as->as_ctx->ac_nsretries)
932 			return (-1);
933 
934 		as->as_ns_idx += 1;
935 		if (as->as_ns_idx <= as->as_ctx->ac_nscount)
936 			break;
937 		as->as_ns_idx = 0;
938 		as->as_ns_cycles++;
939 		DPRINT("asr: asr_iter_ns(): cycle %i\n", as->as_ns_cycles);
940 	}
941 
942 	as->as_timeout = 1000 * (as->as_ctx->ac_nstimeout << as->as_ns_cycles);
943 	if (as->as_ns_cycles > 0)
944 		as->as_timeout /= as->as_ctx->ac_nscount;
945 	if (as->as_timeout < 1000)
946 		as->as_timeout = 1000;
947 
948 	return (0);
949 }
950 
951 enum {
952 	DOM_INIT,
953 	DOM_DOMAIN,
954 	DOM_DONE
955 };
956 
957 /*
958  * Implement the search domain strategy.
959  *
960  * This function works as a generator that constructs complete domains in
961  * buffer "buf" of size "len" for the given host name "name", according to the
962  * search rules defined by the resolving context.  It is supposed to be called
963  * multiple times (with the same name) to generate the next possible domain
964  * name, if any.
965  *
966  * It returns 0 if it could generate a new domain name, or -1 when all
967  * possibilites have been exhausted.
968  */
969 int
970 asr_iter_domain(struct async *as, const char *name, char * buf, size_t len)
971 {
972 #if ASR_OPT_HOSTALIASES
973 	char	*alias;
974 #endif
975 
976 	switch (as->as_dom_step) {
977 
978 	case DOM_INIT:
979 		/* First call */
980 
981 		/*
982 		 * If "name" is an FQDN, that's the only result and we
983 		 * don't try anything else.
984 		 */
985 		if (strlen(name) && name[strlen(name) - 1] ==  '.') {
986 			DPRINT("asr: asr_iter_domain(\"%s\") fqdn\n", name);
987 			as->as_dom_flags |= ASYNC_DOM_FQDN;
988 			as->as_dom_step = DOM_DONE;
989 			return (asr_domcat(name, NULL, buf, len));
990 		}
991 
992 #if ASR_OPT_HOSTALIASES
993 		/*
994 		 * If "name" has no dots, it might be an alias. If so,
995 		 * That's also the only result.
996 		 */
997 		if ((as->as_ctx->ac_options & RES_NOALIASES) == 0 &&
998 		    asr_ndots(name) == 0 &&
999 		    (alias = asr_hostalias(name, buf, len)) != NULL) {
1000 			DPRINT("asr: asr_iter_domain(\"%s\") is alias \"%s\"\n",
1001 			    name, alias);
1002 			as->as_dom_flags |= ASYNC_DOM_HOSTALIAS;
1003 			as->as_dom_step = DOM_DONE;
1004 			return (asr_domcat(alias, NULL, buf, len));
1005 		}
1006 #endif
1007 
1008 		/*
1009 		 * Otherwise, we iterate through the specified search domains.
1010 		 */
1011 		as->as_dom_step = DOM_DOMAIN;
1012 		as->as_dom_idx = 0;
1013 
1014 		/*
1015 		 * If "name" as enough dots, use it as-is first, as indicated
1016 		 * in resolv.conf(5).
1017 		 */
1018 		if ((asr_ndots(name)) >= as->as_ctx->ac_ndots) {
1019 			DPRINT("asr: asr_iter_domain(\"%s\") ndots\n", name);
1020 			as->as_dom_flags |= ASYNC_DOM_NDOTS;
1021 			strlcpy(buf, name, len);
1022 			return (0);
1023 		}
1024 		/* Otherwise, starts using the search domains */
1025 		/* FALLTHROUGH */
1026 
1027 	case DOM_DOMAIN:
1028 		if (as->as_dom_idx < as->as_ctx->ac_domcount) {
1029 			DPRINT("asr: asr_iter_domain(\"%s\") domain \"%s\"\n",
1030 			    name, as->as_ctx->ac_dom[as->as_dom_idx]);
1031 			as->as_dom_flags |= ASYNC_DOM_DOMAIN;
1032 			return (asr_domcat(name,
1033 			    as->as_ctx->ac_dom[as->as_dom_idx++], buf, len));
1034 		}
1035 
1036 		/* No more domain to try. */
1037 
1038 		as->as_dom_step = DOM_DONE;
1039 
1040 		/*
1041 		 * If the name was not tried as an absolute name before,
1042 		 * do it now.
1043 		 */
1044 		if (!(as->as_dom_flags & ASYNC_DOM_NDOTS)) {
1045 			DPRINT("asr: asr_iter_domain(\"%s\") as is\n", name);
1046 			as->as_dom_flags |= ASYNC_DOM_ASIS;
1047 			strlcpy(buf, name, len);
1048 			return (0);
1049 		}
1050 		/* Otherwise, we are done. */
1051 
1052 	case DOM_DONE:
1053 	default:
1054 		DPRINT("asr: asr_iter_domain(\"%s\") done\n", name);
1055 		return (-1);
1056 	}
1057 }
1058 
1059 #if ASR_OPT_HOSTALIASES
1060 /*
1061  * Check if the hostname "name" is a user-defined alias as per hostname(7).
1062  * If so, copies the result in the buffer "abuf" of size "abufsz" and
1063  * return "abuf". Otherwise return NULL.
1064  */
1065 static char *
1066 asr_hostalias(const char *name, char *abuf, size_t abufsz)
1067 {
1068 	FILE	 *fp;
1069 	size_t	  len;
1070 	char	 *file, *buf, *tokens[2];
1071 	int	  ntok;
1072 
1073 	file = getenv("HOSTALIASES");
1074 	if (file == NULL || issetugid() != 0 || (fp = fopen(file, "r")) == NULL)
1075 		return (NULL);
1076 
1077 	DPRINT("asr: looking up aliases in \"%s\"\n", file);
1078 
1079 	while ((buf = fgetln(fp, &len)) != NULL) {
1080 		if (buf[len - 1] == '\n')
1081 			len--;
1082 		buf[len] = '\0';
1083 		if ((ntok = strsplit(buf, tokens, 2)) != 2)
1084 			continue;
1085 		if (!strcasecmp(tokens[0], name)) {
1086 			if (strlcpy(abuf, tokens[1], abufsz) > abufsz)
1087 				continue;
1088 			DPRINT("asr: found alias \"%s\"\n", abuf);
1089 			fclose(fp);
1090 			return (abuf);
1091 		}
1092 	}
1093 
1094 	fclose(fp);
1095 	return (NULL);
1096 }
1097 #endif
1098