update.c revision 225361
1254885Sdumbbell/*
2254885Sdumbbell * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
3254885Sdumbbell * Copyright (C) 1999-2003  Internet Software Consortium.
4254885Sdumbbell *
5254885Sdumbbell * Permission to use, copy, modify, and/or distribute this software for any
6254885Sdumbbell * purpose with or without fee is hereby granted, provided that the above
7254885Sdumbbell * copyright notice and this permission notice appear in all copies.
8254885Sdumbbell *
9254885Sdumbbell * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10254885Sdumbbell * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11254885Sdumbbell * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12254885Sdumbbell * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13254885Sdumbbell * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14254885Sdumbbell * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15254885Sdumbbell * PERFORMANCE OF THIS SOFTWARE.
16254885Sdumbbell */
17254885Sdumbbell
18254885Sdumbbell/* $Id: update.c,v 1.186.16.5 2011-03-25 23:53:52 each Exp $ */
19254885Sdumbbell
20254885Sdumbbell#include <config.h>
21254885Sdumbbell
22254885Sdumbbell#include <isc/netaddr.h>
23254885Sdumbbell#include <isc/print.h>
24254885Sdumbbell#include <isc/serial.h>
25254885Sdumbbell#include <isc/stats.h>
26254885Sdumbbell#include <isc/string.h>
27254885Sdumbbell#include <isc/taskpool.h>
28254885Sdumbbell#include <isc/util.h>
29254885Sdumbbell
30254885Sdumbbell#include <dns/db.h>
31254885Sdumbbell#include <dns/dbiterator.h>
32254885Sdumbbell#include <dns/diff.h>
33254885Sdumbbell#include <dns/dnssec.h>
34254885Sdumbbell#include <dns/events.h>
35254885Sdumbbell#include <dns/fixedname.h>
36254885Sdumbbell#include <dns/journal.h>
37254885Sdumbbell#include <dns/keyvalues.h>
38254885Sdumbbell#include <dns/message.h>
39254885Sdumbbell#include <dns/nsec.h>
40254885Sdumbbell#include <dns/nsec3.h>
41254885Sdumbbell#include <dns/private.h>
42254885Sdumbbell#include <dns/rdataclass.h>
43254885Sdumbbell#include <dns/rdataset.h>
44254885Sdumbbell#include <dns/rdatasetiter.h>
45254885Sdumbbell#include <dns/rdatastruct.h>
46254885Sdumbbell#include <dns/rdatatype.h>
47282199Sdumbbell#include <dns/soa.h>
48282199Sdumbbell#include <dns/ssu.h>
49282199Sdumbbell#include <dns/tsig.h>
50282199Sdumbbell#include <dns/view.h>
51282199Sdumbbell#include <dns/zone.h>
52282199Sdumbbell#include <dns/zt.h>
53282199Sdumbbell
54282199Sdumbbell#include <named/client.h>
55282199Sdumbbell#include <named/log.h>
56282199Sdumbbell#include <named/server.h>
57282199Sdumbbell#include <named/update.h>
58282199Sdumbbell
59282199Sdumbbell/*! \file
60282199Sdumbbell * \brief
61282199Sdumbbell * This module implements dynamic update as in RFC2136.
62282199Sdumbbell */
63282199Sdumbbell
64282199Sdumbbell/*
65282199Sdumbbell *  XXX TODO:
66282199Sdumbbell * - document strict minimality
67282199Sdumbbell */
68282199Sdumbbell
69282199Sdumbbell/**************************************************************************/
70282199Sdumbbell
71282199Sdumbbell/*%
72282199Sdumbbell * Log level for tracing dynamic update protocol requests.
73282199Sdumbbell */
74282199Sdumbbell#define LOGLEVEL_PROTOCOL	ISC_LOG_INFO
75282199Sdumbbell
76282199Sdumbbell/*%
77282199Sdumbbell * Log level for low-level debug tracing.
78254885Sdumbbell */
79254885Sdumbbell#define LOGLEVEL_DEBUG		ISC_LOG_DEBUG(8)
80254885Sdumbbell
81254885Sdumbbell/*%
82254885Sdumbbell * Check an operation for failure.  These macros all assume that
83254885Sdumbbell * the function using them has a 'result' variable and a 'failure'
84254885Sdumbbell * label.
85254885Sdumbbell */
86254885Sdumbbell#define CHECK(op) \
87254885Sdumbbell	do { result = (op); \
88254885Sdumbbell		if (result != ISC_R_SUCCESS) goto failure; \
89254885Sdumbbell	} while (0)
90254885Sdumbbell
91254885Sdumbbell/*%
92254885Sdumbbell * Fail unconditionally with result 'code', which must not
93254885Sdumbbell * be ISC_R_SUCCESS.  The reason for failure presumably has
94254885Sdumbbell * been logged already.
95254885Sdumbbell *
96254885Sdumbbell * The test against ISC_R_SUCCESS is there to keep the Solaris compiler
97254885Sdumbbell * from complaining about "end-of-loop code not reached".
98254885Sdumbbell */
99254885Sdumbbell
100254885Sdumbbell#define FAIL(code) \
101254885Sdumbbell	do {							\
102254885Sdumbbell		result = (code);				\
103254885Sdumbbell		if (result != ISC_R_SUCCESS) goto failure;	\
104254885Sdumbbell	} while (0)
105254885Sdumbbell
106254885Sdumbbell/*%
107254885Sdumbbell * Fail unconditionally and log as a client error.
108254885Sdumbbell * The test against ISC_R_SUCCESS is there to keep the Solaris compiler
109254885Sdumbbell * from complaining about "end-of-loop code not reached".
110254885Sdumbbell */
111254885Sdumbbell#define FAILC(code, msg) \
112254885Sdumbbell	do {							\
113254885Sdumbbell		const char *_what = "failed";			\
114254885Sdumbbell		result = (code);				\
115254885Sdumbbell		switch (result) {				\
116254885Sdumbbell		case DNS_R_NXDOMAIN:				\
117254885Sdumbbell		case DNS_R_YXDOMAIN:				\
118254885Sdumbbell		case DNS_R_YXRRSET:				\
119254885Sdumbbell		case DNS_R_NXRRSET:				\
120254885Sdumbbell			_what = "unsuccessful";			\
121254885Sdumbbell		}						\
122254885Sdumbbell		update_log(client, zone, LOGLEVEL_PROTOCOL,	\
123254885Sdumbbell			   "update %s: %s (%s)", _what,		\
124254885Sdumbbell			   msg, isc_result_totext(result));	\
125254885Sdumbbell		if (result != ISC_R_SUCCESS) goto failure;	\
126254885Sdumbbell	} while (0)
127254885Sdumbbell#define PREREQFAILC(code, msg) \
128254885Sdumbbell	do {							\
129254885Sdumbbell		inc_stats(zone, dns_nsstatscounter_updatebadprereq); \
130254885Sdumbbell		FAILC(code, msg);				\
131254885Sdumbbell	} while (0)
132254885Sdumbbell
133254885Sdumbbell#define FAILN(code, name, msg) \
134254885Sdumbbell	do {								\
135254885Sdumbbell		const char *_what = "failed";				\
136254885Sdumbbell		result = (code);					\
137254885Sdumbbell		switch (result) {					\
138254885Sdumbbell		case DNS_R_NXDOMAIN:					\
139254885Sdumbbell		case DNS_R_YXDOMAIN:					\
140254885Sdumbbell		case DNS_R_YXRRSET:					\
141254885Sdumbbell		case DNS_R_NXRRSET:					\
142254885Sdumbbell			_what = "unsuccessful";				\
143254885Sdumbbell		}							\
144254885Sdumbbell		if (isc_log_wouldlog(ns_g_lctx, LOGLEVEL_PROTOCOL)) {	\
145254885Sdumbbell			char _nbuf[DNS_NAME_FORMATSIZE];		\
146254885Sdumbbell			dns_name_format(name, _nbuf, sizeof(_nbuf));	\
147254885Sdumbbell			update_log(client, zone, LOGLEVEL_PROTOCOL,	\
148254885Sdumbbell				   "update %s: %s: %s (%s)", _what, _nbuf, \
149254885Sdumbbell				   msg, isc_result_totext(result));	\
150254885Sdumbbell		}							\
151254885Sdumbbell		if (result != ISC_R_SUCCESS) goto failure;		\
152254885Sdumbbell	} while (0)
153254885Sdumbbell#define PREREQFAILN(code, name, msg) \
154254885Sdumbbell	do {								\
155254885Sdumbbell		inc_stats(zone, dns_nsstatscounter_updatebadprereq); \
156254885Sdumbbell		FAILN(code, name, msg);					\
157254885Sdumbbell	} while (0)
158254885Sdumbbell
159254885Sdumbbell#define FAILNT(code, name, type, msg) \
160254885Sdumbbell	do {								\
161254885Sdumbbell		const char *_what = "failed";				\
162254885Sdumbbell		result = (code);					\
163254885Sdumbbell		switch (result) {					\
164254885Sdumbbell		case DNS_R_NXDOMAIN:					\
165254885Sdumbbell		case DNS_R_YXDOMAIN:					\
166254885Sdumbbell		case DNS_R_YXRRSET:					\
167254885Sdumbbell		case DNS_R_NXRRSET:					\
168254885Sdumbbell			_what = "unsuccessful";				\
169254885Sdumbbell		}							\
170254885Sdumbbell		if (isc_log_wouldlog(ns_g_lctx, LOGLEVEL_PROTOCOL)) {	\
171254885Sdumbbell			char _nbuf[DNS_NAME_FORMATSIZE];		\
172254885Sdumbbell			char _tbuf[DNS_RDATATYPE_FORMATSIZE];		\
173254885Sdumbbell			dns_name_format(name, _nbuf, sizeof(_nbuf));	\
174254885Sdumbbell			dns_rdatatype_format(type, _tbuf, sizeof(_tbuf)); \
175254885Sdumbbell			update_log(client, zone, LOGLEVEL_PROTOCOL,	\
176254885Sdumbbell				   "update %s: %s/%s: %s (%s)",		\
177254885Sdumbbell				   _what, _nbuf, _tbuf, msg,		\
178254885Sdumbbell				   isc_result_totext(result));		\
179254885Sdumbbell		}							\
180254885Sdumbbell		if (result != ISC_R_SUCCESS) goto failure;		\
181254885Sdumbbell	} while (0)
182254885Sdumbbell#define PREREQFAILNT(code, name, type, msg)				\
183254885Sdumbbell	do {								\
184254885Sdumbbell		inc_stats(zone, dns_nsstatscounter_updatebadprereq); \
185254885Sdumbbell		FAILNT(code, name, type, msg);				\
186254885Sdumbbell	} while (0)
187254885Sdumbbell
188254885Sdumbbell/*%
189254885Sdumbbell * Fail unconditionally and log as a server error.
190254885Sdumbbell * The test against ISC_R_SUCCESS is there to keep the Solaris compiler
191254885Sdumbbell * from complaining about "end-of-loop code not reached".
192254885Sdumbbell */
193254885Sdumbbell#define FAILS(code, msg) \
194254885Sdumbbell	do {							\
195254885Sdumbbell		result = (code);				\
196254885Sdumbbell		update_log(client, zone, LOGLEVEL_PROTOCOL,	\
197254885Sdumbbell			   "error: %s: %s",			\
198254885Sdumbbell			   msg, isc_result_totext(result));	\
199254885Sdumbbell		if (result != ISC_R_SUCCESS) goto failure;	\
200254885Sdumbbell	} while (0)
201254885Sdumbbell
202254885Sdumbbell/*
203254885Sdumbbell * Return TRUE if NS_CLIENTATTR_TCP is set in the attributes other FALSE.
204254885Sdumbbell */
205254885Sdumbbell#define TCPCLIENT(client) (((client)->attributes & NS_CLIENTATTR_TCP) != 0)
206254885Sdumbbell
207254885Sdumbbell/**************************************************************************/
208254885Sdumbbell
209254885Sdumbbelltypedef struct rr rr_t;
210254885Sdumbbell
211254885Sdumbbellstruct rr {
212254885Sdumbbell	/* dns_name_t name; */
213254885Sdumbbell	isc_uint32_t		ttl;
214254885Sdumbbell	dns_rdata_t		rdata;
215254885Sdumbbell};
216254885Sdumbbell
217254885Sdumbbelltypedef struct update_event update_event_t;
218254885Sdumbbell
219254885Sdumbbellstruct update_event {
220254885Sdumbbell	ISC_EVENT_COMMON(update_event_t);
221254885Sdumbbell	dns_zone_t		*zone;
222254885Sdumbbell	isc_result_t		result;
223254885Sdumbbell	dns_message_t		*answer;
224254885Sdumbbell};
225254885Sdumbbell
226254885Sdumbbell/**************************************************************************/
227254885Sdumbbell/*
228254885Sdumbbell * Forward declarations.
229254885Sdumbbell */
230254885Sdumbbell
231254885Sdumbbellstatic void update_action(isc_task_t *task, isc_event_t *event);
232254885Sdumbbellstatic void updatedone_action(isc_task_t *task, isc_event_t *event);
233254885Sdumbbellstatic isc_result_t send_forward_event(ns_client_t *client, dns_zone_t *zone);
234254885Sdumbbellstatic void forward_done(isc_task_t *task, isc_event_t *event);
235254885Sdumbbell
236254885Sdumbbell/**************************************************************************/
237254885Sdumbbell
238254885Sdumbbellstatic void
239254885Sdumbbellupdate_log(ns_client_t *client, dns_zone_t *zone,
240254885Sdumbbell	   int level, const char *fmt, ...) ISC_FORMAT_PRINTF(4, 5);
241254885Sdumbbell
242254885Sdumbbellstatic void
243254885Sdumbbellupdate_log(ns_client_t *client, dns_zone_t *zone,
244254885Sdumbbell	   int level, const char *fmt, ...)
245254885Sdumbbell{
246254885Sdumbbell	va_list ap;
247254885Sdumbbell	char message[4096];
248254885Sdumbbell	char namebuf[DNS_NAME_FORMATSIZE];
249254885Sdumbbell	char classbuf[DNS_RDATACLASS_FORMATSIZE];
250254885Sdumbbell
251254885Sdumbbell	if (client == NULL || zone == NULL)
252254885Sdumbbell		return;
253254885Sdumbbell
254254885Sdumbbell	if (isc_log_wouldlog(ns_g_lctx, level) == ISC_FALSE)
255254885Sdumbbell		return;
256254885Sdumbbell
257254885Sdumbbell	dns_name_format(dns_zone_getorigin(zone), namebuf,
258254885Sdumbbell			sizeof(namebuf));
259254885Sdumbbell	dns_rdataclass_format(dns_zone_getclass(zone), classbuf,
260254885Sdumbbell			      sizeof(classbuf));
261254885Sdumbbell
262254885Sdumbbell	va_start(ap, fmt);
263254885Sdumbbell	vsnprintf(message, sizeof(message), fmt, ap);
264254885Sdumbbell	va_end(ap);
265254885Sdumbbell
266254885Sdumbbell	ns_client_log(client, NS_LOGCATEGORY_UPDATE, NS_LOGMODULE_UPDATE,
267254885Sdumbbell		      level, "updating zone '%s/%s': %s",
268254885Sdumbbell		      namebuf, classbuf, message);
269254885Sdumbbell}
270254885Sdumbbell
271254885Sdumbbell/*%
272254885Sdumbbell * Increment updated-related statistics counters.
273254885Sdumbbell */
274254885Sdumbbellstatic inline void
275254885Sdumbbellinc_stats(dns_zone_t *zone, isc_statscounter_t counter) {
276254885Sdumbbell	isc_stats_increment(ns_g_server->nsstats, counter);
277254885Sdumbbell
278254885Sdumbbell	if (zone != NULL) {
279254885Sdumbbell		isc_stats_t *zonestats = dns_zone_getrequeststats(zone);
280254885Sdumbbell		if (zonestats != NULL)
281254885Sdumbbell			isc_stats_increment(zonestats, counter);
282254885Sdumbbell	}
283254885Sdumbbell}
284254885Sdumbbell
285254885Sdumbbell/*%
286254885Sdumbbell * Check if we could have queried for the contents of this zone or
287254885Sdumbbell * if the zone is potentially updateable.
288254885Sdumbbell * If the zone can potentially be updated and the check failed then
289254885Sdumbbell * log a error otherwise we log a informational message.
290254885Sdumbbell */
291254885Sdumbbellstatic isc_result_t
292254885Sdumbbellcheckqueryacl(ns_client_t *client, dns_acl_t *queryacl, dns_name_t *zonename,
293254885Sdumbbell	      dns_acl_t *updateacl, dns_ssutable_t *ssutable)
294254885Sdumbbell{
295254885Sdumbbell	char namebuf[DNS_NAME_FORMATSIZE];
296254885Sdumbbell	char classbuf[DNS_RDATACLASS_FORMATSIZE];
297254885Sdumbbell	int level;
298254885Sdumbbell	isc_result_t result;
299254885Sdumbbell
300254885Sdumbbell	result = ns_client_checkaclsilent(client, NULL, queryacl, ISC_TRUE);
301254885Sdumbbell	if (result != ISC_R_SUCCESS) {
302254885Sdumbbell		dns_name_format(zonename, namebuf, sizeof(namebuf));
303254885Sdumbbell		dns_rdataclass_format(client->view->rdclass, classbuf,
304254885Sdumbbell				      sizeof(classbuf));
305254885Sdumbbell
306254885Sdumbbell		level = (updateacl == NULL && ssutable == NULL) ?
307254885Sdumbbell				ISC_LOG_INFO : ISC_LOG_ERROR;
308254885Sdumbbell
309254885Sdumbbell		ns_client_log(client, NS_LOGCATEGORY_UPDATE_SECURITY,
310254885Sdumbbell			      NS_LOGMODULE_UPDATE, level,
311254885Sdumbbell			      "update '%s/%s' denied due to allow-query",
312254885Sdumbbell			      namebuf, classbuf);
313254885Sdumbbell	} else if (updateacl == NULL && ssutable == NULL) {
314254885Sdumbbell		dns_name_format(zonename, namebuf, sizeof(namebuf));
315254885Sdumbbell		dns_rdataclass_format(client->view->rdclass, classbuf,
316254885Sdumbbell				      sizeof(classbuf));
317254885Sdumbbell
318254885Sdumbbell		result = DNS_R_REFUSED;
319254885Sdumbbell		ns_client_log(client, NS_LOGCATEGORY_UPDATE_SECURITY,
320254885Sdumbbell			      NS_LOGMODULE_UPDATE, ISC_LOG_INFO,
321254885Sdumbbell			      "update '%s/%s' denied", namebuf, classbuf);
322254885Sdumbbell	}
323254885Sdumbbell	return (result);
324254885Sdumbbell}
325254885Sdumbbell
326254885Sdumbbell/*%
327254885Sdumbbell * Override the default acl logging when checking whether a client
328254885Sdumbbell * can update the zone or whether we can forward the request to the
329254885Sdumbbell * master based on IP address.
330254885Sdumbbell *
331254885Sdumbbell * 'message' contains the type of operation that is being attempted.
332254885Sdumbbell * 'slave' indicates if this is a slave zone.  If 'acl' is NULL then
333254885Sdumbbell * log at debug=3.
334254885Sdumbbell * If the zone has no access controls configured ('acl' == NULL &&
335254885Sdumbbell * 'has_ssutable == ISC_FALS) log the attempt at info, otherwise
336254885Sdumbbell * at error.
337254885Sdumbbell *
338254885Sdumbbell * If the request was signed log that we received it.
339254885Sdumbbell */
340254885Sdumbbellstatic isc_result_t
341254885Sdumbbellcheckupdateacl(ns_client_t *client, dns_acl_t *acl, const char *message,
342254885Sdumbbell	       dns_name_t *zonename, isc_boolean_t slave,
343254885Sdumbbell	       isc_boolean_t has_ssutable)
344254885Sdumbbell{
345254885Sdumbbell	char namebuf[DNS_NAME_FORMATSIZE];
346254885Sdumbbell	char classbuf[DNS_RDATACLASS_FORMATSIZE];
347254885Sdumbbell	int level = ISC_LOG_ERROR;
348254885Sdumbbell	const char *msg = "denied";
349254885Sdumbbell	isc_result_t result;
350254885Sdumbbell
351254885Sdumbbell	if (slave && acl == NULL) {
352254885Sdumbbell		result = DNS_R_NOTIMP;
353254885Sdumbbell		level = ISC_LOG_DEBUG(3);
354254885Sdumbbell		msg = "disabled";
355254885Sdumbbell	} else {
356254885Sdumbbell		result = ns_client_checkaclsilent(client, NULL, acl, ISC_FALSE);
357254885Sdumbbell		if (result == ISC_R_SUCCESS) {
358254885Sdumbbell			level = ISC_LOG_DEBUG(3);
359254885Sdumbbell			msg = "approved";
360254885Sdumbbell		} else if (acl == NULL && !has_ssutable) {
361254885Sdumbbell			level = ISC_LOG_INFO;
362254885Sdumbbell		}
363254885Sdumbbell	}
364254885Sdumbbell
365254885Sdumbbell	if (client->signer != NULL) {
366254885Sdumbbell		dns_name_format(client->signer, namebuf, sizeof(namebuf));
367254885Sdumbbell		ns_client_log(client, NS_LOGCATEGORY_UPDATE_SECURITY,
368254885Sdumbbell			      NS_LOGMODULE_UPDATE, ISC_LOG_INFO,
369254885Sdumbbell			      "signer \"%s\" %s", namebuf, msg);
370254885Sdumbbell	}
371254885Sdumbbell
372254885Sdumbbell	dns_name_format(zonename, namebuf, sizeof(namebuf));
373254885Sdumbbell	dns_rdataclass_format(client->view->rdclass, classbuf,
374254885Sdumbbell			      sizeof(classbuf));
375254885Sdumbbell
376254885Sdumbbell	ns_client_log(client, NS_LOGCATEGORY_UPDATE_SECURITY,
377254885Sdumbbell		      NS_LOGMODULE_UPDATE, level, "%s '%s/%s' %s",
378254885Sdumbbell		      message, namebuf, classbuf, msg);
379254885Sdumbbell	return (result);
380254885Sdumbbell}
381254885Sdumbbell
382254885Sdumbbell/*%
383254885Sdumbbell * Update a single RR in version 'ver' of 'db' and log the
384254885Sdumbbell * update in 'diff'.
385254885Sdumbbell *
386254885Sdumbbell * Ensures:
387254885Sdumbbell * \li	'*tuple' == NULL.  Either the tuple is freed, or its
388254885Sdumbbell *	ownership has been transferred to the diff.
389254885Sdumbbell */
390254885Sdumbbellstatic isc_result_t
391254885Sdumbbelldo_one_tuple(dns_difftuple_t **tuple, dns_db_t *db, dns_dbversion_t *ver,
392254885Sdumbbell	     dns_diff_t *diff)
393254885Sdumbbell{
394254885Sdumbbell	dns_diff_t temp_diff;
395254885Sdumbbell	isc_result_t result;
396254885Sdumbbell
397254885Sdumbbell	/*
398254885Sdumbbell	 * Create a singleton diff.
399254885Sdumbbell	 */
400254885Sdumbbell	dns_diff_init(diff->mctx, &temp_diff);
401254885Sdumbbell	temp_diff.resign = diff->resign;
402254885Sdumbbell	ISC_LIST_APPEND(temp_diff.tuples, *tuple, link);
403254885Sdumbbell
404254885Sdumbbell	/*
405254885Sdumbbell	 * Apply it to the database.
406254885Sdumbbell	 */
407254885Sdumbbell	result = dns_diff_apply(&temp_diff, db, ver);
408254885Sdumbbell	ISC_LIST_UNLINK(temp_diff.tuples, *tuple, link);
409254885Sdumbbell	if (result != ISC_R_SUCCESS) {
410254885Sdumbbell		dns_difftuple_free(tuple);
411254885Sdumbbell		return (result);
412254885Sdumbbell	}
413254885Sdumbbell
414254885Sdumbbell	/*
415254885Sdumbbell	 * Merge it into the current pending journal entry.
416254885Sdumbbell	 */
417254885Sdumbbell	dns_diff_appendminimal(diff, tuple);
418254885Sdumbbell
419254885Sdumbbell	/*
420254885Sdumbbell	 * Do not clear temp_diff.
421254885Sdumbbell	 */
422254885Sdumbbell	return (ISC_R_SUCCESS);
423254885Sdumbbell}
424254885Sdumbbell
425254885Sdumbbell/*%
426282199Sdumbbell * Perform the updates in 'updates' in version 'ver' of 'db' and log the
427254885Sdumbbell * update in 'diff'.
428254885Sdumbbell *
429254885Sdumbbell * Ensures:
430254885Sdumbbell * \li	'updates' is empty.
431254885Sdumbbell */
432254885Sdumbbellstatic isc_result_t
433254885Sdumbbelldo_diff(dns_diff_t *updates, dns_db_t *db, dns_dbversion_t *ver,
434254885Sdumbbell	dns_diff_t *diff)
435254885Sdumbbell{
436254885Sdumbbell	isc_result_t result;
437254885Sdumbbell	while (! ISC_LIST_EMPTY(updates->tuples)) {
438254885Sdumbbell		dns_difftuple_t *t = ISC_LIST_HEAD(updates->tuples);
439254885Sdumbbell		ISC_LIST_UNLINK(updates->tuples, t, link);
440254885Sdumbbell		CHECK(do_one_tuple(&t, db, ver, diff));
441254885Sdumbbell	}
442254885Sdumbbell	return (ISC_R_SUCCESS);
443254885Sdumbbell
444254885Sdumbbell failure:
445254885Sdumbbell	dns_diff_clear(diff);
446254885Sdumbbell	return (result);
447254885Sdumbbell}
448254885Sdumbbell
449254885Sdumbbellstatic isc_result_t
450254885Sdumbbellupdate_one_rr(dns_db_t *db, dns_dbversion_t *ver, dns_diff_t *diff,
451254885Sdumbbell	      dns_diffop_t op, dns_name_t *name, dns_ttl_t ttl,
452254885Sdumbbell	      dns_rdata_t *rdata)
453254885Sdumbbell{
454254885Sdumbbell	dns_difftuple_t *tuple = NULL;
455254885Sdumbbell	isc_result_t result;
456254885Sdumbbell	result = dns_difftuple_create(diff->mctx, op,
457254885Sdumbbell				      name, ttl, rdata, &tuple);
458254885Sdumbbell	if (result != ISC_R_SUCCESS)
459254885Sdumbbell		return (result);
460254885Sdumbbell	return (do_one_tuple(&tuple, db, ver, diff));
461254885Sdumbbell}
462254885Sdumbbell
463254885Sdumbbell/**************************************************************************/
464254885Sdumbbell/*
465254885Sdumbbell * Callback-style iteration over rdatasets and rdatas.
466254885Sdumbbell *
467254885Sdumbbell * foreach_rrset() can be used to iterate over the RRsets
468254885Sdumbbell * of a name and call a callback function with each
469254885Sdumbbell * one.  Similarly, foreach_rr() can be used to iterate
470254885Sdumbbell * over the individual RRs at name, optionally restricted
471254885Sdumbbell * to RRs of a given type.
472254885Sdumbbell *
473254885Sdumbbell * The callback functions are called "actions" and take
474254885Sdumbbell * two arguments: a void pointer for passing arbitrary
475254885Sdumbbell * context information, and a pointer to the current RRset
476254885Sdumbbell * or RR.  By convention, their names end in "_action".
477254885Sdumbbell */
478254885Sdumbbell
479254885Sdumbbell/*
480254885Sdumbbell * XXXRTH  We might want to make this public somewhere in libdns.
481254885Sdumbbell */
482254885Sdumbbell
483254885Sdumbbell/*%
484254885Sdumbbell * Function type for foreach_rrset() iterator actions.
485254885Sdumbbell */
486254885Sdumbbelltypedef isc_result_t rrset_func(void *data, dns_rdataset_t *rrset);
487254885Sdumbbell
488254885Sdumbbell/*%
489254885Sdumbbell * Function type for foreach_rr() iterator actions.
490254885Sdumbbell */
491254885Sdumbbelltypedef isc_result_t rr_func(void *data, rr_t *rr);
492254885Sdumbbell
493254885Sdumbbell/*%
494254885Sdumbbell * Internal context struct for foreach_node_rr().
495254885Sdumbbell */
496254885Sdumbbelltypedef struct {
497254885Sdumbbell	rr_func *	rr_action;
498254885Sdumbbell	void *		rr_action_data;
499254885Sdumbbell} foreach_node_rr_ctx_t;
500254885Sdumbbell
501254885Sdumbbell/*%
502254885Sdumbbell * Internal helper function for foreach_node_rr().
503254885Sdumbbell */
504254885Sdumbbellstatic isc_result_t
505254885Sdumbbellforeach_node_rr_action(void *data, dns_rdataset_t *rdataset) {
506254885Sdumbbell	isc_result_t result;
507254885Sdumbbell	foreach_node_rr_ctx_t *ctx = data;
508254885Sdumbbell	for (result = dns_rdataset_first(rdataset);
509254885Sdumbbell	     result == ISC_R_SUCCESS;
510254885Sdumbbell	     result = dns_rdataset_next(rdataset))
511254885Sdumbbell	{
512254885Sdumbbell		rr_t rr = { 0, DNS_RDATA_INIT };
513254885Sdumbbell
514254885Sdumbbell		dns_rdataset_current(rdataset, &rr.rdata);
515254885Sdumbbell		rr.ttl = rdataset->ttl;
516254885Sdumbbell		result = (*ctx->rr_action)(ctx->rr_action_data, &rr);
517254885Sdumbbell		if (result != ISC_R_SUCCESS)
518254885Sdumbbell			return (result);
519282199Sdumbbell	}
520254885Sdumbbell	if (result != ISC_R_NOMORE)
521254885Sdumbbell		return (result);
522254885Sdumbbell	return (ISC_R_SUCCESS);
523254885Sdumbbell}
524254885Sdumbbell
525254885Sdumbbell/*%
526254885Sdumbbell * For each rdataset of 'name' in 'ver' of 'db', call 'action'
527254885Sdumbbell * with the rdataset and 'action_data' as arguments.  If the name
528254885Sdumbbell * does not exist, do nothing.
529254885Sdumbbell *
530254885Sdumbbell * If 'action' returns an error, abort iteration and return the error.
531254885Sdumbbell */
532254885Sdumbbellstatic isc_result_t
533254885Sdumbbellforeach_rrset(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
534254885Sdumbbell	      rrset_func *action, void *action_data)
535254885Sdumbbell{
536254885Sdumbbell	isc_result_t result;
537254885Sdumbbell	dns_dbnode_t *node;
538254885Sdumbbell	dns_rdatasetiter_t *iter;
539254885Sdumbbell
540254885Sdumbbell	node = NULL;
541254885Sdumbbell	result = dns_db_findnode(db, name, ISC_FALSE, &node);
542254885Sdumbbell	if (result == ISC_R_NOTFOUND)
543254885Sdumbbell		return (ISC_R_SUCCESS);
544254885Sdumbbell	if (result != ISC_R_SUCCESS)
545254885Sdumbbell		return (result);
546254885Sdumbbell
547254885Sdumbbell	iter = NULL;
548254885Sdumbbell	result = dns_db_allrdatasets(db, node, ver,
549254885Sdumbbell				     (isc_stdtime_t) 0, &iter);
550254885Sdumbbell	if (result != ISC_R_SUCCESS)
551254885Sdumbbell		goto cleanup_node;
552254885Sdumbbell
553254885Sdumbbell	for (result = dns_rdatasetiter_first(iter);
554254885Sdumbbell	     result == ISC_R_SUCCESS;
555254885Sdumbbell	     result = dns_rdatasetiter_next(iter))
556254885Sdumbbell	{
557254885Sdumbbell		dns_rdataset_t rdataset;
558254885Sdumbbell
559254885Sdumbbell		dns_rdataset_init(&rdataset);
560254885Sdumbbell		dns_rdatasetiter_current(iter, &rdataset);
561254885Sdumbbell
562254885Sdumbbell		result = (*action)(action_data, &rdataset);
563254885Sdumbbell
564254885Sdumbbell		dns_rdataset_disassociate(&rdataset);
565254885Sdumbbell		if (result != ISC_R_SUCCESS)
566254885Sdumbbell			goto cleanup_iterator;
567254885Sdumbbell	}
568254885Sdumbbell	if (result == ISC_R_NOMORE)
569254885Sdumbbell		result = ISC_R_SUCCESS;
570254885Sdumbbell
571254885Sdumbbell cleanup_iterator:
572254885Sdumbbell	dns_rdatasetiter_destroy(&iter);
573254885Sdumbbell
574254885Sdumbbell cleanup_node:
575254885Sdumbbell	dns_db_detachnode(db, &node);
576254885Sdumbbell
577254885Sdumbbell	return (result);
578254885Sdumbbell}
579254885Sdumbbell
580254885Sdumbbell/*%
581254885Sdumbbell * For each RR of 'name' in 'ver' of 'db', call 'action'
582254885Sdumbbell * with the RR and 'action_data' as arguments.  If the name
583254885Sdumbbell * does not exist, do nothing.
584254885Sdumbbell *
585254885Sdumbbell * If 'action' returns an error, abort iteration
586254885Sdumbbell * and return the error.
587254885Sdumbbell */
588254885Sdumbbellstatic isc_result_t
589254885Sdumbbellforeach_node_rr(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
590254885Sdumbbell		rr_func *rr_action, void *rr_action_data)
591254885Sdumbbell{
592254885Sdumbbell	foreach_node_rr_ctx_t ctx;
593254885Sdumbbell	ctx.rr_action = rr_action;
594254885Sdumbbell	ctx.rr_action_data = rr_action_data;
595254885Sdumbbell	return (foreach_rrset(db, ver, name,
596254885Sdumbbell			      foreach_node_rr_action, &ctx));
597254885Sdumbbell}
598254885Sdumbbell
599254885Sdumbbell
600254885Sdumbbell/*%
601254885Sdumbbell * For each of the RRs specified by 'db', 'ver', 'name', 'type',
602254885Sdumbbell * (which can be dns_rdatatype_any to match any type), and 'covers', call
603254885Sdumbbell * 'action' with the RR and 'action_data' as arguments. If the name
604254885Sdumbbell * does not exist, or if no RRset of the given type exists at the name,
605254885Sdumbbell * do nothing.
606254885Sdumbbell *
607254885Sdumbbell * If 'action' returns an error, abort iteration and return the error.
608254885Sdumbbell */
609254885Sdumbbellstatic isc_result_t
610254885Sdumbbellforeach_rr(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
611254885Sdumbbell	   dns_rdatatype_t type, dns_rdatatype_t covers, rr_func *rr_action,
612254885Sdumbbell	   void *rr_action_data)
613254885Sdumbbell{
614254885Sdumbbell
615254885Sdumbbell	isc_result_t result;
616254885Sdumbbell	dns_dbnode_t *node;
617254885Sdumbbell	dns_rdataset_t rdataset;
618254885Sdumbbell
619254885Sdumbbell	if (type == dns_rdatatype_any)
620254885Sdumbbell		return (foreach_node_rr(db, ver, name,
621254885Sdumbbell					rr_action, rr_action_data));
622254885Sdumbbell
623254885Sdumbbell	node = NULL;
624254885Sdumbbell	if (type == dns_rdatatype_nsec3 ||
625254885Sdumbbell	    (type == dns_rdatatype_rrsig && covers == dns_rdatatype_nsec3))
626254885Sdumbbell		result = dns_db_findnsec3node(db, name, ISC_FALSE, &node);
627254885Sdumbbell	else
628254885Sdumbbell		result = dns_db_findnode(db, name, ISC_FALSE, &node);
629254885Sdumbbell	if (result == ISC_R_NOTFOUND)
630254885Sdumbbell		return (ISC_R_SUCCESS);
631254885Sdumbbell	if (result != ISC_R_SUCCESS)
632254885Sdumbbell		return (result);
633254885Sdumbbell
634254885Sdumbbell	dns_rdataset_init(&rdataset);
635254885Sdumbbell	result = dns_db_findrdataset(db, node, ver, type, covers,
636254885Sdumbbell				     (isc_stdtime_t) 0, &rdataset, NULL);
637254885Sdumbbell	if (result == ISC_R_NOTFOUND) {
638254885Sdumbbell		result = ISC_R_SUCCESS;
639254885Sdumbbell		goto cleanup_node;
640254885Sdumbbell	}
641254885Sdumbbell	if (result != ISC_R_SUCCESS)
642254885Sdumbbell		goto cleanup_node;
643254885Sdumbbell
644254885Sdumbbell	for (result = dns_rdataset_first(&rdataset);
645254885Sdumbbell	     result == ISC_R_SUCCESS;
646254885Sdumbbell	     result = dns_rdataset_next(&rdataset))
647254885Sdumbbell	{
648254885Sdumbbell		rr_t rr = { 0, DNS_RDATA_INIT };
649254885Sdumbbell		dns_rdataset_current(&rdataset, &rr.rdata);
650254885Sdumbbell		rr.ttl = rdataset.ttl;
651254885Sdumbbell		result = (*rr_action)(rr_action_data, &rr);
652254885Sdumbbell		if (result != ISC_R_SUCCESS)
653254885Sdumbbell			goto cleanup_rdataset;
654254885Sdumbbell	}
655254885Sdumbbell	if (result != ISC_R_NOMORE)
656254885Sdumbbell		goto cleanup_rdataset;
657254885Sdumbbell	result = ISC_R_SUCCESS;
658254885Sdumbbell
659254885Sdumbbell cleanup_rdataset:
660254885Sdumbbell	dns_rdataset_disassociate(&rdataset);
661254885Sdumbbell cleanup_node:
662254885Sdumbbell	dns_db_detachnode(db, &node);
663254885Sdumbbell
664254885Sdumbbell	return (result);
665254885Sdumbbell}
666254885Sdumbbell
667254885Sdumbbell/**************************************************************************/
668254885Sdumbbell/*
669254885Sdumbbell * Various tests on the database contents (for prerequisites, etc).
670254885Sdumbbell */
671254885Sdumbbell
672254885Sdumbbell/*%
673254885Sdumbbell * Function type for predicate functions that compare a database RR 'db_rr'
674254885Sdumbbell * against an update RR 'update_rr'.
675254885Sdumbbell */
676254885Sdumbbelltypedef isc_boolean_t rr_predicate(dns_rdata_t *update_rr, dns_rdata_t *db_rr);
677254885Sdumbbell
678254885Sdumbbell/*%
679254885Sdumbbell * Helper function for rrset_exists().
680254885Sdumbbell */
681254885Sdumbbellstatic isc_result_t
682254885Sdumbbellrrset_exists_action(void *data, rr_t *rr) {
683254885Sdumbbell	UNUSED(data);
684254885Sdumbbell	UNUSED(rr);
685254885Sdumbbell	return (ISC_R_EXISTS);
686254885Sdumbbell}
687254885Sdumbbell
688254885Sdumbbell/*%
689254885Sdumbbell * Utility macro for RR existence checking functions.
690254885Sdumbbell *
691254885Sdumbbell * If the variable 'result' has the value ISC_R_EXISTS or
692254885Sdumbbell * ISC_R_SUCCESS, set *exists to ISC_TRUE or ISC_FALSE,
693254885Sdumbbell * respectively, and return success.
694254885Sdumbbell *
695254885Sdumbbell * If 'result' has any other value, there was a failure.
696254885Sdumbbell * Return the failure result code and do not set *exists.
697254885Sdumbbell *
698254885Sdumbbell * This would be more readable as "do { if ... } while(0)",
699254885Sdumbbell * but that form generates tons of warnings on Solaris 2.6.
700254885Sdumbbell */
701254885Sdumbbell#define RETURN_EXISTENCE_FLAG				\
702254885Sdumbbell	return ((result == ISC_R_EXISTS) ?		\
703254885Sdumbbell		(*exists = ISC_TRUE, ISC_R_SUCCESS) :	\
704254885Sdumbbell		((result == ISC_R_SUCCESS) ?		\
705254885Sdumbbell		 (*exists = ISC_FALSE, ISC_R_SUCCESS) :	\
706254885Sdumbbell		 result))
707254885Sdumbbell
708254885Sdumbbell/*%
709254885Sdumbbell * Set '*exists' to true iff an rrset of the given type exists,
710254885Sdumbbell * to false otherwise.
711254885Sdumbbell */
712254885Sdumbbellstatic isc_result_t
713254885Sdumbbellrrset_exists(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
714254885Sdumbbell	     dns_rdatatype_t type, dns_rdatatype_t covers,
715254885Sdumbbell	     isc_boolean_t *exists)
716254885Sdumbbell{
717254885Sdumbbell	isc_result_t result;
718254885Sdumbbell	result = foreach_rr(db, ver, name, type, covers,
719254885Sdumbbell			    rrset_exists_action, NULL);
720254885Sdumbbell	RETURN_EXISTENCE_FLAG;
721254885Sdumbbell}
722254885Sdumbbell
723254885Sdumbbell/*%
724254885Sdumbbell * Set '*visible' to true if the RRset exists and is part of the
725254885Sdumbbell * visible zone.  Otherwise '*visible' is set to false unless a
726254885Sdumbbell * error occurs.
727254885Sdumbbell */
728254885Sdumbbellstatic isc_result_t
729254885Sdumbbellrrset_visible(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
730254885Sdumbbell	      dns_rdatatype_t type, isc_boolean_t *visible)
731254885Sdumbbell{
732254885Sdumbbell	isc_result_t result;
733254885Sdumbbell	dns_fixedname_t fixed;
734254885Sdumbbell
735254885Sdumbbell	dns_fixedname_init(&fixed);
736254885Sdumbbell	result = dns_db_find(db, name, ver, type, DNS_DBFIND_NOWILD,
737254885Sdumbbell			     (isc_stdtime_t) 0, NULL,
738254885Sdumbbell			     dns_fixedname_name(&fixed), NULL, NULL);
739254885Sdumbbell	switch (result) {
740254885Sdumbbell	case ISC_R_SUCCESS:
741254885Sdumbbell		*visible = ISC_TRUE;
742254885Sdumbbell		break;
743254885Sdumbbell	/*
744254885Sdumbbell	 * Glue, obscured, deleted or replaced records.
745254885Sdumbbell	 */
746254885Sdumbbell	case DNS_R_DELEGATION:
747254885Sdumbbell	case DNS_R_DNAME:
748254885Sdumbbell	case DNS_R_CNAME:
749254885Sdumbbell	case DNS_R_NXDOMAIN:
750254885Sdumbbell	case DNS_R_NXRRSET:
751254885Sdumbbell	case DNS_R_EMPTYNAME:
752254885Sdumbbell	case DNS_R_COVERINGNSEC:
753254885Sdumbbell		*visible = ISC_FALSE;
754254885Sdumbbell		result = ISC_R_SUCCESS;
755254885Sdumbbell		break;
756254885Sdumbbell	default:
757254885Sdumbbell		break;
758254885Sdumbbell	}
759254885Sdumbbell	return (result);
760254885Sdumbbell}
761254885Sdumbbell
762254885Sdumbbell/*%
763254885Sdumbbell * Helper function for cname_incompatible_rrset_exists.
764254885Sdumbbell */
765254885Sdumbbellstatic isc_result_t
766254885Sdumbbellcname_compatibility_action(void *data, dns_rdataset_t *rrset) {
767254885Sdumbbell	UNUSED(data);
768254885Sdumbbell	if (rrset->type != dns_rdatatype_cname &&
769254885Sdumbbell	    ! dns_rdatatype_isdnssec(rrset->type))
770254885Sdumbbell		return (ISC_R_EXISTS);
771254885Sdumbbell	return (ISC_R_SUCCESS);
772254885Sdumbbell}
773254885Sdumbbell
774254885Sdumbbell/*%
775254885Sdumbbell * Check whether there is an rrset incompatible with adding a CNAME RR,
776254885Sdumbbell * i.e., anything but another CNAME (which can be replaced) or a
777254885Sdumbbell * DNSSEC RR (which can coexist).
778254885Sdumbbell *
779254885Sdumbbell * If such an incompatible rrset exists, set '*exists' to ISC_TRUE.
780254885Sdumbbell * Otherwise, set it to ISC_FALSE.
781254885Sdumbbell */
782254885Sdumbbellstatic isc_result_t
783254885Sdumbbellcname_incompatible_rrset_exists(dns_db_t *db, dns_dbversion_t *ver,
784254885Sdumbbell				dns_name_t *name, isc_boolean_t *exists) {
785254885Sdumbbell	isc_result_t result;
786254885Sdumbbell	result = foreach_rrset(db, ver, name,
787254885Sdumbbell			       cname_compatibility_action, NULL);
788254885Sdumbbell	RETURN_EXISTENCE_FLAG;
789254885Sdumbbell}
790254885Sdumbbell
791254885Sdumbbell/*%
792254885Sdumbbell * Helper function for rr_count().
793254885Sdumbbell */
794254885Sdumbbellstatic isc_result_t
795254885Sdumbbellcount_rr_action(void *data, rr_t *rr) {
796254885Sdumbbell	int *countp = data;
797254885Sdumbbell	UNUSED(rr);
798254885Sdumbbell	(*countp)++;
799254885Sdumbbell	return (ISC_R_SUCCESS);
800254885Sdumbbell}
801254885Sdumbbell
802254885Sdumbbell/*%
803254885Sdumbbell * Count the number of RRs of 'type' belonging to 'name' in 'ver' of 'db'.
804254885Sdumbbell */
805254885Sdumbbellstatic isc_result_t
806254885Sdumbbellrr_count(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
807254885Sdumbbell	 dns_rdatatype_t type, dns_rdatatype_t covers, int *countp)
808254885Sdumbbell{
809254885Sdumbbell	*countp = 0;
810254885Sdumbbell	return (foreach_rr(db, ver, name, type, covers,
811254885Sdumbbell			   count_rr_action, countp));
812254885Sdumbbell}
813254885Sdumbbell
814254885Sdumbbell/*%
815254885Sdumbbell * Context struct and helper function for name_exists().
816254885Sdumbbell */
817254885Sdumbbell
818254885Sdumbbellstatic isc_result_t
819254885Sdumbbellname_exists_action(void *data, dns_rdataset_t *rrset) {
820254885Sdumbbell	UNUSED(data);
821254885Sdumbbell	UNUSED(rrset);
822254885Sdumbbell	return (ISC_R_EXISTS);
823254885Sdumbbell}
824254885Sdumbbell
825254885Sdumbbell/*%
826254885Sdumbbell * Set '*exists' to true iff the given name exists, to false otherwise.
827254885Sdumbbell */
828254885Sdumbbellstatic isc_result_t
829254885Sdumbbellname_exists(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
830254885Sdumbbell	    isc_boolean_t *exists)
831254885Sdumbbell{
832254885Sdumbbell	isc_result_t result;
833254885Sdumbbell	result = foreach_rrset(db, ver, name,
834254885Sdumbbell			       name_exists_action, NULL);
835254885Sdumbbell	RETURN_EXISTENCE_FLAG;
836254885Sdumbbell}
837254885Sdumbbell
838254885Sdumbbell/*
839254885Sdumbbell *	'ssu_check_t' is used to pass the arguments to
840254885Sdumbbell *	dns_ssutable_checkrules() to the callback function
841254885Sdumbbell *	ssu_checkrule().
842254885Sdumbbell */
843254885Sdumbbelltypedef struct {
844254885Sdumbbell	/* The ownername of the record to be updated. */
845254885Sdumbbell	dns_name_t *name;
846254885Sdumbbell
847254885Sdumbbell	/* The signature's name if the request was signed. */
848254885Sdumbbell	dns_name_t *signer;
849254885Sdumbbell
850254885Sdumbbell	/* The address of the client if the request was received via TCP. */
851254885Sdumbbell	isc_netaddr_t *tcpaddr;
852254885Sdumbbell
853254885Sdumbbell	/* The ssu table to check against. */
854254885Sdumbbell	dns_ssutable_t *table;
855254885Sdumbbell
856254885Sdumbbell	/* the key used for TKEY requests */
857254885Sdumbbell	dst_key_t *key;
858254885Sdumbbell} ssu_check_t;
859254885Sdumbbell
860254885Sdumbbellstatic isc_result_t
861254885Sdumbbellssu_checkrule(void *data, dns_rdataset_t *rrset) {
862254885Sdumbbell	ssu_check_t *ssuinfo = data;
863254885Sdumbbell	isc_boolean_t result;
864254885Sdumbbell
865254885Sdumbbell	/*
866254885Sdumbbell	 * If we're deleting all records, it's ok to delete RRSIG and NSEC even
867254885Sdumbbell	 * if we're normally not allowed to.
868254885Sdumbbell	 */
869254885Sdumbbell	if (rrset->type == dns_rdatatype_rrsig ||
870254885Sdumbbell	    rrset->type == dns_rdatatype_nsec)
871254885Sdumbbell		return (ISC_R_SUCCESS);
872254885Sdumbbell	result = dns_ssutable_checkrules(ssuinfo->table, ssuinfo->signer,
873254885Sdumbbell					 ssuinfo->name, ssuinfo->tcpaddr,
874254885Sdumbbell					 rrset->type, ssuinfo->key);
875254885Sdumbbell	return (result == ISC_TRUE ? ISC_R_SUCCESS : ISC_R_FAILURE);
876254885Sdumbbell}
877254885Sdumbbell
878254885Sdumbbellstatic isc_boolean_t
879254885Sdumbbellssu_checkall(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
880254885Sdumbbell	     dns_ssutable_t *ssutable, dns_name_t *signer,
881254885Sdumbbell	     isc_netaddr_t *tcpaddr, dst_key_t *key)
882254885Sdumbbell{
883254885Sdumbbell	isc_result_t result;
884254885Sdumbbell	ssu_check_t ssuinfo;
885254885Sdumbbell
886254885Sdumbbell	ssuinfo.name = name;
887254885Sdumbbell	ssuinfo.table = ssutable;
888254885Sdumbbell	ssuinfo.signer = signer;
889254885Sdumbbell	ssuinfo.tcpaddr = tcpaddr;
890254885Sdumbbell	ssuinfo.key = key;
891254885Sdumbbell	result = foreach_rrset(db, ver, name, ssu_checkrule, &ssuinfo);
892254885Sdumbbell	return (ISC_TF(result == ISC_R_SUCCESS));
893254885Sdumbbell}
894254885Sdumbbell
895254885Sdumbbell/**************************************************************************/
896254885Sdumbbell/*
897254885Sdumbbell * Checking of "RRset exists (value dependent)" prerequisites.
898254885Sdumbbell *
899254885Sdumbbell * In the RFC2136 section 3.2.5, this is the pseudocode involving
900254885Sdumbbell * a variable called "temp", a mapping of <name, type> tuples to rrsets.
901254885Sdumbbell *
902254885Sdumbbell * Here, we represent the "temp" data structure as (non-minimal) "dns_diff_t"
903254885Sdumbbell * where each tuple has op==DNS_DIFFOP_EXISTS.
904254885Sdumbbell */
905254885Sdumbbell
906254885Sdumbbell
907254885Sdumbbell/*%
908254885Sdumbbell * Append a tuple asserting the existence of the RR with
909254885Sdumbbell * 'name' and 'rdata' to 'diff'.
910254885Sdumbbell */
911254885Sdumbbellstatic isc_result_t
912254885Sdumbbelltemp_append(dns_diff_t *diff, dns_name_t *name, dns_rdata_t *rdata) {
913254885Sdumbbell	isc_result_t result;
914254885Sdumbbell	dns_difftuple_t *tuple = NULL;
915254885Sdumbbell
916254885Sdumbbell	REQUIRE(DNS_DIFF_VALID(diff));
917254885Sdumbbell	CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_EXISTS,
918254885Sdumbbell				   name, 0, rdata, &tuple));
919254885Sdumbbell	ISC_LIST_APPEND(diff->tuples, tuple, link);
920254885Sdumbbell failure:
921254885Sdumbbell	return (result);
922254885Sdumbbell}
923254885Sdumbbell
924254885Sdumbbell/*%
925254885Sdumbbell * Compare two rdatasets represented as sorted lists of tuples.
926254885Sdumbbell * All list elements must have the same owner name and type.
927254885Sdumbbell * Return ISC_R_SUCCESS if the rdatasets are equal, rcode(dns_rcode_nxrrset)
928254885Sdumbbell * if not.
929254885Sdumbbell */
930254885Sdumbbellstatic isc_result_t
931254885Sdumbbelltemp_check_rrset(dns_difftuple_t *a, dns_difftuple_t *b) {
932254885Sdumbbell	for (;;) {
933254885Sdumbbell		if (a == NULL || b == NULL)
934254885Sdumbbell			break;
935254885Sdumbbell		INSIST(a->op == DNS_DIFFOP_EXISTS &&
936254885Sdumbbell		       b->op == DNS_DIFFOP_EXISTS);
937254885Sdumbbell		INSIST(a->rdata.type == b->rdata.type);
938254885Sdumbbell		INSIST(dns_name_equal(&a->name, &b->name));
939254885Sdumbbell		if (dns_rdata_casecompare(&a->rdata, &b->rdata) != 0)
940254885Sdumbbell			return (DNS_R_NXRRSET);
941254885Sdumbbell		a = ISC_LIST_NEXT(a, link);
942254885Sdumbbell		b = ISC_LIST_NEXT(b, link);
943254885Sdumbbell	}
944254885Sdumbbell	if (a != NULL || b != NULL)
945254885Sdumbbell		return (DNS_R_NXRRSET);
946254885Sdumbbell	return (ISC_R_SUCCESS);
947254885Sdumbbell}
948254885Sdumbbell
949254885Sdumbbell/*%
950254885Sdumbbell * A comparison function defining the sorting order for the entries
951254885Sdumbbell * in the "temp" data structure.  The major sort key is the owner name,
952254885Sdumbbell * followed by the type and rdata.
953254885Sdumbbell */
954254885Sdumbbellstatic int
955254885Sdumbbelltemp_order(const void *av, const void *bv) {
956254885Sdumbbell	dns_difftuple_t const * const *ap = av;
957254885Sdumbbell	dns_difftuple_t const * const *bp = bv;
958254885Sdumbbell	dns_difftuple_t const *a = *ap;
959254885Sdumbbell	dns_difftuple_t const *b = *bp;
960254885Sdumbbell	int r;
961254885Sdumbbell	r = dns_name_compare(&a->name, &b->name);
962254885Sdumbbell	if (r != 0)
963254885Sdumbbell		return (r);
964254885Sdumbbell	r = (b->rdata.type - a->rdata.type);
965254885Sdumbbell	if (r != 0)
966254885Sdumbbell		return (r);
967254885Sdumbbell	r = dns_rdata_casecompare(&a->rdata, &b->rdata);
968254885Sdumbbell	return (r);
969254885Sdumbbell}
970254885Sdumbbell
971254885Sdumbbell/*%
972254885Sdumbbell * Check the "RRset exists (value dependent)" prerequisite information
973254885Sdumbbell * in 'temp' against the contents of the database 'db'.
974254885Sdumbbell *
975254885Sdumbbell * Return ISC_R_SUCCESS if the prerequisites are satisfied,
976254885Sdumbbell * rcode(dns_rcode_nxrrset) if not.
977254885Sdumbbell *
978254885Sdumbbell * 'temp' must be pre-sorted.
979254885Sdumbbell */
980254885Sdumbbell
981254885Sdumbbellstatic isc_result_t
982254885Sdumbbelltemp_check(isc_mem_t *mctx, dns_diff_t *temp, dns_db_t *db,
983254885Sdumbbell	   dns_dbversion_t *ver, dns_name_t *tmpname, dns_rdatatype_t *typep)
984254885Sdumbbell{
985254885Sdumbbell	isc_result_t result;
986254885Sdumbbell	dns_name_t *name;
987254885Sdumbbell	dns_dbnode_t *node;
988254885Sdumbbell	dns_difftuple_t *t;
989254885Sdumbbell	dns_diff_t trash;
990254885Sdumbbell
991254885Sdumbbell	dns_diff_init(mctx, &trash);
992254885Sdumbbell
993254885Sdumbbell	/*
994254885Sdumbbell	 * For each name and type in the prerequisites,
995254885Sdumbbell	 * construct a sorted rdata list of the corresponding
996254885Sdumbbell	 * database contents, and compare the lists.
997254885Sdumbbell	 */
998254885Sdumbbell	t = ISC_LIST_HEAD(temp->tuples);
999254885Sdumbbell	while (t != NULL) {
1000254885Sdumbbell		name = &t->name;
1001254885Sdumbbell		(void)dns_name_copy(name, tmpname, NULL);
1002254885Sdumbbell		*typep = t->rdata.type;
1003254885Sdumbbell
1004254885Sdumbbell		/* A new unique name begins here. */
1005254885Sdumbbell		node = NULL;
1006254885Sdumbbell		result = dns_db_findnode(db, name, ISC_FALSE, &node);
1007254885Sdumbbell		if (result == ISC_R_NOTFOUND) {
1008254885Sdumbbell			dns_diff_clear(&trash);
1009254885Sdumbbell			return (DNS_R_NXRRSET);
1010254885Sdumbbell		}
1011254885Sdumbbell		if (result != ISC_R_SUCCESS) {
1012254885Sdumbbell			dns_diff_clear(&trash);
1013254885Sdumbbell			return (result);
1014254885Sdumbbell		}
1015254885Sdumbbell
1016254885Sdumbbell		/* A new unique type begins here. */
1017254885Sdumbbell		while (t != NULL && dns_name_equal(&t->name, name)) {
1018254885Sdumbbell			dns_rdatatype_t type, covers;
1019254885Sdumbbell			dns_rdataset_t rdataset;
1020254885Sdumbbell			dns_diff_t d_rrs; /* Database RRs with
1021254885Sdumbbell						this name and type */
1022254885Sdumbbell			dns_diff_t u_rrs; /* Update RRs with
1023254885Sdumbbell						this name and type */
1024254885Sdumbbell
1025254885Sdumbbell			*typep = type = t->rdata.type;
1026254885Sdumbbell			if (type == dns_rdatatype_rrsig ||
1027254885Sdumbbell			    type == dns_rdatatype_sig)
1028254885Sdumbbell				covers = dns_rdata_covers(&t->rdata);
1029254885Sdumbbell			else if (type == dns_rdatatype_any) {
1030254885Sdumbbell				dns_db_detachnode(db, &node);
1031254885Sdumbbell				dns_diff_clear(&trash);
1032254885Sdumbbell				return (DNS_R_NXRRSET);
1033254885Sdumbbell			} else
1034254885Sdumbbell				covers = 0;
1035254885Sdumbbell
1036254885Sdumbbell			/*
1037254885Sdumbbell			 * Collect all database RRs for this name and type
1038254885Sdumbbell			 * onto d_rrs and sort them.
1039254885Sdumbbell			 */
1040254885Sdumbbell			dns_rdataset_init(&rdataset);
1041254885Sdumbbell			result = dns_db_findrdataset(db, node, ver, type,
1042254885Sdumbbell						     covers, (isc_stdtime_t) 0,
1043254885Sdumbbell						     &rdataset, NULL);
1044254885Sdumbbell			if (result != ISC_R_SUCCESS) {
1045254885Sdumbbell				dns_db_detachnode(db, &node);
1046254885Sdumbbell				dns_diff_clear(&trash);
1047254885Sdumbbell				return (DNS_R_NXRRSET);
1048254885Sdumbbell			}
1049254885Sdumbbell
1050254885Sdumbbell			dns_diff_init(mctx, &d_rrs);
1051254885Sdumbbell			dns_diff_init(mctx, &u_rrs);
1052254885Sdumbbell
1053254885Sdumbbell			for (result = dns_rdataset_first(&rdataset);
1054254885Sdumbbell			     result == ISC_R_SUCCESS;
1055254885Sdumbbell			     result = dns_rdataset_next(&rdataset))
1056254885Sdumbbell			{
1057254885Sdumbbell				dns_rdata_t rdata = DNS_RDATA_INIT;
1058254885Sdumbbell				dns_rdataset_current(&rdataset, &rdata);
1059254885Sdumbbell				result = temp_append(&d_rrs, name, &rdata);
1060254885Sdumbbell				if (result != ISC_R_SUCCESS)
1061254885Sdumbbell					goto failure;
1062254885Sdumbbell			}
1063254885Sdumbbell			if (result != ISC_R_NOMORE)
1064254885Sdumbbell				goto failure;
1065254885Sdumbbell			result = dns_diff_sort(&d_rrs, temp_order);
1066254885Sdumbbell			if (result != ISC_R_SUCCESS)
1067254885Sdumbbell				goto failure;
1068254885Sdumbbell
1069254885Sdumbbell			/*
1070254885Sdumbbell			 * Collect all update RRs for this name and type
1071254885Sdumbbell			 * onto u_rrs.  No need to sort them here -
1072254885Sdumbbell			 * they are already sorted.
1073254885Sdumbbell			 */
1074254885Sdumbbell			while (t != NULL &&
1075254885Sdumbbell			       dns_name_equal(&t->name, name) &&
1076254885Sdumbbell			       t->rdata.type == type)
1077254885Sdumbbell			{
1078254885Sdumbbell				dns_difftuple_t *next =
1079254885Sdumbbell					ISC_LIST_NEXT(t, link);
1080254885Sdumbbell				ISC_LIST_UNLINK(temp->tuples, t, link);
1081254885Sdumbbell				ISC_LIST_APPEND(u_rrs.tuples, t, link);
1082254885Sdumbbell				t = next;
1083254885Sdumbbell			}
1084254885Sdumbbell
1085254885Sdumbbell			/* Compare the two sorted lists. */
1086254885Sdumbbell			result = temp_check_rrset(ISC_LIST_HEAD(u_rrs.tuples),
1087254885Sdumbbell						  ISC_LIST_HEAD(d_rrs.tuples));
1088254885Sdumbbell			if (result != ISC_R_SUCCESS)
1089254885Sdumbbell				goto failure;
1090254885Sdumbbell
1091254885Sdumbbell			/*
1092254885Sdumbbell			 * We are done with the tuples, but we can't free
1093254885Sdumbbell			 * them yet because "name" still points into one
1094254885Sdumbbell			 * of them.  Move them on a temporary list.
1095254885Sdumbbell			 */
1096254885Sdumbbell			ISC_LIST_APPENDLIST(trash.tuples, u_rrs.tuples, link);
1097254885Sdumbbell			ISC_LIST_APPENDLIST(trash.tuples, d_rrs.tuples, link);
1098254885Sdumbbell			dns_rdataset_disassociate(&rdataset);
1099254885Sdumbbell
1100254885Sdumbbell			continue;
1101254885Sdumbbell
1102254885Sdumbbell		    failure:
1103254885Sdumbbell			dns_diff_clear(&d_rrs);
1104254885Sdumbbell			dns_diff_clear(&u_rrs);
1105254885Sdumbbell			dns_diff_clear(&trash);
1106254885Sdumbbell			dns_rdataset_disassociate(&rdataset);
1107254885Sdumbbell			dns_db_detachnode(db, &node);
1108254885Sdumbbell			return (result);
1109254885Sdumbbell		}
1110254885Sdumbbell
1111254885Sdumbbell		dns_db_detachnode(db, &node);
1112254885Sdumbbell	}
1113254885Sdumbbell
1114254885Sdumbbell	dns_diff_clear(&trash);
1115254885Sdumbbell	return (ISC_R_SUCCESS);
1116254885Sdumbbell}
1117254885Sdumbbell
1118254885Sdumbbell/**************************************************************************/
1119254885Sdumbbell/*
1120254885Sdumbbell * Conditional deletion of RRs.
1121254885Sdumbbell */
1122254885Sdumbbell
1123254885Sdumbbell/*%
1124254885Sdumbbell * Context structure for delete_if().
1125254885Sdumbbell */
1126254885Sdumbbell
1127254885Sdumbbelltypedef struct {
1128254885Sdumbbell	rr_predicate *predicate;
1129254885Sdumbbell	dns_db_t *db;
1130254885Sdumbbell	dns_dbversion_t *ver;
1131254885Sdumbbell	dns_diff_t *diff;
1132254885Sdumbbell	dns_name_t *name;
1133254885Sdumbbell	dns_rdata_t *update_rr;
1134254885Sdumbbell} conditional_delete_ctx_t;
1135254885Sdumbbell
1136254885Sdumbbell/*%
1137254885Sdumbbell * Predicate functions for delete_if().
1138254885Sdumbbell */
1139254885Sdumbbell
1140254885Sdumbbell/*%
1141254885Sdumbbell * Return true iff 'db_rr' is neither a SOA nor an NS RR nor
1142254885Sdumbbell * an RRSIG nor an NSEC3PARAM nor a NSEC.
1143254885Sdumbbell */
1144254885Sdumbbellstatic isc_boolean_t
1145254885Sdumbbelltype_not_soa_nor_ns_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
1146254885Sdumbbell	UNUSED(update_rr);
1147254885Sdumbbell	return ((db_rr->type != dns_rdatatype_soa &&
1148254885Sdumbbell		 db_rr->type != dns_rdatatype_ns &&
1149254885Sdumbbell		 db_rr->type != dns_rdatatype_nsec3param &&
1150254885Sdumbbell		 db_rr->type != dns_rdatatype_rrsig &&
1151254885Sdumbbell		 db_rr->type != dns_rdatatype_nsec) ?
1152254885Sdumbbell		ISC_TRUE : ISC_FALSE);
1153254885Sdumbbell}
1154254885Sdumbbell
1155254885Sdumbbell/*%
1156254885Sdumbbell * Return true iff 'db_rr' is neither a RRSIG nor a NSEC.
1157254885Sdumbbell */
1158254885Sdumbbellstatic isc_boolean_t
1159254885Sdumbbelltype_not_dnssec(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
1160254885Sdumbbell	UNUSED(update_rr);
1161254885Sdumbbell	return ((db_rr->type != dns_rdatatype_rrsig &&
1162254885Sdumbbell		 db_rr->type != dns_rdatatype_nsec) ?
1163254885Sdumbbell		ISC_TRUE : ISC_FALSE);
1164254885Sdumbbell}
1165254885Sdumbbell
1166254885Sdumbbell/*%
1167254885Sdumbbell * Return true always.
1168254885Sdumbbell */
1169254885Sdumbbellstatic isc_boolean_t
1170254885Sdumbbelltrue_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
1171254885Sdumbbell	UNUSED(update_rr);
1172254885Sdumbbell	UNUSED(db_rr);
1173254885Sdumbbell	return (ISC_TRUE);
1174254885Sdumbbell}
1175254885Sdumbbell
1176254885Sdumbbell/*%
1177254885Sdumbbell * Return true if the record is a RRSIG.
1178254885Sdumbbell */
1179254885Sdumbbellstatic isc_boolean_t
1180254885Sdumbbellrrsig_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
1181254885Sdumbbell	UNUSED(update_rr);
1182254885Sdumbbell	return ((db_rr->type == dns_rdatatype_rrsig) ?
1183254885Sdumbbell		ISC_TRUE : ISC_FALSE);
1184254885Sdumbbell}
1185254885Sdumbbell
1186254885Sdumbbell/*%
1187254885Sdumbbell * Return true iff the two RRs have identical rdata.
1188254885Sdumbbell */
1189254885Sdumbbellstatic isc_boolean_t
1190254885Sdumbbellrr_equal_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
1191254885Sdumbbell	/*
1192254885Sdumbbell	 * XXXRTH  This is not a problem, but we should consider creating
1193254885Sdumbbell	 *         dns_rdata_equal() (that used dns_name_equal()), since it
1194254885Sdumbbell	 *         would be faster.  Not a priority.
1195254885Sdumbbell	 */
1196254885Sdumbbell	return (dns_rdata_casecompare(update_rr, db_rr) == 0 ?
1197254885Sdumbbell		ISC_TRUE : ISC_FALSE);
1198254885Sdumbbell}
1199254885Sdumbbell
1200254885Sdumbbell/*%
1201254885Sdumbbell * Return true iff 'update_rr' should replace 'db_rr' according
1202254885Sdumbbell * to the special RFC2136 rules for CNAME, SOA, and WKS records.
1203254885Sdumbbell *
1204254885Sdumbbell * RFC2136 does not mention NSEC or DNAME, but multiple NSECs or DNAMEs
1205254885Sdumbbell * make little sense, so we replace those, too.
1206254885Sdumbbell *
1207254885Sdumbbell * Additionally replace RRSIG that have been generated by the same key
1208254885Sdumbbell * for the same type.  This simplifies refreshing a offline KSK by not
1209254885Sdumbbell * requiring that the old RRSIG be deleted.  It also simplifies key
1210254885Sdumbbell * rollover by only requiring that the new RRSIG be added.
1211254885Sdumbbell */
1212254885Sdumbbellstatic isc_boolean_t
1213254885Sdumbbellreplaces_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
1214254885Sdumbbell	dns_rdata_rrsig_t updatesig, dbsig;
1215254885Sdumbbell	isc_result_t result;
1216254885Sdumbbell
1217254885Sdumbbell	if (db_rr->type != update_rr->type)
1218254885Sdumbbell		return (ISC_FALSE);
1219254885Sdumbbell	if (db_rr->type == dns_rdatatype_cname)
1220254885Sdumbbell		return (ISC_TRUE);
1221254885Sdumbbell	if (db_rr->type == dns_rdatatype_dname)
1222254885Sdumbbell		return (ISC_TRUE);
1223254885Sdumbbell	if (db_rr->type == dns_rdatatype_soa)
1224254885Sdumbbell		return (ISC_TRUE);
1225254885Sdumbbell	if (db_rr->type == dns_rdatatype_nsec)
1226254885Sdumbbell		return (ISC_TRUE);
1227254885Sdumbbell	if (db_rr->type == dns_rdatatype_rrsig) {
1228254885Sdumbbell		/*
1229254885Sdumbbell		 * Replace existing RRSIG with the same keyid,
1230254885Sdumbbell		 * covered and algorithm.
1231254885Sdumbbell		 */
1232254885Sdumbbell		result = dns_rdata_tostruct(db_rr, &dbsig, NULL);
1233254885Sdumbbell		RUNTIME_CHECK(result == ISC_R_SUCCESS);
1234254885Sdumbbell		result = dns_rdata_tostruct(update_rr, &updatesig, NULL);
1235254885Sdumbbell		RUNTIME_CHECK(result == ISC_R_SUCCESS);
1236254885Sdumbbell		if (dbsig.keyid == updatesig.keyid &&
1237254885Sdumbbell		    dbsig.covered == updatesig.covered &&
1238254885Sdumbbell		    dbsig.algorithm == updatesig.algorithm)
1239254885Sdumbbell			return (ISC_TRUE);
1240254885Sdumbbell	}
1241254885Sdumbbell	if (db_rr->type == dns_rdatatype_wks) {
1242254885Sdumbbell		/*
1243254885Sdumbbell		 * Compare the address and protocol fields only.  These
1244254885Sdumbbell		 * form the first five bytes of the RR data.  Do a
1245254885Sdumbbell		 * raw binary comparison; unpacking the WKS RRs using
1246254885Sdumbbell		 * dns_rdata_tostruct() might be cleaner in some ways.
1247254885Sdumbbell		 */
1248254885Sdumbbell		INSIST(db_rr->length >= 5 && update_rr->length >= 5);
1249254885Sdumbbell		return (memcmp(db_rr->data, update_rr->data, 5) == 0 ?
1250254885Sdumbbell			ISC_TRUE : ISC_FALSE);
1251254885Sdumbbell	}
1252254885Sdumbbell
1253254885Sdumbbell	if (db_rr->type == dns_rdatatype_nsec3param) {
1254254885Sdumbbell		if (db_rr->length != update_rr->length)
1255254885Sdumbbell			return (ISC_FALSE);
1256254885Sdumbbell		INSIST(db_rr->length >= 4 && update_rr->length >= 4);
1257254885Sdumbbell		/*
1258254885Sdumbbell		 * Replace NSEC3PARAM records that only differ by the
1259254885Sdumbbell		 * flags field.
1260254885Sdumbbell		 */
1261254885Sdumbbell		if (db_rr->data[0] == update_rr->data[0] &&
1262254885Sdumbbell		    memcmp(db_rr->data+2, update_rr->data+2,
1263254885Sdumbbell			   update_rr->length - 2) == 0)
1264254885Sdumbbell			return (ISC_TRUE);
1265254885Sdumbbell	}
1266254885Sdumbbell	return (ISC_FALSE);
1267254885Sdumbbell}
1268254885Sdumbbell
1269254885Sdumbbell/*%
1270254885Sdumbbell * Internal helper function for delete_if().
1271254885Sdumbbell */
1272254885Sdumbbellstatic isc_result_t
1273254885Sdumbbelldelete_if_action(void *data, rr_t *rr) {
1274254885Sdumbbell	conditional_delete_ctx_t *ctx = data;
1275254885Sdumbbell	if ((*ctx->predicate)(ctx->update_rr, &rr->rdata)) {
1276254885Sdumbbell		isc_result_t result;
1277254885Sdumbbell		result = update_one_rr(ctx->db, ctx->ver, ctx->diff,
1278254885Sdumbbell				       DNS_DIFFOP_DEL, ctx->name,
1279254885Sdumbbell				       rr->ttl, &rr->rdata);
1280254885Sdumbbell		return (result);
1281254885Sdumbbell	} else {
1282254885Sdumbbell		return (ISC_R_SUCCESS);
1283254885Sdumbbell	}
1284254885Sdumbbell}
1285254885Sdumbbell
1286254885Sdumbbell/*%
1287254885Sdumbbell * Conditionally delete RRs.  Apply 'predicate' to the RRs
1288254885Sdumbbell * specified by 'db', 'ver', 'name', and 'type' (which can
1289254885Sdumbbell * be dns_rdatatype_any to match any type).  Delete those
1290254885Sdumbbell * RRs for which the predicate returns true, and log the
1291254885Sdumbbell * deletions in 'diff'.
1292254885Sdumbbell */
1293254885Sdumbbellstatic isc_result_t
1294254885Sdumbbelldelete_if(rr_predicate *predicate, dns_db_t *db, dns_dbversion_t *ver,
1295254885Sdumbbell	  dns_name_t *name, dns_rdatatype_t type, dns_rdatatype_t covers,
1296254885Sdumbbell	  dns_rdata_t *update_rr, dns_diff_t *diff)
1297254885Sdumbbell{
1298254885Sdumbbell	conditional_delete_ctx_t ctx;
1299254885Sdumbbell	ctx.predicate = predicate;
1300254885Sdumbbell	ctx.db = db;
1301254885Sdumbbell	ctx.ver = ver;
1302254885Sdumbbell	ctx.diff = diff;
1303254885Sdumbbell	ctx.name = name;
1304254885Sdumbbell	ctx.update_rr = update_rr;
1305254885Sdumbbell	return (foreach_rr(db, ver, name, type, covers,
1306254885Sdumbbell			   delete_if_action, &ctx));
1307254885Sdumbbell}
1308254885Sdumbbell
1309254885Sdumbbell/**************************************************************************/
1310254885Sdumbbell/*%
1311254885Sdumbbell * Prepare an RR for the addition of the new RR 'ctx->update_rr',
1312254885Sdumbbell * with TTL 'ctx->update_rr_ttl', to its rdataset, by deleting
1313254885Sdumbbell * the RRs if it is replaced by the new RR or has a conflicting TTL.
1314254885Sdumbbell * The necessary changes are appended to ctx->del_diff and ctx->add_diff;
1315254885Sdumbbell * we need to do all deletions before any additions so that we don't run
1316254885Sdumbbell * into transient states with conflicting TTLs.
1317254885Sdumbbell */
1318254885Sdumbbell
1319254885Sdumbbelltypedef struct {
1320254885Sdumbbell	dns_db_t *db;
1321254885Sdumbbell	dns_dbversion_t *ver;
1322254885Sdumbbell	dns_diff_t *diff;
1323254885Sdumbbell	dns_name_t *name;
1324254885Sdumbbell	dns_rdata_t *update_rr;
1325254885Sdumbbell	dns_ttl_t update_rr_ttl;
1326254885Sdumbbell	isc_boolean_t ignore_add;
1327254885Sdumbbell	dns_diff_t del_diff;
1328254885Sdumbbell	dns_diff_t add_diff;
1329254885Sdumbbell} add_rr_prepare_ctx_t;
1330254885Sdumbbell
1331254885Sdumbbellstatic isc_result_t
1332254885Sdumbbelladd_rr_prepare_action(void *data, rr_t *rr) {
1333254885Sdumbbell	isc_result_t result = ISC_R_SUCCESS;
1334254885Sdumbbell	add_rr_prepare_ctx_t *ctx = data;
1335254885Sdumbbell	dns_difftuple_t *tuple = NULL;
1336254885Sdumbbell	isc_boolean_t equal;
1337254885Sdumbbell
1338254885Sdumbbell	/*
1339254885Sdumbbell	 * If the update RR is a "duplicate" of the update RR,
1340254885Sdumbbell	 * the update should be silently ignored.
1341254885Sdumbbell	 */
1342254885Sdumbbell	equal = ISC_TF(dns_rdata_casecompare(&rr->rdata, ctx->update_rr) == 0);
1343254885Sdumbbell	if (equal && rr->ttl == ctx->update_rr_ttl) {
1344254885Sdumbbell		ctx->ignore_add = ISC_TRUE;
1345254885Sdumbbell		return (ISC_R_SUCCESS);
1346254885Sdumbbell	}
1347254885Sdumbbell
1348254885Sdumbbell	/*
1349254885Sdumbbell	 * If this RR is "equal" to the update RR, it should
1350254885Sdumbbell	 * be deleted before the update RR is added.
1351254885Sdumbbell	 */
1352254885Sdumbbell	if (replaces_p(ctx->update_rr, &rr->rdata)) {
1353254885Sdumbbell		CHECK(dns_difftuple_create(ctx->del_diff.mctx, DNS_DIFFOP_DEL,
1354254885Sdumbbell					   ctx->name, rr->ttl, &rr->rdata,
1355254885Sdumbbell					   &tuple));
1356254885Sdumbbell		dns_diff_append(&ctx->del_diff, &tuple);
1357254885Sdumbbell		return (ISC_R_SUCCESS);
1358254885Sdumbbell	}
1359254885Sdumbbell
1360254885Sdumbbell	/*
1361254885Sdumbbell	 * If this RR differs in TTL from the update RR,
1362254885Sdumbbell	 * its TTL must be adjusted.
1363254885Sdumbbell	 */
1364254885Sdumbbell	if (rr->ttl != ctx->update_rr_ttl) {
1365254885Sdumbbell		CHECK(dns_difftuple_create(ctx->del_diff.mctx, DNS_DIFFOP_DEL,
1366254885Sdumbbell					   ctx->name, rr->ttl, &rr->rdata,
1367254885Sdumbbell					   &tuple));
1368254885Sdumbbell		dns_diff_append(&ctx->del_diff, &tuple);
1369254885Sdumbbell		if (!equal) {
1370254885Sdumbbell			CHECK(dns_difftuple_create(ctx->add_diff.mctx,
1371254885Sdumbbell						   DNS_DIFFOP_ADD, ctx->name,
1372254885Sdumbbell						   ctx->update_rr_ttl,
1373254885Sdumbbell						   &rr->rdata, &tuple));
1374254885Sdumbbell			dns_diff_append(&ctx->add_diff, &tuple);
1375254885Sdumbbell		}
1376254885Sdumbbell	}
1377254885Sdumbbell failure:
1378254885Sdumbbell	return (result);
1379254885Sdumbbell}
1380254885Sdumbbell
1381254885Sdumbbell/**************************************************************************/
1382254885Sdumbbell/*
1383254885Sdumbbell * Miscellaneous subroutines.
1384254885Sdumbbell */
1385254885Sdumbbell
1386254885Sdumbbell/*%
1387254885Sdumbbell * Extract a single update RR from 'section' of dynamic update message
1388254885Sdumbbell * 'msg', with consistency checking.
1389254885Sdumbbell *
1390254885Sdumbbell * Stores the owner name, rdata, and TTL of the update RR at 'name',
1391254885Sdumbbell * 'rdata', and 'ttl', respectively.
1392254885Sdumbbell */
1393254885Sdumbbellstatic void
1394254885Sdumbbellget_current_rr(dns_message_t *msg, dns_section_t section,
1395254885Sdumbbell	       dns_rdataclass_t zoneclass, dns_name_t **name,
1396254885Sdumbbell	       dns_rdata_t *rdata, dns_rdatatype_t *covers,
1397254885Sdumbbell	       dns_ttl_t *ttl, dns_rdataclass_t *update_class)
1398254885Sdumbbell{
1399254885Sdumbbell	dns_rdataset_t *rdataset;
1400254885Sdumbbell	isc_result_t result;
1401254885Sdumbbell	dns_message_currentname(msg, section, name);
1402254885Sdumbbell	rdataset = ISC_LIST_HEAD((*name)->list);
1403254885Sdumbbell	INSIST(rdataset != NULL);
1404254885Sdumbbell	INSIST(ISC_LIST_NEXT(rdataset, link) == NULL);
1405254885Sdumbbell	*covers = rdataset->covers;
1406254885Sdumbbell	*ttl = rdataset->ttl;
1407254885Sdumbbell	result = dns_rdataset_first(rdataset);
1408254885Sdumbbell	INSIST(result == ISC_R_SUCCESS);
1409254885Sdumbbell	dns_rdataset_current(rdataset, rdata);
1410254885Sdumbbell	INSIST(dns_rdataset_next(rdataset) == ISC_R_NOMORE);
1411254885Sdumbbell	*update_class = rdata->rdclass;
1412254885Sdumbbell	rdata->rdclass = zoneclass;
1413254885Sdumbbell}
1414254885Sdumbbell
1415254885Sdumbbell/*%
1416254885Sdumbbell * Increment the SOA serial number of database 'db', version 'ver'.
1417254885Sdumbbell * Replace the SOA record in the database, and log the
1418254885Sdumbbell * change in 'diff'.
1419254885Sdumbbell */
1420254885Sdumbbell
1421254885Sdumbbell	/*
1422254885Sdumbbell	 * XXXRTH  Failures in this routine will be worth logging, when
1423254885Sdumbbell	 *         we have a logging system.  Failure to find the zonename
1424254885Sdumbbell	 *	   or the SOA rdataset warrant at least an UNEXPECTED_ERROR().
1425254885Sdumbbell	 */
1426254885Sdumbbell
1427254885Sdumbbellstatic isc_result_t
1428254885Sdumbbellincrement_soa_serial(dns_db_t *db, dns_dbversion_t *ver,
1429254885Sdumbbell		     dns_diff_t *diff, isc_mem_t *mctx)
1430254885Sdumbbell{
1431254885Sdumbbell	dns_difftuple_t *deltuple = NULL;
1432254885Sdumbbell	dns_difftuple_t *addtuple = NULL;
1433254885Sdumbbell	isc_uint32_t serial;
1434254885Sdumbbell	isc_result_t result;
1435254885Sdumbbell
1436254885Sdumbbell	CHECK(dns_db_createsoatuple(db, ver, mctx, DNS_DIFFOP_DEL, &deltuple));
1437254885Sdumbbell	CHECK(dns_difftuple_copy(deltuple, &addtuple));
1438254885Sdumbbell	addtuple->op = DNS_DIFFOP_ADD;
1439254885Sdumbbell
1440254885Sdumbbell	serial = dns_soa_getserial(&addtuple->rdata);
1441254885Sdumbbell
1442254885Sdumbbell	/* RFC1982 */
1443254885Sdumbbell	serial = (serial + 1) & 0xFFFFFFFF;
1444254885Sdumbbell	if (serial == 0)
1445254885Sdumbbell		serial = 1;
1446254885Sdumbbell
1447254885Sdumbbell	dns_soa_setserial(serial, &addtuple->rdata);
1448254885Sdumbbell	CHECK(do_one_tuple(&deltuple, db, ver, diff));
1449254885Sdumbbell	CHECK(do_one_tuple(&addtuple, db, ver, diff));
1450254885Sdumbbell	result = ISC_R_SUCCESS;
1451254885Sdumbbell
1452254885Sdumbbell failure:
1453254885Sdumbbell	if (addtuple != NULL)
1454254885Sdumbbell		dns_difftuple_free(&addtuple);
1455254885Sdumbbell	if (deltuple != NULL)
1456254885Sdumbbell		dns_difftuple_free(&deltuple);
1457254885Sdumbbell	return (result);
1458254885Sdumbbell}
1459254885Sdumbbell
1460254885Sdumbbell/*%
1461254885Sdumbbell * Check that the new SOA record at 'update_rdata' does not
1462254885Sdumbbell * illegally cause the SOA serial number to decrease or stay
1463254885Sdumbbell * unchanged relative to the existing SOA in 'db'.
1464254885Sdumbbell *
1465254885Sdumbbell * Sets '*ok' to ISC_TRUE if the update is legal, ISC_FALSE if not.
1466254885Sdumbbell *
1467254885Sdumbbell * William King points out that RFC2136 is inconsistent about
1468254885Sdumbbell * the case where the serial number stays unchanged:
1469254885Sdumbbell *
1470254885Sdumbbell *   section 3.4.2.2 requires a server to ignore a SOA update request
1471254885Sdumbbell *   if the serial number on the update SOA is less_than_or_equal to
1472254885Sdumbbell *   the zone SOA serial.
1473254885Sdumbbell *
1474254885Sdumbbell *   section 3.6 requires a server to ignore a SOA update request if
1475254885Sdumbbell *   the serial is less_than the zone SOA serial.
1476254885Sdumbbell *
1477254885Sdumbbell * Paul says 3.4.2.2 is correct.
1478254885Sdumbbell *
1479254885Sdumbbell */
1480254885Sdumbbellstatic isc_result_t
1481254885Sdumbbellcheck_soa_increment(dns_db_t *db, dns_dbversion_t *ver,
1482254885Sdumbbell		    dns_rdata_t *update_rdata, isc_boolean_t *ok)
1483254885Sdumbbell{
1484254885Sdumbbell	isc_uint32_t db_serial;
1485254885Sdumbbell	isc_uint32_t update_serial;
1486254885Sdumbbell	isc_result_t result;
1487254885Sdumbbell
1488254885Sdumbbell	update_serial = dns_soa_getserial(update_rdata);
1489254885Sdumbbell
1490254885Sdumbbell	result = dns_db_getsoaserial(db, ver, &db_serial);
1491254885Sdumbbell	if (result != ISC_R_SUCCESS)
1492254885Sdumbbell		return (result);
1493254885Sdumbbell
1494254885Sdumbbell	if (DNS_SERIAL_GE(db_serial, update_serial)) {
1495254885Sdumbbell		*ok = ISC_FALSE;
1496254885Sdumbbell	} else {
1497254885Sdumbbell		*ok = ISC_TRUE;
1498254885Sdumbbell	}
1499254885Sdumbbell
1500254885Sdumbbell	return (ISC_R_SUCCESS);
1501254885Sdumbbell
1502254885Sdumbbell}
1503254885Sdumbbell
1504254885Sdumbbell/**************************************************************************/
1505254885Sdumbbell/*
1506254885Sdumbbell * Incremental updating of NSECs and RRSIGs.
1507254885Sdumbbell */
1508254885Sdumbbell
1509254885Sdumbbell#define MAXZONEKEYS 32	/*%< Maximum number of zone keys supported. */
1510254885Sdumbbell
1511254885Sdumbbell/*%
1512254885Sdumbbell * We abuse the dns_diff_t type to represent a set of domain names
1513254885Sdumbbell * affected by the update.
1514254885Sdumbbell */
1515254885Sdumbbellstatic isc_result_t
1516254885Sdumbbellnamelist_append_name(dns_diff_t *list, dns_name_t *name) {
1517254885Sdumbbell	isc_result_t result;
1518254885Sdumbbell	dns_difftuple_t *tuple = NULL;
1519254885Sdumbbell	static dns_rdata_t dummy_rdata = DNS_RDATA_INIT;
1520254885Sdumbbell
1521254885Sdumbbell	CHECK(dns_difftuple_create(list->mctx, DNS_DIFFOP_EXISTS, name, 0,
1522254885Sdumbbell				   &dummy_rdata, &tuple));
1523254885Sdumbbell	dns_diff_append(list, &tuple);
1524254885Sdumbbell failure:
1525254885Sdumbbell	return (result);
1526254885Sdumbbell}
1527254885Sdumbbell
1528254885Sdumbbellstatic isc_result_t
1529254885Sdumbbellnamelist_append_subdomain(dns_db_t *db, dns_name_t *name, dns_diff_t *affected)
1530254885Sdumbbell{
1531254885Sdumbbell	isc_result_t result;
1532254885Sdumbbell	dns_fixedname_t fixedname;
1533254885Sdumbbell	dns_name_t *child;
1534254885Sdumbbell	dns_dbiterator_t *dbit = NULL;
1535254885Sdumbbell
1536254885Sdumbbell	dns_fixedname_init(&fixedname);
1537254885Sdumbbell	child = dns_fixedname_name(&fixedname);
1538254885Sdumbbell
1539254885Sdumbbell	CHECK(dns_db_createiterator(db, DNS_DB_NONSEC3, &dbit));
1540254885Sdumbbell
1541254885Sdumbbell	for (result = dns_dbiterator_seek(dbit, name);
1542254885Sdumbbell	     result == ISC_R_SUCCESS;
1543254885Sdumbbell	     result = dns_dbiterator_next(dbit))
1544254885Sdumbbell	{
1545254885Sdumbbell		dns_dbnode_t *node = NULL;
1546254885Sdumbbell		CHECK(dns_dbiterator_current(dbit, &node, child));
1547254885Sdumbbell		dns_db_detachnode(db, &node);
1548254885Sdumbbell		if (! dns_name_issubdomain(child, name))
1549254885Sdumbbell			break;
1550254885Sdumbbell		CHECK(namelist_append_name(affected, child));
1551254885Sdumbbell	}
1552254885Sdumbbell	if (result == ISC_R_NOMORE)
1553254885Sdumbbell		result = ISC_R_SUCCESS;
1554254885Sdumbbell failure:
1555254885Sdumbbell	if (dbit != NULL)
1556254885Sdumbbell		dns_dbiterator_destroy(&dbit);
1557254885Sdumbbell	return (result);
1558254885Sdumbbell}
1559254885Sdumbbell
1560254885Sdumbbell
1561254885Sdumbbell
1562254885Sdumbbell/*%
1563254885Sdumbbell * Helper function for non_nsec_rrset_exists().
1564254885Sdumbbell */
1565254885Sdumbbellstatic isc_result_t
1566254885Sdumbbellis_non_nsec_action(void *data, dns_rdataset_t *rrset) {
1567254885Sdumbbell	UNUSED(data);
1568254885Sdumbbell	if (!(rrset->type == dns_rdatatype_nsec ||
1569254885Sdumbbell	      rrset->type == dns_rdatatype_nsec3 ||
1570254885Sdumbbell	      (rrset->type == dns_rdatatype_rrsig &&
1571254885Sdumbbell	       (rrset->covers == dns_rdatatype_nsec ||
1572254885Sdumbbell		rrset->covers == dns_rdatatype_nsec3))))
1573254885Sdumbbell		return (ISC_R_EXISTS);
1574254885Sdumbbell	return (ISC_R_SUCCESS);
1575254885Sdumbbell}
1576254885Sdumbbell
1577254885Sdumbbell/*%
1578254885Sdumbbell * Check whether there is an rrset other than a NSEC or RRSIG NSEC,
1579254885Sdumbbell * i.e., anything that justifies the continued existence of a name
1580254885Sdumbbell * after a secure update.
1581254885Sdumbbell *
1582254885Sdumbbell * If such an rrset exists, set '*exists' to ISC_TRUE.
1583254885Sdumbbell * Otherwise, set it to ISC_FALSE.
1584254885Sdumbbell */
1585254885Sdumbbellstatic isc_result_t
1586254885Sdumbbellnon_nsec_rrset_exists(dns_db_t *db, dns_dbversion_t *ver,
1587254885Sdumbbell		     dns_name_t *name, isc_boolean_t *exists)
1588254885Sdumbbell{
1589254885Sdumbbell	isc_result_t result;
1590254885Sdumbbell	result = foreach_rrset(db, ver, name, is_non_nsec_action, NULL);
1591254885Sdumbbell	RETURN_EXISTENCE_FLAG;
1592254885Sdumbbell}
1593254885Sdumbbell
1594254885Sdumbbell/*%
1595254885Sdumbbell * A comparison function for sorting dns_diff_t:s by name.
1596254885Sdumbbell */
1597254885Sdumbbellstatic int
1598254885Sdumbbellname_order(const void *av, const void *bv) {
1599254885Sdumbbell	dns_difftuple_t const * const *ap = av;
1600254885Sdumbbell	dns_difftuple_t const * const *bp = bv;
1601254885Sdumbbell	dns_difftuple_t const *a = *ap;
1602254885Sdumbbell	dns_difftuple_t const *b = *bp;
1603254885Sdumbbell	return (dns_name_compare(&a->name, &b->name));
1604254885Sdumbbell}
1605254885Sdumbbell
1606254885Sdumbbellstatic isc_result_t
1607254885Sdumbbelluniqify_name_list(dns_diff_t *list) {
1608254885Sdumbbell	isc_result_t result;
1609254885Sdumbbell	dns_difftuple_t *p, *q;
1610254885Sdumbbell
1611254885Sdumbbell	CHECK(dns_diff_sort(list, name_order));
1612254885Sdumbbell
1613254885Sdumbbell	p = ISC_LIST_HEAD(list->tuples);
1614254885Sdumbbell	while (p != NULL) {
1615254885Sdumbbell		do {
1616254885Sdumbbell			q = ISC_LIST_NEXT(p, link);
1617254885Sdumbbell			if (q == NULL || ! dns_name_equal(&p->name, &q->name))
1618254885Sdumbbell				break;
1619254885Sdumbbell			ISC_LIST_UNLINK(list->tuples, q, link);
1620254885Sdumbbell			dns_difftuple_free(&q);
1621254885Sdumbbell		} while (1);
1622254885Sdumbbell		p = ISC_LIST_NEXT(p, link);
1623254885Sdumbbell	}
1624254885Sdumbbell failure:
1625254885Sdumbbell	return (result);
1626254885Sdumbbell}
1627254885Sdumbbell
1628254885Sdumbbellstatic isc_result_t
1629254885Sdumbbellis_active(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
1630254885Sdumbbell	  isc_boolean_t *flag, isc_boolean_t *cut, isc_boolean_t *unsecure)
1631254885Sdumbbell{
1632254885Sdumbbell	isc_result_t result;
1633254885Sdumbbell	dns_fixedname_t foundname;
1634254885Sdumbbell	dns_fixedname_init(&foundname);
1635254885Sdumbbell	result = dns_db_find(db, name, ver, dns_rdatatype_any,
1636254885Sdumbbell			     DNS_DBFIND_GLUEOK | DNS_DBFIND_NOWILD,
1637254885Sdumbbell			     (isc_stdtime_t) 0, NULL,
1638254885Sdumbbell			     dns_fixedname_name(&foundname),
1639254885Sdumbbell			     NULL, NULL);
1640254885Sdumbbell	if (result == ISC_R_SUCCESS || result == DNS_R_EMPTYNAME) {
1641254885Sdumbbell		*flag = ISC_TRUE;
1642254885Sdumbbell		*cut = ISC_FALSE;
1643254885Sdumbbell		if (unsecure != NULL)
1644254885Sdumbbell			*unsecure = ISC_FALSE;
1645254885Sdumbbell		return (ISC_R_SUCCESS);
1646254885Sdumbbell	} else if (result == DNS_R_ZONECUT) {
1647254885Sdumbbell		*flag = ISC_TRUE;
1648254885Sdumbbell		*cut = ISC_TRUE;
1649254885Sdumbbell		if (unsecure != NULL) {
1650254885Sdumbbell			/*
1651254885Sdumbbell			 * We are at the zonecut.  Check to see if there
1652254885Sdumbbell			 * is a DS RRset.
1653254885Sdumbbell			 */
1654254885Sdumbbell			if (dns_db_find(db, name, ver, dns_rdatatype_ds, 0,
1655254885Sdumbbell					(isc_stdtime_t) 0, NULL,
1656254885Sdumbbell					dns_fixedname_name(&foundname),
1657254885Sdumbbell					NULL, NULL) == DNS_R_NXRRSET)
1658254885Sdumbbell				*unsecure = ISC_TRUE;
1659254885Sdumbbell			else
1660254885Sdumbbell				*unsecure = ISC_FALSE;
1661254885Sdumbbell		}
1662254885Sdumbbell		return (ISC_R_SUCCESS);
1663254885Sdumbbell	} else if (result == DNS_R_GLUE || result == DNS_R_DNAME ||
1664254885Sdumbbell		   result == DNS_R_DELEGATION || result == DNS_R_NXDOMAIN) {
1665254885Sdumbbell		*flag = ISC_FALSE;
1666254885Sdumbbell		*cut = ISC_FALSE;
1667254885Sdumbbell		if (unsecure != NULL)
1668254885Sdumbbell			*unsecure = ISC_FALSE;
1669254885Sdumbbell		return (ISC_R_SUCCESS);
1670254885Sdumbbell	} else {
1671254885Sdumbbell		/*
1672254885Sdumbbell		 * Silence compiler.
1673254885Sdumbbell		 */
1674254885Sdumbbell		*flag = ISC_FALSE;
1675254885Sdumbbell		*cut = ISC_FALSE;
1676254885Sdumbbell		if (unsecure != NULL)
1677254885Sdumbbell			*unsecure = ISC_FALSE;
1678254885Sdumbbell		return (result);
1679254885Sdumbbell	}
1680254885Sdumbbell}
1681254885Sdumbbell
1682254885Sdumbbell/*%
1683254885Sdumbbell * Find the next/previous name that has a NSEC record.
1684254885Sdumbbell * In other words, skip empty database nodes and names that
1685254885Sdumbbell * have had their NSECs removed because they are obscured by
1686254885Sdumbbell * a zone cut.
1687254885Sdumbbell */
1688254885Sdumbbellstatic isc_result_t
1689254885Sdumbbellnext_active(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
1690254885Sdumbbell	    dns_dbversion_t *ver, dns_name_t *oldname, dns_name_t *newname,
1691254885Sdumbbell	    isc_boolean_t forward)
1692254885Sdumbbell{
1693254885Sdumbbell	isc_result_t result;
1694254885Sdumbbell	dns_dbiterator_t *dbit = NULL;
1695254885Sdumbbell	isc_boolean_t has_nsec = ISC_FALSE;
1696254885Sdumbbell	unsigned int wraps = 0;
1697254885Sdumbbell	isc_boolean_t secure = dns_db_issecure(db);
1698254885Sdumbbell
1699254885Sdumbbell	CHECK(dns_db_createiterator(db, 0, &dbit));
1700254885Sdumbbell
1701254885Sdumbbell	CHECK(dns_dbiterator_seek(dbit, oldname));
1702254885Sdumbbell	do {
1703254885Sdumbbell		dns_dbnode_t *node = NULL;
1704254885Sdumbbell
1705254885Sdumbbell		if (forward)
1706254885Sdumbbell			result = dns_dbiterator_next(dbit);
1707254885Sdumbbell		else
1708254885Sdumbbell			result = dns_dbiterator_prev(dbit);
1709254885Sdumbbell		if (result == ISC_R_NOMORE) {
1710254885Sdumbbell			/*
1711254885Sdumbbell			 * Wrap around.
1712254885Sdumbbell			 */
1713254885Sdumbbell			if (forward)
1714254885Sdumbbell				CHECK(dns_dbiterator_first(dbit));
1715254885Sdumbbell			else
1716254885Sdumbbell				CHECK(dns_dbiterator_last(dbit));
1717254885Sdumbbell			wraps++;
1718254885Sdumbbell			if (wraps == 2) {
1719254885Sdumbbell				update_log(client, zone, ISC_LOG_ERROR,
1720254885Sdumbbell					   "secure zone with no NSECs");
1721254885Sdumbbell				result = DNS_R_BADZONE;
1722254885Sdumbbell				goto failure;
1723254885Sdumbbell			}
1724254885Sdumbbell		}
1725254885Sdumbbell		CHECK(dns_dbiterator_current(dbit, &node, newname));
1726254885Sdumbbell		dns_db_detachnode(db, &node);
1727254885Sdumbbell
1728254885Sdumbbell		/*
1729254885Sdumbbell		 * The iterator may hold the tree lock, and
1730254885Sdumbbell		 * rrset_exists() calls dns_db_findnode() which
1731254885Sdumbbell		 * may try to reacquire it.  To avoid deadlock
1732254885Sdumbbell		 * we must pause the iterator first.
1733254885Sdumbbell		 */
1734254885Sdumbbell		CHECK(dns_dbiterator_pause(dbit));
1735254885Sdumbbell		if (secure) {
1736254885Sdumbbell			CHECK(rrset_exists(db, ver, newname,
1737254885Sdumbbell					   dns_rdatatype_nsec, 0, &has_nsec));
1738254885Sdumbbell		} else {
1739254885Sdumbbell			dns_fixedname_t ffound;
1740254885Sdumbbell			dns_name_t *found;
1741254885Sdumbbell			dns_fixedname_init(&ffound);
1742254885Sdumbbell			found = dns_fixedname_name(&ffound);
1743254885Sdumbbell			result = dns_db_find(db, newname, ver,
1744254885Sdumbbell					     dns_rdatatype_soa,
1745254885Sdumbbell					     DNS_DBFIND_NOWILD, 0, NULL, found,
1746254885Sdumbbell					     NULL, NULL);
1747254885Sdumbbell			if (result == ISC_R_SUCCESS ||
1748254885Sdumbbell			    result == DNS_R_EMPTYNAME ||
1749254885Sdumbbell			    result == DNS_R_NXRRSET ||
1750254885Sdumbbell			    result == DNS_R_CNAME ||
1751254885Sdumbbell			    (result == DNS_R_DELEGATION &&
1752254885Sdumbbell			     dns_name_equal(newname, found))) {
1753254885Sdumbbell				has_nsec = ISC_TRUE;
1754254885Sdumbbell				result = ISC_R_SUCCESS;
1755254885Sdumbbell			} else if (result != DNS_R_NXDOMAIN)
1756254885Sdumbbell				break;
1757254885Sdumbbell		}
1758254885Sdumbbell	} while (! has_nsec);
1759254885Sdumbbell failure:
1760254885Sdumbbell	if (dbit != NULL)
1761254885Sdumbbell		dns_dbiterator_destroy(&dbit);
1762254885Sdumbbell
1763254885Sdumbbell	return (result);
1764254885Sdumbbell}
1765254885Sdumbbell
1766254885Sdumbbell/*%
1767254885Sdumbbell * Add a NSEC record for "name", recording the change in "diff".
1768254885Sdumbbell * The existing NSEC is removed.
1769254885Sdumbbell */
1770254885Sdumbbellstatic isc_result_t
1771254885Sdumbbelladd_nsec(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
1772254885Sdumbbell	 dns_dbversion_t *ver, dns_name_t *name, dns_ttl_t nsecttl,
1773254885Sdumbbell	 dns_diff_t *diff)
1774254885Sdumbbell{
1775254885Sdumbbell	isc_result_t result;
1776254885Sdumbbell	dns_dbnode_t *node = NULL;
1777254885Sdumbbell	unsigned char buffer[DNS_NSEC_BUFFERSIZE];
1778254885Sdumbbell	dns_rdata_t rdata = DNS_RDATA_INIT;
1779254885Sdumbbell	dns_difftuple_t *tuple = NULL;
1780254885Sdumbbell	dns_fixedname_t fixedname;
1781254885Sdumbbell	dns_name_t *target;
1782254885Sdumbbell
1783254885Sdumbbell	dns_fixedname_init(&fixedname);
1784254885Sdumbbell	target = dns_fixedname_name(&fixedname);
1785254885Sdumbbell
1786254885Sdumbbell	/*
1787254885Sdumbbell	 * Find the successor name, aka NSEC target.
1788254885Sdumbbell	 */
1789254885Sdumbbell	CHECK(next_active(client, zone, db, ver, name, target, ISC_TRUE));
1790254885Sdumbbell
1791254885Sdumbbell	/*
1792254885Sdumbbell	 * Create the NSEC RDATA.
1793254885Sdumbbell	 */
1794254885Sdumbbell	CHECK(dns_db_findnode(db, name, ISC_FALSE, &node));
1795254885Sdumbbell	dns_rdata_init(&rdata);
1796254885Sdumbbell	CHECK(dns_nsec_buildrdata(db, ver, node, target, buffer, &rdata));
1797254885Sdumbbell	dns_db_detachnode(db, &node);
1798254885Sdumbbell
1799254885Sdumbbell	/*
1800254885Sdumbbell	 * Delete the old NSEC and record the change.
1801254885Sdumbbell	 */
1802254885Sdumbbell	CHECK(delete_if(true_p, db, ver, name, dns_rdatatype_nsec, 0,
1803254885Sdumbbell			NULL, diff));
1804254885Sdumbbell	/*
1805254885Sdumbbell	 * Add the new NSEC and record the change.
1806254885Sdumbbell	 */
1807254885Sdumbbell	CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD, name,
1808254885Sdumbbell				   nsecttl, &rdata, &tuple));
1809254885Sdumbbell	CHECK(do_one_tuple(&tuple, db, ver, diff));
1810254885Sdumbbell	INSIST(tuple == NULL);
1811282199Sdumbbell
1812254885Sdumbbell failure:
1813254885Sdumbbell	if (node != NULL)
1814254885Sdumbbell		dns_db_detachnode(db, &node);
1815254885Sdumbbell	return (result);
1816254885Sdumbbell}
1817254885Sdumbbell
1818254885Sdumbbell/*%
1819254885Sdumbbell * Add a placeholder NSEC record for "name", recording the change in "diff".
1820254885Sdumbbell */
1821254885Sdumbbellstatic isc_result_t
1822254885Sdumbbelladd_placeholder_nsec(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
1823254885Sdumbbell		     dns_diff_t *diff)
1824254885Sdumbbell{
1825254885Sdumbbell	isc_result_t result;
1826254885Sdumbbell	dns_difftuple_t *tuple = NULL;
1827254885Sdumbbell	isc_region_t r;
1828254885Sdumbbell	unsigned char data[1] = { 0 }; /* The root domain, no bits. */
1829254885Sdumbbell	dns_rdata_t rdata = DNS_RDATA_INIT;
1830254885Sdumbbell
1831254885Sdumbbell	r.base = data;
1832254885Sdumbbell	r.length = sizeof(data);
1833254885Sdumbbell	dns_rdata_fromregion(&rdata, dns_db_class(db), dns_rdatatype_nsec, &r);
1834254885Sdumbbell	CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD, name, 0,
1835254885Sdumbbell				   &rdata, &tuple));
1836254885Sdumbbell	CHECK(do_one_tuple(&tuple, db, ver, diff));
1837254885Sdumbbell failure:
1838254885Sdumbbell	return (result);
1839254885Sdumbbell}
1840254885Sdumbbell
1841254885Sdumbbellstatic isc_result_t
1842254885Sdumbbellfind_zone_keys(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *ver,
1843254885Sdumbbell	       isc_mem_t *mctx, unsigned int maxkeys,
1844254885Sdumbbell	       dst_key_t **keys, unsigned int *nkeys)
1845254885Sdumbbell{
1846254885Sdumbbell	isc_result_t result;
1847254885Sdumbbell	dns_dbnode_t *node = NULL;
1848254885Sdumbbell	const char *directory = dns_zone_getkeydirectory(zone);
1849254885Sdumbbell	CHECK(dns_db_findnode(db, dns_db_origin(db), ISC_FALSE, &node));
1850254885Sdumbbell	CHECK(dns_dnssec_findzonekeys2(db, ver, node, dns_db_origin(db),
1851254885Sdumbbell				       directory, mctx, maxkeys, keys, nkeys));
1852254885Sdumbbell failure:
1853254885Sdumbbell	if (node != NULL)
1854254885Sdumbbell		dns_db_detachnode(db, &node);
1855254885Sdumbbell	return (result);
1856254885Sdumbbell}
1857254885Sdumbbell
1858254885Sdumbbell/*%
1859254885Sdumbbell * Add RRSIG records for an RRset, recording the change in "diff".
1860254885Sdumbbell */
1861254885Sdumbbellstatic isc_result_t
1862254885Sdumbbelladd_sigs(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
1863254885Sdumbbell	 dns_dbversion_t *ver, dns_name_t *name, dns_rdatatype_t type,
1864254885Sdumbbell	 dns_diff_t *diff, dst_key_t **keys, unsigned int nkeys,
1865254885Sdumbbell	 isc_stdtime_t inception, isc_stdtime_t expire,
1866254885Sdumbbell	 isc_boolean_t check_ksk, isc_boolean_t keyset_kskonly)
1867254885Sdumbbell{
1868254885Sdumbbell	isc_result_t result;
1869254885Sdumbbell	dns_dbnode_t *node = NULL;
1870254885Sdumbbell	dns_rdataset_t rdataset;
1871254885Sdumbbell	dns_rdata_t sig_rdata = DNS_RDATA_INIT;
1872254885Sdumbbell	isc_buffer_t buffer;
1873254885Sdumbbell	unsigned char data[1024]; /* XXX */
1874254885Sdumbbell	unsigned int i, j;
1875254885Sdumbbell	isc_boolean_t added_sig = ISC_FALSE;
1876254885Sdumbbell	isc_mem_t *mctx = client->mctx;
1877254885Sdumbbell
1878254885Sdumbbell	dns_rdataset_init(&rdataset);
1879254885Sdumbbell	isc_buffer_init(&buffer, data, sizeof(data));
1880254885Sdumbbell
1881254885Sdumbbell	/* Get the rdataset to sign. */
1882254885Sdumbbell	if (type == dns_rdatatype_nsec3)
1883254885Sdumbbell		CHECK(dns_db_findnsec3node(db, name, ISC_FALSE, &node));
1884254885Sdumbbell	else
1885254885Sdumbbell		CHECK(dns_db_findnode(db, name, ISC_FALSE, &node));
1886254885Sdumbbell	CHECK(dns_db_findrdataset(db, node, ver, type, 0,
1887254885Sdumbbell				  (isc_stdtime_t) 0, &rdataset, NULL));
1888254885Sdumbbell	dns_db_detachnode(db, &node);
1889254885Sdumbbell
1890254885Sdumbbell#define REVOKE(x) ((dst_key_flags(x) & DNS_KEYFLAG_REVOKE) != 0)
1891254885Sdumbbell#define KSK(x) ((dst_key_flags(x) & DNS_KEYFLAG_KSK) != 0)
1892254885Sdumbbell#define ALG(x) dst_key_alg(x)
1893254885Sdumbbell
1894254885Sdumbbell	/*
1895254885Sdumbbell	 * If we are honoring KSK flags then we need to check that we
1896254885Sdumbbell	 * have both KSK and non-KSK keys that are not revoked per
1897254885Sdumbbell	 * algorithm.
1898254885Sdumbbell	 */
1899254885Sdumbbell	for (i = 0; i < nkeys; i++) {
1900254885Sdumbbell		isc_boolean_t both = ISC_FALSE;
1901254885Sdumbbell
1902254885Sdumbbell		if (!dst_key_isprivate(keys[i]))
1903254885Sdumbbell			continue;
1904254885Sdumbbell
1905254885Sdumbbell		if (check_ksk && !REVOKE(keys[i])) {
1906254885Sdumbbell			isc_boolean_t have_ksk, have_nonksk;
1907254885Sdumbbell			if (KSK(keys[i])) {
1908254885Sdumbbell				have_ksk = ISC_TRUE;
1909254885Sdumbbell				have_nonksk = ISC_FALSE;
1910254885Sdumbbell			} else {
1911254885Sdumbbell				have_ksk = ISC_FALSE;
1912254885Sdumbbell				have_nonksk = ISC_TRUE;
1913254885Sdumbbell			}
1914254885Sdumbbell			for (j = 0; j < nkeys; j++) {
1915254885Sdumbbell				if (j == i || ALG(keys[i]) != ALG(keys[j]))
1916254885Sdumbbell					continue;
1917254885Sdumbbell				if (REVOKE(keys[j]))
1918254885Sdumbbell					continue;
1919254885Sdumbbell				if (KSK(keys[j]))
1920254885Sdumbbell					have_ksk = ISC_TRUE;
1921254885Sdumbbell				else
1922254885Sdumbbell					have_nonksk = ISC_TRUE;
1923254885Sdumbbell				both = have_ksk && have_nonksk;
1924254885Sdumbbell				if (both)
1925254885Sdumbbell					break;
1926254885Sdumbbell			}
1927254885Sdumbbell		}
1928254885Sdumbbell
1929254885Sdumbbell		if (both) {
1930254885Sdumbbell			if (type == dns_rdatatype_dnskey) {
1931254885Sdumbbell				if (!KSK(keys[i]) && keyset_kskonly)
1932254885Sdumbbell					continue;
1933254885Sdumbbell			} else if (KSK(keys[i]))
1934254885Sdumbbell				continue;
1935254885Sdumbbell		} else if (REVOKE(keys[i]) && type != dns_rdatatype_dnskey)
1936254885Sdumbbell			continue;
1937254885Sdumbbell
1938254885Sdumbbell		/* Calculate the signature, creating a RRSIG RDATA. */
1939254885Sdumbbell		CHECK(dns_dnssec_sign(name, &rdataset, keys[i],
1940254885Sdumbbell				      &inception, &expire,
1941282199Sdumbbell				      mctx, &buffer, &sig_rdata));
1942254885Sdumbbell
1943254885Sdumbbell		/* Update the database and journal with the RRSIG. */
1944254885Sdumbbell		/* XXX inefficient - will cause dataset merging */
1945254885Sdumbbell		CHECK(update_one_rr(db, ver, diff, DNS_DIFFOP_ADDRESIGN, name,
1946254885Sdumbbell				    rdataset.ttl, &sig_rdata));
1947254885Sdumbbell		dns_rdata_reset(&sig_rdata);
1948254885Sdumbbell		isc_buffer_init(&buffer, data, sizeof(data));
1949254885Sdumbbell		added_sig = ISC_TRUE;
1950254885Sdumbbell	}
1951254885Sdumbbell	if (!added_sig) {
1952254885Sdumbbell		update_log(client, zone, ISC_LOG_ERROR,
1953254885Sdumbbell			   "found no active private keys, "
1954254885Sdumbbell			   "unable to generate any signatures");
1955254885Sdumbbell		result = ISC_R_NOTFOUND;
1956254885Sdumbbell	}
1957254885Sdumbbell
1958254885Sdumbbell failure:
1959254885Sdumbbell	if (dns_rdataset_isassociated(&rdataset))
1960254885Sdumbbell		dns_rdataset_disassociate(&rdataset);
1961254885Sdumbbell	if (node != NULL)
1962254885Sdumbbell		dns_db_detachnode(db, &node);
1963254885Sdumbbell	return (result);
1964254885Sdumbbell}
1965254885Sdumbbell
1966254885Sdumbbell/*
1967254885Sdumbbell * Delete expired RRsigs and any RRsigs we are about to re-sign.
1968254885Sdumbbell * See also zone.c:del_sigs().
1969254885Sdumbbell */
1970254885Sdumbbellstatic isc_result_t
1971254885Sdumbbelldel_keysigs(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
1972254885Sdumbbell	    dns_diff_t *diff, dst_key_t **keys, unsigned int nkeys)
1973254885Sdumbbell{
1974254885Sdumbbell	isc_result_t result;
1975254885Sdumbbell	dns_dbnode_t *node = NULL;
1976254885Sdumbbell	dns_rdataset_t rdataset;
1977254885Sdumbbell	dns_rdata_t rdata = DNS_RDATA_INIT;
1978254885Sdumbbell	unsigned int i;
1979254885Sdumbbell	dns_rdata_rrsig_t rrsig;
1980254885Sdumbbell	isc_boolean_t found;
1981254885Sdumbbell
1982254885Sdumbbell	dns_rdataset_init(&rdataset);
1983254885Sdumbbell
1984254885Sdumbbell	result = dns_db_findnode(db, name, ISC_FALSE, &node);
1985254885Sdumbbell	if (result == ISC_R_NOTFOUND)
1986254885Sdumbbell		return (ISC_R_SUCCESS);
1987254885Sdumbbell	if (result != ISC_R_SUCCESS)
1988254885Sdumbbell		goto failure;
1989254885Sdumbbell	result = dns_db_findrdataset(db, node, ver, dns_rdatatype_rrsig,
1990254885Sdumbbell				     dns_rdatatype_dnskey, (isc_stdtime_t) 0,
1991254885Sdumbbell				     &rdataset, NULL);
1992254885Sdumbbell	dns_db_detachnode(db, &node);
1993254885Sdumbbell
1994254885Sdumbbell	if (result == ISC_R_NOTFOUND)
1995254885Sdumbbell		return (ISC_R_SUCCESS);
1996254885Sdumbbell	if (result != ISC_R_SUCCESS)
1997254885Sdumbbell		goto failure;
1998254885Sdumbbell
1999254885Sdumbbell	for (result = dns_rdataset_first(&rdataset);
2000282199Sdumbbell	     result == ISC_R_SUCCESS;
2001254885Sdumbbell	     result = dns_rdataset_next(&rdataset)) {
2002254885Sdumbbell		dns_rdataset_current(&rdataset, &rdata);
2003254885Sdumbbell		result = dns_rdata_tostruct(&rdata, &rrsig, NULL);
2004254885Sdumbbell		RUNTIME_CHECK(result == ISC_R_SUCCESS);
2005254885Sdumbbell		found = ISC_FALSE;
2006254885Sdumbbell		for (i = 0; i < nkeys; i++) {
2007254885Sdumbbell			if (rrsig.keyid == dst_key_id(keys[i])) {
2008254885Sdumbbell				found = ISC_TRUE;
2009254885Sdumbbell				if (!dst_key_isprivate(keys[i])) {
2010254885Sdumbbell					/*
2011254885Sdumbbell					 * The re-signing code in zone.c
2012254885Sdumbbell					 * will mark this as offline.
2013254885Sdumbbell					 * Just skip the record for now.
2014254885Sdumbbell					 */
2015254885Sdumbbell					break;
2016254885Sdumbbell				}
2017254885Sdumbbell				result = update_one_rr(db, ver, diff,
2018254885Sdumbbell						       DNS_DIFFOP_DEL, name,
2019254885Sdumbbell						       rdataset.ttl, &rdata);
2020254885Sdumbbell				break;
2021254885Sdumbbell			}
2022254885Sdumbbell		}
2023254885Sdumbbell		/*
2024254885Sdumbbell		 * If there is not a matching DNSKEY then delete the RRSIG.
2025254885Sdumbbell		 */
2026254885Sdumbbell		if (!found)
2027254885Sdumbbell			result = update_one_rr(db, ver, diff, DNS_DIFFOP_DEL,
2028254885Sdumbbell					       name, rdataset.ttl, &rdata);
2029254885Sdumbbell		dns_rdata_reset(&rdata);
2030254885Sdumbbell		if (result != ISC_R_SUCCESS)
2031254885Sdumbbell			break;
2032254885Sdumbbell	}
2033254885Sdumbbell	dns_rdataset_disassociate(&rdataset);
2034254885Sdumbbell	if (result == ISC_R_NOMORE)
2035254885Sdumbbell		result = ISC_R_SUCCESS;
2036254885Sdumbbellfailure:
2037254885Sdumbbell	if (node != NULL)
2038254885Sdumbbell		dns_db_detachnode(db, &node);
2039254885Sdumbbell	return (result);
2040254885Sdumbbell}
2041254885Sdumbbell
2042254885Sdumbbellstatic isc_result_t
2043254885Sdumbbelladd_exposed_sigs(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
2044254885Sdumbbell		 dns_dbversion_t *ver, dns_name_t *name, isc_boolean_t cut,
2045254885Sdumbbell		 dns_diff_t *diff, dst_key_t **keys, unsigned int nkeys,
2046254885Sdumbbell		 isc_stdtime_t inception, isc_stdtime_t expire,
2047254885Sdumbbell		 isc_boolean_t check_ksk, isc_boolean_t keyset_kskonly)
2048254885Sdumbbell{
2049254885Sdumbbell	isc_result_t result;
2050254885Sdumbbell	dns_dbnode_t *node;
2051254885Sdumbbell	dns_rdatasetiter_t *iter;
2052254885Sdumbbell
2053254885Sdumbbell	node = NULL;
2054254885Sdumbbell	result = dns_db_findnode(db, name, ISC_FALSE, &node);
2055254885Sdumbbell	if (result == ISC_R_NOTFOUND)
2056254885Sdumbbell		return (ISC_R_SUCCESS);
2057254885Sdumbbell	if (result != ISC_R_SUCCESS)
2058254885Sdumbbell		return (result);
2059254885Sdumbbell
2060254885Sdumbbell	iter = NULL;
2061254885Sdumbbell	result = dns_db_allrdatasets(db, node, ver,
2062254885Sdumbbell				     (isc_stdtime_t) 0, &iter);
2063254885Sdumbbell	if (result != ISC_R_SUCCESS)
2064254885Sdumbbell		goto cleanup_node;
2065254885Sdumbbell
2066254885Sdumbbell	for (result = dns_rdatasetiter_first(iter);
2067254885Sdumbbell	     result == ISC_R_SUCCESS;
2068254885Sdumbbell	     result = dns_rdatasetiter_next(iter))
2069254885Sdumbbell	{
2070254885Sdumbbell		dns_rdataset_t rdataset;
2071254885Sdumbbell		dns_rdatatype_t type;
2072254885Sdumbbell		isc_boolean_t flag;
2073254885Sdumbbell
2074254885Sdumbbell		dns_rdataset_init(&rdataset);
2075254885Sdumbbell		dns_rdatasetiter_current(iter, &rdataset);
2076254885Sdumbbell		type = rdataset.type;
2077254885Sdumbbell		dns_rdataset_disassociate(&rdataset);
2078254885Sdumbbell
2079254885Sdumbbell		/*
2080254885Sdumbbell		 * We don't need to sign unsigned NSEC records at the cut
2081254885Sdumbbell		 * as they are handled elsewhere.
2082254885Sdumbbell		 */
2083254885Sdumbbell		if ((type == dns_rdatatype_rrsig) ||
2084254885Sdumbbell		    (cut && type != dns_rdatatype_ds))
2085254885Sdumbbell			continue;
2086254885Sdumbbell		result = rrset_exists(db, ver, name, dns_rdatatype_rrsig,
2087254885Sdumbbell				      type, &flag);
2088254885Sdumbbell		if (result != ISC_R_SUCCESS)
2089254885Sdumbbell			goto cleanup_iterator;
2090254885Sdumbbell		if (flag)
2091254885Sdumbbell			continue;;
2092254885Sdumbbell		result = add_sigs(client, zone, db, ver, name, type, diff,
2093254885Sdumbbell					  keys, nkeys, inception, expire,
2094254885Sdumbbell					  check_ksk, keyset_kskonly);
2095254885Sdumbbell		if (result != ISC_R_SUCCESS)
2096254885Sdumbbell			goto cleanup_iterator;
2097254885Sdumbbell	}
2098254885Sdumbbell	if (result == ISC_R_NOMORE)
2099254885Sdumbbell		result = ISC_R_SUCCESS;
2100254885Sdumbbell
2101254885Sdumbbell cleanup_iterator:
2102254885Sdumbbell	dns_rdatasetiter_destroy(&iter);
2103254885Sdumbbell
2104254885Sdumbbell cleanup_node:
2105254885Sdumbbell	dns_db_detachnode(db, &node);
2106254885Sdumbbell
2107254885Sdumbbell	return (result);
2108254885Sdumbbell}
2109254885Sdumbbell
2110254885Sdumbbell/*%
2111254885Sdumbbell * Update RRSIG, NSEC and NSEC3 records affected by an update.  The original
2112254885Sdumbbell * update, including the SOA serial update but excluding the RRSIG & NSEC
2113254885Sdumbbell * changes, is in "diff" and has already been applied to "newver" of "db".
2114254885Sdumbbell * The database version prior to the update is "oldver".
2115254885Sdumbbell *
2116254885Sdumbbell * The necessary RRSIG, NSEC and NSEC3 changes will be applied to "newver"
2117254885Sdumbbell * and added (as a minimal diff) to "diff".
2118254885Sdumbbell *
2119254885Sdumbbell * The RRSIGs generated will be valid for 'sigvalidityinterval' seconds.
2120254885Sdumbbell */
2121254885Sdumbbellstatic isc_result_t
2122254885Sdumbbellupdate_signatures(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
2123254885Sdumbbell		  dns_dbversion_t *oldver, dns_dbversion_t *newver,
2124254885Sdumbbell		  dns_diff_t *diff, isc_uint32_t sigvalidityinterval)
2125254885Sdumbbell{
2126254885Sdumbbell	isc_result_t result;
2127254885Sdumbbell	dns_difftuple_t *t;
2128254885Sdumbbell	dns_diff_t diffnames;
2129254885Sdumbbell	dns_diff_t affected;
2130254885Sdumbbell	dns_diff_t sig_diff;
2131254885Sdumbbell	dns_diff_t nsec_diff;
2132254885Sdumbbell	dns_diff_t nsec_mindiff;
2133254885Sdumbbell	isc_boolean_t flag, build_nsec, build_nsec3;
2134254885Sdumbbell	dst_key_t *zone_keys[MAXZONEKEYS];
2135254885Sdumbbell	unsigned int nkeys = 0;
2136254885Sdumbbell	unsigned int i;
2137254885Sdumbbell	isc_stdtime_t now, inception, expire;
2138254885Sdumbbell	dns_ttl_t nsecttl;
2139254885Sdumbbell	dns_rdata_soa_t soa;
2140254885Sdumbbell	dns_rdata_t rdata = DNS_RDATA_INIT;
2141254885Sdumbbell	dns_rdataset_t rdataset;
2142254885Sdumbbell	dns_dbnode_t *node = NULL;
2143254885Sdumbbell	isc_boolean_t check_ksk, keyset_kskonly;
2144254885Sdumbbell	isc_boolean_t unsecure;
2145254885Sdumbbell	isc_boolean_t cut;
2146254885Sdumbbell	dns_rdatatype_t privatetype = dns_zone_getprivatetype(zone);
2147254885Sdumbbell
2148254885Sdumbbell	dns_diff_init(client->mctx, &diffnames);
2149254885Sdumbbell	dns_diff_init(client->mctx, &affected);
2150254885Sdumbbell
2151254885Sdumbbell	dns_diff_init(client->mctx, &sig_diff);
2152254885Sdumbbell	sig_diff.resign = dns_zone_getsigresigninginterval(zone);
2153254885Sdumbbell	dns_diff_init(client->mctx, &nsec_diff);
2154254885Sdumbbell	dns_diff_init(client->mctx, &nsec_mindiff);
2155254885Sdumbbell
2156254885Sdumbbell	result = find_zone_keys(zone, db, newver, client->mctx,
2157254885Sdumbbell				MAXZONEKEYS, zone_keys, &nkeys);
2158254885Sdumbbell	if (result != ISC_R_SUCCESS) {
2159254885Sdumbbell		update_log(client, zone, ISC_LOG_ERROR,
2160254885Sdumbbell			   "could not get zone keys for secure dynamic update");
2161254885Sdumbbell		goto failure;
2162254885Sdumbbell	}
2163254885Sdumbbell
2164254885Sdumbbell	isc_stdtime_get(&now);
2165254885Sdumbbell	inception = now - 3600; /* Allow for some clock skew. */
2166254885Sdumbbell	expire = now + sigvalidityinterval;
2167254885Sdumbbell
2168254885Sdumbbell	/*
2169254885Sdumbbell	 * Do we look at the KSK flag on the DNSKEY to determining which
2170254885Sdumbbell	 * keys sign which RRsets?  First check the zone option then
2171254885Sdumbbell	 * check the keys flags to make sure at least one has a ksk set
2172254885Sdumbbell	 * and one doesn't.
2173254885Sdumbbell	 */
2174254885Sdumbbell	check_ksk = ISC_TF((dns_zone_getoptions(zone) &
2175254885Sdumbbell			    DNS_ZONEOPT_UPDATECHECKKSK) != 0);
2176254885Sdumbbell	keyset_kskonly = ISC_TF((dns_zone_getoptions(zone) &
2177254885Sdumbbell				DNS_ZONEOPT_DNSKEYKSKONLY) != 0);
2178254885Sdumbbell
2179254885Sdumbbell	/*
2180254885Sdumbbell	 * Get the NSEC/NSEC3 TTL from the SOA MINIMUM field.
2181254885Sdumbbell	 */
2182254885Sdumbbell	CHECK(dns_db_findnode(db, dns_db_origin(db), ISC_FALSE, &node));
2183254885Sdumbbell	dns_rdataset_init(&rdataset);
2184254885Sdumbbell	CHECK(dns_db_findrdataset(db, node, newver, dns_rdatatype_soa, 0,
2185254885Sdumbbell				  (isc_stdtime_t) 0, &rdataset, NULL));
2186254885Sdumbbell	CHECK(dns_rdataset_first(&rdataset));
2187254885Sdumbbell	dns_rdataset_current(&rdataset, &rdata);
2188254885Sdumbbell	CHECK(dns_rdata_tostruct(&rdata, &soa, NULL));
2189254885Sdumbbell	nsecttl = soa.minimum;
2190254885Sdumbbell	dns_rdataset_disassociate(&rdataset);
2191254885Sdumbbell	dns_db_detachnode(db, &node);
2192254885Sdumbbell
2193254885Sdumbbell	/*
2194254885Sdumbbell	 * Find all RRsets directly affected by the update, and
2195254885Sdumbbell	 * update their RRSIGs.  Also build a list of names affected
2196254885Sdumbbell	 * by the update in "diffnames".
2197254885Sdumbbell	 */
2198254885Sdumbbell	CHECK(dns_diff_sort(diff, temp_order));
2199254885Sdumbbell
2200254885Sdumbbell	t = ISC_LIST_HEAD(diff->tuples);
2201254885Sdumbbell	while (t != NULL) {
2202254885Sdumbbell		dns_name_t *name = &t->name;
2203254885Sdumbbell		/* Now "name" is a new, unique name affected by the update. */
2204254885Sdumbbell
2205254885Sdumbbell		CHECK(namelist_append_name(&diffnames, name));
2206254885Sdumbbell
2207254885Sdumbbell		while (t != NULL && dns_name_equal(&t->name, name)) {
2208254885Sdumbbell			dns_rdatatype_t type;
2209254885Sdumbbell			type = t->rdata.type;
2210254885Sdumbbell
2211254885Sdumbbell			/*
2212254885Sdumbbell			 * Now "name" and "type" denote a new unique RRset
2213254885Sdumbbell			 * affected by the update.
2214254885Sdumbbell			 */
2215254885Sdumbbell
2216254885Sdumbbell			/* Don't sign RRSIGs. */
2217254885Sdumbbell			if (type == dns_rdatatype_rrsig)
2218254885Sdumbbell				goto skip;
2219254885Sdumbbell
2220254885Sdumbbell			/*
2221254885Sdumbbell			 * Delete all old RRSIGs covering this type, since they
2222254885Sdumbbell			 * are all invalid when the signed RRset has changed.
2223254885Sdumbbell			 * We may not be able to recreate all of them - tough.
2224254885Sdumbbell			 * Special case changes to the zone's DNSKEY records
2225254885Sdumbbell			 * to support offline KSKs.
2226254885Sdumbbell			 */
2227254885Sdumbbell			if (type == dns_rdatatype_dnskey)
2228254885Sdumbbell				del_keysigs(db, newver, name, &sig_diff,
2229254885Sdumbbell					    zone_keys, nkeys);
2230254885Sdumbbell			else
2231254885Sdumbbell				CHECK(delete_if(true_p, db, newver, name,
2232254885Sdumbbell						dns_rdatatype_rrsig, type,
2233254885Sdumbbell						NULL, &sig_diff));
2234254885Sdumbbell
2235254885Sdumbbell			/*
2236254885Sdumbbell			 * If this RRset is still visible after the update,
2237254885Sdumbbell			 * add a new signature for it.
2238254885Sdumbbell			 */
2239254885Sdumbbell			CHECK(rrset_visible(db, newver, name, type, &flag));
2240254885Sdumbbell			if (flag) {
2241254885Sdumbbell				CHECK(add_sigs(client, zone, db, newver, name,
2242254885Sdumbbell					       type, &sig_diff, zone_keys,
2243254885Sdumbbell					       nkeys, inception, expire,
2244254885Sdumbbell					       check_ksk, keyset_kskonly));
2245254885Sdumbbell			}
2246254885Sdumbbell		skip:
2247254885Sdumbbell			/* Skip any other updates to the same RRset. */
2248254885Sdumbbell			while (t != NULL &&
2249254885Sdumbbell			       dns_name_equal(&t->name, name) &&
2250254885Sdumbbell			       t->rdata.type == type)
2251254885Sdumbbell			{
2252254885Sdumbbell				t = ISC_LIST_NEXT(t, link);
2253254885Sdumbbell			}
2254254885Sdumbbell		}
2255254885Sdumbbell	}
2256254885Sdumbbell	update_log(client, zone, ISC_LOG_DEBUG(3), "updated data signatures");
2257254885Sdumbbell
2258254885Sdumbbell	/* Remove orphaned NSECs and RRSIG NSECs. */
2259254885Sdumbbell	for (t = ISC_LIST_HEAD(diffnames.tuples);
2260254885Sdumbbell	     t != NULL;
2261254885Sdumbbell	     t = ISC_LIST_NEXT(t, link))
2262254885Sdumbbell	{
2263254885Sdumbbell		CHECK(non_nsec_rrset_exists(db, newver, &t->name, &flag));
2264254885Sdumbbell		if (! flag) {
2265254885Sdumbbell			CHECK(delete_if(true_p, db, newver, &t->name,
2266254885Sdumbbell					dns_rdatatype_any, 0,
2267254885Sdumbbell					NULL, &sig_diff));
2268254885Sdumbbell		}
2269254885Sdumbbell	}
2270254885Sdumbbell	update_log(client, zone, ISC_LOG_DEBUG(3),
2271254885Sdumbbell		   "removed any orphaned NSEC records");
2272254885Sdumbbell
2273254885Sdumbbell	/*
2274254885Sdumbbell	 * See if we need to build NSEC or NSEC3 chains.
2275254885Sdumbbell	 */
2276254885Sdumbbell	CHECK(dns_private_chains(db, newver, privatetype, &build_nsec,
2277254885Sdumbbell				 &build_nsec3));
2278254885Sdumbbell	if (!build_nsec)
2279254885Sdumbbell		goto update_nsec3;
2280254885Sdumbbell
2281254885Sdumbbell	update_log(client, zone, ISC_LOG_DEBUG(3), "rebuilding NSEC chain");
2282254885Sdumbbell
2283254885Sdumbbell	/*
2284254885Sdumbbell	 * When a name is created or deleted, its predecessor needs to
2285254885Sdumbbell	 * have its NSEC updated.
2286254885Sdumbbell	 */
2287254885Sdumbbell	for (t = ISC_LIST_HEAD(diffnames.tuples);
2288254885Sdumbbell	     t != NULL;
2289254885Sdumbbell	     t = ISC_LIST_NEXT(t, link))
2290254885Sdumbbell	{
2291254885Sdumbbell		isc_boolean_t existed, exists;
2292254885Sdumbbell		dns_fixedname_t fixedname;
2293254885Sdumbbell		dns_name_t *prevname;
2294254885Sdumbbell
2295254885Sdumbbell		dns_fixedname_init(&fixedname);
2296254885Sdumbbell		prevname = dns_fixedname_name(&fixedname);
2297254885Sdumbbell
2298254885Sdumbbell		CHECK(name_exists(db, oldver, &t->name, &existed));
2299254885Sdumbbell		CHECK(name_exists(db, newver, &t->name, &exists));
2300254885Sdumbbell		if (exists == existed)
2301254885Sdumbbell			continue;
2302254885Sdumbbell
2303254885Sdumbbell		/*
2304254885Sdumbbell		 * Find the predecessor.
2305254885Sdumbbell		 * When names become obscured or unobscured in this update
2306254885Sdumbbell		 * transaction, we may find the wrong predecessor because
2307254885Sdumbbell		 * the NSECs have not yet been updated to reflect the delegation
2308254885Sdumbbell		 * change.  This should not matter because in this case,
2309254885Sdumbbell		 * the correct predecessor is either the delegation node or
2310254885Sdumbbell		 * a newly unobscured node, and those nodes are on the
2311254885Sdumbbell		 * "affected" list in any case.
2312254885Sdumbbell		 */
2313254885Sdumbbell		CHECK(next_active(client, zone, db, newver,
2314254885Sdumbbell				  &t->name, prevname, ISC_FALSE));
2315254885Sdumbbell		CHECK(namelist_append_name(&affected, prevname));
2316254885Sdumbbell	}
2317254885Sdumbbell
2318254885Sdumbbell	/*
2319254885Sdumbbell	 * Find names potentially affected by delegation changes
2320254885Sdumbbell	 * (obscured by adding an NS or DNAME, or unobscured by
2321254885Sdumbbell	 * removing one).
2322254885Sdumbbell	 */
2323254885Sdumbbell	for (t = ISC_LIST_HEAD(diffnames.tuples);
2324254885Sdumbbell	     t != NULL;
2325254885Sdumbbell	     t = ISC_LIST_NEXT(t, link))
2326254885Sdumbbell	{
2327254885Sdumbbell		isc_boolean_t ns_existed, dname_existed;
2328254885Sdumbbell		isc_boolean_t ns_exists, dname_exists;
2329254885Sdumbbell
2330254885Sdumbbell		CHECK(rrset_exists(db, oldver, &t->name, dns_rdatatype_ns, 0,
2331254885Sdumbbell				   &ns_existed));
2332254885Sdumbbell		CHECK(rrset_exists(db, oldver, &t->name, dns_rdatatype_dname, 0,
2333254885Sdumbbell				   &dname_existed));
2334254885Sdumbbell		CHECK(rrset_exists(db, newver, &t->name, dns_rdatatype_ns, 0,
2335254885Sdumbbell				   &ns_exists));
2336254885Sdumbbell		CHECK(rrset_exists(db, newver, &t->name, dns_rdatatype_dname, 0,
2337254885Sdumbbell				   &dname_exists));
2338254885Sdumbbell		if ((ns_exists || dname_exists) == (ns_existed || dname_existed))
2339254885Sdumbbell			continue;
2340254885Sdumbbell		/*
2341254885Sdumbbell		 * There was a delegation change.  Mark all subdomains
2342254885Sdumbbell		 * of t->name as potentially needing a NSEC update.
2343254885Sdumbbell		 */
2344254885Sdumbbell		CHECK(namelist_append_subdomain(db, &t->name, &affected));
2345254885Sdumbbell	}
2346254885Sdumbbell
2347254885Sdumbbell	ISC_LIST_APPENDLIST(affected.tuples, diffnames.tuples, link);
2348254885Sdumbbell	INSIST(ISC_LIST_EMPTY(diffnames.tuples));
2349254885Sdumbbell
2350254885Sdumbbell	CHECK(uniqify_name_list(&affected));
2351254885Sdumbbell
2352254885Sdumbbell	/*
2353254885Sdumbbell	 * Determine which names should have NSECs, and delete/create
2354254885Sdumbbell	 * NSECs to make it so.  We don't know the final NSEC targets yet,
2355254885Sdumbbell	 * so we just create placeholder NSECs with arbitrary contents
2356254885Sdumbbell	 * to indicate that their respective owner names should be part of
2357254885Sdumbbell	 * the NSEC chain.
2358254885Sdumbbell	 */
2359254885Sdumbbell	for (t = ISC_LIST_HEAD(affected.tuples);
2360254885Sdumbbell	     t != NULL;
2361254885Sdumbbell	     t = ISC_LIST_NEXT(t, link))
2362254885Sdumbbell	{
2363254885Sdumbbell		isc_boolean_t exists;
2364254885Sdumbbell		dns_name_t *name = &t->name;
2365254885Sdumbbell
2366254885Sdumbbell		CHECK(name_exists(db, newver, name, &exists));
2367254885Sdumbbell		if (! exists)
2368254885Sdumbbell			continue;
2369254885Sdumbbell		CHECK(is_active(db, newver, name, &flag, &cut, NULL));
2370254885Sdumbbell		if (!flag) {
2371254885Sdumbbell			/*
2372254885Sdumbbell			 * This name is obscured.  Delete any
2373254885Sdumbbell			 * existing NSEC record.
2374254885Sdumbbell			 */
2375254885Sdumbbell			CHECK(delete_if(true_p, db, newver, name,
2376254885Sdumbbell					dns_rdatatype_nsec, 0,
2377254885Sdumbbell					NULL, &nsec_diff));
2378254885Sdumbbell			CHECK(delete_if(rrsig_p, db, newver, name,
2379254885Sdumbbell					dns_rdatatype_any, 0, NULL, diff));
2380254885Sdumbbell		} else {
2381254885Sdumbbell			/*
2382254885Sdumbbell			 * This name is not obscured.  It needs to have a
2383254885Sdumbbell			 * NSEC unless it is the at the origin, in which
2384254885Sdumbbell			 * case it should already exist if there is a complete
2385254885Sdumbbell			 * NSEC chain and if there isn't a complete NSEC chain
2386254885Sdumbbell			 * we don't want to add one as that would signal that
2387254885Sdumbbell			 * there is a complete NSEC chain.
2388254885Sdumbbell			 */
2389254885Sdumbbell			if (!dns_name_equal(name, dns_db_origin(db))) {
2390254885Sdumbbell				CHECK(rrset_exists(db, newver, name,
2391254885Sdumbbell						   dns_rdatatype_nsec, 0,
2392254885Sdumbbell						   &flag));
2393254885Sdumbbell				if (!flag)
2394254885Sdumbbell					CHECK(add_placeholder_nsec(db, newver,
2395254885Sdumbbell								   name, diff));
2396254885Sdumbbell			}
2397254885Sdumbbell			CHECK(add_exposed_sigs(client, zone, db, newver, name,
2398254885Sdumbbell					       cut, &sig_diff, zone_keys, nkeys,
2399254885Sdumbbell					       inception, expire, check_ksk,
2400254885Sdumbbell					       keyset_kskonly));
2401254885Sdumbbell		}
2402254885Sdumbbell	}
2403254885Sdumbbell
2404254885Sdumbbell	/*
2405254885Sdumbbell	 * Now we know which names are part of the NSEC chain.
2406254885Sdumbbell	 * Make them all point at their correct targets.
2407254885Sdumbbell	 */
2408254885Sdumbbell	for (t = ISC_LIST_HEAD(affected.tuples);
2409254885Sdumbbell	     t != NULL;
2410254885Sdumbbell	     t = ISC_LIST_NEXT(t, link))
2411254885Sdumbbell	{
2412254885Sdumbbell		CHECK(rrset_exists(db, newver, &t->name,
2413254885Sdumbbell				   dns_rdatatype_nsec, 0, &flag));
2414254885Sdumbbell		if (flag) {
2415254885Sdumbbell			/*
2416254885Sdumbbell			 * There is a NSEC, but we don't know if it is correct.
2417254885Sdumbbell			 * Delete it and create a correct one to be sure.
2418254885Sdumbbell			 * If the update was unnecessary, the diff minimization
2419254885Sdumbbell			 * will take care of eliminating it from the journal,
2420254885Sdumbbell			 * IXFRs, etc.
2421254885Sdumbbell			 *
2422254885Sdumbbell			 * The RRSIG bit should always be set in the NSECs
2423254885Sdumbbell			 * we generate, because they will all get RRSIG NSECs.
2424254885Sdumbbell			 * (XXX what if the zone keys are missing?).
2425254885Sdumbbell			 * Because the RRSIG NSECs have not necessarily been
2426254885Sdumbbell			 * created yet, the correctness of the bit mask relies
2427254885Sdumbbell			 * on the assumption that NSECs are only created if
2428254885Sdumbbell			 * there is other data, and if there is other data,
2429254885Sdumbbell			 * there are other RRSIGs.
2430254885Sdumbbell			 */
2431254885Sdumbbell			CHECK(add_nsec(client, zone, db, newver, &t->name,
2432254885Sdumbbell				       nsecttl, &nsec_diff));
2433254885Sdumbbell		}
2434254885Sdumbbell	}
2435282199Sdumbbell
2436254885Sdumbbell	/*
2437254885Sdumbbell	 * Minimize the set of NSEC updates so that we don't
2438254885Sdumbbell	 * have to regenerate the RRSIG NSECs for NSECs that were
2439254885Sdumbbell	 * replaced with identical ones.
2440254885Sdumbbell	 */
2441254885Sdumbbell	while ((t = ISC_LIST_HEAD(nsec_diff.tuples)) != NULL) {
2442254885Sdumbbell		ISC_LIST_UNLINK(nsec_diff.tuples, t, link);
2443254885Sdumbbell		dns_diff_appendminimal(&nsec_mindiff, &t);
2444254885Sdumbbell	}
2445254885Sdumbbell
2446254885Sdumbbell	update_log(client, zone, ISC_LOG_DEBUG(3),
2447254885Sdumbbell		   "signing rebuilt NSEC chain");
2448254885Sdumbbell
2449254885Sdumbbell	/* Update RRSIG NSECs. */
2450254885Sdumbbell	for (t = ISC_LIST_HEAD(nsec_mindiff.tuples);
2451254885Sdumbbell	     t != NULL;
2452254885Sdumbbell	     t = ISC_LIST_NEXT(t, link))
2453254885Sdumbbell	{
2454254885Sdumbbell		if (t->op == DNS_DIFFOP_DEL) {
2455254885Sdumbbell			CHECK(delete_if(true_p, db, newver, &t->name,
2456254885Sdumbbell					dns_rdatatype_rrsig, dns_rdatatype_nsec,
2457254885Sdumbbell					NULL, &sig_diff));
2458254885Sdumbbell		} else if (t->op == DNS_DIFFOP_ADD) {
2459254885Sdumbbell			CHECK(add_sigs(client, zone, db, newver, &t->name,
2460254885Sdumbbell				       dns_rdatatype_nsec, &sig_diff,
2461254885Sdumbbell				       zone_keys, nkeys, inception, expire,
2462254885Sdumbbell				       check_ksk, keyset_kskonly));
2463254885Sdumbbell		} else {
2464254885Sdumbbell			INSIST(0);
2465254885Sdumbbell		}
2466254885Sdumbbell	}
2467254885Sdumbbell
2468254885Sdumbbell update_nsec3:
2469254885Sdumbbell
2470254885Sdumbbell	/* Record our changes for the journal. */
2471254885Sdumbbell	while ((t = ISC_LIST_HEAD(sig_diff.tuples)) != NULL) {
2472254885Sdumbbell		ISC_LIST_UNLINK(sig_diff.tuples, t, link);
2473254885Sdumbbell		dns_diff_appendminimal(diff, &t);
2474254885Sdumbbell	}
2475254885Sdumbbell	while ((t = ISC_LIST_HEAD(nsec_mindiff.tuples)) != NULL) {
2476254885Sdumbbell		ISC_LIST_UNLINK(nsec_mindiff.tuples, t, link);
2477254885Sdumbbell		dns_diff_appendminimal(diff, &t);
2478254885Sdumbbell	}
2479254885Sdumbbell
2480254885Sdumbbell	INSIST(ISC_LIST_EMPTY(sig_diff.tuples));
2481254885Sdumbbell	INSIST(ISC_LIST_EMPTY(nsec_diff.tuples));
2482254885Sdumbbell	INSIST(ISC_LIST_EMPTY(nsec_mindiff.tuples));
2483254885Sdumbbell
2484254885Sdumbbell	if (!build_nsec3) {
2485254885Sdumbbell		update_log(client, zone, ISC_LOG_DEBUG(3),
2486254885Sdumbbell			   "no NSEC3 chains to rebuild");
2487254885Sdumbbell		goto failure;
2488254885Sdumbbell	}
2489254885Sdumbbell
2490254885Sdumbbell	update_log(client, zone, ISC_LOG_DEBUG(3), "rebuilding NSEC3 chains");
2491254885Sdumbbell
2492254885Sdumbbell	dns_diff_clear(&diffnames);
2493254885Sdumbbell	dns_diff_clear(&affected);
2494254885Sdumbbell
2495254885Sdumbbell	CHECK(dns_diff_sort(diff, temp_order));
2496254885Sdumbbell
2497254885Sdumbbell	/*
2498254885Sdumbbell	 * Find names potentially affected by delegation changes
2499254885Sdumbbell	 * (obscured by adding an NS or DNAME, or unobscured by
2500254885Sdumbbell	 * removing one).
2501254885Sdumbbell	 */
2502254885Sdumbbell	t = ISC_LIST_HEAD(diff->tuples);
2503254885Sdumbbell	while (t != NULL) {
2504254885Sdumbbell		dns_name_t *name = &t->name;
2505254885Sdumbbell
2506254885Sdumbbell		isc_boolean_t ns_existed, dname_existed;
2507254885Sdumbbell		isc_boolean_t ns_exists, dname_exists;
2508254885Sdumbbell		isc_boolean_t exists, existed;
2509254885Sdumbbell
2510254885Sdumbbell		if (t->rdata.type == dns_rdatatype_nsec ||
2511254885Sdumbbell		    t->rdata.type == dns_rdatatype_rrsig) {
2512254885Sdumbbell			t = ISC_LIST_NEXT(t, link);
2513254885Sdumbbell			continue;
2514254885Sdumbbell		}
2515254885Sdumbbell
2516254885Sdumbbell		CHECK(namelist_append_name(&affected, name));
2517254885Sdumbbell
2518254885Sdumbbell		CHECK(rrset_exists(db, oldver, name, dns_rdatatype_ns, 0,
2519254885Sdumbbell				   &ns_existed));
2520254885Sdumbbell		CHECK(rrset_exists(db, oldver, name, dns_rdatatype_dname, 0,
2521254885Sdumbbell				   &dname_existed));
2522254885Sdumbbell		CHECK(rrset_exists(db, newver, name, dns_rdatatype_ns, 0,
2523254885Sdumbbell				   &ns_exists));
2524254885Sdumbbell		CHECK(rrset_exists(db, newver, name, dns_rdatatype_dname, 0,
2525254885Sdumbbell				   &dname_exists));
2526254885Sdumbbell
2527254885Sdumbbell		exists = ns_exists || dname_exists;
2528254885Sdumbbell		existed = ns_existed || dname_existed;
2529254885Sdumbbell		if (exists == existed)
2530254885Sdumbbell			goto nextname;
2531254885Sdumbbell		/*
2532254885Sdumbbell		 * There was a delegation change.  Mark all subdomains
2533254885Sdumbbell		 * of t->name as potentially needing a NSEC3 update.
2534254885Sdumbbell		 */
2535254885Sdumbbell		CHECK(namelist_append_subdomain(db, name, &affected));
2536254885Sdumbbell
2537254885Sdumbbell	nextname:
2538254885Sdumbbell		while (t != NULL && dns_name_equal(&t->name, name))
2539254885Sdumbbell			t = ISC_LIST_NEXT(t, link);
2540254885Sdumbbell	}
2541254885Sdumbbell
2542254885Sdumbbell	for (t = ISC_LIST_HEAD(affected.tuples);
2543254885Sdumbbell	     t != NULL;
2544254885Sdumbbell	     t = ISC_LIST_NEXT(t, link)) {
2545254885Sdumbbell		dns_name_t *name = &t->name;
2546254885Sdumbbell
2547254885Sdumbbell		unsecure = ISC_FALSE;	/* Silence compiler warning. */
2548254885Sdumbbell		CHECK(is_active(db, newver, name, &flag, &cut, &unsecure));
2549254885Sdumbbell
2550254885Sdumbbell		if (!flag) {
2551254885Sdumbbell			CHECK(delete_if(rrsig_p, db, newver, name,
2552254885Sdumbbell					dns_rdatatype_any, 0, NULL, diff));
2553254885Sdumbbell			CHECK(dns_nsec3_delnsec3sx(db, newver, name,
2554254885Sdumbbell						   privatetype, &nsec_diff));
2555254885Sdumbbell		} else {
2556254885Sdumbbell			CHECK(add_exposed_sigs(client, zone, db, newver, name,
2557282199Sdumbbell					       cut, &sig_diff, zone_keys, nkeys,
2558254885Sdumbbell					       inception, expire, check_ksk,
2559254885Sdumbbell					       keyset_kskonly));
2560254885Sdumbbell			CHECK(dns_nsec3_addnsec3sx(db, newver, name, nsecttl,
2561254885Sdumbbell						   unsecure, privatetype,
2562254885Sdumbbell						   &nsec_diff));
2563254885Sdumbbell		}
2564254885Sdumbbell	}
2565254885Sdumbbell
2566254885Sdumbbell	/*
2567254885Sdumbbell	 * Minimize the set of NSEC3 updates so that we don't
2568254885Sdumbbell	 * have to regenerate the RRSIG NSEC3s for NSEC3s that were
2569254885Sdumbbell	 * replaced with identical ones.
2570254885Sdumbbell	 */
2571254885Sdumbbell	while ((t = ISC_LIST_HEAD(nsec_diff.tuples)) != NULL) {
2572254885Sdumbbell		ISC_LIST_UNLINK(nsec_diff.tuples, t, link);
2573254885Sdumbbell		dns_diff_appendminimal(&nsec_mindiff, &t);
2574254885Sdumbbell	}
2575254885Sdumbbell
2576254885Sdumbbell	update_log(client, zone, ISC_LOG_DEBUG(3),
2577254885Sdumbbell		   "signing rebuilt NSEC3 chain");
2578254885Sdumbbell
2579254885Sdumbbell	/* Update RRSIG NSEC3s. */
2580254885Sdumbbell	for (t = ISC_LIST_HEAD(nsec_mindiff.tuples);
2581254885Sdumbbell	     t != NULL;
2582254885Sdumbbell	     t = ISC_LIST_NEXT(t, link))
2583254885Sdumbbell	{
2584254885Sdumbbell		if (t->op == DNS_DIFFOP_DEL) {
2585254885Sdumbbell			CHECK(delete_if(true_p, db, newver, &t->name,
2586254885Sdumbbell					dns_rdatatype_rrsig,
2587254885Sdumbbell					dns_rdatatype_nsec3,
2588254885Sdumbbell					NULL, &sig_diff));
2589254885Sdumbbell		} else if (t->op == DNS_DIFFOP_ADD) {
2590254885Sdumbbell			CHECK(add_sigs(client, zone, db, newver, &t->name,
2591254885Sdumbbell				       dns_rdatatype_nsec3,
2592254885Sdumbbell				       &sig_diff, zone_keys, nkeys,
2593254885Sdumbbell				       inception, expire, check_ksk,
2594254885Sdumbbell				       keyset_kskonly));
2595254885Sdumbbell		} else {
2596254885Sdumbbell			INSIST(0);
2597254885Sdumbbell		}
2598254885Sdumbbell	}
2599254885Sdumbbell
2600254885Sdumbbell	/* Record our changes for the journal. */
2601254885Sdumbbell	while ((t = ISC_LIST_HEAD(sig_diff.tuples)) != NULL) {
2602254885Sdumbbell		ISC_LIST_UNLINK(sig_diff.tuples, t, link);
2603254885Sdumbbell		dns_diff_appendminimal(diff, &t);
2604254885Sdumbbell	}
2605254885Sdumbbell	while ((t = ISC_LIST_HEAD(nsec_mindiff.tuples)) != NULL) {
2606254885Sdumbbell		ISC_LIST_UNLINK(nsec_mindiff.tuples, t, link);
2607254885Sdumbbell		dns_diff_appendminimal(diff, &t);
2608254885Sdumbbell	}
2609254885Sdumbbell
2610254885Sdumbbell	INSIST(ISC_LIST_EMPTY(sig_diff.tuples));
2611254885Sdumbbell	INSIST(ISC_LIST_EMPTY(nsec_diff.tuples));
2612254885Sdumbbell	INSIST(ISC_LIST_EMPTY(nsec_mindiff.tuples));
2613254885Sdumbbell
2614254885Sdumbbell failure:
2615254885Sdumbbell	dns_diff_clear(&sig_diff);
2616254885Sdumbbell	dns_diff_clear(&nsec_diff);
2617254885Sdumbbell	dns_diff_clear(&nsec_mindiff);
2618254885Sdumbbell
2619254885Sdumbbell	dns_diff_clear(&affected);
2620254885Sdumbbell	dns_diff_clear(&diffnames);
2621254885Sdumbbell
2622282199Sdumbbell	for (i = 0; i < nkeys; i++)
2623254885Sdumbbell		dst_key_free(&zone_keys[i]);
2624254885Sdumbbell
2625254885Sdumbbell	return (result);
2626254885Sdumbbell}
2627254885Sdumbbell
2628254885Sdumbbell
2629254885Sdumbbell/**************************************************************************/
2630254885Sdumbbell/*%
2631254885Sdumbbell * The actual update code in all its glory.  We try to follow
2632254885Sdumbbell * the RFC2136 pseudocode as closely as possible.
2633254885Sdumbbell */
2634254885Sdumbbell
2635254885Sdumbbellstatic isc_result_t
2636254885Sdumbbellsend_update_event(ns_client_t *client, dns_zone_t *zone) {
2637254885Sdumbbell	isc_result_t result = ISC_R_SUCCESS;
2638254885Sdumbbell	update_event_t *event = NULL;
2639254885Sdumbbell	isc_task_t *zonetask = NULL;
2640254885Sdumbbell	ns_client_t *evclient;
2641254885Sdumbbell
2642254885Sdumbbell	event = (update_event_t *)
2643254885Sdumbbell		isc_event_allocate(client->mctx, client, DNS_EVENT_UPDATE,
2644254885Sdumbbell				   update_action, NULL, sizeof(*event));
2645254885Sdumbbell	if (event == NULL)
2646254885Sdumbbell		FAIL(ISC_R_NOMEMORY);
2647254885Sdumbbell	event->zone = zone;
2648254885Sdumbbell	event->result = ISC_R_SUCCESS;
2649254885Sdumbbell
2650254885Sdumbbell	evclient = NULL;
2651254885Sdumbbell	ns_client_attach(client, &evclient);
2652254885Sdumbbell	INSIST(client->nupdates == 0);
2653254885Sdumbbell	client->nupdates++;
2654254885Sdumbbell	event->ev_arg = evclient;
2655254885Sdumbbell
2656254885Sdumbbell	dns_zone_gettask(zone, &zonetask);
2657254885Sdumbbell	isc_task_send(zonetask, ISC_EVENT_PTR(&event));
2658254885Sdumbbell
2659254885Sdumbbell failure:
2660254885Sdumbbell	if (event != NULL)
2661254885Sdumbbell		isc_event_free(ISC_EVENT_PTR(&event));
2662254885Sdumbbell	return (result);
2663254885Sdumbbell}
2664254885Sdumbbell
2665254885Sdumbbellstatic void
2666254885Sdumbbellrespond(ns_client_t *client, isc_result_t result) {
2667254885Sdumbbell	isc_result_t msg_result;
2668254885Sdumbbell
2669254885Sdumbbell	msg_result = dns_message_reply(client->message, ISC_TRUE);
2670254885Sdumbbell	if (msg_result != ISC_R_SUCCESS)
2671254885Sdumbbell		goto msg_failure;
2672254885Sdumbbell	client->message->rcode = dns_result_torcode(result);
2673254885Sdumbbell
2674254885Sdumbbell	ns_client_send(client);
2675254885Sdumbbell	return;
2676254885Sdumbbell
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