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