aboutsummaryrefslogtreecommitdiff
path: root/lib/dns.c
blob: cc8593a0a8f6d27c155aba60a11bd9ce38ae3fbe (plain)
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
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
/* This file is part of Mailfromd.
   Copyright (C) 2005-2024 Sergey Poznyakoff

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <sys/types.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <adns.h>
#include <mailutils/alloc.h>
#include <mailutils/argcv.h>
#include <mailutils/io.h>
#include <mailutils/stream.h>
#include <mailutils/cstr.h>
#include <mailutils/wordsplit.h>
#include <mailutils/assoc.h>

#include <mflib/exceptions.h>
#include "libmf.h"
#include "dns.h"

#define DEFAULT_QFLAGS \
	(adns_qf_quoteok_cname|adns_qf_cname_loose|adns_qf_quoteok_query)

static mu_debug_handle_t debug_handle;
static adns_state state;

static void
dns_log_cb(adns_state ads, void *logfndata, const char *fmt, va_list al)
{
/* FIXME: Could have used just:
     mu_diag_vprintf(MU_DIAG_DEBUG, fmt, al);
   but it will emit \e<N> directives in the middle of the string, which
   upsets the mailutils' logstream implementation.

   A possible workaround would be to use logfndata to select between
   mu_diag_vprintf,mu_diag_cont_vprintf or appropriate mu_debug_log_
   call.

   For the time being, a simplified approach is used: */
	mu_stream_vprintf(mu_strerr, fmt, al);
}

static void
dnsbase_finish(void)
{
	if (state) {
		adns_finish(state);
		state = NULL;
	}
}

void
dnsbase_real_init(char *configtext)
{
	int rc;
	int flags;
	mu_debug_level_t lev;
	static int cleanup_installed;

	/* Dispose of a previosly allocated state, if any */
	dnsbase_finish();

	flags = adns_if_nosigpipe;
	if (mu_debug_get_category_level(debug_handle, &lev) == 0
	    && (lev & MU_DEBUG_LEVEL_MASK(MU_DEBUG_TRACE9)))
		flags |= adns_if_debug;
	rc = adns_init_logfn(&state, flags, configtext, dns_log_cb, NULL);
	if (rc) {
		mu_diag_funcall(MU_DIAG_ERROR, "adns_init", NULL, rc);
		exit(1);
	}
	if (!cleanup_installed) {
		atexit(dnsbase_finish);
		cleanup_installed = 1;
	}
}

void
dnsbase_file_init(char const *filename)
{
	if (!filename)
		dnsbase_real_init(NULL);
	else {
		mu_stream_t str;
		mu_off_t sz;
		int rc;
		char *cfg;

		rc = mu_file_stream_create(&str, filename, MU_STREAM_READ);
		if (rc) {
			mu_diag_funcall(MU_DIAG_ERROR, "mu_file_stream_create",
					filename, rc);
			return;
		}
		rc = mu_stream_size(str, &sz);
		if (rc) {
			mu_diag_funcall(MU_DIAG_ERROR, "mu_stream_size",
					filename, rc);
			mu_stream_destroy(&str);
			return;
		}

		if (sz > ((size_t)~0)) {
			mu_error(_("%s too big"), filename);
			mu_stream_destroy(&str);
			return;
		}

		cfg = mu_alloc(sz + 1);

		rc = mu_stream_read(str, cfg, sz, NULL);
		mu_stream_destroy(&str);
		if (rc) {
			mu_diag_funcall(MU_DIAG_ERROR, "mu_stream_read",
					filename, rc);
			return;
		}
		cfg[sz] = 0;
		dnsbase_real_init(cfg);
		free(cfg);
	}
}

static adns_state
get_state(void)
{
	if (!state)
		dnsbase_real_init(NULL);
	return state;
}

size_t
dns_reply_elsize(struct dns_reply *reply)
{
	switch (reply->type) {
	case dns_reply_ip:
		return sizeof(reply->data.ip[0]);
	case dns_reply_ip6:
		return sizeof(reply->data.ip6[0]);
	case dns_reply_str:
		return sizeof(reply->data.str[0]);
	}
	abort();
}

void
dns_reply_init(struct dns_reply *reply, dns_reply_type type, size_t count)
{
	reply->type = type;
	reply->count = count;
	reply->maxcount = count;
	if (count)
		reply->data.ptr = mu_calloc(count, dns_reply_elsize(reply));
	else
		reply->data.ptr = NULL;
}

void
dns_reply_ip_push(struct dns_reply *reply, void *item)
{
	if (reply->count == reply->maxcount)
		reply->data.ip = mu_2nrealloc(reply->data.ip,
					      &reply->maxcount,
					      sizeof(reply->data.ip[0]));
	reply->data.ip[reply->count++] = *(struct in_addr*)item;
}

void
dns_reply_ip6_push(struct dns_reply *reply, void *item)
{
	if (reply->count == reply->maxcount)
		reply->data.ip6 = mu_2nrealloc(reply->data.ip6,
					       &reply->maxcount,
					       sizeof(reply->data.ip6[0]));
	reply->data.ip6[reply->count++] = *(struct in6_addr *)item;
}

void
dns_reply_str_push(struct dns_reply *reply, void *item)
{
	if (reply->count == reply->maxcount)
		reply->data.str = mu_2nrealloc(reply->data.str,
					       &reply->maxcount,
					       sizeof(reply->data.str[0]));
	reply->data.str[reply->count++] = item;
}

void
dns_reply_push(struct dns_reply *reply, void *item)
{
	switch (reply->type) {
	case dns_reply_ip:
		dns_reply_ip_push(reply, item);
		break;
	case dns_reply_ip6:
		dns_reply_ip6_push(reply, item);
		break;
	case dns_reply_str:
		dns_reply_str_push(reply, item);
		break;
	default:
		abort();
	}
}

void
dns_reply_free(struct dns_reply *reply)
{
	int i;

	switch (reply->type) {
	case dns_reply_str:
		for (i = 0; i < reply->count; i++)
			free(reply->data.str[i]);
		free(reply->data.str);
		break;
	case dns_reply_ip:
		free(reply->data.ip);
		break;
	case dns_reply_ip6:
		free(reply->data.ip6);
		break;
	}
}

int
dns_str_is_ipv4(const char *addr)
{
	int dot_count;
	int digit_count;

	dot_count = 0;
	digit_count = 0;
	while (*addr != 0) {
		if (*addr == '.') {
			if (++dot_count > 4)
				return 0;
			digit_count = 0;
		} else if (!(isdigit(*addr) && ++digit_count <= 3)) {
			return 0;
		}
		addr++;
	}

	return dot_count == 3;
}

int
dns_str_is_ipv6(const char *addr)
{
	int col_count = 0; /* Number of colons */
	int dcol = 0;      /* Did we encounter a double-colon? */
	int dig_count = 0; /* Number of digits in the last group */

	for (; *addr; addr++) {
		if (!isascii(*addr))
			return 0;
		else if (isxdigit(*addr)) {
			if (++dig_count > 4)
				return 0;
		} else if (*addr == ':') {
			if (col_count && dig_count == 0 && ++dcol > 1)
				return 0;
			if (++col_count > 7)
				return 0;
			dig_count = 0;
		} else
			return 0;
	}
	return col_count == 7 || dcol;
}

static int
errno_to_dns_status(int e)
{
	switch (e) {
	case 0:
		return dns_success;
	case EAGAIN:
#ifdef EINPROGRESS
	case EINPROGRESS:
#endif
#ifdef ETIMEDOUT
	case ETIMEDOUT:
#endif
		return dns_temp_failure;
	default:
		return dns_failure;
	}
}

/* Table of correspondence between ADNS status codes and dns status.
   Values are increased by 1 to be able to tell whether the entry is
   initialized or not. */
int adns_to_dns_tab[] = {
#define STAT(s) ((s)+1)
	[adns_s_ok]                  = STAT(dns_success),

	[adns_s_nomemory]            = STAT(dns_failure),
	[adns_s_unknownrrtype]       = STAT(dns_failure),
	[adns_s_systemfail]          = STAT(dns_failure),

	/* remotely induced errors, detected locally */
	[adns_s_timeout]             = STAT(dns_temp_failure),
	[adns_s_allservfail]         = STAT(dns_temp_failure),
	[adns_s_norecurse]           = STAT(dns_temp_failure),
	[adns_s_invalidresponse]     = STAT(dns_failure),
	[adns_s_unknownformat]       = STAT(dns_failure),

	/* remotely induced errors), reported by remote server to us */
	[adns_s_rcodeservfail]       = STAT(dns_not_found),
	[adns_s_rcodeformaterror]    = STAT(dns_not_found),
	[adns_s_rcodenotimplemented] = STAT(dns_not_found),
	[adns_s_rcoderefused]        = STAT(dns_not_found),
	[adns_s_rcodeunknown]        = STAT(dns_not_found),

	/* remote configuration errors */
	[adns_s_inconsistent]        = STAT(dns_not_found),
	[adns_s_prohibitedcname]     = STAT(dns_not_found),
	[adns_s_answerdomaininvalid] = STAT(dns_not_found),
	[adns_s_answerdomaintoolong] = STAT(dns_not_found),
	[adns_s_invaliddata]         = STAT(dns_not_found),

	/* permanent problems with the query */
	[adns_s_querydomainwrong]    = STAT(dns_failure),
	[adns_s_querydomaininvalid]  = STAT(dns_failure),
	[adns_s_querydomaintoolong]  = STAT(dns_failure),

	/* permanent errors */
	[adns_s_nxdomain]            = STAT(dns_not_found),
	[adns_s_nodata]              = STAT(dns_not_found),
#undef STAT
};

/* Convert ADNS status code E to DNS status. */
static int
adns_to_dns_status(int e)
{
	int r;

	/* If it is negative, fail right away */
	if (e < 0)
		return dns_failure;
	/* If it is not in table, it still can be a valid, but unhandled
	   value */
	if (e >= MU_ARRAY_SIZE(adns_to_dns_tab))
		return e < adns_s_max_permfail ? dns_not_found : dns_failure;
	/* Now, look up in the table */
	if ((r = adns_to_dns_tab[e]) > 0)
		return r - 1;
	/* If not found in table, use adns_s_max_ constants to decide the
	   error class.
	*/
	if (e < adns_s_max_localfail)
		return dns_failure;
	if (e < adns_s_max_remotefail)
		return dns_not_found;
	if (e < adns_s_max_tempfail)
		return dns_temp_failure;
	if (e < adns_s_max_misconfig)
		return dns_not_found;
	if (e < adns_s_max_misquery)
		return dns_not_found;
	return dns_not_found;
}

/*
 * dns_query and friends - a query wrapper.
 *
 * Adns library expressly disallows CNAMEs pointing to another
 * CNAMEs, and a good thing it does (for the reference, see RFC 1034,
 * section 3.6.2).  However, reportedly such CNAME chains are being
 * used quite often, e.g. for pointing to TXT records.  Thus, a practical
 * need for supporting CNAME chains to some extent does exist.
 *
 * The dns_query function below is a wrapper over adns_synchronous that
 * follows CNAME with limited length, with CNAME loop detection.  The
 * maximum length of a chain is given by the dns_max_cname_chain variable.
 * Values 0 and 1 disable CNAME chain support.  If a the length limit is
 * hit or a CNAME loop is detected, adns_s_prohibitedcname status is
 * returned.
 */
size_t dns_max_cname_chain = 2;

/*
 * To track encountered CNAMES, a singly linked list is used.  This
 * means, among others, that dns_max_cname_chain better be sufficiently
 * small.
 */
struct cname_record {
	struct cname_record *next; /* Pointer to next record */
	char name[1];              /* Actual name follows the structure */
};

/* A list of recorded CNAMEs */
struct cname_record_list {
	size_t count;              /* Number of elements in the list. */
	struct cname_record *head, *tail;
};

#define CNAME_RECORD_LIST_INITIALIZER { 0, NULL, NULL }

/*
 * Free the list entries from RECLIST.  The structure RECLIST points to
 * should be allocated on stack, and therefore not freed.
 */
static void
cname_record_list_free(struct cname_record_list *reclist)
{
	struct cname_record *rec = reclist->head;
	while (rec) {
		struct cname_record *next = rec->next;
		free(rec);
		rec = next;
	}
}

/*
 * Install NAME into RECLIST.  Return pointer to the allocated copy
 * of the name.  Return NULL if NAME is already stored in the list.
 */
static char const *
cname_install(struct cname_record_list *reclist, char const *name)
{
	struct cname_record *rec;

	for (rec = reclist->head; rec; rec = rec->next) {
		if (mu_c_strcasecmp(rec->name, name) == 0)
			return NULL;
	}
	rec = mu_alloc(sizeof(*rec) + strlen(name));
	strcpy(rec->name, name);
	rec->next = NULL;
	if (!reclist->head)
		reclist->head = rec;
	else
		reclist->tail->next = rec;
	reclist->tail = rec;
	reclist->count++;
	return rec->name;
}

/*
 * dns_query - look up a label NAME of RR type TYPE in the DNS.  Follow
 * CNAME chains of up to dns_max_cname_chain elements.  In other respects
 * the behavior is the same as that of adns_synchronous.
 *
 * FIXME: in the presence of a CNAME chain, this function does two
 * extra lookups, compared with the hypothetical libresolv implementation.
 * This is due to the specifics of libadns.
 */
int
dns_query(const char *name, adns_rrtype type, adns_answer **ans_ret)
{
	adns_state state = get_state();
	adns_answer *ans = NULL, *cnans = NULL;
	int rc;

	/*
	 * First, look up the requested RR type.  If the actual record is
	 * a CNAME pointing to the requested RR, this will be handled by
	 * adns due to adns_qf_cname_loose flag in DEFAULT_QFLAGS.
	 *
	 * If it is a CNAME pointing to a CNAME, this will result in the
	 * first extra lookup (see FIXME above).
	 */
	rc = adns_synchronous(state, name, type, DEFAULT_QFLAGS, &ans);
	if (rc == 0 && ans->status == adns_s_prohibitedcname
	    && dns_max_cname_chain > 1) {
		struct cname_record_list cname_rec = CNAME_RECORD_LIST_INITIALIZER;

		/* Record the queried name, first. */
		cname_install(&cname_rec, name);

		/* Follow the CNAME chain. */
		while (cname_rec.count - 1 <= dns_max_cname_chain) {
			if ((rc = adns_synchronous(state, name, adns_r_cname,
						   DEFAULT_QFLAGS, &cnans)))
				break;
			if (cnans->status == adns_s_ok) {
				/*
				 * CNAME found. Record it and continue.
				 */
				name = cname_install(&cname_rec, cnans->rrs.str[0]);
				free(cnans);
				if (!name)
					/*
					 * Loop detected.  Returned ans
					 * retains the adns_s_prohibitedcname
					 * status.
					 */
					break;
			} else if (cnans->status == adns_s_nodata) {
				/*
				 * RR found, but has a different type.
				 * Look up the requested type using the last
				 * recorded name.  This accounts for second
				 * extra lookup.
				 */
				free(cnans);
				rc = adns_synchronous(state, name, type, DEFAULT_QFLAGS, &ans);
				break;
			} else {
				/*
				 * Another error.  Replace original answer with
				 * the last one.
				 */
				free(ans);
				ans = cnans;
				break;
			}
		}
		cname_record_list_free(&cname_rec);
	}

	if (rc == 0)
		*ans_ret = ans;
	else
		free(ans);
	return rc;
}

typedef dns_status (*dns_lookup_fn)(const char *, struct dns_reply *);

static dns_lookup_fn
lookup_function(int resolve_family)
{
	switch (resolve_family) {
	case resolve_ip4:
		return a_lookup;
		break;
	case resolve_ip6:
		return aaaa_lookup;
		break;
	default:
		break;
	}
	return NULL;
}

dns_status
soa_check(const char *name, int resolve_family, struct dns_reply *reply)
{
	dns_status status = dns_failure;
	int rc;
	adns_answer *ans;

	rc = dns_query(name, adns_r_soa_raw, &ans);
	if (rc)
		return errno_to_dns_status(rc);
	status = adns_to_dns_status(ans->status);
	if (status == dns_success) {
		if (resolve_family != resolve_none) {
			dns_lookup_fn lookup = lookup_function(resolve_family);
			if (lookup == NULL)
				return dns_failure;
			status = lookup(ans->rrs.soa->mname, reply);
		} else {
			dns_reply_init(reply, dns_reply_str, 1);
			reply->data.str[0] = mu_strdup (ans->rrs.soa->mname);
		}
		free(ans);
	}
	return status;
}

static dns_status
dns_reply_resolve(struct dns_reply *reply, int family)
{
	size_t i;
	struct dns_reply res;
	dns_lookup_fn lookup;

	if (family == resolve_none)
		return dns_success;

	lookup = lookup_function(family);
	if (lookup == NULL)
		return dns_failure;

	dns_reply_init(&res, (family == resolve_ip4) ? dns_reply_ip : dns_reply_ip6, 0);
	for (i = 0; i < reply->count; i++) {
		struct dns_reply r;
		dns_status stat = lookup(reply->data.str[i], &r);
		if (stat == dns_success) {
			size_t n;
			for (n = 0; n < r.count; n++) {
				dns_reply_push(&res,
					       (family == resolve_ip4)
					       ? (void*) &r.data.ip[n]
					       : (void*) &r.data.ip6[n]);
			}
			dns_reply_free(&r);
		}
	}
	dns_reply_free(reply);
	*reply = res;
	if (res.count == 0)
		return dns_not_found;
	return dns_success;
}

/* Return MX records for the given HOST. */
dns_status
mx_lookup(const char *host, int resolve_family, struct dns_reply *reply)
{
	dns_status status = dns_failure;
	int rc;
	adns_answer *ans;
	int i;

	rc = dns_query(host, adns_r_mx, &ans);
	if (rc)
		return errno_to_dns_status(rc);
	status = adns_to_dns_status(ans->status);
	if (status != dns_success)
		return status;

	dns_reply_init(reply, dns_reply_str, ans->nrrs);
	for (i = 0; i < ans->nrrs; i++)
		reply->data.str[i] = mu_strdup(ans->rrs.inthostaddr[i].ha.host);
	free(ans);

	status = dns_reply_resolve(reply, resolve_family);

	return status;
}

static int
cidr_reverse_ip4(char *buf, size_t bufsize, struct mu_cidr const *cidr)
{
	int i, n;
	char *start = buf;

	for (i = cidr->len - 1; i >= 0; i--) {
		unsigned c = cidr->address[i];
		n = snprintf(buf, bufsize, "%u", c);
		if (n < 0 || n >= bufsize)
			return -1;
		buf += n;
		bufsize -= n;
		*buf++ = '.';
		bufsize--;
	}
	return buf - start;
}

static int
cidr_reverse_ip6(char *buf, size_t bufsize, struct mu_cidr const *cidr)
{
	int i;
	char *start = buf;
	static char xdig[] = "0123456789abcdef";

	if (bufsize < IPV6_DOTTED_BUFSIZE)
		return -1;
	for (i = cidr->len - 1; i >= 0; i--) {
		unsigned c = cidr->address[i];
		*buf++ = xdig[c & 0xf];
		*buf++ = '.';
		*buf++ = xdig[(c >> 4) & 0xf];
		*buf++ = '.';
	}
	return buf - start;
}

static int
cidr_reverse(struct mu_cidr const *cidr, char *buf, size_t bufsize)
{
	size_t n;
	int (*rev)(char *, size_t, struct mu_cidr const *);

	switch (cidr->family) {
	case AF_INET:
		n = IPV4_DOTTED_BUFSIZE;
		rev = cidr_reverse_ip4;
		break;

	case AF_INET6:
		n = IPV6_DOTTED_BUFSIZE;
		rev = cidr_reverse_ip6;
		break;

	default:
		return -1;
	}

	if (n > bufsize)
		return -1;

	return rev(buf, bufsize, cidr);
}

int
cidr_to_arpa(struct mu_cidr const *cidr, char *buf, size_t bufsize)
{
	size_t n;
	char const *domain;

	switch (cidr->family) {
	case AF_INET:
		domain = IPV4_INADDR_DOMAIN;
		break;

	case AF_INET6:
		domain = IPV6_INADDR_DOMAIN;
		break;

	default:
		return -1;
	}

	n = cidr_reverse(cidr, buf, bufsize);
	buf += n;
	bufsize -= n;

	if (strlen(domain) >= bufsize)
		return -1;
	strcpy(buf, domain);
	return 0;
}

int
dns_reverse_ipstr(const char *ipstr, char *buf, size_t bufsize)
{
	struct mu_cidr cidr;
	if (mu_cidr_from_string(&cidr, ipstr))
		return -1;
	return cidr_reverse(&cidr, buf, bufsize);
}

dns_status
dns_reverse_name(const char *ipstr, char *buf, size_t bufsize)
{
	struct mu_cidr cidr;
	if (mu_cidr_from_string(&cidr, ipstr))
		return dns_failure;
	if (cidr_to_arpa(&cidr, buf, bufsize))
		return dns_failure;
	return dns_success;
}

dns_status
dns_resolve_ipstr(const char *ipstr, struct dns_reply *reply)
{
	dns_status status = dns_failure;
	int rc;
	adns_answer *ans;
	struct mu_cidr cidr;
	char buf[IPMAX_INADDR_BUFSIZE];
	size_t buflen = sizeof(buf);

	if (mu_cidr_from_string(&cidr, ipstr))
		return dns_failure;

	if (cidr_to_arpa(&cidr, buf, buflen))
		return dns_failure;

	rc = dns_query(buf, adns_r_ptr_raw, &ans);
	if (rc)
		return errno_to_dns_status(rc);
	status = adns_to_dns_status(ans->status);

	if (status == dns_success) {
		int i;
		dns_reply_init(reply, dns_reply_str, ans->nrrs);
		for (i = 0; i < ans->nrrs; i++) {
			reply->data.str[i] = mu_strdup(ans->rrs.str[i]);
		}
	}
	free(ans);
	return status;
}

dns_status
dns_resolve_hostname(const char *host, int family, char **ipbuf)
{
	dns_status status = dns_failure;
	int rc;
	adns_answer *ans;
	adns_rrtype type;

	switch (family) {
	case resolve_ip4:
		type = adns_r_a;
		break;

	case resolve_ip6:
		type = adns_r_aaaa;
		break;

	default:
		return dns_failure;
	}

	rc = dns_query(host, type, &ans);
	if (rc)
		return errno_to_dns_status(rc);
	status = adns_to_dns_status(ans->status);
	if (status == dns_success) {
		char ipstr[IPMAX_DOTTED_BUFSIZE];
		switch (type) {
		case adns_r_a:
			inet_ntop(AF_INET, &ans->rrs.inaddr[0], ipstr,
				  sizeof(ipstr));
			break;
		case adns_r_aaaa:
			inet_ntop(AF_INET6, &ans->rrs.in6addr[0], ipstr,
				  sizeof(ipstr));
			break;
		default:
			status = dns_failure;
		}
		if (status == dns_success)
			*ipbuf = mu_strdup(ipstr);
	}
	free(ans);
	return status;
}


dns_status
a_lookup(const char *host, struct dns_reply *reply)
{
	dns_status status = dns_failure;
	int rc;
	adns_answer *ans;

	rc = dns_query(host, adns_r_a, &ans);
	if (rc)
		return errno_to_dns_status(rc);
	status = adns_to_dns_s