Home | History | Annotate | Line # | Download | only in ns
update.c revision 1.2.2.3
      1 /*	$NetBSD: update.c,v 1.2.2.3 2019/01/18 08:50:03 pgoyette Exp $	*/
      2 
      3 /*
      4  * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
      5  *
      6  * This Source Code Form is subject to the terms of the Mozilla Public
      7  * License, v. 2.0. If a copy of the MPL was not distributed with this
      8  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
      9  *
     10  * See the COPYRIGHT file distributed with this work for additional
     11  * information regarding copyright ownership.
     12  */
     13 
     14 #include <config.h>
     15 
     16 #include <stdbool.h>
     17 #include <inttypes.h>
     18 
     19 #include <isc/netaddr.h>
     20 #include <isc/print.h>
     21 #include <isc/serial.h>
     22 #include <isc/stats.h>
     23 #include <isc/string.h>
     24 #include <isc/taskpool.h>
     25 #include <isc/util.h>
     26 
     27 #include <dns/db.h>
     28 #include <dns/dbiterator.h>
     29 #include <dns/diff.h>
     30 #include <dns/dnssec.h>
     31 #include <dns/events.h>
     32 #include <dns/fixedname.h>
     33 #include <dns/journal.h>
     34 #include <dns/keyvalues.h>
     35 #include <dns/message.h>
     36 #include <dns/nsec.h>
     37 #include <dns/nsec3.h>
     38 #include <dns/private.h>
     39 #include <dns/rdataclass.h>
     40 #include <dns/rdataset.h>
     41 #include <dns/rdatasetiter.h>
     42 #include <dns/rdatastruct.h>
     43 #include <dns/rdatatype.h>
     44 #include <dns/soa.h>
     45 #include <dns/ssu.h>
     46 #include <dns/tsig.h>
     47 #include <dns/update.h>
     48 #include <dns/view.h>
     49 #include <dns/zone.h>
     50 #include <dns/zt.h>
     51 
     52 #include <ns/client.h>
     53 #include <ns/interfacemgr.h>
     54 #include <ns/log.h>
     55 #include <ns/server.h>
     56 #include <ns/stats.h>
     57 #include <ns/update.h>
     58 
     59 /*! \file
     60  * \brief
     61  * This module implements dynamic update as in RFC2136.
     62  */
     63 
     64 /*
     65  *  XXX TODO:
     66  * - document strict minimality
     67  */
     68 
     69 /**************************************************************************/
     70 
     71 /*%
     72  * Log level for tracing dynamic update protocol requests.
     73  */
     74 #define LOGLEVEL_PROTOCOL	ISC_LOG_INFO
     75 
     76 /*%
     77  * Log level for low-level debug tracing.
     78  */
     79 #define LOGLEVEL_DEBUG		ISC_LOG_DEBUG(8)
     80 
     81 /*%
     82  * Check an operation for failure.  These macros all assume that
     83  * the function using them has a 'result' variable and a 'failure'
     84  * label.
     85  */
     86 #define CHECK(op) \
     87 	do { result = (op); \
     88 		if (result != ISC_R_SUCCESS) goto failure; \
     89 	} while (0)
     90 
     91 /*%
     92  * Fail unconditionally with result 'code', which must not
     93  * be ISC_R_SUCCESS.  The reason for failure presumably has
     94  * been logged already.
     95  *
     96  * The test against ISC_R_SUCCESS is there to keep the Solaris compiler
     97  * from complaining about "end-of-loop code not reached".
     98  */
     99 
    100 #define FAIL(code) \
    101 	do {							\
    102 		result = (code);				\
    103 		if (result != ISC_R_SUCCESS) goto failure;	\
    104 	} while (0)
    105 
    106 /*%
    107  * Fail unconditionally and log as a client error.
    108  * The test against ISC_R_SUCCESS is there to keep the Solaris compiler
    109  * from complaining about "end-of-loop code not reached".
    110  */
    111 #define FAILC(code, msg) \
    112 	do {							\
    113 		const char *_what = "failed";			\
    114 		result = (code);				\
    115 		switch (result) {				\
    116 		case DNS_R_NXDOMAIN:				\
    117 		case DNS_R_YXDOMAIN:				\
    118 		case DNS_R_YXRRSET:				\
    119 		case DNS_R_NXRRSET:				\
    120 			_what = "unsuccessful";			\
    121 		}						\
    122 		update_log(client, zone, LOGLEVEL_PROTOCOL,	\
    123 			   "update %s: %s (%s)", _what,		\
    124 			   msg, isc_result_totext(result));	\
    125 		if (result != ISC_R_SUCCESS) goto failure;	\
    126 	} while (0)
    127 #define PREREQFAILC(code, msg) \
    128 	do {							\
    129 		inc_stats(client, zone, ns_statscounter_updatebadprereq); \
    130 		FAILC(code, msg);				\
    131 	} while (0)
    132 
    133 #define FAILN(code, name, msg) \
    134 	do {								\
    135 		const char *_what = "failed";				\
    136 		result = (code);					\
    137 		switch (result) {					\
    138 		case DNS_R_NXDOMAIN:					\
    139 		case DNS_R_YXDOMAIN:					\
    140 		case DNS_R_YXRRSET:					\
    141 		case DNS_R_NXRRSET:					\
    142 			_what = "unsuccessful";				\
    143 		}							\
    144 		if (isc_log_wouldlog(ns_lctx, LOGLEVEL_PROTOCOL)) {	\
    145 			char _nbuf[DNS_NAME_FORMATSIZE];		\
    146 			dns_name_format(name, _nbuf, sizeof(_nbuf));	\
    147 			update_log(client, zone, LOGLEVEL_PROTOCOL,	\
    148 				   "update %s: %s: %s (%s)", _what, _nbuf, \
    149 				   msg, isc_result_totext(result));	\
    150 		}							\
    151 		if (result != ISC_R_SUCCESS) goto failure;		\
    152 	} while (0)
    153 #define PREREQFAILN(code, name, msg) \
    154 	do {								\
    155 		inc_stats(client, zone, ns_statscounter_updatebadprereq); \
    156 		FAILN(code, name, msg);					\
    157 	} while (0)
    158 
    159 #define FAILNT(code, name, type, msg) \
    160 	do {								\
    161 		const char *_what = "failed";				\
    162 		result = (code);					\
    163 		switch (result) {					\
    164 		case DNS_R_NXDOMAIN:					\
    165 		case DNS_R_YXDOMAIN:					\
    166 		case DNS_R_YXRRSET:					\
    167 		case DNS_R_NXRRSET:					\
    168 			_what = "unsuccessful";				\
    169 		}							\
    170 		if (isc_log_wouldlog(ns_lctx, LOGLEVEL_PROTOCOL)) {	\
    171 			char _nbuf[DNS_NAME_FORMATSIZE];		\
    172 			char _tbuf[DNS_RDATATYPE_FORMATSIZE];		\
    173 			dns_name_format(name, _nbuf, sizeof(_nbuf));	\
    174 			dns_rdatatype_format(type, _tbuf, sizeof(_tbuf)); \
    175 			update_log(client, zone, LOGLEVEL_PROTOCOL,	\
    176 				   "update %s: %s/%s: %s (%s)",		\
    177 				   _what, _nbuf, _tbuf, msg,		\
    178 				   isc_result_totext(result));		\
    179 		}							\
    180 		if (result != ISC_R_SUCCESS) goto failure;		\
    181 	} while (0)
    182 #define PREREQFAILNT(code, name, type, msg)				\
    183 	do {								\
    184 		inc_stats(client, zone, ns_statscounter_updatebadprereq); \
    185 		FAILNT(code, name, type, msg);				\
    186 	} while (0)
    187 
    188 /*%
    189  * Fail unconditionally and log as a server error.
    190  * The test against ISC_R_SUCCESS is there to keep the Solaris compiler
    191  * from complaining about "end-of-loop code not reached".
    192  */
    193 #define FAILS(code, msg) \
    194 	do {							\
    195 		result = (code);				\
    196 		update_log(client, zone, LOGLEVEL_PROTOCOL,	\
    197 			   "error: %s: %s",			\
    198 			   msg, isc_result_totext(result));	\
    199 		if (result != ISC_R_SUCCESS) goto failure;	\
    200 	} while (0)
    201 
    202 /*
    203  * Return TRUE if NS_CLIENTATTR_TCP is set in the attributes other FALSE.
    204  */
    205 #define TCPCLIENT(client) (((client)->attributes & NS_CLIENTATTR_TCP) != 0)
    206 
    207 /**************************************************************************/
    208 
    209 typedef struct rr rr_t;
    210 
    211 struct rr {
    212 	/* dns_name_t name; */
    213 	uint32_t		ttl;
    214 	dns_rdata_t		rdata;
    215 };
    216 
    217 typedef struct update_event update_event_t;
    218 
    219 struct update_event {
    220 	ISC_EVENT_COMMON(update_event_t);
    221 	dns_zone_t		*zone;
    222 	isc_result_t		result;
    223 	dns_message_t		*answer;
    224 };
    225 
    226 /*%
    227  * Prepare an RR for the addition of the new RR 'ctx->update_rr',
    228  * with TTL 'ctx->update_rr_ttl', to its rdataset, by deleting
    229  * the RRs if it is replaced by the new RR or has a conflicting TTL.
    230  * The necessary changes are appended to ctx->del_diff and ctx->add_diff;
    231  * we need to do all deletions before any additions so that we don't run
    232  * into transient states with conflicting TTLs.
    233  */
    234 
    235 typedef struct {
    236 	dns_db_t *db;
    237 	dns_dbversion_t *ver;
    238 	dns_diff_t *diff;
    239 	dns_name_t *name;
    240 	dns_name_t *oldname;
    241 	dns_rdata_t *update_rr;
    242 	dns_ttl_t update_rr_ttl;
    243 	bool ignore_add;
    244 	dns_diff_t del_diff;
    245 	dns_diff_t add_diff;
    246 } add_rr_prepare_ctx_t;
    247 
    248 /**************************************************************************/
    249 /*
    250  * Forward declarations.
    251  */
    252 
    253 static void update_action(isc_task_t *task, isc_event_t *event);
    254 static void updatedone_action(isc_task_t *task, isc_event_t *event);
    255 static isc_result_t send_forward_event(ns_client_t *client, dns_zone_t *zone);
    256 static void forward_done(isc_task_t *task, isc_event_t *event);
    257 static isc_result_t add_rr_prepare_action(void *data, rr_t *rr);
    258 
    259 /**************************************************************************/
    260 
    261 static void
    262 update_log(ns_client_t *client, dns_zone_t *zone,
    263 	   int level, const char *fmt, ...) ISC_FORMAT_PRINTF(4, 5);
    264 
    265 static void
    266 update_log(ns_client_t *client, dns_zone_t *zone,
    267 	   int level, const char *fmt, ...)
    268 {
    269 	va_list ap;
    270 	char message[4096];
    271 	char namebuf[DNS_NAME_FORMATSIZE];
    272 	char classbuf[DNS_RDATACLASS_FORMATSIZE];
    273 
    274 	if (client == NULL) {
    275 		return;
    276 	}
    277 
    278 	if (isc_log_wouldlog(ns_lctx, level) == false) {
    279 		return;
    280 	}
    281 
    282 	va_start(ap, fmt);
    283 	vsnprintf(message, sizeof(message), fmt, ap);
    284 	va_end(ap);
    285 
    286 	if (zone != NULL) {
    287 		dns_name_format(dns_zone_getorigin(zone), namebuf,
    288 				sizeof(namebuf));
    289 		dns_rdataclass_format(dns_zone_getclass(zone), classbuf,
    290 				      sizeof(classbuf));
    291 
    292 		ns_client_log(client, NS_LOGCATEGORY_UPDATE,
    293 			      NS_LOGMODULE_UPDATE,
    294 			      level, "updating zone '%s/%s': %s",
    295 			      namebuf, classbuf, message);
    296 	} else {
    297 		ns_client_log(client, NS_LOGCATEGORY_UPDATE,
    298 			      NS_LOGMODULE_UPDATE,
    299 			      level, "%s", message);
    300 	}
    301 
    302 }
    303 
    304 static void
    305 update_log_cb(void *arg, dns_zone_t *zone, int level, const char *message) {
    306 	update_log(arg, zone, level, "%s", message);
    307 }
    308 
    309 /*%
    310  * Increment updated-related statistics counters.
    311  */
    312 static inline void
    313 inc_stats(ns_client_t *client, dns_zone_t *zone, isc_statscounter_t counter) {
    314 	ns_stats_increment(client->sctx->nsstats, counter);
    315 
    316 	if (zone != NULL) {
    317 		isc_stats_t *zonestats = dns_zone_getrequeststats(zone);
    318 		if (zonestats != NULL)
    319 			isc_stats_increment(zonestats, counter);
    320 	}
    321 }
    322 
    323 /*%
    324  * Check if we could have queried for the contents of this zone or
    325  * if the zone is potentially updateable.
    326  * If the zone can potentially be updated and the check failed then
    327  * log a error otherwise we log a informational message.
    328  */
    329 static isc_result_t
    330 checkqueryacl(ns_client_t *client, dns_acl_t *queryacl, dns_name_t *zonename,
    331 	      dns_acl_t *updateacl, dns_ssutable_t *ssutable)
    332 {
    333 	char namebuf[DNS_NAME_FORMATSIZE];
    334 	char classbuf[DNS_RDATACLASS_FORMATSIZE];
    335 	int level;
    336 	isc_result_t result;
    337 
    338 	result = ns_client_checkaclsilent(client, NULL, queryacl, true);
    339 	if (result != ISC_R_SUCCESS) {
    340 		dns_name_format(zonename, namebuf, sizeof(namebuf));
    341 		dns_rdataclass_format(client->view->rdclass, classbuf,
    342 				      sizeof(classbuf));
    343 
    344 		level = (updateacl == NULL && ssutable == NULL) ?
    345 				ISC_LOG_INFO : ISC_LOG_ERROR;
    346 
    347 		ns_client_log(client, NS_LOGCATEGORY_UPDATE_SECURITY,
    348 			      NS_LOGMODULE_UPDATE, level,
    349 			      "update '%s/%s' denied due to allow-query",
    350 			      namebuf, classbuf);
    351 	} else if (updateacl == NULL && ssutable == NULL) {
    352 		dns_name_format(zonename, namebuf, sizeof(namebuf));
    353 		dns_rdataclass_format(client->view->rdclass, classbuf,
    354 				      sizeof(classbuf));
    355 
    356 		result = DNS_R_REFUSED;
    357 		ns_client_log(client, NS_LOGCATEGORY_UPDATE_SECURITY,
    358 			      NS_LOGMODULE_UPDATE, ISC_LOG_INFO,
    359 			      "update '%s/%s' denied", namebuf, classbuf);
    360 	}
    361 	return (result);
    362 }
    363 
    364 /*%
    365  * Override the default acl logging when checking whether a client
    366  * can update the zone or whether we can forward the request to the
    367  * master based on IP address.
    368  *
    369  * 'message' contains the type of operation that is being attempted.
    370  * 'slave' indicates if this is a slave zone.  If 'acl' is NULL then
    371  * log at debug=3.
    372  * If the zone has no access controls configured ('acl' == NULL &&
    373  * 'has_ssutable == ISC_FALS) log the attempt at info, otherwise
    374  * at error.
    375  *
    376  * If the request was signed log that we received it.
    377  */
    378 static isc_result_t
    379 checkupdateacl(ns_client_t *client, dns_acl_t *acl, const char *message,
    380 	       dns_name_t *zonename, bool slave,
    381 	       bool has_ssutable)
    382 {
    383 	char namebuf[DNS_NAME_FORMATSIZE];
    384 	char classbuf[DNS_RDATACLASS_FORMATSIZE];
    385 	int level = ISC_LOG_ERROR;
    386 	const char *msg = "denied";
    387 	isc_result_t result;
    388 
    389 	if (slave && acl == NULL) {
    390 		result = DNS_R_NOTIMP;
    391 		level = ISC_LOG_DEBUG(3);
    392 		msg = "disabled";
    393 	} else {
    394 		result = ns_client_checkaclsilent(client, NULL, acl, false);
    395 		if (result == ISC_R_SUCCESS) {
    396 			level = ISC_LOG_DEBUG(3);
    397 			msg = "approved";
    398 		} else if (acl == NULL && !has_ssutable) {
    399 			level = ISC_LOG_INFO;
    400 		}
    401 	}
    402 
    403 	if (client->signer != NULL) {
    404 		dns_name_format(client->signer, namebuf, sizeof(namebuf));
    405 		ns_client_log(client, NS_LOGCATEGORY_UPDATE_SECURITY,
    406 			      NS_LOGMODULE_UPDATE, ISC_LOG_INFO,
    407 			      "signer \"%s\" %s", namebuf, msg);
    408 	}
    409 
    410 	dns_name_format(zonename, namebuf, sizeof(namebuf));
    411 	dns_rdataclass_format(client->view->rdclass, classbuf,
    412 			      sizeof(classbuf));
    413 
    414 	ns_client_log(client, NS_LOGCATEGORY_UPDATE_SECURITY,
    415 		      NS_LOGMODULE_UPDATE, level, "%s '%s/%s' %s",
    416 		      message, namebuf, classbuf, msg);
    417 	return (result);
    418 }
    419 
    420 /*%
    421  * Update a single RR in version 'ver' of 'db' and log the
    422  * update in 'diff'.
    423  *
    424  * Ensures:
    425  * \li	'*tuple' == NULL.  Either the tuple is freed, or its
    426  *	ownership has been transferred to the diff.
    427  */
    428 static isc_result_t
    429 do_one_tuple(dns_difftuple_t **tuple, dns_db_t *db, dns_dbversion_t *ver,
    430 	     dns_diff_t *diff)
    431 {
    432 	dns_diff_t temp_diff;
    433 	isc_result_t result;
    434 
    435 	/*
    436 	 * Create a singleton diff.
    437 	 */
    438 	dns_diff_init(diff->mctx, &temp_diff);
    439 	ISC_LIST_APPEND(temp_diff.tuples, *tuple, link);
    440 
    441 	/*
    442 	 * Apply it to the database.
    443 	 */
    444 	result = dns_diff_apply(&temp_diff, db, ver);
    445 	ISC_LIST_UNLINK(temp_diff.tuples, *tuple, link);
    446 	if (result != ISC_R_SUCCESS) {
    447 		dns_difftuple_free(tuple);
    448 		return (result);
    449 	}
    450 
    451 	/*
    452 	 * Merge it into the current pending journal entry.
    453 	 */
    454 	dns_diff_appendminimal(diff, tuple);
    455 
    456 	/*
    457 	 * Do not clear temp_diff.
    458 	 */
    459 	return (ISC_R_SUCCESS);
    460 }
    461 
    462 /*%
    463  * Perform the updates in 'updates' in version 'ver' of 'db' and log the
    464  * update in 'diff'.
    465  *
    466  * Ensures:
    467  * \li	'updates' is empty.
    468  */
    469 static isc_result_t
    470 do_diff(dns_diff_t *updates, dns_db_t *db, dns_dbversion_t *ver,
    471 	dns_diff_t *diff)
    472 {
    473 	isc_result_t result;
    474 	while (! ISC_LIST_EMPTY(updates->tuples)) {
    475 		dns_difftuple_t *t = ISC_LIST_HEAD(updates->tuples);
    476 		ISC_LIST_UNLINK(updates->tuples, t, link);
    477 		CHECK(do_one_tuple(&t, db, ver, diff));
    478 	}
    479 	return (ISC_R_SUCCESS);
    480 
    481  failure:
    482 	dns_diff_clear(diff);
    483 	return (result);
    484 }
    485 
    486 static isc_result_t
    487 update_one_rr(dns_db_t *db, dns_dbversion_t *ver, dns_diff_t *diff,
    488 	      dns_diffop_t op, dns_name_t *name, dns_ttl_t ttl,
    489 	      dns_rdata_t *rdata)
    490 {
    491 	dns_difftuple_t *tuple = NULL;
    492 	isc_result_t result;
    493 	result = dns_difftuple_create(diff->mctx, op,
    494 				      name, ttl, rdata, &tuple);
    495 	if (result != ISC_R_SUCCESS)
    496 		return (result);
    497 	return (do_one_tuple(&tuple, db, ver, diff));
    498 }
    499 
    500 /**************************************************************************/
    501 /*
    502  * Callback-style iteration over rdatasets and rdatas.
    503  *
    504  * foreach_rrset() can be used to iterate over the RRsets
    505  * of a name and call a callback function with each
    506  * one.  Similarly, foreach_rr() can be used to iterate
    507  * over the individual RRs at name, optionally restricted
    508  * to RRs of a given type.
    509  *
    510  * The callback functions are called "actions" and take
    511  * two arguments: a void pointer for passing arbitrary
    512  * context information, and a pointer to the current RRset
    513  * or RR.  By convention, their names end in "_action".
    514  */
    515 
    516 /*
    517  * XXXRTH  We might want to make this public somewhere in libdns.
    518  */
    519 
    520 /*%
    521  * Function type for foreach_rrset() iterator actions.
    522  */
    523 typedef isc_result_t rrset_func(void *data, dns_rdataset_t *rrset);
    524 
    525 /*%
    526  * Function type for foreach_rr() iterator actions.
    527  */
    528 typedef isc_result_t rr_func(void *data, rr_t *rr);
    529 
    530 /*%
    531  * Internal context struct for foreach_node_rr().
    532  */
    533 typedef struct {
    534 	rr_func *	rr_action;
    535 	void *		rr_action_data;
    536 } foreach_node_rr_ctx_t;
    537 
    538 /*%
    539  * Internal helper function for foreach_node_rr().
    540  */
    541 static isc_result_t
    542 foreach_node_rr_action(void *data, dns_rdataset_t *rdataset) {
    543 	isc_result_t result;
    544 	foreach_node_rr_ctx_t *ctx = data;
    545 	for (result = dns_rdataset_first(rdataset);
    546 	     result == ISC_R_SUCCESS;
    547 	     result = dns_rdataset_next(rdataset))
    548 	{
    549 		rr_t rr = { 0, DNS_RDATA_INIT };
    550 
    551 		dns_rdataset_current(rdataset, &rr.rdata);
    552 		rr.ttl = rdataset->ttl;
    553 		result = (*ctx->rr_action)(ctx->rr_action_data, &rr);
    554 		if (result != ISC_R_SUCCESS)
    555 			return (result);
    556 	}
    557 	if (result != ISC_R_NOMORE)
    558 		return (result);
    559 	return (ISC_R_SUCCESS);
    560 }
    561 
    562 /*%
    563  * For each rdataset of 'name' in 'ver' of 'db', call 'action'
    564  * with the rdataset and 'action_data' as arguments.  If the name
    565  * does not exist, do nothing.
    566  *
    567  * If 'action' returns an error, abort iteration and return the error.
    568  */
    569 static isc_result_t
    570 foreach_rrset(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
    571 	      rrset_func *action, void *action_data)
    572 {
    573 	isc_result_t result;
    574 	dns_dbnode_t *node;
    575 	dns_rdatasetiter_t *iter;
    576 	dns_clientinfomethods_t cm;
    577 	dns_clientinfo_t ci;
    578 	dns_dbversion_t *oldver = NULL;
    579 
    580 	dns_clientinfomethods_init(&cm, ns_client_sourceip);
    581 
    582 	/*
    583 	 * Only set the clientinfo 'versionp' if the new version is
    584 	 * different from the current version
    585 	 */
    586 	dns_db_currentversion(db, &oldver);
    587 	dns_clientinfo_init(&ci, NULL, (ver != oldver) ? ver : NULL);
    588 	dns_db_closeversion(db, &oldver, false);
    589 
    590 	node = NULL;
    591 	result = dns_db_findnodeext(db, name, false, &cm, &ci, &node);
    592 	if (result == ISC_R_NOTFOUND)
    593 		return (ISC_R_SUCCESS);
    594 	if (result != ISC_R_SUCCESS)
    595 		return (result);
    596 
    597 	iter = NULL;
    598 	result = dns_db_allrdatasets(db, node, ver,
    599 				     (isc_stdtime_t) 0, &iter);
    600 	if (result != ISC_R_SUCCESS)
    601 		goto cleanup_node;
    602 
    603 	for (result = dns_rdatasetiter_first(iter);
    604 	     result == ISC_R_SUCCESS;
    605 	     result = dns_rdatasetiter_next(iter))
    606 	{
    607 		dns_rdataset_t rdataset;
    608 
    609 		dns_rdataset_init(&rdataset);
    610 		dns_rdatasetiter_current(iter, &rdataset);
    611 
    612 		result = (*action)(action_data, &rdataset);
    613 
    614 		dns_rdataset_disassociate(&rdataset);
    615 		if (result != ISC_R_SUCCESS)
    616 			goto cleanup_iterator;
    617 	}
    618 	if (result == ISC_R_NOMORE)
    619 		result = ISC_R_SUCCESS;
    620 
    621  cleanup_iterator:
    622 	dns_rdatasetiter_destroy(&iter);
    623 
    624  cleanup_node:
    625 	dns_db_detachnode(db, &node);
    626 
    627 	return (result);
    628 }
    629 
    630 /*%
    631  * For each RR of 'name' in 'ver' of 'db', call 'action'
    632  * with the RR and 'action_data' as arguments.  If the name
    633  * does not exist, do nothing.
    634  *
    635  * If 'action' returns an error, abort iteration
    636  * and return the error.
    637  */
    638 static isc_result_t
    639 foreach_node_rr(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
    640 		rr_func *rr_action, void *rr_action_data)
    641 {
    642 	foreach_node_rr_ctx_t ctx;
    643 	ctx.rr_action = rr_action;
    644 	ctx.rr_action_data = rr_action_data;
    645 	return (foreach_rrset(db, ver, name,
    646 			      foreach_node_rr_action, &ctx));
    647 }
    648 
    649 
    650 /*%
    651  * For each of the RRs specified by 'db', 'ver', 'name', 'type',
    652  * (which can be dns_rdatatype_any to match any type), and 'covers', call
    653  * 'action' with the RR and 'action_data' as arguments. If the name
    654  * does not exist, or if no RRset of the given type exists at the name,
    655  * do nothing.
    656  *
    657  * If 'action' returns an error, abort iteration and return the error.
    658  */
    659 static isc_result_t
    660 foreach_rr(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
    661 	   dns_rdatatype_t type, dns_rdatatype_t covers, rr_func *rr_action,
    662 	   void *rr_action_data)
    663 {
    664 
    665 	isc_result_t result;
    666 	dns_dbnode_t *node;
    667 	dns_rdataset_t rdataset;
    668 	dns_clientinfomethods_t cm;
    669 	dns_clientinfo_t ci;
    670 	dns_dbversion_t *oldver = NULL;
    671 	dns_fixedname_t fixed;
    672 
    673 	dns_clientinfomethods_init(&cm, ns_client_sourceip);
    674 
    675 	/*
    676 	 * Only set the clientinfo 'versionp' if the new version is
    677 	 * different from the current version
    678 	 */
    679 	dns_db_currentversion(db, &oldver);
    680 	dns_clientinfo_init(&ci, NULL, (ver != oldver) ? ver : NULL);
    681 	dns_db_closeversion(db, &oldver, false);
    682 
    683 	if (type == dns_rdatatype_any)
    684 		return (foreach_node_rr(db, ver, name,
    685 					rr_action, rr_action_data));
    686 
    687 	node = NULL;
    688 	if (type == dns_rdatatype_nsec3 ||
    689 	    (type == dns_rdatatype_rrsig && covers == dns_rdatatype_nsec3))
    690 		result = dns_db_findnsec3node(db, name, false, &node);
    691 	else
    692 		result = dns_db_findnodeext(db, name, false,
    693 					    &cm, &ci, &node);
    694 	if (result == ISC_R_NOTFOUND)
    695 		return (ISC_R_SUCCESS);
    696 	if (result != ISC_R_SUCCESS)
    697 		return (result);
    698 
    699 	dns_rdataset_init(&rdataset);
    700 	result = dns_db_findrdataset(db, node, ver, type, covers,
    701 				     (isc_stdtime_t) 0, &rdataset, NULL);
    702 	if (result == ISC_R_NOTFOUND) {
    703 		result = ISC_R_SUCCESS;
    704 		goto cleanup_node;
    705 	}
    706 	if (result != ISC_R_SUCCESS)
    707 		goto cleanup_node;
    708 
    709 	if (rr_action == add_rr_prepare_action) {
    710 		add_rr_prepare_ctx_t *ctx = rr_action_data;
    711 
    712 		ctx->oldname = dns_fixedname_initname(&fixed);
    713 		dns_name_copy(name, ctx->oldname, NULL);
    714 		dns_rdataset_getownercase(&rdataset, ctx->oldname);
    715 	}
    716 
    717 	for (result = dns_rdataset_first(&rdataset);
    718 	     result == ISC_R_SUCCESS;
    719 	     result = dns_rdataset_next(&rdataset))
    720 	{
    721 		rr_t rr = { 0, DNS_RDATA_INIT };
    722 		dns_rdataset_current(&rdataset, &rr.rdata);
    723 		rr.ttl = rdataset.ttl;
    724 		result = (*rr_action)(rr_action_data, &rr);
    725 		if (result != ISC_R_SUCCESS)
    726 			goto cleanup_rdataset;
    727 	}
    728 	if (result != ISC_R_NOMORE)
    729 		goto cleanup_rdataset;
    730 	result = ISC_R_SUCCESS;
    731 
    732  cleanup_rdataset:
    733 	dns_rdataset_disassociate(&rdataset);
    734  cleanup_node:
    735 	dns_db_detachnode(db, &node);
    736 
    737 	return (result);
    738 }
    739 
    740 /**************************************************************************/
    741 /*
    742  * Various tests on the database contents (for prerequisites, etc).
    743  */
    744 
    745 /*%
    746  * Function type for predicate functions that compare a database RR 'db_rr'
    747  * against an update RR 'update_rr'.
    748  */
    749 typedef bool rr_predicate(dns_rdata_t *update_rr, dns_rdata_t *db_rr);
    750 
    751 /*%
    752  * Helper function for rrset_exists().
    753  */
    754 static isc_result_t
    755 rrset_exists_action(void *data, rr_t *rr) {
    756 	UNUSED(data);
    757 	UNUSED(rr);
    758 	return (ISC_R_EXISTS);
    759 }
    760 
    761 /*%
    762  * Utility macro for RR existence checking functions.
    763  *
    764  * If the variable 'result' has the value ISC_R_EXISTS or
    765  * ISC_R_SUCCESS, set *exists to true or false,
    766  * respectively, and return success.
    767  *
    768  * If 'result' has any other value, there was a failure.
    769  * Return the failure result code and do not set *exists.
    770  *
    771  * This would be more readable as "do { if ... } while(0)",
    772  * but that form generates tons of warnings on Solaris 2.6.
    773  */
    774 #define RETURN_EXISTENCE_FLAG				\
    775 	return ((result == ISC_R_EXISTS) ?		\
    776 		(*exists = true, ISC_R_SUCCESS) :	\
    777 		((result == ISC_R_SUCCESS) ?		\
    778 		 (*exists = false, ISC_R_SUCCESS) :	\
    779 		 result))
    780 
    781 /*%
    782  * Set '*exists' to true iff an rrset of the given type exists,
    783  * to false otherwise.
    784  */
    785 static isc_result_t
    786 rrset_exists(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
    787 	     dns_rdatatype_t type, dns_rdatatype_t covers,
    788 	     bool *exists)
    789 {
    790 	isc_result_t result;
    791 	result = foreach_rr(db, ver, name, type, covers,
    792 			    rrset_exists_action, NULL);
    793 	RETURN_EXISTENCE_FLAG;
    794 }
    795 
    796 /*%
    797  * Helper function for cname_incompatible_rrset_exists.
    798  */
    799 static isc_result_t
    800 cname_compatibility_action(void *data, dns_rdataset_t *rrset) {
    801 	UNUSED(data);
    802 	if (rrset->type != dns_rdatatype_cname &&
    803 	    ! dns_rdatatype_isdnssec(rrset->type))
    804 		return (ISC_R_EXISTS);
    805 	return (ISC_R_SUCCESS);
    806 }
    807 
    808 /*%
    809  * Check whether there is an rrset incompatible with adding a CNAME RR,
    810  * i.e., anything but another CNAME (which can be replaced) or a
    811  * DNSSEC RR (which can coexist).
    812  *
    813  * If such an incompatible rrset exists, set '*exists' to true.
    814  * Otherwise, set it to false.
    815  */
    816 static isc_result_t
    817 cname_incompatible_rrset_exists(dns_db_t *db, dns_dbversion_t *ver,
    818 				dns_name_t *name, bool *exists) {
    819 	isc_result_t result;
    820 	result = foreach_rrset(db, ver, name,
    821 			       cname_compatibility_action, NULL);
    822 	RETURN_EXISTENCE_FLAG;
    823 }
    824 
    825 /*%
    826  * Helper function for rr_count().
    827  */
    828 static isc_result_t
    829 count_rr_action(void *data, rr_t *rr) {
    830 	int *countp = data;
    831 	UNUSED(rr);
    832 	(*countp)++;
    833 	return (ISC_R_SUCCESS);
    834 }
    835 
    836 /*%
    837  * Count the number of RRs of 'type' belonging to 'name' in 'ver' of 'db'.
    838  */
    839 static isc_result_t
    840 rr_count(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
    841 	 dns_rdatatype_t type, dns_rdatatype_t covers, int *countp)
    842 {
    843 	*countp = 0;
    844 	return (foreach_rr(db, ver, name, type, covers,
    845 			   count_rr_action, countp));
    846 }
    847 
    848 /*%
    849  * Context struct and helper function for name_exists().
    850  */
    851 
    852 static isc_result_t
    853 name_exists_action(void *data, dns_rdataset_t *rrset) {
    854 	UNUSED(data);
    855 	UNUSED(rrset);
    856 	return (ISC_R_EXISTS);
    857 }
    858 
    859 /*%
    860  * Set '*exists' to true iff the given name exists, to false otherwise.
    861  */
    862 static isc_result_t
    863 name_exists(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
    864 	    bool *exists)
    865 {
    866 	isc_result_t result;
    867 	result = foreach_rrset(db, ver, name,
    868 			       name_exists_action, NULL);
    869 	RETURN_EXISTENCE_FLAG;
    870 }
    871 
    872 /*
    873  *	'ssu_check_t' is used to pass the arguments to
    874  *	dns_ssutable_checkrules() to the callback function
    875  *	ssu_checkrule().
    876  */
    877 typedef struct {
    878 	/* The ownername of the record to be updated. */
    879 	dns_name_t *name;
    880 
    881 	/* The signature's name if the request was signed. */
    882 	dns_name_t *signer;
    883 
    884 	/* The address of the client. */
    885 	isc_netaddr_t *addr;
    886 
    887 	/* The ACL environment */
    888 	dns_aclenv_t *aclenv;
    889 
    890 	/* Whether the request was sent via TCP. */
    891 	bool tcp;
    892 
    893 	/* The ssu table to check against. */
    894 	dns_ssutable_t *table;
    895 
    896 	/* the key used for TKEY requests */
    897 	dst_key_t *key;
    898 } ssu_check_t;
    899 
    900 static isc_result_t
    901 ssu_checkrule(void *data, dns_rdataset_t *rrset) {
    902 	ssu_check_t *ssuinfo = data;
    903 	bool result;
    904 
    905 	/*
    906 	 * If we're deleting all records, it's ok to delete RRSIG and NSEC even
    907 	 * if we're normally not allowed to.
    908 	 */
    909 	if (rrset->type == dns_rdatatype_rrsig ||
    910 	    rrset->type == dns_rdatatype_nsec)
    911 		return (ISC_R_SUCCESS);
    912 	result = dns_ssutable_checkrules(ssuinfo->table, ssuinfo->signer,
    913 					 ssuinfo->name, ssuinfo->addr,
    914 					 ssuinfo->tcp, ssuinfo->aclenv,
    915 					 rrset->type, ssuinfo->key);
    916 	return (result == true ? ISC_R_SUCCESS : ISC_R_FAILURE);
    917 }
    918 
    919 static bool
    920 ssu_checkall(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
    921 	     dns_ssutable_t *ssutable, dns_name_t *signer,
    922 	     isc_netaddr_t *addr, dns_aclenv_t *aclenv, bool tcp,
    923 	     dst_key_t *key)
    924 {
    925 	isc_result_t result;
    926 	ssu_check_t ssuinfo;
    927 
    928 	ssuinfo.name = name;
    929 	ssuinfo.table = ssutable;
    930 	ssuinfo.signer = signer;
    931 	ssuinfo.addr = addr;
    932 	ssuinfo.aclenv = aclenv;
    933 	ssuinfo.tcp = tcp;
    934 	ssuinfo.key = key;
    935 	result = foreach_rrset(db, ver, name, ssu_checkrule, &ssuinfo);
    936 	return (result == ISC_R_SUCCESS);
    937 }
    938 
    939 /**************************************************************************/
    940 /*
    941  * Checking of "RRset exists (value dependent)" prerequisites.
    942  *
    943  * In the RFC2136 section 3.2.5, this is the pseudocode involving
    944  * a variable called "temp", a mapping of <name, type> tuples to rrsets.
    945  *
    946  * Here, we represent the "temp" data structure as (non-minimal) "dns_diff_t"
    947  * where each tuple has op==DNS_DIFFOP_EXISTS.
    948  */
    949 
    950 
    951 /*%
    952  * Append a tuple asserting the existence of the RR with
    953  * 'name' and 'rdata' to 'diff'.
    954  */
    955 static isc_result_t
    956 temp_append(dns_diff_t *diff, dns_name_t *name, dns_rdata_t *rdata) {
    957 	isc_result_t result;
    958 	dns_difftuple_t *tuple = NULL;
    959 
    960 	REQUIRE(DNS_DIFF_VALID(diff));
    961 	CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_EXISTS,
    962 				   name, 0, rdata, &tuple));
    963 	ISC_LIST_APPEND(diff->tuples, tuple, link);
    964  failure:
    965 	return (result);
    966 }
    967 
    968 /*%
    969  * Compare two rdatasets represented as sorted lists of tuples.
    970  * All list elements must have the same owner name and type.
    971  * Return ISC_R_SUCCESS if the rdatasets are equal, rcode(dns_rcode_nxrrset)
    972  * if not.
    973  */
    974 static isc_result_t
    975 temp_check_rrset(dns_difftuple_t *a, dns_difftuple_t *b) {
    976 	for (;;) {
    977 		if (a == NULL || b == NULL)
    978 			break;
    979 		INSIST(a->op == DNS_DIFFOP_EXISTS &&
    980 		       b->op == DNS_DIFFOP_EXISTS);
    981 		INSIST(a->rdata.type == b->rdata.type);
    982 		INSIST(dns_name_equal(&a->name, &b->name));
    983 		if (dns_rdata_casecompare(&a->rdata, &b->rdata) != 0)
    984 			return (DNS_R_NXRRSET);
    985 		a = ISC_LIST_NEXT(a, link);
    986 		b = ISC_LIST_NEXT(b, link);
    987 	}
    988 	if (a != NULL || b != NULL)
    989 		return (DNS_R_NXRRSET);
    990 	return (ISC_R_SUCCESS);
    991 }
    992 
    993 /*%
    994  * A comparison function defining the sorting order for the entries
    995  * in the "temp" data structure.  The major sort key is the owner name,
    996  * followed by the type and rdata.
    997  */
    998 static int
    999 temp_order(const void *av, const void *bv) {
   1000 	dns_difftuple_t const * const *ap = av;
   1001 	dns_difftuple_t const * const *bp = bv;
   1002 	dns_difftuple_t const *a = *ap;
   1003 	dns_difftuple_t const *b = *bp;
   1004 	int r;
   1005 	r = dns_name_compare(&a->name, &b->name);
   1006 	if (r != 0)
   1007 		return (r);
   1008 	r = (b->rdata.type - a->rdata.type);
   1009 	if (r != 0)
   1010 		return (r);
   1011 	r = dns_rdata_casecompare(&a->rdata, &b->rdata);
   1012 	return (r);
   1013 }
   1014 
   1015 /*%
   1016  * Check the "RRset exists (value dependent)" prerequisite information
   1017  * in 'temp' against the contents of the database 'db'.
   1018  *
   1019  * Return ISC_R_SUCCESS if the prerequisites are satisfied,
   1020  * rcode(dns_rcode_nxrrset) if not.
   1021  *
   1022  * 'temp' must be pre-sorted.
   1023  */
   1024 
   1025 static isc_result_t
   1026 temp_check(isc_mem_t *mctx, dns_diff_t *temp, dns_db_t *db,
   1027 	   dns_dbversion_t *ver, dns_name_t *tmpname, dns_rdatatype_t *typep)
   1028 {
   1029 	isc_result_t result;
   1030 	dns_name_t *name;
   1031 	dns_dbnode_t *node;
   1032 	dns_difftuple_t *t;
   1033 	dns_diff_t trash;
   1034 
   1035 	dns_diff_init(mctx, &trash);
   1036 
   1037 	/*
   1038 	 * For each name and type in the prerequisites,
   1039 	 * construct a sorted rdata list of the corresponding
   1040 	 * database contents, and compare the lists.
   1041 	 */
   1042 	t = ISC_LIST_HEAD(temp->tuples);
   1043 	while (t != NULL) {
   1044 		name = &t->name;
   1045 		(void)dns_name_copy(name, tmpname, NULL);
   1046 		*typep = t->rdata.type;
   1047 
   1048 		/* A new unique name begins here. */
   1049 		node = NULL;
   1050 		result = dns_db_findnode(db, name, false, &node);
   1051 		if (result == ISC_R_NOTFOUND) {
   1052 			dns_diff_clear(&trash);
   1053 			return (DNS_R_NXRRSET);
   1054 		}
   1055 		if (result != ISC_R_SUCCESS) {
   1056 			dns_diff_clear(&trash);
   1057 			return (result);
   1058 		}
   1059 
   1060 		/* A new unique type begins here. */
   1061 		while (t != NULL && dns_name_equal(&t->name, name)) {
   1062 			dns_rdatatype_t type, covers;
   1063 			dns_rdataset_t rdataset;
   1064 			dns_diff_t d_rrs; /* Database RRs with
   1065 						this name and type */
   1066 			dns_diff_t u_rrs; /* Update RRs with
   1067 						this name and type */
   1068 
   1069 			*typep = type = t->rdata.type;
   1070 			if (type == dns_rdatatype_rrsig ||
   1071 			    type == dns_rdatatype_sig)
   1072 				covers = dns_rdata_covers(&t->rdata);
   1073 			else if (type == dns_rdatatype_any) {
   1074 				dns_db_detachnode(db, &node);
   1075 				dns_diff_clear(&trash);
   1076 				return (DNS_R_NXRRSET);
   1077 			} else
   1078 				covers = 0;
   1079 
   1080 			/*
   1081 			 * Collect all database RRs for this name and type
   1082 			 * onto d_rrs and sort them.
   1083 			 */
   1084 			dns_rdataset_init(&rdataset);
   1085 			result = dns_db_findrdataset(db, node, ver, type,
   1086 						     covers, (isc_stdtime_t) 0,
   1087 						     &rdataset, NULL);
   1088 			if (result != ISC_R_SUCCESS) {
   1089 				dns_db_detachnode(db, &node);
   1090 				dns_diff_clear(&trash);
   1091 				return (DNS_R_NXRRSET);
   1092 			}
   1093 
   1094 			dns_diff_init(mctx, &d_rrs);
   1095 			dns_diff_init(mctx, &u_rrs);
   1096 
   1097 			for (result = dns_rdataset_first(&rdataset);
   1098 			     result == ISC_R_SUCCESS;
   1099 			     result = dns_rdataset_next(&rdataset))
   1100 			{
   1101 				dns_rdata_t rdata = DNS_RDATA_INIT;
   1102 				dns_rdataset_current(&rdataset, &rdata);
   1103 				result = temp_append(&d_rrs, name, &rdata);
   1104 				if (result != ISC_R_SUCCESS)
   1105 					goto failure;
   1106 			}
   1107 			if (result != ISC_R_NOMORE)
   1108 				goto failure;
   1109 			result = dns_diff_sort(&d_rrs, temp_order);
   1110 			if (result != ISC_R_SUCCESS)
   1111 				goto failure;
   1112 
   1113 			/*
   1114 			 * Collect all update RRs for this name and type
   1115 			 * onto u_rrs.  No need to sort them here -
   1116 			 * they are already sorted.
   1117 			 */
   1118 			while (t != NULL &&
   1119 			       dns_name_equal(&t->name, name) &&
   1120 			       t->rdata.type == type)
   1121 			{
   1122 				dns_difftuple_t *next =
   1123 					ISC_LIST_NEXT(t, link);
   1124 				ISC_LIST_UNLINK(temp->tuples, t, link);
   1125 				ISC_LIST_APPEND(u_rrs.tuples, t, link);
   1126 				t = next;
   1127 			}
   1128 
   1129 			/* Compare the two sorted lists. */
   1130 			result = temp_check_rrset(ISC_LIST_HEAD(u_rrs.tuples),
   1131 						  ISC_LIST_HEAD(d_rrs.tuples));
   1132 			if (result != ISC_R_SUCCESS)
   1133 				goto failure;
   1134 
   1135 			/*
   1136 			 * We are done with the tuples, but we can't free
   1137 			 * them yet because "name" still points into one
   1138 			 * of them.  Move them on a temporary list.
   1139 			 */
   1140 			ISC_LIST_APPENDLIST(trash.tuples, u_rrs.tuples, link);
   1141 			ISC_LIST_APPENDLIST(trash.tuples, d_rrs.tuples, link);
   1142 			dns_rdataset_disassociate(&rdataset);
   1143 
   1144 			continue;
   1145 
   1146 		    failure:
   1147 			dns_diff_clear(&d_rrs);
   1148 			dns_diff_clear(&u_rrs);
   1149 			dns_diff_clear(&trash);
   1150 			dns_rdataset_disassociate(&rdataset);
   1151 			dns_db_detachnode(db, &node);
   1152 			return (result);
   1153 		}
   1154 
   1155 		dns_db_detachnode(db, &node);
   1156 	}
   1157 
   1158 	dns_diff_clear(&trash);
   1159 	return (ISC_R_SUCCESS);
   1160 }
   1161 
   1162 /**************************************************************************/
   1163 /*
   1164  * Conditional deletion of RRs.
   1165  */
   1166 
   1167 /*%
   1168  * Context structure for delete_if().
   1169  */
   1170 
   1171 typedef struct {
   1172 	rr_predicate *predicate;
   1173 	dns_db_t *db;
   1174 	dns_dbversion_t *ver;
   1175 	dns_diff_t *diff;
   1176 	dns_name_t *name;
   1177 	dns_rdata_t *update_rr;
   1178 } conditional_delete_ctx_t;
   1179 
   1180 /*%
   1181  * Predicate functions for delete_if().
   1182  */
   1183 
   1184 /*%
   1185  * Return true iff 'db_rr' is neither a SOA nor an NS RR nor
   1186  * an RRSIG nor an NSEC3PARAM nor a NSEC.
   1187  */
   1188 static bool
   1189 type_not_soa_nor_ns_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
   1190 	UNUSED(update_rr);
   1191 	return ((db_rr->type != dns_rdatatype_soa &&
   1192 		 db_rr->type != dns_rdatatype_ns &&
   1193 		 db_rr->type != dns_rdatatype_nsec3param &&
   1194 		 db_rr->type != dns_rdatatype_rrsig &&
   1195 		 db_rr->type != dns_rdatatype_nsec) ?
   1196 		true : false);
   1197 }
   1198 
   1199 /*%
   1200  * Return true iff 'db_rr' is neither a RRSIG nor a NSEC.
   1201  */
   1202 static bool
   1203 type_not_dnssec(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
   1204 	UNUSED(update_rr);
   1205 	return ((db_rr->type != dns_rdatatype_rrsig &&
   1206 		 db_rr->type != dns_rdatatype_nsec) ?
   1207 		true : false);
   1208 }
   1209 
   1210 /*%
   1211  * Return true always.
   1212  */
   1213 static bool
   1214 true_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
   1215 	UNUSED(update_rr);
   1216 	UNUSED(db_rr);
   1217 	return (true);
   1218 }
   1219 
   1220 /*%
   1221  * Return true iff the two RRs have identical rdata.
   1222  */
   1223 static bool
   1224 rr_equal_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
   1225 	/*
   1226 	 * XXXRTH  This is not a problem, but we should consider creating
   1227 	 *         dns_rdata_equal() (that used dns_name_equal()), since it
   1228 	 *         would be faster.  Not a priority.
   1229 	 */
   1230 	return (dns_rdata_casecompare(update_rr, db_rr) == 0 ?
   1231 		true : false);
   1232 }
   1233 
   1234 /*%
   1235  * Return true iff 'update_rr' should replace 'db_rr' according
   1236  * to the special RFC2136 rules for CNAME, SOA, and WKS records.
   1237  *
   1238  * RFC2136 does not mention NSEC or DNAME, but multiple NSECs or DNAMEs
   1239  * make little sense, so we replace those, too.
   1240  *
   1241  * Additionally replace RRSIG that have been generated by the same key
   1242  * for the same type.  This simplifies refreshing a offline KSK by not
   1243  * requiring that the old RRSIG be deleted.  It also simplifies key
   1244  * rollover by only requiring that the new RRSIG be added.
   1245  */
   1246 static bool
   1247 replaces_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
   1248 	dns_rdata_rrsig_t updatesig, dbsig;
   1249 	isc_result_t result;
   1250 
   1251 	if (db_rr->type != update_rr->type)
   1252 		return (false);
   1253 	if (db_rr->type == dns_rdatatype_cname)
   1254 		return (true);
   1255 	if (db_rr->type == dns_rdatatype_dname)
   1256 		return (true);
   1257 	if (db_rr->type == dns_rdatatype_soa)
   1258 		return (true);
   1259 	if (db_rr->type == dns_rdatatype_nsec)
   1260 		return (true);
   1261 	if (db_rr->type == dns_rdatatype_rrsig) {
   1262 		/*
   1263 		 * Replace existing RRSIG with the same keyid,
   1264 		 * covered and algorithm.
   1265 		 */
   1266 		result = dns_rdata_tostruct(db_rr, &dbsig, NULL);
   1267 		RUNTIME_CHECK(result == ISC_R_SUCCESS);
   1268 		result = dns_rdata_tostruct(update_rr, &updatesig, NULL);
   1269 		RUNTIME_CHECK(result == ISC_R_SUCCESS);
   1270 		if (dbsig.keyid == updatesig.keyid &&
   1271 		    dbsig.covered == updatesig.covered &&
   1272 		    dbsig.algorithm == updatesig.algorithm)
   1273 			return (true);
   1274 	}
   1275 	if (db_rr->type == dns_rdatatype_wks) {
   1276 		/*
   1277 		 * Compare the address and protocol fields only.  These
   1278 		 * form the first five bytes of the RR data.  Do a
   1279 		 * raw binary comparison; unpacking the WKS RRs using
   1280 		 * dns_rdata_tostruct() might be cleaner in some ways.
   1281 		 */
   1282 		INSIST(db_rr->length >= 5 && update_rr->length >= 5);
   1283 		return (memcmp(db_rr->data, update_rr->data, 5) == 0 ?
   1284 			true : false);
   1285 	}
   1286 
   1287 	if (db_rr->type == dns_rdatatype_nsec3param) {
   1288 		if (db_rr->length != update_rr->length)
   1289 			return (false);
   1290 		INSIST(db_rr->length >= 4 && update_rr->length >= 4);
   1291 		/*
   1292 		 * Replace NSEC3PARAM records that only differ by the
   1293 		 * flags field.
   1294 		 */
   1295 		if (db_rr->data[0] == update_rr->data[0] &&
   1296 		    memcmp(db_rr->data+2, update_rr->data+2,
   1297 			   update_rr->length - 2) == 0)
   1298 			return (true);
   1299 	}
   1300 	return (false);
   1301 }
   1302 
   1303 /*%
   1304  * Internal helper function for delete_if().
   1305  */
   1306 static isc_result_t
   1307 delete_if_action(void *data, rr_t *rr) {
   1308 	conditional_delete_ctx_t *ctx = data;
   1309 	if ((*ctx->predicate)(ctx->update_rr, &rr->rdata)) {
   1310 		isc_result_t result;
   1311 		result = update_one_rr(ctx->db, ctx->ver, ctx->diff,
   1312 				       DNS_DIFFOP_DEL, ctx->name,
   1313 				       rr->ttl, &rr->rdata);
   1314 		return (result);
   1315 	} else {
   1316 		return (ISC_R_SUCCESS);
   1317 	}
   1318 }
   1319 
   1320 /*%
   1321  * Conditionally delete RRs.  Apply 'predicate' to the RRs
   1322  * specified by 'db', 'ver', 'name', and 'type' (which can
   1323  * be dns_rdatatype_any to match any type).  Delete those
   1324  * RRs for which the predicate returns true, and log the
   1325  * deletions in 'diff'.
   1326  */
   1327 static isc_result_t
   1328 delete_if(rr_predicate *predicate, dns_db_t *db, dns_dbversion_t *ver,
   1329 	  dns_name_t *name, dns_rdatatype_t type, dns_rdatatype_t covers,
   1330 	  dns_rdata_t *update_rr, dns_diff_t *diff)
   1331 {
   1332 	conditional_delete_ctx_t ctx;
   1333 	ctx.predicate = predicate;
   1334 	ctx.db = db;
   1335 	ctx.ver = ver;
   1336 	ctx.diff = diff;
   1337 	ctx.name = name;
   1338 	ctx.update_rr = update_rr;
   1339 	return (foreach_rr(db, ver, name, type, covers,
   1340 			   delete_if_action, &ctx));
   1341 }
   1342 
   1343 /**************************************************************************/
   1344 
   1345 static isc_result_t
   1346 add_rr_prepare_action(void *data, rr_t *rr) {
   1347 	isc_result_t result = ISC_R_SUCCESS;
   1348 	add_rr_prepare_ctx_t *ctx = data;
   1349 	dns_difftuple_t *tuple = NULL;
   1350 	bool equal, case_equal, ttl_equal;
   1351 
   1352 	/*
   1353 	 * Are the new and old cases equal?
   1354 	 */
   1355 	case_equal = dns_name_caseequal(ctx->name, ctx->oldname);
   1356 
   1357 	/*
   1358 	 * Are the ttl's equal?
   1359 	 */
   1360 	ttl_equal = rr->ttl == ctx->update_rr_ttl;
   1361 
   1362 	/*
   1363 	 * If the update RR is a "duplicate" of a existing RR,
   1364 	 * the update should be silently ignored.
   1365 	 */
   1366 	equal = (dns_rdata_casecompare(&rr->rdata, ctx->update_rr) == 0);
   1367 	if (equal && case_equal && ttl_equal) {
   1368 		ctx->ignore_add = true;
   1369 		return (ISC_R_SUCCESS);
   1370 	}
   1371 
   1372 	/*
   1373 	 * If this RR is "equal" to the update RR, it should
   1374 	 * be deleted before the update RR is added.
   1375 	 */
   1376 	if (replaces_p(ctx->update_rr, &rr->rdata)) {
   1377 		CHECK(dns_difftuple_create(ctx->del_diff.mctx, DNS_DIFFOP_DEL,
   1378 					   ctx->oldname, rr->ttl, &rr->rdata,
   1379 					   &tuple));
   1380 		dns_diff_append(&ctx->del_diff, &tuple);
   1381 		return (ISC_R_SUCCESS);
   1382 	}
   1383 
   1384 	/*
   1385 	 * If this RR differs in TTL or case from the update RR,
   1386 	 * its TTL and case must be adjusted.
   1387 	 */
   1388 	if (!ttl_equal || !case_equal) {
   1389 		CHECK(dns_difftuple_create(ctx->del_diff.mctx, DNS_DIFFOP_DEL,
   1390 					   ctx->oldname, rr->ttl, &rr->rdata,
   1391 					   &tuple));
   1392 		dns_diff_append(&ctx->del_diff, &tuple);
   1393 		if (!equal) {
   1394 			CHECK(dns_difftuple_create(ctx->add_diff.mctx,
   1395 						   DNS_DIFFOP_ADD, ctx->name,
   1396 						   ctx->update_rr_ttl,
   1397 						   &rr->rdata, &tuple));
   1398 			dns_diff_append(&ctx->add_diff, &tuple);
   1399 		}
   1400 	}
   1401  failure:
   1402 	return (result);
   1403 }
   1404 
   1405 /**************************************************************************/
   1406 /*
   1407  * Miscellaneous subroutines.
   1408  */
   1409 
   1410 /*%
   1411  * Extract a single update RR from 'section' of dynamic update message
   1412  * 'msg', with consistency checking.
   1413  *
   1414  * Stores the owner name, rdata, and TTL of the update RR at 'name',
   1415  * 'rdata', and 'ttl', respectively.
   1416  */
   1417 static void
   1418 get_current_rr(dns_message_t *msg, dns_section_t section,
   1419 	       dns_rdataclass_t zoneclass, dns_name_t **name,
   1420 	       dns_rdata_t *rdata, dns_rdatatype_t *covers,
   1421 	       dns_ttl_t *ttl, dns_rdataclass_t *update_class)
   1422 {
   1423 	dns_rdataset_t *rdataset;
   1424 	isc_result_t result;
   1425 	dns_message_currentname(msg, section, name);
   1426 	rdataset = ISC_LIST_HEAD((*name)->list);
   1427 	INSIST(rdataset != NULL);
   1428 	INSIST(ISC_LIST_NEXT(rdataset, link) == NULL);
   1429 	*covers = rdataset->covers;
   1430 	*ttl = rdataset->ttl;
   1431 	result = dns_rdataset_first(rdataset);
   1432 	INSIST(result == ISC_R_SUCCESS);
   1433 	dns_rdataset_current(rdataset, rdata);
   1434 	INSIST(dns_rdataset_next(rdataset) == ISC_R_NOMORE);
   1435 	*update_class = rdata->rdclass;
   1436 	rdata->rdclass = zoneclass;
   1437 }
   1438 
   1439 /*%
   1440  * Increment the SOA serial number of database 'db', version 'ver'.
   1441  * Replace the SOA record in the database, and log the
   1442  * change in 'diff'.
   1443  */
   1444 
   1445 	/*
   1446 	 * XXXRTH  Failures in this routine will be worth logging, when
   1447 	 *         we have a logging system.  Failure to find the zonename
   1448 	 *	   or the SOA rdataset warrant at least an UNEXPECTED_ERROR().
   1449 	 */
   1450 
   1451 static isc_result_t
   1452 update_soa_serial(dns_db_t *db, dns_dbversion_t *ver, dns_diff_t *diff,
   1453 		  isc_mem_t *mctx, dns_updatemethod_t method)
   1454 {
   1455 	dns_difftuple_t *deltuple = NULL;
   1456 	dns_difftuple_t *addtuple = NULL;
   1457 	uint32_t serial;
   1458 	isc_result_t result;
   1459 
   1460 	CHECK(dns_db_createsoatuple(db, ver, mctx, DNS_DIFFOP_DEL, &deltuple));
   1461 	CHECK(dns_difftuple_copy(deltuple, &addtuple));
   1462 	addtuple->op = DNS_DIFFOP_ADD;
   1463 
   1464 	serial = dns_soa_getserial(&addtuple->rdata);
   1465 	serial = dns_update_soaserial(serial, method);
   1466 	dns_soa_setserial(serial, &addtuple->rdata);
   1467 	CHECK(do_one_tuple(&deltuple, db, ver, diff));
   1468 	CHECK(do_one_tuple(&addtuple, db, ver, diff));
   1469 	result = ISC_R_SUCCESS;
   1470 
   1471  failure:
   1472 	if (addtuple != NULL)
   1473 		dns_difftuple_free(&addtuple);
   1474 	if (deltuple != NULL)
   1475 		dns_difftuple_free(&deltuple);
   1476 	return (result);
   1477 }
   1478 
   1479 /*%
   1480  * Check that the new SOA record at 'update_rdata' does not
   1481  * illegally cause the SOA serial number to decrease or stay
   1482  * unchanged relative to the existing SOA in 'db'.
   1483  *
   1484  * Sets '*ok' to true if the update is legal, false if not.
   1485  *
   1486  * William King points out that RFC2136 is inconsistent about
   1487  * the case where the serial number stays unchanged:
   1488  *
   1489  *   section 3.4.2.2 requires a server to ignore a SOA update request
   1490  *   if the serial number on the update SOA is less_than_or_equal to
   1491  *   the zone SOA serial.
   1492  *
   1493  *   section 3.6 requires a server to ignore a SOA update request if
   1494  *   the serial is less_than the zone SOA serial.
   1495  *
   1496  * Paul says 3.4.2.2 is correct.
   1497  *
   1498  */
   1499 static isc_result_t
   1500 check_soa_increment(dns_db_t *db, dns_dbversion_t *ver,
   1501 		    dns_rdata_t *update_rdata, bool *ok)
   1502 {
   1503 	uint32_t db_serial;
   1504 	uint32_t update_serial;
   1505 	isc_result_t result;
   1506 
   1507 	update_serial = dns_soa_getserial(update_rdata);
   1508 
   1509 	result = dns_db_getsoaserial(db, ver, &db_serial);
   1510 	if (result != ISC_R_SUCCESS)
   1511 		return (result);
   1512 
   1513 	if (DNS_SERIAL_GE(db_serial, update_serial)) {
   1514 		*ok = false;
   1515 	} else {
   1516 		*ok = true;
   1517 	}
   1518 
   1519 	return (ISC_R_SUCCESS);
   1520 
   1521 }
   1522 
   1523 /**************************************************************************/
   1524 /*%
   1525  * The actual update code in all its glory.  We try to follow
   1526  * the RFC2136 pseudocode as closely as possible.
   1527  */
   1528 
   1529 static isc_result_t
   1530 send_update_event(ns_client_t *client, dns_zone_t *zone) {
   1531 	isc_result_t result = ISC_R_SUCCESS;
   1532 	update_event_t *event = NULL;
   1533 	isc_task_t *zonetask = NULL;
   1534 	ns_client_t *evclient;
   1535 
   1536 	event = (update_event_t *)
   1537 		isc_event_allocate(client->mctx, client, DNS_EVENT_UPDATE,
   1538 				   update_action, NULL, sizeof(*event));
   1539 	if (event == NULL)
   1540 		FAIL(ISC_R_NOMEMORY);
   1541 	event->zone = zone;
   1542 	event->result = ISC_R_SUCCESS;
   1543 
   1544 	evclient = NULL;
   1545 	ns_client_attach(client, &evclient);
   1546 	INSIST(client->nupdates == 0);
   1547 	client->nupdates++;
   1548 	event->ev_arg = evclient;
   1549 
   1550 	dns_zone_gettask(zone, &zonetask);
   1551 	isc_task_send(zonetask, ISC_EVENT_PTR(&event));
   1552 
   1553  failure:
   1554 	if (event != NULL)
   1555 		isc_event_free(ISC_EVENT_PTR(&event));
   1556 	return (result);
   1557 }
   1558 
   1559 static void
   1560 respond(ns_client_t *client, isc_result_t result) {
   1561 	isc_result_t msg_result;
   1562 
   1563 	msg_result = dns_message_reply(client->message, true);
   1564 	if (msg_result != ISC_R_SUCCESS)
   1565 		goto msg_failure;
   1566 	client->message->rcode = dns_result_torcode(result);
   1567 
   1568 	ns_client_send(client);
   1569 	return;
   1570 
   1571  msg_failure:
   1572 	isc_log_write(ns_lctx, NS_LOGCATEGORY_UPDATE, NS_LOGMODULE_UPDATE,
   1573 		      ISC_LOG_ERROR,
   1574 		      "could not create update response message: %s",
   1575 		      isc_result_totext(msg_result));
   1576 	ns_client_next(client, msg_result);
   1577 }
   1578 
   1579 void
   1580 ns_update_start(ns_client_t *client, isc_result_t sigresult) {
   1581 	dns_message_t *request = client->message;
   1582 	isc_result_t result;
   1583 	dns_name_t *zonename;
   1584 	dns_rdataset_t *zone_rdataset;
   1585 	dns_zone_t *zone = NULL, *raw = NULL;
   1586 
   1587 	/*
   1588 	 * Interpret the zone section.
   1589 	 */
   1590 	result = dns_message_firstname(request, DNS_SECTION_ZONE);
   1591 	if (result != ISC_R_SUCCESS)
   1592 		FAILC(DNS_R_FORMERR, "update zone section empty");
   1593 
   1594 	/*
   1595 	 * The zone section must contain exactly one "question", and
   1596 	 * it must be of type SOA.
   1597 	 */
   1598 	zonename = NULL;
   1599 	dns_message_currentname(request, DNS_SECTION_ZONE, &zonename);
   1600 	zone_rdataset = ISC_LIST_HEAD(zonename->list);
   1601 	if (zone_rdataset->type != dns_rdatatype_soa)
   1602 		FAILC(DNS_R_FORMERR,
   1603 		      "update zone section contains non-SOA");
   1604 	if (ISC_LIST_NEXT(zone_rdataset, link) != NULL)
   1605 		FAILC(DNS_R_FORMERR,
   1606 		      "update zone section contains multiple RRs");
   1607 
   1608 	/* The zone section must have exactly one name. */
   1609 	result = dns_message_nextname(request, DNS_SECTION_ZONE);
   1610 	if (result != ISC_R_NOMORE)
   1611 		FAILC(DNS_R_FORMERR,
   1612 		      "update zone section contains multiple RRs");
   1613 
   1614 	result = dns_zt_find(client->view->zonetable, zonename, 0, NULL,
   1615 			     &zone);
   1616 	if (result != ISC_R_SUCCESS)
   1617 		FAILC(DNS_R_NOTAUTH, "not authoritative for update zone");
   1618 
   1619 	/*
   1620 	 * If there is a raw (unsigned) zone associated with this
   1621 	 * zone then it processes the UPDATE request.
   1622 	 */
   1623 	dns_zone_getraw(zone, &raw);
   1624 	if (raw != NULL) {
   1625 		dns_zone_detach(&zone);
   1626 		dns_zone_attach(raw, &zone);
   1627 		dns_zone_detach(&raw);
   1628 	}
   1629 
   1630 	switch(dns_zone_gettype(zone)) {
   1631 	case dns_zone_master:
   1632 	case dns_zone_dlz:
   1633 		/*
   1634 		 * We can now fail due to a bad signature as we now know
   1635 		 * that we are the master.
   1636 		 */
   1637 		if (sigresult != ISC_R_SUCCESS)
   1638 			FAIL(sigresult);
   1639 		CHECK(send_update_event(client, zone));
   1640 		break;
   1641 	case dns_zone_slave:
   1642 	case dns_zone_mirror:
   1643 		CHECK(checkupdateacl(client, dns_zone_getforwardacl(zone),
   1644 				     "update forwarding", zonename, true,
   1645 				     false));
   1646 		CHECK(send_forward_event(client, zone));
   1647 		break;
   1648 	default:
   1649 		FAILC(DNS_R_NOTAUTH, "not authoritative for update zone");
   1650 	}
   1651 	return;
   1652 
   1653  failure:
   1654 	if (result == DNS_R_REFUSED) {
   1655 		INSIST(dns_zone_gettype(zone) == dns_zone_slave ||
   1656 		       dns_zone_gettype(zone) == dns_zone_mirror);
   1657 		inc_stats(client, zone, ns_statscounter_updaterej);
   1658 	}
   1659 	/*
   1660 	 * We failed without having sent an update event to the zone.
   1661 	 * We are still in the client task context, so we can
   1662 	 * simply give an error response without switching tasks.
   1663 	 */
   1664 	respond(client, result);
   1665 	if (zone != NULL)
   1666 		dns_zone_detach(&zone);
   1667 }
   1668 
   1669 /*%
   1670  * DS records are not allowed to exist without corresponding NS records,
   1671  * RFC 3658, 2.2 Protocol Change,
   1672  * "DS RRsets MUST NOT appear at non-delegation points or at a zone's apex".
   1673  */
   1674 
   1675 static isc_result_t
   1676 remove_orphaned_ds(dns_db_t *db, dns_dbversion_t *newver, dns_diff_t *diff) {
   1677 	isc_result_t result;
   1678 	bool ns_exists;
   1679 	dns_difftuple_t *tupple;
   1680 	dns_diff_t temp_diff;
   1681 
   1682 	dns_diff_init(diff->mctx, &temp_diff);
   1683 
   1684 	for (tupple = ISC_LIST_HEAD(diff->tuples);
   1685 	     tupple != NULL;
   1686 	     tupple = ISC_LIST_NEXT(tupple, link)) {
   1687 		if (!((tupple->op == DNS_DIFFOP_DEL &&
   1688 		       tupple->rdata.type == dns_rdatatype_ns) ||
   1689 		      (tupple->op == DNS_DIFFOP_ADD &&
   1690 		       tupple->rdata.type == dns_rdatatype_ds)))
   1691 			continue;
   1692 		CHECK(rrset_exists(db, newver, &tupple->name,
   1693 				   dns_rdatatype_ns, 0, &ns_exists));
   1694 		if (ns_exists &&
   1695 		    !dns_name_equal(&tupple->name, dns_db_origin(db)))
   1696 			continue;
   1697 		CHECK(delete_if(true_p, db, newver, &tupple->name,
   1698 				dns_rdatatype_ds, 0, NULL, &temp_diff));
   1699 	}
   1700 	result = ISC_R_SUCCESS;
   1701 
   1702  failure:
   1703 	for (tupple = ISC_LIST_HEAD(temp_diff.tuples);
   1704 	     tupple != NULL;
   1705 	     tupple = ISC_LIST_HEAD(temp_diff.tuples)) {
   1706 		ISC_LIST_UNLINK(temp_diff.tuples, tupple, link);
   1707 		dns_diff_appendminimal(diff, &tupple);
   1708 	}
   1709 	return (result);
   1710 }
   1711 
   1712 /*
   1713  * This implements the post load integrity checks for mx records.
   1714  */
   1715 static isc_result_t
   1716 check_mx(ns_client_t *client, dns_zone_t *zone,
   1717 	 dns_db_t *db, dns_dbversion_t *newver, dns_diff_t *diff)
   1718 {
   1719 	char tmp[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:123.123.123.123.")];
   1720 	char ownerbuf[DNS_NAME_FORMATSIZE];
   1721 	char namebuf[DNS_NAME_FORMATSIZE];
   1722 	char altbuf[DNS_NAME_FORMATSIZE];
   1723 	dns_difftuple_t *t;
   1724 	dns_fixedname_t fixed;
   1725 	dns_name_t *foundname;
   1726 	dns_rdata_mx_t mx;
   1727 	dns_rdata_t rdata;
   1728 	bool ok = true;
   1729 	bool isaddress;
   1730 	isc_result_t result;
   1731 	struct in6_addr addr6;
   1732 	struct in_addr addr;
   1733 	dns_zoneopt_t options;
   1734 
   1735 	foundname = dns_fixedname_initname(&fixed);
   1736 	dns_rdata_init(&rdata);
   1737 	options = dns_zone_getoptions(zone);
   1738 
   1739 	for (t = ISC_LIST_HEAD(diff->tuples);
   1740 	     t != NULL;
   1741 	     t = ISC_LIST_NEXT(t, link)) {
   1742 		if (t->op != DNS_DIFFOP_ADD ||
   1743 		    t->rdata.type != dns_rdatatype_mx)
   1744 			continue;
   1745 
   1746 		result = dns_rdata_tostruct(&t->rdata, &mx, NULL);
   1747 		RUNTIME_CHECK(result == ISC_R_SUCCESS);
   1748 		/*
   1749 		 * Check if we will error out if we attempt to reload the
   1750 		 * zone.
   1751 		 */
   1752 		dns_name_format(&mx.mx, namebuf, sizeof(namebuf));
   1753 		dns_name_format(&t->name, ownerbuf, sizeof(ownerbuf));
   1754 		isaddress = false;
   1755 		if ((options & DNS_ZONEOPT_CHECKMX) != 0 &&
   1756 		    strlcpy(tmp, namebuf, sizeof(tmp)) < sizeof(tmp)) {
   1757 			if (tmp[strlen(tmp) - 1] == '.')
   1758 				tmp[strlen(tmp) - 1] = '\0';
   1759 			if (inet_pton(AF_INET, tmp, &addr) == 1 ||
   1760 			    inet_pton(AF_INET6, tmp, &addr6) == 1)
   1761 				isaddress = true;
   1762 		}
   1763 
   1764 		if (isaddress && (options & DNS_ZONEOPT_CHECKMXFAIL) != 0) {
   1765 			update_log(client, zone, ISC_LOG_ERROR,
   1766 				   "%s/MX: '%s': %s",
   1767 				   ownerbuf, namebuf,
   1768 				   dns_result_totext(DNS_R_MXISADDRESS));
   1769 			ok = false;
   1770 		} else if (isaddress) {
   1771 			update_log(client, zone, ISC_LOG_WARNING,
   1772 				   "%s/MX: warning: '%s': %s",
   1773 				   ownerbuf, namebuf,
   1774 				   dns_result_totext(DNS_R_MXISADDRESS));
   1775 		}
   1776 
   1777 		/*
   1778 		 * Check zone integrity checks.
   1779 		 */
   1780 		if ((options & DNS_ZONEOPT_CHECKINTEGRITY) == 0)
   1781 			continue;
   1782 		result = dns_db_find(db, &mx.mx, newver, dns_rdatatype_a,
   1783 				     0, 0, NULL, foundname, NULL, NULL);
   1784 		if (result == ISC_R_SUCCESS)
   1785 			continue;
   1786 
   1787 		if (result == DNS_R_NXRRSET) {
   1788 			result = dns_db_find(db, &mx.mx, newver,
   1789 					     dns_rdatatype_aaaa,
   1790 					     0, 0, NULL, foundname,
   1791 					     NULL, NULL);
   1792 			if (result == ISC_R_SUCCESS)
   1793 				continue;
   1794 		}
   1795 
   1796 		if (result == DNS_R_NXRRSET || result == DNS_R_NXDOMAIN) {
   1797 			update_log(client, zone, ISC_LOG_ERROR,
   1798 				   "%s/MX '%s' has no address records "
   1799 				   "(A or AAAA)", ownerbuf, namebuf);
   1800 			ok = false;
   1801 		} else if (result == DNS_R_CNAME) {
   1802 			update_log(client, zone, ISC_LOG_ERROR,
   1803 				   "%s/MX '%s' is a CNAME (illegal)",
   1804 				   ownerbuf, namebuf);
   1805 			ok = false;
   1806 		} else if (result == DNS_R_DNAME) {
   1807 			dns_name_format(foundname, altbuf, sizeof altbuf);
   1808 			update_log(client, zone, ISC_LOG_ERROR,
   1809 				   "%s/MX '%s' is below a DNAME '%s' (illegal)",
   1810 				   ownerbuf, namebuf, altbuf);
   1811 			ok = false;
   1812 		}
   1813 	}
   1814 	return (ok ? ISC_R_SUCCESS : DNS_R_REFUSED);
   1815 }
   1816 
   1817 static isc_result_t
   1818 rr_exists(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
   1819 	  const dns_rdata_t *rdata, bool *flag)
   1820 {
   1821 	dns_rdataset_t rdataset;
   1822 	dns_dbnode_t *node = NULL;
   1823 	isc_result_t result;
   1824 
   1825 	dns_rdataset_init(&rdataset);
   1826 	if (rdata->type == dns_rdatatype_nsec3)
   1827 		CHECK(dns_db_findnsec3node(db, name, false, &node));
   1828 	else
   1829 		CHECK(dns_db_findnode(db, name, false, &node));
   1830 	result = dns_db_findrdataset(db, node, ver, rdata->type, 0,
   1831 				     (isc_stdtime_t) 0, &rdataset, NULL);
   1832 	if (result == ISC_R_NOTFOUND) {
   1833 		*flag = false;
   1834 		result = ISC_R_SUCCESS;
   1835 		goto failure;
   1836 	}
   1837 
   1838 	for (result = dns_rdataset_first(&rdataset);
   1839 	     result == ISC_R_SUCCESS;
   1840 	     result = dns_rdataset_next(&rdataset)) {
   1841 		dns_rdata_t myrdata = DNS_RDATA_INIT;
   1842 		dns_rdataset_current(&rdataset, &myrdata);
   1843 		if (!dns_rdata_casecompare(&myrdata, rdata))
   1844 			break;
   1845 	}
   1846 	dns_rdataset_disassociate(&rdataset);
   1847 	if (result == ISC_R_SUCCESS) {
   1848 		*flag = true;
   1849 	} else if (result == ISC_R_NOMORE) {
   1850 		*flag = false;
   1851 		result = ISC_R_SUCCESS;
   1852 	}
   1853 
   1854  failure:
   1855 	if (node != NULL)
   1856 		dns_db_detachnode(db, &node);
   1857 	return (result);
   1858 }
   1859 
   1860 static isc_result_t
   1861 get_iterations(dns_db_t *db, dns_dbversion_t *ver, dns_rdatatype_t privatetype,
   1862 	       unsigned int *iterationsp)
   1863 {
   1864 	dns_dbnode_t *node = NULL;
   1865 	dns_rdata_nsec3param_t nsec3param;
   1866 	dns_rdataset_t rdataset;
   1867 	isc_result_t result;
   1868 	unsigned int iterations = 0;
   1869 
   1870 	dns_rdataset_init(&rdataset);
   1871 
   1872 	result = dns_db_getoriginnode(db, &node);
   1873 	if (result != ISC_R_SUCCESS)
   1874 		return (result);
   1875 	result = dns_db_findrdataset(db, node, ver, dns_rdatatype_nsec3param,
   1876 				     0, (isc_stdtime_t) 0, &rdataset, NULL);
   1877 	if (result == ISC_R_NOTFOUND)
   1878 		goto try_private;
   1879 	if (result != ISC_R_SUCCESS)
   1880 		goto failure;
   1881 
   1882 	for (result = dns_rdataset_first(&rdataset);
   1883 	     result == ISC_R_SUCCESS;
   1884 	     result = dns_rdataset_next(&rdataset)) {
   1885 		dns_rdata_t rdata = DNS_RDATA_INIT;
   1886 		dns_rdataset_current(&rdataset, &rdata);
   1887 		CHECK(dns_rdata_tostruct(&rdata, &nsec3param, NULL));
   1888 		if ((nsec3param.flags & DNS_NSEC3FLAG_REMOVE) != 0)
   1889 			continue;
   1890 		if (nsec3param.iterations > iterations)
   1891 			iterations = nsec3param.iterations;
   1892 	}
   1893 	if (result != ISC_R_NOMORE)
   1894 		goto failure;
   1895 
   1896 	dns_rdataset_disassociate(&rdataset);
   1897 
   1898  try_private:
   1899 	if (privatetype == 0)
   1900 		goto success;
   1901 
   1902 	result = dns_db_findrdataset(db, node, ver, privatetype,
   1903 				     0, (isc_stdtime_t) 0, &rdataset, NULL);
   1904 	if (result == ISC_R_NOTFOUND)
   1905 		goto success;
   1906 	if (result != ISC_R_SUCCESS)
   1907 		goto failure;
   1908 
   1909 	for (result = dns_rdataset_first(&rdataset);
   1910 	     result == ISC_R_SUCCESS;
   1911 	     result = dns_rdataset_next(&rdataset)) {
   1912 		unsigned char buf[DNS_NSEC3PARAM_BUFFERSIZE];
   1913 		dns_rdata_t private = DNS_RDATA_INIT;
   1914 		dns_rdata_t rdata = DNS_RDATA_INIT;
   1915 
   1916 		dns_rdataset_current(&rdataset, &rdata);
   1917 		if (!dns_nsec3param_fromprivate(&private, &rdata,
   1918 						buf, sizeof(buf)))
   1919 			continue;
   1920 		CHECK(dns_rdata_tostruct(&rdata, &nsec3param, NULL));
   1921 		if ((nsec3param.flags & DNS_NSEC3FLAG_REMOVE) != 0)
   1922 			continue;
   1923 		if (nsec3param.iterations > iterations)
   1924 			iterations = nsec3param.iterations;
   1925 	}
   1926 	if (result != ISC_R_NOMORE)
   1927 		goto failure;
   1928 
   1929  success:
   1930 	*iterationsp = iterations;
   1931 	result = ISC_R_SUCCESS;
   1932 
   1933  failure:
   1934 	if (node != NULL)
   1935 		dns_db_detachnode(db, &node);
   1936 	if (dns_rdataset_isassociated(&rdataset))
   1937 		dns_rdataset_disassociate(&rdataset);
   1938 	return (result);
   1939 }
   1940 
   1941 /*
   1942  * Prevent the zone entering a inconsistent state where
   1943  * NSEC only DNSKEYs are present with NSEC3 chains.
   1944  */
   1945 static isc_result_t
   1946 check_dnssec(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
   1947 	     dns_dbversion_t *ver, dns_diff_t *diff)
   1948 {
   1949 	dns_difftuple_t *tuple;
   1950 	bool nseconly = false, nsec3 = false;
   1951 	isc_result_t result;
   1952 	unsigned int iterations = 0, max;
   1953 	dns_rdatatype_t privatetype = dns_zone_getprivatetype(zone);
   1954 
   1955 	/* Scan the tuples for an NSEC-only DNSKEY or an NSEC3PARAM */
   1956 	for (tuple = ISC_LIST_HEAD(diff->tuples);
   1957 	     tuple != NULL;
   1958 	     tuple = ISC_LIST_NEXT(tuple, link)) {
   1959 		if (tuple->op != DNS_DIFFOP_ADD)
   1960 			continue;
   1961 
   1962 		if (tuple->rdata.type == dns_rdatatype_dnskey) {
   1963 			uint8_t alg;
   1964 			alg = tuple->rdata.data[3];
   1965 			if (alg == DST_ALG_RSAMD5 || alg == DST_ALG_RSASHA1) {
   1966 				nseconly = true;
   1967 				break;
   1968 			}
   1969 		} else if (tuple->rdata.type == dns_rdatatype_nsec3param) {
   1970 			nsec3 = true;
   1971 			break;
   1972 		}
   1973 	}
   1974 
   1975 	/* Check existing DB for NSEC-only DNSKEY */
   1976 	if (!nseconly) {
   1977 		result = dns_nsec_nseconly(db, ver, &nseconly);
   1978 
   1979 		/*
   1980 		 * An NSEC3PARAM update can proceed without a DNSKEY (it
   1981 		 * will trigger a delayed change), so we can ignore
   1982 		 * ISC_R_NOTFOUND here.
   1983 		 */
   1984 		if (result == ISC_R_NOTFOUND)
   1985 			result = ISC_R_SUCCESS;
   1986 
   1987 		CHECK(result);
   1988 	}
   1989 
   1990 	/* Check existing DB for NSEC3 */
   1991 	if (!nsec3)
   1992 		CHECK(dns_nsec3_activex(db, ver, false,
   1993 					privatetype, &nsec3));
   1994 
   1995 	/* Refuse to allow NSEC3 with NSEC-only keys */
   1996 	if (nseconly && nsec3) {
   1997 		update_log(client, zone, ISC_LOG_ERROR,
   1998 			   "NSEC only DNSKEYs and NSEC3 chains not allowed");
   1999 		result = DNS_R_REFUSED;
   2000 		goto failure;
   2001 	}
   2002 
   2003 	/* Verify NSEC3 params */
   2004 	CHECK(get_iterations(db, ver, privatetype, &iterations));
   2005 	CHECK(dns_nsec3_maxiterations(db, ver, client->mctx, &max));
   2006 	if (max != 0 && iterations > max) {
   2007 		update_log(client, zone, ISC_LOG_ERROR,
   2008 			   "too many NSEC3 iterations (%u) for "
   2009 			   "weakest DNSKEY (%u)", iterations, max);
   2010 		result = DNS_R_REFUSED;
   2011 		goto failure;
   2012 	}
   2013 
   2014  failure:
   2015 	return (result);
   2016 }
   2017 
   2018 /*
   2019  * Delay NSEC3PARAM changes as they need to be applied to the whole zone.
   2020  */
   2021 static isc_result_t
   2022 add_nsec3param_records(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
   2023 		       dns_dbversion_t *ver, dns_diff_t *diff)
   2024 {
   2025 	isc_result_t result = ISC_R_SUCCESS;
   2026 	dns_difftuple_t *tuple, *newtuple = NULL, *next;
   2027 	dns_rdata_t rdata = DNS_RDATA_INIT;
   2028 	unsigned char buf[DNS_NSEC3PARAM_BUFFERSIZE + 1];
   2029 	dns_diff_t temp_diff;
   2030 	dns_diffop_t op;
   2031 	bool flag;
   2032 	dns_name_t *name = dns_zone_getorigin(zone);
   2033 	dns_rdatatype_t privatetype = dns_zone_getprivatetype(zone);
   2034 	uint32_t ttl = 0;
   2035 	bool ttl_good = false;
   2036 
   2037 	update_log(client, zone, ISC_LOG_DEBUG(3),
   2038 		    "checking for NSEC3PARAM changes");
   2039 
   2040 	dns_diff_init(diff->mctx, &temp_diff);
   2041 
   2042 	/*
   2043 	 * Extract NSEC3PARAM tuples from list.
   2044 	 */
   2045 	for (tuple = ISC_LIST_HEAD(diff->tuples);
   2046 	     tuple != NULL;
   2047 	     tuple = next) {
   2048 
   2049 		next = ISC_LIST_NEXT(tuple, link);
   2050 
   2051 		if (tuple->rdata.type != dns_rdatatype_nsec3param ||
   2052 		    !dns_name_equal(name, &tuple->name))
   2053 			continue;
   2054 		ISC_LIST_UNLINK(diff->tuples, tuple, link);
   2055 		ISC_LIST_APPEND(temp_diff.tuples, tuple, link);
   2056 	}
   2057 
   2058 	/*
   2059 	 * Extract TTL changes pairs, we don't need to convert these to
   2060 	 * delayed changes.
   2061 	 */
   2062 	for (tuple = ISC_LIST_HEAD(temp_diff.tuples);
   2063 	     tuple != NULL; tuple = next) {
   2064 		if (tuple->op == DNS_DIFFOP_ADD) {
   2065 			if (!ttl_good) {
   2066 				/*
   2067 				 * Any adds here will contain the final
   2068 				 * NSEC3PARAM RRset TTL.
   2069 				 */
   2070 				ttl = tuple->ttl;
   2071 				ttl_good = true;
   2072 			}
   2073 			/*
   2074 			 * Walk the temp_diff list looking for the
   2075 			 * corresponding delete.
   2076 			 */
   2077 			next = ISC_LIST_HEAD(temp_diff.tuples);
   2078 			while (next != NULL) {
   2079 				unsigned char *next_data = next->rdata.data;
   2080 				unsigned char *tuple_data = tuple->rdata.data;
   2081 				if (next->op == DNS_DIFFOP_DEL &&
   2082 				    next->rdata.length == tuple->rdata.length &&
   2083 				    !memcmp(next_data, tuple_data,
   2084 					    next->rdata.length)) {
   2085 					ISC_LIST_UNLINK(temp_diff.tuples, next,
   2086 							link);
   2087 					ISC_LIST_APPEND(diff->tuples, next,
   2088 							link);
   2089 					break;
   2090 				}
   2091 				next = ISC_LIST_NEXT(next, link);
   2092 			}
   2093 			/*
   2094 			 * If we have not found a pair move onto the next
   2095 			 * tuple.
   2096 			 */
   2097 			if (next == NULL) {
   2098 				next = ISC_LIST_NEXT(tuple, link);
   2099 				continue;
   2100 			}
   2101 			/*
   2102 			 * Find the next tuple to be processed before
   2103 			 * unlinking then complete moving the pair to 'diff'.
   2104 			 */
   2105 			next = ISC_LIST_NEXT(tuple, link);
   2106 			ISC_LIST_UNLINK(temp_diff.tuples, tuple, link);
   2107 			ISC_LIST_APPEND(diff->tuples, tuple, link);
   2108 		} else
   2109 			next = ISC_LIST_NEXT(tuple, link);
   2110 	}
   2111 
   2112 	/*
   2113 	 * Preserve any ongoing changes from a BIND 9.6.x upgrade.
   2114 	 *
   2115 	 * Any NSEC3PARAM records with flags other than OPTOUT named
   2116 	 * in managing and should not be touched so revert such changes
   2117 	 * taking into account any TTL change of the NSEC3PARAM RRset.
   2118 	 */
   2119 	for (tuple = ISC_LIST_HEAD(temp_diff.tuples);
   2120 	     tuple != NULL; tuple = next) {
   2121 		next = ISC_LIST_NEXT(tuple, link);
   2122 		if ((tuple->rdata.data[1] & ~DNS_NSEC3FLAG_OPTOUT) != 0) {
   2123 			/*
   2124 			 * If we havn't had any adds then the tuple->ttl must
   2125 			 * be the original ttl and should be used for any
   2126 			 * future changes.
   2127 			 */
   2128 			if (!ttl_good) {
   2129 				ttl = tuple->ttl;
   2130 				ttl_good = true;
   2131 			}
   2132 			op = (tuple->op == DNS_DIFFOP_DEL) ?
   2133 			     DNS_DIFFOP_ADD : DNS_DIFFOP_DEL;
   2134 			CHECK(dns_difftuple_create(diff->mctx, op, name,
   2135 						   ttl, &tuple->rdata,
   2136 						   &newtuple));
   2137 			CHECK(do_one_tuple(&newtuple, db, ver, diff));
   2138 			ISC_LIST_UNLINK(temp_diff.tuples, tuple, link);
   2139 			dns_diff_appendminimal(diff, &tuple);
   2140 		}
   2141 	}
   2142 
   2143 	/*
   2144 	 * We now have just the actual changes to the NSEC3PARAM RRset.
   2145 	 * Convert the adds to delayed adds and the deletions into delayed
   2146 	 * deletions.
   2147 	 */
   2148 	for (tuple = ISC_LIST_HEAD(temp_diff.tuples);
   2149 	     tuple != NULL; tuple = next) {
   2150 		/*
   2151 		 * If we havn't had any adds then the tuple->ttl must be the
   2152 		 * original ttl and should be used for any future changes.
   2153 		 */
   2154 		if (!ttl_good) {
   2155 			ttl = tuple->ttl;
   2156 			ttl_good = true;
   2157 		}
   2158 		if (tuple->op == DNS_DIFFOP_ADD) {
   2159 			bool nseconly = false;
   2160 
   2161 			/*
   2162 			 * Look for any deletes which match this ADD ignoring
   2163 			 * flags.  We don't need to explictly remove them as
   2164 			 * they will be removed a side effect of processing
   2165 			 * the add.
   2166 			 */
   2167 			next = ISC_LIST_HEAD(temp_diff.tuples);
   2168 			while (next != NULL) {
   2169 				unsigned char *next_data = next->rdata.data;
   2170 				unsigned char *tuple_data = tuple->rdata.data;
   2171 				if (next->op != DNS_DIFFOP_DEL ||
   2172 				    next->rdata.length != tuple->rdata.length ||
   2173 				    next_data[0] != tuple_data[0] ||
   2174 				    next_data[2] != tuple_data[2] ||
   2175 				    next_data[3] != tuple_data[3] ||
   2176 				    memcmp(next_data + 4, tuple_data + 4,
   2177 					   tuple->rdata.length - 4)) {
   2178 					next = ISC_LIST_NEXT(next, link);
   2179 					continue;
   2180 				}
   2181 				ISC_LIST_UNLINK(temp_diff.tuples, next, link);
   2182 				ISC_LIST_APPEND(diff->tuples, next, link);
   2183 				next = ISC_LIST_HEAD(temp_diff.tuples);
   2184 			}
   2185 
   2186 			/*
   2187 			 * Create a private-type record to signal that
   2188 			 * we want a delayed NSEC3 chain add/delete
   2189 			 */
   2190 			dns_nsec3param_toprivate(&tuple->rdata, &rdata,
   2191 						 privatetype, buf, sizeof(buf));
   2192 			buf[2] |= DNS_NSEC3FLAG_CREATE;
   2193 
   2194 			/*
   2195 			 * If the zone is not currently capable of
   2196 			 * supporting an NSEC3 chain, then we set the
   2197 			 * INITIAL flag to indicate that these parameters
   2198 			 * are to be used later.
   2199 			 */
   2200 			result = dns_nsec_nseconly(db, ver, &nseconly);
   2201 			if (result == ISC_R_NOTFOUND || nseconly)
   2202 				buf[2] |= DNS_NSEC3FLAG_INITIAL;
   2203 
   2204 			/*
   2205 			 * See if this CREATE request already exists.
   2206 			 */
   2207 			CHECK(rr_exists(db, ver, name, &rdata, &flag));
   2208 
   2209 			if (!flag) {
   2210 				CHECK(dns_difftuple_create(diff->mctx,
   2211 							   DNS_DIFFOP_ADD,
   2212 							   name, 0, &rdata,
   2213 							   &newtuple));
   2214 				CHECK(do_one_tuple(&newtuple, db, ver, diff));
   2215 			}
   2216 
   2217 			/*
   2218 			 * Remove any existing CREATE request to add an
   2219 			 * otherwise indentical chain with a reversed
   2220 			 * OPTOUT state.
   2221 			 */
   2222 			buf[2] ^= DNS_NSEC3FLAG_OPTOUT;
   2223 			CHECK(rr_exists(db, ver, name, &rdata, &flag));
   2224 
   2225 			if (flag) {
   2226 				CHECK(dns_difftuple_create(diff->mctx,
   2227 							   DNS_DIFFOP_DEL,
   2228 							   name, 0, &rdata,
   2229 							   &newtuple));
   2230 				CHECK(do_one_tuple(&newtuple, db, ver, diff));
   2231 			}
   2232 
   2233 			/*
   2234 			 * Find the next tuple to be processed and remove the
   2235 			 * temporary add record.
   2236 			 */
   2237 			next = ISC_LIST_NEXT(tuple, link);
   2238 			CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_DEL,
   2239 						   name, ttl, &tuple->rdata,
   2240 						   &newtuple));
   2241 			CHECK(do_one_tuple(&newtuple, db, ver, diff));
   2242 			ISC_LIST_UNLINK(temp_diff.tuples, tuple, link);
   2243 			dns_diff_appendminimal(diff, &tuple);
   2244 			dns_rdata_reset(&rdata);
   2245 		} else
   2246 			next = ISC_LIST_NEXT(tuple, link);
   2247 	}
   2248 
   2249 	for (tuple = ISC_LIST_HEAD(temp_diff.tuples);
   2250 	     tuple != NULL; tuple = next) {
   2251 
   2252 		INSIST(ttl_good);
   2253 
   2254 		next = ISC_LIST_NEXT(tuple, link);
   2255 		/*
   2256 		 * See if we already have a REMOVE request in progress.
   2257 		 */
   2258 		dns_nsec3param_toprivate(&tuple->rdata, &rdata, privatetype,
   2259 					 buf, sizeof(buf));
   2260 
   2261 		buf[2] |= DNS_NSEC3FLAG_REMOVE | DNS_NSEC3FLAG_NONSEC;
   2262 
   2263 		CHECK(rr_exists(db, ver, name, &rdata, &flag));
   2264 		if (!flag) {
   2265 			buf[2] &= ~DNS_NSEC3FLAG_NONSEC;
   2266 			CHECK(rr_exists(db, ver, name, &rdata, &flag));
   2267 		}
   2268 
   2269 		if (!flag) {
   2270 			CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD,
   2271 						   name, 0, &rdata, &newtuple));
   2272 			CHECK(do_one_tuple(&newtuple, db, ver, diff));
   2273 		}
   2274 		CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD, name,
   2275 					   ttl, &tuple->rdata, &newtuple));
   2276 		CHECK(do_one_tuple(&newtuple, db, ver, diff));
   2277 		ISC_LIST_UNLINK(temp_diff.tuples, tuple, link);
   2278 		dns_diff_appendminimal(diff, &tuple);
   2279 		dns_rdata_reset(&rdata);
   2280 	}
   2281 
   2282 	result = ISC_R_SUCCESS;
   2283  failure:
   2284 	dns_diff_clear(&temp_diff);
   2285 	return (result);
   2286 }
   2287 
   2288 static isc_result_t
   2289 rollback_private(dns_db_t *db, dns_rdatatype_t privatetype,
   2290 		 dns_dbversion_t *ver, dns_diff_t *diff)
   2291 {
   2292 	dns_diff_t temp_diff;
   2293 	dns_diffop_t op;
   2294 	dns_difftuple_t *tuple, *newtuple = NULL, *next;
   2295 	dns_name_t *name = dns_db_origin(db);
   2296 	isc_mem_t *mctx = diff->mctx;
   2297 	isc_result_t result;
   2298 
   2299 	if (privatetype == 0)
   2300 		return (ISC_R_SUCCESS);
   2301 
   2302 	dns_diff_init(mctx, &temp_diff);
   2303 
   2304 	/*
   2305 	 * Extract the changes to be rolled back.
   2306 	 */
   2307 	for (tuple = ISC_LIST_HEAD(diff->tuples);
   2308 	     tuple != NULL; tuple = next) {
   2309 
   2310 		next = ISC_LIST_NEXT(tuple, link);
   2311 
   2312 		if (tuple->rdata.type != privatetype ||
   2313 		    !dns_name_equal(name, &tuple->name))
   2314 			continue;
   2315 
   2316 		/*
   2317 		 * Allow records which indicate that a zone has been
   2318 		 * signed with a DNSKEY to be removed.
   2319 		 */
   2320 		if (tuple->op == DNS_DIFFOP_DEL &&
   2321 		    tuple->rdata.length == 5 &&
   2322 		    tuple->rdata.data[0] != 0 &&
   2323 		    tuple->rdata.data[4] != 0)
   2324 			continue;
   2325 
   2326 		ISC_LIST_UNLINK(diff->tuples, tuple, link);
   2327 		ISC_LIST_PREPEND(temp_diff.tuples, tuple, link);
   2328 	}
   2329 
   2330 	/*
   2331 	 * Rollback the changes.
   2332 	 */
   2333 	while ((tuple = ISC_LIST_HEAD(temp_diff.tuples)) != NULL) {
   2334 		op = (tuple->op == DNS_DIFFOP_DEL) ?
   2335 		      DNS_DIFFOP_ADD : DNS_DIFFOP_DEL;
   2336 		CHECK(dns_difftuple_create(mctx, op, name, tuple->ttl,
   2337 					   &tuple->rdata, &newtuple));
   2338 		CHECK(do_one_tuple(&newtuple, db, ver, &temp_diff));
   2339 	}
   2340 	result = ISC_R_SUCCESS;
   2341 
   2342  failure:
   2343 	dns_diff_clear(&temp_diff);
   2344 	return (result);
   2345 }
   2346 
   2347 /*
   2348  * Add records to cause the delayed signing of the zone by added DNSKEY
   2349  * to remove the RRSIG records generated by a deleted DNSKEY.
   2350  */
   2351 static isc_result_t
   2352 add_signing_records(dns_db_t *db, dns_rdatatype_t privatetype,
   2353 		    dns_dbversion_t *ver, dns_diff_t *diff)
   2354 {
   2355 	dns_difftuple_t *tuple, *newtuple = NULL, *next;
   2356 	dns_rdata_dnskey_t dnskey;
   2357 	dns_rdata_t rdata = DNS_RDATA_INIT;
   2358 	bool flag;
   2359 	isc_region_t r;
   2360 	isc_result_t result = ISC_R_SUCCESS;
   2361 	uint16_t keyid;
   2362 	unsigned char buf[5];
   2363 	dns_name_t *name = dns_db_origin(db);
   2364 	dns_diff_t temp_diff;
   2365 
   2366 	dns_diff_init(diff->mctx, &temp_diff);
   2367 
   2368 	/*
   2369 	 * Extract the DNSKEY tuples from the list.
   2370 	 */
   2371 	for (tuple = ISC_LIST_HEAD(diff->tuples);
   2372 	     tuple != NULL; tuple = next) {
   2373 
   2374 		next = ISC_LIST_NEXT(tuple, link);
   2375 
   2376 		if (tuple->rdata.type != dns_rdatatype_dnskey)
   2377 			continue;
   2378 
   2379 		ISC_LIST_UNLINK(diff->tuples, tuple, link);
   2380 		ISC_LIST_APPEND(temp_diff.tuples, tuple, link);
   2381 	}
   2382 
   2383 	/*
   2384 	 * Extract TTL changes pairs, we don't need signing records for these.
   2385 	 */
   2386 	for (tuple = ISC_LIST_HEAD(temp_diff.tuples);
   2387 	     tuple != NULL; tuple = next) {
   2388 		if (tuple->op == DNS_DIFFOP_ADD) {
   2389 			/*
   2390 			 * Walk the temp_diff list looking for the
   2391 			 * corresponding delete.
   2392 			 */
   2393 			next = ISC_LIST_HEAD(temp_diff.tuples);
   2394 			while (next != NULL) {
   2395 				unsigned char *next_data = next->rdata.data;
   2396 				unsigned char *tuple_data = tuple->rdata.data;
   2397 				if (next->op == DNS_DIFFOP_DEL &&
   2398 				    dns_name_equal(&tuple->name, &next->name) &&
   2399 				    next->rdata.length == tuple->rdata.length &&
   2400 				    !memcmp(next_data, tuple_data,
   2401 					    next->rdata.length)) {
   2402 					ISC_LIST_UNLINK(temp_diff.tuples, next,
   2403 							link);
   2404 					ISC_LIST_APPEND(diff->tuples, next,
   2405 							link);
   2406 					break;
   2407 				}
   2408 				next = ISC_LIST_NEXT(next, link);
   2409 			}
   2410 			/*
   2411 			 * If we have not found a pair move onto the next
   2412 			 * tuple.
   2413 			 */
   2414 			if (next == NULL) {
   2415 				next = ISC_LIST_NEXT(tuple, link);
   2416 				continue;
   2417 			}
   2418 			/*
   2419 			 * Find the next tuple to be processed before
   2420 			 * unlinking then complete moving the pair to 'diff'.
   2421 			 */
   2422 			next = ISC_LIST_NEXT(tuple, link);
   2423 			ISC_LIST_UNLINK(temp_diff.tuples, tuple, link);
   2424 			ISC_LIST_APPEND(diff->tuples, tuple, link);
   2425 		} else
   2426 			next = ISC_LIST_NEXT(tuple, link);
   2427 	}
   2428 
   2429 	/*
   2430 	 * Process the remaining DNSKEY entries.
   2431 	 */
   2432 	for (tuple = ISC_LIST_HEAD(temp_diff.tuples);
   2433 	     tuple != NULL;
   2434 	     tuple = ISC_LIST_HEAD(temp_diff.tuples)) {
   2435 
   2436 		ISC_LIST_UNLINK(temp_diff.tuples, tuple, link);
   2437 		ISC_LIST_APPEND(diff->tuples, tuple, link);
   2438 
   2439 		result = dns_rdata_tostruct(&tuple->rdata, &dnskey, NULL);
   2440 		RUNTIME_CHECK(result == ISC_R_SUCCESS);
   2441 		if ((dnskey.flags &
   2442 		     (DNS_KEYFLAG_OWNERMASK|DNS_KEYTYPE_NOAUTH))
   2443 			 != DNS_KEYOWNER_ZONE)
   2444 			continue;
   2445 
   2446 		dns_rdata_toregion(&tuple->rdata, &r);
   2447 
   2448 		keyid = dst_region_computeid(&r, dnskey.algorithm);
   2449 
   2450 		buf[0] = dnskey.algorithm;
   2451 		buf[1] = (keyid & 0xff00) >> 8;
   2452 		buf[2] = (keyid & 0xff);
   2453 		buf[3] = (tuple->op == DNS_DIFFOP_ADD) ? 0 : 1;
   2454 		buf[4] = 0;
   2455 		rdata.data = buf;
   2456 		rdata.length = sizeof(buf);
   2457 		rdata.type = privatetype;
   2458 		rdata.rdclass = tuple->rdata.rdclass;
   2459 
   2460 		CHECK(rr_exists(db, ver, name, &rdata, &flag));
   2461 		if (flag)
   2462 			continue;
   2463 		CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD,
   2464 					   name, 0, &rdata, &newtuple));
   2465 		CHECK(do_one_tuple(&newtuple, db, ver, diff));
   2466 		INSIST(newtuple == NULL);
   2467 		/*
   2468 		 * Remove any record which says this operation has already
   2469 		 * completed.
   2470 		 */
   2471 		buf[4] = 1;
   2472 		CHECK(rr_exists(db, ver, name, &rdata, &flag));
   2473 		if (flag) {
   2474 			CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_DEL,
   2475 						   name, 0, &rdata, &newtuple));
   2476 			CHECK(do_one_tuple(&newtuple, db, ver, diff));
   2477 			INSIST(newtuple == NULL);
   2478 		}
   2479 	}
   2480 
   2481  failure:
   2482 	dns_diff_clear(&temp_diff);
   2483 	return (result);
   2484 }
   2485 
   2486 static bool
   2487 isdnssec(dns_db_t *db, dns_dbversion_t *ver, dns_rdatatype_t privatetype) {
   2488 	isc_result_t result;
   2489 	bool build_nsec, build_nsec3;
   2490 
   2491 	if (dns_db_issecure(db))
   2492 		return (true);
   2493 
   2494 	result = dns_private_chains(db, ver, privatetype,
   2495 				    &build_nsec, &build_nsec3);
   2496 	RUNTIME_CHECK(result == ISC_R_SUCCESS);
   2497 	return (build_nsec || build_nsec3);
   2498 }
   2499 
   2500 static void
   2501 update_action(isc_task_t *task, isc_event_t *event) {
   2502 	update_event_t *uev = (update_event_t *) event;
   2503 	dns_zone_t *zone = uev->zone;
   2504 	ns_client_t *client = (ns_client_t *)event->ev_arg;
   2505 	isc_result_t result;
   2506 	dns_db_t *db = NULL;
   2507 	dns_dbversion_t *oldver = NULL;
   2508 	dns_dbversion_t *ver = NULL;
   2509 	dns_diff_t diff;	/* Pending updates. */
   2510 	dns_diff_t temp;	/* Pending RR existence assertions. */
   2511 	bool soa_serial_changed = false;
   2512 	isc_mem_t *mctx = client->mctx;
   2513 	dns_rdatatype_t covers;
   2514 	dns_message_t *request = client->message;
   2515 	dns_rdataclass_t zoneclass;
   2516 	dns_name_t *zonename;
   2517 	dns_ssutable_t *ssutable = NULL;
   2518 	dns_fixedname_t tmpnamefixed;
   2519 	dns_name_t *tmpname = NULL;
   2520 	dns_zoneopt_t options;
   2521 	dns_difftuple_t *tuple;
   2522 	dns_rdata_dnskey_t dnskey;
   2523 	bool had_dnskey;
   2524 	dns_rdatatype_t privatetype = dns_zone_getprivatetype(zone);
   2525 	dns_ttl_t maxttl = 0;
   2526 	uint32_t maxrecords;
   2527 	uint64_t records;
   2528 	dns_aclenv_t *env = ns_interfacemgr_getaclenv(client->interface->mgr);
   2529 
   2530 	INSIST(event->ev_type == DNS_EVENT_UPDATE);
   2531 
   2532 	dns_diff_init(mctx, &diff);
   2533 	dns_diff_init(mctx, &temp);
   2534 
   2535 	CHECK(dns_zone_getdb(zone, &db));
   2536 	zonename = dns_db_origin(db);
   2537 	zoneclass = dns_db_class(db);
   2538 	dns_zone_getssutable(zone, &ssutable);
   2539 
   2540 	/*
   2541 	 * Update message processing can leak record existance information
   2542 	 * so check that we are allowed to query this zone.  Additionally
   2543 	 * if we would refuse all updates for this zone we bail out here.
   2544 	 */
   2545 	CHECK(checkqueryacl(client, dns_zone_getqueryacl(zone), zonename,
   2546 			    dns_zone_getupdateacl(zone), ssutable));
   2547 
   2548 	/*
   2549 	 * Get old and new versions now that queryacl has been checked.
   2550 	 */
   2551 	dns_db_currentversion(db, &oldver);
   2552 	CHECK(dns_db_newversion(db, &ver));
   2553 
   2554 	/*
   2555 	 * Check prerequisites.
   2556 	 */
   2557 
   2558 	for (result = dns_message_firstname(request, DNS_SECTION_PREREQUISITE);
   2559 	     result == ISC_R_SUCCESS;
   2560 	     result = dns_message_nextname(request, DNS_SECTION_PREREQUISITE))
   2561 	{
   2562 		dns_name_t *name = NULL;
   2563 		dns_rdata_t rdata = DNS_RDATA_INIT;
   2564 		dns_ttl_t ttl;
   2565 		dns_rdataclass_t update_class;
   2566 		bool flag;
   2567 
   2568 		get_current_rr(request, DNS_SECTION_PREREQUISITE, zoneclass,
   2569 			       &name, &rdata, &covers, &ttl, &update_class);
   2570 
   2571 		if (ttl != 0)
   2572 			PREREQFAILC(DNS_R_FORMERR,
   2573 				    "prerequisite TTL is not zero");
   2574 
   2575 		if (! dns_name_issubdomain(name, zonename))
   2576 			PREREQFAILN(DNS_R_NOTZONE, name,
   2577 				    "prerequisite name is out of zone");
   2578 
   2579 		if (update_class == dns_rdataclass_any) {
   2580 			if (rdata.length != 0)
   2581 				PREREQFAILC(DNS_R_FORMERR,
   2582 				      "class ANY prerequisite "
   2583 				      "RDATA is not empty");
   2584 			if (rdata.type == dns_rdatatype_any) {
   2585 				CHECK(name_exists(db, ver, name, &flag));
   2586 				if (! flag) {
   2587 					PREREQFAILN(DNS_R_NXDOMAIN, name,
   2588 						    "'name in use' "
   2589 						    "prerequisite not "
   2590 						    "satisfied");
   2591 				}
   2592 			} else {
   2593 				CHECK(rrset_exists(db, ver, name,
   2594 						   rdata.type, covers, &flag));
   2595 				if (! flag) {
   2596 					/* RRset does not exist. */
   2597 					PREREQFAILNT(DNS_R_NXRRSET,
   2598 						     name, rdata.type,
   2599 					"'rrset exists (value independent)' "
   2600 					"prerequisite not satisfied");
   2601 				}
   2602 			}
   2603 		} else if (update_class == dns_rdataclass_none) {
   2604 			if (rdata.length != 0)
   2605 				PREREQFAILC(DNS_R_FORMERR,
   2606 					    "class NONE prerequisite "
   2607 					    "RDATA is not empty");
   2608 			if (rdata.type == dns_rdatatype_any) {
   2609 				CHECK(name_exists(db, ver, name, &flag));
   2610 				if (flag) {
   2611 					PREREQFAILN(DNS_R_YXDOMAIN, name,
   2612 						    "'name not in use' "
   2613 						    "prerequisite not "
   2614 						    "satisfied");
   2615 				}
   2616 			} else {
   2617 				CHECK(rrset_exists(db, ver, name,
   2618 						   rdata.type, covers, &flag));
   2619 				if (flag) {
   2620 					/* RRset exists. */
   2621 					PREREQFAILNT(DNS_R_YXRRSET, name,
   2622 						     rdata.type,
   2623 						     "'rrset does not exist' "
   2624 						     "prerequisite not "
   2625 						     "satisfied");
   2626 				}
   2627 			}
   2628 		} else if (update_class == zoneclass) {
   2629 			/* "temp<rr.name, rr.type> += rr;" */
   2630 			result = temp_append(&temp, name, &rdata);
   2631 			if (result != ISC_R_SUCCESS) {
   2632 				UNEXPECTED_ERROR(__FILE__, __LINE__,
   2633 					 "temp entry creation failed: %s",
   2634 						 dns_result_totext(result));
   2635 				FAIL(ISC_R_UNEXPECTED);
   2636 			}
   2637 		} else {
   2638 			PREREQFAILC(DNS_R_FORMERR, "malformed prerequisite");
   2639 		}
   2640 	}
   2641 	if (result != ISC_R_NOMORE)
   2642 		FAIL(result);
   2643 
   2644 	/*
   2645 	 * Perform the final check of the "rrset exists (value dependent)"
   2646 	 * prerequisites.
   2647 	 */
   2648 	if (ISC_LIST_HEAD(temp.tuples) != NULL) {
   2649 		dns_rdatatype_t type;
   2650 
   2651 		/*
   2652 		 * Sort the prerequisite records by owner name,
   2653 		 * type, and rdata.
   2654 		 */
   2655 		result = dns_diff_sort(&temp, temp_order);
   2656 		if (result != ISC_R_SUCCESS)
   2657 			FAILC(result, "'RRset exists (value dependent)' "
   2658 			      "prerequisite not satisfied");
   2659 
   2660 		tmpname = dns_fixedname_initname(&tmpnamefixed);
   2661 		result = temp_check(mctx, &temp, db, ver, tmpname, &type);
   2662 		if (result != ISC_R_SUCCESS)
   2663 			FAILNT(result, tmpname, type,
   2664 			       "'RRset exists (value dependent)' "
   2665 			       "prerequisite not satisfied");
   2666 	}
   2667 
   2668 	update_log(client, zone, LOGLEVEL_DEBUG,
   2669 		   "prerequisites are OK");
   2670 
   2671 	/*
   2672 	 * Check Requestor's Permissions.  It seems a bit silly to do this
   2673 	 * only after prerequisite testing, but that is what RFC2136 says.
   2674 	 */
   2675 	if (ssutable == NULL)
   2676 		CHECK(checkupdateacl(client, dns_zone_getupdateacl(zone),
   2677 				     "update", zonename, false, false));
   2678 	else if (client->signer == NULL && !TCPCLIENT(client))
   2679 		CHECK(checkupdateacl(client, NULL, "update", zonename,
   2680 				     false, true));
   2681 
   2682 	if (dns_zone_getupdatedisabled(zone))
   2683 		FAILC(DNS_R_REFUSED, "dynamic update temporarily disabled "
   2684 				     "because the zone is frozen.  Use "
   2685 				     "'rndc thaw' to re-enable updates.");
   2686 
   2687 	/*
   2688 	 * Perform the Update Section Prescan.
   2689 	 */
   2690 
   2691 	for (result = dns_message_firstname(request, DNS_SECTION_UPDATE);
   2692 	     result == ISC_R_SUCCESS;
   2693 	     result = dns_message_nextname(request, DNS_SECTION_UPDATE))
   2694 	{
   2695 		dns_name_t *name = NULL;
   2696 		dns_rdata_t rdata = DNS_RDATA_INIT;
   2697 		dns_ttl_t ttl;
   2698 		dns_rdataclass_t update_class;
   2699 		get_current_rr(request, DNS_SECTION_UPDATE, zoneclass,
   2700 			       &name, &rdata, &covers, &ttl, &update_class);
   2701 
   2702 		if (! dns_name_issubdomain(name, zonename))
   2703 			FAILC(DNS_R_NOTZONE,
   2704 			      "update RR is outside zone");
   2705 		if (update_class == zoneclass) {
   2706 			/*
   2707 			 * Check for meta-RRs.  The RFC2136 pseudocode says
   2708 			 * check for ANY|AXFR|MAILA|MAILB, but the text adds
   2709 			 * "or any other QUERY metatype"
   2710 			 */
   2711 			if (dns_rdatatype_ismeta(rdata.type)) {
   2712 				FAILC(DNS_R_FORMERR,
   2713 				      "meta-RR in update");
   2714 			}
   2715 			result = dns_zone_checknames(zone, name, &rdata);
   2716 			if (result != ISC_R_SUCCESS)
   2717 				FAIL(DNS_R_REFUSED);
   2718 		} else if (update_class == dns_rdataclass_any) {
   2719 			if (ttl != 0 || rdata.length != 0 ||
   2720 			    (dns_rdatatype_ismeta(rdata.type) &&
   2721 			     rdata.type != dns_rdatatype_any))
   2722 				FAILC(DNS_R_FORMERR,
   2723 				      "meta-RR in update");
   2724 		} else if (update_class == dns_rdataclass_none) {
   2725 			if (ttl != 0 ||
   2726 			    dns_rdatatype_ismeta(rdata.type))
   2727 				FAILC(DNS_R_FORMERR,
   2728 				      "meta-RR in update");
   2729 		} else {
   2730 			update_log(client, zone, ISC_LOG_WARNING,
   2731 				   "update RR has incorrect class %d",
   2732 				   update_class);
   2733 			FAIL(DNS_R_FORMERR);
   2734 		}
   2735 
   2736 		/*
   2737 		 * draft-ietf-dnsind-simple-secure-update-01 says
   2738 		 * "Unlike traditional dynamic update, the client
   2739 		 * is forbidden from updating NSEC records."
   2740 		 */
   2741 		if (rdata.type == dns_rdatatype_nsec3) {
   2742 			FAILC(DNS_R_REFUSED,
   2743 			      "explicit NSEC3 updates are not allowed "
   2744 			      "in secure zones");
   2745 		} else if (rdata.type == dns_rdatatype_nsec) {
   2746 			FAILC(DNS_R_REFUSED,
   2747 			      "explicit NSEC updates are not allowed "
   2748 			      "in secure zones");
   2749 		} else if (rdata.type == dns_rdatatype_rrsig &&
   2750 			   !dns_name_equal(name, zonename)) {
   2751 			FAILC(DNS_R_REFUSED,
   2752 			      "explicit RRSIG updates are currently "
   2753 			      "not supported in secure zones except "
   2754 			      "at the apex");
   2755 		}
   2756 
   2757 		if (ssutable != NULL) {
   2758 			isc_netaddr_t netaddr;
   2759 			dst_key_t *tsigkey = NULL;
   2760 			isc_netaddr_fromsockaddr(&netaddr, &client->peeraddr);
   2761 
   2762 			if (client->message->tsigkey != NULL)
   2763 				tsigkey = client->message->tsigkey->key;
   2764 
   2765 			if (rdata.type != dns_rdatatype_any) {
   2766 				if (!dns_ssutable_checkrules
   2767 				(ssutable, client->signer, name, &netaddr,
   2768 				 TCPCLIENT(client),
   2769 				 env, rdata.type, tsigkey))
   2770 				{
   2771 					FAILC(DNS_R_REFUSED,
   2772 					      "rejected by secure update");
   2773 				}
   2774 			} else {
   2775 				if (!ssu_checkall(db, ver, name, ssutable,
   2776 						  client->signer,
   2777 						  &netaddr, env,
   2778 						  TCPCLIENT(client),
   2779 						  tsigkey))
   2780 				{
   2781 					FAILC(DNS_R_REFUSED,
   2782 					      "rejected by secure update");
   2783 				}
   2784 			}
   2785 		}
   2786 	}
   2787 	if (result != ISC_R_NOMORE)
   2788 		FAIL(result);
   2789 
   2790 	update_log(client, zone, LOGLEVEL_DEBUG,
   2791 		   "update section prescan OK");
   2792 
   2793 	/*
   2794 	 * Process the Update Section.
   2795 	 */
   2796 
   2797 	options = dns_zone_getoptions(zone);
   2798 	for (result = dns_message_firstname(request, DNS_SECTION_UPDATE);
   2799 	     result == ISC_R_SUCCESS;
   2800 	     result = dns_message_nextname(request, DNS_SECTION_UPDATE))
   2801 	{
   2802 		dns_name_t *name = NULL;
   2803 		dns_rdata_t rdata = DNS_RDATA_INIT;
   2804 		dns_ttl_t ttl;
   2805 		dns_rdataclass_t update_class;
   2806 		bool flag;
   2807 
   2808 		get_current_rr(request, DNS_SECTION_UPDATE, zoneclass,
   2809 			       &name, &rdata, &covers, &ttl, &update_class);
   2810 
   2811 		if (update_class == zoneclass) {
   2812 
   2813 			/*
   2814 			 * RFC1123 doesn't allow MF and MD in master zones.
   2815 			 */
   2816 			if (rdata.type == dns_rdatatype_md ||
   2817 			    rdata.type == dns_rdatatype_mf) {
   2818 				char typebuf[DNS_RDATATYPE_FORMATSIZE];
   2819 
   2820 				dns_rdatatype_format(rdata.type, typebuf,
   2821 						     sizeof(typebuf));
   2822 				update_log(client, zone, LOGLEVEL_PROTOCOL,
   2823 					   "attempt to add %s ignored",
   2824 					   typebuf);
   2825 				continue;
   2826 			}
   2827 			if ((rdata.type == dns_rdatatype_ns ||
   2828 			     rdata.type == dns_rdatatype_dname) &&
   2829 			    dns_name_iswildcard(name)) {
   2830 				char typebuf[DNS_RDATATYPE_FORMATSIZE];
   2831 
   2832 				dns_rdatatype_format(rdata.type, typebuf,
   2833 						     sizeof(typebuf));
   2834 				update_log(client, zone,
   2835 					   LOGLEVEL_PROTOCOL,
   2836 					   "attempt to add wildcard %s record "
   2837 					   "ignored", typebuf);
   2838 				continue;
   2839 			}
   2840 			if (rdata.type == dns_rdatatype_cname) {
   2841 				CHECK(cname_incompatible_rrset_exists(db, ver,
   2842 								      name,
   2843 								      &flag));
   2844 				if (flag) {
   2845 					update_log(client, zone,
   2846 						   LOGLEVEL_PROTOCOL,
   2847 						   "attempt to add CNAME "
   2848 						   "alongside non-CNAME "
   2849 						   "ignored");
   2850 					continue;
   2851 				}
   2852 			} else {
   2853 				CHECK(rrset_exists(db, ver, name,
   2854 						   dns_rdatatype_cname, 0,
   2855 						   &flag));
   2856 				if (flag &&
   2857 				    ! dns_rdatatype_isdnssec(rdata.type))
   2858 				{
   2859 					update_log(client, zone,
   2860 						   LOGLEVEL_PROTOCOL,
   2861 						   "attempt to add non-CNAME "
   2862 						   "alongside CNAME ignored");
   2863 					continue;
   2864 				}
   2865 			}
   2866 			if (rdata.type == dns_rdatatype_soa) {
   2867 				bool ok;
   2868 				CHECK(rrset_exists(db, ver, name,
   2869 						   dns_rdatatype_soa, 0,
   2870 						   &flag));
   2871 				if (! flag) {
   2872 					update_log(client, zone,
   2873 						   LOGLEVEL_PROTOCOL,
   2874 						   "attempt to create 2nd "
   2875 						   "SOA ignored");
   2876 					continue;
   2877 				}
   2878 				CHECK(check_soa_increment(db, ver, &rdata,
   2879 							  &ok));
   2880 				if (! ok) {
   2881 					update_log(client, zone,
   2882 						   LOGLEVEL_PROTOCOL,
   2883 						   "SOA update failed to "
   2884 						   "increment serial, "
   2885 						   "ignoring it");
   2886 					continue;
   2887 				}
   2888 				soa_serial_changed = true;
   2889 			}
   2890 
   2891 			if (rdata.type == privatetype) {
   2892 				update_log(client, zone, LOGLEVEL_PROTOCOL,
   2893 					   "attempt to add a private type "
   2894 					   "(%u) record rejected internal "
   2895 					   "use only", privatetype);
   2896 				continue;
   2897 			}
   2898 
   2899 			if (rdata.type == dns_rdatatype_nsec3param) {
   2900 				/*
   2901 				 * Ignore attempts to add NSEC3PARAM records
   2902 				 * with any flags other than OPTOUT.
   2903 				 */
   2904 				if ((rdata.data[1] &
   2905 				     ~DNS_NSEC3FLAG_OPTOUT) != 0)
   2906 				{
   2907 					update_log(client, zone,
   2908 						   LOGLEVEL_PROTOCOL,
   2909 						   "attempt to add NSEC3PARAM "
   2910 						   "record with non OPTOUT "
   2911 						   "flag");
   2912 					continue;
   2913 				}
   2914 			}
   2915 
   2916 			if ((options & DNS_ZONEOPT_CHECKWILDCARD) != 0 &&
   2917 			    dns_name_internalwildcard(name)) {
   2918 				char namestr[DNS_NAME_FORMATSIZE];
   2919 				dns_name_format(name, namestr,
   2920 						sizeof(namestr));
   2921 				update_log(client, zone, LOGLEVEL_PROTOCOL,
   2922 					   "warning: ownername '%s' contains "
   2923 					   "a non-terminal wildcard", namestr);
   2924 			}
   2925 
   2926 			if ((options & DNS_ZONEOPT_CHECKTTL) != 0) {
   2927 				maxttl = dns_zone_getmaxttl(zone);
   2928 				if (ttl > maxttl) {
   2929 					ttl = maxttl;
   2930 					update_log(client, zone,
   2931 						   LOGLEVEL_PROTOCOL,
   2932 						   "reducing TTL to the "
   2933 						   "configured max-zone-ttl %d",
   2934 						   maxttl);
   2935 				}
   2936 			}
   2937 
   2938 			if (isc_log_wouldlog(ns_lctx, LOGLEVEL_PROTOCOL)) {
   2939 				char namestr[DNS_NAME_FORMATSIZE];
   2940 				char typestr[DNS_RDATATYPE_FORMATSIZE];
   2941 				char rdstr[2048];
   2942 				isc_buffer_t buf;
   2943 				int len = 0;
   2944 				const char *truncated = "";
   2945 
   2946 				dns_name_format(name, namestr, sizeof(namestr));
   2947 				dns_rdatatype_format(rdata.type, typestr,
   2948 						     sizeof(typestr));
   2949 				isc_buffer_init(&buf, rdstr, sizeof(rdstr));
   2950 				result = dns_rdata_totext(&rdata, NULL, &buf);
   2951 				if (result == ISC_R_NOSPACE) {
   2952 					len = (int)isc_buffer_usedlength(&buf);
   2953 					truncated = " [TRUNCATED]";
   2954 				} else if (result != ISC_R_SUCCESS) {
   2955 					snprintf(rdstr, sizeof(rdstr), "[dns_"
   2956 						 "rdata_totext failed: %s]",
   2957 						 dns_result_totext(result));
   2958 					len = strlen(rdstr);
   2959 				} else
   2960 					len = (int)isc_buffer_usedlength(&buf);
   2961 				update_log(client, zone, LOGLEVEL_PROTOCOL,
   2962 					   "adding an RR at '%s' %s %.*s%s",
   2963 					   namestr, typestr, len, rdstr,
   2964 					   truncated);
   2965 			}
   2966 
   2967 			/* Prepare the affected RRset for the addition. */
   2968 			{
   2969 				add_rr_prepare_ctx_t ctx;
   2970 				ctx.db = db;
   2971 				ctx.ver = ver;
   2972 				ctx.diff = &diff;
   2973 				ctx.name = name;
   2974 				ctx.oldname = name;
   2975 				ctx.update_rr = &rdata;
   2976 				ctx.update_rr_ttl = ttl;
   2977 				ctx.ignore_add = false;
   2978 				dns_diff_init(mctx, &ctx.del_diff);
   2979 				dns_diff_init(mctx, &ctx.add_diff);
   2980 				CHECK(foreach_rr(db, ver, name, rdata.type,
   2981 						 covers, add_rr_prepare_action,
   2982 						 &ctx));
   2983 
   2984 				if (ctx.ignore_add) {
   2985 					dns_diff_clear(&ctx.del_diff);
   2986 					dns_diff_clear(&ctx.add_diff);
   2987 				} else {
   2988 					result = do_diff(&ctx.del_diff, db, ver,
   2989 							 &diff);
   2990 					if (result == ISC_R_SUCCESS) {
   2991 						result = do_diff(&ctx.add_diff,
   2992 								 db, ver,
   2993 								 &diff);
   2994 					}
   2995 					if (result != ISC_R_SUCCESS) {
   2996 						dns_diff_clear(&ctx.del_diff);
   2997 						dns_diff_clear(&ctx.add_diff);
   2998 						goto failure;
   2999 					}
   3000 					CHECK(update_one_rr(db, ver, &diff,
   3001 							    DNS_DIFFOP_ADD,
   3002 							    name, ttl, &rdata));
   3003 				}
   3004 			}
   3005 		} else if (update_class == dns_rdataclass_any) {
   3006 			if (rdata.type == dns_rdatatype_any) {
   3007 				if (isc_log_wouldlog(ns_lctx,
   3008 						     LOGLEVEL_PROTOCOL))
   3009 				{
   3010 					char namestr[DNS_NAME_FORMATSIZE];
   3011 					dns_name_format(name, namestr,
   3012 							sizeof(namestr));
   3013 					update_log(client, zone,
   3014 						   LOGLEVEL_PROTOCOL,
   3015 						   "delete all rrsets from "
   3016 						   "name '%s'", namestr);
   3017 				}
   3018 				if (dns_name_equal(name, zonename)) {
   3019 					CHECK(delete_if(type_not_soa_nor_ns_p,
   3020 							db, ver, name,
   3021 							dns_rdatatype_any, 0,
   3022 							&rdata, &diff));
   3023 				} else {
   3024 					CHECK(delete_if(type_not_dnssec,
   3025 							db, ver, name,
   3026 							dns_rdatatype_any, 0,
   3027 							&rdata, &diff));
   3028 				}
   3029 			} else if (dns_name_equal(name, zonename) &&
   3030 				   (rdata.type == dns_rdatatype_soa ||
   3031 				    rdata.type == dns_rdatatype_ns)) {
   3032 				update_log(client, zone, LOGLEVEL_PROTOCOL,
   3033 					   "attempt to delete all SOA "
   3034 					   "or NS records ignored");
   3035 				continue;
   3036 			} else {
   3037 				if (isc_log_wouldlog(ns_lctx,
   3038 						     LOGLEVEL_PROTOCOL))
   3039 				{
   3040 					char namestr[DNS_NAME_FORMATSIZE];
   3041 					char typestr[DNS_RDATATYPE_FORMATSIZE];
   3042 					dns_name_format(name, namestr,
   3043 							sizeof(namestr));
   3044 					dns_rdatatype_format(rdata.type,
   3045 							     typestr,
   3046 							     sizeof(typestr));
   3047 					update_log(client, zone,
   3048 						   LOGLEVEL_PROTOCOL,
   3049 						   "deleting rrset at '%s' %s",
   3050 						   namestr, typestr);
   3051 				}
   3052 				CHECK(delete_if(true_p, db, ver, name,
   3053 						rdata.type, covers, &rdata,
   3054 						&diff));
   3055 			}
   3056 		} else if (update_class == dns_rdataclass_none) {
   3057 			char namestr[DNS_NAME_FORMATSIZE];
   3058 			char typestr[DNS_RDATATYPE_FORMATSIZE];
   3059 
   3060 			/*
   3061 			 * The (name == zonename) condition appears in
   3062 			 * RFC2136 3.4.2.4 but is missing from the pseudocode.
   3063 			 */
   3064 			if (dns_name_equal(name, zonename)) {
   3065 				if (rdata.type == dns_rdatatype_soa) {
   3066 					update_log(client, zone,
   3067 						   LOGLEVEL_PROTOCOL,
   3068 						   "attempt to delete SOA "
   3069 						   "ignored");
   3070 					continue;
   3071 				}
   3072 				if (rdata.type == dns_rdatatype_ns) {
   3073 					int count;
   3074 					CHECK(rr_count(db, ver, name,
   3075 						       dns_rdatatype_ns,
   3076 						       0, &count));
   3077 					if (count == 1) {
   3078 						update_log(client, zone,
   3079 							   LOGLEVEL_PROTOCOL,
   3080 							   "attempt to "
   3081 							   "delete last "
   3082 							   "NS ignored");
   3083 						continue;
   3084 					}
   3085 				}
   3086 			}
   3087 			dns_name_format(name, namestr, sizeof(namestr));
   3088 			dns_rdatatype_format(rdata.type, typestr,
   3089 					     sizeof(typestr));
   3090 			update_log(client, zone, LOGLEVEL_PROTOCOL,
   3091 				   "deleting an RR at %s %s", namestr, typestr);
   3092 			CHECK(delete_if(rr_equal_p, db, ver, name, rdata.type,
   3093 					covers, &rdata, &diff));
   3094 		}
   3095 	}
   3096 	if (result != ISC_R_NOMORE)
   3097 		FAIL(result);
   3098 
   3099 	/*
   3100 	 * Check that any changes to DNSKEY/NSEC3PARAM records make sense.
   3101 	 * If they don't then back out all changes to DNSKEY/NSEC3PARAM
   3102 	 * records.
   3103 	 */
   3104 	if (! ISC_LIST_EMPTY(diff.tuples))
   3105 		CHECK(check_dnssec(client, zone, db, ver, &diff));
   3106 
   3107 	if (! ISC_LIST_EMPTY(diff.tuples)) {
   3108 		unsigned int errors = 0;
   3109 		CHECK(dns_zone_nscheck(zone, db, ver, &errors));
   3110 		if (errors != 0) {
   3111 			update_log(client, zone, LOGLEVEL_PROTOCOL,
   3112 				   "update rejected: post update name server "
   3113 				   "sanity check failed");
   3114 			result = DNS_R_REFUSED;
   3115 			goto failure;
   3116 		}
   3117 	}
   3118 	if (! ISC_LIST_EMPTY(diff.tuples)) {
   3119 		result = dns_zone_cdscheck(zone, db, ver);
   3120 		if (result == DNS_R_BADCDS || result == DNS_R_BADCDNSKEY) {
   3121 			update_log(client, zone, LOGLEVEL_PROTOCOL,
   3122 				   "update rejected: bad %s RRset",
   3123 				   result == DNS_R_BADCDS ? "CDS" : "CDNSKEY");
   3124 			result = DNS_R_REFUSED;
   3125 			goto failure;
   3126 		}
   3127 		if (result != ISC_R_SUCCESS)
   3128 			goto failure;
   3129 
   3130 	}
   3131 
   3132 	/*
   3133 	 * If any changes were made, increment the SOA serial number,
   3134 	 * update RRSIGs and NSECs (if zone is secure), and write the update
   3135 	 * to the journal.
   3136 	 */
   3137 	if (! ISC_LIST_EMPTY(diff.tuples)) {
   3138 		char *journalfile;
   3139 		dns_journal_t *journal;
   3140 		bool has_dnskey;
   3141 
   3142 		/*
   3143 		 * Increment the SOA serial, but only if it was not
   3144 		 * changed as a result of an update operation.
   3145 		 */
   3146 		if (! soa_serial_changed) {
   3147 			CHECK(update_soa_serial(db, ver, &diff, mctx,
   3148 				       dns_zone_getserialupdatemethod(zone)));
   3149 		}
   3150 
   3151 		CHECK(check_mx(client, zone, db, ver, &diff));
   3152 
   3153 		CHECK(remove_orphaned_ds(db, ver, &diff));
   3154 
   3155 		CHECK(rrset_exists(db, ver, zonename, dns_rdatatype_dnskey,
   3156 				   0, &has_dnskey));
   3157 
   3158 #define ALLOW_SECURE_TO_INSECURE(zone) \
   3159 	((dns_zone_getoptions(zone) & DNS_ZONEOPT_SECURETOINSECURE) != 0)
   3160 
   3161 		CHECK(rrset_exists(db, oldver, zonename, dns_rdatatype_dnskey,
   3162 				   0, &had_dnskey));
   3163 		if (!ALLOW_SECURE_TO_INSECURE(zone)) {
   3164 			if (had_dnskey && !has_dnskey) {
   3165 				update_log(client, zone, LOGLEVEL_PROTOCOL,
   3166 					   "update rejected: all DNSKEY "
   3167 					   "records removed and "
   3168 					   "'dnssec-secure-to-insecure' "
   3169 					   "not set");
   3170 				result = DNS_R_REFUSED;
   3171 				goto failure;
   3172 			}
   3173 		}
   3174 
   3175 		CHECK(rollback_private(db, privatetype, ver, &diff));
   3176 
   3177 		CHECK(add_signing_records(db, privatetype, ver, &diff));
   3178 
   3179 		CHECK(add_nsec3param_records(client, zone, db, ver, &diff));
   3180 
   3181 		if (had_dnskey && !has_dnskey) {
   3182 			/*
   3183 			 * We are transitioning from secure to insecure.
   3184 			 * Cause all NSEC3 chains to be deleted.  When the
   3185 			 * the last signature for the DNSKEY records are
   3186 			 * remove any NSEC chain present will also be removed.
   3187 			 */
   3188 			 CHECK(dns_nsec3param_deletechains(db, ver, zone,
   3189 							   true, &diff));
   3190 		} else if (has_dnskey && isdnssec(db, ver, privatetype)) {
   3191 			uint32_t interval;
   3192 			dns_update_log_t log;
   3193 
   3194 			interval = dns_zone_getsigvalidityinterval(zone);
   3195 			log.func = update_log_cb;
   3196 			log.arg = client;
   3197 			result = dns_update_signatures(&log, zone, db, oldver,
   3198 						       ver, &diff, interval);
   3199 
   3200 			if (result != ISC_R_SUCCESS) {
   3201 				update_log(client, zone,
   3202 					   ISC_LOG_ERROR,
   3203 					   "RRSIG/NSEC/NSEC3 update failed: %s",
   3204 					   isc_result_totext(result));
   3205 				goto failure;
   3206 			}
   3207 		}
   3208 
   3209 		maxrecords = dns_zone_getmaxrecords(zone);
   3210 		if (maxrecords != 0U) {
   3211 			result = dns_db_getsize(db, ver, &records, NULL);
   3212 			if (result == ISC_R_SUCCESS && records > maxrecords) {
   3213 				update_log(client, zone, ISC_LOG_ERROR,
   3214 					   "records in zone (%"
   3215 					   PRIu64
   3216 					   ") exceeds max-records (%u)",
   3217 					   records, maxrecords);
   3218 				result = DNS_R_TOOMANYRECORDS;
   3219 				goto failure;
   3220 			}
   3221 		}
   3222 
   3223 		journalfile = dns_zone_getjournal(zone);
   3224 		if (journalfile != NULL) {
   3225 			update_log(client, zone, LOGLEVEL_DEBUG,
   3226 				   "writing journal %s", journalfile);
   3227 
   3228 			journal = NULL;
   3229 			result = dns_journal_open(mctx, journalfile,
   3230 						  DNS_JOURNAL_CREATE, &journal);
   3231 			if (result != ISC_R_SUCCESS)
   3232 				FAILS(result, "journal open failed");
   3233 
   3234 			result = dns_journal_write_transaction(journal, &diff);
   3235 			if (result != ISC_R_SUCCESS) {
   3236 				dns_journal_destroy(&journal);
   3237 				FAILS(result, "journal write failed");
   3238 			}
   3239 
   3240 			dns_journal_destroy(&journal);
   3241 		}
   3242 
   3243 		/*
   3244 		 * XXXRTH  Just a note that this committing code will have
   3245 		 *	   to change to handle databases that need two-phase
   3246 		 *	   commit, but this isn't a priority.
   3247 		 */
   3248 		update_log(client, zone, LOGLEVEL_DEBUG,
   3249 			   "committing update transaction");
   3250 
   3251 		dns_db_closeversion(db, &ver, true);
   3252 
   3253 		/*
   3254 		 * Mark the zone as dirty so that it will be written to disk.
   3255 		 */
   3256 		dns_zone_markdirty(zone);
   3257 
   3258 		/*
   3259 		 * Notify slaves of the change we just made.
   3260 		 */
   3261 		dns_zone_notify(zone);
   3262 
   3263 		/*
   3264 		 * Cause the zone to be signed with the key that we
   3265 		 * have just added or have the corresponding signatures
   3266 		 * deleted.
   3267 		 *
   3268 		 * Note: we are already committed to this course of action.
   3269 		 */
   3270 		for (tuple = ISC_LIST_HEAD(diff.tuples);
   3271 		     tuple != NULL;
   3272 		     tuple = ISC_LIST_NEXT(tuple, link)) {
   3273 			isc_region_t r;
   3274 			dns_secalg_t algorithm;
   3275 			uint16_t keyid;
   3276 
   3277 			if (tuple->rdata.type != dns_rdatatype_dnskey)
   3278 				continue;
   3279 
   3280 			dns_rdata_tostruct(&tuple->rdata, &dnskey, NULL);
   3281 			if ((dnskey.flags &
   3282 			     (DNS_KEYFLAG_OWNERMASK|DNS_KEYTYPE_NOAUTH))
   3283 				 != DNS_KEYOWNER_ZONE)
   3284 				continue;
   3285 
   3286 			dns_rdata_toregion(&tuple->rdata, &r);
   3287 			algorithm = dnskey.algorithm;
   3288 			keyid = dst_region_computeid(&r, algorithm);
   3289 
   3290 			result = dns_zone_signwithkey(zone, algorithm, keyid,
   3291 					(tuple->op == DNS_DIFFOP_DEL));
   3292 			if (result != ISC_R_SUCCESS) {
   3293 				update_log(client, zone, ISC_LOG_ERROR,
   3294 					   "dns_zone_signwithkey failed: %s",
   3295 					   dns_result_totext(result));
   3296 			}
   3297 		}
   3298 
   3299 		/*
   3300 		 * Cause the zone to add/delete NSEC3 chains for the
   3301 		 * deferred NSEC3PARAM changes.
   3302 		 *
   3303 		 * Note: we are already committed to this course of action.
   3304 		 */
   3305 		for (tuple = ISC_LIST_HEAD(diff.tuples);
   3306 		     tuple != NULL;
   3307 		     tuple = ISC_LIST_NEXT(tuple, link)) {
   3308 			unsigned char buf[DNS_NSEC3PARAM_BUFFERSIZE];
   3309 			dns_rdata_t rdata = DNS_RDATA_INIT;
   3310 			dns_rdata_nsec3param_t nsec3param;
   3311 
   3312 			if (tuple->rdata.type != privatetype ||
   3313 			    tuple->op != DNS_DIFFOP_ADD)
   3314 				continue;
   3315 
   3316 			if (!dns_nsec3param_fromprivate(&tuple->rdata, &rdata,
   3317 						   buf, sizeof(buf)))
   3318 				continue;
   3319 			dns_rdata_tostruct(&rdata, &nsec3param, NULL);
   3320 			if (nsec3param.flags == 0)
   3321 				continue;
   3322 
   3323 			result = dns_zone_addnsec3chain(zone, &nsec3param);
   3324 			if (result != ISC_R_SUCCESS) {
   3325 				update_log(client, zone, ISC_LOG_ERROR,
   3326 					   "dns_zone_addnsec3chain failed: %s",
   3327 					   dns_result_totext(result));
   3328 			}
   3329 		}
   3330 	} else {
   3331 		update_log(client, zone, LOGLEVEL_DEBUG, "redundant request");
   3332 		dns_db_closeversion(db, &ver, true);
   3333 	}
   3334 	result = ISC_R_SUCCESS;
   3335 	goto common;
   3336 
   3337  failure:
   3338 	/*
   3339 	 * The reason for failure should have been logged at this point.
   3340 	 */
   3341 	if (ver != NULL) {
   3342 		update_log(client, zone, LOGLEVEL_DEBUG,
   3343 			   "rolling back");
   3344 		dns_db_closeversion(db, &ver, false);
   3345 	}
   3346 
   3347  common:
   3348 	dns_diff_clear(&temp);
   3349 	dns_diff_clear(&diff);
   3350 
   3351 	if (oldver != NULL)
   3352 		dns_db_closeversion(db, &oldver, false);
   3353 
   3354 	if (db != NULL)
   3355 		dns_db_detach(&db);
   3356 
   3357 	if (ssutable != NULL)
   3358 		dns_ssutable_detach(&ssutable);
   3359 
   3360 	isc_task_detach(&task);
   3361 	uev->result = result;
   3362 	if (zone != NULL)
   3363 		INSIST(uev->zone == zone); /* we use this later */
   3364 	uev->ev_type = DNS_EVENT_UPDATEDONE;
   3365 	uev->ev_action = updatedone_action;
   3366 	isc_task_send(client->task, &event);
   3367 
   3368 	INSIST(ver == NULL);
   3369 	INSIST(event == NULL);
   3370 }
   3371 
   3372 static void
   3373 updatedone_action(isc_task_t *task, isc_event_t *event) {
   3374 	update_event_t *uev = (update_event_t *) event;
   3375 	ns_client_t *client = (ns_client_t *) event->ev_arg;
   3376 
   3377 	UNUSED(task);
   3378 
   3379 	INSIST(event->ev_type == DNS_EVENT_UPDATEDONE);
   3380 	INSIST(task == client->task);
   3381 
   3382 	INSIST(client->nupdates > 0);
   3383 	switch (uev->result) {
   3384 	case ISC_R_SUCCESS:
   3385 		inc_stats(client, uev->zone, ns_statscounter_updatedone);
   3386 		break;
   3387 	case DNS_R_REFUSED:
   3388 		inc_stats(client, uev->zone, ns_statscounter_updaterej);
   3389 		break;
   3390 	default:
   3391 		inc_stats(client, uev->zone, ns_statscounter_updatefail);
   3392 		break;
   3393 	}
   3394 	if (uev->zone != NULL)
   3395 		dns_zone_detach(&uev->zone);
   3396 	client->nupdates--;
   3397 	respond(client, uev->result);
   3398 	isc_event_free(&event);
   3399 	ns_client_detach(&client);
   3400 }
   3401 
   3402 /*%
   3403  * Update forwarding support.
   3404  */
   3405 
   3406 static void
   3407 forward_fail(isc_task_t *task, isc_event_t *event) {
   3408 	ns_client_t *client = (ns_client_t *)event->ev_arg;
   3409 
   3410 	UNUSED(task);
   3411 
   3412 	INSIST(client->nupdates > 0);
   3413 	client->nupdates--;
   3414 	respond(client, DNS_R_SERVFAIL);
   3415 	isc_event_free(&event);
   3416 	ns_client_detach(&client);
   3417 }
   3418 
   3419 
   3420 static void
   3421 forward_callback(void *arg, isc_result_t result, dns_message_t *answer) {
   3422 	update_event_t *uev = arg;
   3423 	ns_client_t *client = uev->ev_arg;
   3424 	dns_zone_t *zone = uev->zone;
   3425 
   3426 	if (result != ISC_R_SUCCESS) {
   3427 		INSIST(answer == NULL);
   3428 		uev->ev_type = DNS_EVENT_UPDATEDONE;
   3429 		uev->ev_action = forward_fail;
   3430 		inc_stats(client, zone, ns_statscounter_updatefwdfail);
   3431 	} else {
   3432 		uev->ev_type = DNS_EVENT_UPDATEDONE;
   3433 		uev->ev_action = forward_done;
   3434 		uev->answer = answer;
   3435 		inc_stats(client, zone, ns_statscounter_updaterespfwd);
   3436 	}
   3437 	isc_task_send(client->task, ISC_EVENT_PTR(&uev));
   3438 	dns_zone_detach(&zone);
   3439 }
   3440 
   3441 static void
   3442 forward_done(isc_task_t *task, isc_event_t *event) {
   3443 	update_event_t *uev = (update_event_t *) event;
   3444 	ns_client_t *client = (ns_client_t *)event->ev_arg;
   3445 
   3446 	UNUSED(task);
   3447 
   3448 	INSIST(client->nupdates > 0);
   3449 	client->nupdates--;
   3450 	ns_client_sendraw(client, uev->answer);
   3451 	dns_message_destroy(&uev->answer);
   3452 	isc_event_free(&event);
   3453 	ns_client_detach(&client);
   3454 }
   3455 
   3456 static void
   3457 forward_action(isc_task_t *task, isc_event_t *event) {
   3458 	update_event_t *uev = (update_event_t *) event;
   3459 	dns_zone_t *zone = uev->zone;
   3460 	ns_client_t *client = (ns_client_t *)event->ev_arg;
   3461 	isc_result_t result;
   3462 
   3463 	result = dns_zone_forwardupdate(zone, client->message,
   3464 					forward_callback, event);
   3465 	if (result != ISC_R_SUCCESS) {
   3466 		uev->ev_type = DNS_EVENT_UPDATEDONE;
   3467 		uev->ev_action = forward_fail;
   3468 		isc_task_send(client->task, &event);
   3469 		inc_stats(client, zone, ns_statscounter_updatefwdfail);
   3470 		dns_zone_detach(&zone);
   3471 	} else
   3472 		inc_stats(client, zone, ns_statscounter_updatereqfwd);
   3473 	isc_task_detach(&task);
   3474 }
   3475 
   3476 static isc_result_t
   3477 send_forward_event(ns_client_t *client, dns_zone_t *zone) {
   3478 	char namebuf[DNS_NAME_FORMATSIZE];
   3479 	char classbuf[DNS_RDATACLASS_FORMATSIZE];
   3480 	isc_result_t result = ISC_R_SUCCESS;
   3481 	update_event_t *event = NULL;
   3482 	isc_task_t *zonetask = NULL;
   3483 	ns_client_t *evclient;
   3484 
   3485 	/*
   3486 	 * This may take some time so replace this client.
   3487 	 */
   3488 	if (!client->mortal && (client->attributes & NS_CLIENTATTR_TCP) == 0)
   3489 		CHECK(ns_client_replace(client));
   3490 
   3491 	event = (update_event_t *)
   3492 		isc_event_allocate(client->mctx, client, DNS_EVENT_UPDATE,
   3493 				   forward_action, NULL, sizeof(*event));
   3494 	if (event == NULL)
   3495 		FAIL(ISC_R_NOMEMORY);
   3496 	event->zone = zone;
   3497 	event->result = ISC_R_SUCCESS;
   3498 
   3499 	evclient = NULL;
   3500 	ns_client_attach(client, &evclient);
   3501 	INSIST(client->nupdates == 0);
   3502 	client->nupdates++;
   3503 	event->ev_arg = evclient;
   3504 
   3505 	dns_name_format(dns_zone_getorigin(zone), namebuf,
   3506 			sizeof(namebuf));
   3507 	dns_rdataclass_format(dns_zone_getclass(zone), classbuf,
   3508 			      sizeof(classbuf));
   3509 
   3510 	ns_client_log(client, NS_LOGCATEGORY_UPDATE, NS_LOGMODULE_UPDATE,
   3511 		      LOGLEVEL_PROTOCOL, "forwarding update for zone '%s/%s'",
   3512 		      namebuf, classbuf);
   3513 
   3514 	dns_zone_gettask(zone, &zonetask);
   3515 	isc_task_send(zonetask, ISC_EVENT_PTR(&event));
   3516 
   3517  failure:
   3518 	if (event != NULL)
   3519 		isc_event_free(ISC_EVENT_PTR(&event));
   3520 	return (result);
   3521 }
   3522