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