File: logrotate.c

package info (click to toggle)
logrotate 3.22.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,152 kB
  • sloc: sh: 6,666; ansic: 5,245; makefile: 161
file content (3304 lines) | stat: -rw-r--r-- 106,053 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
#include "queue.h"
#include <limits.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <popt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <glob.h>
#include <locale.h>
#include <sys/types.h>
#include <utime.h>
#include <stdint.h>
#include <libgen.h>

#if !defined(PATH_MAX) && defined(__FreeBSD__)
#include <sys/param.h>
#endif

#include "log.h"
#include "logrotate.h"

static char *prev_context;
#ifdef WITH_SELINUX
#include <selinux/selinux.h>
static int selinux_enabled = 0;
static int selinux_enforce = 0;
#endif

#ifdef WITH_ACL
#include "sys/acl.h"
#define acl_type acl_t
#else
#define acl_type void *
#endif

static acl_type prev_acl = NULL;

#if !defined(GLOB_ABORTED) && defined(GLOB_ABEND)
#define GLOB_ABORTED GLOB_ABEND
#endif

#ifdef PATH_MAX
#define STATEFILE_BUFFER_SIZE ( 2 * PATH_MAX + 16 )
#else
#define STATEFILE_BUFFER_SIZE 4096
#endif

#ifdef __hpux
extern int asprintf(char **str, const char *fmt, ...);
#endif

/* Number of seconds in a day */
#define DAY_SECONDS 86400

struct logState {
    char *fn;
    struct tm lastRotated;  /* only tm_hour, tm_mday, tm_mon, tm_year are good! */
    struct stat sb;
    int doRotate;
    int isUsed;     /* True if there is real log file in system for this state. */
    LIST_ENTRY(logState) list;
};

struct logNames {
    char *firstRotated;
    char *disposeName;
    char *finalName;
    char *dirName;
    char *baseName;
};

struct compData {
    size_t prefix_len;
    const char *dformat;
};

static struct logStateList {
    LIST_HEAD(stateSet, logState) head;
} **states;

int numLogs = 0;
int debug = 0;

static unsigned int hashSize;
static const char *mailCommand = DEFAULT_MAIL_COMMAND;
static time_t nowSecs = 0;
static uid_t save_euid;
static gid_t save_egid;

static int globerr(const char *pathname, int theerr)
{
    message(MESS_ERROR, "error accessing %s: %s\n", pathname,
            strerror(theerr));

    /* We want the glob operation to abort on error, so return 1 */
    return 1;
}

/* We could switch to qsort_r to get rid of this global variable,
 * but qsort_r is not portable enough (Linux vs. *BSD vs ...)... */
static struct compData _compData;

static int compGlobResult(const void *result1, const void *result2)  {
    struct tm time_tmp;
    time_t t1, t2;
    const char *r1 = *(char * const*)(result1);
    const char *r2 = *(char * const*)(result2);

    memset(&time_tmp, 0, sizeof(struct tm));
    strptime(r1 + _compData.prefix_len, _compData.dformat, &time_tmp);
    t1 = mktime(&time_tmp);

    memset(&time_tmp, 0, sizeof(struct tm));
    strptime(r2 + _compData.prefix_len, _compData.dformat, &time_tmp);
    t2 = mktime(&time_tmp);

    if (t1 < t2) return -1;
    if (t1 > t2) return  1;
    return 0;
}

static void sortGlobResult(glob_t *result, size_t prefix_len, const char *dformat) {
    if (!dformat || *dformat == '\0') {
        return;
    }

    _compData.prefix_len = prefix_len;
    _compData.dformat = dformat;
    qsort(result->gl_pathv, result->gl_pathc, sizeof(char *), compGlobResult);
}

int switch_user(uid_t user, gid_t group) {
    save_egid = getegid();
    save_euid = geteuid();
    if (save_euid == user && save_egid == group)
        return 0;
    message(MESS_DEBUG, "switching euid from %u to %u and egid from %u to %u (pid %d)\n",
            (unsigned) save_euid, (unsigned) user, (unsigned) save_egid, (unsigned) group, getpid());
    if (setegid(group) || seteuid(user)) {
        message(MESS_ERROR, "error switching euid from %u to %u and egid from %u to %u (pid %d): %s\n",
                (unsigned) save_euid, (unsigned) user, (unsigned) save_egid, (unsigned) group, getpid(),
                strerror(errno));
        return 1;
    }
    return 0;
}

static int switch_user_permanently(const struct logInfo *log) {
    const gid_t group = getegid();
    const uid_t user = geteuid();

    if (!(log->flags & LOG_FLAG_SU)) {
        return 0;
    }

    if (user != log->suUid) {
        message(MESS_ERROR, "current euid (%u) does not match uid of log configuration (%u) (pid %d)\n",
                (unsigned) user, (unsigned) log->suUid, getpid());
        return 1;
    }
    if (group != log->suGid) {
        message(MESS_ERROR, "current egid (%u) does not match gid of log configuration (%u) (pid %d)\n",
                (unsigned) group, (unsigned) log->suGid, getpid());
        return 1;
    }

    /* we are already the final configuration specified user/group */
    if (getuid() == user && getgid() == group) {
        return 0;
    }

    /* switch to full root first */
    if (setgid(getgid()) || setuid(getuid())) {
        message(MESS_ERROR, "error getting rid of euid != uid (pid %d): %s\n",
                getpid(), strerror(errno));
        return 1;
    }

    message(MESS_DEBUG, "switching uid to %u and gid to %u permanently (pid %d)\n",
            (unsigned) user, (unsigned) group, getpid());
    if (setgid(group) || setuid(user)) {
        message(MESS_ERROR, "error switching uid to %u and gid to %u (pid %d): %s\n",
                (unsigned) user, (unsigned) group, getpid(), strerror(errno));
        return 1;
    }

    if (user != ROOT_UID && (setuid(ROOT_UID) != -1 || seteuid(ROOT_UID) != -1)) {
        message(MESS_ERROR, "failed to switch user permanently, able to switch back (pid %d)\n",
                getpid());
        return 1;
    }

    if (chdir("/") != 0) {
        message(MESS_ERROR, "failed to change current directory to root path: %s\n",
                strerror(errno));
        return -1;
    }

    return 0;
}

int switch_user_back(void) {
    return switch_user(save_euid, save_egid);
}

static int switch_user_back_permanently(void) {
    gid_t tmp_egid = save_egid;
    uid_t tmp_euid = save_euid;
    int ret = switch_user(save_euid, save_egid);
    save_euid = tmp_euid;
    save_egid = tmp_egid;
    return ret;
}

static int open_logfile(const char *path, const struct logInfo *log, int write_access) {
    int fd, flags;
    struct stat sb;

    fd = open(path, O_NOFOLLOW | O_NOCTTY | O_NONBLOCK | (write_access ? O_RDWR : O_RDONLY));
    if (fd < 0)
        return fd;

    if (fstat(fd, &sb) != 0) {
        close(fd);
        return -1;
    }

    if (! S_ISREG(sb.st_mode)) {
        close(fd);
        errno = ENOTSUP;
        return -1;
    }

    if (sb.st_nlink != 1 && !(log->flags & LOG_FLAG_ALLOWHARDLINK)) {
        close(fd);
        errno = ENOTSUP;
        return -1;
    }

    /*
     * Unset O_NONBLOCK for portability, since O_NONBLOCK is unspecified for
     * regular files by POSIX.
     */
    if ((flags = fcntl(fd, F_GETFL)) == -1) {
        close(fd);
        return -1;
    }
    if (fcntl(fd, F_SETFL, flags & ~O_NONBLOCK) == -1) {
        close(fd);
        return -1;
    }

    return fd;
}

static void unescape(char *arg)
{
    char *p = arg;
    char *next;
    char escaped;
    while ((next = strchr(p, '\\')) != NULL) {

        p = next;

        switch (p[1]) {
            case 'n':
                escaped = '\n';
                break;
            case '\\':
                escaped = '\\';
                break;
            default:
                ++p;
                continue;
        }

        /* Overwrite the backslash with the intended character,
         * and shift everything down one */
        *p++ = escaped;
        memmove(p, p+1, 1 + strlen(p+1));
    }
}

#define HASH_SIZE_MIN 64
#define HASH_SIZE_MAX 8192
static int allocateHash(unsigned long hs)
{
    unsigned int i;

    /* Enforce some reasonable minimum hash size */
    if (hs < HASH_SIZE_MIN)
        hs = HASH_SIZE_MIN;

    /* Enforce some reasonable maximum hash size */
    if (hs > HASH_SIZE_MAX)
        hs = HASH_SIZE_MAX;

    message(MESS_DEBUG, "Allocating hash table for state file, size %lu entries\n",
            hs);

    states = calloc(hs, sizeof(struct logStateList *));
    if (states == NULL) {
        message_OOM();
        return 1;
    }

    for (i = 0; i < hs; i++) {
        states[i] = malloc(sizeof *states[0]);
        if (states[i] == NULL) {
            message_OOM();
            return 1;
        }
        LIST_INIT(&(states[i]->head));
    }

    hashSize = (unsigned)hs;

    return 0;
}

#define HASH_CONST 13
#if defined(__clang__) && defined(__clang_major__) && (__clang_major__ >= 4)
__attribute__((no_sanitize("unsigned-integer-overflow")))
#endif
static int hashIndex(const char *fn)
{
    unsigned hash = 0;
    if (!hashSize)
        /* hash table not yet allocated */
        return -1;

    while (*fn) {
        hash *= HASH_CONST;
        hash += (unsigned char)*fn++;
    }

    return (int)(hash % hashSize);
}

/* safe implementation of dup2(oldfd, nefd) followed by close(oldfd) */
static int movefd(int oldfd, int newfd)
{
    int rc;
    if (oldfd == newfd)
        /* avoid accidental close of newfd in case it is equal to oldfd */
        return 0;

    rc = dup2(oldfd, newfd);
    if (rc == 0)
        close(oldfd);

    return rc;
}

static int setSecCtx(int fdSrc, const char *src, char **pPrevCtx)
{
#ifdef WITH_SELINUX
    char *srcCtx;
    *pPrevCtx = NULL;

    if (!selinux_enabled)
        /* pretend success */
        return 0;

    /* read security context of fdSrc */
    if (fgetfilecon_raw(fdSrc, &srcCtx) < 0) {
        if (errno == ENOTSUP)
            /* pretend success */
            return 0;

        message(MESS_ERROR, "getting file context %s: %s\n", src,
                strerror(errno));
        return selinux_enforce;
    }

    /* save default security context for restoreSecCtx() */
    if (getfscreatecon_raw(pPrevCtx) < 0) {
        message(MESS_ERROR, "getting default context: %s\n", strerror(errno));
        freecon(srcCtx);
        return selinux_enforce;
    }

    /* set default security context to match fdSrc */
    if (setfscreatecon_raw(srcCtx) < 0) {
        message(MESS_ERROR, "setting default context to %s: %s\n", srcCtx,
                strerror(errno));
        freecon(*pPrevCtx);
        *pPrevCtx = NULL;
        freecon(srcCtx);
        return selinux_enforce;
    }

    message(MESS_DEBUG, "set default create context to %s\n", srcCtx);
    freecon(srcCtx);
#else
    (void) fdSrc;
    (void) src;
    (void) pPrevCtx;
#endif
    return 0;
}

static int setSecCtxByName(const char *src, const struct logInfo *log, char **pPrevCtx)
{
    int hasErrors = 0;
#ifdef WITH_SELINUX
    int fd;

    if (!selinux_enabled)
        /* pretend success */
        return 0;

    fd = open_logfile(src, log, 0);
    if (fd < 0) {
        message(MESS_ERROR, "error opening %s: %s\n", src, strerror(errno));
        return 1;
    }
    hasErrors = setSecCtx(fd, src, pPrevCtx);
    close(fd);
#else
    (void) src;
    (void) log;
    (void) pPrevCtx;
#endif
    return hasErrors;
}

static void restoreSecCtx(char **pPrevCtx)
{
#ifdef WITH_SELINUX
    if (!*pPrevCtx)
        /* no security context saved for restoration */
        return;

    /* set default security context to the previously stored one */
    if (selinux_enabled && setfscreatecon_raw(*pPrevCtx) < 0)
        message(MESS_ERROR, "setting default context to %s: %s\n", *pPrevCtx,
                strerror(errno));

    /* free the memory allocated to save the security context */
    freecon(*pPrevCtx);
    *pPrevCtx = NULL;
#else
    (void) pPrevCtx;
#endif
}

static struct logState *newState(const char *fn)
{
    struct tm now;
    struct logState *new;
    time_t lr_time;

    message(MESS_DEBUG, "Creating new state\n");

    localtime_r(&nowSecs, &now);

    new = malloc(sizeof(*new));
    if (new == NULL) {
        message_OOM();
        return NULL;
    }

    new->fn = strdup(fn);
    if (new->fn  == NULL) {
        message_OOM();
        free(new);
        return NULL;
    }

    new->doRotate = 0;
    new->isUsed = 0;

    memset(&new->lastRotated, 0, sizeof(new->lastRotated));
    new->lastRotated.tm_hour = now.tm_hour;
    new->lastRotated.tm_mday = now.tm_mday;
    new->lastRotated.tm_mon = now.tm_mon;
    new->lastRotated.tm_year = now.tm_year;
    new->lastRotated.tm_isdst = now.tm_isdst;

    /* fill in the rest of the new->lastRotated fields */
    lr_time = mktime(&new->lastRotated);
    localtime_r(&lr_time, &new->lastRotated);

    return new;
}

static struct logState *findState(const char *fn)
{
    const int i = hashIndex(fn);
    struct logState *p;
    if (i < 0)
        /* hash table not yet allocated */
        return NULL;

    for (p = states[i]->head.lh_first; p != NULL; p = p->list.le_next)
        if (!strcmp(fn, p->fn))
            break;

    /* new state */
    if (p == NULL) {
        if ((p = newState(fn)) == NULL)
            return NULL;

        LIST_INSERT_HEAD(&(states[i]->head), p, list);
    }

    return p;
}

static int runScript(const struct logInfo *log, const char *logfn, const char *logrotfn, const char *script)
{
    int rc;
    pid_t pid;

    if (debug) {
        message(MESS_DEBUG, "running script with args %s %s: \"%s\"\n",
                logfn, logrotfn ? logrotfn : "", script);
        return 0;
    }

    pid = fork();

    if (pid == -1) {
        message(MESS_ERROR, "cannot fork: %s\n", strerror(errno));
        return 1;
    }

    if (pid == 0) {
        if (log->flags & LOG_FLAG_SU) {
            if (switch_user_back_permanently() != 0) {
                exit(1);
            }
        }
        execl("/bin/sh", "sh", "-c", (char *) script, "logrotate_script", (char *) logfn, (char *) logrotfn, (char *) NULL);
        message(MESS_ERROR, "cannot execute sub-shell: %s\n", strerror(errno));
        exit(1);
    }

    wait(&rc);
    return rc;
}

#ifdef WITH_ACL
static int is_acl_well_supported(int err)
{
    switch (err) {
        case ENOTSUP:   /* no file system support */
        case EINVAL:    /* acl does not point to a valid ACL */
        case ENOSYS:    /* compatibility - acl_(g|s)et_fd(3) should never return this */
        case EBUSY:     /* compatibility - acl_(g|s)et_fd(3) should never return this */
            return 0;
        default:
            return 1;
    }
}
#endif /* WITH_ACL */

static int createOutputFile(const char *fileName, int flags, const struct stat *sb,
                            acl_type acl, int force_mode)
{
    int fd = -1;
    struct stat sb_create;
    int acl_set = 0;
    int i;

    for (i = 0; i < 2; ++i) {
        struct tm now;
        size_t fileName_size, buf_size;
        char *backupName, *ptr;

        fd = open(fileName, (flags | O_CREAT | O_EXCL | O_NOFOLLOW),
                (S_IRUSR | S_IWUSR) & sb->st_mode);

        if ((fd >= 0) || (errno != EEXIST))
            break;

        /* the destination file already exists, while it should not */
        localtime_r(&nowSecs, &now);
        fileName_size = strlen(fileName);
        buf_size = fileName_size + sizeof("-YYYYMMDDHH.backup");
        backupName = malloc(buf_size);
        if (!backupName) {
            message_OOM();
            return -1;
        }
        ptr = backupName;

        /* construct backupName starting with fileName */
        strcpy(ptr, fileName);
        ptr += fileName_size;
        buf_size -= fileName_size;

        /* append the -YYYYMMDDHH time stamp and the .backup suffix */
        ptr += strftime(ptr, buf_size, "-%Y%m%d%H", &now);
        strcpy(ptr, ".backup");

        message(MESS_ERROR, "destination %s already exists, renaming to %s\n",
                fileName, backupName);
        if (rename(fileName, backupName) != 0) {
            message(MESS_ERROR, "error renaming already existing output file"
                    " %s to %s: %s\n", fileName, backupName, strerror(errno));
            free(backupName);
            return -1;
        }

        free(backupName);

        /* existing file renamed, try it once again */
    }

    if (fd < 0) {
        message(MESS_ERROR, "error creating output file %s: %s\n",
                fileName, strerror(errno));
        return -1;
    }
    if (fchmod(fd, (S_IRUSR | S_IWUSR) & sb->st_mode)) {
        message(MESS_ERROR, "error setting mode of %s: %s\n",
                fileName, strerror(errno));
        close(fd);
        return -1;
    }

    if (fstat(fd, &sb_create)) {
        message(MESS_ERROR, "fstat of %s failed: %s\n", fileName,
                strerror(errno));
        close(fd);
        return -1;
    }

    /* Only attempt to set user/group if running as root */
    if (
        ROOT_UID == geteuid() &&
        (sb_create.st_uid != sb->st_uid || sb_create.st_gid != sb->st_gid) &&
        fchown(fd, sb->st_uid, sb->st_gid)
    ) {
        message(MESS_ERROR, "error setting owner of %s to uid %u and gid %u: %s\n",
                fileName, (unsigned) sb->st_uid, (unsigned) sb->st_gid, strerror(errno));
        close(fd);
        return -1;
    }

#ifdef WITH_ACL
    if (!force_mode && acl) {
        if (acl_set_fd(fd, acl) == -1) {
            if (is_acl_well_supported(errno)) {
                message(MESS_ERROR, "setting ACL for %s: %s\n",
                        fileName, strerror(errno));
                close(fd);
                return -1;
            }
            acl_set = 0;
        }
        else {
            acl_set = 1;
        }
    }
#else
    (void) acl;
#endif

    if (!acl_set || force_mode) {
        if (fchmod(fd, sb->st_mode)) {
            message(MESS_ERROR, "error setting mode of %s: %s\n",
                    fileName, strerror(errno));
            close(fd);
            return -1;
        }
    }

    return fd;
}

/* unlink, but try to call shred from GNU coreutils if LOG_FLAG_SHRED
 * is enabled (in that case fd needs to be a valid file descriptor) */
static int shred_file(int fd, const char *filename, const struct logInfo *log)
{
    char count[12];    /*  11 digits - that's a lot of shredding :)  */
    const char *fullCommand[6];
    int id = 0;
    int status;
    pid_t pid;

    if (log->preremove) {
        message(MESS_DEBUG, "running preremove script\n");
        if (runScript(log, filename, NULL, log->preremove)) {
            message(MESS_ERROR,
                    "error running preremove script "
                    "for %s of '%s'. Not removing this file.\n",
                    filename, log->pattern);
            /* What ever was supposed to happen did not happen,
             * therefore do not unlink the file yet.  */
            return 1;
        }
    }

    if (!(log->flags & LOG_FLAG_SHRED)) {
        goto unlink_file;
    }

    if (!(log->flags & LOG_FLAG_ALLOWHARDLINK)) {
        struct stat sb;
        if (fstat(fd, &sb) != 0) {
            message(MESS_ERROR, "cannot stat %s: %s\n", filename, strerror(errno));
            return 1;
        }

        if (sb.st_nlink != 1) {
            message(MESS_ERROR, "failed to shred \"%s\", because shredding files with"
                    " multiple hard links is disabled for %s.\n",
                    filename, log->pattern);
            return 1;
        }
    }

    message(MESS_DEBUG, "Using shred to remove the file %s\n", filename);

    fullCommand[id++] = "shred";
    fullCommand[id++] = "-u";

    if (log->shred_cycles != 0) {
        fullCommand[id++] = "-n";
        snprintf(count, sizeof(count), "%d", log->shred_cycles);
        fullCommand[id++] = count;
    }
    fullCommand[id++] = "-";
    fullCommand[id++] = NULL;

    pid = fork();

    if (pid == -1) {
        message(MESS_ERROR, "cannot fork: %s\n", strerror(errno));
        return 1;
    }

    if (pid == 0) {
        movefd(fd, STDOUT_FILENO);

        if (switch_user_permanently(log) != 0) {
            exit(1);
        }

        execvp(fullCommand[0], (void *) fullCommand);
        message(MESS_ERROR, "cannot execute shred command: %s\n", strerror(errno));
        exit(1);
    }

    wait(&status);

    if (!WIFEXITED(status) || WEXITSTATUS(status)) {
        message(MESS_ERROR, "Failed to shred %s, trying unlink\n", filename);
        return unlink(filename);
    }

    /* We have to unlink it after shred anyway,
     * because it doesn't remove the file itself */

unlink_file:
    if (unlink(filename) == 0)
        return 0;
    if (errno != ENOENT)
        return 1;

    /* unlink of log file that no longer exists is not a fatal error */
    message(MESS_ERROR, "error unlinking log file %s: %s\n", filename,
            strerror(errno));
    return 0;
}

static int removeLogFile(const char *name, const struct logInfo *log)
{
    int fd = -1;
    int result = 0;
    message(MESS_DEBUG, "removing old log %s\n", name);

    if (log->flags & LOG_FLAG_SHRED) {
        fd = open_logfile(name, log, 1);
        if (fd < 0) {
            message(MESS_ERROR, "error opening %s: %s\n",
                    name, strerror(errno));
            return 1;
        }
    }

    if (!debug && shred_file(fd, name, log)) {
        message(MESS_ERROR, "Failed to remove old log %s: %s\n",
                name, strerror(errno));
        result = 1;
    }

    if (fd != -1)
        close(fd);
    return result;
}

static void setAtimeMtime(int fd, const char *filename, const struct stat *sb)
{
    /* If we can't change atime/mtime, it's not a disaster.  It might
       possibly fail under SELinux. But do try to preserve the
       fractional part if we have utimensat(). */
#if defined HAVE_FUTIMENS && defined HAVE_STRUCT_STAT_ST_ATIM && defined HAVE_STRUCT_STAT_ST_MTIM
    struct timespec ts[2];

    ts[0] = sb->st_atim;
    ts[1] = sb->st_mtim;
    futimens(fd, ts);

    (void)filename;
#elif defined HAVE_UTIMENSAT && defined HAVE_STRUCT_STAT_ST_ATIM && defined HAVE_STRUCT_STAT_ST_MTIM
    struct timespec ts[2];

    ts[0] = sb->st_atim;
    ts[1] = sb->st_mtim;
    utimensat(AT_FDCWD, filename, ts, AT_SYMLINK_NOFOLLOW);

    (void)fd;
#else
    struct utimbuf utim;

    utim.actime = sb->st_atime;
    utim.modtime = sb->st_mtime;
    utime(filename, &utim);

    (void)fd;
#endif
}

static int compressLogFile(const char *name, const struct logInfo *log, const struct stat *sb)
{
    char *compressedName;
    int inFile;
    int outFile;
    int status;
    int compressPipe[2];
    char *prevCtx;
    pid_t pid;

    message(MESS_DEBUG, "compressing log with: %s\n", log->compress_prog);
    if (debug)
        return 0;

    if ((inFile = open_logfile(name, log, log->flags & LOG_FLAG_SHRED)) < 0) {
        message(MESS_ERROR, "unable to open %s (%s) for compression: %s\n",
            name, (log->flags & LOG_FLAG_SHRED) ? "read-write" : "read-only", strerror(errno));
        return 1;
    }

    if (setSecCtx(inFile, name, &prevCtx) != 0) {
        /* error msg already printed */
        close(inFile);
        return 1;
    }

#ifdef WITH_ACL
    if ((prev_acl = acl_get_fd(inFile)) == NULL) {
        if (is_acl_well_supported(errno)) {
            message(MESS_ERROR, "getting file ACL %s: %s\n",
                    name, strerror(errno));
            restoreSecCtx(&prevCtx);
            close(inFile);
            return 1;
        }
    }
#endif

    if (asprintf(&compressedName, "%s%s", name, log->compress_ext) < 0) {
        message_OOM();
        close(inFile);
        return 1;
    }

    outFile =
        createOutputFile(compressedName, O_RDWR, sb, prev_acl, 0);
    restoreSecCtx(&prevCtx);
#ifdef WITH_ACL
    if (prev_acl) {
        acl_free(prev_acl);
        prev_acl = NULL;
    }
#endif
    if (outFile < 0) {
        close(inFile);
        free(compressedName);
        return 1;
    }

    /* pipe used to capture stderr of the compress process */
    if (pipe(compressPipe) < 0) {
        message(MESS_ERROR, "error opening pipe for compress: %s\n",
                strerror(errno));
        close(inFile);
        close(outFile);
        free(compressedName);
        return 1;
    }

    pid = fork();

    if (pid == -1) {
        message(MESS_ERROR, "cannot fork: %s\n", strerror(errno));
        close(inFile);
        close(outFile);
        close(compressPipe[1]);
        close(compressPipe[0]);
        free(compressedName);
        return 1;
    }

    if (pid == 0) {
        const char **fullCommand;
        int i;

        /* close read end of pipe in the child process */
        close(compressPipe[0]);
        free(compressedName);

        movefd(inFile, STDIN_FILENO);
        movefd(outFile, STDOUT_FILENO);

        if (switch_user_permanently(log) != 0) {
            exit(1);
        }

        movefd(compressPipe[1], STDERR_FILENO);

        /* export name of file to compress for custom compress scripts */
        {
                char *envInFilename;
                if (asprintf(&envInFilename, "LOGROTATE_COMPRESSED_FILENAME=%s", name) < 0) {
                    message_OOM();
                    exit(1);
                }
                putenv(envInFilename);
                /* do not free envInFilename, cause putenv(3) might not create a copy */
        }

        fullCommand = malloc(sizeof(*fullCommand) * ((size_t)log->compress_options_count + 2));
        if (!fullCommand) {
            message_OOM();
            exit(1);
        }

        fullCommand[0] = log->compress_prog;
        for (i = 0; i < log->compress_options_count; i++)
            fullCommand[i + 1] = log->compress_options_list[i];
        fullCommand[log->compress_options_count + 1] = NULL;

        execvp(fullCommand[0], (void *) fullCommand);
        message(MESS_ERROR, "cannot execute compress command '%s': %s\n", fullCommand[0], strerror(errno));
        exit(1);
    }

    /* close write end of pipe in the parent process */
    close(compressPipe[1]);

    {
        int error_printed = 0;

        for (;;) {
            char buff[4096];
            ssize_t n_read = read(compressPipe[0], buff, sizeof(buff) - 1);

            if (n_read < 0) {
                if (errno == EINTR)
                    continue;
                else
                    break;
            }

            if (n_read == 0)
                break;

            if (!error_printed) {
                error_printed = 1;
                message(MESS_ERROR, "Compressing program wrote following message "
                        "to stderr when compressing log %s:\n", name);
            }
            buff[n_read] = '\0';
            fprintf(stderr, "%s", buff);
        }
    }

    close(compressPipe[0]);
    wait(&status);

    fsync(outFile);

    if (!WIFEXITED(status) || WEXITSTATUS(status)) {
        message(MESS_ERROR, "failed to compress log %s\n", name);
        close(inFile);
        close(outFile);
        unlink(compressedName);
        free(compressedName);
        return 1;
    }

    setAtimeMtime(outFile, compressedName, sb);

    close(outFile);
    free(compressedName);

    if (shred_file(inFile, name, log)) {
        close(inFile);
        return 1;
    }

    close(inFile);

    return 0;
}

static int mailLog(const struct logInfo *log, const char *logFile, const char *mailComm,
                   const char *uncompressCommand, const char *address, const char *subject)
{
    int mailInput;
    pid_t mailChild, uncompressChild = 0;
    int mailStatus, uncompressStatus;
    int uncompressPipe[2];
    char * const mailArgv[] = { (char *) mailComm, (char *) "-s", (char *) subject, (char *) address, NULL };
    int rc = 0;

    if ((mailInput = open_logfile(logFile, log, 0)) < 0) {
        message(MESS_ERROR, "failed to open %s for mailing: %s\n", logFile,
                strerror(errno));
        return 1;
    }

    if (uncompressCommand) {
        /* pipe used to capture output of the uncompress process */
        if (pipe(uncompressPipe) < 0) {
            message(MESS_ERROR, "error opening pipe for uncompress: %s\n",
                    strerror(errno));
            close(mailInput);
            return 1;
        }

        uncompressChild = fork();

        if (uncompressChild == -1) {
            message(MESS_ERROR, "cannot fork: %s\n", strerror(errno));
            close(mailInput);
            close(uncompressPipe[1]);
            close(uncompressPipe[0]);
            return 1;
        }

        if (uncompressChild == 0) {
            /* uncompress child */

            /* close read end of pipe in the child process */
            close(uncompressPipe[0]);

            movefd(mailInput, STDIN_FILENO);
            movefd(uncompressPipe[1], STDOUT_FILENO);

            if (switch_user_permanently(log) != 0) {
                exit(1);
            }

            execlp(uncompressCommand, uncompressCommand, (char *) NULL);
            message(MESS_ERROR, "cannot execute uncompress command: %s\n", strerror(errno));
            exit(1);
        }

        close(mailInput);
        mailInput = uncompressPipe[0];
        close(uncompressPipe[1]);
    }

    mailChild = fork();

    if (mailChild == -1) {
        message(MESS_ERROR, "cannot fork: %s\n", strerror(errno));
        close(mailInput);
        return 1;
    }

    if (mailChild == 0) {
        movefd(mailInput, STDIN_FILENO);
        close(STDOUT_FILENO);

        /* mail command runs as root */
        if (log->flags & LOG_FLAG_SU) {
            if (switch_user_back_permanently() != 0) {
                exit(1);
            }
        }

        execvp(mailArgv[0], mailArgv);
        message(MESS_ERROR, "cannot execute mail command: %s\n", strerror(errno));
        exit(1);
    }

    close(mailInput);

    waitpid(mailChild, &mailStatus, 0);

    if (!WIFEXITED(mailStatus) || WEXITSTATUS(mailStatus)) {
        message(MESS_ERROR, "mail command failed for %s\n", logFile);
        rc = 1;
    }

    if (uncompressCommand) {
        waitpid(uncompressChild, &uncompressStatus, 0);

        if (!WIFEXITED(uncompressStatus) || WEXITSTATUS(uncompressStatus)) {
            message(MESS_ERROR, "uncompress command failed mailing %s\n",
                    logFile);
            rc = 1;
        }
    }

    return rc;
}

static int mailLogWrapper(const char *mailFilename, const char *mailComm,
                          unsigned logNum, const struct logInfo *log)
{
    /* uncompress already compressed log files before mailing them */
    const char *uncompress_prog = (log->flags & LOG_FLAG_COMPRESS)
        ? log->uncompress_prog
        : NULL;

    const char *subject = mailFilename;
    if (log->flags & LOG_FLAG_MAILFIRST) {
        if (log->flags & LOG_FLAG_DELAYCOMPRESS)
            /* the log we are mailing has not been compressed yet */
            uncompress_prog = NULL;

        if (uncompress_prog)
            /* use correct subject when mailfirst is enabled */
            subject = log->files[logNum];
    }

    return mailLog(log, mailFilename, mailComm, uncompress_prog,
                   log->logAddress, subject);
}

/* Use a heuristic to determine whether stat buffer SB comes from a file
   with sparse blocks.  If the file has fewer blocks than would normally
   be needed for a file of its size, then at least one of the blocks in
   the file is a hole.  In that case, return true.  */
static int is_probably_sparse(struct stat const *sb)
{
#if defined(HAVE_STRUCT_STAT_ST_BLOCKS) && defined(HAVE_STRUCT_STAT_ST_BLKSIZE)
    return (S_ISREG (sb->st_mode)
            && sb->st_blksize != 0
            && sb->st_blocks < sb->st_size / sb->st_blksize);
#else
    return 0;
#endif
}

#define MIN(a,b) ((a) < (b) ? (a) : (b))

/* Return whether the buffer consists entirely of NULs.
   Note the word after the buffer must be non NUL. */

static int is_nul (void const *buf, size_t bufsize)
{
    char const *cbuf = buf;
    char const *cp = buf;

    /* Find the first nonzero *byte*, or the sentinel.  */
    while (*cp++ == 0)
        continue;

    return cbuf + bufsize < cp;
}

static size_t full_write(int fd, const void *buf, size_t count)
{
    size_t total = 0;
    const unsigned char *ptr = (const unsigned char *) buf;

    while (count > 0)
    {
        size_t n_rw;
        for (;;)
        {
            n_rw = (size_t)write (fd, ptr, count);
            if (n_rw == (size_t) -1 && errno == EINTR)
                continue;

            break;
        }
        if (n_rw == (size_t) -1)
            break;
        if (n_rw == 0)
            break;
        total += n_rw;
        ptr += n_rw;
        count -= n_rw;
    }

    return total;
}

static int sparse_copy(int src_fd, int dest_fd, const struct stat *sb,
                       const char *saveLog, const char *currLog)
{
    const int make_holes = is_probably_sparse(sb);
    size_t max_n_read = SIZE_MAX;
    int last_write_made_hole = 0;
    off_t total_n_read = 0;
    char buf[BUFSIZ + 1];

    while (max_n_read) {
        int make_hole = 0;
        size_t bytes_read;
        const ssize_t n_read = read (src_fd, buf, MIN (max_n_read, BUFSIZ));
        if (n_read < 0) {
            if (errno == EINTR) {
                continue;
            }
            message(MESS_ERROR, "error reading %s: %s\n",
                    currLog, strerror(errno));
            return 0;
        }

        if (n_read == 0)
            break;

        bytes_read = (size_t)n_read;

        max_n_read -= bytes_read;
        total_n_read += n_read;

        if (make_holes) {
            /* Sentinel required by is_nul().  */
            buf[bytes_read] = '\1';

            if ((make_hole = is_nul(buf, bytes_read))) {
                if (lseek (dest_fd, n_read, SEEK_CUR) < 0) {
                    message(MESS_ERROR, "error seeking %s: %s\n",
                            saveLog, strerror(errno));
                    return 0;
                }
            }
        }

        if (!make_hole) {
            if (full_write (dest_fd, buf, bytes_read) != bytes_read) {
                message(MESS_ERROR, "error writing to %s: %s\n",
                        saveLog, strerror(errno));
                return 0;
            }
        }

        last_write_made_hole = make_hole;
    }

    if (last_write_made_hole) {
        if (ftruncate(dest_fd, total_n_read) < 0) {
            message(MESS_ERROR, "error ftruncate %s: %s\n",
                    saveLog, strerror(errno));
            return 0;
        }
    }

    return 1;
}

static int copyTruncate(const char *currLog, const char *saveLog, const struct stat *sb,
                        const struct logInfo *log, int skip_copy)
{
    int rc = 1;
    int fdcurr = -1, fdsave = -1;

    message(MESS_DEBUG, "%scopying %s to %s\n", skip_copy ? "skip " : "", currLog, saveLog);

    if (!debug) {
        /* read access is sufficient for 'copy' but not for 'copytruncate' */
        const int read_only = (log->flags & LOG_FLAG_COPY)
            && !(log->flags & LOG_FLAG_COPYTRUNCATE);
        if ((fdcurr = open_logfile(currLog, log, !read_only)) < 0) {
            message(MESS_ERROR, "error opening %s: %s\n", currLog,
                    strerror(errno));
            goto fail;
        }

        if (!skip_copy) {
            char *prevCtx;

            if (setSecCtx(fdcurr, currLog, &prevCtx) != 0) {
                /* error msg already printed */
                goto fail;
            }
#ifdef WITH_ACL
            if ((prev_acl = acl_get_fd(fdcurr)) == NULL) {
                if (is_acl_well_supported(errno)) {
                    message(MESS_ERROR, "getting file ACL %s: %s\n",
                            currLog, strerror(errno));
                    restoreSecCtx(&prevCtx);
                    goto fail;
                }
            }
#endif /* WITH_ACL */
            fdsave = createOutputFile(saveLog, O_WRONLY, sb, prev_acl, 0);
            restoreSecCtx(&prevCtx);
#ifdef WITH_ACL
            if (prev_acl) {
                acl_free(prev_acl);
                prev_acl = NULL;
            }
#endif
            if (fdsave < 0)
                goto fail;

            if (sparse_copy(fdcurr, fdsave, sb, saveLog, currLog) != 1) {
                message(MESS_ERROR, "error copying %s to %s: %s\n", currLog,
                        saveLog, strerror(errno));
                unlink(saveLog);
                goto fail;
            }
        }
    }

    if (log->flags & LOG_FLAG_COPYTRUNCATE) {
        message(MESS_DEBUG, "truncating %s\n", currLog);

        if (!debug) {
            if (fdsave >= 0)
                fsync(fdsave);
            if (ftruncate(fdcurr, 0)) {
                message(MESS_ERROR, "error truncating %s: %s\n", currLog,
                        strerror(errno));
                goto fail;
            }
        }
    } else
        message(MESS_DEBUG, "Not truncating %s\n", currLog);

    rc = 0;
fail:
    if (fdcurr >= 0) {
        close(fdcurr);
    }
    if (fdsave >= 0) {
        close(fdsave);
    }
    return rc;
}

/* return value similar to mktime() but the exact time is ignored */
static time_t mktimeFromDateOnly(const struct tm *src)
{
    /* explicit struct copy to retain C89 compatibility */
    struct tm tmp;
    memcpy(&tmp, src, sizeof tmp);

    /* abstract out (nullify) fields expressing the exact time */
    tmp.tm_hour = 0;
    tmp.tm_min  = 0;
    tmp.tm_sec  = 0;
    return mktime(&tmp);
}

/* return by how many days the date was advanced but ignore exact time */
static long daysElapsed(const struct tm *now, const struct tm *last)
{
    const double diff = difftime(mktimeFromDateOnly(now), mktimeFromDateOnly(last));
    return (long) ((intmax_t)diff / DAY_SECONDS);
}

static int findNeedRotating(const struct logInfo *log, unsigned logNum, int force)
{
    struct stat sb;
    struct logState *state;
    struct tm now;

    message(MESS_DEBUG, "considering log %s\n", log->files[logNum]);

    localtime_r(&nowSecs, &now);

    /* Check if parent directory of this log has safe permissions */
    if ((log->flags & LOG_FLAG_SU) == 0 && getuid() == ROOT_UID) {
        char *ld;
        char *logpath = strdup(log->files[logNum]);
        if (logpath == NULL) {
            message_OOM();
            return 1;
        }
        ld = dirname(logpath);
        if (stat(ld, &sb)) {
            /* If parent directory doesn't exist, it's not real error
               (unless nomissingok is specified)
               and rotation is not needed */
            if (errno != ENOENT || (log->flags & LOG_FLAG_MISSINGOK) == 0) {
                message(MESS_ERROR, "stat of %s failed: %s\n", ld,
                        strerror(errno));
                free(logpath);
                return 1;
            }
            free(logpath);
            return 0;
        }
        /* Don't rotate in directories writable by others or group which is not "root"  */
        if ((sb.st_gid != 0 && (sb.st_mode & S_IWGRP)) || (sb.st_mode & S_IWOTH)) {
            message(MESS_ERROR, "skipping \"%s\" because parent directory has insecure permissions"
                    " (It's world writable or writable by group which is not \"root\")"
                    " Set \"su\" directive in config file to tell logrotate which user/group"
                    " should be used for rotation.\n"
                    ,log->files[logNum]);
            free(logpath);
            return 1;
        }
        free(logpath);
    }

    if (lstat(log->files[logNum], &sb)) {
        if ((log->flags & LOG_FLAG_MISSINGOK) && (errno == ENOENT)) {
            message(MESS_DEBUG, "  log %s does not exist -- skipping\n",
                    log->files[logNum]);
            return 0;
        }
        message(MESS_ERROR, "stat of %s failed: %s\n", log->files[logNum],
                strerror(errno));
        return 1;
    }

    state = findState(log->files[logNum]);
    if (!state)
        return 1;

    state->doRotate = 0;
    state->sb = sb;
    state->isUsed = 1;

    if ((sb.st_mode & S_IFMT) == S_IFLNK) {
        message(MESS_DEBUG, "  log %s is symbolic link. Rotation of symbolic"
                " links is not allowed to avoid security issues -- skipping.\n",
                log->files[logNum]);
        return 0;
    }

    if (!(log->flags & LOG_FLAG_ALLOWHARDLINK) && sb.st_nlink != 1) {
        message(MESS_DEBUG, "  log %s has multiple (%lu) hard links. Rotation of files"
                " with multiple hard links is not allowed for %s -- skipping.\n",
                log->files[logNum], (unsigned long)sb.st_nlink, log->pattern);
        return 0;
    }

    message(MESS_DEBUG, "  Now: %d-%02d-%02d %02d:%02d\n", 1900 + now.tm_year,
            1 + now.tm_mon, now.tm_mday,
            now.tm_hour, now.tm_min);

    message(MESS_DEBUG, "  Last rotated at %d-%02d-%02d %02d:%02d\n", 1900 + state->lastRotated.tm_year,
            1 + state->lastRotated.tm_mon, state->lastRotated.tm_mday,
            state->lastRotated.tm_hour, state->lastRotated.tm_min);

    if (force) {
        /* user forced rotation of logs from command line */
        state->doRotate = 1;
    }
    else if (log->maxsize && sb.st_size > log->maxsize) {
        state->doRotate = 1;
    }
    else if (log->criterium == ROT_SIZE) {
        state->doRotate = (sb.st_size >= log->threshold);
        if (!state->doRotate) {
            message(MESS_DEBUG, "  log does not need rotating "
                    "(log size is below the 'size' threshold)\n");
        }
    } else if (difftime(mktime(&state->lastRotated), mktime(&now)) > (25 * 3600)) {
        /* 25 hours allows for DST changes as well as geographical moves */
        message(MESS_ERROR,
                "log %s last rotated in the future -- rotation forced\n",
                log->files[logNum]);
        state->doRotate = 1;
    } else if (state->lastRotated.tm_year != now.tm_year ||
            state->lastRotated.tm_mon != now.tm_mon ||
            state->lastRotated.tm_mday != now.tm_mday ||
            state->lastRotated.tm_hour != now.tm_hour) {
        long days;
        switch (log->criterium) {
            case ROT_WEEKLY:
                days = daysElapsed(&now, &state->lastRotated);
                /* rotate if date is advanced by 7+ days (exact time is ignored) */
                state->doRotate = (days >= 7)
                    /* ... or if we have not yet rotated today */
                    || (days >= 1
                            /* ... and the selected weekday is today */
                            && (unsigned)now.tm_wday == log->weekday);
                if (!state->doRotate) {
                    message(MESS_DEBUG, "  log does not need rotating "
                            "(log has been rotated at %d-%02d-%02d %02d:%02d, "
                            "which is less than a week ago)\n", 1900 + state->lastRotated.tm_year,
                            1 + state->lastRotated.tm_mon, state->lastRotated.tm_mday,
                            state->lastRotated.tm_hour, state->lastRotated.tm_min);
                }
                break;
            case ROT_HOURLY:
                state->doRotate = ((now.tm_hour != state->lastRotated.tm_hour) ||
                        (now.tm_mday != state->lastRotated.tm_mday) ||
                        (now.tm_mon != state->lastRotated.tm_mon) ||
                        (now.tm_year != state->lastRotated.tm_year));
                if (!state->doRotate) {
                    message(MESS_DEBUG, "  log does not need rotating "
                            "(log has been rotated at %d-%02d-%02d %02d:%02d, "
                            "which is less than an hour ago)\n", 1900 + state->lastRotated.tm_year,
                            1 + state->lastRotated.tm_mon, state->lastRotated.tm_mday,
                            state->lastRotated.tm_hour, state->lastRotated.tm_min);
                }
                break;
            case ROT_DAYS:
                state->doRotate = ((now.tm_mday != state->lastRotated.tm_mday) ||
                        (now.tm_mon != state->lastRotated.tm_mon) ||
                        (now.tm_year != state->lastRotated.tm_year));
                if (!state->doRotate) {
                    message(MESS_DEBUG, "  log does not need rotating "
                            "(log has been rotated at %d-%02d-%02d %02d:%02d, "
                            "which is less than a day ago)\n", 1900 + state->lastRotated.tm_year,
                            1 + state->lastRotated.tm_mon, state->lastRotated.tm_mday,
                            state->lastRotated.tm_hour, state->lastRotated.tm_min);
                }
                break;
            case ROT_MONTHLY:
                /* rotate if the logs haven't been rotated this month or
                   this year */
                state->doRotate = ((now.tm_mon != state->lastRotated.tm_mon) ||
                        (now.tm_year != state->lastRotated.tm_year));
                if (!state->doRotate) {
                    message(MESS_DEBUG, "  log does not need rotating "
                            "(log has been rotated at %d-%02d-%02d %02d:%02d, "
                            "which is less than a month ago)\n", 1900 + state->lastRotated.tm_year,
                            1 + state->lastRotated.tm_mon, state->lastRotated.tm_mday,
                            state->lastRotated.tm_hour, state->lastRotated.tm_min);
                }
                break;
            case ROT_YEARLY:
                /* rotate if the logs haven't been rotated this year */
                state->doRotate = (now.tm_year != state->lastRotated.tm_year);
                if (!state->doRotate) {
                    message(MESS_DEBUG, "  log does not need rotating "
                            "(log has been rotated at %d-%02d-%02d %02d:%02d, "
                            "which is less than a year ago)\n", 1900 + state->lastRotated.tm_year,
                            1 + state->lastRotated.tm_mon, state->lastRotated.tm_mday,
                            state->lastRotated.tm_hour, state->lastRotated.tm_min);
                }
                break;
            case ROT_SIZE:
            default:
                /* ack! */
                state->doRotate = 0;
                break;
        }
        if (log->minsize && sb.st_size < log->minsize) {
            state->doRotate = 0;
            message(MESS_DEBUG, "  log does not need rotating "
                    "('minsize' directive is used and the log "
                    "size is smaller than the minsize value)\n");
        }
        if (log->rotateMinAge && log->rotateMinAge * DAY_SECONDS >= difftime(nowSecs, sb.st_mtime)) {
            state->doRotate = 0;
            message(MESS_DEBUG, "  log does not need rotating "
                    "('minage' directive is used and the log "
                    "age is smaller than the minage days)\n");
        }
    }
    else if (!state->doRotate) {
        message(MESS_DEBUG, "  log does not need rotating "
                "(log has already been rotated)\n");
    }

    /* The notifempty flag overrides the normal criteria */
    if (state->doRotate && !(log->flags & LOG_FLAG_IFEMPTY) && !sb.st_size) {
        state->doRotate = 0;
        message(MESS_DEBUG, "  log does not need rotating "
                "(log is empty)\n");
    }

    if (state->doRotate) {
        message(MESS_DEBUG, "  log needs rotating\n");
    }

    return 0;
}

/* find the rotated file with the highest index */
static int findLastRotated(const struct logNames *rotNames,
                           const char *fileext, const char *compext)
{
    char *pattern;
    int glob_rc;
    glob_t globResult;
    size_t i;
    int last = 0;
    size_t prefixLen, suffixLen;

    if (asprintf(&pattern, "%s/%s.*%s%s", rotNames->dirName,
                 rotNames->baseName, fileext, compext) < 0)
        /* out of memory */
        return -1;

    glob_rc = glob(pattern, 0, globerr, &globResult);
    free(pattern);
    switch (glob_rc) {
        case 0:
            /* glob() succeeded */
            break;

        case GLOB_NOMATCH:
            /* found nothing -> assume first rotation */
            return 0;

        default:
            /* glob() failed */
            return -1;
    }

    prefixLen = strlen(rotNames->dirName) + /* '/' */1
        + strlen(rotNames->baseName) + /* '.' */ 1;
    suffixLen = strlen(fileext) + strlen(compext);

    for (i = 0; i < globResult.gl_pathc; ++i) {
        char *fileName = globResult.gl_pathv[i];
        const size_t fileNameLen = strlen(fileName);
        int num;
        char c;
        if (fileNameLen <= prefixLen + suffixLen)
            /* not enough room for index in this file name */
            continue;

        /* cut off prefix/suffix */
        fileName[fileNameLen - suffixLen] = '\0';
        fileName += prefixLen;

        if (sscanf(fileName, "%d%c", &num, &c) != 1)
            /* index not matched in this file name */
            continue;

        /* update last index */
        if (last < num)
            last = num;
    }

    globfree(&globResult);
    return last;
}

static int prerotateSingleLog(const struct logInfo *log, unsigned logNum,
                              struct logState *state, struct logNames *rotNames)
{
    struct tm now;
    const char *compext = "";
    const char *fileext = "";
    int hasErrors = 0;
    char *glob_pattern;
    glob_t globResult;
    int rc;
    int rotateCount = log->rotateCount ? log->rotateCount : 1;
#define DATEEXT_LEN 64
#define PATTERN_LEN (DATEEXT_LEN * 2)
    char dext_str[DATEEXT_LEN];
    char dformat[PATTERN_LEN] = "";
    char dext_pattern[PATTERN_LEN];
    const char *final_dformat;
    size_t ret;

    if (!state->doRotate)
        return 0;

    /* Logs with rotateCounts of 0 are rotated once, then removed. This
       lets scripts run properly, and everything gets mailed properly. */

    message(MESS_DEBUG, "rotating log %s, log->rotateCount is %d\n",
            log->files[logNum], log->rotateCount);

    if (log->flags & LOG_FLAG_COMPRESS) {
        if (!log->compress_ext) {
            message(MESS_ERROR, "log %s: compression enabled, but compression "
                "extension is not set\n", log->files[logNum]);
            return 1;
        }

        compext = log->compress_ext;
    }

    localtime_r(&nowSecs, &now);
    state->lastRotated = now;

    {
        const char *ld;
        char *logpath = strdup(log->files[logNum]);
        if (logpath == NULL) {
            message_OOM();
            return 1;
        }
        ld = dirname(logpath);
        if (log->oldDir) {
            if (log->oldDir[0] != '/') {
                if (asprintf(&rotNames->dirName, "%s/%s", ld, log->oldDir) < 0) {
                    rotNames->dirName = NULL;
                }
            } else
                rotNames->dirName = strdup(log->oldDir);
        } else
            rotNames->dirName = strdup(ld);
        free(logpath);

        if (rotNames->dirName == NULL) {
            message_OOM();
            return 1;
        }
    }

    {
        char *filename = strdup(log->files[logNum]);
        if (filename == NULL) {
            message_OOM();
            return 1;
        }

        rotNames->baseName = strdup(basename(filename));
        if (rotNames->baseName == NULL) {
            message_OOM();
            free(filename);
            return 1;
        }

        free(filename);
    }

    if (log->addextension) {
        const size_t baseLen = strlen(rotNames->baseName);
        const size_t extLen = strlen(log->addextension);
        if (baseLen >= extLen &&
                strncmp(&(rotNames->baseName[baseLen - extLen]),
                    log->addextension, extLen) == 0) {

            char *tempstr = strndup(rotNames->baseName, baseLen - extLen);
            if (tempstr == NULL) {
                message_OOM();
                return 1;
            }

            free(rotNames->baseName);
            rotNames->baseName = tempstr;
        }
        fileext = log->addextension;
    }

    if (log->extension) {
        const size_t baseLen = strlen(rotNames->baseName);
        const size_t extLen = strlen(log->extension);

        if (baseLen >= extLen &&
                strncmp(&(rotNames->baseName[baseLen - extLen]),
                    log->extension, extLen) == 0) {
            char *tempstr;

            fileext = log->extension;
            tempstr = strndup(rotNames->baseName, baseLen - extLen);
            if (tempstr == NULL) {
                message_OOM();
                return 1;
            }
            free(rotNames->baseName);
            rotNames->baseName = tempstr;
        }
    }

    /* Adjust "now" if we want yesterday's date */
    if (log->flags & LOG_FLAG_DATEYESTERDAY) {
        now.tm_hour = 12; /* set hour to noon to work around DST issues */
        now.tm_mday = now.tm_mday - 1;
        mktime(&now);
    }

    if (log->flags & LOG_FLAG_DATEHOURAGO) {
        now.tm_hour -= 1;
        mktime(&now);
    }

    /* Construct the glob pattern corresponding to the date format */
    dext_str[0] = '\0';
    if (log->dateformat) {
        const char *dext = log->dateformat;
        size_t i = 0, j = 0;

        memset(dext_pattern, 0, sizeof(dext_pattern));
        while (*dext == ' ')
            dext++;
        while (*dext != '\0') {
            /* Will there be a space for a char and '\0'? */
            if (j >= (sizeof(dext_pattern) - 1) ||
                i >= (sizeof(dformat) - 2)) {
                message(MESS_ERROR, "Date format %s is too long\n",
                        log->dateformat);
                return 1;
            }
            if (*dext == '%') {
                switch (*(dext + 1)) {
                    case 'Y':
                        strncat(dext_pattern, "[0-9][0-9]",
                                sizeof(dext_pattern) - strlen(dext_pattern) - 1);
                        j += 10; /* strlen("[0-9][0-9]") */
                        /* FALLTHRU */
                    case 'm':
                    case 'd':
                    case 'H':
                    case 'M':
                    case 'S':
                    case 'V':
                        strncat(dext_pattern, "[0-9][0-9]",
                                sizeof(dext_pattern) - strlen(dext_pattern) - 1);
                        j += 10;
                        if (j >= (sizeof(dext_pattern) - 1)) {
                            message(MESS_ERROR, "Date format %s is too long\n",
                                    log->dateformat);
                            return 1;
                        }
                        dformat[i++] = *(dext++);
                        dformat[i] = *dext;
                        break;
                    case 's':
                        /* End of year 2293 this pattern does not work. */
                        strncat(dext_pattern,
                                "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]",
                                sizeof(dext_pattern) - strlen(dext_pattern) - 1);
                        j += 50;
                        if (j >= (sizeof(dext_pattern) - 1)) {
                            message(MESS_ERROR, "Date format %s is too long\n",
                                    log->dateformat);
                            return 1;
                        }
                        dformat[i++] = *(dext++);
                        dformat[i] = *dext;
                        break;
                    case 'z':
                        strncat(dext_pattern, "[-+][0-9][0-9][0-9][0-9]",
                                sizeof(dext_pattern) - strlen(dext_pattern) - 1);
                        j += 24;
                        if (j >= (sizeof(dext_pattern) - 1)) {
                            message(MESS_ERROR, "Date format %s is too long\n",
                                    log->dateformat);
                            return 1;
                        }
                        dformat[i++] = *(dext++);
                        dformat[i] = *dext;
                        break;
                    default:
                        dformat[i++] = *dext;
                        dformat[i] = '%';
                        dext_pattern[j++] = *dext;
                        break;
                }
            } else {
                dformat[i] = *dext;
                dext_pattern[j++] = *dext;
            }
            ++i;
            ++dext;
        }
        dformat[i] = '\0';
        message(MESS_DEBUG, "Converted '%s' -> '%s'\n", log->dateformat, dformat);
        final_dformat = dformat;
    } else {
        if (log->criterium == ROT_HOURLY) {
            /* hourly adds another two digits */
            final_dformat = "-%Y%m%d%H";
            strncpy(dext_pattern, "-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]",
                    sizeof(dext_pattern));
        } else {
            /* The default dateformat and glob pattern */
            final_dformat = "-%Y%m%d";
            strncpy(dext_pattern, "-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]",
                    sizeof(dext_pattern));
        }
        dext_pattern[PATTERN_LEN - 1] = '\0';
    }

    ret = strftime(dext_str, sizeof(dext_str), final_dformat, &now);
    if (ret == 0) {
        message(MESS_ERROR, "failed to apply date format '%s'\n", final_dformat);
        return 1;
    }

    message(MESS_DEBUG, "dateext suffix '%s'\n", dext_str);
    message(MESS_DEBUG, "glob pattern '%s'\n", dext_pattern);

    if (setSecCtxByName(log->files[logNum], log, &prev_context) != 0) {
        /* error msg already printed */
        return 1;
    }

    /* First compress the previous log when necessary */
    if ((log->flags & LOG_FLAG_COMPRESS) &&
            (log->flags & LOG_FLAG_DELAYCOMPRESS)) {
        if (log->flags & LOG_FLAG_DATEEXT) {
            /* glob for uncompressed files with our pattern */
            if (asprintf(&glob_pattern, "%s/%s%s%s", rotNames->dirName,
                         rotNames->baseName, dext_pattern, fileext) < 0) {
                message_OOM();
                return 1;
            }
            rc = glob(glob_pattern, 0, globerr, &globResult);
            if (!rc && globResult.gl_pathc > 0) {
                size_t glob_count;
                sortGlobResult(&globResult, strlen(rotNames->dirName) + 1 + strlen(rotNames->baseName), dformat);
                for (glob_count = 0; glob_count < globResult.gl_pathc && !hasErrors; glob_count++) {
                    struct stat sbprev;
                    const char *oldName = globResult.gl_pathv[glob_count];

                    if (stat(oldName, &sbprev)) {
                        if (errno == ENOENT)
                            message(MESS_DEBUG, "previous log %s does not exist\n", oldName);
                        else
                            message(MESS_ERROR, "cannot stat %s: %s\n", oldName, strerror(errno));
                    } else {
                        hasErrors = compressLogFile(oldName, log, &sbprev);
                    }
                }
            } else {
                message(MESS_DEBUG,
                        "glob finding logs to compress failed\n");
            }
            globfree(&globResult);
            free(glob_pattern);
        } else {
            struct stat sbprev;
            char *oldName;
            if (asprintf(&oldName, "%s/%s.%d%s", rotNames->dirName,
                         rotNames->baseName, log->logStart, fileext) < 0) {
                message_OOM();
                return 1;
            }
            if (stat(oldName, &sbprev)) {
                if (errno == ENOENT)
                    message(MESS_DEBUG, "previous log %s does not exist\n", oldName);
                else
                    message(MESS_ERROR, "cannot stat %s: %s\n", oldName, strerror(errno));
            } else {
                hasErrors = compressLogFile(oldName, log, &sbprev);
            }
            free(oldName);
        }
    }

    if (log->flags & LOG_FLAG_DATEEXT) {
        /* glob for compressed files with our pattern
         * and compress ext */
        if (asprintf(&glob_pattern, "%s/%s%s%s%s", rotNames->dirName,
                     rotNames->baseName, dext_pattern, fileext, compext) < 0) {
            message_OOM();
            return 1;
        }
        rc = glob(glob_pattern, 0, globerr, &globResult);
        if (!rc) {
            /* search for files to drop, if we find one remember it,
             * if we find another one mail and remove the first and
             * remember the second and so on */
            struct stat fst_buf;
            size_t glob_count, mail_out = (size_t)-1;
            /* Remove the first (n - rotateCount) matches no real rotation
             * needed, since the files have the date in their name. Note that
             * (size_t)-1 == SIZE_T_MAX in rotateCount */
            sortGlobResult(&globResult, strlen(rotNames->dirName) + 1 + strlen(rotNames->baseName), dformat);
            for (glob_count = 0; glob_count < globResult.gl_pathc; glob_count++) {
                if (!stat((globResult.gl_pathv)[glob_count], &fst_buf)) {
                    if (((globResult.gl_pathc >= (size_t)rotateCount) && (glob_count <= (globResult.gl_pathc - (size_t)rotateCount)))
                            || ((log->rotateAge > 0)
                                &&
                                (((intmax_t)difftime(nowSecs, fst_buf.st_mtime) / DAY_SECONDS)
                                 > log->rotateAge))) {
                        if (mail_out != (size_t)-1) {
                            char *mailFilename =
                                (globResult.gl_pathv)[mail_out];
                            if (!hasErrors && log->logAddress)
                                hasErrors = mailLogWrapper(mailFilename, mailCommand,
                                                           logNum, log);
                            if (!hasErrors) {
                                message(MESS_DEBUG, "removing %s\n", mailFilename);
                                hasErrors = removeLogFile(mailFilename, log);
                            }
                        }
                        mail_out = glob_count;
                    }
                }
            }
            if (mail_out != (size_t)-1) {
                /* oldName is oldest Backup found (for unlink later) */
                const char *oldName = globResult.gl_pathv[mail_out];
                rotNames->disposeName = strdup(oldName);
                if (rotNames->disposeName == NULL) {
                    message_OOM();
                    globfree(&globResult);
                    free(glob_pattern);
                    return 1;
                }
            } else {
                free(rotNames->disposeName);
                rotNames->disposeName = NULL;
            }
        } else {
            message(MESS_DEBUG, "glob finding old rotated logs failed\n");
            free(rotNames->disposeName);
            rotNames->disposeName = NULL;
        }
        /* firstRotated is most recently created/compressed rotated log */
        if (asprintf(&rotNames->firstRotated, "%s/%s%s%s%s",
                rotNames->dirName, rotNames->baseName, dext_str, fileext,
                (log->flags & LOG_FLAG_DELAYCOMPRESS) ? "" : compext) < 0) {
            message_OOM();
            rotNames->firstRotated = NULL;
            globfree(&globResult);
            free(glob_pattern);
            return 1;
        }
        globfree(&globResult);
        free(glob_pattern);
    } else {
        int i;
        char *newName = NULL;
        char *oldName;

        if (rotateCount == -1) {
            rotateCount = findLastRotated(rotNames, fileext, compext);
            if (rotateCount < 0) {
                message(MESS_ERROR, "could not find last rotated file: %s/%s.*%s%s\n",
                        rotNames->dirName, rotNames->baseName, fileext, compext);
                return 1;
            }
        }

        if (asprintf(&oldName, "%s/%s.%d%s%s", rotNames->dirName,
                     rotNames->baseName, log->logStart + rotateCount, fileext,
                     compext) < 0) {
            message_OOM();
            return 1;
        }

        if (log->rotateCount != -1) {
            rotNames->disposeName = strdup(oldName);
            if (rotNames->disposeName == NULL) {
                message_OOM();
                free(oldName);
                return 1;
            }
        }

        if (asprintf(&rotNames->firstRotated, "%s/%s.%d%s%s", rotNames->dirName,
                rotNames->baseName, log->logStart, fileext,
                (log->flags & LOG_FLAG_DELAYCOMPRESS) ? "" : compext) < 0) {
            message_OOM();
            free(oldName);
            rotNames->firstRotated = NULL;
            return 1;
        }

        for (i = rotateCount + log->logStart - 1; (i >= log->logStart) && !hasErrors; i--) {
            free(newName);
            newName = oldName;
            if (asprintf(&oldName, "%s/%s.%d%s%s", rotNames->dirName,
                         rotNames->baseName, i, fileext, compext) < 0) {
                message_OOM();
                oldName = NULL;
                break;
            }

            /* remove files hit by maxage */
            if (log->rotateAge) {
                struct stat fst_buf;

                if (stat(oldName, &fst_buf)) {
                    if (errno == ENOENT) {
                        message(MESS_DEBUG, "old log %s does not exist\n",
                                oldName);
                    } else {
                        message(MESS_ERROR, "cannot stat %s: %s\n", oldName,
                                strerror(errno));
                        hasErrors = 1;
                    }

                    continue;
                }

                if (((intmax_t)difftime(nowSecs, fst_buf.st_mtime) / DAY_SECONDS) > log->rotateAge) {
                    if (!hasErrors && log->logAddress)
                        hasErrors = mailLogWrapper(oldName, mailCommand,
                                                   logNum, log);
                    if (!hasErrors)
                        hasErrors = removeLogFile(oldName, log);

                    continue;
                }
            }

            message(MESS_DEBUG,
                    "renaming %s to %s (rotatecount %d, logstart %d, i %d), \n",
                    oldName, newName, rotateCount, log->logStart, i);

            if (!debug && rename(oldName, newName)) {
                if (errno == ENOENT) {
                    message(MESS_DEBUG, "old log %s does not exist\n",
                            oldName);
                } else {
                    message(MESS_ERROR, "error renaming %s to %s: %s\n",
                            oldName, newName, strerror(errno));
                    hasErrors = 1;
                }
            }
        }
        free(newName);
        free(oldName);
    } /* !LOG_FLAG_DATEEXT */

    if (log->flags & LOG_FLAG_DATEEXT) {
        char *destFile;
        struct stat fst_buf;

        if (asprintf(&(rotNames->finalName), "%s/%s%s%s", rotNames->dirName,
                     rotNames->baseName, dext_str, fileext) < 0) {
            message_OOM();
            rotNames->finalName = NULL;
            return 1;
        }
        if (asprintf(&destFile, "%s%s", rotNames->finalName, compext) < 0) {
            message_OOM();
            return 1;
        }
        if (!stat(destFile, &fst_buf)) {
            message(MESS_ERROR,
                    "destination %s already exists, skipping rotation\n",
                    rotNames->firstRotated);
            hasErrors = 1;
        }
        free(destFile);
    } else {
        /* note: the gzip extension is *not* used here! */
        if (asprintf(&(rotNames->finalName), "%s/%s.%d%s", rotNames->dirName,
                     rotNames->baseName, log->logStart, fileext) < 0) {
            message_OOM();
            rotNames->finalName = NULL;
        }
    }

    /* if the last rotation doesn't exist, that's okay */
    if (rotNames->disposeName && access(rotNames->disposeName, F_OK)) {
        message(MESS_DEBUG,
                "log %s doesn't exist -- won't try to dispose of it\n",
                rotNames->disposeName);
        free(rotNames->disposeName);
        rotNames->disposeName = NULL;
    }

    return hasErrors;
}

static int rotateSingleLog(const struct logInfo *log, unsigned logNum,
                           struct logState *state, struct logNames *rotNames)
{
    int hasErrors = 0;
    struct stat sb;
    char *savedContext = NULL;

    if (!state->doRotate)
        return 0;

    if (!hasErrors) {

        if (!(log->flags & (LOG_FLAG_COPYTRUNCATE | LOG_FLAG_COPY))) {
            if (setSecCtxByName(log->files[logNum], log, &savedContext) != 0) {
                /* error msg already printed */
                return 1;
            }
#ifdef WITH_ACL
            if ((prev_acl = acl_get_file(log->files[logNum], ACL_TYPE_ACCESS)) == NULL) {
                if (is_acl_well_supported(errno)) {
                    message(MESS_ERROR, "getting file ACL %s: %s\n",
                            log->files[logNum], strerror(errno));
                    hasErrors = 1;
                }
            }
#endif /* WITH_ACL */
            if (log->flags & LOG_FLAG_TMPFILENAME) {
                char *tmpFilename;

                if (asprintf(&tmpFilename, "%s%s", log->files[logNum], ".tmp") < 0) {
                    message_OOM();
                    restoreSecCtx(&savedContext);
                    return 1;
                }

                message(MESS_DEBUG, "renaming %s to %s\n", log->files[logNum],
                        tmpFilename);
                if (!debug && !hasErrors && rename(log->files[logNum], tmpFilename)) {
                    message(MESS_ERROR, "failed to rename %s to %s: %s\n",
                            log->files[logNum], tmpFilename,
                            strerror(errno));
                    hasErrors = 1;
                }

                free(tmpFilename);
            }
            else {
                message(MESS_DEBUG, "renaming %s to %s\n", log->files[logNum],
                        rotNames->finalName);
                if (!debug && !hasErrors &&
                        rename(log->files[logNum], rotNames->finalName)) {
                    message(MESS_ERROR, "failed to rename %s to %s: %s\n",
                            log->files[logNum], rotNames->finalName,
                            strerror(errno));
                    hasErrors = 1;
                }
            }

            if (!log->rotateCount) {
                const char *ext = "";
                if (log->compress_ext
                        && (log->flags & LOG_FLAG_COMPRESS)
                        && !(log->flags & LOG_FLAG_DELAYCOMPRESS))
                    ext = log->compress_ext;

                free(rotNames->disposeName);
                if (asprintf(&rotNames->disposeName, "%s%s", rotNames->finalName, ext) < 0) {
                    message_OOM();
                    rotNames->disposeName = NULL;
                    return 1;
                }

                message(MESS_DEBUG, "disposeName will be %s\n", rotNames->disposeName);
            }
        }

        if (!hasErrors && (log->flags & LOG_FLAG_CREATE) &&
                !(log->flags & (LOG_FLAG_COPYTRUNCATE | LOG_FLAG_COPY))) {
            int have_create_mode = 0;

            if (log->createUid == NO_UID)
                sb.st_uid = state->sb.st_uid;
            else
                sb.st_uid = log->createUid;

            if (log->createGid == NO_GID)
                sb.st_gid = state->sb.st_gid;
            else
                sb.st_gid = log->createGid;
            if (log->createMode == NO_MODE)
                sb.st_mode = state->sb.st_mode & 0777;
            else {
                sb.st_mode = log->createMode;
                have_create_mode = 1;
            }

            message(MESS_DEBUG, "creating new %s mode = 0%o uid = %d "
                    "gid = %d\n", log->files[logNum], (unsigned int) sb.st_mode,
                    (int) sb.st_uid, (int) sb.st_gid);

            if (!debug) {
                if (!hasErrors) {
                    int fd = createOutputFile(log->files[logNum], O_RDWR,
                            &sb, prev_acl, have_create_mode);
#ifdef WITH_ACL
                    if (prev_acl) {
                        acl_free(prev_acl);
                        prev_acl = NULL;
                    }
#endif
                    if (fd < 0)
                        hasErrors = 1;
                    else {
                        close(fd);
                    }
                }
            }
        }

        restoreSecCtx(&savedContext);

        if (!hasErrors
                && (log->flags & (LOG_FLAG_COPYTRUNCATE | LOG_FLAG_COPY))
                && !(log->flags & LOG_FLAG_TMPFILENAME)) {
            hasErrors = copyTruncate(log->files[logNum], rotNames->finalName,
                                     &state->sb, log,
                                     !log->rotateCount && !log->logAddress);
        }

#ifdef WITH_ACL
        if (prev_acl) {
            acl_free(prev_acl);
            prev_acl = NULL;
        }
#endif /* WITH_ACL */

    }
    return hasErrors;
}

static int postrotateSingleLog(const struct logInfo *log, unsigned logNum,
                               const struct logState *state,
                               const struct logNames *rotNames)
{
    int hasErrors = 0;

    if (!state->doRotate) {
        return 0;
    }

    if (!hasErrors && (log->flags & LOG_FLAG_TMPFILENAME)) {
        char *tmpFilename;
        if (asprintf(&tmpFilename, "%s%s", log->files[logNum], ".tmp") < 0) {
            message_OOM();
            return 1;
        }
        hasErrors = copyTruncate(tmpFilename, rotNames->finalName,
                                 &state->sb, log, /* skip_copy */ 0);
        message(MESS_DEBUG, "removing tmp log %s\n", tmpFilename);
        if (!debug && !hasErrors) {
            unlink(tmpFilename);
        }
        free(tmpFilename);
    }

    if (!hasErrors && (log->flags & LOG_FLAG_COMPRESS) &&
            !(log->flags & LOG_FLAG_DELAYCOMPRESS)) {
        /* whether copying was skipped in rotateSingleLog() -> copyTruncate() */
        int skipped_copy = (log->flags & (LOG_FLAG_COPYTRUNCATE | LOG_FLAG_COPY)) &&
                           !(log->flags & LOG_FLAG_TMPFILENAME) &&
                           !log->rotateCount &&
                           !log->logAddress;

        if (!skipped_copy)
            hasErrors = compressLogFile(rotNames->finalName, log, &state->sb);
    }

    if (!hasErrors && log->logAddress) {
        const char *mailFilename;

        if (log->flags & LOG_FLAG_MAILFIRST)
            mailFilename = rotNames->firstRotated;
        else
            mailFilename = rotNames->disposeName;

        if (mailFilename)
            hasErrors = mailLogWrapper(mailFilename, mailCommand, logNum, log);
    }

    if (!hasErrors && rotNames->disposeName)
        hasErrors = removeLogFile(rotNames->disposeName, log);

    restoreSecCtx(&prev_context);
    return hasErrors;
}

static int rotateLogSet(const struct logInfo *log, int force)
{
    unsigned i, j;
    int hasErrors = 0;
    int *logHasErrors;
    int numRotated = 0;
    struct logState **state;
    struct logNames **rotNames;

    message(MESS_DEBUG, "\nrotating pattern: %s ", log->pattern);
    if (force) {
        message(MESS_DEBUG, "forced from command line ");
    }
    else {
        switch (log->criterium) {
            case ROT_HOURLY:
                message(MESS_DEBUG, "hourly ");
                break;
            case ROT_DAYS:
                message(MESS_DEBUG, "after %jd days ", (intmax_t)log->threshold);
                break;
            case ROT_WEEKLY:
                message(MESS_DEBUG, "weekly ");
                break;
            case ROT_MONTHLY:
                message(MESS_DEBUG, "monthly ");
                break;
            case ROT_YEARLY:
                message(MESS_DEBUG, "yearly ");
                break;
            case ROT_SIZE:
                message(MESS_DEBUG, "%jd bytes ", (intmax_t)log->threshold);
                break;
            default:
                message(MESS_FATAL, "rotateLogSet() does not have case for: %u ",
                        (unsigned) log->criterium);
        }
    }

    if (log->oldDir)
        message(MESS_DEBUG, "olddir is %s, ", log->oldDir);

    if (log->flags & LOG_FLAG_IFEMPTY)
        message(MESS_DEBUG, "empty log files are rotated, ");
    else
        message(MESS_DEBUG, "empty log files are not rotated, ");

    if (log->minsize)
        message(MESS_DEBUG, "only log files >= %jd bytes are rotated, ", (intmax_t)log->minsize);

    if (log->maxsize)
        message(MESS_DEBUG, "log files >= %jd are rotated earlier, ", (intmax_t)log->maxsize);

    if (log->rotateMinAge)
        message(MESS_DEBUG, "only log files older than %d days are rotated, ", log->rotateMinAge);

    if ((log->rotateCount == -1) && (log->rotateAge == 0))
        message(MESS_DEBUG, "old logs are kept forever\n");
    else {
        if (log->logAddress)
            message(MESS_DEBUG, "old logs mailed to %s, ", log->logAddress);

        if (log->rotateCount == 0)
            message(MESS_DEBUG, "no old logs will be kept\n");
        else {
            if (log->rotateCount == -1)
                message(MESS_DEBUG, "(unlimited rotations), ");
            else
                message(MESS_DEBUG, "(%d rotations), ", log->rotateCount);

            message(MESS_DEBUG, "old logs are removed");

            if (log->rotateAge > 0)
                message(MESS_DEBUG, " after %d days", log->rotateAge);

            message(MESS_DEBUG, "\n");
        }
    }

    if (log->numFiles == 0) {
        message(MESS_DEBUG, "No logs found. Rotation not needed.\n");
        return 0;
    }

    logHasErrors = calloc(log->numFiles, sizeof(int));
    if (!logHasErrors) {
        message_OOM();
        return 1;
    }

    if (log->flags & LOG_FLAG_SU) {
        if (switch_user(log->suUid, log->suGid) != 0) {
            free(logHasErrors);
            return 1;
        }
    }

    for (i = 0; i < log->numFiles; i++) {
        const struct logState *logState;
        logHasErrors[i] = findNeedRotating(log, i, force);
        hasErrors |= logHasErrors[i];

        /* sure is a lot of findStating going on .. */
        if (((logState = findState(log->files[i]))) && logState->doRotate)
            numRotated++;
    }

    if (log->first) {
        if (!numRotated) {
            message(MESS_DEBUG, "not running first action script, "
                    "since no logs will be rotated\n");
        } else {
            message(MESS_DEBUG, "running first action script\n");
            if (runScript(log, log->pattern, NULL, log->first)) {
                message(MESS_ERROR, "error running first action script "
                        "for %s\n", log->pattern);
                hasErrors = 1;
                if (log->flags & LOG_FLAG_SU) {
                    if (switch_user_back() != 0) {
                        free(logHasErrors);
                        return 1;
                    }
                }
                /* finish early, firstaction failed, affects all logs in set */
                free(logHasErrors);
                return hasErrors;
            }
        }
    }

    state = malloc(log->numFiles * sizeof(struct logState *));
    rotNames = malloc(log->numFiles * sizeof(struct logNames *));

    if (state == NULL || rotNames == NULL) {
        message_OOM();
        if (log->flags & LOG_FLAG_SU) {
            switch_user_back();
        }
        free(rotNames);
        free(state);
        free(logHasErrors);
        return 1;
    }

    for (j = 0;
            (!(log->flags & LOG_FLAG_SHAREDSCRIPTS) && j < log->numFiles)
            || ((log->flags & LOG_FLAG_SHAREDSCRIPTS) && j < 1); j++) {

        for (i = j;
                ((log->flags & LOG_FLAG_SHAREDSCRIPTS) && i < log->numFiles)
                || (!(log->flags & LOG_FLAG_SHAREDSCRIPTS) && i == j); i++) {
            state[i] = findState(log->files[i]);
            if (!state[i])
                logHasErrors[i] = 1;

            rotNames[i] = malloc(sizeof(struct logNames));
            if (rotNames[i] == NULL) {
                message_OOM();
                if (log->flags & LOG_FLAG_SU) {
                    switch_user_back();
                }
                free(rotNames);
                free(state);
                free(logHasErrors);
                return 1;
            }
            memset(rotNames[i], 0, sizeof(struct logNames));
        }

        if (log->pre
                && (!(
                        (!(log->flags & LOG_FLAG_SHAREDSCRIPTS) && (logHasErrors[j] || !state[j]->doRotate))
                        || (hasErrors && (log->flags & LOG_FLAG_SHAREDSCRIPTS))
                     ))
           ) {
            if (!numRotated) {
                message(MESS_DEBUG, "not running prerotate script, "
                        "since no logs will be rotated\n");
            } else {
                message(MESS_DEBUG, "running prerotate script\n");
                if (runScript(log, (log->flags & LOG_FLAG_SHAREDSCRIPTS) ? log->pattern : log->files[j], NULL, log->pre)) {
                    if (log->flags & LOG_FLAG_SHAREDSCRIPTS)
                        message(MESS_ERROR,
                                "error running shared prerotate script "
                                "for '%s'\n", log->pattern);
                    else {
                        message(MESS_ERROR,
                                "error running non-shared prerotate script "
                                "for %s of '%s'\n", log->files[j], log->pattern);
                    }
                    logHasErrors[j] = 1;
                    hasErrors = 1;
                }
            }
        }

        for (i = j;
             ((log->flags & LOG_FLAG_SHAREDSCRIPTS) && i < log->numFiles)
             || (!(log->flags & LOG_FLAG_SHAREDSCRIPTS) && i == j); i++) {
            if (! ( (logHasErrors[i] && !(log->flags & LOG_FLAG_SHAREDSCRIPTS))
                    || (hasErrors && (log->flags & LOG_FLAG_SHAREDSCRIPTS)) ) ) {
                logHasErrors[i] |= prerotateSingleLog(log, i, state[i], rotNames[i]);
                hasErrors |= logHasErrors[i];
            }
        }

        for (i = j;
                ((log->flags & LOG_FLAG_SHAREDSCRIPTS) && i < log->numFiles)
                || (!(log->flags & LOG_FLAG_SHAREDSCRIPTS) && i == j); i++) {
            if (! ( (logHasErrors[i] && !(log->flags & LOG_FLAG_SHAREDSCRIPTS))
                        || (hasErrors && (log->flags & LOG_FLAG_SHAREDSCRIPTS)) ) ) {
                logHasErrors[i] |=
                    rotateSingleLog(log, i, state[i], rotNames[i]);
                hasErrors |= logHasErrors[i];
            }
        }

        if (log->post
                && (!(
                        (!(log->flags & LOG_FLAG_SHAREDSCRIPTS) && (logHasErrors[j] || !state[j]->doRotate))
                        || (hasErrors && (log->flags & LOG_FLAG_SHAREDSCRIPTS))
                     ))
           ) {
            if (!numRotated) {
                message(MESS_DEBUG, "not running postrotate script, "
                        "since no logs were rotated\n");
            } else {
                const char *logfn = (log->flags & LOG_FLAG_SHAREDSCRIPTS) ? log->pattern : log->files[j];

                /* It only makes sense to pass in a final rotated filename if scripts are not shared */
                const char *logrotfn = (log->flags & LOG_FLAG_SHAREDSCRIPTS) ? NULL : rotNames[j]->finalName;

                message(MESS_DEBUG, "running postrotate script\n");
                if (runScript(log, logfn, logrotfn, log->post)) {
                    if (log->flags & LOG_FLAG_SHAREDSCRIPTS)
                        message(MESS_ERROR,
                                "error running shared postrotate script "
                                "for '%s'\n", log->pattern);
                    else {
                        message(MESS_ERROR,
                                "error running non-shared postrotate script "
                                "for %s of '%s'\n", log->files[j], log->pattern);
                    }
                    logHasErrors[j] = 1;
                    hasErrors = 1;
                }
            }
        }

        for (i = j;
                ((log->flags & LOG_FLAG_SHAREDSCRIPTS) && i < log->numFiles)
                || (!(log->flags & LOG_FLAG_SHAREDSCRIPTS) && i == j); i++) {
            if (! ( (logHasErrors[i] && !(log->flags & LOG_FLAG_SHAREDSCRIPTS))
                        || (hasErrors && (log->flags & LOG_FLAG_SHAREDSCRIPTS)) ) ) {
                logHasErrors[i] |=
                    postrotateSingleLog(log, i, state[i], rotNames[i]);
                hasErrors |= logHasErrors[i];
            }
        }

    }

    for (i = 0; i < log->numFiles; i++) {
        free(rotNames[i]->firstRotated);
        free(rotNames[i]->disposeName);
        free(rotNames[i]->finalName);
        free(rotNames[i]->dirName);
        free(rotNames[i]->baseName);
        free(rotNames[i]);
    }
    free(rotNames);
    free(state);

    if (log->last) {
        if (!numRotated) {
            message(MESS_DEBUG, "not running last action script, "
                    "since no logs will be rotated\n");
        } else {
            message(MESS_DEBUG, "running last action script\n");
            if (runScript(log, log->pattern, NULL, log->last)) {
                message(MESS_ERROR, "error running last action script "
                        "for %s\n", log->pattern);
                hasErrors = 1;
            }
        }
    }

    if (log->flags & LOG_FLAG_SU) {
        if (switch_user_back() != 0) {
            free(logHasErrors);
            return 1;
        }
    }
    free(logHasErrors);
    return hasErrors;
}

static int writeState(const char *stateFilename)
{
    struct logState *p;
    FILE *f;
    char *chptr;
    unsigned int i = 0;
    int error = 0;
    int bytes = 0;
    int fdcurr;
    int fdsave;
    struct stat sb;
    char *tmpFilename = NULL;
    time_t last_time;
    char *prevCtx;
    int force_mode = 0;

    if (!strcmp(stateFilename, "/dev/null"))
        /* explicitly asked not to write the state file */
        return 0;

    fdcurr = open(stateFilename, O_RDONLY);
    if (fdcurr == -1) {
        /* the statefile should exist, lockState() already created an empty
         * state file in case it did not exist initially */
        message(MESS_ERROR, "error opening state file %s: %s\n",
                stateFilename, strerror(errno));
        return 1;
    }

    if (fstat(fdcurr, &sb) == -1) {
        message(MESS_ERROR, "error stating %s: %s\n", stateFilename, strerror(errno));
        close(fdcurr);
        return 1;
    }

    if (!S_ISREG(sb.st_mode)) {
        message(MESS_ERROR, "not writing state to %s because it is not a regular file\n", stateFilename);
        close(fdcurr);
        return 1;
    }

    tmpFilename = malloc(strlen(stateFilename) + 5 );
    if (tmpFilename == NULL) {
        message_OOM();
        close(fdcurr);
        return 1;
    }
    strcpy(tmpFilename, stateFilename);
    strcat(tmpFilename, ".tmp");
    /* Remove possible tmp state file from previous run */
    error = unlink(tmpFilename);
    if (error == -1 && errno != ENOENT) {
        message(MESS_ERROR, "error removing old temporary state file %s: %s\n",
                tmpFilename, strerror(errno));
        free(tmpFilename);
        close(fdcurr);
        return 1;
    }
    error = 0;

    /* get attributes, to assign them to the new state file */

    if (setSecCtx(fdcurr, stateFilename, &prevCtx) != 0) {
        /* error msg already printed */
        free(tmpFilename);
        close(fdcurr);
        return 1;
    }

#ifdef WITH_ACL
    if ((prev_acl = acl_get_fd(fdcurr)) == NULL) {
        if (is_acl_well_supported(errno)) {
            message(MESS_ERROR, "getting file ACL %s: %s\n",
                    stateFilename, strerror(errno));
            restoreSecCtx(&prevCtx);
            free(tmpFilename);
            close(fdcurr);
            return 1;
        }
    }
#endif

    close(fdcurr);

    if (sb.st_mode & (mode_t)S_IROTH) {
        /* drop world-readable flag to prevent others from locking */
        sb.st_mode &= ~(mode_t)S_IROTH;
        force_mode = 1;
    }

    fdsave = createOutputFile(tmpFilename, O_RDWR, &sb, prev_acl, force_mode);
#ifdef WITH_ACL
    if (prev_acl) {
        acl_free(prev_acl);
        prev_acl = NULL;
    }
#endif
    restoreSecCtx(&prevCtx);

    if (fdsave < 0) {
        free(tmpFilename);
        return 1;
    }

    f = fdopen(fdsave, "w");
    if (!f) {
        message(MESS_ERROR, "error creating temp state file %s: %s\n",
                tmpFilename, strerror(errno));
        free(tmpFilename);
        return 1;
    }

    bytes =  fprintf(f, "logrotate state -- version 2\n");
    if (bytes < 0)
        error = bytes;

    /*
     * Time in seconds it takes earth to go around sun.  The value is
     * astronomical measurement (solar year) rather than something derived from
     * a convention (calendar year).
     */
#define SECONDS_IN_YEAR 31556926

    for (i = 0; i < hashSize && error == 0; i++) {
        for (p = states[i]->head.lh_first; p != NULL && error == 0;
                p = p->list.le_next) {

            /* Skip states which are not used for more than a year. */
            last_time = mktime(&p->lastRotated);
            if (!p->isUsed && difftime(nowSecs, last_time) > SECONDS_IN_YEAR) {
                message(MESS_DEBUG, "Removing %s from state file, "
                        "because it does not exist and has not been rotated for one year\n",
                        p->fn);
                continue;
            }

            error = fputc('"', f) == EOF;
            for (chptr = p->fn; *chptr && error == 0; chptr++) {
                switch (*chptr) {
                    case '"':
                    case '\\':
                        error = fputc('\\', f) == EOF;
                        break;
                    case '\n':
                        error = fputc('\\', f) == EOF;
                        if (error == 0) {
                            error = fputc('n', f) == EOF;
                        }
                        continue;
                    default:
                        break;
                }
                if (error == 0 && fputc(*chptr, f) == EOF) {
                    error = 1;
                }
            }

            if (error == 0 && fputc('"', f) == EOF)
                error = 1;

            if (error == 0) {
                bytes = fprintf(f, " %d-%d-%d-%d:%d:%d\n",
                                p->lastRotated.tm_year + 1900,
                                p->lastRotated.tm_mon + 1,
                                p->lastRotated.tm_mday,
                                p->lastRotated.tm_hour,
                                p->lastRotated.tm_min,
                                p->lastRotated.tm_sec);
                if (bytes < 0)
                    error = bytes;
            }
        }
    }

    if (error == 0)
        error = fflush(f);

    if (error == 0)
        error = fsync(fdsave);

    if (error == 0)
        error = fclose(f);
    else
        fclose(f);

    if (error == 0) {
        if (rename(tmpFilename, stateFilename)) {
            message(MESS_ERROR, "error renaming temp state file %s to %s: %s\n",
                    tmpFilename, stateFilename, strerror(errno));
            unlink(tmpFilename);
            error = 1;
        }
    }
    else {
        if (errno)
            message(MESS_ERROR, "error creating temp state file %s: %s\n",
                    tmpFilename, strerror(errno));
        else
            message(MESS_ERROR, "error creating temp state file %s%s\n",
                    tmpFilename, error == ENOMEM ?
                    ": Insufficient storage space is available." : "" );
        unlink(tmpFilename);
    }
    free(tmpFilename);
    return error;
}

static int readState(const char *stateFilename)
{
    FILE *f;
    char buf[STATEFILE_BUFFER_SIZE];
    int line = 0;
    int fd;
    struct stat f_stat;
    int rc = 0;

    message(MESS_DEBUG, "Reading state from file: %s\n", stateFilename);

    fd = open(stateFilename, O_RDONLY);
    if (fd == -1) {
        /* treat non-openable file as an empty file for allocateHash() */
        f_stat.st_size = 0;

        /* Do not return until the hash table is allocated.
         * In debug mode the state file might not exist,
         * cause lockState() is not called */
        if (!debug) {
            message(MESS_ERROR, "error opening state file %s: %s\n",
                    stateFilename, strerror(errno));
            rc = 1;
        } else if (errno == ENOENT) {
            message(MESS_DEBUG, "state file %s does not exist\n",
                    stateFilename);
        } else {
           message(MESS_ERROR, "error opening state file %s; assuming empty state: %s\n",
                   stateFilename, strerror(errno));
        }
    } else {
        if (fstat(fd, &f_stat) == -1) {
            /* treat non-statable file as an empty file for allocateHash() */
            f_stat.st_size = 0;

            message(MESS_ERROR, "error stat()ing state file %s: %s\n",
                    stateFilename, strerror(errno));

            /* do not return until the hash table is allocated */
            rc = 1;
        }
    }

    /* Try to estimate how many state entries we have in the state file.
     * We expect single entry to have around 80 characters (Of course this is
     * just an estimation). During the testing I've found out that 200 entries
     * per single hash entry gives good mem/performance ratio. */
    if (allocateHash((size_t)f_stat.st_size / 80 / 200))
        rc = 1;

    if (rc || (f_stat.st_size == 0)) {
        /* error already occurred, or we have no state file to read from */
        if (fd != -1)
            close(fd);
        return rc;
    }

    f = fdopen(fd, "r");
    if (!f) {
        message(MESS_ERROR, "error opening state file %s: %s\n",
                stateFilename, strerror(errno));
        close(fd);
        return 1;
    }

    if (!fgets(buf, sizeof(buf) - 1, f)) {
        message(MESS_ERROR, "error reading top line of %s\n",
                stateFilename);
        fclose(f);
        return 1;
    }

    if (strcmp(buf, "logrotate state -- version 1\n") != 0 &&
            strcmp(buf, "logrotate state -- version 2\n") != 0) {
        fclose(f);
        message(MESS_ERROR, "bad top line in state file %s\n",
                stateFilename);
        return 1;
    }

    line++;

    while (fgets(buf, sizeof(buf) - 1, f)) {
        const size_t i = strlen(buf);
        char *filename;
        int argc;
        const char **argv = NULL;
        int year, month, day, hour, minute, second;
        struct logState *st;
        time_t lr_time;

        line++;
        if (i == 0) {
            message(MESS_ERROR, "line %d not parsable in state file %s\n",
                    line, stateFilename);
            fclose(f);
            return 1;
        }
        if (buf[i - 1] != '\n') {
            message(MESS_ERROR, "line %d too long in state file %s\n",
                    line, stateFilename);
            fclose(f);
            return 1;
        }

        buf[i - 1] = '\0';

        if (i == 1)
            continue;

        year = month = day = hour = minute = second = 0;
        if (poptParseArgvString(buf, &argc, &argv) || (argc != 2) ||
                (sscanf(argv[1], "%d-%d-%d-%d:%d:%d", &year, &month, &day, &hour, &minute, &second) < 3)) {
            message(MESS_ERROR, "bad line %d in state file %s\n",
                    line, stateFilename);
            free(argv);
            fclose(f);
            return 1;
        }

        /* Hack to hide earlier bug */
        if ((year != 1900) && (year < 1970 || year > 2100)) {
            message(MESS_ERROR,
                    "bad year %d for file %s in state file %s\n", year,
                    argv[0], stateFilename);
            free(argv);
            fclose(f);
            return 1;
        }

        if (month < 1 || month > 12) {
            message(MESS_ERROR,
                    "bad month %d for file %s in state file %s\n", month,
                    argv[0], stateFilename);
            free(argv);
            fclose(f);
            return 1;
        }

        /* 0 to hide earlier bug */
        if (day < 0 || day > 31) {
            message(MESS_ERROR,
                    "bad day %d for file %s in state file %s\n", day,
                    argv[0], stateFilename);
            free(argv);
            fclose(f);
            return 1;
        }

        if (hour < 0 || hour > 23) {
            message(MESS_ERROR,
                    "bad hour %d for file %s in state file %s\n", hour,
                    argv[0], stateFilename);
            free(argv);
            fclose(f);
            return 1;
        }

        if (minute < 0 || minute > 59) {
            message(MESS_ERROR,
                    "bad minute %d for file %s in state file %s\n", minute,
                    argv[0], stateFilename);
            free(argv);
            fclose(f);
            return 1;
        }

        if (second < 0 || second > 59) {
            message(MESS_ERROR,
                    "bad second %d for file %s in state file %s\n", second,
                    argv[0], stateFilename);
            free(argv);
            fclose(f);
            return 1;
        }

        year -= 1900;
        month -= 1;

        filename = strdup(argv[0]);
        if (filename == NULL) {
            message_OOM();
            free(argv);
            fclose(f);
            return 1;
        }
        unescape(filename);

        if ((st = findState(filename)) == NULL) {
            free(argv);
            free(filename);
            fclose(f);
            return 1;
        }

        memset(&st->lastRotated, 0, sizeof(st->lastRotated));
        st->lastRotated.tm_year = year;
        st->lastRotated.tm_mon = month;
        st->lastRotated.tm_mday = day;
        st->lastRotated.tm_hour = hour;
        st->lastRotated.tm_min = minute;
        st->lastRotated.tm_sec = second;
        st->lastRotated.tm_isdst = -1;

        /* fill in the rest of the st->lastRotated fields */
        lr_time = mktime(&st->lastRotated);
        localtime_r(&lr_time, &st->lastRotated);

        free(argv);
        free(filename);
    }

    fclose(f);
    return 0;
}

static int lockState(const char *stateFilename, int skip_state_lock, int wait_for_state_lock)
{
    int lockFd;
    int lockFlags;
    struct stat sb;

    if (!strcmp(stateFilename, "/dev/null")) {
        return 0;
    }

    lockFd = open(stateFilename, O_RDWR | O_CLOEXEC);
    if (lockFd == -1) {
        if (errno == ENOENT) {
            message(MESS_DEBUG, "Creating stub state file: %s\n",
                    stateFilename);

            /* create a stub state file with mode 0640 */
            lockFd = open(stateFilename, O_CREAT | O_EXCL | O_WRONLY,
                          S_IWUSR | S_IRUSR | S_IRGRP);
            if (lockFd == -1) {
                message(MESS_ERROR, "error creating stub state file %s: %s\n",
                        stateFilename, strerror(errno));
                return 1;
            }
        } else {
            message(MESS_ERROR, "error opening state file %s: %s\n",
                    stateFilename, strerror(errno));
            return 1;
        }
    }

    if (skip_state_lock) {
        message(MESS_DEBUG, "Skip locking state file %s\n",
                stateFilename);
        close(lockFd);
        return 0;
    }

    if (fstat(lockFd, &sb) == -1) {
        message(MESS_ERROR, "error stat()ing state file %s: %s\n",
                stateFilename, strerror(errno));
        close(lockFd);
        return 1;
    }

    if (sb.st_mode & S_IROTH) {
        message(MESS_WARN, "state file %s is world-readable"
                " and thus can be locked from other unprivileged users."
                " Skipping lock acquisition...\n",
                stateFilename);
        close(lockFd);
        return 0;
    }

    lockFlags = LOCK_EX;
    if (wait_for_state_lock)
        message(MESS_DEBUG, "waiting for lock on state file %s\n", stateFilename);
    else
        lockFlags |= LOCK_NB;

    if (flock(lockFd, lockFlags) == -1) {
        if (errno == EWOULDBLOCK) {
            message(MESS_ERROR, "state file %s is already locked\n"
                    "logrotate does not support parallel execution on the"
                    " same set of logfiles.\n", stateFilename);
        } else {
            message(MESS_ERROR, "error acquiring lock on state file %s: %s\n",
                    stateFilename, strerror(errno));
        }
        close(lockFd);
        return 1;
    }

    message(MESS_DEBUG, "acquired lock on state file %s\n", stateFilename);

    /* keep lockFd open till we terminate */
    return 0;
}

int main(int argc, const char **argv)
{
    int force = 0;
    int skip_state_lock = 0;
    int wait_for_state_lock = 0;
    const char *stateFile = STATEFILE;
    const char *logFile = NULL;
    FILE *logFd = NULL;
    int rc = 0;
    int arg;
    const char **files;
    poptContext optCon;
    const struct logInfo *log;

    const struct poptOption options[] = {
        {"debug", 'd', 0, NULL, 'd',
            "Don't do anything, just test and print debug messages", NULL},
        {"force", 'f', 0, &force, 0, "Force file rotation", NULL},
        {"mail", 'm', POPT_ARG_STRING, &mailCommand, 0,
            "Command to send mail (instead of `" DEFAULT_MAIL_COMMAND "')",
            "command"},
        {"state", 's', POPT_ARG_STRING, &stateFile, 0,
            "Path of state file",
            "statefile"},
        {"skip-state-lock", '\0', POPT_ARG_NONE, &skip_state_lock, 0, "Do not lock the state file", NULL},
        {"wait-for-state-lock", '\0', POPT_ARG_NONE, &wait_for_state_lock, 0, "Wait for lock on the state file", NULL},
        {"verbose", 'v', 0, NULL, 'v', "Display messages during rotation", NULL},
        {"log", 'l', POPT_ARG_STRING, &logFile, 'l', "Log file or 'syslog' to log to syslog",
            "logfile"},
        {"version", '\0', POPT_ARG_NONE, NULL, 'V', "Display version information", NULL},
        POPT_AUTOHELP { NULL, 0, 0, NULL, 0, NULL, NULL }
    };

    logSetLevel(MESS_WARN);
    setlocale (LC_ALL, "");

    optCon = poptGetContext("logrotate", argc, argv, options, 0);
    poptReadDefaultConfig(optCon, 1);
    poptSetOtherOptionHelp(optCon, "[OPTION...] <configfile>");

    while ((arg = poptGetNextOpt(optCon)) >= 0) {
        switch (arg) {
            case 'd':
                debug = 1;
                message(MESS_WARN, "logrotate in debug mode does nothing"
                        " except printing debug messages!  Consider using verbose"
                        " mode (-v) instead if this is not what you want.\n\n");
                /* fallthrough */
            case 'v':
                logSetLevel(MESS_DEBUG);
                break;
            case 'l':
                if (strcmp(logFile, "syslog") == 0) {
                    logToSyslog(1);
                }
                else {
                    logFd = fopen(logFile, "w");
                    if (!logFd) {
                        message(MESS_ERROR, "error opening log file %s: %s\n",
                                logFile, strerror(errno));
                        break;
                    }
                    logSetMessageFile(logFd);
                }
                break;
            case 'V':
                printf("logrotate %s\n", VERSION);
                printf("\n");
                printf("    Default mail command:       %s\n", DEFAULT_MAIL_COMMAND);
                printf("    Default compress command:   %s\n", COMPRESS_COMMAND);
                printf("    Default uncompress command: %s\n", UNCOMPRESS_COMMAND);
                printf("    Default compress extension: %s\n", COMPRESS_EXT);
                printf("    Default state file path:    %s\n", STATEFILE);
#ifdef WITH_ACL
                printf("    ACL support:                yes\n");
#else
                printf("    ACL support:                no\n");
#endif
#ifdef WITH_SELINUX
                printf("    SELinux support:            yes\n");
#else
                printf("    SELinux support:            no\n");
#endif
                poptFreeContext(optCon);
                exit(0);
            default:
                break;
        }
    }

    if (arg < -1) {
        fprintf(stderr, "logrotate: bad argument %s: %s\n",
                poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
                poptStrerror(rc));
        poptFreeContext(optCon);
        return 2;
    }

    files = poptGetArgs(optCon);
    if (!files) {
        fprintf(stderr, "logrotate " VERSION
                " - Copyright (C) 1995-2001 Red Hat, Inc.\n");
        fprintf(stderr,
                "This may be freely redistributed under the terms of "
                "the GNU General Public License\n\n");
        poptPrintUsage(optCon, stderr, 0);
        poptFreeContext(optCon);
        exit(1);
    }

    if (skip_state_lock && wait_for_state_lock) {
        fprintf(stderr, "logrotate: options --skip-state-lock and"
                " --wait-for-state-lock are mutually exclusive\n");
        poptFreeContext(optCon);
        exit(1);
    }

#ifdef WITH_SELINUX
    selinux_enabled = (is_selinux_enabled() > 0);
    selinux_enforce = security_getenforce();
#endif

    TAILQ_INIT(&logs);

    if (readAllConfigPaths(files))
        rc = 1;

    poptFreeContext(optCon);
    nowSecs = time(NULL);
    /* localtime_r(3) is not required to call tzset(3) */
    tzset();

    if (!debug && lockState(stateFile, skip_state_lock, wait_for_state_lock)) {
        exit(3);
    }

    if (readState(stateFile))
        rc = 1;

    message(MESS_DEBUG, "\nHandling %d logs\n", numLogs);

    for (log = logs.tqh_first; log != NULL; log = log->list.tqe_next)
        rc |= rotateLogSet(log, force);

    if (!debug)
        rc |= writeState(stateFile);

    return (rc != 0);
}

/* vim: set et sw=4 ts=4: */