Home | History | Annotate | Line # | Download | only in dns
xfrin.c revision 1.15
      1 /*	$NetBSD: xfrin.c,v 1.15 2024/09/22 00:14:06 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
      5  *
      6  * SPDX-License-Identifier: MPL-2.0
      7  *
      8  * This Source Code Form is subject to the terms of the Mozilla Public
      9  * License, v. 2.0. If a copy of the MPL was not distributed with this
     10  * file, you can obtain one at https://mozilla.org/MPL/2.0/.
     11  *
     12  * See the COPYRIGHT file distributed with this work for additional
     13  * information regarding copyright ownership.
     14  */
     15 
     16 /*! \file */
     17 
     18 #include <inttypes.h>
     19 #include <stdbool.h>
     20 
     21 #include <isc/mem.h>
     22 #include <isc/netmgr.h>
     23 #include <isc/print.h>
     24 #include <isc/random.h>
     25 #include <isc/result.h>
     26 #include <isc/string.h> /* Required for HP/UX (and others?) */
     27 #include <isc/task.h>
     28 #include <isc/timer.h>
     29 #include <isc/util.h>
     30 
     31 #include <dns/callbacks.h>
     32 #include <dns/catz.h>
     33 #include <dns/db.h>
     34 #include <dns/diff.h>
     35 #include <dns/events.h>
     36 #include <dns/journal.h>
     37 #include <dns/log.h>
     38 #include <dns/message.h>
     39 #include <dns/rdataclass.h>
     40 #include <dns/rdatalist.h>
     41 #include <dns/rdataset.h>
     42 #include <dns/result.h>
     43 #include <dns/soa.h>
     44 #include <dns/transport.h>
     45 #include <dns/tsig.h>
     46 #include <dns/view.h>
     47 #include <dns/xfrin.h>
     48 #include <dns/zone.h>
     49 
     50 #include <dst/dst.h>
     51 
     52 /*
     53  * Incoming AXFR and IXFR.
     54  */
     55 
     56 /*%
     57  * It would be non-sensical (or at least obtuse) to use FAIL() with an
     58  * ISC_R_SUCCESS code, but the test is there to keep the Solaris compiler
     59  * from complaining about "end-of-loop code not reached".
     60  */
     61 #define FAIL(code)                           \
     62 	do {                                 \
     63 		result = (code);             \
     64 		if (result != ISC_R_SUCCESS) \
     65 			goto failure;        \
     66 	} while (0)
     67 
     68 #define CHECK(op)                            \
     69 	do {                                 \
     70 		result = (op);               \
     71 		if (result != ISC_R_SUCCESS) \
     72 			goto failure;        \
     73 	} while (0)
     74 
     75 /*%
     76  * The states of the *XFR state machine.  We handle both IXFR and AXFR
     77  * with a single integrated state machine because they cannot be distinguished
     78  * immediately - an AXFR response to an IXFR request can only be detected
     79  * when the first two (2) response RRs have already been received.
     80  */
     81 typedef enum {
     82 	XFRST_SOAQUERY,
     83 	XFRST_GOTSOA,
     84 	XFRST_INITIALSOA,
     85 	XFRST_FIRSTDATA,
     86 	XFRST_IXFR_DELSOA,
     87 	XFRST_IXFR_DEL,
     88 	XFRST_IXFR_ADDSOA,
     89 	XFRST_IXFR_ADD,
     90 	XFRST_IXFR_END,
     91 	XFRST_AXFR,
     92 	XFRST_AXFR_END
     93 } xfrin_state_t;
     94 
     95 /*%
     96  * Incoming zone transfer context.
     97  */
     98 
     99 struct dns_xfrin_ctx {
    100 	unsigned int magic;
    101 	isc_mem_t *mctx;
    102 	dns_zone_t *zone;
    103 
    104 	isc_refcount_t references;
    105 
    106 	isc_nm_t *netmgr;
    107 
    108 	isc_refcount_t connects; /*%< Connect in progress */
    109 	isc_refcount_t sends;	 /*%< Send in progress */
    110 	isc_refcount_t recvs;	 /*%< Receive in progress */
    111 
    112 	atomic_bool shuttingdown;
    113 
    114 	isc_result_t shutdown_result;
    115 
    116 	dns_name_t name; /*%< Name of zone to transfer */
    117 	dns_rdataclass_t rdclass;
    118 
    119 	dns_messageid_t id;
    120 
    121 	/*%
    122 	 * Requested transfer type (dns_rdatatype_axfr or
    123 	 * dns_rdatatype_ixfr).  The actual transfer type
    124 	 * may differ due to IXFR->AXFR fallback.
    125 	 */
    126 	dns_rdatatype_t reqtype;
    127 
    128 	isc_sockaddr_t primaryaddr;
    129 	isc_sockaddr_t sourceaddr;
    130 
    131 	isc_nmhandle_t *handle;
    132 	isc_nmhandle_t *readhandle;
    133 	isc_nmhandle_t *sendhandle;
    134 
    135 	/*% Buffer for IXFR/AXFR request message */
    136 	isc_buffer_t qbuffer;
    137 	unsigned char qbuffer_data[512];
    138 
    139 	/*%
    140 	 * Whether the zone originally had a database attached at the time this
    141 	 * transfer context was created.  Used by xfrin_destroy() when making
    142 	 * logging decisions.
    143 	 */
    144 	bool zone_had_db;
    145 
    146 	dns_db_t *db;
    147 	dns_dbversion_t *ver;
    148 	dns_diff_t diff; /*%< Pending database changes */
    149 	int difflen;	 /*%< Number of pending tuples */
    150 
    151 	xfrin_state_t state;
    152 	uint32_t end_serial;
    153 	bool is_ixfr;
    154 
    155 	unsigned int nmsg;  /*%< Number of messages recvd */
    156 	unsigned int nrecs; /*%< Number of records recvd */
    157 	uint64_t nbytes;    /*%< Number of bytes received */
    158 
    159 	unsigned int maxrecords; /*%< The maximum number of
    160 				  *   records set for the zone */
    161 
    162 	isc_time_t start; /*%< Start time of the transfer */
    163 	isc_time_t end;	  /*%< End time of the transfer */
    164 
    165 	dns_tsigkey_t *tsigkey; /*%< Key used to create TSIG */
    166 	isc_buffer_t *lasttsig; /*%< The last TSIG */
    167 	dst_context_t *tsigctx; /*%< TSIG verification context */
    168 	unsigned int sincetsig; /*%< recvd since the last TSIG */
    169 
    170 	dns_transport_t *transport;
    171 
    172 	dns_xfrindone_t done;
    173 
    174 	/*%
    175 	 * AXFR- and IXFR-specific data.  Only one is used at a time
    176 	 * according to the is_ixfr flag, so this could be a union,
    177 	 * but keeping them separate makes it a bit simpler to clean
    178 	 * things up when destroying the context.
    179 	 */
    180 	dns_rdatacallbacks_t axfr;
    181 
    182 	struct {
    183 		uint32_t request_serial;
    184 		uint32_t current_serial;
    185 		dns_journal_t *journal;
    186 	} ixfr;
    187 
    188 	dns_rdata_t firstsoa;
    189 	unsigned char *firstsoa_data;
    190 
    191 	isc_tlsctx_cache_t *tlsctx_cache;
    192 
    193 	isc_timer_t *max_time_timer;
    194 	isc_timer_t *max_idle_timer;
    195 };
    196 
    197 #define XFRIN_MAGIC    ISC_MAGIC('X', 'f', 'r', 'I')
    198 #define VALID_XFRIN(x) ISC_MAGIC_VALID(x, XFRIN_MAGIC)
    199 
    200 /**************************************************************************/
    201 /*
    202  * Forward declarations.
    203  */
    204 
    205 static void
    206 xfrin_create(isc_mem_t *mctx, dns_zone_t *zone, dns_db_t *db, isc_nm_t *netmgr,
    207 	     dns_name_t *zonename, dns_rdataclass_t rdclass,
    208 	     dns_rdatatype_t reqtype, const isc_sockaddr_t *primaryaddr,
    209 	     const isc_sockaddr_t *sourceaddr, dns_tsigkey_t *tsigkey,
    210 	     dns_transport_t *transport, isc_tlsctx_cache_t *tlsctx_cache,
    211 	     dns_xfrin_ctx_t **xfrp);
    212 
    213 static isc_result_t
    214 axfr_init(dns_xfrin_ctx_t *xfr);
    215 static isc_result_t
    216 axfr_putdata(dns_xfrin_ctx_t *xfr, dns_diffop_t op, dns_name_t *name,
    217 	     dns_ttl_t ttl, dns_rdata_t *rdata);
    218 static isc_result_t
    219 axfr_apply(dns_xfrin_ctx_t *xfr);
    220 static isc_result_t
    221 axfr_commit(dns_xfrin_ctx_t *xfr);
    222 static isc_result_t
    223 axfr_finalize(dns_xfrin_ctx_t *xfr);
    224 
    225 static isc_result_t
    226 ixfr_init(dns_xfrin_ctx_t *xfr);
    227 static isc_result_t
    228 ixfr_apply(dns_xfrin_ctx_t *xfr);
    229 static isc_result_t
    230 ixfr_putdata(dns_xfrin_ctx_t *xfr, dns_diffop_t op, dns_name_t *name,
    231 	     dns_ttl_t ttl, dns_rdata_t *rdata);
    232 static isc_result_t
    233 ixfr_commit(dns_xfrin_ctx_t *xfr);
    234 
    235 static isc_result_t
    236 xfr_rr(dns_xfrin_ctx_t *xfr, dns_name_t *name, uint32_t ttl,
    237        dns_rdata_t *rdata);
    238 
    239 static isc_result_t
    240 xfrin_start(dns_xfrin_ctx_t *xfr);
    241 
    242 static void
    243 xfrin_connect_done(isc_nmhandle_t *handle, isc_result_t result, void *cbarg);
    244 static isc_result_t
    245 xfrin_send_request(dns_xfrin_ctx_t *xfr);
    246 static void
    247 xfrin_send_done(isc_nmhandle_t *handle, isc_result_t result, void *cbarg);
    248 static void
    249 xfrin_recv_done(isc_nmhandle_t *handle, isc_result_t result,
    250 		isc_region_t *region, void *cbarg);
    251 
    252 static void
    253 xfrin_destroy(dns_xfrin_ctx_t *xfr);
    254 
    255 static void
    256 xfrin_timedout(struct isc_task *, struct isc_event *);
    257 static void
    258 xfrin_idledout(struct isc_task *, struct isc_event *);
    259 static void
    260 xfrin_fail(dns_xfrin_ctx_t *xfr, isc_result_t result, const char *msg);
    261 static isc_result_t
    262 render(dns_message_t *msg, isc_mem_t *mctx, isc_buffer_t *buf);
    263 
    264 static void
    265 xfrin_logv(int level, const char *zonetext, const isc_sockaddr_t *primaryaddr,
    266 	   const char *fmt, va_list ap) ISC_FORMAT_PRINTF(4, 0);
    267 
    268 static void
    269 xfrin_log1(int level, const char *zonetext, const isc_sockaddr_t *primaryaddr,
    270 	   const char *fmt, ...) ISC_FORMAT_PRINTF(4, 5);
    271 
    272 static void
    273 xfrin_log(dns_xfrin_ctx_t *xfr, int level, const char *fmt, ...)
    274 	ISC_FORMAT_PRINTF(3, 4);
    275 
    276 /**************************************************************************/
    277 /*
    278  * AXFR handling
    279  */
    280 
    281 static isc_result_t
    282 axfr_init(dns_xfrin_ctx_t *xfr) {
    283 	isc_result_t result;
    284 
    285 	xfr->is_ixfr = false;
    286 
    287 	if (xfr->db != NULL) {
    288 		dns_db_detach(&xfr->db);
    289 	}
    290 
    291 	CHECK(dns_zone_makedb(xfr->zone, &xfr->db));
    292 
    293 	dns_zone_rpz_enable_db(xfr->zone, xfr->db);
    294 	dns_zone_catz_enable_db(xfr->zone, xfr->db);
    295 
    296 	dns_rdatacallbacks_init(&xfr->axfr);
    297 	CHECK(dns_db_beginload(xfr->db, &xfr->axfr));
    298 	result = ISC_R_SUCCESS;
    299 failure:
    300 	return (result);
    301 }
    302 
    303 static isc_result_t
    304 axfr_putdata(dns_xfrin_ctx_t *xfr, dns_diffop_t op, dns_name_t *name,
    305 	     dns_ttl_t ttl, dns_rdata_t *rdata) {
    306 	isc_result_t result;
    307 
    308 	dns_difftuple_t *tuple = NULL;
    309 
    310 	if (rdata->rdclass != xfr->rdclass) {
    311 		return (DNS_R_BADCLASS);
    312 	}
    313 
    314 	CHECK(dns_zone_checknames(xfr->zone, name, rdata));
    315 	CHECK(dns_difftuple_create(xfr->diff.mctx, op, name, ttl, rdata,
    316 				   &tuple));
    317 	dns_diff_append(&xfr->diff, &tuple);
    318 	if (++xfr->difflen > 100) {
    319 		CHECK(axfr_apply(xfr));
    320 	}
    321 	result = ISC_R_SUCCESS;
    322 failure:
    323 	return (result);
    324 }
    325 
    326 /*
    327  * Store a set of AXFR RRs in the database.
    328  */
    329 static isc_result_t
    330 axfr_apply(dns_xfrin_ctx_t *xfr) {
    331 	isc_result_t result;
    332 	uint64_t records;
    333 
    334 	CHECK(dns_diff_load(&xfr->diff, xfr->axfr.add, xfr->axfr.add_private));
    335 	xfr->difflen = 0;
    336 	dns_diff_clear(&xfr->diff);
    337 	if (xfr->maxrecords != 0U) {
    338 		result = dns_db_getsize(xfr->db, xfr->ver, &records, NULL);
    339 		if (result == ISC_R_SUCCESS && records > xfr->maxrecords) {
    340 			result = DNS_R_TOOMANYRECORDS;
    341 			goto failure;
    342 		}
    343 	}
    344 	result = ISC_R_SUCCESS;
    345 failure:
    346 	return (result);
    347 }
    348 
    349 static isc_result_t
    350 axfr_commit(dns_xfrin_ctx_t *xfr) {
    351 	isc_result_t result;
    352 
    353 	CHECK(axfr_apply(xfr));
    354 	CHECK(dns_db_endload(xfr->db, &xfr->axfr));
    355 	CHECK(dns_zone_verifydb(xfr->zone, xfr->db, NULL));
    356 
    357 	result = ISC_R_SUCCESS;
    358 failure:
    359 	return (result);
    360 }
    361 
    362 static isc_result_t
    363 axfr_finalize(dns_xfrin_ctx_t *xfr) {
    364 	isc_result_t result;
    365 
    366 	CHECK(dns_zone_replacedb(xfr->zone, xfr->db, true));
    367 
    368 	result = ISC_R_SUCCESS;
    369 failure:
    370 	return (result);
    371 }
    372 
    373 /**************************************************************************/
    374 /*
    375  * IXFR handling
    376  */
    377 
    378 static isc_result_t
    379 ixfr_init(dns_xfrin_ctx_t *xfr) {
    380 	isc_result_t result;
    381 	char *journalfile = NULL;
    382 
    383 	if (xfr->reqtype != dns_rdatatype_ixfr) {
    384 		xfrin_log(xfr, ISC_LOG_NOTICE,
    385 			  "got incremental response to AXFR request");
    386 		return (DNS_R_FORMERR);
    387 	}
    388 
    389 	xfr->is_ixfr = true;
    390 	INSIST(xfr->db != NULL);
    391 	xfr->difflen = 0;
    392 
    393 	journalfile = dns_zone_getjournal(xfr->zone);
    394 	if (journalfile != NULL) {
    395 		CHECK(dns_journal_open(xfr->mctx, journalfile,
    396 				       DNS_JOURNAL_CREATE, &xfr->ixfr.journal));
    397 	}
    398 
    399 	result = ISC_R_SUCCESS;
    400 failure:
    401 	return (result);
    402 }
    403 
    404 static isc_result_t
    405 ixfr_putdata(dns_xfrin_ctx_t *xfr, dns_diffop_t op, dns_name_t *name,
    406 	     dns_ttl_t ttl, dns_rdata_t *rdata) {
    407 	isc_result_t result;
    408 	dns_difftuple_t *tuple = NULL;
    409 
    410 	if (rdata->rdclass != xfr->rdclass) {
    411 		return (DNS_R_BADCLASS);
    412 	}
    413 
    414 	if (op == DNS_DIFFOP_ADD) {
    415 		CHECK(dns_zone_checknames(xfr->zone, name, rdata));
    416 	}
    417 	CHECK(dns_difftuple_create(xfr->diff.mctx, op, name, ttl, rdata,
    418 				   &tuple));
    419 	dns_diff_append(&xfr->diff, &tuple);
    420 	if (++xfr->difflen > 100) {
    421 		CHECK(ixfr_apply(xfr));
    422 	}
    423 	result = ISC_R_SUCCESS;
    424 failure:
    425 	return (result);
    426 }
    427 
    428 /*
    429  * Apply a set of IXFR changes to the database.
    430  */
    431 static isc_result_t
    432 ixfr_apply(dns_xfrin_ctx_t *xfr) {
    433 	isc_result_t result;
    434 	uint64_t records;
    435 
    436 	if (xfr->ver == NULL) {
    437 		CHECK(dns_db_newversion(xfr->db, &xfr->ver));
    438 		if (xfr->ixfr.journal != NULL) {
    439 			CHECK(dns_journal_begin_transaction(xfr->ixfr.journal));
    440 		}
    441 	}
    442 	CHECK(dns_diff_apply(&xfr->diff, xfr->db, xfr->ver));
    443 	if (xfr->maxrecords != 0U) {
    444 		result = dns_db_getsize(xfr->db, xfr->ver, &records, NULL);
    445 		if (result == ISC_R_SUCCESS && records > xfr->maxrecords) {
    446 			result = DNS_R_TOOMANYRECORDS;
    447 			goto failure;
    448 		}
    449 	}
    450 	if (xfr->ixfr.journal != NULL) {
    451 		result = dns_journal_writediff(xfr->ixfr.journal, &xfr->diff);
    452 		if (result != ISC_R_SUCCESS) {
    453 			goto failure;
    454 		}
    455 	}
    456 	dns_diff_clear(&xfr->diff);
    457 	xfr->difflen = 0;
    458 	result = ISC_R_SUCCESS;
    459 failure:
    460 	return (result);
    461 }
    462 
    463 static isc_result_t
    464 ixfr_commit(dns_xfrin_ctx_t *xfr) {
    465 	isc_result_t result;
    466 
    467 	CHECK(ixfr_apply(xfr));
    468 	if (xfr->ver != NULL) {
    469 		CHECK(dns_zone_verifydb(xfr->zone, xfr->db, xfr->ver));
    470 		/* XXX enter ready-to-commit state here */
    471 		if (xfr->ixfr.journal != NULL) {
    472 			CHECK(dns_journal_commit(xfr->ixfr.journal));
    473 		}
    474 		dns_db_closeversion(xfr->db, &xfr->ver, true);
    475 		dns_zone_markdirty(xfr->zone);
    476 	}
    477 	result = ISC_R_SUCCESS;
    478 failure:
    479 	return (result);
    480 }
    481 
    482 /**************************************************************************/
    483 /*
    484  * Common AXFR/IXFR protocol code
    485  */
    486 
    487 /*
    488  * Handle a single incoming resource record according to the current
    489  * state.
    490  */
    491 static isc_result_t
    492 xfr_rr(dns_xfrin_ctx_t *xfr, dns_name_t *name, uint32_t ttl,
    493        dns_rdata_t *rdata) {
    494 	isc_result_t result;
    495 
    496 	xfr->nrecs++;
    497 
    498 	if (rdata->type == dns_rdatatype_none ||
    499 	    dns_rdatatype_ismeta(rdata->type))
    500 	{
    501 		char buf[64];
    502 		dns_rdatatype_format(rdata->type, buf, sizeof(buf));
    503 		xfrin_log(xfr, ISC_LOG_NOTICE,
    504 			  "Unexpected %s record in zone transfer", buf);
    505 		FAIL(DNS_R_FORMERR);
    506 	}
    507 
    508 	/*
    509 	 * Immediately reject the entire transfer if the RR that is currently
    510 	 * being processed is an SOA record that is not placed at the zone
    511 	 * apex.
    512 	 */
    513 	if (rdata->type == dns_rdatatype_soa &&
    514 	    !dns_name_equal(&xfr->name, name))
    515 	{
    516 		char namebuf[DNS_NAME_FORMATSIZE];
    517 		dns_name_format(name, namebuf, sizeof(namebuf));
    518 		xfrin_log(xfr, ISC_LOG_DEBUG(3), "SOA name mismatch: '%s'",
    519 			  namebuf);
    520 		FAIL(DNS_R_NOTZONETOP);
    521 	}
    522 
    523 redo:
    524 	switch (xfr->state) {
    525 	case XFRST_SOAQUERY:
    526 		if (rdata->type != dns_rdatatype_soa) {
    527 			xfrin_log(xfr, ISC_LOG_NOTICE,
    528 				  "non-SOA response to SOA query");
    529 			FAIL(DNS_R_FORMERR);
    530 		}
    531 		xfr->end_serial = dns_soa_getserial(rdata);
    532 		if (!DNS_SERIAL_GT(xfr->end_serial, xfr->ixfr.request_serial) &&
    533 		    !dns_zone_isforced(xfr->zone))
    534 		{
    535 			xfrin_log(xfr, ISC_LOG_DEBUG(3),
    536 				  "requested serial %u, "
    537 				  "primary has %u, not updating",
    538 				  xfr->ixfr.request_serial, xfr->end_serial);
    539 			FAIL(DNS_R_UPTODATE);
    540 		}
    541 		xfr->state = XFRST_GOTSOA;
    542 		break;
    543 
    544 	case XFRST_GOTSOA:
    545 		/*
    546 		 * Skip other records in the answer section.
    547 		 */
    548 		break;
    549 
    550 	case XFRST_INITIALSOA:
    551 		if (rdata->type != dns_rdatatype_soa) {
    552 			xfrin_log(xfr, ISC_LOG_NOTICE,
    553 				  "first RR in zone transfer must be SOA");
    554 			FAIL(DNS_R_FORMERR);
    555 		}
    556 		/*
    557 		 * Remember the serial number in the initial SOA.
    558 		 * We need it to recognize the end of an IXFR.
    559 		 */
    560 		xfr->end_serial = dns_soa_getserial(rdata);
    561 		if (xfr->reqtype == dns_rdatatype_ixfr &&
    562 		    !DNS_SERIAL_GT(xfr->end_serial, xfr->ixfr.request_serial) &&
    563 		    !dns_zone_isforced(xfr->zone))
    564 		{
    565 			/*
    566 			 * This must be the single SOA record that is
    567 			 * sent when the current version on the primary
    568 			 * is not newer than the version in the request.
    569 			 */
    570 			xfrin_log(xfr, ISC_LOG_DEBUG(3),
    571 				  "requested serial %u, "
    572 				  "primary has %u, not updating",
    573 				  xfr->ixfr.request_serial, xfr->end_serial);
    574 			FAIL(DNS_R_UPTODATE);
    575 		}
    576 		xfr->firstsoa = *rdata;
    577 		if (xfr->firstsoa_data != NULL) {
    578 			isc_mem_free(xfr->mctx, xfr->firstsoa_data);
    579 		}
    580 		xfr->firstsoa_data = isc_mem_allocate(xfr->mctx, rdata->length);
    581 		memcpy(xfr->firstsoa_data, rdata->data, rdata->length);
    582 		xfr->firstsoa.data = xfr->firstsoa_data;
    583 		xfr->state = XFRST_FIRSTDATA;
    584 		break;
    585 
    586 	case XFRST_FIRSTDATA:
    587 		/*
    588 		 * If the transfer begins with one SOA record, it is an AXFR,
    589 		 * if it begins with two SOAs, it is an IXFR.
    590 		 */
    591 		if (xfr->reqtype == dns_rdatatype_ixfr &&
    592 		    rdata->type == dns_rdatatype_soa &&
    593 		    xfr->ixfr.request_serial == dns_soa_getserial(rdata))
    594 		{
    595 			xfrin_log(xfr, ISC_LOG_DEBUG(3),
    596 				  "got incremental response");
    597 			CHECK(ixfr_init(xfr));
    598 			xfr->state = XFRST_IXFR_DELSOA;
    599 		} else {
    600 			xfrin_log(xfr, ISC_LOG_DEBUG(3),
    601 				  "got nonincremental response");
    602 			CHECK(axfr_init(xfr));
    603 			xfr->state = XFRST_AXFR;
    604 		}
    605 		goto redo;
    606 
    607 	case XFRST_IXFR_DELSOA:
    608 		INSIST(rdata->type == dns_rdatatype_soa);
    609 		CHECK(ixfr_putdata(xfr, DNS_DIFFOP_DEL, name, ttl, rdata));
    610 		xfr->state = XFRST_IXFR_DEL;
    611 		break;
    612 
    613 	case XFRST_IXFR_DEL:
    614 		if (rdata->type == dns_rdatatype_soa) {
    615 			uint32_t soa_serial = dns_soa_getserial(rdata);
    616 			xfr->state = XFRST_IXFR_ADDSOA;
    617 			xfr->ixfr.current_serial = soa_serial;
    618 			goto redo;
    619 		}
    620 		CHECK(ixfr_putdata(xfr, DNS_DIFFOP_DEL, name, ttl, rdata));
    621 		break;
    622 
    623 	case XFRST_IXFR_ADDSOA:
    624 		INSIST(rdata->type == dns_rdatatype_soa);
    625 		CHECK(ixfr_putdata(xfr, DNS_DIFFOP_ADD, name, ttl, rdata));
    626 		xfr->state = XFRST_IXFR_ADD;
    627 		break;
    628 
    629 	case XFRST_IXFR_ADD:
    630 		if (rdata->type == dns_rdatatype_soa) {
    631 			uint32_t soa_serial = dns_soa_getserial(rdata);
    632 			if (soa_serial == xfr->end_serial) {
    633 				CHECK(ixfr_commit(xfr));
    634 				xfr->state = XFRST_IXFR_END;
    635 				break;
    636 			} else if (soa_serial != xfr->ixfr.current_serial) {
    637 				xfrin_log(xfr, ISC_LOG_NOTICE,
    638 					  "IXFR out of sync: "
    639 					  "expected serial %u, got %u",
    640 					  xfr->ixfr.current_serial, soa_serial);
    641 				FAIL(DNS_R_FORMERR);
    642 			} else {
    643 				CHECK(ixfr_commit(xfr));
    644 				xfr->state = XFRST_IXFR_DELSOA;
    645 				goto redo;
    646 			}
    647 		}
    648 		if (rdata->type == dns_rdatatype_ns &&
    649 		    dns_name_iswildcard(name))
    650 		{
    651 			FAIL(DNS_R_INVALIDNS);
    652 		}
    653 		CHECK(ixfr_putdata(xfr, DNS_DIFFOP_ADD, name, ttl, rdata));
    654 		break;
    655 
    656 	case XFRST_AXFR:
    657 		/*
    658 		 * Old BINDs sent cross class A records for non IN classes.
    659 		 */
    660 		if (rdata->type == dns_rdatatype_a &&
    661 		    rdata->rdclass != xfr->rdclass &&
    662 		    xfr->rdclass != dns_rdataclass_in)
    663 		{
    664 			break;
    665 		}
    666 		CHECK(axfr_putdata(xfr, DNS_DIFFOP_ADD, name, ttl, rdata));
    667 		if (rdata->type == dns_rdatatype_soa) {
    668 			/*
    669 			 * Use dns_rdata_compare instead of memcmp to
    670 			 * allow for case differences.
    671 			 */
    672 			if (dns_rdata_compare(rdata, &xfr->firstsoa) != 0) {
    673 				xfrin_log(xfr, ISC_LOG_NOTICE,
    674 					  "start and ending SOA records "
    675 					  "mismatch");
    676 				FAIL(DNS_R_FORMERR);
    677 			}
    678 			CHECK(axfr_commit(xfr));
    679 			xfr->state = XFRST_AXFR_END;
    680 			break;
    681 		}
    682 		break;
    683 	case XFRST_AXFR_END:
    684 	case XFRST_IXFR_END:
    685 		FAIL(DNS_R_EXTRADATA);
    686 		FALLTHROUGH;
    687 	default:
    688 		UNREACHABLE();
    689 	}
    690 	result = ISC_R_SUCCESS;
    691 failure:
    692 	return (result);
    693 }
    694 
    695 isc_result_t
    696 dns_xfrin_create(dns_zone_t *zone, dns_rdatatype_t xfrtype,
    697 		 const isc_sockaddr_t *primaryaddr,
    698 		 const isc_sockaddr_t *sourceaddr, dns_tsigkey_t *tsigkey,
    699 		 dns_transport_t *transport, isc_tlsctx_cache_t *tlsctx_cache,
    700 		 isc_mem_t *mctx, isc_nm_t *netmgr, dns_xfrindone_t done,
    701 		 dns_xfrin_ctx_t **xfrp) {
    702 	dns_name_t *zonename = dns_zone_getorigin(zone);
    703 	dns_xfrin_ctx_t *xfr = NULL;
    704 	isc_result_t result;
    705 	dns_db_t *db = NULL;
    706 
    707 	REQUIRE(xfrp != NULL && *xfrp == NULL);
    708 	REQUIRE(done != NULL);
    709 	REQUIRE(isc_sockaddr_getport(primaryaddr) != 0);
    710 
    711 	(void)dns_zone_getdb(zone, &db);
    712 
    713 	if (xfrtype == dns_rdatatype_soa || xfrtype == dns_rdatatype_ixfr) {
    714 		REQUIRE(db != NULL);
    715 	}
    716 
    717 	xfrin_create(mctx, zone, db, netmgr, zonename, dns_zone_getclass(zone),
    718 		     xfrtype, primaryaddr, sourceaddr, tsigkey, transport,
    719 		     tlsctx_cache, &xfr);
    720 
    721 	if (db != NULL) {
    722 		xfr->zone_had_db = true;
    723 	}
    724 
    725 	xfr->done = done;
    726 
    727 	isc_refcount_init(&xfr->references, 1);
    728 
    729 	/*
    730 	 * Set *xfrp now, before calling xfrin_start(). Asynchronous
    731 	 * netmgr processing could cause the 'done' callback to run in
    732 	 * another thread before we reached the end of the present
    733 	 * function. In that case, if *xfrp hadn't already been
    734 	 * attached, the 'done' function would be unable to detach it.
    735 	 */
    736 	*xfrp = xfr;
    737 
    738 	result = xfrin_start(xfr);
    739 	if (result != ISC_R_SUCCESS) {
    740 		atomic_store(&xfr->shuttingdown, true);
    741 		xfr->shutdown_result = result;
    742 		dns_xfrin_detach(xfrp);
    743 	}
    744 
    745 	if (db != NULL) {
    746 		dns_db_detach(&db);
    747 	}
    748 
    749 	if (result != ISC_R_SUCCESS) {
    750 		char zonetext[DNS_NAME_MAXTEXT + 32];
    751 		dns_zone_name(zone, zonetext, sizeof(zonetext));
    752 		xfrin_log1(ISC_LOG_ERROR, zonetext, primaryaddr,
    753 			   "zone transfer setup failed");
    754 	}
    755 
    756 	return (result);
    757 }
    758 
    759 static void
    760 xfrin_cancelio(dns_xfrin_ctx_t *xfr);
    761 
    762 static void
    763 xfrin_timedout(struct isc_task *task, struct isc_event *event) {
    764 	UNUSED(task);
    765 
    766 	dns_xfrin_ctx_t *xfr = event->ev_arg;
    767 	REQUIRE(VALID_XFRIN(xfr));
    768 
    769 	xfrin_fail(xfr, ISC_R_TIMEDOUT, "maximum transfer time exceeded");
    770 	isc_event_free(&event);
    771 }
    772 
    773 static void
    774 xfrin_idledout(struct isc_task *task, struct isc_event *event) {
    775 	UNUSED(task);
    776 
    777 	dns_xfrin_ctx_t *xfr = event->ev_arg;
    778 	REQUIRE(VALID_XFRIN(xfr));
    779 
    780 	xfrin_fail(xfr, ISC_R_TIMEDOUT, "maximum idle time exceeded");
    781 	isc_event_free(&event);
    782 }
    783 
    784 void
    785 dns_xfrin_shutdown(dns_xfrin_ctx_t *xfr) {
    786 	REQUIRE(VALID_XFRIN(xfr));
    787 
    788 	xfrin_fail(xfr, ISC_R_CANCELED, "shut down");
    789 }
    790 
    791 void
    792 dns_xfrin_attach(dns_xfrin_ctx_t *source, dns_xfrin_ctx_t **target) {
    793 	REQUIRE(VALID_XFRIN(source));
    794 	REQUIRE(target != NULL && *target == NULL);
    795 	(void)isc_refcount_increment(&source->references);
    796 
    797 	*target = source;
    798 }
    799 
    800 void
    801 dns_xfrin_detach(dns_xfrin_ctx_t **xfrp) {
    802 	dns_xfrin_ctx_t *xfr = NULL;
    803 
    804 	REQUIRE(xfrp != NULL && VALID_XFRIN(*xfrp));
    805 
    806 	xfr = *xfrp;
    807 	*xfrp = NULL;
    808 
    809 	if (isc_refcount_decrement(&xfr->references) == 1) {
    810 		xfrin_destroy(xfr);
    811 	}
    812 }
    813 
    814 static void
    815 xfrin_cancelio(dns_xfrin_ctx_t *xfr) {
    816 	if (xfr->readhandle == NULL) {
    817 		return;
    818 	}
    819 
    820 	isc_nm_cancelread(xfr->readhandle);
    821 	/* The xfr->readhandle detach will happen in xfrin_recv_done callback */
    822 }
    823 
    824 static void
    825 xfrin_reset(dns_xfrin_ctx_t *xfr) {
    826 	REQUIRE(VALID_XFRIN(xfr));
    827 
    828 	xfrin_log(xfr, ISC_LOG_INFO, "resetting");
    829 
    830 	REQUIRE(xfr->readhandle == NULL);
    831 	REQUIRE(xfr->sendhandle == NULL);
    832 
    833 	if (xfr->lasttsig != NULL) {
    834 		isc_buffer_free(&xfr->lasttsig);
    835 	}
    836 
    837 	dns_diff_clear(&xfr->diff);
    838 	xfr->difflen = 0;
    839 
    840 	if (xfr->ixfr.journal != NULL) {
    841 		dns_journal_destroy(&xfr->ixfr.journal);
    842 	}
    843 
    844 	if (xfr->axfr.add_private != NULL) {
    845 		(void)dns_db_endload(xfr->db, &xfr->axfr);
    846 	}
    847 
    848 	if (xfr->ver != NULL) {
    849 		dns_db_closeversion(xfr->db, &xfr->ver, false);
    850 	}
    851 }
    852 
    853 static void
    854 xfrin_fail(dns_xfrin_ctx_t *xfr, isc_result_t result, const char *msg) {
    855 	/* Make sure only the first xfrin_fail() trumps */
    856 	if (atomic_compare_exchange_strong(&xfr->shuttingdown, &(bool){ false },
    857 					   true))
    858 	{
    859 		(void)isc_timer_reset(xfr->max_time_timer,
    860 				      isc_timertype_inactive, NULL, NULL, true);
    861 		(void)isc_timer_reset(xfr->max_idle_timer,
    862 				      isc_timertype_inactive, NULL, NULL, true);
    863 
    864 		if (result != DNS_R_UPTODATE && result != DNS_R_TOOMANYRECORDS)
    865 		{
    866 			xfrin_log(xfr, ISC_LOG_ERROR, "%s: %s", msg,
    867 				  isc_result_totext(result));
    868 			if (xfr->is_ixfr) {
    869 				/* Pass special result code to force AXFR retry
    870 				 */
    871 				result = DNS_R_BADIXFR;
    872 			}
    873 		}
    874 		xfrin_cancelio(xfr);
    875 		/*
    876 		 * Close the journal.
    877 		 */
    878 		if (xfr->ixfr.journal != NULL) {
    879 			dns_journal_destroy(&xfr->ixfr.journal);
    880 		}
    881 		if (xfr->done != NULL) {
    882 			(xfr->done)(xfr->zone, result);
    883 			xfr->done = NULL;
    884 		}
    885 		xfr->shutdown_result = result;
    886 	}
    887 }
    888 
    889 static void
    890 xfrin_create(isc_mem_t *mctx, dns_zone_t *zone, dns_db_t *db, isc_nm_t *netmgr,
    891 	     dns_name_t *zonename, dns_rdataclass_t rdclass,
    892 	     dns_rdatatype_t reqtype, const isc_sockaddr_t *primaryaddr,
    893 	     const isc_sockaddr_t *sourceaddr, dns_tsigkey_t *tsigkey,
    894 	     dns_transport_t *transport, isc_tlsctx_cache_t *tlsctx_cache,
    895 	     dns_xfrin_ctx_t **xfrp) {
    896 	dns_xfrin_ctx_t *xfr = NULL;
    897 	dns_zonemgr_t *zmgr = dns_zone_getmgr(zone);
    898 	isc_timermgr_t *timermgr = dns_zonemgr_gettimermgr(zmgr);
    899 	isc_task_t *ztask = NULL;
    900 
    901 	xfr = isc_mem_get(mctx, sizeof(*xfr));
    902 	*xfr = (dns_xfrin_ctx_t){ .netmgr = netmgr,
    903 				  .shutdown_result = ISC_R_UNSET,
    904 				  .rdclass = rdclass,
    905 				  .reqtype = reqtype,
    906 				  .id = (dns_messageid_t)isc_random16(),
    907 				  .maxrecords = dns_zone_getmaxrecords(zone),
    908 				  .primaryaddr = *primaryaddr,
    909 				  .sourceaddr = *sourceaddr,
    910 				  .firstsoa = DNS_RDATA_INIT,
    911 				  .magic = XFRIN_MAGIC };
    912 
    913 	isc_mem_attach(mctx, &xfr->mctx);
    914 	dns_zone_iattach(zone, &xfr->zone);
    915 	dns_name_init(&xfr->name, NULL);
    916 
    917 	isc_refcount_init(&xfr->connects, 0);
    918 	isc_refcount_init(&xfr->sends, 0);
    919 	isc_refcount_init(&xfr->recvs, 0);
    920 
    921 	atomic_init(&xfr->shuttingdown, false);
    922 
    923 	if (db != NULL) {
    924 		dns_db_attach(db, &xfr->db);
    925 	}
    926 
    927 	dns_diff_init(xfr->mctx, &xfr->diff);
    928 
    929 	if (reqtype == dns_rdatatype_soa) {
    930 		xfr->state = XFRST_SOAQUERY;
    931 	} else {
    932 		xfr->state = XFRST_INITIALSOA;
    933 	}
    934 
    935 	isc_time_now(&xfr->start);
    936 
    937 	if (tsigkey != NULL) {
    938 		dns_tsigkey_attach(tsigkey, &xfr->tsigkey);
    939 	}
    940 
    941 	if (transport != NULL) {
    942 		dns_transport_attach(transport, &xfr->transport);
    943 	}
    944 
    945 	dns_name_dup(zonename, mctx, &xfr->name);
    946 
    947 	INSIST(isc_sockaddr_pf(primaryaddr) == isc_sockaddr_pf(sourceaddr));
    948 	isc_sockaddr_setport(&xfr->sourceaddr, 0);
    949 
    950 	/*
    951 	 * Reserve 2 bytes for TCP length at the beginning of the buffer.
    952 	 */
    953 	isc_buffer_init(&xfr->qbuffer, &xfr->qbuffer_data[2],
    954 			sizeof(xfr->qbuffer_data) - 2);
    955 
    956 	isc_tlsctx_cache_attach(tlsctx_cache, &xfr->tlsctx_cache);
    957 
    958 	dns_zone_gettask(zone, &ztask);
    959 	isc_timer_create(timermgr, isc_timertype_inactive, NULL, NULL, ztask,
    960 			 xfrin_timedout, xfr, &xfr->max_time_timer);
    961 	isc_timer_create(timermgr, isc_timertype_inactive, NULL, NULL, ztask,
    962 			 xfrin_idledout, xfr, &xfr->max_idle_timer);
    963 	isc_task_detach(&ztask); /* dns_zone_task() attaches to the task */
    964 
    965 	*xfrp = xfr;
    966 }
    967 
    968 static isc_result_t
    969 get_create_tlsctx(const dns_xfrin_ctx_t *xfr, isc_tlsctx_t **pctx,
    970 		  isc_tlsctx_client_session_cache_t **psess_cache) {
    971 	isc_result_t result = ISC_R_FAILURE;
    972 	isc_tlsctx_t *tlsctx = NULL, *found = NULL;
    973 	isc_tls_cert_store_t *store = NULL, *found_store = NULL;
    974 	isc_tlsctx_client_session_cache_t *sess_cache = NULL,
    975 					  *found_sess_cache = NULL;
    976 	uint32_t tls_versions;
    977 	const char *ciphers = NULL;
    978 	bool prefer_server_ciphers;
    979 	const uint16_t family = isc_sockaddr_pf(&xfr->primaryaddr) == PF_INET6
    980 					? AF_INET6
    981 					: AF_INET;
    982 	const char *tlsname = NULL;
    983 
    984 	REQUIRE(psess_cache != NULL && *psess_cache == NULL);
    985 	REQUIRE(pctx != NULL && *pctx == NULL);
    986 
    987 	INSIST(xfr->transport != NULL);
    988 	tlsname = dns_transport_get_tlsname(xfr->transport);
    989 	INSIST(tlsname != NULL && *tlsname != '\0');
    990 
    991 	/*
    992 	 * Let's try to re-use the already created context. This way
    993 	 * we have a chance to resume the TLS session, bypassing the
    994 	 * full TLS handshake procedure, making establishing
    995 	 * subsequent TLS connections for XoT faster.
    996 	 */
    997 	result = isc_tlsctx_cache_find(xfr->tlsctx_cache, tlsname,
    998 				       isc_tlsctx_cache_tls, family, &found,
    999 				       &found_store, &found_sess_cache);
   1000 	if (result != ISC_R_SUCCESS) {
   1001 		const char *hostname =
   1002 			dns_transport_get_remote_hostname(xfr->transport);
   1003 		const char *ca_file = dns_transport_get_cafile(xfr->transport);
   1004 		const char *cert_file =
   1005 			dns_transport_get_certfile(xfr->transport);
   1006 		const char *key_file =
   1007 			dns_transport_get_keyfile(xfr->transport);
   1008 		char primary_addr_str[INET6_ADDRSTRLEN] = { 0 };
   1009 		isc_netaddr_t primary_netaddr = { 0 };
   1010 		bool hostname_ignore_subject;
   1011 		/*
   1012 		 * So, no context exists. Let's create one using the
   1013 		 * parameters from the configuration file and try to
   1014 		 * store it for further reuse.
   1015 		 */
   1016 		result = isc_tlsctx_createclient(&tlsctx);
   1017 		if (result != ISC_R_SUCCESS) {
   1018 			goto failure;
   1019 		}
   1020 		tls_versions = dns_transport_get_tls_versions(xfr->transport);
   1021 		if (tls_versions != 0) {
   1022 			isc_tlsctx_set_protocols(tlsctx, tls_versions);
   1023 		}
   1024 		ciphers = dns_transport_get_ciphers(xfr->transport);
   1025 		if (ciphers != NULL) {
   1026 			isc_tlsctx_set_cipherlist(tlsctx, ciphers);
   1027 		}
   1028 
   1029 		if (dns_transport_get_prefer_server_ciphers(
   1030 			    xfr->transport, &prefer_server_ciphers))
   1031 		{
   1032 			isc_tlsctx_prefer_server_ciphers(tlsctx,
   1033 							 prefer_server_ciphers);
   1034 		}
   1035 
   1036 		if (hostname != NULL || ca_file != NULL) {
   1037 			/*
   1038 			 * The situation when 'found_store != NULL' while 'found
   1039 			 * == NULL' might appear as there is one to many
   1040 			 * relation between per transport TLS contexts and cert
   1041 			 * stores. That is, there could be one store shared
   1042 			 * between multiple contexts.
   1043 			 */
   1044 			if (found_store == NULL) {
   1045 				/*
   1046 				 * 'ca_file' can equal 'NULL' here, in
   1047 				 * that case the store with system-wide
   1048 				 * CA certificates will be created, just
   1049 				 * as planned.
   1050 				 */
   1051 				result = isc_tls_cert_store_create(ca_file,
   1052 								   &store);
   1053 
   1054 				if (result != ISC_R_SUCCESS) {
   1055 					goto failure;
   1056 				}
   1057 			} else {
   1058 				store = found_store;
   1059 			}
   1060 
   1061 			INSIST(store != NULL);
   1062 			if (hostname == NULL) {
   1063 				/*
   1064 				 * If CA bundle file is specified, but
   1065 				 * hostname is not, then use the primary
   1066 				 * IP address for validation, just like
   1067 				 * dig does.
   1068 				 */
   1069 				INSIST(ca_file != NULL);
   1070 				isc_netaddr_fromsockaddr(&primary_netaddr,
   1071 							 &xfr->primaryaddr);
   1072 				isc_netaddr_format(&primary_netaddr,
   1073 						   primary_addr_str,
   1074 						   sizeof(primary_addr_str));
   1075 				hostname = primary_addr_str;
   1076 			}
   1077 			/*
   1078 			 * According to RFC 8310, Subject field MUST NOT
   1079 			 * be inspected when verifying hostname for DoT.
   1080 			 * Only SubjectAltName must be checked.
   1081 			 */
   1082 			hostname_ignore_subject = true;
   1083 			result = isc_tlsctx_enable_peer_verification(
   1084 				tlsctx, false, store, hostname,
   1085 				hostname_ignore_subject);
   1086 			if (result != ISC_R_SUCCESS) {
   1087 				goto failure;
   1088 			}
   1089 
   1090 			/*
   1091 			 * Let's load client certificate and enable
   1092 			 * Mutual TLS. We do that only in the case when
   1093 			 * Strict TLS is enabled, because Mutual TLS is
   1094 			 * an extension of it.
   1095 			 */
   1096 			if (cert_file != NULL) {
   1097 				INSIST(key_file != NULL);
   1098 
   1099 				result = isc_tlsctx_load_certificate(
   1100 					tlsctx, key_file, cert_file);
   1101 				if (result != ISC_R_SUCCESS) {
   1102 					goto failure;
   1103 				}
   1104 			}
   1105 		}
   1106 
   1107 		isc_tlsctx_enable_dot_client_alpn(tlsctx);
   1108 
   1109 		isc_tlsctx_client_session_cache_create(
   1110 			xfr->mctx, tlsctx,
   1111 			ISC_TLSCTX_CLIENT_SESSION_CACHE_DEFAULT_SIZE,
   1112 			&sess_cache);
   1113 
   1114 		found_store = NULL;
   1115 		result = isc_tlsctx_cache_add(xfr->tlsctx_cache, tlsname,
   1116 					      isc_tlsctx_cache_tls, family,
   1117 					      tlsctx, store, sess_cache, &found,
   1118 					      &found_store, &found_sess_cache);
   1119 		if (result == ISC_R_EXISTS) {
   1120 			/*
   1121 			 * It seems the entry has just been created from within
   1122 			 * another thread while we were initialising
   1123 			 * ours. Although this is unlikely, it could happen
   1124 			 * after startup/re-initialisation. In such a case,
   1125 			 * discard the new context and associated data and use
   1126 			 * the already established one from now on.
   1127 			 *
   1128 			 * Such situation will not occur after the
   1129 			 * initial 'warm-up', so it is not critical
   1130 			 * performance-wise.
   1131 			 */
   1132 			INSIST(found != NULL);
   1133 			isc_tlsctx_free(&tlsctx);
   1134 			/*
   1135 			 * The 'store' variable can be 'NULL' when remote server
   1136 			 * verification is not enabled (that is, when Strict or
   1137 			 * Mutual TLS are not used).
   1138 			 *
   1139 			 * The 'found_store' might be equal to 'store' as there
   1140 			 * is one-to-many relation between a store and
   1141 			 * per-transport TLS contexts. In that case, the call to
   1142 			 * 'isc_tlsctx_cache_find()' above could have returned a
   1143 			 * store via the 'found_store' variable, whose value we
   1144 			 * can assign to 'store' later. In that case,
   1145 			 * 'isc_tlsctx_cache_add()' will return the same value.
   1146 			 * When that happens, we should not free the store
   1147 			 * object, as it is managed by the TLS context cache.
   1148 			 */
   1149 			if (store != NULL && store != found_store) {
   1150 				isc_tls_cert_store_free(&store);
   1151 			}
   1152 			isc_tlsctx_client_session_cache_detach(&sess_cache);
   1153 			/* Let's return the data from the cache. */
   1154 			*psess_cache = found_sess_cache;
   1155 			*pctx = found;
   1156 		} else {
   1157 			/*
   1158 			 * Adding the fresh values into the cache has been
   1159 			 * successful, let's return them
   1160 			 */
   1161 			INSIST(result == ISC_R_SUCCESS);
   1162 			*psess_cache = sess_cache;
   1163 			*pctx = tlsctx;
   1164 		}
   1165 	} else {
   1166 		/*
   1167 		 * The cache lookup has been successful, let's return the
   1168 		 * results.
   1169 		 */
   1170 		INSIST(result == ISC_R_SUCCESS);
   1171 		*psess_cache = found_sess_cache;
   1172 		*pctx = found;
   1173 	}
   1174 
   1175 	return (ISC_R_SUCCESS);
   1176 
   1177 failure:
   1178 	if (tlsctx != NULL) {
   1179 		isc_tlsctx_free(&tlsctx);
   1180 	}
   1181 
   1182 	/*
   1183 	 * The 'found_store' is being managed by the TLS context
   1184 	 * cache. Thus, we should keep it as it is, as it will get
   1185 	 * destroyed alongside the cache. As there is one store per
   1186 	 * multiple TLS contexts, we need to handle store deletion in a
   1187 	 * special way.
   1188 	 */
   1189 	if (store != NULL && store != found_store) {
   1190 		isc_tls_cert_store_free(&store);
   1191 	}
   1192 
   1193 	return (result);
   1194 }
   1195 
   1196 static isc_result_t
   1197 xfrin_start(dns_xfrin_ctx_t *xfr) {
   1198 	isc_result_t result;
   1199 	dns_xfrin_ctx_t *connect_xfr = NULL;
   1200 	dns_transport_type_t transport_type = DNS_TRANSPORT_TCP;
   1201 	isc_tlsctx_t *tlsctx = NULL;
   1202 	isc_tlsctx_client_session_cache_t *sess_cache = NULL;
   1203 	isc_interval_t interval;
   1204 	isc_time_t next;
   1205 
   1206 	(void)isc_refcount_increment0(&xfr->connects);
   1207 	dns_xfrin_attach(xfr, &connect_xfr);
   1208 
   1209 	if (xfr->transport != NULL) {
   1210 		transport_type = dns_transport_get_type(xfr->transport);
   1211 	}
   1212 
   1213 	/* Set the maximum timer */
   1214 	isc_interval_set(&interval, dns_zone_getmaxxfrin(xfr->zone), 0);
   1215 	isc_time_nowplusinterval(&next, &interval);
   1216 	result = isc_timer_reset(xfr->max_time_timer, isc_timertype_once, &next,
   1217 				 NULL, true);
   1218 	RUNTIME_CHECK(result == ISC_R_SUCCESS);
   1219 
   1220 	/* Set the idle timer */
   1221 	isc_interval_set(&interval, dns_zone_getidlein(xfr->zone), 0);
   1222 	isc_time_nowplusinterval(&next, &interval);
   1223 	result = isc_timer_reset(xfr->max_idle_timer, isc_timertype_once, &next,
   1224 				 NULL, true);
   1225 	RUNTIME_CHECK(result == ISC_R_SUCCESS);
   1226 
   1227 	/*
   1228 	 * XXX: timeouts are hard-coded to 30 seconds; this needs to be
   1229 	 * configurable.
   1230 	 */
   1231 	switch (transport_type) {
   1232 	case DNS_TRANSPORT_TCP:
   1233 		isc_nm_tcpdnsconnect(xfr->netmgr, &xfr->sourceaddr,
   1234 				     &xfr->primaryaddr, xfrin_connect_done,
   1235 				     connect_xfr, 30000, 0);
   1236 		break;
   1237 	case DNS_TRANSPORT_TLS: {
   1238 		result = get_create_tlsctx(xfr, &tlsctx, &sess_cache);
   1239 		if (result != ISC_R_SUCCESS) {
   1240 			goto failure;
   1241 		}
   1242 		INSIST(tlsctx != NULL);
   1243 		isc_nm_tlsdnsconnect(xfr->netmgr, &xfr->sourceaddr,
   1244 				     &xfr->primaryaddr, xfrin_connect_done,
   1245 				     connect_xfr, 30000, 0, tlsctx, sess_cache);
   1246 	} break;
   1247 	default:
   1248 		UNREACHABLE();
   1249 	}
   1250 
   1251 	return (ISC_R_SUCCESS);
   1252 
   1253 failure:
   1254 	isc_refcount_decrement0(&xfr->connects);
   1255 	dns_xfrin_detach(&connect_xfr);
   1256 	return (result);
   1257 }
   1258 
   1259 /* XXX the resolver could use this, too */
   1260 
   1261 static isc_result_t
   1262 render(dns_message_t *msg, isc_mem_t *mctx, isc_buffer_t *buf) {
   1263 	dns_compress_t cctx;
   1264 	bool cleanup_cctx = false;
   1265 	isc_result_t result;
   1266 
   1267 	CHECK(dns_compress_init(&cctx, -1, mctx));
   1268 	cleanup_cctx = true;
   1269 	CHECK(dns_message_renderbegin(msg, &cctx, buf));
   1270 	CHECK(dns_message_rendersection(msg, DNS_SECTION_QUESTION, 0));
   1271 	CHECK(dns_message_rendersection(msg, DNS_SECTION_ANSWER, 0));
   1272 	CHECK(dns_message_rendersection(msg, DNS_SECTION_AUTHORITY, 0));
   1273 	CHECK(dns_message_rendersection(msg, DNS_SECTION_ADDITIONAL, 0));
   1274 	CHECK(dns_message_renderend(msg));
   1275 	result = ISC_R_SUCCESS;
   1276 failure:
   1277 	if (cleanup_cctx) {
   1278 		dns_compress_invalidate(&cctx);
   1279 	}
   1280 	return (result);
   1281 }
   1282 
   1283 /*
   1284  * A connection has been established.
   1285  */
   1286 static void
   1287 xfrin_connect_done(isc_nmhandle_t *handle, isc_result_t result, void *cbarg) {
   1288 	dns_xfrin_ctx_t *xfr = (dns_xfrin_ctx_t *)cbarg;
   1289 	char sourcetext[ISC_SOCKADDR_FORMATSIZE];
   1290 	char signerbuf[DNS_NAME_FORMATSIZE];
   1291 	const char *signer = "", *sep = "";
   1292 	isc_sockaddr_t sockaddr;
   1293 	dns_zonemgr_t *zmgr = NULL;
   1294 
   1295 	REQUIRE(VALID_XFRIN(xfr));
   1296 
   1297 	isc_refcount_decrement0(&xfr->connects);
   1298 
   1299 	if (atomic_load(&xfr->shuttingdown)) {
   1300 		result = ISC_R_SHUTTINGDOWN;
   1301 	}
   1302 
   1303 	if (result != ISC_R_SUCCESS) {
   1304 		xfrin_fail(xfr, result, "failed to connect");
   1305 		goto failure;
   1306 	}
   1307 
   1308 	result = isc_nm_xfr_checkperm(handle);
   1309 	if (result != ISC_R_SUCCESS) {
   1310 		xfrin_fail(xfr, result, "connected but unable to transfer");
   1311 		goto failure;
   1312 	}
   1313 
   1314 	zmgr = dns_zone_getmgr(xfr->zone);
   1315 	if (zmgr != NULL) {
   1316 		dns_zonemgr_unreachabledel(zmgr, &xfr->primaryaddr,
   1317 					   &xfr->sourceaddr);
   1318 	}
   1319 
   1320 	xfr->handle = handle;
   1321 	sockaddr = isc_nmhandle_peeraddr(handle);
   1322 	isc_sockaddr_format(&sockaddr, sourcetext, sizeof(sourcetext));
   1323 
   1324 	if (xfr->tsigkey != NULL && xfr->tsigkey->key != NULL) {
   1325 		dns_name_format(dst_key_name(xfr->tsigkey->key), signerbuf,
   1326 				sizeof(signerbuf));
   1327 		sep = " TSIG ";
   1328 		signer = signerbuf;
   1329 	}
   1330 
   1331 	xfrin_log(xfr, ISC_LOG_INFO, "connected using %s%s%s", sourcetext, sep,
   1332 		  signer);
   1333 
   1334 	result = xfrin_send_request(xfr);
   1335 	if (result != ISC_R_SUCCESS) {
   1336 		xfrin_fail(xfr, result, "connected but unable to send");
   1337 	}
   1338 
   1339 failure:
   1340 	switch (result) {
   1341 	case ISC_R_SUCCESS:
   1342 		break;
   1343 	case ISC_R_NETDOWN:
   1344 	case ISC_R_HOSTDOWN:
   1345 	case ISC_R_NETUNREACH:
   1346 	case ISC_R_HOSTUNREACH:
   1347 	case ISC_R_CONNREFUSED:
   1348 	case ISC_R_TIMEDOUT:
   1349 		/*
   1350 		 * Add the server to unreachable primaries table if
   1351 		 * the server has a permanent networking error or
   1352 		 * the connection attempt as timed out.
   1353 		 */
   1354 		zmgr = dns_zone_getmgr(xfr->zone);
   1355 		if (zmgr != NULL) {
   1356 			isc_time_t now;
   1357 
   1358 			TIME_NOW(&now);
   1359 
   1360 			dns_zonemgr_unreachableadd(zmgr, &xfr->primaryaddr,
   1361 						   &xfr->sourceaddr, &now);
   1362 		}
   1363 		break;
   1364 	default:
   1365 		/* Retry sooner than in 10 minutes */
   1366 		break;
   1367 	}
   1368 
   1369 	dns_xfrin_detach(&xfr);
   1370 }
   1371 
   1372 /*
   1373  * Convert a tuple into a dns_name_t suitable for inserting
   1374  * into the given dns_message_t.
   1375  */
   1376 static isc_result_t
   1377 tuple2msgname(dns_difftuple_t *tuple, dns_message_t *msg, dns_name_t **target) {
   1378 	isc_result_t result;
   1379 	dns_rdata_t *rdata = NULL;
   1380 	dns_rdatalist_t *rdl = NULL;
   1381 	dns_rdataset_t *rds = NULL;
   1382 	dns_name_t *name = NULL;
   1383 
   1384 	REQUIRE(target != NULL && *target == NULL);
   1385 
   1386 	CHECK(dns_message_gettemprdata(msg, &rdata));
   1387 	dns_rdata_init(rdata);
   1388 	dns_rdata_clone(&tuple->rdata, rdata);
   1389 
   1390 	CHECK(dns_message_gettemprdatalist(msg, &rdl));
   1391 	dns_rdatalist_init(rdl);
   1392 	rdl->type = tuple->rdata.type;
   1393 	rdl->rdclass = tuple->rdata.rdclass;
   1394 	rdl->ttl = tuple->ttl;
   1395 	ISC_LIST_APPEND(rdl->rdata, rdata, link);
   1396 
   1397 	CHECK(dns_message_gettemprdataset(msg, &rds));
   1398 	CHECK(dns_rdatalist_tordataset(rdl, rds));
   1399 
   1400 	CHECK(dns_message_gettempname(msg, &name));
   1401 	dns_name_clone(&tuple->name, name);
   1402 	ISC_LIST_APPEND(name->list, rds, link);
   1403 
   1404 	*target = name;
   1405 	return (ISC_R_SUCCESS);
   1406 
   1407 failure:
   1408 
   1409 	if (rds != NULL) {
   1410 		dns_rdataset_disassociate(rds);
   1411 		dns_message_puttemprdataset(msg, &rds);
   1412 	}
   1413 	if (rdl != NULL) {
   1414 		ISC_LIST_UNLINK(rdl->rdata, rdata, link);
   1415 		dns_message_puttemprdatalist(msg, &rdl);
   1416 	}
   1417 	if (rdata != NULL) {
   1418 		dns_message_puttemprdata(msg, &rdata);
   1419 	}
   1420 
   1421 	return (result);
   1422 }
   1423 
   1424 /*
   1425  * Build an *XFR request and send its length prefix.
   1426  */
   1427 static isc_result_t
   1428 xfrin_send_request(dns_xfrin_ctx_t *xfr) {
   1429 	isc_result_t result;
   1430 	isc_region_t region;
   1431 	dns_rdataset_t *qrdataset = NULL;
   1432 	dns_message_t *msg = NULL;
   1433 	dns_difftuple_t *soatuple = NULL;
   1434 	dns_name_t *qname = NULL;
   1435 	dns_dbversion_t *ver = NULL;
   1436 	dns_name_t *msgsoaname = NULL;
   1437 	dns_xfrin_ctx_t *send_xfr = NULL;
   1438 
   1439 	/* Create the request message */
   1440 	dns_message_create(xfr->mctx, DNS_MESSAGE_INTENTRENDER, &msg);
   1441 	CHECK(dns_message_settsigkey(msg, xfr->tsigkey));
   1442 
   1443 	/* Create a name for the question section. */
   1444 	CHECK(dns_message_gettempname(msg, &qname));
   1445 	dns_name_clone(&xfr->name, qname);
   1446 
   1447 	/* Formulate the question and attach it to the question name. */
   1448 	CHECK(dns_message_gettemprdataset(msg, &qrdataset));
   1449 	dns_rdataset_makequestion(qrdataset, xfr->rdclass, xfr->reqtype);
   1450 	ISC_LIST_APPEND(qname->list, qrdataset, link);
   1451 	qrdataset = NULL;
   1452 
   1453 	dns_message_addname(msg, qname, DNS_SECTION_QUESTION);
   1454 	qname = NULL;
   1455 
   1456 	if (xfr->reqtype == dns_rdatatype_ixfr) {
   1457 		/* Get the SOA and add it to the authority section. */
   1458 		/* XXX is using the current version the right thing? */
   1459 		dns_db_currentversion(xfr->db, &ver);
   1460 		CHECK(dns_db_createsoatuple(xfr->db, ver, xfr->mctx,
   1461 					    DNS_DIFFOP_EXISTS, &soatuple));
   1462 		xfr->ixfr.request_serial = dns_soa_getserial(&soatuple->rdata);
   1463 		xfr->ixfr.current_serial = xfr->ixfr.request_serial;
   1464 		xfrin_log(xfr, ISC_LOG_DEBUG(3),
   1465 			  "requesting IXFR for serial %u",
   1466 			  xfr->ixfr.request_serial);
   1467 
   1468 		CHECK(tuple2msgname(soatuple, msg, &msgsoaname));
   1469 		dns_message_addname(msg, msgsoaname, DNS_SECTION_AUTHORITY);
   1470 	} else if (xfr->reqtype == dns_rdatatype_soa) {
   1471 		CHECK(dns_db_getsoaserial(xfr->db, NULL,
   1472 					  &xfr->ixfr.request_serial));
   1473 	}
   1474 
   1475 	xfr->id++;
   1476 	xfr->nmsg = 0;
   1477 	xfr->nrecs = 0;
   1478 	xfr->nbytes = 0;
   1479 	isc_time_now(&xfr->start);
   1480 	msg->id = xfr->id;
   1481 	if (xfr->tsigctx != NULL) {
   1482 		dst_context_destroy(&xfr->tsigctx);
   1483 	}
   1484 
   1485 	CHECK(render(msg, xfr->mctx, &xfr->qbuffer));
   1486 
   1487 	/*
   1488 	 * Free the last tsig, if there is one.
   1489 	 */
   1490 	if (xfr->lasttsig != NULL) {
   1491 		isc_buffer_free(&xfr->lasttsig);
   1492 	}
   1493 
   1494 	/*
   1495 	 * Save the query TSIG and don't let message_destroy free it.
   1496 	 */
   1497 	CHECK(dns_message_getquerytsig(msg, xfr->mctx, &xfr->lasttsig));
   1498 
   1499 	isc_buffer_usedregion(&xfr->qbuffer, &region);
   1500 	INSIST(region.length <= 65535);
   1501 
   1502 	dns_xfrin_attach(xfr, &send_xfr);
   1503 	isc_nmhandle_attach(send_xfr->handle, &xfr->sendhandle);
   1504 	isc_refcount_increment0(&send_xfr->sends);
   1505 	isc_nm_send(xfr->handle, &region, xfrin_send_done, send_xfr);
   1506 
   1507 failure:
   1508 	if (qname != NULL) {
   1509 		dns_message_puttempname(msg, &qname);
   1510 	}
   1511 	if (qrdataset != NULL) {
   1512 		dns_message_puttemprdataset(msg, &qrdataset);
   1513 	}
   1514 	if (msg != NULL) {
   1515 		dns_message_detach(&msg);
   1516 	}
   1517 	if (soatuple != NULL) {
   1518 		dns_difftuple_free(&soatuple);
   1519 	}
   1520 	if (ver != NULL) {
   1521 		dns_db_closeversion(xfr->db, &ver, false);
   1522 	}
   1523 
   1524 	return (result);
   1525 }
   1526 
   1527 static void
   1528 xfrin_send_done(isc_nmhandle_t *handle, isc_result_t result, void *cbarg) {
   1529 	dns_xfrin_ctx_t *xfr = (dns_xfrin_ctx_t *)cbarg;
   1530 	dns_xfrin_ctx_t *recv_xfr = NULL;
   1531 
   1532 	REQUIRE(VALID_XFRIN(xfr));
   1533 
   1534 	isc_refcount_decrement0(&xfr->sends);
   1535 	if (atomic_load(&xfr->shuttingdown)) {
   1536 		result = ISC_R_SHUTTINGDOWN;
   1537 	}
   1538 
   1539 	CHECK(result);
   1540 
   1541 	xfrin_log(xfr, ISC_LOG_DEBUG(3), "sent request data");
   1542 
   1543 	dns_xfrin_attach(xfr, &recv_xfr);
   1544 	isc_nmhandle_attach(handle, &recv_xfr->readhandle);
   1545 	isc_refcount_increment0(&recv_xfr->recvs);
   1546 	isc_nm_read(recv_xfr->handle, xfrin_recv_done, recv_xfr);
   1547 
   1548 failure:
   1549 	if (result != ISC_R_SUCCESS) {
   1550 		xfrin_fail(xfr, result, "failed sending request data");
   1551 	}
   1552 
   1553 	isc_nmhandle_detach(&xfr->sendhandle);
   1554 	dns_xfrin_detach(&xfr); /* send_xfr */
   1555 }
   1556 
   1557 static void
   1558 xfrin_recv_done(isc_nmhandle_t *handle, isc_result_t result,
   1559 		isc_region_t *region, void *cbarg) {
   1560 	dns_xfrin_ctx_t *xfr = (dns_xfrin_ctx_t *)cbarg;
   1561 	dns_message_t *msg = NULL;
   1562 	dns_name_t *name = NULL;
   1563 	const dns_name_t *tsigowner = NULL;
   1564 	isc_buffer_t buffer;
   1565 	isc_sockaddr_t peer;
   1566 
   1567 	REQUIRE(VALID_XFRIN(xfr));
   1568 
   1569 	isc_refcount_decrement0(&xfr->recvs);
   1570 
   1571 	if (atomic_load(&xfr->shuttingdown)) {
   1572 		result = ISC_R_SHUTTINGDOWN;
   1573 	}
   1574 
   1575 	/* Stop the idle timer */
   1576 	(void)isc_timer_reset(xfr->max_idle_timer, isc_timertype_inactive, NULL,
   1577 			      NULL, true);
   1578 
   1579 	CHECK(result);
   1580 
   1581 	xfrin_log(xfr, ISC_LOG_DEBUG(7), "received %u bytes", region->length);
   1582 
   1583 	dns_message_create(xfr->mctx, DNS_MESSAGE_INTENTPARSE, &msg);
   1584 
   1585 	CHECK(dns_message_settsigkey(msg, xfr->tsigkey));
   1586 	CHECK(dns_message_setquerytsig(msg, xfr->lasttsig));
   1587 
   1588 	msg->tsigctx = xfr->tsigctx;
   1589 	xfr->tsigctx = NULL;
   1590 
   1591 	dns_message_setclass(msg, xfr->rdclass);
   1592 
   1593 	if (xfr->nmsg > 0) {
   1594 		msg->tcp_continuation = 1;
   1595 	}
   1596 
   1597 	isc_buffer_init(&buffer, region->base, region->length);
   1598 	isc_buffer_add(&buffer, region->length);
   1599 	peer = isc_nmhandle_peeraddr(handle);
   1600 
   1601 	result = dns_message_parse(msg, &buffer,
   1602 				   DNS_MESSAGEPARSE_PRESERVEORDER);
   1603 	if (result == ISC_R_SUCCESS) {
   1604 		dns_message_logpacket(msg, "received message from", &peer,
   1605 				      DNS_LOGCATEGORY_XFER_IN,
   1606 				      DNS_LOGMODULE_XFER_IN, ISC_LOG_DEBUG(10),
   1607 				      xfr->mctx);
   1608 	} else {
   1609 		xfrin_log(xfr, ISC_LOG_DEBUG(10), "dns_message_parse: %s",
   1610 			  isc_result_totext(result));
   1611 	}
   1612 
   1613 	if (result != ISC_R_SUCCESS || msg->rcode != dns_rcode_noerror ||
   1614 	    msg->opcode != dns_opcode_query || msg->rdclass != xfr->rdclass ||
   1615 	    msg->id != xfr->id)
   1616 	{
   1617 		if (result == ISC_R_SUCCESS && msg->rcode != dns_rcode_noerror)
   1618 		{
   1619 			result = dns_result_fromrcode(msg->rcode);
   1620 		} else if (result == ISC_R_SUCCESS &&
   1621 			   msg->opcode != dns_opcode_query)
   1622 		{
   1623 			result = DNS_R_UNEXPECTEDOPCODE;
   1624 		} else if (result == ISC_R_SUCCESS &&
   1625 			   msg->rdclass != xfr->rdclass)
   1626 		{
   1627 			result = DNS_R_BADCLASS;
   1628 		} else if (result == ISC_R_SUCCESS || result == DNS_R_NOERROR) {
   1629 			result = DNS_R_UNEXPECTEDID;
   1630 		}
   1631 
   1632 		if (xfr->reqtype == dns_rdatatype_axfr ||
   1633 		    xfr->reqtype == dns_rdatatype_soa)
   1634 		{
   1635 			goto failure;
   1636 		}
   1637 
   1638 		xfrin_log(xfr, ISC_LOG_DEBUG(3), "got %s, retrying with AXFR",
   1639 			  isc_result_totext(result));
   1640 	try_axfr:
   1641 		isc_nmhandle_detach(&xfr->readhandle);
   1642 		dns_message_detach(&msg);
   1643 		xfrin_reset(xfr);
   1644 		xfr->reqtype = dns_rdatatype_soa;
   1645 		xfr->state = XFRST_SOAQUERY;
   1646 		result = xfrin_start(xfr);
   1647 		if (result != ISC_R_SUCCESS) {
   1648 			xfrin_fail(xfr, result, "failed setting up socket");
   1649 		}
   1650 		dns_xfrin_detach(&xfr); /* recv_xfr */
   1651 		return;
   1652 	}
   1653 
   1654 	/*
   1655 	 * The question section should exist for SOA and in the first
   1656 	 * message of a AXFR or IXFR response.  The question section
   1657 	 * may exist in the 2nd and subsequent messages in a AXFR or
   1658 	 * IXFR response.  If the question section exists it should
   1659 	 * match the question that was sent.
   1660 	 */
   1661 	if (msg->counts[DNS_SECTION_QUESTION] > 1) {
   1662 		xfrin_log(xfr, ISC_LOG_NOTICE, "too many questions (%u)",
   1663 			  msg->counts[DNS_SECTION_QUESTION]);
   1664 		result = DNS_R_FORMERR;
   1665 		goto failure;
   1666 	}
   1667 
   1668 	if ((xfr->state == XFRST_SOAQUERY || xfr->state == XFRST_INITIALSOA) &&
   1669 	    msg->counts[DNS_SECTION_QUESTION] != 1)
   1670 	{
   1671 		xfrin_log(xfr, ISC_LOG_NOTICE, "missing question section");
   1672 		result = DNS_R_FORMERR;
   1673 		goto failure;
   1674 	}
   1675 
   1676 	for (result = dns_message_firstname(msg, DNS_SECTION_QUESTION);
   1677 	     result == ISC_R_SUCCESS;
   1678 	     result = dns_message_nextname(msg, DNS_SECTION_QUESTION))
   1679 	{
   1680 		dns_rdataset_t *rds = NULL;
   1681 
   1682 		name = NULL;
   1683 		dns_message_currentname(msg, DNS_SECTION_QUESTION, &name);
   1684 		if (!dns_name_equal(name, &xfr->name)) {
   1685 			result = DNS_R_FORMERR;
   1686 			xfrin_log(xfr, ISC_LOG_NOTICE,
   1687 				  "question name mismatch");
   1688 			goto failure;
   1689 		}
   1690 		rds = ISC_LIST_HEAD(name->list);
   1691 		INSIST(rds != NULL);
   1692 		if (rds->type != xfr->reqtype) {
   1693 			result = DNS_R_FORMERR;
   1694 			xfrin_log(xfr, ISC_LOG_NOTICE,
   1695 				  "question type mismatch");
   1696 			goto failure;
   1697 		}
   1698 		if (rds->rdclass != xfr->rdclass) {
   1699 			result = DNS_R_FORMERR;
   1700 			xfrin_log(xfr, ISC_LOG_NOTICE,
   1701 				  "question class mismatch");
   1702 			goto failure;
   1703 		}
   1704 	}
   1705 	if (result != ISC_R_NOMORE) {
   1706 		goto failure;
   1707 	}
   1708 
   1709 	/*
   1710 	 * Does the server know about IXFR?  If it doesn't we will get
   1711 	 * a message with a empty answer section or a potentially a CNAME /
   1712 	 * DNAME, the later is handled by xfr_rr() which will return FORMERR
   1713 	 * if the first RR in the answer section is not a SOA record.
   1714 	 */
   1715 	if (xfr->reqtype == dns_rdatatype_ixfr &&
   1716 	    xfr->state == XFRST_INITIALSOA &&
   1717 	    msg->counts[DNS_SECTION_ANSWER] == 0)
   1718 	{
   1719 		xfrin_log(xfr, ISC_LOG_DEBUG(3),
   1720 			  "empty answer section, retrying with AXFR");
   1721 		goto try_axfr;
   1722 	}
   1723 
   1724 	if (xfr->reqtype == dns_rdatatype_soa &&
   1725 	    (msg->flags & DNS_MESSAGEFLAG_AA) == 0)
   1726 	{
   1727 		FAIL(DNS_R_NOTAUTHORITATIVE);
   1728 	}
   1729 
   1730 	result = dns_message_checksig(msg, dns_zone_getview(xfr->zone));
   1731 	if (result != ISC_R_SUCCESS) {
   1732 		xfrin_log(xfr, ISC_LOG_DEBUG(3), "TSIG check failed: %s",
   1733 			  isc_result_totext(result));
   1734 		goto failure;
   1735 	}
   1736 
   1737 	for (result = dns_message_firstname(msg, DNS_SECTION_ANSWER);
   1738 	     result == ISC_R_SUCCESS;
   1739 	     result = dns_message_nextname(msg, DNS_SECTION_ANSWER))
   1740 	{
   1741 		dns_rdataset_t *rds = NULL;
   1742 
   1743 		name = NULL;
   1744 		dns_message_currentname(msg, DNS_SECTION_ANSWER, &name);
   1745 		for (rds = ISC_LIST_HEAD(name->list); rds != NULL;
   1746 		     rds = ISC_LIST_NEXT(rds, link))
   1747 		{
   1748 			for (result = dns_rdataset_first(rds);
   1749 			     result == ISC_R_SUCCESS;
   1750 			     result = dns_rdataset_next(rds))
   1751 			{
   1752 				dns_rdata_t rdata = DNS_RDATA_INIT;
   1753 				dns_rdataset_current(rds, &rdata);
   1754 				CHECK(xfr_rr(xfr, name, rds->ttl, &rdata));
   1755 			}
   1756 		}
   1757 	}
   1758 	if (result != ISC_R_NOMORE) {
   1759 		goto failure;
   1760 	}
   1761 
   1762 	if (dns_message_gettsig(msg, &tsigowner) != NULL) {
   1763 		/*
   1764 		 * Reset the counter.
   1765 		 */
   1766 		xfr->sincetsig = 0;
   1767 
   1768 		/*
   1769 		 * Free the last tsig, if there is one.
   1770 		 */
   1771 		if (xfr->lasttsig != NULL) {
   1772 			isc_buffer_free(&xfr->lasttsig);
   1773 		}
   1774 
   1775 		/*
   1776 		 * Update the last tsig pointer.
   1777 		 */
   1778 		CHECK(dns_message_getquerytsig(msg, xfr->mctx, &xfr->lasttsig));
   1779 	} else if (dns_message_gettsigkey(msg) != NULL) {
   1780 		xfr->sincetsig++;
   1781 		if (xfr->sincetsig > 100 || xfr->nmsg == 0 ||
   1782 		    xfr->state == XFRST_AXFR_END ||
   1783 		    xfr->state == XFRST_IXFR_END)
   1784 		{
   1785 			result = DNS_R_EXPECTEDTSIG;
   1786 			goto failure;
   1787 		}
   1788 	}
   1789 
   1790 	/*
   1791 	 * Update the number of messages received.
   1792 	 */
   1793 	xfr->nmsg++;
   1794 
   1795 	/*
   1796 	 * Update the number of bytes received.
   1797 	 */
   1798 	xfr->nbytes += buffer.used;
   1799 
   1800 	/*
   1801 	 * Take the context back.
   1802 	 */
   1803 	INSIST(xfr->tsigctx == NULL);
   1804 	xfr->tsigctx = msg->tsigctx;
   1805 	msg->tsigctx = NULL;
   1806 
   1807 	switch (xfr->state) {
   1808 	case XFRST_GOTSOA:
   1809 		xfr->reqtype = dns_rdatatype_axfr;
   1810 		xfr->state = XFRST_INITIALSOA;
   1811 		CHECK(xfrin_send_request(xfr));
   1812 		break;
   1813 	case XFRST_AXFR_END:
   1814 		CHECK(axfr_finalize(xfr));
   1815 		FALLTHROUGH;
   1816 	case XFRST_IXFR_END:
   1817 		/*
   1818 		 * Close the journal.
   1819 		 */
   1820 		if (xfr->ixfr.journal != NULL) {
   1821 			dns_journal_destroy(&xfr->ixfr.journal);
   1822 		}
   1823 
   1824 		/*
   1825 		 * Inform the caller we succeeded.
   1826 		 */
   1827 		if (xfr->done != NULL) {
   1828 			(xfr->done)(xfr->zone, ISC_R_SUCCESS);
   1829 			xfr->done = NULL;
   1830 		}
   1831 
   1832 		atomic_store(&xfr->shuttingdown, true);
   1833 		(void)isc_timer_reset(xfr->max_time_timer,
   1834 				      isc_timertype_inactive, NULL, NULL, true);
   1835 		xfr->shutdown_result = ISC_R_SUCCESS;
   1836 		break;
   1837 	default:
   1838 		/*
   1839 		 * Read the next message.
   1840 		 */
   1841 		/* The readhandle is still attached */
   1842 		/* The recv_xfr is still attached */
   1843 		dns_message_detach(&msg);
   1844 		isc_refcount_increment0(&xfr->recvs);
   1845 		isc_nm_read(xfr->handle, xfrin_recv_done, xfr);
   1846 		isc_time_t next;
   1847 		isc_interval_t interval;
   1848 		isc_interval_set(&interval, dns_zone_getidlein(xfr->zone), 0);
   1849 		isc_time_nowplusinterval(&next, &interval);
   1850 		result = isc_timer_reset(xfr->max_idle_timer,
   1851 					 isc_timertype_once, &next, NULL, true);
   1852 		RUNTIME_CHECK(result == ISC_R_SUCCESS);
   1853 		return;
   1854 	}
   1855 
   1856 failure:
   1857 	if (result != ISC_R_SUCCESS) {
   1858 		xfrin_fail(xfr, result, "failed while receiving responses");
   1859 	}
   1860 
   1861 	if (msg != NULL) {
   1862 		dns_message_detach(&msg);
   1863 	}
   1864 	isc_nmhandle_detach(&xfr->readhandle);
   1865 	dns_xfrin_detach(&xfr); /* recv_xfr */
   1866 }
   1867 
   1868 static void
   1869 xfrin_destroy(dns_xfrin_ctx_t *xfr) {
   1870 	uint64_t msecs;
   1871 	uint64_t persec;
   1872 	const char *result_str;
   1873 
   1874 	REQUIRE(VALID_XFRIN(xfr));
   1875 
   1876 	/* Safe-guards */
   1877 	REQUIRE(atomic_load(&xfr->shuttingdown));
   1878 	isc_refcount_destroy(&xfr->references);
   1879 	isc_refcount_destroy(&xfr->connects);
   1880 	isc_refcount_destroy(&xfr->recvs);
   1881 	isc_refcount_destroy(&xfr->sends);
   1882 
   1883 	INSIST(xfr->shutdown_result != ISC_R_UNSET);
   1884 
   1885 	/*
   1886 	 * If we're called through dns_xfrin_detach() and are not
   1887 	 * shutting down, we can't know what the transfer status is as
   1888 	 * we are only called when the last reference is lost.
   1889 	 */
   1890 	result_str = isc_result_totext(xfr->shutdown_result);
   1891 	xfrin_log(xfr, ISC_LOG_INFO, "Transfer status: %s", result_str);
   1892 
   1893 	/*
   1894 	 * Calculate the length of time the transfer took,
   1895 	 * and print a log message with the bytes and rate.
   1896 	 */
   1897 	isc_time_now(&xfr->end);
   1898 	msecs = isc_time_microdiff(&xfr->end, &xfr->start) / 1000;
   1899 	if (msecs == 0) {
   1900 		msecs = 1;
   1901 	}
   1902 	persec = (xfr->nbytes * 1000) / msecs;
   1903 	xfrin_log(xfr, ISC_LOG_INFO,
   1904 		  "Transfer completed: %d messages, %d records, "
   1905 		  "%" PRIu64 " bytes, "
   1906 		  "%u.%03u secs (%u bytes/sec) (serial %u)",
   1907 		  xfr->nmsg, xfr->nrecs, xfr->nbytes,
   1908 		  (unsigned int)(msecs / 1000), (unsigned int)(msecs % 1000),
   1909 		  (unsigned int)persec, xfr->end_serial);
   1910 
   1911 	if (xfr->readhandle != NULL) {
   1912 		isc_nmhandle_detach(&xfr->readhandle);
   1913 	}
   1914 	if (xfr->sendhandle != NULL) {
   1915 		isc_nmhandle_detach(&xfr->sendhandle);
   1916 	}
   1917 
   1918 	if (xfr->transport != NULL) {
   1919 		dns_transport_detach(&xfr->transport);
   1920 	}
   1921 
   1922 	if (xfr->tsigkey != NULL) {
   1923 		dns_tsigkey_detach(&xfr->tsigkey);
   1924 	}
   1925 
   1926 	if (xfr->lasttsig != NULL) {
   1927 		isc_buffer_free(&xfr->lasttsig);
   1928 	}
   1929 
   1930 	dns_diff_clear(&xfr->diff);
   1931 
   1932 	if (xfr->ixfr.journal != NULL) {
   1933 		dns_journal_destroy(&xfr->ixfr.journal);
   1934 	}
   1935 
   1936 	if (xfr->axfr.add_private != NULL) {
   1937 		(void)dns_db_endload(xfr->db, &xfr->axfr);
   1938 	}
   1939 
   1940 	if (xfr->tsigctx != NULL) {
   1941 		dst_context_destroy(&xfr->tsigctx);
   1942 	}
   1943 
   1944 	if ((xfr->name.attributes & DNS_NAMEATTR_DYNAMIC) != 0) {
   1945 		dns_name_free(&xfr->name, xfr->mctx);
   1946 	}
   1947 
   1948 	if (xfr->ver != NULL) {
   1949 		dns_db_closeversion(xfr->db, &xfr->ver, false);
   1950 	}
   1951 
   1952 	if (xfr->db != NULL) {
   1953 		dns_db_detach(&xfr->db);
   1954 	}
   1955 
   1956 	if (xfr->zone != NULL) {
   1957 		if (!xfr->zone_had_db &&
   1958 		    xfr->shutdown_result == ISC_R_SUCCESS &&
   1959 		    dns_zone_gettype(xfr->zone) == dns_zone_mirror)
   1960 		{
   1961 			dns_zone_log(xfr->zone, ISC_LOG_INFO,
   1962 				     "mirror zone is now in use");
   1963 		}
   1964 		xfrin_log(xfr, ISC_LOG_DEBUG(99), "freeing transfer context");
   1965 		/*
   1966 		 * xfr->zone must not be detached before xfrin_log() is called.
   1967 		 */
   1968 		dns_zone_idetach(&xfr->zone);
   1969 	}
   1970 
   1971 	if (xfr->firstsoa_data != NULL) {
   1972 		isc_mem_free(xfr->mctx, xfr->firstsoa_data);
   1973 	}
   1974 
   1975 	if (xfr->tlsctx_cache != NULL) {
   1976 		isc_tlsctx_cache_detach(&xfr->tlsctx_cache);
   1977 	}
   1978 
   1979 	isc_timer_destroy(&xfr->max_idle_timer);
   1980 	isc_timer_destroy(&xfr->max_time_timer);
   1981 
   1982 	isc_mem_putanddetach(&xfr->mctx, xfr, sizeof(*xfr));
   1983 }
   1984 
   1985 /*
   1986  * Log incoming zone transfer messages in a format like
   1987  * transfer of <zone> from <address>: <message>
   1988  */
   1989 static void
   1990 xfrin_logv(int level, const char *zonetext, const isc_sockaddr_t *primaryaddr,
   1991 	   const char *fmt, va_list ap) {
   1992 	char primarytext[ISC_SOCKADDR_FORMATSIZE];
   1993 	char msgtext[2048];
   1994 
   1995 	isc_sockaddr_format(primaryaddr, primarytext, sizeof(primarytext));
   1996 	vsnprintf(msgtext, sizeof(msgtext), fmt, ap);
   1997 
   1998 	isc_log_write(dns_lctx, DNS_LOGCATEGORY_XFER_IN, DNS_LOGMODULE_XFER_IN,
   1999 		      level, "transfer of '%s' from %s: %s", zonetext,
   2000 		      primarytext, msgtext);
   2001 }
   2002 
   2003 /*
   2004  * Logging function for use when a xfrin_ctx_t has not yet been created.
   2005  */
   2006 
   2007 static void
   2008 xfrin_log1(int level, const char *zonetext, const isc_sockaddr_t *primaryaddr,
   2009 	   const char *fmt, ...) {
   2010 	va_list ap;
   2011 
   2012 	if (!isc_log_wouldlog(dns_lctx, level)) {
   2013 		return;
   2014 	}
   2015 
   2016 	va_start(ap, fmt);
   2017 	xfrin_logv(level, zonetext, primaryaddr, fmt, ap);
   2018 	va_end(ap);
   2019 }
   2020 
   2021 /*
   2022  * Logging function for use when there is a xfrin_ctx_t.
   2023  */
   2024 
   2025 static void
   2026 xfrin_log(dns_xfrin_ctx_t *xfr, int level, const char *fmt, ...) {
   2027 	va_list ap;
   2028 	char zonetext[DNS_NAME_MAXTEXT + 32];
   2029 
   2030 	if (!isc_log_wouldlog(dns_lctx, level)) {
   2031 		return;
   2032 	}
   2033 
   2034 	dns_zone_name(xfr->zone, zonetext, sizeof(zonetext));
   2035 
   2036 	va_start(ap, fmt);
   2037 	xfrin_logv(level, zonetext, &xfr->primaryaddr, fmt, ap);
   2038 	va_end(ap);
   2039 }
   2040