xref: /openbsd-src/lib/libc/asr/asr.c (revision 0b7734b3d77bb9b21afec6f4621cae6c805dbd45)
1 /*	$OpenBSD: asr.c,v 1.54 2016/06/18 15:25:28 reyk 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 /*
166  * Same as above, but run in a loop that handles the fd conditions result.
167  */
168 int
169 asr_run_sync(struct asr_query *as, struct asr_result *ar)
170 {
171 	struct pollfd	 fds[1];
172 	struct timespec	 pollstart, pollend, elapsed;
173 	int		 timeout, r, p, saved_errno = errno;
174 
175 	while ((r = asr_run(as, ar)) == ASYNC_COND) {
176 		fds[0].fd = ar->ar_fd;
177 		fds[0].events = (ar->ar_cond == ASR_WANT_READ) ? POLLIN:POLLOUT;
178 
179 		timeout = ar->ar_timeout;
180 	again:
181 		if (clock_gettime(CLOCK_MONOTONIC, &pollstart))
182 			break;
183 		p = poll(fds, 1, timeout);
184 		if (p == -1 && errno == EINTR) {
185 			if (clock_gettime(CLOCK_MONOTONIC, &pollend))
186 				break;
187 
188 			timespecsub(&pollend, &pollstart, &elapsed);
189 			timeout -= (elapsed.tv_sec * 1000) +
190 			    (elapsed.tv_nsec / 1000000);
191 			if (timeout < 1)
192 				break;
193 			goto again;
194 		}
195 
196 		/*
197 		 * Otherwise, just ignore the error and let asr_run()
198 		 * catch the failure.
199 		 */
200 	}
201 
202 	errno = saved_errno;
203 
204 	return (r);
205 }
206 DEF_WEAK(asr_run_sync);
207 
208 /*
209  * Create a new async request of the given "type" on the async context "ac".
210  * Take a reference on it so it does not gets deleted while the async query
211  * is running.
212  */
213 struct asr_query *
214 _asr_async_new(struct asr_ctx *ac, int type)
215 {
216 	struct asr_query	*as;
217 
218 	DPRINT("asr: asr_async_new(ctx=%p) type=%i refcount=%i\n", ac, type,
219 	    ac ? ac->ac_refcount : 0);
220 	if (ac == NULL || (as = calloc(1, sizeof(*as))) == NULL)
221 		return (NULL);
222 
223 	ac->ac_refcount += 1;
224 	as->as_ctx = ac;
225 	as->as_fd = -1;
226 	as->as_type = type;
227 	as->as_state = ASR_STATE_INIT;
228 
229 	return (as);
230 }
231 
232 /*
233  * Free an async query and unref the associated context.
234  */
235 void
236 _asr_async_free(struct asr_query *as)
237 {
238 	DPRINT("asr: asr_async_free(%p)\n", as);
239 	switch (as->as_type) {
240 	case ASR_SEND:
241 		if (as->as_fd != -1)
242 			close(as->as_fd);
243 		if (as->as.dns.obuf && !(as->as.dns.flags & ASYNC_EXTOBUF))
244 			free(as->as.dns.obuf);
245 		if (as->as.dns.ibuf)
246 			free(as->as.dns.ibuf);
247 		if (as->as.dns.dname)
248 			free(as->as.dns.dname);
249 		break;
250 
251 	case ASR_SEARCH:
252 		if (as->as.search.subq)
253 			_asr_async_free(as->as.search.subq);
254 		if (as->as.search.name)
255 			free(as->as.search.name);
256 		break;
257 
258 	case ASR_GETRRSETBYNAME:
259 		if (as->as.rrset.subq)
260 			_asr_async_free(as->as.rrset.subq);
261 		if (as->as.rrset.name)
262 			free(as->as.rrset.name);
263 		break;
264 
265 	case ASR_GETHOSTBYNAME:
266 	case ASR_GETHOSTBYADDR:
267 		if (as->as.hostnamadr.subq)
268 			_asr_async_free(as->as.hostnamadr.subq);
269 		if (as->as.hostnamadr.name)
270 			free(as->as.hostnamadr.name);
271 		break;
272 
273 	case ASR_GETNETBYNAME:
274 	case ASR_GETNETBYADDR:
275 		if (as->as.netnamadr.subq)
276 			_asr_async_free(as->as.netnamadr.subq);
277 		if (as->as.netnamadr.name)
278 			free(as->as.netnamadr.name);
279 		break;
280 
281 	case ASR_GETADDRINFO:
282 		if (as->as.ai.subq)
283 			_asr_async_free(as->as.ai.subq);
284 		if (as->as.ai.aifirst)
285 			freeaddrinfo(as->as.ai.aifirst);
286 		if (as->as.ai.hostname)
287 			free(as->as.ai.hostname);
288 		if (as->as.ai.servname)
289 			free(as->as.ai.servname);
290 		if (as->as.ai.fqdn)
291 			free(as->as.ai.fqdn);
292 		break;
293 
294 	case ASR_GETNAMEINFO:
295 		if (as->as.ni.subq)
296 			_asr_async_free(as->as.ni.subq);
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 explicitely 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 ((!strncmp(tok[i], "ndots:", 6))) {
607 				e = NULL;
608 				d = strtonum(tok[i] + 6, 1, 16, &e);
609 				if (e == NULL)
610 					ac->ac_ndots = d;
611 			}
612 		}
613 	}
614 }
615 
616 /*
617  * Setup an async context with the config specified in the string "str".
618  */
619 static int
620 asr_ctx_from_string(struct asr_ctx *ac, const char *str)
621 {
622 	char		 buf[512], *ch;
623 
624 	asr_ctx_parse(ac, str);
625 
626 	if (ac->ac_dbcount == 0) {
627 		/* No lookup directive */
628 		asr_ctx_parse(ac, DEFAULT_LOOKUP);
629 	}
630 
631 	if (ac->ac_nscount == 0)
632 		asr_ctx_parse(ac, "nameserver 127.0.0.1");
633 
634 	if (ac->ac_domain == NULL)
635 		if (gethostname(buf, sizeof buf) == 0) {
636 			ch = strchr(buf, '.');
637 			if (ch)
638 				ac->ac_domain = strdup(ch + 1);
639 			else /* Assume root. see resolv.conf(5) */
640 				ac->ac_domain = strdup("");
641 		}
642 
643 	/* If no search domain was specified, use the local subdomains */
644 	if (ac->ac_domcount == 0)
645 		for (ch = ac->ac_domain; ch; ) {
646 			asr_ctx_add_searchdomain(ac, ch);
647 			ch = strchr(ch, '.');
648 			if (ch && asr_ndots(++ch) == 0)
649 				break;
650 		}
651 
652 	return (0);
653 }
654 
655 /*
656  * Setup the "ac" async context from the file at location "path".
657  */
658 static int
659 asr_ctx_from_file(struct asr_ctx *ac, const char *path)
660 {
661 	FILE	*cf;
662 	char	 buf[4096];
663 	ssize_t	 r;
664 
665 	cf = fopen(path, "re");
666 	if (cf == NULL)
667 		return (-1);
668 
669 	r = fread(buf, 1, sizeof buf - 1, cf);
670 	if (feof(cf) == 0) {
671 		DPRINT("asr: config file too long: \"%s\"\n", path);
672 		r = -1;
673 	}
674 	fclose(cf);
675 	if (r == -1)
676 		return (-1);
677 	buf[r] = '\0';
678 
679 	return asr_ctx_from_string(ac, buf);
680 }
681 
682 /*
683  * Parse lines in the configuration string. For each one, split it into
684  * tokens and pass them to "pass0" for processing.
685  */
686 static int
687 asr_ctx_parse(struct asr_ctx *ac, const char *str)
688 {
689 	size_t		 len;
690 	const char	*line;
691 	char		 buf[1024];
692 	char		*tok[10];
693 	int		 ntok;
694 
695 	line = str;
696 	while (*line) {
697 		len = strcspn(line, "\n\0");
698 		if (len < sizeof buf) {
699 			memmove(buf, line, len);
700 			buf[len] = '\0';
701 		} else
702 			buf[0] = '\0';
703 		line += len;
704 		if (*line == '\n')
705 			line++;
706 		buf[strcspn(buf, ";#")] = '\0';
707 		if ((ntok = strsplit(buf, tok, 10)) == 0)
708 			continue;
709 
710 		pass0(tok, ntok, ac);
711 	}
712 
713 	return (0);
714 }
715 
716 /*
717  * Check for environment variables altering the configuration as described
718  * in resolv.conf(5).  Although not documented there, this feature is disabled
719  * for setuid/setgid programs.
720  */
721 static void
722 asr_ctx_envopts(struct asr_ctx *ac)
723 {
724 	char	buf[4096], *e;
725 	size_t	s;
726 
727 	if (issetugid()) {
728 		ac->ac_options |= RES_NOALIASES;
729 		return;
730 	}
731 
732 	if ((e = getenv("RES_OPTIONS")) != NULL) {
733 		strlcpy(buf, "options ", sizeof buf);
734 		strlcat(buf, e, sizeof buf);
735 		s = strlcat(buf, "\n", sizeof buf);
736 		if (s < sizeof buf)
737 			asr_ctx_parse(ac, buf);
738 	}
739 
740 	if ((e = getenv("LOCALDOMAIN")) != NULL) {
741 		strlcpy(buf, "search ", sizeof buf);
742 		strlcat(buf, e, sizeof buf);
743 		s = strlcat(buf, "\n", sizeof buf);
744 		if (s < sizeof buf)
745 			asr_ctx_parse(ac, buf);
746 	}
747 }
748 
749 /*
750  * Parse a resolv.conf(5) nameserver string into a sockaddr.
751  */
752 static int
753 asr_parse_nameserver(struct sockaddr *sa, const char *s)
754 {
755 	in_port_t	 portno = 53;
756 
757 	if (_asr_sockaddr_from_str(sa, PF_UNSPEC, s) == -1)
758 		return (-1);
759 
760 	if (sa->sa_family == PF_INET)
761 		((struct sockaddr_in *)sa)->sin_port = htons(portno);
762 	else if (sa->sa_family == PF_INET6)
763 		((struct sockaddr_in6 *)sa)->sin6_port = htons(portno);
764 
765 	return (0);
766 }
767 
768 /*
769  * Turn a (uncompressed) DNS domain name into a regular nul-terminated string
770  * where labels are separated by dots. The result is put into the "buf" buffer,
771  * truncated if it exceeds "max" chars. The function returns "buf".
772  */
773 char *
774 _asr_strdname(const char *_dname, char *buf, size_t max)
775 {
776 	const unsigned char *dname = _dname;
777 	char	*res;
778 	size_t	 left, n, count;
779 
780 	if (_dname[0] == 0) {
781 		strlcpy(buf, ".", max);
782 		return buf;
783 	}
784 
785 	res = buf;
786 	left = max - 1;
787 	for (n = 0; dname[0] && left; n += dname[0]) {
788 		count = (dname[0] < (left - 1)) ? dname[0] : (left - 1);
789 		memmove(buf, dname + 1, count);
790 		dname += dname[0] + 1;
791 		left -= count;
792 		buf += count;
793 		if (left) {
794 			left -= 1;
795 			*buf++ = '.';
796 		}
797 	}
798 	buf[0] = 0;
799 
800 	return (res);
801 }
802 
803 /*
804  * Read and split the next line from the given namedb file.
805  * Return -1 on error, or put the result in the "tokens" array of
806  * size "ntoken" and returns the number of token on the line.
807  */
808 int
809 _asr_parse_namedb_line(FILE *file, char **tokens, int ntoken, char *lbuf, size_t sz)
810 {
811 	size_t	  len;
812 	char	 *buf;
813 	int	  ntok;
814 
815     again:
816 	if ((buf = fgetln(file, &len)) == NULL)
817 		return (-1);
818 
819 	if (len >= sz)
820 		goto again;
821 
822 	if (buf[len - 1] == '\n')
823 		len--;
824 	else {
825 		memcpy(lbuf, buf, len);
826 		buf = lbuf;
827 	}
828 
829 	buf[len] = '\0';
830 	buf[strcspn(buf, "#")] = '\0';
831 	if ((ntok = strsplit(buf, tokens, ntoken)) == 0)
832 		goto again;
833 
834 	return (ntok);
835 }
836 
837 /*
838  * Update the async context so that it uses the next configured DB.
839  * Return 0 on success, or -1 if no more DBs is available.
840  */
841 int
842 _asr_iter_db(struct asr_query *as)
843 {
844 	if (as->as_db_idx >= as->as_ctx->ac_dbcount) {
845 		DPRINT("asr_iter_db: done\n");
846 		return (-1);
847 	}
848 
849 	as->as_db_idx += 1;
850 	DPRINT("asr_iter_db: %i\n", as->as_db_idx);
851 
852 	return (0);
853 }
854