Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
/*	$NetBSD: update.c,v 1.12 2023/01/25 21:43:30 christos Exp $	*/

/*
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
 *
 * SPDX-License-Identifier: MPL-2.0
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at https://mozilla.org/MPL/2.0/.
 *
 * See the COPYRIGHT file distributed with this work for additional
 * information regarding copyright ownership.
 */

#include <inttypes.h>
#include <stdbool.h>
#include <time.h>

#include <isc/log.h>
#include <isc/magic.h>
#include <isc/mem.h>
#include <isc/netaddr.h>
#include <isc/platform.h>
#include <isc/print.h>
#include <isc/random.h>
#include <isc/serial.h>
#include <isc/stats.h>
#include <isc/stdtime.h>
#include <isc/string.h>
#include <isc/taskpool.h>
#include <isc/time.h>
#include <isc/util.h>

#include <dns/db.h>
#include <dns/dbiterator.h>
#include <dns/diff.h>
#include <dns/dnssec.h>
#include <dns/events.h>
#include <dns/fixedname.h>
#include <dns/journal.h>
#include <dns/kasp.h>
#include <dns/keyvalues.h>
#include <dns/log.h>
#include <dns/message.h>
#include <dns/nsec.h>
#include <dns/nsec3.h>
#include <dns/private.h>
#include <dns/rdataclass.h>
#include <dns/rdataset.h>
#include <dns/rdatasetiter.h>
#include <dns/rdatastruct.h>
#include <dns/rdatatype.h>
#include <dns/result.h>
#include <dns/soa.h>
#include <dns/ssu.h>
#include <dns/stats.h>
#include <dns/tsig.h>
#include <dns/update.h>
#include <dns/view.h>
#include <dns/zone.h>
#include <dns/zt.h>

/**************************************************************************/

#define STATE_MAGIC	       ISC_MAGIC('S', 'T', 'T', 'E')
#define DNS_STATE_VALID(state) ISC_MAGIC_VALID(state, STATE_MAGIC)

/*%
 * Log level for tracing dynamic update protocol requests.
 */
#define LOGLEVEL_PROTOCOL ISC_LOG_INFO

/*%
 * Log level for low-level debug tracing.
 */
#define LOGLEVEL_DEBUG ISC_LOG_DEBUG(8)

/*%
 * Check an operation for failure.  These macros all assume that
 * the function using them has a 'result' variable and a 'failure'
 * label.
 */
#define CHECK(op)                            \
	do {                                 \
		result = (op);               \
		if (result != ISC_R_SUCCESS) \
			goto failure;        \
	} while (0)

/*%
 * Fail unconditionally with result 'code', which must not
 * be ISC_R_SUCCESS.  The reason for failure presumably has
 * been logged already.
 *
 * The test against ISC_R_SUCCESS is there to keep the Solaris compiler
 * from complaining about "end-of-loop code not reached".
 */

#define FAIL(code)                           \
	do {                                 \
		result = (code);             \
		if (result != ISC_R_SUCCESS) \
			goto failure;        \
	} while (0)

/*%
 * Fail unconditionally and log as a client error.
 * The test against ISC_R_SUCCESS is there to keep the Solaris compiler
 * from complaining about "end-of-loop code not reached".
 */
#define FAILC(code, msg)                                                       \
	do {                                                                   \
		const char *_what = "failed";                                  \
		result = (code);                                               \
		switch (result) {                                              \
		case DNS_R_NXDOMAIN:                                           \
		case DNS_R_YXDOMAIN:                                           \
		case DNS_R_YXRRSET:                                            \
		case DNS_R_NXRRSET:                                            \
			_what = "unsuccessful";                                \
		}                                                              \
		update_log(log, zone, LOGLEVEL_PROTOCOL, "update %s: %s (%s)", \
			   _what, msg, isc_result_totext(result));             \
		if (result != ISC_R_SUCCESS)                                   \
			goto failure;                                          \
	} while (0)

#define FAILN(code, name, msg)                                             \
	do {                                                               \
		const char *_what = "failed";                              \
		result = (code);                                           \
		switch (result) {                                          \
		case DNS_R_NXDOMAIN:                                       \
		case DNS_R_YXDOMAIN:                                       \
		case DNS_R_YXRRSET:                                        \
		case DNS_R_NXRRSET:                                        \
			_what = "unsuccessful";                            \
		}                                                          \
		if (isc_log_wouldlog(dns_lctx, LOGLEVEL_PROTOCOL)) {       \
			char _nbuf[DNS_NAME_FORMATSIZE];                   \
			dns_name_format(name, _nbuf, sizeof(_nbuf));       \
			update_log(log, zone, LOGLEVEL_PROTOCOL,           \
				   "update %s: %s: %s (%s)", _what, _nbuf, \
				   msg, isc_result_totext(result));        \
		}                                                          \
		if (result != ISC_R_SUCCESS)                               \
			goto failure;                                      \
	} while (0)

#define FAILNT(code, name, type, msg)                                         \
	do {                                                                  \
		const char *_what = "failed";                                 \
		result = (code);                                              \
		switch (result) {                                             \
		case DNS_R_NXDOMAIN:                                          \
		case DNS_R_YXDOMAIN:                                          \
		case DNS_R_YXRRSET:                                           \
		case DNS_R_NXRRSET:                                           \
			_what = "unsuccessful";                               \
		}                                                             \
		if (isc_log_wouldlog(dns_lctx, LOGLEVEL_PROTOCOL)) {          \
			char _nbuf[DNS_NAME_FORMATSIZE];                      \
			char _tbuf[DNS_RDATATYPE_FORMATSIZE];                 \
			dns_name_format(name, _nbuf, sizeof(_nbuf));          \
			dns_rdatatype_format(type, _tbuf, sizeof(_tbuf));     \
			update_log(log, zone, LOGLEVEL_PROTOCOL,              \
				   "update %s: %s/%s: %s (%s)", _what, _nbuf, \
				   _tbuf, msg, isc_result_totext(result));    \
		}                                                             \
		if (result != ISC_R_SUCCESS)                                  \
			goto failure;                                         \
	} while (0)

/*%
 * Fail unconditionally and log as a server error.
 * The test against ISC_R_SUCCESS is there to keep the Solaris compiler
 * from complaining about "end-of-loop code not reached".
 */
#define FAILS(code, msg)                                                       \
	do {                                                                   \
		result = (code);                                               \
		update_log(log, zone, LOGLEVEL_PROTOCOL, "error: %s: %s", msg, \
			   isc_result_totext(result));                         \
		if (result != ISC_R_SUCCESS)                                   \
			goto failure;                                          \
	} while (0)

/**************************************************************************/

typedef struct rr rr_t;

struct rr {
	/* dns_name_t name; */
	uint32_t ttl;
	dns_rdata_t rdata;
};

typedef struct update_event update_event_t;

/**************************************************************************/

static void
update_log(dns_update_log_t *callback, dns_zone_t *zone, int level,
	   const char *fmt, ...) ISC_FORMAT_PRINTF(4, 5);

static void
update_log(dns_update_log_t *callback, dns_zone_t *zone, int level,
	   const char *fmt, ...) {
	va_list ap;
	char message[4096];

	if (callback == NULL) {
		return;
	}

	if (!isc_log_wouldlog(dns_lctx, level)) {
		return;
	}

	va_start(ap, fmt);
	vsnprintf(message, sizeof(message), fmt, ap);
	va_end(ap);

	(callback->func)(callback->arg, zone, level, message);
}

/*%
 * Update a single RR in version 'ver' of 'db' and log the
 * update in 'diff'.
 *
 * Ensures:
 * \li	'*tuple' == NULL.  Either the tuple is freed, or its
 *	ownership has been transferred to the diff.
 */
static isc_result_t
do_one_tuple(dns_difftuple_t **tuple, dns_db_t *db, dns_dbversion_t *ver,
	     dns_diff_t *diff) {
	dns_diff_t temp_diff;
	isc_result_t result;

	/*
	 * Create a singleton diff.
	 */
	dns_diff_init(diff->mctx, &temp_diff);
	ISC_LIST_APPEND(temp_diff.tuples, *tuple, link);

	/*
	 * Apply it to the database.
	 */
	result = dns_diff_apply(&temp_diff, db, ver);
	ISC_LIST_UNLINK(temp_diff.tuples, *tuple, link);
	if (result != ISC_R_SUCCESS) {
		dns_difftuple_free(tuple);
		return (result);
	}

	/*
	 * Merge it into the current pending journal entry.
	 */
	dns_diff_appendminimal(diff, tuple);

	/*
	 * Do not clear temp_diff.
	 */
	return (ISC_R_SUCCESS);
}

static isc_result_t
update_one_rr(dns_db_t *db, dns_dbversion_t *ver, dns_diff_t *diff,
	      dns_diffop_t op, dns_name_t *name, dns_ttl_t ttl,
	      dns_rdata_t *rdata) {
	dns_difftuple_t *tuple = NULL;
	isc_result_t result;
	result = dns_difftuple_create(diff->mctx, op, name, ttl, rdata, &tuple);
	if (result != ISC_R_SUCCESS) {
		return (result);
	}
	return (do_one_tuple(&tuple, db, ver, diff));
}

/**************************************************************************/
/*
 * Callback-style iteration over rdatasets and rdatas.
 *
 * foreach_rrset() can be used to iterate over the RRsets
 * of a name and call a callback function with each
 * one.  Similarly, foreach_rr() can be used to iterate
 * over the individual RRs at name, optionally restricted
 * to RRs of a given type.
 *
 * The callback functions are called "actions" and take
 * two arguments: a void pointer for passing arbitrary
 * context information, and a pointer to the current RRset
 * or RR.  By convention, their names end in "_action".
 */

/*
 * XXXRTH  We might want to make this public somewhere in libdns.
 */

/*%
 * Function type for foreach_rrset() iterator actions.
 */
typedef isc_result_t
rrset_func(void *data, dns_rdataset_t *rrset);

/*%
 * Function type for foreach_rr() iterator actions.
 */
typedef isc_result_t
rr_func(void *data, rr_t *rr);

/*%
 * Internal context struct for foreach_node_rr().
 */
typedef struct {
	rr_func *rr_action;
	void *rr_action_data;
} foreach_node_rr_ctx_t;

/*%
 * Internal helper function for foreach_node_rr().
 */
static isc_result_t
foreach_node_rr_action(void *data, dns_rdataset_t *rdataset) {
	isc_result_t result;
	foreach_node_rr_ctx_t *ctx = data;
	for (result = dns_rdataset_first(rdataset); result == ISC_R_SUCCESS;
	     result = dns_rdataset_next(rdataset))
	{
		rr_t rr = { 0, DNS_RDATA_INIT };

		dns_rdataset_current(rdataset, &rr.rdata);
		rr.ttl = rdataset->ttl;
		result = (*ctx->rr_action)(ctx->rr_action_data, &rr);
		if (result != ISC_R_SUCCESS) {
			return (result);
		}
	}
	if (result != ISC_R_NOMORE) {
		return (result);
	}
	return (ISC_R_SUCCESS);
}

/*%
 * For each rdataset of 'name' in 'ver' of 'db', call 'action'
 * with the rdataset and 'action_data' as arguments.  If the name
 * does not exist, do nothing.
 *
 * If 'action' returns an error, abort iteration and return the error.
 */
static isc_result_t
foreach_rrset(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
	      rrset_func *action, void *action_data) {
	isc_result_t result;
	dns_dbnode_t *node;
	dns_rdatasetiter_t *iter;

	node = NULL;
	result = dns_db_findnode(db, name, false, &node);
	if (result == ISC_R_NOTFOUND) {
		return (ISC_R_SUCCESS);
	}
	if (result != ISC_R_SUCCESS) {
		return (result);
	}

	iter = NULL;
	result = dns_db_allrdatasets(db, node, ver, 0, (isc_stdtime_t)0, &iter);
	if (result != ISC_R_SUCCESS) {
		goto cleanup_node;
	}

	for (result = dns_rdatasetiter_first(iter); result == ISC_R_SUCCESS;
	     result = dns_rdatasetiter_next(iter))
	{
		dns_rdataset_t rdataset;

		dns_rdataset_init(&rdataset);
		dns_rdatasetiter_current(iter, &rdataset);

		result = (*action)(action_data, &rdataset);

		dns_rdataset_disassociate(&rdataset);
		if (result != ISC_R_SUCCESS) {
			goto cleanup_iterator;
		}
	}
	if (result == ISC_R_NOMORE) {
		result = ISC_R_SUCCESS;
	}

cleanup_iterator:
	dns_rdatasetiter_destroy(&iter);

cleanup_node:
	dns_db_detachnode(db, &node);

	return (result);
}

/*%
 * For each RR of 'name' in 'ver' of 'db', call 'action'
 * with the RR and 'action_data' as arguments.  If the name
 * does not exist, do nothing.
 *
 * If 'action' returns an error, abort iteration
 * and return the error.
 */
static isc_result_t
foreach_node_rr(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
		rr_func *rr_action, void *rr_action_data) {
	foreach_node_rr_ctx_t ctx;
	ctx.rr_action = rr_action;
	ctx.rr_action_data = rr_action_data;
	return (foreach_rrset(db, ver, name, foreach_node_rr_action, &ctx));
}

/*%
 * For each of the RRs specified by 'db', 'ver', 'name', 'type',
 * (which can be dns_rdatatype_any to match any type), and 'covers', call
 * 'action' with the RR and 'action_data' as arguments. If the name
 * does not exist, or if no RRset of the given type exists at the name,
 * do nothing.
 *
 * If 'action' returns an error, abort iteration and return the error.
 */
static isc_result_t
foreach_rr(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
	   dns_rdatatype_t type, dns_rdatatype_t covers, rr_func *rr_action,
	   void *rr_action_data) {
	isc_result_t result;
	dns_dbnode_t *node;
	dns_rdataset_t rdataset;

	if (type == dns_rdatatype_any) {
		return (foreach_node_rr(db, ver, name, rr_action,
					rr_action_data));
	}

	node = NULL;
	if (type == dns_rdatatype_nsec3 ||
	    (type == dns_rdatatype_rrsig && covers == dns_rdatatype_nsec3))
	{
		result = dns_db_findnsec3node(db, name, false, &node);
	} else {
		result = dns_db_findnode(db, name, false, &node);
	}
	if (result == ISC_R_NOTFOUND) {
		return (ISC_R_SUCCESS);
	}
	if (result != ISC_R_SUCCESS) {
		return (result);
	}

	dns_rdataset_init(&rdataset);
	result = dns_db_findrdataset(db, node, ver, type, covers,
				     (isc_stdtime_t)0, &rdataset, NULL);
	if (result == ISC_R_NOTFOUND) {
		result = ISC_R_SUCCESS;
		goto cleanup_node;
	}
	if (result != ISC_R_SUCCESS) {
		goto cleanup_node;
	}

	for (result = dns_rdataset_first(&rdataset); result == ISC_R_SUCCESS;
	     result = dns_rdataset_next(&rdataset))
	{
		rr_t rr = { 0, DNS_RDATA_INIT };
		dns_rdataset_current(&rdataset, &rr.rdata);
		rr.ttl = rdataset.ttl;
		result = (*rr_action)(rr_action_data, &rr);
		if (result != ISC_R_SUCCESS) {
			goto cleanup_rdataset;
		}
	}
	if (result != ISC_R_NOMORE) {
		goto cleanup_rdataset;
	}
	result = ISC_R_SUCCESS;

cleanup_rdataset:
	dns_rdataset_disassociate(&rdataset);
cleanup_node:
	dns_db_detachnode(db, &node);

	return (result);
}

/**************************************************************************/
/*
 * Various tests on the database contents (for prerequisites, etc).
 */

/*%
 * Function type for predicate functions that compare a database RR 'db_rr'
 * against an update RR 'update_rr'.
 */
typedef bool
rr_predicate(dns_rdata_t *update_rr, dns_rdata_t *db_rr);

/*%
 * Helper function for rrset_exists().
 */
static isc_result_t
rrset_exists_action(void *data, rr_t *rr) {
	UNUSED(data);
	UNUSED(rr);
	return (ISC_R_EXISTS);
}

/*%
 * Utility macro for RR existence checking functions.
 *
 * If the variable 'result' has the value ISC_R_EXISTS or
 * ISC_R_SUCCESS, set *exists to true or false,
 * respectively, and return success.
 *
 * If 'result' has any other value, there was a failure.
 * Return the failure result code and do not set *exists.
 *
 * This would be more readable as "do { if ... } while(0)",
 * but that form generates tons of warnings on Solaris 2.6.
 */
#define RETURN_EXISTENCE_FLAG                                         \
	return ((result == ISC_R_EXISTS)                              \
			? (*exists = true, ISC_R_SUCCESS)             \
			: ((result == ISC_R_SUCCESS)                  \
				   ? (*exists = false, ISC_R_SUCCESS) \
				   : result))

/*%
 * Set '*exists' to true iff an rrset of the given type exists,
 * to false otherwise.
 */
static isc_result_t
rrset_exists(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
	     dns_rdatatype_t type, dns_rdatatype_t covers, bool *exists) {
	isc_result_t result;
	result = foreach_rr(db, ver, name, type, covers, rrset_exists_action,
			    NULL);
	RETURN_EXISTENCE_FLAG;
}

/*%
 * Set '*visible' to true if the RRset exists and is part of the
 * visible zone.  Otherwise '*visible' is set to false unless a
 * error occurs.
 */
static isc_result_t
rrset_visible(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
	      dns_rdatatype_t type, bool *visible) {
	isc_result_t result;
	dns_fixedname_t fixed;

	dns_fixedname_init(&fixed);
	result = dns_db_find(db, name, ver, type, DNS_DBFIND_NOWILD,
			     (isc_stdtime_t)0, NULL, dns_fixedname_name(&fixed),
			     NULL, NULL);
	switch (result) {
	case ISC_R_SUCCESS:
		*visible = true;
		break;
	/*
	 * Glue, obscured, deleted or replaced records.
	 */
	case DNS_R_DELEGATION:
	case DNS_R_DNAME:
	case DNS_R_CNAME:
	case DNS_R_NXDOMAIN:
	case DNS_R_NXRRSET:
	case DNS_R_EMPTYNAME:
	case DNS_R_COVERINGNSEC:
		*visible = false;
		result = ISC_R_SUCCESS;
		break;
	default:
		*visible = false; /* silence false compiler warning */
		break;
	}
	return (result);
}

/*%
 * Context struct and helper function for name_exists().
 */

static isc_result_t
name_exists_action(void *data, dns_rdataset_t *rrset) {
	UNUSED(data);
	UNUSED(rrset);
	return (ISC_R_EXISTS);
}

/*%
 * Set '*exists' to true iff the given name exists, to false otherwise.
 */
static isc_result_t
name_exists(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
	    bool *exists) {
	isc_result_t result;
	result = foreach_rrset(db, ver, name, name_exists_action, NULL);
	RETURN_EXISTENCE_FLAG;
}

/**************************************************************************/
/*
 * Checking of "RRset exists (value dependent)" prerequisites.
 *
 * In the RFC2136 section 3.2.5, this is the pseudocode involving
 * a variable called "temp", a mapping of <name, type> tuples to rrsets.
 *
 * Here, we represent the "temp" data structure as (non-minimal) "dns_diff_t"
 * where each tuple has op==DNS_DIFFOP_EXISTS.
 */

/*%
 * A comparison function defining the sorting order for the entries
 * in the "temp" data structure.  The major sort key is the owner name,
 * followed by the type and rdata.
 */
static int
temp_order(const void *av, const void *bv) {
	dns_difftuple_t const *const *ap = av;
	dns_difftuple_t const *const *bp = bv;
	dns_difftuple_t const *a = *ap;
	dns_difftuple_t const *b = *bp;
	int r;
	r = dns_name_compare(&a->name, &b->name);
	if (r != 0) {
		return (r);
	}
	r = (b->rdata.type - a->rdata.type);
	if (r != 0) {
		return (r);
	}
	r = dns_rdata_casecompare(&a->rdata, &b->rdata);
	return (r);
}

/**************************************************************************/
/*
 * Conditional deletion of RRs.
 */

/*%
 * Context structure for delete_if().
 */

typedef struct {
	rr_predicate *predicate;
	dns_db_t *db;
	dns_dbversion_t *ver;
	dns_diff_t *diff;
	dns_name_t *name;
	dns_rdata_t *update_rr;
} conditional_delete_ctx_t;

/*%
 * Predicate functions for delete_if().
 */

/*%
 * Return true always.
 */
static bool
true_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
	UNUSED(update_rr);
	UNUSED(db_rr);
	return (true);
}

/*%
 * Return true if the record is a RRSIG.
 */
static bool
rrsig_p(dns_rdata_t *update_rr, dns_rdata_t *db_rr) {
	UNUSED(update_rr);
	return ((db_rr->type == dns_rdatatype_rrsig) ? true : false);
}

/*%
 * Internal helper function for delete_if().
 */
static isc_result_t
delete_if_action(void *data, rr_t *rr) {
	conditional_delete_ctx_t *ctx = data;
	if ((*ctx->predicate)(ctx->update_rr, &rr->rdata)) {
		isc_result_t result;
		result = update_one_rr(ctx->db, ctx->ver, ctx->diff,
				       DNS_DIFFOP_DEL, ctx->name, rr->ttl,
				       &rr->rdata);
		return (result);
	} else {
		return (ISC_R_SUCCESS);
	}
}

/*%
 * Conditionally delete RRs.  Apply 'predicate' to the RRs
 * specified by 'db', 'ver', 'name', and 'type' (which can
 * be dns_rdatatype_any to match any type).  Delete those
 * RRs for which the predicate returns true, and log the
 * deletions in 'diff'.
 */
static isc_result_t
delete_if(rr_predicate *predicate, dns_db_t *db, dns_dbversion_t *ver,
	  dns_name_t *name, dns_rdatatype_t type, dns_rdatatype_t covers,
	  dns_rdata_t *update_rr, dns_diff_t *diff) {
	conditional_delete_ctx_t ctx;
	ctx.predicate = predicate;
	ctx.db = db;
	ctx.ver = ver;
	ctx.diff = diff;
	ctx.name = name;
	ctx.update_rr = update_rr;
	return (foreach_rr(db, ver, name, type, covers, delete_if_action,
			   &ctx));
}

/**************************************************************************/
/*
 * Incremental updating of NSECs and RRSIGs.
 */

/*%
 * We abuse the dns_diff_t type to represent a set of domain names
 * affected by the update.
 */
static isc_result_t
namelist_append_name(dns_diff_t *list, dns_name_t *name) {
	isc_result_t result;
	dns_difftuple_t *tuple = NULL;
	static dns_rdata_t dummy_rdata = DNS_RDATA_INIT;

	CHECK(dns_difftuple_create(list->mctx, DNS_DIFFOP_EXISTS, name, 0,
				   &dummy_rdata, &tuple));
	dns_diff_append(list, &tuple);
failure:
	return (result);
}

static isc_result_t
namelist_append_subdomain(dns_db_t *db, dns_name_t *name,
			  dns_diff_t *affected) {
	isc_result_t result;
	dns_fixedname_t fixedname;
	dns_name_t *child;
	dns_dbiterator_t *dbit = NULL;

	child = dns_fixedname_initname(&fixedname);

	CHECK(dns_db_createiterator(db, DNS_DB_NONSEC3, &dbit));

	for (result = dns_dbiterator_seek(dbit, name); result == ISC_R_SUCCESS;
	     result = dns_dbiterator_next(dbit))
	{
		dns_dbnode_t *node = NULL;
		CHECK(dns_dbiterator_current(dbit, &node, child));
		dns_db_detachnode(db, &node);
		if (!dns_name_issubdomain(child, name)) {
			break;
		}
		CHECK(namelist_append_name(affected, child));
	}
	if (result == ISC_R_NOMORE) {
		result = ISC_R_SUCCESS;
	}
failure:
	if (dbit != NULL) {
		dns_dbiterator_destroy(&dbit);
	}
	return (result);
}

/*%
 * Helper function for non_nsec_rrset_exists().
 */
static isc_result_t
is_non_nsec_action(void *data, dns_rdataset_t *rrset) {
	UNUSED(data);
	if (!(rrset->type == dns_rdatatype_nsec ||
	      rrset->type == dns_rdatatype_nsec3 ||
	      (rrset->type == dns_rdatatype_rrsig &&
	       (rrset->covers == dns_rdatatype_nsec ||
		rrset->covers == dns_rdatatype_nsec3))))
	{
		return (ISC_R_EXISTS);
	}
	return (ISC_R_SUCCESS);
}

/*%
 * Check whether there is an rrset other than a NSEC or RRSIG NSEC,
 * i.e., anything that justifies the continued existence of a name
 * after a secure update.
 *
 * If such an rrset exists, set '*exists' to true.
 * Otherwise, set it to false.
 */
static isc_result_t
non_nsec_rrset_exists(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
		      bool *exists) {
	isc_result_t result;
	result = foreach_rrset(db, ver, name, is_non_nsec_action, NULL);
	RETURN_EXISTENCE_FLAG;
}

/*%
 * A comparison function for sorting dns_diff_t:s by name.
 */
static int
name_order(const void *av, const void *bv) {
	dns_difftuple_t const *const *ap = av;
	dns_difftuple_t const *const *bp = bv;
	dns_difftuple_t const *a = *ap;
	dns_difftuple_t const *b = *bp;
	return (dns_name_compare(&a->name, &b->name));
}

static isc_result_t
uniqify_name_list(dns_diff_t *list) {
	isc_result_t result;
	dns_difftuple_t *p, *q;

	CHECK(dns_diff_sort(list, name_order));

	p = ISC_LIST_HEAD(list->tuples);
	while (p != NULL) {
		do {
			q = ISC_LIST_NEXT(p, link);
			if (q == NULL || !dns_name_equal(&p->name, &q->name)) {
				break;
			}
			ISC_LIST_UNLINK(list->tuples, q, link);
			dns_difftuple_free(&q);
		} while (1);
		p = ISC_LIST_NEXT(p, link);
	}
failure:
	return (result);
}

static isc_result_t
is_active(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name, bool *flag,
	  bool *cut, bool *unsecure) {
	isc_result_t result;
	dns_fixedname_t foundname;
	dns_fixedname_init(&foundname);
	result = dns_db_find(db, name, ver, dns_rdatatype_any,
			     DNS_DBFIND_GLUEOK | DNS_DBFIND_NOWILD,
			     (isc_stdtime_t)0, NULL,
			     dns_fixedname_name(&foundname), NULL, NULL);
	if (result == ISC_R_SUCCESS || result == DNS_R_EMPTYNAME) {
		*flag = true;
		*cut = false;
		if (unsecure != NULL) {
			*unsecure = false;
		}
		return (ISC_R_SUCCESS);
	} else if (result == DNS_R_ZONECUT) {
		*flag = true;
		*cut = true;
		if (unsecure != NULL) {
			/*
			 * We are at the zonecut.  Check to see if there
			 * is a DS RRset.
			 */
			if (dns_db_find(db, name, ver, dns_rdatatype_ds, 0,
					(isc_stdtime_t)0, NULL,
					dns_fixedname_name(&foundname), NULL,
					NULL) == DNS_R_NXRRSET)
			{
				*unsecure = true;
			} else {
				*unsecure = false;
			}
		}
		return (ISC_R_SUCCESS);
	} else if (result == DNS_R_GLUE || result == DNS_R_DNAME ||
		   result == DNS_R_DELEGATION || result == DNS_R_NXDOMAIN)
	{
		*flag = false;
		*cut = false;
		if (unsecure != NULL) {
			*unsecure = false;
		}
		return (ISC_R_SUCCESS);
	} else {
		/*
		 * Silence compiler.
		 */
		*flag = false;
		*cut = false;
		if (unsecure != NULL) {
			*unsecure = false;
		}
		return (result);
	}
}

/*%
 * Find the next/previous name that has a NSEC record.
 * In other words, skip empty database nodes and names that
 * have had their NSECs removed because they are obscured by
 * a zone cut.
 */
static isc_result_t
next_active(dns_update_log_t *log, dns_zone_t *zone, dns_db_t *db,
	    dns_dbversion_t *ver, dns_name_t *oldname, dns_name_t *newname,
	    bool forward) {
	isc_result_t result;
	dns_dbiterator_t *dbit = NULL;
	bool has_nsec = false;
	unsigned int wraps = 0;
	bool secure = dns_db_issecure(db);

	CHECK(dns_db_createiterator(db, 0, &dbit));

	CHECK(dns_dbiterator_seek(dbit, oldname));
	do {
		dns_dbnode_t *node = NULL;

		if (forward) {
			result = dns_dbiterator_next(dbit);
		} else {
			result = dns_dbiterator_prev(dbit);
		}
		if (result == ISC_R_NOMORE) {
			/*
			 * Wrap around.
			 */
			if (forward) {
				CHECK(dns_dbiterator_first(dbit));
			} else {
				CHECK(dns_dbiterator_last(dbit));
			}
			wraps++;
			if (wraps == 2) {
				update_log(log, zone, ISC_LOG_ERROR,
					   "secure zone with no NSECs");
				result = DNS_R_BADZONE;
				goto failure;
			}
		}
		CHECK(dns_dbiterator_current(dbit, &node, newname));
		dns_db_detachnode(db, &node);

		/*
		 * The iterator may hold the tree lock, and
		 * rrset_exists() calls dns_db_findnode() which
		 * may try to reacquire it.  To avoid deadlock
		 * we must pause the iterator first.
		 */
		CHECK(dns_dbiterator_pause(dbit));
		if (secure) {
			CHECK(rrset_exists(db, ver, newname, dns_rdatatype_nsec,
					   0, &has_nsec));
		} else {
			dns_fixedname_t ffound;
			dns_name_t *found;
			found = dns_fixedname_initname(&ffound);
			result = dns_db_find(
				db, newname, ver, dns_rdatatype_soa,
				DNS_DBFIND_NOWILD, 0, NULL, found, NULL, NULL);
			if (result == ISC_R_SUCCESS ||
			    result == DNS_R_EMPTYNAME ||
			    result == DNS_R_NXRRSET || result == DNS_R_CNAME ||
			    (result == DNS_R_DELEGATION &&
			     dns_name_equal(newname, found)))
			{
				has_nsec = true;
				result = ISC_R_SUCCESS;
			} else if (result != DNS_R_NXDOMAIN) {
				break;
			}
		}
	} while (!has_nsec);
failure:
	if (dbit != NULL) {
		dns_dbiterator_destroy(&dbit);
	}

	return (result);
}

/*%
 * Add a NSEC record for "name", recording the change in "diff".
 * The existing NSEC is removed.
 */
static isc_result_t
add_nsec(dns_update_log_t *log, dns_zone_t *zone, dns_db_t *db,
	 dns_dbversion_t *ver, dns_name_t *name, dns_ttl_t nsecttl,
	 dns_diff_t *diff) {
	isc_result_t result;
	dns_dbnode_t *node = NULL;
	unsigned char buffer[DNS_NSEC_BUFFERSIZE];
	dns_rdata_t rdata = DNS_RDATA_INIT;
	dns_difftuple_t *tuple = NULL;
	dns_fixedname_t fixedname;
	dns_name_t *target;

	target = dns_fixedname_initname(&fixedname);

	/*
	 * Find the successor name, aka NSEC target.
	 */
	CHECK(next_active(log, zone, db, ver, name, target, true));

	/*
	 * Create the NSEC RDATA.
	 */
	CHECK(dns_db_findnode(db, name, false, &node));
	dns_rdata_init(&rdata);
	CHECK(dns_nsec_buildrdata(db, ver, node, target, buffer, &rdata));
	dns_db_detachnode(db, &node);

	/*
	 * Delete the old NSEC and record the change.
	 */
	CHECK(delete_if(true_p, db, ver, name, dns_rdatatype_nsec, 0, NULL,
			diff));
	/*
	 * Add the new NSEC and record the change.
	 */
	CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD, name, nsecttl,
				   &rdata, &tuple));
	CHECK(do_one_tuple(&tuple, db, ver, diff));
	INSIST(tuple == NULL);

failure:
	if (node != NULL) {
		dns_db_detachnode(db, &node);
	}
	return (result);
}

/*%
 * Add a placeholder NSEC record for "name", recording the change in "diff".
 */
static isc_result_t
add_placeholder_nsec(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
		     dns_diff_t *diff) {
	isc_result_t result;
	dns_difftuple_t *tuple = NULL;
	isc_region_t r;
	unsigned char data[1] = { 0 }; /* The root domain, no bits. */
	dns_rdata_t rdata = DNS_RDATA_INIT;

	r.base = data;
	r.length = sizeof(data);
	dns_rdata_fromregion(&rdata, dns_db_class(db), dns_rdatatype_nsec, &r);
	CHECK(dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD, name, 0, &rdata,
				   &tuple));
	CHECK(do_one_tuple(&tuple, db, ver, diff));
failure:
	return (result);
}

static isc_result_t
find_zone_keys(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *ver,
	       isc_mem_t *mctx, unsigned int maxkeys, dst_key_t **keys,
	       unsigned int *nkeys) {
	isc_result_t result;
	isc_stdtime_t now;
	dns_dbnode_t *node = NULL;
	const char *directory = dns_zone_getkeydirectory(zone);

	CHECK(dns_db_findnode(db, dns_db_origin(db), false, &node));
	isc_stdtime_get(&now);

	dns_zone_lock_keyfiles(zone);
	result = dns_dnssec_findzonekeys(db, ver, node, dns_db_origin(db),
					 directory, now, mctx, maxkeys, keys,
					 nkeys);
	dns_zone_unlock_keyfiles(zone);

failure:
	if (node != NULL) {
		dns_db_detachnode(db, &node);
	}
	return (result);
}

/*%
 * Add RRSIG records for an RRset, recording the change in "diff".
 */
static isc_result_t
add_sigs(dns_update_log_t *log, dns_zone_t *zone, dns_db_t *db,
	 dns_dbversion_t *ver, dns_name_t *name, dns_rdatatype_t type,
	 dns_diff_t *diff, dst_key_t **keys, unsigned int nkeys,
	 isc_stdtime_t inception, isc_stdtime_t expire, bool check_ksk,
	 bool keyset_kskonly) {
	isc_result_t result;
	dns_dbnode_t *node = NULL;
	dns_kasp_t *kasp = dns_zone_getkasp(zone);
	dns_rdataset_t rdataset;
	dns_rdata_t sig_rdata = DNS_RDATA_INIT;
	dns_stats_t *dnssecsignstats = dns_zone_getdnssecsignstats(zone);
	isc_buffer_t buffer;
	unsigned char data[1024]; /* XXX */
	unsigned int i, j;
	bool added_sig = false;
	bool use_kasp = false;
	isc_mem_t *mctx = diff->mctx;

	if (kasp != NULL) {
		check_ksk = false;
		keyset_kskonly = true;
		use_kasp = true;
	}

	dns_rdataset_init(&rdataset);
	isc_buffer_init(&buffer, data, sizeof(data));

	/* Get the rdataset to sign. */
	if (type == dns_rdatatype_nsec3) {
		CHECK(dns_db_findnsec3node(db, name, false, &node));
	} else {
		CHECK(dns_db_findnode(db, name, false, &node));
	}
	CHECK(dns_db_findrdataset(db, node, ver, type, 0, (isc_stdtime_t)0,
				  &rdataset, NULL));
	dns_db_detachnode(db, &node);

#define REVOKE(x) ((dst_key_flags(x) & DNS_KEYFLAG_REVOKE) != 0)
#define KSK(x)	  ((dst_key_flags(x) & DNS_KEYFLAG_KSK) != 0)
#define ID(x)	  dst_key_id(x)
#define ALG(x)	  dst_key_alg(x)

	/*
	 * If we are honoring KSK flags then we need to check that we
	 * have both KSK and non-KSK keys that are not revoked per
	 * algorithm.
	 */
	for (i = 0; i < nkeys; i++) {
		bool both = false;

		/* Don't add signatures for offline or inactive keys */
		if (!dst_key_isprivate(keys[i])) {
			continue;
		}
		if (dst_key_inactive(keys[i])) {
			continue;
		}

		if (check_ksk && !REVOKE(keys[i])) {
			bool have_ksk, have_nonksk;
			if (KSK(keys[i])) {
				have_ksk = true;
				have_nonksk = false;
			} else {
				have_ksk = false;
				have_nonksk = true;
			}
			for (j = 0; j < nkeys; j++) {
				if (j == i || ALG(keys[i]) != ALG(keys[j])) {
					continue;
				}

				/* Don't consider inactive keys, however
				 * the KSK may be temporary offline, so do
				 * consider KSKs which private key files are
				 * unavailable.
				 */
				if (dst_key_inactive(keys[j])) {
					continue;
				}

				if (REVOKE(keys[j])) {
					continue;
				}
				if (KSK(keys[j])) {
					have_ksk = true;
				} else if (dst_key_isprivate(keys[j])) {
					have_nonksk = true;
				}
				both = have_ksk && have_nonksk;
				if (both) {
					break;
				}
			}
		}

		if (use_kasp) {
			/*
			 * A dnssec-policy is found. Check what RRsets this
			 * key should sign.
			 */
			isc_stdtime_t when;
			isc_result_t kresult;
			bool ksk = false;
			bool zsk = false;

			kresult = dst_key_getbool(keys[i], DST_BOOL_KSK, &ksk);
			if (kresult != ISC_R_SUCCESS) {
				if (KSK(keys[i])) {
					ksk = true;
				}
			}
			kresult = dst_key_getbool(keys[i], DST_BOOL_ZSK, &zsk);
			if (kresult != ISC_R_SUCCESS) {
				if (!KSK(keys[i])) {
					zsk = true;
				}
			}

			if (type == dns_rdatatype_dnskey ||
			    type == dns_rdatatype_cdnskey ||
			    type == dns_rdatatype_cds)
			{
				/*
				 * DNSKEY RRset is signed with KSK.
				 * CDS and CDNSKEY RRsets too (RFC 7344, 4.1).
				 */
				if (!ksk) {
					continue;
				}
			} else if (!zsk) {
				/*
				 * Other RRsets are signed with ZSK.
				 */
				continue;
			} else if (zsk &&
				   !dst_key_is_signing(keys[i], DST_BOOL_ZSK,
						       inception, &when))
			{
				/*
				 * This key is not active for zone-signing.
				 */
				continue;
			}

			/*
			 * If this key is revoked, it may only sign the
			 * DNSKEY RRset.
			 */
			if (REVOKE(keys[i]) && type != dns_rdatatype_dnskey) {
				continue;
			}
		} else if (both) {
			/*
			 * CDS and CDNSKEY are signed with KSK (RFC 7344, 4.1).
			 */
			if (type == dns_rdatatype_dnskey ||
			    type == dns_rdatatype_cdnskey ||
			    type == dns_rdatatype_cds)
			{
				if (!KSK(keys[i]) && keyset_kskonly) {
					continue;
				}
			} else if (KSK(keys[i])) {
				continue;
			}
		} else if (REVOKE(keys[i]) && type != dns_rdatatype_dnskey) {
			continue;
		}

		/* Calculate the signature, creating a RRSIG RDATA. */
		CHECK(dns_dnssec_sign(name, &rdataset, keys[i], &inception,
				      &expire, mctx, &buffer, &sig_rdata));

		/* Update the database and journal with the RRSIG. */
		/* XXX inefficient - will cause dataset merging */
		CHECK(update_one_rr(db, ver, diff, DNS_DIFFOP_ADDRESIGN, name,
				    rdataset.ttl, &sig_rdata));
		dns_rdata_reset(&sig_rdata);
		isc_buffer_init(&buffer, data, sizeof(data));
		added_sig = true;
		/* Update DNSSEC sign statistics. */
		if (dnssecsignstats != NULL) {
			dns_dnssecsignstats_increment(dnssecsignstats,
						      ID(keys[i]),
						      (uint8_t)ALG(keys[i]),
						      dns_dnssecsignstats_sign);
		}
	}
	if (!added_sig) {
		update_log(log, zone, ISC_LOG_ERROR,
			   "found no active private keys, "
			   "unable to generate any signatures");
		result = ISC_R_NOTFOUND;
	}

failure:
	if (dns_rdataset_isassociated(&rdataset)) {
		dns_rdataset_disassociate(&rdataset);
	}
	if (node != NULL) {
		dns_db_detachnode(db, &node);
	}
	return (result);
}

/*
 * Delete expired RRsigs and any RRsigs we are about to re-sign.
 * See also zone.c:del_sigs().
 */
static isc_result_t
del_keysigs(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
	    dns_diff_t *diff, dst_key_t **keys, unsigned int nkeys) {
	isc_result_t result;
	dns_dbnode_t *node = NULL;
	dns_rdataset_t rdataset;
	dns_rdata_t rdata = DNS_RDATA_INIT;
	unsigned int i;
	dns_rdata_rrsig_t rrsig;
	bool found;

	dns_rdataset_init(&rdataset);

	result = dns_db_findnode(db, name, false, &node);
	if (result == ISC_R_NOTFOUND) {
		return (ISC_R_SUCCESS);
	}
	if (result != ISC_R_SUCCESS) {
		goto failure;
	}
	result = dns_db_findrdataset(db, node, ver, dns_rdatatype_rrsig,
				     dns_rdatatype_dnskey, (isc_stdtime_t)0,
				     &rdataset, NULL);
	dns_db_detachnode(db, &node);

	if (result == ISC_R_NOTFOUND) {
		return (ISC_R_SUCCESS);
	}
	if (result != ISC_R_SUCCESS) {
		goto failure;
	}

	for (result = dns_rdataset_first(&rdataset); result == ISC_R_SUCCESS;
	     result = dns_rdataset_next(&rdataset))
	{
		dns_rdataset_current(&rdataset, &rdata);
		result = dns_rdata_tostruct(&rdata, &rrsig, NULL);
		RUNTIME_CHECK(result == ISC_R_SUCCESS);
		found = false;
		for (i = 0; i < nkeys; i++) {
			if (rrsig.keyid == dst_key_id(keys[i])) {
				found = true;
				if (!dst_key_isprivate(keys[i]) &&
				    !dst_key_inactive(keys[i]))
				{
					/*
					 * The re-signing code in zone.c
					 * will mark this as offline.
					 * Just skip the record for now.
					 */
					break;
				}
				result = update_one_rr(db, ver, diff,
						       DNS_DIFFOP_DEL, name,
						       rdataset.ttl, &rdata);
				break;
			}
		}
		/*
		 * If there is not a matching DNSKEY then delete the RRSIG.
		 */
		if (!found) {
			result = update_one_rr(db, ver, diff, DNS_DIFFOP_DEL,
					       name, rdataset.ttl, &rdata);
		}
		dns_rdata_reset(&rdata);
		if (result != ISC_R_SUCCESS) {
			break;
		}
	}
	dns_rdataset_disassociate(&rdataset);
	if (result == ISC_R_NOMORE) {
		result = ISC_R_SUCCESS;
	}
failure:
	if (node != NULL) {
		dns_db_detachnode(db, &node);
	}
	return (result);
}

static isc_result_t
add_exposed_sigs(dns_update_log_t *log, dns_zone_t *zone, dns_db_t *db,
		 dns_dbversion_t *ver, dns_name_t *name, bool cut,
		 dns_diff_t *diff, dst_key_t **keys, unsigned int nkeys,
		 isc_stdtime_t inception, isc_stdtime_t expire, bool check_ksk,
		 bool keyset_kskonly, unsigned int *sigs) {
	isc_result_t result;
	dns_dbnode_t *node;
	dns_rdatasetiter_t *iter;

	node = NULL;
	result = dns_db_findnode(db, name, false, &node);
	if (result == ISC_R_NOTFOUND) {
		return (ISC_R_SUCCESS);
	}
	if (result != ISC_R_SUCCESS) {
		return (result);
	}

	iter = NULL;
	result = dns_db_allrdatasets(db, node, ver, 0, (isc_stdtime_t)0, &iter);
	if (result != ISC_R_SUCCESS) {
		goto cleanup_node;
	}

	for (result = dns_rdatasetiter_first(iter); result == ISC_R_SUCCESS;
	     result = dns_rdatasetiter_next(iter))
	{
		dns_rdataset_t rdataset;
		dns_rdatatype_t type;
		bool flag;

		dns_rdataset_init(&rdataset);
		dns_rdatasetiter_current(iter, &rdataset);
		type = rdataset.type;
		dns_rdataset_disassociate(&rdataset);

		/*
		 * We don't need to sign unsigned NSEC records at the cut
		 * as they are handled elsewhere.
		 */
		if ((type == dns_rdatatype_rrsig) ||
		    (cut && type != dns_rdatatype_ds))
		{
			continue;
		}
		result = rrset_exists(db, ver, name, dns_rdatatype_rrsig, type,
				      &flag);
		if (result != ISC_R_SUCCESS) {
			goto cleanup_iterator;
		}
		if (flag) {
			continue;
		}
		result = add_sigs(log, zone, db, ver, name, type, diff, keys,
				  nkeys, inception, expire, check_ksk,
				  keyset_kskonly);
		if (result != ISC_R_SUCCESS) {
			goto cleanup_iterator;
		}
		(*sigs)++;
	}
	if (result == ISC_R_NOMORE) {
		result = ISC_R_SUCCESS;
	}

cleanup_iterator:
	dns_rdatasetiter_destroy(&iter);

cleanup_node:
	dns_db_detachnode(db, &node);

	return (result);
}

/*%
 * Update RRSIG, NSEC and NSEC3 records affected by an update.  The original
 * update, including the SOA serial update but excluding the RRSIG & NSEC
 * changes, is in "diff" and has already been applied to "newver" of "db".
 * The database version prior to the update is "oldver".
 *
 * The necessary RRSIG, NSEC and NSEC3 changes will be applied to "newver"
 * and added (as a minimal diff) to "diff".
 *
 * The RRSIGs generated will be valid for 'sigvalidityinterval' seconds.
 */
isc_result_t
dns_update_signatures(dns_update_log_t *log, dns_zone_t *zone, dns_db_t *db,
		      dns_dbversion_t *oldver, dns_dbversion_t *newver,
		      dns_diff_t *diff, uint32_t sigvalidityinterval) {
	return (dns_update_signaturesinc(log, zone, db, oldver, newver, diff,
					 sigvalidityinterval, NULL));
}

struct dns_update_state {
	unsigned int magic;
	dns_diff_t diffnames;
	dns_diff_t affected;
	dns_diff_t sig_diff;
	dns_diff_t nsec_diff;
	dns_diff_t nsec_mindiff;
	dns_diff_t work;
	dst_key_t *zone_keys[DNS_MAXZONEKEYS];
	unsigned int nkeys;
	isc_stdtime_t inception, expire, soaexpire, keyexpire;
	dns_ttl_t nsecttl;
	bool check_ksk, keyset_kskonly, build_nsec3;
	enum {
		sign_updates,
		remove_orphaned,
		build_chain,
		process_nsec,
		sign_nsec,
		update_nsec3,
		process_nsec3,
		sign_nsec3
	} state;
};

static uint32_t
dns__jitter_expire(dns_zone_t *zone, uint32_t sigvalidityinterval) {
	/* Spread out signatures over time */
	if (sigvalidityinterval >= 3600U) {
		uint32_t expiryinterval =
			dns_zone_getsigresigninginterval(zone);

		if (sigvalidityinterval < 7200U) {
			expiryinterval = 1200;
		} else if (expiryinterval > sigvalidityinterval) {
			expiryinterval = sigvalidityinterval;
		} else {
			expiryinterval = sigvalidityinterval - expiryinterval;
		}
		uint32_t jitter = isc_random_uniform(expiryinterval);
		sigvalidityinterval -= jitter;
	}
	return (sigvalidityinterval);
}

isc_result_t
dns_update_signaturesinc(dns_update_log_t *log, dns_zone_t *zone, dns_db_t *db,
			 dns_dbversion_t *oldver, dns_dbversion_t *newver,
			 dns_diff_t *diff, uint32_t sigvalidityinterval,
			 dns_update_state_t **statep) {
	isc_result_t result = ISC_R_SUCCESS;
	dns_update_state_t mystate, *state;

	dns_difftuple_t *t, *next;
	bool flag, build_nsec;
	unsigned int i;
	isc_stdtime_t now;
	dns_rdata_soa_t soa;
	dns_rdata_t rdata = DNS_RDATA_INIT;
	dns_rdataset_t rdataset;
	dns_dbnode_t *node = NULL;
	bool unsecure;
	bool cut;
	dns_rdatatype_t privatetype = dns_zone_getprivatetype(zone);
	unsigned int sigs = 0;
	unsigned int maxsigs = dns_zone_getsignatures(zone);

	if (statep == NULL || *statep == NULL) {
		if (statep == NULL) {
			state = &mystate;
		} else {
			state = isc_mem_get(diff->mctx, sizeof(*state));
		}

		dns_diff_init(diff->mctx, &state->diffnames);
		dns_diff_init(diff->mctx, &state->affected);
		dns_diff_init(diff->mctx, &state->sig_diff);
		dns_diff_init(diff->mctx, &state->nsec_diff);
		dns_diff_init(diff->mctx, &state->nsec_mindiff);
		dns_diff_init(diff->mctx, &state->work);
		state->nkeys = 0;
		state->build_nsec3 = false;

		result = find_zone_keys(zone, db, newver, diff->mctx,
					DNS_MAXZONEKEYS, state->zone_keys,
					&state->nkeys);
		if (result != ISC_R_SUCCESS) {
			update_log(log, zone, ISC_LOG_ERROR,
				   "could not get zone keys for secure "
				   "dynamic update");
			goto failure;
		}

		isc_stdtime_get(&now);
		state->inception = now - 3600; /* Allow for some clock skew. */
		state->expire = now +
				dns__jitter_expire(zone, sigvalidityinterval);
		state->soaexpire = now + sigvalidityinterval;
		state->keyexpire = dns_zone_getkeyvalidityinterval(zone);
		if (state->keyexpire == 0) {
			state->keyexpire = state->expire;
		} else {
			state->keyexpire += now;
		}

		/*
		 * Do we look at the KSK flag on the DNSKEY to determining which
		 * keys sign which RRsets?  First check the zone option then
		 * check the keys flags to make sure at least one has a ksk set
		 * and one doesn't.
		 */
		state->check_ksk = ((dns_zone_getoptions(zone) &
				     DNS_ZONEOPT_UPDATECHECKKSK) != 0);
		state->keyset_kskonly = ((dns_zone_getoptions(zone) &
					  DNS_ZONEOPT_DNSKEYKSKONLY) != 0);

		/*
		 * Calculate the NSEC/NSEC3 TTL as a minimum of the SOA TTL and
		 * MINIMUM field.
		 */
		CHECK(dns_db_findnode(db, dns_db_origin(db), false, &node));
		dns_rdataset_init(&rdataset);
		CHECK(dns_db_findrdataset(db, node, newver, dns_rdatatype_soa,
					  0, (isc_stdtime_t)0, &rdataset,
					  NULL));
		CHECK(dns_rdataset_first(&rdataset));
		dns_rdataset_current(&rdataset, &rdata);
		CHECK(dns_rdata_tostruct(&rdata, &soa, NULL));
		state->nsecttl = ISC_MIN(rdataset.ttl, soa.minimum);
		dns_rdataset_disassociate(&rdataset);
		dns_db_detachnode(db, &node);

		/*
		 * Find all RRsets directly affected by the update, and
		 * update their RRSIGs.  Also build a list of names affected
		 * by the update in "diffnames".
		 */
		CHECK(dns_diff_sort(diff, temp_order));
		state->state = sign_updates;
		state->magic = STATE_MAGIC;
		if (statep != NULL) {
			*statep = state;
		}
	} else {
		REQUIRE(DNS_STATE_VALID(*statep));
		state = *statep;
	}

next_state:
	switch (state->state) {
	case sign_updates:
		t = ISC_LIST_HEAD(diff->tuples);
		while (t != NULL) {
			dns_name_t *name = &t->name;
			/*
			 * Now "name" is a new, unique name affected by the
			 * update.
			 */

			CHECK(namelist_append_name(&state->diffnames, name));

			while (t != NULL && dns_name_equal(&t->name, name)) {
				dns_rdatatype_t type;
				type = t->rdata.type;

				/*
				 * Now "name" and "type" denote a new unique
				 * RRset affected by the update.
				 */

				/* Don't sign RRSIGs. */
				if (type == dns_rdatatype_rrsig) {
					goto skip;
				}

				/*
				 * Delete all old RRSIGs covering this type,
				 * since they are all invalid when the signed
				 * RRset has changed.  We may not be able to
				 * recreate all of them - tough.
				 * Special case changes to the zone's DNSKEY
				 * records to support offline KSKs.
				 */
				if (type == dns_rdatatype_dnskey) {
					del_keysigs(db, newver, name,
						    &state->sig_diff,
						    state->zone_keys,
						    state->nkeys);
				} else {
					CHECK(delete_if(
						true_p, db, newver, name,
						dns_rdatatype_rrsig, type, NULL,
						&state->sig_diff));
				}

				/*
				 * If this RRset is still visible after the
				 * update, add a new signature for it.
				 */
				CHECK(rrset_visible(db, newver, name, type,
						    &flag));
				if (flag) {
					isc_stdtime_t exp;
					if (type == dns_rdatatype_dnskey ||
					    type == dns_rdatatype_cdnskey ||
					    type == dns_rdatatype_cds)
					{
						exp = state->keyexpire;
					} else if (type == dns_rdatatype_soa) {
						exp = state->soaexpire;
					} else {
						exp = state->expire;
					}

					CHECK(add_sigs(
						log, zone, db, newver, name,
						type, &state->sig_diff,
						state->zone_keys, state->nkeys,
						state->inception, exp,
						state->check_ksk,
						state->keyset_kskonly));
					sigs++;
				}
			skip:
				/* Skip any other updates to the same RRset. */
				while (t != NULL &&
				       dns_name_equal(&t->name, name) &&
				       t->rdata.type == type)
				{
					next = ISC_LIST_NEXT(t, link);
					ISC_LIST_UNLINK(diff->tuples, t, link);
					ISC_LIST_APPEND(state->work.tuples, t,
							link);
					t = next;
				}
			}
			if (state != &mystate && sigs > maxsigs) {
				return (DNS_R_CONTINUE);
			}
		}
		ISC_LIST_APPENDLIST(diff->tuples, state->work.tuples, link);

		update_log(log, zone, ISC_LOG_DEBUG(3),
			   "updated data signatures");
		FALLTHROUGH;
	case remove_orphaned:
		state->state = remove_orphaned;

		/* Remove orphaned NSECs and RRSIG NSECs. */
		for (t = ISC_LIST_HEAD(state->diffnames.tuples); t != NULL;
		     t = ISC_LIST_NEXT(t, link))
		{
			CHECK(non_nsec_rrset_exists(db, newver, &t->name,
						    &flag));
			if (!flag) {
				CHECK(delete_if(true_p, db, newver, &t->name,
						dns_rdatatype_any, 0, NULL,
						&state->sig_diff));
			}
		}
		update_log(log, zone, ISC_LOG_DEBUG(3),
			   "removed any orphaned NSEC records");

		/*
		 * See if we need to build NSEC or NSEC3 chains.
		 */
		CHECK(dns_private_chains(db, newver, privatetype, &build_nsec,
					 &state->build_nsec3));
		if (!build_nsec) {
			state->state = update_nsec3;
			goto next_state;
		}

		update_log(log, zone, ISC_LOG_DEBUG(3),
			   "rebuilding NSEC chain");

		FALLTHROUGH;
	case build_chain:
		state->state = build_chain;
		/*
		 * When a name is created or deleted, its predecessor needs to
		 * have its NSEC updated.
		 */
		for (t = ISC_LIST_HEAD(state->diffnames.tuples); t != NULL;
		     t = ISC_LIST_NEXT(t, link))
		{
			bool existed, exists;
			dns_fixedname_t fixedname;
			dns_name_t *prevname;

			prevname = dns_fixedname_initname(&fixedname);

			if (oldver != NULL) {
				CHECK(name_exists(db, oldver, &t->name,
						  &existed));
			} else {
				existed = false;
			}
			CHECK(name_exists(db, newver, &t->name, &exists));
			if (exists == existed) {
				continue;
			}

			/*
			 * Find the predecessor.
			 * When names become obscured or unobscured in this
			 * update transaction, we may find the wrong
			 * predecessor because the NSECs have not yet been
			 * updated to reflect the delegation change.  This
			 * should not matter because in this case, the correct
			 * predecessor is either the delegation node or a
			 * newly unobscured node, and those nodes are on the
			 * "affected" list in any case.
			 */
			CHECK(next_active(log, zone, db, newver, &t->name,
					  prevname, false));
			CHECK(namelist_append_name(&state->affected, prevname));
		}

		/*
		 * Find names potentially affected by delegation changes
		 * (obscured by adding an NS or DNAME, or unobscured by
		 * removing one).
		 */
		for (t = ISC_LIST_HEAD(state->diffnames.tuples); t != NULL;
		     t = ISC_LIST_NEXT(t, link))
		{
			bool ns_existed, dname_existed;
			bool ns_exists, dname_exists;

			if (oldver != NULL) {
				CHECK(rrset_exists(db, oldver, &t->name,
						   dns_rdatatype_ns, 0,
						   &ns_existed));
			} else {
				ns_existed = false;
			}
			if (oldver != NULL) {
				CHECK(rrset_exists(db, oldver, &t->name,
						   dns_rdatatype_dname, 0,
						   &dname_existed));
			} else {
				dname_existed = false;
			}
			CHECK(rrset_exists(db, newver, &t->name,
					   dns_rdatatype_ns, 0, &ns_exists));
			CHECK(rrset_exists(db, newver, &t->name,
					   dns_rdatatype_dname, 0,
					   &dname_exists));
			if ((ns_exists || dname_exists) ==
			    (ns_existed || dname_existed))
			{
				continue;
			}
			/*
			 * There was a delegation change.  Mark all subdomains
			 * of t->name as potentially needing a NSEC update.
			 */
			CHECK(namelist_append_subdomain(db, &t->name,
							&state->affected));
		}
		ISC_LIST_APPENDLIST(state->affected.tuples,
				    state->diffnames.tuples, link);
		INSIST(ISC_LIST_EMPTY(state->diffnames.tuples));

		CHECK(uniqify_name_list(&state->affected));

		FALLTHROUGH;
	case process_nsec:
		state->state = process_nsec;

		/*
		 * Determine which names should have NSECs, and delete/create
		 * NSECs to make it so.  We don't know the final NSEC targets
		 * yet, so we just create placeholder NSECs with arbitrary
		 * contents to indicate that their respective owner names
		 * should be part of the NSEC chain.
		 */
		while ((t = ISC_LIST_HEAD(state->affected.tuples)) != NULL) {
			bool exists;
			dns_name_t *name = &t->name;

			CHECK(name_exists(db, newver, name, &exists));
			if (!exists) {
				goto unlink;
			}
			CHECK(is_active(db, newver, name, &flag, &cut, NULL));
			if (!flag) {
				/*
				 * This name is obscured.  Delete any
				 * existing NSEC record.
				 */
				CHECK(delete_if(true_p, db, newver, name,
						dns_rdatatype_nsec, 0, NULL,
						&state->nsec_diff));
				CHECK(delete_if(rrsig_p, db, newver, name,
						dns_rdatatype_any, 0, NULL,
						diff));
			} else {
				/*
				 * This name is not obscured.  It needs to have
				 * a NSEC unless it is the at the origin, in
				 * which case it should already exist if there
				 * is a complete NSEC chain and if there isn't
				 * a complete NSEC chain we don't want to add
				 * one as that would signal that there is a
				 * complete NSEC chain.
				 */
				if (!dns_name_equal(name, dns_db_origin(db))) {
					CHECK(rrset_exists(db, newver, name,
							   dns_rdatatype_nsec,
							   0, &flag));
					if (!flag) {
						CHECK(add_placeholder_nsec(
							db, newver, name,
							diff));
					}
				}
				CHECK(add_exposed_sigs(
					log, zone, db, newver, name, cut,
					&state->sig_diff, state->zone_keys,
					state->nkeys, state->inception,
					state->expire, state->check_ksk,
					state->keyset_kskonly, &sigs));
			}
		unlink:
			ISC_LIST_UNLINK(state->affected.tuples, t, link);
			ISC_LIST_APPEND(state->work.tuples, t, link);
			if (state != &mystate && sigs > maxsigs) {
				return (DNS_R_CONTINUE);
			}
		}
		ISC_LIST_APPENDLIST(state->affected.tuples, state->work.tuples,
				    link);

		/*
		 * Now we know which names are part of the NSEC chain.
		 * Make them all point at their correct targets.
		 */
		for (t = ISC_LIST_HEAD(state->affected.tuples); t != NULL;
		     t = ISC_LIST_NEXT(t, link))
		{
			CHECK(rrset_exists(db, newver, &t->name,
					   dns_rdatatype_nsec, 0, &flag));
			if (flag) {
				/*
				 * There is a NSEC, but we don't know if it
				 * is correct. Delete it and create a correct
				 * one to be sure. If the update was
				 * unnecessary, the diff minimization
				 * will take care of eliminating it from the
				 * journal, IXFRs, etc.
				 *
				 * The RRSIG bit should always be set in the
				 * NSECs we generate, because they will all
				 * get RRSIG NSECs.
				 * (XXX what if the zone keys are missing?).
				 * Because the RRSIG NSECs have not necessarily
				 * been created yet, the correctness of the
				 * bit mask relies on the assumption that NSECs
				 * are only created if there is other data, and
				 * if there is other data, there are other
				 * RRSIGs.
				 */
				CHECK(add_nsec(log, zone, db, newver, &t->name,
					       state->nsecttl,
					       &state->nsec_diff));
			}
		}

		/*
		 * Minimize the set of NSEC updates so that we don't
		 * have to regenerate the RRSIG NSECs for NSECs that were
		 * replaced with identical ones.
		 */
		while ((t = ISC_LIST_HEAD(state->nsec_diff.tuples)) != NULL) {
			ISC_LIST_UNLINK(state->nsec_diff.tuples, t, link);
			dns_diff_appendminimal(&state->nsec_mindiff, &t);
		}

		update_log(log, zone, ISC_LOG_DEBUG(3),
			   "signing rebuilt NSEC chain");

		FALLTHROUGH;
	case sign_nsec:
		state->state = sign_nsec;
		/* Update RRSIG NSECs. */
		while ((t = ISC_LIST_HEAD(state->nsec_mindiff.tuples)) != NULL)
		{
			if (t->op == DNS_DIFFOP_DEL) {
				CHECK(delete_if(true_p, db, newver, &t->name,
						dns_rdatatype_rrsig,
						dns_rdatatype_nsec, NULL,
						&state->sig_diff));
			} else if (t->op == DNS_DIFFOP_ADD) {
				CHECK(add_sigs(log, zone, db, newver, &t->name,
					       dns_rdatatype_nsec,
					       &state->sig_diff,
					       state->zone_keys, state->nkeys,
					       state->inception, state->expire,
					       state->check_ksk,
					       state->keyset_kskonly));
				sigs++;
			} else {
				UNREACHABLE();
			}
			ISC_LIST_UNLINK(state->nsec_mindiff.tuples, t, link);
			ISC_LIST_APPEND(state->work.tuples, t, link);
			if (state != &mystate && sigs > maxsigs) {
				return (DNS_R_CONTINUE);
			}
		}
		ISC_LIST_APPENDLIST(state->nsec_mindiff.tuples,
				    state->work.tuples, link);
		FALLTHROUGH;
	case update_nsec3:
		state->state = update_nsec3;

		/* Record our changes for the journal. */
		while ((t = ISC_LIST_HEAD(state->sig_diff.tuples)) != NULL) {
			ISC_LIST_UNLINK(state->sig_diff.tuples, t, link);
			dns_diff_appendminimal(diff, &t);
		}
		while ((t = ISC_LIST_HEAD(state->nsec_mindiff.tuples)) != NULL)
		{
			ISC_LIST_UNLINK(state->nsec_mindiff.tuples, t, link);
			dns_diff_appendminimal(diff, &t);
		}

		INSIST(ISC_LIST_EMPTY(state->sig_diff.tuples));
		INSIST(ISC_LIST_EMPTY(state->nsec_diff.tuples));
		INSIST(ISC_LIST_EMPTY(state->nsec_mindiff.tuples));

		if (!state->build_nsec3) {
			update_log(log, zone, ISC_LOG_DEBUG(3),
				   "no NSEC3 chains to rebuild");
			goto failure;
		}

		update_log(log, zone, ISC_LOG_DEBUG(3),
			   "rebuilding NSEC3 chains");

		dns_diff_clear(&state->diffnames);
		dns_diff_clear(&state->affected);

		CHECK(dns_diff_sort(diff, temp_order));

		/*
		 * Find names potentially affected by delegation changes
		 * (obscured by adding an NS or DNAME, or unobscured by
		 * removing one).
		 */
		t = ISC_LIST_HEAD(diff->tuples);
		while (t != NULL) {
			dns_name_t *name = &t->name;

			bool ns_existed, dname_existed;
			bool ns_exists, dname_exists;
			bool exists, existed;

			if (t->rdata.type == dns_rdatatype_nsec ||
			    t->rdata.type == dns_rdatatype_rrsig)
			{
				t = ISC_LIST_NEXT(t, link);
				continue;
			}

			CHECK(namelist_append_name(&state->affected, name));

			if (oldver != NULL) {
				CHECK(rrset_exists(db, oldver, name,
						   dns_rdatatype_ns, 0,
						   &ns_existed));
			} else {
				ns_existed = false;
			}
			if (oldver != NULL) {
				CHECK(rrset_exists(db, oldver, name,
						   dns_rdatatype_dname, 0,
						   &dname_existed));
			} else {
				dname_existed = false;
			}
			CHECK(rrset_exists(db, newver, name, dns_rdatatype_ns,
					   0, &ns_exists));
			CHECK(rrset_exists(db, newver, name,
					   dns_rdatatype_dname, 0,
					   &dname_exists));

			exists = ns_exists || dname_exists;
			existed = ns_existed || dname_existed;
			if (exists == existed) {
				goto nextname;
			}
			/*
			 * There was a delegation change.  Mark all subdomains
			 * of t->name as potentially needing a NSEC3 update.
			 */
			CHECK(namelist_append_subdomain(db, name,
							&state->affected));

		nextname:
			while (t != NULL && dns_name_equal(&t->name, name)) {
				t = ISC_LIST_NEXT(t, link);
			}
		}

		FALLTHROUGH;
	case process_nsec3:
		state->state = process_nsec3;
		while ((t = ISC_LIST_HEAD(state->affected.tuples)) != NULL) {
			dns_name_t *name = &t->name;

			unsecure = false; /* Silence compiler warning. */
			CHECK(is_active(db, newver, name, &flag, &cut,
					&unsecure));

			if (!flag) {
				CHECK(delete_if(rrsig_p, db, newver, name,
						dns_rdatatype_any, 0, NULL,
						diff));
				CHECK(dns_nsec3_delnsec3sx(db, newver, name,
							   privatetype,
							   &state->nsec_diff));
			} else {
				CHECK(add_exposed_sigs(
					log, zone, db, newver, name, cut,
					&state->sig_diff, state->zone_keys,
					state->nkeys, state->inception,
					state->expire, state->check_ksk,
					state->keyset_kskonly, &sigs));
				CHECK(dns_nsec3_addnsec3sx(
					db, newver, name, state->nsecttl,
					unsecure, privatetype,
					&state->nsec_diff));
			}
			ISC_LIST_UNLINK(state->affected.tuples, t, link);
			ISC_LIST_APPEND(state->work.tuples, t, link);
			if (state != &mystate && sigs > maxsigs) {
				return (DNS_R_CONTINUE);
			}
		}
		ISC_LIST_APPENDLIST(state->affected.tuples, state->work.tuples,
				    link);

		/*
		 * Minimize the set of NSEC3 updates so that we don't
		 * have to regenerate the RRSIG NSEC3s for NSEC3s that were
		 * replaced with identical ones.
		 */
		while ((t = ISC_LIST_HEAD(state->nsec_diff.tuples)) != NULL) {
			ISC_LIST_UNLINK(state->nsec_diff.tuples, t, link);
			dns_diff_appendminimal(&state->nsec_mindiff, &t);
		}

		update_log(log, zone, ISC_LOG_DEBUG(3),
			   "signing rebuilt NSEC3 chain");

		FALLTHROUGH;
	case sign_nsec3:
		state->state = sign_nsec3;
		/* Update RRSIG NSEC3s. */
		while ((t = ISC_LIST_HEAD(state->nsec_mindiff.tuples)) != NULL)
		{
			if (t->op == DNS_DIFFOP_DEL) {
				CHECK(delete_if(true_p, db, newver, &t->name,
						dns_rdatatype_rrsig,
						dns_rdatatype_nsec3, NULL,
						&state->sig_diff));
			} else if (t->op == DNS_DIFFOP_ADD) {
				CHECK(add_sigs(log, zone, db, newver, &t->name,
					       dns_rdatatype_nsec3,
					       &state->sig_diff,
					       state->zone_keys, state->nkeys,
					       state->inception, state->expire,
					       state->check_ksk,
					       state->keyset_kskonly));
				sigs++;
			} else {
				UNREACHABLE();
			}
			ISC_LIST_UNLINK(state->nsec_mindiff.tuples, t, link);
			ISC_LIST_APPEND(state->work.tuples, t, link);
			if (state != &mystate && sigs > maxsigs) {
				return (DNS_R_CONTINUE);
			}
		}
		ISC_LIST_APPENDLIST(state->nsec_mindiff.tuples,
				    state->work.tuples, link);

		/* Record our changes for the journal. */
		while ((t = ISC_LIST_HEAD(state->sig_diff.tuples)) != NULL) {
			ISC_LIST_UNLINK(state->sig_diff.tuples, t, link);
			dns_diff_appendminimal(diff, &t);
		}
		while ((t = ISC_LIST_HEAD(state->nsec_mindiff.tuples)) != NULL)
		{
			ISC_LIST_UNLINK(state->nsec_mindiff.tuples, t, link);
			dns_diff_appendminimal(diff, &t);
		}

		INSIST(ISC_LIST_EMPTY(state->sig_diff.tuples));
		INSIST(ISC_LIST_EMPTY(state->nsec_diff.tuples));
		INSIST(ISC_LIST_EMPTY(state->nsec_mindiff.tuples));
		break;
	default:
		UNREACHABLE();
	}

failure:
	if (node != NULL) {
		dns_db_detachnode(db, &node);
	}

	dns_diff_clear(&state->sig_diff);
	dns_diff_clear(&state->nsec_diff);
	dns_diff_clear(&state->nsec_mindiff);

	dns_diff_clear(&state->affected);
	dns_diff_clear(&state->diffnames);
	dns_diff_clear(&state->work);

	for (i = 0; i < state->nkeys; i++) {
		dst_key_free(&state->zone_keys[i]);
	}

	if (state != &mystate) {
		*statep = NULL;
		state->magic = 0;
		isc_mem_put(diff->mctx, state, sizeof(*state));
	}

	return (result);
}

static isc_stdtime_t
epoch_to_yyyymmdd(time_t when) {
	struct tm t, *tm = localtime_r(&when, &t);
	if (tm == NULL) {
		return (0);
	}
	return (((tm->tm_year + 1900) * 10000) + ((tm->tm_mon + 1) * 100) +
		tm->tm_mday);
}

static uint32_t
dns__update_soaserial(uint32_t serial, dns_updatemethod_t method) {
	isc_stdtime_t now;

	switch (method) {
	case dns_updatemethod_none:
		return (serial);
	case dns_updatemethod_unixtime:
		isc_stdtime_get(&now);
		return (now);
	case dns_updatemethod_date:
		isc_stdtime_get(&now);
		return (epoch_to_yyyymmdd((time_t)now) * 100);
	case dns_updatemethod_increment:
		/* RFC1982 */
		serial = (serial + 1) & 0xFFFFFFFF;
		if (serial == 0) {
			return (1);
		}
		return (serial);
	default:
		UNREACHABLE();
	}
}

uint32_t
dns_update_soaserial(uint32_t serial, dns_updatemethod_t method,
		     dns_updatemethod_t *used) {
	uint32_t new_serial = dns__update_soaserial(serial, method);
	switch (method) {
	case dns_updatemethod_none:
	case dns_updatemethod_increment:
		break;
	case dns_updatemethod_unixtime:
	case dns_updatemethod_date:
		if (!(new_serial != 0 && isc_serial_gt(new_serial, serial))) {
			/*
			 * If the new date serial following YYYYMMDD00 is equal
			 * to or smaller than the current serial, but YYYYMMDD99
			 * would be larger, pretend we have used the
			 * "dns_updatemethod_date" method.
			 */
			if (method == dns_updatemethod_unixtime ||
			    !isc_serial_gt(new_serial + 99, serial))
			{
				method = dns_updatemethod_increment;
			}
			new_serial = dns__update_soaserial(
				serial, dns_updatemethod_increment);
		}
		break;
	default:
		UNREACHABLE();
	}

	if (used != NULL) {
		*used = method;
	}

	return (new_serial);
}