xref: /openbsd-src/lib/libc/asr/asr.c (revision 48950c12d106c85f315112191a0228d7b83b9510)
1 /*	$OpenBSD: asr.c,v 1.14 2012/11/24 15:12:48 eric 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 bind file\nnameserver 127.0.0.1\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 		if (as->as.hostnamadr.dname)
305 			free(as->as.hostnamadr.dname);
306 		break;
307 
308 	case ASR_GETNETBYNAME:
309 	case ASR_GETNETBYADDR:
310 		if (as->as.netnamadr.subq)
311 			async_free(as->as.netnamadr.subq);
312 		if (as->as.netnamadr.name)
313 			free(as->as.netnamadr.name);
314 		break;
315 
316 	case ASR_GETADDRINFO:
317 		if (as->as.ai.subq)
318 			async_free(as->as.ai.subq);
319 		if (as->as.ai.aifirst)
320 			freeaddrinfo(as->as.ai.aifirst);
321 		if (as->as.ai.hostname)
322 			free(as->as.ai.hostname);
323 		if (as->as.ai.servname)
324 			free(as->as.ai.servname);
325 		if (as->as.ai.fqdn)
326 			free(as->as.ai.fqdn);
327 		break;
328 
329 	case ASR_GETNAMEINFO:
330 		if (as->as.ni.subq)
331 			async_free(as->as.ni.subq);
332 		break;
333 	}
334 
335 	asr_ctx_unref(as->as_ctx);
336 	free(as);
337 }
338 
339 /*
340  * Get a context from the given resolver. This takes a new reference to
341  * the returned context, which *must* be explicitely dropped when done
342  * using this context.
343  */
344 struct asr_ctx *
345 asr_use_resolver(struct asr *asr)
346 {
347 	struct asr **priv;
348 
349 	if (asr == NULL) {
350 		DPRINT("using thread-local resolver\n");
351 		priv = _THREAD_PRIVATE(_asr, asr, &_asr);
352 		if (*priv == NULL) {
353 			DPRINT("setting up thread-local resolver\n");
354 			*priv = async_resolver(NULL);
355 		}
356 		asr = *priv;
357 	}
358 
359 	asr_check_reload(asr);
360 	asr_ctx_ref(asr->a_ctx);
361 	return (asr->a_ctx);
362 }
363 
364 static void
365 asr_ctx_ref(struct asr_ctx *ac)
366 {
367 	DPRINT("asr: asr_ctx_ref(ctx=%p) refcount=%i\n", ac, ac->ac_refcount);
368 	ac->ac_refcount += 1;
369 }
370 
371 /*
372  * Drop a reference to an async context, freeing it if the reference
373  * count drops to 0.
374  */
375 void
376 asr_ctx_unref(struct asr_ctx *ac)
377 {
378 	DPRINT("asr: asr_ctx_unref(ctx=%p) refcount=%i\n", ac, ac->ac_refcount);
379 	if (--ac->ac_refcount)
380 		return;
381 
382 	asr_ctx_free(ac);
383 }
384 
385 static void
386 asr_ctx_free(struct asr_ctx *ac)
387 {
388 	int i;
389 
390 	if (ac->ac_domain)
391 		free(ac->ac_domain);
392 	for (i = 0; i < ac->ac_nscount; i++)
393 		free(ac->ac_ns[i]);
394 	for (i = 0; i < ac->ac_domcount; i++)
395 		free(ac->ac_dom[i]);
396 
397 	free(ac);
398 }
399 
400 /*
401  * Reload the configuration file if it has changed on disk.
402  */
403 static void
404 asr_check_reload(struct asr *asr)
405 {
406 	struct asr_ctx	*ac;
407 #if ASR_OPT_RELOADCONF
408 	struct stat	 st;
409 	struct timespec	 tp;
410 #endif
411 
412 	if (asr->a_path == NULL)
413 		return;
414 
415 #if ASR_OPT_RELOADCONF
416 	if (clock_gettime(CLOCK_MONOTONIC, &tp) == -1)
417 		return;
418 
419 	if ((tp.tv_sec - asr->a_rtime) < RELOAD_DELAY)
420 		return;
421 	asr->a_rtime = tp.tv_sec;
422 
423 	DPRINT("asr: checking for update of \"%s\"\n", asr->a_path);
424 	if (stat(asr->a_path, &st) == -1 ||
425 	    asr->a_mtime == st.st_mtime ||
426 	    (ac = asr_ctx_create()) == NULL)
427 		return;
428 	asr->a_mtime = st.st_mtime;
429 #else
430 	if ((ac = asr_ctx_create()) == NULL)
431 		return;
432 #endif
433 
434 	DPRINT("asr: reloading config file\n");
435 	if (asr_ctx_from_file(ac, asr->a_path) == -1) {
436 		asr_ctx_free(ac);
437 		return;
438 	}
439 
440 #if ASR_OPT_ENVOPTS
441 	asr_ctx_envopts(ac);
442 #endif
443 	if (asr->a_ctx)
444 		asr_ctx_unref(asr->a_ctx);
445 	asr->a_ctx = ac;
446 }
447 
448 /*
449  * Construct a fully-qualified domain name for the given name and domain.
450  * If "name" ends with a '.' it is considered as a FQDN by itself.
451  * Otherwise, the domain, which must be a FQDN, is appended to "name" (it
452  * may have a leading dot which would be ignored). If the domain is null,
453  * then "." is used. Return the length of the constructed FQDN or (0) on
454  * error.
455  */
456 size_t
457 asr_make_fqdn(const char *name, const char *domain, char *buf, size_t buflen)
458 {
459 	size_t	len;
460 
461 	if (domain == NULL)
462 		domain = ".";
463 	else if ((len = strlen(domain)) == 0)
464 		return (0);
465 	else if (domain[len -1] != '.')
466 		return (0);
467 
468 	len = strlen(name);
469 	if (len == 0) {
470 		strlcpy(buf, domain, buflen);
471 	} else if (name[len - 1] !=  '.') {
472 		if (domain[0] == '.')
473 			domain += 1;
474 		strlcpy(buf, name, buflen);
475 		strlcat(buf, ".", buflen);
476 		strlcat(buf, domain, buflen);
477 	} else {
478 		strlcpy(buf, name, buflen);
479 	}
480 
481 	return (strlen(buf));
482 }
483 
484 /*
485  * Concatenate a name and a domain name. The result has no trailing dot.
486  */
487 size_t
488 asr_domcat(const char *name, const char *domain, char *buf, size_t buflen)
489 {
490 	size_t	r;
491 
492 	r = asr_make_fqdn(name, domain, buf, buflen);
493 	if (r == 0)
494 		return (0);
495 	buf[r - 1] = '\0';
496 
497 	return (r - 1);
498 }
499 
500 /*
501  * Count the dots in a string.
502  */
503 static int
504 asr_ndots(const char *s)
505 {
506 	int n;
507 
508 	for (n = 0; *s; s++)
509 		if (*s == '.')
510 			n += 1;
511 
512 	return (n);
513 }
514 
515 /*
516  * Allocate a new empty context.
517  */
518 static struct asr_ctx *
519 asr_ctx_create(void)
520 {
521 	struct asr_ctx	*ac;
522 
523 	if ((ac = calloc(1, sizeof(*ac))) == NULL)
524 		return (NULL);
525 
526 	ac->ac_options = RES_RECURSE | RES_DEFNAMES | RES_DNSRCH;
527 	ac->ac_refcount = 1;
528 	ac->ac_ndots = 1;
529 	ac->ac_family[0] = AF_INET;
530 	ac->ac_family[1] = AF_INET6;
531 	ac->ac_family[2] = -1;
532 
533 	ac->ac_hostfile = DEFAULT_HOSTFILE;
534 
535 	ac->ac_nscount = 0;
536 	ac->ac_nstimeout = 1000;
537 	ac->ac_nsretries = 3;
538 
539 	return (ac);
540 }
541 
542 /*
543  * Add a search domain to the async context.
544  */
545 static int
546 asr_ctx_add_searchdomain(struct asr_ctx *ac, const char *domain)
547 {
548 	char buf[MAXDNAME];
549 
550 	if (ac->ac_domcount == ASR_MAXDOM)
551 		return (-1);
552 
553 	if (asr_make_fqdn(domain, NULL, buf, sizeof(buf)) == 0)
554 		return (-1);
555 
556 	if ((ac->ac_dom[ac->ac_domcount] = strdup(buf)) == NULL)
557 		return (0);
558 
559 	ac->ac_domcount += 1;
560 
561 	return (1);
562 }
563 
564 static int
565 strsplit(char *line, char **tokens, int ntokens)
566 {
567 	int	ntok;
568 	char	*cp, **tp;
569 
570 	for (cp = line, tp = tokens, ntok = 0;
571 	    ntok < ntokens && (*tp = strsep(&cp, " \t")) != NULL; )
572 		if (**tp != '\0') {
573 			tp++;
574 			ntok++;
575 		}
576 
577 	return (ntok);
578 }
579 
580 /*
581  * Pass on a split config line.
582  */
583 static void
584 pass0(char **tok, int n, struct asr_ctx *ac)
585 {
586 	int		 i, j, d;
587 	const char	*e;
588 	struct sockaddr_storage	ss;
589 
590 	if (!strcmp(tok[0], "nameserver")) {
591 		if (ac->ac_nscount == ASR_MAXNS)
592 			return;
593 		if (n != 2)
594 			return;
595 		if (asr_parse_nameserver((struct sockaddr*)&ss, tok[1]))
596 			return;
597 		if ((ac->ac_ns[ac->ac_nscount] = calloc(1, ss.ss_len)) == NULL)
598 			return;
599 		memmove(ac->ac_ns[ac->ac_nscount], &ss, ss.ss_len);
600 		ac->ac_nscount += 1;
601 
602 	} else if (!strcmp(tok[0], "domain")) {
603 		if (n != 2)
604 			return;
605 		if (ac->ac_domain)
606 			return;
607 		ac->ac_domain = strdup(tok[1]);
608 
609 	} else if (!strcmp(tok[0], "lookup")) {
610 		/* ignore the line if we already set lookup */
611 		if (ac->ac_dbcount != 0)
612 			return;
613 		if (n - 1 > ASR_MAXDB)
614 			return;
615 		/* ensure that each lookup is only given once */
616 		for (i = 1; i < n; i++)
617 			for (j = i + 1; j < n; j++)
618 				if (!strcmp(tok[i], tok[j]))
619 					return;
620 		for (i = 1; i < n; i++, ac->ac_dbcount++) {
621 			if (!strcmp(tok[i], "yp")) {
622 				ac->ac_db[i-1] = ASR_DB_YP;
623 			} else if (!strcmp(tok[i], "bind")) {
624 				ac->ac_db[i-1] = ASR_DB_DNS;
625 			} else if (!strcmp(tok[i], "file")) {
626 				ac->ac_db[i-1] = ASR_DB_FILE;
627 			} else {
628 				/* ignore the line */
629 				ac->ac_dbcount = 0;
630 				return;
631 			}
632 		}
633 	} else if (!strcmp(tok[0], "search")) {
634 		/* resolv.conf says the last line wins */
635 		for (i = 0; i < ac->ac_domcount; i++)
636 			free(ac->ac_dom[i]);
637 		ac->ac_domcount = 0;
638 		for (i = 1; i < n; i++)
639 			asr_ctx_add_searchdomain(ac, tok[i]);
640 
641 	} else if (!strcmp(tok[0], "family")) {
642 		if (n == 1 || n > 3)
643 			return;
644 		for (i = 1; i < n; i++)
645 			if (strcmp(tok[i], "inet4") && strcmp(tok[i], "inet6"))
646 				return;
647 		for (i = 1; i < n; i++)
648 			ac->ac_family[i - 1] = strcmp(tok[i], "inet4") ? \
649 			    AF_INET6 : AF_INET;
650 		ac->ac_family[i - 1] = -1;
651 
652 	} else if (!strcmp(tok[0], "options")) {
653 		for (i = 1; i < n; i++) {
654 			if (!strcmp(tok[i], "tcp"))
655 				ac->ac_options |= RES_USEVC;
656 			else if ((!strncmp(tok[i], "ndots:", 6))) {
657 				e = NULL;
658 				d = strtonum(tok[i] + 6, 1, 16, &e);
659 				if (e == NULL)
660 					ac->ac_ndots = d;
661 			}
662 		}
663 	}
664 }
665 
666 /*
667  * Setup an async context with the config specified in the string "str".
668  */
669 static int
670 asr_ctx_from_string(struct asr_ctx *ac, const char *str)
671 {
672 	char		 buf[512], *ch;
673 
674 	asr_ctx_parse(ac, str);
675 
676 	if (ac->ac_dbcount == 0) {
677 		/* No lookup directive */
678 		asr_ctx_parse(ac, DEFAULT_LOOKUP);
679 	}
680 
681 	if (ac->ac_nscount == 0)
682 		asr_ctx_parse(ac, "nameserver 127.0.0.1");
683 
684 	if (ac->ac_domain == NULL)
685 		if (gethostname(buf, sizeof buf) == 0) {
686 			ch = strchr(buf, '.');
687 			if (ch)
688 				ac->ac_domain = strdup(ch + 1);
689 			else /* Assume root. see resolv.conf(5) */
690 				ac->ac_domain = strdup("");
691 		}
692 
693 	/* If no search domain was specified, use the local subdomains */
694 	if (ac->ac_domcount == 0)
695 		for (ch = ac->ac_domain; ch; ) {
696 			asr_ctx_add_searchdomain(ac, ch);
697 			ch = strchr(ch, '.');
698 			if (ch && asr_ndots(++ch) == 0)
699 				break;
700 		}
701 
702 	return (0);
703 }
704 
705 /*
706  * Setup the "ac" async context from the file at location "path".
707  */
708 static int
709 asr_ctx_from_file(struct asr_ctx *ac, const char *path)
710 {
711 	FILE	*cf;
712 	char	 buf[4096];
713 	ssize_t	 r;
714 
715 	cf = fopen(path, "r");
716 	if (cf == NULL)
717 		return (-1);
718 
719 	r = fread(buf, 1, sizeof buf - 1, cf);
720 	if (feof(cf) == 0) {
721 		DPRINT("asr: config file too long: \"%s\"\n", path);
722 		r = -1;
723 	}
724 	fclose(cf);
725 	if (r == -1)
726 		return (-1);
727 	buf[r] = '\0';
728 
729 	return asr_ctx_from_string(ac, buf);
730 }
731 
732 /*
733  * Parse lines in the configuration string. For each one, split it into
734  * tokens and pass them to "pass0" for processing.
735  */
736 static int
737 asr_ctx_parse(struct asr_ctx *ac, const char *str)
738 {
739 	size_t		 len;
740 	const char	*line;
741 	char		 buf[1024];
742 	char		*tok[10];
743 	int		 ntok;
744 
745 	line = str;
746 	while (*line) {
747 		len = strcspn(line, "\n\0");
748 		if (len < sizeof buf) {
749 			memmove(buf, line, len);
750 			buf[len] = '\0';
751 		} else
752 			buf[0] = '\0';
753 		line += len;
754 		if (*line == '\n')
755 			line++;
756 		buf[strcspn(buf, ";#")] = '\0';
757 		if ((ntok = strsplit(buf, tok, 10)) == 0)
758 			continue;
759 
760 		pass0(tok, ntok, ac);
761 	}
762 
763 	return (0);
764 }
765 
766 #if ASR_OPT_ENVOPTS
767 /*
768  * Check for environment variables altering the configuration as described
769  * in resolv.conf(5).  Altough not documented there, this feature is disabled
770  * for setuid/setgid programs.
771  */
772 static void
773 asr_ctx_envopts(struct asr_ctx *ac)
774 {
775 	char	buf[4096], *e;
776 	size_t	s;
777 
778 	if (issetugid()) {
779 		ac->ac_options |= RES_NOALIASES;
780 		return;
781 	}
782 
783 	if ((e = getenv("RES_OPTIONS")) != NULL) {
784 		strlcpy(buf, "options ", sizeof buf);
785 		strlcat(buf, e, sizeof buf);
786 		s = strlcat(buf, "\n", sizeof buf);
787 		s = strlcat(buf, "\n", sizeof buf);
788 		if (s < sizeof buf)
789 			asr_ctx_parse(ac, buf);
790 	}
791 
792 	if ((e = getenv("LOCALDOMAIN")) != NULL) {
793 		strlcpy(buf, "search ", sizeof buf);
794 		strlcat(buf, e, sizeof buf);
795 		s = strlcat(buf, "\n", sizeof buf);
796 		if (s < sizeof buf)
797 			asr_ctx_parse(ac, buf);
798 	}
799 }
800 #endif
801 
802 /*
803  * Parse a resolv.conf(5) nameserver string into a sockaddr.
804  */
805 static int
806 asr_parse_nameserver(struct sockaddr *sa, const char *s)
807 {
808 	const char	*estr;
809 	char		 buf[256];
810 	char		*port = NULL;
811 	in_port_t	 portno = 53;
812 
813 	if (*s == '[') {
814 		strlcpy(buf, s + 1, sizeof buf);
815 		s = buf;
816 		port = strchr(buf, ']');
817 		if (port == NULL)
818 			return (-1);
819 		*port++ = '\0';
820 		if (*port != ':')
821 			return (-1);
822 		port++;
823 	}
824 
825 	if (port) {
826 		portno = strtonum(port, 1, USHRT_MAX, &estr);
827 		if (estr)
828 			return (-1);
829 	}
830 
831 	if (sockaddr_from_str(sa, PF_UNSPEC, s) == -1)
832 		return (-1);
833 
834 	if (sa->sa_family == PF_INET)
835 		((struct sockaddr_in *)sa)->sin_port = htons(portno);
836 	else if (sa->sa_family == PF_INET6)
837 		((struct sockaddr_in6 *)sa)->sin6_port = htons(portno);
838 
839 	return (0);
840 }
841 
842 /*
843  * Turn a (uncompressed) DNS domain name into a regular nul-terminated string
844  * where labels are separated by dots. The result is put into the "buf" buffer,
845  * truncated if it exceeds "max" chars. The function returns "buf".
846  */
847 char*
848 asr_strdname(const char *_dname, char *buf, size_t max)
849 {
850 	const unsigned char *dname = _dname;
851 	char	*res;
852 	size_t	 left, n, count;
853 
854 	if (_dname[0] == 0) {
855 		strlcpy(buf, ".", max);
856 		return buf;
857 	}
858 
859 	res = buf;
860 	left = max - 1;
861 	for (n = 0; dname[0] && left; n += dname[0]) {
862 		count = (dname[0] < (left - 1)) ? dname[0] : (left - 1);
863 		memmove(buf, dname + 1, count);
864 		dname += dname[0] + 1;
865 		left -= count;
866 		buf += count;
867 		if (left) {
868 			left -= 1;
869 			*buf++ = '.';
870 		}
871 	}
872 	buf[0] = 0;
873 
874 	return (res);
875 }
876 
877 /*
878  * Read and split the next line from the given namedb file.
879  * Return -1 on error, or put the result in the "tokens" array of
880  * size "ntoken" and returns the number of token on the line.
881  */
882 int
883 asr_parse_namedb_line(FILE *file, char **tokens, int ntoken)
884 {
885 	size_t	  len;
886 	char	 *buf;
887 	int	  ntok;
888 
889     again:
890 	if ((buf = fgetln(file, &len)) == NULL)
891 		return (-1);
892 
893 	if (buf[len - 1] == '\n')
894 		len--;
895 
896 	buf[len] = '\0';
897 	buf[strcspn(buf, "#")] = '\0';
898 	if ((ntok = strsplit(buf, tokens, ntoken)) == 0)
899 		goto again;
900 
901 	return (ntok);
902 }
903 
904 /*
905  * Update the async context so that it uses the next configured DB.
906  * Return 0 on success, or -1 if no more DBs is available.
907  */
908 int
909 asr_iter_db(struct async *as)
910 {
911 	if (as->as_db_idx >= as->as_ctx->ac_dbcount) {
912 		DPRINT("asr_iter_db: done\n");
913 		return (-1);
914 	}
915 
916 	as->as_db_idx += 1;
917 	as->as_ns_idx = 0;
918 	DPRINT("asr_iter_db: %i\n", as->as_db_idx);
919 
920 	return (0);
921 }
922 
923 /*
924  * Set the async context nameserver index to the next nameserver of the
925  * currently used DB (assuming it is DNS), cycling over the list until the
926  * maximum retry counter is reached.  Return 0 on success, or -1 if all
927  * nameservers were used.
928  */
929 int
930 asr_iter_ns(struct async *as)
931 {
932 	for (;;) {
933 		if (as->as_ns_cycles >= as->as_ctx->ac_nsretries)
934 			return (-1);
935 
936 		as->as_ns_idx += 1;
937 		if (as->as_ns_idx <= as->as_ctx->ac_nscount)
938 			break;
939 		as->as_ns_idx = 0;
940 		as->as_ns_cycles++;
941 		DPRINT("asr: asr_iter_ns(): cycle %i\n", as->as_ns_cycles);
942 	}
943 
944 	return (0);
945 }
946 
947 enum {
948 	DOM_INIT,
949 	DOM_DOMAIN,
950 	DOM_DONE
951 };
952 
953 /*
954  * Implement the search domain strategy.
955  *
956  * This function works as a generator that constructs complete domains in
957  * buffer "buf" of size "len" for the given host name "name", according to the
958  * search rules defined by the resolving context.  It is supposed to be called
959  * multiple times (with the same name) to generate the next possible domain
960  * name, if any.
961  *
962  * It returns 0 if it could generate a new domain name, or -1 when all
963  * possibilites have been exhausted.
964  */
965 int
966 asr_iter_domain(struct async *as, const char *name, char * buf, size_t len)
967 {
968 #if ASR_OPT_HOSTALIASES
969 	char	*alias;
970 #endif
971 
972 	switch (as->as_dom_step) {
973 
974 	case DOM_INIT:
975 		/* First call */
976 
977 		/*
978 		 * If "name" is an FQDN, that's the only result and we
979 		 * don't try anything else.
980 		 */
981 		if (strlen(name) && name[strlen(name) - 1] ==  '.') {
982 			DPRINT("asr: asr_iter_domain(\"%s\") fqdn\n", name);
983 			as->as_dom_flags |= ASYNC_DOM_FQDN;
984 			as->as_dom_step = DOM_DONE;
985 			return (asr_domcat(name, NULL, buf, len));
986 		}
987 
988 #if ASR_OPT_HOSTALIASES
989 		/*
990 		 * If "name" has no dots, it might be an alias. If so,
991 		 * That's also the only result.
992 		 */
993 		if ((as->as_ctx->ac_options & RES_NOALIASES) == 0 &&
994 		    asr_ndots(name) == 0 &&
995 		    (alias = asr_hostalias(name, buf, len)) != NULL) {
996 			DPRINT("asr: asr_iter_domain(\"%s\") is alias \"%s\"\n",
997 			    name, alias);
998 			as->as_dom_flags |= ASYNC_DOM_HOSTALIAS;
999 			as->as_dom_step = DOM_DONE;
1000 			return (asr_domcat(alias, NULL, buf, len));
1001 		}
1002 #endif
1003 
1004 		/*
1005 		 * Otherwise, we iterate through the specified search domains.
1006 		 */
1007 		as->as_dom_step = DOM_DOMAIN;
1008 		as->as_dom_idx = 0;
1009 
1010 		/*
1011 		 * If "name" as enough dots, use it as-is first, as indicated
1012 		 * in resolv.conf(5).
1013 		 */
1014 		if ((asr_ndots(name)) >= as->as_ctx->ac_ndots) {
1015 			DPRINT("asr: asr_iter_domain(\"%s\") ndots\n", name);
1016 			as->as_dom_flags |= ASYNC_DOM_NDOTS;
1017 			strlcpy(buf, name, len);
1018 			return (0);
1019 		}
1020 		/* Otherwise, starts using the search domains */
1021 		/* FALLTHROUGH */
1022 
1023 	case DOM_DOMAIN:
1024 		if (as->as_dom_idx < as->as_ctx->ac_domcount) {
1025 			DPRINT("asr: asr_iter_domain(\"%s\") domain \"%s\"\n",
1026 			    name, as->as_ctx->ac_dom[as->as_dom_idx]);
1027 			as->as_dom_flags |= ASYNC_DOM_DOMAIN;
1028 			return (asr_domcat(name,
1029 			    as->as_ctx->ac_dom[as->as_dom_idx++], buf, len));
1030 		}
1031 
1032 		/* No more domain to try. */
1033 
1034 		as->as_dom_step = DOM_DONE;
1035 
1036 		/*
1037 		 * If the name was not tried as an absolute name before,
1038 		 * do it now.
1039 		 */
1040 		if (!(as->as_dom_flags & ASYNC_DOM_NDOTS)) {
1041 			DPRINT("asr: asr_iter_domain(\"%s\") as is\n", name);
1042 			as->as_dom_flags |= ASYNC_DOM_ASIS;
1043 			strlcpy(buf, name, len);
1044 			return (0);
1045 		}
1046 		/* Otherwise, we are done. */
1047 
1048 	case DOM_DONE:
1049 	default:
1050 		DPRINT("asr: asr_iter_domain(\"%s\") done\n", name);
1051 		return (-1);
1052 	}
1053 }
1054 
1055 #if ASR_OPT_HOSTALIASES
1056 /*
1057  * Check if the hostname "name" is a user-defined alias as per hostname(7).
1058  * If so, copies the result in the buffer "abuf" of size "abufsz" and
1059  * return "abuf". Otherwise return NULL.
1060  */
1061 static char *
1062 asr_hostalias(const char *name, char *abuf, size_t abufsz)
1063 {
1064 	FILE	 *fp;
1065 	size_t	  len;
1066 	char	 *file, *buf, *tokens[2];
1067 	int	  ntok;
1068 
1069 	file = getenv("HOSTALIASES");
1070 	if (file == NULL || issetugid() != 0 || (fp = fopen(file, "r")) == NULL)
1071 		return (NULL);
1072 
1073 	DPRINT("asr: looking up aliases in \"%s\"\n", file);
1074 
1075 	while ((buf = fgetln(fp, &len)) != NULL) {
1076 		if (buf[len - 1] == '\n')
1077 			len--;
1078 		buf[len] = '\0';
1079 		if ((ntok = strsplit(buf, tokens, 2)) != 2)
1080 			continue;
1081 		if (!strcasecmp(tokens[0], name)) {
1082 			if (strlcpy(abuf, tokens[1], abufsz) > abufsz)
1083 				continue;
1084 			DPRINT("asr: found alias \"%s\"\n", abuf);
1085 			fclose(fp);
1086 			return (abuf);
1087 		}
1088 	}
1089 
1090 	fclose(fp);
1091 	return (NULL);
1092 }
1093 #endif
1094