]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - 6/contrib/bind9/bin/named/update.c
Clone Kip's Xen on stable/6 tree so that I can work on improving FreeBSD/amd64
[FreeBSD/FreeBSD.git] / 6 / contrib / bind9 / bin / named / update.c
1 /*
2  * Copyright (C) 2004-2008  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.88.2.5.2.35 2008/01/17 23:45:27 tbox Exp $ */
19
20 #include <config.h>
21
22 #include <isc/print.h>
23 #include <isc/string.h>
24 #include <isc/taskpool.h>
25 #include <isc/util.h>
26
27 #include <dns/db.h>
28 #include <dns/dbiterator.h>
29 #include <dns/diff.h>
30 #include <dns/dnssec.h>
31 #include <dns/events.h>
32 #include <dns/fixedname.h>
33 #include <dns/journal.h>
34 #include <dns/message.h>
35 #include <dns/nsec.h>
36 #include <dns/rdataclass.h>
37 #include <dns/rdataset.h>
38 #include <dns/rdatasetiter.h>
39 #include <dns/rdatastruct.h>
40 #include <dns/rdatatype.h>
41 #include <dns/soa.h>
42 #include <dns/ssu.h>
43 #include <dns/view.h>
44 #include <dns/zone.h>
45 #include <dns/zt.h>
46
47 #include <named/client.h>
48 #include <named/log.h>
49 #include <named/update.h>
50
51 /*
52  * This module implements dynamic update as in RFC2136.
53  */
54
55 /*
56   XXX TODO:
57   - document strict minimality
58 */
59
60 /**************************************************************************/
61
62 /*
63  * Log level for tracing dynamic update protocol requests.
64  */
65 #define LOGLEVEL_PROTOCOL       ISC_LOG_INFO
66
67 /*
68  * Log level for low-level debug tracing.
69  */
70 #define LOGLEVEL_DEBUG          ISC_LOG_DEBUG(8)
71
72 /*
73  * Check an operation for failure.  These macros all assume that
74  * the function using them has a 'result' variable and a 'failure'
75  * label.
76  */
77 #define CHECK(op) \
78         do { result = (op);                                      \
79                if (result != ISC_R_SUCCESS) goto failure;        \
80         } while (0)
81
82 /*
83  * Fail unconditionally with result 'code', which must not
84  * be ISC_R_SUCCESS.  The reason for failure presumably has
85  * been logged already.
86  *
87  * The test against ISC_R_SUCCESS is there to keep the Solaris compiler
88  * from complaining about "end-of-loop code not reached".
89  */
90
91 #define FAIL(code) \
92         do {                                                    \
93                 result = (code);                                \
94                 if (result != ISC_R_SUCCESS) goto failure;      \
95         } while (0)
96
97 /*
98  * Fail unconditionally and log as a client error.
99  * The test against ISC_R_SUCCESS is there to keep the Solaris compiler
100  * from complaining about "end-of-loop code not reached".
101  */
102 #define FAILC(code, msg) \
103         do {                                                    \
104                 const char *_what = "failed";                   \
105                 result = (code);                                \
106                 switch (result) {                               \
107                 case DNS_R_NXDOMAIN:                            \
108                 case DNS_R_YXDOMAIN:                            \
109                 case DNS_R_YXRRSET:                             \
110                 case DNS_R_NXRRSET:                             \
111                         _what = "unsuccessful";                 \
112                 }                                               \
113                 update_log(client, zone, LOGLEVEL_PROTOCOL,     \
114                               "update %s: %s (%s)", _what,      \
115                               msg, isc_result_totext(result));  \
116                 if (result != ISC_R_SUCCESS) goto failure;      \
117         } while (0)
118
119 #define FAILN(code, name, msg) \
120         do {                                                            \
121                 const char *_what = "failed";                           \
122                 result = (code);                                        \
123                 switch (result) {                                       \
124                 case DNS_R_NXDOMAIN:                                    \
125                 case DNS_R_YXDOMAIN:                                    \
126                 case DNS_R_YXRRSET:                                     \
127                 case DNS_R_NXRRSET:                                     \
128                         _what = "unsuccessful";                         \
129                 }                                                       \
130                 if (isc_log_wouldlog(ns_g_lctx, LOGLEVEL_PROTOCOL)) {   \
131                         char _nbuf[DNS_NAME_FORMATSIZE];                \
132                         dns_name_format(name, _nbuf, sizeof(_nbuf));    \
133                         update_log(client, zone, LOGLEVEL_PROTOCOL,     \
134                                    "update %s: %s: %s (%s)", _what, _nbuf, \
135                                    msg, isc_result_totext(result));     \
136                 }                                                       \
137                 if (result != ISC_R_SUCCESS) goto failure;              \
138         } while (0)
139
140 #define FAILNT(code, name, type, msg) \
141         do {                                                            \
142                 const char *_what = "failed";                           \
143                 result = (code);                                        \
144                 switch (result) {                                       \
145                 case DNS_R_NXDOMAIN:                                    \
146                 case DNS_R_YXDOMAIN:                                    \
147                 case DNS_R_YXRRSET:                                     \
148                 case DNS_R_NXRRSET:                                     \
149                         _what = "unsuccessful";                         \
150                 }                                                       \
151                 if (isc_log_wouldlog(ns_g_lctx, LOGLEVEL_PROTOCOL)) {   \
152                         char _nbuf[DNS_NAME_FORMATSIZE];                \
153                         char _tbuf[DNS_RDATATYPE_FORMATSIZE];           \
154                         dns_name_format(name, _nbuf, sizeof(_nbuf));    \
155                         dns_rdatatype_format(type, _tbuf, sizeof(_tbuf)); \
156                         update_log(client, zone, LOGLEVEL_PROTOCOL,     \
157                                    "update %s: %s/%s: %s (%s)",         \
158                                    _what, _nbuf, _tbuf, msg,            \
159                                    isc_result_totext(result));          \
160                 }                                                       \
161                 if (result != ISC_R_SUCCESS) goto failure;              \
162         } while (0)
163 /*
164  * Fail unconditionally and log as a server error.
165  * The test against ISC_R_SUCCESS is there to keep the Solaris compiler
166  * from complaining about "end-of-loop code not reached".
167  */
168 #define FAILS(code, msg) \
169         do {                                                    \
170                 result = (code);                                \
171                 update_log(client, zone, LOGLEVEL_PROTOCOL,     \
172                               "error: %s: %s",                  \
173                               msg, isc_result_totext(result));  \
174                 if (result != ISC_R_SUCCESS) goto failure;      \
175         } while (0)
176
177 /**************************************************************************/
178
179 typedef struct rr rr_t;
180
181 struct rr {
182         /* dns_name_t name; */
183         isc_uint32_t            ttl;
184         dns_rdata_t             rdata;
185 };
186
187 typedef struct update_event update_event_t;
188
189 struct update_event {
190         ISC_EVENT_COMMON(update_event_t);
191         dns_zone_t              *zone;
192         isc_result_t            result;
193         dns_message_t           *answer;
194 };
195
196 /**************************************************************************/
197 /*
198  * Forward declarations.
199  */
200
201 static void update_action(isc_task_t *task, isc_event_t *event);
202 static void updatedone_action(isc_task_t *task, isc_event_t *event);
203 static isc_result_t send_forward_event(ns_client_t *client, dns_zone_t *zone);
204 static void forward_done(isc_task_t *task, isc_event_t *event);
205
206 /**************************************************************************/
207
208 static void
209 update_log(ns_client_t *client, dns_zone_t *zone,
210            int level, const char *fmt, ...) ISC_FORMAT_PRINTF(4, 5);
211
212 static void
213 update_log(ns_client_t *client, dns_zone_t *zone,
214            int level, const char *fmt, ...)
215 {
216         va_list ap;
217         char message[4096];
218         char namebuf[DNS_NAME_FORMATSIZE];
219         char classbuf[DNS_RDATACLASS_FORMATSIZE];
220
221         if (client == NULL || zone == NULL)
222                 return;
223
224         if (isc_log_wouldlog(ns_g_lctx, level) == ISC_FALSE)
225                 return;
226
227         dns_name_format(dns_zone_getorigin(zone), namebuf,
228                         sizeof(namebuf));
229         dns_rdataclass_format(dns_zone_getclass(zone), classbuf,
230                               sizeof(classbuf));
231
232         va_start(ap, fmt);
233         vsnprintf(message, sizeof(message), fmt, ap);
234         va_end(ap);
235
236         ns_client_log(client, NS_LOGCATEGORY_UPDATE, NS_LOGMODULE_UPDATE,
237                       level, "updating zone '%s/%s': %s",
238                       namebuf, classbuf, message);
239 }
240
241 static isc_result_t
242 checkupdateacl(ns_client_t *client, dns_acl_t *acl, const char *message,
243                dns_name_t *zonename, isc_boolean_t slave)
244 {
245         char namebuf[DNS_NAME_FORMATSIZE];
246         char classbuf[DNS_RDATACLASS_FORMATSIZE];
247         int level = ISC_LOG_ERROR;
248         const char *msg = "denied";
249         isc_result_t result;
250
251         if (slave && acl == NULL) {
252                 result = DNS_R_NOTIMP;
253                 level = ISC_LOG_DEBUG(3);
254                 msg = "disabled";
255         } else
256                 result = ns_client_checkaclsilent(client, acl, ISC_FALSE);
257
258         if (result == ISC_R_SUCCESS) {
259                 level = ISC_LOG_DEBUG(3);
260                 msg = "approved";
261         }
262
263         dns_name_format(zonename, namebuf, sizeof(namebuf));
264         dns_rdataclass_format(client->view->rdclass, classbuf,
265                               sizeof(classbuf));
266
267         ns_client_log(client, NS_LOGCATEGORY_UPDATE_SECURITY,
268                               NS_LOGMODULE_UPDATE, level, "%s '%s/%s' %s",
269                               message, namebuf, classbuf, msg);
270         return (result);
271 }
272
273 /*
274  * Update a single RR in version 'ver' of 'db' and log the
275  * update in 'diff'.
276  *
277  * Ensures:
278  *   '*tuple' == NULL.  Either the tuple is freed, or its
279  *         ownership has been transferred to the diff.
280  */
281 static isc_result_t
282 do_one_tuple(dns_difftuple_t **tuple,
283              dns_db_t *db, dns_dbversion_t *ver,
284              dns_diff_t *diff)
285 {
286         dns_diff_t temp_diff;
287         isc_result_t result;
288
289         /*
290          * Create a singleton diff.
291          */
292         dns_diff_init(diff->mctx, &temp_diff);
293         ISC_LIST_APPEND(temp_diff.tuples, *tuple, link);
294
295         /*
296          * Apply it to the database.
297          */
298         result = dns_diff_apply(&temp_diff, db, ver);
299         ISC_LIST_UNLINK(temp_diff.tuples, *tuple, link);
300         if (result != ISC_R_SUCCESS) {
301                 dns_difftuple_free(tuple);
302                 return (result);
303         }
304
305         /*
306          * Merge it into the current pending journal entry.
307          */
308         dns_diff_appendminimal(diff, tuple);
309
310         /*
311          * Do not clear temp_diff.
312          */
313         return (ISC_R_SUCCESS);
314 }
315
316 /*
317  * Perform the updates in 'updates' in version 'ver' of 'db' and log the
318  * update in 'diff'.
319  *
320  * Ensures:
321  *   'updates' is empty.
322  */
323 static isc_result_t
324 do_diff(dns_diff_t *updates, dns_db_t *db, dns_dbversion_t *ver,
325         dns_diff_t *diff)
326 {
327         isc_result_t result;
328         while (! ISC_LIST_EMPTY(updates->tuples)) {
329                 dns_difftuple_t *t = ISC_LIST_HEAD(updates->tuples);
330                 ISC_LIST_UNLINK(updates->tuples, t, link);
331                 CHECK(do_one_tuple(&t, db, ver, diff));
332         }
333         return (ISC_R_SUCCESS);
334
335  failure:
336         dns_diff_clear(diff);
337         return (result);
338 }
339
340 static isc_result_t
341 update_one_rr(dns_db_t *db, dns_dbversion_t *ver, dns_diff_t *diff,
342               dns_diffop_t op, dns_name_t *name,
343               dns_ttl_t ttl, dns_rdata_t *rdata)
344 {
345         dns_difftuple_t *tuple = NULL;
346         isc_result_t result;
347         result = dns_difftuple_create(diff->mctx, op,
348                                       name, ttl, rdata, &tuple);
349         if (result != ISC_R_SUCCESS)
350                 return (result);
351         return (do_one_tuple(&tuple, db, ver, diff));
352 }
353
354 /**************************************************************************/
355 /*
356  * Callback-style iteration over rdatasets and rdatas.
357  *
358  * foreach_rrset() can be used to iterate over the RRsets
359  * of a name and call a callback function with each
360  * one.  Similarly, foreach_rr() can be used to iterate
361  * over the individual RRs at name, optionally restricted
362  * to RRs of a given type.
363  *
364  * The callback functions are called "actions" and take
365  * two arguments: a void pointer for passing arbitrary
366  * context information, and a pointer to the current RRset
367  * or RR.  By convention, their names end in "_action".
368  */
369
370 /*
371  * XXXRTH  We might want to make this public somewhere in libdns.
372  */
373
374 /*
375  * Function type for foreach_rrset() iterator actions.
376  */
377 typedef isc_result_t rrset_func(void *data, dns_rdataset_t *rrset);
378
379 /*
380  * Function type for foreach_rr() iterator actions.
381  */
382 typedef isc_result_t rr_func(void *data, rr_t *rr);
383
384 /*
385  * Internal context struct for foreach_node_rr().
386  */
387 typedef struct {
388         rr_func *       rr_action;
389         void *          rr_action_data;
390 } foreach_node_rr_ctx_t;
391
392 /*
393  * Internal helper function for foreach_node_rr().
394  */
395 static isc_result_t
396 foreach_node_rr_action(void *data, dns_rdataset_t *rdataset) {
397         isc_result_t result;
398         foreach_node_rr_ctx_t *ctx = data;
399         for (result = dns_rdataset_first(rdataset);
400              result == ISC_R_SUCCESS;
401              result = dns_rdataset_next(rdataset))
402         {
403                 rr_t rr = { 0, DNS_RDATA_INIT };
404
405                 dns_rdataset_current(rdataset, &rr.rdata);
406                 rr.ttl = rdataset->ttl;
407                 result = (*ctx->rr_action)(ctx->rr_action_data, &rr);
408                 if (result != ISC_R_SUCCESS)
409                         return (result);
410         }
411         if (result != ISC_R_NOMORE)
412                 return (result);
413         return (ISC_R_SUCCESS);
414 }
415
416 /*
417  * For each rdataset of 'name' in 'ver' of 'db', call 'action'
418  * with the rdataset and 'action_data' as arguments.  If the name
419  * does not exist, do nothing.
420  *
421  * If 'action' returns an error, abort iteration and return the error.
422  */
423 static isc_result_t
424 foreach_rrset(dns_db_t *db,
425               dns_dbversion_t *ver,
426               dns_name_t *name,
427               rrset_func *action,
428               void *action_data)
429 {
430         isc_result_t result;
431         dns_dbnode_t *node;
432         dns_rdatasetiter_t *iter;
433
434         node = NULL;
435         result = dns_db_findnode(db, name, ISC_FALSE, &node);
436         if (result == ISC_R_NOTFOUND)
437                 return (ISC_R_SUCCESS);
438         if (result != ISC_R_SUCCESS)
439                 return (result);
440
441         iter = NULL;
442         result = dns_db_allrdatasets(db, node, ver,
443                                      (isc_stdtime_t) 0, &iter);
444         if (result != ISC_R_SUCCESS)
445                 goto cleanup_node;
446
447         for (result = dns_rdatasetiter_first(iter);
448              result == ISC_R_SUCCESS;
449              result = dns_rdatasetiter_next(iter))
450         {
451                 dns_rdataset_t rdataset;
452
453                 dns_rdataset_init(&rdataset);
454                 dns_rdatasetiter_current(iter, &rdataset);
455
456                 result = (*action)(action_data, &rdataset);
457
458                 dns_rdataset_disassociate(&rdataset);
459                 if (result != ISC_R_SUCCESS)
460                         goto cleanup_iterator;
461         }
462         if (result == ISC_R_NOMORE)
463                 result = ISC_R_SUCCESS;
464
465  cleanup_iterator:
466         dns_rdatasetiter_destroy(&iter);
467
468  cleanup_node:
469         dns_db_detachnode(db, &node);
470
471         return (result);
472 }
473
474 /*
475  * For each RR of 'name' in 'ver' of 'db', call 'action'
476  * with the RR and 'action_data' as arguments.  If the name
477  * does not exist, do nothing.
478  *
479  * If 'action' returns an error, abort iteration
480  * and return the error.
481  */
482 static isc_result_t
483 foreach_node_rr(dns_db_t *db,
484             dns_dbversion_t *ver,
485             dns_name_t *name,
486             rr_func *rr_action,
487             void *rr_action_data)
488 {
489         foreach_node_rr_ctx_t ctx;
490         ctx.rr_action = rr_action;
491         ctx.rr_action_data = rr_action_data;
492         return (foreach_rrset(db, ver, name,
493                               foreach_node_rr_action, &ctx));
494 }
495
496
497 /*
498  * For each of the RRs specified by 'db', 'ver', 'name', 'type',
499  * (which can be dns_rdatatype_any to match any type), and 'covers', call
500  * 'action' with the RR and 'action_data' as arguments. If the name
501  * does not exist, or if no RRset of the given type exists at the name,
502  * do nothing.
503  *
504  * If 'action' returns an error, abort iteration and return the error.
505  */
506 static isc_result_t
507 foreach_rr(dns_db_t *db,
508            dns_dbversion_t *ver,
509            dns_name_t *name,
510            dns_rdatatype_t type,
511            dns_rdatatype_t covers,
512            rr_func *rr_action,
513            void *rr_action_data)
514 {
515
516         isc_result_t result;
517         dns_dbnode_t *node;
518         dns_rdataset_t rdataset;
519
520         if (type == dns_rdatatype_any)
521                 return (foreach_node_rr(db, ver, name,
522                                         rr_action, rr_action_data));
523
524         node = NULL;
525         result = dns_db_findnode(db, name, ISC_FALSE, &node);
526         if (result == ISC_R_NOTFOUND)
527                 return (ISC_R_SUCCESS);
528         if (result != ISC_R_SUCCESS)
529                 return (result);
530
531         dns_rdataset_init(&rdataset);
532         result = dns_db_findrdataset(db, node, ver, type, covers,
533                                      (isc_stdtime_t) 0, &rdataset, NULL);
534         if (result == ISC_R_NOTFOUND) {
535                 result = ISC_R_SUCCESS;
536                 goto cleanup_node;
537         }
538         if (result != ISC_R_SUCCESS)
539                 goto cleanup_node;
540
541         for (result = dns_rdataset_first(&rdataset);
542              result == ISC_R_SUCCESS;
543              result = dns_rdataset_next(&rdataset))
544         {
545                 rr_t rr = { 0, DNS_RDATA_INIT };
546                 dns_rdataset_current(&rdataset, &rr.rdata);
547                 rr.ttl = rdataset.ttl;
548                 result = (*rr_action)(rr_action_data, &rr);
549                 if (result != ISC_R_SUCCESS)
550                         goto cleanup_rdataset;
551         }
552         if (result != ISC_R_NOMORE)
553                 goto cleanup_rdataset;
554         result = ISC_R_SUCCESS;
555
556  cleanup_rdataset:
557         dns_rdataset_disassociate(&rdataset);
558  cleanup_node:
559         dns_db_detachnode(db, &node);
560
561         return (result);
562 }
563
564 /**************************************************************************/
565 /*
566  * Various tests on the database contents (for prerequisites, etc).
567  */
568
569 /*
570  * Function type for predicate functions that compare a database RR 'db_rr'
571  * against an update RR 'update_rr'.
572  */
573 typedef isc_boolean_t rr_predicate(dns_rdata_t *update_rr, dns_rdata_t *db_rr);
574
575 /*
576  * Helper function for rrset_exists().
577  */
578 static isc_result_t
579 rrset_exists_action(void *data, rr_t *rr) {
580         UNUSED(data);
581         UNUSED(rr);
582         return (ISC_R_EXISTS);
583 }
584
585 /*
586  * Utility macro for RR existence checking functions.
587  *
588  * If the variable 'result' has the value ISC_R_EXISTS or
589  * ISC_R_SUCCESS, set *exists to ISC_TRUE or ISC_FALSE,
590  * respectively, and return success.
591  *
592  * If 'result' has any other value, there was a failure.
593  * Return the failure result code and do not set *exists.
594  *
595  * This would be more readable as "do { if ... } while(0)",
596  * but that form generates tons of warnings on Solaris 2.6.
597  */
598 #define RETURN_EXISTENCE_FLAG                           \
599         return ((result == ISC_R_EXISTS) ?              \
600                 (*exists = ISC_TRUE, ISC_R_SUCCESS) :   \
601                 ((result == ISC_R_SUCCESS) ?            \
602                  (*exists = ISC_FALSE, ISC_R_SUCCESS) : \
603                  result))
604
605 /*
606  * Set '*exists' to true iff an rrset of the given type exists,
607  * to false otherwise.
608  */
609 static isc_result_t
610 rrset_exists(dns_db_t *db, dns_dbversion_t *ver,
611              dns_name_t *name, dns_rdatatype_t type, dns_rdatatype_t covers,
612              isc_boolean_t *exists)
613 {
614         isc_result_t result;
615         result = foreach_rr(db, ver, name, type, covers,
616                             rrset_exists_action, NULL);
617         RETURN_EXISTENCE_FLAG;
618 }
619
620 /*
621  * Helper function for cname_incompatible_rrset_exists.
622  */
623 static isc_result_t
624 cname_compatibility_action(void *data, dns_rdataset_t *rrset) {
625         UNUSED(data);
626         if (rrset->type != dns_rdatatype_cname &&
627             ! dns_rdatatype_isdnssec(rrset->type))
628                 return (ISC_R_EXISTS);
629         return (ISC_R_SUCCESS);
630 }
631
632 /*
633  * Check whether there is an rrset incompatible with adding a CNAME RR,
634  * i.e., anything but another CNAME (which can be replaced) or a
635  * DNSSEC RR (which can coexist).
636  *
637  * If such an incompatible rrset exists, set '*exists' to ISC_TRUE.
638  * Otherwise, set it to ISC_FALSE.
639  */
640 static isc_result_t
641 cname_incompatible_rrset_exists(dns_db_t *db, dns_dbversion_t *ver,
642                                 dns_name_t *name, isc_boolean_t *exists) {
643         isc_result_t result;
644         result = foreach_rrset(db, ver, name,
645                                cname_compatibility_action, NULL);
646         RETURN_EXISTENCE_FLAG;
647 }
648
649 /*
650  * Helper function for rr_count().
651  */
652 static isc_result_t
653 count_rr_action(void *data, rr_t *rr) {
654         int *countp = data;
655         UNUSED(rr);
656         (*countp)++;
657         return (ISC_R_SUCCESS);
658 }
659
660 /*
661  * Count the number of RRs of 'type' belonging to 'name' in 'ver' of 'db'.
662  */
663 static isc_result_t
664 rr_count(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
665          dns_rdatatype_t type, dns_rdatatype_t covers, int *countp)
666 {
667         *countp = 0;
668         return (foreach_rr(db, ver, name, type, covers,
669                            count_rr_action, countp));
670 }
671
672 /*
673  * Context struct and helper function for name_exists().
674  */
675
676 static isc_result_t
677 name_exists_action(void *data, dns_rdataset_t *rrset) {
678         UNUSED(data);
679         UNUSED(rrset);
680         return (ISC_R_EXISTS);
681 }
682
683 /*
684  * Set '*exists' to true iff the given name exists, to false otherwise.
685  */
686 static isc_result_t
687 name_exists(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
688             isc_boolean_t *exists)
689 {
690         isc_result_t result;
691         result = foreach_rrset(db, ver, name,
692                                name_exists_action, NULL);
693         RETURN_EXISTENCE_FLAG;
694 }
695
696 typedef struct {
697         dns_name_t *name, *signer;
698         dns_ssutable_t *table;
699 } ssu_check_t;
700
701 static isc_result_t
702 ssu_checkrule(void *data, dns_rdataset_t *rrset) {
703         ssu_check_t *ssuinfo = data;
704         isc_boolean_t result;
705
706         /*
707          * If we're deleting all records, it's ok to delete RRSIG and NSEC even
708          * if we're normally not allowed to.
709          */
710         if (rrset->type == dns_rdatatype_rrsig ||
711             rrset->type == dns_rdatatype_nsec)
712                 return (ISC_R_SUCCESS);
713         result = dns_ssutable_checkrules(ssuinfo->table, ssuinfo->signer,
714                                          ssuinfo->name, rrset->type);
715         return (result == ISC_TRUE ? ISC_R_SUCCESS : ISC_R_FAILURE);
716 }
717
718 static isc_boolean_t
719 ssu_checkall(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
720              dns_ssutable_t *ssutable, dns_name_t *signer)
721 {
722         isc_result_t result;
723         ssu_check_t ssuinfo;
724
725         ssuinfo.name = name;
726         ssuinfo.table = ssutable;
727         ssuinfo.signer = signer;
728         result = foreach_rrset(db, ver, name, ssu_checkrule, &ssuinfo);
729         return (ISC_TF(result == ISC_R_SUCCESS));
730 }
731
732 /**************************************************************************/
733 /*
734  * Checking of "RRset exists (value dependent)" prerequisites.
735  *
736  * In the RFC2136 section 3.2.5, this is the pseudocode involving
737  * a variable called "temp", a mapping of <name, type> tuples to rrsets.
738  *
739  * Here, we represent the "temp" data structure as (non-minimial) "dns_diff_t"
740  * where each typle has op==DNS_DIFFOP_EXISTS.
741  */
742
743
744 /*
745  * Append a tuple asserting the existence of the RR with
746  * 'name' and 'rdata' to 'diff'.
747  */
748 static isc_result_t
749 temp_append(dns_diff_t *diff, dns_name_t *name, dns_rdata_t *rdata) {
750         isc_result_t result;
751         dns_difftuple_t *tuple = NULL;
752
753         REQUIRE(DNS_DIFF_VALID(diff));
754         CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_EXISTS,
755                                       name, 0, rdata, &tuple));
756         ISC_LIST_APPEND(diff->tuples, tuple, link);
757  failure:
758         return (result);
759 }
760
761 /*
762  * Compare two rdatasets represented as sorted lists of tuples.
763  * All list elements must have the same owner name and type.
764  * Return ISC_R_SUCCESS if the rdatasets are equal, rcode(dns_rcode_nxrrset)
765  * if not.
766  */
767 static isc_result_t
768 temp_check_rrset(dns_difftuple_t *a, dns_difftuple_t *b) {
769         for (;;) {
770                 if (a == NULL || b == NULL)
771                         break;
772                 INSIST(a->op == DNS_DIFFOP_EXISTS &&
773                        b->op == DNS_DIFFOP_EXISTS);
774                 INSIST(a->rdata.type == b->rdata.type);
775                 INSIST(dns_name_equal(&a->name, &b->name));
776                 if (dns_rdata_compare(&a->rdata, &b->rdata) != 0)
777                         return (DNS_R_NXRRSET);
778                 a = ISC_LIST_NEXT(a, link);
779                 b = ISC_LIST_NEXT(b, link);
780         }
781         if (a != NULL || b != NULL)
782                 return (DNS_R_NXRRSET);
783         return (ISC_R_SUCCESS);
784 }
785
786 /*
787  * A comparison function defining the sorting order for the entries
788  * in the "temp" data structure.  The major sort key is the owner name,
789  * followed by the type and rdata.
790  */
791 static int
792 temp_order(const void *av, const void *bv) {
793         dns_difftuple_t const * const *ap = av;
794         dns_difftuple_t const * const *bp = bv;
795         dns_difftuple_t const *a = *ap;
796         dns_difftuple_t const *b = *bp;
797         int r;
798         r = dns_name_compare(&a->name, &b->name);
799         if (r != 0)
800                 return (r);
801         r = (b->rdata.type - a->rdata.type);
802         if (r != 0)
803                 return (r);
804         r = dns_rdata_compare(&a->rdata, &b->rdata);
805         return (r);
806 }
807
808 /*
809  * Check the "RRset exists (value dependent)" prerequisite information
810  * in 'temp' against the contents of the database 'db'.
811  *
812  * Return ISC_R_SUCCESS if the prerequisites are satisfied,
813  * rcode(dns_rcode_nxrrset) if not.
814  *
815  * 'temp' must be pre-sorted.
816  */
817
818 static isc_result_t
819 temp_check(isc_mem_t *mctx, dns_diff_t *temp, dns_db_t *db,
820            dns_dbversion_t *ver, dns_name_t *tmpname, dns_rdatatype_t *typep)
821 {
822         isc_result_t result;
823         dns_name_t *name;
824         dns_dbnode_t *node;
825         dns_difftuple_t *t;
826         dns_diff_t trash;
827
828         dns_diff_init(mctx, &trash);
829
830         /*
831          * For each name and type in the prerequisites,
832          * construct a sorted rdata list of the corresponding
833          * database contents, and compare the lists.
834          */
835         t = ISC_LIST_HEAD(temp->tuples);
836         while (t != NULL) {
837                 name = &t->name;
838                 (void)dns_name_copy(name, tmpname, NULL);
839                 *typep = t->rdata.type;
840
841                 /* A new unique name begins here. */
842                 node = NULL;
843                 result = dns_db_findnode(db, name, ISC_FALSE, &node);
844                 if (result == ISC_R_NOTFOUND) {
845                         dns_diff_clear(&trash);
846                         return (DNS_R_NXRRSET);
847                 }
848                 if (result != ISC_R_SUCCESS) {
849                         dns_diff_clear(&trash);
850                         return (result);
851                 }
852
853                 /* A new unique type begins here. */
854                 while (t != NULL && dns_name_equal(&t->name, name)) {
855                         dns_rdatatype_t type, covers;
856                         dns_rdataset_t rdataset;
857                         dns_diff_t d_rrs; /* Database RRs with
858                                                 this name and type */
859                         dns_diff_t u_rrs; /* Update RRs with
860                                                 this name and type */
861
862                         *typep = type = t->rdata.type;
863                         if (type == dns_rdatatype_rrsig ||
864                             type == dns_rdatatype_sig)
865                                 covers = dns_rdata_covers(&t->rdata);
866                         else
867                                 covers = 0;
868
869                         /*
870                          * Collect all database RRs for this name and type
871                          * onto d_rrs and sort them.
872                          */
873                         dns_rdataset_init(&rdataset);
874                         result = dns_db_findrdataset(db, node, ver, type,
875                                                      covers, (isc_stdtime_t) 0,
876                                                      &rdataset, NULL);
877                         if (result != ISC_R_SUCCESS) {
878                                 dns_db_detachnode(db, &node);
879                                 dns_diff_clear(&trash);
880                                 return (DNS_R_NXRRSET);
881                         }
882
883                         dns_diff_init(mctx, &d_rrs);
884                         dns_diff_init(mctx, &u_rrs);
885
886                         for (result = dns_rdataset_first(&rdataset);
887                              result == ISC_R_SUCCESS;
888                              result = dns_rdataset_next(&rdataset))
889                         {
890                                 dns_rdata_t rdata = DNS_RDATA_INIT;
891                                 dns_rdataset_current(&rdataset, &rdata);
892                                 result = temp_append(&d_rrs, name, &rdata);
893                                 if (result != ISC_R_SUCCESS)
894                                         goto failure;
895                         }
896                         if (result != ISC_R_NOMORE)
897                                 goto failure;
898                         result = dns_diff_sort(&d_rrs, temp_order);
899                         if (result != ISC_R_SUCCESS)
900                                 goto failure;
901
902                         /*
903                          * Collect all update RRs for this name and type
904                          * onto u_rrs.  No need to sort them here -
905                          * they are already sorted.
906                          */
907                         while (t != NULL &&
908                                dns_name_equal(&t->name, name) &&
909                                t->rdata.type == type)
910                         {
911                                 dns_difftuple_t *next =
912                                         ISC_LIST_NEXT(t, link);
913                                 ISC_LIST_UNLINK(temp->tuples, t, link);
914                                 ISC_LIST_APPEND(u_rrs.tuples, t, link);
915                                 t = next;
916                         }
917
918                         /* Compare the two sorted lists. */
919                         result = temp_check_rrset(ISC_LIST_HEAD(u_rrs.tuples),
920                                                   ISC_LIST_HEAD(d_rrs.tuples));
921                         if (result != ISC_R_SUCCESS)
922                                 goto failure;
923
924                         /*
925                          * We are done with the tuples, but we can't free
926                          * them yet because "name" still points into one
927                          * of them.  Move them on a temporary list.
928                          */
929                         ISC_LIST_APPENDLIST(trash.tuples, u_rrs.tuples, link);
930                         ISC_LIST_APPENDLIST(trash.tuples, d_rrs.tuples, link);
931                         dns_rdataset_disassociate(&rdataset);
932
933                         continue;
934
935                     failure:
936                         dns_diff_clear(&d_rrs);
937                         dns_diff_clear(&u_rrs);
938                         dns_diff_clear(&trash);
939                         dns_rdataset_disassociate(&rdataset);
940                         dns_db_detachnode(db, &node);
941                         return (result);
942                 }
943
944                 dns_db_detachnode(db, &node);
945         }
946
947         dns_diff_clear(&trash);
948         return (ISC_R_SUCCESS);
949 }
950
951 /**************************************************************************/
952 /*
953  * Conditional deletion of RRs.
954  */
955
956 /*
957  * Context structure for delete_if().
958  */
959
960 typedef struct {
961         rr_predicate *predicate;
962         dns_db_t *db;
963         dns_dbversion_t *ver;
964         dns_diff_t *diff;
965         dns_name_t *name;
966         dns_rdata_t *update_rr;
967 } conditional_delete_ctx_t;
968
969 /*
970  * Predicate functions for delete_if().
971  */
972
973 /*
974  * Return true iff 'db_rr' is neither a SOA nor an NS RR nor
975  * an RRSIG nor a NSEC.
976  */
977 static isc_boolean_t
978 type_not_soa_nor_ns_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
979         UNUSED(update_rr);
980         return ((db_rr->type != dns_rdatatype_soa &&
981                  db_rr->type != dns_rdatatype_ns &&
982                  db_rr->type != dns_rdatatype_rrsig &&
983                  db_rr->type != dns_rdatatype_nsec) ?
984                 ISC_TRUE : ISC_FALSE);
985 }
986
987 /*
988  * Return true iff 'db_rr' is neither a RRSIG nor a NSEC.
989  */
990 static isc_boolean_t
991 type_not_dnssec(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
992         UNUSED(update_rr);
993         return ((db_rr->type != dns_rdatatype_rrsig &&
994                  db_rr->type != dns_rdatatype_nsec) ?
995                 ISC_TRUE : ISC_FALSE);
996 }
997
998 /*
999  * Return true always.
1000  */
1001 static isc_boolean_t
1002 true_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
1003         UNUSED(update_rr);
1004         UNUSED(db_rr);
1005         return (ISC_TRUE);
1006 }
1007
1008 /*
1009  * Return true iff the two RRs have identical rdata.
1010  */
1011 static isc_boolean_t
1012 rr_equal_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
1013         /*
1014          * XXXRTH  This is not a problem, but we should consider creating
1015          *         dns_rdata_equal() (that used dns_name_equal()), since it
1016          *         would be faster.  Not a priority.
1017          */
1018         return (dns_rdata_compare(update_rr, db_rr) == 0 ?
1019                 ISC_TRUE : ISC_FALSE);
1020 }
1021
1022 /*
1023  * Return true iff 'update_rr' should replace 'db_rr' according
1024  * to the special RFC2136 rules for CNAME, SOA, and WKS records.
1025  *
1026  * RFC2136 does not mention NSEC or DNAME, but multiple NSECs or DNAMEs
1027  * make little sense, so we replace those, too.
1028  */
1029 static isc_boolean_t
1030 replaces_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
1031         if (db_rr->type != update_rr->type)
1032                 return (ISC_FALSE);
1033         if (db_rr->type == dns_rdatatype_cname)
1034                 return (ISC_TRUE);
1035         if (db_rr->type == dns_rdatatype_dname)
1036                 return (ISC_TRUE);
1037         if (db_rr->type == dns_rdatatype_soa)
1038                 return (ISC_TRUE);
1039         if (db_rr->type == dns_rdatatype_nsec)
1040                 return (ISC_TRUE);
1041         if (db_rr->type == dns_rdatatype_wks) {
1042                 /*
1043                  * Compare the address and protocol fields only.  These
1044                  * form the first five bytes of the RR data.  Do a
1045                  * raw binary comparison; unpacking the WKS RRs using
1046                  * dns_rdata_tostruct() might be cleaner in some ways,
1047                  * but it would require us to pass around an mctx.
1048                  */
1049                 INSIST(db_rr->length >= 5 && update_rr->length >= 5);
1050                 return (memcmp(db_rr->data, update_rr->data, 5) == 0 ?
1051                         ISC_TRUE : ISC_FALSE);
1052         }
1053         return (ISC_FALSE);
1054 }
1055
1056 /*
1057  * Internal helper function for delete_if().
1058  */
1059 static isc_result_t
1060 delete_if_action(void *data, rr_t *rr) {
1061         conditional_delete_ctx_t *ctx = data;
1062         if ((*ctx->predicate)(ctx->update_rr, &rr->rdata)) {
1063                 isc_result_t result;
1064                 result = update_one_rr(ctx->db, ctx->ver, ctx->diff,
1065                                        DNS_DIFFOP_DEL, ctx->name,
1066                                        rr->ttl, &rr->rdata);
1067                 return (result);
1068         } else {
1069                 return (ISC_R_SUCCESS);
1070         }
1071 }
1072
1073 /*
1074  * Conditionally delete RRs.  Apply 'predicate' to the RRs
1075  * specified by 'db', 'ver', 'name', and 'type' (which can
1076  * be dns_rdatatype_any to match any type).  Delete those
1077  * RRs for which the predicate returns true, and log the
1078  * deletions in 'diff'.
1079  */
1080 static isc_result_t
1081 delete_if(rr_predicate *predicate,
1082           dns_db_t *db,
1083           dns_dbversion_t *ver,
1084           dns_name_t *name,
1085           dns_rdatatype_t type,
1086           dns_rdatatype_t covers,
1087           dns_rdata_t *update_rr,
1088           dns_diff_t *diff)
1089 {
1090         conditional_delete_ctx_t ctx;
1091         ctx.predicate = predicate;
1092         ctx.db = db;
1093         ctx.ver = ver;
1094         ctx.diff = diff;
1095         ctx.name = name;
1096         ctx.update_rr = update_rr;
1097         return (foreach_rr(db, ver, name, type, covers,
1098                            delete_if_action, &ctx));
1099 }
1100
1101 /**************************************************************************/
1102 /*
1103  * Prepare an RR for the addition of the new RR 'ctx->update_rr',
1104  * with TTL 'ctx->update_rr_ttl', to its rdataset, by deleting
1105  * the RRs if it is replaced by the new RR or has a conflicting TTL.
1106  * The necessary changes are appended to ctx->del_diff and ctx->add_diff;
1107  * we need to do all deletions before any additions so that we don't run
1108  * into transient states with conflicting TTLs.
1109  */
1110
1111 typedef struct {
1112         dns_db_t *db;
1113         dns_dbversion_t *ver;
1114         dns_diff_t *diff;
1115         dns_name_t *name;
1116         dns_rdata_t *update_rr;
1117         dns_ttl_t update_rr_ttl;
1118         isc_boolean_t ignore_add;
1119         dns_diff_t del_diff;
1120         dns_diff_t add_diff;
1121 } add_rr_prepare_ctx_t;
1122
1123 static isc_result_t
1124 add_rr_prepare_action(void *data, rr_t *rr) {
1125         isc_result_t result = ISC_R_SUCCESS;
1126         add_rr_prepare_ctx_t *ctx = data;
1127         dns_difftuple_t *tuple = NULL;
1128         isc_boolean_t equal;
1129
1130         /*
1131          * If the update RR is a "duplicate" of the update RR,
1132          * the update should be silently ignored.
1133          */
1134         equal = ISC_TF(dns_rdata_compare(&rr->rdata, ctx->update_rr) == 0);
1135         if (equal && rr->ttl == ctx->update_rr_ttl) {
1136                 ctx->ignore_add = ISC_TRUE;
1137                 return (ISC_R_SUCCESS);
1138         }
1139
1140         /*
1141          * If this RR is "equal" to the update RR, it should
1142          * be deleted before the update RR is added.
1143          */
1144         if (replaces_p(ctx->update_rr, &rr->rdata)) {
1145                 CHECK(dns_difftuple_create(ctx->del_diff.mctx,
1146                                            DNS_DIFFOP_DEL, ctx->name,
1147                                            rr->ttl,
1148                                            &rr->rdata,
1149                                            &tuple));
1150                 dns_diff_append(&ctx->del_diff, &tuple);
1151                 return (ISC_R_SUCCESS);
1152         }
1153
1154         /*
1155          * If this RR differs in TTL from the update RR,
1156          * its TTL must be adjusted.
1157          */
1158         if (rr->ttl != ctx->update_rr_ttl) {
1159                 CHECK(dns_difftuple_create(ctx->del_diff.mctx,
1160                                            DNS_DIFFOP_DEL, ctx->name,
1161                                            rr->ttl,
1162                                            &rr->rdata,
1163                                            &tuple));
1164                 dns_diff_append(&ctx->del_diff, &tuple);
1165                 if (!equal) {
1166                         CHECK(dns_difftuple_create(ctx->add_diff.mctx,
1167                                                    DNS_DIFFOP_ADD, ctx->name,
1168                                                    ctx->update_rr_ttl,
1169                                                    &rr->rdata,
1170                                                    &tuple));
1171                         dns_diff_append(&ctx->add_diff, &tuple);
1172                 }
1173         }
1174  failure:
1175         return (result);
1176 }
1177
1178 /**************************************************************************/
1179 /*
1180  * Miscellaneous subroutines.
1181  */
1182
1183 /*
1184  * Extract a single update RR from 'section' of dynamic update message
1185  * 'msg', with consistency checking.
1186  *
1187  * Stores the owner name, rdata, and TTL of the update RR at 'name',
1188  * 'rdata', and 'ttl', respectively.
1189  */
1190 static void
1191 get_current_rr(dns_message_t *msg, dns_section_t section,
1192                dns_rdataclass_t zoneclass,
1193                dns_name_t **name, dns_rdata_t *rdata, dns_rdatatype_t *covers,
1194                dns_ttl_t *ttl,
1195                dns_rdataclass_t *update_class)
1196 {
1197         dns_rdataset_t *rdataset;
1198         isc_result_t result;
1199         dns_message_currentname(msg, section, name);
1200         rdataset = ISC_LIST_HEAD((*name)->list);
1201         INSIST(rdataset != NULL);
1202         INSIST(ISC_LIST_NEXT(rdataset, link) == NULL);
1203         *covers = rdataset->covers;
1204         *ttl = rdataset->ttl;
1205         result = dns_rdataset_first(rdataset);
1206         INSIST(result == ISC_R_SUCCESS);
1207         dns_rdataset_current(rdataset, rdata);
1208         INSIST(dns_rdataset_next(rdataset) == ISC_R_NOMORE);
1209         *update_class = rdata->rdclass;
1210         rdata->rdclass = zoneclass;
1211 }
1212
1213 /*
1214  * Increment the SOA serial number of database 'db', version 'ver'.
1215  * Replace the SOA record in the database, and log the
1216  * change in 'diff'.
1217  */
1218
1219         /*
1220          * XXXRTH  Failures in this routine will be worth logging, when
1221          *         we have a logging system.  Failure to find the zonename
1222          *         or the SOA rdataset warrant at least an UNEXPECTED_ERROR().
1223          */
1224
1225 static isc_result_t
1226 increment_soa_serial(dns_db_t *db, dns_dbversion_t *ver,
1227                      dns_diff_t *diff, isc_mem_t *mctx)
1228 {
1229         dns_difftuple_t *deltuple = NULL;
1230         dns_difftuple_t *addtuple = NULL;
1231         isc_uint32_t serial;
1232         isc_result_t result;
1233
1234         CHECK(dns_db_createsoatuple(db, ver, mctx, DNS_DIFFOP_DEL, &deltuple));
1235         CHECK(dns_difftuple_copy(deltuple, &addtuple));
1236         addtuple->op = DNS_DIFFOP_ADD;
1237
1238         serial = dns_soa_getserial(&addtuple->rdata);
1239
1240         /* RFC1982 */
1241         serial = (serial + 1) & 0xFFFFFFFF;
1242         if (serial == 0)
1243                 serial = 1;
1244
1245         dns_soa_setserial(serial, &addtuple->rdata);
1246         CHECK(do_one_tuple(&deltuple, db, ver, diff));
1247         CHECK(do_one_tuple(&addtuple, db, ver, diff));
1248         result = ISC_R_SUCCESS;
1249
1250  failure:
1251         if (addtuple != NULL)
1252                 dns_difftuple_free(&addtuple);
1253         if (deltuple != NULL)
1254                 dns_difftuple_free(&deltuple);
1255         return (result);
1256 }
1257
1258 /*
1259  * Check that the new SOA record at 'update_rdata' does not
1260  * illegally cause the SOA serial number to decrease or stay
1261  * unchanged relative to the existing SOA in 'db'.
1262  *
1263  * Sets '*ok' to ISC_TRUE if the update is legal, ISC_FALSE if not.
1264  *
1265  * William King points out that RFC2136 is inconsistent about
1266  * the case where the serial number stays unchanged:
1267  *
1268  *   section 3.4.2.2 requires a server to ignore a SOA update request
1269  *   if the serial number on the update SOA is less_than_or_equal to
1270  *   the zone SOA serial.
1271  *
1272  *   section 3.6 requires a server to ignore a SOA update request if
1273  *   the serial is less_than the zone SOA serial.
1274  *
1275  * Paul says 3.4.2.2 is correct.
1276  *
1277  */
1278 static isc_result_t
1279 check_soa_increment(dns_db_t *db, dns_dbversion_t *ver,
1280                     dns_rdata_t *update_rdata,
1281                     isc_boolean_t *ok)
1282 {
1283         isc_uint32_t db_serial;
1284         isc_uint32_t update_serial;
1285         isc_result_t result;
1286
1287         update_serial = dns_soa_getserial(update_rdata);
1288
1289         result = dns_db_getsoaserial(db, ver, &db_serial);
1290         if (result != ISC_R_SUCCESS)
1291                 return (result);
1292
1293         if (DNS_SERIAL_GE(db_serial, update_serial)) {
1294                 *ok = ISC_FALSE;
1295         } else {
1296                 *ok = ISC_TRUE;
1297         }
1298
1299         return (ISC_R_SUCCESS);
1300
1301 }
1302
1303 /**************************************************************************/
1304 /*
1305  * Incremental updating of NSECs and RRSIGs.
1306  */
1307
1308 #define MAXZONEKEYS 32  /* Maximum number of zone keys supported. */
1309
1310 /*
1311  * We abuse the dns_diff_t type to represent a set of domain names
1312  * affected by the update.
1313  */
1314 static isc_result_t
1315 namelist_append_name(dns_diff_t *list, dns_name_t *name) {
1316         isc_result_t result;
1317         dns_difftuple_t *tuple = NULL;
1318         static dns_rdata_t dummy_rdata = { NULL, 0, 0, 0, 0,
1319                                            { (void*)(-1), (void*)(-1) } };
1320         CHECK(dns_difftuple_create(list->mctx, DNS_DIFFOP_EXISTS, name, 0,
1321                                    &dummy_rdata, &tuple));
1322         dns_diff_append(list, &tuple);
1323  failure:
1324         return (result);
1325 }
1326
1327 static isc_result_t
1328 namelist_append_subdomain(dns_db_t *db, dns_name_t *name, dns_diff_t *affected)
1329 {
1330         isc_result_t result;
1331         dns_fixedname_t fixedname;
1332         dns_name_t *child;
1333         dns_dbiterator_t *dbit = NULL;
1334
1335         dns_fixedname_init(&fixedname);
1336         child = dns_fixedname_name(&fixedname);
1337
1338         CHECK(dns_db_createiterator(db, ISC_FALSE, &dbit));
1339
1340         for (result = dns_dbiterator_seek(dbit, name);
1341              result == ISC_R_SUCCESS;
1342              result = dns_dbiterator_next(dbit))
1343         {
1344                 dns_dbnode_t *node = NULL;
1345                 CHECK(dns_dbiterator_current(dbit, &node, child));
1346                 dns_db_detachnode(db, &node);
1347                 if (! dns_name_issubdomain(child, name))
1348                         break;
1349                 CHECK(namelist_append_name(affected, child));
1350         }
1351         if (result == ISC_R_NOMORE)
1352                 result = ISC_R_SUCCESS;
1353  failure:
1354         if (dbit != NULL)
1355                 dns_dbiterator_destroy(&dbit);
1356         return (result);
1357 }
1358
1359
1360
1361 /*
1362  * Helper function for non_nsec_rrset_exists().
1363  */
1364 static isc_result_t
1365 is_non_nsec_action(void *data, dns_rdataset_t *rrset) {
1366         UNUSED(data);
1367         if (!(rrset->type == dns_rdatatype_nsec ||
1368               (rrset->type == dns_rdatatype_rrsig &&
1369                rrset->covers == dns_rdatatype_nsec)))
1370                 return (ISC_R_EXISTS);
1371         return (ISC_R_SUCCESS);
1372 }
1373
1374 /*
1375  * Check whether there is an rrset other than a NSEC or RRSIG NSEC,
1376  * i.e., anything that justifies the continued existence of a name
1377  * after a secure update.
1378  *
1379  * If such an rrset exists, set '*exists' to ISC_TRUE.
1380  * Otherwise, set it to ISC_FALSE.
1381  */
1382 static isc_result_t
1383 non_nsec_rrset_exists(dns_db_t *db, dns_dbversion_t *ver,
1384                      dns_name_t *name, isc_boolean_t *exists)
1385 {
1386         isc_result_t result;
1387         result = foreach_rrset(db, ver, name,
1388                                is_non_nsec_action, NULL);
1389         RETURN_EXISTENCE_FLAG;
1390 }
1391
1392 /*
1393  * A comparison function for sorting dns_diff_t:s by name.
1394  */
1395 static int
1396 name_order(const void *av, const void *bv) {
1397         dns_difftuple_t const * const *ap = av;
1398         dns_difftuple_t const * const *bp = bv;
1399         dns_difftuple_t const *a = *ap;
1400         dns_difftuple_t const *b = *bp;
1401         return (dns_name_compare(&a->name, &b->name));
1402 }
1403
1404 static isc_result_t
1405 uniqify_name_list(dns_diff_t *list) {
1406         isc_result_t result;
1407         dns_difftuple_t *p, *q;
1408
1409         CHECK(dns_diff_sort(list, name_order));
1410
1411         p = ISC_LIST_HEAD(list->tuples);
1412         while (p != NULL) {
1413                 do {
1414                         q = ISC_LIST_NEXT(p, link);
1415                         if (q == NULL || ! dns_name_equal(&p->name, &q->name))
1416                                 break;
1417                         ISC_LIST_UNLINK(list->tuples, q, link);
1418                         dns_difftuple_free(&q);
1419                 } while (1);
1420                 p = ISC_LIST_NEXT(p, link);
1421         }
1422  failure:
1423         return (result);
1424 }
1425
1426
1427 static isc_result_t
1428 is_glue(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
1429         isc_boolean_t *flag)
1430 {
1431         isc_result_t result;
1432         dns_fixedname_t foundname;
1433         dns_fixedname_init(&foundname);
1434         result = dns_db_find(db, name, ver, dns_rdatatype_any,
1435                              DNS_DBFIND_GLUEOK | DNS_DBFIND_NOWILD,
1436                              (isc_stdtime_t) 0, NULL,
1437                              dns_fixedname_name(&foundname),
1438                              NULL, NULL);
1439         if (result == ISC_R_SUCCESS) {
1440                 *flag = ISC_FALSE;
1441                 return (ISC_R_SUCCESS);
1442         } else if (result == DNS_R_ZONECUT) {
1443                 /*
1444                  * We are at the zonecut.  The name will have an NSEC, but
1445                  * non-delegation will be omitted from the type bit map.
1446                  */
1447                 *flag = ISC_FALSE;
1448                 return (ISC_R_SUCCESS);
1449         } else if (result == DNS_R_GLUE || result == DNS_R_DNAME) {
1450                 *flag = ISC_TRUE;
1451                 return (ISC_R_SUCCESS);
1452         } else {
1453                 return (result);
1454         }
1455 }
1456
1457 /*
1458  * Find the next/previous name that has a NSEC record.
1459  * In other words, skip empty database nodes and names that
1460  * have had their NSECs removed because they are obscured by
1461  * a zone cut.
1462  */
1463 static isc_result_t
1464 next_active(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
1465             dns_dbversion_t *ver, dns_name_t *oldname, dns_name_t *newname,
1466             isc_boolean_t forward)
1467 {
1468         isc_result_t result;
1469         dns_dbiterator_t *dbit = NULL;
1470         isc_boolean_t has_nsec;
1471         unsigned int wraps = 0;
1472
1473         CHECK(dns_db_createiterator(db, ISC_FALSE, &dbit));
1474
1475         CHECK(dns_dbiterator_seek(dbit, oldname));
1476         do {
1477                 dns_dbnode_t *node = NULL;
1478
1479                 if (forward)
1480                         result = dns_dbiterator_next(dbit);
1481                 else
1482                         result = dns_dbiterator_prev(dbit);
1483                 if (result == ISC_R_NOMORE) {
1484                         /*
1485                          * Wrap around.
1486                          */
1487                         if (forward)
1488                                 CHECK(dns_dbiterator_first(dbit));
1489                         else
1490                                 CHECK(dns_dbiterator_last(dbit));
1491                         wraps++;
1492                         if (wraps == 2) {
1493                                 update_log(client, zone, ISC_LOG_ERROR,
1494                                            "secure zone with no NSECs");
1495                                 result = DNS_R_BADZONE;
1496                                 goto failure;
1497                         }
1498                 }
1499                 CHECK(dns_dbiterator_current(dbit, &node, newname));
1500                 dns_db_detachnode(db, &node);
1501
1502                 /*
1503                  * The iterator may hold the tree lock, and
1504                  * rrset_exists() calls dns_db_findnode() which
1505                  * may try to reacquire it.  To avoid deadlock
1506                  * we must pause the iterator first.
1507                  */
1508                 CHECK(dns_dbiterator_pause(dbit));
1509                 CHECK(rrset_exists(db, ver, newname,
1510                                    dns_rdatatype_nsec, 0, &has_nsec));
1511
1512         } while (! has_nsec);
1513  failure:
1514         if (dbit != NULL)
1515                 dns_dbiterator_destroy(&dbit);
1516
1517         return (result);
1518 }
1519
1520 /*
1521  * Add a NSEC record for "name", recording the change in "diff".
1522  * The existing NSEC is removed.
1523  */
1524 static isc_result_t
1525 add_nsec(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
1526          dns_dbversion_t *ver, dns_name_t *name, dns_ttl_t nsecttl,
1527          dns_diff_t *diff)
1528 {
1529         isc_result_t result;
1530         dns_dbnode_t *node = NULL;
1531         unsigned char buffer[DNS_NSEC_BUFFERSIZE];
1532         dns_rdata_t rdata = DNS_RDATA_INIT;
1533         dns_difftuple_t *tuple = NULL;
1534         dns_fixedname_t fixedname;
1535         dns_name_t *target;
1536
1537         dns_fixedname_init(&fixedname);
1538         target = dns_fixedname_name(&fixedname);
1539
1540         /*
1541          * Find the successor name, aka NSEC target.
1542          */
1543         CHECK(next_active(client, zone, db, ver, name, target, ISC_TRUE));
1544
1545         /*
1546          * Create the NSEC RDATA.
1547          */
1548         CHECK(dns_db_findnode(db, name, ISC_FALSE, &node));
1549         dns_rdata_init(&rdata);
1550         CHECK(dns_nsec_buildrdata(db, ver, node, target, buffer, &rdata));
1551         dns_db_detachnode(db, &node);
1552
1553         /*
1554          * Delete the old NSEC and record the change.
1555          */
1556         CHECK(delete_if(true_p, db, ver, name, dns_rdatatype_nsec, 0,
1557                         NULL, diff));
1558         /*
1559          * Add the new NSEC and record the change.
1560          */
1561         CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD, name,
1562                                    nsecttl, &rdata, &tuple));
1563         CHECK(do_one_tuple(&tuple, db, ver, diff));
1564         INSIST(tuple == NULL);
1565
1566  failure:
1567         if (node != NULL)
1568                 dns_db_detachnode(db, &node);
1569         return (result);
1570 }
1571
1572 /*
1573  * Add a placeholder NSEC record for "name", recording the change in "diff".
1574  */
1575 static isc_result_t
1576 add_placeholder_nsec(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
1577                     dns_diff_t *diff) {
1578         isc_result_t result;
1579         dns_difftuple_t *tuple = NULL;
1580         isc_region_t r;
1581         unsigned char data[1] = { 0 }; /* The root domain, no bits. */
1582         dns_rdata_t rdata = DNS_RDATA_INIT;
1583
1584         r.base = data;
1585         r.length = sizeof(data);
1586         dns_rdata_fromregion(&rdata, dns_db_class(db), dns_rdatatype_nsec, &r);
1587         CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD, name, 0,
1588                                    &rdata, &tuple));
1589         CHECK(do_one_tuple(&tuple, db, ver, diff));
1590  failure:
1591         return (result);
1592 }
1593
1594 static isc_result_t
1595 find_zone_keys(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *ver,
1596                isc_mem_t *mctx, unsigned int maxkeys,
1597                dst_key_t **keys, unsigned int *nkeys)
1598 {
1599         isc_result_t result;
1600         dns_dbnode_t *node = NULL;
1601         const char *directory = dns_zone_getkeydirectory(zone);
1602         CHECK(dns_db_findnode(db, dns_db_origin(db), ISC_FALSE, &node));
1603         CHECK(dns_dnssec_findzonekeys2(db, ver, node, dns_db_origin(db),
1604                                        directory, mctx, maxkeys, keys, nkeys));
1605  failure:
1606         if (node != NULL)
1607                 dns_db_detachnode(db, &node);
1608         return (result);
1609 }
1610
1611 /*
1612  * Add RRSIG records for an RRset, recording the change in "diff".
1613  */
1614 static isc_result_t
1615 add_sigs(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
1616          dns_rdatatype_t type, dns_diff_t *diff, dst_key_t **keys,
1617          unsigned int nkeys, isc_mem_t *mctx, isc_stdtime_t inception,
1618          isc_stdtime_t expire)
1619 {
1620         isc_result_t result;
1621         dns_dbnode_t *node = NULL;
1622         dns_rdataset_t rdataset;
1623         dns_rdata_t sig_rdata = DNS_RDATA_INIT;
1624         isc_buffer_t buffer;
1625         unsigned char data[1024]; /* XXX */
1626         unsigned int i;
1627
1628         dns_rdataset_init(&rdataset);
1629         isc_buffer_init(&buffer, data, sizeof(data));
1630
1631         /* Get the rdataset to sign. */
1632         CHECK(dns_db_findnode(db, name, ISC_FALSE, &node));
1633         CHECK(dns_db_findrdataset(db, node, ver, type, 0,
1634                                   (isc_stdtime_t) 0,
1635                                   &rdataset, NULL));
1636         dns_db_detachnode(db, &node);
1637
1638         for (i = 0; i < nkeys; i++) {
1639                 if (!dst_key_isprivate(keys[i]))
1640                         continue;
1641                 /* Calculate the signature, creating a RRSIG RDATA. */
1642                 CHECK(dns_dnssec_sign(name, &rdataset, keys[i],
1643                                       &inception, &expire,
1644                                       mctx, &buffer, &sig_rdata));
1645
1646                 /* Update the database and journal with the RRSIG. */
1647                 /* XXX inefficient - will cause dataset merging */
1648                 CHECK(update_one_rr(db, ver, diff, DNS_DIFFOP_ADD, name,
1649                                     rdataset.ttl, &sig_rdata));
1650                 dns_rdata_reset(&sig_rdata);
1651         }
1652
1653  failure:
1654         if (dns_rdataset_isassociated(&rdataset))
1655                 dns_rdataset_disassociate(&rdataset);
1656         if (node != NULL)
1657                 dns_db_detachnode(db, &node);
1658         return (result);
1659 }
1660
1661 /*
1662  * Update RRSIG and NSEC records affected by an update.  The original
1663  * update, including the SOA serial update but exluding the RRSIG & NSEC
1664  * changes, is in "diff" and has already been applied to "newver" of "db".
1665  * The database version prior to the update is "oldver".
1666  *
1667  * The necessary RRSIG and NSEC changes will be applied to "newver"
1668  * and added (as a minimal diff) to "diff".
1669  *
1670  * The RRSIGs generated will be valid for 'sigvalidityinterval' seconds.
1671  */
1672 static isc_result_t
1673 update_signatures(ns_client_t *client, dns_zone_t *zone, dns_db_t *db,
1674                   dns_dbversion_t *oldver, dns_dbversion_t *newver,
1675                   dns_diff_t *diff, isc_uint32_t sigvalidityinterval)
1676 {
1677         isc_result_t result;
1678         dns_difftuple_t *t;
1679         dns_diff_t diffnames;
1680         dns_diff_t affected;
1681         dns_diff_t sig_diff;
1682         dns_diff_t nsec_diff;
1683         dns_diff_t nsec_mindiff;
1684         isc_boolean_t flag;
1685         dst_key_t *zone_keys[MAXZONEKEYS];
1686         unsigned int nkeys = 0;
1687         unsigned int i;
1688         isc_stdtime_t now, inception, expire;
1689         dns_ttl_t nsecttl;
1690         dns_rdata_soa_t soa;
1691         dns_rdata_t rdata = DNS_RDATA_INIT;
1692         dns_rdataset_t rdataset;
1693         dns_dbnode_t *node = NULL;
1694
1695         dns_diff_init(client->mctx, &diffnames);
1696         dns_diff_init(client->mctx, &affected);
1697
1698         dns_diff_init(client->mctx, &sig_diff);
1699         dns_diff_init(client->mctx, &nsec_diff);
1700         dns_diff_init(client->mctx, &nsec_mindiff);
1701
1702         result = find_zone_keys(zone, db, newver, client->mctx,
1703                                 MAXZONEKEYS, zone_keys, &nkeys);
1704         if (result != ISC_R_SUCCESS) {
1705                 update_log(client, zone, ISC_LOG_ERROR,
1706                            "could not get zone keys for secure dynamic update");
1707                 goto failure;
1708         }
1709
1710         isc_stdtime_get(&now);
1711         inception = now - 3600; /* Allow for some clock skew. */
1712         expire = now + sigvalidityinterval;
1713
1714         /*
1715          * Get the NSEC's TTL from the SOA MINIMUM field.
1716          */
1717         CHECK(dns_db_findnode(db, dns_db_origin(db), ISC_FALSE, &node));
1718         dns_rdataset_init(&rdataset);
1719         CHECK(dns_db_findrdataset(db, node, newver, dns_rdatatype_soa, 0,
1720                                   (isc_stdtime_t) 0, &rdataset, NULL));
1721         CHECK(dns_rdataset_first(&rdataset));
1722         dns_rdataset_current(&rdataset, &rdata);
1723         CHECK(dns_rdata_tostruct(&rdata, &soa, NULL));
1724         nsecttl = soa.minimum;
1725         dns_rdataset_disassociate(&rdataset);
1726         dns_db_detachnode(db, &node);
1727
1728         /*
1729          * Find all RRsets directly affected by the update, and
1730          * update their RRSIGs.  Also build a list of names affected
1731          * by the update in "diffnames".
1732          */
1733         CHECK(dns_diff_sort(diff, temp_order));
1734
1735         t = ISC_LIST_HEAD(diff->tuples);
1736         while (t != NULL) {
1737                 dns_name_t *name = &t->name;
1738                 /* Now "name" is a new, unique name affected by the update. */
1739
1740                 CHECK(namelist_append_name(&diffnames, name));
1741
1742                 while (t != NULL && dns_name_equal(&t->name, name)) {
1743                         dns_rdatatype_t type;
1744                         type = t->rdata.type;
1745
1746                         /*
1747                          * Now "name" and "type" denote a new unique RRset
1748                          * affected by the update.
1749                          */
1750
1751                         /* Don't sign RRSIGs. */
1752                         if (type == dns_rdatatype_rrsig)
1753                                 goto skip;
1754
1755                         /*
1756                          * Delete all old RRSIGs covering this type, since they
1757                          * are all invalid when the signed RRset has changed.
1758                          * We may not be able to recreate all of them - tough.
1759                          */
1760                         CHECK(delete_if(true_p, db, newver, name,
1761                                         dns_rdatatype_rrsig, type,
1762                                         NULL, &sig_diff));
1763
1764                         /*
1765                          * If this RRset still exists after the update,
1766                          * add a new signature for it.
1767                          */
1768                         CHECK(rrset_exists(db, newver, name, type, 0, &flag));
1769                         if (flag) {
1770                                 CHECK(add_sigs(db, newver, name, type,
1771                                                &sig_diff, zone_keys, nkeys,
1772                                                client->mctx, inception,
1773                                                expire));
1774                         }
1775                 skip:
1776                         /* Skip any other updates to the same RRset. */
1777                         while (t != NULL &&
1778                                dns_name_equal(&t->name, name) &&
1779                                t->rdata.type == type)
1780                         {
1781                                 t = ISC_LIST_NEXT(t, link);
1782                         }
1783                 }
1784         }
1785
1786         /* Remove orphaned NSECs and RRSIG NSECs. */
1787         for (t = ISC_LIST_HEAD(diffnames.tuples);
1788              t != NULL;
1789              t = ISC_LIST_NEXT(t, link))
1790         {
1791                 CHECK(non_nsec_rrset_exists(db, newver, &t->name, &flag));
1792                 if (! flag) {
1793                         CHECK(delete_if(true_p, db, newver, &t->name,
1794                                         dns_rdatatype_any, 0,
1795                                         NULL, &sig_diff));
1796                 }
1797         }
1798
1799         /*
1800          * When a name is created or deleted, its predecessor needs to
1801          * have its NSEC updated.
1802          */
1803         for (t = ISC_LIST_HEAD(diffnames.tuples);
1804              t != NULL;
1805              t = ISC_LIST_NEXT(t, link))
1806         {
1807                 isc_boolean_t existed, exists;
1808                 dns_fixedname_t fixedname;
1809                 dns_name_t *prevname;
1810
1811                 dns_fixedname_init(&fixedname);
1812                 prevname = dns_fixedname_name(&fixedname);
1813
1814                 CHECK(name_exists(db, oldver, &t->name, &existed));
1815                 CHECK(name_exists(db, newver, &t->name, &exists));
1816                 if (exists == existed)
1817                         continue;
1818
1819                 /*
1820                  * Find the predecessor.
1821                  * When names become obscured or unobscured in this update
1822                  * transaction, we may find the wrong predecessor because
1823                  * the NSECs have not yet been updated to reflect the delegation
1824                  * change.  This should not matter because in this case,
1825                  * the correct predecessor is either the delegation node or
1826                  * a newly unobscured node, and those nodes are on the
1827                  * "affected" list in any case.
1828                  */
1829                 CHECK(next_active(client, zone, db, newver,
1830                                   &t->name, prevname, ISC_FALSE));
1831                 CHECK(namelist_append_name(&affected, prevname));
1832         }
1833
1834         /*
1835          * Find names potentially affected by delegation changes
1836          * (obscured by adding an NS or DNAME, or unobscured by
1837          * removing one).
1838          */
1839         for (t = ISC_LIST_HEAD(diffnames.tuples);
1840              t != NULL;
1841              t = ISC_LIST_NEXT(t, link))
1842         {
1843                 isc_boolean_t ns_existed, dname_existed;
1844                 isc_boolean_t ns_exists, dname_exists;
1845
1846                 CHECK(rrset_exists(db, oldver, &t->name, dns_rdatatype_ns, 0,
1847                                    &ns_existed));
1848                 CHECK(rrset_exists(db, oldver, &t->name, dns_rdatatype_dname, 0,
1849                                    &dname_existed));
1850                 CHECK(rrset_exists(db, newver, &t->name, dns_rdatatype_ns, 0,
1851                                    &ns_exists));
1852                 CHECK(rrset_exists(db, newver, &t->name, dns_rdatatype_dname, 0,
1853                                    &dname_exists));
1854                 if ((ns_exists || dname_exists) == (ns_existed || dname_existed))
1855                         continue;
1856                 /*
1857                  * There was a delegation change.  Mark all subdomains
1858                  * of t->name as potentially needing a NSEC update.
1859                  */
1860                 CHECK(namelist_append_subdomain(db, &t->name, &affected));
1861         }
1862
1863         ISC_LIST_APPENDLIST(affected.tuples, diffnames.tuples, link);
1864         INSIST(ISC_LIST_EMPTY(diffnames.tuples));
1865
1866         CHECK(uniqify_name_list(&affected));
1867
1868         /*
1869          * Determine which names should have NSECs, and delete/create
1870          * NSECs to make it so.  We don't know the final NSEC targets yet,
1871          * so we just create placeholder NSECs with arbitrary contents
1872          * to indicate that their respective owner names should be part of
1873          * the NSEC chain.
1874          */
1875         for (t = ISC_LIST_HEAD(affected.tuples);
1876              t != NULL;
1877              t = ISC_LIST_NEXT(t, link))
1878         {
1879                 isc_boolean_t exists;
1880                 CHECK(name_exists(db, newver, &t->name, &exists));
1881                 if (! exists)
1882                         continue;
1883                 CHECK(is_glue(db, newver, &t->name, &flag));
1884                 if (flag) {
1885                         /*
1886                          * This name is obscured.  Delete any
1887                          * existing NSEC record.
1888                          */
1889                         CHECK(delete_if(true_p, db, newver, &t->name,
1890                                         dns_rdatatype_nsec, 0,
1891                                         NULL, &nsec_diff));
1892                 } else {
1893                         /*
1894                          * This name is not obscured.  It should have a NSEC.
1895                          */
1896                         CHECK(rrset_exists(db, newver, &t->name,
1897                                            dns_rdatatype_nsec, 0, &flag));
1898                         if (! flag)
1899                                 CHECK(add_placeholder_nsec(db, newver, &t->name,
1900                                                           diff));
1901                 }
1902         }
1903
1904         /*
1905          * Now we know which names are part of the NSEC chain.
1906          * Make them all point at their correct targets.
1907          */
1908         for (t = ISC_LIST_HEAD(affected.tuples);
1909              t != NULL;
1910              t = ISC_LIST_NEXT(t, link))
1911         {
1912                 CHECK(rrset_exists(db, newver, &t->name,
1913                                    dns_rdatatype_nsec, 0, &flag));
1914                 if (flag) {
1915                         /*
1916                          * There is a NSEC, but we don't know if it is correct.
1917                          * Delete it and create a correct one to be sure.
1918                          * If the update was unnecessary, the diff minimization
1919                          * will take care of eliminating it from the journal,
1920                          * IXFRs, etc.
1921                          *
1922                          * The RRSIG bit should always be set in the NSECs
1923                          * we generate, because they will all get RRSIG NSECs.
1924                          * (XXX what if the zone keys are missing?).
1925                          * Because the RRSIG NSECs have not necessarily been
1926                          * created yet, the correctness of the bit mask relies
1927                          * on the assumption that NSECs are only created if
1928                          * there is other data, and if there is other data,
1929                          * there are other RRSIGs.
1930                          */
1931                         CHECK(add_nsec(client, zone, db, newver, &t->name,
1932                                        nsecttl, &nsec_diff));
1933                 }
1934         }
1935
1936         /*
1937          * Minimize the set of NSEC updates so that we don't
1938          * have to regenerate the RRSIG NSECs for NSECs that were
1939          * replaced with identical ones.
1940          */
1941         while ((t = ISC_LIST_HEAD(nsec_diff.tuples)) != NULL) {
1942                 ISC_LIST_UNLINK(nsec_diff.tuples, t, link);
1943                 dns_diff_appendminimal(&nsec_mindiff, &t);
1944         }
1945
1946         /* Update RRSIG NSECs. */
1947         for (t = ISC_LIST_HEAD(nsec_mindiff.tuples);
1948              t != NULL;
1949              t = ISC_LIST_NEXT(t, link))
1950         {
1951                 if (t->op == DNS_DIFFOP_DEL) {
1952                         CHECK(delete_if(true_p, db, newver, &t->name,
1953                                         dns_rdatatype_rrsig, dns_rdatatype_nsec,
1954                                         NULL, &sig_diff));
1955                 } else if (t->op == DNS_DIFFOP_ADD) {
1956                         CHECK(add_sigs(db, newver, &t->name, dns_rdatatype_nsec,
1957                                        &sig_diff, zone_keys, nkeys,
1958                                        client->mctx, inception, expire));
1959                 } else {
1960                         INSIST(0);
1961                 }
1962         }
1963
1964         /* Record our changes for the journal. */
1965         while ((t = ISC_LIST_HEAD(sig_diff.tuples)) != NULL) {
1966                 ISC_LIST_UNLINK(sig_diff.tuples, t, link);
1967                 dns_diff_appendminimal(diff, &t);
1968         }
1969         while ((t = ISC_LIST_HEAD(nsec_mindiff.tuples)) != NULL) {
1970                 ISC_LIST_UNLINK(nsec_mindiff.tuples, t, link);
1971                 dns_diff_appendminimal(diff, &t);
1972         }
1973
1974         INSIST(ISC_LIST_EMPTY(sig_diff.tuples));
1975         INSIST(ISC_LIST_EMPTY(nsec_diff.tuples));
1976         INSIST(ISC_LIST_EMPTY(nsec_mindiff.tuples));
1977
1978  failure:
1979         dns_diff_clear(&sig_diff);
1980         dns_diff_clear(&nsec_diff);
1981         dns_diff_clear(&nsec_mindiff);
1982
1983         dns_diff_clear(&affected);
1984         dns_diff_clear(&diffnames);
1985
1986         for (i = 0; i < nkeys; i++)
1987                 dst_key_free(&zone_keys[i]);
1988
1989         return (result);
1990 }
1991
1992
1993 /**************************************************************************/
1994 /*
1995  * The actual update code in all its glory.  We try to follow
1996  * the RFC2136 pseudocode as closely as possible.
1997  */
1998
1999 static isc_result_t
2000 send_update_event(ns_client_t *client, dns_zone_t *zone) {
2001         isc_result_t result = ISC_R_SUCCESS;
2002         update_event_t *event = NULL;
2003         isc_task_t *zonetask = NULL;
2004         ns_client_t *evclient;
2005
2006         event = (update_event_t *)
2007                 isc_event_allocate(client->mctx, client, DNS_EVENT_UPDATE,
2008                                    update_action, NULL, sizeof(*event));
2009         if (event == NULL)
2010                 FAIL(ISC_R_NOMEMORY);
2011         event->zone = zone;
2012         event->result = ISC_R_SUCCESS;
2013
2014         evclient = NULL;
2015         ns_client_attach(client, &evclient);
2016         INSIST(client->nupdates == 0);
2017         client->nupdates++;
2018         event->ev_arg = evclient;
2019
2020         dns_zone_gettask(zone, &zonetask);
2021         isc_task_send(zonetask, ISC_EVENT_PTR(&event));
2022
2023  failure:
2024         if (event != NULL)
2025                 isc_event_free(ISC_EVENT_PTR(&event));
2026         return (result);
2027 }
2028
2029 static void
2030 respond(ns_client_t *client, isc_result_t result) {
2031         isc_result_t msg_result;
2032
2033         msg_result = dns_message_reply(client->message, ISC_TRUE);
2034         if (msg_result != ISC_R_SUCCESS)
2035                 goto msg_failure;
2036         client->message->rcode = dns_result_torcode(result);
2037
2038         ns_client_send(client);
2039         return;
2040
2041  msg_failure:
2042         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_UPDATE, NS_LOGMODULE_UPDATE,
2043                       ISC_LOG_ERROR,
2044                       "could not create update response message: %s",
2045                       isc_result_totext(msg_result));
2046         ns_client_next(client, msg_result);
2047 }
2048
2049 void
2050 ns_update_start(ns_client_t *client, isc_result_t sigresult) {
2051         dns_message_t *request = client->message;
2052         isc_result_t result;
2053         dns_name_t *zonename;
2054         dns_rdataset_t *zone_rdataset;
2055         dns_zone_t *zone = NULL;
2056
2057         /*
2058          * Interpret the zone section.
2059          */
2060         result = dns_message_firstname(request, DNS_SECTION_ZONE);
2061         if (result != ISC_R_SUCCESS)
2062                 FAILC(DNS_R_FORMERR,
2063                       "update zone section empty");
2064
2065         /*
2066          * The zone section must contain exactly one "question", and
2067          * it must be of type SOA.
2068          */
2069         zonename = NULL;
2070         dns_message_currentname(request, DNS_SECTION_ZONE, &zonename);
2071         zone_rdataset = ISC_LIST_HEAD(zonename->list);
2072         if (zone_rdataset->type != dns_rdatatype_soa)
2073                 FAILC(DNS_R_FORMERR,
2074                       "update zone section contains non-SOA");
2075         if (ISC_LIST_NEXT(zone_rdataset, link) != NULL)
2076                 FAILC(DNS_R_FORMERR,
2077                       "update zone section contains multiple RRs");
2078
2079         /* The zone section must have exactly one name. */
2080         result = dns_message_nextname(request, DNS_SECTION_ZONE);
2081         if (result != ISC_R_NOMORE)
2082                 FAILC(DNS_R_FORMERR,
2083                       "update zone section contains multiple RRs");
2084
2085         result = dns_zt_find(client->view->zonetable, zonename, 0, NULL,
2086                              &zone);
2087         if (result != ISC_R_SUCCESS)
2088                 FAILC(DNS_R_NOTAUTH,
2089                       "not authoritative for update zone");
2090
2091         switch(dns_zone_gettype(zone)) {
2092         case dns_zone_master:
2093                 /*
2094                  * We can now fail due to a bad signature as we now know
2095                  * that we are the master.
2096                  */
2097                 if (sigresult != ISC_R_SUCCESS)
2098                         FAIL(sigresult);
2099                 CHECK(send_update_event(client, zone));
2100                 break;
2101         case dns_zone_slave:
2102                 CHECK(checkupdateacl(client, dns_zone_getforwardacl(zone),
2103                                      "update forwarding", zonename, ISC_TRUE));
2104                 CHECK(send_forward_event(client, zone));
2105                 break;
2106         default:
2107                 FAILC(DNS_R_NOTAUTH,
2108                       "not authoritative for update zone");
2109         }
2110         return;
2111
2112  failure:
2113         /*
2114          * We failed without having sent an update event to the zone.
2115          * We are still in the client task context, so we can
2116          * simply give an error response without switching tasks.
2117          */
2118         respond(client, result);
2119         if (zone != NULL)
2120                 dns_zone_detach(&zone);
2121 }
2122
2123 /*
2124  * DS records are not allowed to exist without corresponding NS records,
2125  * draft-ietf-dnsext-delegation-signer-11.txt, 2.2 Protocol Change,
2126  * "DS RRsets MUST NOT appear at non-delegation points or at a zone's apex".
2127  */
2128
2129 static isc_result_t
2130 remove_orphaned_ds(dns_db_t *db, dns_dbversion_t *newver, dns_diff_t *diff) {
2131         isc_result_t result;
2132         isc_boolean_t ns_exists, ds_exists;
2133         dns_difftuple_t *t;
2134
2135         for (t = ISC_LIST_HEAD(diff->tuples);
2136              t != NULL;
2137              t = ISC_LIST_NEXT(t, link)) {
2138                 if (t->op != DNS_DIFFOP_DEL ||
2139                     t->rdata.type != dns_rdatatype_ns)
2140                         continue;
2141                 CHECK(rrset_exists(db, newver, &t->name, dns_rdatatype_ns, 0,
2142                                    &ns_exists));
2143                 if (ns_exists)
2144                         continue;
2145                 CHECK(rrset_exists(db, newver, &t->name, dns_rdatatype_ds, 0,
2146                                    &ds_exists));
2147                 if (!ds_exists)
2148                         continue;
2149                 CHECK(delete_if(true_p, db, newver, &t->name,
2150                                 dns_rdatatype_ds, 0, NULL, diff));
2151         }
2152         return (ISC_R_SUCCESS);
2153
2154  failure:
2155         return (result);
2156 }
2157
2158 static void
2159 update_action(isc_task_t *task, isc_event_t *event) {
2160         update_event_t *uev = (update_event_t *) event;
2161         dns_zone_t *zone = uev->zone;
2162         ns_client_t *client = (ns_client_t *)event->ev_arg;
2163
2164         isc_result_t result;
2165         dns_db_t *db = NULL;
2166         dns_dbversion_t *oldver = NULL;
2167         dns_dbversion_t *ver = NULL;
2168         dns_diff_t diff;        /* Pending updates. */
2169         dns_diff_t temp;        /* Pending RR existence assertions. */
2170         isc_boolean_t soa_serial_changed = ISC_FALSE;
2171         isc_mem_t *mctx = client->mctx;
2172         dns_rdatatype_t covers;
2173         dns_message_t *request = client->message;
2174         dns_rdataclass_t zoneclass;
2175         dns_name_t *zonename;
2176         dns_ssutable_t *ssutable = NULL;
2177         dns_fixedname_t tmpnamefixed;
2178         dns_name_t *tmpname = NULL;
2179
2180         INSIST(event->ev_type == DNS_EVENT_UPDATE);
2181
2182         dns_diff_init(mctx, &diff);
2183         dns_diff_init(mctx, &temp);
2184
2185         CHECK(dns_zone_getdb(zone, &db));
2186         zonename = dns_db_origin(db);
2187         zoneclass = dns_db_class(db);
2188         dns_zone_getssutable(zone, &ssutable);
2189         dns_db_currentversion(db, &oldver);
2190         CHECK(dns_db_newversion(db, &ver));
2191
2192         /*
2193          * Check prerequisites.
2194          */
2195
2196         for (result = dns_message_firstname(request, DNS_SECTION_PREREQUISITE);
2197              result == ISC_R_SUCCESS;
2198              result = dns_message_nextname(request, DNS_SECTION_PREREQUISITE))
2199         {
2200                 dns_name_t *name = NULL;
2201                 dns_rdata_t rdata = DNS_RDATA_INIT;
2202                 dns_ttl_t ttl;
2203                 dns_rdataclass_t update_class;
2204                 isc_boolean_t flag;
2205
2206                 get_current_rr(request, DNS_SECTION_PREREQUISITE, zoneclass,
2207                                &name, &rdata, &covers, &ttl, &update_class);
2208
2209                 if (ttl != 0)
2210                         FAILC(DNS_R_FORMERR, "prerequisite TTL is not zero");
2211
2212                 if (! dns_name_issubdomain(name, zonename))
2213                         FAILN(DNS_R_NOTZONE, name,
2214                                 "prerequisite name is out of zone");
2215
2216                 if (update_class == dns_rdataclass_any) {
2217                         if (rdata.length != 0)
2218                                 FAILC(DNS_R_FORMERR,
2219                                       "class ANY prerequisite "
2220                                       "RDATA is not empty");
2221                         if (rdata.type == dns_rdatatype_any) {
2222                                 CHECK(name_exists(db, ver, name, &flag));
2223                                 if (! flag) {
2224                                         FAILN(DNS_R_NXDOMAIN, name,
2225                                               "'name in use' prerequisite "
2226                                               "not satisfied");
2227                                 }
2228                         } else {
2229                                 CHECK(rrset_exists(db, ver, name,
2230                                                    rdata.type, covers, &flag));
2231                                 if (! flag) {
2232                                         /* RRset does not exist. */
2233                                         FAILNT(DNS_R_NXRRSET, name, rdata.type,
2234                                         "'rrset exists (value independent)' "
2235                                         "prerequisite not satisfied");
2236                                 }
2237                         }
2238                 } else if (update_class == dns_rdataclass_none) {
2239                         if (rdata.length != 0)
2240                                 FAILC(DNS_R_FORMERR,
2241                                       "class NONE prerequisite "
2242                                       "RDATA is not empty");
2243                         if (rdata.type == dns_rdatatype_any) {
2244                                 CHECK(name_exists(db, ver, name, &flag));
2245                                 if (flag) {
2246                                         FAILN(DNS_R_YXDOMAIN, name,
2247                                               "'name not in use' prerequisite "
2248                                               "not satisfied");
2249                                 }
2250                         } else {
2251                                 CHECK(rrset_exists(db, ver, name,
2252                                                    rdata.type, covers, &flag));
2253                                 if (flag) {
2254                                         /* RRset exists. */
2255                                         FAILNT(DNS_R_YXRRSET, name, rdata.type,
2256                                                "'rrset does not exist' "
2257                                                "prerequisite not satisfied");
2258                                 }
2259                         }
2260                 } else if (update_class == zoneclass) {
2261                         /* "temp<rr.name, rr.type> += rr;" */
2262                         result = temp_append(&temp, name, &rdata);
2263                         if (result != ISC_R_SUCCESS) {
2264                                 UNEXPECTED_ERROR(__FILE__, __LINE__,
2265                                          "temp entry creation failed: %s",
2266                                                  dns_result_totext(result));
2267                                 FAIL(ISC_R_UNEXPECTED);
2268                         }
2269                 } else {
2270                         FAILC(DNS_R_FORMERR, "malformed prerequisite");
2271                 }
2272         }
2273         if (result != ISC_R_NOMORE)
2274                 FAIL(result);
2275
2276
2277         /*
2278          * Perform the final check of the "rrset exists (value dependent)"
2279          * prerequisites.
2280          */
2281         if (ISC_LIST_HEAD(temp.tuples) != NULL) {
2282                 dns_rdatatype_t type;
2283
2284                 /*
2285                  * Sort the prerequisite records by owner name,
2286                  * type, and rdata.
2287                  */
2288                 result = dns_diff_sort(&temp, temp_order);
2289                 if (result != ISC_R_SUCCESS)
2290                         FAILC(result, "'RRset exists (value dependent)' "
2291                               "prerequisite not satisfied");
2292
2293                 dns_fixedname_init(&tmpnamefixed);
2294                 tmpname = dns_fixedname_name(&tmpnamefixed);
2295                 result = temp_check(mctx, &temp, db, ver, tmpname, &type);
2296                 if (result != ISC_R_SUCCESS)
2297                         FAILNT(result, tmpname, type,
2298                                "'RRset exists (value dependent)' "
2299                                "prerequisite not satisfied");
2300         }
2301
2302         update_log(client, zone, LOGLEVEL_DEBUG,
2303                    "prerequisites are OK");
2304
2305         /*
2306          * Check Requestor's Permissions.  It seems a bit silly to do this
2307          * only after prerequisite testing, but that is what RFC2136 says.
2308          */
2309         result = ISC_R_SUCCESS;
2310         if (ssutable == NULL)
2311                 CHECK(checkupdateacl(client, dns_zone_getupdateacl(zone),
2312                                      "update", zonename, ISC_FALSE));
2313         else if (client->signer == NULL)
2314                 CHECK(checkupdateacl(client, NULL, "update", zonename,
2315                                      ISC_FALSE));
2316
2317         if (dns_zone_getupdatedisabled(zone))
2318                 FAILC(DNS_R_REFUSED, "dynamic update temporarily disabled");
2319
2320         /*
2321          * Perform the Update Section Prescan.
2322          */
2323
2324         for (result = dns_message_firstname(request, DNS_SECTION_UPDATE);
2325              result == ISC_R_SUCCESS;
2326              result = dns_message_nextname(request, DNS_SECTION_UPDATE))
2327         {
2328                 dns_name_t *name = NULL;
2329                 dns_rdata_t rdata = DNS_RDATA_INIT;
2330                 dns_ttl_t ttl;
2331                 dns_rdataclass_t update_class;
2332                 get_current_rr(request, DNS_SECTION_UPDATE, zoneclass,
2333                                &name, &rdata, &covers, &ttl, &update_class);
2334
2335                 if (! dns_name_issubdomain(name, zonename))
2336                         FAILC(DNS_R_NOTZONE,
2337                               "update RR is outside zone");
2338                 if (update_class == zoneclass) {
2339                         /*
2340                          * Check for meta-RRs.  The RFC2136 pseudocode says
2341                          * check for ANY|AXFR|MAILA|MAILB, but the text adds
2342                          * "or any other QUERY metatype"
2343                          */
2344                         if (dns_rdatatype_ismeta(rdata.type)) {
2345                                 FAILC(DNS_R_FORMERR,
2346                                       "meta-RR in update");
2347                         }
2348                         result = dns_zone_checknames(zone, name, &rdata);
2349                         if (result != ISC_R_SUCCESS)
2350                                 FAIL(DNS_R_REFUSED);
2351                 } else if (update_class == dns_rdataclass_any) {
2352                         if (ttl != 0 || rdata.length != 0 ||
2353                             (dns_rdatatype_ismeta(rdata.type) &&
2354                              rdata.type != dns_rdatatype_any))
2355                                 FAILC(DNS_R_FORMERR,
2356                                       "meta-RR in update");
2357                 } else if (update_class == dns_rdataclass_none) {
2358                         if (ttl != 0 ||
2359                             dns_rdatatype_ismeta(rdata.type))
2360                                 FAILC(DNS_R_FORMERR,
2361                                       "meta-RR in update");
2362                 } else {
2363                         update_log(client, zone, ISC_LOG_WARNING,
2364                                    "update RR has incorrect class %d",
2365                                    update_class);
2366                         FAIL(DNS_R_FORMERR);
2367                 }
2368                 /*
2369                  * draft-ietf-dnsind-simple-secure-update-01 says
2370                  * "Unlike traditional dynamic update, the client
2371                  * is forbidden from updating NSEC records."
2372                  */
2373                 if (dns_db_issecure(db)) {
2374                         if (rdata.type == dns_rdatatype_nsec) {
2375                                 FAILC(DNS_R_REFUSED,
2376                                       "explicit NSEC updates are not allowed "
2377                                       "in secure zones");
2378                         }
2379                         else if (rdata.type == dns_rdatatype_rrsig) {
2380                                 FAILC(DNS_R_REFUSED,
2381                                       "explicit RRSIG updates are currently not "
2382                                       "supported in secure zones");
2383                         }
2384                 }
2385
2386                 if (ssutable != NULL && client->signer != NULL) {
2387                         if (rdata.type != dns_rdatatype_any) {
2388                                 if (!dns_ssutable_checkrules(ssutable,
2389                                                              client->signer,
2390                                                              name, rdata.type))
2391                                         FAILC(DNS_R_REFUSED,
2392                                               "rejected by secure update");
2393                         }
2394                         else {
2395                                 if (!ssu_checkall(db, ver, name, ssutable,
2396                                                   client->signer))
2397                                         FAILC(DNS_R_REFUSED,
2398                                               "rejected by secure update");
2399                         }
2400                 }
2401         }
2402         if (result != ISC_R_NOMORE)
2403                 FAIL(result);
2404
2405         update_log(client, zone, LOGLEVEL_DEBUG,
2406                    "update section prescan OK");
2407
2408         /*
2409          * Process the Update Section.
2410          */
2411
2412         for (result = dns_message_firstname(request, DNS_SECTION_UPDATE);
2413              result == ISC_R_SUCCESS;
2414              result = dns_message_nextname(request, DNS_SECTION_UPDATE))
2415         {
2416                 dns_name_t *name = NULL;
2417                 dns_rdata_t rdata = DNS_RDATA_INIT;
2418                 dns_ttl_t ttl;
2419                 dns_rdataclass_t update_class;
2420                 isc_boolean_t flag;
2421
2422                 get_current_rr(request, DNS_SECTION_UPDATE, zoneclass,
2423                                &name, &rdata, &covers, &ttl, &update_class);
2424
2425                 if (update_class == zoneclass) {
2426
2427                         /*
2428                          * RFC 1123 doesn't allow MF and MD in master zones.                             */
2429                         if (rdata.type == dns_rdatatype_md ||
2430                             rdata.type == dns_rdatatype_mf) {
2431                                 char typebuf[DNS_RDATATYPE_FORMATSIZE];
2432
2433                                 dns_rdatatype_format(rdata.type, typebuf,
2434                                                      sizeof(typebuf));
2435                                 update_log(client, zone, LOGLEVEL_PROTOCOL,
2436                                            "attempt to add %s ignored",
2437                                            typebuf);
2438                                 continue;
2439                         }
2440                         if (rdata.type == dns_rdatatype_ns &&
2441                             dns_name_iswildcard(name)) {
2442                                 update_log(client, zone,
2443                                            LOGLEVEL_PROTOCOL,
2444                                            "attempt to add wildcard NS record"
2445                                            "ignored");
2446                                 continue;
2447                         }
2448                         if (rdata.type == dns_rdatatype_cname) {
2449                                 CHECK(cname_incompatible_rrset_exists(db, ver,
2450                                                                       name,
2451                                                                       &flag));
2452                                 if (flag) {
2453                                         update_log(client, zone,
2454                                                    LOGLEVEL_PROTOCOL,
2455                                                    "attempt to add CNAME "
2456                                                    "alongside non-CNAME "
2457                                                    "ignored");
2458                                         continue;
2459                                 }
2460                         } else {
2461                                 CHECK(rrset_exists(db, ver, name,
2462                                                    dns_rdatatype_cname, 0,
2463                                                    &flag));
2464                                 if (flag &&
2465                                     ! dns_rdatatype_isdnssec(rdata.type))
2466                                 {
2467                                         update_log(client, zone,
2468                                                    LOGLEVEL_PROTOCOL,
2469                                                    "attempt to add non-CNAME "
2470                                                    "alongside CNAME ignored");
2471                                         continue;
2472                                 }
2473                         }
2474                         if (rdata.type == dns_rdatatype_soa) {
2475                                 isc_boolean_t ok;
2476                                 CHECK(rrset_exists(db, ver, name,
2477                                                    dns_rdatatype_soa, 0,
2478                                                    &flag));
2479                                 if (! flag) {
2480                                         update_log(client, zone,
2481                                                    LOGLEVEL_PROTOCOL,
2482                                                    "attempt to create 2nd "
2483                                                    "SOA ignored");
2484                                         continue;
2485                                 }
2486                                 CHECK(check_soa_increment(db, ver, &rdata,
2487                                                           &ok));
2488                                 if (! ok) {
2489                                         update_log(client, zone,
2490                                                    LOGLEVEL_PROTOCOL,
2491                                                    "SOA update failed to "
2492                                                    "increment serial, "
2493                                                    "ignoring it");
2494                                         continue;
2495                                 }
2496                                 soa_serial_changed = ISC_TRUE;
2497                         }
2498
2499                         if (isc_log_wouldlog(ns_g_lctx, LOGLEVEL_PROTOCOL)) {
2500                                 char namestr[DNS_NAME_FORMATSIZE];
2501                                 char typestr[DNS_RDATATYPE_FORMATSIZE];
2502                                 dns_name_format(name, namestr,
2503                                                 sizeof(namestr));
2504                                 dns_rdatatype_format(rdata.type, typestr,
2505                                                      sizeof(typestr));
2506                                 update_log(client, zone,
2507                                            LOGLEVEL_PROTOCOL,
2508                                            "adding an RR at '%s' %s",
2509                                            namestr, typestr);
2510                         }
2511
2512                         /* Prepare the affected RRset for the addition. */
2513                         {
2514                                 add_rr_prepare_ctx_t ctx;
2515                                 ctx.db = db;
2516                                 ctx.ver = ver;
2517                                 ctx.diff = &diff;
2518                                 ctx.name = name;
2519                                 ctx.update_rr = &rdata;
2520                                 ctx.update_rr_ttl = ttl;
2521                                 ctx.ignore_add = ISC_FALSE;
2522                                 dns_diff_init(mctx, &ctx.del_diff);
2523                                 dns_diff_init(mctx, &ctx.add_diff);
2524                                 CHECK(foreach_rr(db, ver, name, rdata.type,
2525                                                  covers, add_rr_prepare_action,
2526                                                  &ctx));
2527
2528                                 if (ctx.ignore_add) {
2529                                         dns_diff_clear(&ctx.del_diff);
2530                                         dns_diff_clear(&ctx.add_diff);
2531                                 } else {
2532                                         CHECK(do_diff(&ctx.del_diff, db, ver, &diff));
2533                                         CHECK(do_diff(&ctx.add_diff, db, ver, &diff));
2534                                         CHECK(update_one_rr(db, ver, &diff,
2535                                                             DNS_DIFFOP_ADD,
2536                                                             name, ttl, &rdata));
2537                                 }
2538                         }
2539                 } else if (update_class == dns_rdataclass_any) {
2540                         if (rdata.type == dns_rdatatype_any) {
2541                                 if (isc_log_wouldlog(ns_g_lctx,
2542                                                      LOGLEVEL_PROTOCOL))
2543                                 {
2544                                         char namestr[DNS_NAME_FORMATSIZE];
2545                                         dns_name_format(name, namestr,
2546                                                         sizeof(namestr));
2547                                         update_log(client, zone,
2548                                                    LOGLEVEL_PROTOCOL,
2549                                                    "delete all rrsets from "
2550                                                    "name '%s'", namestr);
2551                                 }
2552                                 if (dns_name_equal(name, zonename)) {
2553                                         CHECK(delete_if(type_not_soa_nor_ns_p,
2554                                                         db, ver, name,
2555                                                         dns_rdatatype_any, 0,
2556                                                         &rdata, &diff));
2557                                 } else {
2558                                         CHECK(delete_if(type_not_dnssec,
2559                                                         db, ver, name,
2560                                                         dns_rdatatype_any, 0,
2561                                                         &rdata, &diff));
2562                                 }
2563                         } else if (dns_name_equal(name, zonename) &&
2564                                    (rdata.type == dns_rdatatype_soa ||
2565                                     rdata.type == dns_rdatatype_ns)) {
2566                                 update_log(client, zone,
2567                                            LOGLEVEL_PROTOCOL,
2568                                            "attempt to delete all SOA "
2569                                            "or NS records ignored");
2570                                 continue;
2571                         } else {
2572                                 if (isc_log_wouldlog(ns_g_lctx,
2573                                                      LOGLEVEL_PROTOCOL))
2574                                 {
2575                                         char namestr[DNS_NAME_FORMATSIZE];
2576                                         char typestr[DNS_RDATATYPE_FORMATSIZE];
2577                                         dns_name_format(name, namestr,
2578                                                         sizeof(namestr));
2579                                         dns_rdatatype_format(rdata.type,
2580                                                              typestr,
2581                                                              sizeof(typestr));
2582                                         update_log(client, zone,
2583                                                    LOGLEVEL_PROTOCOL,
2584                                                    "deleting rrset at '%s' %s",
2585                                                    namestr, typestr);
2586                                 }
2587                                 CHECK(delete_if(true_p, db, ver, name,
2588                                                 rdata.type, covers, &rdata,
2589                                                 &diff));
2590                         }
2591                 } else if (update_class == dns_rdataclass_none) {
2592                         /*
2593                          * The (name == zonename) condition appears in
2594                          * RFC2136 3.4.2.4 but is missing from the pseudocode.
2595                          */
2596                         if (dns_name_equal(name, zonename)) {
2597                                 if (rdata.type == dns_rdatatype_soa) {
2598                                         update_log(client, zone,
2599                                                    LOGLEVEL_PROTOCOL,
2600                                                    "attempt to delete SOA "
2601                                                    "ignored");
2602                                         continue;
2603                                 }
2604                                 if (rdata.type == dns_rdatatype_ns) {
2605                                         int count;
2606                                         CHECK(rr_count(db, ver, name,
2607                                                        dns_rdatatype_ns,
2608                                                        0, &count));
2609                                         if (count == 1) {
2610                                                 update_log(client, zone,
2611                                                            LOGLEVEL_PROTOCOL,
2612                                                            "attempt to "
2613                                                            "delete last "
2614                                                            "NS ignored");
2615                                                 continue;
2616                                         }
2617                                 }
2618                         }
2619                         update_log(client, zone,
2620                                    LOGLEVEL_PROTOCOL,
2621                                    "deleting an RR");
2622                         CHECK(delete_if(rr_equal_p, db, ver, name,
2623                                         rdata.type, covers, &rdata, &diff));
2624                 }
2625         }
2626         if (result != ISC_R_NOMORE)
2627                 FAIL(result);
2628
2629         /*
2630          * If any changes were made, increment the SOA serial number,
2631          * update RRSIGs and NSECs (if zone is secure), and write the update
2632          * to the journal.
2633          */
2634         if (! ISC_LIST_EMPTY(diff.tuples)) {
2635                 char *journalfile;
2636                 dns_journal_t *journal;
2637
2638                 /*
2639                  * Increment the SOA serial, but only if it was not
2640                  * changed as a result of an update operation.
2641                  */
2642                 if (! soa_serial_changed) {
2643                         CHECK(increment_soa_serial(db, ver, &diff, mctx));
2644                 }
2645
2646                 CHECK(remove_orphaned_ds(db, ver, &diff));
2647
2648                 if (dns_db_issecure(db)) {
2649                         result = update_signatures(client, zone, db, oldver,
2650                                                    ver, &diff,
2651                                          dns_zone_getsigvalidityinterval(zone));
2652                         if (result != ISC_R_SUCCESS) {
2653                                 update_log(client, zone,
2654                                            ISC_LOG_ERROR,
2655                                            "RRSIG/NSEC update failed: %s",
2656                                            isc_result_totext(result));
2657                                 goto failure;
2658                         }
2659                 }
2660
2661                 journalfile = dns_zone_getjournal(zone);
2662                 if (journalfile != NULL) {
2663                         update_log(client, zone, LOGLEVEL_DEBUG,
2664                                    "writing journal %s", journalfile);
2665
2666                         journal = NULL;
2667                         result = dns_journal_open(mctx, journalfile,
2668                                                   ISC_TRUE, &journal);
2669                         if (result != ISC_R_SUCCESS)
2670                                 FAILS(result, "journal open failed");
2671
2672                         result = dns_journal_write_transaction(journal, &diff);
2673                         if (result != ISC_R_SUCCESS) {
2674                                 dns_journal_destroy(&journal);
2675                                 FAILS(result, "journal write failed");
2676                         }
2677
2678                         dns_journal_destroy(&journal);
2679                 }
2680
2681                 /*
2682                  * XXXRTH  Just a note that this committing code will have
2683                  *         to change to handle databases that need two-phase
2684                  *         commit, but this isn't a priority.
2685                  */
2686                 update_log(client, zone, LOGLEVEL_DEBUG,
2687                            "committing update transaction");
2688                 dns_db_closeversion(db, &ver, ISC_TRUE);
2689
2690                 /*
2691                  * Mark the zone as dirty so that it will be written to disk.
2692                  */
2693                 dns_zone_markdirty(zone);
2694
2695                 /*
2696                  * Notify slaves of the change we just made.
2697                  */
2698                 dns_zone_notify(zone);
2699         } else {
2700                 update_log(client, zone, LOGLEVEL_DEBUG, "redundant request");
2701                 dns_db_closeversion(db, &ver, ISC_TRUE);
2702         }
2703         result = ISC_R_SUCCESS;
2704         goto common;
2705
2706  failure:
2707         /*
2708          * The reason for failure should have been logged at this point.
2709          */
2710         if (ver != NULL) {
2711                 update_log(client, zone, LOGLEVEL_DEBUG,
2712                            "rolling back");
2713                 dns_db_closeversion(db, &ver, ISC_FALSE);
2714         }
2715
2716  common:
2717         dns_diff_clear(&temp);
2718         dns_diff_clear(&diff);
2719
2720         if (oldver != NULL)
2721                 dns_db_closeversion(db, &oldver, ISC_FALSE);
2722
2723         if (db != NULL)
2724                 dns_db_detach(&db);
2725
2726         if (ssutable != NULL)
2727                 dns_ssutable_detach(&ssutable);
2728
2729         if (zone != NULL)
2730                 dns_zone_detach(&zone);
2731
2732         isc_task_detach(&task);
2733         uev->result = result;
2734         uev->ev_type = DNS_EVENT_UPDATEDONE;
2735         uev->ev_action = updatedone_action;
2736         isc_task_send(client->task, &event);
2737         INSIST(event == NULL);
2738 }
2739
2740 static void
2741 updatedone_action(isc_task_t *task, isc_event_t *event) {
2742         update_event_t *uev = (update_event_t *) event;
2743         ns_client_t *client = (ns_client_t *) event->ev_arg;
2744
2745         UNUSED(task);
2746
2747         INSIST(event->ev_type == DNS_EVENT_UPDATEDONE);
2748         INSIST(task == client->task);
2749
2750         INSIST(client->nupdates > 0);
2751         client->nupdates--;
2752         respond(client, uev->result);
2753         isc_event_free(&event);
2754         ns_client_detach(&client);
2755 }
2756
2757 /*
2758  * Update forwarding support.
2759  */
2760
2761 static void
2762 forward_fail(isc_task_t *task, isc_event_t *event) {
2763         ns_client_t *client = (ns_client_t *)event->ev_arg;
2764
2765         UNUSED(task);
2766
2767         INSIST(client->nupdates > 0);
2768         client->nupdates--;
2769         respond(client, DNS_R_SERVFAIL);
2770         isc_event_free(&event);
2771         ns_client_detach(&client);
2772 }
2773
2774
2775 static void
2776 forward_callback(void *arg, isc_result_t result, dns_message_t *answer) {
2777         update_event_t *uev = arg;
2778         ns_client_t *client = uev->ev_arg;
2779
2780         if (result != ISC_R_SUCCESS) {
2781                 INSIST(answer == NULL);
2782                 uev->ev_type = DNS_EVENT_UPDATEDONE;
2783                 uev->ev_action = forward_fail;
2784         } else {
2785                 uev->ev_type = DNS_EVENT_UPDATEDONE;
2786                 uev->ev_action = forward_done;
2787                 uev->answer = answer;
2788         }
2789         isc_task_send(client->task, ISC_EVENT_PTR(&uev));
2790 }
2791
2792 static void
2793 forward_done(isc_task_t *task, isc_event_t *event) {
2794         update_event_t *uev = (update_event_t *) event;
2795         ns_client_t *client = (ns_client_t *)event->ev_arg;
2796
2797         UNUSED(task);
2798
2799         INSIST(client->nupdates > 0);
2800         client->nupdates--;
2801         ns_client_sendraw(client, uev->answer);
2802         dns_message_destroy(&uev->answer);
2803         isc_event_free(&event);
2804         ns_client_detach(&client);
2805 }
2806
2807 static void
2808 forward_action(isc_task_t *task, isc_event_t *event) {
2809         update_event_t *uev = (update_event_t *) event;
2810         dns_zone_t *zone = uev->zone;
2811         ns_client_t *client = (ns_client_t *)event->ev_arg;
2812         isc_result_t result;
2813
2814         result = dns_zone_forwardupdate(zone, client->message,
2815                                         forward_callback, event);
2816         if (result != ISC_R_SUCCESS) {
2817                 uev->ev_type = DNS_EVENT_UPDATEDONE;
2818                 uev->ev_action = forward_fail;
2819                 isc_task_send(client->task, &event);
2820         }
2821         dns_zone_detach(&zone);
2822         isc_task_detach(&task);
2823 }
2824
2825 static isc_result_t
2826 send_forward_event(ns_client_t *client, dns_zone_t *zone) {
2827         isc_result_t result = ISC_R_SUCCESS;
2828         update_event_t *event = NULL;
2829         isc_task_t *zonetask = NULL;
2830         ns_client_t *evclient;
2831
2832         event = (update_event_t *)
2833                 isc_event_allocate(client->mctx, client, DNS_EVENT_UPDATE,
2834                                    forward_action, NULL, sizeof(*event));
2835         if (event == NULL)
2836                 FAIL(ISC_R_NOMEMORY);
2837         event->zone = zone;
2838         event->result = ISC_R_SUCCESS;
2839
2840         evclient = NULL;
2841         ns_client_attach(client, &evclient);
2842         INSIST(client->nupdates == 0);
2843         client->nupdates++;
2844         event->ev_arg = evclient;
2845
2846         dns_zone_gettask(zone, &zonetask);
2847         isc_task_send(zonetask, ISC_EVENT_PTR(&event));
2848
2849  failure:
2850         if (event != NULL)
2851                 isc_event_free(ISC_EVENT_PTR(&event));
2852         return (result);
2853 }