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
|
/*
* Copyright (C)
* 2013 - EATON
* 2024-2025 - Jim Klimov <jimklimov+nut@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*! \file nutconf.cpp
\brief NUT configuration tool
\author Frederic Bohe <fredericbohe@eaton.com>
\author Vaclav Krpec <vaclavkrpec@eaton.com>
*/
#include "config.h"
#include "nutconf.hpp"
#include "nutstream.hpp"
extern "C" {
/* FIXME? Is it counter-intentional to use our C common library
* for C++ code (here for common printing of version banner)? */
#include "common.h"
#if (defined WITH_NUTSCANNER)
/* NOTE: `libnutscan` itself gets linked in at run-time, no ltdl optionality */
# include "nut-scan.h"
# include "nutscan-init.h"
# include "nutscan-device.h"
#endif /* WITH_NUTSCANNER */
}
#include <iostream>
#include <list>
#include <vector>
#include <map>
#include <stdexcept>
#include <cassert>
#include <cstring>
#include <cstdlib>
class Usage {
private:
/** Usage text */
static const char * s_text[];
/** Private constructor (no instances) */
Usage() {}
public:
/** Print version and usage to stderr */
static void print(const std::string & bin);
/** Print version info to stdout */
static void printVersion(const std::string & bin);
}; // end of class usage
const char * Usage::s_text[] = {
" -h -help",
" --help Display this help and exit",
" -V",
" --version Display tool version on stdout and exit",
" --autoconfigure Perform automatic configuration",
" --is-configured Checks whether NUT is configured",
" --local <directory> Sets configuration directory",
" --system Sets configuration directory to " CONFPATH " (default)",
" NOTE: If NUT_CONFPATH envvar is set,",
" it is the default unless overridden by",
" --system (lower prio) or --local DIR",
" --get-mode Gets NUT mode (see below)",
" --set-mode <NUT mode> Sets NUT mode (see below)",
" --set-monitor <spec> Configures one monitor (see below)",
" All existing entries are removed; however, it may be",
" specified multiple times to set multiple entries",
" --add-monitor <spec> Same as --set-monitor, but keeps existing entries",
" The two options are mutually exclusive",
" --set-listen <addr> [<port>] Configures one listen address for the NUT daemon",
" All existing entries are removed; however, it may be",
" specified multiple times to set multiple entries",
" --add-listen <addr> [<port>] Same as --set-listen, but keeps existing entries",
" The two options are mutually exclusive",
" --set-device <spec> Configures one UPS device (see below)",
" All existing devices are removed; however, it may be",
" specified multiple times to set multiple devices",
" --add-device <spec> Same as --set-device, but keeps existing devices",
" The two options are mutually exclusive",
" --set-notifyflags <type> <flag>+ Configures notify flags for notification type",
" See below for the types and supported flags",
" Existing flags are replaced",
" --add-notifyflags <type> <flag>+ Same as --set-notifyflags, but keeps existing flags",
" --set-notifymsg <type> <message> Configures notification message for the type",
" --set-notifycmd <command> Configures notification command",
" --set-shutdowncmd <command> Configures shutdown command",
" --set-minsupplies <supp_no> Configures minimum of required power supplies",
" --set-powerdownflag <file> Configures powerdown flag file",
" --set-user <spec> Configures one user (see below)",
" All existing users are removed; however, it may be",
" specified multiple times to set multiple users",
" --add-user <spec> Same as --set-user, but keeps existing users",
" The two options are mutually exclusive",
/* FIXME: Alias as "-D"? Is this the same as nut_debug_level
* NOTE: upsdebugx() not used here directly (yet?), though we
* could setenv() the envvar for libnutscan perhaps? */
" -v",
" --verbose Increase verbosity of output one level",
" May be specified multiple times",
#if (defined WITH_NUTSCANNER)
#if (defined WITH_SNMP)
" --scan-snmp <spec> Scan SNMP devices (see below)",
" May be specified multiple times",
#endif // defined WITH_SNMP
#if (defined WITH_USB)
" --scan-usb Scan USB devices",
#endif // defined WITH_USB
#if (defined WITH_NEON)
" --scan-xml-http [<timeout>] Scan XML/HTTP devices (optional timeout in us)",
#endif // defined WITH_NEON
" --scan-nut <spec> Scan NUT devices (see below for the specs)",
" May be specified multiple times",
#if (defined WITH_AVAHI)
" --scan-avahi [<timeout>] Scan Avahi devices (optional timeout in us)",
#endif // defined WITH_AVAHI
#if (defined WITH_IPMI)
" --scan-ipmi <spec> Scan IPMI devices (see below)",
" May be specified multiple times",
#endif // defined WITH_IPMI
" --scan-serial <port>* Scan for serial devices on specified ports",
#endif // defined WITH_NUTSCANNER
"",
"NUT modes: standalone, netserver, netclient, controlled, manual, none",
"Monitor is specified by the following sequence:",
" <ups_ID> <host>[:<port>] <power_value> <user> <passwd> (\"primary\"|\"secondary\")",
"UPS device is specified by the following sequence:",
" <ups_ID> <driver> <port> [<key>=<value>]*",
"Notification types:",
" ONLINE, ONBATT, LOWBATT, FSD, COMMOK, COMMBAD, SHUTDOWN, REPLBATT, NOCOMM, NOPARENT,",
" CAL, NOTCAL, OFF, NOTOFF, BYPASS, NOTBYPASS, ECO, NOTECO, ALARM, NOTALARM,",
" OVER, NOTOVER, TRIM, NOTTRIM, BOOST, NOTBOOST,",
" OTHER, NOTOTHER, SUSPEND_STARTING, SUSPEND_FINISHED",
"Notification flags:",
" SYSLOG, WALL, EXEC, IGNORE",
"User specification:",
"The very 1st argument is the username (but see the upsmon exception, below).",
"Next arguments use scheme of key/value pairs in form <key>=<value>",
"Known keys are:",
" password, actions (from {SET,FSD}), instcmds (accepted multiple times)",
"Specially, for the upsmon user, the 1st argument takes form of",
" upsmon={master|slave}",
#if (defined WITH_NUTSCANNER)
#if (defined WITH_SNMP)
"SNMP device scan specification:",
" <start IP> <stop IP> [<attr>=<val>]*",
"Known attributes are:",
" timeout (in us), community, sec-level, sec-name, auth-password, priv-password,",
" auth-protocol, priv-protocol, peer-name",
#endif // defined WITH_SNMP
"NUT device scan specification:",
" <start IP> <stop IP> <port> [<us_timeout>]",
#if (defined WITH_IPMI)
"IMPI device scan specification:",
" <start IP> <stop IP> [<attr>=<val>]*",
"Known attributes are:",
" username, password, auth-type, cipher-suite-id, K-g-BMC-key, priv-level,",
" workaround-flags, version",
#endif // defined WITH_IPMI
#endif // defined WITH_NUTSCANNER
"",
};
/**
* Print version info to stdout (like other NUT tools)
*/
void Usage::printVersion(const std::string & bin) {
std::cout
<< "Network UPS Tools " << bin
<< " " << describe_NUT_VERSION_once() << std::endl;
}
/**
* Print help text (including version info) to stderr
*/
void Usage::print(const std::string & bin) {
std::cerr
<< "Network UPS Tools " << bin
<< " " << describe_NUT_VERSION_once() << std::endl
<< std::endl
<< "Usage: " << bin << " [OPTIONS]" << std::endl
<< std::endl
<< "OPTIONS:" << std::endl;
for (size_t i = 0; i < sizeof(s_text) / sizeof(char *); ++i) {
std::cerr << s_text[i] << std::endl;
}
std::cerr
/* << std::endl // last line of s_text is blank */
<< suggest_doc_links(bin.c_str(), nullptr);
/* Method output brings its own endl */
}
/** Command line options */
class Options {
public:
/** Options list */
typedef std::list<std::string> List;
/** Option arguments list */
typedef std::list<std::string> Arguments;
protected:
/** Options map */
typedef std::multimap<std::string, Arguments> Map;
private:
/** Option type */
typedef enum {
singleDash, /**< Single-dash prefixed option */
doubleDash, /**< Double-dash prefixed option */
} type_t;
/** Arguments of the last option processed (\c nullptr means bin. args) */
Arguments * m_last;
/** Binary arguments */
Arguments m_args;
/** Single-dashed options */
Map m_single;
/** Double-dashed options */
Map m_double;
/**
* \brief Add option
*
* \param type Option type
* \param opt Option
*/
void add(type_t type, const std::string & opt);
/**
* \brief Add argument to the last option
*
* \param arg Argument
*/
inline void addArg(const std::string & arg) {
Arguments * args = nullptr != m_last ? m_last : &m_args;
args->push_back(arg);
}
/**
* \brief Count options
*
* \param map Option map
* \param opt Option
*
* \return Options count
*/
size_t count(const Map & map, const std::string & opt) const;
/**
* \brief Get option arguments
*
* \param[in] map Option map
* \param[in] opt Option
* \param[out] args Option arguments
* \param[in] order Option order (1st by default)
*
* \retval true IFF the option was specified on the command line
* \retval false otherwise
*/
bool get(const Map & map, const std::string & opt, Arguments & args, size_t order = 0) const;
/**
* \brief Get options list
*
* \param[in] map Option map
* \param[out] list Option list
*
* \return List of options
*/
void strings(const Map & map, List & list) const;
/**
* \brief Dump options (for debugging reasons)
*
* \param stream Output stream
*/
void dump(std::ostream & stream) const;
public:
/**
* \brief Constructor (from \c main routine arguments)
*
* \param argv Argument list
* \param argc Argument count
*/
Options(char * const argv[], int argc);
/**
* \brief Count single-dashed options
*
* \param opt Option
*
* \return Options count
*/
inline size_t countSingle(const std::string & opt) const {
return count(m_single, opt);
}
/**
* \brief Count double-dashed options
*
* \param opt Option
*
* \return Options count
*/
inline size_t countDouble(const std::string & opt) const {
return count(m_double, opt);
}
/**
* \brief Count options (single or double dashed)
*
* \param opt Option
*
* \return Options count
*/
inline bool count(const std::string & opt) const {
return countSingle(opt) + countDouble(opt);
}
/**
* \brief Check single-dashed option existence
*
* \param opt Option
*
* \retval true IFF the option was specified on the command line
* \retval false otherwise
*/
inline bool existsSingle(const std::string & opt) const {
return countSingle(opt) > 0;
}
/**
* \brief Check double-dashed option existence
*
* \param opt Option
*
* \retval true IFF the option was specified on the command line
* \retval false otherwise
*/
inline bool existsDouble(const std::string & opt) const {
return countDouble(opt) > 0;
}
/**
* \brief Check option existence (single or double dashed)
*
* \param opt Option
*
* \retval true IFF the option was specified on the command line
* \retval false otherwise
*/
inline bool exists(const std::string & opt) const {
return existsSingle(opt) || existsDouble(opt);
}
/**
* \brief Get single-dashed option arguments
*
* \param[in] opt Option
* \param[out] args Option arguments
* \param[in] order Option order (1st by default)
*
* \retval true IFF the option was specified on the command line
* \retval false otherwise
*/
inline bool getSingle(const std::string & opt, Arguments & args, size_t order = 0) const {
return get(m_single, opt, args, order);
}
/**
* \brief Get double-dashed option arguments
*
* \param[in] opt Option
* \param[out] args Option arguments
* \param[in] order Option order (1st by default)
*
* \retval true IFF the option was specified on the command line
* \retval false otherwise
*/
inline bool getDouble(const std::string & opt, Arguments & args, size_t order = 0) const {
return get(m_double, opt, args, order);
}
/**
* \brief Get binary arguments
*
* \return Arguments of the binary itself
*/
inline const Arguments & get() const { return m_args; }
/**
* \brief Get single-dashed options list
*
* \return List of single-dashed options
*/
inline List stringsSingle() const {
List list;
strings(m_single, list);
return list;
}
/**
* \brief Get double-dashed options list
*
* \return List of double-dashed options
*/
inline List stringsDouble() const {
List list;
strings(m_double, list);
return list;
}
/**
* \brief Get all options list
*
* \return List of single or double-dashed options
*/
inline List strings() const;
}; // end of class Options
void Options::add(Options::type_t type, const std::string & opt) {
Map * map;
switch (type) {
case singleDash:
map = &m_single;
break;
case doubleDash:
map = &m_double;
break;
#if (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH_POP) && ( (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_COVERED_SWITCH_DEFAULT) || (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE) )
# pragma GCC diagnostic push
#endif
#ifdef HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_COVERED_SWITCH_DEFAULT
# pragma GCC diagnostic ignored "-Wcovered-switch-default"
#endif
#ifdef HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE
# pragma GCC diagnostic ignored "-Wunreachable-code"
#endif
/* Older CLANG (e.g. clang-3.4) seems to not support the GCC pragmas above */
#ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunreachable-code"
# pragma clang diagnostic ignored "-Wcovered-switch-default"
#endif
default:
/* Must not occur thanks to enum.
* But otherwise we can see
* error: 'map' may be used uninitialized
* from some overly zealous compilers.
*/
if (1) { // scoping
std::stringstream e;
e << "Options::add() got unsupported enum value";
throw std::logic_error(e.str());
}
#ifdef __clang__
# pragma clang diagnostic pop
#endif
#if (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH_POP) && ( (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_COVERED_SWITCH_DEFAULT) || (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE) )
# pragma GCC diagnostic pop
#endif
}
Map::iterator entry = map->insert(Map::value_type(opt, Arguments()));
m_last = &entry->second;
}
size_t Options::count(const Options::Map & map, const std::string & opt) const {
size_t cnt = 0;
Map::const_iterator entry = map.find(opt);
for (; entry != map.end() && entry->first == opt; ++entry)
++cnt;
return cnt;
}
bool Options::get(const Options::Map & map, const std::string & opt, Arguments & args, size_t order) const {
Map::const_iterator entry = map.find(opt);
if (map.end() == entry)
return false;
for (; order; --order) {
Map::const_iterator next = entry;
++next;
if (map.end() == next || next->first != opt)
return false;
entry = next;
}
args = entry->second;
return true;
}
void Options::strings(const Map & map, List & list) const {
for (Map::const_iterator opt = map.begin(); opt != map.end(); ++opt)
list.push_back(opt->first);
}
void Options::dump(std::ostream & stream) const {
stream << "----- Options dump begin -----" << std::endl;
Map::const_iterator opt;
Arguments::const_iterator arg;
for (opt = m_single.begin(); opt != m_single.end(); ++opt) {
stream << '-' << opt->first << ' ';
for (arg = opt->second.begin(); arg != opt->second.end(); ++arg)
stream << *arg << ' ';
stream << std::endl;
}
for (opt = m_double.begin(); opt != m_double.end(); ++opt) {
stream << "--" << opt->first << ' ';
for (arg = opt->second.begin(); arg != opt->second.end(); ++arg)
stream << *arg << ' ';
stream << std::endl;
}
stream << "-- ";
for (arg = m_args.begin(); arg != m_args.end(); ++arg)
stream << *arg;
stream << std::endl << "----- Options dump end -----" << std::endl;
}
Options::Options(char * const argv[], int argc): m_last(nullptr) {
int i;
for (i = 1; i < argc; ++i) {
const std::string arg(argv[i]);
// Empty string is the current option argument, too
// '-' alone is also an option argument
// (like stdout placeholder etc)
if (arg.empty() || '-' != arg[0] || 1 == arg.size())
addArg(arg);
// Single-dashed option
else if ('-' != arg[1])
add(singleDash, arg.substr(1));
// "--" alone is valid as it means that what follows
// belongs to the binary ("empty" option arguments)
else if (2 == arg.size())
m_last = nullptr;
// Double-dashed option
else if ('-' != arg[2])
add(doubleDash, arg.substr(2));
// "---" prefix means an option argument
else
addArg(arg);
}
// Options debugging
//dump(std::cerr);
}
Options::List Options::strings() const {
List list = stringsSingle();
strings(m_double, list);
return list;
}
#if (defined WITH_NUTSCANNER)
/** NUT scanner wrapper */
class NutScanner {
public:
/** Device info */
class Device {
friend class NutScanner;
public:
/** Device type */
typedef nutscan_device_type_t type_t;
/** Device options */
typedef std::map<std::string, const std::string> options_t;
public:
const std::string type; /**< Type */
const std::string driver; /**< Driver */
const std::string port; /**< Port */
const options_t options; /**< Options */
private:
/**
* \brief Create options
*
* \param opt libnutscan device options
*
* \return Device option list
*/
static options_t createOptions(nutscan_options_t * opt);
/** Constructor */
Device(nutscan_device_t * dev);
}; // end of class Device
/** Device list */
typedef std::list<Device> devices_t;
/** SNMP attributes */
struct SNMPAttributes {
std::string community; /**< Community */
std::string sec_level; /**< Sec. level */
std::string sec_name; /**< Sec. name */
std::string auth_passwd; /**< Authentication password */
std::string priv_passwd; /**< Priv. password */
std::string auth_proto; /**< Authentication protocol */
std::string priv_proto; /**< Priv. protocol */
std::string peer_name; /**< Peer name */
}; // end of class SNMPAttributes
/** IMPI attributes */
struct IPMIAttributes {
std::string username; /**< Username */
std::string passwd; /**< Password */
int auth_type; /**< Authentication type */
int cipher_suite_id; /**< Cipher suite ID */
std::string K_g_BMC_key; /**< Optional 2nd key */
int priv_level; /**< Priviledge level */
unsigned wa_flags; /**< Workaround flags */
int version; /**< IPMI protocol version */
/** Constructor */
IPMIAttributes():
auth_type(IPMI_AUTHENTICATION_TYPE_MD5),
cipher_suite_id(3),
priv_level(IPMI_PRIVILEGE_LEVEL_ADMIN),
wa_flags(0),
version(IPMI_1_5)
{}
}; // end of struct IMPIAttributes
private:
/** NUT scanner initialization/finalization */
struct InitFinal {
/** Initialization */
InitFinal() { nutscan_init(); }
/** Finalization */
~InitFinal() { nutscan_free(); }
}; // end of struct InitFinal
/** Initializer / finalizer */
static InitFinal s_init_final;
/**
* \brief Transform nut-scan provided devices into list of device info
*
* The nut-scan provided device list is destroyed.
*
* \param dev_list nut-scan provided device list
*
* \return Device info list
*/
static devices_t dev2list(nutscan_device_t * dev_list);
/** Instantiation forbidden */
NutScanner() {}
public:
/**
* \brief Scan for SNMP devices
*
* \param start_ip Address range left border
* \param stop_ip Address range right border
* \param us_timeout Device scan timeout
* \param attrs SNMP attributes
*
* \return Device list
*/
static devices_t devicesSNMP(
const std::string & start_ip,
const std::string & stop_ip,
useconds_t us_timeout,
const SNMPAttributes & attrs);
/**
* \brief Scan for USB devices
*
* \return Device list
*/
inline static devices_t devicesUSB() {
// FIXME: Since NUT v2.8.2 nutscan_scan_usb accepts
// a `nutscan_usb_t * scanopts` to tweak what values
// it reports -- make use of it in this class.
// A nullptr value causes safe defaults to be used,
// as decided by the library.
nutscan_device_t * dev = ::nutscan_scan_usb(nullptr);
return dev2list(dev);
}
/**
* \brief Scan for XML/HTTP devices (broadcast)
*
* \param us_timeout Scan timeout
*
* \return Device list
*/
inline static devices_t devicesXMLHTTP(useconds_t us_timeout) {
nutscan_xml_t xml_sec;
nutscan_device_t * dev;
::memset(&xml_sec, 0, sizeof(xml_sec));
/* Set the default values for XML HTTP (run_xml()) */
xml_sec.port_http = 80;
xml_sec.port_udp = 4679;
xml_sec.usec_timeout = us_timeout;
xml_sec.peername = nullptr;
dev = ::nutscan_scan_xml_http_range(nullptr, nullptr, us_timeout, &xml_sec);
return dev2list(dev);
}
/**
* \brief Scan for NUT (pseudo-)devices
*
* \param start_ip Address range left border
* \param stop_ip Address range right border
* \param port Port
* \param us_timeout Device scan timeout
*
* \return Device list
*/
inline static devices_t devicesNUT(
const std::string & start_ip,
const std::string & stop_ip,
const std::string & port,
useconds_t us_timeout)
{
nutscan_device_t * dev = ::nutscan_scan_nut(
start_ip.c_str(), stop_ip.c_str(), port.c_str(), us_timeout);
return dev2list(dev);
}
/**
* \brief Scan for Avahi devices
*
* \param us_timeout Scan timeout
*
* \return Device list
*/
inline static devices_t devicesAvahi(useconds_t us_timeout) {
nutscan_device_t * dev = ::nutscan_scan_avahi(us_timeout);
return dev2list(dev);
}
/**
* \brief Scan for IPMI devices
*
* \return Device list
*/
static devices_t devicesIPMI(
const std::string & start_ip,
const std::string & stop_ip,
const IPMIAttributes & attrs);
/**
* \brief Scan for Eaton serial devices
*
* \param ports List of serial ports
*
* \return Device list
*/
static devices_t devicesEatonSerial(const std::list<std::string> & ports);
}; // end of class NutScanner
NutScanner::InitFinal NutScanner::s_init_final;
NutScanner::Device::options_t NutScanner::Device::createOptions(nutscan_options_t * opt) {
options_t options;
// Create options
for (; nullptr != opt; opt = opt->next) {
assert(nullptr != opt->option);
options.insert(
options_t::value_type(opt->option,
nullptr != opt->value ? opt->value : ""));
}
return options;
}
NutScanner::Device::Device(nutscan_device_t * dev):
type(nutscan_device_type_string(dev->type)),
driver(nullptr != dev->driver ? dev->driver : ""),
port(nullptr != dev->port ? dev->port : ""),
options(createOptions(dev->opt))
{}
NutScanner::devices_t NutScanner::dev2list(nutscan_device_t * dev_list) {
devices_t list;
nutscan_device_t * dev = dev_list;
for (; dev != nullptr; dev = dev->next) {
// Skip devices of type NONE
// TBD: This happens with the serial scan on an invalid device
// Should be fixed in libnutscan I think
if (TYPE_NONE == dev->type)
continue;
list.push_back(Device(dev));
}
::nutscan_free_device(dev_list);
return list;
}
NutScanner::devices_t NutScanner::devicesSNMP(
const std::string & start_ip,
const std::string & stop_ip,
useconds_t us_timeout,
const SNMPAttributes & attrs)
{
nutscan_snmp_t snmp_attrs;
::memset(&snmp_attrs, 0, sizeof(snmp_attrs));
// TBD: const casting is necessery
// Shouldn't the nutscan_snmp_t items be constant?
if (!attrs.community.empty())
snmp_attrs.community = const_cast<char *>(attrs.community.c_str());
if (!attrs.sec_level.empty())
snmp_attrs.secLevel = const_cast<char *>(attrs.sec_level.c_str());
if (!attrs.sec_name.empty())
snmp_attrs.secName = const_cast<char *>(attrs.sec_name.c_str());
if (!attrs.auth_passwd.empty())
snmp_attrs.authPassword = const_cast<char *>(attrs.auth_passwd.c_str());
if (!attrs.priv_passwd.empty())
snmp_attrs.privPassword = const_cast<char *>(attrs.priv_passwd.c_str());
if (!attrs.auth_proto.empty())
snmp_attrs.authProtocol = const_cast<char *>(attrs.auth_proto.c_str());
if (!attrs.priv_proto.empty())
snmp_attrs.privProtocol = const_cast<char *>(attrs.priv_proto.c_str());
if (!attrs.peer_name.empty())
snmp_attrs.peername = const_cast<char *>(attrs.peer_name.c_str());
nutscan_device_t * dev = ::nutscan_scan_snmp(
start_ip.c_str(), stop_ip.c_str(), us_timeout, &snmp_attrs);
return dev2list(dev);
}
NutScanner::devices_t NutScanner::devicesIPMI(
const std::string & start_ip,
const std::string & stop_ip,
const IPMIAttributes & attrs)
{
nutscan_ipmi_t ipmi_attrs;
::memset(&ipmi_attrs, 0, sizeof(ipmi_attrs));
// TBD: const casting is necessary
// Shouldn't the nutscan_ipmi_t C-string items be constant?
if (!attrs.username.empty())
ipmi_attrs.username = const_cast<char *>(attrs.username.c_str());
if (!attrs.passwd.empty())
ipmi_attrs.password = const_cast<char *>(attrs.passwd.c_str());
ipmi_attrs.authentication_type = attrs.auth_type;
ipmi_attrs.cipher_suite_id = attrs.cipher_suite_id;
if (!attrs.K_g_BMC_key.empty())
ipmi_attrs.K_g_BMC_key = const_cast<char *>(attrs.K_g_BMC_key.c_str());
ipmi_attrs.privilege_level = attrs.priv_level;
ipmi_attrs.workaround_flags = attrs.wa_flags;
ipmi_attrs.ipmi_version = attrs.version;
nutscan_device_t * dev = ::nutscan_scan_ipmi(
start_ip.c_str(), stop_ip.c_str(), &ipmi_attrs);
return dev2list(dev);
}
NutScanner::devices_t NutScanner::devicesEatonSerial(const std::list<std::string> & ports) {
std::string port_list;
std::list<std::string>::const_iterator port = ports.begin();
while (port != ports.end()) {
port_list += *port;
++port;
if (port == ports.end())
break;
port_list += ' ';
}
nutscan_device_t * dev = ::nutscan_scan_eaton_serial(port_list.c_str());
return dev2list(dev);
}
#endif // defined WITH_NUTSCANNER
/** nutconf tool specific options */
class NutConfOptions: public Options {
public:
/**
* \brief Option mode (getter/setter)
*
* The mode is typically used for options that act as a value (info)
* getter when specified without arguments while if given arguments,
* it sets the value (info).
*/
typedef enum {
NOT_SPECIFIED, /**< Option not specified on command line */
GETTER, /**< Option is a getter */
SETTER, /**< Option is a setter */
} mode_t;
/** Listen address specification */
typedef std::pair<std::string, std::string> ListenAddrSpec;
/** Device specification */
struct DeviceSpec {
/** Device settings map */
typedef std::map<std::string, std::string> Map;
std::string id; /**< Device identifier */
Map settings; /**< Device settings */
}; // end of struct DeviceSpec
/** Notify flags specification */
typedef std::pair<bool, std::list<std::string> > NotifyFlagsSpec;
/** Notify flags specifications */
typedef std::map<std::string, NotifyFlagsSpec> NotifyFlagsSpecs;
/** Notify messages specifications */
typedef std::map<std::string, std::string> NotifyMsgSpecs;
/** User specification */
struct UserSpec {
std::string name; /**< Username */
std::string passwd; /**< Password */
std::list<std::string> actions; /**< Actions */
std::list<std::string> instcmds; /**< Instant commands */
}; // end of struct UserSpec
/** upsmon user specification */
struct UpsmonUserSpec: public UserSpec {
std::string mode; /**< upsmon mode (master/slave) */
}; // end of struct UpsmonUserSpec
/** User specification list */
typedef std::list<UserSpec *> UserSpecs;
private:
/** Unknown options */
List m_unknown;
/** Option specification errors */
std::list<std::string> m_errors;
/**
* \brief Option mode getter (including arguments for setters)
*
* \param[in] opt Option
* \param[out] args Option arguments
* \param[in] order Option order (1st by default)
*
* \retval NOT_SPECIFIED if the option was not specified on the command line
* \retval GETTER if the option has no arguments
* \retval SETTER otherwise (option specified with arguments)
*/
mode_t optMode(const std::string & opt, Arguments & args, size_t order = 0) const;
/**
* \brief Option mode getter
*
* \param opt Option
* \param order Option order (1st by default)
*
* \retval NOT_SPECIFIED if the option was not specified on the command line
* \retval GETTER if the option has no arguments
* \retval SETTER otherwise (option specified with arguments)
*/
mode_t optMode(const std::string & opt, size_t order = 0) const {
Arguments args;
return optMode(opt, args, order);
}
public:
/** Options are valid */
bool valid;
/** --autoconfigure */
bool autoconfigure;
/** --is-configured */
bool is_configured;
/** --local argument */
std::string local;
/** --system */
bool system;
/** --get-mode */
bool get_mode;
/** --set-mode argument */
std::string mode;
/** --{add|set}-monitor arguments (all the monitors) */
std::vector<std::string> monitors;
/** Set monitor options count */
size_t set_monitor_cnt;
/** Add monitor options count */
size_t add_monitor_cnt;
/** --{add|set}-listen arguments (all the addresses) */
std::vector<ListenAddrSpec> listen_addrs;
/** Set listen address options count */
size_t set_listen_cnt;
/** Add listen address options count */
size_t add_listen_cnt;
/** Device specifications */
std::vector<DeviceSpec> devices;
/** Set devices options count */
size_t set_device_cnt;
/** Add devices options count */
size_t add_device_cnt;
/** Notify flags specifications */
NotifyFlagsSpecs notify_flags;
/** Set notify flags options count */
size_t set_notify_flags_cnt;
/** Add notify flags options count */
size_t add_notify_flags_cnt;
/** Notify messages specifications */
NotifyMsgSpecs notify_msgs;
/** Set notify message options count */
size_t set_notify_msg_cnt;
/** Notify command */
std::string notify_cmd;
/** Shutdown command */
std::string shutdown_cmd;
/** Min. supplies */
std::string min_supplies;
/** Powerdown flag */
std::string powerdown_flag;
/** Users specifications */
UserSpecs users;
/** Set user options count */
size_t set_user_cnt;
/** Add user options count */
size_t add_user_cnt;
/** Verbosity level */
unsigned int verbose;
/** Scan NUT devices options count */
size_t scan_nut_cnt;
/** Scan USB devices */
bool scan_usb;
/** Scan xml_http_devices */
bool scan_xml_http;
/** Scan Avahi devices */
bool scan_avahi;
/** Scan IPMI devices */
size_t scan_ipmi_cnt;
/** Scan SNMP devices options count */
size_t scan_snmp_cnt;
/** Scan Eaton serial devices */
bool scan_serial;
/** Constructor */
NutConfOptions(char * const argv[], int argc);
/** Destructor */
~NutConfOptions();
/**
* \brief Report invalid options to STDERR
*
* BEWARE: throws an exception if options are valid.
* Check that using the \ref valid flag.
*/
void reportInvalid() const
#if (defined __cplusplus) && (__cplusplus < 201100)
throw(std::logic_error)
#endif
;
/**
* \brief Get NUT mode
*
* \return NUT mode (if --mode option was specified with an argument)
*/
inline std::string getMode() const {
Arguments args;
if (SETTER != optMode("mode", args))
return "";
assert(!args.empty());
return args.front();
}
/**
* \brief Get monitor definition
*
* \param[out] ups UPS name
* \param[out] host_port Host (possibly including port specification)
* \param[out] pwr_val Power value
* \param[out] user Username
* \param[out] passwd User password
* \param[out] mode Monitor mode
* \param[in] which Monitor order (1st by default)
*/
void getMonitor(
std::string & ups,
std::string & host_port,
std::string & pwr_val,
std::string & user,
std::string & passwd,
std::string & mode,
size_t which = 0) const
#if (defined __cplusplus) && (__cplusplus < 201100)
throw(std::range_error)
#endif
;
private:
/**
* \brief Check --mode argument validity
*
* \param mode Mode argument
*
* \retval true IFF the mode is set correctly
* \retval false otherwise
*/
static bool checkMode(const std::string & mode);
/**
* \brief Add another user specification
*
* The method is responsible for parsing --{set|add}-user option arguments
* and storing the user specification in \ref users list.
*
* \param args User specification (raw)
*/
void addUser(const Arguments & args);
}; // end of class NutConfOptions
NutConfOptions::mode_t NutConfOptions::optMode(const std::string & opt, Arguments & args, size_t order) const {
if (!getDouble(opt, args, order))
return NOT_SPECIFIED;
if (args.empty())
return GETTER;
return SETTER;
}
NutConfOptions::NutConfOptions(char * const argv[], int argc):
Options(argv, argc),
valid(true),
autoconfigure(false),
is_configured(false),
system(false),
get_mode(false),
set_monitor_cnt(0),
add_monitor_cnt(0),
set_listen_cnt(0),
add_listen_cnt(0),
set_device_cnt(0),
add_device_cnt(0),
set_notify_flags_cnt(0),
add_notify_flags_cnt(0),
set_notify_msg_cnt(0),
set_user_cnt(0),
add_user_cnt(0),
verbose(0),
scan_nut_cnt(0),
scan_usb(false),
scan_xml_http(false),
scan_avahi(false),
scan_ipmi_cnt(0),
scan_snmp_cnt(0),
scan_serial(false)
{
static const std::string sDash("-");
static const std::string dDash("--");
// Specify single-dashed options
List list = stringsSingle();
for (List::const_iterator opt = list.begin(); opt != list.end(); ++opt) {
// Known options
if ("v" == *opt) {
++verbose;
}
// Unknown option
else {
m_unknown.push_back(sDash + *opt);
}
}
// Specify double-dashed options
list = stringsDouble();
for (List::const_iterator opt = list.begin(); opt != list.end(); ++opt) {
// Known options
if ("autoconfigure" == *opt) {
if (autoconfigure)
m_errors.push_back("--autoconfigure option specified more than once");
else
autoconfigure = true;
}
else if ("is-configured" == *opt) {
if (is_configured)
m_errors.push_back("--is-configured option specified more than once");
else
is_configured = true;
}
else if ("local" == *opt) {
Arguments args;
if (!local.empty())
m_errors.push_back("--local option specified more than once");
else if (NutConfOptions::SETTER != optMode("local", args))
m_errors.push_back("--local option requires an argument");
else if (args.size() > 1)
m_errors.push_back("Only one directory may be specified with the --local option");
else
local = args.front();
}
else if ("system" == *opt) {
if (system)
m_errors.push_back("--system option specified more than once");
else
system = true;
}
else if ("get-mode" == *opt) {
if (get_mode)
m_errors.push_back("--get-mode option specified more than once");
else
get_mode = true;
}
else if ("set-mode" == *opt) {
Arguments args;
if (!mode.empty())
m_errors.push_back("--set-mode option specified more than once");
else if (NutConfOptions::SETTER != optMode(*opt, args))
m_errors.push_back("--set-mode option requires an argument");
else if (args.size() > 1)
m_errors.push_back("Only one argument allowed for the --set-mode option");
else if (args.size() == 1 && !checkMode(args.front()))
m_errors.push_back("Unknown NUT mode: \"" + args.front() + "\"");
else
mode = args.front();
}
else if ("set-monitor" == *opt || "add-monitor" == *opt) {
size_t * cnt = ('s' == (*opt)[0] ? &set_monitor_cnt : &add_monitor_cnt);
Arguments args;
if (NutConfOptions::SETTER != optMode(*opt, args, *cnt))
m_errors.push_back("--" + *opt + " option requires arguments");
else if (args.size() != 6)
m_errors.push_back("--" + *opt + " option requires exactly 6 arguments");
else
for (Arguments::const_iterator arg = args.begin(); arg != args.end(); ++arg)
monitors.push_back(*arg);
++*cnt;
}
else if ("set-listen" == *opt || "add-listen" == *opt) {
size_t * cnt = ('s' == (*opt)[0] ? &set_listen_cnt : &add_listen_cnt);
Arguments args;
if (NutConfOptions::SETTER != optMode(*opt, args, *cnt))
m_errors.push_back("--" + *opt + " option requires arguments");
else if (args.size() < 1 || args.size() > 2)
m_errors.push_back("--" + *opt + " option requires 1 or 2 arguments");
else {
ListenAddrSpec addr_port(args.front(), args.size() > 1 ? args.back() : "");
listen_addrs.push_back(addr_port);
}
++*cnt;
}
else if ("set-device" == *opt || "add-device" == *opt) {
size_t * cnt = ('s' == (*opt)[0] ? &set_device_cnt : &add_device_cnt);
Arguments args;
if (NutConfOptions::SETTER != optMode(*opt, args, *cnt))
m_errors.push_back("--" + *opt + " option requires arguments");
else if (args.size() < 3)
m_errors.push_back("--" + *opt + " option requires at least 3 arguments");
else {
DeviceSpec dev;
Arguments::const_iterator arg = args.begin();
assert(args.size() >= 3);
dev.id = *arg++;
dev.settings["driver"] = *arg++;
dev.settings["port"] = *arg++;
for (; arg != args.end(); ++arg) {
size_t eq_pos = (*arg).find('=');
if (std::string::npos == eq_pos)
m_errors.push_back("--" + *opt +
" option extra argument '" +
*arg + "' is illegal");
else
dev.settings[(*arg).substr(0, eq_pos)] =
(*arg).substr(eq_pos + 1);
}
devices.push_back(dev);
}
++*cnt;
}
else if ("set-notifyflags" == *opt || "add-notifyflags" == *opt) {
bool set = 's' == (*opt)[0];
size_t * cnt = (set ? &set_notify_flags_cnt : &add_notify_flags_cnt);
Arguments args;
if (NutConfOptions::SETTER != optMode(*opt, args, *cnt))
m_errors.push_back("--" + *opt + " option requires arguments");
else if (args.size() < 2)
m_errors.push_back("--" + *opt + " option requires at least 2 arguments");
else {
Arguments::const_iterator arg = args.begin();
const std::string & type = *arg++;
NotifyFlagsSpecs::iterator flags = notify_flags.lower_bound(type);
if (flags != notify_flags.end() && flags->first == type)
m_errors.push_back(
"--" + *opt + " option: conflicting specifications " +
"for notification type " + type);
else {
flags = notify_flags.insert(flags,
NotifyFlagsSpecs::value_type(
type,
NotifyFlagsSpec(set, std::list<std::string>())));
for (; arg != args.end(); ++arg)
flags->second.second.push_back(*arg);
}
}
++*cnt;
}
else if ("set-notifymsg" == *opt) {
Arguments args;
if (NutConfOptions::SETTER != optMode(*opt, args, set_notify_msg_cnt))
m_errors.push_back("--" + *opt + " option requires arguments");
else if (args.size() != 2) {
m_errors.push_back("--" + *opt + " option requires 2 arguments");
m_errors.push_back(" (perhaps you need to quote the message?)");
}
else {
notify_msgs[args.front()] = args.back();
}
++set_notify_msg_cnt;
}
else if ("set-notifycmd" == *opt) {
Arguments args;
if (!notify_cmd.empty())
m_errors.push_back("--set-notifycmd option specified more than once");
else if (NutConfOptions::SETTER != optMode("set-notifycmd", args))
m_errors.push_back("--set-notifycmd option requires an argument");
else if (args.size() > 1) {
m_errors.push_back("Too many arguments for the --set-notifycmd option");
m_errors.push_back(" (perhaps you need to quote the command?)");
}
else
notify_cmd = args.front();
}
else if ("set-shutdowncmd" == *opt) {
Arguments args;
if (!shutdown_cmd.empty())
m_errors.push_back("--set-shutdowncmd option specified more than once");
else if (NutConfOptions::SETTER != optMode("set-shutdowncmd", args))
m_errors.push_back("--set-shutdowncmd option requires an argument");
else if (args.size() > 1) {
m_errors.push_back("Too many arguments for the --set-shutdowncmd option");
m_errors.push_back(" (perhaps you need to quote the command?)");
}
else
shutdown_cmd = args.front();
}
else if ("set-minsupplies" == *opt) {
Arguments args;
if (!min_supplies.empty())
m_errors.push_back("--set-minsupplies option specified more than once");
else if (NutConfOptions::SETTER != optMode("set-minsupplies", args))
m_errors.push_back("--set-minsupplies option requires an argument");
else if (args.size() > 1) {
m_errors.push_back("Too many arguments for the --set-minsupplies option");
}
else
min_supplies = args.front();
}
else if ("set-powerdownflag" == *opt) {
Arguments args;
if (!powerdown_flag.empty())
m_errors.push_back("--set-powerdownflag option specified more than once");
else if (NutConfOptions::SETTER != optMode("set-powerdownflag", args))
m_errors.push_back("--set-powerdownflag option requires an argument");
else if (args.size() > 1) {
m_errors.push_back("Too many arguments for the --set-powerdownflag option");
}
else
powerdown_flag = args.front();
}
else if ("set-user" == *opt || "add-user" == *opt) {
size_t * cnt = ('s' == (*opt)[0] ? &set_user_cnt : &add_user_cnt);
Arguments args;
if (NutConfOptions::SETTER != optMode(*opt, args, *cnt))
m_errors.push_back("--" + *opt + " option requires arguments");
else
addUser(args);
++*cnt;
}
else if ("verbose" == *opt) {
++verbose;
}
#if (defined WITH_NUTSCANNER)
#if (defined WITH_USB)
else if ("scan-usb" == *opt) {
if (scan_usb)
m_errors.push_back("--scan-usb option specified more than once");
else
scan_usb = true;
}
#endif // defined WITH_USB
else if ("scan-nut" == *opt) {
Arguments args;
getDouble(*opt, args, scan_nut_cnt);
if (args.size() < 3)
m_errors.push_back("--scan-nut option requires at least 3 arguments");
else if (args.size() > 4)
m_errors.push_back("--scan-nut option requires at most 4 arguments");
++scan_nut_cnt;
}
#if (defined WITH_NEON)
else if ("scan-xml-http" == *opt) {
if (scan_xml_http)
m_errors.push_back("--scan-xml-http option specified more than once");
else {
Arguments args;
getDouble(*opt, args);
if (args.size() > 1)
m_errors.push_back("--scan-xml-http option accepts only one argument");
scan_xml_http = true;
}
}
#endif // defined WITH_NEON
#if (defined WITH_AVAHI)
else if ("scan-avahi" == *opt) {
if (scan_avahi)
m_errors.push_back("--scan-avahi option specified more than once");
else {
Arguments args;
getDouble(*opt, args);
if (args.size() > 1)
m_errors.push_back("--scan-avahi option accepts only one argument");
scan_avahi = true;
}
}
#endif // defined WITH_AVAHI
#if (defined WITH_IPMI)
else if ("scan-ipmi" == *opt) {
Arguments args;
getDouble(*opt, args, scan_ipmi_cnt);
if (args.size() < 2)
m_errors.push_back("--scan-ipmi option requires at least 2 arguments");
++scan_ipmi_cnt;
}
#endif // defined WITH_IPMI
#if (defined WITH_SNMP)
else if ("scan-snmp" == *opt) {
Arguments args;
getDouble(*opt, args, scan_snmp_cnt);
if (args.size() < 2)
m_errors.push_back("--scan-snmp option requires at least 2 arguments");
++scan_snmp_cnt;
}
#endif // defined WITH_SNMP
else if ("scan-serial" == *opt) {
if (scan_serial)
m_errors.push_back("--scan-serial option specified more than once");
else
scan_serial = true;
}
#endif // defined WITH_NUTSCANNER)
// Unknown option
else {
m_unknown.push_back(dDash + *opt);
}
}
// Options are valid IFF we know all of them
// and there are no direct binary arguments
valid = m_unknown.empty() && m_errors.empty() && get().empty();
// --set-monitor and --add-monitor are mutually exclusive
if (set_monitor_cnt > 0 && add_monitor_cnt > 0) {
m_errors.push_back("--set-monitor and --add-monitor options can't both be specified");
valid = false;
}
// --set-listen and --add-listen are mutually exclusive
if (set_listen_cnt > 0 && add_listen_cnt > 0) {
m_errors.push_back("--set-listen and --add-listen options can't both be specified");
valid = false;
}
// --set-device and --add-device are mutually exclusive
if (set_device_cnt > 0 && add_device_cnt > 0) {
m_errors.push_back("--set-device and --add-device options can't both be specified");
valid = false;
}
// --set-user and --add-user are mutually exclusive
if (set_user_cnt > 0 && add_user_cnt > 0) {
m_errors.push_back("--set-user and --add-user options can't both be specified");
valid = false;
}
}
NutConfOptions::~NutConfOptions() {
UserSpecs::iterator user = users.begin();
for (; user != users.end(); ++user) {
delete *user;
*user = nullptr;
}
}
void NutConfOptions::reportInvalid() const
#if (defined __cplusplus) && (__cplusplus < 201100)
throw(std::logic_error)
#endif
{
if (valid)
throw std::logic_error("No invalid options to report");
List::const_iterator unknown_opt = m_unknown.begin();
for (; unknown_opt != m_unknown.end(); ++unknown_opt) {
std::cerr << "Unknown option: " << *unknown_opt << std::endl;
}
std::list<std::string>::const_iterator error = m_errors.begin();
for (; error != m_errors.end(); ++error) {
std::cerr << "Option error: " << *error << std::endl;
}
// No direct arguments expected
const Arguments & args = get();
Arguments::const_iterator arg = args.begin();
for (; arg != args.end(); ++arg) {
std::cerr << "Unexpected argument: " << *arg << std::endl;
}
}
bool NutConfOptions::checkMode(const std::string & mode) {
if ("standalone" == mode) return true;
if ("netserver" == mode) return true;
if ("netclient" == mode) return true;
if ("controlled" == mode) return true;
if ("manual" == mode) return true;
if ("none" == mode) return true;
return false;
}
/**
* \brief Automatically destroyed dynamic object pointer
*
* The template class is useful in situation where you need to
* create a dynamic object, process its attributes and automatically
* destroy it in case of error simply by leaving the scope
* (i.e. not having to worry about calling \c delete by hand).
*/
template <typename T>
class autodelete_ptr {
private:
T * m_impl;
/** Cleanup */
inline void cleanup() {
if (nullptr != m_impl)
delete m_impl;
m_impl = nullptr;
}
public:
/** Constructor (unset) */
autodelete_ptr(): m_impl(nullptr) {}
/** Constructor */
autodelete_ptr(T * ptr): m_impl(ptr) {}
/** Setter */
inline autodelete_ptr & operator = (T * ptr) {
cleanup();
m_impl = ptr;
return *this;
}
/** Pointer accessor */
inline operator T * () const { return m_impl; }
/** Pointer accessor */
inline T * operator -> () const { return m_impl; }
/** Pointer overtake (invalidates the object) */
inline T * give() {
T * ptr = m_impl;
m_impl = nullptr;
return ptr;
}
/** Destructor */
~autodelete_ptr() {
cleanup();
}
private:
/** Copying is forbidden */
autodelete_ptr(const autodelete_ptr & orig) {
NUT_UNUSED_VARIABLE(orig);
}
/** Assignment is forbidden */
autodelete_ptr & operator = (const autodelete_ptr & orig) {
NUT_UNUSED_VARIABLE(orig);
}
}; // end of template class autodelete_ptr
void NutConfOptions::addUser(const Options::Arguments & args) {
assert(args.size() > 0);
Arguments::const_iterator arg_iter = args.begin();
// Create new user specification
autodelete_ptr<UserSpec> user;
const std::string & name = *arg_iter;
// upsmon user (apparently)
// Note that we use pragmatic do ... while (0) loop to enable break
do if (name.size() >= 6 && name.substr(0, 6) == "upsmon") {
if (6 == name.size()) {
m_errors.push_back("upsmon user specification requires monitor mode");
return;
}
// Fall-through to ordinary user specification
if ('=' != name[6])
break;
UpsmonUserSpec * upsmon_user = new UpsmonUserSpec;
upsmon_user->name = "upsmon";
upsmon_user->mode = name.substr(7);
user = upsmon_user;
} while (0); // end of pragmatic do ... while (0) loop
// Ordinary user
if (nullptr == user) {
user = new UserSpec;
user->name = name;
}
assert(nullptr != user);
// Set user attributes
bool errors = false;
for (++arg_iter; arg_iter != args.end(); ++arg_iter) {
const std::string & arg = *arg_iter;
size_t eq_pos = arg.find('=');
if (std::string::npos == eq_pos) {
m_errors.push_back("Illegal user attribute specification: \"" + arg + '"');
errors = true;
continue;
}
const std::string attr = arg.substr(0, eq_pos);
const std::string val = arg.substr(eq_pos + 1);
if ("password" == attr)
user->passwd = val;
else if ("actions" == attr)
user->actions.push_back(val);
else if ("instcmds" == attr)
user->instcmds.push_back(val);
else {
m_errors.push_back("Unknown user attribute: \"" + attr + '"');
errors = true;
}
}
if (errors)
return;
// Store user specification
users.push_back(user.give());
}
void NutConfOptions::getMonitor(
std::string & ups,
std::string & host_port,
std::string & pwr_val,
std::string & user,
std::string & passwd,
std::string & mode_arg,
size_t which) const
#if (defined __cplusplus) && (__cplusplus < 201100)
throw(std::range_error)
#endif
{
if (which >= monitors.size() / 6)
throw std::range_error("INTERNAL ERROR: monitors index overflow");
size_t base_idx = 6 * which;
assert(monitors.size() >= base_idx + 6);
ups = monitors[base_idx];
host_port = monitors[base_idx + 1];
pwr_val = monitors[base_idx + 2];
user = monitors[base_idx + 3];
passwd = monitors[base_idx + 4];
mode_arg = monitors[base_idx + 5];
}
/**
* \brief Sources configuration object from file (if exists)
*
* If the file doesn't exist, the conf. object is unchanged
* (and the result is indicated by the return value).
* If the file exists, but can't be parsed, an error is reported
* and the execution is terminated.
*
* \param config Configuration object
* \param file_name File name
*
* \retval true if the configuration file was sourced
* \retval false if the file doesn't exist
*/
static bool source(nut::Serialisable * config, const std::string & file_name) {
nut::NutFile file(file_name);
if (!file.exists())
return false;
file.openx();
bool parsed_ok = config->parseFrom(file);
file.closex();
if (parsed_ok)
return true;
std::cerr << "Error: Failed to parse " << file_name << std::endl;
::exit(1);
}
/**
* \brief Store configuration object to file
*
* If the file exists, it's rewritten.
*
* \param config Configuration object
* \param file_name File name
*/
static void store(nut::Serialisable * config, const std::string & file_name) {
nut::NutFile file(file_name, nut::NutFile::WRITE_ONLY);
bool written_ok = config->writeTo(file);
file.closex();
if (written_ok)
return;
std::cerr << "Error: Failed to write " << file_name << std::endl;
::exit(1);
}
/**
* \brief Check whether NUT was configured
*
* \param etc Configuration directory
*
* \retval true IFF nut.conf exists and MODE != none
* \retval false otherwise
*/
static bool isConfigured(const std::string & etc) {
nut::NutFile nut_conf_file(etc + "/nut.conf");
if (!nut_conf_file.exists())
return false;
nut_conf_file.openx();
nut::NutConfiguration nut_conf;
nut_conf.parseFrom(nut_conf_file);
return
nut::NutConfiguration::MODE_UNKNOWN != nut_conf.mode &&
nut::NutConfiguration::MODE_NONE != nut_conf.mode;
}
/**
* \brief Transform monitor specification
*
* Transform monitor specification from cmd. line to monitor configuration.
*
* \param i Monitor index
* \param options nutconf options
*
* \return Monitor configuration
*/
static nut::UpsmonConfiguration::Monitor monitor(
size_t i,
const NutConfOptions & options)
{
nut::UpsmonConfiguration::Monitor monitor;
std::string host_port, pwr_val, mode;
options.getMonitor(
monitor.upsname, host_port, pwr_val,
monitor.username, monitor.password, mode,
i);
// Parse host[:port]
unsigned short port = 0;
size_t colon_idx = host_port.rfind(':');
if (std::string::npos != colon_idx) {
std::stringstream ss(host_port.substr(colon_idx + 1));
if ((ss >> port).fail()) {
std::cerr
<< "Error: failed to parse host specification \""
<< host_port << '"' << std::endl;
::exit(1);
}
}
// Parse power value
unsigned int power_value;
std::stringstream ss(pwr_val);
if ((ss >> power_value).fail()) {
std::cerr
<< "Error: failed to parse power value \""
<< pwr_val << '"' << std::endl;
::exit(1);
}
monitor.hostname = host_port.substr(0, colon_idx);
monitor.port = port;
monitor.powerValue = power_value;
monitor.isPrimary = ("primary" == mode || "master" == mode);
return monitor;
}
/**
* \brief NUT mode getter
*
* \param etc Configuration directory
*
* \return NUT mode (as string)
*/
static std::string getMode(const std::string & etc) {
std::string nut_conf_file(etc + "/nut.conf");
std::stringstream e;
nut::NutConfiguration nut_conf;
// Source previous configuration
source(&nut_conf, nut_conf_file);
nut::NutConfiguration::NutMode mode = nut_conf.mode;
switch (mode) {
case nut::NutConfiguration::MODE_UNKNOWN: return "unknown";
case nut::NutConfiguration::MODE_NONE: return "none";
case nut::NutConfiguration::MODE_STANDALONE: return "standalone";
case nut::NutConfiguration::MODE_NETSERVER: return "netserver";
case nut::NutConfiguration::MODE_NETCLIENT: return "netclient";
case nut::NutConfiguration::MODE_CONTROLLED: return "controlled";
case nut::NutConfiguration::MODE_MANUAL: return "manual";
#if (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH_POP) && ( (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_COVERED_SWITCH_DEFAULT) || (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE) )
# pragma GCC diagnostic push
#endif
#ifdef HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_COVERED_SWITCH_DEFAULT
# pragma GCC diagnostic ignored "-Wcovered-switch-default"
#endif
#ifdef HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE
# pragma GCC diagnostic ignored "-Wunreachable-code"
#endif
/* Older CLANG (e.g. clang-3.4) seems to not support the GCC pragmas above */
#ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunreachable-code"
# pragma clang diagnostic ignored "-Wcovered-switch-default"
#endif
default:
break;
}
e << "INTERNAL ERROR: Unknown NUT mode: " << mode;
throw std::logic_error(e.str());
#ifdef __clang__
# pragma clang diagnostic pop
#endif
#if (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH_POP) && ( (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_COVERED_SWITCH_DEFAULT) || (defined HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_UNREACHABLE_CODE) )
# pragma GCC diagnostic pop
#endif
}
/**
* \brief NUT mode setter
*
* \param mode Mode
* \param etc Configuration directory
*/
static void setMode(const std::string & mode, const std::string & etc) {
std::string nut_conf_file(etc + "/nut.conf");
nut::NutConfiguration nut_conf;
// Source previous configuration (if any)
source(&nut_conf, nut_conf_file);
// Set mode
nut_conf.mode = nut::NutConfiguration::NutModeFromString(mode);
// Store configuration
store(&nut_conf, nut_conf_file);
}
/**
* \brief Set monitors in upsmon.conf
*
* \param monitors Monitor list
* \param etc Configuration directory
* \param keep_ex Keep existing entries (discard by default)
*/
static void setMonitors(
const std::list<nut::UpsmonConfiguration::Monitor> & monitors,
const std::string & etc, bool keep_ex = false)
{
std::string upsmon_conf_file(etc + "/upsmon.conf");
nut::UpsmonConfiguration upsmon_conf;
// Source previous configuration (if any)
source(&upsmon_conf, upsmon_conf_file);
// Remove existing monitors (unless we want to keep them)
if (!keep_ex)
upsmon_conf.monitors.clear();
// Add monitors to the current ones (if any)
std::list<nut::UpsmonConfiguration::Monitor>::const_iterator
monitor = monitors.begin();
for (; monitor != monitors.end(); ++monitor)
upsmon_conf.monitors.push_back(*monitor);
// Store configuration
store(&upsmon_conf, upsmon_conf_file);
}
/**
* \brief Transform listen address specification
*
* Transform listen address specification from cmd. line to listen address configuration.
*
* \param i Listen address index
* \param options nutconf options
*
* \return Listen address configuration
*/
static nut::UpsdConfiguration::Listen listenAddr(
size_t i,
const NutConfOptions & options)
{
nut::UpsdConfiguration::Listen listen_addr;
const NutConfOptions::ListenAddrSpec & addr_spec = options.listen_addrs[i];
listen_addr.address = addr_spec.first;
// Parse port
if (!addr_spec.second.empty()) {
unsigned short port = 0;
std::stringstream ss(addr_spec.second);
if ((ss >> port).fail()) {
std::cerr
<< "Error: failed to parse port specification \""
<< addr_spec.second << '"' << std::endl;
::exit(1);
}
listen_addr.port = port;
}
return listen_addr;
}
/**
* \brief Set listen addresses in upsd.conf
*
* \param listen_addrs Address list
* \param etc Configuration directory
* \param keep_ex Keep existing entries (discard by default)
*/
static void setListenAddrs(
const std::list<nut::UpsdConfiguration::Listen> & listen_addrs,
const std::string & etc, bool keep_ex = false)
{
std::string upsd_conf_file(etc + "/upsd.conf");
nut::UpsdConfiguration upsd_conf;
// Source previous configuration (if any)
source(&upsd_conf, upsd_conf_file);
// Remove existing listen addresses (unless we want to keep them)
if (!keep_ex)
upsd_conf.listens.clear();
// Add listen addresses to the current ones (if any)
std::list<nut::UpsdConfiguration::Listen>::const_iterator
listen = listen_addrs.begin();
for (; listen != listen_addrs.end(); ++listen)
upsd_conf.listens.push_back(*listen);
// Store configuration
store(&upsd_conf, upsd_conf_file);
}
/**
* \brief Set devices in ups.conf
*
* \param devices Device list
* \param etc Configuration directory
* \param keep_ex Keep existing entries (discard by default)
*/
static void setDevices(
const std::vector<NutConfOptions::DeviceSpec> & devices,
const std::string & etc, bool keep_ex = false)
{
std::string ups_conf_file(etc + "/ups.conf");
nut::UpsConfiguration ups_conf;
// Source previous configuration (if any)
source(&ups_conf, ups_conf_file);
// Remove existing devices (unless we want to keep them)
if (!keep_ex) {
nut::UpsConfiguration::SectionMap::iterator
ups = ups_conf.sections.begin();
for (; ups != ups_conf.sections.end(); ++ups) {
// Keep global section
if (ups->first.empty())
continue;
ups_conf.sections.erase(ups);
}
}
// Add devices to the current ones (if any)
std::vector<NutConfOptions::DeviceSpec>::const_iterator
dev = devices.begin();
for (; dev != devices.end(); ++dev) {
const std::string & id = (*dev).id;
NutConfOptions::DeviceSpec::Map::const_iterator
setting = (*dev).settings.begin();
for (; setting != (*dev).settings.end(); ++setting)
ups_conf.setKey(id, setting->first, setting->second);
}
// Store configuration
store(&ups_conf, ups_conf_file);
}
/**
* \brief Set notify flags in upsmon.conf
*
* \param flags Notify flags specifications
* \param etc Configuration directory
*/
static void setNotifyFlags(
const NutConfOptions::NotifyFlagsSpecs & flags,
const std::string & etc)
{
std::string upsmon_conf_file(etc + "/upsmon.conf");
nut::UpsmonConfiguration upsmon_conf;
// Source previous configuration (if any)
source(&upsmon_conf, upsmon_conf_file);
NutConfOptions::NotifyFlagsSpecs::const_iterator specs = flags.begin();
for (; specs != flags.end(); ++specs) {
// Resolve notification type
nut::UpsmonConfiguration::NotifyType type =
nut::UpsmonConfiguration::NotifyTypeFromString(specs->first);
if (nut::UpsmonConfiguration::NOTIFY_TYPE_MAX == type) {
std::cerr
<< "Error: failed to parse notification type specification \""
<< specs->first << '"' << std::endl;
::exit(1);
}
nut::Settable<unsigned int> & sum =
upsmon_conf.notifyFlags[type];
// Clear current flags (unless we want to keep them)
if (specs->second.first || !sum.set())
sum = nut::UpsmonConfiguration::NOTIFY_IGNORE;
// Assemble flags
std::list<std::string>::const_iterator spec = specs->second.second.begin();
for (; spec != specs->second.second.end(); ++spec) {
nut::UpsmonConfiguration::NotifyFlag flag =
nut::UpsmonConfiguration::NotifyFlagFromString(*spec);
sum |= static_cast<unsigned int>(flag);
}
}
// Store configuration
store(&upsmon_conf, upsmon_conf_file);
}
/**
* \brief Set notify messages in upsmon.conf
*
* \param msgs Notify messages specifications
* \param etc Configuration directory
*/
static void setNotifyMsgs(
const NutConfOptions::NotifyMsgSpecs & msgs,
const std::string & etc)
{
std::string upsmon_conf_file(etc + "/upsmon.conf");
nut::UpsmonConfiguration upsmon_conf;
// Source previous configuration (if any)
source(&upsmon_conf, upsmon_conf_file);
NutConfOptions::NotifyMsgSpecs::const_iterator spec = msgs.begin();
for (; spec != msgs.end(); ++spec) {
// Resolve notification type
nut::UpsmonConfiguration::NotifyType type =
nut::UpsmonConfiguration::NotifyTypeFromString(spec->first);
if (nut::UpsmonConfiguration::NOTIFY_TYPE_MAX == type) {
std::cerr
<< "Error: failed to parse notification type specification \""
<< spec->first << '"' << std::endl;
::exit(1);
}
// Set message
upsmon_conf.notifyMessages[type] = spec->second;
}
// Store configuration
store(&upsmon_conf, upsmon_conf_file);
}
/**
* \brief Set notify command in upsmon.conf
*
* \param cmd Notify command
* \param etc Configuration directory
*/
static void setNotifyCmd(const std::string & cmd, const std::string & etc)
{
std::string upsmon_conf_file(etc + "/upsmon.conf");
nut::UpsmonConfiguration upsmon_conf;
// Source previous configuration (if any)
source(&upsmon_conf, upsmon_conf_file);
upsmon_conf.notifyCmd = cmd;
// Store configuration
store(&upsmon_conf, upsmon_conf_file);
}
/**
* \brief Set shutdown command in upsmon.conf
*
* \param cmd Shutdown command
* \param etc Configuration directory
*/
static void setShutdownCmd(const std::string & cmd, const std::string & etc)
{
std::string upsmon_conf_file(etc + "/upsmon.conf");
nut::UpsmonConfiguration upsmon_conf;
// Source previous configuration (if any)
source(&upsmon_conf, upsmon_conf_file);
upsmon_conf.shutdownCmd = cmd;
// Store configuration
store(&upsmon_conf, upsmon_conf_file);
}
/**
* \brief Set minimum of power supplies in upsmon.conf
*
* \param min_supplies Minimum of power supplies
* \param etc Configuration directory
*/
static void setMinSupplies(const std::string & min_supplies, const std::string & etc) {
std::string upsmon_conf_file(etc + "/upsmon.conf");
nut::UpsmonConfiguration upsmon_conf;
// Source previous configuration (if any)
source(&upsmon_conf, upsmon_conf_file);
unsigned int min;
std::stringstream ss(min_supplies);
if ((ss >> min).fail()) {
std::cerr
<< "Error: invalid min. power supplies specification: \""
<< min_supplies << '"' << std::endl;
::exit(1);
}
upsmon_conf.minSupplies = min;
// Store configuration
store(&upsmon_conf, upsmon_conf_file);
}
/**
* \brief Set powerdown flag file in upsmon.conf
*
* \param powerdown_flag Powerdown flag file
* \param etc Configuration directory
*/
static void setPowerdownFlag(const std::string & powerdown_flag, const std::string & etc) {
std::string upsmon_conf_file(etc + "/upsmon.conf");
nut::UpsmonConfiguration upsmon_conf;
// Source previous configuration (if any)
source(&upsmon_conf, upsmon_conf_file);
upsmon_conf.powerDownFlag = powerdown_flag;
// Store configuration
store(&upsmon_conf, upsmon_conf_file);
}
/**
* \brief Set users in upsd.users
*
* \param users User list
* \param etc Configuration directory
* \param keep_ex Keep existing entries (discard by default)
*/
static void setUsers(
const NutConfOptions::UserSpecs & users,
const std::string & etc, bool keep_ex = false)
{
std::string upsd_users_file(etc + "/upsd.users");
nut::UpsdUsersConfiguration upsd_users;
// Source previous configuration (if any)
source(&upsd_users, upsd_users_file);
// Remove existing users (unless we want to keep them)
if (!keep_ex) {
nut::UpsdUsersConfiguration::SectionMap::iterator
user = upsd_users.sections.begin();
for (; user != upsd_users.sections.end(); ++user) {
// Keep global section
if (user->first.empty())
continue;
upsd_users.sections.erase(user);
}
}
// Set/add users and/or their attributes
NutConfOptions::UserSpecs::const_iterator
user_iter = users.begin();
for (; user_iter != users.end(); ++user_iter) {
const NutConfOptions::UserSpec * user = *user_iter;
const std::string & username = user->name;
// Set password
if (!user->passwd.empty())
upsd_users.setPassword(username, user->passwd);
// Set actions
std::list<std::string>::const_iterator action = user->actions.begin();
for (; action != user->actions.end(); ++action)
upsd_users.addActions(username, nut::ConfigParamList(1, *action));
// Set instant commands
std::list<std::string>::const_iterator cmd = user->instcmds.begin();
for (; cmd != user->instcmds.end(); ++cmd)
upsd_users.addInstantCommands(username, nut::ConfigParamList(1, *cmd));
// upsmon user-specific settings
if ("upsmon" == username) {
const NutConfOptions::UpsmonUserSpec * upsmon_user =
static_cast<const NutConfOptions::UpsmonUserSpec *>(user);
// Set upsmon mode
nut::UpsdUsersConfiguration::upsmon_mode_t mode =
nut::UpsdUsersConfiguration::UPSMON_UNDEF;
if ("primary" == upsmon_user->mode || "master" == upsmon_user->mode)
mode = nut::UpsdUsersConfiguration::UPSMON_PRIMARY;
else if ("secondary" == upsmon_user->mode || "slave" == upsmon_user->mode)
mode = nut::UpsdUsersConfiguration::UPSMON_SECONDARY;
else {
std::cerr
<< "Error: Invalid upsmon mode specification: \""
<< upsmon_user->mode << '"' << std::endl;
::exit(1);
}
upsd_users.setUpsmonMode(mode);
}
}
// Store configuration
store(&upsd_users, upsd_users_file);
}
#if (defined WITH_NUTSCANNER)
/**
* \brief Print devices info
*
* \param devices Device list
* \param verbose Verbosity level
*/
static void printDevicesInfo(const NutScanner::devices_t & devices, unsigned int verbose = 0) {
NutScanner::devices_t::const_iterator dev_iter = devices.begin();
nut::GenericConfiguration devices_conf;
unsigned int dev_no = 1;
for (; dev_iter != devices.end(); ++dev_iter, ++dev_no) {
const NutScanner::Device & dev = *dev_iter;
// Print just plain list
if (verbose == 0)
std::cout
<< dev.type << ' '
<< dev.driver << ' '
<< dev.port << std::endl;
// Assemble full info
else {
std::stringstream name;
name << "device_type_" << dev.type << "_no_";
name.width(3);
name.fill('0');
name << dev_no;
nut::GenericConfigSection & device_conf = devices_conf[name.str()];
device_conf.name = name.str();
// Set driver
nut::GenericConfigSectionEntry & driver = device_conf["driver"];
driver.name = "driver";
driver.values.push_back(dev.driver);
// Set port
nut::GenericConfigSectionEntry & port = device_conf["port"];
port.name = "port";
port.values.push_back(dev.port);
// Set options
NutScanner::Device::options_t::const_iterator
opt = dev.options.begin();
for (; opt != dev.options.end(); ++opt) {
nut::GenericConfigSectionEntry & option = device_conf[opt->first];
option.name = opt->first;
option.values.push_back(opt->second);
}
}
}
// Print full info
if (0 != verbose) {
nut::NutMemory info;
devices_conf.writeTo(info);
std::string info_str;
assert(nut::NutStream::NUTS_OK == info.getString(info_str));
std::cout << info_str;
}
}
/**
* \brief Scan for SNMP devices
*
* \param options Options
*/
static void scanSNMPdevices(const NutConfOptions & options) {
for (size_t i = 0; ; ++i) {
NutConfOptions::Arguments args;
bool ok = options.getDouble("scan-snmp", args, i);
if (!ok) break;
// Sanity checks
assert(args.size() >= 2);
NutConfOptions::Arguments::const_iterator arg = args.begin();
const std::string & start_ip = *arg++;
const std::string & stop_ip = *arg++;
// TBD: where should we get the default?
useconds_t us_timeout = 1000000;
NutScanner::SNMPAttributes attrs;
// Parse <attr>=<val> pairs
bool errors = false;
for (; arg != args.end(); ++arg) {
size_t eq_pos = (*arg).find('=');
if (std::string::npos == eq_pos) {
std::cerr
<< "Error: Invalid SNMP attribute specification: \""
<< *arg << '"' << std::endl;
errors = true;
continue;
}
std::string attr = (*arg).substr(0, eq_pos);
std::string val = (*arg).substr(eq_pos + 1);
if ("timeout" == attr) {
std::stringstream ss(val);
if ((ss >> us_timeout).fail()) {
std::cerr
<< "Error: Invalid SNMP timeout specification: \""
<< val << '"' << std::endl;
errors = true;
continue;
}
}
else if ("community" == attr) {
attrs.community = val;
}
else if ("sec-level" == attr) {
attrs.sec_level = val;
}
else if ("sec-name" == attr) {
attrs.sec_name = val;
}
else if ("auth-password" == attr) {
attrs.auth_passwd = val;
}
else if ("priv-password" == attr) {
attrs.priv_passwd = val;
}
else if ("auth-protocol" == attr) {
attrs.auth_proto = val;
}
else if ("priv-protocol" == attr) {
attrs.priv_proto = val;
}
else if ("peer-name" == attr) {
attrs.peer_name = val;
}
else {
std::cerr
<< "Error: Unknown SNMP attribute: \""
<< attr << '"' << std::endl;
errors = true;
}
}
if (errors) continue;
NutScanner::devices_t devices = NutScanner::devicesSNMP(
start_ip, stop_ip, us_timeout, attrs);
printDevicesInfo(devices, options.verbose);
}
}
/**
* \brief Scan for USB devices
*
* \param options Options
*/
static void scanUSBdevices(const NutConfOptions & options) {
NutScanner::devices_t devices = NutScanner::devicesUSB();
printDevicesInfo(devices, options.verbose);
}
/**
* \brief Scan for NUT devices
*
* \param options Options
*/
static void scanNUTdevices(const NutConfOptions & options) {
for (size_t i = 0; ; ++i) {
NutConfOptions::Arguments args;
bool ok = options.getDouble("scan-nut", args, i);
if (!ok) break;
// Sanity checks
assert(args.size() >= 3);
NutConfOptions::Arguments::const_iterator arg = args.begin();
const std::string & start_ip = *arg++;
const std::string & stop_ip = *arg++;
const std::string & port = *arg++;
// TBD: where should we get the default?
useconds_t us_timeout = 1000000;
if (arg != args.end()) {
std::stringstream ss(*arg);
ss >> us_timeout;
}
NutScanner::devices_t devices = NutScanner::devicesNUT(
start_ip, stop_ip, port, us_timeout);
printDevicesInfo(devices, options.verbose);
}
}
/**
* \brief Scan for XML/HTTP devices
*
* \param options Options
*/
static void scanXMLHTTPdevices(const NutConfOptions & options) {
NutConfOptions::Arguments args;
bool ok = options.getDouble("scan-xml-http", args);
// Sanity checks
assert(ok);
// TBD: where should we get the default?
useconds_t us_timeout = 1000000;
if (!args.empty()) {
std::stringstream ss(args.front());
ss >> us_timeout;
}
NutScanner::devices_t devices = NutScanner::devicesXMLHTTP(us_timeout);
printDevicesInfo(devices, options.verbose);
}
/**
* \brief Scan for Avahi devices
*
* \param options Options
*/
static void scanAvahiDevices(const NutConfOptions & options) {
NutConfOptions::Arguments args;
bool ok = options.getDouble("scan-avahi", args);
// Sanity checks
assert(ok);
// TBD: where should we get the default?
useconds_t us_timeout = 1000000;
if (!args.empty()) {
std::stringstream ss(args.front());
ss >> us_timeout;
}
NutScanner::devices_t devices = NutScanner::devicesAvahi(us_timeout);
printDevicesInfo(devices, options.verbose);
}
/**
* \brief Scan for IPMI devices
*
* \param options Options
*/
static void scanIPMIdevices(const NutConfOptions & options) {
for (size_t i = 0; ; ++i) {
NutConfOptions::Arguments args;
bool ok = options.getDouble("scan-ipmi", args, i);
if (!ok) break;
// Sanity checks
assert(args.size() >= 2);
NutConfOptions::Arguments::const_iterator arg = args.begin();
const std::string & start_ip = *arg++;
const std::string & stop_ip = *arg++;
NutScanner::IPMIAttributes attrs;
// Parse <attr>=<val> pairs
bool errors = false;
for (; arg != args.end(); ++arg) {
size_t eq_pos = (*arg).find('=');
if (std::string::npos == eq_pos) {
std::cerr
<< "Error: Invalid IPMI attribute specification: \""
<< *arg << '"' << std::endl;
errors = true;
continue;
}
std::string attr = (*arg).substr(0, eq_pos);
std::string val = (*arg).substr(eq_pos + 1);
if ("username" == attr) {
attrs.username = val;
}
else if ("password" == attr) {
attrs.passwd = val;
}
else if ("auth-type" == attr) {
if ("none" == val)
attrs.auth_type = IPMI_AUTHENTICATION_TYPE_NONE;
else if ("MD2" == val)
attrs.auth_type = IPMI_AUTHENTICATION_TYPE_MD2;
else if ("MD5" == val)
attrs.auth_type = IPMI_AUTHENTICATION_TYPE_MD5;
else if ("plain-password" == val)
attrs.auth_type = IPMI_AUTHENTICATION_TYPE_STRAIGHT_PASSWORD_KEY;
else if ("OEM" == val)
attrs.auth_type = IPMI_AUTHENTICATION_TYPE_OEM_PROP;
else if ("RMCPplus" == val)
attrs.auth_type = IPMI_AUTHENTICATION_TYPE_RMCPPLUS;
else {
std::cerr
<< "Error: Invalid IPMI auth. type: \""
<< val << '"' << std::endl;
errors = true;
continue;
}
}
else if ("cipher-suite-id" == attr) {
std::stringstream ss(val);
if ((ss >> attrs.cipher_suite_id).fail()) {
std::cerr
<< "Error: Invalid IPMI cipher suite ID: \""
<< val << '"' << std::endl;
errors = true;
continue;
}
}
else if ("K-g-BMC-key" == attr) {
attrs.K_g_BMC_key = val;
}
else if ("priv-level" == attr) {
std::stringstream ss(val);
if ((ss >> attrs.priv_level).fail()) {
std::cerr
<< "Error: Invalid IPMI priv. level: \""
<< val << '"' << std::endl;
errors = true;
continue;
}
}
else if ("workaround-flags" == attr) {
std::stringstream ss(val);
if ((ss >> attrs.wa_flags).fail()) {
std::cerr
<< "Error: Invalid IPMI workaround flags: \""
<< val << '"' << std::endl;
errors = true;
continue;
}
}
else if ("version" == attr) {
if ("1.5" == val)
attrs.version = IPMI_1_5;
else if ("2.0" == val)
attrs.version = IPMI_2_0;
else {
std::cerr
<< "Error: Unsupported IPMI version "
<< val << std::endl;
errors = true;
continue;
}
}
else {
std::cerr
<< "Error: Unknown IPMI attribute: \""
<< attr << '"' << std::endl;
errors = true;
}
}
if (errors) continue;
NutScanner::devices_t devices = NutScanner::devicesIPMI(
start_ip, stop_ip, attrs);
printDevicesInfo(devices, options.verbose);
}
}
/**
* \brief Scan for serial devices devices
*
* \param options Options
*/
static void scanSerialDevices(const NutConfOptions & options) {
NutConfOptions::Arguments args;
bool ok = options.getDouble("scan-serial", args);
// Sanity checks
assert(ok);
NutScanner::devices_t devices = NutScanner::devicesEatonSerial(args);
printDevicesInfo(devices, options.verbose);
}
#endif // defined WITH_NUTSCANNER
/**
* \brief Main routine (exceptions unsafe)
*
* \param argc Argument count
* \param argv Arguments
*
* \return 0 always (exits on error)
*/
static int mainx(int argc, char * const argv[]) {
const char *prog = xbasename(argv[0]);
char *s = nullptr;
// Get options
NutConfOptions options(argv, argc);
// Usage
if (options.exists("help") || options.existsSingle("h")) {
Usage::print(prog);
::exit(0);
}
// Usage
if (options.exists("version") || options.existsSingle("V")) {
Usage::printVersion(prog);
::exit(0);
}
// Check that command-line options validity
if (!options.valid) {
options.reportInvalid();
Usage::print(argv[0]);
::exit(1);
}
// Set configuration directory
std::string etc(CONFPATH);
s = ::getenv("NUT_CONFPATH");
if (s != nullptr && !options.system)
etc = s;
if (!options.local.empty()) {
etc = options.local;
}
// Check configuration directory availability
nut::NutFile etc_dir(etc);
if (!etc_dir.exists()) {
std::cerr << "Error: Configuration directory " << etc << " isn't available" << std::endl;
::exit(1);
}
// --is-configured query
if (options.is_configured) {
bool is_configured = isConfigured(etc);
std::cout << (is_configured ? "true" : "false") << std::endl;
::exit(is_configured ? 0 : 1);
}
// --get-mode
if (options.get_mode) {
std::cout << getMode(etc) << std::endl;
}
// --set-mode
if (!options.mode.empty()) {
setMode(options.mode, etc);
}
// Monitors were set
if (!options.monitors.empty()) {
std::list<nut::UpsmonConfiguration::Monitor> monitors;
for (size_t n = options.monitors.size() / 6, i = 0; i < n; ++i) {
monitors.push_back(monitor(i, options));
}
setMonitors(monitors, etc, options.add_monitor_cnt > 0);
}
// Listen addresses were set
if (!options.listen_addrs.empty()) {
std::list<nut::UpsdConfiguration::Listen> listen_addrs;
for (size_t i = 0; i < options.listen_addrs.size(); ++i) {
listen_addrs.push_back(listenAddr(i, options));
}
setListenAddrs(listen_addrs, etc, options.add_listen_cnt > 0);
}
// Devices were set
if (!options.devices.empty()) {
setDevices(options.devices, etc, options.add_device_cnt > 0);
}
// Notify flags were set
if (!options.notify_flags.empty()) {
setNotifyFlags(options.notify_flags, etc);
}
// Notify messages were set
if (!options.notify_msgs.empty()) {
setNotifyMsgs(options.notify_msgs, etc);
}
// Notify command was set
if (!options.notify_cmd.empty()) {
setNotifyCmd(options.notify_cmd, etc);
}
// Shutdown command was set
if (!options.shutdown_cmd.empty()) {
setShutdownCmd(options.shutdown_cmd, etc);
}
// Min. of power supplies was set
if (!options.min_supplies.empty()) {
setMinSupplies(options.min_supplies, etc);
}
// Powerdown flag file was set
if (!options.powerdown_flag.empty()) {
setPowerdownFlag(options.powerdown_flag, etc);
}
// Users were set
if (!options.users.empty()) {
setUsers(options.users, etc, options.add_user_cnt > 0);
}
#if (defined WITH_NUTSCANNER)
// SNMP devices scan
if (options.scan_snmp_cnt) {
scanSNMPdevices(options);
}
// USB devices scan
if (options.scan_usb) {
scanUSBdevices(options);
}
// NUT devices scan
if (options.scan_nut_cnt) {
scanNUTdevices(options);
}
// XML/HTTP devices scan
if (options.scan_xml_http) {
scanXMLHTTPdevices(options);
}
// Avahi devices scan
if (options.scan_avahi) {
scanAvahiDevices(options);
}
// IPMI devices scan
if (options.scan_ipmi_cnt) {
scanIPMIdevices(options);
}
// Serial devices scan
if (options.scan_serial) {
scanSerialDevices(options);
}
#endif // defined WITH_NUTSCANNER
return 0;
}
/**
* \brief Main routine exception-safe wrapper
*
* Exceptions should never leak...
*
* \param argc Argument count
* \param argv Arguments
*/
int main(int argc, char * const argv[]) {
try {
return mainx(argc, argv);
}
catch (const std::exception & e) {
std::cerr
<< "Error: " << e.what() << std::endl;
}
catch (...) {
std::cerr
<< "INTERNAL ERROR: exception of unknown origin caught" << std::endl
<< "Please issue a bug report to nut-upsdev@lists.alioth.debian.org"
<< std::endl;
}
::exit(128);
}
|