summaryrefslogtreecommitdiff
path: root/bin/named/xfrout.c
blob: 91800a30df9f5168a248dde46865f0aeeb1fba82 (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
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
/*
 * Copyright (C) 1999, 2000  Internet Software Consortium.
 * 
 * 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 INTERNET SOFTWARE CONSORTIUM DISCLAIMS
 * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
 * CONSORTIUM 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.
 */

/* $Id: xfrout.c,v 1.49 2000/03/23 00:54:44 gson Exp $ */

#include <config.h>

#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#include <sys/types.h>

#include <isc/assertions.h>
#include <isc/error.h>
#include <isc/mem.h>
#include <isc/result.h>
#include <isc/timer.h>
#include <isc/util.h>

#include <dns/acl.h>
#include <dns/db.h>
#include <dns/dbiterator.h>
#include <dns/fixedname.h>
#include <dns/journal.h>
#include <dns/message.h>
#include <dns/name.h>
#include <dns/peer.h>
#include <dns/rdata.h>
#include <dns/rdatalist.h>
#include <dns/rdataset.h>
#include <dns/rdatasetiter.h>
#include <dns/rdatastruct.h>
#include <dns/result.h>
#include <dns/types.h>
#include <dns/view.h>
#include <dns/zone.h>
#include <dns/zt.h>

#include <named/client.h>
#include <named/globals.h>
#include <named/log.h>
#include <named/server.h>
#include <named/xfrout.h>

/*
 * Outgoing AXFR and IXFR.
 */

/*
 * TODO:
 *  - IXFR over UDP
 */

#define XFROUT_COMMON_LOGARGS \
	ns_g_lctx, DNS_LOGCATEGORY_XFER_OUT, NS_LOGMODULE_XFER_OUT

#define XFROUT_PROTOCOL_LOGARGS \
	XFROUT_COMMON_LOGARGS, ISC_LOG_INFO

#define XFROUT_DEBUG_LOGARGS(n) \
	XFROUT_COMMON_LOGARGS, ISC_LOG_DEBUG(n)

/*
 * Fail unconditionally and log as a client error.
 */
#define FAILC(code, msg) \
	do {							\
		result = (code);				\
		isc_log_write(XFROUT_PROTOCOL_LOGARGS,		\
			      "bad zone transfer request: %s (%s)", \
		      	      msg, isc_result_totext(code));	\
		goto failure;					\
	} while (0)

#define CHECK(op) \
     	do { result = (op); 					\
		if (result != DNS_R_SUCCESS) goto failure; 	\
	} while (0)

/**************************************************************************/
/*
 * A db_rr_iterator_t is an iterator that iterates over an entire database,
 * returning one RR at a time, in some arbitrary order. 
 */
	
typedef struct db_rr_iterator db_rr_iterator_t;

struct db_rr_iterator {
	isc_result_t		result;
	dns_db_t		*db;
    	dns_dbiterator_t 	*dbit;
	dns_dbversion_t 	*ver;
	isc_stdtime_t		now;
	dns_dbnode_t		*node;
	dns_fixedname_t		fixedname;
    	dns_rdatasetiter_t 	*rdatasetit;
	dns_rdataset_t 		rdataset;
	dns_rdata_t		rdata;
};

isc_result_t db_rr_iterator_init(db_rr_iterator_t *it, dns_db_t *db,
				 dns_dbversion_t *ver, isc_stdtime_t now);

isc_result_t db_rr_iterator_first(db_rr_iterator_t *it);

isc_result_t db_rr_iterator_next(db_rr_iterator_t *it);

void db_rr_iterator_current(db_rr_iterator_t *it, dns_name_t **name, 
			    isc_uint32_t *ttl, dns_rdata_t **rdata);

void db_rr_iterator_destroy(db_rr_iterator_t *it);

isc_result_t
db_rr_iterator_init(db_rr_iterator_t *it, dns_db_t *db, dns_dbversion_t *ver,
		    isc_stdtime_t now)
{
	isc_result_t result;
	it->db = db;
	it->dbit = NULL;
	it->ver = ver;
	it->now = now;
	it->node = NULL;
	result = dns_db_createiterator(it->db, ISC_FALSE, &it->dbit);
	if (result != DNS_R_SUCCESS)
		return (result);
	it->rdatasetit = NULL;
	dns_rdataset_init(&it->rdataset);
	dns_fixedname_init(&it->fixedname);
	INSIST(! dns_rdataset_isassociated(&it->rdataset));
	it->result = DNS_R_SUCCESS;
	return (it->result);
}

isc_result_t
db_rr_iterator_first(db_rr_iterator_t *it) {
	it->result = dns_dbiterator_first(it->dbit);
	if (it->result != DNS_R_SUCCESS)
		return (it->result);
	it->result = dns_dbiterator_current(it->dbit, &it->node,
				    dns_fixedname_name(&it->fixedname));
	if (it->result != DNS_R_SUCCESS) 
		return (it->result);

	it->result = dns_db_allrdatasets(it->db, it->node,
					 it->ver, it->now,
					 &it->rdatasetit);
	if (it->result != DNS_R_SUCCESS) 
		return (it->result);
		
	it->result = dns_rdatasetiter_first(it->rdatasetit);
	if (it->result != DNS_R_SUCCESS) 
		return (it->result);

	dns_rdatasetiter_current(it->rdatasetit, &it->rdataset);
	
	it->result = dns_rdataset_first(&it->rdataset);
	return (it->result);
}


isc_result_t
db_rr_iterator_next(db_rr_iterator_t *it) {
	if (it->result != DNS_R_SUCCESS)
		return (it->result);

	INSIST(it->dbit != NULL);
	INSIST(it->node != NULL);
	INSIST(it->rdatasetit != NULL);

	it->result = dns_rdataset_next(&it->rdataset);
	if (it->result == DNS_R_NOMORE) {
		dns_rdataset_disassociate(&it->rdataset);
		it->result = dns_rdatasetiter_next(it->rdatasetit);
		while (it->result == DNS_R_NOMORE) {
			dns_rdatasetiter_destroy(&it->rdatasetit);
			dns_db_detachnode(it->db, &it->node);
			it->result = dns_dbiterator_next(it->dbit);
			if (it->result == DNS_R_NOMORE) {
				/* We are at the end of the entire database. */
				return (it->result);
			}
			if (it->result != DNS_R_SUCCESS)
				return (it->result);
			it->result = dns_dbiterator_current(it->dbit,
				    &it->node,
				    dns_fixedname_name(&it->fixedname));
			if (it->result != DNS_R_SUCCESS)
				return (it->result);
			it->result = dns_db_allrdatasets(it->db, it->node,
					 it->ver, it->now,
					 &it->rdatasetit);
			if (it->result != DNS_R_SUCCESS)
				return (it->result);
			it->result = dns_rdatasetiter_first(it->rdatasetit);
		}
		if (it->result != DNS_R_SUCCESS)
			return (it->result);
		dns_rdatasetiter_current(it->rdatasetit, &it->rdataset);
	}
	return (it->result);
}

void
db_rr_iterator_destroy(db_rr_iterator_t *it) {
	if (dns_rdataset_isassociated(&it->rdataset))
		dns_rdataset_disassociate(&it->rdataset);
	if (it->rdatasetit != NULL)
		dns_rdatasetiter_destroy(&it->rdatasetit);
	if (it->node != NULL)
		dns_db_detachnode(it->db, &it->node);
	dns_dbiterator_destroy(&it->dbit);
}

void
db_rr_iterator_current(db_rr_iterator_t *it, dns_name_t **name,
		      isc_uint32_t *ttl, dns_rdata_t **rdata)
{
	REQUIRE(name != NULL && *name == NULL);
	REQUIRE(it->result == DNS_R_SUCCESS);
	*name = dns_fixedname_name(&it->fixedname);
	*ttl = it->rdataset.ttl;
	dns_rdataset_current(&it->rdataset, &it->rdata);
	*rdata = &it->rdata;
}

/**************************************************************************/

/* Log an RR (for debugging) */

static void
log_rr(dns_name_t *name, dns_rdata_t *rdata, isc_uint32_t ttl) {
	isc_result_t result;

	isc_buffer_t buf;
	char mem[2000];
	isc_region_t r;
	dns_rdatalist_t rdl;
	dns_rdataset_t rds;

	rdl.type = rdata->type;
	rdl.rdclass = rdata->rdclass;
	rdl.ttl = ttl;
	ISC_LIST_INIT(rdl.rdata);
	ISC_LINK_INIT(&rdl, link);
	dns_rdataset_init(&rds);
	ISC_LIST_APPEND(rdl.rdata, rdata, link);
	RUNTIME_CHECK(dns_rdatalist_tordataset(&rdl, &rds) == DNS_R_SUCCESS);
		
	isc_buffer_init(&buf, mem, sizeof(mem), ISC_BUFFERTYPE_TEXT);
	result = dns_rdataset_totext(&rds, name,
				     ISC_FALSE, ISC_FALSE, &buf);

	/* Get rid of final newline. */
	INSIST(buf.used >= 1 && ((char *) buf.base)[buf.used-1] == '\n');
	buf.used--;
	
	if (result == DNS_R_SUCCESS) {
		isc_buffer_used(&buf, &r);
		isc_log_write(XFROUT_DEBUG_LOGARGS(8),
			      "%.*s", (int) r.length, (char *) r.base);
	} else {
		isc_log_write(XFROUT_DEBUG_LOGARGS(8),
			      "<RR too large to print>");
	}
}

/**************************************************************************/
/*
 * An 'rrstream_t' is a polymorphic iterator that returns
 * a stream of resource records.  There are multiple implementations,
 * e.g. for generating AXFR and IXFR records streams.
 */

typedef struct rrstream_methods rrstream_methods_t;

typedef struct rrstream {
	isc_mem_t 		*mctx;
	rrstream_methods_t	*methods;
} rrstream_t;

struct rrstream_methods {	
	isc_result_t 		(*first)(rrstream_t *);
	isc_result_t 		(*next)(rrstream_t *);
	void			(*current)(rrstream_t *,
					   dns_name_t **,
					   isc_uint32_t *,
					   dns_rdata_t **);
	void 			(*destroy)(rrstream_t **);
};

/**************************************************************************/
/*
 * An 'ixfr_rrstream_t' is an 'rrstream_t' that returns
 * an IXFR-like RR stream from a journal file.
 *
 * The SOA at the beginning of each sequence of additions
 * or deletions are included in the stream, but the extra
 * SOAs at the beginning and end of the entire transfer are
 * not included.
 */

typedef struct ixfr_rrstream {
	rrstream_t		common;
	dns_journal_t 		*journal;
} ixfr_rrstream_t;

/* Forward declarations. */
static void ixfr_rrstream_destroy(rrstream_t **sp);
static rrstream_methods_t ixfr_rrstream_methods;

/*
 * Returns: anything dns_journal_open() or dns_journal_iter_init()
 * may return.
 */

static isc_result_t
ixfr_rrstream_create(isc_mem_t *mctx,
		     const char *journal_filename,
		     isc_uint32_t begin_serial,
		     isc_uint32_t end_serial,
		     rrstream_t **sp)
{
	ixfr_rrstream_t *s;
	isc_result_t result;

	INSIST(sp != NULL && *sp == NULL);

	s = isc_mem_get(mctx, sizeof(*s));
	if (s == NULL)
		return (DNS_R_NOMEMORY);
	s->common.mctx = mctx;
	s->common.methods = &ixfr_rrstream_methods;
	s->journal = NULL;
	
	CHECK(dns_journal_open(mctx, journal_filename,
			       ISC_FALSE, &s->journal));
	CHECK(dns_journal_iter_init(s->journal, begin_serial, end_serial));

	*sp = (rrstream_t *) s;
	return (DNS_R_SUCCESS);

 failure:
	ixfr_rrstream_destroy((rrstream_t **) &s);
	return (result);
}

static isc_result_t
ixfr_rrstream_first(rrstream_t *rs)
{
	ixfr_rrstream_t *s = (ixfr_rrstream_t *) rs;
	return (dns_journal_first_rr(s->journal));
}

static isc_result_t
ixfr_rrstream_next(rrstream_t *rs)
{
	ixfr_rrstream_t *s = (ixfr_rrstream_t *) rs;	
	return (dns_journal_next_rr(s->journal));
}


static void
ixfr_rrstream_current(rrstream_t *rs,
		       dns_name_t **name, isc_uint32_t *ttl,
		       dns_rdata_t **rdata)
{
	ixfr_rrstream_t *s = (ixfr_rrstream_t *) rs;	
	dns_journal_current_rr(s->journal, name, ttl, rdata);
}

static void
ixfr_rrstream_destroy(rrstream_t **rsp) {
	ixfr_rrstream_t *s = (ixfr_rrstream_t *) *rsp;
	if (s->journal != 0)
		dns_journal_destroy(&s->journal);
	isc_mem_put(s->common.mctx, s, sizeof(*s));
}

static rrstream_methods_t ixfr_rrstream_methods = 
{
	ixfr_rrstream_first,
	ixfr_rrstream_next,
	ixfr_rrstream_current,		
	ixfr_rrstream_destroy
};

/**************************************************************************/
/*
 * An 'ixfr_rrstream_t' is an 'rrstream_t' that returns
 * an AXFR-like RR stream from a database.
 *
 * The SOAs at the beginning and end of the transfer are
 * not included in the stream.
 */

typedef struct axfr_rrstream {
	rrstream_t		common;
	int 			state;
	db_rr_iterator_t		it;
	isc_boolean_t		it_valid;
} axfr_rrstream_t;

/* Forward declarations. */
static void axfr_rrstream_destroy(rrstream_t **rsp);
static rrstream_methods_t axfr_rrstream_methods;

static isc_result_t
axfr_rrstream_create(isc_mem_t *mctx,
		      dns_db_t *db,
		      dns_dbversion_t *ver,
		      rrstream_t **sp)
{
	axfr_rrstream_t *s;
	isc_result_t result;

	INSIST(sp != NULL && *sp == NULL);

	s = isc_mem_get(mctx, sizeof(*s));
	if (s == NULL)
		return (DNS_R_NOMEMORY);
	s->common.mctx = mctx;
	s->common.methods = &axfr_rrstream_methods;
	s->it_valid = ISC_FALSE;

	CHECK(db_rr_iterator_init(&s->it, db, ver, 0));
	s->it_valid = ISC_TRUE;

	*sp = (rrstream_t *) s;
	return (DNS_R_SUCCESS);

 failure:
	axfr_rrstream_destroy((rrstream_t **) &s);
	return (result);
}

static isc_result_t
axfr_rrstream_first(rrstream_t *rs)
{
	axfr_rrstream_t *s = (axfr_rrstream_t *) rs;
	isc_result_t result;
	result = db_rr_iterator_first(&s->it);
	/* Skip SOA records. */
	for (;;) {
		dns_name_t *name_dummy = NULL;
		isc_uint32_t ttl_dummy;
		dns_rdata_t *rdata = NULL;
		db_rr_iterator_current(&s->it, &name_dummy,
				      &ttl_dummy, &rdata);
		if (rdata->type != dns_rdatatype_soa)
			break;
		result = db_rr_iterator_next(&s->it);
		if (result != DNS_R_SUCCESS)
			break;
	}
	return (result);
}

static isc_result_t
axfr_rrstream_next(rrstream_t *rs)
{
	axfr_rrstream_t *s = (axfr_rrstream_t *) rs;
	isc_result_t result;
	
	/* Skip SOA records. */
	for (;;) {
		dns_name_t *name_dummy = NULL;
		isc_uint32_t ttl_dummy;
		dns_rdata_t *rdata = NULL;
		result = db_rr_iterator_next(&s->it);
		if (result != DNS_R_SUCCESS)
			break;
		db_rr_iterator_current(&s->it, &name_dummy,
				      &ttl_dummy, &rdata);
		if (rdata->type != dns_rdatatype_soa)
			break;
	}
	return (result);
}

static void
axfr_rrstream_current(rrstream_t *rs,
		       dns_name_t **name, isc_uint32_t *ttl,
		       dns_rdata_t **rdata)
{
	axfr_rrstream_t *s = (axfr_rrstream_t *) rs;
	db_rr_iterator_current(&s->it, name, ttl, rdata);
}

static void
axfr_rrstream_destroy(rrstream_t **rsp) {
	axfr_rrstream_t *s = (axfr_rrstream_t *) *rsp;
	if (s->it_valid)
		db_rr_iterator_destroy(&s->it); 
	isc_mem_put(s->common.mctx, s, sizeof(*s));
}

static rrstream_methods_t axfr_rrstream_methods = 
{
	axfr_rrstream_first,
	axfr_rrstream_next,
	axfr_rrstream_current,		
	axfr_rrstream_destroy
};

/**************************************************************************/
/*
 * An 'soa_rrstream_t' is a degenerate 'rrstream_t' that returns
 * a single SOA record.
 */

typedef struct soa_rrstream {
	rrstream_t		common;
	dns_difftuple_t 	*soa_tuple;
} soa_rrstream_t;

/* Forward declarations. */
static void soa_rrstream_destroy(rrstream_t **rsp);
static rrstream_methods_t soa_rrstream_methods;

static isc_result_t
soa_rrstream_create(isc_mem_t *mctx,
		    dns_db_t *db,
		    dns_dbversion_t *ver,
		    rrstream_t **sp)
{
	soa_rrstream_t *s;
	isc_result_t result;

	INSIST(sp != NULL && *sp == NULL);

	s = isc_mem_get(mctx, sizeof(*s));
	if (s == NULL)
		return (DNS_R_NOMEMORY);
	s->common.mctx = mctx;
	s->common.methods = &soa_rrstream_methods;
	s->soa_tuple = NULL;
	
	CHECK(dns_db_createsoatuple(db, ver, mctx, DNS_DIFFOP_EXISTS,
				    &s->soa_tuple));

	*sp = (rrstream_t *) s;
	return (DNS_R_SUCCESS);

 failure:
	soa_rrstream_destroy((rrstream_t **) &s);
	return (result);
}

static isc_result_t
soa_rrstream_first(rrstream_t *rs) {
	UNUSED(rs);
	return (DNS_R_SUCCESS);
}

static isc_result_t
soa_rrstream_next(rrstream_t *rs) {
	UNUSED(rs);
	return (DNS_R_NOMORE);
}

static void
soa_rrstream_current(rrstream_t *rs,
		     dns_name_t **name, isc_uint32_t *ttl,
		     dns_rdata_t **rdata)
{
	soa_rrstream_t *s = (soa_rrstream_t *) rs;	
	*name = &s->soa_tuple->name;
	*ttl = s->soa_tuple->ttl;
	*rdata = &s->soa_tuple->rdata;
}

static void
soa_rrstream_destroy(rrstream_t **rsp) {
	soa_rrstream_t *s = (soa_rrstream_t *) *rsp;
	if (s->soa_tuple != NULL)
		dns_difftuple_free(&s->soa_tuple);
	isc_mem_put(s->common.mctx, s, sizeof(*s));
}

static rrstream_methods_t soa_rrstream_methods = 
{
	soa_rrstream_first,
	soa_rrstream_next,
	soa_rrstream_current,		
	soa_rrstream_destroy
};

/**************************************************************************/
/*
 * A 'compound_rrstream_t' objects owns a soa_rrstream
 * and another rrstream, the "data stream".  It returns
 * a concatenated stream consisting of the soa_rrstream, then
 * the data stream, then the soa_rrstream again.
 *
 * The component streams are owned by the compound_rrstream_t 
 * and are destroyed with it.
 */

typedef struct compound_rrstream {
	rrstream_t		common;
	rrstream_t		*components[3];
	int			state;
	isc_result_t		result;
} compound_rrstream_t;

/* Forward declarations. */
static void compound_rrstream_destroy(rrstream_t **rsp);
static isc_result_t compound_rrstream_next(rrstream_t *rs);
static rrstream_methods_t compound_rrstream_methods;

/*
 * Requires:
 *	soa_stream != NULL && *soa_stream != NULL
 *	data_stream != NULL && *data_stream != NULL
 *	sp != NULL && *sp == NULL
 *
 * Ensures:
 *	*soa_stream == NULL
 *	*data_stream == NULL
 *	*sp points to a valid compound_rrstream_t
 *	The soa and data streams will be destroyed
 *	when the compound_rrstream_t is destroyed.
 */
static isc_result_t
compound_rrstream_create(isc_mem_t *mctx,
			 rrstream_t **soa_stream,
			 rrstream_t **data_stream,
			 rrstream_t **sp)
{
	compound_rrstream_t *s;

	INSIST(sp != NULL && *sp == NULL);

	s = isc_mem_get(mctx, sizeof(*s));
	if (s == NULL)
		return (DNS_R_NOMEMORY);
	s->common.mctx = mctx;
	s->common.methods = &compound_rrstream_methods;
	s->components[0] = *soa_stream;
	s->components[1] = *data_stream;
	s->components[2] = *soa_stream;
	s->state = -1;
	s->result = ISC_R_FAILURE;

	*soa_stream = NULL;
	*data_stream = NULL;
	*sp = (rrstream_t *) s;
	return (DNS_R_SUCCESS);
}

static isc_result_t
compound_rrstream_first(rrstream_t *rs) {
	compound_rrstream_t *s = (compound_rrstream_t *) rs;
	s->state = 0;
	do {
		rrstream_t *curstream = s->components[s->state];
		s->result = curstream->methods->first(curstream);
	} while (s->result == DNS_R_NOMORE && s->state < 2) ;
	return (s->result);
}

static isc_result_t
compound_rrstream_next(rrstream_t *rs) {
	compound_rrstream_t *s = (compound_rrstream_t *) rs;
	rrstream_t *curstream = s->components[s->state];	
	s->result = curstream->methods->next(curstream);
	while (s->result == DNS_R_NOMORE) {
		if (s->state == 2)
			return (DNS_R_NOMORE);
		s->state++;
		curstream = s->components[s->state];
		s->result = curstream->methods->first(curstream);
	}
	return (s->result);
}

static void
compound_rrstream_current(rrstream_t *rs,
		     dns_name_t **name, isc_uint32_t *ttl,
		     dns_rdata_t **rdata)
{
	compound_rrstream_t *s = (compound_rrstream_t *) rs;
	rrstream_t *curstream;
	INSIST(0 <= s->state && s->state < 3);
	INSIST(s->result == DNS_R_SUCCESS);
	curstream = s->components[s->state];
	curstream->methods->current(curstream, name, ttl, rdata);
}

static void
compound_rrstream_destroy(rrstream_t **rsp) {
	compound_rrstream_t *s = (compound_rrstream_t *) *rsp;
	s->components[0]->methods->destroy(&s->components[0]);
	s->components[1]->methods->destroy(&s->components[1]);
	s->components[2] = NULL; /* Copy of components[0]. */
	isc_mem_put(s->common.mctx, s, sizeof(*s));
}

static rrstream_methods_t compound_rrstream_methods = 
{
	compound_rrstream_first,
	compound_rrstream_next,
	compound_rrstream_current,		
	compound_rrstream_destroy
};

/**************************************************************************/
/*
 * An 'xfrout_ctx_t' contains the state of an outgoing AXFR or IXFR
 * in progress.
 */

typedef struct {
	isc_mem_t 		*mctx;
	ns_client_t		*client;
	unsigned int 		id;		/* ID of request */
	dns_name_t		*qname;		/* Question name of request */
	dns_rdatatype_t		qtype;		/* dns_rdatatype_{a,i}xfr */
	dns_db_t 		*db;
	dns_dbversion_t 	*ver;
	isc_quota_t		*quota;
	rrstream_t 		*stream;	/* The XFR RR stream */
	isc_boolean_t		end_of_stream;	/* EOS has been reached */
	isc_buffer_t 		buf;		/* Buffer for message owner
						   names and rdatas */
	isc_buffer_t 		txlenbuf;	/* Transmit length buffer */
	isc_buffer_t		txbuf;		/* Transmit message buffer */
	void 			*txmem;
	unsigned int 		txmemlen;
	unsigned int		nmsg;		/* Number of messages sent */
	dns_tsigkey_t		*tsigkey;	/* Key used to create TSIG */
	dns_rdata_any_tsig_t	*lasttsig;	/* the last TSIG */
	isc_boolean_t		many_answers;
	int			sends;		/* Send in progress */
	isc_boolean_t		shuttingdown;
} xfrout_ctx_t;

static isc_result_t
xfrout_ctx_create(isc_mem_t *mctx, ns_client_t *client,
		  unsigned int id, dns_name_t *qname, dns_rdatatype_t qtype,
		  dns_db_t *db, dns_dbversion_t *ver, isc_quota_t *quota,
		  rrstream_t *stream, dns_tsigkey_t *tsigkey,
		  dns_rdata_any_tsig_t *lasttsig,
		  unsigned int maxtime,
		  unsigned int idletime,
		  isc_boolean_t many_answers,
		  xfrout_ctx_t **xfrp);

static void sendstream(xfrout_ctx_t *xfr);

static void xfrout_senddone(isc_task_t *task, isc_event_t *event);
static void xfrout_fail(xfrout_ctx_t *xfr, isc_result_t result, char *msg);
static void xfrout_maybe_destroy(xfrout_ctx_t *xfr);
static void xfrout_ctx_destroy(xfrout_ctx_t **xfrp);
static void xfrout_client_shutdown(void *arg, isc_result_t result);

/**************************************************************************/

void
ns_xfr_start(ns_client_t *client, dns_rdatatype_t reqtype)
{
	isc_result_t result;
	dns_name_t *question_name;
	dns_rdataset_t *question_rdataset;
	dns_zone_t *zone = NULL;
	dns_db_t *db = NULL;
	dns_dbversion_t *ver = NULL;
	dns_rdataclass_t question_class;
	rrstream_t *soa_stream = NULL;
	rrstream_t *data_stream = NULL;
	rrstream_t *stream = NULL;
	dns_difftuple_t *current_soa_tuple = NULL;
	dns_name_t *soa_name;
	dns_rdataset_t *soa_rdataset;
	dns_rdata_t soa_rdata;
	isc_boolean_t have_soa = ISC_FALSE;
	char *mnemonic = NULL;	
	isc_mem_t *mctx = client->mctx;
	dns_message_t *request = client->message;
	xfrout_ctx_t *xfr = NULL;
	isc_quota_t *quota = NULL;
	dns_transfer_format_t format = ns_g_server->transfer_format;
	isc_netaddr_t na;
	dns_peer_t *peer = NULL;

	switch (reqtype) {
	case dns_rdatatype_axfr:
		mnemonic = "AXFR";
		break;
	case dns_rdatatype_ixfr:
		mnemonic = "IXFR";
		break;
	default:
		INSIST(0);
		break;
	}
	
	isc_log_write(XFROUT_DEBUG_LOGARGS(6), "got %s request", mnemonic);

	/*
	 * Apply quota.
	 */
	result = isc_quota_attach(&ns_g_server->xfroutquota, &quota);
	if (result != DNS_R_SUCCESS) {
		isc_log_write(XFROUT_COMMON_LOGARGS, ISC_LOG_WARNING,
			      "zone transfer request denied: %s",
			      isc_result_totext(result));
		goto failure;
	}

	/*
	 * Interpret the question section.
	 */
	result = dns_message_firstname(request, DNS_SECTION_QUESTION);
	INSIST(result == DNS_R_SUCCESS);

	/*
	 * The question section must contain exactly one question, and
	 * it must be for AXFR/IXFR as appropriate.
	 */
	question_name = NULL;
	dns_message_currentname(request, DNS_SECTION_QUESTION, &question_name);
	question_rdataset = ISC_LIST_HEAD(question_name->list);
	question_class = question_rdataset->rdclass;
	INSIST(question_rdataset->type == reqtype);
	if (ISC_LIST_NEXT(question_rdataset, link) != NULL)
		FAILC(DNS_R_FORMERR,
		      "multiple questions in AXFR/IXFR request");
	result = dns_message_nextname(request, DNS_SECTION_QUESTION);
	if (result != DNS_R_NOMORE)
		FAILC(DNS_R_FORMERR,
		      "multiple questions in AXFR/IXFR request");

	result = dns_zt_find(client->view->zonetable, question_name, NULL, &zone);
	if (result != DNS_R_SUCCESS)
		FAILC(DNS_R_NOTAUTH,
		      "AXFR/IXFR requested for non-authoritative zone");
	switch(dns_zone_gettype(zone)) {
	case dns_zone_master:
	case dns_zone_slave:
		break;	/* Master and slave zones are OK for transfer. */
	default:
		FAILC(DNS_R_NOTAUTH,
		      "AXFR/IXFR requested for non-authoritative zone"); 
	}
	CHECK(dns_zone_getdb(zone, &db));
	dns_db_currentversion(db, &ver);

	isc_log_write(XFROUT_DEBUG_LOGARGS(6), "%s question section OK",
		      mnemonic);

	/*
	 * Check the authority section.  Look for a SOA record with
	 * the same name and class as the question.
	 */
	for (result = dns_message_firstname(request, DNS_SECTION_AUTHORITY);
	     result == DNS_R_SUCCESS;
	     result = dns_message_nextname(request, DNS_SECTION_AUTHORITY))
	{
		soa_name = NULL;
		dns_message_currentname(request, DNS_SECTION_AUTHORITY,
					&soa_name);

		/* Ignore data whose owner name is not the zone apex. */
		if (! dns_name_equal(soa_name, question_name))
			continue;
		
		for (soa_rdataset = ISC_LIST_HEAD(soa_name->list);
		     soa_rdataset != NULL;
		     soa_rdataset = ISC_LIST_NEXT(soa_rdataset, link))
		{
			/* Ignore non-SOA data. */
			if (soa_rdataset->type != dns_rdatatype_soa)
				continue;
			if (soa_rdataset->rdclass != question_class)
				continue;

			CHECK(dns_rdataset_first(soa_rdataset));
			dns_rdataset_current(soa_rdataset, &soa_rdata);
			result = dns_rdataset_next(soa_rdataset);
			if (result == DNS_R_SUCCESS)
				FAILC(DNS_R_FORMERR,
				      "IXFR authority section "
				      "has multiple SOAs");
			have_soa = ISC_TRUE;
			goto got_soa;
		}
	}
 got_soa:
	if (result != DNS_R_NOMORE)
		CHECK(result);

	isc_log_write(XFROUT_DEBUG_LOGARGS(6), "%s authority section OK",
		      mnemonic);

	/* Decide whether to allow this transfer. */
	CHECK(ns_client_checkacl(client, "zone transfer", 
				 dns_zone_getxfracl(zone),
				 ISC_TRUE));

	/* AXFR over UDP is not possible. */
	if (reqtype == dns_rdatatype_axfr &&
	    (client->attributes & NS_CLIENTATTR_TCP) == 0) {
		FAILC(DNS_R_FORMERR, "attempted AXFR over UDP");
	}

	/* Look up the requesting server in the peer table. */
	isc_netaddr_fromsockaddr(&na, &client->peeraddr);
	(void) dns_peerlist_peerbyaddr(client->view->peers,
				       &na, &peer);
	   
	/* Decide on the transfer format (one-answer or many-answers). */
	if (peer != NULL)
		(void) dns_peer_gettransferformat(peer, &format);
	
	/* Get a dynamically allocated copy of the current SOA. */
	CHECK(dns_db_createsoatuple(db, ver, mctx, DNS_DIFFOP_EXISTS,
				    &current_soa_tuple));
	
	if (reqtype == dns_rdatatype_ixfr) {
		isc_uint32_t begin_serial, current_serial;
		isc_boolean_t provide_ixfr;
		
		/*
		 * Outgoing IXFR may have been disabled for this peer
		 * or globally.
		 */
		provide_ixfr = ns_g_server->provide_ixfr;
		if (peer != NULL)
			(void) dns_peer_getprovideixfr(peer, &provide_ixfr);
		if (provide_ixfr == ISC_FALSE)
			goto axfr_fallback;
		
		if (! have_soa)
			FAILC(DNS_R_FORMERR,
			      "IXFR request missing SOA");

		begin_serial = dns_soa_getserial(&soa_rdata);
		current_serial = dns_soa_getserial(&current_soa_tuple->rdata);

		/*
		 * RFC1995 says "If an IXFR query with the same or
		 * newer version number than that of the server 
		 * is received, it is replied to with a single SOA 
		 * record of the server's current version, just as
		 * in AXFR".  The claim about AXFR is incorrect,
		 * but other than that, we do as the RFC says.
		 *
		 * Sending a single SOA record is also how we refuse 
		 * IXFR over UDP (currently, we always do).
		 */
		if (DNS_SERIAL_GE(begin_serial, current_serial) ||
		    (client->attributes & NS_CLIENTATTR_TCP) == 0)
	        {
			CHECK(soa_rrstream_create(mctx, db, ver, &stream));
			goto have_stream;
		}
		result = ixfr_rrstream_create(mctx,
					      dns_zone_getjournal(zone),
					      begin_serial,
					      current_serial,
					      &data_stream);
		if (result == ISC_R_NOTFOUND ||
		    result == DNS_R_RANGE) {
			isc_log_write(XFROUT_DEBUG_LOGARGS(4),
				      "IXFR version not in journal, "
				      "falling back to AXFR");
			goto axfr_fallback;
		}
		CHECK(result);
	} else {
	axfr_fallback:
		CHECK(axfr_rrstream_create(mctx, db, ver,
					   &data_stream));
	}

	/* Bracket the the data stream with SOAs. */
	CHECK(soa_rrstream_create(mctx, db, ver, &soa_stream));
	CHECK(compound_rrstream_create(mctx, &soa_stream, &data_stream,
				       &stream));
	soa_stream = NULL;
	data_stream = NULL;

 have_stream:
	/*
	 * Create the xfrout context object.  This transfers the ownership
	 * of "stream", "db", "ver", and "quota" to the xfrout context object.
	 */
	CHECK(xfrout_ctx_create(mctx, client, request->id, question_name, 
				reqtype, db, ver, quota, stream,
				request->tsigkey, request->tsig,
				dns_zone_getmaxxfrout(zone),
				dns_zone_getidleout(zone),
				(format == dns_many_answers) ?
					ISC_TRUE : ISC_FALSE,
				&xfr));
	stream = NULL;
	db = NULL;
	ver = NULL;
	quota = NULL;
	
	CHECK(xfr->stream->methods->first(xfr->stream));

	/*
	 * Hand the context over to sendstream().  Set xfr to NULL;
	 * sendstream() is responsible for either passing the
	 * context on to a later event handler or destroying it.
	 */
	sendstream(xfr);
	xfr = NULL;
	
	result = DNS_R_SUCCESS;

 failure:
	if (quota != NULL)
		isc_quota_detach(&quota);
	if (current_soa_tuple != NULL)
		dns_difftuple_free(&current_soa_tuple);
	if (stream != NULL)
		stream->methods->destroy(&stream);
	if (soa_stream != NULL)
		soa_stream->methods->destroy(&soa_stream);
	if (data_stream != NULL)
		data_stream->methods->destroy(&data_stream);
	if (ver != NULL)
		dns_db_closeversion(db, &ver, ISC_FALSE);
	if (db != NULL)
		dns_db_detach(&db);
	if (zone != NULL)
		dns_zone_detach(&zone);
	/* XXX kludge */
	if (xfr != NULL) {
		xfrout_fail(xfr, result, "setting up zone transfer");
	} else if (result != DNS_R_SUCCESS) {
		isc_log_write(XFROUT_DEBUG_LOGARGS(3),
			      "zone transfer setup failed"); 
		ns_client_error(client, result);
	}
}




static isc_result_t
xfrout_ctx_create(isc_mem_t *mctx, ns_client_t *client, unsigned int id,
		  dns_name_t *qname, dns_rdatatype_t qtype,
		  dns_db_t *db, dns_dbversion_t *ver, isc_quota_t *quota,
		  rrstream_t *stream, dns_tsigkey_t *tsigkey,
		  dns_rdata_any_tsig_t *lasttsig, unsigned int maxtime,
		  unsigned int idletime, isc_boolean_t many_answers,
		  xfrout_ctx_t **xfrp)
{
	xfrout_ctx_t *xfr;
	isc_result_t result;
	unsigned int len;
	void *mem;
	isc_interval_t maxinterval, idleinterval;
	isc_time_t expires;
	
	INSIST(xfrp != NULL && *xfrp == NULL);
	xfr = isc_mem_get(mctx, sizeof(*xfr));
	if (xfr == NULL)
		return (DNS_R_NOMEMORY);
	xfr->mctx = mctx;
	xfr->client = NULL;
	ns_client_attach(client, &xfr->client);
	xfr->id = id;
	xfr->qname = qname;
	xfr->qtype = qtype;
	xfr->db = db;
	xfr->ver = ver;
	xfr->quota = quota;
	xfr->stream = stream;
	xfr->end_of_stream = ISC_FALSE;
	xfr->tsigkey = tsigkey;
	xfr->lasttsig = lasttsig;
	xfr->txmem = NULL;
	xfr->txmemlen = 0;
	xfr->nmsg = 0;
	xfr->many_answers = many_answers,
	xfr->sends = 0;
	xfr->shuttingdown = ISC_FALSE;
	
	/*
	 * Allocate a temporary buffer for the uncompressed response
	 * message data.  The size should be no more than 65535 bytes
	 * so that the compressed data will fit in a TCP message,
	 * and no less than 65535 bytes so that an almost maximum-sized
	 * RR will fit.  Note that although 65535-byte RRs are allowed
	 * in principle, they cannot be zone-transferred (at least not
	 * if uncompressible), because the message and RR headers would
	 * push the size of the TCP message over the 65536 byte limit.
	 */
	len = 65535;
	mem = isc_mem_get(mctx, len);
	if (mem == NULL) {
		result = DNS_R_NOMEMORY;
		goto failure;
	}
	isc_buffer_init(&xfr->buf, mem, len, ISC_BUFFERTYPE_BINARY);

	/*
	 * Allocate another temporary buffer for the compressed
	 * response message and its TCP length prefix.
	 */
	len = 2 + 65535;
	mem = isc_mem_get(mctx, len);
	if (mem == NULL) {
		result = DNS_R_NOMEMORY;
		goto failure;
	}
	isc_buffer_init(&xfr->txlenbuf, mem, 2, ISC_BUFFERTYPE_BINARY);
	isc_buffer_init(&xfr->txbuf, (char *) mem + 2, len - 2,
			ISC_BUFFERTYPE_BINARY);
	xfr->txmem = mem;
	xfr->txmemlen = len;

	isc_interval_set(&maxinterval, maxtime, 0);
	CHECK(isc_time_nowplusinterval(&expires, &maxinterval));
	isc_interval_set(&idleinterval, idletime, 0);

	CHECK(isc_timer_reset(xfr->client->timer,
			      isc_timertype_once,
			      &expires, &idleinterval,
			      ISC_FALSE));

	/*
	 * Register a shutdown callback with the client, so that we
	 * can stop the transfer immediately when the client task
	 * gets a shutdown event.
	 */
	xfr->client->shutdown = xfrout_client_shutdown;
	xfr->client->shutdown_arg = xfr;
		
	*xfrp = xfr;
	return (DNS_R_SUCCESS);
	
failure:
	xfrout_ctx_destroy(&xfr);
	return (result);
}


/*
 * Arrange to send as much as we can of "stream" without blocking.
 *
 * Requires:
 *	The stream iterator is initialized and points at an RR,
 *      or possiby at the end of the stream (that is, the 
 *      _first method of the iterator has been called).
 */
static void
sendstream(xfrout_ctx_t *xfr)
{
	dns_message_t *msg = NULL;
	isc_result_t result;
	isc_region_t used;
	isc_region_t region;
	dns_rdataset_t *qrdataset;
	int n_rrs;

	isc_buffer_clear(&xfr->buf);
	isc_buffer_clear(&xfr->txlenbuf);
	isc_buffer_clear(&xfr->txbuf);

	/*
	 * Build a response dns_message_t, temporarily storing the raw, 
	 * uncompressed owner names and RR data contiguously in xfr->buf.
	 * We know that if the uncompressed data fits in xfr->buf,
	 * the compressed data will surely fit in a TCP message.
	 */

	msg = NULL;
	CHECK(dns_message_create(xfr->mctx, DNS_MESSAGE_INTENTRENDER, &msg));

	msg->id = xfr->id;
	msg->rcode = dns_rcode_noerror;
	msg->flags = DNS_MESSAGEFLAG_QR | DNS_MESSAGEFLAG_AA;
	if ((xfr->client->attributes & NS_CLIENTATTR_RA) != 0)
		msg->flags |= DNS_MESSAGEFLAG_RA;
	msg->tsigkey = xfr->tsigkey;
	msg->querytsig = xfr->lasttsig;

	/*
	 * Include a question section in the first message only. 
	 * BIND 8.2.1 will not recognize an IXFR if it does not have a
	 * question section.
	 */
	if (xfr->nmsg == 0) {
		dns_name_t *qname = NULL;
		isc_region_t r;

		/*
		 * Reserve space for the 12-byte message header
		 * and 4 bytes of question.
		 */
		isc_buffer_add(&xfr->buf, 12 + 4);
		
		qrdataset = NULL;
		result = dns_message_gettemprdataset(msg, &qrdataset);
		if (result != ISC_R_SUCCESS)
			goto failure;
		dns_rdataset_init(qrdataset);
		dns_rdataset_makequestion(qrdataset,
					  xfr->client->message->rdclass,
					  xfr->qtype);

		result = dns_message_gettempname(msg, &qname);
		if (result != ISC_R_SUCCESS)
			goto failure;
		dns_name_init(qname, NULL);
		isc_buffer_available(&xfr->buf, &r);
		INSIST(r.length >= xfr->qname->length);
		r.length = xfr->qname->length;
		isc_buffer_putmem(&xfr->buf, xfr->qname->ndata,
				  xfr->qname->length);
		dns_name_fromregion(qname, &r);
		ISC_LIST_INIT(qname->list);
		ISC_LIST_APPEND(qname->list, qrdataset, link);

		dns_message_addname(msg, qname, DNS_SECTION_QUESTION);
	}
	else
		msg->tcp_continuation = 1;
	
	/*
	 * Try to fit in as many RRs as possible, unless "one-answer"
	 * format has been requested.
	 */
	for (n_rrs = 0; ; n_rrs++) {
		dns_name_t *name = NULL;
		isc_uint32_t ttl;
		dns_rdata_t *rdata = NULL;
		
		dns_name_t *msgname = NULL;
		dns_rdata_t *msgrdata = NULL;
		dns_rdatalist_t *msgrdl = NULL;
		dns_rdataset_t *msgrds = NULL;
		
		unsigned int size;
		isc_region_t r;

		xfr->stream->methods->current(xfr->stream,
					      &name, &ttl, &rdata);
		size = name->length + 10 + rdata->length;
		isc_buffer_available(&xfr->buf, &r);
		if (size >= r.length) {
			/*
			 * RR would not fit.  If there are other RRs in the 
			 * buffer, send them now and leave this RR to the 
			 * next message.  If this RR overflows the buffer
			 * all by itself, fail.
			 *
			 * In theory some RRs might fit in a TCP message 
			 * when compressed even if they do not fit when
			 * uncompressed, but surely we don't want
			 * to send such monstrosities to an unsuspecting
			 * slave.
			 */
			if (n_rrs == 0) {
				isc_log_write(XFROUT_COMMON_LOGARGS,
					      ISC_LOG_WARNING,
					      "RR too large for zone transfer "
					      "(%d bytes)", size);
				/* XXX DNS_R_RRTOOLARGE? */
				result = ISC_R_NOSPACE;
				goto failure;
			}
			break;
		}

		log_rr(name, rdata, ttl); /* XXX */
		
		dns_message_gettempname(msg, &msgname);
		dns_name_init(msgname, NULL);
		isc_buffer_available(&xfr->buf, &r);
		INSIST(r.length >= name->length);
		r.length = name->length;
		isc_buffer_putmem(&xfr->buf, name->ndata, name->length);
		dns_name_fromregion(msgname, &r);

		/* Reserve space for RR header. */
		isc_buffer_add(&xfr->buf, 10);
		
		dns_message_gettemprdata(msg, &msgrdata);
		isc_buffer_available(&xfr->buf, &r);
		r.length = rdata->length;
		isc_buffer_putmem(&xfr->buf, rdata->data, rdata->length);
		dns_rdata_init(msgrdata);
		dns_rdata_fromregion(msgrdata,
				     rdata->rdclass, rdata->type, &r);

		dns_message_gettemprdatalist(msg, &msgrdl);
		msgrdl->type = rdata->type;
		msgrdl->rdclass = rdata->rdclass;
		msgrdl->ttl = ttl;
		ISC_LIST_INIT(msgrdl->rdata);
		ISC_LINK_INIT(msgrdl, link);
		ISC_LIST_APPEND(msgrdl->rdata, msgrdata, link);

		dns_message_gettemprdataset(msg, &msgrds);
		dns_rdataset_init(msgrds);
		result = dns_rdatalist_tordataset(msgrdl, msgrds);
		INSIST(result == DNS_R_SUCCESS);

		ISC_LIST_APPEND(msgname->list, msgrds, link);

		dns_message_addname(msg, msgname, DNS_SECTION_ANSWER);

		result = xfr->stream->methods->next(xfr->stream);
		if (result == DNS_R_NOMORE) {
			xfr->end_of_stream = ISC_TRUE;
			break;
		}
		CHECK(result);

		if (! xfr->many_answers)
			break;
	}

	if ((xfr->client->attributes & NS_CLIENTATTR_TCP) != 0) {
		CHECK(dns_message_renderbegin(msg, &xfr->txbuf));
		CHECK(dns_message_rendersection(msg, DNS_SECTION_QUESTION, 0));
		CHECK(dns_message_rendersection(msg, DNS_SECTION_ANSWER, 0));
		CHECK(dns_message_renderend(msg));
		
		isc_buffer_used(&xfr->txbuf, &used);
		isc_buffer_putuint16(&xfr->txlenbuf, used.length);
		region.base = xfr->txlenbuf.base;
		region.length = 2 + used.length;
		isc_log_write(XFROUT_DEBUG_LOGARGS(8),
			      "sending zone transfer TCP message of %d bytes",
			      used.length);
		CHECK(isc_socket_send(xfr->client->tcpsocket, /* XXX */
				      &region, xfr->client->task,
				      xfrout_senddone,
				      xfr));
		xfr->sends++;
	} else {
		isc_log_write(XFROUT_DEBUG_LOGARGS(8),
			      "sending IXFR UDP response");
		/* XXX kludge */
		dns_message_destroy(&xfr->client->message);
		xfr->client->message = msg;
		msg = NULL;
		ns_client_send(xfr->client);
		xfrout_ctx_destroy(&xfr);
		return;
	}

	/* Advance lasttsig to be the last TSIG generated */
	xfr->lasttsig = msg->tsig;

	/* Clear this field so the TSIG is not destroyed */
	msg->tsig = NULL;

	/*
	 * If this is the first message, clear this too, since this is
	 * also pointed to by the request.
	 */
	if (xfr->nmsg == 0)
		msg->querytsig = NULL;

	xfr->nmsg++;

 failure:
	/*
	 * XXXRTH  need to cleanup qname and qrdataset...
	 */
	if (msg != NULL) {
		dns_message_destroy(&msg);
	}
	if (result == DNS_R_SUCCESS)
		return;

	xfrout_fail(xfr, result, "sending zone data");
}

static void
xfrout_ctx_destroy(xfrout_ctx_t **xfrp) {
	xfrout_ctx_t *xfr = *xfrp;

	INSIST(xfr->sends == 0);

	xfr->client->shutdown = NULL;
	xfr->client->shutdown_arg = NULL;

	if (xfr->stream != NULL)
		xfr->stream->methods->destroy(&xfr->stream);
	if (xfr->buf.base != NULL)
		isc_mem_put(xfr->mctx, xfr->buf.base, xfr->buf.length);
	if (xfr->txmem != NULL)
		isc_mem_put(xfr->mctx, xfr->txmem, xfr->txmemlen);
	if (xfr->lasttsig != NULL) {
		dns_rdata_freestruct(xfr->lasttsig);
		isc_mem_put(xfr->mctx, xfr->lasttsig, sizeof(*xfr->lasttsig));
	}
	if (xfr->quota != NULL)
		isc_quota_detach(&xfr->quota);		
	if (xfr->ver != NULL) 
		dns_db_closeversion(xfr->db, &xfr->ver, ISC_FALSE);
	if (xfr->db != NULL)
		dns_db_detach(&xfr->db);

	ns_client_detach(&xfr->client);

	isc_mem_put(xfr->mctx, xfr, sizeof(*xfr));

	*xfrp = NULL;
}

static void
xfrout_senddone(isc_task_t *task, isc_event_t *event) {
	isc_socketevent_t *sev = (isc_socketevent_t *) event;	
	xfrout_ctx_t *xfr = (xfrout_ctx_t *) event->arg;
	isc_result_t evresult = sev->result;
	UNUSED(task);
	INSIST(event->type == ISC_SOCKEVENT_SENDDONE);
	isc_event_free(&event);
	xfr->sends--;
	INSIST(xfr->sends == 0);
	(void) isc_timer_touch(xfr->client->timer);
	if (xfr->shuttingdown == ISC_TRUE) {
		xfrout_maybe_destroy(xfr);
	} else if (evresult != ISC_R_SUCCESS) {
		xfrout_fail(xfr, evresult, "send");
	} else if (xfr->end_of_stream == ISC_FALSE) {
		sendstream(xfr);
	} else {
		/* End of zone transfer stream. */
		isc_log_write(XFROUT_DEBUG_LOGARGS(6),
			      "end of outgoing zone transfer");
		ns_client_next(xfr->client, DNS_R_SUCCESS);
		xfrout_ctx_destroy(&xfr);
	}
}

static void
xfrout_fail(xfrout_ctx_t *xfr, isc_result_t result, char *msg)
{
	xfr->shuttingdown = ISC_TRUE;
	isc_log_write(XFROUT_COMMON_LOGARGS, ISC_LOG_ERROR,
		      "outgoing zone transfer: %s: %s",
		      msg, isc_result_totext(result));
	xfrout_maybe_destroy(xfr);
}

static void
xfrout_maybe_destroy(xfrout_ctx_t *xfr) {
	INSIST(xfr->shuttingdown == ISC_TRUE);
	if (xfr->sends > 0) {
		/*
		 * If we are currently sending, cancel it and wait for
		 * cancel event before destroying the context.
		 */
		isc_socket_cancel(xfr->client->tcpsocket, xfr->client->task,
				  ISC_SOCKCANCEL_SEND);
	} else {
		ns_client_next(xfr->client, ISC_R_CANCELED);
		xfrout_ctx_destroy(&xfr);
	}
}

static void
xfrout_client_shutdown(void *arg, isc_result_t result)
{
	xfrout_ctx_t *xfr = (xfrout_ctx_t *) arg;
	xfrout_fail(xfr, result, "aborted");
}