File: rollerd

package info (click to toggle)
dnssec-tools 1.13-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 16,064 kB
  • sloc: perl: 44,399; ansic: 31,547; cpp: 21,306; sh: 15,813; xml: 2,113; makefile: 1,390; pascal: 836; python: 290; csh: 11
file content (7689 lines) | stat: -rwxr-xr-x 195,168 bytes parent folder | download
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
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
#!/usr/bin/perl
#
# Copyright 2005-2012 SPARTA, Inc.  All rights reserved.  See the COPYING
# file distributed with this software for details.
#
#
# rollerd
#
#	This script manages the key rollover process.
#
#	ZSK rollover uses the Pre-Publish Method of rollover and takes
#	place in four phases:
#		- wait until it's time to perform a ZSK rollover
#		- sign the zone with the KSK and Published ZSK
#		- wait for old zone data to expire from caches
#		- sign the zone with the new Current ZSK key
#
#	KSK rollover uses the Double Signature Method of rollover and takes
#	place in seven phases:
#		- wait for cache data to expire
#		- generate a new (published) KSK
#		- wait for the old DNSKEY RRset to expire from caches
#		- roll the KSKs
#		- transfer new keyset to the parent
#			(currently, this is done manually)
#		- wait for parent to publish the new DS record
#			(currently, this is done manually)
#		- reload the zone
#
#	See the pod for much more information.
#

#
# If we're executing from a packed environment, make sure we've got the
# library path for the packed modules.
#
BEGIN
{
	if($ENV{'PAR_TEMP'})
	{
		unshift @INC, ("$ENV{'PAR_TEMP'}/inc/lib");
	}
}


use strict;

use Cwd;
use Getopt::Long qw(:config no_ignore_case_always);

use Net::DNS::SEC::Tools::dnssectools;
use Net::DNS::SEC::Tools::conf;
use Net::DNS::SEC::Tools::defaults;
use Net::DNS::SEC::Tools::keyrec;
use Net::DNS::SEC::Tools::rolllog;
use Net::DNS::SEC::Tools::rollmgr;
use Net::DNS::SEC::Tools::rollrec;
use Net::DNS::SEC::Tools::timetrans;
use Net::DNS::SEC::Tools::tooloptions;
use Net::DNS::SEC::Tools::BootStrap;

use Net::DNS::ZoneFile::Fast;

use POSIX qw(setsid);
use POSIX qw(setuid);

#
# Version information.
#
my $NAME   = "rollerd";
my $VERS   = "$NAME version: 1.13.0";
my $DTVERS = "DNSSEC-Tools Version: 1.13";

#######################################################################

my $ME		= "rollerd";

#
# Some path variables to be set from the config file.
#
my $dtconfig;				# DNSSEC-Tools configuration file.
my $rndc;				# BIND name server control program.
my $rrchk;				# Rollrec file checking program.
my $zonesigner;				# Zone-signing program.

my $PWD = '/bin/pwd';

my $DEFAULT_NAP	= 60;

##########################################
#
# Method selected for calculating rollover times.
#

my $RM_ENDROLL	  = 1;		# Calculate from end of last roll.
my $RM_KEYGEN	  = 2;		# Calculate from last key generation.
my $RM_STARTROLL  = 3;		# Calculate from start of last roll.  (NYI)

my $krollmethod = $RM_ENDROLL;	# Rollover calculation to use for KSKs.
my $zrollmethod = $RM_ENDROLL;	# Rollover calculation to use for ZSKs.

##########################################
#
# Data required for command line options.
#

my $rollrecfile;			# Rollrec file to be managed.

my %dtconf;				# DNSSEC-Tools config file.
my $DT_LOADZONE	= 'roll_loadzone';
my $DT_LOGFILE	= 'roll_logfile';
my $DT_LOGLEVEL	= 'roll_loglevel';
my $DT_LOGTZ	= 'log_tz';
my $DT_SLEEP	= 'roll_sleeptime';
my $DT_USERNAME	= 'roll_username';

my $OPT_ALWAYSSIGN = 'alwayssign';
my $OPT_AUTOSIGN   = 'autosign';
my $OPT_DIR	   = 'directory';
my $OPT_DISPLAY	   = 'display';
my $OPT_DTCONF	   = 'dtconfig';
my $OPT_FOREGROUND = 'foreground';
my $OPT_HELP	   = 'help';
my $OPT_LOGFILE	   = 'logfile';
my $OPT_LOGLEVEL   = 'loglevel';
my $OPT_LOGTZ	   = 'logtz';
my $OPT_NORELOAD   = 'noreload';
my $OPT_PARAMS	   = 'parameters';
my $OPT_PIDFILE    = 'pidfile';
my $OPT_REALM	   = 'realm';
my $OPT_RRFILE	   = 'rrfile';
my $OPT_SINGLERUN  = 'singlerun';
my $OPT_SLEEP	   = 'sleep';
my $OPT_USERNAME   = 'username';
my $OPT_VERBOSE	   = 'verbose';
my $OPT_VERSION	   = 'Version';
my $OPT_ZONESIGNER = 'zonesigner';
my $OPT_ZSARGS	   = 'zsargs';

my %opts = ();			# Filled option array.
my @opts =
(
	"rrfile=s",			# Rollrec file.
	"directory=s",			# Execution directory.
	"display",			# Use output GUI.
	"logfile=s",			# Log file.
	"loglevel=s",			# Logging level.
	"logtz=s",			# Logging timezone.
	"noreload",			# Don't reload zone files.
	"pidfile=s",			# pid storage file.
	"dtconfig=s",			# dnssec-tools config file to use.
	"sleep=i",			# Sleep amount (in seconds.)
	"parameters",			# Display the parameters and exit.
	"autosign!",			# Autosign flag.
	"singlerun",			# Single run:  process everything once.
	"foreground",			# Run in the foreground; don't fork.
	"alwayssign",			# Always sign when running in singlerun.
	"username=s",			# User name for which to run as.
	"realm=s",			# Realm we're running in.
	"help",				# Give a usage message and exit.
	"verbose",			# Verbose output.
	"Version",			# Display the version number.
	"zonesigner=s",			# Location of zonesigner executable.
	"zsargs=s",			# Arguments for zonesigner.
);

#
# Flag values for the various options.  Variable/option connection should
# be obvious.
#
my $alwayssign = 0;			# Always sign the zone in -singlerun.
my $autosign = 0;			# Autosign updated zones.
my $dtcf;				# DNSSEC-Tools configuration file.
my $foreground = 0;			# Run in the foreground.
my $logfile;				# Log file.
my $loglevel;				# Logging level.
my $loglevel_save;			# Saved logging level.
my $logtz;				# Logging timestamp.
my $zoneload = 1;			# Zone-reload flag.
my $pidfile;				# Pid storage file.
my $realm;				# Our realm.
my $singlerun = 0;			# Single run only.
my $sleep_override = 0;			# Sleep-override flag.
my $sleepcnt;				# Time we've slept so far.
my $sleeptime;				# Sleep interval in seconds.
my $username;				# User name we'll change to.
my $gzsargs = '';			# Global zsargs for zonesigner.
my $verbose = 0;			# Verbose option.

my $display = 0;			# Do display processing.

my $boottime = gmtime();		# Timestamp of rollerd's start time.

my $MIN_SLEEP = 10;			# Minimum time rollerd will sleep.

my $curdir;				# Directory.
my $keyarch;				# Key-archive program.
my $packed = 0;				# Flag indicating if running packed.
my $xqtdir;				# Execution directory.

#######################################################################

my $EVT_FULLLIST   = 1;		# Full list is run every N seconds.
my $EVT_QUEUE_SOON = 2;		# Queues, with "soon" events.

#
# "full list" queue processing is the classic rollerd method of handling its
# queue.  Every N seconds, the entire queue of zones is scanned to see if any
# rollover events must be handled.
#
# "soon" queue processing is experimental.  It maintains a sub-queue of the
# rollover events that must be handled soon.  Rather than processing the full
# queue of managed zones every N seconds, the "soon queue" is handled as the
# events occur.
#
# "soon" processing is still being tested and should *not* be considered
# reliable!  (yet...)
#

my $eventmaster = $EVT_FULLLIST;
# my $eventmaster = $EVT_QUEUE_SOON;

my @event_methods =
(
	"dummy",
	"Full List",
	"Soon Queue",
);

#######################################################################
#
# Soon Queue data.
#

my $QUEUE_ERRTIME = 60;			# Time to sleep on rollrec error.

#
# $QUEUE_SOONLIMIT defines the length of "soon".  When building the soon
# queue, any zone with an event between now and (now + $QUEUE_SOONLIMIT)
# will be added to the soon queue.  This is a seconds count.
#
# This value will depend on the number of managed zones and their lifespans.
# The default value is for a day, which means the soon queue will hold all
# events that will occur within the next 24 hours.
#
my $QUEUE_SOONLIMIT = 86400;

my $QUEUE_RUNSCAN = '<<< run full scan >>>';	# Fake rollrec name to trigger
						# a full scan.

my %queue_eventtimes = ();
my %queue_maxttls    = ();
my %queue_signtimes  = ();
my @queue_allzones   = ();
my @queue_sooners    = ();

my $queue_firstsoon;			# Index of first unprocessed soon entry.
my $queue_lastscan;			# GMT of last full scan.
my $queue_scantime;			# Time taken for last full scan.
my $queue_scanskips;			# Count of zones skipped in scan.
my $queue_soonend;			# End of current "soon" period.

#######################################################################

my $queued_int = 0;			# Queued-SIGINT flag.
my $queued_hup = 0;			# Queued-SIGHUP flag.

my $wassigned;				# Flag indicating zone was signed.

my $ret;				# Return code from main().
my $runerr;				# Execution error -- used in runner().

#
# If we find the rollrec file is empty, we'll give an error message
# only on an occasional pass through the zone list.
#
my $MAXRRFERRS = 5;			# Number of list passes to stay quiet.
my $rrferrors = 0;			# Count of times through list.

#
# Detect required Perl modules.
#
dnssec_tools_load_mods('Date::Parse'	=> "",
		       'Date::Format'	=> "",);

#
# Do Everything.
#
$ret = main();
exit($ret);

#-----------------------------------------------------------------------------
# Routine:	main()
#
# Purpose:	Do Everything.
#
#		basic steps:
#			while rollrec file is not empty
#				read rollrec file
#
#				for each rollrec in the rollrec file
#					handle according to its phase
#
sub main
{
	my $olderr;					# Saved error action.
	my $ret;					# General return code.

	#
	# Initialize a few things...
	#	- force unbuffered output
	#	- default error action
	#	- set run-packed flag
	#
	$| = 1;
	erraction(ERR_MSG);
	$packed = runpacked();

	#
	# Parse our command line into an options hash.
	#
	GetOptions(\%opts,@opts) || usage();

	#
	# Set up the appropriate DNSSEC-Tools config file.  If we're running
	# in a packed configuration, we'll use the config file in the packed
	# environment's directory.
	#
	if($packed)
	{
		$opts{$OPT_DIR} = ".";
		setconffile("$ENV{'PAR_TEMP'}/inc/dnssec-tools.conf");
	}

	#
	# If there's a -dtconfig command line option, we'll use that,
	#
	if(exists($opts{$OPT_DTCONF}))
	{
		setconffile($opts{$OPT_DTCONF});
	}

	#
	# Check our options and arguments.
	#
	optsandargs();

	#
	# Run our configuration checks and make sure any error messages
	# will be printed.
	#
	$olderr = erraction(ERR_MSG);
#	if(dt_confcheck(0) > 0)
#	{
#		dt_confcheck(1);
#		print STDERR "\nrollerd:  configuration checks failed, halting\n";
#		rolllog_log(LOG_ALWAYS,"","rollerd configuration checks failed");
#		cleanup();
#	}
	erraction($olderr);

	#
	# Check our required external commands.
	#
	getprogs();
	cmdcheck(\%opts);

	#
	# Daemonize ourself.
	#
	exit(0) if(!$singlerun && !$foreground && fork());
	POSIX::setsid();

	#
	# Ensure we're the only rollerd running and drop a pid file.
	#
	if(rollmgr_dropid() == 0)
	{
		print STDERR "another rollerd is already running\n";
		rolllog_log(LOG_ALWAYS,"","another rollerd tried to start");
		cleanup();
	}

	#
	# If it hasn't been set yet, get the pathname for zonesigner.
	#
	if(($zonesigner eq '') &&
	   (($zonesigner=dt_cmdpath('zonesigner')) eq ''))
	{
		print STDERR "no absolute path defined for zonesigner; exiting...\n";
		rolllog_log(LOG_ALWAYS,"","no absolute path defined for zonesigner; exiting...");
		cleanup();
	}

	#
	# Tell the log we're up.
	#
	bootmsg(1);

	#
	# Mark the domains as being under our control.
	#
	eminent_domains($rollrecfile);

	#
	# Set up the command channel.
	#
	if(($ret=rollmgr_channel(1)) != 1)
	{
		my @errs =
		    (
			'Unable to connect to the server.',
			'Unable to create a Unix socket.',
			'Unable to bind to the Unix socket.',
			'Unable to change the permissions on the Unix socket.',
			'Unable to listen on the Unix socket.',
			'Communications socket name was longer than allowed for a Unix socket.',
		    );

		#
		# Adjust for array index.
		#
		$ret *= -1;

		rolllog_log(LOG_FATAL,"","unable to create control communications channel:  $errs[$ret]");

		exit(3);
	}

	#
	# Main event loop.  If the rollrec file is okay, we'll read it,
	# check its zones -- rolling 'em if need be -- and saving its state.
	# We'll always check for user commands and then sleep a bit.
	#
	if($eventmaster == $EVT_FULLLIST)
	{
		rolllog_log(LOG_ALWAYS,""," ");

		full_list_event_loop();
	}
	if($eventmaster == $EVT_QUEUE_SOON)
	{
		rolllog_log(LOG_ALWAYS,""," ");
		queue_soon_event_loop();
	}
	else
	{
		rolllog_log(LOG_FATAL,"","invalid event handler specified; cannot continue");
		print STDERR "rollerd:  invalid event handler specified; cannot continue\n";
		exit(1);
	}

}

#-----------------------------------------------------------------------------
# Routine:	eminent_domains()
#
# Purpose:	Mark the domains in the rollrec file as being under our
#		control.
#
sub eminent_domains
{
	my $rrf	 = shift;				# Rollrec file.

	#
	# Exit with failure if the rollrec file is bad.
	# 
	if(!rrfokay($rrf,""))
	{
		rolllog_log(LOG_FATAL,'',"rollrec file \"$rrf\" invalid");
		return(0);
	}

	#
	# Get the current contents of the rollrec file.
	#
	rollrec_lock();
	rollrec_read($rollrecfile);

	#
	# For each rollrec entry, get the keyrec file and mark its zone
	# entry as being controlled by us.
	#
	foreach my $rname (rollrec_names())
	{
		my $rrr;		# Reference to rollrec.
		my $prefix;		# Rollrec's directory field.
		my $keyrec;		# Keyrec's filename.

		#
		# Get the rollrec for this name.  If it doesn't have one,
		# whinge and continue to the next.
		#
		$rrr = rollrec_fullrec($rname);
		if(!defined($rrr))
		{
			rolllog_log(LOG_ERR,$rname,"no rollrec defined for zone");
			next;
		}

		#
		# Check for a directory.  We'll use rollerd's execution
		# directory if one isn't defined.
		#
		$prefix = $xqtdir;
		$prefix = $rrr->{'directory'} if(defined($rrr->{'directory'}));

		#
		# Build the keyrec file.
		#
		$keyrec = $rrr->{'keyrec'};
		$keyrec = "$prefix/$keyrec" if($keyrec !~ /^\//);

		#
		# Set the error flag if either the zonefile or the keyrec
		# file don't exist.
		#
		if(! -e $keyrec)
		{
			rolllog_log(LOG_ERR,$rname,"keyrec \"$keyrec\" does not exist");
			next;
		}

		#
		# Mark the keyrec's zone as being under our control.
		#
		keyrec_read($keyrec);
		keyrec_setval('zone',$rname,'rollmgr',"rollerd");
		keyrec_close();
	}

	#
	# Save the current rollrec file state.
	#
	rollrec_close();
	rollrec_unlock();

	#
	# Return success.
	# 
	return(1);
}

#-----------------------------------------------------------------------------
# Routine:	full_list_event_loop()
#
# Purpose:	Rollover event handler -- full queue.
#
#		Every $sleeptime seconds, it checks the entire set of rollrecs
#		to see if any rollover actions must be taken.
#
#		This method works fine for small numbers of zones; it gets
#		unwieldy as the number of managed zones increases.
#
#		This is the original event-loop code.
#
sub full_list_event_loop
{
	while(42)
	{
# rolllog_log(LOG_ALWAYS,"","looping ----------------------------------------");

		#
		# Turn off signal handlers so they don't interrupt us
		# while we're running the queue.
		#
		controllers(0);
		$sleep_override = 0;

		#
		# If we have a valid rollrec file, we'll read its contents
		# and handle for expired KSKs and ZSKs.
		#
		if(rrfchk($rollrecfile))
		{
			my $kronos1;			# Check's start time.
			my $kronos2;			# Check's end time.
			my $kronodiff;			# Difference of times.
			my $kronos;			# difference string.

			#
			# Get the contents of the rollrec file and check
			# for expired KSKs and ZSKs.
			#
			rollrec_lock();
			if(rollrec_read($rollrecfile) > 0)
			{
				#
				# Check the zones for expired ZSKs.  We'll also
				# keep track of how long it takes to check the
				# ZSKs.
				#
				$kronos1 = time;
				rollkeys();
				$kronos2 = time;
				$kronodiff = $kronos2 - $kronos1;
				$kronos = timetrans($kronodiff);
				rolllog_log(LOG_TMI,"<timer>","keys checked in $kronos");

				#
				# Save the current rollrec file state.
				#
				rollrec_close();
			}
			rollrec_unlock();
		}

		#
		# Check for user commands.
		#
		commander();

		#
		# We'll stop now if we're only running the queue once.
		#
		if($singlerun)
		{
			rolllog_log(LOG_INFO,"","rollover manager shutting down at end of single-run execution");
			halt_handler();
			exit(0);
		}

		#
		# Turn on our signal handlers and then take a nap.
		#
		controllers(1);
		sleeper($sleeptime);

	}
}

#-----------------------------------------------------------------------------
# Routine:	rollkeys()
#
# Purpose:	Go through the zones in the rollrec file and start rolling
#		the ZSKs and KSKs for those which have expired.
#
sub rollkeys
{
	my @rrfstats;			# Stats for rollrec file.

	#
	# Let the display program know we're starting a roll cycle.
	#
	display("startroll <all> 0");

	#
	# Check the zones in the rollrec file to see if they're ready
	# to roll.
	#
	foreach my $rname (rollrec_names())
	{
		my $rrr;		# Reference to rollrec.
		my %rr;			# Rollrec hash.

		#
		# Close down if we've received an INT signal.
		#
		if($queued_int)
		{
			rolllog_log(LOG_INFO,$rname,"received immediate shutdown command");
			halt_handler();
		}

		#
		# Return to our execution directory.
		#
		rolllog_log(LOG_TMI,$rname,"execution directory:  chdir($xqtdir)");
		chdir($xqtdir);

		#
		# Ensure the logging level is set correctly.
		#
		$loglevel = $loglevel_save;

		#
		# Get the rollrec for this name.  If it doesn't have one,
		# whinge and continue to the next.
		# (This should never happen, but...)
		#
		$rrr = rollrec_fullrec($rname);
		if(!defined($rrr))
		{
			rolllog_log(LOG_ERR,$rname,"no rollrec defined for zone");
			next;
		}
		%rr = %$rrr;

		#
		# Set the logging level to the rollrec entry's level (if it
		# has one) for the duration of processing this zone.
		#
		$loglevel_save = $loglevel;
		if(defined($rr{'loglevel'}))
		{
			my $llev;			# Logging level.

			$llev = rolllog_num($rr{'loglevel'});
			if($llev != -1)
			{
				$loglevel = $llev;
				rolllog_level($loglevel,0);
			}
			else
			{
				rolllog_log(LOG_ERR,$rname,"invalid rollrec logging level \"$rr{'loglevel'}\"");
			}
		}

		#
		# Don't do anything with skip records.
		#
		if($rr{'rollrec_type'} eq "skip")
		{
			rolllog_log(LOG_TMI,$rname,"is a skip rollrec");
			next;
		}

		#
		# If this rollrec has a directory record, we'll move into
		# that directory for execution.  If the chdir() fails, we'll
		# skip this rollrec.
		#
		if(exists($rr{'directory'}))
		{
			my $rrdir = $rr{'directory'};

			if(chdir($rrdir) == 0)
			{
				rolllog_log(LOG_ERR,$rname,"invalid rollrec directory \"$rrdir\"; skipping...");
				next;
			}
			rolllog_log(LOG_TMI,$rname,"using rollrec directory \"$rrdir\"");
		}

		#
		# If the zone's keyrec file doesn't exist, we'll try to
		# create it with a simple zonesigner call.
		#
		if(! -e $rrr->{'keyrec'})
		{
			rolllog_log(LOG_ERR,$rname,"keyrec \"$rrr->{'keyrec'}\" does not exist; running initial zonesigner");
			signer($rname, "initial", 0);
		}

		#
		# Ensure the record has the KSK and ZSK phase fields.
		#
		if($rr{'kskphase'} == -1)
		{
			rolllog_log(LOG_TMI,$rname,"new kskphase entry");
			nextphase($rname,$rrr,0,'KSK')
		}
		if($rr{'zskphase'} == -1)
		{
			rolllog_log(LOG_TMI,$rname,"new zskphase entry");
			nextphase($rname,$rrr,0,'ZSK')
		}

		#
		# Turn off the flag indicating that the zone was signed.
		# 
		$wassigned = 0;

		#
		# If this zone's current KSK has expired, we'll get it rolling.
		# 
		if(ksk_expired($rname,$rrr,"kskcur"))
		{
			rolllog_log(LOG_TMI,$rname,"current KSK has expired\n") if($rr{'zskphase'} == 0);

			ksk_phaser($rname,$rrr);
		}
		else
		{
			rolllog_log(LOG_TMI,$rname,"current KSK still valid");
		}

		#
		# If this zone's current ZSK has expired, we'll get it rolling.
		# 
		if(zsk_expired($rname,$rrr,"zskcur"))
		{
			rolllog_log(LOG_INFO,$rname,"current ZSK has expired\n") if($rr{'zskphase'} == 0);
			zsk_phaser($rname,$rrr);
		}
		else
		{
			rolllog_log(LOG_TMI,$rname,"current ZSK still valid");
		}

		#
		# If -alwayssign was specified, always sign the zone
		# even if we didn't need to for this period.
		#
		if($alwayssign && !$wassigned)
		{
			my $krr;		# Ref to keyrec data.
			my $extraargs = "";	# Phase-dependent argument.

			rolllog_log(LOG_TMI,$rname, "signing the zone $rrr->{'zonename'} (-alwayssign specified)");

			#
			# Check value and file existence, etc.
			#
			$krr = opts_zonekr($rrr->{'keyrec'},$rrr->{'zonename'});

			#
			# Tell the signer what phase we're in so it
			# can decide what key to use.
			#
			if($rrr->{'zskphase'} > 0)
			{
				$extraargs = "ZSK phase $rrr->{'zskphase'}";
			}
			elsif($rrr->{'kskphase'} > 0)
			{
				$extraargs = "KSK phase $rrr->{'kskphase'}";
			}

			#
			# KSK signing uses double-signature so nothing
			# is needed since zonesigner always uses all
			# available keys.
			#

			#
			# Actually do the signing.
			#
			my $ret = signer($rname, $extraargs, $krr);
			if($ret)
			{
				rolllog_log(LOG_ERR, "signing $rname failed!");
			}
		}
	}

	#
	# Ensure the logging level is set correctly.
	#
	$loglevel = $loglevel_save;
	rolllog_level($loglevel,0);
}

#=============================================================================
#=============================================================================
#=============================================================================
#=============================================================================
#=============================================================================

#-----------------------------------------------------------------------------
# Routine:	queue_soon_event_loop()
#
# Purpose:	Rollover event handler -- timed event queue with "soon" queue.
#
#		Periodically, the entire set of rollrecs is scanned to find
#		the set of events that will occur "soon".  ("soon" may be
#		defined as within the next 12 hours, 24 hours, etc.)
#		These rollrecs are added to a queue in chronological order.
#
#		rollerd will sleep until the next event occurs, then handle
#		those events that have triggered.  The next event-expiration
#		times are recalculated for the list of "soon" events as well
#		as the events which have just been handled.  If the just-
#		handled events fall within the "soon" timeframe, they are
#		reinserted in the "soon" queue.
#
#		Rescanning of the full set of rollrecs must occur periodically
#		in order to keep the "soon" queue populated.
#
#		The definition of "soon" and the rescan time period are not
#		universally definite numbers.  They will almost certainly
#		depend on the numbers of zones managed by each installation,
#		plus the key lifespans for those zones.
#
#		This event loop was added in Spring, 2011.
#
sub queue_soon_event_loop
{
rolllog_log(LOG_ALWAYS,""," ");
rolllog_log(LOG_ALWAYS,"","   not worrying about signal handlers at the moment!");
rolllog_log(LOG_ALWAYS,"","   what should happen with -singlerun?");
rolllog_log(LOG_ALWAYS,""," ");
rolllog_log(LOG_INFO,"","           QUEUE_SOONLIMIT - $QUEUE_SOONLIMIT");
rolllog_log(LOG_ALWAYS,""," ");

	#
	# Time for the Main Event*!
	#
	# * loop
	#
	while(42)
	{
# rolllog_log(LOG_ALWAYS,"","looping full -----------------------------------");

		#
		# Turn off signal handlers while we're reading the rollrec file.
		#
		controllers(0);

		#
		# If we have a valid rollrec file, we'll read its contents
		# and handle for expired KSKs and ZSKs.
		#
		if(rrfchk($rollrecfile) == 0)
		{
			rolllog_log(LOG_ERR,"","rrfchk($rollrecfile) failed");
			sleeper($QUEUE_ERRTIME);
			next;
		}

		#
		# Read the rollrec file.
		#
		# WARNING:  We're only locking the file while we're reading
		#	    it!  This may not be the safest way to do this.
		#
		rollrec_lock();
		rollrec_read($rollrecfile);
		rollrec_close();
		rollrec_unlock();

		#
		# Turn on signal handlers while we're scanning the full queue.
		#
		controllers(1);

		#
		# Calculate event times for each rollrec entry.
		#
		queue_scanall();

#		queue_prteventtimes();

		#
		# Check all the events that will be happening "soon".
		#
		while(42)
		{
			my $nextrrn;		# Next rollrec to handle.
			my $naptime;		# Time until next event.
			my $now;		# Current time.
			my $ind;		# Loop index.
			my @savenames = ();	# Rollrecs to return to soonlist
			my $kronos1;		# Start time for soon loop.
			my $kronos2;		# End time for soon loop.
			my $kronos;		# Time taken in soon loop.

# rolllog_log(LOG_ALWAYS,"","looping soon -----------------------");
			#
			# Rescan the entire list of zones if the soon list
			# is empty.
			#
			# This should never happen.  There should always be,
			# at the very least, an entry that schedules the next
			# full scan.
			#
			if(@queue_sooners == 0)
			{
				rolllog_log(LOG_ERR,"","DANGER!!!  soonlist is empty and shouldn't be!");
				goto endsooners;
			}

# queue_prteventtimes();

			#
			# Get the time until the next event.
			#
			$nextrrn = $queue_sooners[0];
			$naptime = $queue_eventtimes{$nextrrn};

			#
			# Turn on our signal handlers and then take a nap.
			#
			controllers(1);

#			$naptime = 60 if($naptime <= 0);
			$sleeptime = $naptime;
# queue_prtsooners();
# rolllog_log(LOG_ALWAYS,"","queue_sooners (" . @queue_sooners . " entries)");
			sleeper($naptime) if($naptime > 0);

			#
			# Turn off signal handlers so they don't interrupt us
			# while we're scanning the soon queue.
			#
			controllers(0);
			$sleep_override = 0;

			#
			# Get this iteration's idea of the current time.
			#
			$now = gmtime(time);
			$now = str2time($now);

			#
			# Calculate the next-event time for each of the zones
			# in the @queue_sooners list.
			#
			rolllog_log(LOG_TMI,"","starting scan of soon queue");
			$kronos1 = time;
			queue_scansooners($now);
			$kronos2 = time;
			$kronos = $kronos2 - $kronos1;
			$kronos = timetrans($kronos);
# rolllog_log(LOG_ALWAYS,"","scanned soon queue (" . @queue_sooners . " zones) in $kronos");

			#
			# Get the rollrec file.
			#
			rollrec_lock();
			if(rollrec_read($rollrecfile) <= 0)
			{
				rolllog_log(LOG_ALWAYS,"","DANGER!!!  rollrec_read($rollrecfile) failed");
				last;
			}

			#
			# Reset the index for the next imminent soon event.
			#
			$queue_firstsoon = 0;

			#
			# Turn on signal handlers so the user can query the
			# queue while we're running the queue.
			#
			controllers(1);

			#
			# Run through our queue of soon-to-happen rollover
			# events.
			#
			$kronos1 = time;
			for($ind=0; $ind < @queue_sooners; $ind++)
			{
				my $rrn = $queue_sooners[$ind];
				my $rrr;
				my $nxt;

				#
				# Check for user commands.
				#
				commander();

				#
				# Rescan the entire list of zones if we've hit
				# the run-scan fake rollrec name.
				#
				#
#				goto endsooners if($rrn eq $QUEUE_RUNSCAN);
				if($rrn eq $QUEUE_RUNSCAN)
				{
					rolllog_log(LOG_TMI,"","RUNSCAN hit!   stopping soon-loop");
					goto endsooners;
				}

				$rrr = rollrec_fullrec($rrn);

				#
				# Skip this zone if this is a skip zone.
				#
				next if($rrr->{'rollrec_type'} eq 'skip');

				#
				# Proceed to the next zone if the zone is in a
				# state that requires administrative attention.
				#
				next if($rrr->{'kskphase'} == 6);

				if($queue_eventtimes{$rrn} > 0)
				{
					rollrec_unlock();
					last;
				}

				#
				# Handle the rollover event.
				#
				queue_rollevent($rrn);
				$queue_firstsoon++;

				#
				# Add this zone to our savelist if it has its
				# next rollover event soon.
				#
				$nxt = queue_scanone($rrn,$now);
				if(($nxt < $queue_eventtimes{$QUEUE_RUNSCAN}) &&
				   (! $singlerun))
				{
					push @savenames, $rrn;
				}

			}
			$kronos2 = time;

			#
			# Save the current rollrec file state and get the
			# time stats.
			#
			rollrec_close();
			rollrec_unlock();
			$kronos = $kronos2 - $kronos1;
			$kronos = timetrans($kronos);

			#
			# Check for user commands.
			#
			commander();

			#
			# We'll stop now if we're only running the queue once.
			#
			if($singlerun)
			{
				rolllog_log(LOG_INFO,"","rollover manager shutting down at end of single-run execution");
				halt_handler();
				exit(0);
			}

			#
			# Remove the zones we've just handled from the sooners
			# list.  Also, add in the zones that we just handled
			# that are still within the "soon" time.
			#
			splice @queue_sooners, 0, $ind;
			$queue_firstsoon = 0;
			push @queue_sooners, @savenames;

			#
			# Sort the sooners list.  The sorting is done based on
			# the amount of time before each zone's next event.
			#
			@queue_sooners  = sort { $queue_eventtimes{$a} <=> $queue_eventtimes {$b} } @queue_sooners;

		}

  endsooners:
		rollrec_unlock();

	}

}

#-----------------------------------------------------------------------------
# Routine:	queue_scanall()
#
# Purpose:	Calculate the next-event time for each of the zones in the
#		rollrec file.  Zones that fall within our "soon" limit, will
#		be added to the @queue_sooners list.
#
sub queue_scanall
{
	my $cronus;					# Current time.
	my $kronos1;					# Scan start time.
	my $kronos2;					# Scan end time.

	my $lasttime;			# Last rollrec's event time.

# rolllog_log(LOG_ALWAYS,"","queue_scanall:  running a full scan");

	#
	# Reset all our queuing lists.
	#
	%queue_eventtimes = ();
	@queue_allzones   = ();
	@queue_sooners    = ();
	$queue_scanskips  = 0;

	#
	# Get the base time.
	#
	$kronos1 = time;
	$cronus = gmtime($kronos1);
	$cronus = str2time($cronus);

	#
	# Recalculate the next-event time for every zone in the rollrec file.
	# If the zone falls within the soon limit, it'll be added to
	# @queue_sooners. All zones will be added to @queue_allzones.
	#
	foreach my $rrn (rollrec_names())
	{
		my $next;

		$next = queue_scanone($rrn,$cronus);

		push @queue_allzones, $rrn;
		push @queue_sooners, $rrn if($next < $QUEUE_SOONLIMIT);
	}

	#
	# Sort the zone lists we'll use for queuing.  The sorting is done
	# based on the amount of time before each zone's next event.
	#
	@queue_allzones = sort { $queue_eventtimes{$a} <=> $queue_eventtimes {$b} } @queue_allzones;
	@queue_sooners  = sort { $queue_eventtimes{$a} <=> $queue_eventtimes {$b} } @queue_sooners;

	#
	# Figure out how long the scan took.
	#
	$queue_lastscan = time;
	$kronos2 = time;
	$queue_scantime = $kronos2 - $kronos1;
	$queue_soonend = $cronus + $QUEUE_SOONLIMIT;

	#
	# Arrange for the next full scan.
	#
	$queue_eventtimes{$QUEUE_RUNSCAN} = $QUEUE_SOONLIMIT;
	push @queue_sooners, $QUEUE_RUNSCAN;

	#
	# If no zones fall within the "soon" timeframe, we'll schedule
	# another scan for shortly before the next zone needs to be handled.
	#
	if(@queue_sooners == 0)
	{
		my $rrn;				# Rollrec name.
		my $nevt;				# Next event time.

		$rrn = @queue_allzones[0];
		$nevt = $queue_eventtimes{$rrn};

		$sleeptime = $nevt - $queue_scantime - 60;
	}

# queue_prteventtimes();
# queue_prtsooners();
}

#-----------------------------------------------------------------------------
# Routine:	queue_scansooners()
#
# Purpose:	Calculate the next-event time for each of the zones in the
#		@queue_sooners list.  If the zone still falls within our
#		"soon" limit, it'll be kept in the @queue_sooners list.
#
sub queue_scansooners
{
	my $cronus = shift;	# Current time.
	my @newsooners = ();	# Temporary list of new sooners.
	my $nextscan;		# Time of next full scan.
	my $tdiff;		# Time difference between now and last scan.

# rolllog_log(LOG_INFO,"","queue_scansooners:  down in");

	#
	# Figure out when the next full scan will take place.
	#
	$tdiff = time - $queue_lastscan;
	$nextscan = $QUEUE_SOONLIMIT - $tdiff;
	$queue_eventtimes{$QUEUE_RUNSCAN} = $nextscan;

	#
	# Recalculate the next-event time for each zone in the @queue_sooners
	# list.  If the zone is still within the soon limit, it'll be kept in
	# @queue_sooners.
	#
	foreach my $rrn (@queue_sooners)
	{
		my $nxt;

		#
		# Close down if we've received an INT signal.
		#
		if($queued_int)
		{
			rolllog_log(LOG_INFO,$rrn,"received immediate shutdown command");
			halt_handler();
		}

		next if($rrn eq $QUEUE_RUNSCAN);

		$nxt = queue_scanone($rrn,$cronus);
		push @newsooners, $rrn if($nxt < $nextscan);
	}

	#
	# Schedule the next full scan.
	#
	push @newsooners, $QUEUE_RUNSCAN;

	#
	# Sort the new list of soon zones.  The sorting is done based
	# on the amount of time before each zone's next event.
	#
	@newsooners = sort { $queue_eventtimes{$a} <=> $queue_eventtimes {$b} } @newsooners;

	#
	# Replace our soon list.
	#
	@queue_sooners = @newsooners;

# queue_prtsooners();
}

#-----------------------------------------------------------------------------
# Routine:	queue_scanone()
#
# Purpose:	Find the number of seconds until the given zone's next event.
#		The event time will be saved in the Big List o' Event Times.
#
sub queue_scanone
{
	my $rrn = shift;			# Rollrec name.
	my $cronus = shift;			# Time to check.

	my $next;				# Rollrec's next event time.

	#
	# Get the zone's next-event time.
	#
	$next = queue_evttime($rrn,$cronus);

	#
	# Set the zone's time data and return the value to our caller.
	#
	$queue_eventtimes{$rrn}	= $next;
	return($next);
}

#-----------------------------------------------------------------------------
# Routine:	queue_evttime()
#
# Purpose:	Find the number of seconds until the given zone's next event.
#		An event is either when a zone moves into key rollover or when
#		a zone already in rollover moves to the next rollover phase.
#
#		If a zone is not in rollover, the event time is calculated by
		
#		We'll calculate this time based on the maximum TTL in the
#		zone's signed zonefile.  However, if If the signed zonefile
#		hasn't been modified since we last checked, we'll use the
#		maximum TTL we saved the last time we noticed it had been
#		updated.
#
sub queue_evttime
{
	my $rrn	   = shift;			# Name of rollrec to check.
	my $cronus = shift;			# Time to calculate from.

	my %rr;					# Rollrec hash.
	my $rrr;				# Reference to rollrec.

	my $zonefile;				# Zone file.
	my @szstat;				# stat() info for signed zone.
	my $maxttl;				# Zone's maximum TTL value.
	my $phstart;				# Start of zone's phase.

	my $endtime;				# End-date in seconds.
	my $timediff;				# Time until expiration.

	#
	# Get the zone's rollrec.
	#
	$rrr = rollrec_fullrec($rrn);
	%rr  = %$rrr;

	#
	# Get a few fields from the rollrec.
	#
	$zonefile = $rrr->{'zonefile'};
	$phstart  = $rrr->{'phasestart'};

	#
	# If we're not in rollover, the event time is calculated based
	# on key lifetime.
	# If we are in rollover, the event time is calculated based on
	# the maximum TTL of the zone's resource records.
	#
	if(($rr{'kskphase'} == 0) && ($rr{'zskphase'} == 0))
	{
		my $krf;			# Zone's keyrec filename.
		my $krr;			# Zone's keyrec reference.
		my @keys;			# Zone's key lists.
		my $kwait;			# Time until KSK rollover.
		my $zwait;			# Time until ZSK rollover.
		my $kmin = -1;			# Minimum KSK lifetime.
		my $zmin = -1;			# Minimum ZSK lifetime.

		#
		# Get the zone's keyrec.
		#
		$krf = $rrr->{'keyrec'};
		keyrec_read($krf);
		keyrec_close();

		$krr = keyrec_fullrec($rrr->{'zonename'});

		#
		# Find the minimum key lifespan for the keys in the zone's
		# Current KSK set.
		#
		@keys = split / /, keyrec_signset_keys($rrr->{'zonename'}, 'kskcur');
		foreach my $key (@keys)
		{
			my $life = keyrec_recval($key,'ksklife');

			$kmin = $life if($kmin == -1);
			$kmin = $life if($life < $kmin);
		}

		#
		# Find the minimum key lifespan for the keys in the zone's
		# Current ZSK set.
		#
		@keys = split / /, keyrec_signset_keys($rrr->{'zonename'}, 'zskcur');
		foreach my $key (@keys)
		{
			my $life = keyrec_recval($key,'zsklife');

			$zmin = $life if($zmin == -1);
			$zmin = $life if($life < $zmin);
		}

		#
		# Figure out how long we have until the next rollover.
		#
		$kwait = ($rrr->{'ksk_rollsecs'} + $kmin) - $cronus;
		$zwait = ($rrr->{'zsk_rollsecs'} + $zmin) - $cronus;

		#
		# Return the minimum time-until-rollover.
		#
		$timediff = ($kwait < $zwait) ? $kwait : $zwait;
		return($timediff);
	}

	#
	# If the signed zonefile hasn't been modified since we last
	# checked, we'll use the maximum TTL we saved the last time
	# we noticed it had been updated.
	#
	@szstat = stat($zonefile);
	if($szstat[8] > $queue_signtimes{$rrn})
	{
		#
		# Get the signed zonefile's maximum TTL and double it.
		#
		$maxttl	 = queue_maxttl($zonefile);
		$maxttl	*= 2;

		#
		# Squirrel away some values we'll use later.
		#
		$queue_maxttls{$rrn}	= $maxttl;
		$queue_signtimes{$rrn}	= $szstat[8];
	}
	else
	{
		$maxttl = $queue_maxttls{$rrn};
		$queue_scanskips++;
	}

	#
	# Get the zone's "next event" time by adding the start of its
	# last phase-change to twice the maximum TTL.
	#
	$endtime  = str2time($phstart);
	$endtime += $maxttl;

	#
	# Find the difference between the next-event time and now.
	#
	$timediff = $endtime - $cronus;

	return($timediff)
}

#-----------------------------------------------------------------------------
# Routine:	queue_maxttl()
#
# Purpose:	Determine the maximum TTL for the resource records in the zone
#		we were given.  The max TTL will be returned to the caller.
#
sub queue_maxttl
{
	my $signdb = shift;		# Signed zone's db filename.

	my $rrsref;			# Reference to zone's resource records.
	my @rrs;			# Zone's resource records.
	my $numrrs;			# Number of resource records in zone.
	my $rrref;			# Reference to a resource record.
	my %rr;				# A resource record to examine.
	my $maxttl = -1;		# Zone's maximum time-to-live value.
	my $ttl;			# Time-to-live value from a record.

	#
	# Ensure the zone file exists and is readable.
	#
	if((! -e $signdb) || (! -r $signdb))
	{
		return(-1);
	}

	#
	# Get the zone's resource record collection.
	#
	$rrsref = Net::DNS::ZoneFile::Fast::parse(file => $signdb);

	#
	# Get the number of resource records in the zone.
	#
	@rrs = @$rrsref;
	$numrrs = @rrs;

	#
	# Look at each resource record and save the largest value.
	#
	for(my $ind=0;$ind<$numrrs;$ind++)
	{
		$rrref = $rrs[$ind];
		%rr = %$rrref;

		$ttl = $rr{'ttl'};
		$maxttl = $ttl if($ttl > $maxttl);
	}

	#
	# Return the zone's maximum TTL value to our caller.
	#
	return($maxttl);
}

#-----------------------------------------------------------------------------
# Routine:	queue_prteventtimes()
#
sub queue_prteventtimes
{
	foreach my $rrn (@queue_allzones)
	{
		my $rrr;
		my $kpflag;
		my $zpflag;

		$rrr = rollrec_fullrec($rrn);

		$kpflag = $rrr->{'kskphase'};
		$zpflag = $rrr->{'zskphase'};
		if($kpflag)
		{
			rolllog_log(LOG_ALWAYS,"","\t$rrn\t$queue_eventtimes{$rrn}\tksk expired\n");
		}
		elsif($zpflag)
		{
			rolllog_log(LOG_ALWAYS,"","\t$rrn\t$queue_eventtimes{$rrn}\tzsk expired\n");
		}
		else
		{
			rolllog_log(LOG_ALWAYS,"","\t$rrn\t$queue_eventtimes{$rrn}\tnormal\n");
		}
	}
}

#-----------------------------------------------------------------------------
# Routine:	queue_prtsooners()
#
sub queue_prtsooners
{
	my $maxind;					# Last index to check.
	my $rrn;					# Zone name.

	rolllog_log(LOG_ALWAYS,"","queue_sooners (" . @queue_sooners . " entries):\n");

	$maxind = (@queue_sooners < 30) ? @queue_sooners : 30;

	for(my $ind=0; $ind < $maxind; $ind++)
	{
		$rrn = $queue_sooners[$ind];
		rolllog_log(LOG_ALWAYS,"","    <$rrn>      $queue_eventtimes{$rrn} seconds until event\n");
	}

	$rrn = "$QUEUE_RUNSCAN";
	rolllog_log(LOG_ALWAYS,"","    <$rrn>      $queue_eventtimes{$rrn} seconds until event\n");

}

#-----------------------------------------------------------------------------
# Routine:      queue_rollevent()
#
# Purpose	Handle the rollover event for a single rollrec entry.
#
sub queue_rollevent
{
	my $rname = shift;		# Rollrec to handle.
	my $rrr;			# Reference to rollrec.
	my %rr;				# Rollrec hash.

	rolllog_log(LOG_TMI,$rname,"queue_rollevent:  rolling $rname");

	#
	# Return to our execution directory.
	#
#	rolllog_log(LOG_TMI,$rname,"execution directory:  chdir($xqtdir)");
	chdir($xqtdir);

	#
	# Ensure the logging level is set correctly.
	#
	$loglevel = $loglevel_save;

	#
	# Get the rollrec for this name.  If it doesn't have one, whinge and
	# continue to the next rollrec.
	# (This should never happen, but...)
	#
	$rrr = rollrec_fullrec($rname);
	if(!defined($rrr))
	{
		rolllog_log(LOG_ERR,$rname,"no rollrec defined for zone");
		return;
	}
	%rr = %$rrr;

	#
	# Don't do anything with skip records.
	#
	if($rrr->{'rollrec_type'} eq "skip")
	{
		rolllog_log(LOG_TMI,$rname,"is a skip rollrec");
		return;
	}

	#
	# Set the logging level to the rollrec entry's level (if it has one)
	# for the duration of processing this zone.
	#
	$loglevel_save = $loglevel;
	if(defined($rr{'loglevel'}))
	{
		my $llev;			# Logging level.

		$llev = rolllog_num($rr{'loglevel'});
		if($llev != -1)
		{
			$loglevel = $llev;
			rolllog_level($loglevel,0);
		}
		else
		{
			rolllog_log(LOG_ERR,$rname,"invalid rollrec logging level \"$rr{'loglevel'}\"");
		}
	}

	#
	# If this rollrec has a directory record, we'll move into that directory
	# for execution.  If the chdir() fails, we'll skip this rollrec.
	#
	if(exists($rr{'directory'}))
	{
		my $rrdir = $rr{'directory'};

		if(chdir($rrdir) == 0)
		{
			rolllog_log(LOG_ERR,$rname,"invalid rollrec directory \"$rrdir\"; skipping...");
			return;
		}
		rolllog_log(LOG_TMI,$rname,"using rollrec directory \"$rrdir\"");
	}

	#
	# Ensure the record has the KSK and ZSK phase fields.
	#
	if($rr{'kskphase'} == -1)
	{
		rolllog_log(LOG_TMI,$rname,"new kskphase entry");
		nextphase($rname,$rrr,0,'KSK')
	}
	if($rr{'zskphase'} == -1)
	{
		rolllog_log(LOG_TMI,$rname,"new zskphase entry");
		nextphase($rname,$rrr,0,'ZSK')
	}

	#
	# If this zone's current KSK has expired, we'll get it rolling.
	# 
	if(ksk_expired($rname,$rrr,"kskcur"))
	{
		rolllog_log(LOG_TMI,$rname,"current KSK has expired\n") if($rr{'zskphase'} == 0);

		ksk_phaser($rname,$rrr);
	}
	else
	{
		rolllog_log(LOG_TMI,$rname,"current KSK still valid");
	}

	#
	# If this zone's current ZSK has expired, we'll get it rolling.
	# 
	if(zsk_expired($rname,$rrr,"zskcur"))
	{
		rolllog_log(LOG_INFO,$rname,"current ZSK has expired\n") if($rr{'zskphase'} == 0);
		zsk_phaser($rname,$rrr);
	}
	else
	{
		rolllog_log(LOG_TMI,$rname,"current ZSK still valid");
	}

	#
	# If -alwayssign was specified, always sign the zone, even if we
	# didn't need to for this period.
	#

	#
	# XXX:  This could double sign if some of the above steps already
	#	signed the zone.  We should only sign if nothing was done above.
	#
	if($alwayssign)
	{
		my $krr;		# Ref to keyrec data.
		my $extraargs = "";	# Phase-dependent argument.

		#
		# This is only safe to do if we're not waiting for caches
		# to expire.
		#
		if(($rrr->{'zskphase'} != 1) &&
		   ($rrr->{'zskphase'} != 3) &&
		   ($rrr->{'kskphase'} != 1) &&
		   ($rrr->{'kskphase'} != 3))
		{
			rolllog_log(LOG_TMI,$rname, "Signing the zone $rrr->{'zonename'} (-alwayssign specified)");

			#
			# Check value and file existence, etc.
			#
			$krr = opts_zonekr($rrr->{'keyrec'},$rrr->{'zonename'});

			#
			# Tell the signer what phase we're in so it
			# can decide what key to use.
			#
			if($rrr->{'zskphase'} > 0)
			{
				$extraargs = "ZSK phase $rrr->{'zskphase'}";
			}
			elsif($rrr->{'kskphase'} > 0)
			{
				$extraargs = "KSK phase $rrr->{'kskphase'}";
			}

			#
			# KSK signing uses double-signature so nothing is needed
			# since zonesigner always uses all available keys.
			#

			#
			# Actually do the signing.
			#
			my $ret = signer($rname, $extraargs, $krr);
			if($ret)
			{
				rolllog_log(LOG_ERR, "signing $rname failed!");
			}
		}
		else
		{
			rolllog_log(LOG_TMI,$rname, "Not signing the zone $rrr->{'zonename'} (-alwayssign was specified but we're awaiting cache timeouts so we can't sign now)");
		}
	}

	#
	# Reset the logging level is set correctly.
	#
	$loglevel = $loglevel_save;
	rolllog_level($loglevel,0);
}

#=============================================================================
#=============================================================================
#=============================================================================
#=============================================================================
#=============================================================================


###############################################################################

#-----------------------------------------------------------------------------
# Routine:	zsk_expired()
#
# Purpose:	This routine returns a boolean indicating if the specified
#		zone has an expired ZSK key of the given type.
#
#		The zone's keyrec file name is taken from the given rollrec
#		entry.  The keyrec file is read and the zone's entry found.
#		The key keyrec of the specified key type (currently, just
#		"zskcur") is pulled from the keyrec file.  Each key in the
#		named signing set will be checked.
#		
#		Key expiration is determined by comparing the key keyrec's
#		gensecs field to the current time.  The key hasn't expired
#		if the current time is less than the gensecs; the key has
#		expired if the current time is greater than the gensecs.
#
sub zsk_expired
{
	my $rname = shift;			# Name of rollrec rec.
	my $rrr = shift;			# Reference to rollrec.
	my $keyset = shift;			# Key to check.

	my %rr;					# Rollrec hash.

	my $krname;				# Name of keyrec.
	my $krec;				# Keyrec reference.
	my %set;				# Keyrec hash.

	my $khr;				# Ref to key's hash.
	my %kh;					# Key's hash.

	my @signset;				# Key's signing set.

	my $chronostr;				# Text expiration time.
	my $cronus;				# Current time.
	my $expired = 0;			# Expired-zone flag.
	my $minlife = -1;			# Minimum ZSK life.
	my $minhr;				# Ref to min-key's keyrec.
	my $rolltime;				# Time roll should occur.
	my $starter;				# Time 0 for calc'ing rolltime.
	my $waitsecs;				# Time to expiration.

	#
	# Get the rollrec's hash.
	#
	%rr = %$rrr;

	#
	# If this zone is in the middle of KSK rollover, we'll stop
	# working on ZSK rollover.
	#
	if($rr{'kskphase'} > 0)
	{
		my $pstr;				# Phase string.
		$pstr = ": " . rollmgr_get_phase('KSK', $rr{'kskphase'});
		$pstr = '' if($pstr eq ": ");

		rolllog_log(LOG_TMI,$rname,"in KSK rollover (phase $rr{'kskphase'}$pstr); not attempting ZSK rollover");
		return(0);
	}

	#
	# If this zone is in the middle of rollover processing, we'll
	# immediately assume the key has expired.
	#
	return(1) if($rr{'zskphase'} > 0);

	#
	# Get the rollin' key's keyrec for our zone.
	#
	$krname = $rr{'keyrec'};
	$krec = zonekeykr($rname,$rr{'zonename'},$krname,$keyset);
	if($krec == 0)
	{
		rolllog_log(LOG_ERR,$rname,"unable to find a keyrec for ZSK \"$keyset\" in \"$krname\"");
		return(0);
	}
	%set   = %$krec;

	#
	# Make sure we've got an actual set keyrec and keys.
	#
	if($set{'keyrec_type'} ne 'set')
	{
		rolllog_log(LOG_ERR,$rname,"\"$keyset\"'s keyrec is not a set keyrec");
		return(0);
	}
	if(!defined($set{'keys'}) || ($set{'keys'} eq ""))
	{
		rolllog_log(LOG_ERR,$rname,"\"$krname\" has no keys; unable to check expiration");
		return(0);
	}

	#
	# Ensure that there's a signing set.
	#
	@signset = split / /, $set{'keys'};
	if(@signset == 0)
	{
		rolllog_log(LOG_ERR,$rname,"\"$krname\" has no keys; unable to check expiration");
		return(0);
	}

	#
	# Check each key in the signing set to find the one with the shortest
	# lifespan.  We'll calculate rollover times based on that.
	#
	foreach my $keyname (@signset)
	{
		my $keylife;			# Key's life value.

		#
		# Get the key's keyrec hash.
		#
		$khr = keyrec_fullrec($keyname);
		next if(!$khr);
		%kh = %$khr;

		#
		# Ensure that required keyrec field exists.
		#
		if(!defined($kh{"zsklife"}))
		{
			rolllog_log(LOG_ERR,$rname,"keyrec does not contain a zsklife record");
			return(0);
		}

		#
		# If this key's life is shorter than any we've seen, it
		# becomes the new minimum.  If this is the first key we're
		# looking at, we'll save it as the minimum.
		#
		$keylife = $kh{'zsklife'};
		if($minlife == -1)
		{
			$minlife = $keylife;
			$minhr	 = $khr;
		}
		else
		{
			if($keylife < $minlife)
			{
				$minlife = $keylife;
				$minhr	 = $khr;
			}
		}
	}

if(!defined($minhr))
{
rolllog_log(LOG_ALWAYS,$rname,"--------> zsk_expired:  couldn't find minimum key keyrec");
return(0);
}

	#
	# Get the minimum key's keyrec hash.
	#
	%kh = %$minhr;

	#
	# Get the start time on which the expiration time is based.
	#
	if($zrollmethod == $RM_ENDROLL)
	{
		#
		# Ensure that required rollrec field exists.
		#
		if(!defined($rr{'zsk_rollsecs'}))
		{
			rolllog_log(LOG_INFO,$rname,"creating new zsk_rollsecs record and forcing ZSK rollover");
			rollstamp($rname,'zsk');
			return(0);
		}
		$starter = $rr{'zsk_rollsecs'};
	}
	elsif($zrollmethod == $RM_KEYGEN)
	{
		#
		# Ensure that required keyrec field exists.
		#
		if(!defined($kh{'keyrec_gensecs'}))
		{
			rolllog_log(LOG_ERR,$rname,"keyrec does not contain a keyrec_gensecs record");
			return(0);
		}
		$starter = $kh{'keyrec_gensecs'};
	}
	elsif($zrollmethod == $RM_STARTROLL)
	{
		rolllog_log(LOG_ERR,$rname,"RM_STARTROLL not yet implemented");
		return(0);
	}

	#
	# Don't roll immediately if the rollrec file was newly created.
	#
	if($starter == 0)
	{
		rollstamp($rname,'zsk');
		return(0);
	}

	#
	# Get the key's expiration time.
	#
	$rolltime = $starter + $minlife;

	#
	# Get the current time.
	#
#	$cronus	 = time;
	$cronus = gmtime(time);
	$cronus = str2time($cronus);

	#
	# Figure out the log message we should give.
	#
	$waitsecs = $rolltime - $cronus;
	if($waitsecs >= 0)
	{
		$chronostr = timetrans($waitsecs);
		rolllog_log(LOG_EXPIRE,$rname,"        expiration in $chronostr\n");
		display("expiration $rname 0 ZSK $waitsecs");
	}
	else
	{
		$waitsecs = $cronus - $rolltime;
		$chronostr = timetrans($waitsecs);
		rolllog_log(LOG_EXPIRE,$rname,"        expired $chronostr ago\n");
		display("zskphase $rname 0");
	}

	#
	# The keyset has expired if the current time has passed the keyset's
	# lifespan.
	# The keyset has not expired if the keyset's lifespan has yet to reach
	# the current time.
	#
	$expired = 1 if($cronus > $rolltime);

	#
	# If the keyset has not expired and the zone file has been modified,
	# we'll sign the zone file.  We won't created any new keys or take
	# any other rollover actions.
	#
	zonemodified($rrr,$rname) if(!$expired);

	#
	# Return the success/failure indication.
	#
	return($expired);
}

#-----------------------------------------------------------------------------
# Routine:	zsk_phaser()
#
# Purpose:	Move the specified zone's ZSKs through the appropriate phases.
#
sub zsk_phaser
{
	my $rname = shift;		# Zone name.
	my $rrr = shift;		# Reference to rollrec.

	my $ph;				# Zone's current rollover phase.

	#
	# Get this rollrec record's current phase.
	#
	$ph = $rrr->{'zskphase'};

	#
	# Work on this rollrec's phase.
	#
	$ph = phasecmd(\&nextphase,$rname,$rrr,'normal','ZSK')	if($ph == 0);
	$ph = phasecmd(\&phasewait,$rname,$rrr,'zsk1')		if($ph == 1);
	$ph = phasecmd(\&zsk_phase2,$rname,$rrr,'zsk2')		if($ph == 2);
	$ph = phasecmd(\&phasewait,$rname,$rrr,'zsk3')		if($ph == 3);
	$ph = phasecmd(\&zsk_phase4,$rname,$rrr,'zsk4')		if($ph == 4);
}

#-----------------------------------------------------------------------------
# Routine:	zsk_phase2()
#
# Purpose:	Perform the phase 2 steps of the ZSK rollover.  These are:
#
#			- sign the zone with the KSK and Published ZSK
#			- reload the zone
#			- wait for old zone data to expire
#
sub zsk_phase2
{
	my $rname = shift;		# Name of rollrec.
	my $rrr = shift;		# Reference to rollrec.

	my %rr = %$rrr;			# Rollrec hash.

	my $krf;			# Rollrec's keyrec name.
	my %krf;			# Keyrec hash.
	my $krr;			# Keyrec reference.

	my $ret;			# Result from command executions.

	#
	# Get the rollrec's associated keyrec file and ensure that it exists.
	#
	$krf = $rr{'keyrec'};
	if(!$krf  || ($krf eq ""))
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 2:  no keyrec for zone specified");
		return(2);
	}
	if(! -e $krf)
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 2:  keyrec \"$krf\" for zone does not exist");
		return(2);
	}

	#
	# Get the keyrec.
	#
	$krr = opts_zonekr($krf,$rr{'zonename'});
	%krf = %$krr;

	#
	# Sign the zone with the Published ZSK.
	#
	$ret = signer($rname,"ZSK phase 2",$krr);
	if($ret)
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 2:  unable to sign zone with the Published ZSK");
		return(-1);
	}

	#
	# Re-read the keyrec file, since it was rewritten by zonesigner.
	# Also, we'll get rid of any changes we've made to the keyrec.
	# (This *shouldn't* be a problem; further testing will tell...)
	#
	keyrec_discard();
	$ret = keyrec_read($krf);
	if($ret < 0)
	{
		if($ret == -3)
		{
			rolllog_log(LOG_ERR,$rname,"ZSK phase 2:  keyname collision in keyrec \"$krf\"; marking $rname as skipped");
		}
		else
		{
			rolllog_log(LOG_ERR,$rname,"ZSK phase 2:  unable to read keyrec \"$krf\"; marking $rname as skipped");
		}
		skipnow($rname);
		return(-1);
	}

	#
	# Update the timestamp in the zone's keyrec.
	#
	keyrec_settime("zone",$rname);
	keyrec_write();

	#
	# Reload the zone.
	#
	$ret = loadzone($rndc,$rname,$rr{'zonename'},"ZSK phase 2");
	if($ret != 0)
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 2:  unable to reload zone, rc - $ret");
	}

	#
	# Return the next phase number.
	#
	return(3);
}

#-----------------------------------------------------------------------------
# Routine:	zsk_phase4()
#
# Purpose:	Perform the phase 4 steps of the rollover.  These are:
#
#			- juggle the ZSKs in the zone's keyrec
#			- sign the zone with the KSK and new current ZSK
#			- reload the zone
#			- return the zone to the pre-rollover state
#
sub zsk_phase4
{
	my $rname = shift;		# Name of rollrec.
	my $rrr = shift;		# Reference to rollrec.

	my %rr = %$rrr;			# Rollrec hash.

	my $krf;			# Rollrec's keyrec name.
	my $krr;			# Keyrec reference.

	my $ret;			# Result from command executions.

	#
	# Get the rollrec's associated keyrec file and ensure that it
	# exists.
	#
	$krf = $rr{'keyrec'};
	if(!$krf  || ($krf eq ""))
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 4:  no keyrec for zone specified");
		return(-1);
	}
	if(! -e $krf)
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 4:  keyrec \"$krf\" for zone does not exist");
		return(-1);
	}

	#
	# Get the keyrec.
	#
	rolllog_log(LOG_TMI,$rname,"keyrec file is $krf");
	$krr = opts_zonekr($krf,$rr{'zonename'});

	#
	# Adjust ZSKs in the zone's keyrec.
	#
	$ret = signer($rname,"ZSK phase 4a",$krr);
	if($ret)
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 4:  unable to adjust ZSK keyrec");
		return(-1);
	}

	#
	# Sign the zone with the Current ZSK.
	#
	$ret = signer($rname,"ZSK phase 4b",$krr);
	if($ret)
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 4:  unable to sign zone with the Current ZSK");
		return(-1);
	}

	#
	# Reload the zone.
	#
	$ret = loadzone($rndc,$rname,$rr{'zonename'},"ZSK phase 4");
	if($ret != 0)
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 4:  unable to reload zone, rc - $ret");
	}

	#
	# Set a timestamp for the completion of the ZSK roll.
	#
	rollstamp($rname,'zsk');
	clearzoneerr($rname,$rrr);
	return(5);
}

###############################################################################

#-----------------------------------------------------------------------------
# Routine:	ksk_expired()
#
# Purpose:	This routine determines if the specified zone has an expired
#		KSK and returns a boolean indicating this.  The given KSK
#		type is checked for expiration.
#
#		The zone's keyrec file name is taken from the given rollrec
#		entry.  The keyrec file is read and the zone's entry found.
#		The key keyrec of the specified key type (currently, just
#		"kskcur") is pulled from the keyrec file.  Each key in the
#		named signing set will be checked.
#
#		Key expiration is determined by comparing the key keyrec's
#		gensecs field to the current time.  The key hasn't expired
#		if the current time is less than the gensecs; the key has
#		expired if the current time is greater than the gensecs.
#
sub ksk_expired
{
	my $rname = shift;			# Name of rollrec rec.
	my $rrr = shift;			# Reference to rollrec.
	my $keyset = shift;			# Key to check.

	my %rr;					# Rollrec hash.

	my $krname;				# Name of keyrec.
	my $krec;				# Keyrec reference.
	my %set;				# Keyrec hash.

	my $khr;				# Ref to key's hash.
	my %kh;					# Key's hash.

	my @signset;				# Key's signing set.

	my $chronostr;				# Text expiration time.
	my $cronus;				# Current time.
	my $expired = 0;			# Expired-zone flag.
	my $minlife = -1;			# Minimum KSK life.
	my $minhr;				# Ref to min-key's keyrec.
	my $rolltime;				# Time roll should occur.
	my $starter;				# Time 0 for calc'ing rolltime.
	my $waitsecs;				# Time to expiration.

	#
	# Get the rollrec's hash.
	#
	%rr = %$rrr;

	#
	# If this zone is in the middle of ZSK rollover, we'll stop
	# working on KSK rollover.
	#
	if($rr{'zskphase'} > 0)
	{
		my $pstr;				# Phase string.

		$pstr = ": " . rollmgr_get_phase('KSK', $rr{'kskphase'});
		$pstr = '' if($pstr eq ": ");

		rolllog_log(LOG_TMI,$rname,"in ZSK rollover (phase $rr{'zskphase'}$pstr); not attempting KSK rollover");
		return(0);
	}

	#
	# If this zone is in the middle of rollover processing, we'll
	# immediately assume the key has expired.
	#
	return(1) if($rr{'kskphase'} > 0);

	#
	# Get the rollin' key's keyrec for our zone.
	#
	$krname = $rr{'keyrec'};
	$krec = zonekeykr($rname,$rr{'zonename'},$krname,$keyset);
	if($krec == 0)
	{
		rolllog_log(LOG_ERR,$rname,"unable to find a KSK keyrec for \"$keyset\" in \"$krname\"");
		return(0);
	}
	%set   = %$krec;

	#
	# Make sure we've got an actual set keyrec and keys.
	#
	if($set{'keyrec_type'} ne 'set')
	{
		rolllog_log(LOG_ERR,$rname,"\"$keyset\"'s keyrec is not a set keyrec");
		return(0);
	}
	if(!defined($set{'keys'}) || ($set{'keys'} eq ""))
	{
		rolllog_log(LOG_ERR,$rname,"\"$krname\" has no keys; unable to check expiration");
		zoneerr($rname,$rrr);
		return(0);
	}

	#
	# Ensure that there's a signing set.
	#
	@signset = split / /, $set{'keys'};
	if(@signset == 0)
	{
		rolllog_log(LOG_ERR,$rname,"\"$krname\" has no keys; unable to check expiration");
		zoneerr($rname,$rrr);
		return(0);
	}

	#
	# Check each key in the signing set to find the one with the shortest
	# lifespan.  We'll calculate rollover times based on that.
	#
	foreach my $keyname (@signset)
	{
		my $keylife;			# Key's life value.

		#
		# Get the key's keyrec hash.
		#
		$khr = keyrec_fullrec($keyname);
		if($khr == 0)
		{
			rolllog_log(LOG_ERR,$rname,"unable to find key \"$keyname\" in keyrec; this should not have happened");
			zoneerr($rname,$rrr);
			return(0);
		}
		%kh = %$khr;

		#
		# Ensure that required keyrec field exists.
		#
		if(!defined($kh{"ksklife"}))
		{
			rolllog_log(LOG_ERR,$rname,"keyrec does not contain a ksklife record");
			zoneerr($rname,$rrr);
			return(0);
		}

		#
		# If this key's life is shorter than any we've seen, it
		# becomes the new minimum.  If this is the first key we're
		# looking at, we'll save it as the minimum.
		#
		$keylife = $kh{'ksklife'};
		if($minlife == -1)
		{
			$minlife = $keylife;
			$minhr	 = $khr;
		}
		else
		{
			if($keylife < $minlife)
			{
				$minlife = $keylife;
				$minhr	 = $khr;
			}
		}
	}

	#
	# Get the minimum key's keyrec hash.
	#
	%kh = %$minhr;

	#
	# Get the start time on which the expiration time is based.
	#
	if($krollmethod == $RM_ENDROLL)
	{
		#
		# Ensure that required rollrec field exists.
		#
		if(!defined($rr{'ksk_rollsecs'}))
		{
			rolllog_log(LOG_INFO,$rname,"creating new ksk_rollsecs record and forcing KSK rollover");
			rollstamp($rname,'ksk');
			return(0);
		}
		$starter = $rr{'ksk_rollsecs'};
	}
	elsif($krollmethod == $RM_KEYGEN)
	{
		#
		# Ensure that required keyrec field exists.
		#
		if(!defined($kh{'keyrec_gensecs'}))
		{
			rolllog_log(LOG_ERR,$rname,"keyrec does not contain a keyrec_gensecs record");
			return(0);
		}
		$starter = $kh{'keyrec_gensecs'};
	}
	elsif($krollmethod == $RM_STARTROLL)
	{
		rolllog_log(LOG_ERR,$rname,"RM_STARTROLL not yet implemented");
		return(0);
	}

	#
	# Don't roll immediately if the rollrec file was newly created.
	#
	if($starter == 0)
	{
		rollstamp($rname,'ksk');
		return(0);
	}

	#
	# Get the key's expiration time.
	#
	$rolltime = $starter + $minlife;

	#
	# Get the current time.
	#
	$cronus = gmtime(time);
	$cronus = str2time($cronus);

	#
	# Figure out the log message we should give.
	#
	$waitsecs = $rolltime - $cronus;
	if($waitsecs >= 0)
	{
		$chronostr = timetrans($waitsecs);
		rolllog_log(LOG_EXPIRE,$rname,"        expiration in $chronostr\n");
		display("expiration $rname 0 KSK $waitsecs");
	}
	else
	{
		$waitsecs = $cronus - $rolltime;
		$chronostr = timetrans($waitsecs);
		rolllog_log(LOG_EXPIRE,$rname,"        expired $chronostr ago\n");
		display("kskphase $rname 0");
	}

	#
	# The key has expired if the current time has passed the key's lifespan.
	# The key has not expired if the key's lifespan has yet to reach the
	# current time.
	#
	$expired = 1 if($cronus > $rolltime);

	#
	# If the keyset has not expired and the zone file has been modified,
	# we'll sign the zone file.  We won't created any new keys or take
	# any other rollover actions.
	#
	zonemodified($rrr,$rname) if(!$expired);

	#
	# Return the success/failure indication.
	#
	return($expired);
}

#-----------------------------------------------------------------------------
# Routine:	ksk_phaser()
#
# Purpose:	Move the specified zone's KSKs through the appropriate phases.
#
#		Phases:
#			1 - wait for cache data to expire
#			2 - generate a new (published) KSK
#			3 - wait for the old DNSKEY RRset to expire from caches
#			4 - roll the KSKs
#			5 - transfer new keyset to the parent
#			6 - wait for parent to publish the new DS record
#			7 - reload the zone
#
sub ksk_phaser
{
	my $rname = shift;		# Zone name.
	my $rrr	  = shift;		# Reference to rollrec.
	my $ph;				# Zone's current rollover phase.

	#
	# Get this rollrec record's current phase.
	#
	$ph = $rrr->{'kskphase'};

	#
	# Work on this rollrec's phase.
	#
	$ph = phasecmd(\&nextphase,$rname,$rrr,'normal','KSK')	if($ph == 0);
	$ph = phasecmd(\&phasewait,$rname,$rrr,'ksk1')		if($ph == 1);
	$ph = phasecmd(\&ksk_phase2,$rname,$rrr,'ksk2')		if($ph == 2);
	$ph = phasecmd(\&phasewait,$rname,$rrr,'ksk3')		if($ph == 3);
	$ph = phasecmd(\&ksk_phase4,$rname,$rrr,'ksk4')		if($ph == 4);
	$ph = phasecmd(\&ksk_phase5,$rname,$rrr,'ksk5')		if($ph == 5);
	$ph = phasecmd(\&ksk_phase6,$rname,$rrr,'ksk6')		if($ph == 6);
	$ph = phasecmd(\&ksk_phase7,$rname,$rrr,'ksk7')		if($ph == 7);
}

#-----------------------------------------------------------------------------
# Routine:	ksk_phase2()
#
# Purpose:	Perform the phase 2 steps of the KSK rollover.  These are:
#			- generate a new KSK to be the Published KSK
#			- add the new Published KSK to the zone file
#			- re-sign the zone file with the Current KSK, the (new)
#			  Published KSK, and the Current ZSK
#			- reload the zone file
#		The first three steps are handled by zonesigner.
#
sub ksk_phase2
{
	my $rname = shift;		# Name of rollrec.
	my $rrr = shift;		# Reference to rollrec.

	my %rr = %$rrr;			# Rollrec hash.

	my $krf;			# Rollrec's keyrec name.
	my $krr;			# Keyrec reference.

	my $ret;			# Result from command executions.

	#
	# Get the rollrec's associated keyrec file and ensure that it exists.
	#
	$krf = $rr{'keyrec'};
	if(!$krf || ($krf eq ""))
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 2:  no keyrec for zone specified");
		return(-1);
	}
	if(! -e $krf)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 2:  keyrec \"$krf\" for zone does not exist");
		return(-1);
	}

	#
	# Get the keyrec.
	#
	$krr = opts_zonekr($krf,$rr{'zonename'});

	#
	# Sign the zone with a new Published KSK.
	#
	$ret = signer($rname,"KSK phase 2",$krr);
	if($ret)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 2:  unable to sign zone with the Published KSK");
		return(-1);
	}

	#
	# Reload the zone.
	#
	$ret = loadzone($rndc,$rname,$rr{'zonename'},"KSK phase 2");
	if($ret != 0)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 2:  unable to reload zone, rc - $ret");
	}

	#
	# On to the phase 3.
	#
	return(3);
}

#-----------------------------------------------------------------------------
# Routine:	ksk_phase4()
#
# Purpose:	Perform the phase 4 steps of the KSK rollover.  These are:
#			- delete the Current KSK from the zone file
#			- move the Published KSK to be the Current KSK
#			- sign the zone file with the (new) Current KSK
#		These steps are handled by zonesigner.
#
sub ksk_phase4
{
	my $rname = shift;		# Name of rollrec.
	my $rrr = shift;		# Reference to rollrec.

	my %rr = %$rrr;			# Rollrec hash.
	my $krf;			# Rollrec's keyrec name.
	my $krr;			# Keyrec reference.

	my $ret;			# Result from command executions.

	#
	# Get the rollrec's associated keyrec file and ensure that it exists.
	#
	$krf = $rr{'keyrec'};
	if(!$krf || ($krf eq ""))
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 4:  no keyrec for zone specified");
		return(-1);
	}
	if(! -e $krf)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 4:  keyrec \"$krf\" for zone does not exist");
		return(-1);
	}

	#
	# Get the keyrec.
	#
	$krr = opts_zonekr($krf,$rr{'zonename'});

	#
	# Roll the Published KSK to the Current KSK.
	#
	$ret = signer($rname,"KSK phase 4",$krr);
	if($ret)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 4:  unable to roll the Published KSK to the Current KSK");
		return(-1);
	}

	#
	# Now to phase 5.
	#
	return(5);
}

#-----------------------------------------------------------------------------
# Routine:	ksk_phase5()
#
# Purpose:	Perform the phase 5 steps of the KSK rollover.  These are:
#			- notify the admin that the new keyset should be
#			  transferred to the parent zone
#
#		This is currently handled by telling the admin to transfer
#		the keyset.  It would be nice to have an automated method
#		of keyset transfer; one may be added in future.
#
#
sub ksk_phase5
{
	my $rname = shift;		# Name of rollrec.
	my $rrr = shift;		# Reference to rollrec.

	my $ret;			# Return code from mail
	my $auto = 0;			# Automatic-transfer flag.

	if($auto)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 5:  automatic keyset transfer not yet supported");
		return(-1);
	}
	elsif(($dtconf{'admin-email'}  eq 'nomail') ||
	      ($rrr->{'administrator'} eq 'nomail'))
	{
		rolllog_log(LOG_INFO,$rname,"KSK phase 5:  admin must transfer keyset");
	}
	else
	{
		my $subject;			# Subject for email to admin.
		my $msg;			# Message to admin.
		my $admin;			# Zone's administrator.

		$subject = "assistance needed with KSK rollover of zone $rname";
		$msg = "
The zone \"$rname\" is in the middle of KSK rollover.  In order for rollover
to continue, its keyset must be transferred to its parent.";

		#
		# If this zone has its own administrator listed, we won't use
		# the default.
		#
		if(exists($rrr->{'administrator'}))
		{
			$admin = $rrr->{'administrator'};
			$ret = dt_adminmail($subject,$msg,$admin);
		}
		else
		{
			$ret = dt_adminmail($subject,$msg);
		}

		if($ret == 1)
		{
			rolllog_log(LOG_INFO,$rname,"KSK phase 5:  admin notified to transfer keyset");
		}
		else
		{
			rolllog_log(LOG_INFO,$rname,"KSK phase 5:  admin must transfer keyset");
			rolllog_log(LOG_ERR,$rname,"KSK phase 5:  invalid admin; unable to notify about transferring keyset");
		}
	}

	#
	# Pressing on to phase 6.
	#
	return(6);
}

#-----------------------------------------------------------------------------
# Routine:	ksk_phase6()
#
# Purpose:	Perform the phase 6 steps of the KSK rollover.  These are:
#			- wait for the parent to publish the DS record
#
#		This is currently handled by the admin telling us that the
#		DS record has been published.  It would be nice to have an
#		automated method of determining this; one may be added in
#		future.
#
sub ksk_phase6
{
	my $rname = shift;		# Name of rollrec.
	my $rrr = shift;		# Reference to rollrec.

	my $auto = 0;			# Automatic-transfer flag.

	if($auto)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 6:  automatic DS-record determination not yet supported");
		return(-1);
	}
	else
	{
		rolllog_log(LOG_INFO,$rname,"KSK phase 6:  waiting for parental publication of DS record");
	}

	return(6);
}

#-----------------------------------------------------------------------------
# Routine:	ksk_phase7()
#
# Purpose:	Perform the phase 7 steps of the KSK rollover.  These are:
#			- load the zone
#			- archive keys that need to be archived
#			- move to phase 0
#			- save a timestamp for rollover completion
#
#
sub ksk_phase7
{
	my $rname = shift;		# Name of rolling rollrec.
	my $rrr = shift;		# Reference to zone's rollrec record.

	my %rr = %$rrr;			# Rollrec hash.
	my $krf;			# Rollrec's keyrec name.
	my $zname;			# Name of rolling zone.
	my $keyarch_cmd;		# Keyarch command string.

	my $ret;			# Result from command executions.

	#
	# Reload the zone.
	#
	$ret = loadzone($rndc,$rname,$rr{'zonename'},"KSK phase 7");
	if($ret != 0)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 7:  unable to reload zone, rc - $ret");
	}

	#
	# Set up the keyarch command we'll be executing.
	#
	$krf = $rr{'keyrec'};
	$zname = $rr{'zonename'};
	$keyarch_cmd = "$keyarch -dtconf $dtcf -zone $zname $krf -verbose";

	rolllog_log(LOG_TMI,$rname,"keyarch:  running <$keyarch_cmd>");
	$ret = runner($rname,"$keyarch_cmd",$krf,1,1);
	if($ret < 0)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 7:  unable to archive KSK keys, rc - $ret");

		zoneerr($rname,$rrr);
		return(-1);
	}
	else
	{
		rolllog_log(LOG_INFO,$rname,"KSK phase 7:  zone, key files archived");
		clearzoneerr($rname,$rrr);
	}

	#
	# Set a timestamp for the completion of the KSK roll.
	#
	rollstamp($rname,'ksk');

	#
	# Returning to normal rollover state.
	#
	return(8);
}

###############################################################################

#-----------------------------------------------------------------------------
# Routine:	maxttl()
#
# Purpose:	Calculate the zone's maximum TTL value, based on the largest
#		TTL in its zone file.
#
sub maxttl
{
	my $signdb = shift;		# Signed zone's db filename.

	my $rrsref;			# Reference to zone's resource records.
	my @rrs;			# Zone's resource records.
	my $numrrs;			# Number of resource records in zone.
	my $rrref;			# Reference to a resource record.
	my %rr;				# A resource record to examine.
	my $maxttl = -1;		# Zone's maximum time-to-live value.
	my $ttl;			# Time-to-live value from a record.

	#
	# Ensure the zone file exists.
	#
	if(! -e $signdb)
	{
		rolllog_log(LOG_ERR,$signdb,"zone file \"$signdb\" does not exist");
		return(-1);
	}

	#
	# Get the zone's resource record collection.
	#
	$rrsref = Net::DNS::ZoneFile::Fast::parse(file => $signdb);

	#
	# Get the number of resource records in the zone.
	#
	@rrs = @$rrsref;
	$numrrs = @rrs;

	#
	# Look at each resource record and save the largest value.
	#
	for(my $ind=0;$ind<$numrrs;$ind++)
	{
		$rrref = $rrs[$ind];
		%rr = %$rrref;

		$ttl = $rr{'ttl'};
		$maxttl = $ttl if($ttl > $maxttl);
	}

	#
	# Return the zone's maximum TTL value to our caller.
	#
	return($maxttl);
}

#-----------------------------------------------------------------------------
# Routine:	ttlexpire()
#
# Purpose:	Returns a boolean indicating if we can move to the next phase
#		of rollover.  This is calculated by adding twice the TTL
#		length to the time we entered this phase.  If this is greater
#		than the current time, then we must wait a bit longer.  If
#		this is less than the current time, then we can proceed to
#		the next rollover phase.
#
# Return Values:
#		0 - Zone's expiry date has not passed.
#		1 - Zone's expiry date has passed.
#
sub ttlexpire
{
	my $rname   = shift;			# Name of rollrec.
	my $rrr	    = shift;			# Reference to rollrec.
	my $phase   = shift;			# Zone's current phase.
	my $keytype = shift;			# Type of key.

	my $phasedesc = rollmgr_get_phase($keytype, $phase);

	my %rr;					# Rollrec hash.

	my $zonefile;				# Zone file.
	my $maxttl;				# Zone's maximum TTL value.
	my $phstart;				# Start of zone's phase.

	my $curtime;				# Current time string.
	my $curtempus;				# Current time in seconds.
	my $endtempus;				# End-date in seconds.

	my $timediff;				# Time until expiration.
	my $tdstr;				# String of timediff.

	#
	# Get a few fields from the rollrec.
	#
	%rr = %$rrr;
	$zonefile = $rr{'zonefile'};
	$phstart  = $rr{'phasestart'};

	#
	# Get the signed zonefile's maximum TTL and save it into the
	# rollrec.  We'll then double it as a safety margin.
	#
	$maxttl	= maxttl($zonefile);
	rollrec_setval($rname,"maxttl",$maxttl);
	$maxttl	*= 2;

	#
	# Get the current time in seconds.
	#
	$curtime = gmtime;
	$curtempus = str2time($curtime);

	#
	# Get the phase's end time by adding its start time (in seconds)
	# to the TTL.
	#
	$endtempus = str2time($phstart);
	$endtempus += $maxttl;

	#
	# Give any desired verbose output.
	#
	if($verbose)
	{
		my $endtime;				# End-date string.

		$endtime = ctime($endtempus);
		chomp $endtime;

		rolllog_log(LOG_TMI,$rname,"$keytype phase $phase rollover TTL check");
		rolllog_log(LOG_TMI,$rname,"$keytype phase $phase endtime\t$endtime");
		rolllog_log(LOG_TMI,$rname,"$keytype phase $phase curtime\t$curtime");
	}

	#
	# Return success if we've passed the zone's adjusted end-date.
	# Return failure (not expired) if the zone's adjusted end-date
	# is in the future.
	#
	return(1) if($curtempus >= $endtempus);

	$timediff = $endtempus - $curtempus;
	$tdstr = timetrans($timediff);

	$phasedesc = " ($phasedesc)";
	$phasedesc = '' if($phasedesc eq ' ()');

	rolllog_log(LOG_INFO,$rname,"$keytype phase $phase$phasedesc; cache expires in $tdstr");
	display("expiration $rname $phase $keytype $timediff");

	return(0)
}

#-----------------------------------------------------------------------------
# Routine:	holddownexpire()
#
# Purpose:	Returns a boolean indicating if we can move to the next phase
#		of rollover based on the hold-down timer of RFC5011,
#		which is 30 days long.
#
# Return Values:
#		0 - Zone's hold-down timer is still active.
#		1 - Zone's hold-down timer date/time has passed.
#
sub holddownexpire
{
	my $rname   = shift;			# Name of rollrec.
	my $rrr	    = shift;			# Reference to rollrec.
	my $phase   = shift;			# Zone's current phase.
	my $keytype = shift;			# Type of key.

	my $phasedesc = rollmgr_get_phase($keytype, $phase);

	my %rr;					# Rollrec hash.

	my $zonefile;				# Zone file.
	my $maxttl;				# Zone's maximum TTL value.
	my $phstart;				# Start of zone's phase.
	my $holddowntime;			# Hold-down time.

	my $curtime;				# Current time string.
	my $curtempus;				# Current time in seconds.
	my $endtempus;				# End-date in seconds.

	my $timediff;				# Time until expiration.
	my $tdstr;				# String of timediff.

	my $addholddown;

	#
	# This is only needed for phase 3 (currently, at least.)
	#
	return(1) if($phase != 3);

	#
	# Get a few fields from the rollrec.
	#
	%rr = %$rrr;
	$zonefile = $rr{'zonefile'};
	$phstart  = $rr{'phasestart'};

	#
	# By default, we use a hold-down time of 60 days which is twice what
	# is required for validators to use as a add-hold-time (RFC5011).
	# (Ideally this should be longer and can be set by the user if needed.)
	#
	$holddowntime =
	    Net::DNS::ZoneFile::Fast::ttl_fromtext($rr{'holddowntime'});

	#
	# Default to 60 days.
	# lsdnssec should change too if this default is changed.
	#
	$holddowntime ||= 2 * 30 * 24 * 60 * 60;

	#
	# Get the current time in seconds.
	#
	$curtime = gmtime;
	$curtempus = str2time($curtime);

	#
	# Get the phase's end time (in seconds) and add the hold-down.
	#
	$endtempus = str2time($phstart);
	$endtempus += $holddowntime;

	#
	# Give any desired verbose output.
	#
	if($verbose)
	{
		my $endtime;				# End-date string.

		$endtime = ctime($endtempus);
		chomp $endtime;

		rolllog_log(LOG_TMI,$rname,"$keytype phase $phase hold-down time check");
		rolllog_log(LOG_TMI,$rname,"$keytype phase $phase endtime\t$endtime");
		rolllog_log(LOG_TMI,$rname,"$keytype phase $phase curtime\t$curtime");
	}

	#
	# Return success if we've passed the zone's adjusted end-date.
	# Return failure (not expired) if the zone's adjusted end-date
	# is in the future.
	#
	return(1) if($curtempus >= $endtempus);

	$timediff = $endtempus - $curtempus;
	$tdstr = timetrans($timediff);

	$phasedesc = " ($phasedesc)";
	$phasedesc = '' if($phasedesc eq ' ()');

	rolllog_log(LOG_INFO,$rname,"$keytype phase $phase$phasedesc; hold-down timer expires in $tdstr");
	display("holddown $rname $phase $keytype $timediff");

	return(0)
}

#-----------------------------------------------------------------------------
# Routine:	rollstamp()
#
# Purpose:	This routine sets the timestamp records for a KSK or
#		ZSK roll in the rollrec file.
#
sub rollstamp
{
	my $rname  = shift;			# Rollrec name.
	my $prefix = shift;			# Key-type prefix.

	my $date;				# Date key.
	my $secs;				# Seconds key.

	my $timesecs;				# Current-time seconds count.
	my $timestr;				# Current-time string.

	#
	# Build the rollrec keys we'll be using.
	#
	$date = $prefix . "_rolldate";
	$secs = $prefix . "_rollsecs";

	#
	# Get the timestamps.
	#
#	$timesecs = time();
#	$timestr  = gmtime($timesecs);
	$timestr = gmtime(time);
	$timesecs = str2time($timestr);

	#
	# Set the rollrec records to now and write the file.
	#
	rollrec_setval($rname,$date,$timestr);
	rollrec_setval($rname,$secs,$timesecs);
	rollrec_write();
}

#-----------------------------------------------------------------------------
# Routine:	phasecmd()
#
# Purpose:	Run a list of commands for this rollover phase.  If a list is
#		not defined for this phase, then we'll use the default action.
#
sub phasecmd
{
	my $phasefunc = shift;		# Reference to phase function.
	my $rname = shift;		# Zone name.
	my $rrr = shift;		# Reference to rollrec.
	my $phase = shift;		# Phase we're handling.
	my $ptaux = shift;		# Auxiliary phase type.

	my $progkey = "prog-$phase";	# Config. key for phase's programs.
	my $cmdlist;			# Execution flag.
	my @cmds;			# List of commands to run for phase.
	my $ret;			# Return value from phase function.

	my %rr = %$rrr;			# Rollrec hash.
	my $cmdargs;			# Arguments to the command.
	my $phasetype;			# Phase type.
	my $phasenum;			# Phase number.
	my $newphase;			# New phase number.

	#
	# Get the command list for this rollover phase.  Force the default
	# if a command list isn't defined for the phase.
	#
	if(!defined($dtconf{$progkey}) || ($dtconf{$progkey} eq ''))
	{
		$cmdlist = 'default';
	}
	else
	{
		$cmdlist = $dtconf{$progkey}
	}
	@cmds = split /!/, $cmdlist;

	#
	# Break out the phase atoms.  If this is a normal phase, then
	# we'll be alchemists and transmute the atoms we need.
	#
	if($phase eq 'normal')
	{
		$phasetype = 'normal';
		$phasenum  = 1;
	}
	else
	{
		$phase = lc($phase);
		$phase =~ /([kz]sk)(\d)/;
		$phasetype = $1;
		$phasenum  = $2;

		#
		# Set a variable for phasewait().
		#
		$ptaux = $phasetype if(! defined($ptaux));
	}

	#
	# Run the commands defined for this phase.  The default commands
	# are handled internally to rollerd.
	#
	foreach my $cmd (@cmds)
	{
		#
		# Get rid of any leading or trailing blanks.
		#
		$cmd =~ s/^\s*(.*?)\s*$/$1/;

		#
		# Take this phase's normal rollover action if the command
		# is "default".
		#
		if($cmd =~ /^default$/i)
		{
			#
			# Run the phase-specific routine.
			#
			# When this change was made, nextphase() (and the old
			# kskphase() and zskphase()) were the only phasefuncs
			# that used the third and fourth arguments.  The fourth
			# was originally $phasetype, but it's being changed to
			# $ptaux.
			#
			$ret = $phasefunc->($rname,$rrr,$phasenum,$ptaux);
			return($phasenum) if($ret < 0);

			#
			# This is a special case for when we're in normal
			# rollover.
			# (Yes, in this situation, normal is a special case.)
			#
			$phasenum = 0 if($phase eq '0');

			#
			# Save the return code as our new phase.
			#
			$newphase = $ret;
		}
		else
		{
			#
			# Set up the arguments for the command.
			#
			$cmdargs = "$rr{'zonename'} $phase $rname $rollrecfile $rr{'keyrec'}";

			#
			# Execute the phase's locally defined program.
			#
			$ret = localprog($rname,$cmd,$cmdargs,$phase);

			#
			# Stay in this phase if this command didn't succeed.
			#
			return($phasenum) if($ret != 0);
		}


	}

	#
	# If we've reached the final rollover phase, we'll go to non-rollover.
	#
	if(($phase eq 'ksk7') || ($phase eq 'zsk4'))
	{
		$newphase = 0;
	}

	#
	# Special handling if the phase has changed, followed by special
	# handling if it hasn't.
	#
	if($phasenum != $newphase)
	{
		#
		# Set the new KSK phase.
		#
		if($phase =~ /^ksk/)
		{
			nextphase($rname,$rrr,$newphase,'KSK');
		}

		#
		# Set the new ZSK phase.
		#
		if($phase =~ /^zsk/)
		{
			nextphase($rname,$rrr,$newphase,'ZSK');
		}

		zonemodified($rrr,$rname) if($newphase == 0);
	}
	else
	{
		#
		# Re-sign the zone file if it has been modified more recently
		# than the signed zone file.
		#
		zonemodified($rrr,$rname);
	}

	#
	# Return the phase number we should be in.
	#
	return($newphase);
}

#-----------------------------------------------------------------------------
# Routine:	phasewait()
#
# Purpose:	Check if this zone's rollover wait phase is over.
#		The zone's phase number -- current or new -- is returned.
#		KSKs will also be checked for trust-anchorship and if the
#		hold-down timer has expired.
#
sub phasewait
{
	my $rname     = shift;			# Name of rollrec.
	my $rrr	      = shift;			# Reference to rollrec.
	my $phase     = shift;			# Rollover phase.
	my $phasetype = shift;			# Rollover phase type.

	#
	# Make sure we've got the latest and greatest rollrec.
	#
	$rrr = rollrec_fullrec($rname);

	#
	# Check if we can go to the next rollover phase.  If not, we'll
	# go to the next rollrec entry and return to this later.
	#
	if($phasetype =~ /zsk/i)
	{
		if(!ttlexpire($rname,$rrr,$phase,'ZSK'))
		{
			return($phase);
		}
	}
	else
	{
		return($phase) if(!ttlexpire($rname,$rrr,$phase,'KSK'));
		return($phase) if((boolconvert($rrr->{'istrustanchor'}) == 1) &&
				  !holddownexpire($rname,$rrr,$phase));
	}

	#
	# Return the next phase number.
	#
	return($phase + 1);
}

#-----------------------------------------------------------------------------
# Routine:	nextphase()
#
# Purpose:	Moves a rollrec into the next rollover phase, setting both the
#		phase number and the phase start time.
#
sub nextphase
{
	my $rname	= shift;			# Name of rollrec.
	my $rrr		= shift;			# Rollrec reference.
	my $phase	= shift;			# New phase.
	my $phasetype	= shift;			# Type of rollover.

	my $phasedesc;					# Human phase descr.
	my $ptlc;					# Lowercase phasetype.
	my $phasekey;					# Phase hashkey.
	my $phaselife;					# Life hashkey.
	my $curphase;					# Current phase hashkey.

	my %rr = %$rrr;					# Rollrec hash.

	my $krname;					# Name of key's rollrec.
	my $krec;					# Key's keyrec.

	my $setrec;					# Set's keyrec.
	my $setlist;					# Set's key list.

	my $exptime;					# Key's time to expiry.
	my $chronostr;					# Pretty rollover time.

	#
	# Set up the phase description.
	#
	$phasedesc = rollmgr_get_phase($phasetype,$phase);
	$phasedesc = " ($phasedesc)";
	$phasedesc = '' if($phasedesc eq ' ()');

	#
	# Set up some phasetype-based hash keys.
	#
	$ptlc = lc($phasetype);
	$phasekey = $ptlc . 'phase';
	$phaselife = $ptlc . 'life';
	$curphase = $ptlc . 'cur';

	#
	# Give a log message about this rollover phase.
	#
	if($phase == 1)
	{
		rolllog_log(LOG_TMI,$rname,"starting $phasetype rollover");
	}
	else
	{
		rolllog_log(LOG_TMI,$rname,"moving to $phasetype phase $phase$phasedesc");
	}

	rolllog_log(LOG_PHASE,$rname,"$phasetype phase $phase$phasedesc");

	#
	# Get the latest and greatest rollrec file.
	#
	rollrec_close();
	rollrec_read($rollrecfile);

	#
	# Change the zone's phase and plop it on disk.
	#
	$rrr->{$phasekey} = $phase;
	rollrec_setval($rname,$phasekey,$phase);
	rollrec_settime($rname);
	rollrec_write();
	rollrec_close();
	rollrec_read($rollrecfile);

	#
	# Get the rollin' key's keyrec for our zone.
	#
	$krname = $rr{'keyrec'};
	$setrec = zonekeykr($rname,$rr{'zonename'},$krname,$curphase);
	if($setrec == 0)
	{
		rolllog_log(LOG_ERR,$rname,"unable to find a keyrec for the $curphase signing set in \"$krname\"");
		return(0);
	}

	#
	# Make sure we've got an actual set keyrec and keys.
	#
	if($setrec->{'keyrec_type'} ne 'set')
	{
		rolllog_log(LOG_ERR,$rname,"\"$krname\"'s keyrec is not a set keyrec; unable to move to $phasetype phase $phase");
		return(0);
	}
	if(!defined($setrec->{'keys'}) || ($setrec->{'keys'} eq ""))
	{
		rolllog_log(LOG_ERR,$rname,"\"$krname\" has no keys; unable to move to $phasetype phase $phase");
		return(0);
	}

	#
	# Find the key with the shortest lifetime.
	#
	$setlist = $setrec->{'keys'};
	foreach my $key (split / /, $setlist)
	{
		my $lifetime = keyrec_recval($key,$phaselife);
		if(($exptime == 0) || ($lifetime < $exptime))
		{
			$exptime = $lifetime;
		}
	}

	#
	# Send phase info to the display program.
	#
	$exptime = ($rrr->{'maxttl'} * 2) if($phase != 0);
	display("$phasekey $rname $phase $exptime");

	$chronostr = timetrans($exptime);
	rolllog_log(LOG_INFO,$rname,"    $phasetype expiration in $chronostr");

	#
	# Reset the phasestart field if we've completed a rollover cycle.
	#
	if($phase == 0)
	{
		rollrec_settime($rname);
		rollrec_write();
		rollrec_close();
		rollrec_read($rollrecfile);
	}
	return(0);
}

#-----------------------------------------------------------------------------
# Routine:	localprog()
#
# Purpose:	This routine runs a locally-configured command as part or all
#		of a rollover phase.  The programs must be configured in the
#		dnssec-tools.conf file in order to be run here.
#
sub localprog
{
	my $rname = shift;			# Rollrec name.
	my $cmd = shift;			# Command.
	my $cmdargs = shift;			# Command arguments.
	my $phase = shift;			# Phase we're in.
	my $out = '';				# Command output.
	my $ret;				# Execution return code.

	#
	# Tell the world about this command.
	#
	rolllog_log(LOG_INFO,$rname,"executing local program \"$cmd $cmdargs\"");

	#
	# Execute the local command.  We'll save the stdout and stderr output
	# in case it's needed later.  (Well..., we don't do anything with it
	# right now, but someone might someday want it.
	#
	open(LPROG,"$cmd $cmdargs 2>&1 |");
	while(<LPROG>)
	{
		$out .= $_;
	}
	chomp $out;
	close(LPROG);
	$ret = $? >> 8;

	#
	# Give a message based on return code.
	#
	if($ret > 0)
	{
		rolllog_log(LOG_ERR,$rname,"$phase command $cmd returned error $ret");
	}
	else
	{
		rolllog_log(LOG_INFO,$rname,"$phase command $cmd succeeded");
	}

	return($ret);
}

#-----------------------------------------------------------------------------
# Routine:	signer()
#
# Purpose:	Signs a zone with a specified ZSK.
#
#		On success, the return value of the zone-signing command
#			is returned.
#		On failure, "" is returned.
#
sub signer
{
	my $rname  = shift;			# Name of rollrec.
	my $zsflag = shift;			# Flag for key generation.
	my $krr	   = shift;			# Reference to zone's keyrec.

	my $rrr;				# Reference to zone's rollrec.
	my $zsargs;				# Zonesigner args from rollrec.

	my $zonefile;				# Zone file from keyrec.
	my $zonesigned;				# Signed zone file from keyrec.
	my $cmdstr;				# Command to be executed.
	my $initial = 0;			# Initial-signing flag.
	my $signonly = '';			# Sign-only flag.

	#
	# If we've been requested to sign a quiescent zone, we'll set a
	# flag and remove the marker from the phase indicator.
	#
	if($zsflag =~ / -signonly/)
	{
		$signonly = '-signonly';
		$zsflag =~ s/ -signonly//;
	}

	#
	# Convert the caller's version of $zsflag into what it actually
	# means for the zonesigner execution.
	#
	if($zsflag eq 'KSK phase 2')
	{
		$zsflag = '-newpubksk';
	}
	elsif($zsflag eq 'KSK phase 4')
	{
		$zsflag = '-rollksk';
	}
	elsif($zsflag eq 'ZSK phase 2' || $zsflag eq 'ZSK phase 3')
	{
		$zsflag = '-usezskpub';
	}
	elsif($zsflag eq 'ZSK phase 4')
	{
		signer($rname,'ZSK phase 4a',$krr);
		signer($rname,'ZSK phase 4b',$krr);
		return;
	}
	elsif($zsflag eq 'ZSK phase 4a')
	{
		$zsflag = '-rollzsk';
	}
	elsif($zsflag eq 'ZSK phase 4b')
	{
		$zsflag = '';
	}
	elsif($zsflag eq 'always-sign')
	{
		$zsflag = '-usezskpub';
	}
	elsif($zsflag eq 'initial')
	{
		$zsflag	 = '-genkeys';
		$initial = 1;
	}
	elsif($zsflag =~ /[KZ]SK phase [013567]/)
	{
		$zsflag	 = '';
	}

	#
	# Get the rollrec and any user-specified zonesigner arguments
	# for this zone.
	#
	$rrr = rollrec_fullrec($rname);
	$zsargs = $rrr->{'zsargs'};

	#
	# If there are any user-specified zonesigner arguments, add them
	# to the zonesigner options.  If there aren't any, we'll add
	# any global zonesigner args (from rollerd's -zsargs option).
	#
	if($zsargs ne '')
	{
		$zsflag = "$zsflag $zsargs";
	}
	else
	{
		$zsflag .= " $gzsargs" if($gzsargs ne '');
	}

	#
	# If the -zone flag wasn't specified, we'll force it in here.
	#
	if($zsflag !~ /-zone/)
	{
		$zsflag .= " -zone $rrr->{'zonename'}";
	}

	#
	# If the -krf flag wasn't specified, we'll force it in here.
	#
	if($zsflag !~ /-krf/)
	{
		$zsflag .= " -krf $rrr->{'keyrec'}";
	}

	#
	# If the -krf flag wasn't specified, we'll force it in here.
	#
	if($signonly)
	{
		$zsflag .= " -signonly";
	}

	#
	# Set up a few data for the zonesigner command.  Normally, these
	# will be taken from the keyrec file.  In the unusual(?) case of
	# needing an initial signing, these will be generated.
	#
	if($initial)
	{
		$zonefile   = $rrr->{'zonename'};
		$zonesigned = '';
	}
	else
	{
		#
		# Dig a few data out of the zone's keyrec file.
		#
		$zonefile = getkrval($rname,$krr,"zonefile");
		return("") if($zonefile eq "");

		$zonesigned = getkrval($rname,$krr,"signedzone");
		return("") if($zonesigned eq "");
	}

	#
	# Build the command to execute.
	#
	$cmdstr = "$zonesigner -rollmgr rollerd -dtconfig $dtcf $zsflag $zonefile $zonesigned";

	rolllog_log(LOG_INFO,$rname,"executing \"$cmdstr\"");

	#
	# Have zonesigner sign the zone for us.
	#
	$ret = runner($rname,$cmdstr,$rrr->{'keyrec'},1,0);
	$ret >>= 8;

	if($ret != 0)
	{
		skipnow($rname);
		zoneerr($rname,$rrr);
	}
	else
	{
		$rrr->{'signed'} = 1;
		$wassigned = 1;
	}

	return($ret);
}

#-----------------------------------------------------------------------------
# Routine:	runner()
#
# Purpose:	This routine executes another command.
#
sub runner
{
	my $rname = shift;			# Name of rollrec rec.
	my $cmd = shift;			# Command to execute.
	my $krf = shift;			# Zone's keyrec file.
	my $errflag = shift;			# On-error flag.
	my $negerrflag = shift;			# Only-negative-error flag.

	my $ret;				# Command's return code.
	my $out = '';				# Command's output.

	#
	# Close the current keyrec file.
	#
	keyrec_discard();

	#
	# Execute the specific command.
	#
	rolllog_log(LOG_TMI,$rname,"executing \"$cmd\"");

	#
	# Execute the given command.  We'll save the stdout and stderr
	# output in case it's needed later.
	#
	$runerr = 0;
	open(ZS,"$cmd 2>&1 |") || runerr();
	while(<ZS>)
	{
		$out .= $_;
	}
	chomp $out;
	close(ZS);
	$ret = $? >> 8;

	#
	# If the error flag is set and the command exited with an error,
	# we'll log the output.
	#
	if($errflag)
	{
		if((! $negerrflag && ($runerr != 0)) ||
		   (  $negerrflag && ($runerr <  0)))
		{
			$out =~ s/^	if zonesigner appears hung, .*\n$//ms;
			$out =~ s/^	\(see the \"Entropy\" section .*\n$//ms;

			rolllog_log(LOG_ERR,$rname,"execution error for command \"$cmd\"");
			rolllog_log(LOG_ERR,$rname,"error output - \"$out\"");
		}
	}

	#
	# Re-read current keyrec file.
	#
	keyrec_read($krf);

	return($runerr);
}

#-----------------------------------------------------------------------------
# Routine:	runerr()
#
# Purpose:	This routine sets a global flag indicating an error has
#		been encountered when running an external command.
#
sub runerr
{
	$runerr = 1;
}

#-----------------------------------------------------------------------------
# Routine:	zonekeykr()
#
# Purpose:	This routine returns the specified key's keyrec from the
#		specified zone from the specified keyrec file.
#		This routine is big on specified things.
#
sub zonekeykr
{
	my $rname = shift;			# Name of rollrec record.
	my $zname = shift;			# Name of zone.
	my $krname = shift;			# Name of keyrec.
	my $key = shift;			# Key to check.

	my $ret;				# Return code.
	my $krec;				# Keyrec reference.
	my %kh;					# Keyrec hash.

	#
	# Close the open keyrec file.
	#
	keyrec_discard();

	#
	# Read the keyrec file.
	#
	$ret = keyrec_read($krname);
	if($ret < 0)
	{
		if($ret == -3)
		{
			rolllog_log(LOG_ERR,$rname,"keyname collision in keyrec \"$krname\"; marking $rname as skipped");
		}
		else
		{
			rolllog_log(LOG_ERR,$rname,"unable to read keyrec \"$krname\"; marking $rname as skipped");
		}
		skipnow($rname);
	}

	#
	# Get the zone's keyrec and complain if it doesn't exist.
	#
	$krec = keyrec_fullrec($zname);
	if(!defined($krec))
	{
		rolllog_log(LOG_ERR,$rname,"keyrec file \"$krname\" does not contain a keyrec for zone \"$zname\"");
		return(0);
	}
	%kh   = %$krec;

	#
	# Get the key's keyrec and complain if it doesn't exist.
	#
	$key = $kh{$key};
	$krec = keyrec_fullrec($key);
	if(!defined($krec))
	{
		rolllog_log(LOG_ERR,$rname,"keyrec file \"$krname\" does not contain a keyrec for key \"$key\"");
		return(0);
	}

	#
	# Return the keyrec reference.
	#
	return($krec);
}

#-----------------------------------------------------------------------------
# Routine:	getkrval()
#
# Purpose:	This routine returns the value of a specified field in a
#		keyrec.  Error checking is performed to ensure that the
#		field exists in the keyrec and that it doesn't have an
#		empty value.
#
sub getkrval
{
	my $rname = shift;				# Rollrec's name.
	my $krr	  = shift;				# Keyrec reference.
	my $field = shift;				# Keyrec's field.

	my %kh = %$krr;					# Keyrec hash.
	my $val;					# Field's value.

	#
	# Ensure that the requested field exists.
	#
	if(!defined($kh{$field}))
	{
		rolllog_log(LOG_ERR,$rname,"keyrec has no entry for \"$field\"");
		return("");
	}

	#
	# Get the field from the keyrec.
	#
	$val = $kh{$field};

	#
	# Give an error if the value is empty.
	#
	if($val eq "")
	{
		rolllog_log(LOG_ERR,$rname,"keyrec has an empty entry for \"$field\"");
	}

	#
	# Return the keyrec field.
	#
	return($val);
}

##############################################################################

#-----------------------------------------------------------------------------
# Routine:	optsandargs()
#
# Purpose:	Parse our options and arguments.
#
sub optsandargs
{
	my $argc = @ARGV;		# Number of arguments.
	my $opterrs = 0;		# Count of option-related errors.

	#
	# Get the base values.
	#
	$dtconfig = getconffile();
	%dtconf = parseconfig();

	#
	# Check our options.
	#
	opts_onerr(0);

	#
	# Get a bunch of option values.
	#
	$singlerun  = $opts{$OPT_SINGLERUN};
	$foreground = $opts{$OPT_FOREGROUND};
	$alwayssign = $opts{$OPT_ALWAYSSIGN} || 0;
	$pidfile    = $opts{$OPT_PIDFILE};
	$realm	    = $opts{$OPT_REALM};
	$verbose    = $opts{$OPT_VERBOSE};
	$logfile    = $opts{$OPT_LOGFILE}    || $dtconf{$DT_LOGFILE};
	$loglevel   = $opts{$OPT_LOGLEVEL}   || $dtconf{$DT_LOGLEVEL} || LOG_DEFAULT;
	$logtz	    = $opts{$OPT_LOGTZ}	     || $dtconf{$DT_LOGTZ};
	$sleeptime  = $opts{$OPT_SLEEP}	     || $dtconf{$DT_SLEEP}    || $DEFAULT_NAP;
	$dtcf	    = $opts{$OPT_DTCONF}     || getconffile();
	$display    = $opts{$OPT_DISPLAY}    || 0;
	$gzsargs    = $opts{$OPT_ZSARGS}     || '';
	$username   = $opts{$OPT_USERNAME}   || $dtconf{$DT_USERNAME} || '';
	$xqtdir	    = $opts{$OPT_DIR}	     || '.';
	$zonesigner = $opts{$OPT_ZONESIGNER} || $dtconf{$OPT_ZONESIGNER} || '';

	#
	# Check for autosign presence or absence.
	#
	$autosign  = defined($opts{'autosign'}) ?
				$opts{$OPT_AUTOSIGN} :
				(defined($dtconf{'autosign'}) ?
					$dtconf{$OPT_AUTOSIGN} :
					dnssec_tools_default("autosign"));

	#
	# Determine whether or not we'll load zones.
	#
	$zoneload = dnssec_tools_default($DT_LOADZONE);
	$zoneload = $dtconf{$DT_LOADZONE} if(defined($dtconf{$DT_LOADZONE}));
	$zoneload = 0 if(defined($opts{$OPT_NORELOAD}));
	$zoneload = boolconvert($zoneload);

	#
	# Show the version number if requested
	#
	usage()   if(defined($opts{$OPT_HELP}));
	version() if(defined($opts{$OPT_VERSION}));

	#
	# Check for a rollrec file name.
	#
	$rollrecfile = $opts{$OPT_RRFILE} || rollrec_default();
	$curdir = getcwd();
	if($rollrecfile !~ /^\//)
	{
		$rollrecfile = "$curdir/$rollrecfile";
	}

	#
	# Validate and switch to the given username -- if we can.
	#
	if($username ne '')
	{
		my $uid;			# Uid we're switching to.
		my $ret;			# Return from setuid().

		#
		# If the username is really a uid, we'll convert it to a name.
		#
		if($username =~ /^[0-9]+$/)
		{
			$username = getpwuid($username);
		}

		#
		# Convert the name to a uid.
		#
		$uid = getpwnam($username);
		if($uid eq '')
		{
			print STDERR "rollerd:  unknown user \"$username\"\n";
			$opterrs++;
		}

		#
		# Change the uid of the process.
		#
		$! = '';
		$> = $uid;
#		POSIX::setuid($uid);
		$ret = $!;
		if($ret ne '')
		{
			print STDERR "rollerd:  unable to switch to user \"$username\" -- $ret\n";
			$opterrs++;
		}
	}

	#
	# Build a global zonesigner argument string.  We'll convert the
	# internal equals signs to dashes or spaces, as appropriate.
	#
	if($gzsargs ne '')
	{
		my @args = split / /, $gzsargs;		# Argument array.

		#
		# Put the arguments into the form zonesigner is expecting
		# and join up the bits into a single argument string.
		#
		for(my $ind=0; $ind < @args; $ind++)
		{
			$args[$ind] =~ s/^=/-/;
			$args[$ind] =~ s/=/ /g;
		}

		$gzsargs = join ' ', @args;
	}

	#
	# Validate our execution directory.
	#
	if($xqtdir eq ".")
	{
		$xqtdir = `$PWD`;
		chomp($xqtdir);
	}
	if(!defined($xqtdir))
	{
		print STDERR "rollerd:  no execution directory defined\n";
		$opterrs++;
	}
	if(! -e $xqtdir)
	{
		print STDERR "rollerd:  execution directory \"$xqtdir\" does not exist\n";
		$opterrs++;
	}
	if(! -d $xqtdir)
	{
		print STDERR "rollerd:  execution directory \"$xqtdir\" is not a directory\n";
		$opterrs++;
	}

	#
	# If the user only wants the parameters, print 'em and exit.
	#
	if($opts{$OPT_PARAMS})
	{
		print "$ME parameters:\n";
		print "\trollrec file   \"$rollrecfile\"\n";
		print "\tdirectory      \"$xqtdir\"\n";
		print "\tconfig file    \"$dtconfig\"\n";
		print "\tlogfile        \"$logfile\"\n";
		print "\tloglevel       \"$loglevel\"\n";
		print "\tlogtz          \"$logtz\"\n";
		print "\tautosign       \"$autosign\"\n";
		print "\tzone reload    \"$zoneload\"\n";
		print "\tsleeptime      \"$sleeptime\"\n";
		exit(0)
	}

	#
	# Whine if the rollrec file doesn't exist.
	#
	if(!rrfokay($rollrecfile,""))
	{
		print STDERR "rollerd:  rollrec file \"$rollrecfile\" does not exist\n\n";
		print STDERR "rollerd:  not stopping execution; waiting for a rollrec\n";
	}

	#
	# Move into our execution directory.
	#
	chdir($xqtdir);

	#
	# Ensure a log file was given on the command line or in the config file.
	#
	if(!defined($logfile))
	{
		print STDERR "rollerd:  no logfile specified on command line or in dnssec-tools.conf\n";
		$opterrs++;
	}

	#
	# Ensure the log file's directory actually exists.
	#
	if($logfile =~ /\//)
	{
		my @logbits;			# Components of logfile's path.
		my $logdir;			# Logfile's directory.

		#
		# Get the log directory without the logfile.
		#
		@logbits = split /\//, $logfile;
		pop @logbits;
		$logdir = join '/', @logbits;
		$logdir = '/' if($logdir eq '');

		#
		# Check for the existence of the log directory.
		#
		if(! -e $logdir)
		{
			print STDERR "rollerd:  logfile's directory \"$logdir\" does not exist\n";
			$opterrs++;
		}
	}

	#
	# If a pid file was specified, we'll pass it to the rollmgr module.
	#
	if(defined($pidfile) && ($pidfile ne ''))
	{
		rollmgr_set_idfile($pidfile);
	}

	#
	# Set the logging level and file.
	#
	$loglevel_save = $loglevel;
	rolllog_level($loglevel,1);
	rolllog_file($logfile,1);

	#
	# Set a dummy value to turn off KSK phase 5 mail, iff no recipient
	# has been set.
	#
	if(!exists($dtconf{'admin-email'}))
	{
		$dtconf{'admin-email'} = 'nomail';
	}

	#
	# Set the logging timezone.
	#
	if(rolllog_settz($logtz) eq '')
	{
		print STDERR "rollerd:  invalid log timezone \"$logtz\"\n";
		$opterrs++;
	}

	#
	# Exit if there were any option-related errors.
	#
	exit(1) if($opterrs > 0);

	#
	# Start up our display program if -display was given.
	#
	displayer($display);

}

#-----------------------------------------------------------------------------
# Routine:	getprogs()
#
# Purpose:	Get some program paths.
#
sub getprogs
{
	#
	# If we're running packed, we'll force the command paths to be taken
	# from the packed versions.
	#
	#	NOTE:  In this version of packed rollerd, we're assuming
	#	       that rollerd will not be interacting with named.
	#	       Consequently, we won't be using rndc.
	#
	if($packed)
	{
		$rndc 	    = '';
		$keyarch    = "$ENV{'PAR_TEMP'}/inc/keyarch";
		$rrchk	    = "$ENV{'PAR_TEMP'}/inc/rollchk";
		$zonesigner = "$ENV{'PAR_TEMP'}/inc/zonesigner";

		delete($opts{'rndc'});
		$opts{'keyarch'}     = "keyarch";
		$opts{'rollchk'}     = "rollchk";
		$opts{'zonesigner'}  = "zonesigner";
		$opts{'keygen'}	     = "dnssec-keygen";
		$opts{'zonesign'}    = "dnssec-signzone";
		$opts{'zonecheck'}   = "named-checkzone";

		return;
	}

	#
	# Get the paths to the external commands.  If they aren't defined,
	# use the default command names.
	#
	$keyarch = $dtconf{'keyarch'}	  || dnssec_tools_default("keyarch");
	$rndc 	 = $dtconf{'rndc'}	  || dnssec_tools_default("rndc");
	$rrchk	 = $dtconf{'rollrec_chk'} || dnssec_tools_default("rollrec_check");
}

#-----------------------------------------------------------------------------
# Routine:	bootmsg()
#
# Purpose:	Write a start-up message to the log.
#
sub bootmsg
{
	my $bootflag = shift;				# Boot flag.

	if($bootflag)
	{
		rolllog_log(LOG_ALWAYS,"","$ME starting " . ("-" x 40));
	}
	else
	{
		rolllog_log(LOG_ALWAYS,"","$ME changing logfiles " . ("-" x 31));
	}

	rolllog_log(LOG_ALWAYS,"","$ME parameters:");
	rolllog_log(LOG_ALWAYS,"","	rollrec file	\"$rollrecfile\"");
	rolllog_log(LOG_ALWAYS,"","	realm       	\"$realm\"");
	rolllog_log(LOG_ALWAYS,"","	directory	\"$xqtdir\"");
	rolllog_log(LOG_ALWAYS,"","	config file	\"$dtconfig\"");
	rolllog_log(LOG_ALWAYS,"","	logfile		\"$logfile\"");
	rolllog_log(LOG_ALWAYS,"","	loglevel	\"$loglevel\"");
	rolllog_log(LOG_ALWAYS,"","	logtz		\"$logtz\"");
	rolllog_log(LOG_ALWAYS,"","	always-sign	\"". $alwayssign ."\"");
	rolllog_log(LOG_ALWAYS,"","	autosign	\"$autosign\"");
	rolllog_log(LOG_ALWAYS,"","	single-run	\"$singlerun\"");
	rolllog_log(LOG_ALWAYS,"","	zone reload	\"$zoneload\"");
	if($eventmaster == $EVT_FULLLIST)
	{
		rolllog_log(LOG_ALWAYS,"","	sleeptime	\"$sleeptime\"");
	}
	rolllog_log(LOG_ALWAYS,"","	zone reload	\"$zoneload\"");
	rolllog_log(LOG_ALWAYS,"","	event method	\"$event_methods[$eventmaster]\"");

	if($username ne '')
	{
		rolllog_log(LOG_ALWAYS,"","		running as	\"$username\"");
	}

	rolllog_log(LOG_ALWAYS,""," ");
}

#-----------------------------------------------------------------------------
# Routine:	rrfchk()
#
# Purpose:	This routine performs initial checking of the rollrec file.
#		Several errors and problems are checked for in each rollrec
#		marked as a a roll rollrec.
#
#		Errors:
#			The following errors are checked:
#				- the zonefile exists
#				- the keyrec file exists
#
#			If any of these are violated, the rollrec's type will
#			be changed to a skip rollrec.  This prevents lots of
#			unnecessary repeated log messages of an invalid rollrec.
#
#		Problems:
#			The following problems are checked:
#				- no zonename field exists
#
#			If any of these problems are found, they will be fixed.
#			
#
sub rrfchk
{
	my $rrf	 = shift;				# Rollrec file.
	my $modified = 0;				# Modified flag.

	#
	# Return failure if the rollrec file is bad.
	# 
	if(!rrfokay($rrf,""))
	{
		return(0);
	}

	#
	# Get the current contents of the rollrec file.
	#
	rollrec_lock();
	rollrec_read($rollrecfile);

	#
	# For each roll rollrec, check if its zonefile and keyrec file exist.
	# If not, we'll change it to being a skip rollrec.
	#
	foreach my $rname (rollrec_names())
	{
		my $rrr;		# Reference to rollrec.
		my %rr;			# Rollrec hash.
		my $phase;		# Rollrec's phase.

		my $errs = 0;		# Missing file errors.
		my $prefix;		# Rollrec's directory field.
		my $keyrec;		# Keyrec's filename.
		my $zonefile;		# Zone's filename.

		#
		# Get the rollrec for this name.  If it doesn't have one,
		# whinge and continue to the next.
		#
		$rrr = rollrec_fullrec($rname);
		if(!defined($rrr))
		{
			rolllog_log(LOG_ERR,$rname,"no rollrec defined for zone");
			next;
		}
		%rr = %$rrr;

		#
		# Don't look at skip records.
		#
		next if($rr{'rollrec_type'} eq "skip");

		#
		# Check for a directory.  We'll use rollerd's execution
		# directory if one isn't defined.
		#
		$prefix = $xqtdir;
		$prefix = $rr{'directory'} if(defined($rr{'directory'}));

		#--------------------------------------------------
		# Errors...
		#

		#
		# Get our important files.
		#
		$zonefile = $rr{'zonefile'};
		$zonefile = "$prefix/$zonefile" if($zonefile !~ /^\//);
		$keyrec	  = $rr{'keyrec'};
		$keyrec	  = "$prefix/$keyrec" if($keyrec !~ /^\//);

		#
		# Set the error flag if either the zonefile or the keyrec
		# file don't exist.
		#
		if(! -e $zonefile)
		{
			rolllog_log(LOG_ERR,$rname,"keyrec \"$rrr->{'keyrec'}\" does not exist; running initial zonesigner");
			if(signer($rname, "initial", 0) != 0)
			{
				rolllog_log(LOG_ERR,$rname,"unable to do an initial signing of zone");
				$errs++;
			}
		}
		if(! -e $keyrec)
		{
			rolllog_log(LOG_ERR,$rname,"keyrec \"$keyrec\" does not exist");
			$errs++;
		}

		#--------------------------------------------------
		# Problems...
		#

		#
		# Add a zonename field to the file and our rollrec hash
		# if it isn't already in the hash.
		#
		if(!defined($rr{'zonename'}))
		{
			rolllog_log(LOG_INFO,$rname,"adding missing zonename field ($rname) to rollrec");
			$rr{'zonename'} = $rname;
			rollrec_setval($rname,'zonename',$rname);
		}

		#
		# Get our important files.
		#
		$zonefile = $rr{'zonefile'};
		$zonefile = "$prefix/$zonefile" if($zonefile !~ /^\//);
		$keyrec	  = $rr{'keyrec'};
		$keyrec	  = "$prefix/$keyrec" if($keyrec !~ /^\//);

		#
		# Skip this record if the zonefile and keyrec file exist.
		#
		next if(!$errs);

		#
		# If one of the files doesn't exist, then change the rollrec
		# to a skip record.  There's no reason we should bang our
		# head against non-existent files.
		#
		rolllog_log(LOG_ERR,$rname,"changing roll record to a skip record");
		rollrec_rectype($rname,"skip");
		$modified++;
		display("badzone $rname 0");

	}

	#
	# Save the current rollrec file state.
	#
	rollrec_close();
	rollrec_unlock();

	#
	# Return success.
	# 
	return(1);
}

#-----------------------------------------------------------------------------
# Routine:	rrfokay()
#
# Purpose:	This routine checks to see if a rollrec file is okay.
#
#		Returns:
#			0 - file is in error
#			1 - file is okay
#
sub rrfokay
{
	my $rrf = shift;				# Rollrec file to check.
	my $mp  = shift;				# Message prefix.
	my $ret = 1;					# Return code.
	my $err;					# Error message.

	#
	# Check that the file exists and is non-zero in length.  If one of
	# those conditions fails, we'll set an error message and return code.
	#
	if(! -e $rrf)
	{
		$err = "rollrec file \"$rrf\" does not exist";
		$ret = 0;
	}
	elsif(-z $rrf)
	{
		$err = "rollrec file \"$rrf\" is zero length";
		$ret = 0;
	}

	#
	# If we found an error, we'll (maybe) give an error message and
	# bump our error count.
	#
	if($ret == 0)
	{
		if($rrferrors == 0)
		{
			rolllog_log(LOG_ERR,$mp,$err);
			$rrferrors = $MAXRRFERRS;
		}
		else
		{
			$rrferrors--;
		}

		return(0);
	}

	#
	# Reset our error count and return success.
	#
	$rrferrors = 0;
	return(1);
}

#-----------------------------------------------------------------------------
# Routine:	clearzoneerr()
#
# Purpose:	Reset a zone's error count.
#
sub clearzoneerr
{
	my $rname = shift;			# Name of rollrec rec.
	my $rrr = shift;			# Reference to rollrec.
	my %rr;					# Rollrec hash.

	#
	# Get the rollrec's hash.
	#
	%rr = %$rrr;

	if($rr{'curerrors'} != 0)
	{
		rollrec_setval($rname,'curerrors',0);

		rolllog_log(LOG_TMI,$rname,"resetting the error count");
	}
}

#-----------------------------------------------------------------------------
# Routine:	zoneerr()
#
# Purpose:	Increment a zone's error count.  If the count of maximum
#		consecutive errors is exceeded, the zone is changed to
#		be a roll zone.
#
sub zoneerr
{
	my $rname = shift;			# Name of rollrec rec.
	my $rrr = shift;			# Reference to rollrec.

	my %rr;					# Rollrec hash.
	my $curerrs = 0;			# Zone's current error count.
	my $maxerrs;				# Zone's maximum error count.

	#
	# Get the rollrec's hash.
	#
	%rr = %$rrr;

	#
	# Get the zone's maximum error count.
	#
	$maxerrs = $rr{'maxerrors'};
	$maxerrs = $dtconf{'zone_errors'}	if(! exists($rr{'maxerrors'}));

	#
	# If there's a maximum error count set for this zone, we'll increase
	# the count and see if we need to stop worrying about this zone.
	#
	if($maxerrs > 0)
	{
		#
		# Increment the zone's maximum error count.
		#
		$curerrs = $rr{'curerrors'} + 1;

		#
		# Save the new value.
		#
		$rr{'curerrors'} = $curerrs;
		rollrec_setval($rname,'curerrors',$curerrs);
		rollrec_write();

		#
		# If we've exceeded the maximum error count, change the zone
		# to a skip zone.
		#
		if($curerrs > $maxerrs)
		{
			rolllog_log(LOG_INFO,$rname,"too many errors, zone will now be skipped");
			skipnow($rname);
		}
	}

}

#-----------------------------------------------------------------------------
# Routine:	sleeper()
#
# Purpose:	Sleep for a specific amount of time.  This will take into
#		account interrupts we've taken from rollctl.
#		We may be overridden by a rollctl command.
#
sub sleeper
{
	my $nap;				# Time left to sleep.

	return if($sleep_override);

	rolllog_log(LOG_TMI,"","sleeping for $sleeptime seconds");

	$sleepcnt = 0;

	while($sleepcnt < $sleeptime)
	{
		$nap = $sleeptime - $sleepcnt;

		$sleepcnt += sleep($nap);
	}
}

#-----------------------------------------------------------------------------
# Routine:	sleeper_awake()
#
# Purpose:	This routine forces rollerd to run its queue.  It does this
#		by setting the elapsed-sleep-time equal to the time-to-sleep.
#
sub sleeper_awake
{
	$sleepcnt = $sleeptime;
}

#-----------------------------------------------------------------------------
# Routine:	sleeper_override()
#
# Purpose:	This routine sets the sleep-override flag.
#
sub sleeper_override
{
	$sleep_override = 1;
}

#-----------------------------------------------------------------------------
# Routine:	commander()
#
# Purpose:	Get any commands sent to rollerd's command socket.
#
sub commander
{
	my $cmd;				# Client's command.
	my $data;				# Command's data.
	my $gstr = ROLLMGR_GROUP;		# Group command indicator.

	rolllog_log(LOG_TMI,'<command>',"checking commands");

	#
	# Read and handle all the commands we've been sent.
	#
	while(42)
	{
		#
		# Get the command, return if there wasn't one.
		#
		($cmd,$data) = rollmgr_getcmd(5);
		return if(!defined($cmd));

		rolllog_log(LOG_TMI,'<command>',"cmd   - \"$cmd\"");
		rolllog_log(LOG_TMI,'<command>',"data  - \"$data\"") if($data ne "");

		#
		# Deal with the command as zone-related or as a group command.
		#
		if($cmd =~ /^$gstr/)
		{

			$cmd =~ s/^$gstr//;
			groupcmd($cmd,$data);
		}
		else
		{
			if(singlecmd($cmd,$data) == 1)
			{
				last;
			}
		}

		rollmgr_closechan();
	}
}

#-----------------------------------------------------------------------------
# Routine:	groupcmd()
#
# Purpose:	Execute a command for each zone in a zone group.
#
sub groupcmd
{
	my $cmd = shift;			# Client's command.
	my $data = shift;			# Command's data.
	my %zgcmds;				# Zone group commands.
	my @zonegroup;				# Zones in the named group.

	#
	# Get the list of recognized zone-group commands.  If the requested
	# command isn't allowed for zone groups, we'll quietly run it as
	# a regular command.
	#
	%zgcmds = rollrec_zonegroup_cmds();
	if(! defined($zgcmds{$cmd}))
	{
		singlecmd($cmd,$data);
		return;
	}

	#
	# Run the named command on each zone in the specified zone group.
	# 
	@zonegroup = rollrec_zonegroup($data);
	foreach my $zn (@zonegroup)
	{
		singlecmd($cmd,$zn);
	}

}

#-----------------------------------------------------------------------------
# Routine:	singlecmd()
#
# Purpose:	Execute a single command.
#
sub singlecmd
{
	my $cmd = shift;				# Client's command.
	my $data = shift;				# Command's data.

	if($cmd eq ROLLCMD_DISPLAY())
	{
		cmd_display($data);
	}
	elsif($cmd eq ROLLCMD_DSPUB())
	{
		cmd_dspub($data);
	}
	elsif($cmd eq ROLLCMD_DSPUBALL())
	{
		cmd_dspuball();
	}
	elsif($cmd eq ROLLCMD_LOGFILE())
	{
		cmd_logfile($data);
	}
	elsif($cmd eq ROLLCMD_LOGLEVEL())
	{
		cmd_loglevel($data);
	}
	elsif($cmd eq ROLLCMD_LOGMSG())
	{
		cmd_logmsg($data);
	}
	elsif($cmd eq ROLLCMD_LOGTZ())
	{
		cmd_logtz($data);
	}
	elsif($cmd eq ROLLCMD_MERGERRFS())
	{
		cmd_mergerrfs($data);
	}
	elsif($cmd eq ROLLCMD_PHASEMSG())
	{
		cmd_phasemsg($data);
	}
	elsif($cmd eq ROLLCMD_ROLLALL())
	{
		cmd_rollall();
	}
	elsif($cmd eq ROLLCMD_ROLLALLKSKS())
	{
		cmd_rollallksks();
	}
	elsif($cmd eq ROLLCMD_ROLLALLZSKS())
	{
		cmd_rollallzsks();
	}
	elsif($cmd eq ROLLCMD_ROLLREC())
	{
		return(1) if(cmd_rollrec($data));
	}
	elsif($cmd eq ROLLCMD_ROLLKSK())
	{
		cmd_rollnow($data,'KSK');
	}
	elsif($cmd eq ROLLCMD_ROLLZONE())
	{
		cmd_rollzone($data);
	}
	elsif($cmd eq ROLLCMD_ROLLZSK())
	{
		cmd_rollnow($data,'ZSK');
	}
	elsif($cmd eq ROLLCMD_RUNQUEUE())
	{
		cmd_runqueue($data);
	}
	elsif($cmd eq ROLLCMD_QUEUELIST())
	{
		cmd_queuelist($data);
	}
	elsif($cmd eq ROLLCMD_QUEUESTATUS())
	{
		cmd_queuestatus($data);
	}
	elsif($cmd eq ROLLCMD_SHUTDOWN())
	{
		cmd_shutdown($data);
	}
	elsif($cmd eq ROLLCMD_SIGNZONE())
	{
		cmd_signzone($data);
	}
	elsif($cmd eq ROLLCMD_SIGNZONES())
	{
		cmd_signzones($data);
	}
	elsif($cmd eq ROLLCMD_SKIPALL())
	{
		cmd_skipall();
	}
	elsif($cmd eq ROLLCMD_SKIPZONE())
	{
		cmd_skipzone($data);
	}
	elsif($cmd eq ROLLCMD_SLEEPTIME())
	{
		cmd_sleeptime($data);
	}
	elsif($cmd eq ROLLCMD_SPLITRRF())
	{
		cmd_splitrrf($data);
	}
	elsif($cmd eq ROLLCMD_STATUS())
	{
		cmd_status($data);
	}
	elsif($cmd eq ROLLCMD_ZONEGROUP())
	{
		cmd_zonegroup($data);
	}
	elsif($cmd eq ROLLCMD_ZONELOG())
	{
		cmd_zonelog($data);
	}
	elsif($cmd eq ROLLCMD_ZONESTATUS())
	{
		cmd_zonestatus($data);
	}
	elsif($cmd eq ROLLCMD_ZSARGS())
	{
		cmd_zsargs($data);
	}
	else
	{
		rolllog_log(LOG_ERR,'<command>',"invalid command  - \"$cmd\"");
	}

	return(0);
}

#-----------------------------------------------------------------------------
# Routine:	cmd_display()
#
# Purpose:	Start or stop the rollerd display program.
#
sub cmd_display
{
	my $onflag = shift;				# Display-on flag.

	rolllog_log(LOG_TMI,'<command>',"display command received; status flag - \"$onflag\"");

	#
	# Do nothing if the we're already doing what the user wants.
	#
	if($display == $onflag)
	{
		if($display == 1)
		{
			rolllog_log(LOG_INFO,'<command>',"graphical display is already on");
		}
		else
		{
			rolllog_log(LOG_INFO,'<command>',"graphical display is already off");
		}
		rollmgr_sendresp(ROLLCMD_RC_DISPLAY,"display status already as requested");
		return;
	}

	#
	# Change the logfile and give an appropriate set of log messages.
	#
	if($onflag)
	{
		displayer(1);
		rolllog_log(LOG_INFO,'<command>',"rollerd display started");
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"rollerd display started");
	}
	else
	{
		displayer(0);
		rolllog_log(LOG_INFO,'<command>',"rollerd display stopped");
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"rollerd display stopped");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_dspub()
#
# Purpose:	Move a zone from KSK rollover phase 6 to phase 7.
#
sub cmd_dspub
{
	my $zone = shift;				# Command's data.

	my $rrr;					# Reference to rollrec.
	my $phase;					# Zone's phase.

	rolllog_log(LOG_TMI,'<command>',"dspub command received; zone - \"$zone\"");

	#
	# Get the zone's rollrec.
	#
	$rrr = rollrec_fullrec($zone);
	if(!defined($rrr))
	{
		rolllog_log(LOG_ERR,'<command>',"no rollrec defined for zone $zone");
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"$zone not in rollrec file $rollrecfile");
		return;
	}

	#
	# Ensure we're in the proper KSK-rollover phase to do this command.
	#
	$phase = rollrec_recval($zone,'kskphase');
	if($phase != 6)
	{
		rolllog_log(LOG_INFO,'<command>',"zone not in KSK-rollover phase 6");
		rollmgr_sendresp(ROLLCMD_RC_BADZONEDATA,"$zone not in KSK-rollover phase 6");
		return;
	}

	#
	# Change the zone's rollover phase to phase 7 (the final phase).
	#
	nextphase($zone,$rrr,7,'KSK');
	rollmgr_sendresp(ROLLCMD_RC_OKAY,"zone \"$zone\" now in KSK rollover phase 7");
	sleeper_override();
}

#-----------------------------------------------------------------------------
# Routine:	cmd_dspuball()
#
# Purpose:	Move all zones that are currently in KSK rollover phase 6
#		to phase 7.
#
sub cmd_dspuball
{
	my $rrr;					# Reference to rollrec.
	my $phase;					# Zone's phase.

	rolllog_log(LOG_TMI,'<command>',"dspuball command received");

	foreach my $zone (sort(rollrec_names()))
	{
		#
		# Ensure we're in the proper KSK-rollover phase.
		#
		$phase = rollrec_recval($zone,'kskphase');
		next if($phase != 6);

		#
		# Get the rollrec for this name.
		#
		$rrr = rollrec_fullrec($zone);
		if(!defined($rrr))
		{
			rollmgr_sendresp(ROLLCMD_RC_BADZONE,"$zone not in rollrec file $rollrecfile");
		}

		#
		# Change the zone's rollover phase to phase 7.
		#
		nextphase($zone,$rrr,7,'KSK');
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"zone \"$zone\" now in KSK rollover phase 7");
	}

	sleeper_override();
}

#-----------------------------------------------------------------------------
# Routine:	cmd_logfile()
#
# Purpose:	Set the logfile to the user's specified file.  Nothing is done
#		if the user requests the same log file as is currently in use.
#
sub cmd_logfile
{
	my $newlog = shift;				# New log file.
	my $oldlog;					# Old log file.

	rolllog_log(LOG_TMI,'<command>',"logfile command received; new log file - \"$newlog\"");

	#
	# Do nothing if the new logfile is the same as the current logfile.
	#
	$oldlog = rolllog_file();
	if($oldlog eq $newlog)
	{
		rolllog_log(LOG_INFO,'<command>',"new logfile ($newlog) same as the old logfile");
		return;
	}

	#
	# Change the logfile and give an appropriate set of log messages.
	#
	rolllog_log(LOG_INFO,'<command>',"logfile changed from $oldlog to $newlog");
	rolllog_log(LOG_INFO,'<command>',"closing logfile $oldlog");
	$oldlog = rolllog_file($newlog,0);
	if($oldlog ne "")
	{
		rolllog_log(LOG_INFO,'<command>',"logfile changed from $oldlog to $newlog");
		bootmsg(0);
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"logfile changed to \"$newlog\"");
	}
	else
	{
		rolllog_log(LOG_ERR,'<command>',"unable to change logfile to $newlog");
		rollmgr_sendresp(ROLLCMD_RC_BADFILE,"unable to change logfile to \"$newlog\"");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_loglevel()
#
# Purpose:	Set the logging level to the user's specified level.
#
sub cmd_loglevel
{
	my $newlvl = shift;				# New level.
	my $oldlvl;					# Old level.

	my $oldstr;					# Old level's string.
	my $newstr;					# New level's string.

	$newstr = rolllog_str($newlvl);
	rolllog_log(LOG_TMI,'<command>',"loglevel command received; new logging level - \"$newstr\"");

	$oldlvl = rolllog_level($newlvl,0);
	if($oldlvl >= 0)
	{
		$oldstr = rolllog_str($oldlvl);

		rolllog_log(LOG_INFO,'<command>',"loglevel changed from $oldstr to $newstr");
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"loglevel changed from \"$oldstr\" to \"$newstr\"");

		$loglevel	= $newlvl;
		$loglevel_save	= $newlvl;
	}
	else
	{
		rolllog_log(LOG_ERR,'<command>',"unable to change loglevel to $newlvl");
		rollmgr_sendresp(ROLLCMD_RC_BADLEVEL,"invalid loglevel \"$newlvl\"");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_logmsg()
#
# Purpose:	Write a log message to the log file.
#
#		The way we check for a valid log level is only good in a
#		single-threaded environment.
#
sub cmd_logmsg
{
	my $logstr = shift;			# Log level and message.

	my $loglvl;				# Logging level.
	my $logmsg;				# Log message.

	my $oldlvl;				# Real logging level.
	my $goodlvl;				# Real version of new level.

	rolllog_log(LOG_TMI,'<command>',"logmsg command received");

	#
	# Dig the log level and message out of our argument.
	#
	$logstr =~ /^\((\w+)\)(.*)$/;
	$loglvl = $1;
	$logmsg = $2;

	#
	# Check the validity of the caller's log level.  If it's invalid,
	# rolllog_level() will return a failure and we'll return.
	#
	$oldlvl = rolllog_level($loglvl,0);
	if($oldlvl < 0)
	{
		rolllog_log(LOG_INFO,'<command>',"invalid loglevel ($loglvl) specified for logmsg command");
		rollmgr_sendresp(ROLLCMD_RC_BADLEVEL,"invalid loglevel \"$loglvl\"");
		return;
	}

	#
	# Reset the logging level and write the caller's message.
	#
	$goodlvl = rolllog_level($oldlvl,0);
	rolllog_log($goodlvl,"<user msg>",$logmsg);
	rollmgr_sendresp(ROLLCMD_RC_OKAY,"message written to log");
}

#-----------------------------------------------------------------------------
# Routine:	cmd_logtz()
#
# Purpose:	Set the timezone for log messages' timestamps.
#
sub cmd_logtz
{
	my $newtz = shift;			# New logging timezone.

	my $oldtz;				# Current logging timezone.

	rolllog_log(LOG_TMI,'<command>',"logtz command received");

	#
	# Set the new timezone for log messages.  If it's invalid, we'll
	# return a failure and then return.
	#
	$oldtz = rolllog_settz($newtz);
	if($oldtz eq '')
	{
		rolllog_log(LOG_INFO,'<command>',"invalid timezone ($newtz) specified for logtz command");
		rollmgr_sendresp(ROLLCMD_RC_BADTZ,"invalid logtz \"$newtz\"");
		return;
	}

	#
	# Let the user know all's well.
	#
	rolllog_log(LOG_INFO,"<command>","logging timezone set to $newtz");
	rollmgr_sendresp(ROLLCMD_RC_OKAY,"new logging timezone set");
}

#-----------------------------------------------------------------------------
# Routine:	cmd_mergerrfs()
#
# Purpose:	Merge a set of rollrec files into the current rollrec and
#		start rollover for those zones.
#
sub cmd_mergerrfs
{
	my $rrfs = shift;			# New rollrec files.
	my @rrfs;				# List of rollrec files.

	rolllog_log(LOG_TMI,'<command>',"mergerrfs command received");

	#
	# Divide the string of rollrec files into a list.
	#
	@rrfs = split ':', $rrfs;

	#
	# Merge the new rollrecs with the current one.
	#
	if(rollrec_merge($rollrecfile,@rrfs) < 0)
	{
		rolllog_log(LOG_INFO,'<command>',"unable to merge rollrecs ($rrfs) with current rollrec file");
		rollmgr_sendresp(ROLLCMD_RC_BADFILE,"unable to merge rollrecs \"$rrfs\"");
		return;
	}

	#
	# Let the user know all's well.
	#
	rolllog_log(LOG_INFO,"<command>","zone files merged");
	rollmgr_sendresp(ROLLCMD_RC_OKAY,"zonefiles merged");
	display("readrrf dummy 0");
}

#-----------------------------------------------------------------------------
# Routine:	cmd_phasemsg()
#
# Purpose:	Set the phase-message length for log messages.
#
sub cmd_phasemsg
{
	my $pmsg = shift;			# Phase-message length.

	rolllog_log(LOG_TMI,'<command>',"phasemsg command received");

	#
	# Set our phase-message length.
	#
	if(rollmgr_phasemsg($pmsg) == 1)
	{
		rollmgr_sendresp(ROLLCMD_RC_OKAY,'phase-message length set');
		return;
	}

	#
	# If it fails, return the failure to the caller.
	#
	rolllog_log(LOG_INFO,'<command>',"invalid phase-message ($pmsg)");
	rollmgr_sendresp(ROLLCMD_RC_BADLEVEL,"invalid phase-message length \"$pmsg\"");
}

#-----------------------------------------------------------------------------
# Routine:	cmd_rollall()
#
# Purpose:	This command resumes rollover for all suspended zones in the
#		rollrec file.  The zones' rollrec records are marked as being
#		"roll" records, which will cause rollerd to start working on
#		them.  This change is reflected in the rollrec file.  rollnow()
#		is called for each suspended zone, in order to resume rollover.
#		We'll also keep track of the suspended zones we were and weren't
#		able to stop and report them to the caller.
#
sub cmd_rollall
{
	my $good = "";					# Resumed zones.
	my $bad	 = "";					# Unresumed zones.

	my $cnt	 = 0;					# Total count.
	my $gcnt = 0;					# Resumed count.
	my $bcnt = 0;					# Unresumed count.

	rolllog_log(LOG_TMI,'<command>',"rollall command received");

	#
	# Each suspended zone in the rollrec file will be returned to the
	# rollover process.  We'll keep track of the suspended zones that were
	# resumed and those that weren't in order to provide an appropriate
	# response message.
	#
	foreach my $zone (rollrec_names())
	{
		$cnt++;

		#
		# If the resume worked, increment the good count and add
		# the domain name to the list of good zones.  If it didn't
		# work, do the same for the bad count and bad-zone list.
		#
		if(rollnow($zone,'restart',1) == 1)
		{
			$gcnt++;
			$good .= "$zone ";
		}
		else
		{
			$bcnt++;
			$bad .= "$zone ";
		}
	}

	#
	# Get rid of trailing whitespace.
	#
	chomp $good;
	chomp $bad;

	#
	# Send a response message to the caller.
	#
	if($gcnt == $cnt)
	{
		rollmgr_sendresp(ROLLCMD_RC_OKAY,$good);
	}
	else
	{
		my $resp;				# Response message.

		$resp = "unable to resume roll process for zones:  $bad\n";

		#
		# If there were any zones that were resumed, we'll add them
		# to the message as well.
		#
		if($gcnt > 0)
		{
			$resp .= "zones now resumed:  $good\n";
		}

		chomp $resp;
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,$resp);
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_rollallksks()
#
# Purpose:	This command moves all the zones in the rollrec file into
#		immediate KSK rollover.
#
sub cmd_rollallksks
{
	rolllog_log(LOG_TMI,'<command>',"rollallksks command received");
	rollemall('KSK');
}

#-----------------------------------------------------------------------------
# Routine:	cmd_rollallzsks()
#
# Purpose:	This command moves all the zones in the rollrec file into
#		immediate ZSK rollover.
#
sub cmd_rollallzsks
{
	rolllog_log(LOG_TMI,'<command>',"rollallzsks command received");
	rollemall('ZSK');
}

#-----------------------------------------------------------------------------
# Routine:	cmd_rollrec()
#
# Purpose:	This routine changes the rollrec file being used by rollerd.
#		If this command is successful, then the communications channel
#		will be closed.
#
sub cmd_rollrec
{
	my $rrf = shift;				# New rollrec file.

	rolllog_log(LOG_TMI,'<command>',"rollrec command received; rollrec file - \"$rrf\"");

	if(rrfokay($rrf,'<command>'))
	{
		rolllog_log(LOG_INFO,'<command>',"------------------------------------------------");
		rolllog_log(LOG_INFO,'<command>',"setting rollrec file from \"$rollrecfile\" to \"$rrf\"");
		$rollrecfile = $rrf;

		rollmgr_sendresp(ROLLCMD_RC_OKAY,"rollerd now using rollrec file $rrf");
		display("rollrec $rrf 0");

		#
		# Close the channel and return success.
		#
		rollmgr_closechan();
		return(1);
	}

	rolllog_log(LOG_ERR,'<command>',"invalid rollrec file \"$rrf\"");
	rollmgr_sendresp(ROLLCMD_RC_BADROLLREC,"invalid rollrec file \"$rrf\"");
	return(0);
}

#-----------------------------------------------------------------------------
# Routine:	cmd_rollnow()
#
# Purpose:	This command moves a zone into immediate KSK or ZSK rollover.
#		It calls rollnow() to move the zone into immediate rollover.
#
sub cmd_rollnow
{
	my $zone = shift;				# Command's data.
	my $rolltype = shift;				# Type of rollover.

	my $rtlc;					# LC rollover type.
	my $rollret;					# Retcode from rolling.
	my $rrr;					# Rollrec reference.
	my %rr;						# Rollrec hash.

	$rtlc = lc($rolltype);
	rolllog_log(LOG_TMI,'<command>',"roll" . $rtlc . " command received; zone - \"$zone\"");

	#
	# Get the zone's rollrec.
	#
	$rrr = rollrec_fullrec($zone);
	if(!defined($rrr))
	{
		rolllog_log(LOG_ERR,'<command>',"no rollrec defined for zone $zone");
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"$zone not in rollrec file $rollrecfile");
		return(0);
	}
	%rr = %$rrr;

	#
	# Don't proceed if this zone is in the middle of KSK rollover.
	#
	if($rr{'kskphase'} > 0)
	{
		rolllog_log(LOG_TMI,'<command>',"in KSK rollover (phase $rr{'kskphase'}); not attempting ZSK rollover");
		rollmgr_sendresp(ROLLCMD_RC_KSKROLL,"$zone is already engaged in a KSK rollover");
		return(0);
	}

	#
	# Don't proceed if this zone is in the middle of ZSK rollover.
	#
	if($rr{'zskphase'} > 0)
	{
		rolllog_log(LOG_TMI,'<command>',"in ZSK rollover (phase $rr{'zskphase'}); not attempting ZSK rollover");
		rollmgr_sendresp(ROLLCMD_RC_ZSKROLL,"$zone is already engaged in a ZSK rollover");
		return(0);
	}

	#
	# Do the rollover and send an appropriate response.
	#
	$rollret = rollnow($zone,$rolltype,1);
	if($rollret == 1)
	{
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"$zone $rolltype rollover started");
	}
	elsif($rollret == 0)
	{
		rolllog_log(LOG_ERR,'<command>',"$zone not in rollrec file $rollrecfile");
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"$zone not in rollrec file $rollrecfile");
	}
	elsif($rollret == -1)
	{
		rolllog_log(LOG_ERR,'<command>',"$zone has bad values in rollrec file $rollrecfile");
		rollmgr_sendresp(ROLLCMD_RC_BADZONEDATA,"$zone has bad values in rollrec file $rollrecfile");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_rollzone()
#
# Purpose:	This command restores a skipped zone to rollover processing. 
#
sub cmd_rollzone
{
	my $zone = shift;				# Command's data.

	rolllog_log(LOG_TMI,'<command>',"rollzone command received; zone - \"$zone\"");

	if(rollnow($zone,'restart',1) == 1)
	{
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"$zone rollover started");
	}
	else
	{
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"$zone not in rollrec file $rollrecfile");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_rollzsk()
#
# Purpose:	This command moves a zone into immediate rollover.  It calls
#		rollnow() to move the zone into immediate ZSK rollover.
#
sub cmd_rollzsk
{
	my $zone = shift;				# Command's data.
	my $rollret;					# Retcode from rolling.

	my $rrr;					# Rollrec reference.
	my %rr;						# Rollrec hash.

	rolllog_log(LOG_TMI,'<command>',"rollzsk command received; zone - \"$zone\"");

	#
	# Get the zone's rollrec.
	#
	$rrr = rollrec_fullrec($zone);
	if(!defined($rrr))
	{
		rolllog_log(LOG_ERR,'<command>',"no rollrec defined for zone $zone");
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"$zone not in rollrec file $rollrecfile");
	}
	%rr = %$rrr;

	#
	# Don't proceed if this zone is in the middle of KSK rollover.
	#
	if($rr{'kskphase'} > 0)
	{
		rolllog_log(LOG_TMI,'<command>',"in KSK rollover (phase $rr{'kskphase'}); not attempting ZSK rollover");
		rollmgr_sendresp(ROLLCMD_RC_KSKROLL,"$zone is already engaged in a KSK rollover");
		return(0);
	}

	#
	# Don't proceed if this zone is in the middle of ZSK rollover.
	#
	if($rr{'zskphase'} > 0)
	{
		rolllog_log(LOG_TMI,'<command>',"in ZSK rollover (phase $rr{'zskphase'}); not attempting ZSK rollover");
		rollmgr_sendresp(ROLLCMD_RC_ZSKROLL,"$zone is already engaged in a ZSK rollover");
		return(0);
	}

	#
	# Do the ZSK rollover and send an appropriate response.
	#
	$rollret = rollnow($zone,'ZSK',1);
	if($rollret == 1)
	{
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"$zone ZSK rollover started");
	}
	elsif($rollret == 0)
	{
		rolllog_log(LOG_ERR,'<command>',"$zone not in rollrec file $rollrecfile");
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"$zone not in rollrec file $rollrecfile");
	}
	elsif($rollret == -1)
	{
		rolllog_log(LOG_ERR,'<command>',"$zone has bad values in rollrec file $rollrecfile");
		rollmgr_sendresp(ROLLCMD_RC_BADZONEDATA,"$zone has bad values in rollrec file $rollrecfile");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_runqueue()
#
# Purpose:	This command forces rollerd to run its queue.  It does this
#		by setting the elapsed-sleep-time equal to the time-to-sleep.
#		Upon return, sleeper() will see that sleepers must awake, 
#		and rollerd will go run its rollrec queue.
#
sub cmd_runqueue
{
	rolllog_log(LOG_TMI,'<command>',"runqueue command received");

	rolllog_log(LOG_INFO,'<command>',"checking rollrec queue");
	rollmgr_sendresp(ROLLCMD_RC_OKAY,"rollerd checking rollrec queue");
	sleeper_awake();
}

#-----------------------------------------------------------------------------
# Routine:	cmd_queuelist()
#
# Purpose:	This command returns the soon queue.  The zones and times
#		until their next events are returned.
#
sub cmd_queuelist
{
	my $zncnt;				# Number of zones we'll report.
	my $outstr = '';			# Response to caller.

	rolllog_log(LOG_TMI,'<command>',"queuelist command received");

	#
	# Ensure that this command makes sense to respond to.
	#
	if($eventmaster != $EVT_QUEUE_SOON)
	{
		rollmgr_sendresp(ROLLCMD_RC_BADEVENT,"rollerd not running the queue-soon event handler");
		return;
	}

	$zncnt = @queue_sooners - $queue_firstsoon;

	$outstr = "Soon-Queue List  ($zncnt zones)\n";

	for(my $ind = $queue_firstsoon; $ind < @queue_sooners; $ind++)
	{
		my $zn = $queue_sooners[$ind];
		$outstr .= "    $zn    " . timetrans($queue_eventtimes{$zn}) . " until next event\n";
	}

	rollmgr_sendresp(ROLLCMD_RC_OKAY,$outstr);
}

#-----------------------------------------------------------------------------
# Routine:	cmd_queuestatus()
#
# Purpose:	This command returns the status of the queuing system.
#
sub cmd_queuestatus
{
	my $allcnt;			# Count of all zones we're managing.
	my $sooncnt;			# Count of zones that will roll soon.
	my $scantime;			# Time until next full scan.
	my $nexttime;			# Time until next rollover event.
	my $fprdtime;			# Time between full scans.
	my $soonend;			# End of current soon period.

	my $nextzone;			# Zone with next rollover event.
	my $outstr;			# Response to caller.

	rolllog_log(LOG_TMI,'<command>',"queuestatus command received");

	#
	# Ensure that this command makes sense to respond to.
	#
	if($eventmaster != $EVT_QUEUE_SOON)
	{
		rollmgr_sendresp(ROLLCMD_RC_BADEVENT,"rollerd not running the queue-soon event handler");
		return;
	}

	#
	# Get the data we'll need...
	#
	$allcnt	  = @queue_allzones;
	$sooncnt  = @queue_sooners;
	$soonend  = time + $queue_eventtimes{$QUEUE_RUNSCAN};
	$soonend  = localtime($soonend);

	$scantime = timetrans($queue_eventtimes{$QUEUE_RUNSCAN});
	$nextzone = $queue_sooners[$queue_firstsoon];

	$nexttime = $queue_eventtimes{$nextzone};
	if($nexttime <= 0)
	{
		$nexttime = "happening now";
	}
	else
	{
		$nexttime = "in " . timetrans($nexttime);
	}

	$fprdtime = timetrans($QUEUE_SOONLIMIT);

	#
	# ... and build a response.
	#
	$outstr  = "$event_methods[$eventmaster] queuing method\n";
	$outstr  = "$fprdtime between FULL scans\n";
	$outstr .= "$allcnt zones managed\n";
	$outstr .= "$sooncnt zones with SOON rollover events\n";
	$outstr .= "\n";
	$outstr .= "next FULL zone scan in $scantime\n";
	$outstr .= "end of current SOON scan period $soonend (local)\n";
	$outstr .= "next rollover event $nexttime  ($nextzone)\n";

	rollmgr_sendresp(ROLLCMD_RC_OKAY,$outstr);
}

#-----------------------------------------------------------------------------
# Routine:	cmd_shutdown()
#
# Purpose:	This command forces rollerd to shut down.
#
sub cmd_shutdown
{
	rolllog_log(LOG_TMI,'<command>',"shutdown command received");
	rollmgr_sendresp(ROLLCMD_RC_OKAY,"rollerd shutting down");

	halt_handler();
}

#-----------------------------------------------------------------------------
# Routine:	cmd_signzone()
#
# Purpose:	This command causes a zone signing, without any key creation
#		or rolling.
#
sub cmd_signzone
{
	my $zone = shift;				# Command's data.

	my $rrr;					# Rollrec reference.
	my $krr;					# Keyrec reference.
	my $phasestr;					# Phase argument.

	rolllog_log(LOG_TMI,'<command>',"signzone command received");

	#
	# Get the current phase values for the zone.
	#
	$rrr = rollrec_fullrec($zone);

	#
	# Get the phase string we'll use for signing.
	#
	$phasestr = phaseargs($rrr->{'kskphase'},$rrr->{'zskphase'});

	#
	# Check value and file existence, etc.
	#
	$krr = opts_zonekr($rrr->{'keyrec'},$zone);

	#
	# Sign the zone.
	#
	rolllog_log(LOG_PHASE,'<command>',"mid-phase, user-initiated signing of $zone");
	if(signer($zone,$phasestr,$krr) == 0)
	{
		rolllog_log(LOG_TMI,'<command>',"rollerd signed zone $zone");
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"rollerd signed zone $zone");
	}
	else
	{
		rolllog_log(LOG_ERR,'<command>',"unable to sign zone $zone");
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"unable to sign zone $zone");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_signzones()
#
# Purpose:	This command causes all unskipped zones to be signed, without
#		any key creation or rolling.
#
sub cmd_signzones
{
	my $skipflag = shift;				# Command's data.

	my $rrr;					# Rollrec reference.
	my $krr;					# Keyrec reference.
	my $phasestr;					# Phase argument.
	my @errzones = ();				# Unsigned zones.

	rolllog_log(LOG_TMI,'<command>',"signzones command received; data - \"$skipflag\"");

	#
	# Convert the textual zone-skip flag into an easy-to-use boolean.
	#
	$skipflag = ($skipflag eq 'active') ? 1 : 0;

	#
	# Sign each active zone in the rollrec file.  Any skipped zones will
	# not be signed.
	#
	foreach my $zone (rollrec_names())
	{
		#
		# Get the current rollrec for this zone and (maybe) skip
		# any skipped zones.
		#
		$rrr = rollrec_fullrec($zone);
		next if($skipflag && ($rrr->{'rollrec_type'} eq 'skip'));

		#
		# Get the phase string we'll use for signing.
		#
		$phasestr = phaseargs($rrr->{'kskphase'},$rrr->{'zskphase'});

		#
		# Check value and file existence, etc.
		#
		$krr = opts_zonekr($rrr->{'keyrec'},$zone);

		#
		# Sign the zone.
		#
		rolllog_log(LOG_PHASE,'<command>',"mid-phase, user-initiated signing of $zone");
		if(signer($zone,$phasestr,$krr) != 0)
		{
			push @errzones, $zone;
		}
	}

	#
	# If we signed all the zones, we'll send a success message.
	# If we couldn't sign any zones, we'll return the list of bad
	# zones to the caller.
	#
	if(@errzones == 0)
	{
		rolllog_log(LOG_TMI,'<command>',"rollerd signed all zones");
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"rollerd signed all zones");
	}
	else
	{
		my $errstr = join(', ', @errzones);
		rolllog_log(LOG_ERR,'<command>',"unable to sign all zones:  $errstr");
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"unable to sign all zones:  $errstr");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_skipall()
#
# Purpose:	This command stops rollover for all the zones in the rollrec
#		file.  The zones' rollrec records are marked as being "skip"
#		records, which will cause rollerd to ignore them.  This change
#		is reflected in the rollrec file.  skipnow() is called for each
#		zone, in order to stop rollover.  We'll also keep track of the
#		zones we were and weren't able to stop and report them to the
#		caller.
#
sub cmd_skipall
{
	my $good = "";					# Skipped zones.
	my $bad	 = "";					# Unskipped zones.

	my $cnt	 = 0;					# Total count.
	my $gcnt = 0;					# Skipped count.
	my $bcnt = 0;					# Unskipped count.

	rolllog_log(LOG_TMI,'<command>',"skipall command received");

	#
	# Each zone in the rollrec file will be removed from the rollover
	# process.  We'll keep track of the zones that were skipped and those
	# that weren't in order to provide an appropriate response message.
	#
	foreach my $zone (rollrec_names())
	{
		$cnt++;

		#
		# If the skip worked, increment the good count and add
		# the domain name to the list of good zones.  If it didn't
		# work, do the same for the bad count and bad-zone list.
		#
		if(skipnow($zone) == 1)
		{
			$gcnt++;
			$good .= "$zone ";
		}
		else
		{
			$bcnt++;
			$bad .= "$zone ";
		}
	}

	#
	# We still don't need no steenkin' trailing whitespace.
	#
	chomp $good;
	chomp $bad;

	#
	# Send a response message to the caller.
	#
	if($gcnt == $cnt)
	{
		rollmgr_sendresp(ROLLCMD_RC_OKAY,$good);
	}
	else
	{
		my $resp;				# Response message.

		$resp = "zones not in rollrec file $rollrecfile:  $bad\n";

		#
		# If there were any zones that were removed from rollover,
		# we'll add them to the message as well.
		#
		if($gcnt > 0)
		{
			$resp .= "zones now skipped:  $good\n";
		}

		rollmgr_sendresp(ROLLCMD_RC_BADZONE,$resp);
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_skipzone()
#
# Purpose:	This command removes a zone from rollover processing. 
#
sub cmd_skipzone
{
	my $zone = shift;				# Command's data.

	rolllog_log(LOG_TMI,'<command>',"skipzone command received; zone - \"$zone\"");

	if(skipnow($zone) == 1)
	{
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"$zone rollover stopped");
	}
	else
	{
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"$zone not in rollrec file $rollrecfile");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_sleeptime()
#
# Purpose:	This command sets rollerd's time-to-sleep to the user's
#		specified value.  This must be above a "constant" minimum
#		sleep time in order to prevent malicious users from making
#		rollerd continually run its queue without any resting.
#
#		It might be good to also enforce a maximum sleep time.
#
sub cmd_sleeptime
{
	my $newnap = shift;				# New sleep time.

	rolllog_log(LOG_TMI,'<command>',"sleeptime command received; new sleep time - \"$newnap\"");

	if($newnap < $MIN_SLEEP)
	{
		rolllog_log(LOG_ERR,'<command>',"sleep-time must be >= $MIN_SLEEP");
		rollmgr_sendresp(ROLLCMD_RC_BADSLEEP,"invalid sleep-time \"$newnap\"");
	}
	else
	{
		rolllog_log(LOG_INFO,'<command>',"setting sleep-time to $newnap");
		$sleeptime = $newnap;
		$sleepcnt  = $newnap;

		rollmgr_sendresp(ROLLCMD_RC_OKAY,"sleep-time set to $newnap");
		display("sleeptime all $sleeptime");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_splitrrf()
#
# Purpose:	Split the current rollrec file in two.  The specified rollrec
#		entries are moved into a new file.
#
sub cmd_splitrrf
{
	my $args = shift;			# New rollrec file and rollrecs.
	my $newrrf;				# New rollrec file.
	my @rrfs;				# Rollrec entries to move.

	rolllog_log(LOG_TMI,'<command>',"splitrrf command received");

	#
	# Divide the string of arguments into a list.
	#
	@rrfs = split ':', $args;

	#
	# Get the new rollrec file name from the front of the list.
	#
	$newrrf = shift @rrfs;

	#
	# Lock the file so others can't use it.  We'll also read the file
	# to make sure we have the current version.
	#
	rollrec_lock();
	rollrec_close();
	rollrec_read($rollrecfile);

	#
	# Split the rollrecs into the new file.
	#
	if(rollrec_split($newrrf,@rrfs) < 0)
	{
		rolllog_log(LOG_INFO,'<command>',"unable to split rollrec from current rollrec file to \"$newrrf\"");
		rollmgr_sendresp(ROLLCMD_RC_BADFILE,"unable to split current rollrec to \"$newrrf\"");
		return;
	}

	#
	# Unlock the file so others can use it.
	#
	rollrec_unlock();

	#
	# Let the user know all's well.
	#
	rolllog_log(LOG_INFO,"<command>","current rollrec split to \"$newrrf\"");
	rollmgr_sendresp(ROLLCMD_RC_OKAY,"zonefiles split");
	display("readrrf dummy 0");
}

#-----------------------------------------------------------------------------
# Routine:	cmd_status()
#
# Purpose:	Give a caller some rollerd settings.
#
sub cmd_status
{
	my $data = shift;				# Command's data.

	my $lfile;					# Log file.
	my $lvl;					# Logging level.
	my $lvlstr;					# Logging level string.
	my $tz;						# Logging timezone.
	my $outbuf = "";				# Response buffer.

	#
	# Get the info to report.
	#
	$lfile	= rolllog_file();
	$lvl	= rolllog_level();
	$lvlstr	= rolllog_str($lvl);
	$tz     = rolllog_gettz();

	#
	# Build status report.
	#
	$outbuf  = "boot-time:          $boottime\n";
	$outbuf .= "realm:              $realm\n";
	$outbuf .= "directory:          $curdir\n";
	$outbuf .= "rollrec file:       $rollrecfile\n";
	$outbuf .= "config file:        $dtconfig\n";
	$outbuf .= "logfile:            $lfile\n";
	$outbuf .= "loglevel:           $lvl\n";
	$outbuf .= "logtz:              $tz\n";
	$outbuf .= "always-sign:        $alwayssign\n";
	$outbuf .= "autosign:           $autosign\n";
	$outbuf .= "zone reload:        $zoneload\n";

	if($eventmaster == $EVT_FULLLIST)
	{
		$outbuf .= "sleeptime:          $sleeptime\n";
	}

	$outbuf .= "event method:       $event_methods[$eventmaster]\n";

	if($username ne '')
	{
		$outbuf .= "running as:         $username\n";
	}

	$outbuf	.= "\n";
	$outbuf	.= "$VERS\n";
	$outbuf	.= "$DTVERS\n";

	#
	# Send the status report to the caller.
	#
	rolllog_log(LOG_TMI,'<command>',"status command received");
	rollmgr_sendresp(ROLLCMD_RC_OKAY,$outbuf);
}

#-----------------------------------------------------------------------------
# Routine:	cmd_zonegroup()
#
# Purpose:	Give a caller info about the zone groups or the list of zone
#		in a specified group.
#
sub cmd_zonegroup
{
	my $data = shift;				# Command's data.
	my $outbuf = '';				# Response buffer.
	my $errbuf = '';				# Error buffer.

	#
	# Get the info to report.
	#
	if($data eq '')
	{
		my %zgroups;				# Zone groups.

		#
		# Get the list of zone groups.
		#
		%zgroups = rollrec_zonegroups();

		#
		# Build the list of zone groups and count of zones in
		# that group.
		#
		foreach my $zg (sort(keys(%zgroups)))
		{
			$outbuf .= "$zg:\t$zgroups{$zg} zones\n";		
		}

		#
		# Mark an error if there are no zone groups.
		#
		if($outbuf eq '')
		{
			$errbuf = "no zone groups defined";
		}
	}
	else
	{
		my @zgroup;				# Zone group.

		@zgroup = rollrec_zonegroup($data);

		#
		# Buid the list of zones in this group.  If there are no
		# zones in this group, this isn't really a zone group.
		#
		if(@zgroup > 0)
		{
			$outbuf = join("\n",@zgroup);
		}
		else
		{
			$errbuf = "invalid zone group \"$data\"";
		}
		
	}

	#
	# Send the status report to the caller.
	#
	chomp $outbuf;
	if($outbuf ne '')
	{
		rolllog_log(LOG_TMI,'<command>',"zonegroup($data) command received");
		rollmgr_sendresp(ROLLCMD_RC_OKAY,$outbuf);
	}
	else
	{
		rolllog_log(LOG_INFO,'<command>',$errbuf);
		rollmgr_sendresp(ROLLCMD_RC_BADZONEGROUP,$errbuf);
	}

}

#-----------------------------------------------------------------------------
# Routine:	cmd_zonelog()
#
# Purpose:	Set the logging level for a zone.
#
sub cmd_zonelog
{
	my $data = shift;				# Command's data.

	my $rrr;					# Reference to rollrec.
	my %rr;						# Rollrec hash.

	my $zone;					# User's zone.
	my $llev;					# User's logging level.
	my $llevstr;					# String of log level.

	rolllog_log(LOG_TMI,'<command>',"zonelog command received");

	#
	# Get the zone and logging level from the command data.
	#
	$data =~ /^(.*):(.*)$/;
	$zone = $1;
	$llev = $2;

	#
	# Convert the user's logging level to its numeric form.
	#
	$llev = rolllog_num($llev);

	#
	# Ensure that the logging level is valid.
	#
	if($llev == -1)
	{
		rollmgr_sendresp(ROLLCMD_RC_BADLEVEL,"invalid logging level \"$llev\"");
		rolllog_log(LOG_ALWAYS,'<command>',"invalid logging level \"$llev\" specified for zone \"$zone\"\n");
		return;
	}

	#
	# Read the rollrec file.  Complain and return if we couldn't.
	#
	rollrec_lock();
	if(rollrec_read($rollrecfile) <= 0)
	{
		rollrec_unlock();
		rollmgr_sendresp(ROLLCMD_RC_RRFOPEN,"unable to open rollrec file $rollrecfile");
		rolllog_log(LOG_ALWAYS,'<command>',"unable to open rollrec file $rollrecfile\n");
		return;
	}

	#
	# Get the specified zone's roll record.
	#
	$rrr = rollrec_fullrec($zone);
	if(!defined($rrr))
	{
		rollrec_unlock();
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"invalid zone \"$zone\" specified");
		rolllog_log(LOG_ALWAYS,'<command>',"invalid zone \"$zone\" specified for zonelog command\n");
		return;
	}
	%rr = %$rrr;

	#
	# Set the zone's logging level.
	#
	rollrec_setval($zone,"loglevel",$llev);

	#
	# Write and unlock the rollrec file.
	#
	rollrec_close();
	rollrec_unlock();

	#
	# Report the command and return.
	#
	$llevstr = rolllog_str($llev);
	rolllog_log(LOG_INFO,'<command>',"set the logging level for zone $zone to $llevstr");
	return(1);
}

#-----------------------------------------------------------------------------
# Routine:	cmd_zonestatus()
#
# Purpose:	Return zone status to the control program.
#
sub cmd_zonestatus
{
	my $data = shift;				# Command's data.

	my $cnt = 0;					# Zone count.
	my $outbuf = "";				# Zone status line.

	rolllog_log(LOG_TMI,'<command>',"zonestatus command received");

	rollrec_lock();

	#
	# Read the rollrec file.  If we couldn't, complain and return.
	#
	if(rollrec_read($rollrecfile) <= 0)
	{
		rollrec_unlock();
		rollmgr_sendresp(ROLLCMD_RC_RRFOPEN,"unable to open rollrec file $rollrecfile");
		rolllog_log(LOG_ALWAYS,'<command>',"unable to open rollrec file $rollrecfile\n");
		return;
	}

#	rolllog_log(LOG_ALWAYS,'<command>',"zone status:");

	#
	# Add the status of each zone in the rollrec file to our output buffer.
	#
	foreach my $rname (rollrec_names())
	{
		my $rrr;		# Reference to rollrec.
		my %rr;			# Rollrec hash.

		my $phase;		# Rollrec's phase.
		my $pstr;		# Phase string.

		my $rtype;		# Rollrec's record type.

		#
		# Get the rollrec for this name.
		#
		$rrr = rollrec_fullrec($rname);
		next if(!defined($rrr));
		%rr = %$rrr;

		#
		# Get the data we're interested in.
		#
		if($rr{'kskphase'} > 0)
		{
			$phase = 'KSK ' . $rr{'kskphase'};
			$pstr = rollmgr_get_phase('KSK', $rr{'kskphase'});
		}
		else
		{
			$phase = 'ZSK ' . $rr{'zskphase'};
			$pstr = rollmgr_get_phase('ZSK', $rr{'zskphase'});
		}

		$phase = "$phase: $pstr" if($pstr ne '');
		$rtype = $rr{'rollrec_type'};
		$phase = '-' if($rtype eq 'skip');

		#
		# Add the data to the output buffer and bump our zone count.
		#
		$outbuf .= "$rname/$rr{'zonename'}\t$rtype\t$phase\n";
#		rolllog_log(LOG_ALWAYS,'<command>',"\t$rname/$rr{'zonename'}\t$rtype\t$phase\n");
		$cnt++;
	}

	#
	# Send a response to the control program.
	#
	if($cnt == 0)
	{
		rollmgr_sendresp(ROLLCMD_RC_NOZONES,"no zones defined in $rollrecfile");
		rolllog_log(LOG_ALWAYS,'<command>',"no zones defined in $rollrecfile\n");
	}
	else
	{
		rollmgr_sendresp(ROLLCMD_RC_OKAY,$outbuf);
	}

	rollrec_unlock();
}

#-----------------------------------------------------------------------------
# Routine:	cmd_zsargs()
#
# Purpose:	Set zone-specific arguments.
#
sub cmd_zsargs
{
	my $data = shift;			# Command's data.

	my @args = ();				# Command's split args.
	my @zsargs = ();			# Zonesigner's args.
	my @zones = ();				# Zones to modify.
	my @badzones = ();			# Invalid zones.

	my $zsargstr = '';			# Final argument string.
	my $clear = 0;				# Flag for zapping argstr.

	rolllog_log(LOG_TMI,'<command>',"zsargs command received");

	#
	# Split the argument into its molecules.
	#
	@args = split /,/, $data;

	#
	# Divide up the arguments between zones and zonesigner arguments.
	# Zonesigner arguments have equal signs; zones don't.
	#
	foreach my $arg (@args)
	{
		if($arg =~ /\=/)
		{
			push @zsargs, $arg;
		}
		else
		{
			push @zones, $arg;
		}
	}

	#
	# Ensure we've got both zones and zonesigner arguments.
	#
	if(@zsargs == 0)
	{
		rollmgr_sendresp(ROLLCMD_RC_NOARGS,"no arguments given to zsargs command");
		rolllog_log(LOG_ALWAYS,'<command>',"no arguments given to zsargs command\n");
		return;
	}
	if(@zones == 0)
	{
		rollmgr_sendresp(ROLLCMD_RC_NOZONES,"no zones given to zsargs command");
		rolllog_log(LOG_ALWAYS,'<command>',"no zones given to zsargs command\n");
		return;
	}

	#
	# Put the arguments into the form zonesigner is expecting and join
	# up the bits into a single argument string.
	#
	for(my $ind=0; $ind < @zsargs; $ind++)
	{
		$zsargs[$ind] =~ s/^=/-/;
		$zsargs[$ind] =~ s/=/ /;
	}

	$zsargstr = join ' ', @zsargs;

	#
	# Set the "clear argument" flag if the fake "clear" option is given.
	#
	$clear = 1 if($zsargstr =~ /-clear/);

	#
	# Read the rollrec file.  If we couldn't read it, complain and return.
	#
	rollrec_lock();
	if(rollrec_read($rollrecfile) <= 0)
	{
		rollrec_unlock();
		rollmgr_sendresp(ROLLCMD_RC_RRFOPEN,"unable to open rollrec file $rollrecfile");
		rolllog_log(LOG_ALWAYS,'<command>',"unable to open rollrec file $rollrecfile\n");
		return;
	}

	#
	# Ensure the specified zones are in the rollrec file.
	# 
	foreach my $rname (@zones)
	{
		my $rrr;		# Reference to rollrec.

		$rrr = rollrec_fullrec($rname);
		if(!defined($rrr))
		{
			push @badzones, $rname;
		}
	}

	#
	# Return an error if any zones were specified that aren't in the
	# rollrec file,
	# 
	if(@badzones > 0)
	{
		rollrec_unlock();
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"non-existent zones specified - @badzones");
		rolllog_log(LOG_ALWAYS,'<command>',"non-existent zones specified - @badzones\n");
		return;
	}

	#
	# Set (or clear) the new zsargs field in the rollrec entries for the
	# given zones.
	#
	foreach my $zone (@zones)
	{
		if($clear)
		{
			rollrec_delfield($zone,"zsargs");
			rolllog_log(LOG_INFO,'<command>',"clearing zsargs from zone $zone to $zsargstr");
		}
		else
		{
			rollrec_setval($zone,"zsargs",$zsargstr);
			rolllog_log(LOG_INFO,'<command>',"setting zsargs for zone $zone to $zsargstr");
		}
	}

	#
	# Tidy up the rollrec file and tell the user we're done.
	#
	rollrec_write();
	rollrec_close();
	rollrec_unlock();
	rollmgr_sendresp(ROLLCMD_RC_OKAY,"zsargs command completed\n");
}

#-----------------------------------------------------------------------------
# Routine:	rollemall()
#
# Purpose:	This command moves all the zones in the rollrec file into
#		immediate rollover.  The type of rollover is specified by the
#		caller.  rollnow() is called for each zone, in order to start
#		rollover.  We'll also keep track of the zones we were and
#		weren't able to put in rollover, and report them to the caller.
#
sub rollemall
{
	my $rt = shift;					# Rollover type.

	my $good = '';					# Rolled zones.
	my $bad	 = '';					# Unrolled zones.

	my $cnt	 = 0;					# Total count.
	my $gcnt = 0;					# Rolled count.
	my $bcnt = 0;					# Unrolled count.

	#
	# Each zone in the rollrec file will be put in the rollover process,
	# starting after that initial wait period.  We'll keep track of the
	# zones that were rolled and those that weren't in order to provide
	# an appropriate response message.
	#
	foreach my $zone (rollrec_names())
	{
		$cnt++;

		#
		# If the rollover worked, increment the good count and add
		# the domain name to the list of good zones.  If it didn't
		# work, do the same for the bad count and bad-zone list.
		#
		if(rollnow($zone,$rt,0) == 1)
		{
			$gcnt++;
			$good .= "$zone ";
		}
		else
		{
			$bcnt++;
			$bad .= "$zone ";
		}
	}

	#
	# We don't need no steenkin' trailing whitespace.
	#
	chomp $good;
	chomp $bad;

	#
	# Send a response message to the caller.
	#
	if($gcnt == $cnt)
	{
		rollmgr_sendresp(ROLLCMD_RC_OKAY,$good);
	}
	else
	{
		my $resp;				# Response message.

		$resp = "zones not in rollrec file $rollrecfile:  $bad\n";

		#
		# If there were any zones that were put into rollover,
		# we'll add them to the message as well.
		#
		if($gcnt > 0)
		{
			$resp .= "zones now in $rt rollover:  $good\n";
		}

		rollmgr_sendresp(ROLLCMD_RC_BADZONE,$resp);
	}
}

#-----------------------------------------------------------------------------
# Routine:	rollnow()
#
# Purpose:	This command moves a zone into immediate rollover for the
#		specified key type.  It doesn't sit in the initial waiting
#		period, but starts right off in rollover phase 2.
#
sub rollnow
{
	my $zone     = shift;			# Zone to roll.
	my $rolltype = shift;			# Type of roll to start.
	my $force    = shift;			# Force-rollover flag.
	my $rollstr;				# String of roll type.

	#
	# Re-read the rollrec file and change the record's type.  We'll
	# also move the zone to phase 2 of rollover.
	#
	rollrec_lock();
	if(rollrec_read($rollrecfile) > 0)
	{
		my $rrr;				# Reference to rollrec.
		my %rr;					# Rollrec hash.

		my $dir;				# Zone's directory.
		my $krf;				# Zone's keyrec.
		my $znf;				# Zone's zonefile.

		#
		# Get the rollrec for the zone.
		#
		$rrr = rollrec_fullrec($zone);
		if(!defined($rrr))
		{
			rolllog_log(LOG_ERR,'<command>',"no rollrec defined for zone $zone");
			rollrec_close();
			rollrec_unlock();
			return(0);
		}
		%rr = %$rrr;

		#
		# If the caller isn't demanding a rollover, we'll make sure
		# the zone isn't already rolling.
		#
		if(! $force)
		{
			if($rr{'kskphase'} > 0)
			{
				rolllog_log(LOG_TMI,'<command>',"in KSK rollover (phase $rr{'kskphase'}); not attempting rollover");
				rollrec_close();
				rollrec_unlock();
				return(0);
			}

			if($rr{'zskphase'} > 0)
			{
				rolllog_log(LOG_TMI,'<command>',"in ZSK rollover (phase $rr{'zskphase'}); not attempting rollover");
				rollrec_close();
				rollrec_unlock();
				return(0);
			}

		}

		#
		# Do a few very simple validation checks.
		#
		$dir = '.';
		$krf = $rr{'keyrec'};
		$znf = $rr{'zonefile'};
		if(exists($rr{'directory'}))
		{
			$dir = $rr{'directory'};
			$krf = "$dir/$krf" if($krf !~ /^\//);
			$znf = "$dir/$znf" if($znf !~ /^\//);
		}
		if((! -e $dir) || (! -e $krf) || (! -e $znf))
		{
			rollrec_close();
			rollrec_unlock();
			return(-1);
		}

		#
		# A skip record is changed to a regular rollrec.
		#
		if($rr{'rollrec_type'} eq 'skip')
		{
			rolllog_log(LOG_INFO,'<command>',"$zone skip rollrec changed to a roll rollrec");
			rollrec_rectype($zone,"roll");
			$rrr = rollrec_fullrec($zone);
		}

		#
		# Change the zone's phase to rollover phase 1 (starting).
		#
		# WJH: This used to be set to phase 2 to bypass
		# the initial rollover waiting period and get right to the
		# nitty gritty of doing a rollover.  But I changed it back
		# to phase one, which is especially important for frequent
		# or sudden rollovers.
		#
		if($rolltype eq 'KSK')
		{
			nextphase($zone,$rrr,1,'KSK');
			$rollstr = 'KSK rollover';
		}
		elsif($rolltype eq 'ZSK')
		{
			nextphase($zone,$rrr,1,'ZSK');
			$rollstr = 'ZSK rollover';
		}
		elsif($rolltype eq 'restart')
		{
			# Do nothing, just move from skip to roll.
			$rollstr = 'restart';
		}

		#
		# Write the rollrec file.
		#
		rollrec_write();
	}

	#
	# Unlock the rollrec file.
	#
	rollrec_close();
	rollrec_unlock();

	#
	# Set the sleep values such that the queue will be run.
	#
	sleeper_awake();
	rolllog_log(LOG_INFO,'<command>',"forcing a $rollstr for zone $zone");

	#
	# This is probably not the right thing to do.
	#
	display("startroll $zone 0");
	return(1);
}

#-----------------------------------------------------------------------------
# Routine:	skipnow()
#
# Purpose:	This command prevents a zone from rolling over.  It is marked
#		as a skip record in the rollrec file.
#
sub skipnow
{
	my $zone = shift;				# Command's data.
	my $rrr;					# Reference to rollrec.
	my %rr;						# Rollrec hash.

	#
	# Get the rollrec for the zone.
	#
	$rrr = rollrec_fullrec($zone);
	if(!defined($rrr))
	{
		rolllog_log(LOG_ERR,'<command>',"no rollrec defined for zone $zone");
		return(0);
	}
	%rr = %$rrr;

	#
	# Re-read the rollrec file and change the record's type.  We'll
	# also move the zone to phase 0 of both KSK and ZSK rollover.
	#
	rollrec_lock();
	if(rollrec_read($rollrecfile) > 0)
	{
		#
		# A roll record is changed to a skip rollrec and its
		# phases set to 0.
		#
		if($rr{'rollrec_type'} eq "roll")
		{
			rolllog_log(LOG_INFO,'<command>',"$zone roll rollrec changed to a skip rollrec");

			rollrec_rectype($zone,"skip");
			display("stoproll $zone 0");
		}

		#
		# Set the zone's KSK and ZSK rollover phases to 0.
		#
#		rollrec_setval($zone,"kskphase",0);
#		rollrec_setval($zone,"zskphase",0);

		#
		# Write the rollrec file.
		#
		rollrec_write();

	}

	#
	# Unlock the rollrec file.
	#
	rollrec_close();
	rollrec_unlock();

	#
	# Log the event and return success.
	#
	rolllog_log(LOG_INFO,'<command>',"forcing a skiproll for zone $zone");
	return(1);
}

#-----------------------------------------------------------------------------
# Routine:	controllers()
#
# Purpose:	Initialize handlers for our externally provided commands.
#
sub controllers
{
	my $onflag = shift;				# Handler on/off flag.

	#
	# Set the signal handlers that will manage incoming commands.
	#
	if($onflag)
	{
		if($queued_int)
		{
			$queued_int = 0;
			halt_handler();
		}

		if($queued_hup)
		{
			$queued_hup = 0;
			intcmd_handler();
		}

		$SIG{'HUP'} = \&intcmd_handler;
		$SIG{'INT'} = \&halt_handler;
	}
	else
	{
		$SIG{'HUP'} = \&queue_hup_handler;
		$SIG{'INT'} = \&queue_int_handler;
	}
}

#-----------------------------------------------------------------------------
# Routine:	loadzone()
#
# Purpose:	Initiates zone-reload, but obeys the $zoneload flag.
#
sub loadzone
{
	my $rndc = shift;				# Zone-loading program.
	my $rname = shift;				# Rollrec name of zone.
	my $zonename = shift;				# Zone to reload.
	my $phase = shift;				# Zone's current phase.
	my $ret;					# Return code.

	#
	# If the user doesn't want to reload the zone, we'll pretend we have.
	#
	if(!$zoneload)
	{
		rolllog_log(LOG_INFO,$rname,"not reloading zone for $phase\n");
		return(0);
	}

	#
	# Reload the zone for real.
	#
	rolllog_log(LOG_INFO,$rname,"reloading zone for $phase\n");
	$ret = rollmgr_loadzone($rndc,$zonename);
	return($ret);
}

#-----------------------------------------------------------------------------
# Routine:	zonemodified()
#
# Purpose:	Checks if a zone file has been modified more recently than
#		its signed version.  If so, then the zone file will be
#		re-signed -- without any keys created or other rollover
#		actions taken.
#
#		The "more recent" check is performed by comparing the date
#		of last modification for the two zone files.  If the unsigned
#		zonefile's date is greater than the signed zonefile's date,
#		then it is assumed the unsigned zonefile was modified.
#
#		This only works if the signed and unsigned zonefiles are
#		in different files.
#
sub zonemodified
{
	my $rrr = shift;			# Rollrec reference.
	my $rname = shift;			# Zone under consideration.

	my $krf = $rrr->{'keyrec'};		# Zone's keyrec file.
	my $zfs;				# Signed zonefile.
	my $zfu;				# Unsigned zonefile.
	my @zfst;				# Zonefile stat info.
	my $zfstime;				# Update time of signed zone.
	my $zfutime;				# Update time of unsigned zone.

	#
	# Go no further here if we aren't autosigning.
	#
	return if(! $autosign);

	#
	# Get the name of the zonefile.  If the name is null, we'll read
	# the keyrec and get the name again.
	#
	if(($zfu = keyrec_recval($rname,'zonefile')) eq '')
	{
		keyrec_read($krf);
		$zfu = keyrec_recval($rname,'zonefile');
	}

	#
	# Now we'll get the name of the signed zonefile.
	#
	$zfs = keyrec_recval($rname,'signedzone');
	if($zfs ne $rrr->{'zonefile'})
	{
		rolllog_log(LOG_ERR,$rname,"rollrec and keyrec disagree about name of signed zone file");
		rolllog_log(LOG_ERR,$rname,"  rollrec's signed zone file - $rrr->{'zonefile'}");
		rolllog_log(LOG_ERR,$rname,"  keyrec's signed zone file  - $zfs");
	}

	#
	# Get the last modification time of the signed zonefile.
	#
	@zfst = stat($zfs);
	$zfstime = @zfst[9];

	#
	# Get the last modification time of the unsigned zonefile.
	#
	@zfst = stat($zfu);
	$zfutime = @zfst[9];

	#
	# Check the last modification times, and sign the zonefile if it's
	# been changed more recently than the unsigned zonefile.
	#
	if($zfutime > $zfstime)
	{
		my $krr;			# Ref to zone's keyrec.
		my $pstr;			# Phase string.

		rolllog_log(LOG_PHASE,$rname,"zonefile modified; re-signing");

		#
		# Get the current phase (in string form) and a ref
		# to the keyrec.
		#
		$pstr = phaseargs($rrr->{'kskphase'},$rrr->{'zskphase'});
		$krr = keyrec_fullrec($rname);

		#
		# Sign -- just sign -- the zone.
		#
		if(signer($rname,$pstr,$krr) == 0)
		{
			rolllog_log(LOG_TMI,$rname,"rollerd signed zone");
		}
		else
		{
			rolllog_log(LOG_ERR,$rname,"unable to sign zone");
		}
	}
}

#-----------------------------------------------------------------------------
# Routine:	phaseargs()
#
# Purpose:	Translates the KSK phase or ZSK phase into the appropriate
#		arguments for a sign-only zonesigner call.
#
sub phaseargs
{
	my $kpval = shift;			# KSK phase value.
	my $zpval = shift;			# ZSK phase value.
	my $phasestr;				# Translated argument list.

	#
	# Set up the appropriate arguments to sign with.
	#
	if($kpval)
	{
		$phasestr = "KSK phase $kpval -signonly";
	}
	elsif($zpval)
	{
		$phasestr = "ZSK phase $zpval -signonly";
	}
	else
	{
		$phasestr = ' -signonly';
	}

	return($phasestr);
}

#-----------------------------------------------------------------------------
# Routine:	queue_int_handler()
#
# Purpose:	Remember that a sig INT was received for later processing.
#
sub queue_int_handler
{
	$queued_int = 1;
}

#-----------------------------------------------------------------------------
# Routine:	queue_hup_handler()
#
# Purpose:	Remember that a sig HUP was received for later processing.
#
sub queue_hup_handler
{
	$queued_hup = 1;
}

#-----------------------------------------------------------------------------
# Routine:	intcmd_handler()
#
# Purpose:	Handle an interrupt and get a command.
#
sub intcmd_handler
{
	rolllog_log(LOG_TMI,'<command>',"rollover manager:  got a command interrupt\n");

	controllers(0);
	commander();
	controllers(1);
}

#-----------------------------------------------------------------------------
# Routine:	halt_handler()
#
# Purpose:	Handle the "halt" command.
#
sub halt_handler
{
	display("halt rollerd 0");

	rolllog_log(LOG_ALWAYS,"","rollover manager shutting down...\n");
	rollrec_write(1);	# dump the current file with commands
	rollmgr_rmid();
	exit(0);
}

#-----------------------------------------------------------------------------
# Routine:	cleanup()
#
# Purpose:	Perform whatever clean-up is required.
#
sub cleanup
{
	rolllog_log(LOG_ALWAYS,"cleaning up...") if($loglevel == LOG_TMI);
	rollmgr_rmid();
	exit(0);
}

#-----------------------------------------------------------------------------
# Routine:	displayer()
#
# Purpose:	Turn on/off the graphical display, depending on the display
#		flag.
#
sub displayer
{
	#
	# Set the global display flag to an argument -- iff we got one.
	#
	if(@_ == 1)
	{
		$display = shift;
	}

	#
	# Turn on or off the graphical display, depending on the display flag.
	#
	if($display)
	{
		open(DISPLAY, "|blinkenlights $rollrecfile");
	}
	else
	{
		display("halt rollerd 1");
		close(DISPLAY);
	}
}

#-----------------------------------------------------------------------------
# Routine:	display()
#
# Purpose:	Send a message to the display program iff the display flag
#		is on.  If we couldn't send the message, then we'll turn
#		the flag off.
#
sub display
{
	my $dmsg = shift;				# Message to send.
	my $savedsel;					# Saved descriptor.
	my $ret;					# Retcode from print.

	#
	# Don't try anything if we aren't connected to a display program.
	#
#	return if(!$display);
	return if(fileno(DISPLAY) == -1);

	#
	# Force this message to be unbuffered.
	#
	$savedsel = select(DISPLAY);
	$| = 1;
	$ret = print DISPLAY "$dmsg\n";
	select($savedsel);

	if(!$ret)
	{
		rolllog_log(LOG_INFO,'<command>',"unable to send message to blinkenlights; turning off display");
		$display = 0;
	}
}

#----------------------------------------------------------------------
# Routine:	version()
#
# Purpose:	Print the version number(s) and exit.
#
sub version
{
	print STDERR "$VERS\n";
	print STDERR "$DTVERS\n";

	exit(0);
}

#-----------------------------------------------------------------------------
# Routine:	usage()
#
# Purpose:	Print a usage message and exit.
#
sub usage
{
	print STDERR "usage:  rollerd [options]\n";
	print STDERR "\toptions:\n";
	print STDERR "\t\t-rrfile <rollrec-file>\n";
	print STDERR "\t\t-directory <dir>\n";
	print STDERR "\t\t-logfile <logfile>\n";
	print STDERR "\t\t-loglevel <level>\n";
	print STDERR "\t\t-noreload\n";
	print STDERR "\t\t-pidfile <pidfile>\n";
	print STDERR "\t\t-sleep <sleeptime>\n";
	print STDERR "\t\t-dtconfig <dnssec-tools-config-file>\n";
	print STDERR "\t\t-zonesigner <full-path-to-zonesigner>\n";
	print STDERR "\t\t-display\n";
	print STDERR "\t\t-parameters\n";
	print STDERR "\t\t-autosign | -noautosign\n";
	print STDERR "\t\t-singlerun\n";
	print STDERR "\t\t-foreground\n";
	print STDERR "\t\t-alwayssign\n";
	print STDERR "\t\t-username <username>\n";
	print STDERR "\t\t-zsargs <argument-list>\n";
	print STDERR "\t\t-verbose\n";
	print STDERR "\t\t-Version\n";
	print STDERR "\t\t-help\n";
	exit(0);
}

1;

##############################################################################
#

=pod

=head1 NAME

rollerd - DNSSEC-Tools daemon to manage DNSSEC key rollover

=head1 SYNOPSIS

  rollerd [-options] -rrfile <rollrec_file>

=head1 DESCRIPTION

The B<rollerd> daemon manages key rollover for zones.  B<rollerd> is just a
scheduler for zone rollover; it uses B<zonesigner> to perform the actual key
generation, zone signing, and key manipulation.

B<rollerd> manages both KSK and ZSK rollover, though only one rollover type
per zone may take place at a time.  Initiation of KSK rollovers takes
precedence over the initiation of ZSK rollovers.

B<rollerd> uses two methods of key rollover.  The Pre-Publish Method of key
rollover is used for ZSK key rollovers.  The Double Signature Method of key
rollover is used for KSK rollovers.  These methods are described more fully
below.

B<rollerd> maintains zone rollover state in files called I<rollrec> files;
zone/key mappings are stored in I<keyrec> files.  B<rollerd> only modifies
I<rollrec> files.  For the most part, B<rollerd> does not modify I<keyrec>
directly, but relies on B<zonesigner> to update those files as needed.
(The exceptions where B<rollerd> modifies I<keyrec> files.  At start-up,
it will mark each managed zone's I<keyrec> file to indicate the zone is under
B<rollerd>'s control.  During the course of rollover, B<rollerd> will also
update a zone's rollover times in its I<keyrec> file.)

The administrator may control B<rollerd> with the B<rollctl> command.  A large
number of commands are available to control and modify B<rollerd>'s operation,
as well as to retrieve information about rollover and daemon status.

The zone administrator will need to update their zone files periodically.  If
B<rollerd> is managing zones, then problems could arise if modified zones were
signed without B<rollerd>'s knowledge.  To prevent such problems, B<rollerd>
can be configured to automatically re-sign a zone when its zonefile is found
to be newer than its corresponding signed zonefile.  (The files' "last
modification" timestamps are compared.)  The zone will be re-signed without
any other rollover actions taking place, so no new keys will be generated, no
key rollovers will occur, and the various rollover timers will be unaffected.

B<rollerd> will perform these re-signs by default, but this can be further
controlled by the I<autosign> configuration parameter and B<rollerd>'s
B<-autosign>/B<-noautosign> command line options.  If B<rollerd> is configured
to not perform automatic re-signing, the administrator can still get this
controlled behavior by use of the B<zonesigner> or B<rollctl> commands.

If the B<rollrec> file does not exist or is of zero length, B<rollerd> will
give an error message and continue running.  It will periodically wake up and
check for a usable B<rollrec> file.  Once it finds the specified B<rollrec>
file exists and isn't empty, then it will proceed with normal rollover
management.

=head2 ZSK Rollover Using the Pre-Publish Method

The Pre-Publish Method has four phases that are entered when it is time to
perform ZSK rollover:

    1. wait for old zone data to expire from caches
    2. sign the zone with the KSK and Published ZSK
    3. wait for old zone data to expire from caches
    4. adjust keys in keyrec and sign the zone with new Current ZSK

B<rollerd> uses the B<zonesigner> command during ZSK rollover phases 2 and 4.
B<zonesigner> will generate keys as required and sign the zone during these
two phases.

The Pre-Publish Method of key rollover is defined in the Step-by-Step DNS
Security Operator Guidance Document.  See that document for more detailed
information.

=head2 KSK Rollover Using the Double Signature Method

The Double Signature Method has seven phases that are entered when it is time
to perform KSK rollover:

    1. wait for old zone data to expire from caches
    2. generate a new (published) KSK
    3. wait for the old DNSKEY RRset to expire from caches
    4. roll the KSKs
    5. transfer new keyset to the parent
    6. wait for parent to publish the new DS record
    7. reload the zone

B<rollerd> uses the B<zonesigner> command during KSK rollover phases 2 and 4.
B<zonesigner> will generate keys as required and sign the zone during these
two phases.

Currently, step 6 is handled manually.  In step 5, B<rollerd> informs the
administrator via email that the zone's keyset must be transferred to its
parent in order for rollover to continue.  In step 6, after the keyset has
been transferred to the parent and the parent has published a new DS record,
the administrator uses B<rollctl> to inform B<rollerd> that the DS record has
been published and rollover may continue.

The Double Signature Method of key rollover is defined in the Step-by-Step
DNS Security Operator Guidance Document.  See that document for more detailed
information.

=head2 KSK Rollover Using the Double Signature Method and RFC5011

RFC5011 describes how remote-validating resolvers must track KSK changes
within a zone.  If configured for RFC5011 behavior, B<rollerd> and
B<zonesigner> add an extra-long period of time between the point a new KSK is
created and published and the point where the actual switch to using it takes
place.  RFC5011 specifies that remote validators should add a "hold-down
timer" to the rollover process, such that the new key is not added as a
trust-anchor until 30 days have past.  Thus, B<rollerd> will wait for 60 days
(by default) during phase 3 of the KSK rollover process if the "istrustanchor"
field of the I<rollrec> definition has been set to either 1 or "yes".  To wait
for a different length of time other than 60 days, use the B<holddowntime>
field.

At this time, the other conventions of RFC5011 are not being followed.
Specifically, it's not waiting for a while before removing the old key
and it's not adding the revoke bit to the old key after switching.

=head2 Site-Specific Rollover Actions

An administrator can specify site-specific commands to be run during the
various rollover phases.  The commands can be run in place of the default
B<rollerd> rollover actions, or in addition to them.  This subsection
describes how to make use of site-specific rollover actions.

This capability is provided to allow different installations to handle
rollover according to their specific needs.  For example, it is anticipated
that this might be helpful to sites using HSM hardware, or to allow for
enhanced reporting to administrators.  This has been used with simple test
programs to ensure that it actually works.  However, it has not yet been used
in actual HSM environment or with other production-level software
replacements.

See the I<ZSK Rollover Using the Pre-Publish Method> and I<KSK Rollover
Using the Double Signature Method> sections for descriptions of the default
rollover actions.

B<WARNING:> This has the potential of being a dangerous capability.  Be
I<very> careful when setting up and using it.  Take care with the site-specific
commands to be executed and the permissions and ownership of B<rollerd> and
its data files.

=head3 DNSSEC-Tools Configuration File Changes

The DNSSEC-Tools configuration file must be modified to tell B<rollerd> what
must be run for the non-default rollover phase actions.  Key/value pairs may
be set for each rollover phase to control how that phase differs from the
default.

The value portion of the configuration entry contains the path to the
site-specific phase command, along with any arguments it might need.
Multiple commands are separated by bangs.

The reserved I<default> command tells B<rollerd> to use its normal rollover
action for a particular phase.  This may be combined with other commands to
provide things such as specialized logging or notifications.

B<rollerd> will only alter the behavior of a rollover phase if the
configuration file contains an entry for that phase.  If not, the default
action will be taken.

For example, this configuration line tells B<rollerd> that for ZSK rollover
phase 2, instead of using its normal B<zonesigner> executions it should run
the B<hsm-signer> command.

    prog-zsk2        hsm-signer

In this example, this configuration line informs B<rollerd> that when entering
KSK rollover phase 1 and ZSK rollover phase 1, it should execute the
B<log-and-mail> command, then use the normal rollover action for those phases.

    prog-ksk1        /usr/local/sbin/log-and-mail mary ! default
    prog-zsk1        /usr/local/sbin/log-and-mail bob!default

The following configuration keys are used for controlling KSK rollover
phases: I<prog-ksk1>, I<prog-ksk2>, I<prog-ksk3>, I<prog-ksk4>, I<prog-ksk5>,
I<prog-ksk6>, and I<prog-ksk7>,

The following configuration keys are used for controlling ZSK rollover phases:
I<prog-zsk1>, I<prog-zsk2>, I<prog-zsk3>, and I<prog-zsk4>.

The I<prog-normal> configuration key controls the normal, non-rollover state.

=head3 Site-Specific Commands

To be generally useful, the site-specific commands executed by B<rollerd>
will be given a standard set of arguments, and a standard set of exit
values will be recognized.  

The standard arguments from B<rollerd> are:
    1. zonename - Zone to be handled.
    2. phase - Zone's current rollover phase (e.g., zsk1, ksk6, normal.)
    3. rollrec name - Zone's entry key in the rollrec file.
    4. rollrec file - The path to the rollrec file.
    5. keyrec file - The path to the zone's keyrec file.

The I<prog-phase> entry in the configuration file may specify additional
options and arguments for a command.  These will be included on the execution
command line I<prior> to the standard arguments.

The standard exit values expected by B<rollerd> are:
    0. The zone can move to the next rollover phase.
       This is only applicable to the current command; other
       commands in this phase's command list must still be run.
    1. The zone should stay in the current rollover phase.
       This is not necessarily the result of an error. 
    2. An error was found in the arguments given to the command.
    3. An error was encountered during execution.

If a rollover phase's configuration entry lists multiple commands, they will
be executed in the order listed.  If any command in that command list fails,
processing stops there.

The B<rp-wrapper> command shows how a site-specific command may be written.
B<rp-wrapper> may be used as a skeleton on which to build a more useful
rollover-phase command.

=head3 Considerations for Site-Specific Commands

The following should be taken into consideration when writing a site-specific
command for a rollover phase.

=over 4

=item execution length

A phase command should not execute very long.  As currently written, B<rollerd>
serializes zone rollover.  So the longer a phase command takes to execute, the
longer it will take to get to the next zone.  If a phase command sleeps or
actively waits, so to speak, for the next phase timeout, then every zone
B<rollerd> manages will be left waiting.

=item follow interface guidelines

Follow the standards for arguments and exit values.  Not following the
standards is likely to negatively affect zone rollover.

=item frequency of command execution

If B<rollerd> is operating in its traditional "full list" processing mode, a
phase command list will be executed every time B<rollerd> cycles through its
zone list and a zone is in that particular command's phase.  For example, if
<i>prog_zsk1</i> is defined for example.com, that command list will be
executed for example.com every time B<rollerd> runs its zone list and finds
example.com is in the ZSK phase 1 rollover state.  A phase command B<must> take
this into account so it doesn't perform its actions more frequently than
necessary.  This is most likely an issue for the various rollover wait states,
and possibly the normal state.

If B<rollerd> is operating in the experimental "soon queue" processing mode, a
phase command list will be executed for a zone only when a phase change
occurs.  Since phase changes are time queued, this should not happen more than
once per phase.  A phase command B<should> take this into account, in case the
soon queue is reordered before the zone leaves the queue, or queue timing is
relatively swift.  This is most likely an issue for the various rollover wait
states.

B<WARNING:>  "soon queue" processing is I<experimental>.  Care should be taken
when using this processing method, as it may still have some lingering bugs.

=back

=head2 Zone Reloading

B<rollerd> has the opportunity to inform the DNS daemon to reload a zone in
KSK phase 2, KSK phase 7, ZSK phase 2, and ZSK phase 4.  This is the
B<rollerd>'s default behavior.  However, there are situations where this
shouldn't be done, such as for off-line signing.

The B<roll_loadzone> field of the DNSSEC-Tools configuration file is a boolean
field that overrides the default to force the zone-reload behavior either on
or off.  This field takes precedence over the default.

Similarly, the B<-noreload> option prevents B<rollerd> from requesting a zone
reload, and it takes precedence over the B<roll_loadzone> configuration field
and the default.

=head2 I<rollrec> Files

The zones to be managed by B<rollerd> are described in a I<rollrec>
file.  Generally speaking most people will want to use the B<rollinit>
command to create an initial I<rollrec> file instead of typing their
own from scratch.  See the INITIALIZATION AND USAGE section below and
the B<rollinit> manual page for details. Each zone's entry contains
data needed by B<rollerd> and some data useful to a user.  Below is a
sample I<rollrec> entry:

	roll "example.com"
		zonename        "example.com"
		zonefile        "example.com.signed"
		keyrec          "example.com.krf"
		zonegroup       "demo-zones"
		directory	"dir-example.com"
		kskphase        "0"
		zskphase        "3"
		ksk_rollsecs    "1172614842"
		ksk_rolldate    "Tue Feb 27 22:20:42 2007"
		zsk_rollsecs    "1172615087"
		zsk_rolldate    "Tue Feb 27 22:24:47 2007"
		maxttl          "60"
		display         "1"
		phasestart      "Tue Feb 27 22:25:07 2007"
        	# optional records for RFC5011 rolling:
		istrustanchor   "no"
        	holddowntime    "60D"

The first line gives the I<rollrec> entry's name.  The name distinguishes it
from other I<rollrec> entries and must be unique.  This may be the zone's
name, but this is not a requirement.  The following lines give the zone's
name, the zone's signed zone file, I<keyrec> file, the current rollover
phases, the rollover timestamps, and other information.  The zone group is
optional and allows a set of related zones to be controlled with a single
B<rollctl> execution, rather than one execution per zone.

If either of the I<zonefile> or I<keyrec> files do not exist, then a "roll"
I<rollrec> will be changed into a "skip" I<rollrec>.  That record will not be
processed.

A more detailed explanation may be found in I<rollrec(5)>.

=head2 Directories

B<rollerd>'s execution directory is either the directory in which it is
executed or the directory passed in the B<-directory> command-line option.
Any files used by B<rollerd> that were not specified with absolute paths use
this directory as their base.

A I<rollrec> file's I<directory> field informs B<rollerd> where the zone's
files may be found.  For that zone, B<rollerd> will move into that directory,
then return to its execution directory when it finishes rollover operations
for that zone.  If the I<directory> value is a relative path, it will be
appended to B<rollerd>'s execution directory.  If the I<directory> value is an
absolute path, it will be used as is.

=head2 Controlling B<rollerd> with B<rollctl>

The B<rollctl> command is used to control the behavior of B<rollerd>.  A
number of commands are available, such as starting or stopping rollover for a
selected zone or all zones, turning on or off a GUI rollover display, and
halting B<rollerd> execution.  The communications path between B<rollerd> and
B<rollctl> is operating system-dependent.  On Unix-like systems, it is a Unix
pipe that should B<only> be writable by the user which runs I<rollerd>.  A
more detailed explanation of B<rollctl> may be found in I<rollctl(8)>.

=head2 A Note About Files and Filenames

There are a number of files and filenames used by B<rollerd> and
B<zonesigner>.  The user must be aware of the files used by these programs,
where the files are located, and where the programs are executed.

By default, B<rollerd> will change directory to the DNSSEC-Tools directory,
though this may be changed by the B<-directory> option.  Any programs started
by B<rollerd>, most importantly B<zonesigner>, will run in this same
directory.  If files and directories referenced by these programs are named
with relative paths, those paths must be relative to this directory.

The I<rollrec> entry name is used as a key to the I<rollrec> file and to the
zone's I<keyrec> file.  This entry does not have to be the name of the
entry's domain, but it is a very good idea to make it so.  Whatever is used
for this entry name, the same name B<must> be used for the zone I<keyrec> in
that zone's I<keyrec> file.

It is probably easiest to store I<rollrec> files, I<keyrec> files, zone
files, and key files in a single directory.

=head1 INITIALIZATION AND USAGE

The following steps must be taken to initialize and use B<rollerd>.  This
assumes that zone files have been created, and that BIND and DNSSEC-Tools
have been installed.

=over 4

=item 0. sign zones

The zones to be managed by B<rollerd> must be signed.  Use B<zonesigner> to
create the signed zone files and the I<keyrec> files needed by B<rollerd>.
The I<rollrec> file created in the next step B<must> use the I<keyrec> file
names and the signed zone file names created here.

This step is optional.  If it is bypassed, then (in step 4 and later)
B<rollerd> will perform the initial key creation and zone signing of your
zones using the defaults found in the DNSSEC-Tools configuration file.
B<rollerd> determines if it must perform these initial operations by whether
it can find the I<keyrec> file for a zone (as specified in the I<rollrec>
file.  If it can't, it performs the initial operations; if it can, it assumes
the zone's initial operations have been performed.

=item 1. create I<rollrec> file

Before B<rollerd> may be used, a I<rollrec> file must first be created.
While this file may be built by hand, the B<rollinit> command was
written specifically to build the file.

=item 2. select operational parameters

A number of B<rollerd>'s operational parameters are taken from the
DNSSEC-Tools configuration file.  However, these may be overridden
by command-line options.  See the OPTIONS section below for more details.
If non-standard parameters are desired to always be used, the appropriate
fields in the DNSSEC-Tools configuration file may be modified to use these
values.

=item 3. install the rollover configuration

The complete rollover configuration -- B<rollerd>, I<rollrec> file,
DNSSEC-Tools configuration file values, zone files -- should be installed.  
The appropriate places for these locations are both installation-dependent
and operating system-dependent.

=item 4. test the rollover configuration

The complete rollover configuration should be tested.  

Edit the zone files so that their zones have short TTL values.  A minute TTL
should be sufficient.  Test rollovers of this speed should B<only> be done
in a test environment without the real signed zone.

Run the following command:

    rollerd -rrfile test.rollrec -logfile - -loglevel info -sleep 60

This command assumes the test I<rollrec> file is B<test.rollrec>.  It writes
a fair amount of log messages to the terminal, and checks its queue every 60
seconds.  Follow the messages to ensure that the appropriate actions, as
required by the Pre-Publish Method, are taking place.

=item 5. set B<rollerd> to start at boot

Once the configuration is found to work, B<rollerd> should be set to start
at system boot.  The actual operations required for this step are operating
system-dependent.

=item 6. reboot and verify

The system should be rebooted and the B<rollerd> logfile checked to ensure
that B<rollerd> is operating properly.

=back

=head1 OPTIONS

There are a number of operational parameters that define how B<rollerd> works.
These parameters define things such as the I<rollrec> file, the logging level,
and the log file.  These parameters can be set in the DNSSEC-Tools
configuration file or given as options on the B<rollerd> command line.
The command line options override values in the configuration file.

The following options are recognized:

=over 4

=item B<-alwayssign>

Tells B<rollerd> to sign the zones that aren't in the middle of being
rolled.  This allows B<rollerd> to refresh signed zone signatures and
allows complete management of zone signing to be taken over by B<rollerd>.

The downside to using this option is that all the non-rolling zones will be
signed after every sleep, which may be expensive computationally.

Note:  The zone files are not updated or installed at this time.
Manual copying and installation are still needed.

=item B<-autosign> | B<-noautosign>

Automatic zone-signing flag.  If this is set, then a zone's zonefile will
be re-signed (and only re-signed) if it is found to be newer than the
corresponding signed zonefile.

=item B<-directory dir>

Sets the B<rollerd> execution directory.  This must be a valid directory.

=item B<-display>

Starts the B<blinkenlights> graphical display program to show the status of
zones managed by B<rollerd>.

=item B<-dtconfig config_file>

Name of an alternate DNSSEC-Tools configuration file to be processed.
If specified, this configuration file is used I<in place> of the normal
DNSSEC-Tools configuration file B<not> in addition to it.  Also, it will be
handled prior to I<keyrec> files, I<rollrec> files, and command-line options.

=item B<-foreground>

Run in the foreground and do not fork into a daemon.

=item B<-logfile log_file>

Sets the B<rollerd> log file to I<log_file>.
This must be a valid logging file, meaning that if I<log_file> already
exists, it must be a regular file.  The only exceptions to this are if
I<logfile> is B</dev/stdout>, B</dev/tty>, B<->.  Of these three, using a
I<log_file> of B<-> is preferable since Perl will properly convert the B<->
to the process' standard output.

=item B<-loglevel level>

Sets B<rollerd>'s logging level to I<level>.  B<rollmgr.pm(3)> contains a list
of the valid logging levels.

=item B<-noreload>

Prevents B<rollerd> from telling the DNS daemon to reload zones.

=item B<-parameters>

Prints a set of B<rollerd> parameters and then exits.  This shows the
parameters with which B<rollerd> will execute, but very little parameter
validation is performed.

=item B<-pidfile pid_file>

Stores the running process PID into I<pid_file>.  This defaults to
B</var/run/rollerd.pid> on most systems.

=item B<-rrfile rollrec_file>

Name of the I<rollrec> file to be processed.  This is the only required
"option".

=item B<-realm realm_name>

Name of the realm in which B<rollerd> is running.  This is for use with the
DNSSEC-Tools realms facility as a means of easily identifying different
instantiations of B<rollerd>.  It is informational only (e.g., B<ps> output
and log files) and is not used for anything else.

=item B<-singlerun>

Processes all needed steps once and exits.  This is not the ideal way to run
B<rollerd>, but it is potentially useful for environments where keying
material is only available when specific hardware tokens have been made
available.

The timing between the steps will be potentially longer since the
time between B<rollerd> runs is dependent on when B<rollerd> is executed.
"cmd" lines must be added to the I<rollrec> file to do particular actions.

The following lines should serve as examples:

  cmd "rollzsk example.com"
  cmd "rollksk example.com"
  cmd "dspub example.com"   # (for when the parent publishes
			    # the new ksk)

The I<-singlerun> option implicitly implies I<-foreground> as well.

=item B<-sleep sleeptime>

Sets B<rollerd>'s sleep time to I<sleeptime>.  The sleep time is the amount
of time (in seconds) B<rollerd> waits between processing its I<rollrec>-based
queue.

=item B<-username username>

B<username> is the user for which the B<rollerd> daemon will be executed.
The B<rollerd> process' effective uid will be set to the uid corresponding
to B<username>.

If B<username> is a username, it must correspond to a valid uid; if it is
a uid, it must correspond to a valid username.

If B<rollerd> does not have the appropriate O/S magic (e.g., for Unix,
installed as I<setuid> program and owned by root) then it will only be able
to switch to those users to which the executing user has privilege to switch.
This restriction is dependent on the operating system and the manner by which
B<rollerd> is installed.

When using this option, the target user must have access to the various
directories, logs, and data files that B<rollerd> requires to execute.
Without this access, proper execution cannot occur.

=item B<-zsargs arglist>

Additional B<zonesigner> arguments that will be passed to all B<zonesigner>
executions. These arguments will override the corresponding arguments in the
DNSSEC-Tools configuration file, and the zones' I<keyrec> files.  If a zone's
B<rollrec> entry contains a I<zsargs> field, then it will be used instead of
those specified by this argument.

Given the B<rollerd> argument processing, the new arguments for B<zonesigner>
cannot be specified as expected.  Instead, the arguments should be given in
the following manner.  The leading dash should be replaced with an equals sign.
If the option takes an argument, the space that would separate the option from
the option's argument should also be replaced by an equals sign.  If multiple
arguments will be passed via B<-zsargs>, quotes must be used to group them
into a single argument.

B<rollerd> translates these arguments to the appropriate format for
B<zonesigner>.  These examples should clarify the modifications:

    normal zonesigner option     rollerd -zsargs option
    ------------------------     ----------------------
    -nokrfile                    -zsargs =nokrfile
    -zskcount 5 -kskcount 3      -zsargs "=zskcount=5 =kskcount=3"

=item B<-Version>

Displays the version information for B<rollerd> and the DNSSEC-Tools package.

=item B<-help>

Display a usage message.

=item B<-verbose>

Verbose output will be given.

=back

=head1 ASSUMPTIONS

B<rollerd> uses the B<rndc> command to communicate with the BIND
B<named> daemon.  Therefore, it assumes that appropriate measures have been
taken so that this communication is possible.

=head1 KNOWN PROBLEMS

The following problems (or potential problems) are known:

=over 4

=item -

Any process that can write to the rollover socket can send commands to
B<rollerd>.  This is probably not a Good Thing.

=back

=head1 COPYRIGHT

Copyright 2005-2012 SPARTA, Inc.  All rights reserved.
See the COPYING file included with the DNSSEC-Tools package for details.

=head1 AUTHOR

Wayne Morrison, tewok@tislabs.com

=head1 SEE ALSO

B<blinkenlights(8)>,
B<dtrealms(8)>,
B<named(8)>,
B<rndc(8)>,
B<rp-wrapper(8)>,
B<rollchk(8)>,
B<rollctl(8)>,
B<rollinit(8)>,
B<zonesigner(8)>

B<Net::DNS::SEC::Tools::conf.pm(3)>,
B<Net::DNS::SEC::Tools::defaults.pm(3)>,
B<Net::DNS::SEC::Tools::keyrec.pm(3)>,
B<Net::DNS::SEC::Tools::rolllog.pm(3)>,
B<Net::DNS::SEC::Tools::rollmgr.pm(3)>,
B<Net::DNS::SEC::Tools::rollrec.pm(3)>

B<rollrec(5)>

=cut