xref: /openbsd-src/lib/libc/asr/asr.c (revision 172af5aabca08f148872bb5e3d655512d942977c)
1 /*	$OpenBSD: asr.c,v 1.39 2015/09/02 13:47:47 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/socket.h>
20 #include <sys/stat.h>
21 #include <netinet/in.h>
22 #include <arpa/inet.h>
23 #include <arpa/nameser.h>
24 #include <netdb.h>
25 
26 #include <asr.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <resolv.h>
31 #include <poll.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <limits.h>
37 
38 #include "asr_private.h"
39 
40 #ifndef ASR_OPT_THREADSAFE
41 #define ASR_OPT_THREADSAFE 1
42 #endif
43 #ifndef ASR_OPT_HOSTALIASES
44 #define ASR_OPT_HOSTALIASES 1
45 #endif
46 #ifndef ASR_OPT_ENVOPTS
47 #define ASR_OPT_ENVOPTS 1
48 #endif
49 #ifndef ASR_OPT_RELOADCONF
50 #define ASR_OPT_RELOADCONF 1
51 #endif
52 #ifndef ASR_OPT_ALTCONF
53 #define ASR_OPT_ALTCONF 1
54 #endif
55 
56 #if ASR_OPT_THREADSAFE
57 #include "thread_private.h"
58 #endif
59 
60 #define DEFAULT_CONFFILE	_PATH_RESCONF
61 #define DEFAULT_CONF		"lookup file\n"
62 #define DEFAULT_LOOKUP		"lookup bind file"
63 
64 #define RELOAD_DELAY		15 /* seconds */
65 
66 static void asr_check_reload(struct asr *);
67 static struct asr_ctx *asr_ctx_create(void);
68 static void asr_ctx_ref(struct asr_ctx *);
69 static void asr_ctx_free(struct asr_ctx *);
70 static int asr_ctx_add_searchdomain(struct asr_ctx *, const char *);
71 static int asr_ctx_from_file(struct asr_ctx *, const char *);
72 static int asr_ctx_from_string(struct asr_ctx *, const char *);
73 static int asr_ctx_parse(struct asr_ctx *, const char *);
74 static int asr_parse_nameserver(struct sockaddr *, const char *);
75 static int asr_ndots(const char *);
76 static void pass0(char **, int, struct asr_ctx *);
77 static int strsplit(char *, char **, int);
78 #if ASR_OPT_ENVOPTS
79 static void asr_ctx_envopts(struct asr_ctx *);
80 #endif
81 #if ASR_OPT_THREADSAFE
82 static void *__THREAD_NAME(_asr);
83 #else
84 #	define _THREAD_PRIVATE(a, b, c)  (c)
85 #endif
86 
87 static struct asr *_asr = NULL;
88 
89 /* Allocate and configure an async "resolver". */
90 void *
91 asr_resolver(const char *conf)
92 {
93 	static int	 init = 0;
94 	struct asr	*asr;
95 
96 	if (init == 0) {
97 #ifdef DEBUG
98 		if (getenv("ASR_DEBUG"))
99 			asr_debug = stderr;
100 #endif
101 		init = 1;
102 	}
103 
104 	if ((asr = calloc(1, sizeof(*asr))) == NULL)
105 		goto fail;
106 
107 #if ASR_OPT_ALTCONF
108 	/* If not setuid/setgid, allow to use an alternate config. */
109 	if (conf == NULL && !issetugid())
110 		conf = getenv("ASR_CONFIG");
111 #endif
112 
113 	if (conf == NULL)
114 		conf = DEFAULT_CONFFILE;
115 
116 	if (conf[0] == '!') {
117 		/* Use the rest of the string as config file */
118 		if ((asr->a_ctx = asr_ctx_create()) == NULL)
119 			goto fail;
120 		if (asr_ctx_from_string(asr->a_ctx, conf + 1) == -1)
121 			goto fail;
122 	} else {
123 		/* Use the given config file */
124 		asr->a_path = strdup(conf);
125 		if (asr->a_path == NULL)
126 			goto fail;
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->a_path);
149 		free(asr);
150 	}
151 
152 	return (NULL);
153 }
154 
155 /*
156  * Free the "asr" async resolver (or the thread-local resolver if NULL).
157  * Drop the reference to the current context.
158  */
159 void
160 asr_resolver_done(void *arg)
161 {
162 	struct asr *asr = arg;
163 	struct asr **priv;
164 
165 	if (asr == NULL) {
166 		priv = _THREAD_PRIVATE(_asr, _asr, &_asr);
167 		if (*priv == NULL)
168 			return;
169 		asr = *priv;
170 		*priv = NULL;
171 	}
172 
173 	asr_ctx_unref(asr->a_ctx);
174 	free(asr->a_path);
175 	free(asr);
176 }
177 
178 /*
179  * Cancel an async query.
180  */
181 void
182 asr_abort(struct asr_query *as)
183 {
184 	asr_async_free(as);
185 }
186 
187 /*
188  * Resume the "as" async query resolution.  Return one of ASYNC_COND,
189  * or ASYNC_DONE and put query-specific return values in the user-allocated
190  * memory at "ar".
191  */
192 int
193 asr_run(struct asr_query *as, struct asr_result *ar)
194 {
195 	int	r, saved_errno = errno;
196 
197 	DPRINT("asr: asr_run(%p, %p) %s ctx=[%p]\n", as, ar,
198 	    asr_querystr(as->as_type), as->as_ctx);
199 	r = as->as_run(as, ar);
200 
201 	DPRINT("asr: asr_run(%p, %p) -> %s", as, ar, asr_transitionstr(r));
202 #ifdef DEBUG
203 	if (r == ASYNC_COND)
204 #endif
205 		DPRINT(" fd=%i timeout=%i", ar->ar_fd, ar->ar_timeout);
206 	DPRINT("\n");
207 	if (r == ASYNC_DONE)
208 		asr_async_free(as);
209 
210 	errno = saved_errno;
211 
212 	return (r);
213 }
214 
215 /*
216  * Same as above, but run in a loop that handles the fd conditions result.
217  */
218 int
219 asr_run_sync(struct asr_query *as, struct asr_result *ar)
220 {
221 	struct pollfd	 fds[1];
222 	int		 r, saved_errno = errno;
223 
224 	while ((r = asr_run(as, ar)) == ASYNC_COND) {
225 		fds[0].fd = ar->ar_fd;
226 		fds[0].events = (ar->ar_cond == ASR_WANT_READ) ? POLLIN:POLLOUT;
227 	again:
228 		r = poll(fds, 1, ar->ar_timeout);
229 		if (r == -1 && errno == EINTR)
230 			goto again;
231 		/*
232 		 * Otherwise, just ignore the error and let asr_run()
233 		 * catch the failure.
234 		 */
235 	}
236 
237 	errno = saved_errno;
238 
239 	return (r);
240 }
241 
242 /*
243  * Create a new async request of the given "type" on the async context "ac".
244  * Take a reference on it so it does not gets deleted while the async query
245  * is running.
246  */
247 struct asr_query *
248 asr_async_new(struct asr_ctx *ac, int type)
249 {
250 	struct asr_query	*as;
251 
252 	DPRINT("asr: asr_async_new(ctx=%p) type=%i refcount=%i\n", ac, type,
253 	    ac ? ac->ac_refcount : 0);
254 	if (ac == NULL || (as = calloc(1, sizeof(*as))) == NULL)
255 		return (NULL);
256 
257 	ac->ac_refcount += 1;
258 	as->as_ctx = ac;
259 	as->as_fd = -1;
260 	as->as_type = type;
261 	as->as_state = ASR_STATE_INIT;
262 
263 	return (as);
264 }
265 
266 /*
267  * Free an async query and unref the associated context.
268  */
269 void
270 asr_async_free(struct asr_query *as)
271 {
272 	DPRINT("asr: asr_async_free(%p)\n", as);
273 	switch (as->as_type) {
274 	case ASR_SEND:
275 		if (as->as_fd != -1)
276 			close(as->as_fd);
277 		if (as->as.dns.obuf && !(as->as.dns.flags & ASYNC_EXTOBUF))
278 			free(as->as.dns.obuf);
279 		if (as->as.dns.ibuf)
280 			free(as->as.dns.ibuf);
281 		if (as->as.dns.dname)
282 			free(as->as.dns.dname);
283 		break;
284 
285 	case ASR_SEARCH:
286 		if (as->as.search.subq)
287 			asr_async_free(as->as.search.subq);
288 		if (as->as.search.name)
289 			free(as->as.search.name);
290 		break;
291 
292 	case ASR_GETRRSETBYNAME:
293 		if (as->as.rrset.subq)
294 			asr_async_free(as->as.rrset.subq);
295 		if (as->as.rrset.name)
296 			free(as->as.rrset.name);
297 		break;
298 
299 	case ASR_GETHOSTBYNAME:
300 	case ASR_GETHOSTBYADDR:
301 		if (as->as.hostnamadr.subq)
302 			asr_async_free(as->as.hostnamadr.subq);
303 		if (as->as.hostnamadr.name)
304 			free(as->as.hostnamadr.name);
305 		break;
306 
307 	case ASR_GETNETBYNAME:
308 	case ASR_GETNETBYADDR:
309 		if (as->as.netnamadr.subq)
310 			asr_async_free(as->as.netnamadr.subq);
311 		if (as->as.netnamadr.name)
312 			free(as->as.netnamadr.name);
313 		break;
314 
315 	case ASR_GETADDRINFO:
316 		if (as->as.ai.subq)
317 			asr_async_free(as->as.ai.subq);
318 		if (as->as.ai.aifirst)
319 			freeaddrinfo(as->as.ai.aifirst);
320 		if (as->as.ai.hostname)
321 			free(as->as.ai.hostname);
322 		if (as->as.ai.servname)
323 			free(as->as.ai.servname);
324 		if (as->as.ai.fqdn)
325 			free(as->as.ai.fqdn);
326 		break;
327 
328 	case ASR_GETNAMEINFO:
329 		if (as->as.ni.subq)
330 			asr_async_free(as->as.ni.subq);
331 		break;
332 	}
333 
334 	asr_ctx_unref(as->as_ctx);
335 	free(as);
336 }
337 
338 /*
339  * Get a context from the given resolver. This takes a new reference to
340  * the returned context, which *must* be explicitely dropped when done
341  * using this context.
342  */
343 struct asr_ctx *
344 asr_use_resolver(void *arg)
345 {
346 	struct asr *asr = arg;
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 = asr_resolver(NULL);
355 		}
356 		asr = *priv;
357 	}
358 	if (asr != NULL) {
359 		asr_check_reload(asr);
360 		asr_ctx_ref(asr->a_ctx);
361 		return (asr->a_ctx);
362 	}
363 	return (NULL);
364 }
365 
366 static void
367 asr_ctx_ref(struct asr_ctx *ac)
368 {
369 	DPRINT("asr: asr_ctx_ref(ctx=%p) refcount=%i\n", ac, ac->ac_refcount);
370 	ac->ac_refcount += 1;
371 }
372 
373 /*
374  * Drop a reference to an async context, freeing it if the reference
375  * count drops to 0.
376  */
377 void
378 asr_ctx_unref(struct asr_ctx *ac)
379 {
380 	DPRINT("asr: asr_ctx_unref(ctx=%p) refcount=%i\n", ac,
381 	    ac ? ac->ac_refcount : 0);
382 	if (ac == NULL)
383 		return;
384 	if (--ac->ac_refcount)
385 		return;
386 
387 	asr_ctx_free(ac);
388 }
389 
390 static void
391 asr_ctx_free(struct asr_ctx *ac)
392 {
393 	int i;
394 
395 	if (ac->ac_domain)
396 		free(ac->ac_domain);
397 	for (i = 0; i < ASR_MAXNS; i++)
398 		free(ac->ac_ns[i]);
399 	for (i = 0; i < ASR_MAXDOM; i++)
400 		free(ac->ac_dom[i]);
401 
402 	free(ac);
403 }
404 
405 /*
406  * Reload the configuration file if it has changed on disk.
407  */
408 static void
409 asr_check_reload(struct asr *asr)
410 {
411 	struct asr_ctx	*ac;
412 #if ASR_OPT_RELOADCONF
413 	struct stat	 st;
414 	struct timespec	 ts;
415 	pid_t		 pid;
416 #endif
417 
418 	if (asr->a_path == NULL)
419 		return;
420 
421 #if ASR_OPT_RELOADCONF
422 
423 	pid = getpid();
424 	if (pid != asr->a_pid) {
425 		asr->a_pid = pid;
426 		asr->a_rtime = 0;
427 	}
428 
429 	if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
430 		return;
431 
432 	if ((ts.tv_sec - asr->a_rtime) < RELOAD_DELAY && asr->a_rtime != 0)
433 		return;
434 	asr->a_rtime = ts.tv_sec;
435 
436 	DPRINT("asr: checking for update of \"%s\"\n", asr->a_path);
437 	if (stat(asr->a_path, &st) == -1 ||
438 	    asr->a_mtime == st.st_mtime ||
439 	    (ac = asr_ctx_create()) == NULL)
440 		return;
441 	asr->a_mtime = st.st_mtime;
442 #else
443 	if ((ac = asr_ctx_create()) == NULL)
444 		return;
445 #endif
446 
447 	DPRINT("asr: reloading config file\n");
448 	if (asr_ctx_from_file(ac, asr->a_path) == -1) {
449 		asr_ctx_free(ac);
450 		return;
451 	}
452 
453 #if ASR_OPT_ENVOPTS
454 	asr_ctx_envopts(ac);
455 #endif
456 	if (asr->a_ctx)
457 		asr_ctx_unref(asr->a_ctx);
458 	asr->a_ctx = ac;
459 }
460 
461 /*
462  * Construct a fully-qualified domain name for the given name and domain.
463  * If "name" ends with a '.' it is considered as a FQDN by itself.
464  * Otherwise, the domain, which must be a FQDN, is appended to "name" (it
465  * may have a leading dot which would be ignored). If the domain is null,
466  * then "." is used. Return the length of the constructed FQDN or (0) on
467  * error.
468  */
469 size_t
470 asr_make_fqdn(const char *name, const char *domain, char *buf, size_t buflen)
471 {
472 	size_t	len;
473 
474 	if (domain == NULL)
475 		domain = ".";
476 	else if ((len = strlen(domain)) == 0)
477 		return (0);
478 	else if (domain[len -1] != '.')
479 		return (0);
480 
481 	len = strlen(name);
482 	if (len == 0) {
483 		if (strlcpy(buf, domain, buflen) >= buflen)
484 			return (0);
485 	} else if (name[len - 1] !=  '.') {
486 		if (domain[0] == '.')
487 			domain += 1;
488 		if (strlcpy(buf, name, buflen) >= buflen ||
489 		    strlcat(buf, ".", buflen) >= buflen ||
490 		    strlcat(buf, domain, buflen) >= buflen)
491 			return (0);
492 	} else {
493 		if (strlcpy(buf, name, buflen) >= buflen)
494 			return (0);
495 	}
496 
497 	return (strlen(buf));
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_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 		/* ensure that each lookup is only given once */
609 		for (i = 1; i < n; i++)
610 			for (j = i + 1; j < n; j++)
611 				if (!strcmp(tok[i], tok[j]))
612 					return;
613 		ac->ac_dbcount = 0;
614 		for (i = 1; i < n && ac->ac_dbcount < ASR_MAXDB; i++) {
615 			if (!strcmp(tok[i], "yp"))
616 				ac->ac_db[ac->ac_dbcount++] = ASR_DB_YP;
617 			else if (!strcmp(tok[i], "bind"))
618 				ac->ac_db[ac->ac_dbcount++] = ASR_DB_DNS;
619 			else if (!strcmp(tok[i], "file"))
620 				ac->ac_db[ac->ac_dbcount++] = ASR_DB_FILE;
621 		}
622 	} else if (!strcmp(tok[0], "search")) {
623 		/* resolv.conf says the last line wins */
624 		for (i = 0; i < ASR_MAXDOM; i++)
625 			free(ac->ac_dom[i]);
626 		ac->ac_domcount = 0;
627 		for (i = 1; i < n; i++)
628 			asr_ctx_add_searchdomain(ac, tok[i]);
629 
630 	} else if (!strcmp(tok[0], "family")) {
631 		if (n == 1 || n > 3)
632 			return;
633 		for (i = 1; i < n; i++)
634 			if (strcmp(tok[i], "inet4") && strcmp(tok[i], "inet6"))
635 				return;
636 		for (i = 1; i < n; i++)
637 			ac->ac_family[i - 1] = strcmp(tok[i], "inet4") ? \
638 			    AF_INET6 : AF_INET;
639 		ac->ac_family[i - 1] = -1;
640 
641 	} else if (!strcmp(tok[0], "options")) {
642 		for (i = 1; i < n; i++) {
643 			if (!strcmp(tok[i], "tcp"))
644 				ac->ac_options |= RES_USEVC;
645 			else if ((!strncmp(tok[i], "ndots:", 6))) {
646 				e = NULL;
647 				d = strtonum(tok[i] + 6, 1, 16, &e);
648 				if (e == NULL)
649 					ac->ac_ndots = d;
650 			}
651 		}
652 	}
653 }
654 
655 /*
656  * Setup an async context with the config specified in the string "str".
657  */
658 static int
659 asr_ctx_from_string(struct asr_ctx *ac, const char *str)
660 {
661 	char		 buf[512], *ch;
662 
663 	asr_ctx_parse(ac, str);
664 
665 	if (ac->ac_dbcount == 0) {
666 		/* No lookup directive */
667 		asr_ctx_parse(ac, DEFAULT_LOOKUP);
668 	}
669 
670 	if (ac->ac_nscount == 0)
671 		asr_ctx_parse(ac, "nameserver 127.0.0.1");
672 
673 	if (ac->ac_domain == NULL)
674 		if (gethostname(buf, sizeof buf) == 0) {
675 			ch = strchr(buf, '.');
676 			if (ch)
677 				ac->ac_domain = strdup(ch + 1);
678 			else /* Assume root. see resolv.conf(5) */
679 				ac->ac_domain = strdup("");
680 		}
681 
682 	/* If no search domain was specified, use the local subdomains */
683 	if (ac->ac_domcount == 0)
684 		for (ch = ac->ac_domain; ch; ) {
685 			asr_ctx_add_searchdomain(ac, ch);
686 			ch = strchr(ch, '.');
687 			if (ch && asr_ndots(++ch) == 0)
688 				break;
689 		}
690 
691 	return (0);
692 }
693 
694 /*
695  * Setup the "ac" async context from the file at location "path".
696  */
697 static int
698 asr_ctx_from_file(struct asr_ctx *ac, const char *path)
699 {
700 	FILE	*cf;
701 	char	 buf[4096];
702 	ssize_t	 r;
703 
704 	cf = fopen(path, "re");
705 	if (cf == NULL)
706 		return (-1);
707 
708 	r = fread(buf, 1, sizeof buf - 1, cf);
709 	if (feof(cf) == 0) {
710 		DPRINT("asr: config file too long: \"%s\"\n", path);
711 		r = -1;
712 	}
713 	fclose(cf);
714 	if (r == -1)
715 		return (-1);
716 	buf[r] = '\0';
717 
718 	return asr_ctx_from_string(ac, buf);
719 }
720 
721 /*
722  * Parse lines in the configuration string. For each one, split it into
723  * tokens and pass them to "pass0" for processing.
724  */
725 static int
726 asr_ctx_parse(struct asr_ctx *ac, const char *str)
727 {
728 	size_t		 len;
729 	const char	*line;
730 	char		 buf[1024];
731 	char		*tok[10];
732 	int		 ntok;
733 
734 	line = str;
735 	while (*line) {
736 		len = strcspn(line, "\n\0");
737 		if (len < sizeof buf) {
738 			memmove(buf, line, len);
739 			buf[len] = '\0';
740 		} else
741 			buf[0] = '\0';
742 		line += len;
743 		if (*line == '\n')
744 			line++;
745 		buf[strcspn(buf, ";#")] = '\0';
746 		if ((ntok = strsplit(buf, tok, 10)) == 0)
747 			continue;
748 
749 		pass0(tok, ntok, ac);
750 	}
751 
752 	return (0);
753 }
754 
755 #if ASR_OPT_ENVOPTS
756 /*
757  * Check for environment variables altering the configuration as described
758  * in resolv.conf(5).  Altough not documented there, this feature is disabled
759  * for setuid/setgid programs.
760  */
761 static void
762 asr_ctx_envopts(struct asr_ctx *ac)
763 {
764 	char	buf[4096], *e;
765 	size_t	s;
766 
767 	if (issetugid()) {
768 		ac->ac_options |= RES_NOALIASES;
769 		return;
770 	}
771 
772 	if ((e = getenv("RES_OPTIONS")) != NULL) {
773 		strlcpy(buf, "options ", sizeof buf);
774 		strlcat(buf, e, sizeof buf);
775 		s = strlcat(buf, "\n", sizeof buf);
776 		s = strlcat(buf, "\n", sizeof buf);
777 		if (s < sizeof buf)
778 			asr_ctx_parse(ac, buf);
779 	}
780 
781 	if ((e = getenv("LOCALDOMAIN")) != NULL) {
782 		strlcpy(buf, "search ", sizeof buf);
783 		strlcat(buf, e, sizeof buf);
784 		s = strlcat(buf, "\n", sizeof buf);
785 		if (s < sizeof buf)
786 			asr_ctx_parse(ac, buf);
787 	}
788 }
789 #endif
790 
791 /*
792  * Parse a resolv.conf(5) nameserver string into a sockaddr.
793  */
794 static int
795 asr_parse_nameserver(struct sockaddr *sa, const char *s)
796 {
797 	const char	*estr;
798 	char		 buf[256];
799 	char		*port = NULL;
800 	in_port_t	 portno = 53;
801 
802 	if (*s == '[') {
803 		strlcpy(buf, s + 1, sizeof buf);
804 		s = buf;
805 		port = strchr(buf, ']');
806 		if (port == NULL)
807 			return (-1);
808 		*port++ = '\0';
809 		if (*port != ':')
810 			return (-1);
811 		port++;
812 	}
813 
814 	if (port) {
815 		portno = strtonum(port, 1, USHRT_MAX, &estr);
816 		if (estr)
817 			return (-1);
818 	}
819 
820 	if (asr_sockaddr_from_str(sa, PF_UNSPEC, s) == -1)
821 		return (-1);
822 
823 	if (sa->sa_family == PF_INET)
824 		((struct sockaddr_in *)sa)->sin_port = htons(portno);
825 	else if (sa->sa_family == PF_INET6)
826 		((struct sockaddr_in6 *)sa)->sin6_port = htons(portno);
827 
828 	return (0);
829 }
830 
831 /*
832  * Turn a (uncompressed) DNS domain name into a regular nul-terminated string
833  * where labels are separated by dots. The result is put into the "buf" buffer,
834  * truncated if it exceeds "max" chars. The function returns "buf".
835  */
836 char *
837 asr_strdname(const char *_dname, char *buf, size_t max)
838 {
839 	const unsigned char *dname = _dname;
840 	char	*res;
841 	size_t	 left, n, count;
842 
843 	if (_dname[0] == 0) {
844 		strlcpy(buf, ".", max);
845 		return buf;
846 	}
847 
848 	res = buf;
849 	left = max - 1;
850 	for (n = 0; dname[0] && left; n += dname[0]) {
851 		count = (dname[0] < (left - 1)) ? dname[0] : (left - 1);
852 		memmove(buf, dname + 1, count);
853 		dname += dname[0] + 1;
854 		left -= count;
855 		buf += count;
856 		if (left) {
857 			left -= 1;
858 			*buf++ = '.';
859 		}
860 	}
861 	buf[0] = 0;
862 
863 	return (res);
864 }
865 
866 /*
867  * Read and split the next line from the given namedb file.
868  * Return -1 on error, or put the result in the "tokens" array of
869  * size "ntoken" and returns the number of token on the line.
870  */
871 int
872 asr_parse_namedb_line(FILE *file, char **tokens, int ntoken, char *lbuf, size_t sz)
873 {
874 	size_t	  len;
875 	char	 *buf;
876 	int	  ntok;
877 
878     again:
879 	if ((buf = fgetln(file, &len)) == NULL)
880 		return (-1);
881 
882 	if (len >= sz)
883 		goto again;
884 
885 	if (buf[len - 1] == '\n')
886 		len--;
887 	else {
888 		memcpy(lbuf, buf, len);
889 		buf = lbuf;
890 	}
891 
892 	buf[len] = '\0';
893 	buf[strcspn(buf, "#")] = '\0';
894 	if ((ntok = strsplit(buf, tokens, ntoken)) == 0)
895 		goto again;
896 
897 	return (ntok);
898 }
899 
900 /*
901  * Update the async context so that it uses the next configured DB.
902  * Return 0 on success, or -1 if no more DBs is available.
903  */
904 int
905 asr_iter_db(struct asr_query *as)
906 {
907 	if (as->as_db_idx >= as->as_ctx->ac_dbcount) {
908 		DPRINT("asr_iter_db: done\n");
909 		return (-1);
910 	}
911 
912 	as->as_db_idx += 1;
913 	DPRINT("asr_iter_db: %i\n", as->as_db_idx);
914 
915 	return (0);
916 }
917 
918 /*
919  * Check if the hostname "name" is a user-defined alias as per hostname(7).
920  * If so, copies the result in the buffer "abuf" of size "abufsz" and
921  * return "abuf". Otherwise return NULL.
922  */
923 char *
924 asr_hostalias(struct asr_ctx *ac, const char *name, char *abuf, size_t abufsz)
925 {
926 #if ASR_OPT_HOSTALIASES
927 	FILE	 *fp;
928 	size_t	  len;
929 	char	 *file, *buf, *tokens[2];
930 	int	  ntok;
931 
932 	if (ac->ac_options & RES_NOALIASES ||
933 	    asr_ndots(name) != 0 ||
934 	    issetugid() ||
935 	    (file = getenv("HOSTALIASES")) == NULL ||
936 	    (fp = fopen(file, "re")) == NULL)
937 		return (NULL);
938 
939 	DPRINT("asr: looking up aliases in \"%s\"\n", file);
940 
941 	while ((buf = fgetln(fp, &len)) != NULL) {
942 		if (buf[len - 1] == '\n')
943 			len--;
944 		buf[len] = '\0';
945 		if ((ntok = strsplit(buf, tokens, 2)) != 2)
946 			continue;
947 		if (!strcasecmp(tokens[0], name)) {
948 			if (strlcpy(abuf, tokens[1], abufsz) > abufsz)
949 				continue;
950 			DPRINT("asr: found alias \"%s\"\n", abuf);
951 			fclose(fp);
952 			return (abuf);
953 		}
954 	}
955 
956 	fclose(fp);
957 #endif
958 	return (NULL);
959 }
960