xref: /openbsd-src/lib/libc/asr/asr.c (revision c90a81c56dcebd6a1b73fe4aff9b03385b8e63b3)
1 /*	$OpenBSD: asr.c,v 1.61 2018/10/22 17:31:24 krw 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 <errno.h>
28 #include <fcntl.h>
29 #include <resolv.h>
30 #include <poll.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <limits.h>
36 
37 #include "asr_private.h"
38 
39 #include "thread_private.h"
40 
41 #define DEFAULT_CONF		"lookup file\n"
42 #define DEFAULT_LOOKUP		"lookup bind file"
43 
44 #define RELOAD_DELAY		15 /* seconds */
45 
46 static void asr_check_reload(struct asr *);
47 static struct asr_ctx *asr_ctx_create(void);
48 static void asr_ctx_ref(struct asr_ctx *);
49 static void asr_ctx_free(struct asr_ctx *);
50 static int asr_ctx_add_searchdomain(struct asr_ctx *, const char *);
51 static int asr_ctx_from_file(struct asr_ctx *, const char *);
52 static int asr_ctx_from_string(struct asr_ctx *, const char *);
53 static int asr_ctx_parse(struct asr_ctx *, const char *);
54 static int asr_parse_nameserver(struct sockaddr *, const char *);
55 static int asr_ndots(const char *);
56 static void pass0(char **, int, struct asr_ctx *);
57 static int strsplit(char *, char **, int);
58 static void asr_ctx_envopts(struct asr_ctx *);
59 static void *__THREAD_NAME(_asr);
60 
61 static struct asr *_asr = NULL;
62 
63 /* Allocate and configure an async "resolver". */
64 static void *
65 _asr_resolver(void)
66 {
67 	static int	 init = 0;
68 	struct asr	*asr;
69 
70 	if (init == 0) {
71 #ifdef DEBUG
72 		if (getenv("ASR_DEBUG"))
73 			_asr_debug = stderr;
74 #endif
75 		init = 1;
76 	}
77 
78 	if ((asr = calloc(1, sizeof(*asr))) == NULL)
79 		goto fail;
80 
81 	asr_check_reload(asr);
82 	if (asr->a_ctx == NULL) {
83 		if ((asr->a_ctx = asr_ctx_create()) == NULL)
84 			goto fail;
85 		if (asr_ctx_from_string(asr->a_ctx, DEFAULT_CONF) == -1)
86 			goto fail;
87 		asr_ctx_envopts(asr->a_ctx);
88 	}
89 
90 #ifdef DEBUG
91 	_asr_dump_config(_asr_debug, asr);
92 #endif
93 	return (asr);
94 
95     fail:
96 	if (asr) {
97 		if (asr->a_ctx)
98 			asr_ctx_free(asr->a_ctx);
99 		free(asr);
100 	}
101 
102 	return (NULL);
103 }
104 
105 /*
106  * Free the "asr" async resolver (or the thread-local resolver if NULL).
107  * Drop the reference to the current context.
108  */
109 void
110 _asr_resolver_done(void *arg)
111 {
112 	struct asr *asr = arg;
113 	struct asr **priv;
114 
115 	if (asr == NULL) {
116 		priv = _THREAD_PRIVATE(_asr, _asr, &_asr);
117 		if (*priv == NULL)
118 			return;
119 		asr = *priv;
120 		*priv = NULL;
121 	}
122 
123 	_asr_ctx_unref(asr->a_ctx);
124 	free(asr);
125 }
126 
127 /*
128  * Cancel an async query.
129  */
130 void
131 asr_abort(struct asr_query *as)
132 {
133 	_asr_async_free(as);
134 }
135 
136 /*
137  * Resume the "as" async query resolution.  Return one of ASYNC_COND,
138  * or ASYNC_DONE and put query-specific return values in the user-allocated
139  * memory at "ar".
140  */
141 int
142 asr_run(struct asr_query *as, struct asr_result *ar)
143 {
144 	int	r, saved_errno = errno;
145 
146 	DPRINT("asr: asr_run(%p, %p) %s ctx=[%p]\n", as, ar,
147 	    _asr_querystr(as->as_type), as->as_ctx);
148 	r = as->as_run(as, ar);
149 
150 	DPRINT("asr: asr_run(%p, %p) -> %s", as, ar, _asr_transitionstr(r));
151 #ifdef DEBUG
152 	if (r == ASYNC_COND)
153 #endif
154 		DPRINT(" fd=%i timeout=%i", ar->ar_fd, ar->ar_timeout);
155 	DPRINT("\n");
156 	if (r == ASYNC_DONE)
157 		_asr_async_free(as);
158 
159 	errno = saved_errno;
160 
161 	return (r);
162 }
163 DEF_WEAK(asr_run);
164 
165 static int
166 poll_intrsafe(struct pollfd *fds, nfds_t nfds, int timeout)
167 {
168 	struct timespec pollstart, pollend, elapsed;
169 	int r;
170 
171 	if (clock_gettime(CLOCK_MONOTONIC, &pollstart))
172 		return -1;
173 
174 	while ((r = poll(fds, 1, timeout)) == -1 && errno == EINTR) {
175 		if (clock_gettime(CLOCK_MONOTONIC, &pollend))
176 			return -1;
177 		timespecsub(&pollend, &pollstart, &elapsed);
178 		timeout -= elapsed.tv_sec * 1000 + elapsed.tv_nsec / 1000000;
179 		if (timeout < 1)
180 			return 0;
181 	}
182 
183 	return r;
184 }
185 
186 /*
187  * Same as asr_run, but run in a loop that handles the fd conditions result.
188  */
189 int
190 asr_run_sync(struct asr_query *as, struct asr_result *ar)
191 {
192 	struct pollfd	 fds[1];
193 	int		 r, saved_errno = errno;
194 
195 	while ((r = asr_run(as, ar)) == ASYNC_COND) {
196 		fds[0].fd = ar->ar_fd;
197 		fds[0].events = (ar->ar_cond == ASR_WANT_READ) ? POLLIN:POLLOUT;
198 
199 		if (poll_intrsafe(fds, 1, ar->ar_timeout) == -1) {
200 			memset(ar, 0, sizeof(*ar));
201 			ar->ar_errno = errno;
202 			ar->ar_h_errno = NETDB_INTERNAL;
203 			ar->ar_gai_errno = EAI_SYSTEM;
204 			ar->ar_rrset_errno = NETDB_INTERNAL;
205 			_asr_async_free(as);
206 			errno = saved_errno;
207 			return ASYNC_DONE;
208 		}
209 
210 		/*
211 		 * Otherwise, just ignore the error and let asr_run()
212 		 * catch the failure.
213 		 */
214 	}
215 
216 	errno = saved_errno;
217 
218 	return (r);
219 }
220 DEF_WEAK(asr_run_sync);
221 
222 /*
223  * Create a new async request of the given "type" on the async context "ac".
224  * Take a reference on it so it does not get deleted while the async query
225  * is running.
226  */
227 struct asr_query *
228 _asr_async_new(struct asr_ctx *ac, int type)
229 {
230 	struct asr_query	*as;
231 
232 	DPRINT("asr: asr_async_new(ctx=%p) type=%i refcount=%i\n", ac, type,
233 	    ac ? ac->ac_refcount : 0);
234 	if (ac == NULL || (as = calloc(1, sizeof(*as))) == NULL)
235 		return (NULL);
236 
237 	ac->ac_refcount += 1;
238 	as->as_ctx = ac;
239 	as->as_fd = -1;
240 	as->as_type = type;
241 	as->as_state = ASR_STATE_INIT;
242 
243 	return (as);
244 }
245 
246 /*
247  * Free an async query and unref the associated context.
248  */
249 void
250 _asr_async_free(struct asr_query *as)
251 {
252 	DPRINT("asr: asr_async_free(%p)\n", as);
253 
254 	if (as->as_subq)
255 		_asr_async_free(as->as_subq);
256 
257 	switch (as->as_type) {
258 	case ASR_SEND:
259 		if (as->as_fd != -1)
260 			close(as->as_fd);
261 		if (as->as.dns.obuf && !(as->as_flags & ASYNC_EXTOBUF))
262 			free(as->as.dns.obuf);
263 		if (as->as.dns.ibuf)
264 			free(as->as.dns.ibuf);
265 		if (as->as.dns.dname)
266 			free(as->as.dns.dname);
267 		break;
268 
269 	case ASR_SEARCH:
270 		if (as->as.search.name)
271 			free(as->as.search.name);
272 		break;
273 
274 	case ASR_GETRRSETBYNAME:
275 		if (as->as.rrset.name)
276 			free(as->as.rrset.name);
277 		break;
278 
279 	case ASR_GETHOSTBYNAME:
280 	case ASR_GETHOSTBYADDR:
281 		if (as->as.hostnamadr.name)
282 			free(as->as.hostnamadr.name);
283 		break;
284 
285 	case ASR_GETADDRINFO:
286 		if (as->as.ai.aifirst)
287 			freeaddrinfo(as->as.ai.aifirst);
288 		if (as->as.ai.hostname)
289 			free(as->as.ai.hostname);
290 		if (as->as.ai.servname)
291 			free(as->as.ai.servname);
292 		if (as->as.ai.fqdn)
293 			free(as->as.ai.fqdn);
294 		break;
295 
296 	case ASR_GETNAMEINFO:
297 		break;
298 	}
299 
300 	_asr_ctx_unref(as->as_ctx);
301 	free(as);
302 }
303 
304 /*
305  * Get a context from the given resolver. This takes a new reference to
306  * the returned context, which *must* be explicitly dropped when done
307  * using this context.
308  */
309 struct asr_ctx *
310 _asr_use_resolver(void *arg)
311 {
312 	struct asr *asr = arg;
313 	struct asr **priv;
314 
315 	if (asr == NULL) {
316 		DPRINT("using thread-local resolver\n");
317 		priv = _THREAD_PRIVATE(_asr, _asr, &_asr);
318 		if (*priv == NULL) {
319 			DPRINT("setting up thread-local resolver\n");
320 			*priv = _asr_resolver();
321 		}
322 		asr = *priv;
323 	}
324 	if (asr != NULL) {
325 		asr_check_reload(asr);
326 		asr_ctx_ref(asr->a_ctx);
327 		return (asr->a_ctx);
328 	}
329 	return (NULL);
330 }
331 
332 static void
333 asr_ctx_ref(struct asr_ctx *ac)
334 {
335 	DPRINT("asr: asr_ctx_ref(ctx=%p) refcount=%i\n", ac, ac->ac_refcount);
336 	ac->ac_refcount += 1;
337 }
338 
339 /*
340  * Drop a reference to an async context, freeing it if the reference
341  * count drops to 0.
342  */
343 void
344 _asr_ctx_unref(struct asr_ctx *ac)
345 {
346 	DPRINT("asr: asr_ctx_unref(ctx=%p) refcount=%i\n", ac,
347 	    ac ? ac->ac_refcount : 0);
348 	if (ac == NULL)
349 		return;
350 	if (--ac->ac_refcount)
351 		return;
352 
353 	asr_ctx_free(ac);
354 }
355 
356 static void
357 asr_ctx_free(struct asr_ctx *ac)
358 {
359 	int i;
360 
361 	if (ac->ac_domain)
362 		free(ac->ac_domain);
363 	for (i = 0; i < ASR_MAXNS; i++)
364 		free(ac->ac_ns[i]);
365 	for (i = 0; i < ASR_MAXDOM; i++)
366 		free(ac->ac_dom[i]);
367 
368 	free(ac);
369 }
370 
371 /*
372  * Reload the configuration file if it has changed on disk.
373  */
374 static void
375 asr_check_reload(struct asr *asr)
376 {
377 	struct asr_ctx	*ac;
378 	struct stat	 st;
379 	struct timespec	 ts;
380 	pid_t		 pid;
381 
382 	pid = getpid();
383 	if (pid != asr->a_pid) {
384 		asr->a_pid = pid;
385 		asr->a_rtime = 0;
386 	}
387 
388 	if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
389 		return;
390 
391 	if ((ts.tv_sec - asr->a_rtime) < RELOAD_DELAY && asr->a_rtime != 0)
392 		return;
393 	asr->a_rtime = ts.tv_sec;
394 
395 	DPRINT("asr: checking for update of \"%s\"\n", _PATH_RESCONF);
396 	if (stat(_PATH_RESCONF, &st) == -1 ||
397 	    asr->a_mtime == st.st_mtime ||
398 	    (ac = asr_ctx_create()) == NULL)
399 		return;
400 	asr->a_mtime = st.st_mtime;
401 
402 	DPRINT("asr: reloading config file\n");
403 	if (asr_ctx_from_file(ac, _PATH_RESCONF) == -1) {
404 		asr_ctx_free(ac);
405 		return;
406 	}
407 
408 	asr_ctx_envopts(ac);
409 	if (asr->a_ctx)
410 		_asr_ctx_unref(asr->a_ctx);
411 	asr->a_ctx = ac;
412 }
413 
414 /*
415  * Construct a fully-qualified domain name for the given name and domain.
416  * If "name" ends with a '.' it is considered as a FQDN by itself.
417  * Otherwise, the domain, which must be a FQDN, is appended to "name" (it
418  * may have a leading dot which would be ignored). If the domain is null,
419  * then "." is used. Return the length of the constructed FQDN or (0) on
420  * error.
421  */
422 size_t
423 _asr_make_fqdn(const char *name, const char *domain, char *buf, size_t buflen)
424 {
425 	size_t	len;
426 
427 	if (domain == NULL)
428 		domain = ".";
429 	else if ((len = strlen(domain)) == 0)
430 		return (0);
431 	else if (domain[len -1] != '.')
432 		return (0);
433 
434 	len = strlen(name);
435 	if (len == 0) {
436 		if (strlcpy(buf, domain, buflen) >= buflen)
437 			return (0);
438 	} else if (name[len - 1] !=  '.') {
439 		if (domain[0] == '.')
440 			domain += 1;
441 		if (strlcpy(buf, name, buflen) >= buflen ||
442 		    strlcat(buf, ".", buflen) >= buflen ||
443 		    strlcat(buf, domain, buflen) >= buflen)
444 			return (0);
445 	} else {
446 		if (strlcpy(buf, name, buflen) >= buflen)
447 			return (0);
448 	}
449 
450 	return (strlen(buf));
451 }
452 
453 /*
454  * Count the dots in a string.
455  */
456 static int
457 asr_ndots(const char *s)
458 {
459 	int n;
460 
461 	for (n = 0; *s; s++)
462 		if (*s == '.')
463 			n += 1;
464 
465 	return (n);
466 }
467 
468 /*
469  * Allocate a new empty context.
470  */
471 static struct asr_ctx *
472 asr_ctx_create(void)
473 {
474 	struct asr_ctx	*ac;
475 
476 	if ((ac = calloc(1, sizeof(*ac))) == NULL)
477 		return (NULL);
478 
479 	ac->ac_options = RES_RECURSE | RES_DEFNAMES | RES_DNSRCH;
480 	ac->ac_refcount = 1;
481 	ac->ac_ndots = 1;
482 	ac->ac_family[0] = AF_INET;
483 	ac->ac_family[1] = AF_INET6;
484 	ac->ac_family[2] = -1;
485 
486 	ac->ac_nscount = 0;
487 	ac->ac_nstimeout = 5;
488 	ac->ac_nsretries = 4;
489 
490 	return (ac);
491 }
492 
493 struct asr_ctx *
494 _asr_no_resolver(void)
495 {
496 	return asr_ctx_create();
497 }
498 
499 /*
500  * Add a search domain to the async context.
501  */
502 static int
503 asr_ctx_add_searchdomain(struct asr_ctx *ac, const char *domain)
504 {
505 	char buf[MAXDNAME];
506 
507 	if (ac->ac_domcount == ASR_MAXDOM)
508 		return (-1);
509 
510 	if (_asr_make_fqdn(domain, NULL, buf, sizeof(buf)) == 0)
511 		return (-1);
512 
513 	if ((ac->ac_dom[ac->ac_domcount] = strdup(buf)) == NULL)
514 		return (0);
515 
516 	ac->ac_domcount += 1;
517 
518 	return (1);
519 }
520 
521 static int
522 strsplit(char *line, char **tokens, int ntokens)
523 {
524 	int	ntok;
525 	char	*cp, **tp;
526 
527 	for (cp = line, tp = tokens, ntok = 0;
528 	    ntok < ntokens && (*tp = strsep(&cp, " \t")) != NULL; )
529 		if (**tp != '\0') {
530 			tp++;
531 			ntok++;
532 		}
533 
534 	return (ntok);
535 }
536 
537 /*
538  * Pass on a split config line.
539  */
540 static void
541 pass0(char **tok, int n, struct asr_ctx *ac)
542 {
543 	int		 i, j, d;
544 	const char	*e;
545 	struct sockaddr_storage	ss;
546 
547 	if (!strcmp(tok[0], "nameserver")) {
548 		if (ac->ac_nscount == ASR_MAXNS)
549 			return;
550 		if (n != 2)
551 			return;
552 		if (asr_parse_nameserver((struct sockaddr *)&ss, tok[1]))
553 			return;
554 		if ((ac->ac_ns[ac->ac_nscount] = calloc(1, ss.ss_len)) == NULL)
555 			return;
556 		memmove(ac->ac_ns[ac->ac_nscount], &ss, ss.ss_len);
557 		ac->ac_nscount += 1;
558 
559 	} else if (!strcmp(tok[0], "domain")) {
560 		if (n != 2)
561 			return;
562 		if (ac->ac_domain)
563 			return;
564 		ac->ac_domain = strdup(tok[1]);
565 
566 	} else if (!strcmp(tok[0], "lookup")) {
567 		/* ensure that each lookup is only given once */
568 		for (i = 1; i < n; i++)
569 			for (j = i + 1; j < n; j++)
570 				if (!strcmp(tok[i], tok[j]))
571 					return;
572 		ac->ac_dbcount = 0;
573 		for (i = 1; i < n && ac->ac_dbcount < ASR_MAXDB; i++) {
574 			if (!strcmp(tok[i], "yp")) {
575 				/* silently deprecated */
576 			} else if (!strcmp(tok[i], "bind"))
577 				ac->ac_db[ac->ac_dbcount++] = ASR_DB_DNS;
578 			else if (!strcmp(tok[i], "file"))
579 				ac->ac_db[ac->ac_dbcount++] = ASR_DB_FILE;
580 		}
581 	} else if (!strcmp(tok[0], "search")) {
582 		/* resolv.conf says the last line wins */
583 		for (i = 0; i < ASR_MAXDOM; i++) {
584 			free(ac->ac_dom[i]);
585 			ac->ac_dom[i] = NULL;
586 		}
587 		ac->ac_domcount = 0;
588 		for (i = 1; i < n; i++)
589 			asr_ctx_add_searchdomain(ac, tok[i]);
590 
591 	} else if (!strcmp(tok[0], "family")) {
592 		if (n == 1 || n > 3)
593 			return;
594 		for (i = 1; i < n; i++)
595 			if (strcmp(tok[i], "inet4") && strcmp(tok[i], "inet6"))
596 				return;
597 		for (i = 1; i < n; i++)
598 			ac->ac_family[i - 1] = strcmp(tok[i], "inet4") ? \
599 			    AF_INET6 : AF_INET;
600 		ac->ac_family[i - 1] = -1;
601 
602 	} else if (!strcmp(tok[0], "options")) {
603 		for (i = 1; i < n; i++) {
604 			if (!strcmp(tok[i], "tcp"))
605 				ac->ac_options |= RES_USEVC;
606 			else if (!strcmp(tok[i], "edns0"))
607 				ac->ac_options |= RES_USE_EDNS0;
608 			else if ((!strncmp(tok[i], "ndots:", 6))) {
609 				e = NULL;
610 				d = strtonum(tok[i] + 6, 1, 16, &e);
611 				if (e == NULL)
612 					ac->ac_ndots = d;
613 			}
614 		}
615 	}
616 }
617 
618 /*
619  * Setup an async context with the config specified in the string "str".
620  */
621 static int
622 asr_ctx_from_string(struct asr_ctx *ac, const char *str)
623 {
624 	char		 buf[512], *ch;
625 
626 	asr_ctx_parse(ac, str);
627 
628 	if (ac->ac_dbcount == 0) {
629 		/* No lookup directive */
630 		asr_ctx_parse(ac, DEFAULT_LOOKUP);
631 	}
632 
633 	if (ac->ac_nscount == 0)
634 		asr_ctx_parse(ac, "nameserver 127.0.0.1");
635 
636 	if (ac->ac_domain == NULL)
637 		if (gethostname(buf, sizeof buf) == 0) {
638 			ch = strchr(buf, '.');
639 			if (ch)
640 				ac->ac_domain = strdup(ch + 1);
641 			else /* Assume root. see resolv.conf(5) */
642 				ac->ac_domain = strdup("");
643 		}
644 
645 	/* If no search domain was specified, use the local subdomains */
646 	if (ac->ac_domcount == 0)
647 		for (ch = ac->ac_domain; ch; ) {
648 			asr_ctx_add_searchdomain(ac, ch);
649 			ch = strchr(ch, '.');
650 			if (ch && asr_ndots(++ch) == 0)
651 				break;
652 		}
653 
654 	return (0);
655 }
656 
657 /*
658  * Setup the "ac" async context from the file at location "path".
659  */
660 static int
661 asr_ctx_from_file(struct asr_ctx *ac, const char *path)
662 {
663 	FILE	*cf;
664 	char	 buf[4096];
665 	ssize_t	 r;
666 
667 	cf = fopen(path, "re");
668 	if (cf == NULL)
669 		return (-1);
670 
671 	r = fread(buf, 1, sizeof buf - 1, cf);
672 	if (feof(cf) == 0) {
673 		DPRINT("asr: config file too long: \"%s\"\n", path);
674 		r = -1;
675 	}
676 	fclose(cf);
677 	if (r == -1)
678 		return (-1);
679 	buf[r] = '\0';
680 
681 	return asr_ctx_from_string(ac, buf);
682 }
683 
684 /*
685  * Parse lines in the configuration string. For each one, split it into
686  * tokens and pass them to "pass0" for processing.
687  */
688 static int
689 asr_ctx_parse(struct asr_ctx *ac, const char *str)
690 {
691 	size_t		 len;
692 	const char	*line;
693 	char		 buf[1024];
694 	char		*tok[10];
695 	int		 ntok;
696 
697 	line = str;
698 	while (*line) {
699 		len = strcspn(line, "\n\0");
700 		if (len < sizeof buf) {
701 			memmove(buf, line, len);
702 			buf[len] = '\0';
703 		} else
704 			buf[0] = '\0';
705 		line += len;
706 		if (*line == '\n')
707 			line++;
708 		buf[strcspn(buf, ";#")] = '\0';
709 		if ((ntok = strsplit(buf, tok, 10)) == 0)
710 			continue;
711 
712 		pass0(tok, ntok, ac);
713 	}
714 
715 	return (0);
716 }
717 
718 /*
719  * Check for environment variables altering the configuration as described
720  * in resolv.conf(5).  Although not documented there, this feature is disabled
721  * for setuid/setgid programs.
722  */
723 static void
724 asr_ctx_envopts(struct asr_ctx *ac)
725 {
726 	char	buf[4096], *e;
727 	size_t	s;
728 
729 	if (issetugid()) {
730 		ac->ac_options |= RES_NOALIASES;
731 		return;
732 	}
733 
734 	if ((e = getenv("RES_OPTIONS")) != NULL) {
735 		strlcpy(buf, "options ", sizeof buf);
736 		strlcat(buf, e, sizeof buf);
737 		s = strlcat(buf, "\n", sizeof buf);
738 		if (s < sizeof buf)
739 			asr_ctx_parse(ac, buf);
740 	}
741 
742 	if ((e = getenv("LOCALDOMAIN")) != NULL) {
743 		strlcpy(buf, "search ", sizeof buf);
744 		strlcat(buf, e, sizeof buf);
745 		s = strlcat(buf, "\n", sizeof buf);
746 		if (s < sizeof buf)
747 			asr_ctx_parse(ac, buf);
748 	}
749 }
750 
751 /*
752  * Parse a resolv.conf(5) nameserver string into a sockaddr.
753  */
754 static int
755 asr_parse_nameserver(struct sockaddr *sa, const char *s)
756 {
757 	in_port_t	 portno = 53;
758 
759 	if (_asr_sockaddr_from_str(sa, PF_UNSPEC, s) == -1)
760 		return (-1);
761 
762 	if (sa->sa_family == PF_INET)
763 		((struct sockaddr_in *)sa)->sin_port = htons(portno);
764 	else if (sa->sa_family == PF_INET6)
765 		((struct sockaddr_in6 *)sa)->sin6_port = htons(portno);
766 
767 	return (0);
768 }
769 
770 /*
771  * Turn a (uncompressed) DNS domain name into a regular nul-terminated string
772  * where labels are separated by dots. The result is put into the "buf" buffer,
773  * truncated if it exceeds "max" chars. The function returns "buf".
774  */
775 char *
776 _asr_strdname(const char *_dname, char *buf, size_t max)
777 {
778 	const unsigned char *dname = _dname;
779 	char	*res;
780 	size_t	 left, n, count;
781 
782 	if (_dname[0] == 0) {
783 		strlcpy(buf, ".", max);
784 		return buf;
785 	}
786 
787 	res = buf;
788 	left = max - 1;
789 	for (n = 0; dname[0] && left; n += dname[0]) {
790 		count = (dname[0] < (left - 1)) ? dname[0] : (left - 1);
791 		memmove(buf, dname + 1, count);
792 		dname += dname[0] + 1;
793 		left -= count;
794 		buf += count;
795 		if (left) {
796 			left -= 1;
797 			*buf++ = '.';
798 		}
799 	}
800 	buf[0] = 0;
801 
802 	return (res);
803 }
804 
805 /*
806  * Read and split the next line from the given namedb file.
807  * Return -1 on error, or put the result in the "tokens" array of
808  * size "ntoken" and returns the number of token on the line.
809  */
810 int
811 _asr_parse_namedb_line(FILE *file, char **tokens, int ntoken, char *lbuf, size_t sz)
812 {
813 	size_t	  len;
814 	char	 *buf;
815 	int	  ntok;
816 
817     again:
818 	if ((buf = fgetln(file, &len)) == NULL)
819 		return (-1);
820 
821 	if (len >= sz)
822 		goto again;
823 
824 	if (buf[len - 1] == '\n')
825 		len--;
826 	else {
827 		memcpy(lbuf, buf, len);
828 		buf = lbuf;
829 	}
830 
831 	buf[len] = '\0';
832 	buf[strcspn(buf, "#")] = '\0';
833 	if ((ntok = strsplit(buf, tokens, ntoken)) == 0)
834 		goto again;
835 
836 	return (ntok);
837 }
838 
839 /*
840  * Update the async context so that it uses the next configured DB.
841  * Return 0 on success, or -1 if no more DBs is available.
842  */
843 int
844 _asr_iter_db(struct asr_query *as)
845 {
846 	if (as->as_db_idx >= as->as_ctx->ac_dbcount) {
847 		DPRINT("asr_iter_db: done\n");
848 		return (-1);
849 	}
850 
851 	as->as_db_idx += 1;
852 	DPRINT("asr_iter_db: %i\n", as->as_db_idx);
853 
854 	return (0);
855 }
856