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