1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654
|
/*****************************************************************************
*
* UTILS.C - Miscellaneous utility functions for Icinga
*
* Copyright (c) 1999-2009 Ethan Galstad (egalstad@nagios.org)
* Copyright (c) 2009-2013 Nagios Core Development Team and Community Contributors
* Copyright (c) 2009-2015 Icinga Development Team (http://www.icinga.org)
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*****************************************************************************/
#include "../include/config.h"
#include "../include/common.h"
#include "../include/objects.h"
#include "../include/statusdata.h"
#include "../include/comments.h"
#include "../include/macros.h"
#include "../include/icinga.h"
#include "../include/broker.h"
#include "../include/nebmods.h"
#include "../include/nebmodules.h"
#ifdef EMBEDDEDPERL
#include "../include/epn_icinga.h"
static PerlInterpreter *my_perl = NULL;
int use_embedded_perl = TRUE;
#endif
/* mutex lock for operations on check_result_list */
pthread_mutex_t check_result_list_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char *config_file;
extern char *log_file;
extern char *command_file;
extern char *temp_file;
extern char *temp_path;
extern char *check_result_path;
extern char *check_result_path;
extern char *lock_file;
extern char *log_archive_path;
extern char *auth_file;
extern char *p1_file;
extern char *nagios_user;
extern char *nagios_group;
extern char *macro_x_names[MACRO_X_COUNT];
extern char *macro_user[MAX_USER_MACROS];
extern customvariablesmember *macro_custom_host_vars;
extern customvariablesmember *macro_custom_service_vars;
extern customvariablesmember *macro_custom_contact_vars;
extern host *macro_host_ptr;
extern hostgroup *macro_hostgroup_ptr;
extern service *macro_service_ptr;
extern servicegroup *macro_servicegroup_ptr;
extern contact *macro_contact_ptr;
extern contactgroup *macro_contactgroup_ptr;
extern char *global_host_event_handler;
extern char *global_service_event_handler;
extern command *global_host_event_handler_ptr;
extern command *global_service_event_handler_ptr;
extern char *ocsp_command;
extern char *ochp_command;
extern command *ocsp_command_ptr;
extern command *ochp_command_ptr;
extern char *illegal_object_chars;
extern char *illegal_output_chars;
extern int use_regexp_matches;
extern int use_true_regexp_matching;
extern int sigshutdown;
extern int sigrestart;
extern char *sigs[35];
extern int caught_signal;
extern int sig_id;
extern int daemon_mode;
extern int daemon_dumps_core;
extern int nagios_pid;
extern int use_daemon_log;
extern int use_syslog;
extern int use_syslog_local_facility;
extern int syslog_local_facility;
extern int log_notifications;
extern int log_service_retries;
extern int log_host_retries;
extern int log_event_handlers;
extern int log_external_commands;
extern int log_passive_checks;
extern unsigned long logging_options;
extern unsigned long syslog_options;
extern int service_check_timeout;
extern int service_check_timeout_state;
extern int host_check_timeout;
extern int event_handler_timeout;
extern int notification_timeout;
extern int ocsp_timeout;
extern int ochp_timeout;
extern int log_initial_states;
extern double sleep_time;
extern int interval_length;
extern int service_inter_check_delay_method;
extern int host_inter_check_delay_method;
extern int service_interleave_factor_method;
extern int max_host_check_spread;
extern int max_service_check_spread;
extern int command_check_interval;
extern int check_reaper_interval;
extern int max_check_reaper_time;
extern int service_freshness_check_interval;
extern int host_freshness_check_interval;
extern int auto_rescheduling_interval;
extern int auto_rescheduling_window;
extern int check_external_commands;
extern int check_orphaned_services;
extern int check_orphaned_hosts;
extern int check_service_freshness;
extern int log_stale_services;
extern int log_stale_hosts;
extern int check_host_freshness;
extern int auto_reschedule_checks;
extern int additional_freshness_latency;
extern int use_aggressive_host_checking;
extern unsigned long cached_host_check_horizon;
extern unsigned long cached_service_check_horizon;
extern int enable_predictive_host_dependency_checks;
extern int enable_predictive_service_dependency_checks;
extern int soft_state_dependencies;
extern int retain_state_information;
extern int retention_update_interval;
extern int use_retained_program_state;
extern int dump_retained_host_service_states_to_neb;
extern int use_retained_scheduling_info;
extern int retention_scheduling_horizon;
extern unsigned long modified_host_process_attributes;
extern unsigned long modified_service_process_attributes;
extern unsigned long retained_host_attribute_mask;
extern unsigned long retained_service_attribute_mask;
extern unsigned long retained_contact_host_attribute_mask;
extern unsigned long retained_contact_service_attribute_mask;
extern unsigned long retained_process_host_attribute_mask;
extern unsigned long retained_process_service_attribute_mask;
extern unsigned long next_comment_id;
extern unsigned long next_downtime_id;
extern unsigned long next_event_id;
extern unsigned long next_notification_id;
extern int log_rotation_method;
extern time_t program_start;
extern time_t last_command_check;
extern time_t last_command_status_update;
extern time_t last_log_rotation;
extern int verify_config;
extern int test_scheduling;
extern check_result check_result_info;
extern int max_parallel_service_checks;
extern int currently_running_service_checks;
extern int enable_notifications;
extern int execute_service_checks;
extern int accept_passive_service_checks;
extern int execute_host_checks;
extern int accept_passive_host_checks;
extern int enable_event_handlers;
extern int obsess_over_services;
extern int obsess_over_hosts;
extern int enable_failure_prediction;
extern int process_performance_data;
extern int translate_passive_host_checks;
extern int passive_host_checks_are_soft;
extern int aggregate_status_updates;
extern int status_update_interval;
extern int time_change_threshold;
extern unsigned long event_broker_options;
extern int process_performance_data;
extern int enable_flap_detection;
extern double low_service_flap_threshold;
extern double high_service_flap_threshold;
extern double low_host_flap_threshold;
extern double high_host_flap_threshold;
extern int use_large_installation_tweaks;
extern int enable_environment_macros;
extern int free_child_process_memory;
extern int child_processes_fork_twice;
extern int enable_embedded_perl;
extern int use_embedded_perl_implicitly;
extern int stalking_event_handlers_for_hosts;
extern int stalking_event_handlers_for_services;
extern int stalking_notifications_for_hosts;
extern int stalking_notifications_for_services;
extern int date_format;
extern int keep_unknown_macros;
extern contact *contact_list;
extern contactgroup *contactgroup_list;
extern host *host_list;
extern hostgroup *hostgroup_list;
extern service *service_list;
extern servicegroup *servicegroup_list;
extern timed_event *event_list_high;
extern timed_event *event_list_low;
extern notification *notification_list;
extern command *command_list;
extern timeperiod *timeperiod_list;
extern int command_file_fd;
extern FILE *command_file_fp;
extern int command_file_created;
#ifdef HAVE_TZNAME
#ifdef CYGWIN
extern char *_tzname[2] __declspec(dllimport);
#else
extern char *tzname[2];
#endif
#endif
extern check_result *check_result_list;
extern unsigned long max_check_result_file_age;
extern dbuf check_result_dbuf;
extern pthread_t worker_threads[TOTAL_WORKER_THREADS];
extern circular_buffer external_command_buffer;
extern circular_buffer check_result_buffer;
extern circular_buffer event_broker_buffer;
extern int external_command_buffer_slots;
extern check_stats check_statistics[MAX_CHECK_STATS_TYPES];
extern char *debug_file;
extern int debug_level;
extern int debug_verbosity;
extern unsigned long max_debug_file_size;
extern unsigned long max_check_result_list_items;
/* from GNU defines errno as a macro, since it's a per-thread variable */
#ifndef errno
extern int errno;
#endif
/******************************************************************/
/****************** REGISTERED FILE DESCRIPTORS *******************/
/******************************************************************/
#define REGISTERED_FD_MAX 16
int registered_fds[REGISTERED_FD_MAX];
pthread_mutex_t registered_fds_lock;
int init_registered_fds(void)
{
int i;
for (i = 0; i < REGISTERED_FD_MAX; i++) {
registered_fds[i] = -1;
}
return pthread_mutex_init(®istered_fds_lock, NULL);
}
int register_fd(int fd)
{
if (pthread_mutex_lock(®istered_fds_lock) != 0)
return -1;
errno = ENOBUFS;
int rc = -1;
int i;
for (i = 0; i < REGISTERED_FD_MAX; i++) {
if (registered_fds[i] > -1) continue;
registered_fds[i] = fd;
rc = 0;
break;
}
pthread_mutex_unlock(®istered_fds_lock);
return rc;
}
int deregister_fd(int fd)
{
if (pthread_mutex_lock(®istered_fds_lock) != 0)
return -1;
errno = ENOENT;
int rc = -1;
int i;
for (i = 0; i < REGISTERED_FD_MAX; i++) {
if (registered_fds[i] != fd) continue;
registered_fds[i] = -1;
rc = 0;
break;
}
pthread_mutex_unlock(®istered_fds_lock);
return rc;
}
int close_registered_fds(void)
{
if (pthread_mutex_lock(®istered_fds_lock) != 0)
return -1;
int i;
for (i = 0; i < REGISTERED_FD_MAX; i++) {
if (registered_fds[i] < 0) continue;
close(registered_fds[i]);
registered_fds[i] = -1;
}
pthread_mutex_unlock(®istered_fds_lock);
return 0;
}
/******************************************************************/
/******************** SYSTEM COMMAND FUNCTIONS ********************/
/******************************************************************/
/* executes a system command - used for notifications, event handlers, etc. */
int my_system_r(icinga_macros *mac, char *cmd, int timeout, int *early_timeout, double *exectime, char **output, int max_output_length) {
pid_t pid = 0;
int status = 0;
int result = 0;
char buffer[MAX_INPUT_BUFFER] = "";
int fd[2];
FILE *fp = NULL;
int bytes_read = 0;
struct timeval start_time, end_time;
dbuf output_dbuf;
int dbuf_chunk = 1024;
int flags;
#ifdef EMBEDDEDPERL
char *temp_buffer = NULL;
char fname[512] = "";
char *args[5] = {"", DO_CLEAN, "", "", NULL };
SV *plugin_hndlr_cr = NULL; /* perl.h holds typedef struct */
STRLEN n_a;
char *perl_output = NULL;
int count;
int use_epn = FALSE;
#ifdef aTHX
dTHX;
#endif
dSP;
#endif
log_debug_info(DEBUGL_FUNCTIONS, 0, "my_system_r()\n");
/* initialize return variables */
if (output != NULL)
*output = NULL;
*early_timeout = FALSE;
*exectime = 0.0;
/* if no command was passed, return with no error */
if (cmd == NULL)
return STATE_OK;
log_debug_info(DEBUGL_COMMANDS, 1, "Running command '%s'...\n", cmd);
#ifdef EMBEDDEDPERL
/* get"filename" component of command */
strncpy(fname, cmd, strcspn(cmd, " "));
fname[strcspn(cmd, " ")] = '\x0';
/* should we use the embedded Perl interpreter to run this script? */
use_epn = file_uses_embedded_perl(fname);
/* if yes, do some initialization */
if (use_epn == TRUE) {
args[0] = fname;
args[2] = "";
if (strchr(cmd, ' ') == NULL)
args[3] = "";
else
args[3] = cmd + strlen(fname) + 1;
/* call our perl interpreter to compile and optionally cache the compiled script. */
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs(sv_2mortal(newSVpv(args[0], 0)));
XPUSHs(sv_2mortal(newSVpv(args[1], 0)));
XPUSHs(sv_2mortal(newSVpv(args[2], 0)));
XPUSHs(sv_2mortal(newSVpv(args[3], 0)));
PUTBACK;
call_pv("Embed::Persistent::eval_file", G_EVAL);
SPAGAIN;
if (SvTRUE(ERRSV)) {
/*
* XXXX need pipe open to send the compilation failure message back to Icinga ?
*/
(void) POPs ;
asprintf(&temp_buffer, "%s", SvPVX(ERRSV));
log_debug_info(DEBUGL_COMMANDS, 0, "Embedded perl failed to compile %s, compile error %s\n", fname, temp_buffer);
logit(NSLOG_RUNTIME_WARNING, TRUE, "%s\n", temp_buffer);
my_free(temp_buffer);
return STATE_UNKNOWN;
} else {
plugin_hndlr_cr = newSVsv(POPs);
log_debug_info(DEBUGL_COMMANDS, 0, "Embedded perl successfully compiled %s and returned plugin handler (Perl subroutine code ref)\n", fname);
PUTBACK ;
FREETMPS ;
LEAVE ;
}
}
#endif
/* create a pipe */
pipe(fd);
/* make the pipe non-blocking */
fcntl(fd[0], F_SETFL, O_NONBLOCK);
fcntl(fd[1], F_SETFL, O_NONBLOCK);
/* get the command start time */
gettimeofday(&start_time, NULL);
#ifdef USE_EVENT_BROKER
/* send data to event broker */
end_time.tv_sec = 0L;
end_time.tv_usec = 0L;
broker_system_command(NEBTYPE_SYSTEM_COMMAND_START, NEBFLAG_NONE, NEBATTR_NONE, start_time, end_time, *exectime, timeout, *early_timeout, result, cmd, NULL, NULL);
#endif
/* fork */
pid = fork();
/* return an error if we couldn't fork */
if (pid == -1) {
logit(NSLOG_RUNTIME_WARNING, TRUE, "Warning: fork() in my_system_r() failed for command \"%s\"\n", cmd);
/* close both ends of the pipe */
close(fd[0]);
close(fd[1]);
return STATE_UNKNOWN;
}
/* execute the command in the child process */
if (pid == 0) {
/* become process group leader */
setpgid(0, 0);
/* set environment variables */
set_all_macro_environment_vars_r(mac, TRUE);
/* ADDED 11/12/07 EG */
/* close external command file and shut down worker thread */
close_command_file();
/* close any file descriptors on behalf of our event brokers */
close_registered_fds();
/* reset signal handling */
reset_sighandler();
/* close pipe for reading */
close(fd[0]);
/* prevent fd from being inherited by child processed */
flags = fcntl(fd[1], F_GETFD, 0);
flags |= FD_CLOEXEC;
fcntl(fd[1], F_SETFD, flags);
/* trap commands that timeout */
signal(SIGALRM, my_system_sighandler);
alarm(timeout);
/******** BEGIN EMBEDDED PERL CODE EXECUTION ********/
#ifdef EMBEDDEDPERL
if (use_epn == TRUE) {
/* execute our previously compiled script - by call_pv("Embed::Persistent::eval_file",..) */
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs(sv_2mortal(newSVpv(args[0], 0)));
XPUSHs(sv_2mortal(newSVpv(args[1], 0)));
XPUSHs(plugin_hndlr_cr);
XPUSHs(sv_2mortal(newSVpv(args[3], 0)));
PUTBACK;
count = call_pv("Embed::Persistent::run_package", G_ARRAY);
/* count is a debug hook. It should always be two (2), because the persistence framework tries to return two (2) args */
SPAGAIN;
perl_output = POPpx ;
strip(perl_output);
strncpy(buffer, (perl_output == NULL) ? "" : perl_output, sizeof(buffer));
buffer[sizeof(buffer)-1] = '\x0';
status = POPi ;
PUTBACK;
FREETMPS;
LEAVE;
log_debug_info(DEBUGL_COMMANDS, 0, "Embedded perl ran command %s with output %d, %s\n", fname, status, buffer);
/* write the output back to the parent process */
write(fd[1], buffer, strlen(buffer) + 1);
/* close pipe for writing */
close(fd[1]);
/* reset the alarm */
alarm(0);
_exit(status);
}
#endif
/******** END EMBEDDED PERL CODE EXECUTION ********/
/* run the command */
fp = (FILE *)popen(cmd, "r");
/* report an error if we couldn't run the command */
if (fp == NULL) {
strncpy(buffer, "(Error: Could not execute command)\n", sizeof(buffer) - 1);
buffer[sizeof(buffer)-1] = '\x0';
/* write the error back to the parent process */
write(fd[1], buffer, strlen(buffer) + 1);
result = STATE_CRITICAL;
} else {
/* write all the lines of output back to the parent process */
while (fgets(buffer, sizeof(buffer) - 1, fp))
write(fd[1], buffer, strlen(buffer));
/* close the command and get termination status */
status = pclose(fp);
/* report an error if we couldn't close the command */
if (status == -1)
result = STATE_CRITICAL;
else {
if (WEXITSTATUS(status) == 0 && WIFSIGNALED(status))
result = 128 + WTERMSIG(status);
result = WEXITSTATUS(status);
}
}
/* close pipe for writing */
close(fd[1]);
/* reset the alarm */
alarm(0);
/* clear environment variables */
set_all_macro_environment_vars_r(mac, FALSE);
#ifndef DONT_USE_MEMORY_PERFORMANCE_TWEAKS
/* free allocated memory */
/* this needs to be done last, so we don't free memory for variables before they're used above */
if (free_child_process_memory == TRUE)
free_memory(mac);
#endif
_exit(result);
}
/* parent waits for child to finish executing command */
else {
/* close pipe for writing */
close(fd[1]);
/* wait for child to exit */
waitpid(pid, &status, 0);
/* get the end time for running the command */
gettimeofday(&end_time, NULL);
/* return execution time in milliseconds */
*exectime = (double)((double)(end_time.tv_sec - start_time.tv_sec) + (double)((end_time.tv_usec - start_time.tv_usec) / 1000) / 1000.0);
if (*exectime < 0.0)
*exectime = 0.0;
/* get the exit code returned from the program */
result = WEXITSTATUS(status);
/* check for possibly missing scripts/binaries/etc */
if (result == 126 || result == 127) {
logit(NSLOG_RUNTIME_WARNING, TRUE, "Warning: Attempting to execute the command \"%s\" resulted in a return code of %d. Make sure the script or binary you are trying to execute actually exists...\n", cmd, result);
}
/* check bounds on the return value */
if (result < -1 || result > 3)
result = STATE_UNKNOWN;
/* initialize dynamic buffer */
dbuf_init(&output_dbuf, dbuf_chunk);
/* Opsera patch to check timeout before attempting to read output via pipe. Originally by Sven Nierlein */
/* if there was a critical return code AND the command time exceeded the timeout thresholds, assume a timeout */
if (result == STATE_CRITICAL && (end_time.tv_sec - start_time.tv_sec) >= timeout) {
/* set the early timeout flag */
*early_timeout = TRUE;
/* try to kill the command that timed out by sending termination signal to child process group */
kill((pid_t)(-pid), SIGTERM);
sleep(1);
kill((pid_t)(-pid), SIGKILL);
}
/* read output if timeout has not occurred */
else {
/* initialize output */
strcpy(buffer, "");
/* try and read the results from the command output (retry if we encountered a signal) */
do {
bytes_read = read(fd[0], buffer, sizeof(buffer) - 1);
/* append data we just read to dynamic buffer */
if (bytes_read > 0) {
buffer[bytes_read] = '\x0';
dbuf_strcat(&output_dbuf, buffer);
}
/* handle errors */
if (bytes_read == -1) {
/* we encountered a recoverable error, so try again */
if (errno == EINTR)
continue;
/* patch by Henning Brauer to prevent CPU hogging */
else if (errno == EAGAIN) {
struct pollfd pfd;
pfd.fd = fd[0];
pfd.events = POLLIN;
poll(&pfd, 1, -1);
continue;
} else
break;
}
/* we're done */
if (bytes_read == 0)
break;
} while (1);
/* cap output length - this isn't necessary, but it keeps runaway plugin output from causing problems */
if (max_output_length > 0 && output_dbuf.used_size > max_output_length)
output_dbuf.buf[max_output_length] = '\x0';
if (output != NULL && output_dbuf.buf)
*output = (char *)strdup(output_dbuf.buf);
}
log_debug_info(DEBUGL_COMMANDS, 1, "Execution time=%.3f sec, early timeout=%d, result=%d, output=%s\n", *exectime, *early_timeout, result, (output_dbuf.buf == NULL) ? "(null)" : output_dbuf.buf);
#ifdef USE_EVENT_BROKER
/* send data to event broker */
broker_system_command(NEBTYPE_SYSTEM_COMMAND_END, NEBFLAG_NONE, NEBATTR_NONE, start_time, end_time, *exectime, timeout, *early_timeout, result, cmd, (output_dbuf.buf == NULL) ? NULL : output_dbuf.buf, NULL);
#endif
/* free memory */
dbuf_free(&output_dbuf);
/* close the pipe for reading */
close(fd[0]);
}
return result;
}
/*
* For API compatibility, we must include a my_system() whose
* signature doesn't include the icinga_macros variable.
* IDOUtils uses this. Possibly other modules as well.
*/
int my_system(char *cmd, int timeout, int *early_timeout, double *exectime, char **output, int max_output_length) {
return my_system_r(get_global_macros(), cmd, timeout, early_timeout, exectime, output, max_output_length);
}
/* given a "raw" command, return the "expanded" or "whole" command line */
int get_raw_command_line_r(icinga_macros *mac, command *cmd_ptr, char *cmd, char **full_command, int macro_options) {
char temp_arg[MAX_COMMAND_BUFFER] = "";
char *arg_buffer = NULL;
register int x = 0;
register int y = 0;
register int arg_index = 0;
register int escaped = FALSE;
log_debug_info(DEBUGL_FUNCTIONS, 0, "get_raw_command_line_r()\n");
/* clear the argv macros */
clear_argv_macros_r(mac);
/* make sure we've got all the requirements */
if (cmd_ptr == NULL || full_command == NULL)
return ERROR;
log_debug_info(DEBUGL_COMMANDS | DEBUGL_CHECKS | DEBUGL_MACROS, 2, "Raw Command Input: %s\n", cmd_ptr->command_line);
/* get the full command line */
*full_command = (char *)strdup((cmd_ptr->command_line == NULL) ? "" : cmd_ptr->command_line);
/* XXX: Crazy indent */
/* get the command arguments */
if (cmd != NULL) {
/* skip the command name (we're about to get the arguments)... */
for (arg_index = 0;; arg_index++) {
if (cmd[arg_index] == '!' || cmd[arg_index] == '\x0')
break;
}
/* get each command argument */
for (x = 0; x < MAX_COMMAND_ARGUMENTS; x++) {
/* we reached the end of the arguments... */
if (cmd[arg_index] == '\x0')
break;
/* get the next argument */
/* can't use strtok(), as that's used in process_macros... */
for (arg_index++, y = 0; y < sizeof(temp_arg) - 1; arg_index++) {
/* backslashes escape */
if (cmd[arg_index] == '\\' && escaped == FALSE) {
escaped = TRUE;
continue;
}
/* end of argument */
if ((cmd[arg_index] == '!' && escaped == FALSE) || cmd[arg_index] == '\x0')
break;
/* normal of escaped char */
temp_arg[y] = cmd[arg_index];
y++;
/* clear escaped flag */
escaped = FALSE;
}
temp_arg[y] = '\x0';
/* ADDED 01/29/04 EG */
/* process any macros we find in the argument */
process_macros_r(mac, temp_arg, &arg_buffer, macro_options);
mac->argv[x] = arg_buffer;
}
}
log_debug_info(DEBUGL_COMMANDS | DEBUGL_CHECKS | DEBUGL_MACROS, 2, "Expanded Command Output: %s\n", *full_command);
return OK;
}
/*
* This function modifies the global macro struct and is thus not
* threadsafe
*/
int get_raw_command_line(command *cmd_ptr, char *cmd, char **full_command, int macro_options) {
icinga_macros *mac;
mac = get_global_macros();
return get_raw_command_line_r(mac, cmd_ptr, cmd, full_command, macro_options);
}
/******************************************************************/
/******************** ENVIRONMENT FUNCTIONS ***********************/
/******************************************************************/
/* sets or unsets an environment variable */
int set_environment_var(char *name, char *value, int set) {
#ifndef HAVE_SETENV
char *env_string = NULL;
#endif
/* we won't mess with null variable names */
if (name == NULL)
return ERROR;
/* set the environment variable */
if (set == TRUE) {
#ifdef HAVE_SETENV
setenv(name, (value == NULL) ? "" : value, 1);
#else
/* needed for Solaris and systems that don't have setenv() */
/* this will leak memory, but in a "controlled" way, since lost memory should be freed when the child process exits */
asprintf(&env_string, "%s=%s", name, (value == NULL) ? "" : value);
if (env_string)
putenv(env_string);
#endif
}
/* clear the variable */
else {
#ifdef HAVE_UNSETENV
unsetenv(name);
#endif
}
return OK;
}
/******************************************************************/
/************************* TIME FUNCTIONS *************************/
/******************************************************************/
/* Checks if the given time is in daylight time saving period */
int is_dlst_time(time_t *time) {
struct tm tm_s;
struct tm *bt = localtime_r(time, &tm_s);
return bt->tm_isdst;
}
/* Returns the shift in seconds if the given times are across the daylight time saving period change */
int get_dlst_shift(time_t *start, time_t *end) {
int shift = 0, dlst_end, dlst_start;
dlst_start = is_dlst_time(start);
dlst_end = is_dlst_time(end);
if (dlst_start < dlst_end) {
shift = 3600;
} else if (dlst_start > dlst_end) {
shift = -3600;
}
return shift;
}
/*#define TEST_TIMEPERIODS_A 1*/
/* see if the specified time falls into a valid time range in the given time period */
int check_time_against_period(time_t test_time, timeperiod *tperiod) {
timeperiodexclusion *temp_timeperiodexclusion = NULL;
timeperiodexclusion *first_timeperiodexclusion = NULL;
daterange *temp_daterange = NULL;
timerange *temp_timerange = NULL;
time_t midnight = 0L;
time_t start_time = (time_t)0L;
time_t end_time = (time_t)0L;
int found_match = FALSE;
struct tm *t, tm_s;
int daterange_type = 0;
unsigned long days = 0L;
time_t day_range_start = (time_t)0L;
time_t day_range_end = (time_t)0L;
int test_time_year = 0;
int test_time_mon = 0;
int test_time_wday = 0;
int year = 0;
int shift;
log_debug_info(DEBUGL_FUNCTIONS, 0, "check_time_against_period()\n");
/* if no period was specified, assume the time is good */
if (tperiod == NULL)
return OK;
/* test exclusions first - if exclusions match current time, bail out with an error */
/* clear exclusions list before recursing (and restore afterwards) to prevent endless loops... */
first_timeperiodexclusion = tperiod->exclusions;
tperiod->exclusions = NULL;
for (temp_timeperiodexclusion = first_timeperiodexclusion; temp_timeperiodexclusion != NULL; temp_timeperiodexclusion = temp_timeperiodexclusion->next) {
if (check_time_against_period(test_time, temp_timeperiodexclusion->timeperiod_ptr) == OK) {
tperiod->exclusions = first_timeperiodexclusion;
return ERROR;
}
}
tperiod->exclusions = first_timeperiodexclusion;
/* save values for later */
t = localtime_r(&test_time, &tm_s);
test_time_year = t->tm_year;
test_time_mon = t->tm_mon;
test_time_wday = t->tm_wday;
/* calculate the start of the day (midnight, 00:00 hours) when the specified test time occurs */
t->tm_sec = 0;
t->tm_min = 0;
t->tm_hour = 0;
midnight = (unsigned long)mktime(t);
/**** check exceptions first ****/
for (daterange_type = 0; daterange_type < DATERANGE_TYPES; daterange_type++) {
for (temp_daterange = tperiod->exceptions[daterange_type]; temp_daterange != NULL; temp_daterange = temp_daterange->next) {
#ifdef TEST_TIMEPERIODS_A
printf("TYPE: %d\n", daterange_type);
printf("TEST: %lu = %s", (unsigned long)test_time, ctime(&test_time));
printf("MIDNIGHT: %lu = %s", (unsigned long)midnight, ctime(&midnight));
#endif
/* get the start time */
switch (daterange_type) {
case DATERANGE_CALENDAR_DATE:
t->tm_sec = 0;
t->tm_min = 0;
t->tm_hour = 0;
t->tm_wday = 0;
t->tm_mday = temp_daterange->smday;
t->tm_mon = temp_daterange->smon;
t->tm_year = (temp_daterange->syear - 1900);
t->tm_isdst = -1;
start_time = mktime(t);
break;
case DATERANGE_MONTH_DATE:
start_time = calculate_time_from_day_of_month(test_time_year, temp_daterange->smon, temp_daterange->smday);
break;
case DATERANGE_MONTH_DAY:
start_time = calculate_time_from_day_of_month(test_time_year, test_time_mon, temp_daterange->smday);
break;
case DATERANGE_MONTH_WEEK_DAY:
start_time = calculate_time_from_weekday_of_month(test_time_year, temp_daterange->smon, temp_daterange->swday, temp_daterange->swday_offset);
break;
case DATERANGE_WEEK_DAY:
start_time = calculate_time_from_weekday_of_month(test_time_year, test_time_mon, temp_daterange->swday, temp_daterange->swday_offset);
break;
default:
continue;
break;
}
/* get the end time */
switch (daterange_type) {
case DATERANGE_CALENDAR_DATE:
t->tm_sec = 0;
t->tm_min = 0;
t->tm_hour = 0;
t->tm_wday = 0;
t->tm_mday = temp_daterange->emday;
t->tm_mon = temp_daterange->emon;
t->tm_year = (temp_daterange->eyear - 1900);
t->tm_isdst = -1;
end_time = mktime(t);
break;
case DATERANGE_MONTH_DATE:
year = test_time_year;
end_time = calculate_time_from_day_of_month(year, temp_daterange->emon, temp_daterange->emday);
/* advance a year if necessary: august 2 - february 5 */
if (end_time < start_time) {
year++;
end_time = calculate_time_from_day_of_month(year, temp_daterange->emon, temp_daterange->emday);
}
break;
case DATERANGE_MONTH_DAY:
end_time = calculate_time_from_day_of_month(test_time_year, test_time_mon, temp_daterange->emday);
break;
case DATERANGE_MONTH_WEEK_DAY:
year = test_time_year;
end_time = calculate_time_from_weekday_of_month(year, temp_daterange->emon, temp_daterange->ewday, temp_daterange->ewday_offset);
/* advance a year if necessary: thursday 2 august - monday 3 february */
if (end_time < start_time) {
year++;
end_time = calculate_time_from_weekday_of_month(year, temp_daterange->emon, temp_daterange->ewday, temp_daterange->ewday_offset);
}
break;
case DATERANGE_WEEK_DAY:
end_time = calculate_time_from_weekday_of_month(test_time_year, test_time_mon, temp_daterange->ewday, temp_daterange->ewday_offset);
break;
default:
continue;
break;
}
#ifdef TEST_TIMEPERIODS_A
printf("START: %lu = %s", (unsigned long)start_time, ctime(&start_time));
printf("END: %lu = %s", (unsigned long)end_time, ctime(&end_time));
#endif
/* start date was bad, so skip this date range */
if ((unsigned long)start_time == 0L)
continue;
/* end date was bad - see if we can handle the error */
if ((unsigned long)end_time == 0L) {
switch (daterange_type) {
case DATERANGE_CALENDAR_DATE:
continue;
break;
case DATERANGE_MONTH_DATE:
/* end date can't be helped, so skip it */
if (temp_daterange->emday < 0)
continue;
/* else end date slipped past end of month, so use last day of month as end date */
/* use same year calculated above */
end_time = calculate_time_from_day_of_month(year, temp_daterange->emon, -1);
break;
case DATERANGE_MONTH_DAY:
/* end date can't be helped, so skip it */
if (temp_daterange->emday < 0)
continue;
/* else end date slipped past end of month, so use last day of month as end date */
end_time = calculate_time_from_day_of_month(test_time_year, test_time_mon, -1);
break;
case DATERANGE_MONTH_WEEK_DAY:
/* end date can't be helped, so skip it */
if (temp_daterange->ewday_offset < 0)
continue;
/* else end date slipped past end of month, so use last day of month as end date */
/* use same year calculated above */
end_time = calculate_time_from_day_of_month(year, test_time_mon, -1);
break;
case DATERANGE_WEEK_DAY:
/* end date can't be helped, so skip it */
if (temp_daterange->ewday_offset < 0)
continue;
/* else end date slipped past end of month, so use last day of month as end date */
end_time = calculate_time_from_day_of_month(test_time_year, test_time_mon, -1);
break;
default:
continue;
break;
}
}
/* calculate skip date start (and end) */
if (temp_daterange->skip_interval > 1) {
/* skip start date must be before test time */
if (start_time > test_time)
continue;
/* check if interval is across dlst change and gets the compensation */
shift = get_dlst_shift(&start_time, &midnight);
/* how many days have passed between skip start date and test time? */
days = (shift + midnight - (unsigned long)start_time) / (3600 * 24);
/* if test date doesn't fall on a skip interval day, bail out early */
if ((days % temp_daterange->skip_interval) != 0)
continue;
/* use midnight of test date as start time */
else
start_time = (time_t)midnight;
/* if skipping range has no end, use test date as end */
if ((daterange_type == DATERANGE_CALENDAR_DATE) && (is_daterange_single_day(temp_daterange) == TRUE))
end_time = (time_t)midnight;
}
#ifdef TEST_TIMEPERIODS_A
printf("NEW START: %lu = %s", (unsigned long)start_time, ctime(&start_time));
printf("NEW END: %lu = %s", (unsigned long)end_time, ctime(&end_time));
printf("%d DAYS PASSED\n", days);
printf("DLST SHIFT: %d", shift);
#endif
/* time falls into the range of days */
if (midnight >= start_time && midnight <= end_time)
found_match = TRUE;
/* found a day match, so see if time ranges are good */
if (found_match == TRUE) {
for (temp_timerange = temp_daterange->times; temp_timerange != NULL; temp_timerange = temp_timerange->next) {
/* ranges with start/end of zero mean exlude this day */
if (temp_timerange->range_start == 0 && temp_timerange->range_end == 0) {
#ifdef TEST_TIMEPERIODS_A
printf("0 MINUTE RANGE EXCLUSION\n");
#endif
continue;
}
day_range_start = (time_t)(midnight + temp_timerange->range_start);
day_range_end = (time_t)(midnight + temp_timerange->range_end);
#ifdef TEST_TIMEPERIODS_A
printf(" RANGE START: %lu (%lu) = %s", temp_timerange->range_start, (unsigned long)day_range_start, ctime(&day_range_start));
printf(" RANGE END: %lu (%lu) = %s", temp_timerange->range_end, (unsigned long)day_range_end, ctime(&day_range_end));
#endif
/* if the user-specified time falls in this range, return with a positive result */
if (test_time >= day_range_start && test_time <= day_range_end)
return OK;
}
/* no match, so bail with error */
return ERROR;
}
}
}
/**** check normal, weekly rotating schedule last ****/
/* check weekday time ranges */
for (temp_timerange = tperiod->days[test_time_wday]; temp_timerange != NULL; temp_timerange = temp_timerange->next) {
day_range_start = (time_t)(midnight + temp_timerange->range_start);
day_range_end = (time_t)(midnight + temp_timerange->range_end);
/* if the user-specified time falls in this range, return with a positive result */
if (test_time >= day_range_start && test_time <= day_range_end)
return OK;
}
return ERROR;
}
/*#define TEST_TIMEPERIODS_B 1*/
/* Separate this out from public get_next_valid_time for testing, so we can mock current_time */
void _get_next_valid_time(time_t pref_time, time_t current_time, time_t *valid_time, timeperiod *tperiod) {
time_t preferred_time = (time_t)0L;
/*
* Moving checks at the top with preferred time
* in Nagios, all is done within _get_next_valid_time
*/
/*
* preferred time must be now or in the future
*/
preferred_time = (pref_time < current_time) ? current_time : pref_time;
/*
* if no timeperiod, go with the preferred time
*/
if (tperiod == NULL) {
*valid_time = preferred_time;
return;
}
/*
* if the preferred time is valid in timeperiod, go with it
* ithis is necessary because the code below won't catch
* exceptions where peferred day is last (or only) date in
* timeperiod (date range) and last valid time has already
* passed.
* performing this check and bailing out early allows us to
* skip having to check the next instance of a date range
* exception or weekday to determine the next valid time
*/
if (check_time_against_period(preferred_time, tperiod) == OK) {
#ifdef TEST_TIMEPERIODS_B
printf("PREF TIME IS VALID\n");
#endif
*valid_time = preferred_time;
return;
}
/*
* first check for possible timeperiod excuslions before getting a valid_time
*/
get_earliest_time(preferred_time, valid_time, current_time, tperiod, 0);
}
/*
* calculate the earliest time possible including checks for timepriod exclusion
*/
void get_earliest_time(time_t pref_time, time_t *valid_time, time_t current_time, timeperiod *tperiod, int level) {
time_t earliest_time;
timeperiodexclusion *temp_timeperiodexclusion = NULL;
timeperiodexclusion *first_timeperiodexclusion = NULL;
/*
* function can get called recursivly, pushing alternating level
* see below in timeperiod exclusion loop
*/
if ((level % 2) == 0) {
/*
* initial hit here, and then alternating by 2 the timeperiod exclusions
*/
_get_next_valid_time_per_timeperiod(pref_time, &earliest_time, current_time, tperiod);
if (*valid_time == 0)
*valid_time = earliest_time;
else if (earliest_time < *valid_time)
*valid_time = earliest_time;
} else {
/*
* first timeperiod exclusion hits here, alternating by 2
*/
get_min_invalid_time_per_timeperiod(pref_time, &earliest_time, current_time, tperiod);
if (*valid_time == 0)
*valid_time = earliest_time;
else if (earliest_time < *valid_time)
*valid_time = earliest_time + 1;
}
/*
* loop through all available exclusions in this timeperiod and alternate level
*/
first_timeperiodexclusion = tperiod->exclusions;
tperiod->exclusions = NULL;
for (temp_timeperiodexclusion = first_timeperiodexclusion; temp_timeperiodexclusion != NULL; temp_timeperiodexclusion = temp_timeperiodexclusion->next) {
get_earliest_time(pref_time, valid_time, current_time, temp_timeperiodexclusion->timeperiod_ptr, level + 1);
}
tperiod->exclusions = first_timeperiodexclusion;
}
/*
* _get_next_valid_time in Nagios
*/
void _get_next_valid_time_per_timeperiod(time_t pref_time, time_t *valid_time, time_t current_time, timeperiod *tperiod) {
time_t preferred_time = (time_t)0L;
timerange *temp_timerange;
daterange *temp_daterange;
time_t midnight = 0L;
struct tm *t, tm_s;
time_t day_start = (time_t)0L;
time_t day_range_start = (time_t)0L;
time_t day_range_end = (time_t)0L;
time_t start_time = (time_t)0L;
time_t end_time = (time_t)0L;
int have_earliest_time = FALSE;
time_t earliest_time = (time_t)0L;
time_t earliest_day = (time_t)0L;
time_t potential_time = (time_t)0L;
int weekday = 0;
int has_looped = FALSE;
int days_into_the_future = 0;
int daterange_type = 0;
unsigned long days = 0L;
unsigned long advance_interval = 0L;
int year = 0; /* new */
int month = 0; /* new */
int pref_time_year = 0;
int pref_time_mon = 0;
int pref_time_wday = 0;
int current_time_year = 0;
int current_time_mon = 0;
int current_time_mday = 0;
int shift;
log_debug_info(DEBUGL_FUNCTIONS, 0, "get_next_valid_time_per_timeperiod()\n");
/* preferred time must be now or in the future */
preferred_time = pref_time;
/* if no timeperiod, go with preferred time */
if (tperiod == NULL) {
*valid_time = preferred_time;
return;
}
/* calculate the start of the day (midnight, 00:00 hours) of preferred time */
t = localtime_r(&preferred_time, &tm_s);
t->tm_sec = 0;
t->tm_min = 0;
t->tm_hour = 0;
midnight = (unsigned long)mktime(t);
/* save pref time values for later */
pref_time_year = t->tm_year;
pref_time_mon = t->tm_mon;
// pref_time_mday = t->tm_mday; <- somehow unused
pref_time_wday = t->tm_wday;
/* save current time values for later */
t = localtime_r(¤t_time, &tm_s);
current_time_year = t->tm_year;
current_time_mon = t->tm_mon;
current_time_mday = t->tm_mday;
// current_time_wday = t->tm_wday; <- somehow unused
#ifdef TEST_TIMEPERIODS_B
printf("PREF TIME: %lu = %s", (unsigned long)preferred_time, ctime(&preferred_time));
printf("CURRENT TIME: %lu = %s", (unsigned long)current_time, ctime(¤t_time));
printf("PREF YEAR: %d, MON: %d, MDAY: %d, WDAY: %d\n", pref_time_year, pref_time_mon, pref_time_mday, pref_time_wday);
printf("CURRENT YEAR: %d, MON: %d, MDAY: %d, WDAY: %d\n", current_time_year, current_time_mon, current_time_mday, current_time_wday);
#endif
/**** check exceptions (in this timeperiod definition) first ****/
for (daterange_type = 0; daterange_type < DATERANGE_TYPES; daterange_type++) {
#ifdef TEST_TIMEPERIODS_B
printf("TYPE: %d\n", daterange_type);
#endif
for (temp_daterange = tperiod->exceptions[daterange_type]; temp_daterange != NULL; temp_daterange = temp_daterange->next) {
/* get the start time */
switch (daterange_type) {
case DATERANGE_CALENDAR_DATE: /* 2009-08-11 */
t->tm_sec = 0;
t->tm_min = 0;
t->tm_hour = 0;
t->tm_mday = temp_daterange->smday;
t->tm_mon = temp_daterange->smon;
t->tm_year = (temp_daterange->syear - 1900);
t->tm_isdst = -1;
start_time = mktime(t);
break;
case DATERANGE_MONTH_DATE: /* january 1 */
/* what year should we use? */
year = (pref_time_year < current_time_year) ? current_time_year : pref_time_year;
/* advance an additional year if we already passed the end month date */
if ((temp_daterange->emon < current_time_mon) || ((temp_daterange->emon == current_time_mon) && temp_daterange->emday < current_time_mday))
year++;
start_time = calculate_time_from_day_of_month(year, temp_daterange->smon, temp_daterange->smday);
break;
case DATERANGE_MONTH_DAY: /* day 3 */
/* what year should we use? */
year = (pref_time_year < current_time_year) ? current_time_year : pref_time_year;
/* use current month */
month = current_time_mon;
/* advance an additional month (and possibly the year) if we already passed the end day of month */
if (temp_daterange->emday < current_time_mday) {
/*if(month==1){*/
if (month == 11) {
month = 0;
year++;
} else
month++;
}
start_time = calculate_time_from_day_of_month(year, month, temp_daterange->smday);
break;
case DATERANGE_MONTH_WEEK_DAY: /* thursday 2 april */
/* what year should we use? */
year = (pref_time_year < current_time_year) ? current_time_year : pref_time_year;
/* calculate time of specified weekday of specific month */
start_time = calculate_time_from_weekday_of_month(year, temp_daterange->smon, temp_daterange->swday, temp_daterange->swday_offset);
/* advance to next year if we've passed this month weekday already this year */
if (start_time < preferred_time) {
year++;
start_time = calculate_time_from_weekday_of_month(year, temp_daterange->smon, temp_daterange->swday, temp_daterange->swday_offset);
}
break;
case DATERANGE_WEEK_DAY: /* wednesday 1 */
/* what year should we use? */
year = (pref_time_year < current_time_year) ? current_time_year : pref_time_year;
/* calculate time of specified weekday of month */
start_time = calculate_time_from_weekday_of_month(year, pref_time_mon, temp_daterange->swday, temp_daterange->swday_offset);
/* advance to next month (or year) if we've passed this weekday of this month already */
if (start_time < preferred_time) {
month = pref_time_mon;
if (month == 11) {
month = 0;
year++;
} else
month++;
start_time = calculate_time_from_weekday_of_month(year, month, temp_daterange->swday, temp_daterange->swday_offset);
}
break;
default:
continue;
break;
}
#ifdef TEST_TIMEPERIODS_B
printf("START TIME: %lu = %s", start_time, ctime(&start_time));
#endif
/* get the end time */
switch (daterange_type) {
case DATERANGE_CALENDAR_DATE:
t->tm_sec = 0;
t->tm_min = 0;
t->tm_hour = 0;
t->tm_mday = temp_daterange->emday;
t->tm_mon = temp_daterange->emon;
t->tm_year = (temp_daterange->eyear - 1900);
t->tm_isdst = -1;
end_time = mktime(t);
break;
case DATERANGE_MONTH_DATE:
/* use same year as was calculated for start time above */
end_time = calculate_time_from_day_of_month(year, temp_daterange->emon, temp_daterange->emday);
/* advance a year if necessary: august 5 - feburary 2 */
if (end_time < start_time) {
year++;
end_time = calculate_time_from_day_of_month(year, temp_daterange->emon, temp_daterange->emday);
}
break;
case DATERANGE_MONTH_DAY:
/* use same year and month as was calculated for start time above */
/*
* 2011-10-22 MF
* original implementation uses
* end_time=calculate_time_from_day_of_month(year,month,temp_daterange->emday);
* so why +1 ?
*/
end_time = calculate_time_from_day_of_month(year, month, temp_daterange->emday + 1);
break;
case DATERANGE_MONTH_WEEK_DAY:
/* use same year as was calculated for start time above */
end_time = calculate_time_from_weekday_of_month(year, temp_daterange->emon, temp_daterange->ewday, temp_daterange->ewday_offset);
/* advance a year if necessary: thursday 2 august - monday 3 february */
if (end_time < start_time) {
year++;
end_time = calculate_time_from_weekday_of_month(year, temp_daterange->emon, temp_daterange->ewday, temp_daterange->ewday_offset);
}
break;
case DATERANGE_WEEK_DAY:
/* use same year and month as was calculated for start time above */
end_time = calculate_time_from_weekday_of_month(year, month, temp_daterange->ewday, temp_daterange->ewday_offset);
break;
default:
continue;
break;
}
#ifdef TEST_TIMEPERIODS_B
printf("STARTTIME: %lu = %s", (unsigned long)start_time, ctime(&start_time));
printf("ENDTIME1: %lu = %s", (unsigned long)end_time, ctime(&end_time));
#endif
/* start date was bad, so skip this date range */
if ((unsigned long)start_time == 0L)
continue;
/* end date was bad - see if we can handle the error */
if ((unsigned long)end_time == 0L) {
switch (daterange_type) {
case DATERANGE_CALENDAR_DATE:
continue;
break;
case DATERANGE_MONTH_DATE:
/* end date can't be helped, so skip it */
if (temp_daterange->emday < 0)
continue;
/* else end date slipped past end of month, so use last day of month as end date */
end_time = calculate_time_from_day_of_month(year, temp_daterange->emon, -1);
break;
case DATERANGE_MONTH_DAY:
/* end date can't be helped, so skip it */
if (temp_daterange->emday < 0)
continue;
/* else end date slipped past end of month, so use last day of month as end date */
end_time = calculate_time_from_day_of_month(year, month, -1);
break;
case DATERANGE_MONTH_WEEK_DAY:
/* end date can't be helped, so skip it */
if (temp_daterange->ewday_offset < 0)
continue;
/* else end date slipped past end of month, so use last day of month as end date */
end_time = calculate_time_from_day_of_month(year, pref_time_mon, -1);
break;
case DATERANGE_WEEK_DAY:
/* end date can't be helped, so skip it */
if (temp_daterange->ewday_offset < 0)
continue;
/* else end date slipped past end of month, so use last day of month as end date */
end_time = calculate_time_from_day_of_month(year, month, -1);
break;
default:
continue;
break;
}
}
#ifdef TEST_TIMEPERIODS_B
printf("ENDTIME2: %lu = %s", (unsigned long)end_time, ctime(&end_time));
#endif
/* if skipping days... */
if (temp_daterange->skip_interval > 1) {
/* advance to the next possible skip date */
if (start_time < preferred_time) {
/* check if interval is across dlst change and gets the compensation */
shift = get_dlst_shift(&start_time, &midnight);
/* how many days have passed between skip start date and preferred time? */
days = (shift + midnight - (unsigned long)start_time) / (3600 * 24);
#ifdef TEST_TIMEPERIODS_B
printf("MIDNIGHT: %lu = %s", midnight, ctime(&midnight));
printf("%lu SECONDS PASSED\n", (midnight - (unsigned long)start_time));
printf("%d DAYS PASSED\n", days);
printf("REMAINDER: %d\n", (days % temp_daterange->skip_interval));
printf("SKIP INTERVAL: %d\n", temp_daterange->skip_interval);
printf("DLST SHIFT: %d", shift);
#endif
/* advance start date to next skip day */
if ((days % temp_daterange->skip_interval) == 0)
start_time += (days * 3600 * 24);
else
start_time += ((days - (days % temp_daterange->skip_interval) + temp_daterange->skip_interval) * 3600 * 24);
}
/* if skipping has no end, use start date as end */
if ((daterange_type == DATERANGE_CALENDAR_DATE) && is_daterange_single_day(temp_daterange) == TRUE)
end_time = start_time;
}
#ifdef TEST_TIMEPERIODS_B
printf("\nSTART: %lu = %s", (unsigned long)start_time, ctime(&start_time));
printf("END: %lu = %s", (unsigned long)end_time, ctime(&end_time));
printf("PREFERRED: %lu = %s", (unsigned long)preferred_time, ctime(&preferred_time));
printf("CURRENT: %lu = %s", (unsigned long)current_time, ctime(¤t_time));
#endif
/* skip this date range its out of bounds with what we want */
if (preferred_time > end_time)
continue;
/* how many days at a time should we advance? */
if (temp_daterange->skip_interval > 1)
advance_interval = temp_daterange->skip_interval;
else
advance_interval = 1;
/* advance through the date range */
for (day_start = start_time; day_start <= end_time; day_start += (advance_interval * 3600 * 24)) {
/* we already found a time from a higher-precendence date range exception */
if (day_start >= earliest_day && have_earliest_time == TRUE)
continue;
for (temp_timerange = temp_daterange->times; temp_timerange != NULL; temp_timerange = temp_timerange->next) {
/* ranges with start/end of zero mean exlude this day */
if (temp_timerange->range_start == 0 && temp_timerange->range_end == 0)
continue;
day_range_start = (time_t)(day_start + temp_timerange->range_start);
day_range_end = (time_t)(day_start + temp_timerange->range_end);
#ifdef TEST_TIMEPERIODS_B
printf(" RANGE START: %lu (%lu) = %s", temp_timerange->range_start, (unsigned long)day_range_start, ctime(&day_range_start));
printf(" RANGE END: %lu (%lu) = %s", temp_timerange->range_end, (unsigned long)day_range_end, ctime(&day_range_end));
#endif
/* range is out of bounds */
if (day_range_end < preferred_time)
continue;
/* preferred time occurs before range start, so use range start time as earliest potential time */
if (day_range_start >= preferred_time)
potential_time = day_range_start;
/* preferred time occurs between range start/end, so use preferred time as earliest potential time */
else if (day_range_end >= preferred_time)
potential_time = preferred_time;
/* is this the earliest time found thus far? */
if (have_earliest_time == FALSE || potential_time < earliest_time) {
have_earliest_time = TRUE;
earliest_time = potential_time;
earliest_day = day_start;
#ifdef TEST_TIMEPERIODS_B
printf(" EARLIEST TIME: %lu = %s", (unsigned long)earliest_time, ctime(&earliest_time));
#endif
}
}
}
}
}
/**** find next available time from normal, weekly rotating schedule (in this timeperiod definition) ****/
/* check a one week rotation of time */
has_looped = FALSE;
for (weekday = pref_time_wday, days_into_the_future = 0;; weekday++, days_into_the_future++) {
/* break out of the loop if we have checked an entire week already */
if (has_looped == TRUE && weekday >= pref_time_wday)
break;
if (weekday >= 7) {
weekday -= 7;
has_looped = TRUE;
}
/* calculate start of this future weekday */
day_start = (time_t)(midnight + (days_into_the_future * 3600 * 24));
/* we already found a time from a higher-precendence date range exception */
if (day_start == earliest_day)
continue;
/* check all time ranges for this day of the week */
for (temp_timerange = tperiod->days[weekday]; temp_timerange != NULL; temp_timerange = temp_timerange->next) {
/* calculate the time for the start of this time range */
day_range_start = (time_t)(day_start + temp_timerange->range_start);
if ((have_earliest_time == FALSE || day_range_start < earliest_time) && day_range_start >= preferred_time) {
have_earliest_time = TRUE;
earliest_time = day_range_start;
earliest_day = day_start;
}
}
}
/* if we couldn't find a time period there must be none defined */
if (have_earliest_time == FALSE || earliest_time == (time_t)0)
*valid_time = (time_t)preferred_time;
/* else use the calculated time */
else
*valid_time = earliest_time;
return;
}
/*
* for timeperiod exclusions, Icinga special from #459
*/
void get_min_invalid_time_per_timeperiod(time_t pref_time, time_t *valid_time, time_t current_time, timeperiod *tperiod) {
time_t preferred_time = (time_t)0L;
timerange *temp_timerange;
daterange *temp_daterange;
time_t midnight = 0L;
struct tm *t, tm_s;
time_t day_start = (time_t)0L;
#ifdef TEST_TIMEPERIODS_B
time_t day_range_start = (time_t)0L;
#endif
time_t day_range_end = (time_t)0L;
time_t start_time = (time_t)0L;
time_t end_time = (time_t)0L;
int have_latest_time = FALSE;
time_t latest_time = (time_t)0L;
time_t earliest_day = (time_t)0L;
time_t potential_time = (time_t)0L;
int weekday = 0;
int has_looped = FALSE;
int days_into_the_future = 0;
int daterange_type = 0;
unsigned long days = 0L;
unsigned long advance_interval = 0L;
int year = 0; /* new */
int month = 0; /* new */
int pref_time_year = 0;
int pref_time_mon = 0;
int pref_time_wday = 0;
int current_time_year = 0;
int current_time_mon = 0;
int current_time_mday = 0;
int shift;
log_debug_info(DEBUGL_FUNCTIONS, 0, "get_min_valid_time_per_timeperiod()\n");
/* preferred time passed as pameter */
preferred_time = pref_time;
/* if no timeperiod, go with preferred time */
if (tperiod == NULL) {
*valid_time = preferred_time;
return;
}
/* calculate the start of the day (midnight, 00:00 hours) of preferred time */
t = localtime_r(&preferred_time, &tm_s);
t->tm_sec = 0;
t->tm_min = 0;
t->tm_hour = 0;
midnight = (unsigned long)mktime(t);
/* save pref time values for later */
pref_time_year = t->tm_year;
pref_time_mon = t->tm_mon;
// pref_time_mday = t->tm_mday; <- unused
pref_time_wday = t->tm_wday;
/* save current time values for later */
t = localtime_r(¤t_time, &tm_s);
current_time_year = t->tm_year;
current_time_mon = t->tm_mon;
current_time_mday = t->tm_mday;
// current_time_wday = t->tm_wday; <- unused
#ifdef TEST_TIMEPERIODS_B
printf("PREF TIME: %lu = %s",(unsigned long)preferred_time,ctime(&preferred_time));
printf("CURRENT TIME: %lu = %s",(unsigned long)current_time,ctime(¤t_time));
printf("PREF YEAR: %d, MON: %d, MDAY: %d, WDAY: %d\n",pref_time_year,pref_time_mon,pref_time_mday,pref_time_wday);
printf("CURRENT YEAR: %d, MON: %d, MDAY: %d, WDAY: %d\n",current_time_year,current_time_mon,current_time_mday,current_time_wday);
#endif
/**** check exceptions (in this timeperiod definition) first ****/
for (daterange_type = 0; daterange_type < DATERANGE_TYPES; daterange_type++) {
#ifdef TEST_TIMEPERIODS_B
printf("TYPE: %d\n",daterange_type);
#endif
for (temp_daterange = tperiod->exceptions[daterange_type]; temp_daterange != NULL; temp_daterange = temp_daterange->next) {
/* get the start time */
switch (daterange_type) {
case DATERANGE_CALENDAR_DATE: /* 2009-08-11 */
t->tm_sec = 0;
t->tm_min = 0;
t->tm_hour = 0;
t->tm_mday = temp_daterange->smday;
t->tm_mon = temp_daterange->smon;
t->tm_year = (temp_daterange->syear - 1900);
t->tm_isdst = -1;
start_time = mktime(t);
break;
case DATERANGE_MONTH_DATE: /* january 1 */
/* what year should we use? */
year = (pref_time_year < current_time_year) ? current_time_year : pref_time_year;
/* advance an additional year if we already passed the end month date */
if ((temp_daterange->emon < current_time_mon) || ((temp_daterange->emon == current_time_mon) && temp_daterange->emday < current_time_mday))
year++;
start_time = calculate_time_from_day_of_month(year, temp_daterange->smon, temp_daterange->smday);
break;
case DATERANGE_MONTH_DAY: /* day 3 */
/* what year should we use? */
year = (pref_time_year < current_time_year) ? current_time_year : pref_time_year;
/* use current month */
month = current_time_mon;
/* advance an additional month (and possibly the year) if we already passed the end day of month */
if (temp_daterange->emday < current_time_mday) {
/*if(month==1){*/
if (month == 11) {
month = 0;
year++;
} else
month++;
}
start_time = calculate_time_from_day_of_month(year, month, temp_daterange->smday);
break;
case DATERANGE_MONTH_WEEK_DAY: /* thursday 2 april */
/* what year should we use? */
year = (pref_time_year < current_time_year) ? current_time_year : pref_time_year;
/* calculate time of specified weekday of specific month */
start_time = calculate_time_from_weekday_of_month(year, temp_daterange->smon, temp_daterange->swday, temp_daterange->swday_offset);
/* advance to next year if we've passed this month weekday already this year */
if (start_time < preferred_time) {
year++;
start_time = calculate_time_from_weekday_of_month(year, temp_daterange->smon, temp_daterange->swday, temp_daterange->swday_offset);
}
break;
case DATERANGE_WEEK_DAY: /* wednesday 1 */
/* what year should we use? */
year = (pref_time_year < current_time_year) ? current_time_year : pref_time_year;
/* calculate time of specified weekday of month */
start_time = calculate_time_from_weekday_of_month(year, pref_time_mon, temp_daterange->swday, temp_daterange->swday_offset);
/* advance to next month (or year) if we've passed this weekday of this month already */
if (start_time < preferred_time) {
month = pref_time_mon;
if (month == 11) {
month = 0;
year++;
} else
month++;
start_time = calculate_time_from_weekday_of_month(year, month, temp_daterange->swday, temp_daterange->swday_offset);
}
break;
default:
continue;
break;
}
/* get the end time */
switch (daterange_type) {
case DATERANGE_CALENDAR_DATE:
t->tm_sec = 0;
t->tm_min = 0;
t->tm_hour = 0;
t->tm_mday = temp_daterange->emday;
t->tm_mon = temp_daterange->emon;
t->tm_year = (temp_daterange->eyear - 1900);
t->tm_isdst = -1;
end_time = mktime(t);
break;
case DATERANGE_MONTH_DATE:
/* use same year as was calculated for start time above */
end_time = calculate_time_from_day_of_month(year, temp_daterange->emon, temp_daterange->emday);
/* advance a year if necessary: august 5 - february 2 */
if (end_time < start_time) {
year++;
end_time = calculate_time_from_day_of_month(year, temp_daterange->emon, temp_daterange->emday);
}
break;
case DATERANGE_MONTH_DAY:
/* use same year and month as was calculated for start time above */
end_time = calculate_time_from_day_of_month(year, month, temp_daterange->emday + 1);
break;
case DATERANGE_MONTH_WEEK_DAY:
/* use same year as was calculated for start time above */
end_time = calculate_time_from_weekday_of_month(year, temp_daterange->emon, temp_daterange->ewday, temp_daterange->ewday_offset);
/* advance a year if necessary: thursday 2 august - monday 3 february */
if (end_time < start_time) {
year++;
end_time = calculate_time_from_weekday_of_month(year, temp_daterange->emon, temp_daterange->ewday, temp_daterange->ewday_offset);
}
break;
case DATERANGE_WEEK_DAY:
/* use same year and month as was calculated for start time above */
end_time = calculate_time_from_weekday_of_month(year, month, temp_daterange->ewday, temp_daterange->ewday_offset);
break;
default:
continue;
break;
}
#ifdef TEST_TIMEPERIODS_B
printf("STARTTIME: %lu = %s",(unsigned long)start_time,ctime(&start_time));
printf("ENDTIME1: %lu = %s",(unsigned long)end_time,ctime(&end_time));
#endif
/* start date was bad, so skip this date range */
if ((unsigned long)start_time == 0L)
continue;
/* end date was bad - see if we can handle the error */
if ((unsigned long)end_time == 0L) {
switch (daterange_type) {
case DATERANGE_CALENDAR_DATE:
continue;
break;
case DATERANGE_MONTH_DATE:
/* end date can't be helped, so skip it */
if (temp_daterange->emday < 0)
continue;
/* else end date slipped past end of month, so use last day of month as end date */
end_time = calculate_time_from_day_of_month(year, temp_daterange->emon, -1);
break;
case DATERANGE_MONTH_DAY:
/* end date can't be helped, so skip it */
if (temp_daterange->emday < 0)
continue;
/* else end date slipped past end of month, so use last day of month as end date */
end_time = calculate_time_from_day_of_month(year, month, -1);
break;
case DATERANGE_MONTH_WEEK_DAY:
/* end date can't be helped, so skip it */
if (temp_daterange->ewday_offset < 0)
continue;
/* else end date slipped past end of month, so use last day of month as end date */
end_time = calculate_time_from_day_of_month(year, pref_time_mon, -1);
break;
case DATERANGE_WEEK_DAY:
/* end date can't be helped, so skip it */
if (temp_daterange->ewday_offset < 0)
continue;
/* else end date slipped past end of month, so use last day of month as end date */
end_time = calculate_time_from_day_of_month(year, month, -1);
break;
default:
continue;
break;
}
}
/* if skipping days... */
if (temp_daterange->skip_interval > 1) {
/* advance to the next possible skip date */
if (start_time < preferred_time) {
/* check if interval is across dlst change and gets the compensation */
shift = get_dlst_shift(&start_time, &midnight);
/* how many days have passed between skip start date and preferred time? */
days = (shift + midnight - (unsigned long)start_time) / (3600 * 24);
/* advance start date to next skip day */
if ((days % temp_daterange->skip_interval) == 0)
start_time += (days * 3600 * 24);
else
start_time += ((days - (days % temp_daterange->skip_interval) + temp_daterange->skip_interval) * 3600 * 24);
}
/* if skipping has no end, use start date as end */
if ((daterange_type == DATERANGE_CALENDAR_DATE) && is_daterange_single_day(temp_daterange) == TRUE)
end_time = start_time;
}
/* skip this date range its out of bounds with what we want */
if (preferred_time > end_time)
continue;
/* how many days at a time should we advance? */
if (temp_daterange->skip_interval > 1)
advance_interval = temp_daterange->skip_interval;
else
advance_interval = 1;
/* advance through the date range */
for (day_start = start_time; day_start <= end_time; day_start += (advance_interval * 3600 * 24)) {
/* we already found a time from a higher-precendence date range exception */
/*
* here we use have_latest_time instead of have_earliest_time
*/
if (day_start >= earliest_day && have_latest_time == TRUE)
continue;
for (temp_timerange = temp_daterange->times; temp_timerange != NULL; temp_timerange = temp_timerange->next) {
/* REMOVED
* ranges with start/end of zero mean exlude this day
* if(temp_timerange->range_start==0 && temp_timerange->range_end==0)
* continue;
*/
day_range_end = (time_t)(day_start + temp_timerange->range_end);
#ifdef TEST_TIMEPERIODS_B
day_range_start = (time_t)(day_start + temp_timerange->range_start);
printf(" RANGE START: %lu (%lu) = %s",temp_timerange->range_start,(unsigned long)day_range_start,ctime(&day_range_start));
printf(" RANGE END: %lu (%lu) = %s",temp_timerange->range_end,(unsigned long)day_range_end,ctime(&day_range_end));
#endif
/* range is out of bounds */
if (day_range_end < preferred_time)
continue;
/* REMOVED
* preferred time occurs before range start, so use range start time as earliest potential time
* if(day_range_start>=preferred_time)
* potential_time=day_range_start;
* preferred time occurs between range start/end, so use preferred time as earliest potential time
*else if(day_range_end>=preferred_time)
* potential_time=preferred_time;
*/
potential_time = day_range_end;
/* is this the earliest time found thus far? */
if (have_latest_time == FALSE || potential_time < latest_time) {
/*
* save it as latest_time instead of earliest_time
*/
have_latest_time = TRUE;
latest_time = potential_time;
earliest_day = day_start;
}
}
}
}
}
/**** find next available time from normal, weekly rotating schedule (in this timeperiod definition) ****/
/* check a one week rotation of time */
has_looped = FALSE;
for (weekday = pref_time_wday, days_into_the_future = 0;; weekday++, days_into_the_future++) {
/* break out of the loop if we have checked an entire week already */
if (has_looped == TRUE && weekday >= pref_time_wday)
break;
if (weekday >= 7) {
weekday -= 7;
has_looped = TRUE;
}
/* calculate start of this future weekday */
day_start = (time_t)(midnight + (days_into_the_future * 3600 * 24));
/* we already found a time from a higher-precendence date range exception */
if (day_start == earliest_day)
continue;
/* check all time ranges for this day of the week */
for (temp_timerange = tperiod->days[weekday]; temp_timerange != NULL; temp_timerange = temp_timerange->next) {
#ifdef TEST_TIMEPERIODS_B
/* calculate the time for the start of this time range */
day_range_start = (time_t)(day_start + temp_timerange->range_start);
#endif
/*
* also calculate day_range_end to assign to lastest_time again
*/
day_range_end = (time_t)(day_start + temp_timerange->range_end);
if ((have_latest_time == FALSE || day_range_end < latest_time) && day_range_end >= preferred_time) {
have_latest_time = TRUE;
latest_time = day_range_end;
earliest_day = day_start;
}
}
}
/* if we couldn't find a time period there must be none defined */
if (have_latest_time == FALSE || latest_time == (time_t)0)
*valid_time = (time_t)preferred_time;
/* else use the calculated time */
else
*valid_time = latest_time;
return;
}
/* given a preferred time, get the next valid time within a time period */
void get_next_valid_time(time_t pref_time, time_t *valid_time, timeperiod *tperiod) {
time_t current_time = (time_t)0L;
log_debug_info(DEBUGL_FUNCTIONS, 0, "get_next_valid_time()\n");
/* get time right now, preferred time must be now or in the future */
time(¤t_time);
_get_next_valid_time(pref_time, current_time, valid_time, tperiod);
}
/* tests if a date range covers just a single day */
int is_daterange_single_day(daterange *dr) {
if (dr == NULL)
return FALSE;
if (dr->syear != dr->eyear)
return FALSE;
if (dr->smon != dr->emon)
return FALSE;
if (dr->smday != dr->emday)
return FALSE;
if (dr->swday != dr->ewday)
return FALSE;
if (dr->swday_offset != dr->ewday_offset)
return FALSE;
return TRUE;
}
/* returns a time (midnight) of particular (3rd, last) day in a given month */
time_t calculate_time_from_day_of_month(int year, int month, int monthday) {
time_t midnight;
int day = 0;
struct tm t;
#ifdef TEST_TIMEPERIODS
printf("YEAR: %d, MON: %d, MDAY: %d\n", year, month, monthday);
#endif
/* positive day (3rd day) */
if (monthday > 0) {
t.tm_sec = 0;
t.tm_min = 0;
t.tm_hour = 0;
t.tm_year = year;
t.tm_mon = month;
t.tm_mday = monthday;
t.tm_isdst = -1;
midnight = mktime(&t);
#ifdef TEST_TIMEPERIODS
printf("MIDNIGHT CALC: %s", ctime(&midnight));
#endif
/* if we rolled over to the next month, time is invalid */
/* assume the user's intention is to keep it in the current month */
if (t.tm_mon != month)
midnight = (time_t)0L;
}
/* negative offset (last day, 3rd to last day) */
else {
/* find last day in the month */
day = 32;
do {
/* back up a day */
day--;
/* make the new time */
t.tm_mon = month;
t.tm_year = year;
t.tm_mday = day;
t.tm_isdst = -1;
midnight = mktime(&t);
} while (t.tm_mon != month);
/* now that we know the last day, back up more */
/* make the new time */
t.tm_mon = month;
t.tm_year = year;
/* -1 means last day of month, so add one to to make this correct - Mike Bird */
t.tm_mday += (monthday < -30) ? -30 : monthday + 1;
t.tm_isdst = -1;
midnight = mktime(&t);
/* if we rolled over to the previous month, time is invalid */
/* assume the user's intention is to keep it in the current month */
if (t.tm_mon != month)
midnight = (time_t)0L;
}
return midnight;
}
/* returns a time (midnight) of particular (3rd, last) weekday in a given month */
time_t calculate_time_from_weekday_of_month(int year, int month, int weekday, int weekday_offset) {
time_t midnight;
int days = 0;
int weeks = 0;
struct tm t;
t.tm_sec = 0;
t.tm_min = 0;
t.tm_hour = 0;
t.tm_year = year;
t.tm_mon = month;
t.tm_mday = 1;
t.tm_isdst = -1;
midnight = mktime(&t);
/* how many days must we advance to reach the first instance of the weekday this month? */
days = weekday - (t.tm_wday);
if (days < 0)
days += 7;
/* positive offset (3rd thursday) */
if (weekday_offset > 0) {
/* how many weeks must we advance (no more than 5 possible) */
weeks = (weekday_offset > 5) ? 5 : weekday_offset;
days += ((weeks - 1) * 7);
/* make the new time */
t.tm_mon = month;
t.tm_year = year;
t.tm_mday = days + 1;
t.tm_isdst = -1;
midnight = mktime(&t);
/* if we rolled over to the next month, time is invalid */
/* assume the user's intention is to keep it in the current month */
if (t.tm_mon != month)
midnight = (time_t)0L;
}
/* negative offset (last thursday, 3rd to last tuesday) */
else {
/* find last instance of weekday in the month */
days += (5 * 7);
do {
/* back up a week */
days -= 7;
/* make the new time */
t.tm_mon = month;
t.tm_year = year;
t.tm_mday = days + 1;
t.tm_isdst = -1;
midnight = mktime(&t);
} while (t.tm_mon != month);
/* now that we know the last instance of the weekday, back up more */
weeks = (weekday_offset < -5) ? -5 : weekday_offset;
days = ((weeks + 1) * 7);
/* make the new time */
t.tm_mon = month;
t.tm_year = year;
t.tm_mday += days;
t.tm_isdst = -1;
midnight = mktime(&t);
/* if we rolled over to the previous month, time is invalid */
/* assume the user's intention is to keep it in the current month */
if (t.tm_mon != month)
midnight = (time_t)0L;
}
return midnight;
}
/* get the next time to schedule a log rotation */
time_t get_next_log_rotation_time(void) {
time_t current_time;
struct tm *t, tm_s;
int is_dst_now = FALSE;
time_t run_time;
time(¤t_time);
t = localtime_r(¤t_time, &tm_s);
t->tm_min = 0;
t->tm_sec = 0;
is_dst_now = (t->tm_isdst > 0) ? TRUE : FALSE;
switch (log_rotation_method) {
case LOG_ROTATION_HOURLY:
t->tm_hour++;
run_time = mktime(t);
break;
case LOG_ROTATION_DAILY:
t->tm_mday++;
t->tm_hour = 0;
run_time = mktime(t);
break;
case LOG_ROTATION_WEEKLY:
t->tm_mday += (7 - t->tm_wday);
t->tm_hour = 0;
run_time = mktime(t);
break;
case LOG_ROTATION_MONTHLY:
default:
t->tm_mon++;
t->tm_mday = 1;
t->tm_hour = 0;
run_time = mktime(t);
break;
}
if (is_dst_now == TRUE && t->tm_isdst == 0)
run_time += 3600;
else if (is_dst_now == FALSE && t->tm_isdst > 0)
run_time -= 3600;
return run_time;
}
/******************************************************************/
/******************** SIGNAL HANDLER FUNCTIONS ********************/
/******************************************************************/
/* trap signals so we can exit gracefully */
void setup_sighandler(void) {
/* reset the shutdown flag */
sigshutdown = FALSE;
/* remove buffering from stderr, stdin, and stdout */
setbuf(stdin, (char *)NULL);
setbuf(stdout, (char *)NULL);
setbuf(stderr, (char *)NULL);
/* initialize signal handling */
signal(SIGPIPE, SIG_IGN);
signal(SIGQUIT, sighandler);
signal(SIGTERM, sighandler);
signal(SIGHUP, sighandler);
if (daemon_dumps_core == FALSE && daemon_mode == TRUE)
signal(SIGSEGV, sighandler);
return;
}
/* reset signal handling... */
void reset_sighandler(void) {
/* set signal handling to default actions */
signal(SIGQUIT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
signal(SIGHUP, SIG_DFL);
signal(SIGSEGV, SIG_DFL);
signal(SIGPIPE, SIG_DFL);
return;
}
/* handle signals */
void sighandler(int sig) {
int x = 0;
/* if shutdown is already true, we're in a signal trap loop! */
/* changed 09/07/06 to only exit on segfaults */
if (sigshutdown == TRUE && sig == SIGSEGV)
exit(ERROR);
caught_signal = TRUE;
if (sig < 0)
sig = -sig;
for (x = 0; sigs[x] != (char *)NULL; x++);
sig %= x;
sig_id = sig;
/* log errors about segfaults now, as we might not get a chance to later */
/* all other signals are logged at a later point in main() to prevent problems with NPTL */
if (sig == SIGSEGV)
logit(NSLOG_PROCESS_INFO, TRUE, "Caught SIG%s, shutting down...\n", sigs[sig]);
/* we received a SIGHUP, so restart... */
if (sig == SIGHUP)
sigrestart = TRUE;
/* else begin shutting down... */
else if (sig < 16)
sigshutdown = TRUE;
return;
}
/* handle timeouts when executing service checks */
/* 07/16/08 EG also called when parent process gets a TERM signal */
void service_check_sighandler(int sig) {
struct timeval end_time;
/* get the current time */
gettimeofday(&end_time, NULL);
check_result_info.return_code = service_check_timeout_state;
check_result_info.finish_time = end_time;
check_result_info.early_timeout = TRUE;
/* write check result to file */
if (check_result_info.output_file_fp) {
fprintf(check_result_info.output_file_fp, "finish_time=%lu.%lu\n", check_result_info.finish_time.tv_sec, check_result_info.finish_time.tv_usec);
fprintf(check_result_info.output_file_fp, "early_timeout=%d\n", check_result_info.early_timeout);
fprintf(check_result_info.output_file_fp, "exited_ok=%d\n", check_result_info.exited_ok);
fprintf(check_result_info.output_file_fp, "return_code=%d\n", check_result_info.return_code);
fprintf(check_result_info.output_file_fp, "output=%s\n", "(Service Check Timed Out)");
/* close the temp file */
fclose(check_result_info.output_file_fp);
/* move check result to queue directory */
move_check_result_to_queue(check_result_info.output_file);
}
/* free check result memory */
free_check_result(&check_result_info);
/* try to kill the command that timed out by sending termination signal to our process group */
/* we also kill ourselves while doing this... */
kill((pid_t)0, SIGKILL);
/* force the child process (service check) to exit... */
_exit(STATE_CRITICAL);
}
/* handle timeouts when executing host checks */
/* 07/16/08 EG also called when parent process gets a TERM signal */
void host_check_sighandler(int sig) {
struct timeval end_time;
/* get the current time */
gettimeofday(&end_time, NULL);
check_result_info.return_code = STATE_CRITICAL;
check_result_info.finish_time = end_time;
check_result_info.early_timeout = TRUE;
/* write check result to file */
if (check_result_info.output_file_fp) {
fprintf(check_result_info.output_file_fp, "finish_time=%lu.%lu\n", check_result_info.finish_time.tv_sec, check_result_info.finish_time.tv_usec);
fprintf(check_result_info.output_file_fp, "early_timeout=%d\n", check_result_info.early_timeout);
fprintf(check_result_info.output_file_fp, "exited_ok=%d\n", check_result_info.exited_ok);
fprintf(check_result_info.output_file_fp, "return_code=%d\n", check_result_info.return_code);
fprintf(check_result_info.output_file_fp, "output=%s\n", "(Host Check Timed Out)");
/* close the temp file */
fclose(check_result_info.output_file_fp);
/* move check result to queue directory */
move_check_result_to_queue(check_result_info.output_file);
}
/* free check result memory */
free_check_result(&check_result_info);
/* try to kill the command that timed out by sending termination signal to our process group */
/* we also kill ourselves while doing this... */
kill((pid_t)0, SIGKILL);
/* force the child process (service check) to exit... */
_exit(STATE_CRITICAL);
}
/* handle timeouts when executing commands via my_system_r() */
void my_system_sighandler(int sig) {
/* force the child process to exit... */
_exit(STATE_CRITICAL);
}
/******************************************************************/
/************************ DAEMON FUNCTIONS ************************/
/******************************************************************/
int daemon_init(void) {
pid_t pid = -1;
int pidno = 0;
int lockfile = 0;
int val = 0;
char buf[256];
struct flock lock;
char *homedir = NULL;
#ifdef RLIMIT_CORE
struct rlimit limit;
#endif
/* change working directory. scuttle home if we're dumping core */
homedir = getenv("HOME");
if (daemon_dumps_core == TRUE && homedir != NULL)
chdir(homedir);
else
chdir("/");
umask(S_IWGRP | S_IWOTH);
lockfile = open(lock_file, O_RDWR | O_CREAT, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);
if (lockfile < 0) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Failed to obtain lock on file %s: %s\n", lock_file, strerror(errno));
logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR, TRUE, "Bailing out due to errors encountered while attempting to daemonize... (PID=%d)", (int)getpid());
cleanup();
exit(ERROR);
}
/* see if we can read the contents of the lockfile */
if ((val = read(lockfile, buf, (size_t)10)) < 0) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Lockfile exists but cannot be read");
cleanup();
exit(ERROR);
}
/* we read something - check the PID */
if (val > 0) {
if ((val = sscanf(buf, "%d", &pidno)) < 1) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Lockfile '%s' does not contain a valid PID (%s)", lock_file, buf);
cleanup();
exit(ERROR);
}
}
/* check for SIGHUP */
if (val == 1 && (pid = (pid_t)pidno) == getpid()) {
close(lockfile);
return OK;
}
/* exit on errors... */
if ((pid = fork()) < 0)
return(ERROR);
/* parent process goes away.. */
else if ((int)pid != 0)
exit(OK);
/* child continues... */
/* child becomes session leader... */
setsid();
/* place a file lock on the lock file */
lock.l_type = F_WRLCK;
lock.l_start = 0;
lock.l_whence = SEEK_SET;
lock.l_len = 0;
if (fcntl(lockfile, F_SETLK, &lock) < 0) {
if (errno == EACCES || errno == EAGAIN) {
fcntl(lockfile, F_GETLK, &lock);
logit(NSLOG_RUNTIME_ERROR, TRUE, "Lockfile '%s' looks like its already held by another instance of %s (PID %d). Bailing out...", PROGRAM_NAME, lock_file, (int)lock.l_pid);
} else
logit(NSLOG_RUNTIME_ERROR, TRUE, "Cannot lock lockfile '%s': %s. Bailing out...", lock_file, strerror(errno));
cleanup();
exit(ERROR);
}
/* prevent daemon from dumping a core file... */
#ifdef RLIMIT_CORE
if (daemon_dumps_core == FALSE) {
getrlimit(RLIMIT_CORE, &limit);
limit.rlim_cur = 0;
setrlimit(RLIMIT_CORE, &limit);
}
#endif
/* write PID to lockfile... */
lseek(lockfile, 0, SEEK_SET);
ftruncate(lockfile, 0);
sprintf(buf, "%d\n", (int)getpid());
write(lockfile, buf, strlen(buf));
/* make sure lock file stays open while program is executing... */
val = fcntl(lockfile, F_GETFD, 0);
val |= FD_CLOEXEC;
fcntl(lockfile, F_SETFD, val);
/* close existing stdin, stdout, stderr */
close(0);
close(1);
close(2);
/* THIS HAS TO BE DONE TO AVOID PROBLEMS WITH STDERR BEING REDIRECTED TO SERVICE MESSAGE PIPE! */
/* re-open stdin, stdout, stderr with known values */
open("/dev/null", O_RDONLY);
open("/dev/null", O_WRONLY);
open("/dev/null", O_WRONLY);
#ifdef USE_EVENT_BROKER
/* send program data to broker */
broker_program_state(NEBTYPE_PROCESS_DAEMONIZE, NEBFLAG_NONE, NEBATTR_NONE, NULL);
#endif
return OK;
}
/******************************************************************/
/*********************** SECURITY FUNCTIONS ***********************/
/******************************************************************/
/* drops privileges */
int drop_privileges(char *user, char *group) {
uid_t uid = -1;
gid_t gid = -1;
struct group *grp = NULL;
struct passwd *pw = NULL;
int result = OK;
log_debug_info(DEBUGL_FUNCTIONS, 0, "drop_privileges() start\n");
log_debug_info(DEBUGL_PROCESS, 0, "Original UID/GID: %d/%d\n", (int)getuid(), (int)getgid());
/* only drop privileges if we're running as root, so we don't interfere with being debugged while running as some random user */
if (getuid() != 0)
return OK;
/* set effective group ID */
if (group != NULL) {
/* see if this is a group name */
if (strspn(group, "0123456789") < strlen(group)) {
grp = (struct group *)getgrnam(group);
if (grp != NULL)
gid = (gid_t)(grp->gr_gid);
else
logit(NSLOG_RUNTIME_WARNING, TRUE, "Warning: Could not get group entry for '%s'", group);
}
/* else we were passed the GID */
else
gid = (gid_t)atoi(group);
}
/* set effective user ID */
if (user != NULL) {
/* see if this is a user name */
if (strspn(user, "0123456789") < strlen(user)) {
pw = (struct passwd *)getpwnam(user);
if (pw != NULL)
uid = (uid_t)(pw->pw_uid);
else
logit(NSLOG_RUNTIME_WARNING, TRUE, "Warning: Could not get passwd entry for '%s'", user);
}
/* else we were passed the UID */
else
uid = (uid_t)atoi(user);
}
/* now that we know what to change to, we fix log file permissions */
fix_log_file_owner(uid, gid);
/* set effective group ID if other than current EGID */
if (gid != getegid()) {
if (setgid(gid) == -1) {
logit(NSLOG_RUNTIME_WARNING, TRUE, "Warning: Could not set effective GID=%d", (int)gid);
result = ERROR;
}
}
#ifdef HAVE_INITGROUPS
if (uid != geteuid()) {
/* initialize supplementary groups */
if (initgroups(user, gid) == -1) {
if (errno == EPERM)
logit(NSLOG_RUNTIME_WARNING, TRUE, "Warning: Unable to change supplementary groups using initgroups() -- I hope you know what you're doing");
else {
logit(NSLOG_RUNTIME_WARNING, TRUE, "Warning: Possibly root user failed dropping privileges with initgroups()");
return ERROR;
}
}
}
#endif
if (setuid(uid) == -1) {
logit(NSLOG_RUNTIME_WARNING, TRUE, "Warning: Could not set effective UID=%d", (int)uid);
result = ERROR;
}
log_debug_info(DEBUGL_PROCESS, 0, "New UID/GID: %d/%d\n", (int)getuid(), (int)getgid());
return result;
}
/******************************************************************/
/************************* IPC FUNCTIONS **************************/
/******************************************************************/
/* move check result to queue directory */
int move_check_result_to_queue(char *checkresult_file) {
char *output_file = NULL;
char *temp_buffer = NULL;
int output_file_fd = -1;
mode_t new_umask = 077;
mode_t old_umask;
int result = 0;
/* save the file creation mask */
old_umask = umask(new_umask);
/* create a safe temp file */
asprintf(&output_file, "%s/cXXXXXX", check_result_path);
output_file_fd = mkstemp(output_file);
/* file created okay */
if (output_file_fd >= 0) {
log_debug_info(DEBUGL_CHECKS, 2, "Moving temp check result file '%s' to queue file '%s'...\n", checkresult_file, output_file);
#ifdef __CYGWIN__
/* Cygwin cannot rename open files - gives Permission Denied */
/* close the file */
close(output_file_fd);
#endif
/* move the original file */
result = my_rename(checkresult_file, output_file);
#ifndef __CYGWIN__
/* close the file */
close(output_file_fd);
#endif
/* create an ok-to-go indicator file */
asprintf(&temp_buffer, "%s.ok", output_file);
if ((output_file_fd = open(temp_buffer, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR)) >= 0)
close(output_file_fd);
my_free(temp_buffer);
/* delete the original file if it couldn't be moved */
if (result != 0)
unlink(checkresult_file);
} else
result = -1;
/* reset the file creation mask */
umask(old_umask);
/* log a warning on errors */
if (result != 0)
logit(NSLOG_RUNTIME_WARNING, TRUE, "Warning: Unable to move file '%s' to check results queue.\n", checkresult_file);
/* free memory */
my_free(output_file);
return OK;
}
/* processes files in the check result queue directory */
int process_check_result_queue(char *dirname) {
char file[MAX_FILENAME_LENGTH];
DIR *dirp = NULL;
struct dirent *dirfile = NULL;
register int x = 0;
struct stat stat_buf;
struct stat ok_stat_buf;
char *temp_buffer = NULL;
int result = OK;
unsigned long list_length = 0;
check_result *current = check_result_list;
if (max_check_result_list_items != 0) {
/* get the number of items currently to-be-processed
* already on the checkresult list
*/
while (current != NULL) {
list_length++;
current = current->next;
}
log_debug_info(DEBUGL_CHECKS, 1, "check_result_list has %lu items\n", list_length);
/* on larger setups, the list in memory might have grown
* large, and we would just stash too much results into
* the list, so bail early here, letting checkresults
* being processed first, then reaping again.
*/
if (list_length > max_check_result_list_items) {
log_debug_info(DEBUGL_CHECKS, 1, "Skipping check result queue as there are %lu/%lu results not handled by the reaper\n", list_length, max_check_result_list_items);
return OK;
}
}
/* make sure we have what we need */
if (dirname == NULL) {
logit(NSLOG_CONFIG_ERROR, TRUE, "Error: No check result queue directory specified.\n");
return ERROR;
}
/* open the directory for reading */
if ((dirp = opendir(dirname)) == NULL) {
logit(NSLOG_CONFIG_ERROR, TRUE, "Error: Could not open check result queue directory '%s' for reading.\n", dirname);
return ERROR;
}
log_debug_info(DEBUGL_CHECKS, 1, "Starting to read check result queue '%s'...\n", dirname);
/* process all files in the directory... */
while ((dirfile = readdir(dirp)) != NULL) {
/* create /path/to/file */
snprintf(file, sizeof(file), "%s/%s", dirname, dirfile->d_name);
file[sizeof(file)-1] = '\x0';
/* process this if it's a check result file... */
x = strlen(dirfile->d_name);
if (x == 7 && dirfile->d_name[0] == 'c') {
if (stat(file, &stat_buf) == -1) {
logit(NSLOG_RUNTIME_WARNING, TRUE, "Warning: Could not stat() check result file '%s'.\n", file);
continue;
}
/*
* don't process symlinked files, we only care
* about real files
*/
if (!S_ISREG(stat_buf.st_mode))
continue;
/* at this point we have a regular file... */
/*
* if the file is too old, we delete it
* otherwise we will leave old files there
*/
if (stat_buf.st_mtime + max_check_result_file_age < time(NULL)) {
delete_check_result_file(file);
continue;
}
/* can we find the associated ok-to-go file ? */
asprintf(&temp_buffer, "%s.ok", file);
result = stat(temp_buffer, &ok_stat_buf);
my_free(temp_buffer);
if (result == -1)
continue;
/* process the file */
result = process_check_result_file(file);
/* break out if we encountered an error */
if (result == ERROR)
break;
}
}
closedir(dirp);
return result;
}
/* reads check result(s) from a file */
int process_check_result_file(char *fname) {
mmapfile *thefile = NULL;
char *input = NULL;
char *var = NULL;
char *val = NULL;
char *v1 = NULL, *v2 = NULL;
time_t current_time;
check_result *new_cr = NULL;
if (fname == NULL)
return ERROR;
time(¤t_time);
log_debug_info(DEBUGL_CHECKS, 1, "Processing check result file: '%s'\n", fname);
/* open the file for reading */
if ((thefile = mmap_fopen(fname)) == NULL) {
/* try removing the file - zero length files can't be mmap()'ed, so it might exist */
unlink(fname);
return ERROR;
}
/* read in all lines from the file */
while (1) {
/* free memory */
my_free(input);
/* read the next line */
if ((input = mmap_fgets_multiline(thefile)) == NULL)
break;
/* skip comments */
if (input[0] == '#')
continue;
/* empty line indicates end of record */
else if (input[0] == '\n') {
/* we have something... */
if (new_cr) {
/* do we have the minimum amount of data? */
if (new_cr->host_name != NULL && new_cr->output != NULL) {
/* add check result to list in memory */
add_check_result_to_list(new_cr);
/* reset pointer */
new_cr = NULL;
}
/* discard partial input */
else {
free_check_result(new_cr);
init_check_result(new_cr);
new_cr->output_file = (char *)strdup(fname);
}
}
}
if ((var = my_strtok(input, "=")) == NULL)
continue;
if ((val = my_strtok(NULL, "\n")) == NULL)
continue;
/* found the file time */
if (!strcmp(var, "file_time")) {
/* file is too old - ignore check results it contains and delete it */
/* this will only work as intended if file_time comes before check results */
if (max_check_result_file_age > 0 && (current_time - (strtoul(val, NULL, 0)) > max_check_result_file_age)) {
break;
}
}
/* else we have check result data */
else {
/* allocate new check result if necessary */
if (new_cr == NULL) {
if ((new_cr = (check_result *)malloc(sizeof(check_result))) == NULL)
continue;
/* init values */
init_check_result(new_cr);
new_cr->output_file = (char *)strdup(fname);
}
if (!strcmp(var, "host_name"))
new_cr->host_name = (char *)strdup(val);
else if (!strcmp(var, "service_description")) {
new_cr->service_description = (char *)strdup(val);
new_cr->object_check_type = SERVICE_CHECK;
} else if (!strcmp(var, "check_type"))
new_cr->check_type = atoi(val);
else if (!strcmp(var, "check_options"))
new_cr->check_options = atoi(val);
else if (!strcmp(var, "scheduled_check"))
new_cr->scheduled_check = atoi(val);
else if (!strcmp(var, "reschedule_check"))
new_cr->reschedule_check = atoi(val);
else if (!strcmp(var, "latency"))
new_cr->latency = strtod(val, NULL);
else if (!strcmp(var, "start_time")) {
if ((v1 = strtok(val, ".")) == NULL)
continue;
if ((v2 = strtok(NULL, "\n")) == NULL)
continue;
new_cr->start_time.tv_sec = strtoul(v1, NULL, 0);
new_cr->start_time.tv_usec = strtoul(v2, NULL, 0);
} else if (!strcmp(var, "finish_time")) {
if ((v1 = strtok(val, ".")) == NULL)
continue;
if ((v2 = strtok(NULL, "\n")) == NULL)
continue;
new_cr->finish_time.tv_sec = strtoul(v1, NULL, 0);
new_cr->finish_time.tv_usec = strtoul(v2, NULL, 0);
} else if (!strcmp(var, "early_timeout"))
new_cr->early_timeout = atoi(val);
else if (!strcmp(var, "exited_ok"))
new_cr->exited_ok = atoi(val);
else if (!strcmp(var, "return_code"))
new_cr->return_code = atoi(val);
else if (!strcmp(var, "output"))
new_cr->output = (char *)strdup(val);
}
}
/* we have something */
if (new_cr) {
/* do we have the minimum amount of data? */
if (new_cr->host_name != NULL && new_cr->output != NULL) {
/* add check result to list in memory */
add_check_result_to_list(new_cr);
/* reset pointer */
new_cr = NULL;
}
/* discard partial input */
/* free memory for current check result record */
else {
free_check_result(new_cr);
my_free(new_cr);
}
}
/* free memory and close file */
my_free(input);
mmap_fclose(thefile);
/* delete the file (as well its ok-to-go file) if it's too old */
/* other (current) files are deleted later (when results are processed) */
delete_check_result_file(fname);
return OK;
}
/* deletes as check result file, as well as its ok-to-go file */
int delete_check_result_file(char *fname) {
char *temp_buffer = NULL;
/* delete the result file */
unlink(fname);
/* delete the ok-to-go file */
asprintf(&temp_buffer, "%s.ok", fname);
unlink(temp_buffer);
my_free(temp_buffer);
return OK;
}
/* reads the first host/service check result from the list in memory */
check_result *read_check_result(void) {
check_result *first_cr = NULL;
if (check_result_list == NULL)
return NULL;
/* lock the check_result_list mutex, in case an event broker is
also trying to change it in a concurrent thread */
pthread_mutex_lock(&check_result_list_mutex);
first_cr = check_result_list;
check_result_list = check_result_list->next;
/* forcibly detach this check result from the list tail */
first_cr->next = NULL;
/* unlock the mutex; all the destructive operations are done */
pthread_mutex_unlock(&check_result_list_mutex);
return first_cr;
}
/* initializes a host/service check result */
int init_check_result(check_result *info) {
if (info == NULL)
return ERROR;
/* reset vars */
info->object_check_type = HOST_CHECK;
info->host_name = NULL;
info->service_description = NULL;
info->check_type = HOST_CHECK_ACTIVE;
info->check_options = CHECK_OPTION_NONE;
info->scheduled_check = FALSE;
info->reschedule_check = FALSE;
info->output_file_fp = NULL;
info->output_file_fd = -1;
info->latency = 0.0;
info->start_time.tv_sec = 0;
info->start_time.tv_usec = 0;
info->finish_time.tv_sec = 0;
info->finish_time.tv_usec = 0;
info->early_timeout = FALSE;
info->exited_ok = TRUE;
info->return_code = 0;
info->output = NULL;
info->next = NULL;
return OK;
}
/* adds a new host/service check result to the list in memory */
int add_check_result_to_list(check_result *new_cr) {
check_result *temp_cr = NULL;
check_result *last_cr = NULL;
if (new_cr == NULL)
return ERROR;
/* lock the check_result_list mutex, so that different threads
can inter-mix calls to add_check_result (i.e. from an event broker) */
pthread_mutex_lock(&check_result_list_mutex);
/* add to list, sorted by finish time (asc) */
/* find insertion point */
last_cr = check_result_list;
for (temp_cr = check_result_list; temp_cr != NULL; temp_cr = temp_cr->next) {
if (temp_cr->finish_time.tv_sec >= new_cr->finish_time.tv_sec) {
if (temp_cr->finish_time.tv_sec > new_cr->finish_time.tv_sec)
break;
else if (temp_cr->finish_time.tv_usec > new_cr->finish_time.tv_usec)
break;
}
last_cr = temp_cr;
}
/* item goes at head of list */
if (check_result_list == NULL || temp_cr == check_result_list) {
new_cr->next = check_result_list;
check_result_list = new_cr;
}
/* item goes in middle or at end of list */
else {
new_cr->next = temp_cr;
last_cr->next = new_cr;
}
/* unlock the mutex; all the destructive operations are done */
pthread_mutex_unlock(&check_result_list_mutex);
return OK;
}
/* frees all memory associated with the check result list */
int free_check_result_list(void) {
check_result *this_cr = NULL;
check_result *next_cr = NULL;
for (this_cr = check_result_list; this_cr != NULL; this_cr = next_cr) {
next_cr = this_cr->next;
free_check_result(this_cr);
my_free(this_cr);
}
check_result_list = NULL;
return OK;
}
/* frees memory associated with a host/service check result */
int free_check_result(check_result *info) {
if (info == NULL)
return OK;
my_free(info->host_name);
my_free(info->service_description);
my_free(info->output_file);
my_free(info->output);
return OK;
}
/* creates external command file as a named pipe (FIFO) and opens it for reading (non-blocked mode) */
int open_command_file(void) {
struct stat st;
int result = 0;
mode_t old_mask = (mode_t) 0;
/* if we're not checking external commands, don't do anything */
if (check_external_commands == FALSE)
return OK;
/* the command file was already created */
if (command_file_created == TRUE)
return OK;
/* reset umask (group needs write permissions) */
old_mask = umask(S_IWOTH);
/* use existing FIFO if possible */
if (!(stat(command_file, &st) != -1 && (st.st_mode & S_IFIFO))) {
/* create the external command file as a named pipe (FIFO) */
if ((result = mkfifo(command_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)) != 0) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Could not create external command file '%s' as named pipe: (%d) -> %s. If this file already exists and you are sure that another copy of %s is not running, you should delete this file.\n", command_file, errno, strerror(errno), PROGRAM_NAME);
return ERROR;
}
}
/* restore umask after mkfifo */
umask(old_mask);
/* open the command file for reading (non-blocked) - O_TRUNC flag cannot be used due to errors on some systems */
/* NOTE: file must be opened read-write for poll() to work */
if ((command_file_fd = open(command_file, O_RDWR | O_NONBLOCK)) < 0) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Could not open external command file for reading via open(): (%d) -> %s\n", errno, strerror(errno));
return ERROR;
}
/* re-open the FIFO for use with fgets() */
if ((command_file_fp = (FILE *)fdopen(command_file_fd, "r")) == NULL) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Could not open external command file for reading via fdopen(): (%d) -> %s\n", errno, strerror(errno));
return ERROR;
}
/* initialize worker thread */
if (init_command_file_worker_thread() == ERROR) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Could not initialize command file worker thread.\n");
/* close the command file */
fclose(command_file_fp);
/* delete the named pipe */
unlink(command_file);
return ERROR;
}
/* set a flag to remember we already created the file */
command_file_created = TRUE;
return OK;
}
/* closes the external command file FIFO and deletes it */
int close_command_file(void) {
/* if we're not checking external commands, don't do anything */
if (check_external_commands == FALSE)
return OK;
/* the command file wasn't created or was already cleaned up */
if (command_file_created == FALSE)
return OK;
/* reset our flag */
command_file_created = FALSE;
/* close the command file */
fclose(command_file_fp);
return OK;
}
/******************************************************************/
/************************ STRING FUNCTIONS ************************/
/******************************************************************/
/* gets the next string from a buffer in memory - strings are terminated by newlines, which are removed */
char *get_next_string_from_buf(char *buf, int *start_index, int bufsize) {
char *sptr = NULL;
char *nl = "\n";
int x;
if (buf == NULL || start_index == NULL)
return NULL;
if (bufsize < 0)
return NULL;
if (*start_index >= (bufsize - 1))
return NULL;
sptr = buf + *start_index;
/* end of buffer */
if (sptr[0] == '\x0')
return NULL;
x = strcspn(sptr, nl);
sptr[x] = '\x0';
*start_index += x + 1;
return sptr;
}
/* determines whether or not an object name (host, service, etc) contains illegal characters */
int contains_illegal_object_chars(char *name) {
register int x = 0;
register int y = 0;
if (name == NULL || illegal_object_chars == NULL)
return FALSE;
x = (int)strlen(name) - 1;
for (; x >= 0; x--) {
/* illegal user-specified characters */
if (illegal_object_chars != NULL)
for (y = 0; illegal_object_chars[y]; y++)
if (name[x] == illegal_object_chars[y])
return TRUE;
}
return FALSE;
}
/* escapes newlines in a string */
char *escape_newlines(char *rawbuf) {
char *newbuf = NULL;
register int x, y;
if (rawbuf == NULL)
return NULL;
/* allocate enough memory to escape all chars if necessary */
if ((newbuf = malloc((strlen(rawbuf) * 2) + 1)) == NULL)
return NULL;
for (x = 0, y = 0; rawbuf[x] != (char)'\x0'; x++) {
/* escape backslashes */
if (rawbuf[x] == '\\') {
newbuf[y++] = '\\';
newbuf[y++] = '\\';
}
/* escape newlines */
else if (rawbuf[x] == '\n') {
newbuf[y++] = '\\';
newbuf[y++] = 'n';
}
else
newbuf[y++] = rawbuf[x];
}
newbuf[y] = '\x0';
return newbuf;
}
/* compares strings */
int compare_strings(char *val1a, char *val2a) {
/* use the compare_hashdata() function */
return compare_hashdata(val1a, NULL, val2a, NULL);
}
/******************************************************************/
/************************* FILE FUNCTIONS *************************/
/******************************************************************/
/* renames a file - works across filesystems (Mike Wiacek) */
int my_rename(char *source, char *dest) {
int rename_result = 0;
/* make sure we have something */
if (source == NULL || dest == NULL)
return -1;
/* first see if we can rename file with standard function */
rename_result = rename(source, dest);
/* handle any errors... */
if (rename_result == -1) {
/* an error occurred because the source and dest files are on different filesystems */
if (errno == EXDEV) {
/* try copying the file */
if (my_fcopy(source, dest) == ERROR) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Unable to rename file '%s' to '%s': %s\n", source, dest, strerror(errno));
return -1;
}
/* delete the original file */
unlink(source);
/* reset result since we successfully copied file */
rename_result = 0;
}
/* some other error occurred */
else {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Unable to rename file '%s' to '%s': %s\n", source, dest, strerror(errno));
return rename_result;
}
}
return rename_result;
}
/*
* copy a file from the path at source to the already opened
* destination file dest.
* This is handy when creating tempfiles with mkstemp()
*/
int my_fdcopy(char *source, char *dest, int dest_fd) {
int source_fd, rd_result = 0, wr_result = 0;
unsigned long tot_written = 0, tot_read = 0, buf_size = 0;
struct stat st;
char *buf;
/* open source file for reading */
if ((source_fd = open(source, O_RDONLY, 0644)) < 0) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Unable to open file '%s' for reading: %s\n", source, strerror(errno));
return ERROR;
}
/*
* find out how large the source-file is so we can be sure
* we've written all of it
*/
if (fstat(source_fd, &st) < 0) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Unable to stat source file '%s' for my_fcopy(): %s\n", source, strerror(errno));
close(source_fd);
return ERROR;
}
/*
* If the file is huge, read it and write it in chunks.
* This value (128K) is the result of "pick-one-at-random"
* with some minimal testing and may not be optimal for all
* hardware setups, but it should work ok for most. It's
* faster than 1K buffers and 1M buffers, so change at your
* own peril. Note that it's useful to make it fit in the L2
* cache, so larger isn't necessarily better.
*/
buf_size = st.st_size > 128 << 10 ? 128 << 10 : st.st_size;
buf = malloc(buf_size);
if (!buf) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Unable to malloc(%lu) bytes: %s\n", buf_size, strerror(errno));
close(source_fd);
return ERROR;
}
/* most of the times, this loop will be gone through once */
while (tot_written < st.st_size) {
int loop_wr = 0;
rd_result = read(source_fd, buf, buf_size);
if (rd_result < 0) {
if (errno == EAGAIN || errno == EINTR)
continue;
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: my_fcopy() failed to read from '%s': %s\n", source, strerror(errno));
break;
}
tot_read += rd_result;
while (loop_wr < rd_result) {
wr_result = write(dest_fd, buf + loop_wr, rd_result - loop_wr);
if (wr_result < 0) {
if (errno == EAGAIN || errno == EINTR)
continue;
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: my_fcopy() failed to write to '%s': %s\n", dest, strerror(errno));
break;
}
loop_wr += wr_result;
}
if (wr_result < 0)
break;
tot_written += loop_wr;
}
/*
* clean up irregardless of how things went. dest_fd comes from
* our caller, so we mustn't close it.
*/
close(source_fd);
free(buf);
if (rd_result < 0 || wr_result < 0) {
/* don't leave half-written files around */
unlink(dest);
return ERROR;
}
return OK;
}
/* copies a file */
int my_fcopy(char *source, char *dest) {
int dest_fd, result;
/* make sure we have something */
if (source == NULL || dest == NULL)
return ERROR;
/* unlink destination file first (not doing so can cause problems on network file systems like CIFS) */
unlink(dest);
/* open destination file for writing */
if ((dest_fd = open(dest, O_WRONLY | O_TRUNC | O_CREAT | O_APPEND, 0644)) < 0) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Unable to open file '%s' for writing: %s\n", dest, strerror(errno));
return ERROR;
}
result = my_fdcopy(source, dest, dest_fd);
close(dest_fd);
return result;
}
/******************************************************************/
/******************** DYNAMIC BUFFER FUNCTIONS ********************/
/******************************************************************/
/* initializes a dynamic buffer */
int dbuf_init(dbuf *db, int chunk_size) {
if (db == NULL)
return ERROR;
db->buf = NULL;
db->used_size = 0L;
db->allocated_size = 0L;
db->chunk_size = chunk_size;
return OK;
}
/* frees a dynamic buffer */
int dbuf_free(dbuf *db) {
if (db == NULL)
return ERROR;
if (db->buf != NULL)
my_free(db->buf);
db->buf = NULL;
db->used_size = 0L;
db->allocated_size = 0L;
return OK;
}
/* dynamically expands a string */
int dbuf_strcat(dbuf *db, char *buf) {
char *newbuf = NULL;
unsigned long buflen = 0L;
unsigned long new_size = 0L;
unsigned long memory_needed = 0L;
if (db == NULL || buf == NULL)
return ERROR;
/* how much memory should we allocate (if any)? */
buflen = strlen(buf);
new_size = db->used_size + buflen + 1;
/* we need more memory */
if (db->allocated_size < new_size) {
memory_needed = ((ceil(new_size / db->chunk_size) + 1) * db->chunk_size);
/* allocate memory to store old and new string */
if ((newbuf = (char *)realloc((void *)db->buf, (size_t)memory_needed)) == NULL)
return ERROR;
/* update buffer pointer */
db->buf = newbuf;
/* update allocated size */
db->allocated_size = memory_needed;
/* terminate buffer */
db->buf[db->used_size] = '\x0';
}
/* append the new string */
strcat(db->buf, buf);
/* update size allocated */
db->used_size += buflen;
return OK;
}
/******************************************************************/
/******************** EMBEDDED PERL FUNCTIONS *********************/
/******************************************************************/
/* initializes embedded perl interpreter */
int init_embedded_perl(char **env) {
#ifdef EMBEDDEDPERL
char **embedding = NULL;
int exitstatus = 0;
int argc = 2;
struct stat stat_buf;
/* make sure the P1 file exists... */
if (p1_file == NULL || stat(p1_file, &stat_buf) != 0) {
use_embedded_perl = FALSE;
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: p1.pl file required for embedded Perl interpreter is missing!\n");
}
else {
embedding = malloc(2 * sizeof(char *));
if (embedding == NULL)
return ERROR;
*embedding = strdup("");
*(embedding + 1) = strdup(p1_file);
use_embedded_perl = TRUE;
PERL_SYS_INIT3(&argc, &embedding, &env);
if ((my_perl = perl_alloc()) == NULL) {
use_embedded_perl = FALSE;
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Could not allocate memory for embedded Perl interpreter!\n");
}
}
/* a fatal error occurred... */
if (use_embedded_perl == FALSE) {
logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR, TRUE, "Bailing out due to errors encountered while initializing the embedded Perl interpreter. (PID=%d)\n", (int)getpid());
cleanup();
exit(ERROR);
}
perl_construct(my_perl);
exitstatus = perl_parse(my_perl, xs_init, 2, (char **)embedding, env);
if (!exitstatus)
exitstatus = perl_run(my_perl);
#endif
return OK;
}
/* closes embedded perl interpreter */
int deinit_embedded_perl(void) {
#ifdef EMBEDDEDPERL
PL_perl_destruct_level = 0;
perl_destruct(my_perl);
perl_free(my_perl);
PERL_SYS_TERM();
#endif
return OK;
}
/* checks to see if we should run a script using the embedded Perl interpreter */
int file_uses_embedded_perl(char *fname) {
#ifndef EMBEDDEDPERL
return FALSE;
#else
int line, use_epn = FALSE;
FILE *fp = NULL;
char buf[256] = "";
if (enable_embedded_perl != TRUE)
return FALSE;
/* open the file, check if its a Perl script and see if we can use epn */
fp = fopen(fname, "r");
if (fp == NULL)
return FALSE;
/* grab the first line - we should see Perl. go home if not */
if (fgets(buf, 80, fp) == NULL || strstr(buf, "/bin/perl") == NULL) {
fclose(fp);
return FALSE;
}
/* epn directives must be found in first ten lines of plugin */
for (line = 1; line < 10; line++) {
if (fgets(buf, sizeof(buf) - 1, fp) == NULL)
break;
buf[sizeof(buf) - 1] = '\0';
/* line contains Icinga directives - keep Nagios compatibility */
if (strstr(buf, "# nagios:") || strstr(buf, "# icinga:")) {
char *p;
p = strstr(buf + 8, "epn");
if (!p)
continue;
/*
* we found it, so close the file and return
* whatever it shows. '+epn' means yes. everything
* else means no.
*/
fclose(fp);
return *(p - 1) == '+' ? TRUE : FALSE;
}
}
fclose(fp);
return use_embedded_perl_implicitly;
#endif
}
/******************************************************************/
/************************ THREAD FUNCTIONS ************************/
/******************************************************************/
/* initializes command file worker thread */
int init_command_file_worker_thread(void) {
int result = 0;
sigset_t newmask;
/* initialize circular buffer */
external_command_buffer.head = 0;
external_command_buffer.tail = 0;
external_command_buffer.items = 0;
external_command_buffer.high = 0;
external_command_buffer.overflow = 0L;
external_command_buffer.buffer = (void **)malloc(external_command_buffer_slots * sizeof(char **));
if (external_command_buffer.buffer == NULL)
return ERROR;
/* initialize mutex (only on cold startup) */
if (sigrestart == FALSE)
pthread_mutex_init(&external_command_buffer.buffer_lock, NULL);
/* new thread should block all signals */
sigfillset(&newmask);
pthread_sigmask(SIG_BLOCK, &newmask, NULL);
/* create worker thread */
result = pthread_create(&worker_threads[COMMAND_WORKER_THREAD], NULL, command_file_worker_thread, NULL);
/* main thread should unblock all signals */
pthread_sigmask(SIG_UNBLOCK, &newmask, NULL);
if (result)
return ERROR;
return OK;
}
/* shutdown command file worker thread */
int shutdown_command_file_worker_thread(void) {
int result = 0;
/* 2010-01-04 AE:
* calling pthread_cancel(0) will cause segfaults with some
* thread libraries. It's possible that will happen if the
* user has a number of config files larger than the max
* open file descriptor limit (ulimit -n) and some retarded
* eventbroker module leaks filedescriptors, since we'll then
* enter the cleanup() routine from main() before we've
* spawned any threads.
*/
if (worker_threads[COMMAND_WORKER_THREAD]) {
/* tell the worker thread to exit */
result = pthread_cancel(worker_threads[COMMAND_WORKER_THREAD]);
/* wait for the worker thread to exit */
if (result == 0) {
result = pthread_join(worker_threads[COMMAND_WORKER_THREAD], NULL);
}
/* we're being called from a fork()'ed child process - can't cancel thread, so just cleanup memory */
else {
cleanup_command_file_worker_thread(NULL);
}
}
return OK;
}
/* clean up resources used by command file worker thread */
void cleanup_command_file_worker_thread(void *arg) {
register int x = 0;
/* release memory allocated to circular buffer */
for (x = external_command_buffer.tail; x != external_command_buffer.head; x = (x + 1) % external_command_buffer_slots) {
my_free(((char **)external_command_buffer.buffer)[x]);
}
my_free(external_command_buffer.buffer);
return;
}
/* worker thread - artificially increases buffer of named pipe */
void * command_file_worker_thread(void *arg) {
char input_buffer[MAX_EXTERNAL_COMMAND_LENGTH];
struct pollfd pfd;
int pollval;
struct timeval tv;
int buffer_items = 0;
int result = 0;
/* specify cleanup routine */
pthread_cleanup_push(cleanup_command_file_worker_thread, NULL);
/* set cancellation info */
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
while (1) {
/* should we shutdown? */
pthread_testcancel();
/* wait for data to arrive */
/* select seems to not work, so we have to use poll instead */
/* 10-15-08 EG check into implementing William's patch @ http://blog.netways.de/2008/08/15/nagios-unter-mac-os-x-installieren/ */
/* 10-15-08 EG poll() seems broken on OSX - see Jonathan's patch a few lines down */
pfd.fd = command_file_fd;
pfd.events = POLLIN;
pollval = poll(&pfd, 1, 500);
/* loop if no data */
if (pollval == 0)
continue;
/* check for errors */
if (pollval == -1) {
switch (errno) {
case EBADF:
write_to_log("command_file_worker_thread(): poll(): EBADF", logging_options, NULL);
break;
case ENOMEM:
write_to_log("command_file_worker_thread(): poll(): ENOMEM", logging_options, NULL);
break;
case EFAULT:
write_to_log("command_file_worker_thread(): poll(): EFAULT", logging_options, NULL);
break;
case EINTR:
/* this can happen when running under a debugger like gdb */
/*
write_to_log("command_file_worker_thread(): poll(): EINTR (impossible)",logging_options,NULL);
*/
break;
default:
write_to_log("command_file_worker_thread(): poll(): Unknown errno value.", logging_options, NULL);
break;
}
continue;
}
/* should we shutdown? */
pthread_testcancel();
/* get number of items in the buffer */
pthread_mutex_lock(&external_command_buffer.buffer_lock);
buffer_items = external_command_buffer.items;
pthread_mutex_unlock(&external_command_buffer.buffer_lock);
#ifdef DEBUG_CFWT
printf("(CFWT) BUFFER ITEMS: %d/%d\n", buffer_items, external_command_buffer_slots);
#endif
/* 10-15-08 Fix for OS X by Jonathan Saggau - see http://www.jonathansaggau.com/blog/2008/09/using_shark_and_custom_dtrace.html */
/* Not sure if this would have negative effects on other OSes... */
if (buffer_items == 0) {
/* pause a bit so OS X doesn't go nuts with CPU overload */
tv.tv_sec = 0;
tv.tv_usec = 500;
select(0, NULL, NULL, NULL, &tv);
}
/* process all commands in the file (named pipe) if there's some space in the buffer */
if (buffer_items < external_command_buffer_slots) {
/* clear EOF condition from prior run (FreeBSD fix) */
/* FIXME: use_poll_on_cmd_pipe: Still needed? */
clearerr(command_file_fp);
/* read and process the next command in the file */
while (fgets(input_buffer, (int)(sizeof(input_buffer) - 1), command_file_fp) != NULL) {
#ifdef DEBUG_CFWT
printf("(CFWT) READ: %s", input_buffer);
#endif
/* submit the external command for processing (retry if buffer is full) */
while ((result = submit_external_command(input_buffer, &buffer_items)) == ERROR && buffer_items == external_command_buffer_slots) {
/* wait a bit */
tv.tv_sec = 0;
tv.tv_usec = 250000;
select(0, NULL, NULL, NULL, &tv);
/* should we shutdown? */
pthread_testcancel();
}
#ifdef DEBUG_CFWT
printf("(CFWT) RES: %d, BUFFER_ITEMS: %d/%d\n", result, buffer_items, external_comand_buffer_slots);
#endif
/* bail if the circular buffer is full */
if (buffer_items == external_command_buffer_slots)
break;
/* should we shutdown? */
pthread_testcancel();
}
} else {
/* HB 06-07-2009:
* We should wait for the event queuing to catch up some commands
* from the buffer if for this atomic run the buffer is filled completely or
* is overrun
*/
/* wait a bit */
tv.tv_sec = 0;
tv.tv_usec = 250000;
select(0, NULL, NULL, NULL, &tv);
/* should we shutdown? */
pthread_testcancel();
}
}
/* removes cleanup handler - this should never be reached */
pthread_cleanup_pop(0);
return NULL;
}
/* submits an external command for processing */
int submit_external_command(char *cmd, int *buffer_items) {
int result = OK;
if (cmd == NULL || external_command_buffer.buffer == NULL) {
if (buffer_items != NULL)
*buffer_items = -1;
return ERROR;
}
/* obtain a lock for writing to the buffer */
pthread_mutex_lock(&external_command_buffer.buffer_lock);
if (external_command_buffer.items < external_command_buffer_slots) {
/* save the line in the buffer */
((char **)external_command_buffer.buffer)[external_command_buffer.head] = (char *)strdup(cmd);
/* increment the head counter and items */
external_command_buffer.head = (external_command_buffer.head + 1) % external_command_buffer_slots;
external_command_buffer.items++;
if (external_command_buffer.items > external_command_buffer.high)
external_command_buffer.high = external_command_buffer.items;
}
/* buffer was full */
else
result = ERROR;
/* return number of items now in buffer */
if (buffer_items != NULL)
*buffer_items = external_command_buffer.items;
/* release lock on buffer */
pthread_mutex_unlock(&external_command_buffer.buffer_lock);
return result;
}
/* submits a raw external command (without timestamp) for processing */
int submit_raw_external_command(char *cmd, time_t *ts, int *buffer_items) {
char *newcmd = NULL;
int result = OK;
time_t timestamp;
if (cmd == NULL)
return ERROR;
/* get the time */
if (ts != NULL)
timestamp = *ts;
else
time(×tamp);
/* create the command string */
asprintf(&newcmd, "[%lu] %s", (unsigned long)timestamp, cmd);
/* submit the command */
result = submit_external_command(newcmd, buffer_items);
/* free allocated memory */
my_free(newcmd);
return result;
}
/******************************************************************/
/********************** CHECK STATS FUNCTIONS *********************/
/******************************************************************/
/* initialize check statistics data structures */
int init_check_stats(void) {
int x = 0;
int y = 0;
for (x = 0; x < MAX_CHECK_STATS_TYPES; x++) {
check_statistics[x].current_bucket = 0;
for (y = 0; y < CHECK_STATS_BUCKETS; y++)
check_statistics[x].bucket[y] = 0;
check_statistics[x].overflow_bucket = 0;
for (y = 0; y < 3; y++)
check_statistics[x].minute_stats[y] = 0;
check_statistics[x].last_update = (time_t)0L;
}
return OK;
}
/* records stats for a given type of check */
int update_check_stats(int check_type, time_t check_time) {
time_t current_time;
unsigned long minutes = 0L;
int new_current_bucket = 0;
int this_bucket = 0;
int x = 0;
if (check_type < 0 || check_type >= MAX_CHECK_STATS_TYPES)
return ERROR;
time(¤t_time);
if ((unsigned long)check_time == 0L) {
#ifdef DEBUG_CHECK_STATS
printf("TYPE[%d] CHECK TIME==0!\n", check_type);
#endif
check_time = current_time;
}
/* do some sanity checks on the age of the stats data before we start... */
/* get the new current bucket number */
minutes = ((unsigned long)check_time - (unsigned long)program_start) / 60;
new_current_bucket = minutes % CHECK_STATS_BUCKETS;
/* its been more than 15 minutes since stats were updated, so clear the stats */
if ((((unsigned long)current_time - (unsigned long)check_statistics[check_type].last_update) / 60) > CHECK_STATS_BUCKETS) {
for (x = 0; x < CHECK_STATS_BUCKETS; x++)
check_statistics[check_type].bucket[x] = 0;
check_statistics[check_type].overflow_bucket = 0;
#ifdef DEBUG_CHECK_STATS
printf("CLEARING ALL: TYPE[%d], CURRENT=%lu, LASTUPDATE=%lu\n", check_type, (unsigned long)current_time, (unsigned long)check_statistics[check_type].last_update);
#endif
}
/* different current bucket number than last time */
else if (new_current_bucket != check_statistics[check_type].current_bucket) {
/* clear stats in buckets between last current bucket and new current bucket - stats haven't been updated in a while */
for (x = check_statistics[check_type].current_bucket; x < (CHECK_STATS_BUCKETS * 2); x++) {
this_bucket = (x + CHECK_STATS_BUCKETS + 1) % CHECK_STATS_BUCKETS;
if (this_bucket == new_current_bucket)
break;
#ifdef DEBUG_CHECK_STATS
printf("CLEARING BUCKET %d, (NEW=%d, OLD=%d)\n", this_bucket, new_current_bucket, check_statistics[check_type].current_bucket);
#endif
/* clear old bucket value */
check_statistics[check_type].bucket[this_bucket] = 0;
}
/* update the current bucket number, push old value to overflow bucket */
check_statistics[check_type].overflow_bucket = check_statistics[check_type].bucket[new_current_bucket];
check_statistics[check_type].current_bucket = new_current_bucket;
check_statistics[check_type].bucket[new_current_bucket] = 0;
}
#ifdef DEBUG_CHECK_STATS
else
printf("NO CLEARING NEEDED\n");
#endif
/* increment the value of the current bucket */
check_statistics[check_type].bucket[new_current_bucket]++;
#ifdef DEBUG_CHECK_STATS
printf("TYPE[%d].BUCKET[%d]=%d\n", check_type, new_current_bucket, check_statistics[check_type].bucket[new_current_bucket]);
printf(" ");
for (x = 0; x < CHECK_STATS_BUCKETS; x++)
printf("[%d] ", check_statistics[check_type].bucket[x]);
printf(" (%d)\n", check_statistics[check_type].overflow_bucket);
#endif
/* record last update time */
check_statistics[check_type].last_update = current_time;
return OK;
}
/* generate 1/5/15 minute stats for a given type of check */
int generate_check_stats(void) {
time_t current_time;
int x = 0;
int new_current_bucket = 0;
int this_bucket = 0;
int last_bucket = 0;
int this_bucket_value = 0;
int last_bucket_value = 0;
int bucket_value = 0;
int seconds = 0;
int minutes = 0;
int check_type = 0;
float this_bucket_weight = 0.0;
float last_bucket_weight = 0.0;
// int left_value = 0; <- unused, is this intendet?
// int right_value = 0; <- unused, is this intendet?
time(¤t_time);
/* do some sanity checks on the age of the stats data before we start... */
/* get the new current bucket number */
minutes = ((unsigned long)current_time - (unsigned long)program_start) / 60;
new_current_bucket = minutes % CHECK_STATS_BUCKETS;
for (check_type = 0; check_type < MAX_CHECK_STATS_TYPES; check_type++) {
/* its been more than 15 minutes since stats were updated, so clear the stats */
if ((((unsigned long)current_time - (unsigned long)check_statistics[check_type].last_update) / 60) > CHECK_STATS_BUCKETS) {
for (x = 0; x < CHECK_STATS_BUCKETS; x++)
check_statistics[check_type].bucket[x] = 0;
check_statistics[check_type].overflow_bucket = 0;
#ifdef DEBUG_CHECK_STATS
printf("GEN CLEARING ALL: TYPE[%d], CURRENT=%lu, LASTUPDATE=%lu\n", check_type, (unsigned long)current_time, (unsigned long)check_statistics[check_type].last_update);
#endif
}
/* different current bucket number than last time */
else if (new_current_bucket != check_statistics[check_type].current_bucket) {
/* clear stats in buckets between last current bucket and new current bucket - stats haven't been updated in a while */
for (x = check_statistics[check_type].current_bucket; x < (CHECK_STATS_BUCKETS * 2); x++) {
this_bucket = (x + CHECK_STATS_BUCKETS + 1) % CHECK_STATS_BUCKETS;
if (this_bucket == new_current_bucket)
break;
#ifdef DEBUG_CHECK_STATS
printf("GEN CLEARING BUCKET %d, (NEW=%d, OLD=%d), CURRENT=%lu, LASTUPDATE=%lu\n", this_bucket, new_current_bucket, check_statistics[check_type].current_bucket, (unsigned long)current_time, (unsigned long)check_statistics[check_type].last_update);
#endif
/* clear old bucket value */
check_statistics[check_type].bucket[this_bucket] = 0;
}
/* update the current bucket number, push old value to overflow bucket */
check_statistics[check_type].overflow_bucket = check_statistics[check_type].bucket[new_current_bucket];
check_statistics[check_type].current_bucket = new_current_bucket;
check_statistics[check_type].bucket[new_current_bucket] = 0;
}
#ifdef DEBUG_CHECK_STATS
else
printf("GEN NO CLEARING NEEDED: TYPE[%d], CURRENT=%lu, LASTUPDATE=%lu\n", check_type, (unsigned long)current_time, (unsigned long)check_statistics[check_type].last_update);
#endif
/* update last check time */
check_statistics[check_type].last_update = current_time;
}
/* determine weights to use for this/last buckets */
seconds = ((unsigned long)current_time - (unsigned long)program_start) % 60;
this_bucket_weight = (seconds / 60.0);
last_bucket_weight = ((60 - seconds) / 60.0);
/* update statistics for all check types */
for (check_type = 0; check_type < MAX_CHECK_STATS_TYPES; check_type++) {
/* clear the old statistics */
for (x = 0; x < 3; x++)
check_statistics[check_type].minute_stats[x] = 0;
/* loop through each bucket */
for (x = 0; x < CHECK_STATS_BUCKETS; x++) {
/* which buckets should we use for this/last bucket? */
this_bucket = (check_statistics[check_type].current_bucket + CHECK_STATS_BUCKETS - x) % CHECK_STATS_BUCKETS;
last_bucket = (this_bucket + CHECK_STATS_BUCKETS - 1) % CHECK_STATS_BUCKETS;
/* raw/unweighted value for this bucket */
this_bucket_value = check_statistics[check_type].bucket[this_bucket];
/* raw/unweighted value for last bucket - use overflow bucket if last bucket is current bucket */
if (last_bucket == check_statistics[check_type].current_bucket)
last_bucket_value = check_statistics[check_type].overflow_bucket;
else
last_bucket_value = check_statistics[check_type].bucket[last_bucket];
/* determine value by weighting this/last buckets... */
/* if this is the current bucket, use its full value + weighted % of last bucket */
if (x == 0) {
// right_value = this_bucket_value;
// left_value = (int)floor(last_bucket_value * last_bucket_weight);
bucket_value = (int)(this_bucket_value + floor(last_bucket_value * last_bucket_weight));
}
/* otherwise use weighted % of this and last bucket */
else {
// right_value = (int)ceil(this_bucket_value * this_bucket_weight);
// left_value = (int)floor(last_bucket_value * last_bucket_weight);
bucket_value = (int)(ceil(this_bucket_value * this_bucket_weight) + floor(last_bucket_value * last_bucket_weight));
}
/* 1 minute stats */
if (x == 0)
check_statistics[check_type].minute_stats[0] = bucket_value;
/* 5 minute stats */
if (x < 5)
check_statistics[check_type].minute_stats[1] += bucket_value;
/* 15 minute stats */
if (x < 15)
check_statistics[check_type].minute_stats[2] += bucket_value;
#ifdef DEBUG_CHECK_STATS2
printf("X=%d, THIS[%d]=%d, LAST[%d]=%d, 1/5/15=%d,%d,%d L=%d R=%d\n", x, this_bucket, this_bucket_value, last_bucket, last_bucket_value, check_statistics[check_type].minute_stats[0], check_statistics[check_type].minute_stats[1], check_statistics[check_type].minute_stats[2], left_value, right_value);
#endif
/* record last update time */
check_statistics[check_type].last_update = current_time;
}
#ifdef DEBUG_CHECK_STATS
printf("TYPE[%d] 1/5/15 = %d, %d, %d (seconds=%d, this_weight=%f, last_weight=%f)\n", check_type, check_statistics[check_type].minute_stats[0], check_statistics[check_type].minute_stats[1], check_statistics[check_type].minute_stats[2], seconds, this_bucket_weight, last_bucket_weight);
#endif
}
return OK;
}
/******************************************************************/
/************************* MISC FUNCTIONS *************************/
/******************************************************************/
/* returns Icinga version */
char *get_program_version(void) {
return (char *)PROGRAM_VERSION;
}
/* returns Icinga modification date */
char *get_program_modification_date(void) {
return (char *)PROGRAM_MODIFICATION_DATE;
}
int has_shell_metachars(const char *s) {
if (*s != '/' && *s != '.')
return 1;
if (strpbrk(s, "!$^&*()~[]\\|{};<>?'\""))
return 1;
return 0;
}
/******************************************************************/
/*********************** CLEANUP FUNCTIONS ************************/
/******************************************************************/
/* do some cleanup before we exit */
void cleanup(void) {
#ifdef USE_EVENT_BROKER
/* unload modules */
if (test_scheduling == FALSE && verify_config == FALSE) {
neb_free_callback_list();
neb_unload_all_modules(NEBMODULE_FORCE_UNLOAD, (sigshutdown == TRUE) ? NEBMODULE_NEB_SHUTDOWN : NEBMODULE_NEB_RESTART);
neb_free_module_list();
neb_deinit_modules();
}
#endif
/* free all allocated memory - including macros */
free_memory(get_global_macros());
/* close the log file */
close_log_file();
return;
}
/* free the memory allocated to the linked lists */
void free_memory(icinga_macros *mac) {
timed_event *this_event = NULL;
timed_event *next_event = NULL;
/* free all allocated memory for the object definitions */
free_object_data();
/* free memory allocated to comments */
free_comment_data();
/* free check result list */
free_check_result_list();
/* free memory for the high priority event list */
this_event = event_list_high;
while (this_event != NULL) {
if (this_event->event_type == EVENT_SCHEDULED_DOWNTIME)
my_free(this_event->event_data);
next_event = this_event->next;
my_free(this_event);
this_event = next_event;
}
/* reset the event pointer */
event_list_high = NULL;
/* free memory for the low priority event list */
this_event = event_list_low;
while (this_event != NULL) {
if (this_event->event_type == EVENT_SCHEDULED_DOWNTIME)
my_free(this_event->event_data);
next_event = this_event->next;
my_free(this_event);
this_event = next_event;
}
/* reset the event pointer */
event_list_low = NULL;
/* free memory for global event handlers */
my_free(global_host_event_handler);
my_free(global_service_event_handler);
/* free any notification list that may have been overlooked */
free_notification_list();
/* free obsessive compulsive commands */
my_free(ocsp_command);
my_free(ochp_command);
/*
* free memory associated with macros.
* It's ok to only free the volatile ones, as the non-volatile
* are always free()'d before assignment if they're set.
* Doing a full free of them here means we'll wipe the constant
* macros when we get a reload or restart request through the
* command pipe, or when we receive a SIGHUP.
*/
clear_volatile_macros_r(mac);
free_macrox_names();
/* free illegal char strings */
my_free(illegal_object_chars);
my_free(illegal_output_chars);
/* free Icinga user and group */
my_free(nagios_user);
my_free(nagios_group);
/* free file/path variables */
my_free(log_file);
my_free(debug_file);
my_free(temp_file);
my_free(temp_path);
my_free(check_result_path);
my_free(command_file);
my_free(lock_file);
my_free(auth_file);
my_free(p1_file);
my_free(log_archive_path);
return;
}
/* free a notification list that was created */
void free_notification_list(void) {
notification *temp_notification = NULL;
notification *next_notification = NULL;
temp_notification = notification_list;
while (temp_notification != NULL) {
next_notification = temp_notification->next;
my_free(temp_notification);
temp_notification = next_notification;
}
/* reset notification list pointer */
notification_list = NULL;
return;
}
/* reset all system-wide variables, so when we've receive a SIGHUP we can restart cleanly */
int reset_variables(void) {
log_file = (char *)strdup(DEFAULT_LOG_FILE);
temp_file = (char *)strdup(DEFAULT_TEMP_FILE);
temp_path = (char *)strdup(DEFAULT_TEMP_PATH);
check_result_path = (char *)strdup(DEFAULT_CHECK_RESULT_PATH);
command_file = (char *)strdup(DEFAULT_COMMAND_FILE);
lock_file = (char *)strdup(DEFAULT_LOCK_FILE);
auth_file = (char *)strdup(DEFAULT_AUTH_FILE);
p1_file = (char *)strdup(DEFAULT_P1_FILE);
log_archive_path = (char *)strdup(DEFAULT_LOG_ARCHIVE_PATH);
debug_file = (char *)strdup(DEFAULT_DEBUG_FILE);
nagios_user = (char *)strdup(DEFAULT_ICINGA_USER);
nagios_group = (char *)strdup(DEFAULT_ICINGA_GROUP);
use_regexp_matches = FALSE;
use_true_regexp_matching = FALSE;
use_daemon_log = DEFAULT_USE_DAEMON_LOG;
use_syslog = DEFAULT_USE_SYSLOG;
use_syslog_local_facility = DEFAULT_USE_SYSLOG_LOCAL_FACILITY;
syslog_local_facility = DEFAULT_SYSLOG_LOCAL_FACILITY;
log_service_retries = DEFAULT_LOG_SERVICE_RETRIES;
log_host_retries = DEFAULT_LOG_HOST_RETRIES;
log_initial_states = DEFAULT_LOG_INITIAL_STATES;
log_notifications = DEFAULT_NOTIFICATION_LOGGING;
log_event_handlers = DEFAULT_LOG_EVENT_HANDLERS;
log_external_commands = DEFAULT_LOG_EXTERNAL_COMMANDS;
log_passive_checks = DEFAULT_LOG_PASSIVE_CHECKS;
logging_options = NSLOG_RUNTIME_ERROR | NSLOG_RUNTIME_WARNING | NSLOG_VERIFICATION_ERROR | NSLOG_VERIFICATION_WARNING | NSLOG_CONFIG_ERROR | NSLOG_CONFIG_WARNING | NSLOG_PROCESS_INFO | NSLOG_HOST_NOTIFICATION | NSLOG_SERVICE_NOTIFICATION | NSLOG_EVENT_HANDLER | NSLOG_EXTERNAL_COMMAND | NSLOG_PASSIVE_CHECK | NSLOG_HOST_UP | NSLOG_HOST_DOWN | NSLOG_HOST_UNREACHABLE | NSLOG_SERVICE_OK | NSLOG_SERVICE_WARNING | NSLOG_SERVICE_UNKNOWN | NSLOG_SERVICE_CRITICAL | NSLOG_INFO_MESSAGE;
syslog_options = NSLOG_RUNTIME_ERROR | NSLOG_RUNTIME_WARNING | NSLOG_VERIFICATION_ERROR | NSLOG_VERIFICATION_WARNING | NSLOG_CONFIG_ERROR | NSLOG_CONFIG_WARNING | NSLOG_PROCESS_INFO | NSLOG_HOST_NOTIFICATION | NSLOG_SERVICE_NOTIFICATION | NSLOG_EVENT_HANDLER | NSLOG_EXTERNAL_COMMAND | NSLOG_PASSIVE_CHECK | NSLOG_HOST_UP | NSLOG_HOST_DOWN | NSLOG_HOST_UNREACHABLE | NSLOG_SERVICE_OK | NSLOG_SERVICE_WARNING | NSLOG_SERVICE_UNKNOWN | NSLOG_SERVICE_CRITICAL | NSLOG_INFO_MESSAGE;
service_check_timeout = DEFAULT_SERVICE_CHECK_TIMEOUT;
host_check_timeout = DEFAULT_HOST_CHECK_TIMEOUT;
event_handler_timeout = DEFAULT_EVENT_HANDLER_TIMEOUT;
notification_timeout = DEFAULT_NOTIFICATION_TIMEOUT;
ocsp_timeout = DEFAULT_OCSP_TIMEOUT;
ochp_timeout = DEFAULT_OCHP_TIMEOUT;
sleep_time = DEFAULT_SLEEP_TIME;
interval_length = DEFAULT_INTERVAL_LENGTH;
service_inter_check_delay_method = ICD_SMART;
host_inter_check_delay_method = ICD_SMART;
service_interleave_factor_method = ILF_SMART;
max_service_check_spread = DEFAULT_SERVICE_CHECK_SPREAD;
max_host_check_spread = DEFAULT_HOST_CHECK_SPREAD;
use_aggressive_host_checking = DEFAULT_AGGRESSIVE_HOST_CHECKING;
cached_host_check_horizon = DEFAULT_CACHED_HOST_CHECK_HORIZON;
cached_service_check_horizon = DEFAULT_CACHED_SERVICE_CHECK_HORIZON;
enable_predictive_host_dependency_checks = DEFAULT_ENABLE_PREDICTIVE_HOST_DEPENDENCY_CHECKS;
enable_predictive_service_dependency_checks = DEFAULT_ENABLE_PREDICTIVE_SERVICE_DEPENDENCY_CHECKS;
soft_state_dependencies = FALSE;
retain_state_information = FALSE;
retention_update_interval = DEFAULT_RETENTION_UPDATE_INTERVAL;
use_retained_program_state = TRUE;
dump_retained_host_service_states_to_neb = FALSE;
use_retained_scheduling_info = FALSE;
retention_scheduling_horizon = DEFAULT_RETENTION_SCHEDULING_HORIZON;
modified_host_process_attributes = MODATTR_NONE;
modified_service_process_attributes = MODATTR_NONE;
retained_host_attribute_mask = 0L;
retained_service_attribute_mask = 0L;
retained_process_host_attribute_mask = 0L;
retained_process_service_attribute_mask = 0L;
retained_contact_host_attribute_mask = 0L;
retained_contact_service_attribute_mask = 0L;
command_check_interval = DEFAULT_COMMAND_CHECK_INTERVAL;
check_reaper_interval = DEFAULT_CHECK_REAPER_INTERVAL;
max_check_reaper_time = DEFAULT_MAX_REAPER_TIME;
max_check_result_file_age = DEFAULT_MAX_CHECK_RESULT_AGE;
service_freshness_check_interval = DEFAULT_FRESHNESS_CHECK_INTERVAL;
host_freshness_check_interval = DEFAULT_FRESHNESS_CHECK_INTERVAL;
auto_rescheduling_interval = DEFAULT_AUTO_RESCHEDULING_INTERVAL;
auto_rescheduling_window = DEFAULT_AUTO_RESCHEDULING_WINDOW;
check_external_commands = DEFAULT_CHECK_EXTERNAL_COMMANDS;
check_orphaned_services = DEFAULT_CHECK_ORPHANED_SERVICES;
check_orphaned_hosts = DEFAULT_CHECK_ORPHANED_HOSTS;
check_service_freshness = DEFAULT_CHECK_SERVICE_FRESHNESS;
log_stale_services = DEFAULT_LOG_STALE_SERVICES;
log_stale_hosts = DEFAULT_LOG_STALE_HOSTS;
check_host_freshness = DEFAULT_CHECK_HOST_FRESHNESS;
auto_reschedule_checks = DEFAULT_AUTO_RESCHEDULE_CHECKS;
log_rotation_method = LOG_ROTATION_NONE;
last_command_check = 0L;
last_command_status_update = 0L;
last_log_rotation = 0L;
max_parallel_service_checks = DEFAULT_MAX_PARALLEL_SERVICE_CHECKS;
currently_running_service_checks = 0;
enable_notifications = TRUE;
execute_service_checks = TRUE;
accept_passive_service_checks = TRUE;
execute_host_checks = TRUE;
accept_passive_service_checks = TRUE;
enable_event_handlers = TRUE;
obsess_over_services = FALSE;
obsess_over_hosts = FALSE;
enable_failure_prediction = TRUE;
next_comment_id = 0L; /* comment and downtime id get initialized to nonzero elsewhere */
next_downtime_id = 0L;
next_event_id = 1;
next_notification_id = 1;
aggregate_status_updates = TRUE;
status_update_interval = DEFAULT_STATUS_UPDATE_INTERVAL;
event_broker_options = BROKER_NOTHING;
time_change_threshold = DEFAULT_TIME_CHANGE_THRESHOLD;
enable_flap_detection = DEFAULT_ENABLE_FLAP_DETECTION;
low_service_flap_threshold = DEFAULT_LOW_SERVICE_FLAP_THRESHOLD;
high_service_flap_threshold = DEFAULT_HIGH_SERVICE_FLAP_THRESHOLD;
low_host_flap_threshold = DEFAULT_LOW_HOST_FLAP_THRESHOLD;
high_host_flap_threshold = DEFAULT_HIGH_HOST_FLAP_THRESHOLD;
process_performance_data = DEFAULT_PROCESS_PERFORMANCE_DATA;
translate_passive_host_checks = DEFAULT_TRANSLATE_PASSIVE_HOST_CHECKS;
passive_host_checks_are_soft = DEFAULT_PASSIVE_HOST_CHECKS_SOFT;
use_large_installation_tweaks = DEFAULT_USE_LARGE_INSTALLATION_TWEAKS;
enable_environment_macros = TRUE;
free_child_process_memory = -1;
child_processes_fork_twice = -1;
additional_freshness_latency = DEFAULT_ADDITIONAL_FRESHNESS_LATENCY;
enable_embedded_perl = DEFAULT_ENABLE_EMBEDDED_PERL;
use_embedded_perl_implicitly = DEFAULT_USE_EMBEDDED_PERL_IMPLICITLY;
stalking_event_handlers_for_hosts = DEFAULT_STALKING_EVENT_HANDLERS_FOR_HOSTS;
stalking_event_handlers_for_services = DEFAULT_STALKING_EVENT_HANDLERS_FOR_SERVICES;
stalking_notifications_for_hosts = DEFAULT_STALKING_NOTIFICATIONS_FOR_HOSTS;
stalking_notifications_for_services = DEFAULT_STALKING_NOTIFICATIONS_FOR_SERVICES;
keep_unknown_macros = FALSE;
external_command_buffer_slots = DEFAULT_EXTERNAL_COMMAND_BUFFER_SLOTS;
debug_level = DEFAULT_DEBUG_LEVEL;
debug_verbosity = DEFAULT_DEBUG_VERBOSITY;
max_debug_file_size = DEFAULT_MAX_DEBUG_FILE_SIZE;
max_check_result_list_items = DEFAULT_MAX_CHECK_RESULT_LIST_ITEMS;
date_format = DATE_FORMAT_US;
/* initialize macros */
init_macros();
global_host_event_handler = NULL;
global_service_event_handler = NULL;
global_host_event_handler_ptr = NULL;
global_service_event_handler_ptr = NULL;
ocsp_command = NULL;
ochp_command = NULL;
ocsp_command_ptr = NULL;
ochp_command_ptr = NULL;
/* reset umask */
umask(S_IWGRP | S_IWOTH);
return OK;
}
|