update.c revision 225736
1/*
2 * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
3 * Copyright (C) 1999-2003  Internet Software Consortium.
4 *
5 * Permission to use, copy, modify, and/or distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11 * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15 * PERFORMANCE OF THIS SOFTWARE.
16 */
17
18/* $Id: update.c,v 1.186.16.5 2011-03-25 23:53:52 each Exp $ */
19
20#include <config.h>
21
22#include <isc/netaddr.h>
23#include <isc/print.h>
24#include <isc/serial.h>
25#include <isc/stats.h>
26#include <isc/string.h>
27#include <isc/taskpool.h>
28#include <isc/util.h>
29
30#include <dns/db.h>
31#include <dns/dbiterator.h>
32#include <dns/diff.h>
33#include <dns/dnssec.h>
34#include <dns/events.h>
35#include <dns/fixedname.h>
36#include <dns/journal.h>
37#include <dns/keyvalues.h>
38#include <dns/message.h>
39#include <dns/nsec.h>
40#include <dns/nsec3.h>
41#include <dns/private.h>
42#include <dns/rdataclass.h>
43#include <dns/rdataset.h>
44#include <dns/rdatasetiter.h>
45#include <dns/rdatastruct.h>
46#include <dns/rdatatype.h>
47#include <dns/soa.h>
48#include <dns/ssu.h>
49#include <dns/tsig.h>
50#include <dns/view.h>
51#include <dns/zone.h>
52#include <dns/zt.h>
53
54#include <named/client.h>
55#include <named/log.h>
56#include <named/server.h>
57#include <named/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(zone, dns_nsstatscounter_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_g_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(zone, dns_nsstatscounter_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_g_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(zone, dns_nsstatscounter_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
209typedef struct rr rr_t;
210
211struct rr {
212	/* dns_name_t name; */
213	isc_uint32_t		ttl;
214	dns_rdata_t		rdata;
215};
216
217typedef struct update_event update_event_t;
218
219struct 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/*
228 * Forward declarations.
229 */
230
231static void update_action(isc_task_t *task, isc_event_t *event);
232static void updatedone_action(isc_task_t *task, isc_event_t *event);
233static isc_result_t send_forward_event(ns_client_t *client, dns_zone_t *zone);
234static void forward_done(isc_task_t *task, isc_event_t *event);
235
236/**************************************************************************/
237
238static void
239update_log(ns_client_t *client, dns_zone_t *zone,
240	   int level, const char *fmt, ...) ISC_FORMAT_PRINTF(4, 5);
241
242static void
243update_log(ns_client_t *client, dns_zone_t *zone,
244	   int level, const char *fmt, ...)
245{
246	va_list ap;
247	char message[4096];
248	char namebuf[DNS_NAME_FORMATSIZE];
249	char classbuf[DNS_RDATACLASS_FORMATSIZE];
250
251	if (client == NULL || zone == NULL)
252		return;
253
254	if (isc_log_wouldlog(ns_g_lctx, level) == ISC_FALSE)
255		return;
256
257	dns_name_format(dns_zone_getorigin(zone), namebuf,
258			sizeof(namebuf));
259	dns_rdataclass_format(dns_zone_getclass(zone), classbuf,
260			      sizeof(classbuf));
261
262	va_start(ap, fmt);
263	vsnprintf(message, sizeof(message), fmt, ap);
264	va_end(ap);
265
266	ns_client_log(client, NS_LOGCATEGORY_UPDATE, NS_LOGMODULE_UPDATE,
267		      level, "updating zone '%s/%s': %s",
268		      namebuf, classbuf, message);
269}
270
271/*%
272 * Increment updated-related statistics counters.
273 */
274static inline void
275inc_stats(dns_zone_t *zone, isc_statscounter_t counter) {
276	isc_stats_increment(ns_g_server->nsstats, counter);
277
278	if (zone != NULL) {
279		isc_stats_t *zonestats = dns_zone_getrequeststats(zone);
280		if (zonestats != NULL)
281			isc_stats_increment(zonestats, counter);
282	}
283}
284
285/*%
286 * Check if we could have queried for the contents of this zone or
287 * if the zone is potentially updateable.
288 * If the zone can potentially be updated and the check failed then
289 * log a error otherwise we log a informational message.
290 */
291static isc_result_t
292checkqueryacl(ns_client_t *client, dns_acl_t *queryacl, dns_name_t *zonename,
293	      dns_acl_t *updateacl, dns_ssutable_t *ssutable)
294{
295	char namebuf[DNS_NAME_FORMATSIZE];
296	char classbuf[DNS_RDATACLASS_FORMATSIZE];
297	int level;
298	isc_result_t result;
299
300	result = ns_client_checkaclsilent(client, NULL, queryacl, ISC_TRUE);
301	if (result != ISC_R_SUCCESS) {
302		dns_name_format(zonename, namebuf, sizeof(namebuf));
303		dns_rdataclass_format(client->view->rdclass, classbuf,
304				      sizeof(classbuf));
305
306		level = (updateacl == NULL && ssutable == NULL) ?
307				ISC_LOG_INFO : ISC_LOG_ERROR;
308
309		ns_client_log(client, NS_LOGCATEGORY_UPDATE_SECURITY,
310			      NS_LOGMODULE_UPDATE, level,
311			      "update '%s/%s' denied due to allow-query",
312			      namebuf, classbuf);
313	} else if (updateacl == NULL && ssutable == NULL) {
314		dns_name_format(zonename, namebuf, sizeof(namebuf));
315		dns_rdataclass_format(client->view->rdclass, classbuf,
316				      sizeof(classbuf));
317
318		result = DNS_R_REFUSED;
319		ns_client_log(client, NS_LOGCATEGORY_UPDATE_SECURITY,
320			      NS_LOGMODULE_UPDATE, ISC_LOG_INFO,
321			      "update '%s/%s' denied", namebuf, classbuf);
322	}
323	return (result);
324}
325
326/*%
327 * Override the default acl logging when checking whether a client
328 * can update the zone or whether we can forward the request to the
329 * master based on IP address.
330 *
331 * 'message' contains the type of operation that is being attempted.
332 * 'slave' indicates if this is a slave zone.  If 'acl' is NULL then
333 * log at debug=3.
334 * If the zone has no access controls configured ('acl' == NULL &&
335 * 'has_ssutable == ISC_FALS) log the attempt at info, otherwise
336 * at error.
337 *
338 * If the request was signed log that we received it.
339 */
340static isc_result_t
341checkupdateacl(ns_client_t *client, dns_acl_t *acl, const char *message,
342	       dns_name_t *zonename, isc_boolean_t slave,
343	       isc_boolean_t has_ssutable)
344{
345	char namebuf[DNS_NAME_FORMATSIZE];
346	char classbuf[DNS_RDATACLASS_FORMATSIZE];
347	int level = ISC_LOG_ERROR;
348	const char *msg = "denied";
349	isc_result_t result;
350
351	if (slave && acl == NULL) {
352		result = DNS_R_NOTIMP;
353		level = ISC_LOG_DEBUG(3);
354		msg = "disabled";
355	} else {
356		result = ns_client_checkaclsilent(client, NULL, acl, ISC_FALSE);
357		if (result == ISC_R_SUCCESS) {
358			level = ISC_LOG_DEBUG(3);
359			msg = "approved";
360		} else if (acl == NULL && !has_ssutable) {
361			level = ISC_LOG_INFO;
362		}
363	}
364
365	if (client->signer != NULL) {
366		dns_name_format(client->signer, namebuf, sizeof(namebuf));
367		ns_client_log(client, NS_LOGCATEGORY_UPDATE_SECURITY,
368			      NS_LOGMODULE_UPDATE, ISC_LOG_INFO,
369			      "signer \"%s\" %s", namebuf, msg);
370	}
371
372	dns_name_format(zonename, namebuf, sizeof(namebuf));
373	dns_rdataclass_format(client->view->rdclass, classbuf,
374			      sizeof(classbuf));
375
376	ns_client_log(client, NS_LOGCATEGORY_UPDATE_SECURITY,
377		      NS_LOGMODULE_UPDATE, level, "%s '%s/%s' %s",
378		      message, namebuf, classbuf, msg);
379	return (result);
380}
381
382/*%
383 * Update a single RR in version 'ver' of 'db' and log the
384 * update in 'diff'.
385 *
386 * Ensures:
387 * \li	'*tuple' == NULL.  Either the tuple is freed, or its
388 *	ownership has been transferred to the diff.
389 */
390static isc_result_t
391do_one_tuple(dns_difftuple_t **tuple, dns_db_t *db, dns_dbversion_t *ver,
392	     dns_diff_t *diff)
393{
394	dns_diff_t temp_diff;
395	isc_result_t result;
396
397	/*
398	 * Create a singleton diff.
399	 */
400	dns_diff_init(diff->mctx, &temp_diff);
401	temp_diff.resign = diff->resign;
402	ISC_LIST_APPEND(temp_diff.tuples, *tuple, link);
403
404	/*
405	 * Apply it to the database.
406	 */
407	result = dns_diff_apply(&temp_diff, db, ver);
408	ISC_LIST_UNLINK(temp_diff.tuples, *tuple, link);
409	if (result != ISC_R_SUCCESS) {
410		dns_difftuple_free(tuple);
411		return (result);
412	}
413
414	/*
415	 * Merge it into the current pending journal entry.
416	 */
417	dns_diff_appendminimal(diff, tuple);
418
419	/*
420	 * Do not clear temp_diff.
421	 */
422	return (ISC_R_SUCCESS);
423}
424
425/*%
426 * Perform the updates in 'updates' in version 'ver' of 'db' and log the
427 * update in 'diff'.
428 *
429 * Ensures:
430 * \li	'updates' is empty.
431 */
432static isc_result_t
433do_diff(dns_diff_t *updates, dns_db_t *db, dns_dbversion_t *ver,
434	dns_diff_t *diff)
435{
436	isc_result_t result;
437	while (! ISC_LIST_EMPTY(updates->tuples)) {
438		dns_difftuple_t *t = ISC_LIST_HEAD(updates->tuples);
439		ISC_LIST_UNLINK(updates->tuples, t, link);
440		CHECK(do_one_tuple(&t, db, ver, diff));
441	}
442	return (ISC_R_SUCCESS);
443
444 failure:
445	dns_diff_clear(diff);
446	return (result);
447}
448
449static isc_result_t
450update_one_rr(dns_db_t *db, dns_dbversion_t *ver, dns_diff_t *diff,
451	      dns_diffop_t op, dns_name_t *name, dns_ttl_t ttl,
452	      dns_rdata_t *rdata)
453{
454	dns_difftuple_t *tuple = NULL;
455	isc_result_t result;
456	result = dns_difftuple_create(diff->mctx, op,
457				      name, ttl, rdata, &tuple);
458	if (result != ISC_R_SUCCESS)
459		return (result);
460	return (do_one_tuple(&tuple, db, ver, diff));
461}
462
463/**************************************************************************/
464/*
465 * Callback-style iteration over rdatasets and rdatas.
466 *
467 * foreach_rrset() can be used to iterate over the RRsets
468 * of a name and call a callback function with each
469 * one.  Similarly, foreach_rr() can be used to iterate
470 * over the individual RRs at name, optionally restricted
471 * to RRs of a given type.
472 *
473 * The callback functions are called "actions" and take
474 * two arguments: a void pointer for passing arbitrary
475 * context information, and a pointer to the current RRset
476 * or RR.  By convention, their names end in "_action".
477 */
478
479/*
480 * XXXRTH  We might want to make this public somewhere in libdns.
481 */
482
483/*%
484 * Function type for foreach_rrset() iterator actions.
485 */
486typedef isc_result_t rrset_func(void *data, dns_rdataset_t *rrset);
487
488/*%
489 * Function type for foreach_rr() iterator actions.
490 */
491typedef isc_result_t rr_func(void *data, rr_t *rr);
492
493/*%
494 * Internal context struct for foreach_node_rr().
495 */
496typedef struct {
497	rr_func *	rr_action;
498	void *		rr_action_data;
499} foreach_node_rr_ctx_t;
500
501/*%
502 * Internal helper function for foreach_node_rr().
503 */
504static isc_result_t
505foreach_node_rr_action(void *data, dns_rdataset_t *rdataset) {
506	isc_result_t result;
507	foreach_node_rr_ctx_t *ctx = data;
508	for (result = dns_rdataset_first(rdataset);
509	     result == ISC_R_SUCCESS;
510	     result = dns_rdataset_next(rdataset))
511	{
512		rr_t rr = { 0, DNS_RDATA_INIT };
513
514		dns_rdataset_current(rdataset, &rr.rdata);
515		rr.ttl = rdataset->ttl;
516		result = (*ctx->rr_action)(ctx->rr_action_data, &rr);
517		if (result != ISC_R_SUCCESS)
518			return (result);
519	}
520	if (result != ISC_R_NOMORE)
521		return (result);
522	return (ISC_R_SUCCESS);
523}
524
525/*%
526 * For each rdataset of 'name' in 'ver' of 'db', call 'action'
527 * with the rdataset and 'action_data' as arguments.  If the name
528 * does not exist, do nothing.
529 *
530 * If 'action' returns an error, abort iteration and return the error.
531 */
532static isc_result_t
533foreach_rrset(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
534	      rrset_func *action, void *action_data)
535{
536	isc_result_t result;
537	dns_dbnode_t *node;
538	dns_rdatasetiter_t *iter;
539
540	node = NULL;
541	result = dns_db_findnode(db, name, ISC_FALSE, &node);
542	if (result == ISC_R_NOTFOUND)
543		return (ISC_R_SUCCESS);
544	if (result != ISC_R_SUCCESS)
545		return (result);
546
547	iter = NULL;
548	result = dns_db_allrdatasets(db, node, ver,
549				     (isc_stdtime_t) 0, &iter);
550	if (result != ISC_R_SUCCESS)
551		goto cleanup_node;
552
553	for (result = dns_rdatasetiter_first(iter);
554	     result == ISC_R_SUCCESS;
555	     result = dns_rdatasetiter_next(iter))
556	{
557		dns_rdataset_t rdataset;
558
559		dns_rdataset_init(&rdataset);
560		dns_rdatasetiter_current(iter, &rdataset);
561
562		result = (*action)(action_data, &rdataset);
563
564		dns_rdataset_disassociate(&rdataset);
565		if (result != ISC_R_SUCCESS)
566			goto cleanup_iterator;
567	}
568	if (result == ISC_R_NOMORE)
569		result = ISC_R_SUCCESS;
570
571 cleanup_iterator:
572	dns_rdatasetiter_destroy(&iter);
573
574 cleanup_node:
575	dns_db_detachnode(db, &node);
576
577	return (result);
578}
579
580/*%
581 * For each RR of 'name' in 'ver' of 'db', call 'action'
582 * with the RR and 'action_data' as arguments.  If the name
583 * does not exist, do nothing.
584 *
585 * If 'action' returns an error, abort iteration
586 * and return the error.
587 */
588static isc_result_t
589foreach_node_rr(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
590		rr_func *rr_action, void *rr_action_data)
591{
592	foreach_node_rr_ctx_t ctx;
593	ctx.rr_action = rr_action;
594	ctx.rr_action_data = rr_action_data;
595	return (foreach_rrset(db, ver, name,
596			      foreach_node_rr_action, &ctx));
597}
598
599
600/*%
601 * For each of the RRs specified by 'db', 'ver', 'name', 'type',
602 * (which can be dns_rdatatype_any to match any type), and 'covers', call
603 * 'action' with the RR and 'action_data' as arguments. If the name
604 * does not exist, or if no RRset of the given type exists at the name,
605 * do nothing.
606 *
607 * If 'action' returns an error, abort iteration and return the error.
608 */
609static isc_result_t
610foreach_rr(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
611	   dns_rdatatype_t type, dns_rdatatype_t covers, rr_func *rr_action,
612	   void *rr_action_data)
613{
614
615	isc_result_t result;
616	dns_dbnode_t *node;
617	dns_rdataset_t rdataset;
618
619	if (type == dns_rdatatype_any)
620		return (foreach_node_rr(db, ver, name,
621					rr_action, rr_action_data));
622
623	node = NULL;
624	if (type == dns_rdatatype_nsec3 ||
625	    (type == dns_rdatatype_rrsig && covers == dns_rdatatype_nsec3))
626		result = dns_db_findnsec3node(db, name, ISC_FALSE, &node);
627	else
628		result = dns_db_findnode(db, name, ISC_FALSE, &node);
629	if (result == ISC_R_NOTFOUND)
630		return (ISC_R_SUCCESS);
631	if (result != ISC_R_SUCCESS)
632		return (result);
633
634	dns_rdataset_init(&rdataset);
635	result = dns_db_findrdataset(db, node, ver, type, covers,
636				     (isc_stdtime_t) 0, &rdataset, NULL);
637	if (result == ISC_R_NOTFOUND) {
638		result = ISC_R_SUCCESS;
639		goto cleanup_node;
640	}
641	if (result != ISC_R_SUCCESS)
642		goto cleanup_node;
643
644	for (result = dns_rdataset_first(&rdataset);
645	     result == ISC_R_SUCCESS;
646	     result = dns_rdataset_next(&rdataset))
647	{
648		rr_t rr = { 0, DNS_RDATA_INIT };
649		dns_rdataset_current(&rdataset, &rr.rdata);
650		rr.ttl = rdataset.ttl;
651		result = (*rr_action)(rr_action_data, &rr);
652		if (result != ISC_R_SUCCESS)
653			goto cleanup_rdataset;
654	}
655	if (result != ISC_R_NOMORE)
656		goto cleanup_rdataset;
657	result = ISC_R_SUCCESS;
658
659 cleanup_rdataset:
660	dns_rdataset_disassociate(&rdataset);
661 cleanup_node:
662	dns_db_detachnode(db, &node);
663
664	return (result);
665}
666
667/**************************************************************************/
668/*
669 * Various tests on the database contents (for prerequisites, etc).
670 */
671
672/*%
673 * Function type for predicate functions that compare a database RR 'db_rr'
674 * against an update RR 'update_rr'.
675 */
676typedef isc_boolean_t rr_predicate(dns_rdata_t *update_rr, dns_rdata_t *db_rr);
677
678/*%
679 * Helper function for rrset_exists().
680 */
681static isc_result_t
682rrset_exists_action(void *data, rr_t *rr) {
683	UNUSED(data);
684	UNUSED(rr);
685	return (ISC_R_EXISTS);
686}
687
688/*%
689 * Utility macro for RR existence checking functions.
690 *
691 * If the variable 'result' has the value ISC_R_EXISTS or
692 * ISC_R_SUCCESS, set *exists to ISC_TRUE or ISC_FALSE,
693 * respectively, and return success.
694 *
695 * If 'result' has any other value, there was a failure.
696 * Return the failure result code and do not set *exists.
697 *
698 * This would be more readable as "do { if ... } while(0)",
699 * but that form generates tons of warnings on Solaris 2.6.
700 */
701#define RETURN_EXISTENCE_FLAG				\
702	return ((result == ISC_R_EXISTS) ?		\
703		(*exists = ISC_TRUE, ISC_R_SUCCESS) :	\
704		((result == ISC_R_SUCCESS) ?		\
705		 (*exists = ISC_FALSE, ISC_R_SUCCESS) :	\
706		 result))
707
708/*%
709 * Set '*exists' to true iff an rrset of the given type exists,
710 * to false otherwise.
711 */
712static isc_result_t
713rrset_exists(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
714	     dns_rdatatype_t type, dns_rdatatype_t covers,
715	     isc_boolean_t *exists)
716{
717	isc_result_t result;
718	result = foreach_rr(db, ver, name, type, covers,
719			    rrset_exists_action, NULL);
720	RETURN_EXISTENCE_FLAG;
721}
722
723/*%
724 * Set '*visible' to true if the RRset exists and is part of the
725 * visible zone.  Otherwise '*visible' is set to false unless a
726 * error occurs.
727 */
728static isc_result_t
729rrset_visible(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
730	      dns_rdatatype_t type, isc_boolean_t *visible)
731{
732	isc_result_t result;
733	dns_fixedname_t fixed;
734
735	dns_fixedname_init(&fixed);
736	result = dns_db_find(db, name, ver, type, DNS_DBFIND_NOWILD,
737			     (isc_stdtime_t) 0, NULL,
738			     dns_fixedname_name(&fixed), NULL, NULL);
739	switch (result) {
740	case ISC_R_SUCCESS:
741		*visible = ISC_TRUE;
742		break;
743	/*
744	 * Glue, obscured, deleted or replaced records.
745	 */
746	case DNS_R_DELEGATION:
747	case DNS_R_DNAME:
748	case DNS_R_CNAME:
749	case DNS_R_NXDOMAIN:
750	case DNS_R_NXRRSET:
751	case DNS_R_EMPTYNAME:
752	case DNS_R_COVERINGNSEC:
753		*visible = ISC_FALSE;
754		result = ISC_R_SUCCESS;
755		break;
756	default:
757		break;
758	}
759	return (result);
760}
761
762/*%
763 * Helper function for cname_incompatible_rrset_exists.
764 */
765static isc_result_t
766cname_compatibility_action(void *data, dns_rdataset_t *rrset) {
767	UNUSED(data);
768	if (rrset->type != dns_rdatatype_cname &&
769	    ! dns_rdatatype_isdnssec(rrset->type))
770		return (ISC_R_EXISTS);
771	return (ISC_R_SUCCESS);
772}
773
774/*%
775 * Check whether there is an rrset incompatible with adding a CNAME RR,
776 * i.e., anything but another CNAME (which can be replaced) or a
777 * DNSSEC RR (which can coexist).
778 *
779 * If such an incompatible rrset exists, set '*exists' to ISC_TRUE.
780 * Otherwise, set it to ISC_FALSE.
781 */
782static isc_result_t
783cname_incompatible_rrset_exists(dns_db_t *db, dns_dbversion_t *ver,
784				dns_name_t *name, isc_boolean_t *exists) {
785	isc_result_t result;
786	result = foreach_rrset(db, ver, name,
787			       cname_compatibility_action, NULL);
788	RETURN_EXISTENCE_FLAG;
789}
790
791/*%
792 * Helper function for rr_count().
793 */
794static isc_result_t
795count_rr_action(void *data, rr_t *rr) {
796	int *countp = data;
797	UNUSED(rr);
798	(*countp)++;
799	return (ISC_R_SUCCESS);
800}
801
802/*%
803 * Count the number of RRs of 'type' belonging to 'name' in 'ver' of 'db'.
804 */
805static isc_result_t
806rr_count(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
807	 dns_rdatatype_t type, dns_rdatatype_t covers, int *countp)
808{
809	*countp = 0;
810	return (foreach_rr(db, ver, name, type, covers,
811			   count_rr_action, countp));
812}
813
814/*%
815 * Context struct and helper function for name_exists().
816 */
817
818static isc_result_t
819name_exists_action(void *data, dns_rdataset_t *rrset) {
820	UNUSED(data);
821	UNUSED(rrset);
822	return (ISC_R_EXISTS);
823}
824
825/*%
826 * Set '*exists' to true iff the given name exists, to false otherwise.
827 */
828static isc_result_t
829name_exists(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
830	    isc_boolean_t *exists)
831{
832	isc_result_t result;
833	result = foreach_rrset(db, ver, name,
834			       name_exists_action, NULL);
835	RETURN_EXISTENCE_FLAG;
836}
837
838/*
839 *	'ssu_check_t' is used to pass the arguments to
840 *	dns_ssutable_checkrules() to the callback function
841 *	ssu_checkrule().
842 */
843typedef struct {
844	/* The ownername of the record to be updated. */
845	dns_name_t *name;
846
847	/* The signature's name if the request was signed. */
848	dns_name_t *signer;
849
850	/* The address of the client if the request was received via TCP. */
851	isc_netaddr_t *tcpaddr;
852
853	/* The ssu table to check against. */
854	dns_ssutable_t *table;
855
856	/* the key used for TKEY requests */
857	dst_key_t *key;
858} ssu_check_t;
859
860static isc_result_t
861ssu_checkrule(void *data, dns_rdataset_t *rrset) {
862	ssu_check_t *ssuinfo = data;
863	isc_boolean_t result;
864
865	/*
866	 * If we're deleting all records, it's ok to delete RRSIG and NSEC even
867	 * if we're normally not allowed to.
868	 */
869	if (rrset->type == dns_rdatatype_rrsig ||
870	    rrset->type == dns_rdatatype_nsec)
871		return (ISC_R_SUCCESS);
872	result = dns_ssutable_checkrules(ssuinfo->table, ssuinfo->signer,
873					 ssuinfo->name, ssuinfo->tcpaddr,
874					 rrset->type, ssuinfo->key);
875	return (result == ISC_TRUE ? ISC_R_SUCCESS : ISC_R_FAILURE);
876}
877
878static isc_boolean_t
879ssu_checkall(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
880	     dns_ssutable_t *ssutable, dns_name_t *signer,
881	     isc_netaddr_t *tcpaddr, dst_key_t *key)
882{
883	isc_result_t result;
884	ssu_check_t ssuinfo;
885
886	ssuinfo.name = name;
887	ssuinfo.table = ssutable;
888	ssuinfo.signer = signer;
889	ssuinfo.tcpaddr = tcpaddr;
890	ssuinfo.key = key;
891	result = foreach_rrset(db, ver, name, ssu_checkrule, &ssuinfo);
892	return (ISC_TF(result == ISC_R_SUCCESS));
893}
894
895/**************************************************************************/
896/*
897 * Checking of "RRset exists (value dependent)" prerequisites.
898 *
899 * In the RFC2136 section 3.2.5, this is the pseudocode involving
900 * a variable called "temp", a mapping of <name, type> tuples to rrsets.
901 *
902 * Here, we represent the "temp" data structure as (non-minimal) "dns_diff_t"
903 * where each tuple has op==DNS_DIFFOP_EXISTS.
904 */
905
906
907/*%
908 * Append a tuple asserting the existence of the RR with
909 * 'name' and 'rdata' to 'diff'.
910 */
911static isc_result_t
912temp_append(dns_diff_t *diff, dns_name_t *name, dns_rdata_t *rdata) {
913	isc_result_t result;
914	dns_difftuple_t *tuple = NULL;
915
916	REQUIRE(DNS_DIFF_VALID(diff));
917	CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_EXISTS,
918				   name, 0, rdata, &tuple));
919	ISC_LIST_APPEND(diff->tuples, tuple, link);
920 failure:
921	return (result);
922}
923
924/*%
925 * Compare two rdatasets represented as sorted lists of tuples.
926 * All list elements must have the same owner name and type.
927 * Return ISC_R_SUCCESS if the rdatasets are equal, rcode(dns_rcode_nxrrset)
928 * if not.
929 */
930static isc_result_t
931temp_check_rrset(dns_difftuple_t *a, dns_difftuple_t *b) {
932	for (;;) {
933		if (a == NULL || b == NULL)
934			break;
935		INSIST(a->op == DNS_DIFFOP_EXISTS &&
936		       b->op == DNS_DIFFOP_EXISTS);
937		INSIST(a->rdata.type == b->rdata.type);
938		INSIST(dns_name_equal(&a->name, &b->name));
939		if (dns_rdata_casecompare(&a->rdata, &b->rdata) != 0)
940			return (DNS_R_NXRRSET);
941		a = ISC_LIST_NEXT(a, link);
942		b = ISC_LIST_NEXT(b, link);
943	}
944	if (a != NULL || b != NULL)
945		return (DNS_R_NXRRSET);
946	return (ISC_R_SUCCESS);
947}
948
949/*%
950 * A comparison function defining the sorting order for the entries
951 * in the "temp" data structure.  The major sort key is the owner name,
952 * followed by the type and rdata.
953 */
954static int
955temp_order(const void *av, const void *bv) {
956	dns_difftuple_t const * const *ap = av;
957	dns_difftuple_t const * const *bp = bv;
958	dns_difftuple_t const *a = *ap;
959	dns_difftuple_t const *b = *bp;
960	int r;
961	r = dns_name_compare(&a->name, &b->name);
962	if (r != 0)
963		return (r);
964	r = (b->rdata.type - a->rdata.type);
965	if (r != 0)
966		return (r);
967	r = dns_rdata_casecompare(&a->rdata, &b->rdata);
968	return (r);
969}
970
971/*%
972 * Check the "RRset exists (value dependent)" prerequisite information
973 * in 'temp' against the contents of the database 'db'.
974 *
975 * Return ISC_R_SUCCESS if the prerequisites are satisfied,
976 * rcode(dns_rcode_nxrrset) if not.
977 *
978 * 'temp' must be pre-sorted.
979 */
980
981static isc_result_t
982temp_check(isc_mem_t *mctx, dns_diff_t *temp, dns_db_t *db,
983	   dns_dbversion_t *ver, dns_name_t *tmpname, dns_rdatatype_t *typep)
984{
985	isc_result_t result;
986	dns_name_t *name;
987	dns_dbnode_t *node;
988	dns_difftuple_t *t;
989	dns_diff_t trash;
990
991	dns_diff_init(mctx, &trash);
992
993	/*
994	 * For each name and type in the prerequisites,
995	 * construct a sorted rdata list of the corresponding
996	 * database contents, and compare the lists.
997	 */
998	t = ISC_LIST_HEAD(temp->tuples);
999	while (t != NULL) {
1000		name = &t->name;
1001		(void)dns_name_copy(name, tmpname, NULL);
1002		*typep = t->rdata.type;
1003
1004		/* A new unique name begins here. */
1005		node = NULL;
1006		result = dns_db_findnode(db, name, ISC_FALSE, &node);
1007		if (result == ISC_R_NOTFOUND) {
1008			dns_diff_clear(&trash);
1009			return (DNS_R_NXRRSET);
1010		}
1011		if (result != ISC_R_SUCCESS) {
1012			dns_diff_clear(&trash);
1013			return (result);
1014		}
1015
1016		/* A new unique type begins here. */
1017		while (t != NULL && dns_name_equal(&t->name, name)) {
1018			dns_rdatatype_t type, covers;
1019			dns_rdataset_t rdataset;
1020			dns_diff_t d_rrs; /* Database RRs with
1021						this name and type */
1022			dns_diff_t u_rrs; /* Update RRs with
1023						this name and type */
1024
1025			*typep = type = t->rdata.type;
1026			if (type == dns_rdatatype_rrsig ||
1027			    type == dns_rdatatype_sig)
1028				covers = dns_rdata_covers(&t->rdata);
1029			else if (type == dns_rdatatype_any) {
1030				dns_db_detachnode(db, &node);
1031				dns_diff_clear(&trash);
1032				return (DNS_R_NXRRSET);
1033			} else
1034				covers = 0;
1035
1036			/*
1037			 * Collect all database RRs for this name and type
1038			 * onto d_rrs and sort them.
1039			 */
1040			dns_rdataset_init(&rdataset);
1041			result = dns_db_findrdataset(db, node, ver, type,
1042						     covers, (isc_stdtime_t) 0,
1043						     &rdataset, NULL);
1044			if (result != ISC_R_SUCCESS) {
1045				dns_db_detachnode(db, &node);
1046				dns_diff_clear(&trash);
1047				return (DNS_R_NXRRSET);
1048			}
1049
1050			dns_diff_init(mctx, &d_rrs);
1051			dns_diff_init(mctx, &u_rrs);
1052
1053			for (result = dns_rdataset_first(&rdataset);
1054			     result == ISC_R_SUCCESS;
1055			     result = dns_rdataset_next(&rdataset))
1056			{
1057				dns_rdata_t rdata = DNS_RDATA_INIT;
1058				dns_rdataset_current(&rdataset, &rdata);
1059				result = temp_append(&d_rrs, name, &rdata);
1060				if (result != ISC_R_SUCCESS)
1061					goto failure;
1062			}
1063			if (result != ISC_R_NOMORE)
1064				goto failure;
1065			result = dns_diff_sort(&d_rrs, temp_order);
1066			if (result != ISC_R_SUCCESS)
1067				goto failure;
1068
1069			/*
1070			 * Collect all update RRs for this name and type
1071			 * onto u_rrs.  No need to sort them here -
1072			 * they are already sorted.
1073			 */
1074			while (t != NULL &&
1075			       dns_name_equal(&t->name, name) &&
1076			       t->rdata.type == type)
1077			{
1078				dns_difftuple_t *next =
1079					ISC_LIST_NEXT(t, link);
1080				ISC_LIST_UNLINK(temp->tuples, t, link);
1081				ISC_LIST_APPEND(u_rrs.tuples, t, link);
1082				t = next;
1083			}
1084
1085			/* Compare the two sorted lists. */
1086			result = temp_check_rrset(ISC_LIST_HEAD(u_rrs.tuples),
1087						  ISC_LIST_HEAD(d_rrs.tuples));
1088			if (result != ISC_R_SUCCESS)
1089				goto failure;
1090
1091			/*
1092			 * We are done with the tuples, but we can't free
1093			 * them yet because "name" still points into one
1094			 * of them.  Move them on a temporary list.
1095			 */
1096			ISC_LIST_APPENDLIST(trash.tuples, u_rrs.tuples, link);
1097			ISC_LIST_APPENDLIST(trash.tuples, d_rrs.tuples, link);
1098			dns_rdataset_disassociate(&rdataset);
1099
1100			continue;
1101
1102		    failure:
1103			dns_diff_clear(&d_rrs);
1104			dns_diff_clear(&u_rrs);
1105			dns_diff_clear(&trash);
1106			dns_rdataset_disassociate(&rdataset);
1107			dns_db_detachnode(db, &node);
1108			return (result);
1109		}
1110
1111		dns_db_detachnode(db, &node);
1112	}
1113
1114	dns_diff_clear(&trash);
1115	return (ISC_R_SUCCESS);
1116}
1117
1118/**************************************************************************/
1119/*
1120 * Conditional deletion of RRs.
1121 */
1122
1123/*%
1124 * Context structure for delete_if().
1125 */
1126
1127typedef struct {
1128	rr_predicate *predicate;
1129	dns_db_t *db;
1130	dns_dbversion_t *ver;
1131	dns_diff_t *diff;
1132	dns_name_t *name;
1133	dns_rdata_t *update_rr;
1134} conditional_delete_ctx_t;
1135
1136/*%
1137 * Predicate functions for delete_if().
1138 */
1139
1140/*%
1141 * Return true iff 'db_rr' is neither a SOA nor an NS RR nor
1142 * an RRSIG nor an NSEC3PARAM nor a NSEC.
1143 */
1144static isc_boolean_t
1145type_not_soa_nor_ns_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
1146	UNUSED(update_rr);
1147	return ((db_rr->type != dns_rdatatype_soa &&
1148		 db_rr->type != dns_rdatatype_ns &&
1149		 db_rr->type != dns_rdatatype_nsec3param &&
1150		 db_rr->type != dns_rdatatype_rrsig &&
1151		 db_rr->type != dns_rdatatype_nsec) ?
1152		ISC_TRUE : ISC_FALSE);
1153}
1154
1155/*%
1156 * Return true iff 'db_rr' is neither a RRSIG nor a NSEC.
1157 */
1158static isc_boolean_t
1159type_not_dnssec(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
1160	UNUSED(update_rr);
1161	return ((db_rr->type != dns_rdatatype_rrsig &&
1162		 db_rr->type != dns_rdatatype_nsec) ?
1163		ISC_TRUE : ISC_FALSE);
1164}
1165
1166/*%
1167 * Return true always.
1168 */
1169static isc_boolean_t
1170true_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
1171	UNUSED(update_rr);
1172	UNUSED(db_rr);
1173	return (ISC_TRUE);
1174}
1175
1176/*%
1177 * Return true if the record is a RRSIG.
1178 */
1179static isc_boolean_t
1180rrsig_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
1181	UNUSED(update_rr);
1182	return ((db_rr->type == dns_rdatatype_rrsig) ?
1183		ISC_TRUE : ISC_FALSE);
1184}
1185
1186/*%
1187 * Return true iff the two RRs have identical rdata.
1188 */
1189static isc_boolean_t
1190rr_equal_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
1191	/*
1192	 * XXXRTH  This is not a problem, but we should consider creating
1193	 *         dns_rdata_equal() (that used dns_name_equal()), since it
1194	 *         would be faster.  Not a priority.
1195	 */
1196	return (dns_rdata_casecompare(update_rr, db_rr) == 0 ?
1197		ISC_TRUE : ISC_FALSE);
1198}
1199
1200/*%
1201 * Return true iff 'update_rr' should replace 'db_rr' according
1202 * to the special RFC2136 rules for CNAME, SOA, and WKS records.
1203 *
1204 * RFC2136 does not mention NSEC or DNAME, but multiple NSECs or DNAMEs
1205 * make little sense, so we replace those, too.
1206 *
1207 * Additionally replace RRSIG that have been generated by the same key
1208 * for the same type.  This simplifies refreshing a offline KSK by not
1209 * requiring that the old RRSIG be deleted.  It also simplifies key
1210 * rollover by only requiring that the new RRSIG be added.
1211 */
1212static isc_boolean_t
1213replaces_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
1214	dns_rdata_rrsig_t updatesig, dbsig;
1215	isc_result_t result;
1216
1217	if (db_rr->type != update_rr->type)
1218		return (ISC_FALSE);
1219	if (db_rr->type == dns_rdatatype_cname)
1220		return (ISC_TRUE);
1221	if (db_rr->type == dns_rdatatype_dname)
1222		return (ISC_TRUE);
1223	if (db_rr->type == dns_rdatatype_soa)
1224		return (ISC_TRUE);
1225	if (db_rr->type == dns_rdatatype_nsec)
1226		return (ISC_TRUE);
1227	if (db_rr->type == dns_rdatatype_rrsig) {
1228		/*
1229		 * Replace existing RRSIG with the same keyid,
1230		 * covered and algorithm.
1231		 */
1232		result = dns_rdata_tostruct(db_rr, &dbsig, NULL);
1233		RUNTIME_CHECK(result == ISC_R_SUCCESS);
1234		result = dns_rdata_tostruct(update_rr, &updatesig, NULL);
1235		RUNTIME_CHECK(result == ISC_R_SUCCESS);
1236		if (dbsig.keyid == updatesig.keyid &&
1237		    dbsig.covered == updatesig.covered &&
1238		    dbsig.algorithm == updatesig.algorithm)
1239			return (ISC_TRUE);
1240	}
1241	if (db_rr->type == dns_rdatatype_wks) {
1242		/*
1243		 * Compare the address and protocol fields only.  These
1244		 * form the first five bytes of the RR data.  Do a
1245		 * raw binary comparison; unpacking the WKS RRs using
1246		 * dns_rdata_tostruct() might be cleaner in some ways.
1247		 */
1248		INSIST(db_rr->length >= 5 && update_rr->length >= 5);
1249		return (memcmp(db_rr->data, update_rr->data, 5) == 0 ?
1250			ISC_TRUE : ISC_FALSE);
1251	}
1252
1253	if (db_rr->type == dns_rdatatype_nsec3param) {
1254		if (db_rr->length != update_rr->length)
1255			return (ISC_FALSE);
1256		INSIST(db_rr->length >= 4 && update_rr->length >= 4);
1257		/*
1258		 * Replace NSEC3PARAM records that only differ by the
1259		 * flags field.
1260		 */
1261		if (db_rr->data[0] == update_rr->data[0] &&
1262		    memcmp(db_rr->data+2, update_rr->data+2,
1263			   update_rr->length - 2) == 0)
1264			return (ISC_TRUE);
1265	}
1266	return (ISC_FALSE);
1267}
1268
1269/*%
1270 * Internal helper function for delete_if().
1271 */
1272static isc_result_t
1273delete_if_action(void *data, rr_t *rr) {
1274	conditional_delete_ctx_t *ctx = data;
1275	if ((*ctx->predicate)(ctx->update_rr, &rr->rdata)) {
1276		isc_result_t result;
1277		result = update_one_rr(ctx->db, ctx->ver, ctx->diff,
1278				       DNS_DIFFOP_DEL, ctx->name,
1279				       rr->ttl, &rr->rdata);
1280		return (result);
1281	} else {
1282		return (ISC_R_SUCCESS);
1283	}
1284}
1285
1286/*%
1287 * Conditionally delete RRs.  Apply 'predicate' to the RRs
1288 * specified by 'db', 'ver', 'name', and 'type' (which can
1289 * be dns_rdatatype_any to match any type).  Delete those
1290 * RRs for which the predicate returns true, and log the
1291 * deletions in 'diff'.
1292 */
1293static isc_result_t
1294delete_if(rr_predicate *predicate, dns_db_t *db, dns_dbversion_t *ver,
1295	  dns_name_t *name, dns_rdatatype_t type, dns_rdatatype_t covers,
1296	  dns_rdata_t *update_rr, dns_diff_t *diff)
1297{
1298	conditional_delete_ctx_t ctx;
1299	ctx.predicate = predicate;
1300	ctx.db = db;
1301	ctx.ver = ver;
1302	ctx.diff = diff;
1303	ctx.name = name;
1304	ctx.update_rr = update_rr;
1305	return (foreach_rr(db, ver, name, type, covers,
1306			   delete_if_action, &ctx));
1307}
1308
1309/**************************************************************************/
1310/*%
1311 * Prepare an RR for the addition of the new RR 'ctx->update_rr',
1312 * with TTL 'ctx->update_rr_ttl', to its rdataset, by deleting
1313 * the RRs if it is replaced by the new RR or has a conflicting TTL.
1314 * The necessary changes are appended to ctx->del_diff and ctx->add_diff;
1315 * we need to do all deletions before any additions so that we don't run
1316 * into transient states with conflicting TTLs.
1317 */
1318
1319typedef struct {
1320	dns_db_t *db;
1321	dns_dbversion_t *ver;
1322	dns_diff_t *diff;
1323	dns_name_t *name;
1324	dns_rdata_t *update_rr;
1325	dns_ttl_t update_rr_ttl;
1326	isc_boolean_t ignore_add;
1327	dns_diff_t del_diff;
1328	dns_diff_t add_diff;
1329} add_rr_prepare_ctx_t;
1330
1331static isc_result_t
1332add_rr_prepare_action(void *data, rr_t *rr) {
1333	isc_result_t result = ISC_R_SUCCESS;
1334	add_rr_prepare_ctx_t *ctx = data;
1335	dns_difftuple_t *tuple = NULL;
1336	isc_boolean_t equal;
1337
1338	/*
1339	 * If the update RR is a "duplicate" of the update RR,
1340	 * the update should be silently ignored.
1341	 */
1342	equal = ISC_TF(dns_rdata_casecompare(&rr->rdata, ctx->update_rr) == 0);
1343	if (equal && rr->ttl == ctx->update_rr_ttl) {
1344		ctx->ignore_add = ISC_TRUE;
1345		return (ISC_R_SUCCESS);
1346	}
1347
1348	/*
1349	 * If this RR is "equal" to the update RR, it should
1350	 * be deleted before the update RR is added.
1351	 */
1352	if (replaces_p(ctx->update_rr, &rr->rdata)) {
1353		CHECK(dns_difftuple_create(ctx->del_diff.mctx, DNS_DIFFOP_DEL,
1354					   ctx->name, rr->ttl, &rr->rdata,
1355					   &tuple));
1356		dns_diff_append(&ctx->del_diff, &tuple);
1357		return (ISC_R_SUCCESS);
1358	}
1359
1360	/*
1361	 * If this RR differs in TTL from the update RR,
1362	 * its TTL must be adjusted.
1363	 */
1364	if (rr->ttl != ctx->update_rr_ttl) {
1365		CHECK(dns_difftuple_create(ctx->del_diff.mctx, DNS_DIFFOP_DEL,
1366					   ctx->name, rr->ttl, &rr->rdata,
1367					   &tuple));
1368		dns_diff_append(&ctx->del_diff, &tuple);
1369		if (!equal) {
1370			CHECK(dns_difftuple_create(ctx->add_diff.mctx,
1371						   DNS_DIFFOP_ADD, ctx->name,
1372						   ctx->update_rr_ttl,
1373						   &rr->rdata, &tuple));
1374			dns_diff_append(&ctx->add_diff, &tuple);
1375		}
1376	}
1377 failure:
1378	return (result);
1379}
1380
1381/**************************************************************************/
1382/*
1383 * Miscellaneous subroutines.
1384 */
1385
1386/*%
1387 * Extract a single update RR from 'section' of dynamic update message
1388 * 'msg', with consistency checking.
1389 *
1390 * Stores the owner name, rdata, and TTL of the update RR at 'name',
1391 * 'rdata', and 'ttl', respectively.
1392 */
1393static void
1394get_current_rr(dns_message_t *msg, dns_section_t section,
1395	       dns_rdataclass_t zoneclass, dns_name_t **name,
1396	       dns_rdata_t *rdata, dns_rdatatype_t *covers,
1397	       dns_ttl_t *ttl, dns_rdataclass_t *update_class)
1398{
1399	dns_rdataset_t *rdataset;
1400	isc_result_t result;
1401	dns_message_currentname(msg, section, name);
1402	rdataset = ISC_LIST_HEAD((*name)->list);
1403	INSIST(rdataset != NULL);
1404	INSIST(ISC_LIST_NEXT(rdataset, link) == NULL);
1405	*covers = rdataset->covers;
1406	*ttl = rdataset->ttl;
1407	result = dns_rdataset_first(rdataset);
1408	INSIST(result == ISC_R_SUCCESS);
1409	dns_rdataset_current(rdataset, rdata);
1410	INSIST(dns_rdataset_next(rdataset) == ISC_R_NOMORE);
1411	*update_class = rdata->rdclass;
1412	rdata->rdclass = zoneclass;
1413}
1414
1415/*%
1416 * Increment the SOA serial number of database 'db', version 'ver'.
1417 * Replace the SOA record in the database, and log the
1418 * change in 'diff'.
1419 */
1420
1421	/*
1422	 * XXXRTH  Failures in this routine will be worth logging, when
1423	 *         we have a logging system.  Failure to find the zonename
1424	 *	   or the SOA rdataset warrant at least an UNEXPECTED_ERROR().
1425	 */
1426
1427static isc_result_t
1428increment_soa_serial(dns_db_t *db, dns_dbversion_t *ver,
1429		     dns_diff_t *diff, isc_mem_t *mctx)
1430{
1431	dns_difftuple_t *deltuple = NULL;
1432	dns_difftuple_t *addtuple = NULL;
1433	isc_uint32_t serial;
1434	isc_result_t result;
1435
1436	CHECK(dns_db_createsoatuple(db, ver, mctx, DNS_DIFFOP_DEL, &deltuple));
1437	CHECK(dns_difftuple_copy(deltuple, &addtuple));
1438	addtuple->op = DNS_DIFFOP_ADD;
1439
1440	serial = dns_soa_getserial(&addtuple->rdata);
1441
1442	/* RFC1982 */
1443	serial = (serial + 1) & 0xFFFFFFFF;
1444	if (serial == 0)
1445		serial = 1;
1446
1447	dns_soa_setserial(serial, &addtuple->rdata);
1448	CHECK(do_one_tuple(&deltuple, db, ver, diff));
1449	CHECK(do_one_tuple(&addtuple, db, ver, diff));
1450	result = ISC_R_SUCCESS;
1451
1452 failure:
1453	if (addtuple != NULL)
1454		dns_difftuple_free(&addtuple);
1455	if (deltuple != NULL)
1456		dns_difftuple_free(&deltuple);
1457	return (result);
1458}
1459
1460/*%
1461 * Check that the new SOA record at 'update_rdata' does not
1462 * illegally cause the SOA serial number to decrease or stay
1463 * unchanged relative to the existing SOA in 'db'.
1464 *
1465 * Sets '*ok' to ISC_TRUE if the update is legal, ISC_FALSE if not.
1466 *
1467 * William King points out that RFC2136 is inconsistent about
1468 * the case where the serial number stays unchanged:
1469 *
1470 *   section 3.4.2.2 requires a server to ignore a SOA update request
1471 *   if the serial number on the update SOA is less_than_or_equal to
1472 *   the zone SOA serial.
1473 *
1474 *   section 3.6 requires a server to ignore a SOA update request if
1475 *   the serial is less_than the zone SOA serial.
1476 *
1477 * Paul says 3.4.2.2 is correct.
1478 *
1479 */
1480static isc_result_t
1481check_soa_increment(dns_db_t *db, dns_dbversion_t *ver,
1482		    dns_rdata_t *update_rdata, isc_boolean_t *ok)
1483{
1484	isc_uint32_t db_serial;
1485	isc_uint32_t update_serial;
1486	isc_result_t result;
1487
1488	update_serial = dns_soa_getserial(update_rdata);
1489
1490	result = dns_db_getsoaserial(db, ver, &db_serial);
1491	if (result != ISC_R_SUCCESS)
1492		return (result);
1493
1494	if (DNS_SERIAL_GE(db_serial, update_serial)) {
1495		*ok = ISC_FALSE;
1496	} else {
1497		*ok = ISC_TRUE;
1498	}
1499
1500	return (ISC_R_SUCCESS);
1501
1502}
1503
1504/**************************************************************************/
1505/*
1506 * Incremental updating of NSECs and RRSIGs.
1507 */
1508
1509#define MAXZONEKEYS 32	/*%< Maximum number of zone keys supported. */
1510
1511/*%
1512 * We abuse the dns_diff_t type to represent a set of domain names
1513 * affected by the update.
1514 */
1515static isc_result_t
1516namelist_append_name(dns_diff_t *list, dns_name_t *name) {
1517	isc_result_t result;
1518	dns_difftuple_t *tuple = NULL;
1519	static dns_rdata_t dummy_rdata = DNS_RDATA_INIT;
1520
1521	CHECK(dns_difftuple_create(list->mctx, DNS_DIFFOP_EXISTS, name, 0,
1522				   &dummy_rdata, &tuple));
1523	dns_diff_append(list, &tuple);
1524 failure:
1525	return (result);
1526}
1527
1528static isc_result_t
1529namelist_append_subdomain(dns_db_t *db, dns_name_t *name, dns_diff_t *affected)
1530{
1531	isc_result_t result;
1532	dns_fixedname_t fixedname;
1533	dns_name_t *child;
1534	dns_dbiterator_t *dbit = NULL;
1535
1536	dns_fixedname_init(&fixedname);
1537	child = dns_fixedname_name(&fixedname);
1538
1539	CHECK(dns_db_createiterator(db, DNS_DB_NONSEC3, &dbit));
1540
1541	for (result = dns_dbiterator_seek(dbit, name);
1542	     result == ISC_R_SUCCESS;
1543	     result = dns_dbiterator_next(dbit))
1544	{
1545		dns_dbnode_t *node = NULL;
1546		CHECK(dns_dbiterator_current(dbit, &node, child));
1547		dns_db_detachnode(db, &node);
1548		if (! dns_name_issubdomain(child, name))
1549			break;
1550		CHECK(namelist_append_name(affected, child));
1551	}
1552	if (result == ISC_R_NOMORE)
1553		result = ISC_R_SUCCESS;
1554 failure:
1555	if (dbit != NULL)
1556		dns_dbiterator_destroy(&dbit);
1557	return (result);
1558}
1559
1560
1561
1562/*%
1563 * Helper function for non_nsec_rrset_exists().
1564 */
1565static isc_result_t
1566is_non_nsec_action(void *data, dns_rdataset_t *rrset) {
1567	UNUSED(data);
1568	if (!(rrset->type == dns_rdatatype_nsec ||
1569	      rrset->type == dns_rdatatype_nsec3 ||
1570	      (rrset->type == dns_rdatatype_rrsig &&
1571	       (rrset->covers == dns_rdatatype_nsec ||
1572		rrset->covers == dns_rdatatype_nsec3))))
1573		return (ISC_R_EXISTS);
1574	return (ISC_R_SUCCESS);
1575}
1576
1577/*%
1578 * Check whether there is an rrset other than a NSEC or RRSIG NSEC,
1579 * i.e., anything that justifies the continued existence of a name
1580 * after a secure update.
1581 *
1582 * If such an rrset exists, set '*exists' to ISC_TRUE.
1583 * Otherwise, set it to ISC_FALSE.
1584 */
1585static isc_result_t
1586non_nsec_rrset_exists(dns_db_t *db, dns_dbversion_t *ver,
1587		     dns_name_t *name, isc_boolean_t *exists)
1588{
1589	isc_result_t result;
1590	result = foreach_rrset(db, ver, name, is_non_nsec_action, NULL);
1591	RETURN_EXISTENCE_FLAG;
1592}
1593
1594/*%
1595 * A comparison function for sorting dns_diff_t:s by name.
1596 */
1597static int
1598name_order(const void *av, const void *bv) {
1599	dns_difftuple_t const * const *ap = av;
1600	dns_difftuple_t const * const *bp = bv;
1601	dns_difftuple_t const *a = *ap;
1602	dns_difftuple_t const *b = *bp;
1603	return (dns_name_compare(&a->name, &b->name));
1604}
1605
1606static isc_result_t
1607uniqify_name_list(dns_diff_t *list) {
1608	isc_result_t result;
1609	dns_difftuple_t *p, *q;
1610
1611	CHECK(dns_diff_sort(list, name_order));
1612
1613	p = ISC_LIST_HEAD(list->tuples);
1614	while (p != NULL) {
1615		do {
1616			q = ISC_LIST_NEXT(p, link);
1617			if (q == NULL || ! dns_name_equal(&p->name, &q->name))
1618				break;
1619			ISC_LIST_UNLINK(list->tuples, q, link);
1620			dns_difftuple_free(&q);
1621		} while (1);
1622		p = ISC_LIST_NEXT(p, link);
1623	}
1624 failure:
1625	return (result);
1626}
1627
1628static isc_result_t
1629is_active(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
1630	  isc_boolean_t *flag, isc_boolean_t *cut, isc_boolean_t *unsecure)
1631{
1632	isc_result_t result;
1633	dns_fixedname_t foundname;
1634	dns_fixedname_init(&foundname);
1635	result = dns_db_find(db, name, ver, dns_rdatatype_any,
1636			     DNS_DBFIND_GLUEOK | DNS_DBFIND_NOWILD,
1637			     (isc_stdtime_t) 0, NULL,
1638			     dns_fixedname_name(&foundname),
1639			     NULL, NULL);
1640	if (result == ISC_R_SUCCESS || result == DNS_R_EMPTYNAME) {
1641		*flag = ISC_TRUE;
1642		*cut = ISC_FALSE;
1643		if (unsecure != NULL)
1644			*unsecure = ISC_FALSE;
1645		return (ISC_R_SUCCESS);
1646	} else if (result == DNS_R_ZONECUT) {
1647		*flag = ISC_TRUE;
1648		*cut = ISC_TRUE;
1649		if (unsecure != NULL) {
1650			/*
1651			 * We are at the zonecut.  Check to see if there
1652			 * is a DS RRset.
1653			 */
1654			if (dns_db_find(db, name, ver, dns_rdatatype_ds, 0,
1655					(isc_stdtime_t) 0, NULL,
1656					dns_fixedname_name(&foundname),
1657					NULL, NULL) == DNS_R_NXRRSET)
1658				*unsecure = ISC_TRUE;
1659			else
1660				*unsecure = ISC_FALSE;
1661		}
1662		return (ISC_R_SUCCESS);
1663	} else if (result == DNS_R_GLUE || result == DNS_R_DNAME ||
1664		   result == DNS_R_DELEGATION || result == DNS_R_NXDOMAIN) {
1665		*flag = ISC_FALSE;
1666		*cut = ISC_FALSE;
1667		if (unsecure != NULL)
1668			*unsecure = ISC_FALSE;
1669		return (ISC_R_SUCCESS);
1670	} else {
1671		/*
1672		 * Silence compiler.
1673		 */
1674		*flag = ISC_FALSE;
1675		*cut = ISC_FALSE;
1676		if (unsecure != NULL)
1677			*unsecure = ISC_FALSE;
1678		return (result);
1679	}
1680}
1681
1682/*%
1683 * Find the next/previous name that has a NSEC record.
1684 * In other words, skip empty database nodes and names that
1685 * have had their NSECs removed because they are obscured by
1686 * a zone cut.
1687 */
1688static isc_result_t
1689next_active(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
1690	    dns_dbversion_t *ver, dns_name_t *oldname, dns_name_t *newname,
1691	    isc_boolean_t forward)
1692{
1693	isc_result_t result;
1694	dns_dbiterator_t *dbit = NULL;
1695	isc_boolean_t has_nsec = ISC_FALSE;
1696	unsigned int wraps = 0;
1697	isc_boolean_t secure = dns_db_issecure(db);
1698
1699	CHECK(dns_db_createiterator(db, 0, &dbit));
1700
1701	CHECK(dns_dbiterator_seek(dbit, oldname));
1702	do {
1703		dns_dbnode_t *node = NULL;
1704
1705		if (forward)
1706			result = dns_dbiterator_next(dbit);
1707		else
1708			result = dns_dbiterator_prev(dbit);
1709		if (result == ISC_R_NOMORE) {
1710			/*
1711			 * Wrap around.
1712			 */
1713			if (forward)
1714				CHECK(dns_dbiterator_first(dbit));
1715			else
1716				CHECK(dns_dbiterator_last(dbit));
1717			wraps++;
1718			if (wraps == 2) {
1719				update_log(client, zone, ISC_LOG_ERROR,
1720					   "secure zone with no NSECs");
1721				result = DNS_R_BADZONE;
1722				goto failure;
1723			}
1724		}
1725		CHECK(dns_dbiterator_current(dbit, &node, newname));
1726		dns_db_detachnode(db, &node);
1727
1728		/*
1729		 * The iterator may hold the tree lock, and
1730		 * rrset_exists() calls dns_db_findnode() which
1731		 * may try to reacquire it.  To avoid deadlock
1732		 * we must pause the iterator first.
1733		 */
1734		CHECK(dns_dbiterator_pause(dbit));
1735		if (secure) {
1736			CHECK(rrset_exists(db, ver, newname,
1737					   dns_rdatatype_nsec, 0, &has_nsec));
1738		} else {
1739			dns_fixedname_t ffound;
1740			dns_name_t *found;
1741			dns_fixedname_init(&ffound);
1742			found = dns_fixedname_name(&ffound);
1743			result = dns_db_find(db, newname, ver,
1744					     dns_rdatatype_soa,
1745					     DNS_DBFIND_NOWILD, 0, NULL, found,
1746					     NULL, NULL);
1747			if (result == ISC_R_SUCCESS ||
1748			    result == DNS_R_EMPTYNAME ||
1749			    result == DNS_R_NXRRSET ||
1750			    result == DNS_R_CNAME ||
1751			    (result == DNS_R_DELEGATION &&
1752			     dns_name_equal(newname, found))) {
1753				has_nsec = ISC_TRUE;
1754				result = ISC_R_SUCCESS;
1755			} else if (result != DNS_R_NXDOMAIN)
1756				break;
1757		}
1758	} while (! has_nsec);
1759 failure:
1760	if (dbit != NULL)
1761		dns_dbiterator_destroy(&dbit);
1762
1763	return (result);
1764}
1765
1766/*%
1767 * Add a NSEC record for "name", recording the change in "diff".
1768 * The existing NSEC is removed.
1769 */
1770static isc_result_t
1771add_nsec(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
1772	 dns_dbversion_t *ver, dns_name_t *name, dns_ttl_t nsecttl,
1773	 dns_diff_t *diff)
1774{
1775	isc_result_t result;
1776	dns_dbnode_t *node = NULL;
1777	unsigned char buffer[DNS_NSEC_BUFFERSIZE];
1778	dns_rdata_t rdata = DNS_RDATA_INIT;
1779	dns_difftuple_t *tuple = NULL;
1780	dns_fixedname_t fixedname;
1781	dns_name_t *target;
1782
1783	dns_fixedname_init(&fixedname);
1784	target = dns_fixedname_name(&fixedname);
1785
1786	/*
1787	 * Find the successor name, aka NSEC target.
1788	 */
1789	CHECK(next_active(client, zone, db, ver, name, target, ISC_TRUE));
1790
1791	/*
1792	 * Create the NSEC RDATA.
1793	 */
1794	CHECK(dns_db_findnode(db, name, ISC_FALSE, &node));
1795	dns_rdata_init(&rdata);
1796	CHECK(dns_nsec_buildrdata(db, ver, node, target, buffer, &rdata));
1797	dns_db_detachnode(db, &node);
1798
1799	/*
1800	 * Delete the old NSEC and record the change.
1801	 */
1802	CHECK(delete_if(true_p, db, ver, name, dns_rdatatype_nsec, 0,
1803			NULL, diff));
1804	/*
1805	 * Add the new NSEC and record the change.
1806	 */
1807	CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD, name,
1808				   nsecttl, &rdata, &tuple));
1809	CHECK(do_one_tuple(&tuple, db, ver, diff));
1810	INSIST(tuple == NULL);
1811
1812 failure:
1813	if (node != NULL)
1814		dns_db_detachnode(db, &node);
1815	return (result);
1816}
1817
1818/*%
1819 * Add a placeholder NSEC record for "name", recording the change in "diff".
1820 */
1821static isc_result_t
1822add_placeholder_nsec(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
1823		     dns_diff_t *diff)
1824{
1825	isc_result_t result;
1826	dns_difftuple_t *tuple = NULL;
1827	isc_region_t r;
1828	unsigned char data[1] = { 0 }; /* The root domain, no bits. */
1829	dns_rdata_t rdata = DNS_RDATA_INIT;
1830
1831	r.base = data;
1832	r.length = sizeof(data);
1833	dns_rdata_fromregion(&rdata, dns_db_class(db), dns_rdatatype_nsec, &r);
1834	CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD, name, 0,
1835				   &rdata, &tuple));
1836	CHECK(do_one_tuple(&tuple, db, ver, diff));
1837 failure:
1838	return (result);
1839}
1840
1841static isc_result_t
1842find_zone_keys(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *ver,
1843	       isc_mem_t *mctx, unsigned int maxkeys,
1844	       dst_key_t **keys, unsigned int *nkeys)
1845{
1846	isc_result_t result;
1847	dns_dbnode_t *node = NULL;
1848	const char *directory = dns_zone_getkeydirectory(zone);
1849	CHECK(dns_db_findnode(db, dns_db_origin(db), ISC_FALSE, &node));
1850	CHECK(dns_dnssec_findzonekeys2(db, ver, node, dns_db_origin(db),
1851				       directory, mctx, maxkeys, keys, nkeys));
1852 failure:
1853	if (node != NULL)
1854		dns_db_detachnode(db, &node);
1855	return (result);
1856}
1857
1858/*%
1859 * Add RRSIG records for an RRset, recording the change in "diff".
1860 */
1861static isc_result_t
1862add_sigs(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
1863	 dns_dbversion_t *ver, dns_name_t *name, dns_rdatatype_t type,
1864	 dns_diff_t *diff, dst_key_t **keys, unsigned int nkeys,
1865	 isc_stdtime_t inception, isc_stdtime_t expire,
1866	 isc_boolean_t check_ksk, isc_boolean_t keyset_kskonly)
1867{
1868	isc_result_t result;
1869	dns_dbnode_t *node = NULL;
1870	dns_rdataset_t rdataset;
1871	dns_rdata_t sig_rdata = DNS_RDATA_INIT;
1872	isc_buffer_t buffer;
1873	unsigned char data[1024]; /* XXX */
1874	unsigned int i, j;
1875	isc_boolean_t added_sig = ISC_FALSE;
1876	isc_mem_t *mctx = client->mctx;
1877
1878	dns_rdataset_init(&rdataset);
1879	isc_buffer_init(&buffer, data, sizeof(data));
1880
1881	/* Get the rdataset to sign. */
1882	if (type == dns_rdatatype_nsec3)
1883		CHECK(dns_db_findnsec3node(db, name, ISC_FALSE, &node));
1884	else
1885		CHECK(dns_db_findnode(db, name, ISC_FALSE, &node));
1886	CHECK(dns_db_findrdataset(db, node, ver, type, 0,
1887				  (isc_stdtime_t) 0, &rdataset, NULL));
1888	dns_db_detachnode(db, &node);
1889
1890#define REVOKE(x) ((dst_key_flags(x) & DNS_KEYFLAG_REVOKE) != 0)
1891#define KSK(x) ((dst_key_flags(x) & DNS_KEYFLAG_KSK) != 0)
1892#define ALG(x) dst_key_alg(x)
1893
1894	/*
1895	 * If we are honoring KSK flags then we need to check that we
1896	 * have both KSK and non-KSK keys that are not revoked per
1897	 * algorithm.
1898	 */
1899	for (i = 0; i < nkeys; i++) {
1900		isc_boolean_t both = ISC_FALSE;
1901
1902		if (!dst_key_isprivate(keys[i]))
1903			continue;
1904
1905		if (check_ksk && !REVOKE(keys[i])) {
1906			isc_boolean_t have_ksk, have_nonksk;
1907			if (KSK(keys[i])) {
1908				have_ksk = ISC_TRUE;
1909				have_nonksk = ISC_FALSE;
1910			} else {
1911				have_ksk = ISC_FALSE;
1912				have_nonksk = ISC_TRUE;
1913			}
1914			for (j = 0; j < nkeys; j++) {
1915				if (j == i || ALG(keys[i]) != ALG(keys[j]))
1916					continue;
1917				if (REVOKE(keys[j]))
1918					continue;
1919				if (KSK(keys[j]))
1920					have_ksk = ISC_TRUE;
1921				else
1922					have_nonksk = ISC_TRUE;
1923				both = have_ksk && have_nonksk;
1924				if (both)
1925					break;
1926			}
1927		}
1928
1929		if (both) {
1930			if (type == dns_rdatatype_dnskey) {
1931				if (!KSK(keys[i]) && keyset_kskonly)
1932					continue;
1933			} else if (KSK(keys[i]))
1934				continue;
1935		} else if (REVOKE(keys[i]) && type != dns_rdatatype_dnskey)
1936			continue;
1937
1938		/* Calculate the signature, creating a RRSIG RDATA. */
1939		CHECK(dns_dnssec_sign(name, &rdataset, keys[i],
1940				      &inception, &expire,
1941				      mctx, &buffer, &sig_rdata));
1942
1943		/* Update the database and journal with the RRSIG. */
1944		/* XXX inefficient - will cause dataset merging */
1945		CHECK(update_one_rr(db, ver, diff, DNS_DIFFOP_ADDRESIGN, name,
1946				    rdataset.ttl, &sig_rdata));
1947		dns_rdata_reset(&sig_rdata);
1948		isc_buffer_init(&buffer, data, sizeof(data));
1949		added_sig = ISC_TRUE;
1950	}
1951	if (!added_sig) {
1952		update_log(client, zone, ISC_LOG_ERROR,
1953			   "found no active private keys, "
1954			   "unable to generate any signatures");
1955		result = ISC_R_NOTFOUND;
1956	}
1957
1958 failure:
1959	if (dns_rdataset_isassociated(&rdataset))
1960		dns_rdataset_disassociate(&rdataset);
1961	if (node != NULL)
1962		dns_db_detachnode(db, &node);
1963	return (result);
1964}
1965
1966/*
1967 * Delete expired RRsigs and any RRsigs we are about to re-sign.
1968 * See also zone.c:del_sigs().
1969 */
1970static isc_result_t
1971del_keysigs(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
1972	    dns_diff_t *diff, dst_key_t **keys, unsigned int nkeys)
1973{
1974	isc_result_t result;
1975	dns_dbnode_t *node = NULL;
1976	dns_rdataset_t rdataset;
1977	dns_rdata_t rdata = DNS_RDATA_INIT;
1978	unsigned int i;
1979	dns_rdata_rrsig_t rrsig;
1980	isc_boolean_t found;
1981
1982	dns_rdataset_init(&rdataset);
1983
1984	result = dns_db_findnode(db, name, ISC_FALSE, &node);
1985	if (result == ISC_R_NOTFOUND)
1986		return (ISC_R_SUCCESS);
1987	if (result != ISC_R_SUCCESS)
1988		goto failure;
1989	result = dns_db_findrdataset(db, node, ver, dns_rdatatype_rrsig,
1990				     dns_rdatatype_dnskey, (isc_stdtime_t) 0,
1991				     &rdataset, NULL);
1992	dns_db_detachnode(db, &node);
1993
1994	if (result == ISC_R_NOTFOUND)
1995		return (ISC_R_SUCCESS);
1996	if (result != ISC_R_SUCCESS)
1997		goto failure;
1998
1999	for (result = dns_rdataset_first(&rdataset);
2000	     result == ISC_R_SUCCESS;
2001	     result = dns_rdataset_next(&rdataset)) {
2002		dns_rdataset_current(&rdataset, &rdata);
2003		result = dns_rdata_tostruct(&rdata, &rrsig, NULL);
2004		RUNTIME_CHECK(result == ISC_R_SUCCESS);
2005		found = ISC_FALSE;
2006		for (i = 0; i < nkeys; i++) {
2007			if (rrsig.keyid == dst_key_id(keys[i])) {
2008				found = ISC_TRUE;
2009				if (!dst_key_isprivate(keys[i])) {
2010					/*
2011					 * The re-signing code in zone.c
2012					 * will mark this as offline.
2013					 * Just skip the record for now.
2014					 */
2015					break;
2016				}
2017				result = update_one_rr(db, ver, diff,
2018						       DNS_DIFFOP_DEL, name,
2019						       rdataset.ttl, &rdata);
2020				break;
2021			}
2022		}
2023		/*
2024		 * If there is not a matching DNSKEY then delete the RRSIG.
2025		 */
2026		if (!found)
2027			result = update_one_rr(db, ver, diff, DNS_DIFFOP_DEL,
2028					       name, rdataset.ttl, &rdata);
2029		dns_rdata_reset(&rdata);
2030		if (result != ISC_R_SUCCESS)
2031			break;
2032	}
2033	dns_rdataset_disassociate(&rdataset);
2034	if (result == ISC_R_NOMORE)
2035		result = ISC_R_SUCCESS;
2036failure:
2037	if (node != NULL)
2038		dns_db_detachnode(db, &node);
2039	return (result);
2040}
2041
2042static isc_result_t
2043add_exposed_sigs(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
2044		 dns_dbversion_t *ver, dns_name_t *name, isc_boolean_t cut,
2045		 dns_diff_t *diff, dst_key_t **keys, unsigned int nkeys,
2046		 isc_stdtime_t inception, isc_stdtime_t expire,
2047		 isc_boolean_t check_ksk, isc_boolean_t keyset_kskonly)
2048{
2049	isc_result_t result;
2050	dns_dbnode_t *node;
2051	dns_rdatasetiter_t *iter;
2052
2053	node = NULL;
2054	result = dns_db_findnode(db, name, ISC_FALSE, &node);
2055	if (result == ISC_R_NOTFOUND)
2056		return (ISC_R_SUCCESS);
2057	if (result != ISC_R_SUCCESS)
2058		return (result);
2059
2060	iter = NULL;
2061	result = dns_db_allrdatasets(db, node, ver,
2062				     (isc_stdtime_t) 0, &iter);
2063	if (result != ISC_R_SUCCESS)
2064		goto cleanup_node;
2065
2066	for (result = dns_rdatasetiter_first(iter);
2067	     result == ISC_R_SUCCESS;
2068	     result = dns_rdatasetiter_next(iter))
2069	{
2070		dns_rdataset_t rdataset;
2071		dns_rdatatype_t type;
2072		isc_boolean_t flag;
2073
2074		dns_rdataset_init(&rdataset);
2075		dns_rdatasetiter_current(iter, &rdataset);
2076		type = rdataset.type;
2077		dns_rdataset_disassociate(&rdataset);
2078
2079		/*
2080		 * We don't need to sign unsigned NSEC records at the cut
2081		 * as they are handled elsewhere.
2082		 */
2083		if ((type == dns_rdatatype_rrsig) ||
2084		    (cut && type != dns_rdatatype_ds))
2085			continue;
2086		result = rrset_exists(db, ver, name, dns_rdatatype_rrsig,
2087				      type, &flag);
2088		if (result != ISC_R_SUCCESS)
2089			goto cleanup_iterator;
2090		if (flag)
2091			continue;;
2092		result = add_sigs(client, zone, db, ver, name, type, diff,
2093					  keys, nkeys, inception, expire,
2094					  check_ksk, keyset_kskonly);
2095		if (result != ISC_R_SUCCESS)
2096			goto cleanup_iterator;
2097	}
2098	if (result == ISC_R_NOMORE)
2099		result = ISC_R_SUCCESS;
2100
2101 cleanup_iterator:
2102	dns_rdatasetiter_destroy(&iter);
2103
2104 cleanup_node:
2105	dns_db_detachnode(db, &node);
2106
2107	return (result);
2108}
2109
2110/*%
2111 * Update RRSIG, NSEC and NSEC3 records affected by an update.  The original
2112 * update, including the SOA serial update but excluding the RRSIG & NSEC
2113 * changes, is in "diff" and has already been applied to "newver" of "db".
2114 * The database version prior to the update is "oldver".
2115 *
2116 * The necessary RRSIG, NSEC and NSEC3 changes will be applied to "newver"
2117 * and added (as a minimal diff) to "diff".
2118 *
2119 * The RRSIGs generated will be valid for 'sigvalidityinterval' seconds.
2120 */
2121static isc_result_t
2122update_signatures(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
2123		  dns_dbversion_t *oldver, dns_dbversion_t *newver,
2124		  dns_diff_t *diff, isc_uint32_t sigvalidityinterval)
2125{
2126	isc_result_t result;
2127	dns_difftuple_t *t;
2128	dns_diff_t diffnames;
2129	dns_diff_t affected;
2130	dns_diff_t sig_diff;
2131	dns_diff_t nsec_diff;
2132	dns_diff_t nsec_mindiff;
2133	isc_boolean_t flag, build_nsec, build_nsec3;
2134	dst_key_t *zone_keys[MAXZONEKEYS];
2135	unsigned int nkeys = 0;
2136	unsigned int i;
2137	isc_stdtime_t now, inception, expire;
2138	dns_ttl_t nsecttl;
2139	dns_rdata_soa_t soa;
2140	dns_rdata_t rdata = DNS_RDATA_INIT;
2141	dns_rdataset_t rdataset;
2142	dns_dbnode_t *node = NULL;
2143	isc_boolean_t check_ksk, keyset_kskonly;
2144	isc_boolean_t unsecure;
2145	isc_boolean_t cut;
2146	dns_rdatatype_t privatetype = dns_zone_getprivatetype(zone);
2147
2148	dns_diff_init(client->mctx, &diffnames);
2149	dns_diff_init(client->mctx, &affected);
2150
2151	dns_diff_init(client->mctx, &sig_diff);
2152	sig_diff.resign = dns_zone_getsigresigninginterval(zone);
2153	dns_diff_init(client->mctx, &nsec_diff);
2154	dns_diff_init(client->mctx, &nsec_mindiff);
2155
2156	result = find_zone_keys(zone, db, newver, client->mctx,
2157				MAXZONEKEYS, zone_keys, &nkeys);
2158	if (result != ISC_R_SUCCESS) {
2159		update_log(client, zone, ISC_LOG_ERROR,
2160			   "could not get zone keys for secure dynamic update");
2161		goto failure;
2162	}
2163
2164	isc_stdtime_get(&now);
2165	inception = now - 3600; /* Allow for some clock skew. */
2166	expire = now + sigvalidityinterval;
2167
2168	/*
2169	 * Do we look at the KSK flag on the DNSKEY to determining which
2170	 * keys sign which RRsets?  First check the zone option then
2171	 * check the keys flags to make sure at least one has a ksk set
2172	 * and one doesn't.
2173	 */
2174	check_ksk = ISC_TF((dns_zone_getoptions(zone) &
2175			    DNS_ZONEOPT_UPDATECHECKKSK) != 0);
2176	keyset_kskonly = ISC_TF((dns_zone_getoptions(zone) &
2177				DNS_ZONEOPT_DNSKEYKSKONLY) != 0);
2178
2179	/*
2180	 * Get the NSEC/NSEC3 TTL from the SOA MINIMUM field.
2181	 */
2182	CHECK(dns_db_findnode(db, dns_db_origin(db), ISC_FALSE, &node));
2183	dns_rdataset_init(&rdataset);
2184	CHECK(dns_db_findrdataset(db, node, newver, dns_rdatatype_soa, 0,
2185				  (isc_stdtime_t) 0, &rdataset, NULL));
2186	CHECK(dns_rdataset_first(&rdataset));
2187	dns_rdataset_current(&rdataset, &rdata);
2188	CHECK(dns_rdata_tostruct(&rdata, &soa, NULL));
2189	nsecttl = soa.minimum;
2190	dns_rdataset_disassociate(&rdataset);
2191	dns_db_detachnode(db, &node);
2192
2193	/*
2194	 * Find all RRsets directly affected by the update, and
2195	 * update their RRSIGs.  Also build a list of names affected
2196	 * by the update in "diffnames".
2197	 */
2198	CHECK(dns_diff_sort(diff, temp_order));
2199
2200	t = ISC_LIST_HEAD(diff->tuples);
2201	while (t != NULL) {
2202		dns_name_t *name = &t->name;
2203		/* Now "name" is a new, unique name affected by the update. */
2204
2205		CHECK(namelist_append_name(&diffnames, name));
2206
2207		while (t != NULL && dns_name_equal(&t->name, name)) {
2208			dns_rdatatype_t type;
2209			type = t->rdata.type;
2210
2211			/*
2212			 * Now "name" and "type" denote a new unique RRset
2213			 * affected by the update.
2214			 */
2215
2216			/* Don't sign RRSIGs. */
2217			if (type == dns_rdatatype_rrsig)
2218				goto skip;
2219
2220			/*
2221			 * Delete all old RRSIGs covering this type, since they
2222			 * are all invalid when the signed RRset has changed.
2223			 * We may not be able to recreate all of them - tough.
2224			 * Special case changes to the zone's DNSKEY records
2225			 * to support offline KSKs.
2226			 */
2227			if (type == dns_rdatatype_dnskey)
2228				del_keysigs(db, newver, name, &sig_diff,
2229					    zone_keys, nkeys);
2230			else
2231				CHECK(delete_if(true_p, db, newver, name,
2232						dns_rdatatype_rrsig, type,
2233						NULL, &sig_diff));
2234
2235			/*
2236			 * If this RRset is still visible after the update,
2237			 * add a new signature for it.
2238			 */
2239			CHECK(rrset_visible(db, newver, name, type, &flag));
2240			if (flag) {
2241				CHECK(add_sigs(client, zone, db, newver, name,
2242					       type, &sig_diff, zone_keys,
2243					       nkeys, inception, expire,
2244					       check_ksk, keyset_kskonly));
2245			}
2246		skip:
2247			/* Skip any other updates to the same RRset. */
2248			while (t != NULL &&
2249			       dns_name_equal(&t->name, name) &&
2250			       t->rdata.type == type)
2251			{
2252				t = ISC_LIST_NEXT(t, link);
2253			}
2254		}
2255	}
2256	update_log(client, zone, ISC_LOG_DEBUG(3), "updated data signatures");
2257
2258	/* Remove orphaned NSECs and RRSIG NSECs. */
2259	for (t = ISC_LIST_HEAD(diffnames.tuples);
2260	     t != NULL;
2261	     t = ISC_LIST_NEXT(t, link))
2262	{
2263		CHECK(non_nsec_rrset_exists(db, newver, &t->name, &flag));
2264		if (! flag) {
2265			CHECK(delete_if(true_p, db, newver, &t->name,
2266					dns_rdatatype_any, 0,
2267					NULL, &sig_diff));
2268		}
2269	}
2270	update_log(client, zone, ISC_LOG_DEBUG(3),
2271		   "removed any orphaned NSEC records");
2272
2273	/*
2274	 * See if we need to build NSEC or NSEC3 chains.
2275	 */
2276	CHECK(dns_private_chains(db, newver, privatetype, &build_nsec,
2277				 &build_nsec3));
2278	if (!build_nsec)
2279		goto update_nsec3;
2280
2281	update_log(client, zone, ISC_LOG_DEBUG(3), "rebuilding NSEC chain");
2282
2283	/*
2284	 * When a name is created or deleted, its predecessor needs to
2285	 * have its NSEC updated.
2286	 */
2287	for (t = ISC_LIST_HEAD(diffnames.tuples);
2288	     t != NULL;
2289	     t = ISC_LIST_NEXT(t, link))
2290	{
2291		isc_boolean_t existed, exists;
2292		dns_fixedname_t fixedname;
2293		dns_name_t *prevname;
2294
2295		dns_fixedname_init(&fixedname);
2296		prevname = dns_fixedname_name(&fixedname);
2297
2298		CHECK(name_exists(db, oldver, &t->name, &existed));
2299		CHECK(name_exists(db, newver, &t->name, &exists));
2300		if (exists == existed)
2301			continue;
2302
2303		/*
2304		 * Find the predecessor.
2305		 * When names become obscured or unobscured in this update
2306		 * transaction, we may find the wrong predecessor because
2307		 * the NSECs have not yet been updated to reflect the delegation
2308		 * change.  This should not matter because in this case,
2309		 * the correct predecessor is either the delegation node or
2310		 * a newly unobscured node, and those nodes are on the
2311		 * "affected" list in any case.
2312		 */
2313		CHECK(next_active(client, zone, db, newver,
2314				  &t->name, prevname, ISC_FALSE));
2315		CHECK(namelist_append_name(&affected, prevname));
2316	}
2317
2318	/*
2319	 * Find names potentially affected by delegation changes
2320	 * (obscured by adding an NS or DNAME, or unobscured by
2321	 * removing one).
2322	 */
2323	for (t = ISC_LIST_HEAD(diffnames.tuples);
2324	     t != NULL;
2325	     t = ISC_LIST_NEXT(t, link))
2326	{
2327		isc_boolean_t ns_existed, dname_existed;
2328		isc_boolean_t ns_exists, dname_exists;
2329
2330		CHECK(rrset_exists(db, oldver, &t->name, dns_rdatatype_ns, 0,
2331				   &ns_existed));
2332		CHECK(rrset_exists(db, oldver, &t->name, dns_rdatatype_dname, 0,
2333				   &dname_existed));
2334		CHECK(rrset_exists(db, newver, &t->name, dns_rdatatype_ns, 0,
2335				   &ns_exists));
2336		CHECK(rrset_exists(db, newver, &t->name, dns_rdatatype_dname, 0,
2337				   &dname_exists));
2338		if ((ns_exists || dname_exists) == (ns_existed || dname_existed))
2339			continue;
2340		/*
2341		 * There was a delegation change.  Mark all subdomains
2342		 * of t->name as potentially needing a NSEC update.
2343		 */
2344		CHECK(namelist_append_subdomain(db, &t->name, &affected));
2345	}
2346
2347	ISC_LIST_APPENDLIST(affected.tuples, diffnames.tuples, link);
2348	INSIST(ISC_LIST_EMPTY(diffnames.tuples));
2349
2350	CHECK(uniqify_name_list(&affected));
2351
2352	/*
2353	 * Determine which names should have NSECs, and delete/create
2354	 * NSECs to make it so.  We don't know the final NSEC targets yet,
2355	 * so we just create placeholder NSECs with arbitrary contents
2356	 * to indicate that their respective owner names should be part of
2357	 * the NSEC chain.
2358	 */
2359	for (t = ISC_LIST_HEAD(affected.tuples);
2360	     t != NULL;
2361	     t = ISC_LIST_NEXT(t, link))
2362	{
2363		isc_boolean_t exists;
2364		dns_name_t *name = &t->name;
2365
2366		CHECK(name_exists(db, newver, name, &exists));
2367		if (! exists)
2368			continue;
2369		CHECK(is_active(db, newver, name, &flag, &cut, NULL));
2370		if (!flag) {
2371			/*
2372			 * This name is obscured.  Delete any
2373			 * existing NSEC record.
2374			 */
2375			CHECK(delete_if(true_p, db, newver, name,
2376					dns_rdatatype_nsec, 0,
2377					NULL, &nsec_diff));
2378			CHECK(delete_if(rrsig_p, db, newver, name,
2379					dns_rdatatype_any, 0, NULL, diff));
2380		} else {
2381			/*
2382			 * This name is not obscured.  It needs to have a
2383			 * NSEC unless it is the at the origin, in which
2384			 * case it should already exist if there is a complete
2385			 * NSEC chain and if there isn't a complete NSEC chain
2386			 * we don't want to add one as that would signal that
2387			 * there is a complete NSEC chain.
2388			 */
2389			if (!dns_name_equal(name, dns_db_origin(db))) {
2390				CHECK(rrset_exists(db, newver, name,
2391						   dns_rdatatype_nsec, 0,
2392						   &flag));
2393				if (!flag)
2394					CHECK(add_placeholder_nsec(db, newver,
2395								   name, diff));
2396			}
2397			CHECK(add_exposed_sigs(client, zone, db, newver, name,
2398					       cut, &sig_diff, zone_keys, nkeys,
2399					       inception, expire, check_ksk,
2400					       keyset_kskonly));
2401		}
2402	}
2403
2404	/*
2405	 * Now we know which names are part of the NSEC chain.
2406	 * Make them all point at their correct targets.
2407	 */
2408	for (t = ISC_LIST_HEAD(affected.tuples);
2409	     t != NULL;
2410	     t = ISC_LIST_NEXT(t, link))
2411	{
2412		CHECK(rrset_exists(db, newver, &t->name,
2413				   dns_rdatatype_nsec, 0, &flag));
2414		if (flag) {
2415			/*
2416			 * There is a NSEC, but we don't know if it is correct.
2417			 * Delete it and create a correct one to be sure.
2418			 * If the update was unnecessary, the diff minimization
2419			 * will take care of eliminating it from the journal,
2420			 * IXFRs, etc.
2421			 *
2422			 * The RRSIG bit should always be set in the NSECs
2423			 * we generate, because they will all get RRSIG NSECs.
2424			 * (XXX what if the zone keys are missing?).
2425			 * Because the RRSIG NSECs have not necessarily been
2426			 * created yet, the correctness of the bit mask relies
2427			 * on the assumption that NSECs are only created if
2428			 * there is other data, and if there is other data,
2429			 * there are other RRSIGs.
2430			 */
2431			CHECK(add_nsec(client, zone, db, newver, &t->name,
2432				       nsecttl, &nsec_diff));
2433		}
2434	}
2435
2436	/*
2437	 * Minimize the set of NSEC updates so that we don't
2438	 * have to regenerate the RRSIG NSECs for NSECs that were
2439	 * replaced with identical ones.
2440	 */
2441	while ((t = ISC_LIST_HEAD(nsec_diff.tuples)) != NULL) {
2442		ISC_LIST_UNLINK(nsec_diff.tuples, t, link);
2443		dns_diff_appendminimal(&nsec_mindiff, &t);
2444	}
2445
2446	update_log(client, zone, ISC_LOG_DEBUG(3),
2447		   "signing rebuilt NSEC chain");
2448
2449	/* Update RRSIG NSECs. */
2450	for (t = ISC_LIST_HEAD(nsec_mindiff.tuples);
2451	     t != NULL;
2452	     t = ISC_LIST_NEXT(t, link))
2453	{
2454		if (t->op == DNS_DIFFOP_DEL) {
2455			CHECK(delete_if(true_p, db, newver, &t->name,
2456					dns_rdatatype_rrsig, dns_rdatatype_nsec,
2457					NULL, &sig_diff));
2458		} else if (t->op == DNS_DIFFOP_ADD) {
2459			CHECK(add_sigs(client, zone, db, newver, &t->name,
2460				       dns_rdatatype_nsec, &sig_diff,
2461				       zone_keys, nkeys, inception, expire,
2462				       check_ksk, keyset_kskonly));
2463		} else {
2464			INSIST(0);
2465		}
2466	}
2467
2468 update_nsec3:
2469
2470	/* Record our changes for the journal. */
2471	while ((t = ISC_LIST_HEAD(sig_diff.tuples)) != NULL) {
2472		ISC_LIST_UNLINK(sig_diff.tuples, t, link);
2473		dns_diff_appendminimal(diff, &t);
2474	}
2475	while ((t = ISC_LIST_HEAD(nsec_mindiff.tuples)) != NULL) {
2476		ISC_LIST_UNLINK(nsec_mindiff.tuples, t, link);
2477		dns_diff_appendminimal(diff, &t);
2478	}
2479
2480	INSIST(ISC_LIST_EMPTY(sig_diff.tuples));
2481	INSIST(ISC_LIST_EMPTY(nsec_diff.tuples));
2482	INSIST(ISC_LIST_EMPTY(nsec_mindiff.tuples));
2483
2484	if (!build_nsec3) {
2485		update_log(client, zone, ISC_LOG_DEBUG(3),
2486			   "no NSEC3 chains to rebuild");
2487		goto failure;
2488	}
2489
2490	update_log(client, zone, ISC_LOG_DEBUG(3), "rebuilding NSEC3 chains");
2491
2492	dns_diff_clear(&diffnames);
2493	dns_diff_clear(&affected);
2494
2495	CHECK(dns_diff_sort(diff, temp_order));
2496
2497	/*
2498	 * Find names potentially affected by delegation changes
2499	 * (obscured by adding an NS or DNAME, or unobscured by
2500	 * removing one).
2501	 */
2502	t = ISC_LIST_HEAD(diff->tuples);
2503	while (t != NULL) {
2504		dns_name_t *name = &t->name;
2505
2506		isc_boolean_t ns_existed, dname_existed;
2507		isc_boolean_t ns_exists, dname_exists;
2508		isc_boolean_t exists, existed;
2509
2510		if (t->rdata.type == dns_rdatatype_nsec ||
2511		    t->rdata.type == dns_rdatatype_rrsig) {
2512			t = ISC_LIST_NEXT(t, link);
2513			continue;
2514		}
2515
2516		CHECK(namelist_append_name(&affected, name));
2517
2518		CHECK(rrset_exists(db, oldver, name, dns_rdatatype_ns, 0,
2519				   &ns_existed));
2520		CHECK(rrset_exists(db, oldver, name, dns_rdatatype_dname, 0,
2521				   &dname_existed));
2522		CHECK(rrset_exists(db, newver, name, dns_rdatatype_ns, 0,
2523				   &ns_exists));
2524		CHECK(rrset_exists(db, newver, name, dns_rdatatype_dname, 0,
2525				   &dname_exists));
2526
2527		exists = ns_exists || dname_exists;
2528		existed = ns_existed || dname_existed;
2529		if (exists == existed)
2530			goto nextname;
2531		/*
2532		 * There was a delegation change.  Mark all subdomains
2533		 * of t->name as potentially needing a NSEC3 update.
2534		 */
2535		CHECK(namelist_append_subdomain(db, name, &affected));
2536
2537	nextname:
2538		while (t != NULL && dns_name_equal(&t->name, name))
2539			t = ISC_LIST_NEXT(t, link);
2540	}
2541
2542	for (t = ISC_LIST_HEAD(affected.tuples);
2543	     t != NULL;
2544	     t = ISC_LIST_NEXT(t, link)) {
2545		dns_name_t *name = &t->name;
2546
2547		unsecure = ISC_FALSE;	/* Silence compiler warning. */
2548		CHECK(is_active(db, newver, name, &flag, &cut, &unsecure));
2549
2550		if (!flag) {
2551			CHECK(delete_if(rrsig_p, db, newver, name,
2552					dns_rdatatype_any, 0, NULL, diff));
2553			CHECK(dns_nsec3_delnsec3sx(db, newver, name,
2554						   privatetype, &nsec_diff));
2555		} else {
2556			CHECK(add_exposed_sigs(client, zone, db, newver, name,
2557					       cut, &sig_diff, zone_keys, nkeys,
2558					       inception, expire, check_ksk,
2559					       keyset_kskonly));
2560			CHECK(dns_nsec3_addnsec3sx(db, newver, name, nsecttl,
2561						   unsecure, privatetype,
2562						   &nsec_diff));
2563		}
2564	}
2565
2566	/*
2567	 * Minimize the set of NSEC3 updates so that we don't
2568	 * have to regenerate the RRSIG NSEC3s for NSEC3s that were
2569	 * replaced with identical ones.
2570	 */
2571	while ((t = ISC_LIST_HEAD(nsec_diff.tuples)) != NULL) {
2572		ISC_LIST_UNLINK(nsec_diff.tuples, t, link);
2573		dns_diff_appendminimal(&nsec_mindiff, &t);
2574	}
2575
2576	update_log(client, zone, ISC_LOG_DEBUG(3),
2577		   "signing rebuilt NSEC3 chain");
2578
2579	/* Update RRSIG NSEC3s. */
2580	for (t = ISC_LIST_HEAD(nsec_mindiff.tuples);
2581	     t != NULL;
2582	     t = ISC_LIST_NEXT(t, link))
2583	{
2584		if (t->op == DNS_DIFFOP_DEL) {
2585			CHECK(delete_if(true_p, db, newver, &t->name,
2586					dns_rdatatype_rrsig,
2587					dns_rdatatype_nsec3,
2588					NULL, &sig_diff));
2589		} else if (t->op == DNS_DIFFOP_ADD) {
2590			CHECK(add_sigs(client, zone, db, newver, &t->name,
2591				       dns_rdatatype_nsec3,
2592				       &sig_diff, zone_keys, nkeys,
2593				       inception, expire, check_ksk,
2594				       keyset_kskonly));
2595		} else {
2596			INSIST(0);
2597		}
2598	}
2599
2600	/* Record our changes for the journal. */
2601	while ((t = ISC_LIST_HEAD(sig_diff.tuples)) != NULL) {
2602		ISC_LIST_UNLINK(sig_diff.tuples, t, link);
2603		dns_diff_appendminimal(diff, &t);
2604	}
2605	while ((t = ISC_LIST_HEAD(nsec_mindiff.tuples)) != NULL) {
2606		ISC_LIST_UNLINK(nsec_mindiff.tuples, t, link);
2607		dns_diff_appendminimal(diff, &t);
2608	}
2609
2610	INSIST(ISC_LIST_EMPTY(sig_diff.tuples));
2611	INSIST(ISC_LIST_EMPTY(nsec_diff.tuples));
2612	INSIST(ISC_LIST_EMPTY(nsec_mindiff.tuples));
2613
2614 failure:
2615	dns_diff_clear(&sig_diff);
2616	dns_diff_clear(&nsec_diff);
2617	dns_diff_clear(&nsec_mindiff);
2618
2619	dns_diff_clear(&affected);
2620	dns_diff_clear(&diffnames);
2621
2622	for (i = 0; i < nkeys; i++)
2623		dst_key_free(&zone_keys[i]);
2624
2625	return (result);
2626}
2627
2628
2629/**************************************************************************/
2630/*%
2631 * The actual update code in all its glory.  We try to follow
2632 * the RFC2136 pseudocode as closely as possible.
2633 */
2634
2635static isc_result_t
2636send_update_event(ns_client_t *client, dns_zone_t *zone) {
2637	isc_result_t result = ISC_R_SUCCESS;
2638	update_event_t *event = NULL;
2639	isc_task_t *zonetask = NULL;
2640	ns_client_t *evclient;
2641
2642	event = (update_event_t *)
2643		isc_event_allocate(client->mctx, client, DNS_EVENT_UPDATE,
2644				   update_action, NULL, sizeof(*event));
2645	if (event == NULL)
2646		FAIL(ISC_R_NOMEMORY);
2647	event->zone = zone;
2648	event->result = ISC_R_SUCCESS;
2649
2650	evclient = NULL;
2651	ns_client_attach(client, &evclient);
2652	INSIST(client->nupdates == 0);
2653	client->nupdates++;
2654	event->ev_arg = evclient;
2655
2656	dns_zone_gettask(zone, &zonetask);
2657	isc_task_send(zonetask, ISC_EVENT_PTR(&event));
2658
2659 failure:
2660	if (event != NULL)
2661		isc_event_free(ISC_EVENT_PTR(&event));
2662	return (result);
2663}
2664
2665static void
2666respond(ns_client_t *client, isc_result_t result) {
2667	isc_result_t msg_result;
2668
2669	msg_result = dns_message_reply(client->message, ISC_TRUE);
2670	if (msg_result != ISC_R_SUCCESS)
2671		goto msg_failure;
2672	client->message->rcode = dns_result_torcode(result);
2673
2674	ns_client_send(client);
2675	return;
2676
2677 msg_failure:
2678	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_UPDATE, NS_LOGMODULE_UPDATE,
2679		      ISC_LOG_ERROR,
2680		      "could not create update response message: %s",
2681		      isc_result_totext(msg_result));
2682	ns_client_next(client, msg_result);
2683}
2684
2685void
2686ns_update_start(ns_client_t *client, isc_result_t sigresult) {
2687	dns_message_t *request = client->message;
2688	isc_result_t result;
2689	dns_name_t *zonename;
2690	dns_rdataset_t *zone_rdataset;
2691	dns_zone_t *zone = NULL;
2692
2693	/*
2694	 * Interpret the zone section.
2695	 */
2696	result = dns_message_firstname(request, DNS_SECTION_ZONE);
2697	if (result != ISC_R_SUCCESS)
2698		FAILC(DNS_R_FORMERR, "update zone section empty");
2699
2700	/*
2701	 * The zone section must contain exactly one "question", and
2702	 * it must be of type SOA.
2703	 */
2704	zonename = NULL;
2705	dns_message_currentname(request, DNS_SECTION_ZONE, &zonename);
2706	zone_rdataset = ISC_LIST_HEAD(zonename->list);
2707	if (zone_rdataset->type != dns_rdatatype_soa)
2708		FAILC(DNS_R_FORMERR,
2709		      "update zone section contains non-SOA");
2710	if (ISC_LIST_NEXT(zone_rdataset, link) != NULL)
2711		FAILC(DNS_R_FORMERR,
2712		      "update zone section contains multiple RRs");
2713
2714	/* The zone section must have exactly one name. */
2715	result = dns_message_nextname(request, DNS_SECTION_ZONE);
2716	if (result != ISC_R_NOMORE)
2717		FAILC(DNS_R_FORMERR,
2718		      "update zone section contains multiple RRs");
2719
2720	result = dns_zt_find(client->view->zonetable, zonename, 0, NULL,
2721			     &zone);
2722	if (result != ISC_R_SUCCESS)
2723		FAILC(DNS_R_NOTAUTH, "not authoritative for update zone");
2724
2725	switch(dns_zone_gettype(zone)) {
2726	case dns_zone_master:
2727	case dns_zone_dlz:
2728		/*
2729		 * We can now fail due to a bad signature as we now know
2730		 * that we are the master.
2731		 */
2732		if (sigresult != ISC_R_SUCCESS)
2733			FAIL(sigresult);
2734		CHECK(send_update_event(client, zone));
2735		break;
2736	case dns_zone_slave:
2737		CHECK(checkupdateacl(client, dns_zone_getforwardacl(zone),
2738				     "update forwarding", zonename, ISC_TRUE,
2739				     ISC_FALSE));
2740		CHECK(send_forward_event(client, zone));
2741		break;
2742	default:
2743		FAILC(DNS_R_NOTAUTH, "not authoritative for update zone");
2744	}
2745	return;
2746
2747 failure:
2748	if (result == DNS_R_REFUSED) {
2749		INSIST(dns_zone_gettype(zone) == dns_zone_slave);
2750		inc_stats(zone, dns_nsstatscounter_updaterej);
2751	}
2752	/*
2753	 * We failed without having sent an update event to the zone.
2754	 * We are still in the client task context, so we can
2755	 * simply give an error response without switching tasks.
2756	 */
2757	respond(client, result);
2758	if (zone != NULL)
2759		dns_zone_detach(&zone);
2760}
2761
2762/*%
2763 * DS records are not allowed to exist without corresponding NS records,
2764 * RFC 3658, 2.2 Protocol Change,
2765 * "DS RRsets MUST NOT appear at non-delegation points or at a zone's apex".
2766 */
2767
2768static isc_result_t
2769remove_orphaned_ds(dns_db_t *db, dns_dbversion_t *newver, dns_diff_t *diff) {
2770	isc_result_t result;
2771	isc_boolean_t ns_exists;
2772	dns_difftuple_t *tupple;
2773	dns_diff_t temp_diff;
2774
2775	dns_diff_init(diff->mctx, &temp_diff);
2776
2777	for (tupple = ISC_LIST_HEAD(diff->tuples);
2778	     tupple != NULL;
2779	     tupple = ISC_LIST_NEXT(tupple, link)) {
2780		if (!((tupple->op == DNS_DIFFOP_DEL &&
2781		       tupple->rdata.type == dns_rdatatype_ns) ||
2782		      (tupple->op == DNS_DIFFOP_ADD &&
2783		       tupple->rdata.type == dns_rdatatype_ds)))
2784			continue;
2785		CHECK(rrset_exists(db, newver, &tupple->name,
2786				   dns_rdatatype_ns, 0, &ns_exists));
2787		if (ns_exists &&
2788		    !dns_name_equal(&tupple->name, dns_db_origin(db)))
2789			continue;
2790		CHECK(delete_if(true_p, db, newver, &tupple->name,
2791				dns_rdatatype_ds, 0, NULL, &temp_diff));
2792	}
2793	result = ISC_R_SUCCESS;
2794
2795 failure:
2796	for (tupple = ISC_LIST_HEAD(temp_diff.tuples);
2797	     tupple != NULL;
2798	     tupple = ISC_LIST_HEAD(temp_diff.tuples)) {
2799		ISC_LIST_UNLINK(temp_diff.tuples, tupple, link);
2800		dns_diff_appendminimal(diff, &tupple);
2801	}
2802	return (result);
2803}
2804
2805/*
2806 * This implements the post load integrity checks for mx records.
2807 */
2808static isc_result_t
2809check_mx(ns_client_t *client, dns_zone_t *zone,
2810	 dns_db_t *db, dns_dbversion_t *newver, dns_diff_t *diff)
2811{
2812	char tmp[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:123.123.123.123.")];
2813	char ownerbuf[DNS_NAME_FORMATSIZE];
2814	char namebuf[DNS_NAME_FORMATSIZE];
2815	char altbuf[DNS_NAME_FORMATSIZE];
2816	dns_difftuple_t *t;
2817	dns_fixedname_t fixed;
2818	dns_name_t *foundname;
2819	dns_rdata_mx_t mx;
2820	dns_rdata_t rdata;
2821	isc_boolean_t ok = ISC_TRUE;
2822	isc_boolean_t isaddress;
2823	isc_result_t result;
2824	struct in6_addr addr6;
2825	struct in_addr addr;
2826	unsigned int options;
2827
2828	dns_fixedname_init(&fixed);
2829	foundname = dns_fixedname_name(&fixed);
2830	dns_rdata_init(&rdata);
2831	options = dns_zone_getoptions(zone);
2832
2833	for (t = ISC_LIST_HEAD(diff->tuples);
2834	     t != NULL;
2835	     t = ISC_LIST_NEXT(t, link)) {
2836		if (t->op != DNS_DIFFOP_ADD ||
2837		    t->rdata.type != dns_rdatatype_mx)
2838			continue;
2839
2840		result = dns_rdata_tostruct(&t->rdata, &mx, NULL);
2841		RUNTIME_CHECK(result == ISC_R_SUCCESS);
2842		/*
2843		 * Check if we will error out if we attempt to reload the
2844		 * zone.
2845		 */
2846		dns_name_format(&mx.mx, namebuf, sizeof(namebuf));
2847		dns_name_format(&t->name, ownerbuf, sizeof(ownerbuf));
2848		isaddress = ISC_FALSE;
2849		if ((options & DNS_RDATA_CHECKMX) != 0 &&
2850		    strlcpy(tmp, namebuf, sizeof(tmp)) < sizeof(tmp)) {
2851			if (tmp[strlen(tmp) - 1] == '.')
2852				tmp[strlen(tmp) - 1] = '\0';
2853			if (inet_aton(tmp, &addr) == 1 ||
2854			    inet_pton(AF_INET6, tmp, &addr6) == 1)
2855				isaddress = ISC_TRUE;
2856		}
2857
2858		if (isaddress && (options & DNS_RDATA_CHECKMXFAIL) != 0) {
2859			update_log(client, zone, ISC_LOG_ERROR,
2860				   "%s/MX: '%s': %s",
2861				   ownerbuf, namebuf,
2862				   dns_result_totext(DNS_R_MXISADDRESS));
2863			ok = ISC_FALSE;
2864		} else if (isaddress) {
2865			update_log(client, zone, ISC_LOG_WARNING,
2866				   "%s/MX: warning: '%s': %s",
2867				   ownerbuf, namebuf,
2868				   dns_result_totext(DNS_R_MXISADDRESS));
2869		}
2870
2871		/*
2872		 * Check zone integrity checks.
2873		 */
2874		if ((options & DNS_ZONEOPT_CHECKINTEGRITY) == 0)
2875			continue;
2876		result = dns_db_find(db, &mx.mx, newver, dns_rdatatype_a,
2877				     0, 0, NULL, foundname, NULL, NULL);
2878		if (result == ISC_R_SUCCESS)
2879			continue;
2880
2881		if (result == DNS_R_NXRRSET) {
2882			result = dns_db_find(db, &mx.mx, newver,
2883					     dns_rdatatype_aaaa,
2884					     0, 0, NULL, foundname,
2885					     NULL, NULL);
2886			if (result == ISC_R_SUCCESS)
2887				continue;
2888		}
2889
2890		if (result == DNS_R_NXRRSET || result == DNS_R_NXDOMAIN) {
2891			update_log(client, zone, ISC_LOG_ERROR,
2892				   "%s/MX '%s' has no address records "
2893				   "(A or AAAA)", ownerbuf, namebuf);
2894			ok = ISC_FALSE;
2895		} else if (result == DNS_R_CNAME) {
2896			update_log(client, zone, ISC_LOG_ERROR,
2897				   "%s/MX '%s' is a CNAME (illegal)",
2898				   ownerbuf, namebuf);
2899			ok = ISC_FALSE;
2900		} else if (result == DNS_R_DNAME) {
2901			dns_name_format(foundname, altbuf, sizeof altbuf);
2902			update_log(client, zone, ISC_LOG_ERROR,
2903				   "%s/MX '%s' is below a DNAME '%s' (illegal)",
2904				   ownerbuf, namebuf, altbuf);
2905			ok = ISC_FALSE;
2906		}
2907	}
2908	return (ok ? ISC_R_SUCCESS : DNS_R_REFUSED);
2909}
2910
2911static isc_result_t
2912rr_exists(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
2913	  const dns_rdata_t *rdata, isc_boolean_t *flag)
2914{
2915	dns_rdataset_t rdataset;
2916	dns_dbnode_t *node = NULL;
2917	isc_result_t result;
2918
2919	dns_rdataset_init(&rdataset);
2920	if (rdata->type == dns_rdatatype_nsec3)
2921		CHECK(dns_db_findnsec3node(db, name, ISC_FALSE, &node));
2922	else
2923		CHECK(dns_db_findnode(db, name, ISC_FALSE, &node));
2924	result = dns_db_findrdataset(db, node, ver, rdata->type, 0,
2925				     (isc_stdtime_t) 0, &rdataset, NULL);
2926	if (result == ISC_R_NOTFOUND) {
2927		*flag = ISC_FALSE;
2928		result = ISC_R_SUCCESS;
2929		goto failure;
2930	}
2931
2932	for (result = dns_rdataset_first(&rdataset);
2933	     result == ISC_R_SUCCESS;
2934	     result = dns_rdataset_next(&rdataset)) {
2935		dns_rdata_t myrdata = DNS_RDATA_INIT;
2936		dns_rdataset_current(&rdataset, &myrdata);
2937		if (!dns_rdata_casecompare(&myrdata, rdata))
2938			break;
2939	}
2940	dns_rdataset_disassociate(&rdataset);
2941	if (result == ISC_R_SUCCESS) {
2942		*flag = ISC_TRUE;
2943	} else if (result == ISC_R_NOMORE) {
2944		*flag = ISC_FALSE;
2945		result = ISC_R_SUCCESS;
2946	}
2947
2948 failure:
2949	if (node != NULL)
2950		dns_db_detachnode(db, &node);
2951	return (result);
2952}
2953
2954static isc_result_t
2955get_iterations(dns_db_t *db, dns_dbversion_t *ver, dns_rdatatype_t privatetype,
2956	       unsigned int *iterationsp)
2957{
2958	dns_dbnode_t *node = NULL;
2959	dns_rdata_nsec3param_t nsec3param;
2960	dns_rdataset_t rdataset;
2961	isc_result_t result;
2962	unsigned int iterations = 0;
2963
2964	dns_rdataset_init(&rdataset);
2965
2966	result = dns_db_getoriginnode(db, &node);
2967	if (result != ISC_R_SUCCESS)
2968		return (result);
2969	result = dns_db_findrdataset(db, node, ver, dns_rdatatype_nsec3param,
2970				     0, (isc_stdtime_t) 0, &rdataset, NULL);
2971	if (result == ISC_R_NOTFOUND)
2972		goto try_private;
2973	if (result != ISC_R_SUCCESS)
2974		goto failure;
2975
2976	for (result = dns_rdataset_first(&rdataset);
2977	     result == ISC_R_SUCCESS;
2978	     result = dns_rdataset_next(&rdataset)) {
2979		dns_rdata_t rdata = DNS_RDATA_INIT;
2980		dns_rdataset_current(&rdataset, &rdata);
2981		CHECK(dns_rdata_tostruct(&rdata, &nsec3param, NULL));
2982		if ((nsec3param.flags & DNS_NSEC3FLAG_REMOVE) != 0)
2983			continue;
2984		if (nsec3param.iterations > iterations)
2985			iterations = nsec3param.iterations;
2986	}
2987	if (result != ISC_R_NOMORE)
2988		goto failure;
2989
2990	dns_rdataset_disassociate(&rdataset);
2991
2992 try_private:
2993	if (privatetype == 0)
2994		goto success;
2995
2996	result = dns_db_findrdataset(db, node, ver, privatetype,
2997				     0, (isc_stdtime_t) 0, &rdataset, NULL);
2998	if (result == ISC_R_NOTFOUND)
2999		goto success;
3000	if (result != ISC_R_SUCCESS)
3001		goto failure;
3002
3003	for (result = dns_rdataset_first(&rdataset);
3004	     result == ISC_R_SUCCESS;
3005	     result = dns_rdataset_next(&rdataset)) {
3006		unsigned char buf[DNS_NSEC3PARAM_BUFFERSIZE];
3007		dns_rdata_t private = DNS_RDATA_INIT;
3008		dns_rdata_t rdata = DNS_RDATA_INIT;
3009
3010		dns_rdataset_current(&rdataset, &rdata);
3011		if (!dns_nsec3param_fromprivate(&private, &rdata,
3012						buf, sizeof(buf)))
3013			continue;
3014		CHECK(dns_rdata_tostruct(&rdata, &nsec3param, NULL));
3015		if ((nsec3param.flags & DNS_NSEC3FLAG_REMOVE) != 0)
3016			continue;
3017		if (nsec3param.iterations > iterations)
3018			iterations = nsec3param.iterations;
3019	}
3020	if (result != ISC_R_NOMORE)
3021		goto failure;
3022
3023 success:
3024	*iterationsp = iterations;
3025	result = ISC_R_SUCCESS;
3026
3027 failure:
3028	if (node != NULL)
3029		dns_db_detachnode(db, &node);
3030	if (dns_rdataset_isassociated(&rdataset))
3031		dns_rdataset_disassociate(&rdataset);
3032	return (result);
3033}
3034
3035/*
3036 * Prevent the zone entering a inconsistent state where
3037 * NSEC only DNSKEYs are present with NSEC3 chains.
3038 */
3039static isc_result_t
3040check_dnssec(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
3041	     dns_dbversion_t *ver, dns_diff_t *diff)
3042{
3043	dns_difftuple_t *tuple;
3044	isc_boolean_t nseconly = ISC_FALSE, nsec3 = ISC_FALSE;
3045	isc_result_t result;
3046	unsigned int iterations = 0, max;
3047	dns_rdatatype_t privatetype = dns_zone_getprivatetype(zone);
3048
3049	/* Scan the tuples for an NSEC-only DNSKEY or an NSEC3PARAM */
3050	for (tuple = ISC_LIST_HEAD(diff->tuples);
3051	     tuple != NULL;
3052	     tuple = ISC_LIST_NEXT(tuple, link)) {
3053		if (tuple->op != DNS_DIFFOP_ADD)
3054			continue;
3055
3056		if (tuple->rdata.type == dns_rdatatype_dnskey) {
3057			isc_uint8_t alg;
3058			alg = tuple->rdata.data[3];
3059			if (alg == DST_ALG_RSAMD5 || alg == DST_ALG_RSASHA1 ||
3060			    alg == DST_ALG_DSA || alg == DST_ALG_ECC) {
3061				nseconly = ISC_TRUE;
3062				break;
3063			}
3064		} else if (tuple->rdata.type == dns_rdatatype_nsec3param) {
3065			nsec3 = ISC_TRUE;
3066			break;
3067		}
3068	}
3069
3070	/* Check existing DB for NSEC-only DNSKEY */
3071	if (!nseconly)
3072		CHECK(dns_nsec_nseconly(db, ver, &nseconly));
3073
3074	/* Check existing DB for NSEC3 */
3075	if (!nsec3)
3076		CHECK(dns_nsec3_activex(db, ver, ISC_FALSE,
3077					privatetype, &nsec3));
3078
3079	/* Refuse to allow NSEC3 with NSEC-only keys */
3080	if (nseconly && nsec3) {
3081		update_log(client, zone, ISC_LOG_ERROR,
3082			   "NSEC only DNSKEYs and NSEC3 chains not allowed");
3083		result = DNS_R_REFUSED;
3084		goto failure;
3085	}
3086
3087	/* Verify NSEC3 params */
3088	CHECK(get_iterations(db, ver, privatetype, &iterations));
3089	CHECK(dns_nsec3_maxiterations(db, ver, client->mctx, &max));
3090	if (max != 0 && iterations > max) {
3091		update_log(client, zone, ISC_LOG_ERROR,
3092			   "too many NSEC3 iterations (%u) for "
3093			   "weakest DNSKEY (%u)", iterations, max);
3094		result = DNS_R_REFUSED;
3095		goto failure;
3096	}
3097
3098 failure:
3099	return (result);
3100}
3101
3102/*
3103 * Delay NSEC3PARAM changes as they need to be applied to the whole zone.
3104 */
3105static isc_result_t
3106add_nsec3param_records(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
3107		       dns_dbversion_t *ver, dns_diff_t *diff)
3108{
3109	isc_result_t result = ISC_R_SUCCESS;
3110	dns_difftuple_t *tuple, *newtuple = NULL, *next;
3111	dns_rdata_t rdata = DNS_RDATA_INIT;
3112	unsigned char buf[DNS_NSEC3PARAM_BUFFERSIZE + 1];
3113	dns_diff_t temp_diff;
3114	dns_diffop_t op;
3115	isc_boolean_t flag;
3116	dns_name_t *name = dns_zone_getorigin(zone);
3117	dns_rdatatype_t privatetype = dns_zone_getprivatetype(zone);
3118	isc_uint32_t ttl = 0;
3119	isc_boolean_t ttl_good = ISC_FALSE;
3120
3121	update_log(client, zone, ISC_LOG_DEBUG(3),
3122		    "checking for NSEC3PARAM changes");
3123
3124	dns_diff_init(diff->mctx, &temp_diff);
3125
3126	/*
3127	 * Extract NSEC3PARAM tuples from list.
3128	 */
3129	for (tuple = ISC_LIST_HEAD(diff->tuples);
3130	     tuple != NULL;
3131	     tuple = next) {
3132
3133		next = ISC_LIST_NEXT(tuple, link);
3134
3135		if (tuple->rdata.type != dns_rdatatype_nsec3param ||
3136		    !dns_name_equal(name, &tuple->name))
3137			continue;
3138		ISC_LIST_UNLINK(diff->tuples, tuple, link);
3139		ISC_LIST_APPEND(temp_diff.tuples, tuple, link);
3140	}
3141
3142	/*
3143	 * Extract TTL changes pairs, we don't need to convert these to
3144	 * delayed changes.
3145	 */
3146	for (tuple = ISC_LIST_HEAD(temp_diff.tuples);
3147	     tuple != NULL; tuple = next) {
3148		if (tuple->op == DNS_DIFFOP_ADD) {
3149			if (!ttl_good) {
3150				/*
3151				 * Any adds here will contain the final
3152				 * NSEC3PARAM RRset TTL.
3153				 */
3154				ttl = tuple->ttl;
3155				ttl_good = ISC_TRUE;
3156			}
3157			/*
3158			 * Walk the temp_diff list looking for the
3159			 * corresponding delete.
3160			 */
3161			next = ISC_LIST_HEAD(temp_diff.tuples);
3162			while (next != NULL) {
3163				unsigned char *next_data = next->rdata.data;
3164				unsigned char *tuple_data = tuple->rdata.data;
3165				if (next->op == DNS_DIFFOP_DEL &&
3166				    next->rdata.length == tuple->rdata.length &&
3167				    !memcmp(next_data, tuple_data,
3168					    next->rdata.length)) {
3169					ISC_LIST_UNLINK(temp_diff.tuples, next,
3170							link);
3171					ISC_LIST_APPEND(diff->tuples, next,
3172							link);
3173					break;
3174				}
3175				next = ISC_LIST_NEXT(next, link);
3176			}
3177			/*
3178			 * If we have not found a pair move onto the next
3179			 * tuple.
3180			 */
3181			if (next == NULL) {
3182				next = ISC_LIST_NEXT(tuple, link);
3183				continue;
3184			}
3185			/*
3186			 * Find the next tuple to be processed before
3187			 * unlinking then complete moving the pair to 'diff'.
3188			 */
3189			next = ISC_LIST_NEXT(tuple, link);
3190			ISC_LIST_UNLINK(temp_diff.tuples, tuple, link);
3191			ISC_LIST_APPEND(diff->tuples, tuple, link);
3192		} else
3193			next = ISC_LIST_NEXT(tuple, link);
3194	}
3195
3196	/*
3197	 * Preserve any ongoing changes from a BIND 9.6.x upgrade.
3198	 *
3199	 * Any NSEC3PARAM records with flags other than OPTOUT named
3200	 * in managing and should not be touched so revert such changes
3201	 * taking into account any TTL change of the NSEC3PARAM RRset.
3202	 */
3203	for (tuple = ISC_LIST_HEAD(temp_diff.tuples);
3204	     tuple != NULL; tuple = next) {
3205		next = ISC_LIST_NEXT(tuple, link);
3206		if ((tuple->rdata.data[1] & ~DNS_NSEC3FLAG_OPTOUT) != 0) {
3207			/*
3208			 * If we havn't had any adds then the tuple->ttl must
3209			 * be the original ttl and should be used for any
3210			 * future changes.
3211			 */
3212			if (!ttl_good) {
3213				ttl = tuple->ttl;
3214				ttl_good = ISC_TRUE;
3215			}
3216			op = (tuple->op == DNS_DIFFOP_DEL) ?
3217			     DNS_DIFFOP_ADD : DNS_DIFFOP_DEL;
3218			CHECK(dns_difftuple_create(diff->mctx, op, name,
3219						   ttl, &tuple->rdata,
3220						   &newtuple));
3221			CHECK(do_one_tuple(&newtuple, db, ver, diff));
3222			ISC_LIST_UNLINK(temp_diff.tuples, tuple, link);
3223			dns_diff_appendminimal(diff, &tuple);
3224		}
3225	}
3226
3227	/*
3228	 * We now have just the actual changes to the NSEC3PARAM RRset.
3229	 * Convert the adds to delayed adds and the deletions into delayed
3230	 * deletions.
3231	 */
3232	for (tuple = ISC_LIST_HEAD(temp_diff.tuples);
3233	     tuple != NULL; tuple = next) {
3234		/*
3235		 * If we havn't had any adds then the tuple->ttl must be the
3236		 * original ttl and should be used for any future changes.
3237		 */
3238		if (!ttl_good) {
3239			ttl = tuple->ttl;
3240			ttl_good = ISC_TRUE;
3241		}
3242		if (tuple->op == DNS_DIFFOP_ADD) {
3243			/*
3244			 * Look for any deletes which match this ADD ignoring
3245			 * OPTOUT.  We don't need to explictly remove them as
3246			 * they will be removed a side effect of processing
3247			 * the add.
3248			 */
3249			next = ISC_LIST_HEAD(temp_diff.tuples);
3250			while (next != NULL) {
3251				unsigned char *next_data = next->rdata.data;
3252				unsigned char *tuple_data = tuple->rdata.data;
3253				if (next->op != DNS_DIFFOP_DEL ||
3254				    next->rdata.length != tuple->rdata.length ||
3255				    next_data[0] != tuple_data[0] ||
3256				    next_data[2] != tuple_data[2] ||
3257				    next_data[3] != tuple_data[3] ||
3258				    memcmp(next_data + 4, tuple_data + 4,
3259					   tuple->rdata.length - 4)) {
3260					next = ISC_LIST_NEXT(next, link);
3261					continue;
3262				}
3263				ISC_LIST_UNLINK(temp_diff.tuples, next, link);
3264				ISC_LIST_APPEND(diff->tuples, next, link);
3265				next = ISC_LIST_HEAD(temp_diff.tuples);
3266			}
3267			/*
3268			 * See if we already have a CREATE request in progress.
3269			 */
3270			dns_nsec3param_toprivate(&tuple->rdata, &rdata,
3271						 privatetype, buf, sizeof(buf));
3272			buf[2] |= DNS_NSEC3FLAG_CREATE;
3273			CHECK(rr_exists(db, ver, name, &rdata, &flag));
3274
3275			if (!flag) {
3276				CHECK(dns_difftuple_create(diff->mctx,
3277							   DNS_DIFFOP_ADD,
3278							   name, 0, &rdata,
3279							   &newtuple));
3280				CHECK(do_one_tuple(&newtuple, db, ver, diff));
3281			}
3282
3283			/*
3284			 * Remove any existing CREATE request to add an
3285			 * otherwise indentical chain with a reversed
3286			 * OPTOUT state.
3287			 */
3288			buf[2] ^= DNS_NSEC3FLAG_OPTOUT;
3289			CHECK(rr_exists(db, ver, name, &rdata, &flag));
3290
3291			if (flag) {
3292				CHECK(dns_difftuple_create(diff->mctx,
3293							   DNS_DIFFOP_DEL,
3294							   name, 0, &rdata,
3295							   &newtuple));
3296				CHECK(do_one_tuple(&newtuple, db, ver, diff));
3297			}
3298
3299			/*
3300			 * Find the next tuple to be processed and remove the
3301			 * temporary add record.
3302			 */
3303			next = ISC_LIST_NEXT(tuple, link);
3304			CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_DEL,
3305						   name, ttl, &tuple->rdata,
3306						   &newtuple));
3307			CHECK(do_one_tuple(&newtuple, db, ver, diff));
3308			ISC_LIST_UNLINK(temp_diff.tuples, tuple, link);
3309			dns_diff_appendminimal(diff, &tuple);
3310			dns_rdata_reset(&rdata);
3311		} else
3312			next = ISC_LIST_NEXT(tuple, link);
3313	}
3314
3315	for (tuple = ISC_LIST_HEAD(temp_diff.tuples);
3316	     tuple != NULL; tuple = next) {
3317
3318		INSIST(ttl_good);
3319
3320		next = ISC_LIST_NEXT(tuple, link);
3321		/*
3322		 * See if we already have a REMOVE request in progress.
3323		 */
3324		dns_nsec3param_toprivate(&tuple->rdata, &rdata, privatetype,
3325					 buf, sizeof(buf));
3326
3327		buf[2] |= DNS_NSEC3FLAG_REMOVE | DNS_NSEC3FLAG_NONSEC;
3328
3329		CHECK(rr_exists(db, ver, name, &rdata, &flag));
3330		if (!flag) {
3331			buf[2] &= ~DNS_NSEC3FLAG_NONSEC;
3332			CHECK(rr_exists(db, ver, name, &rdata, &flag));
3333		}
3334
3335		if (!flag) {
3336			CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD,
3337						   name, 0, &rdata, &newtuple));
3338			CHECK(do_one_tuple(&newtuple, db, ver, diff));
3339		}
3340		CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD, name,
3341					   ttl, &tuple->rdata, &newtuple));
3342		CHECK(do_one_tuple(&newtuple, db, ver, diff));
3343		ISC_LIST_UNLINK(temp_diff.tuples, tuple, link);
3344		dns_diff_appendminimal(diff, &tuple);
3345		dns_rdata_reset(&rdata);
3346	}
3347
3348	result = ISC_R_SUCCESS;
3349 failure:
3350	dns_diff_clear(&temp_diff);
3351	return (result);
3352}
3353
3354static isc_result_t
3355rollback_private(dns_db_t *db, dns_rdatatype_t privatetype,
3356		 dns_dbversion_t *ver, dns_diff_t *diff)
3357{
3358	dns_diff_t temp_diff;
3359	dns_diffop_t op;
3360	dns_difftuple_t *tuple, *newtuple = NULL, *next;
3361	dns_name_t *name = dns_db_origin(db);
3362	isc_mem_t *mctx = diff->mctx;
3363	isc_result_t result;
3364
3365	if (privatetype == 0)
3366		return (ISC_R_SUCCESS);
3367
3368	dns_diff_init(mctx, &temp_diff);
3369
3370	/*
3371	 * Extract the changes to be rolled back.
3372	 */
3373	for (tuple = ISC_LIST_HEAD(diff->tuples);
3374	     tuple != NULL; tuple = next) {
3375
3376		next = ISC_LIST_NEXT(tuple, link);
3377
3378		if (tuple->rdata.type != privatetype ||
3379		    !dns_name_equal(name, &tuple->name))
3380			continue;
3381
3382		/*
3383		 * Allow records which indicate that a zone has been
3384		 * signed with a DNSKEY to be be removed.
3385		 */
3386		if (tuple->op == DNS_DIFFOP_DEL &&
3387		    tuple->rdata.length == 5 &&
3388		    tuple->rdata.data[0] != 0 &&
3389		    tuple->rdata.data[4] != 0)
3390			continue;
3391
3392		ISC_LIST_UNLINK(diff->tuples, tuple, link);
3393		ISC_LIST_PREPEND(temp_diff.tuples, tuple, link);
3394	}
3395
3396	/*
3397	 * Rollback the changes.
3398	 */
3399	while ((tuple = ISC_LIST_HEAD(temp_diff.tuples)) != NULL) {
3400		op = (tuple->op == DNS_DIFFOP_DEL) ?
3401		      DNS_DIFFOP_ADD : DNS_DIFFOP_DEL;
3402		CHECK(dns_difftuple_create(mctx, op, name, tuple->ttl,
3403					   &tuple->rdata, &newtuple));
3404		CHECK(do_one_tuple(&newtuple, db, ver, &temp_diff));
3405	}
3406	result = ISC_R_SUCCESS;
3407
3408 failure:
3409	dns_diff_clear(&temp_diff);
3410	return (result);
3411}
3412
3413/*
3414 * Add records to cause the delayed signing of the zone by added DNSKEY
3415 * to remove the RRSIG records generated by a deleted DNSKEY.
3416 */
3417static isc_result_t
3418add_signing_records(dns_db_t *db, dns_rdatatype_t privatetype,
3419		    dns_dbversion_t *ver, dns_diff_t *diff)
3420{
3421	dns_difftuple_t *tuple, *newtuple = NULL, *next;
3422	dns_rdata_dnskey_t dnskey;
3423	dns_rdata_t rdata = DNS_RDATA_INIT;
3424	isc_boolean_t flag;
3425	isc_region_t r;
3426	isc_result_t result = ISC_R_SUCCESS;
3427	isc_uint16_t keyid;
3428	unsigned char buf[5];
3429	dns_name_t *name = dns_db_origin(db);
3430	dns_diff_t temp_diff;
3431
3432	dns_diff_init(diff->mctx, &temp_diff);
3433
3434	/*
3435	 * Extract the DNSKEY tuples from the list.
3436	 */
3437	for (tuple = ISC_LIST_HEAD(diff->tuples);
3438	     tuple != NULL; tuple = next) {
3439
3440		next = ISC_LIST_NEXT(tuple, link);
3441
3442		if (tuple->rdata.type != dns_rdatatype_dnskey)
3443			continue;
3444
3445		ISC_LIST_UNLINK(diff->tuples, tuple, link);
3446		ISC_LIST_APPEND(temp_diff.tuples, tuple, link);
3447	}
3448
3449	/*
3450	 * Extract TTL changes pairs, we don't need signing records for these.
3451	 */
3452	for (tuple = ISC_LIST_HEAD(temp_diff.tuples);
3453	     tuple != NULL; tuple = next) {
3454		if (tuple->op == DNS_DIFFOP_ADD) {
3455			/*
3456			 * Walk the temp_diff list looking for the
3457			 * corresponding delete.
3458			 */
3459			next = ISC_LIST_HEAD(temp_diff.tuples);
3460			while (next != NULL) {
3461				unsigned char *next_data = next->rdata.data;
3462				unsigned char *tuple_data = tuple->rdata.data;
3463				if (next->op == DNS_DIFFOP_DEL &&
3464				    dns_name_equal(&tuple->name, &next->name) &&
3465				    next->rdata.length == tuple->rdata.length &&
3466				    !memcmp(next_data, tuple_data,
3467					    next->rdata.length)) {
3468					ISC_LIST_UNLINK(temp_diff.tuples, next,
3469							link);
3470					ISC_LIST_APPEND(diff->tuples, next,
3471							link);
3472					break;
3473				}
3474				next = ISC_LIST_NEXT(next, link);
3475			}
3476			/*
3477			 * If we have not found a pair move onto the next
3478			 * tuple.
3479			 */
3480			if (next == NULL) {
3481				next = ISC_LIST_NEXT(tuple, link);
3482				continue;
3483			}
3484			/*
3485			 * Find the next tuple to be processed before
3486			 * unlinking then complete moving the pair to 'diff'.
3487			 */
3488			next = ISC_LIST_NEXT(tuple, link);
3489			ISC_LIST_UNLINK(temp_diff.tuples, tuple, link);
3490			ISC_LIST_APPEND(diff->tuples, tuple, link);
3491		} else
3492			next = ISC_LIST_NEXT(tuple, link);
3493	}
3494
3495	/*
3496	 * Process the remaining DNSKEY entries.
3497	 */
3498	for (tuple = ISC_LIST_HEAD(temp_diff.tuples);
3499	     tuple != NULL;
3500	     tuple = ISC_LIST_HEAD(temp_diff.tuples)) {
3501
3502		ISC_LIST_UNLINK(temp_diff.tuples, tuple, link);
3503		ISC_LIST_APPEND(diff->tuples, tuple, link);
3504
3505		dns_rdata_tostruct(&tuple->rdata, &dnskey, NULL);
3506		if ((dnskey.flags &
3507		     (DNS_KEYFLAG_OWNERMASK|DNS_KEYTYPE_NOAUTH))
3508			 != DNS_KEYOWNER_ZONE)
3509			continue;
3510
3511		dns_rdata_toregion(&tuple->rdata, &r);
3512
3513		keyid = dst_region_computeid(&r, dnskey.algorithm);
3514
3515		buf[0] = dnskey.algorithm;
3516		buf[1] = (keyid & 0xff00) >> 8;
3517		buf[2] = (keyid & 0xff);
3518		buf[3] = (tuple->op == DNS_DIFFOP_ADD) ? 0 : 1;
3519		buf[4] = 0;
3520		rdata.data = buf;
3521		rdata.length = sizeof(buf);
3522		rdata.type = privatetype;
3523		rdata.rdclass = tuple->rdata.rdclass;
3524
3525		CHECK(rr_exists(db, ver, name, &rdata, &flag));
3526		if (flag)
3527			continue;
3528		CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD,
3529					   name, 0, &rdata, &newtuple));
3530		CHECK(do_one_tuple(&newtuple, db, ver, diff));
3531		INSIST(newtuple == NULL);
3532		/*
3533		 * Remove any record which says this operation has already
3534		 * completed.
3535		 */
3536		buf[4] = 1;
3537		CHECK(rr_exists(db, ver, name, &rdata, &flag));
3538		if (flag) {
3539			CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_DEL,
3540						   name, 0, &rdata, &newtuple));
3541			CHECK(do_one_tuple(&newtuple, db, ver, diff));
3542			INSIST(newtuple == NULL);
3543		}
3544	}
3545
3546 failure:
3547	dns_diff_clear(&temp_diff);
3548	return (result);
3549}
3550
3551static isc_boolean_t
3552isdnssec(dns_db_t *db, dns_dbversion_t *ver, dns_rdatatype_t privatetype) {
3553	isc_result_t result;
3554	isc_boolean_t build_nsec, build_nsec3;
3555
3556	if (dns_db_issecure(db))
3557		return (ISC_TRUE);
3558
3559	result = dns_private_chains(db, ver, privatetype,
3560				    &build_nsec, &build_nsec3);
3561	RUNTIME_CHECK(result == ISC_R_SUCCESS);
3562	return (build_nsec || build_nsec3);
3563}
3564
3565static void
3566update_action(isc_task_t *task, isc_event_t *event) {
3567	update_event_t *uev = (update_event_t *) event;
3568	dns_zone_t *zone = uev->zone;
3569	ns_client_t *client = (ns_client_t *)event->ev_arg;
3570
3571	isc_result_t result;
3572	dns_db_t *db = NULL;
3573	dns_dbversion_t *oldver = NULL;
3574	dns_dbversion_t *ver = NULL;
3575	dns_diff_t diff;	/* Pending updates. */
3576	dns_diff_t temp;	/* Pending RR existence assertions. */
3577	isc_boolean_t soa_serial_changed = ISC_FALSE;
3578	isc_mem_t *mctx = client->mctx;
3579	dns_rdatatype_t covers;
3580	dns_message_t *request = client->message;
3581	dns_rdataclass_t zoneclass;
3582	dns_name_t *zonename;
3583	dns_ssutable_t *ssutable = NULL;
3584	dns_fixedname_t tmpnamefixed;
3585	dns_name_t *tmpname = NULL;
3586	unsigned int options;
3587	dns_difftuple_t *tuple;
3588	dns_rdata_dnskey_t dnskey;
3589	isc_boolean_t had_dnskey;
3590	dns_rdatatype_t privatetype = dns_zone_getprivatetype(zone);
3591
3592	INSIST(event->ev_type == DNS_EVENT_UPDATE);
3593
3594	dns_diff_init(mctx, &diff);
3595	dns_diff_init(mctx, &temp);
3596
3597	CHECK(dns_zone_getdb(zone, &db));
3598	zonename = dns_db_origin(db);
3599	zoneclass = dns_db_class(db);
3600	dns_zone_getssutable(zone, &ssutable);
3601
3602	/*
3603	 * Update message processing can leak record existance information
3604	 * so check that we are allowed to query this zone.  Additionally
3605	 * if we would refuse all updates for this zone we bail out here.
3606	 */
3607	CHECK(checkqueryacl(client, dns_zone_getqueryacl(zone), zonename,
3608			    dns_zone_getupdateacl(zone), ssutable));
3609
3610	/*
3611	 * Get old and new versions now that queryacl has been checked.
3612	 */
3613	dns_db_currentversion(db, &oldver);
3614	CHECK(dns_db_newversion(db, &ver));
3615
3616	/*
3617	 * Check prerequisites.
3618	 */
3619
3620	for (result = dns_message_firstname(request, DNS_SECTION_PREREQUISITE);
3621	     result == ISC_R_SUCCESS;
3622	     result = dns_message_nextname(request, DNS_SECTION_PREREQUISITE))
3623	{
3624		dns_name_t *name = NULL;
3625		dns_rdata_t rdata = DNS_RDATA_INIT;
3626		dns_ttl_t ttl;
3627		dns_rdataclass_t update_class;
3628		isc_boolean_t flag;
3629
3630		get_current_rr(request, DNS_SECTION_PREREQUISITE, zoneclass,
3631			       &name, &rdata, &covers, &ttl, &update_class);
3632
3633		if (ttl != 0)
3634			PREREQFAILC(DNS_R_FORMERR,
3635				    "prerequisite TTL is not zero");
3636
3637		if (! dns_name_issubdomain(name, zonename))
3638			PREREQFAILN(DNS_R_NOTZONE, name,
3639				    "prerequisite name is out of zone");
3640
3641		if (update_class == dns_rdataclass_any) {
3642			if (rdata.length != 0)
3643				PREREQFAILC(DNS_R_FORMERR,
3644				      "class ANY prerequisite "
3645				      "RDATA is not empty");
3646			if (rdata.type == dns_rdatatype_any) {
3647				CHECK(name_exists(db, ver, name, &flag));
3648				if (! flag) {
3649					PREREQFAILN(DNS_R_NXDOMAIN, name,
3650						    "'name in use' "
3651						    "prerequisite not "
3652						    "satisfied");
3653				}
3654			} else {
3655				CHECK(rrset_exists(db, ver, name,
3656						   rdata.type, covers, &flag));
3657				if (! flag) {
3658					/* RRset does not exist. */
3659					PREREQFAILNT(DNS_R_NXRRSET, name, rdata.type,
3660					"'rrset exists (value independent)' "
3661					"prerequisite not satisfied");
3662				}
3663			}
3664		} else if (update_class == dns_rdataclass_none) {
3665			if (rdata.length != 0)
3666				PREREQFAILC(DNS_R_FORMERR,
3667					    "class NONE prerequisite "
3668					    "RDATA is not empty");
3669			if (rdata.type == dns_rdatatype_any) {
3670				CHECK(name_exists(db, ver, name, &flag));
3671				if (flag) {
3672					PREREQFAILN(DNS_R_YXDOMAIN, name,
3673						    "'name not in use' "
3674						    "prerequisite not "
3675						    "satisfied");
3676				}
3677			} else {
3678				CHECK(rrset_exists(db, ver, name,
3679						   rdata.type, covers, &flag));
3680				if (flag) {
3681					/* RRset exists. */
3682					PREREQFAILNT(DNS_R_YXRRSET, name,
3683						     rdata.type,
3684						     "'rrset does not exist' "
3685						     "prerequisite not "
3686						     "satisfied");
3687				}
3688			}
3689		} else if (update_class == zoneclass) {
3690			/* "temp<rr.name, rr.type> += rr;" */
3691			result = temp_append(&temp, name, &rdata);
3692			if (result != ISC_R_SUCCESS) {
3693				UNEXPECTED_ERROR(__FILE__, __LINE__,
3694					 "temp entry creation failed: %s",
3695						 dns_result_totext(result));
3696				FAIL(ISC_R_UNEXPECTED);
3697			}
3698		} else {
3699			PREREQFAILC(DNS_R_FORMERR, "malformed prerequisite");
3700		}
3701	}
3702	if (result != ISC_R_NOMORE)
3703		FAIL(result);
3704
3705	/*
3706	 * Perform the final check of the "rrset exists (value dependent)"
3707	 * prerequisites.
3708	 */
3709	if (ISC_LIST_HEAD(temp.tuples) != NULL) {
3710		dns_rdatatype_t type;
3711
3712		/*
3713		 * Sort the prerequisite records by owner name,
3714		 * type, and rdata.
3715		 */
3716		result = dns_diff_sort(&temp, temp_order);
3717		if (result != ISC_R_SUCCESS)
3718			FAILC(result, "'RRset exists (value dependent)' "
3719			      "prerequisite not satisfied");
3720
3721		dns_fixedname_init(&tmpnamefixed);
3722		tmpname = dns_fixedname_name(&tmpnamefixed);
3723		result = temp_check(mctx, &temp, db, ver, tmpname, &type);
3724		if (result != ISC_R_SUCCESS)
3725			FAILNT(result, tmpname, type,
3726			       "'RRset exists (value dependent)' "
3727			       "prerequisite not satisfied");
3728	}
3729
3730	update_log(client, zone, LOGLEVEL_DEBUG,
3731		   "prerequisites are OK");
3732
3733	/*
3734	 * Check Requestor's Permissions.  It seems a bit silly to do this
3735	 * only after prerequisite testing, but that is what RFC2136 says.
3736	 */
3737	if (ssutable == NULL)
3738		CHECK(checkupdateacl(client, dns_zone_getupdateacl(zone),
3739				     "update", zonename, ISC_FALSE, ISC_FALSE));
3740	else if (client->signer == NULL && !TCPCLIENT(client))
3741		CHECK(checkupdateacl(client, NULL, "update", zonename,
3742				     ISC_FALSE, ISC_TRUE));
3743
3744	if (dns_zone_getupdatedisabled(zone))
3745		FAILC(DNS_R_REFUSED, "dynamic update temporarily disabled "
3746				     "because the zone is frozen.  Use "
3747				     "'rndc thaw' to re-enable updates.");
3748
3749	/*
3750	 * Perform the Update Section Prescan.
3751	 */
3752
3753	for (result = dns_message_firstname(request, DNS_SECTION_UPDATE);
3754	     result == ISC_R_SUCCESS;
3755	     result = dns_message_nextname(request, DNS_SECTION_UPDATE))
3756	{
3757		dns_name_t *name = NULL;
3758		dns_rdata_t rdata = DNS_RDATA_INIT;
3759		dns_ttl_t ttl;
3760		dns_rdataclass_t update_class;
3761		get_current_rr(request, DNS_SECTION_UPDATE, zoneclass,
3762			       &name, &rdata, &covers, &ttl, &update_class);
3763
3764		if (! dns_name_issubdomain(name, zonename))
3765			FAILC(DNS_R_NOTZONE,
3766			      "update RR is outside zone");
3767		if (update_class == zoneclass) {
3768			/*
3769			 * Check for meta-RRs.  The RFC2136 pseudocode says
3770			 * check for ANY|AXFR|MAILA|MAILB, but the text adds
3771			 * "or any other QUERY metatype"
3772			 */
3773			if (dns_rdatatype_ismeta(rdata.type)) {
3774				FAILC(DNS_R_FORMERR,
3775				      "meta-RR in update");
3776			}
3777			result = dns_zone_checknames(zone, name, &rdata);
3778			if (result != ISC_R_SUCCESS)
3779				FAIL(DNS_R_REFUSED);
3780		} else if (update_class == dns_rdataclass_any) {
3781			if (ttl != 0 || rdata.length != 0 ||
3782			    (dns_rdatatype_ismeta(rdata.type) &&
3783			     rdata.type != dns_rdatatype_any))
3784				FAILC(DNS_R_FORMERR,
3785				      "meta-RR in update");
3786		} else if (update_class == dns_rdataclass_none) {
3787			if (ttl != 0 ||
3788			    dns_rdatatype_ismeta(rdata.type))
3789				FAILC(DNS_R_FORMERR,
3790				      "meta-RR in update");
3791		} else {
3792			update_log(client, zone, ISC_LOG_WARNING,
3793				   "update RR has incorrect class %d",
3794				   update_class);
3795			FAIL(DNS_R_FORMERR);
3796		}
3797
3798		/*
3799		 * draft-ietf-dnsind-simple-secure-update-01 says
3800		 * "Unlike traditional dynamic update, the client
3801		 * is forbidden from updating NSEC records."
3802		 */
3803		if (rdata.type == dns_rdatatype_nsec3) {
3804			FAILC(DNS_R_REFUSED,
3805			      "explicit NSEC3 updates are not allowed "
3806			      "in secure zones");
3807		} else if (rdata.type == dns_rdatatype_nsec) {
3808			FAILC(DNS_R_REFUSED,
3809			      "explicit NSEC updates are not allowed "
3810			      "in secure zones");
3811		} else if (rdata.type == dns_rdatatype_rrsig &&
3812			   !dns_name_equal(name, zonename)) {
3813			FAILC(DNS_R_REFUSED,
3814			      "explicit RRSIG updates are currently "
3815			      "not supported in secure zones except "
3816			      "at the apex");
3817		}
3818
3819		if (ssutable != NULL) {
3820			isc_netaddr_t *tcpaddr, netaddr;
3821			dst_key_t *tsigkey = NULL;
3822			/*
3823			 * If this is a TCP connection then pass the
3824			 * address of the client through for tcp-self
3825			 * and 6to4-self otherwise pass NULL.  This
3826			 * provides weak address based authentication.
3827			 */
3828			if (TCPCLIENT(client)) {
3829				isc_netaddr_fromsockaddr(&netaddr,
3830							 &client->peeraddr);
3831				tcpaddr = &netaddr;
3832			} else
3833				tcpaddr = NULL;
3834
3835			if (client->message->tsigkey != NULL)
3836				tsigkey = client->message->tsigkey->key;
3837
3838			if (rdata.type != dns_rdatatype_any) {
3839				if (!dns_ssutable_checkrules(ssutable,
3840							     client->signer,
3841							     name, tcpaddr,
3842							     rdata.type,
3843							     tsigkey))
3844					FAILC(DNS_R_REFUSED,
3845					      "rejected by secure update");
3846			} else {
3847				if (!ssu_checkall(db, ver, name, ssutable,
3848						  client->signer, tcpaddr,
3849						  tsigkey))
3850					FAILC(DNS_R_REFUSED,
3851					      "rejected by secure update");
3852			}
3853		}
3854	}
3855	if (result != ISC_R_NOMORE)
3856		FAIL(result);
3857
3858	update_log(client, zone, LOGLEVEL_DEBUG,
3859		   "update section prescan OK");
3860
3861	/*
3862	 * Process the Update Section.
3863	 */
3864
3865	options = dns_zone_getoptions(zone);
3866	for (result = dns_message_firstname(request, DNS_SECTION_UPDATE);
3867	     result == ISC_R_SUCCESS;
3868	     result = dns_message_nextname(request, DNS_SECTION_UPDATE))
3869	{
3870		dns_name_t *name = NULL;
3871		dns_rdata_t rdata = DNS_RDATA_INIT;
3872		dns_ttl_t ttl;
3873		dns_rdataclass_t update_class;
3874		isc_boolean_t flag;
3875
3876		get_current_rr(request, DNS_SECTION_UPDATE, zoneclass,
3877			       &name, &rdata, &covers, &ttl, &update_class);
3878
3879		if (update_class == zoneclass) {
3880
3881			/*
3882			 * RFC1123 doesn't allow MF and MD in master zones.				 */
3883			if (rdata.type == dns_rdatatype_md ||
3884			    rdata.type == dns_rdatatype_mf) {
3885				char typebuf[DNS_RDATATYPE_FORMATSIZE];
3886
3887				dns_rdatatype_format(rdata.type, typebuf,
3888						     sizeof(typebuf));
3889				update_log(client, zone, LOGLEVEL_PROTOCOL,
3890					   "attempt to add %s ignored",
3891					   typebuf);
3892				continue;
3893			}
3894			if ((rdata.type == dns_rdatatype_ns ||
3895			     rdata.type == dns_rdatatype_dname) &&
3896			    dns_name_iswildcard(name)) {
3897				char typebuf[DNS_RDATATYPE_FORMATSIZE];
3898
3899				dns_rdatatype_format(rdata.type, typebuf,
3900						     sizeof(typebuf));
3901				update_log(client, zone,
3902					   LOGLEVEL_PROTOCOL,
3903					   "attempt to add wildcard %s record "
3904					   "ignored", typebuf);
3905				continue;
3906			}
3907			if (rdata.type == dns_rdatatype_cname) {
3908				CHECK(cname_incompatible_rrset_exists(db, ver,
3909								      name,
3910								      &flag));
3911				if (flag) {
3912					update_log(client, zone,
3913						   LOGLEVEL_PROTOCOL,
3914						   "attempt to add CNAME "
3915						   "alongside non-CNAME "
3916						   "ignored");
3917					continue;
3918				}
3919			} else {
3920				CHECK(rrset_exists(db, ver, name,
3921						   dns_rdatatype_cname, 0,
3922						   &flag));
3923				if (flag &&
3924				    ! dns_rdatatype_isdnssec(rdata.type))
3925				{
3926					update_log(client, zone,
3927						   LOGLEVEL_PROTOCOL,
3928						   "attempt to add non-CNAME "
3929						   "alongside CNAME ignored");
3930					continue;
3931				}
3932			}
3933			if (rdata.type == dns_rdatatype_soa) {
3934				isc_boolean_t ok;
3935				CHECK(rrset_exists(db, ver, name,
3936						   dns_rdatatype_soa, 0,
3937						   &flag));
3938				if (! flag) {
3939					update_log(client, zone,
3940						   LOGLEVEL_PROTOCOL,
3941						   "attempt to create 2nd "
3942						   "SOA ignored");
3943					continue;
3944				}
3945				CHECK(check_soa_increment(db, ver, &rdata,
3946							  &ok));
3947				if (! ok) {
3948					update_log(client, zone,
3949						   LOGLEVEL_PROTOCOL,
3950						   "SOA update failed to "
3951						   "increment serial, "
3952						   "ignoring it");
3953					continue;
3954				}
3955				soa_serial_changed = ISC_TRUE;
3956			}
3957
3958			if (rdata.type == privatetype) {
3959				update_log(client, zone, LOGLEVEL_PROTOCOL,
3960					   "attempt to add a private type "
3961					   "(%u) record rejected internal "
3962					   "use only", privatetype);
3963				continue;
3964			}
3965
3966			if (rdata.type == dns_rdatatype_nsec3param) {
3967				/*
3968				 * Ignore attempts to add NSEC3PARAM records
3969				 * with any flags other than OPTOUT.
3970				 */
3971				if ((rdata.data[1] & ~DNS_NSEC3FLAG_OPTOUT) != 0) {
3972					update_log(client, zone,
3973						   LOGLEVEL_PROTOCOL,
3974						   "attempt to add NSEC3PARAM "
3975						   "record with non OPTOUT "
3976						   "flag");
3977					continue;
3978				}
3979			}
3980
3981			if ((options & DNS_ZONEOPT_CHECKWILDCARD) != 0 &&
3982			    dns_name_internalwildcard(name)) {
3983				char namestr[DNS_NAME_FORMATSIZE];
3984				dns_name_format(name, namestr,
3985						sizeof(namestr));
3986				update_log(client, zone, LOGLEVEL_PROTOCOL,
3987					   "warning: ownername '%s' contains "
3988					   "a non-terminal wildcard", namestr);
3989			}
3990
3991			if (isc_log_wouldlog(ns_g_lctx, LOGLEVEL_PROTOCOL)) {
3992				char namestr[DNS_NAME_FORMATSIZE];
3993				char typestr[DNS_RDATATYPE_FORMATSIZE];
3994				dns_name_format(name, namestr,
3995						sizeof(namestr));
3996				dns_rdatatype_format(rdata.type, typestr,
3997						     sizeof(typestr));
3998				update_log(client, zone, LOGLEVEL_PROTOCOL,
3999					   "adding an RR at '%s' %s",
4000					   namestr, typestr);
4001			}
4002
4003			/* Prepare the affected RRset for the addition. */
4004			{
4005				add_rr_prepare_ctx_t ctx;
4006				ctx.db = db;
4007				ctx.ver = ver;
4008				ctx.diff = &diff;
4009				ctx.name = name;
4010				ctx.update_rr = &rdata;
4011				ctx.update_rr_ttl = ttl;
4012				ctx.ignore_add = ISC_FALSE;
4013				dns_diff_init(mctx, &ctx.del_diff);
4014				dns_diff_init(mctx, &ctx.add_diff);
4015				CHECK(foreach_rr(db, ver, name, rdata.type,
4016						 covers, add_rr_prepare_action,
4017						 &ctx));
4018
4019				if (ctx.ignore_add) {
4020					dns_diff_clear(&ctx.del_diff);
4021					dns_diff_clear(&ctx.add_diff);
4022				} else {
4023					CHECK(do_diff(&ctx.del_diff, db, ver,
4024						      &diff));
4025					CHECK(do_diff(&ctx.add_diff, db, ver,
4026						      &diff));
4027					CHECK(update_one_rr(db, ver, &diff,
4028							    DNS_DIFFOP_ADD,
4029							    name, ttl, &rdata));
4030				}
4031			}
4032		} else if (update_class == dns_rdataclass_any) {
4033			if (rdata.type == dns_rdatatype_any) {
4034				if (isc_log_wouldlog(ns_g_lctx,
4035						     LOGLEVEL_PROTOCOL))
4036				{
4037					char namestr[DNS_NAME_FORMATSIZE];
4038					dns_name_format(name, namestr,
4039							sizeof(namestr));
4040					update_log(client, zone,
4041						   LOGLEVEL_PROTOCOL,
4042						   "delete all rrsets from "
4043						   "name '%s'", namestr);
4044				}
4045				if (dns_name_equal(name, zonename)) {
4046					CHECK(delete_if(type_not_soa_nor_ns_p,
4047							db, ver, name,
4048							dns_rdatatype_any, 0,
4049							&rdata, &diff));
4050				} else {
4051					CHECK(delete_if(type_not_dnssec,
4052							db, ver, name,
4053							dns_rdatatype_any, 0,
4054							&rdata, &diff));
4055				}
4056			} else if (dns_name_equal(name, zonename) &&
4057				   (rdata.type == dns_rdatatype_soa ||
4058				    rdata.type == dns_rdatatype_ns)) {
4059				update_log(client, zone, LOGLEVEL_PROTOCOL,
4060					   "attempt to delete all SOA "
4061					   "or NS records ignored");
4062				continue;
4063			} else {
4064				if (isc_log_wouldlog(ns_g_lctx,
4065						     LOGLEVEL_PROTOCOL))
4066				{
4067					char namestr[DNS_NAME_FORMATSIZE];
4068					char typestr[DNS_RDATATYPE_FORMATSIZE];
4069					dns_name_format(name, namestr,
4070							sizeof(namestr));
4071					dns_rdatatype_format(rdata.type,
4072							     typestr,
4073							     sizeof(typestr));
4074					update_log(client, zone,
4075						   LOGLEVEL_PROTOCOL,
4076						   "deleting rrset at '%s' %s",
4077						   namestr, typestr);
4078				}
4079				CHECK(delete_if(true_p, db, ver, name,
4080						rdata.type, covers, &rdata,
4081						&diff));
4082			}
4083		} else if (update_class == dns_rdataclass_none) {
4084			char namestr[DNS_NAME_FORMATSIZE];
4085			char typestr[DNS_RDATATYPE_FORMATSIZE];
4086
4087			/*
4088			 * The (name == zonename) condition appears in
4089			 * RFC2136 3.4.2.4 but is missing from the pseudocode.
4090			 */
4091			if (dns_name_equal(name, zonename)) {
4092				if (rdata.type == dns_rdatatype_soa) {
4093					update_log(client, zone,
4094						   LOGLEVEL_PROTOCOL,
4095						   "attempt to delete SOA "
4096						   "ignored");
4097					continue;
4098				}
4099				if (rdata.type == dns_rdatatype_ns) {
4100					int count;
4101					CHECK(rr_count(db, ver, name,
4102						       dns_rdatatype_ns,
4103						       0, &count));
4104					if (count == 1) {
4105						update_log(client, zone,
4106							   LOGLEVEL_PROTOCOL,
4107							   "attempt to "
4108							   "delete last "
4109							   "NS ignored");
4110						continue;
4111					}
4112				}
4113			}
4114			dns_name_format(name, namestr, sizeof(namestr));
4115			dns_rdatatype_format(rdata.type, typestr,
4116					     sizeof(typestr));
4117			update_log(client, zone, LOGLEVEL_PROTOCOL,
4118				   "deleting an RR at %s %s", namestr, typestr);
4119			CHECK(delete_if(rr_equal_p, db, ver, name, rdata.type,
4120					covers, &rdata, &diff));
4121		}
4122	}
4123	if (result != ISC_R_NOMORE)
4124		FAIL(result);
4125
4126	/*
4127	 * Check that any changes to DNSKEY/NSEC3PARAM records make sense.
4128	 * If they don't then back out all changes to DNSKEY/NSEC3PARAM
4129	 * records.
4130	 */
4131	if (! ISC_LIST_EMPTY(diff.tuples))
4132		CHECK(check_dnssec(client, zone, db, ver, &diff));
4133
4134	if (! ISC_LIST_EMPTY(diff.tuples)) {
4135		unsigned int errors = 0;
4136		CHECK(dns_zone_nscheck(zone, db, ver, &errors));
4137		if (errors != 0) {
4138			update_log(client, zone, LOGLEVEL_PROTOCOL,
4139				   "update rejected: post update name server "
4140				   "sanity check failed");
4141			result = DNS_R_REFUSED;
4142			goto failure;
4143		}
4144	}
4145
4146	/*
4147	 * If any changes were made, increment the SOA serial number,
4148	 * update RRSIGs and NSECs (if zone is secure), and write the update
4149	 * to the journal.
4150	 */
4151	if (! ISC_LIST_EMPTY(diff.tuples)) {
4152		char *journalfile;
4153		dns_journal_t *journal;
4154		isc_boolean_t has_dnskey;
4155
4156		/*
4157		 * Increment the SOA serial, but only if it was not
4158		 * changed as a result of an update operation.
4159		 */
4160		if (! soa_serial_changed) {
4161			CHECK(increment_soa_serial(db, ver, &diff, mctx));
4162		}
4163
4164		CHECK(check_mx(client, zone, db, ver, &diff));
4165
4166		CHECK(remove_orphaned_ds(db, ver, &diff));
4167
4168		CHECK(rrset_exists(db, ver, zonename, dns_rdatatype_dnskey,
4169				   0, &has_dnskey));
4170
4171#define ALLOW_SECURE_TO_INSECURE(zone) \
4172	((dns_zone_getoptions(zone) & DNS_ZONEOPT_SECURETOINSECURE) != 0)
4173
4174		if (!ALLOW_SECURE_TO_INSECURE(zone)) {
4175			CHECK(rrset_exists(db, oldver, zonename,
4176					   dns_rdatatype_dnskey, 0,
4177					   &had_dnskey));
4178			if (had_dnskey && !has_dnskey) {
4179				update_log(client, zone, LOGLEVEL_PROTOCOL,
4180					   "update rejected: all DNSKEY "
4181					   "records removed and "
4182					   "'dnssec-secure-to-insecure' "
4183					   "not set");
4184				result = DNS_R_REFUSED;
4185				goto failure;
4186			}
4187		}
4188
4189		CHECK(rollback_private(db, privatetype, ver, &diff));
4190
4191		CHECK(add_signing_records(db, privatetype, ver, &diff));
4192
4193		CHECK(add_nsec3param_records(client, zone, db, ver, &diff));
4194
4195		if (!has_dnskey) {
4196			/*
4197			 * We are transitioning from secure to insecure.
4198			 * Cause all NSEC3 chains to be deleted.  When the
4199			 * the last signature for the DNSKEY records are
4200			 * remove any NSEC chain present will also be removed.
4201			 */
4202			 CHECK(dns_nsec3param_deletechains(db, ver, zone,
4203							   &diff));
4204		} else if (has_dnskey && isdnssec(db, ver, privatetype)) {
4205			isc_uint32_t interval;
4206			interval = dns_zone_getsigvalidityinterval(zone);
4207			result = update_signatures(client, zone, db, oldver,
4208						   ver, &diff, interval);
4209			if (result != ISC_R_SUCCESS) {
4210				update_log(client, zone,
4211					   ISC_LOG_ERROR,
4212					   "RRSIG/NSEC/NSEC3 update failed: %s",
4213					   isc_result_totext(result));
4214				goto failure;
4215			}
4216		}
4217
4218		journalfile = dns_zone_getjournal(zone);
4219		if (journalfile != NULL) {
4220			update_log(client, zone, LOGLEVEL_DEBUG,
4221				   "writing journal %s", journalfile);
4222
4223			journal = NULL;
4224			result = dns_journal_open(mctx, journalfile,
4225						  ISC_TRUE, &journal);
4226			if (result != ISC_R_SUCCESS)
4227				FAILS(result, "journal open failed");
4228
4229			result = dns_journal_write_transaction(journal, &diff);
4230			if (result != ISC_R_SUCCESS) {
4231				dns_journal_destroy(&journal);
4232				FAILS(result, "journal write failed");
4233			}
4234
4235			dns_journal_destroy(&journal);
4236		}
4237
4238		/*
4239		 * XXXRTH  Just a note that this committing code will have
4240		 *	   to change to handle databases that need two-phase
4241		 *	   commit, but this isn't a priority.
4242		 */
4243		update_log(client, zone, LOGLEVEL_DEBUG,
4244			   "committing update transaction");
4245
4246		dns_db_closeversion(db, &ver, ISC_TRUE);
4247
4248		/*
4249		 * Mark the zone as dirty so that it will be written to disk.
4250		 */
4251		dns_zone_markdirty(zone);
4252
4253		/*
4254		 * Notify slaves of the change we just made.
4255		 */
4256		dns_zone_notify(zone);
4257
4258		/*
4259		 * Cause the zone to be signed with the key that we
4260		 * have just added or have the corresponding signatures
4261		 * deleted.
4262		 *
4263		 * Note: we are already committed to this course of action.
4264		 */
4265		for (tuple = ISC_LIST_HEAD(diff.tuples);
4266		     tuple != NULL;
4267		     tuple = ISC_LIST_NEXT(tuple, link)) {
4268			isc_region_t r;
4269			dns_secalg_t algorithm;
4270			isc_uint16_t keyid;
4271
4272			if (tuple->rdata.type != dns_rdatatype_dnskey)
4273				continue;
4274
4275			dns_rdata_tostruct(&tuple->rdata, &dnskey, NULL);
4276			if ((dnskey.flags &
4277			     (DNS_KEYFLAG_OWNERMASK|DNS_KEYTYPE_NOAUTH))
4278				 != DNS_KEYOWNER_ZONE)
4279				continue;
4280
4281			dns_rdata_toregion(&tuple->rdata, &r);
4282			algorithm = dnskey.algorithm;
4283			keyid = dst_region_computeid(&r, algorithm);
4284
4285			result = dns_zone_signwithkey(zone, algorithm, keyid,
4286					ISC_TF(tuple->op == DNS_DIFFOP_DEL));
4287			if (result != ISC_R_SUCCESS) {
4288				update_log(client, zone, ISC_LOG_ERROR,
4289					   "dns_zone_signwithkey failed: %s",
4290					   dns_result_totext(result));
4291			}
4292		}
4293
4294		/*
4295		 * Cause the zone to add/delete NSEC3 chains for the
4296		 * deferred NSEC3PARAM changes.
4297		 *
4298		 * Note: we are already committed to this course of action.
4299		 */
4300		for (tuple = ISC_LIST_HEAD(diff.tuples);
4301		     tuple != NULL;
4302		     tuple = ISC_LIST_NEXT(tuple, link)) {
4303			unsigned char buf[DNS_NSEC3PARAM_BUFFERSIZE];
4304			dns_rdata_t rdata = DNS_RDATA_INIT;
4305			dns_rdata_nsec3param_t nsec3param;
4306
4307			if (tuple->rdata.type != privatetype ||
4308			    tuple->op != DNS_DIFFOP_ADD)
4309				continue;
4310
4311			if (!dns_nsec3param_fromprivate(&tuple->rdata, &rdata,
4312						   buf, sizeof(buf)))
4313				continue;
4314			dns_rdata_tostruct(&rdata, &nsec3param, NULL);
4315			if (nsec3param.flags == 0)
4316				continue;
4317
4318			result = dns_zone_addnsec3chain(zone, &nsec3param);
4319			if (result != ISC_R_SUCCESS) {
4320				update_log(client, zone, ISC_LOG_ERROR,
4321					   "dns_zone_addnsec3chain failed: %s",
4322					   dns_result_totext(result));
4323			}
4324		}
4325	} else {
4326		update_log(client, zone, LOGLEVEL_DEBUG, "redundant request");
4327		dns_db_closeversion(db, &ver, ISC_TRUE);
4328	}
4329	result = ISC_R_SUCCESS;
4330	goto common;
4331
4332 failure:
4333	/*
4334	 * The reason for failure should have been logged at this point.
4335	 */
4336	if (ver != NULL) {
4337		update_log(client, zone, LOGLEVEL_DEBUG,
4338			   "rolling back");
4339		dns_db_closeversion(db, &ver, ISC_FALSE);
4340	}
4341
4342 common:
4343	dns_diff_clear(&temp);
4344	dns_diff_clear(&diff);
4345
4346	if (oldver != NULL)
4347		dns_db_closeversion(db, &oldver, ISC_FALSE);
4348
4349	if (db != NULL)
4350		dns_db_detach(&db);
4351
4352	if (ssutable != NULL)
4353		dns_ssutable_detach(&ssutable);
4354
4355	isc_task_detach(&task);
4356	uev->result = result;
4357	if (zone != NULL)
4358		INSIST(uev->zone == zone); /* we use this later */
4359	uev->ev_type = DNS_EVENT_UPDATEDONE;
4360	uev->ev_action = updatedone_action;
4361	isc_task_send(client->task, &event);
4362	INSIST(event == NULL);
4363}
4364
4365static void
4366updatedone_action(isc_task_t *task, isc_event_t *event) {
4367	update_event_t *uev = (update_event_t *) event;
4368	ns_client_t *client = (ns_client_t *) event->ev_arg;
4369
4370	UNUSED(task);
4371
4372	INSIST(event->ev_type == DNS_EVENT_UPDATEDONE);
4373	INSIST(task == client->task);
4374
4375	INSIST(client->nupdates > 0);
4376	switch (uev->result) {
4377	case ISC_R_SUCCESS:
4378		inc_stats(uev->zone, dns_nsstatscounter_updatedone);
4379		break;
4380	case DNS_R_REFUSED:
4381		inc_stats(uev->zone, dns_nsstatscounter_updaterej);
4382		break;
4383	default:
4384		inc_stats(uev->zone, dns_nsstatscounter_updatefail);
4385		break;
4386	}
4387	if (uev->zone != NULL)
4388		dns_zone_detach(&uev->zone);
4389	client->nupdates--;
4390	respond(client, uev->result);
4391	isc_event_free(&event);
4392	ns_client_detach(&client);
4393}
4394
4395/*%
4396 * Update forwarding support.
4397 */
4398
4399static void
4400forward_fail(isc_task_t *task, isc_event_t *event) {
4401	ns_client_t *client = (ns_client_t *)event->ev_arg;
4402
4403	UNUSED(task);
4404
4405	INSIST(client->nupdates > 0);
4406	client->nupdates--;
4407	respond(client, DNS_R_SERVFAIL);
4408	isc_event_free(&event);
4409	ns_client_detach(&client);
4410}
4411
4412
4413static void
4414forward_callback(void *arg, isc_result_t result, dns_message_t *answer) {
4415	update_event_t *uev = arg;
4416	ns_client_t *client = uev->ev_arg;
4417	dns_zone_t *zone = uev->zone;
4418
4419	if (result != ISC_R_SUCCESS) {
4420		INSIST(answer == NULL);
4421		uev->ev_type = DNS_EVENT_UPDATEDONE;
4422		uev->ev_action = forward_fail;
4423		inc_stats(zone, dns_nsstatscounter_updatefwdfail);
4424	} else {
4425		uev->ev_type = DNS_EVENT_UPDATEDONE;
4426		uev->ev_action = forward_done;
4427		uev->answer = answer;
4428		inc_stats(zone, dns_nsstatscounter_updaterespfwd);
4429	}
4430	isc_task_send(client->task, ISC_EVENT_PTR(&uev));
4431	dns_zone_detach(&zone);
4432}
4433
4434static void
4435forward_done(isc_task_t *task, isc_event_t *event) {
4436	update_event_t *uev = (update_event_t *) event;
4437	ns_client_t *client = (ns_client_t *)event->ev_arg;
4438
4439	UNUSED(task);
4440
4441	INSIST(client->nupdates > 0);
4442	client->nupdates--;
4443	ns_client_sendraw(client, uev->answer);
4444	dns_message_destroy(&uev->answer);
4445	isc_event_free(&event);
4446	ns_client_detach(&client);
4447}
4448
4449static void
4450forward_action(isc_task_t *task, isc_event_t *event) {
4451	update_event_t *uev = (update_event_t *) event;
4452	dns_zone_t *zone = uev->zone;
4453	ns_client_t *client = (ns_client_t *)event->ev_arg;
4454	isc_result_t result;
4455
4456	result = dns_zone_forwardupdate(zone, client->message,
4457					forward_callback, event);
4458	if (result != ISC_R_SUCCESS) {
4459		uev->ev_type = DNS_EVENT_UPDATEDONE;
4460		uev->ev_action = forward_fail;
4461		isc_task_send(client->task, &event);
4462		inc_stats(zone, dns_nsstatscounter_updatefwdfail);
4463		dns_zone_detach(&zone);
4464	} else
4465		inc_stats(zone, dns_nsstatscounter_updatereqfwd);
4466	isc_task_detach(&task);
4467}
4468
4469static isc_result_t
4470send_forward_event(ns_client_t *client, dns_zone_t *zone) {
4471	isc_result_t result = ISC_R_SUCCESS;
4472	update_event_t *event = NULL;
4473	isc_task_t *zonetask = NULL;
4474	ns_client_t *evclient;
4475
4476	event = (update_event_t *)
4477		isc_event_allocate(client->mctx, client, DNS_EVENT_UPDATE,
4478				   forward_action, NULL, sizeof(*event));
4479	if (event == NULL)
4480		FAIL(ISC_R_NOMEMORY);
4481	event->zone = zone;
4482	event->result = ISC_R_SUCCESS;
4483
4484	evclient = NULL;
4485	ns_client_attach(client, &evclient);
4486	INSIST(client->nupdates == 0);
4487	client->nupdates++;
4488	event->ev_arg = evclient;
4489
4490	dns_zone_gettask(zone, &zonetask);
4491	isc_task_send(zonetask, ISC_EVENT_PTR(&event));
4492
4493 failure:
4494	if (event != NULL)
4495		isc_event_free(ISC_EVENT_PTR(&event));
4496	return (result);
4497}
4498