aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/lib/libc/asr/asr.c
blob: be7904e52dbca6d18c98d938c0c55282545612cd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
/*	$OpenBSD: asr.c,v 1.3 2012/04/15 22:25:14 eric Exp $	*/
/*
 * Copyright (c) 2010-2012 Eric Faurot <eric@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "includes.h"

#include <sys/types.h>
#include <sys/stat.h>

#include <netinet/in.h>
#include <arpa/inet.h>
#include <arpa/nameser.h>

#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <resolv.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include "asr.h"
#include "asr_private.h"
#define __THREAD_NAME(x) __ ## x
#define _THREAD_PRIVATE(a, b, c) (c)

#define DEFAULT_CONFFILE	"/etc/resolv.conf"
#define DEFAULT_HOSTFILE	"/etc/hosts"
#define DEFAULT_CONF		"lookup bind file\nnameserver 127.0.0.1\n"
#define DEFAULT_LOOKUP		"lookup bind file"

#define RELOAD_DELAY		15 /* seconds */

static void asr_check_reload(struct asr *);
static struct asr_ctx *asr_ctx_create(void);
static void asr_ctx_ref(struct asr_ctx *);
static void asr_ctx_free(struct asr_ctx *);
static int asr_ctx_add_searchdomain(struct asr_ctx *, const char *);
static int asr_ctx_from_file(struct asr_ctx *, const char *);
static int asr_ctx_from_string(struct asr_ctx *, const char *);
static int asr_ctx_parse(const char*, int(*)(char**, int, struct asr_ctx*),
    struct asr_ctx *);
static int asr_parse_nameserver(struct sockaddr *, const char *);
static char *asr_hostalias(const char *, char *, size_t);
static int asr_ndots(const char *);
static void asr_ctx_envopts(struct asr_ctx *);
static int pass0(char **, int, struct asr_ctx *);

static void *__THREAD_NAME(_asr);
static struct asr *_asr = NULL;

#define issetugid() ((getuid() != geteuid()))

/* Allocate and configure an async "resolver". */
struct asr *
async_resolver(const char *conf)
{
	static int	 init = 0;
	struct asr	*asr;

#ifdef DEBUG
	if (init == 0) {
		if (getenv("ASR_DEBUG"))
			asr_debug = 1;
		init = 1;
	}
#endif
	if ((asr = calloc(1, sizeof(*asr))) == NULL)
		goto fail;

	/* If not setuid/setgid, allow to use an alternate config. */
	if (conf == NULL && !issetugid())
		conf = getenv("ASR_CONFIG");

	if (conf == NULL)
		conf = DEFAULT_CONFFILE;

	if (conf[0] == '!') {
		/* Use the rest of the string as config file */
		if ((asr->a_ctx = asr_ctx_create()) == NULL)
			goto fail;
		if (asr_ctx_from_string(asr->a_ctx, conf + 1) == -1)
			goto fail;
	} else {
		/* Use the given config file */
		asr->a_path = strdup(conf);
		asr_check_reload(asr);
		if (asr->a_ctx == NULL) {
			if ((asr->a_ctx = asr_ctx_create()) == NULL)
				goto fail;
			if (asr_ctx_from_string(asr->a_ctx, DEFAULT_CONF) == -1)
				goto fail;
			asr_ctx_envopts(asr->a_ctx);
		}
	}

#ifdef DEBUG
	asr_dump(asr);
#endif
	return (asr);

    fail:
	if (asr) {
		if (asr->a_ctx)
			asr_ctx_free(asr->a_ctx);
		free(asr);
	}

	return (NULL);
}

/*
 * Free the "asr" async resolver (or the thread-local resolver if NULL).
 * Drop the reference to the current context.
 */
void
async_resolver_done(struct asr *asr)
{
	struct asr **priv;

	if (asr == NULL) {
		priv = _THREAD_PRIVATE(_asr, asr, &_asr);
		if (*priv == NULL)
			return;
		asr = *priv;
		*priv = NULL;
	}

	asr_ctx_unref(asr->a_ctx);
	if (asr->a_path)
		free(asr->a_path);
	free(asr);
}

/*
 * Cancel an async query.
 */
void
async_abort(struct async *as)
{
	async_free(as);
}

/*
 * Resume the "as" async query resolution.  Return one of ASYNC_COND,
 * ASYNC_YIELD or ASYNC_DONE and put query-specific return values in
 * the user-allocated memory at "ar".
 */
int
async_run(struct async *as, struct async_res *ar)
{
	int	r;

#ifdef DEBUG
	asr_printf("asr: async_run(%p, %p) %s ctx=[%p]\n",
		as, ar, asr_querystr(as->as_type), as->as_ctx);
#endif
	r = as->as_run(as, ar);

#ifdef DEBUG
	if (asr_debug) {
		asr_printf("asr: async_run(%p, %p) -> %s", as, ar,
		    asr_transitionstr(r));
		if (r == ASYNC_COND)
			asr_printf(" fd=%i timeout=%i\n",
			    ar->ar_fd, ar->ar_timeout);
		else
			asr_printf("\n");
		fflush(stderr);
	}
#endif
	if (r == ASYNC_DONE)
		async_free(as);

	return (r);
}

/*
 * Same as above, but run in a loop that handles the fd conditions result.
 */
int
async_run_sync(struct async *as, struct async_res *ar)
{
	struct pollfd		 fds[1];
	int			 r;

	while((r = async_run(as, ar)) == ASYNC_COND) {
		fds[0].fd = ar->ar_fd;
		fds[0].events = (ar->ar_cond == ASYNC_READ) ? POLLIN : POLLOUT;
	again:
		r = poll(fds, 1, ar->ar_timeout);
		if (r == -1 && errno == EINTR)
			goto again;
		if (r == -1) /* XXX Is it possible? and what to do if so? */
			err(1, "poll");
	}

	return (r);
}

/*
 * Create a new async request of the given "type" on the async context "ac".
 * Take a reference on it so it does not gets deleted while the async query
 * is running.
 */
struct async *
async_new(struct asr_ctx *ac, int type)
{
	struct async	*as;
#ifdef DEBUG
	asr_printf("asr: async_new(ctx=%p) type=%i refcount=%i\n",
	    ac, type, ac->ac_refcount);
#endif
	if ((as = calloc(1, sizeof(*as))) == NULL)
		return (NULL);

	ac->ac_refcount += 1;
	as->as_ctx = ac;
	as->as_fd = -1;
	as->as_type = type;
	as->as_state = ASR_STATE_INIT;

	return (as);
}

/*
 * Free an async query and unref the associated context.
 */
void
async_free(struct async *as)
{
#ifdef DEBUG
	asr_printf("asr: async_free(%p)\n", as);
#endif
	switch(as->as_type) {
	case ASR_SEND:
		if (as->as_fd != -1)
			close(as->as_fd);
		if (as->as.dns.obuf && !(as->as.dns.flags & ASYNC_EXTOBUF))
			free (as->as.dns.obuf);
		if (as->as.dns.ibuf && !(as->as.dns.flags & ASYNC_EXTIBUF))
			free (as->as.dns.ibuf);
		if (as->as.dns.dname)
			free(as->as.dns.dname);
		break;

	case ASR_SEARCH:
		if (as->as.search.subq)
			async_free(as->as.search.subq);
		if (as->as.search.name)
			free(as->as.search.name);
		break;

	case ASR_GETRRSETBYNAME:
		if (as->as.rrset.subq)
			async_free(as->as.rrset.subq);
		if (as->as.rrset.name)
			free(as->as.rrset.name);
		break;

	case ASR_GETHOSTBYNAME:
	case ASR_GETHOSTBYADDR:
		if (as->as.hostnamadr.subq)
			async_free(as->as.hostnamadr.subq);
		if (as->as.hostnamadr.name)
			free(as->as.hostnamadr.name);
		if (as->as.hostnamadr.dname)
			free(as->as.hostnamadr.dname);
		break;

	case ASR_GETNETBYNAME:
	case ASR_GETNETBYADDR:
		if (as->as.netnamadr.subq)
			async_free(as->as.netnamadr.subq);
		if (as->as.netnamadr.name)
			free(as->as.netnamadr.name);
		break;

	case ASR_GETADDRINFO:
		if (as->as.ai.subq)
			async_free(as->as.ai.subq);
		if (as->as.ai.aifirst)
			freeaddrinfo(as->as.ai.aifirst);
		if (as->as.ai.hostname)
			free(as->as.ai.hostname);
		if (as->as.ai.servname)
			free(as->as.ai.servname);
		break;

	case ASR_GETNAMEINFO:
		if (as->as.ni.subq)
			async_free(as->as.ni.subq);
		break;

	case ASR_HOSTADDR:
		if (as->as.host.name)
			free(as->as.host.name);
		if (as->as.host.subq)
			async_free(as->as.host.subq);
		if (as->as.host.pkt)
			free(as->as.host.pkt);
		if (as->as.host.file)
			fclose(as->as.host.file);
		break;
	}

	asr_ctx_unref(as->as_ctx);
	free(as);
}

/*
 * Get a context from the given resolver. This takes a new reference to
 * the returned context, which *must* be explicitely dropped when done
 * using this context.
 */
struct asr_ctx *
asr_use_resolver(struct asr *asr)
{
	struct asr **priv;

	if (asr == NULL) {
		/* Use the thread-local resolver. */
#ifdef DEBUG
		asr_printf("using thread-local resolver\n");
#endif
		priv = _THREAD_PRIVATE(_asr, asr, &_asr);
		if (*priv == NULL) {
#ifdef DEBUG
			asr_printf("setting up thread-local resolver\n");
#endif
			*priv = async_resolver(NULL);
		}
		asr = *priv;
	}

	asr_check_reload(asr);
	asr_ctx_ref(asr->a_ctx);
	return (asr->a_ctx);
}

static void
asr_ctx_ref(struct asr_ctx *ac)
{
#ifdef DEBUG
	asr_printf("asr: asr_ctx_ref(ctx=%p) refcount=%i\n",
	    ac, ac->ac_refcount);
#endif
	ac->ac_refcount += 1;
}

/*
 * Drop a reference to an async context, freeing it if the reference
 * count drops to 0.
 */
void
asr_ctx_unref(struct asr_ctx *ac)
{
#ifdef DEBUG
	asr_printf("asr: asr_ctx_unref(ctx=%p) refcount=%i\n",
	    ac, ac->ac_refcount);
#endif
	if (--ac->ac_refcount)
		return;
	
	asr_ctx_free(ac);
}

static void
asr_ctx_free(struct asr_ctx *ac)
{
	int i;

	if (ac->ac_domain)
		free(ac->ac_domain);
	for(i = 0; i < ac->ac_nscount; i++)
		free(ac->ac_ns[i]);
	for(i = 0; i < ac->ac_domcount; i++)
		free(ac->ac_dom[i]);

	free(ac);
}

/*
 * Reload the configuration file if it has changed on disk.
 */
static void
asr_check_reload(struct asr *asr)
{
        struct stat	 st;
	struct asr_ctx	*ac;
	struct timespec	 tp;

	if (asr->a_path == NULL)
		return;

#ifdef HAVE_CLOCK_GETTIME
	if (clock_gettime(CLOCK_MONOTONIC, &tp) == -1)
		return;
#else
	struct timeval tv;

	if (gettimeofday(&tv, NULL) == 0)
		return;
	tp.tv_sec = tv.tv_sec;
#endif

	if ((tp.tv_sec - asr->a_rtime) < RELOAD_DELAY)
		return;
	asr->a_rtime = tp.tv_sec;

#ifdef DEBUG
	asr_printf("asr: checking for update of \"%s\"\n", asr->a_path);
#endif

	if (stat(asr->a_path, &st) == -1 ||
	    asr->a_mtime == st.st_mtime ||
	    (ac = asr_ctx_create()) == NULL)
		return;
	asr->a_mtime = st.st_mtime;

#ifdef DEBUG
	asr_printf("asr: reloading config file\n");
#endif

	if (asr_ctx_from_file(ac, asr->a_path) == -1) {
		asr_ctx_free(ac);
		return;
	}

	asr_ctx_envopts(ac);
	if (asr->a_ctx)
		asr_ctx_unref(asr->a_ctx);
	asr->a_ctx = ac;
}

/* 
 * Construct a fully-qualified domain name for the given name and domain.
 * If "name" ends with a '.' it is considered as a FQDN by itself.
 * Otherwise, the domain, which must be a FQDN, is appended to "name" (it
 * may have a leading dot which would be ignored). If the domain is null,
 * then "." is used. Return the length of the constructed FQDN or (0) on
 * error.
 */
size_t
asr_make_fqdn(const char *name, const char *domain, char *buf, size_t buflen)
{
	size_t	len;

	if (domain == NULL)
		domain = ".";
	else if ((len = strlen(domain)) == 0)
		return (0);
	else if (domain[len -1] != '.')
		return (0);

	len = strlen(name);
	if (len == 0) {
		strlcpy(buf, domain, buflen);
	} else if (name[len - 1] !=  '.') {
		if (domain[0] == '.')
			domain += 1;
		strlcpy(buf, name, buflen);
		strlcat(buf, ".", buflen);
		strlcat(buf, domain, buflen);
	} else {
		strlcpy(buf, name, buflen);
	}

	return (strlen(buf));
}

/*
 * Concatenate a name and a domain name. The result has no trailing dot.
 */
size_t
asr_domcat(const char *name, const char *domain, char *buf, size_t buflen)
{
	size_t	r;

	r = asr_make_fqdn(name, domain, buf, buflen);
	if (r == 0)
		return (0);
	buf[r - 1] = '\0';

	return (r - 1);
}

/*
 * Count the dots in a string.
 */
static int
asr_ndots(const char *s)
{
	int n;

	for(n = 0; *s; s++)
		if (*s == '.')
			n += 1;

	return (n);
}

/* 
 * Allocate a new empty context.
 */
static struct asr_ctx *
asr_ctx_create(void)
{
	struct asr_ctx	*ac;

	if ((ac = calloc(1, sizeof(*ac))) == NULL)
		return (NULL);

	ac->ac_options = RES_RECURSE | RES_DEFNAMES | RES_DNSRCH;
	ac->ac_refcount = 1;
	ac->ac_ndots = 1;
	ac->ac_family[0] = AF_INET;
	ac->ac_family[1] = AF_INET6;
	ac->ac_family[2] = -1;

	ac->ac_hostfile = DEFAULT_HOSTFILE;

	ac->ac_nscount = 0;
	ac->ac_nstimeout = 1000;
	ac->ac_nsretries = 3;

	return (ac);
}

/*
 * Add a search domain to the async context.
 */
static int
asr_ctx_add_searchdomain(struct asr_ctx *ac, const char *domain)
{
	char buf[MAXDNAME];

	if (ac->ac_domcount == ASR_MAXDOM)
		return (-1);

	if (asr_make_fqdn(domain, NULL, buf, sizeof(buf)) == 0)
		return (-1);

	if ((ac->ac_dom[ac->ac_domcount] = strdup(buf)) == NULL)
		return (0);

	ac->ac_domcount += 1;

	return (1);
}

/*
 * Pass on a split config line.
 */
static int
pass0(char **tok, int n, struct asr_ctx *ac)
{
	int		 i, j, d;
	const char	*e;
	struct sockaddr_storage	ss;

	if (!strcmp(tok[0], "nameserver")) {
		if (ac->ac_nscount == ASR_MAXNS)
			return (0);
		if (n != 2)
			return (0);
		if (asr_parse_nameserver((struct sockaddr*)&ss, tok[1]))
			return (0);
		if ((ac->ac_ns[ac->ac_nscount] = calloc(1, SS_LEN(&ss))) == NULL)
			return (0);
		memmove(ac->ac_ns[ac->ac_nscount], &ss, SS_LEN(&ss));
		ac->ac_nscount += 1;

	} else if (!strcmp(tok[0], "domain")) {
		if (n != 2)
			return (0);
		if (ac->ac_domain)
			return (0);
		ac->ac_domain = strdup(tok[1]);

	} else if (!strcmp(tok[0], "lookup")) {
		/* ignore the line if we already set lookup */
		if (ac->ac_dbcount != 0)
			return (0);
		if (n - 1 > ASR_MAXDB)
			return (0);
		/* ensure that each lookup is only given once */
		for(i = 1; i < n; i++)
			for(j = i + 1; j < n; j++)
				if (!strcmp(tok[i], tok[j]))
					return (0);
		for(i = 1; i < n; i++, ac->ac_dbcount++) {
			if (!strcmp(tok[i], "yp")) {
				ac->ac_db[i-1] = ASR_DB_YP;
			} else if (!strcmp(tok[i], "bind")) {
				ac->ac_db[i-1] = ASR_DB_DNS;
			} else if (!strcmp(tok[i], "file")) {
				ac->ac_db[i-1] = ASR_DB_FILE;
			} else {
				/* ignore the line */
				ac->ac_dbcount = 0;
				return (0);
			}
		}
	} else if (!strcmp(tok[0], "search")) {
		/* resolv.conf says the last line wins */
		for(i = 0; i < ac->ac_domcount; i++)
			free(ac->ac_dom[i]);
		ac->ac_domcount = 0;
		for(i = 1; i < n; i++)
			asr_ctx_add_searchdomain(ac, tok[i]);

	} else if (!strcmp(tok[0], "family")) {
		if (n == 1 || n > 3)
			return (0);
		for (i = 1; i < n; i++)
			if (strcmp(tok[i], "inet4") && strcmp(tok[i], "inet6"))
				return (0);
		for (i = 1; i < n; i++)
			ac->ac_family[i - 1] = strcmp(tok[i], "inet4") ? \
			    AF_INET6 : AF_INET;
		ac->ac_family[i - 1] = -1;

	} else if (!strcmp(tok[0], "options")) {
		for(i = 1; i < n; i++) {
			if (!strcmp(tok[i], "tcp"))
				ac->ac_options |= RES_USEVC;
			else if ((!strncmp(tok[i], "ndots:", 6))) {
				e = NULL;
				d = strtonum(tok[i] + 6, 1, 16, &e);
				if (e == NULL)
					ac->ac_ndots = d;
			}
		}
	}

	return (0);
}

/*
 * Setup an async context with the config specified in the string "str".
 */
static int
asr_ctx_from_string(struct asr_ctx *ac, const char *str)
{
	char		 buf[512], *ch;

	asr_ctx_parse(str, pass0, ac);

	if (ac->ac_dbcount == 0) {
		/* No lookup directive */
		asr_ctx_parse(DEFAULT_LOOKUP, pass0, ac);
	}

	if (ac->ac_nscount == 0)
		asr_ctx_parse("nameserver 127.0.0.1", pass0, ac);

	if (ac->ac_domain == NULL)
		if (gethostname(buf, sizeof buf) == 0) {
			ch = strchr(buf, '.');
			if (ch)
				ac->ac_domain = strdup(ch + 1);
			else /* Assume root. see resolv.conf(5) */
				ac->ac_domain = strdup("");
		}

	/* If no search domain was specified, use the local subdomains */
	if (ac->ac_domcount == 0)
		for(ch = ac->ac_domain; ch; ) {
			asr_ctx_add_searchdomain(ac, ch);
			ch = strchr(ch, '.');
			if (ch && asr_ndots(++ch) == 0)
				break;
		}

	return (0);
}

/*
 * Setup the "ac" async context from the file at location "path".
 */
static int
asr_ctx_from_file(struct asr_ctx *ac, const char *path)
{
	FILE	*cf;
	char	 buf[4096];
	ssize_t	 r;

	cf = fopen(path, "r");
	if (cf == NULL)
		return (-1);

	r = fread(buf, 1, sizeof buf - 1, cf);
	if (feof(cf) == 0) {
#ifdef DEBUG
		asr_printf("asr: config file too long: \"%s\"\n", path);
#endif
		r = -1;
	}
	fclose(cf);
	if (r == -1)
		return (-1);
	buf[r] = '\0';
 
	return asr_ctx_from_string(ac, buf);
}

/*
 * Parse a configuration string.  Lines are read one by one, comments are
 * stripped and the remaining line is split into tokens which are passed
 * to the "cb" callback function.  Parsing stops if the callback returns
 * non-zero.
 */
static int
asr_ctx_parse(const char *str, int (*cb)(char**, int, struct asr_ctx*),
    struct asr_ctx *ac)
{
	size_t		 len;
	const char	*line;
	char		 buf[1024];
	char		*tok[10], **tp, *cp;
	int		 ntok;

	line = str;
	while (*line) {
		len = strcspn(line, "\n\0");
		if (len < sizeof buf) {
			memmove(buf, line, len);
			buf[len] = '\0';
		} else
			buf[0] = '\0';
		line += len;
		if (*line == '\n')
			line++;
		buf[strcspn(buf, ";#")] = '\0';
		for(cp = buf, tp = tok, ntok = 0;
		    tp < &tok[10] && (*tp = strsep(&cp, " \t")) != NULL; )
			if (**tp != '\0') {
				tp++;
				ntok++;
			}
		*tp = NULL;

		if (tok[0] == NULL)
			continue;

		if (cb(tok, ntok, ac))
			break;
	}

	return (0);
}

/*
 * Check for environment variables altering the configuration as described
 * in resolv.conf(5).  Altough not documented there, this feature is disabled
 * for setuid/setgid programs.
 */
static void
asr_ctx_envopts(struct asr_ctx *ac)
{
	char	buf[4096], *e;
	size_t	s;

	if (issetugid()) {
		ac->ac_options |= RES_NOALIASES;
		return;
	}

	if ((e = getenv("RES_OPTIONS")) != NULL) {
		strlcpy(buf, "options ", sizeof buf);
		strlcat(buf, e, sizeof buf);
		s = strlcat(buf, "\n", sizeof buf);
		s = strlcat(buf, "\n", sizeof buf);
		if (s < sizeof buf)
			asr_ctx_parse(buf, pass0, ac);
	}

	if ((e = getenv("LOCALDOMAIN")) != NULL) {
		strlcpy(buf, "search ", sizeof buf);
		strlcat(buf, e, sizeof buf);
		s = strlcat(buf, "\n", sizeof buf);
		if (s < sizeof buf)
			asr_ctx_parse(buf, pass0, ac);
	}
}

/*
 * Parse a resolv.conf(5) nameserver string into a sockaddr.
 */ 
static int
asr_parse_nameserver(struct sockaddr *sa, const char *s)
{
	const char	*estr;
	char		 buf[256];
	char		*port = NULL;
	in_port_t	 portno = 53;

	if (*s == '[') {
		strlcpy(buf, s + 1, sizeof buf);
		s = buf;
		port = strchr(buf, ']');
		if (port == NULL)
			return (-1);
		*port++ = '\0';
		if (*port != ':')
			return (-1);
		port++;
	}
	
	if (port) {
		portno = strtonum(port, 1, USHRT_MAX, &estr);
		if (estr)
			return (-1);
	}

	if (sockaddr_from_str(sa, PF_UNSPEC, s) == -1)
		return (-1);

	if (sa->sa_family == PF_INET)
		((struct sockaddr_in *)sa)->sin_port = htons(portno);
	else if (sa->sa_family == PF_INET6)
		((struct sockaddr_in6 *)sa)->sin6_port = htons(portno);

	return (0);
}

/*
 * Turn a (uncompressed) DNS domain name into a regular nul-terminated string
 * where labels are separated by dots. The result is put into the "buf" buffer,
 * truncated if it exceeds "max" chars. The function returns "buf".
 */
char*
asr_strdname(const char *_dname, char *buf, size_t max)
{
	const unsigned char *dname = _dname;
	char	*res;
	size_t	 left, n, count;

	if (_dname[0] == 0) {
		strlcpy(buf, ".", max);
		return buf;
	}

	res = buf;
	left = max - 1;
	for (n = 0; dname[0] && left; n += dname[0]) {
		count = (dname[0] < (left - 1)) ? dname[0] : (left - 1);
		memmove(buf, dname + 1, count);
		dname += dname[0] + 1;
		left -= count;
		buf += count;
		if (left) {
			left -= 1;
			*buf++ = '.';
		}
	}
	buf[0] = 0;

	return (res);
}

/*
 * Read and split the next line from the given namedb file.
 * Return -1 on error, or put the result in the "tokens" array of
 * size "ntoken" and returns the number of token on the line.
 */
int
asr_parse_namedb_line(FILE *file, char **tokens, int ntoken)
{
	size_t	  len;
	char	 *buf, *cp, **tp;
	int	  ntok;

  again:
	if ((buf = fgetln(file, &len)) == NULL)
		return (-1);

	if (buf[len - 1] == '\n')
		len--;

	buf[len] = '\0';
	buf[strcspn(buf, "#")] = '\0';
	for(cp = buf, tp = tokens, ntok = 0;
	    ntok < ntoken && (*tp = strsep(&cp, " \t")) != NULL;)
		if (**tp != '\0') {
			tp++;
			ntok++;
		}
	*tp = NULL;
	if (tokens[0] == NULL)
		goto again;

	return (ntok);
}

/*
 * Update the async context so that it uses the next configured DB.
 * Return 0 on success, or -1 if no more DBs is available.
 */
int
asr_iter_db(struct async *as)
{
	if (as->as_db_idx >= as->as_ctx->ac_dbcount) {
#ifdef DEBUG
		asr_printf("asr_iter_db: done\n");
#endif
		return (-1);
	}

	as->as_db_idx += 1;
	as->as_ns_idx = 0;
#ifdef DEBUG
	asr_printf("asr_iter_db: %i\n", as->as_db_idx);
#endif
	return (0);
}

/*
 * Set the async context nameserver index to the next nameserver of the
 * currently used DB (assuming it is DNS), cycling over the list until the
 * maximum retry counter is reached.  Return 0 on success, or -1 if all
 * nameservers were used.
 */
int
asr_iter_ns(struct async *as)
{
	for (;;) {
		if (as->as_ns_cycles >= as->as_ctx->ac_nsretries)
			return (-1);

		as->as_ns_idx += 1;
		if (as->as_ns_idx <= as->as_ctx->ac_nscount)
			break;
		as->as_ns_idx = 0;
		as->as_ns_cycles++;
#ifdef DEBUG
		asr_printf("asr: asr_iter_ns(): cycle %i\n", as->as_ns_cycles);
#endif
	}

	return (0);
}

enum {
	DOM_INIT,
	DOM_DOMAIN,
	DOM_DONE
};

/*
 * Implement the search domain strategy.
 *
 * This function works as a generator that constructs complete domains in
 * buffer "buf" of size "len" for the given host name "name", according to the
 * search rules defined by the resolving context.  It is supposed to be called
 * multiple times (with the same name) to generate the next possible domain
 * name, if any.
 *
 * It returns 0 if it could generate a new domain name, or -1 when all
 * possibilites have been exhausted.
 */
int
asr_iter_domain(struct async *as, const char *name, char * buf, size_t len)
{
	char	*alias;

	switch(as->as_dom_step) {

	case DOM_INIT:
		/* First call */

		/*
		 * If "name" is an FQDN, that's the only result and we
		 * don't try anything else.
		 */
		if (strlen(name) && name[strlen(name) - 1] ==  '.') {
#ifdef DEBUG
			asr_printf("asr: asr_iter_domain(\"%s\") fqdn\n", name);
#endif
			as->as_dom_flags |= ASYNC_DOM_FQDN;
			as->as_dom_step = DOM_DONE;
			return (asr_domcat(name, NULL, buf, len));
		}

		/*
		 * If "name" has no dots, it might be an alias. If so,
		 * That's also the only result.
		 */
		if ((as->as_ctx->ac_options & RES_NOALIASES) == 0 &&
		    asr_ndots(name) == 0 &&
		    (alias = asr_hostalias(name, buf, len)) != NULL) {
#ifdef DEBUG
			asr_printf("asr: asr_iter_domain(\"%s\") is alias "
			    "\"%s\"\n", name, alias);
#endif
			as->as_dom_flags |= ASYNC_DOM_HOSTALIAS;
			as->as_dom_step = DOM_DONE;
			return (asr_domcat(alias, NULL, buf, len));
		}

		/*
		 * Otherwise, we iterate through the specified search domains.
		 */
		as->as_dom_step = DOM_DOMAIN;
		as->as_dom_idx = 0;

		/*
		 * If "name" as enough dots, use it as-is first, as indicated
		 * in resolv.conf(5).
		 */
		if ((asr_ndots(name)) >= as->as_ctx->ac_ndots) {
#ifdef DEBUG
			asr_printf("asr: asr_iter_domain(\"%s\") ndots\n",
			    name);
#endif
			as->as_dom_flags |= ASYNC_DOM_NDOTS;
			strlcpy(buf, name, len);
			return (0);
		}
		/* Otherwise, starts using the search domains */
		/* FALLTHROUGH */

	case DOM_DOMAIN:
		if (as->as_dom_idx < as->as_ctx->ac_domcount) {
#ifdef DEBUG
			asr_printf("asr: asr_iter_domain(\"%s\") "
			    "domain \"%s\"\n", name,
			    as->as_ctx->ac_dom[as->as_dom_idx]);
#endif
			as->as_dom_flags |= ASYNC_DOM_DOMAIN;
			return (asr_domcat(name,
			    as->as_ctx->ac_dom[as->as_dom_idx++], buf, len));
		}

		/* No more domain to try. */

		as->as_dom_step = DOM_DONE;

		/*
		 * If the name was not tried as an absolute name before,
		 * do it now.
		 */
		if (!(as->as_dom_flags & ASYNC_DOM_NDOTS)) {
#ifdef DEBUG
			asr_printf("asr: asr_iter_domain(\"%s\") as is\n",
			    name);
#endif
			as->as_dom_flags |= ASYNC_DOM_ASIS;
			strlcpy(buf, name, len);
			return (0);
		}
		/* Otherwise, we are done. */

	case DOM_DONE:
	default:
#ifdef DEBUG
		asr_printf("asr: asr_iter_domain(\"%s\") done\n", name);
#endif
		return (-1);
	}	
}

/*
 * Check if the hostname "name" is a user-defined alias as per hostname(7).
 * If so, copies the result in the buffer "abuf" of size "abufsz" and
 * return "abuf". Otherwise return NULL.
 */
static char *
asr_hostalias(const char *name, char *abuf, size_t abufsz)
{
	FILE	 *fp;
	size_t	  len;
	char	 *file, *buf, *cp, **tp, *tokens[2];
	int	  ntok;

	file = getenv("HOSTALIASES");
	if (file == NULL || issetugid() != 0 || (fp = fopen(file, "r")) == NULL)
		return (NULL);

#ifdef DEBUG
	asr_printf("asr: looking up aliases in \"%s\"\n", file);
#endif

	while ((buf = fgetln(fp, &len)) != NULL) {
		if (buf[len - 1] == '\n')
			len--;
		buf[len] = '\0';
		for(cp = buf, tp = tokens, ntok = 0;
		    ntok < 2 && (*tp = strsep(&cp, " \t")) != NULL; )
			if (**tp != '\0') {
				tp++;
				ntok++;
			}
		if (ntok != 2)
			continue;
		if (!strcasecmp(tokens[0], name)) {
			if (strlcpy(abuf, tokens[1], abufsz) > abufsz)
				continue;
#ifdef DEBUG
			asr_printf("asr: found alias \"%s\"\n", abuf);
#endif
			fclose(fp);
			return (abuf);
		}
	}

	fclose(fp);
	return (NULL);
}