summaryrefslogtreecommitdiff
path: root/src/knot/server/zones.c
blob: dbc1340fe542a802d5d08ca613df7c6a84ca6fe1 (plain)
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
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
/*  Copyright (C) 2011 CZ.NIC, z.s.p.o. <knot-dns@labs.nic.cz>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <sys/stat.h>
#include <unistd.h>

#include "common/lists.h"
#include "common/prng.h"
#include "libknot/dname.h"
#include "libknot/util/wire.h"
#include "knot/zone/zone-dump-text.h"
#include "knot/zone/zone-load.h"
#include "libknot/zone/zone.h"
#include "libknot/zone/zonedb.h"
#include "knot/conf/conf.h"
#include "knot/other/debug.h"
#include "knot/other/error.h"
#include "knot/other/log.h"
#include "knot/server/notify.h"
#include "knot/server/server.h"
#include "libknot/updates/xfr-in.h"
#include "knot/server/zones.h"
#include "libknot/util/error.h"
#include "knot/zone/zone-dump.h"
#include "libknot/nameserver/name-server.h"
#include "libknot/updates/changesets.h"
#include "libknot/tsig-op.h"
#include "libknot/packet/response.h"

static const size_t XFRIN_CHANGESET_BINARY_SIZE = 100;
static const size_t XFRIN_CHANGESET_BINARY_STEP = 100;

/* Forward declarations. */
static int zones_dump_zone_text(knot_zone_contents_t *zone,  const char *zf);

/*----------------------------------------------------------------------------*/

/*!
 * \brief Wrapper for TCP send.
 */
#include "knot/server/tcp-handler.h"
static int zones_send_cb(int fd, sockaddr_t *addr, uint8_t *msg, size_t msglen)
{
	return tcp_send(fd, msg, msglen);
}

/*----------------------------------------------------------------------------*/

/*! \brief Zone data destructor function. */
static int zonedata_destroy(knot_zone_t *zone)
{
	if (zone == NULL) {
		return KNOTD_EINVAL;
	}
	
	dbg_zones_verb("zones: zonedata_destroy(%p) called\n", zone);
	
	zonedata_t *zd = (zonedata_t *)knot_zone_data(zone);
	if (!zd) {
		return KNOTD_EINVAL;
	}

	/* Cancel REFRESH timer. */
	if (zd->xfr_in.timer) {
		evsched_t *sch = zd->xfr_in.timer->parent;
		evsched_cancel(sch, zd->xfr_in.timer);
		evsched_event_free(sch, zd->xfr_in.timer);
		zd->xfr_in.timer = 0;
	}

	/* Cancel EXPIRE timer. */
	if (zd->xfr_in.expire) {
		evsched_t *sch = zd->xfr_in.expire->parent;
		evsched_cancel(sch, zd->xfr_in.expire);
		evsched_event_free(sch, zd->xfr_in.expire);
		zd->xfr_in.expire = 0;
	}

	/* Remove list of pending NOTIFYs. */
	pthread_mutex_lock(&zd->lock);
	notify_ev_t *ev = 0, *evn = 0;
	WALK_LIST_DELSAFE(ev, evn, zd->notify_pending) {
		zones_cancel_notify(zd, ev);
	}
	pthread_mutex_unlock(&zd->lock);

	/* Cancel IXFR DB sync timer. */
	if (zd->ixfr_dbsync) {
		evsched_t *sch = zd->ixfr_dbsync->parent;
		evsched_cancel(sch, zd->ixfr_dbsync);
		evsched_event_free(sch, zd->ixfr_dbsync);
		zd->ixfr_dbsync = 0;
	}

	/* Destroy mutex. */
	pthread_mutex_destroy(&zd->lock);
	pthread_mutex_destroy(&zd->xfr_in.lock);

	acl_delete(&zd->xfr_in.acl);
	acl_delete(&zd->xfr_out);
	acl_delete(&zd->notify_in);
	acl_delete(&zd->notify_out);

	/* Close IXFR db. */
	journal_release(zd->ixfr_db);

	free(zd);
	
	/* Invalidate. */
	zone->dtor = 0;
	zone->data = 0;

	return KNOTD_EOK;
}

/*! \brief Zone data constructor function. */
static int zonedata_init(conf_zone_t *cfg, knot_zone_t *zone)
{
	if (cfg == NULL || zone == NULL) {
		return KNOTD_EINVAL;
	}
	zonedata_t *zd = malloc(sizeof(zonedata_t));
	if (!zd) {
		return KNOTD_ENOMEM;
	}
	memset(zd, 0, sizeof(zonedata_t));

	/* Link to config. */
	zd->conf = cfg;
	zd->server = 0;

	/* Initialize mutex. */
	pthread_mutex_init(&zd->lock, 0);

	/* Initialize ACLs. */
	zd->xfr_out = 0;
	zd->notify_in = 0;
	zd->notify_out = 0;

	/* Initialize XFR-IN. */
	sockaddr_init(&zd->xfr_in.master, -1);
	zd->xfr_in.timer = 0;
	zd->xfr_in.expire = 0;
	zd->xfr_in.next_id = -1;
	zd->xfr_in.acl = 0;
	zd->xfr_in.wrkr = 0;
	zd->xfr_in.bootstrap_retry = 0;
	pthread_mutex_init(&zd->xfr_in.lock, 0);

	/* Initialize NOTIFY. */
	init_list(&zd->notify_pending);

	/* Initialize IXFR database. */
	zd->ixfr_db = journal_open(cfg->ixfr_db, cfg->ixfr_fslimit,
	                           JOURNAL_LAZY, JOURNAL_DIRTY);
	if (!zd->ixfr_db) {
		int ret = journal_create(cfg->ixfr_db, JOURNAL_NCOUNT);
		if (ret != KNOTD_EOK) {
			log_server_error("Failed to create journal file "
			                 "'%s'\n", cfg->ixfr_db);
		}
		zd->ixfr_db = journal_open(cfg->ixfr_db, cfg->ixfr_fslimit,
		                           JOURNAL_LAZY, JOURNAL_DIRTY);
	}
	
	if (zd->ixfr_db == 0) {
		log_server_error("Failed to open journal file "
		                 "'%s'\n", cfg->ixfr_db);
	}

	/* Initialize IXFR database syncing event. */
	zd->ixfr_dbsync = 0;

	/* Set and install destructor. */
	zone->data = zd;
	zone->dtor = zonedata_destroy;

	/* Set zonefile SOA serial. */
	const knot_rrset_t *soa_rrs = 0;
	const knot_rdata_t *soa_rr = 0;

	/* Load serial. */
	zd->zonefile_serial = 0;
	const knot_zone_contents_t *contents = knot_zone_contents(zone);
	if (contents) {
		soa_rrs = knot_node_rrset(knot_zone_contents_apex(contents),
					  KNOT_RRTYPE_SOA);
		assert(soa_rrs != NULL);
		soa_rr = knot_rrset_rdata(soa_rrs);
		int64_t serial = knot_rdata_soa_serial(soa_rr);
		zd->zonefile_serial = (uint32_t)serial;
		if (serial < 0) {
			return KNOTD_EINVAL;
		}
	}

	return KNOTD_EOK;
}

/*!
 * \brief Return SOA timer value.
 *
 * \param zone Pointer to zone.
 * \param rr_func RDATA specificator.
 * \return Timer in miliseconds.
 */
static uint32_t zones_soa_timer(knot_zone_t *zone,
                                uint32_t (*rr_func)(const knot_rdata_t*))
{
	if (!zone) {
		dbg_zones_verb("zones: zones_soa_timer() called "
		               "with NULL zone\n");
	}

	uint32_t ret = 0;

	/* Retrieve SOA RDATA. */
	const knot_rrset_t *soa_rrs = 0;
	const knot_rdata_t *soa_rr = 0;
	knot_zone_contents_t * zc = knot_zone_get_contents((zone));
	if (!zc) {
		return 0;
	}

	soa_rrs = knot_node_rrset(knot_zone_contents_apex(zc),
	                            KNOT_RRTYPE_SOA);
	assert(soa_rrs != NULL);
	soa_rr = knot_rrset_rdata(soa_rrs);
	ret = rr_func(soa_rr);

	/* Convert to miliseconds. */
	return ret * 1000;
}

/*!
 * \brief Return SOA REFRESH timer value.
 *
 * \param zone Pointer to zone.
 * \return REFRESH timer in miliseconds.
 */
static uint32_t zones_soa_refresh(knot_zone_t *zone)
{
	return zones_soa_timer(zone, knot_rdata_soa_refresh);
}

/*!
 * \brief Return SOA RETRY timer value.
 *
 * \param zone Pointer to zone.
 * \return RETRY timer in miliseconds.
 */
static uint32_t zones_soa_retry(knot_zone_t *zone)
{
	return zones_soa_timer(zone, knot_rdata_soa_retry);
}

/*!
 * \brief Return SOA EXPIRE timer value.
 *
 * \param zone Pointer to zone.
 * \return EXPIRE timer in miliseconds.
 */
static uint32_t zones_soa_expire(knot_zone_t *zone)
{
	return zones_soa_timer(zone, knot_rdata_soa_expire);
}

/*!
 * \brief XFR/IN expire event handler.
 */
static int zones_expire_ev(event_t *e)
{
	rcu_read_lock();
	dbg_zones("zones: EXPIRE timer event\n");
	knot_zone_t *zone = (knot_zone_t *)e->data;
	if (!zone) {
		return KNOTD_EINVAL;
	}
	if (!zone->data) {
		return KNOTD_EINVAL;
	}

	zonedata_t *zd = (zonedata_t *)zone->data;
	
	/* Won't accept any pending SOA responses. */
	zd->xfr_in.next_id = -1;

	/* Mark the zone as expired. This will remove the zone contents. */
	knot_zone_contents_t *contents = knot_zonedb_expire_zone(
			zd->server->nameserver->zone_db, zone->name);

	if (contents == NULL) {
		log_server_warning("Non-existent zone expired. Ignoring.\n");
		rcu_read_unlock();
		return 0;
	}
	
	
	rcu_read_unlock();
	
	dbg_zones_verb("zones: zone %s expired, waiting for xfers to finish\n",
	               zd->conf->name);
	pthread_mutex_lock(&zd->xfr_in.lock);
	dbg_zones_verb("zones: zone %s locked, no xfers are running\n",
	               zd->conf->name);
	
	synchronize_rcu();
	pthread_mutex_unlock(&zd->xfr_in.lock);
	
	log_server_info("Zone '%s' expired.\n", zd->conf->name);
	
	/* Early finish this event to prevent lockup during cancellation. */
	dbg_zones("zones: zone expired, removing from database\n");
	evsched_event_finished(e->parent);
	
	/* Cancel REFRESH timer. */
	if (zd->xfr_in.timer) {
		evsched_cancel(e->parent, zd->xfr_in.timer);
		evsched_event_free(e->parent, zd->xfr_in.timer);
		zd->xfr_in.timer = 0;
	}

	/* Free EXPIRE timer. */
	if (zd->xfr_in.expire) {
		evsched_event_free(e->parent, zd->xfr_in.expire);
		zd->xfr_in.expire = 0;
	}
	
	knot_zone_contents_deep_free(&contents, 0);
	
	return 0;
}

/*!
 * \brief Zone REFRESH or RETRY event.
 */
static int zones_refresh_ev(event_t *e)
{
	dbg_zones("zones: REFRESH or RETRY timer event\n");
	knot_zone_t *zone = (knot_zone_t *)e->data;
	if (!zone) {
		return KNOTD_EINVAL;
	}

	/* Cancel pending timers. */
	zonedata_t *zd = (zonedata_t *)knot_zone_data(zone);
	if (!zd) {
		return KNOTD_EINVAL;
	}

	/* Prepare buffer for query. */
	uint8_t qbuf[SOCKET_MTU_SZ];
	size_t buflen = SOCKET_MTU_SZ;

	/* Lock RCU. */
	rcu_read_lock();

	/* Check for contents. */
	if (!knot_zone_contents(zone)) {

		/* Bootstrap from XFR master. */
		knot_ns_xfr_t xfr_req;
		memset(&xfr_req, 0, sizeof(knot_ns_xfr_t));
		memcpy(&xfr_req.addr, &zd->xfr_in.master, sizeof(sockaddr_t));
		memcpy(&xfr_req.saddr, &zd->xfr_in.via, sizeof(sockaddr_t));
		xfr_req.data = (void *)zone;
		xfr_req.send = zones_send_cb;

		/* Select transfer method. */
		xfr_req.type = XFR_TYPE_AIN;
		xfr_req.zone = zone;
		
		/* Select TSIG key. */
		if (zd->xfr_in.tsig_key.name) {
			xfr_req.tsig_key = &zd->xfr_in.tsig_key;
		}

		/* Unlock zone contents. */
		rcu_read_unlock();

		/* Enqueue XFR request. */
		int locked = pthread_mutex_trylock(&zd->xfr_in.lock);
		if (locked != 0) {
			dbg_zones("zones: already bootstrapping '%s'\n",
			          zd->conf->name);
			return KNOTD_EOK;
		}

		log_zone_info("Attempting to bootstrap zone %s from master\n",
			      zd->conf->name);
		pthread_mutex_unlock(&zd->xfr_in.lock);
		
		return xfr_request(zd->server->xfr_h, &xfr_req);
	}
	
	/* Do not issue SOA query if transfer is pending. */
	int locked = pthread_mutex_trylock(&zd->xfr_in.lock);
	if (locked != 0) {
		dbg_zones("zones: zone '%s' is being transferred, "
		          "deferring SOA query\n",
		          zd->conf->name);
		
		/* Reschedule as RETRY timer. */
		evsched_schedule(e->parent, e, zones_soa_retry(zone));
		dbg_zones("zones: RETRY of '%s' after %u seconds\n",
		          zd->conf->name, zones_soa_retry(zone) / 1000);
		
		/* Unlock RCU. */
		rcu_read_unlock();
		return KNOTD_EOK;
	} else {
		pthread_mutex_unlock(&zd->xfr_in.lock);
	}
	
	/* Invalidate pending SOA query. */
	event_t *soa_pending = zd->soa_pending;
	zd->soa_pending = NULL;
	
	/*! \todo [TSIG] CHANGE!!! only for compatibility now. */
	knot_ns_xfr_t xfr_req;
	memset(&xfr_req, 0, sizeof(knot_ns_xfr_t));
	xfr_req.wire = qbuf;

	/* Create query. */
	int ret = xfrin_create_soa_query(zone->name, &xfr_req, &buflen);
	if (ret == KNOT_EOK) {

		sockaddr_t *master = &zd->xfr_in.master;

		/* Create socket on random port. */
		int sock = socket_create(master->family, SOCK_DGRAM);
		
		/* Check requested source. */
		sockaddr_t *via = &zd->xfr_in.via;
		if (via->len > 0) {
			if (bind(sock, via->ptr, via->len) < 0) {
				socket_close(sock);
				sock = -1;
			}
		}

		/* Send query. */
		ret = KNOTD_ERROR;
		if (sock > -1) {
			int sent = sendto(sock, qbuf, buflen, 0,
			                  master->ptr, master->len);
		
			/* Store ID of the awaited response. */
			if (sent == buflen) {
				ret = KNOTD_EOK;
			} else {
				socket_close(sock);
				sock = -1;
			}
		}
		
		/* Check result. */
		if (ret == KNOTD_EOK) {
			zd->xfr_in.next_id = knot_wire_get_id(qbuf);
			dbg_zones("zones: expecting SOA response "
			          "ID=%d for '%s'\n",
			          zd->xfr_in.next_id, zd->conf->name);
			
			/* Watch socket. */
			knot_ns_xfr_t req;
			memset(&req, 0, sizeof(req));
			req.session = sock;
			req.type = XFR_TYPE_SOA;
			req.zone = zone;
			memcpy(&req.addr, master, sizeof(sockaddr_t));
			memcpy(&req.saddr, &zd->xfr_in.via, sizeof(sockaddr_t));
			sockaddr_update(&req.addr);
			ret = xfr_request(zd->server->xfr_h, &req);
		}
	} else {
		ret = KNOTD_ERROR;
	}
	
	if (ret != KNOTD_EOK) {
		log_server_warning("Failed to issue SOA query for zone '%s'.\n",
		                   zd->conf->name);
	}

	/* Schedule EXPIRE timer on first attempt. */
	if (!zd->xfr_in.expire) {
		uint32_t expire_tmr = zones_soa_expire(zone);
		zd->xfr_in.expire = evsched_schedule_cb(
					      e->parent,
					      zones_expire_ev,
					      zone, expire_tmr);
		dbg_zones("zones: EXPIRE of '%s' after %u seconds\n",
		          zd->conf->name, expire_tmr / 1000);
	}

	/* Reschedule as RETRY timer. */
	evsched_schedule(e->parent, e, zones_soa_retry(zone));
	dbg_zones("zones: RETRY of '%s' after %u seconds\n",
	          zd->conf->name, zones_soa_retry(zone) / 1000);

	/* Unlock RCU. */
	rcu_read_unlock();
	
	/* Close invalidated SOA query. */
	evsched_event_finished(e->parent);
	if (soa_pending != NULL) {
		/* Execute */
		evsched_schedule(e->parent, soa_pending, 0);
	}
	return ret;
}

/*!
 * \brief Send NOTIFY to slave server.
 */
static int zones_notify_send(event_t *e)
{
	dbg_notify("notify: NOTIFY timer event\n");
	
	notify_ev_t *ev = (notify_ev_t *)e->data;
	knot_zone_t *zone = ev->zone;
	if (!zone) {
		log_zone_error("NOTIFY invalid event received\n");
		evsched_event_free(e->parent, e);
		free(ev);
		return KNOTD_EINVAL;
	}

	/* Check for answered/cancelled query. */
	zonedata_t *zd = (zonedata_t *)knot_zone_data(zone);
	knot_zone_contents_t *contents = knot_zone_get_contents(zone);

	/* Reduce number of available retries. */
	--ev->retries;

	/* Check number of retries. */
	if (ev->retries < 0) {
		log_server_notice("NOTIFY query maximum number of retries "
				  "for zone '%s' exceeded.\n",
				  zd->conf->name);
		pthread_mutex_lock(&zd->lock);
		rem_node(&ev->n);
		evsched_event_free(e->parent, e);
		free(ev);
		pthread_mutex_unlock(&zd->lock);
		return KNOTD_EMALF;
	}

	/* Prepare buffer for query. */
	uint8_t qbuf[SOCKET_MTU_SZ];
	size_t buflen = sizeof(qbuf);

        /* RFC suggests 60s, but it is configurable. */
        int retry_tmr = ev->timeout * 1000;
 
        /* Reschedule. */
        conf_read_lock();
        evsched_schedule(e->parent, e, retry_tmr);
        dbg_notify("notify: Query RETRY after %u secs (zone '%s')\n",
                   retry_tmr / 1000, zd->conf->name);
        conf_read_unlock();

	/* Create query. */
	int ret = notify_create_request(contents, qbuf, &buflen);
	if (ret == KNOTD_EOK && zd->server) {

		/* Lock RCU. */
		rcu_read_lock();

		/* Create socket on random port. */
		int sock = socket_create(ev->addr.family, SOCK_DGRAM);
		
		/* Check requested source. */
		if (ev->saddr.len > 0) {
			if (bind(sock, ev->saddr.ptr, ev->saddr.len) < 0) {
				socket_close(sock);
				sock = -1;
			}
		}

		/* Send query. */
		ret = -1;
		if (sock > -1) {
			ret = sendto(sock, qbuf, buflen, 0,
				     ev->addr.ptr, ev->addr.len);
		}

		/* Store ID of the awaited response. */
		if (ret == buflen) {
			ev->msgid = knot_wire_get_id(qbuf);
			
		}

		/* Watch socket. */
		knot_ns_xfr_t req;
		memset(&req, 0, sizeof(req));
		req.session = sock;
		req.type = XFR_TYPE_NOTIFY;
		req.zone = zone;
		memcpy(&req.addr, &ev->addr, sizeof(sockaddr_t));
		memcpy(&req.saddr, &ev->saddr, sizeof(sockaddr_t));
		xfr_request(zd->server->xfr_h, &req);

		/* Unlock RCU */
		rcu_read_unlock();
	}

	return ret;
}

/*! \brief Function for marking nodes as synced and updated. */
static int zones_ixfrdb_sync_apply(journal_t *j, journal_node_t *n)
{
	/* Check for dirty bit (not synced to permanent storage). */
	if (n->flags & JOURNAL_DIRTY) {

		/* Remove dirty bit. */
		n->flags = n->flags & ~JOURNAL_DIRTY;

		/* Sync. */
		journal_update(j, n);
	}

	return KNOTD_EOK;
}

/*!
 * \brief Sync chagnes in zone to zonefile.
 */
static int zones_zonefile_sync_ev(event_t *e)
{
	dbg_zones("zones: IXFR database SYNC timer event\n");

	/* Fetch zone. */
	knot_zone_t *zone = (knot_zone_t *)e->data;
	if (!zone) {
		return KNOTD_EINVAL;
	}

	/* Fetch zone data. */
	zonedata_t *zd = (zonedata_t *)zone->data;
	if (!zd) {
		return KNOTD_EINVAL;
	}

	/* Execute zonefile sync. */
	journal_t *j = journal_retain(zd->ixfr_db);
	int ret = zones_zonefile_sync(zone, j);
	journal_release(j);
	if (ret == KNOTD_EOK) {
		log_zone_info("Applied differences of '%s' to zonefile.\n",
		              zd->conf->name);
	} else if (ret != KNOTD_ERANGE) {
		log_zone_warning("Failed to apply differences of '%s' "
		                 "to zonefile.\n",
		                 zd->conf->name);
	}

	/* Reschedule. */
	conf_read_lock();
	evsched_schedule(e->parent, e, zd->conf->dbsync_timeout * 1000);
	dbg_zones("zones: next IXFR database SYNC of '%s' in %d seconds\n",
	          zd->conf->name, zd->conf->dbsync_timeout);
	conf_read_unlock();

	return ret;
}

/*!
 * \brief Update ACL list from configuration.
 *
 * \param acl Pointer to existing or NULL ACL.
 * \param acl_list List of remotes from configuration.
 *
 * \retval KNOTD_EOK on success.
 * \retval KNOTD_EINVAL on invalid parameters.
 * \retval KNOTD_ENOMEM on failed memory allocation.
 */
static int zones_set_acl(acl_t **acl, list* acl_list)
{
	if (!acl || !acl_list) {
		return KNOTD_EINVAL;
	}

	/* Truncate old ACL. */
	acl_delete(acl);

	/* Create new ACL. */
	*acl = acl_new(ACL_DENY, 0);
	if (!*acl) {
		return KNOTD_ENOMEM;
	}

	/* Load ACL rules. */
	conf_remote_t *r = 0;
	WALK_LIST(r, *acl_list) {

		/* Initialize address. */
		/*! Port matching disabled, port = 0. */
		sockaddr_t addr;
		conf_iface_t *cfg_if = r->remote;
		int ret = sockaddr_set(&addr, cfg_if->family,
		                       cfg_if->address, 0);
		sockaddr_setprefix(&addr, cfg_if->prefix);

		/* Load rule. */
		if (ret > 0) {
			/*! \todo Correct search for the longest prefix match.
			 *        This just favorizes remotes with TSIG.
			 *        (issue #1675)
			 */
			unsigned flags = 0;
			if (cfg_if->key != NULL) {
				flags = ACL_PREFER;
			}
			acl_create(*acl, &addr, ACL_ACCEPT, cfg_if, flags);
		}
	}

	return KNOTD_EOK;
}

/*!
 * \brief Load zone to zone database.
 *
 * \param zonedb Zone database to load the zone into.
 * \param zone_name Zone name (owner of the apex node).
 * \param source Path to zone file source.
 * \param filename Path to requested compiled zone file.
 *
 * \retval KNOTD_EOK
 * \retval KNOTD_EINVAL
 * \retval KNOTD_EZONEINVAL
 */
static int zones_load_zone(knot_zonedb_t *zonedb, const char *zone_name,
			   const char *source, const char *filename)
{
	knot_zone_t *zone = NULL;
	size_t zlen = strlen(zone_name);
	char *zname = NULL;
	if (zlen > 0) {
		if ((zname = strdup(zone_name)) == NULL) {
			return KNOTD_ENOMEM;
		}
	} else {
		return KNOTD_EINVAL;
	}
	
	zname[zlen - 1] = '\0'; /* Trim last dot */

	/* Check path */
	if (filename) {
		dbg_zones("zones: parsing zone database '%s'\n", filename);
		zloader_t *zl = 0;
		int ret = knot_zload_open(&zl, filename);
		switch(ret) {
		case KNOT_EOK:
			/* OK */
			break;
		case KNOT_EFEWDATA:
			log_server_error("Couldn't find compiled zone. "
			                 "Please recompile '%s'.\n", zname);
			free(zname);
			return KNOTD_EZONEINVAL;
		case KNOT_ECRC:
			log_server_error("Compiled zone db CRC mismatch, "
			                 "db is corrupted or .crc file is "
			                 "deleted. Please recompile '%s'.\n",
			                 zname);
			free(zname);
			return KNOTD_EZONEINVAL;
		case KNOT_EMALF:
			log_server_error("Compiled db '%s' is too old. "
			                 "Please recompile '%s'.\n",
			                 filename, zname);
			free(zname);
			return KNOTD_EZONEINVAL;
		case KNOT_ERROR:
		case KNOT_ENOMEM:
		default:
			log_server_error("Failed to load compiled zone file "
			                 "'%s'.\n", filename);
			free(zname);
			return KNOTD_EZONEINVAL;
		}

		/* Check if the db is up-to-date */
		int src_changed = strcmp(source, zl->source) != 0;
		if (src_changed || knot_zload_needs_update(zl)) {
			log_server_warning("Database for zone '%s' is not "
			                   "up-to-date. Please recompile.\n",
			                   zname);
		}

		zone = knot_zload_load(zl);
		
		/* Check loaded name. */
		const knot_dname_t *dname = knot_zone_name(zone);
		knot_dname_t *dname_req = 0;
		dname_req = knot_dname_new_from_str(zone_name, zlen, 0);
		if (knot_dname_compare(dname, dname_req) != 0) {
			log_server_warning("Origin of the zone db file is "
			                   "different than '%s'\n",
			                   zone_name);
			knot_zone_deep_free(&zone, 0);
			zone = 0;
			
		}
		knot_dname_free(&dname_req);

		/* CLEANUP */
//		knot_zone_contents_dump(zone->contents, 1);
//		int errs = knot_zone_contents_integrity_check(zone->contents);
//		fprintf(stderr, "INTEGRITY CHECK OF ZONE. ERRORS: %d\n", errs);

		if (zone) {
			/* save the timestamp from the zone db file */
			struct stat s;
			if (stat(filename, &s) < 0) {
				dbg_zones("zones: failed to stat() zone db, "
					  "something is seriously wrong\n");
				knot_zone_deep_free(&zone, 0);
				zone = 0;
			} else {
				knot_zone_set_version(zone, s.st_mtime);
				if (knot_zonedb_add_zone(zonedb, zone) != 0){
					knot_zone_deep_free(&zone, 0);
					zone = 0;
				}
			}
		}

		knot_zload_close(zl);

		if (!zone) {
			log_server_error("Failed to load "
					 "db '%s' for zone '%s'.\n",
					 filename, zname);
			free(zname);
			return KNOTD_EZONEINVAL;
		}
	} else {
		/* db is null. */
		log_server_error("No file name for zone '%s'.\n", zname);
		free(zname);
		return KNOTD_EINVAL;
	}

	/* CLEANUP */
//	knot_zone_dump(zone, 1);
	free(zname);

	return KNOTD_EOK;
}

/*----------------------------------------------------------------------------*/

/*! \brief Return 'serial_from' part of the key. */
static inline uint32_t ixfrdb_key_from(uint64_t k)
{
	/*      64    32       0
	 * key = [TO   |   FROM]
	 * Need: Least significant 32 bits.
	 */
	return (uint32_t)(k & ((uint64_t)0x00000000ffffffff));
}

/*----------------------------------------------------------------------------*/

/*! \brief Return 'serial_to' part of the key. */
static inline uint32_t ixfrdb_key_to(uint64_t k)
{
	/*      64    32       0
	 * key = [TO   |   FROM]
	 * Need: Most significant 32 bits.
	 */
	return (uint32_t)(k >> (uint64_t)32);
}

/*----------------------------------------------------------------------------*/

/*! \brief Compare function to match entries with target serial. */
static inline int ixfrdb_key_to_cmp(uint64_t k, uint64_t to)
{
	/*      64    32       0
	 * key = [TO   |   FROM]
	 * Need: Most significant 32 bits.
	 */
	return ((uint64_t)ixfrdb_key_to(k)) - to;
}

/*----------------------------------------------------------------------------*/

/*! \brief Compare function to match entries with starting serial. */
static inline int ixfrdb_key_from_cmp(uint64_t k, uint64_t from)
{
	/*      64    32       0
	 * key = [TO   |   FROM]
	 * Need: Least significant 32 bits.
	 */
	return ((uint64_t)ixfrdb_key_from(k)) - from;
}

/*----------------------------------------------------------------------------*/

/*! \brief Make key for journal from serials. */
static inline uint64_t ixfrdb_key_make(uint32_t from, uint32_t to)
{
	/*      64    32       0
	 * key = [TO   |   FROM]
	 */
	return (((uint64_t)to) << ((uint64_t)32)) | ((uint64_t)from);
}

/*----------------------------------------------------------------------------*/

static int zones_changesets_from_binary(knot_changesets_t *chgsets)
{
	assert(chgsets != NULL);
	assert(chgsets->allocated >= chgsets->count);
	/*
	 * Parses changesets from the binary format stored in chgsets->data
	 * into the changeset_t structures.
	 */
	knot_rrset_t *rrset = 0;
	int ret = 0;

	for (int i = 0; i < chgsets->count; ++i) {

		/* Read initial changeset RRSet - SOA. */
		knot_changeset_t* chs = chgsets->sets + i;
		size_t remaining = chs->size;
		ret = knot_zload_rrset_deserialize(&rrset, chs->data, &remaining);
		if (ret != KNOT_EOK) {
			dbg_xfr("xfr: SOA: failed to deserialize data "
			        "from changeset, %s\n", knot_strerror(ret));
			return KNOTD_EMALF;
		}

		/* in this special case (changesets loaded
		 * from journal) the SOA serial should already
		 * be set, check it.
		 */
		assert(knot_rrset_type(rrset) == KNOT_RRTYPE_SOA);
		assert(chs->serial_from ==
		       knot_rdata_soa_serial(knot_rrset_rdata(rrset)));
		knot_changeset_store_soa(&chs->soa_from, &chs->serial_from,
					 rrset);

		dbg_xfr_verb("xfr: reading RRSets to REMOVE\n");

		/* Read remaining RRSets */
		int in_remove_section = 1;
		while (remaining > 0) {

			/* Parse next RRSet. */
			rrset = 0;
			uint8_t *stream = chs->data + (chs->size - remaining);
			ret = knot_zload_rrset_deserialize(&rrset, stream, &remaining);
			if (ret != KNOT_EOK) {
				dbg_xfr("xfr: failed to deserialize data "
				        "from changeset, %s\n",
				        knot_strerror(ret));
				return KNOTD_EMALF;
			}

			/* Check for next SOA. */
			if (knot_rrset_type(rrset) == KNOT_RRTYPE_SOA) {

				/* Move to ADD section if in REMOVE. */
				if (in_remove_section) {
					knot_changeset_store_soa(
						&chgsets->sets[i].soa_to,
						&chgsets->sets[i].serial_to,
						rrset);
					dbg_xfr_verb("xfr: reading RRSets"
					             " to ADD\n");
					in_remove_section = 0;
				} else {
					/* Final SOA. */
					dbg_xfr_verb("xfr: extra SOA\n");
					knot_rrset_free(&rrset);
					break;
				}
			} else {
				/* Remove RRSets. */
				if (in_remove_section) {
					ret = knot_changeset_add_rrset(
						&chgsets->sets[i].remove,
						&chgsets->sets[i].remove_count,
						&chgsets->sets[i]
						    .remove_allocated,
						rrset);
				} else {
				/* Add RRSets. */
					ret = knot_changeset_add_rrset(
						&chgsets->sets[i].add,
						&chgsets->sets[i].add_count,
						&chgsets->sets[i].add_allocated,
						rrset);
				}

				/* Check result. */
				if (ret != KNOT_EOK) {
					dbg_xfr("xfr: failed to add/remove "
					        "RRSet to changeset: %s\n",
					        knot_strerror(ret));
					return KNOTD_ERROR;
				}
			}
		}
		
		dbg_xfr_verb("xfr: read all RRSets in changeset\n");
	}

	return KNOTD_EOK;
}

/*----------------------------------------------------------------------------*/

static int zones_load_changesets(const knot_zone_t *zone, 
                                 knot_changesets_t *dst,
                                 uint32_t from, uint32_t to)
{
	if (!zone || !dst) {
		dbg_zones_detail("Bad arguments: zone=%p, dst=%p\n", zone, dst);
		return KNOTD_EINVAL;
	}
	if (!zone->data) {
		dbg_zones_detail("Bad arguments: zone->data=%p\n", zone->data);
		return KNOTD_EINVAL;
	}
	
	dbg_xfr("Loading changesets from serial %u to %u\n", from, to);

	/* Fetch zone-specific data. */
	zonedata_t *zd = (zonedata_t *)knot_zone_data(zone);
	if (!zd->ixfr_db) {
		dbg_zones_detail("Bad arguments: zd->ixfr_db=%p\n", zone->data);
		return KNOTD_EINVAL;
	}
	
	/* Retain journal for changeset loading. */
	journal_t *j = journal_retain(zd->ixfr_db);

	/* Read entries from starting serial until finished. */
	uint32_t found_to = from;
	journal_node_t *n = 0;
	int ret = journal_fetch(j, from, ixfrdb_key_from_cmp, &n);
	if (ret != KNOTD_EOK) {
		dbg_xfr("xfr: failed to fetch starting changeset: %s\n",
		        knotd_strerror(ret));
		journal_release(j);
		return ret;
	}
	
	while (n != 0 && n != journal_end(j)) {

		/* Check for history end. */
		if (to == found_to) {
			break;
		}

		/*! \todo Increment and decrement to reserve +1,
		 *        but not incremented counter.*/
		/* Check changesets size if needed. */
		++dst->count;
		ret = knot_changesets_check_size(dst);
		--dst->count;
		if (ret != KNOT_EOK) {
			--dst->count;
			dbg_xfr("xfr: failed to check changesets size: %s\n",
			        knot_strerror(ret));
			journal_release(j);
			return KNOTD_ERROR;
		}

		/* Initialize changeset. */
		dbg_xfr_detail("xfr: reading entry #%zu id=%llu\n",
		               dst->count, (unsigned long long)n->id);
		knot_changeset_t *chs = dst->sets + dst->count;
		chs->serial_from = ixfrdb_key_from(n->id);
		chs->serial_to = ixfrdb_key_to(n->id);
		chs->data = malloc(n->len);
		if (!chs->data) {
			journal_release(j);
			return KNOTD_ENOMEM;
		}

		/* Read journal entry. */
		ret = journal_read(j, n->id, 0, (char*)chs->data);
		if (ret != KNOTD_EOK) {
			dbg_xfr("xfr: failed to read data from journal\n");
			free(chs->data);
			journal_release(j);
			return KNOTD_ERROR;
		}

		/* Update changeset binary size. */
		chs->size = chs->allocated = n->len;

		/* Next node. */
		found_to = chs->serial_to;
		++dst->count;
		++n;

		/*! \todo Check consistency. */
	}
	
	dbg_xfr_detail("xfr: Journal entries read.\n");
	journal_release(j);

	/* Unpack binary data. */
	int unpack_ret = zones_changesets_from_binary(dst);
	if (unpack_ret != KNOT_EOK) {
		dbg_xfr("xfr: failed to unpack changesets "
		        "from binary, %s\n", knot_strerror(unpack_ret));
		return KNOTD_ERROR;
	}

	/* Check for complete history. */
	if (to != found_to) {
		dbg_xfr_detail("Returning ERANGE\n");
		return KNOTD_ERANGE;
	}

	/* History reconstructed. */
	dbg_xfr_detail("Returning EOK\n");
	return KNOTD_EOK;
}

/*----------------------------------------------------------------------------*/

/*!
 * \brief Apply changesets to zone from journal.
 *
 * \param zone Specified zone.
 *
 * \retval KNOTD_EOK if successful.
 * \retval KNOTD_EINVAL on invalid parameters.
 * \retval KNOTD_ENOENT if zone has no contents.
 * \retval KNOTD_ERROR on unspecified error.
 */
static int zones_journal_apply(knot_zone_t *zone)
{
	/* Fetch zone. */
	if (!zone) {
		return KNOTD_EINVAL;
	}

	knot_zone_contents_t *contents = knot_zone_get_contents(zone);
	zonedata_t *zd = (zonedata_t *)knot_zone_data(zone);
	if (!contents || !zd) {
		return KNOTD_ENOENT;
	}

	/* Fetch SOA serial. */
	const knot_rrset_t *soa_rrs = 0;
	const knot_rdata_t *soa_rr = 0;
	soa_rrs = knot_node_rrset(knot_zone_contents_apex(contents),
	                            KNOT_RRTYPE_SOA);
	assert(soa_rrs != NULL);
	soa_rr = knot_rrset_rdata(soa_rrs);
	int64_t serial_ret = knot_rdata_soa_serial(soa_rr);
	if (serial_ret < 0) {
		return KNOTD_EINVAL;
	}
	uint32_t serial = (uint32_t)serial_ret;

	/* Load all pending changesets. */
	dbg_zones_verb("zones: loading all changesets of '%s' from SERIAL %u\n",
	               zd->conf->name, serial);
	knot_changesets_t* chsets = malloc(sizeof(knot_changesets_t));
	memset(chsets, 0, sizeof(knot_changesets_t));
	/*! \todo Check what should be the upper bound. */
	int ret = zones_load_changesets(zone, chsets, serial, serial - 1);
	if (ret == KNOTD_EOK || ret == KNOTD_ERANGE) {
		if (chsets->count > 0) {
			/* Apply changesets. */
			log_server_info("Applying '%zu' changesets from journal "
			                "to zone '%s'.\n",
			                chsets->count, zd->conf->name);
			knot_zone_contents_t *contents = NULL;
			int apply_ret = xfrin_apply_changesets(zone, chsets,
			                                       &contents);
			if (apply_ret != KNOT_EOK) {
				log_server_error("Failed to apply changesets to"
				                 "'%s' - Apply failed: %s\n",
				                 zd->conf->name,
				                 knot_strerror(apply_ret));
				ret = KNOTD_ERROR;

				// Cleanup old and new contents
				xfrin_rollback_update(zone->contents,
				                      &contents,
				                      &chsets->changes);
			}

			/* Switch zone immediately. */
			apply_ret = xfrin_switch_zone(zone, contents,
			                              XFR_TYPE_IIN);
			if (apply_ret == KNOT_EOK) {
				xfrin_cleanup_successful_update(
				                        &chsets->changes);
			} else {
				log_server_error("Failed to apply changesets to"
				                 " '%s' - Switch failed: %s\n",
				                 zd->conf->name,
				                 knot_strerror(apply_ret));
				ret = KNOTD_ERROR;

				// Cleanup old and new contents
				xfrin_rollback_update(zone->contents,
				                      &contents,
				                      &chsets->changes);
			}
		}
	} else {
		dbg_zones("zones: failed to load changesets - %s\n",
		          knotd_strerror(ret));
	}

	/* Free changesets and return. */
	knot_free_changesets(&chsets);
	return ret;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief Fill the new database with zones.
 *
 * Zones that should be retained are just added from the old database to the
 * new. New zones are loaded.
 *
 * \param ns Name server instance.
 * \param zone_conf Zone configuration.
 * \param db_old Old zone database.
 * \param db_new New zone database.
 *
 * \return Number of inserted zones.
 */
static int zones_insert_zones(knot_nameserver_t *ns,
			      const list *zone_conf,
                              const knot_zonedb_t *db_old,
                              knot_zonedb_t *db_new)
{
	/*! \todo Change to zone contents. */

	node *n = 0;
	int inserted = 0;
	/* for all zones in the configuration */
	WALK_LIST(n, *zone_conf) {
		conf_zone_t *z = (conf_zone_t *)n;

		/* Convert the zone name into a domain name. */
		/* Local allocation, will be discarded. */
		knot_dname_t *zone_name = knot_dname_new_from_str(z->name,
		                                         strlen(z->name), NULL);
		if (zone_name == NULL) {
			log_server_error("Error creating domain name from zone"
			                 " name\n");
			return inserted;
		}

		dbg_zones_verb("zones: inserting zone %s into the new database.\n",
		               z->name);

		/* try to find the zone in the current zone db */
		knot_zone_t *zone = knot_zonedb_find_zone(db_old,
		                                          zone_name);
		int reload = 0;

		/* Attempt to bootstrap if db or source does not exist. */
		struct stat s = {};
		int stat_ret = stat(z->file, &s);
		if (zone != NULL && stat_ret == 0) {
			/* if found, check timestamp of the file against the
			 * loaded zone
			 */
			if (knot_zone_version(zone) < s.st_mtime) {
				/* the file is newer, reload! */
				reload = 1;
			}
		} else {
			reload = 1;
		}

		/* Reload zone file. */
		int ret = KNOTD_ERROR;
		if (reload) {
			/* Zone file not exists and has master set. */
			if (stat_ret < 0 && !EMPTY_LIST(z->acl.xfr_in)) {

				/* Create stub database. */
				dbg_zones_verb("zones: loading stub zone '%s' "
				               "for bootstrap.\n",
				               z->name);
				knot_dname_t *owner = 0;
				owner = knot_dname_deep_copy(zone_name);
				knot_zone_t* sz = knot_zone_new_empty(owner);
				if (sz) {
					/* Add stub zone to db_new. */
					ret = knot_zonedb_add_zone(db_new, sz);
					if (ret != KNOT_EOK) {
						dbg_zones("zones: failed to add "
						          "stub zone '%s'.\n",
						          z->name);
						knot_zone_deep_free(&sz, 0);
						sz = 0;
						ret = KNOTD_ERROR;
					} else {
						log_server_info("Will attempt to "
								"bootstrap zone "
								"%s from AXFR "
								"master.\n",
								z->name);
						--inserted;
					}

				} else {
					dbg_zones("zones: failed to create "
					          "stub zone '%s'.\n",
					          z->name);
					ret = KNOTD_ERROR;
				}

			} else {
				dbg_zones_verb("zones: loading zone '%s' "
				               "from '%s'\n",
				               z->name,
				               z->db);
				ret = zones_load_zone(db_new, z->name,
				                      z->file, z->db);
				if (ret == KNOTD_EOK) {
					log_server_info("Loaded zone '%s'\n",
					                z->name);
				}
			}

			/* Find zone. */
			if (ret == KNOTD_EOK) {
				/* Find the new zone */
				zone = knot_zonedb_find_zone(db_new,
				                             zone_name);
				++inserted;
				
				dbg_zones_verb("zones: inserted '%s' into "
				               "database, initializing data\n",
				               z->name);

				/* Initialize zone-related data. */
				zonedata_init(z, zone);

			}
			/* unused return value, if not loaded, just continue */
		} else {
			/* just insert the zone into the new zone db */
			dbg_zones_verb("zones: found '%s' in old database, "
			               "copying to new.\n",
			               z->name);
			/* Only if zone file exists. */
			if (stat_ret == 0) {
				log_server_info("Zone '%s' is up-to-date, no need "
				                "for reload.\n", z->name);
			}
			int ret = knot_zonedb_add_zone(db_new, zone);
			if (ret != KNOT_EOK) {
				log_server_error("Error adding known zone '%s' to"
				                 " the new database - %s\n",
				                 z->name, knot_strerror(ret));
			} else {
				++inserted;
			}
		}

		/* Update zone data. */
		if (zone) {
			zonedata_t *zd = (zonedata_t *)knot_zone_data(zone);

			/* Update refs. */
			zd->conf = z;

			/* Update ACLs. */
			dbg_zones("Updating zone ACLs.\n");
			zones_set_acl(&zd->xfr_in.acl, &z->acl.xfr_in);
			zones_set_acl(&zd->xfr_out, &z->acl.xfr_out);
			zones_set_acl(&zd->notify_in, &z->acl.notify_in);
			zones_set_acl(&zd->notify_out, &z->acl.notify_out);

			/* Update server pointer. */
			zd->server = (server_t *)knot_ns_get_data(ns);

			/* Update master server address. */
			memset(&zd->xfr_in.tsig_key, 0, sizeof(knot_key_t));
			sockaddr_init(&zd->xfr_in.master, -1);
			sockaddr_init(&zd->xfr_in.via, -1);
			if (!EMPTY_LIST(z->acl.xfr_in)) {
				conf_remote_t *r = HEAD(z->acl.xfr_in);
				conf_iface_t *cfg_if = r->remote;
				sockaddr_set(&zd->xfr_in.master,
					     cfg_if->family,
					     cfg_if->address,
					     cfg_if->port);
				if (cfg_if->via) {
					sockaddr_set(&zd->xfr_in.via,
					             cfg_if->via->family,
					             cfg_if->via->address,
					             0);
				}

				if (cfg_if->key) {
					memcpy(&zd->xfr_in.tsig_key,
					       cfg_if->key,
					       sizeof(knot_key_t));
				}

				dbg_zones("zones: using %s:%d as XFR master "
				          "for '%s'\n",
				          cfg_if->address,
				          cfg_if->port,
				          z->name);
			}

			/* Apply changesets from journal. */
			zones_journal_apply(zone);

			/* Update events scheduled for zone. */
			zones_timers_update(zone, z, 
			             ((server_t *)knot_ns_get_data(ns))->sched);
		}

		/* CLEANUP */
//		knot_zone_contents_dump(knot_zone_get_contents(zone), 1);

		/* Directly discard zone. */
		knot_dname_free(&zone_name);
	}
	return inserted;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief Remove zones present in the configuration from the old database.
 *
 * After calling this function, the old zone database should contain only zones
 * that should be completely deleted.
 *
 * \param zone_conf Zone configuration.
 * \param db_old Old zone database to remove zones from.
 *
 * \retval KNOTD_EOK
 * \retval KNOTD_ERROR
 */
static int zones_remove_zones(const knot_zonedb_t *db_new,
                              knot_zonedb_t *db_old)
{
	const knot_zone_t **new_zones = knot_zonedb_zones(db_new);
	if (new_zones == NULL) {
		return KNOTD_ENOMEM;
	}

	for (int i = 0; i < knot_zonedb_zone_count(db_new); ++i) {
		/* try to find the new zone in the old DB
		 * if the pointers match, remove the zone from old DB
		 */
		/*! \todo Find better way of removing zone with given pointer.*/
		knot_zone_t *old_zone = knot_zonedb_find_zone(
		                        db_old, knot_zone_name(new_zones[i]));
		if (old_zone == new_zones[i]) {
dbg_zones_exec(
			char *name = knot_dname_to_str(knot_zone_name(old_zone));
			dbg_zones_verb("zones: zone pointers match, removing zone %s "
                                       "from database.\n", name);
			free(name);
);
			knot_zone_t * rm = knot_zonedb_remove_zone(db_old,
			                              knot_zone_name(old_zone));
			assert(rm == old_zone);
		}
	}

	free(new_zones);

	return KNOTD_EOK;
}

/*----------------------------------------------------------------------------*/

static int zones_verify_tsig_query(const knot_packet_t *query,
                                   const knot_rrset_t *tsig_rr,
                                   const knot_key_t *key,
                                   knot_rcode_t *rcode, uint16_t *tsig_rcode,
                                   uint64_t *tsig_prev_time_signed)
{
	assert(tsig_rr != NULL);
	assert(key != NULL);
	assert(rcode != NULL);
	assert(tsig_rcode != NULL);

	/*
	 * 1) Check if we support the requested algorithm.
	 */
	tsig_algorithm_t alg = tsig_rdata_alg(tsig_rr);
	if (tsig_alg_digest_length(alg) == 0) {
		log_answer_info("Unsupported digest algorithm "
		                "requested, treating as bad key\n");
		/*! \todo [TSIG] It is unclear from RFC if I
		 *               should treat is as a bad key
		 *               or some other error.
		 */
		*rcode = KNOT_RCODE_NOTAUTH;
		*tsig_rcode = KNOT_TSIG_RCODE_BADKEY;
		return KNOT_TSIG_EBADKEY;
	}

	const knot_dname_t *kname = knot_rrset_owner(tsig_rr);
	assert(kname != NULL);

	/*
	 * 2) Find the particular key used by the TSIG.
	 */
	if (key && kname && knot_dname_compare(key->name, kname) == 0) {
		dbg_zones_verb("Found claimed TSIG key for comparison\n");
	} else {
		*rcode = KNOT_RCODE_NOTAUTH;
		*tsig_rcode = KNOT_TSIG_RCODE_BADKEY;
		return KNOT_TSIG_EBADKEY;
	}

	/*
	 * 3) Validate the query with TSIG.
	 */
	/* Prepare variables for TSIG */
	/*! \todo These need to be saved to the response somehow. */
	//size_t tsig_size = tsig_wire_maxsize(key);
	size_t digest_max_size = tsig_alg_digest_length(key->algorithm);
	//size_t digest_size = 0;
	//uint64_t tsig_prev_time_signed = 0;
	//uint8_t *digest = (uint8_t *)malloc(digest_max_size);
	//memset(digest, 0 , digest_max_size);

	/* Copy MAC from query. */
	dbg_zones_verb("Validating TSIG from query\n");

	//const uint8_t* mac = tsig_rdata_mac(tsig_rr);
	size_t mac_len = tsig_rdata_mac_length(tsig_rr);

	int ret = KNOT_EOK;

	if (mac_len > digest_max_size) {
		*rcode = KNOT_RCODE_FORMERR;
		dbg_zones("MAC length %zu exceeds digest "
		       "maximum size %zu\n", mac_len, digest_max_size);
		return KNOT_EMALF;
	} else {
		//memcpy(digest, mac, mac_len);
		//digest_size = mac_len;

		/* Check query TSIG. */
		ret = knot_tsig_server_check(tsig_rr,
		                             knot_packet_wireformat(query),
		                             knot_packet_size(query), key);
		dbg_zones_verb("knot_tsig_server_check() returned %s\n",
		               knot_strerror(ret));

		/* Evaluate TSIG check results. */
		switch(ret) {
		case KNOT_EOK:
			*rcode = KNOT_RCODE_NOERROR;
			break;
		case KNOT_TSIG_EBADKEY:
			*tsig_rcode = KNOT_TSIG_RCODE_BADKEY;
			*rcode = KNOT_RCODE_NOTAUTH;
			break;
		case KNOT_TSIG_EBADSIG:
			*tsig_rcode = KNOT_TSIG_RCODE_BADSIG;
			*rcode = KNOT_RCODE_NOTAUTH;
			break;
		case KNOT_TSIG_EBADTIME:
			*tsig_rcode = KNOT_TSIG_RCODE_BADTIME;
			// store the time signed from the query
			*tsig_prev_time_signed = tsig_rdata_time_signed(tsig_rr);
			*rcode = KNOT_RCODE_NOTAUTH;
			break;
		case KNOT_EMALF:
			*rcode = KNOT_RCODE_FORMERR;
			break;
		default:
			*rcode = KNOT_RCODE_SERVFAIL;
		}
	}

	return ret;
}

/*----------------------------------------------------------------------------*/

static int zones_check_tsig_query(const knot_zone_t *zone,
                                  knot_packet_t *query,
                                  const sockaddr_t *addr,
                                  knot_rcode_t *rcode,
                                  uint16_t *tsig_rcode,
                                  knot_key_t **tsig_key_zone,
                                  uint64_t *tsig_prev_time_signed)
{
	assert(zone != NULL);
	assert(query != NULL);
	assert(rcode != NULL);
	assert(tsig_key_zone != NULL);

	const knot_rrset_t *tsig = NULL;

	if (knot_packet_additional_rrset_count(query) > 0) {
		/*! \todo warning */
		tsig = knot_packet_additional_rrset(query,
		                 knot_packet_additional_rrset_count(query) - 1);
		if (knot_rrset_type(tsig) == KNOT_RRTYPE_TSIG) {
			dbg_zones_verb("found TSIG in normal query\n");
        } else {
            tsig = NULL; /* Invalidate if not TSIG RRTYPE. */
        }
	}

	if (tsig == NULL) {
		// no TSIG, this is completely valid
		*tsig_rcode = 0;
		return KNOT_EOK;
	}

	// if there is some TSIG in the query, find the TSIG associated with
	// the zone
	//knot_key_t *tsig_key_zone = NULL;

	dbg_zones_verb("Checking zone and ACL.\n");
	int ret = zones_query_check_zone(zone, addr, tsig_key_zone, rcode);

	/*! \todo What if there is TSIG, but no key is configured? */

	if (ret == KNOTD_EOK) {
		if (*tsig_key_zone != NULL) {
			// everything OK, so check TSIG
			dbg_zones_verb("Verifying TSIG.\n");
			ret = zones_verify_tsig_query(query, tsig, *tsig_key_zone,
			                              rcode, tsig_rcode,
			                              tsig_prev_time_signed);
		} else {
			dbg_zones_verb("No key configured for zone.\n");
			// no key configured for zone, return BADKEY
			*tsig_rcode = KNOT_TSIG_RCODE_BADKEY;
			*rcode = KNOT_RCODE_NOTAUTH;
			ret = KNOT_TSIG_EBADKEY;
		}
	}

	// save TSIG RR to query structure
	knot_packet_set_tsig(query, tsig);

	return ret;
}

/*----------------------------------------------------------------------------*/
/* API functions                                                              */
/*----------------------------------------------------------------------------*/

int zones_update_db_from_config(const conf_t *conf, knot_nameserver_t *ns,
                               knot_zonedb_t **db_old)
{
	/* Check parameters */
	if (conf == NULL || ns == NULL) {
		return KNOTD_EINVAL;
	}

	/* Lock RCU to ensure none will deallocate any data under our hands. */
	rcu_read_lock();

	/* Grab a pointer to the old database */
	*db_old = ns->zone_db;
	if (*db_old == NULL) {
		log_server_error("Missing zone database in nameserver structure"
		                 ".\n");
		return KNOTD_ERROR;
	}

	/* Create new zone DB */
	knot_zonedb_t *db_new = knot_zonedb_new();
	if (db_new == NULL) {
		return KNOTD_ERROR;
	}

	log_server_info("Loading %d compiled zones...\n", conf->zones_count);

	/* Insert all required zones to the new zone DB. */
	int inserted = zones_insert_zones(ns, &conf->zones, *db_old, db_new);

	log_server_info("Loaded %d out of %d zones.\n", inserted,
	                conf->zones_count);

	if (inserted != conf->zones_count) {
		log_server_warning("Not all the zones were loaded.\n");
	}

	dbg_zones_detail("zones: old db in nameserver: %p, old db stored: %p, "
	                 "new db: %p\n", ns->zone_db, *db_old, db_new);

	/* Switch the databases. */
	(void)rcu_xchg_pointer(&ns->zone_db, db_new);

	dbg_zones_detail("db in nameserver: %p, old db stored: %p, new db: %p\n",
	                 ns->zone_db, *db_old, db_new);

	/*
	 * Remove all zones present in the new DB from the old DB.
	 * No new thread can access these zones in the old DB, as the
	 * databases are already switched.
	 *
	 * Beware - only the exact same zones (same pointer) may be removed.
	 * All other have been loaded again so that the old must be destroyed.
	 */
	int ret = zones_remove_zones(db_new, *db_old);
	if (ret != KNOTD_EOK) {
		return ret;
	}

	/* Unlock RCU, messing with any data will not affect us now */
	rcu_read_unlock();

	return KNOTD_EOK;
}

int zones_zonefile_sync(knot_zone_t *zone, journal_t *journal)
{
	if (!zone) {
		return KNOTD_EINVAL;
	}
	if (!zone->data) {
		return KNOTD_EINVAL;
	}

	/* Fetch zone data. */
	int ret = KNOTD_EOK;
	zonedata_t *zd = (zonedata_t *)zone->data;

	/* Lock zone data. */
	pthread_mutex_lock(&zd->lock);

	knot_zone_contents_t *contents = knot_zone_get_contents(zone);
	if (!contents) {
		pthread_mutex_unlock(&zd->lock);
		return KNOTD_EINVAL;
	}

	/* Latest zone serial. */
	const knot_rrset_t *soa_rrs = 0;
	const knot_rdata_t *soa_rr = 0;
	soa_rrs = knot_node_rrset(knot_zone_contents_apex(contents),
	                            KNOT_RRTYPE_SOA);
	assert(soa_rrs != NULL);

	soa_rr = knot_rrset_rdata(soa_rrs);
	int64_t serial_ret = knot_rdata_soa_serial(soa_rr);
	if (serial_ret < 0) {
		pthread_mutex_unlock(&zd->lock);
		return KNOTD_EINVAL;
	}
	uint32_t serial_to = (uint32_t)serial_ret;

	/* Check for difference against zonefile serial. */
	if (zd->zonefile_serial != serial_to) {

		/* Save zone to zonefile. */
		conf_read_lock();
		dbg_zones("zones: syncing '%s' differences to '%s' "
		          "(SOA serial %u)\n",
		          zd->conf->name, zd->conf->file, serial_to);
		ret = zones_dump_zone_text(contents, zd->conf->file);
		if (ret != KNOTD_EOK) {
			dbg_zones("zones: failed to sync '%s' to '%s'\n",
			          zd->conf->name, zd->conf->file);
			pthread_mutex_unlock(&zd->lock);
			return ret;
		}
		
		conf_read_unlock();

		/* Update journal entries. */
		dbg_zones_verb("zones: unmarking all dirty nodes "
		               "in '%s' journal\n",
		               zd->conf->name);
		journal_walk(journal, zones_ixfrdb_sync_apply);

		/* Update zone file serial. */
		dbg_zones("zones: new '%s' zonefile serial is %u\n",
		          zd->conf->name, serial_to);
		zd->zonefile_serial = serial_to;
	} else {
		dbg_zones_verb("zones: '%s' zonefile is in sync "
		               "with differences\n", zd->conf->name);
		ret = KNOTD_ERANGE;
	}

	/* Unlock zone data. */
	pthread_mutex_unlock(&zd->lock);

	return ret;
}

/*----------------------------------------------------------------------------*/

int zones_query_check_zone(const knot_zone_t *zone, const sockaddr_t *addr,
                           knot_key_t **tsig_key, knot_rcode_t *rcode)
{
	if (addr == NULL || tsig_key == NULL || rcode == NULL) {
		dbg_zones_verb("Wrong arguments.\n");

		if (rcode != NULL) {
			*rcode = KNOT_RCODE_SERVFAIL;
		}
		return KNOTD_EINVAL;
	}

	/* Check zone data. */
	const zonedata_t *zd = (const zonedata_t *)knot_zone_data(zone);
	if (zd == NULL) {
		dbg_zones("zones: invalid zone data for zone %p\n", zone);
		*rcode = KNOT_RCODE_SERVFAIL;
		return KNOTD_ERROR;
	}

	/* Check xfr-out ACL */
	acl_key_t *match = NULL;
	if (acl_match(zd->xfr_out, addr, &match) == ACL_DENY) {
		log_answer_warning("Unauthorized query or request for XFR "
		                   "'%s/OUT'.\n", zd->conf->name);
		*rcode = KNOT_RCODE_REFUSED;
		return KNOTD_EACCES;
	} else {
		dbg_zones("zones: authorized query or request for XFR "
		          "'%s/OUT'. match=%p\n", zd->conf->name, match);
		if (match) {
			/* Save configured TSIG key for comparison. */
			conf_iface_t *iface = (conf_iface_t*)(match->val);
			dbg_zones_detail("iface=%p, iface->key=%p\n",
					 iface, iface->key);
			*tsig_key = iface->key;
		}
	}
	return KNOTD_EOK;
}

/*----------------------------------------------------------------------------*/

int zones_xfr_check_zone(knot_ns_xfr_t *xfr, knot_rcode_t *rcode)
{
	if (xfr == NULL || rcode == NULL) {
		return KNOTD_EINVAL;
	}

	/* Check if the zone is found. */
	if (xfr->zone == NULL) {
		*rcode = KNOT_RCODE_REFUSED;
		return KNOTD_EACCES;
	}

	/* Check zone contents. */
	if (knot_zone_contents(xfr->zone) == NULL) {
		dbg_zones("zones: invalid zone contents for zone %p\n",
		          xfr->zone);
		*rcode = KNOT_RCODE_SERVFAIL;
		return KNOTD_EEXPIRED;
	}

	return zones_query_check_zone(xfr->zone, &xfr->addr, &xfr->tsig_key,
	                              rcode);
}

/*----------------------------------------------------------------------------*/

int zones_normal_query_answer(knot_nameserver_t *nameserver,
                              knot_packet_t *query, const sockaddr_t *addr,
                              uint8_t *resp_wire, size_t *rsize)
{
	rcu_read_lock();

	knot_packet_t *resp = NULL;
	const knot_zone_t *zone = NULL;

	dbg_zones_verb("Preparing response structure.\n");
	int ret = knot_ns_prep_normal_response(nameserver, query, &resp, &zone);

	// check for TSIG in the query
	if (knot_packet_additional_rrset_count(query) > 0) {
		/*! \todo warning */
		const knot_rrset_t *tsig = knot_packet_additional_rrset(query,
		                 knot_packet_additional_rrset_count(query) - 1);
		if (knot_rrset_type(tsig) == KNOT_RRTYPE_TSIG) {
			dbg_zones_verb("found TSIG in normal query\n");
			knot_packet_set_tsig(query, tsig);
		}
	}

	knot_rcode_t rcode = 0;

	switch (ret) {
	case KNOT_EOK:
		rcode = KNOT_RCODE_NOERROR;
		break;
	case KNOT_EMALF:
		// no TSIG signing in this case
		rcode = KNOT_RCODE_FORMERR;
		break;
	default:
		// no TSIG signing in this case
		rcode = KNOT_RCODE_SERVFAIL;
		break;
	}

	if (zone == NULL && knot_packet_tsig(query) == NULL) {
		/*! \todo If there is TSIG, this should be probably handled
		 *        as a key error.
		 */
		rcode = KNOT_RCODE_REFUSED;
	}

	if (rcode != KNOT_RCODE_NOERROR) {
		dbg_zones_verb("Failed preparing response structure: %s.\n",
		               knot_strerror(rcode));
		if (resp == NULL) {
			knot_ns_error_response(nameserver, knot_packet_id(query),
					      rcode, resp_wire, rsize);
			rcu_read_unlock();
			return KNOT_EOK;
		}
		knot_ns_error_response_full(nameserver, resp, rcode, resp_wire,
		                            rsize);
//		knot_ns_error_response(nameserver, knot_packet_id(query),
//		                       rcode, resp_wire, rsize);
	} else {
		/*
		 * Now we have zone. Verify TSIG if it is in the packet.
		 */
		assert(resp != NULL);
		assert(rcode == KNOT_RCODE_NOERROR);
		uint16_t tsig_rcode = 0;
		knot_key_t *tsig_key_zone = NULL;
        uint64_t tsig_prev_time_signed = 0; /*! \todo Verify, as it was uninitialized! */

		size_t answer_size = *rsize;
		int ret = KNOT_EOK;

		if (zone == NULL) {
			assert(knot_packet_tsig(query) != NULL);
			// treat as BADKEY error
			rcode = KNOT_RCODE_NOTAUTH;
			tsig_rcode = KNOT_TSIG_RCODE_BADKEY;
			ret = KNOT_TSIG_EBADKEY;
		} else {
			dbg_zones_verb("Checking TSIG in query.\n");
			ret = zones_check_tsig_query(zone, query, addr,
			                             &rcode, &tsig_rcode,
			                             &tsig_key_zone,
			                             &tsig_prev_time_signed);
		}

		if (ret == KNOT_EOK) {
			dbg_zones_verb("TSIG check successful. Answering "
			               "query.\n");
			assert(tsig_rcode == 0);

			// reserve place for the TSIG
			if (tsig_key_zone != NULL) {
				size_t tsig_max_size =
				         tsig_wire_maxsize(tsig_key_zone);
				knot_packet_set_tsig_size(resp, tsig_max_size);
			}
			ret = knot_ns_answer_normal(nameserver, zone, resp,
			                            resp_wire, &answer_size);

			dbg_zones_detail("rsize = %zu\n", *rsize);
			dbg_zones_detail("answer_size = %zu\n", answer_size);

			assert(ret == KNOT_EOK);

			// sign the message
			if (tsig_key_zone != NULL) {
				dbg_zones_verb("Signing message with TSIG.\n");
				// TODO check
				//*rsize = answer_size;

				const knot_rrset_t *tsig =
				      knot_packet_tsig(knot_packet_query(resp));

				size_t digest_max_size =
				                tsig_alg_digest_length(
				                      tsig_key_zone->algorithm);
				uint8_t *digest = (uint8_t *)malloc(
				                        digest_max_size);
				if (digest == NULL) {
					knot_packet_free(&resp);
					rcu_read_unlock();
					return KNOT_ENOMEM;
				}
				size_t digest_size = digest_max_size;

				ret = knot_tsig_sign(resp_wire, &answer_size,
				               *rsize, tsig_rdata_mac(tsig),
				               tsig_rdata_mac_length(tsig),
				               digest, &digest_size,
				               tsig_key_zone, tsig_rcode,
				               tsig_prev_time_signed);
				
				free(digest);

				dbg_zones_detail("answer_size = %zu\n",
				                 answer_size);

				if (ret != KNOT_EOK) {
					dbg_zones_verb("Failed to sign message:"
					            "%s\n", knot_strerror(ret));
					rcode = KNOT_RCODE_SERVFAIL;
				} else {
					*rsize = answer_size;
				}
			} else {
				*rsize = answer_size;
			}
		} else {
			dbg_zones_verb("Failed TSIG check: %s, TSIG err: %u.\n",
			               knot_strerror(ret), tsig_rcode);

			if (tsig_rcode != 0) {
				dbg_zones_verb("Sending TSIG error.\n");
				// first, convert the response to wire format
				answer_size = *rsize;
				knot_response_set_rcode(resp, rcode);

				ret = ns_response_to_wire(resp, resp_wire,
				                          &answer_size);

				dbg_zones_detail("Packet to wire returned %d\n",
				                 ret);

				// then add the TSIG to the wire format
				if (ret == KNOT_EOK &&
				    tsig_rcode != KNOT_TSIG_RCODE_BADTIME) {
					dbg_zones_verb("Adding TSIG.\n");
					ret = knot_tsig_add(resp_wire,
					                    &answer_size,
					                    *rsize, tsig_rcode,
					                     knot_packet_tsig(
					                            query));

					*rsize = answer_size;

				} else if (tsig_rcode
				           == KNOT_TSIG_RCODE_BADTIME) {
					dbg_zones_verb("Signing error resp.\n");
					//*rsize = answer_size;

					const knot_rrset_t *tsig =
					      knot_packet_tsig(
					          knot_packet_query(resp));

					size_t digest_max_size =
					           tsig_alg_digest_length(
					              tsig_key_zone->algorithm);
					uint8_t *digest = (uint8_t *)malloc(
					                       digest_max_size);
					if (digest == NULL) {
						knot_packet_free(&resp);
						rcu_read_unlock();
						return KNOT_ENOMEM;
					}
					size_t digest_size = digest_max_size;

					ret = knot_tsig_sign(resp_wire,
					    &answer_size, *rsize,
					    tsig_rdata_mac(tsig),
					    tsig_rdata_mac_length(tsig),
					    digest, &digest_size, tsig_key_zone,
					    tsig_rcode, tsig_prev_time_signed);

					*rsize = answer_size;
				} else {
					dbg_zones_verb("Failed.\n");
					rcode = KNOT_RCODE_SERVFAIL;
				}
			}
			// in other case the RCODE is set and ret != KNOT_EOK
			// and a normal error is returned below
		}

		if (ret != KNOT_EOK) {
			knot_ns_error_response_full(nameserver, resp,
			                            rcode, resp_wire,
			                            rsize);
		}
	}

	knot_packet_free(&resp);
	rcu_read_unlock();

	return KNOT_EOK;
}

/*----------------------------------------------------------------------------*/

int zones_process_response(knot_nameserver_t *nameserver, 
                           sockaddr_t *from,
                           knot_packet_t *packet, uint8_t *response_wire,
                           size_t *rsize)
{
	if (!packet || !rsize || nameserver == NULL || from == NULL ||
	    response_wire == NULL) {
		return KNOTD_EINVAL;
	}
	
	/* Declare no response. */
	*rsize = 0;

	/* Handle SOA query response, cancel EXPIRE timer
	 * and start AXFR transfer if needed.
	 * Reset REFRESH timer on finish.
	 */
	if (knot_packet_qtype(packet) == KNOT_RRTYPE_SOA) {
		
		if (knot_packet_rcode(packet) != KNOT_RCODE_NOERROR) {
			/*! \todo Handle error response. */
			return KNOTD_ERROR;
		}

		/* Find matching zone and ID. */
		const knot_dname_t *zone_name = knot_packet_qname(packet);
		/*! \todo Change the access to the zone db. */
		knot_zone_t *zone = knot_zonedb_find_zone(
		                        nameserver->zone_db,
		                        zone_name);

		/* Get zone contents. */
		rcu_read_lock();
		const knot_zone_contents_t *contents =
				knot_zone_contents(zone);

		if (!zone || !knot_zone_data(zone) || !contents) {
			rcu_read_unlock();
			return KNOTD_EINVAL;
		}

		/* Match ID against awaited. */
		zonedata_t *zd = (zonedata_t *)knot_zone_data(zone);
		uint16_t pkt_id = knot_packet_id(packet);
		if ((int)pkt_id != zd->xfr_in.next_id) {
			rcu_read_unlock();
			return KNOTD_ERROR;
		}

		/* Check SOA SERIAL. */
		int ret = xfrin_transfer_needed(contents, packet);
		dbg_zones_verb("xfrin_transfer_needed() returned %s\n",
		               knot_strerror(ret));
		if (ret < 0) {
			/* RETRY/EXPIRE timers running, do not interfere. */
			rcu_read_unlock();
			return KNOTD_ERROR;
		}
		
		/* No updates available. */
		evsched_t *sched =
			((server_t *)knot_ns_get_data(nameserver))->sched;
		if (ret == 0) {
			char r_addr[SOCKADDR_STRLEN];
			int r_port = sockaddr_portnum(from);
			sockaddr_tostr(from, r_addr, sizeof(r_addr));
			log_zone_info("SOA query of '%s' to %s:%d: Answered, no "
				      "transfer needed.\n",
			              zd->conf->name, r_addr, r_port);
			rcu_read_unlock();

			/* Reinstall timers. */
			zones_timers_update(zone, zd->conf, sched);
			return KNOTD_EOK;
		}
		
		assert(ret > 0);
		
		/* Already transferring. */
		if (pthread_mutex_trylock(&zd->xfr_in.lock) != 0) {
			/* Unlock zone contents. */
			dbg_zones("zones: SOA response received, but zone is "
			          "being transferred, refusing to start another "
			          "transfer\n");
			rcu_read_unlock();
			return KNOTD_EOK;
		} else {
			pthread_mutex_unlock(&zd->xfr_in.lock);
		}

		/* Prepare XFR client transfer. */
		knot_ns_xfr_t xfr_req;
		memset(&xfr_req, 0, sizeof(knot_ns_xfr_t));
		memcpy(&xfr_req.addr, &zd->xfr_in.master, sizeof(sockaddr_t));
		memcpy(&xfr_req.saddr, &zd->xfr_in.via, sizeof(sockaddr_t));
		xfr_req.zone = (void *)zone;
		xfr_req.send = zones_send_cb;

		/* Select transfer method. */
		xfr_req.type = zones_transfer_to_use(contents);
		
		/* Select TSIG key. */
		if (zd->xfr_in.tsig_key.name) {
			xfr_req.tsig_key = &zd->xfr_in.tsig_key;
		}

		/* Unlock zone contents. */
		rcu_read_unlock();

		/* Enqueue XFR request. */
		return xfr_request(((server_t *)knot_ns_get_data(
		                     nameserver))->xfr_h, &xfr_req);
	}

	return KNOTD_EOK;
}

/*----------------------------------------------------------------------------*/

knot_ns_xfr_type_t zones_transfer_to_use(const knot_zone_contents_t *zone)
{
	/*! \todo Implement. */
	return XFR_TYPE_IIN;
}

/*----------------------------------------------------------------------------*/

static int zones_find_zone_for_xfr(const knot_zone_contents_t *zone, 
                                   const char **zonefile, const char **zonedb)
{
	/* find the zone file name and zone db file name for the zone */
	conf_t *cnf = conf();
	node *n = NULL;
	WALK_LIST(n, cnf->zones) {
		conf_zone_t *zone_conf = (conf_zone_t *)n;
		knot_dname_t *zone_name = knot_dname_new_from_str(
			zone_conf->name, strlen(zone_conf->name), NULL);
		if (zone_name == NULL) {
			return KNOTD_ENOMEM;
		}

		int r = knot_dname_compare(zone_name, knot_node_owner(
		                              knot_zone_contents_apex(zone)));

		/* Directly discard dname, won't be needed. */
		knot_dname_free(&zone_name);

		if (r == 0) {
			/* found the right zone */
			*zonefile = zone_conf->file;
			*zonedb = zone_conf->db;
			return KNOTD_EOK;
		}
	}

	char *name = knot_dname_to_str(knot_node_owner(
	                 knot_zone_contents_apex(zone)));
	dbg_zones("zones: no zone found for the zone received by transfer "
	          "(%s).\n", name);
	free(name);

	return KNOTD_ENOENT;
}

/*----------------------------------------------------------------------------*/

static int zones_open_free_filename(const char *old_name, char **new_name)
{
	/* find zone name not present on the disk */
	size_t name_size = strlen(old_name);
	*new_name = malloc(name_size + 7 + 1);
	if (*new_name == NULL) {
		return -1;
	}
	memcpy(*new_name, old_name, name_size + 1);
	strncat(*new_name, ".XXXXXX", 7);
	dbg_zones_verb("zones: creating temporary zone file\n");
	mode_t old_mode = umask(077);
	int fd = mkstemp(*new_name);
	(void) umask(old_mode);
	if (fd < 0) {
		dbg_zones_verb("zones: couldn't create temporary zone file\n");
		free(*new_name);
		*new_name = NULL;
	}
	
	return fd;
}

/*----------------------------------------------------------------------------*/

static int zones_dump_zone_text(knot_zone_contents_t *zone, const char *fname)
{
	assert(zone != NULL && fname != NULL);

	char *new_fname = NULL;
	int fd = zones_open_free_filename(fname, &new_fname);
	if (fd < 0) {
		log_zone_warning("Failed to find filename for temporary "
		                 "storage of the transferred zone.\n");
		return KNOTD_ERROR;
	}
	
	if (zone_dump_text(zone, fd) != KNOTD_EOK) {
		log_zone_warning("Failed to save the transferred zone to '%s'.\n",
		                 new_fname);
		close(fd);
		unlink(new_fname);
		free(new_fname);
		return KNOTD_ERROR;
	}

	/* Swap temporary zonefile and new zonefile. */
	close(fd);
	int ret = rename(new_fname, fname);
	if (ret < 0 && ret != EEXIST) {
		log_zone_warning("Failed to replace old zone file '%s'' with a new"
		                 " zone file '%s'.\n", fname, new_fname);
		unlink(new_fname);
		free(new_fname);
		return KNOTD_ERROR;
	}


	free(new_fname);
	return KNOTD_EOK;
}

/*----------------------------------------------------------------------------*/

static int zones_dump_zone_binary(knot_zone_contents_t *zone, 
                                   const char *zonedb,
                                   const char *zonefile)
{
	assert(zone != NULL && zonedb != NULL);

	char *new_zonedb = NULL;
	int fd = zones_open_free_filename(zonedb, &new_zonedb);
	if (fd < 0) {
		dbg_zones("zones: failed to find free filename for temporary "
		          "storage of the zone binary file '%s'\n",
		          zonedb);
		return KNOTD_ERROR;
	}

	crc_t crc_value;
	if (knot_zdump_dump(zone, fd, zonefile, &crc_value) != KNOT_EOK) {
		close(fd);
		unlink(new_zonedb);
		free(new_zonedb);
		return KNOTD_ERROR;
	}

	/* Delete old CRC file. */
	char *zonedb_crc = knot_zdump_crc_file(zonedb);
	if (zonedb_crc == NULL) {
		close(fd);
		unlink(new_zonedb);
		free(new_zonedb);
		return KNOTD_ENOMEM;
	}
	remove(zonedb_crc);

	/* New CRC file. */
	char *new_zonedb_crc = knot_zdump_crc_file(new_zonedb);
	if (new_zonedb_crc == NULL) {
		dbg_zdump("Failed to create CRC file path from %s.\n",
		          new_zonedb);
		free(zonedb_crc);
		close(fd);
		unlink(new_zonedb);
		free(new_zonedb);
		return KNOTD_ENOMEM;
	}

	/* Write CRC value to CRC file. */
	FILE *f_crc = fopen(new_zonedb_crc, "w");
	if (f_crc == NULL) {
		dbg_zdump("Cannot open CRC file %s!\n",
		          zonedb_crc);
		unlink(new_zonedb);
		return KNOTD_ERROR;
	} else {
		fprintf(f_crc, "%lu\n",
		        (unsigned long)crc_value);
		fclose(f_crc);
	}

	/* Swap CRC files. */
	int ret = KNOTD_EOK;
	if (rename(new_zonedb_crc, zonedb_crc) < 0) {
		dbg_zdump("Failed to replace old zonedb CRC %s "
		          "with new CRC zone file %s.\n",
		          zonedb_crc,
		          new_zonedb_crc);
		unlink(new_zonedb);
		unlink(new_zonedb_crc);
		ret = KNOTD_ERROR;
	} else {
		/* Swap zone databases. */
		int swap_res = rename(new_zonedb, zonedb);
		if (swap_res < 0 && swap_res != EEXIST) {
			dbg_zdump("Failed to replace old zonedb %s "
			          "with new zone file %s.\n",
			          new_zonedb,
			          zonedb);
			ret = KNOTD_ERROR;
			unlink(new_zonedb);
		} else {

		}
	}

	free(new_zonedb_crc);
	free(zonedb_crc);
	close(fd);
	free(new_zonedb);


	return ret;
}

/*----------------------------------------------------------------------------*/

int zones_save_zone(const knot_ns_xfr_t *xfr)
{
	if (xfr == NULL || xfr->new_contents == NULL) {
		return KNOTD_EINVAL;
	}
	
	knot_zone_contents_t *zone = xfr->new_contents;
	
	const char *zonefile = NULL;
	const char *zonedb = NULL;
	
	int ret = zones_find_zone_for_xfr(zone, &zonefile, &zonedb);
	if (ret != KNOTD_EOK) {
		return ret;
	}
	
	assert(zonefile != NULL && zonedb != NULL);
	
	/* dump the zone into text zone file */
	ret = zones_dump_zone_text(zone, zonefile);
	if (ret != KNOTD_EOK) {
		return KNOTD_ERROR;
	}
	/* dump the zone into binary db file */
	ret = zones_dump_zone_binary(zone, zonedb, zonefile);
	if (ret != KNOTD_EOK) {
		return KNOTD_ERROR;
	}
	
	return KNOTD_EOK;
}

/*----------------------------------------------------------------------------*/

int zones_ns_conf_hook(const struct conf_t *conf, void *data)
{
	knot_nameserver_t *ns = (knot_nameserver_t *)data;
	dbg_zones_verb("zones: reconfiguring name server.\n");
	
	/* Set NSID. */
	knot_ns_set_nsid(ns, conf->nsid, conf->nsid_len);

	knot_zonedb_t *old_db = 0;

	int ret = zones_update_db_from_config(conf, ns, &old_db);
	if (ret != KNOTD_EOK) {
		return ret;
	}
	/* Wait until all readers finish with reading the zones. */
	synchronize_rcu();

	dbg_zones_verb("zones: nameserver's zone db: %p, old db: %p\n",
	               ns->zone_db, old_db);

	/* Delete all deprecated zones and delete the old database. */
	knot_zonedb_deep_free(&old_db);

	return KNOTD_EOK;
}

/*----------------------------------------------------------------------------*/

static int zones_check_binary_size(uint8_t **data, size_t *allocated,
                                   size_t required)
{
	if (required <= *allocated) {
		return KNOTD_EOK;
	}

	/* Allocate new memory block. */
	size_t new_count = required;
	uint8_t *new_data = malloc(new_count * sizeof(uint8_t));
	if (new_data == NULL) {
		return KNOTD_ENOMEM;
	}

	/* Clear memory block and copy old data. */
	memset(new_data, 0, new_count * sizeof(uint8_t));
	memcpy(new_data, *data, *allocated);

	/* Switch pointers and free old pointer. */
	free(*data);
	*data = new_data;
	*allocated = new_count;

	return KNOTD_EOK;
}

/*----------------------------------------------------------------------------*/

static int zones_changeset_rrset_to_binary(uint8_t **data, size_t *size,
                                           size_t *allocated,
                                           knot_rrset_t *rrset)
{
	assert(data != NULL);
	assert(size != NULL);
	assert(allocated != NULL);

	/*
	 * In *data, there is the whole changeset in the binary format,
	 * the actual RRSet will be just appended to it
	 */

	uint8_t *binary = NULL;
	size_t actual_size = 0;
	int ret = knot_zdump_rrset_serialize(rrset, &binary, &actual_size);
	if (ret != KNOT_EOK || binary == NULL) {
		dbg_zones("knot_zdump_rrset_serialize() returned %s\n",
		          knot_strerror(ret));
		return KNOTD_ERROR;  /*! \todo Other code? */
	}

	ret = zones_check_binary_size(data, allocated, *size + actual_size);
	if (ret != KNOTD_EOK) {
		free(binary);
		return ret;
	}

	memcpy(*data + *size, binary, actual_size);
	*size += actual_size;
	free(binary);

	return KNOTD_EOK;
}

/*----------------------------------------------------------------------------*/

int zones_changesets_to_binary(knot_changesets_t *chgsets)
{
	assert(chgsets != NULL);
	assert(chgsets->allocated >= chgsets->count);

	/*
	 * Converts changesets to the binary format stored in chgsets->data
	 * from the changeset_t structures.
	 */
	int ret;

	for (int i = 0; i < chgsets->count; ++i) {
		knot_changeset_t *ch = &chgsets->sets[i];
		assert(ch->data == NULL);
		assert(ch->size == 0);

		/* 1) origin SOA */
		ret = zones_changeset_rrset_to_binary(&ch->data, &ch->size,
		                                &ch->allocated, ch->soa_from);
		if (ret != KNOTD_EOK) {
			free(ch->data);
			ch->data = NULL;
			dbg_zones("zones_changeset_rrset_to_binary(): %s\n",
			          knot_strerror(ret));
			return ret;
		}

		int j;

		/* 2) remove RRsets */
		assert(ch->remove_allocated >= ch->remove_count);
		for (j = 0; j < ch->remove_count; ++j) {
			ret = zones_changeset_rrset_to_binary(&ch->data,
			                                      &ch->size,
			                                      &ch->allocated,
			                                      ch->remove[j]);
			if (ret != KNOTD_EOK) {
				free(ch->data);
				ch->data = NULL;
				dbg_zones("zones_changeset_rrset_to_binary(): %s\n",
					  knot_strerror(ret));
				return ret;
			}
		}

		/* 3) new SOA */
		ret = zones_changeset_rrset_to_binary(&ch->data, &ch->size,
		                                &ch->allocated, ch->soa_to);
		if (ret != KNOTD_EOK) {
			free(ch->data);
			ch->data = NULL;
			dbg_zones("zones_changeset_rrset_to_binary(): %s\n",
				  knot_strerror(ret));
			return ret;
		}

		/* 4) add RRsets */
		assert(ch->add_allocated >= ch->add_count);
		for (j = 0; j < ch->add_count; ++j) {
			ret = zones_changeset_rrset_to_binary(&ch->data,
			                                      &ch->size,
			                                      &ch->allocated,
			                                      ch->add[j]);
			if (ret != KNOTD_EOK) {
				free(ch->data);
				ch->data = NULL;
				dbg_zones("zones_changeset_rrset_to_binary(): %s\n",
					  knot_strerror(ret));
				return ret;
			}
		}
	}

	return KNOTD_EOK;
}

/*----------------------------------------------------------------------------*/

int zones_store_changesets(knot_ns_xfr_t *xfr)
{
	if (xfr == NULL || xfr->data == NULL || xfr->zone == NULL) {
		return KNOTD_EINVAL;
	}
	
	knot_zone_t *zone = xfr->zone;
	knot_changesets_t *src = (knot_changesets_t *)xfr->data;

	/* Fetch zone-specific data. */
	zonedata_t *zd = (zonedata_t *)zone->data;
	if (!zd->ixfr_db) {
		return KNOTD_EINVAL;
	}

	/* Retain journal for changeset loading. */
	journal_t *j = journal_retain(zd->ixfr_db);
	
	/* Begin writing to journal. */
	for (unsigned i = 0; i < src->count; ++i) {

		/* Make key from serials. */
		knot_changeset_t* chs = src->sets + i;
		uint64_t k = ixfrdb_key_make(chs->serial_from, chs->serial_to);

		/* Write entry. */
		int ret = journal_write(j, k, (const char*)chs->data, chs->size);

		/* Check for errors. */
		while (ret != KNOTD_EOK) {

			/* Sync to zonefile may be needed. */
			if (ret == KNOTD_EAGAIN) {

				/* Cancel sync timer. */
				event_t *tmr = zd->ixfr_dbsync;
				if (tmr) {
					dbg_xfr_verb("xfr: cancelling zonefile "
					             "SYNC timer of '%s'\n",
					             zd->conf->name);
					evsched_cancel(tmr->parent, tmr);
				}

				/* Synchronize. */
				dbg_xfr_verb("xfr: forcing zonefile SYNC "
				             "of '%s'\n",
				             zd->conf->name);
				ret = zones_zonefile_sync(zone, j);
				if (ret != KNOTD_EOK && ret != KNOTD_ERANGE) {
					continue;
				}

				/* Reschedule sync timer. */
				if (tmr) {
					/* Fetch sync timeout. */
					conf_read_lock();
					int timeout = zd->conf->dbsync_timeout;
					timeout *= 1000; /* Convert to ms. */
					conf_read_unlock();

					/* Reschedule. */
					dbg_xfr_verb("xfr: resuming SYNC "
					             "of '%s'\n",
					             zd->conf->name);
					evsched_schedule(tmr->parent, tmr,
					                 timeout);

				}

				/* Attempt to write again. */
				ret = journal_write(j, k, (const char*)chs->data,
						    chs->size);
			} else {
				/* Other errors. */
				journal_release(j);
				return KNOTD_ERROR;
			}
		}

		/* Free converted binary data. */
		free(chs->data);
		chs->data = 0;
		chs->size = 0;
	}
	
	/* Release journal. */
	journal_release(j);

	/* Written changesets to journal. */
	return KNOTD_EOK;
}

/*----------------------------------------------------------------------------*/

int zones_xfr_load_changesets(knot_ns_xfr_t *xfr, uint32_t serial_from,
                              uint32_t serial_to) 
{
	if (!xfr || !xfr->zone || !knot_zone_contents(xfr->zone)) {
		dbg_zones_detail("Wrong parameters: xfr=%p,"
		                " xfr->zone = %p\n", xfr, xfr->zone);
		return KNOTD_EINVAL;
	}
	
	knot_changesets_t *chgsets = (knot_changesets_t *)
	                               calloc(1, sizeof(knot_changesets_t));
	CHECK_ALLOC_LOG(chgsets, KNOTD_ENOMEM);
	
	int ret = ns_serial_compare(serial_to, serial_from);
	dbg_zones_verb("Compared serials, result: %d\n", ret);
	
	/* if serial_to is not larger than serial_from, do not load anything */
	if (ret <= 0) {
		xfr->data = chgsets;
		return KNOTD_EOK;
	}
	
	dbg_zones("Loading changesets...\n");
	
	ret = zones_load_changesets(xfr->zone, chgsets,
	                                serial_from, serial_to);
	if (ret != KNOTD_EOK) {
		dbg_zones_verb("Loading changesets failed: %s\n",
		               knotd_strerror(ret));
		knot_free_changesets(&chgsets);
		return ret;
	}
	
	xfr->data = chgsets;
	return KNOTD_EOK;
}

/*----------------------------------------------------------------------------*/

int zones_timers_update(knot_zone_t *zone, conf_zone_t *cfzone, evsched_t *sch)
{
	if (!sch || !zone) {
		return KNOTD_EINVAL;
	}

	/* Fetch zone data. */
	zonedata_t *zd = (zonedata_t *)zone->data;
	if (!zd) {
		return KNOTD_EINVAL;
	}

	/* Cancel REFRESH timer. */
	if (zd->xfr_in.timer) {
		evsched_cancel(sch, zd->xfr_in.timer);
		evsched_event_free(sch, zd->xfr_in.timer);
		zd->xfr_in.timer = 0;
	}

	/* Cancel EXPIRE timer. */
	if (zd->xfr_in.expire) {
		evsched_cancel(sch, zd->xfr_in.expire);
		evsched_event_free(sch, zd->xfr_in.expire);
		zd->xfr_in.expire = 0;
	}

	/* Remove list of pending NOTIFYs. */
	pthread_mutex_lock(&zd->lock);
	notify_ev_t *ev = 0, *evn = 0;
	WALK_LIST_DELSAFE(ev, evn, zd->notify_pending) {
		zones_cancel_notify(zd, ev);
	}
	pthread_mutex_unlock(&zd->lock);

	/* Check XFR/IN master server. */
	if (zd->xfr_in.master.ptr) {

		/* Schedule REFRESH timer. */
		uint32_t refresh_tmr = 0;
		if (knot_zone_contents(zone)) {
			refresh_tmr = zones_soa_refresh(zone);
		} else {
			refresh_tmr = zd->xfr_in.bootstrap_retry;
		}
		zd->xfr_in.timer = evsched_schedule_cb(sch, zones_refresh_ev,
							 zone, refresh_tmr);
		dbg_zones("zone: REFRESH set to %u\n", refresh_tmr);
	}

	/* Schedule IXFR database syncing. */
	/*! \todo Sync timer should not be reset after each xfr (issue #1348) */
	int sync_timeout = cfzone->dbsync_timeout * 1000; /* Convert to ms. */
	if (zd->ixfr_dbsync) {
		evsched_cancel(sch, zd->ixfr_dbsync);
		evsched_event_free(sch, zd->ixfr_dbsync);
		zd->ixfr_dbsync = 0;
	}
	if (zd->ixfr_db) {
		zd->ixfr_dbsync = evsched_schedule_cb(sch,
		                                      zones_zonefile_sync_ev,
		                                      zone, sync_timeout);
	}

	/* Do not issue NOTIFY queries if stub. */
	if (!knot_zone_contents(zone)) {
		conf_read_unlock();
		return KNOTD_EOK;
	}

	/* Schedule NOTIFY to slaves. */
	conf_remote_t *r = 0;
	conf_read_lock();
	WALK_LIST(r, cfzone->acl.notify_out) {

		/* Fetch remote. */
		conf_iface_t *cfg_if = r->remote;

		/* Create request. */
		notify_ev_t *ev = malloc(sizeof(notify_ev_t));
		if (!ev) {
			free(ev);
			dbg_zones("notify: out of memory to create "
				    "NOTIFY query for %s\n", cfg_if->name);
			continue;
		}

		/* Parse server address. */
		sockaddr_init(&ev->saddr, -1);
		int ret = sockaddr_set(&ev->addr, cfg_if->family,
				       cfg_if->address,
				       cfg_if->port);
		conf_iface_t *via = cfg_if->via;
		if (ret > 0 && via != NULL) {
			ret = sockaddr_set(&ev->saddr, via->family,
			                   via->address, 0);
		}
		if (ret < 1) {
			free(ev);
			dbg_zones("notify: NOTIFY slave %s has invalid "
				    "address\n", cfg_if->name);
			continue;
		}

		/* Prepare request. */
		ev->retries = cfzone->notify_retries + 1; /* first + N retries*/
		ev->msgid = 0;
		ev->zone = zone;
		ev->timeout = cfzone->notify_timeout;

		/* Schedule request (30 - 60s random delay). */
		int tmr_s = 30 + (int)(30.0 * tls_rand());
		pthread_mutex_lock(&zd->lock);
		ev->timer = evsched_schedule_cb(sch, zones_notify_send, ev,
						tmr_s * 1000);
		add_tail(&zd->notify_pending, &ev->n);
		pthread_mutex_unlock(&zd->lock);

		log_server_info("Scheduled '%s' NOTIFY query "
				"after %d s to %s:%d\n", zd->conf->name,
			    tmr_s, cfg_if->address, cfg_if->port);
	}

	conf_read_unlock();

	return KNOTD_EOK;
}

int zones_cancel_notify(zonedata_t *zd, notify_ev_t *ev)
{
	if (!zd || !ev || !ev->timer) {
		return KNOTD_EINVAL;
	}

	/* Wait for event to finish running. */
#ifdef KNOTD_NOTIFY_DEBUG
	int pkt_id = ev->msgid; /*< Do not optimize! */
#endif
	event_t *tmr = ev->timer;
	ev->timer = 0;
	pthread_mutex_unlock(&zd->lock);
	evsched_cancel(tmr->parent, tmr);

	/* Re-lock and find again (if not deleted). */
	pthread_mutex_lock(&zd->lock);
	int match_exists = 0;
	notify_ev_t *tmpev = 0;
	WALK_LIST(tmpev, zd->notify_pending) {
		if (tmpev == ev) {
			match_exists = 1;
			break;
		}
	}

	/* Event deleted before cancelled. */
	if (!match_exists) {
		dbg_notify("notify: NOTIFY event for query ID=%u was "
		           "deleted before cancellation.\n",
		           pkt_id);
		return KNOTD_EOK;

	}

	/* Free event (won't be scheduled again). */
	dbg_notify("notify: NOTIFY query ID=%u event cancelled.\n",
	           pkt_id);
	rem_node(&ev->n);
	evsched_event_free(tmr->parent, tmr);
	free(ev);
	return KNOTD_EOK;
}