1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600
|
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 1999 - 2006, Digium, Inc.
*
* Mark Spencer <markster@digium.com>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
*
* \brief The Asterisk Management Interface - AMI
*
* \author Mark Spencer <markster@digium.com>
*
* OpenSSL http://www.openssl.org - for AMI/SSL
*
* At the moment this file contains a number of functions, namely:
*
* - data structures storing AMI state
* - AMI-related API functions, used by internal asterisk components
* - handlers for AMI-related CLI functions
* - handlers for AMI functions (available through the AMI socket)
* - the code for the main AMI listener thread and individual session threads
* - the http handlers invoked for AMI-over-HTTP by the threads in main/http.c
*
* \ref amiconf
*/
/*! \li \ref manager.c uses the configuration file \ref manager.conf and \ref users.conf
* \addtogroup configuration_file
*/
/*! \page manager.conf manager.conf
* \verbinclude manager.conf.sample
*/
/*! \page users.conf users.conf
* \verbinclude users.conf.sample
*/
/*** MODULEINFO
<support_level>core</support_level>
***/
#include "asterisk.h"
#include "asterisk/paths.h" /* use various ast_config_AST_* */
#include <ctype.h>
#include <sys/time.h>
#include <signal.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <regex.h>
#include "asterisk/channel.h"
#include "asterisk/file.h"
#include "asterisk/manager.h"
#include "asterisk/module.h"
#include "asterisk/config.h"
#include "asterisk/callerid.h"
#include "asterisk/lock.h"
#include "asterisk/cli.h"
#include "asterisk/app.h"
#include "asterisk/pbx.h"
#include "asterisk/md5.h"
#include "asterisk/acl.h"
#include "asterisk/utils.h"
#include "asterisk/tcptls.h"
#include "asterisk/http.h"
#include "asterisk/ast_version.h"
#include "asterisk/threadstorage.h"
#include "asterisk/linkedlists.h"
#include "asterisk/term.h"
#include "asterisk/astobj2.h"
#include "asterisk/features.h"
#include "asterisk/security_events.h"
#include "asterisk/aoc.h"
#include "asterisk/strings.h"
#include "asterisk/stringfields.h"
#include "asterisk/presencestate.h"
#include "asterisk/stasis_message_router.h"
#include "asterisk/stasis_channels.h"
#include "asterisk/stasis_bridges.h"
#include "asterisk/test.h"
#include "asterisk/json.h"
#include "asterisk/bridge.h"
#include "asterisk/features_config.h"
#include "asterisk/rtp_engine.h"
#include "asterisk/format_cache.h"
#include "asterisk/translate.h"
#include "asterisk/taskprocessor.h"
/*** DOCUMENTATION
<manager name="Ping" language="en_US">
<synopsis>
Keepalive command.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
</syntax>
<description>
<para>A 'Ping' action will ellicit a 'Pong' response. Used to keep the
manager connection open.</para>
</description>
</manager>
<manager name="Events" language="en_US">
<synopsis>
Control Event Flow.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="EventMask" required="true">
<enumlist>
<enum name="on">
<para>If all events should be sent.</para>
</enum>
<enum name="off">
<para>If no events should be sent.</para>
</enum>
<enum name="system,call,log,...">
<para>To select which flags events should have to be sent.</para>
</enum>
</enumlist>
</parameter>
</syntax>
<description>
<para>Enable/Disable sending of events to this manager client.</para>
</description>
</manager>
<manager name="Logoff" language="en_US">
<synopsis>
Logoff Manager.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
</syntax>
<description>
<para>Logoff the current manager session.</para>
</description>
<see-also>
<ref type="manager">Login</ref>
</see-also>
</manager>
<manager name="Login" language="en_US">
<synopsis>
Login Manager.
</synopsis>
<syntax>
<parameter name="ActionID">
<para>ActionID for this transaction. Will be returned.</para>
</parameter>
<parameter name="Username" required="true">
<para>Username to login with as specified in manager.conf.</para>
</parameter>
<parameter name="Secret">
<para>Secret to login with as specified in manager.conf.</para>
</parameter>
</syntax>
<description>
<para>Login Manager.</para>
</description>
<see-also>
<ref type="manager">Logoff</ref>
</see-also>
</manager>
<manager name="Challenge" language="en_US">
<synopsis>
Generate Challenge for MD5 Auth.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="AuthType" required="true">
<para>Digest algorithm to use in the challenge. Valid values are:</para>
<enumlist>
<enum name="MD5" />
</enumlist>
</parameter>
</syntax>
<description>
<para>Generate a challenge for MD5 authentication.</para>
</description>
</manager>
<manager name="Hangup" language="en_US">
<synopsis>
Hangup channel.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>The exact channel name to be hungup, or to use a regular expression, set this parameter to: /regex/</para>
<para>Example exact channel: SIP/provider-0000012a</para>
<para>Example regular expression: /^SIP/provider-.*$/</para>
</parameter>
<parameter name="Cause">
<para>Numeric hangup cause.</para>
</parameter>
</syntax>
<description>
<para>Hangup a channel.</para>
</description>
</manager>
<manager name="Status" language="en_US">
<synopsis>
List channel status.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="false">
<para>The name of the channel to query for status.</para>
</parameter>
<parameter name="Variables">
<para>Comma <literal>,</literal> separated list of variable to include.</para>
</parameter>
<parameter name="AllVariables">
<para>If set to "true", the Status event will include all channel variables for
the requested channel(s).</para>
<enumlist>
<enum name="true"/>
<enum name="false"/>
</enumlist>
</parameter>
</syntax>
<description>
<para>Will return the status information of each channel along with the
value for the specified channel variables.</para>
</description>
<responses>
<list-elements>
<xi:include xpointer="xpointer(/docs/managerEvent[@name='Status'])" />
</list-elements>
<xi:include xpointer="xpointer(/docs/managerEvent[@name='StatusComplete'])" />
</responses>
</manager>
<managerEvent language="en_US" name="Status">
<managerEventInstance class="EVENT_FLAG_CALL">
<synopsis>Raised in response to a Status command.</synopsis>
<syntax>
<parameter name="ActionID" required="false"/>
<channel_snapshot/>
<parameter name="Type">
<para>Type of channel</para>
</parameter>
<parameter name="DNID">
<para>Dialed number identifier</para>
</parameter>
<parameter name="EffectiveConnectedLineNum">
</parameter>
<parameter name="EffectiveConnectedLineName">
</parameter>
<parameter name="TimeToHangup">
<para>Absolute lifetime of the channel</para>
</parameter>
<parameter name="BridgeID">
<para>Identifier of the bridge the channel is in, may be empty if not in one</para>
</parameter>
<parameter name="Application">
<para>Application currently executing on the channel</para>
</parameter>
<parameter name="Data">
<para>Data given to the currently executing channel</para>
</parameter>
<parameter name="Nativeformats">
<para>Media formats the connected party is willing to send or receive</para>
</parameter>
<parameter name="Readformat">
<para>Media formats that frames from the channel are received in</para>
</parameter>
<parameter name="Readtrans">
<para>Translation path for media received in native formats</para>
</parameter>
<parameter name="Writeformat">
<para>Media formats that frames to the channel are accepted in</para>
</parameter>
<parameter name="Writetrans">
<para>Translation path for media sent to the connected party</para>
</parameter>
<parameter name="Callgroup">
<para>Configured call group on the channel</para>
</parameter>
<parameter name="Pickupgroup">
<para>Configured pickup group on the channel</para>
</parameter>
<parameter name="Seconds">
<para>Number of seconds the channel has been active</para>
</parameter>
</syntax>
<see-also>
<ref type="manager">Status</ref>
</see-also>
</managerEventInstance>
</managerEvent>
<managerEvent language="en_US" name="StatusComplete">
<managerEventInstance class="EVENT_FLAG_CALL">
<synopsis>Raised in response to a Status command.</synopsis>
<syntax>
<parameter name="Items">
<para>Number of Status events returned</para>
</parameter>
</syntax>
<see-also>
<ref type="manager">Status</ref>
</see-also>
</managerEventInstance>
</managerEvent>
<manager name="Setvar" language="en_US">
<synopsis>
Sets a channel variable or function value.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel">
<para>Channel to set variable for.</para>
</parameter>
<parameter name="Variable" required="true">
<para>Variable name, function or expression.</para>
</parameter>
<parameter name="Value" required="true">
<para>Variable or function value.</para>
</parameter>
</syntax>
<description>
<para>This command can be used to set the value of channel variables or dialplan
functions.</para>
<note>
<para>If a channel name is not provided then the variable is considered global.</para>
</note>
</description>
<see-also>
<ref type="manager">Getvar</ref>
</see-also>
</manager>
<manager name="Getvar" language="en_US">
<synopsis>
Gets a channel variable or function value.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel">
<para>Channel to read variable from.</para>
</parameter>
<parameter name="Variable" required="true">
<para>Variable name, function or expression.</para>
</parameter>
</syntax>
<description>
<para>Get the value of a channel variable or function return.</para>
<note>
<para>If a channel name is not provided then the variable is considered global.</para>
</note>
</description>
<see-also>
<ref type="manager">Setvar</ref>
</see-also>
</manager>
<manager name="GetConfig" language="en_US">
<synopsis>
Retrieve configuration.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Filename" required="true">
<para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
</parameter>
<parameter name="Category">
<para>Category in configuration file.</para>
</parameter>
<parameter name="Filter">
<para>A comma separated list of
<replaceable>name_regex</replaceable>=<replaceable>value_regex</replaceable>
expressions which will cause only categories whose variables match all expressions
to be considered. The special variable name <literal>TEMPLATES</literal>
can be used to control whether templates are included. Passing
<literal>include</literal> as the value will include templates
along with normal categories. Passing
<literal>restrict</literal> as the value will restrict the operation to
ONLY templates. Not specifying a <literal>TEMPLATES</literal> expression
results in the default behavior which is to not include templates.</para>
</parameter>
</syntax>
<description>
<para>This action will dump the contents of a configuration
file by category and contents or optionally by specified category only.
In the case where a category name is non-unique, a filter may be specified
to match only categories with matching variable values.</para>
</description>
<see-also>
<ref type="manager">GetConfigJSON</ref>
<ref type="manager">UpdateConfig</ref>
<ref type="manager">CreateConfig</ref>
<ref type="manager">ListCategories</ref>
</see-also>
</manager>
<manager name="GetConfigJSON" language="en_US">
<synopsis>
Retrieve configuration (JSON format).
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Filename" required="true">
<para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
</parameter>
<parameter name="Category">
<para>Category in configuration file.</para>
</parameter>
<parameter name="Filter">
<xi:include xpointer="xpointer(/docs/manager[@name='GetConfig']/syntax/parameter[@name='Filter']/para[1])" />
</parameter>
</syntax>
<description>
<para>This action will dump the contents of a configuration file by category
and contents in JSON format or optionally by specified category only.
This only makes sense to be used using rawman over the HTTP interface.
In the case where a category name is non-unique, a filter may be specified
to match only categories with matching variable values.</para>
</description>
<see-also>
<ref type="manager">GetConfig</ref>
<ref type="manager">UpdateConfig</ref>
<ref type="manager">CreateConfig</ref>
<ref type="manager">ListCategories</ref>
</see-also>
</manager>
<manager name="UpdateConfig" language="en_US">
<synopsis>
Update basic configuration.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="SrcFilename" required="true">
<para>Configuration filename to read (e.g. <filename>foo.conf</filename>).</para>
</parameter>
<parameter name="DstFilename" required="true">
<para>Configuration filename to write (e.g. <filename>foo.conf</filename>)</para>
</parameter>
<parameter name="Reload">
<para>Whether or not a reload should take place (or name of specific module).</para>
</parameter>
<parameter name="PreserveEffectiveContext">
<para>Whether the effective category contents should be preserved on template change. Default is true (pre 13.2 behavior).</para>
</parameter>
<parameter name="Action-000000">
<para>Action to take.</para>
<para>0's represent 6 digit number beginning with 000000.</para>
<enumlist>
<enum name="NewCat" />
<enum name="RenameCat" />
<enum name="DelCat" />
<enum name="EmptyCat" />
<enum name="Update" />
<enum name="Delete" />
<enum name="Append" />
<enum name="Insert" />
</enumlist>
</parameter>
<parameter name="Cat-000000">
<para>Category to operate on.</para>
<xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
</parameter>
<parameter name="Var-000000">
<para>Variable to work on.</para>
<xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
</parameter>
<parameter name="Value-000000">
<para>Value to work on.</para>
<xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
</parameter>
<parameter name="Match-000000">
<para>Extra match required to match line.</para>
<xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
</parameter>
<parameter name="Line-000000">
<para>Line in category to operate on (used with delete and insert actions).</para>
<xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
</parameter>
<parameter name="Options-000000">
<para>A comma separated list of action-specific options.</para>
<enumlist>
<enum name="NewCat"><para>One or more of the following... </para>
<enumlist>
<enum name="allowdups"><para>Allow duplicate category names.</para></enum>
<enum name="template"><para>This category is a template.</para></enum>
<enum name="inherit="template[,...]""><para>Templates from which to inherit.</para></enum>
</enumlist>
</enum>
</enumlist>
<para> </para>
<para>The following actions share the same options...</para>
<enumlist>
<enum name="RenameCat"/>
<enum name="DelCat"/>
<enum name="EmptyCat"/>
<enum name="Update"/>
<enum name="Delete"/>
<enum name="Append"/>
<enum name="Insert"><para> </para>
<enumlist>
<enum name="catfilter="<expression>[,...]""><para> </para>
<xi:include xpointer="xpointer(/docs/manager[@name='GetConfig']/syntax/parameter[@name='Filter']/para[1])" />
<para><literal>catfilter</literal> is most useful when a file
contains multiple categories with the same name and you wish to
operate on specific ones instead of all of them.</para>
</enum>
</enumlist>
</enum>
</enumlist>
<xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
</parameter>
</syntax>
<description>
<para>This action will modify, create, or delete configuration elements
in Asterisk configuration files.</para>
</description>
<see-also>
<ref type="manager">GetConfig</ref>
<ref type="manager">GetConfigJSON</ref>
<ref type="manager">CreateConfig</ref>
<ref type="manager">ListCategories</ref>
</see-also>
</manager>
<manager name="CreateConfig" language="en_US">
<synopsis>
Creates an empty file in the configuration directory.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Filename" required="true">
<para>The configuration filename to create (e.g. <filename>foo.conf</filename>).</para>
</parameter>
</syntax>
<description>
<para>This action will create an empty file in the configuration
directory. This action is intended to be used before an UpdateConfig
action.</para>
</description>
<see-also>
<ref type="manager">GetConfig</ref>
<ref type="manager">GetConfigJSON</ref>
<ref type="manager">UpdateConfig</ref>
<ref type="manager">ListCategories</ref>
</see-also>
</manager>
<manager name="ListCategories" language="en_US">
<synopsis>
List categories in configuration file.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Filename" required="true">
<para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
</parameter>
</syntax>
<description>
<para>This action will dump the categories in a given file.</para>
</description>
<see-also>
<ref type="manager">GetConfig</ref>
<ref type="manager">GetConfigJSON</ref>
<ref type="manager">UpdateConfig</ref>
<ref type="manager">CreateConfig</ref>
</see-also>
</manager>
<manager name="Redirect" language="en_US">
<synopsis>
Redirect (transfer) a call.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>Channel to redirect.</para>
</parameter>
<parameter name="ExtraChannel">
<para>Second call leg to transfer (optional).</para>
</parameter>
<parameter name="Exten" required="true">
<para>Extension to transfer to.</para>
</parameter>
<parameter name="ExtraExten">
<para>Extension to transfer extrachannel to (optional).</para>
</parameter>
<parameter name="Context" required="true">
<para>Context to transfer to.</para>
</parameter>
<parameter name="ExtraContext">
<para>Context to transfer extrachannel to (optional).</para>
</parameter>
<parameter name="Priority" required="true">
<para>Priority to transfer to.</para>
</parameter>
<parameter name="ExtraPriority">
<para>Priority to transfer extrachannel to (optional).</para>
</parameter>
</syntax>
<description>
<para>Redirect (transfer) a call.</para>
</description>
<see-also>
<ref type="manager">BlindTransfer</ref>
</see-also>
</manager>
<manager name="Atxfer" language="en_US">
<synopsis>
Attended transfer.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>Transferer's channel.</para>
</parameter>
<parameter name="Exten" required="true">
<para>Extension to transfer to.</para>
</parameter>
<parameter name="Context">
<para>Context to transfer to.</para>
</parameter>
</syntax>
<description>
<para>Attended transfer.</para>
</description>
<see-also>
<ref type="managerEvent">AttendedTransfer</ref>
</see-also>
</manager>
<manager name="CancelAtxfer" language="en_US">
<synopsis>
Cancel an attended transfer.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>The transferer channel.</para>
</parameter>
</syntax>
<description>
<para>Cancel an attended transfer. Note, this uses the configured cancel attended transfer
feature option (atxferabort) to cancel the transfer. If not available this action will fail.
</para>
</description>
<see-also>
<ref type="managerEvent">AttendedTransfer</ref>
</see-also>
</manager>
<manager name="Originate" language="en_US">
<synopsis>
Originate a call.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>Channel name to call.</para>
</parameter>
<parameter name="Exten">
<para>Extension to use (requires <literal>Context</literal> and
<literal>Priority</literal>)</para>
</parameter>
<parameter name="Context">
<para>Context to use (requires <literal>Exten</literal> and
<literal>Priority</literal>)</para>
</parameter>
<parameter name="Priority">
<para>Priority to use (requires <literal>Exten</literal> and
<literal>Context</literal>)</para>
</parameter>
<parameter name="Application">
<para>Application to execute.</para>
</parameter>
<parameter name="Data">
<para>Data to use (requires <literal>Application</literal>).</para>
</parameter>
<parameter name="Timeout" default="30000">
<para>How long to wait for call to be answered (in ms.).</para>
</parameter>
<parameter name="CallerID">
<para>Caller ID to be set on the outgoing channel.</para>
</parameter>
<parameter name="Variable">
<para>Channel variable to set, multiple Variable: headers are allowed.</para>
</parameter>
<parameter name="Account">
<para>Account code.</para>
</parameter>
<parameter name="EarlyMedia">
<para>Set to <literal>true</literal> to force call bridge on early media..</para>
</parameter>
<parameter name="Async">
<para>Set to <literal>true</literal> for fast origination.</para>
</parameter>
<parameter name="Codecs">
<para>Comma-separated list of codecs to use for this call.</para>
</parameter>
<parameter name="ChannelId">
<para>Channel UniqueId to be set on the channel.</para>
</parameter>
<parameter name="OtherChannelId">
<para>Channel UniqueId to be set on the second local channel.</para>
</parameter>
</syntax>
<description>
<para>Generates an outgoing call to a
<replaceable>Extension</replaceable>/<replaceable>Context</replaceable>/<replaceable>Priority</replaceable>
or <replaceable>Application</replaceable>/<replaceable>Data</replaceable></para>
</description>
<see-also>
<ref type="managerEvent">OriginateResponse</ref>
</see-also>
</manager>
<managerEvent language="en_US" name="OriginateResponse">
<managerEventInstance class="EVENT_FLAG_CALL">
<synopsis>Raised in response to an Originate command.</synopsis>
<syntax>
<parameter name="ActionID" required="false"/>
<parameter name="Response">
<enumlist>
<enum name="Failure"/>
<enum name="Success"/>
</enumlist>
</parameter>
<parameter name="Channel"/>
<parameter name="Context"/>
<parameter name="Exten"/>
<parameter name="Application"/>
<parameter name="Data"/>
<parameter name="Reason"/>
<parameter name="Uniqueid"/>
<parameter name="CallerIDNum"/>
<parameter name="CallerIDName"/>
</syntax>
<see-also>
<ref type="manager">Originate</ref>
</see-also>
</managerEventInstance>
</managerEvent>
<manager name="Command" language="en_US">
<synopsis>
Execute Asterisk CLI Command.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Command" required="true">
<para>Asterisk CLI command to run.</para>
</parameter>
</syntax>
<description>
<para>Run a CLI command.</para>
</description>
</manager>
<manager name="ExtensionState" language="en_US">
<synopsis>
Check Extension Status.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Exten" required="true">
<para>Extension to check state on.</para>
</parameter>
<parameter name="Context" required="true">
<para>Context for extension.</para>
</parameter>
</syntax>
<description>
<para>Report the extension state for given extension. If the extension has a hint,
will use devicestate to check the status of the device connected to the extension.</para>
<para>Will return an <literal>Extension Status</literal> message. The response will include
the hint for the extension and the status.</para>
</description>
<see-also>
<ref type="managerEvent">ExtensionStatus</ref>
</see-also>
</manager>
<manager name="PresenceState" language="en_US">
<synopsis>
Check Presence State
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Provider" required="true">
<para>Presence Provider to check the state of</para>
</parameter>
</syntax>
<description>
<para>Report the presence state for the given presence provider.</para>
<para>Will return a <literal>Presence State</literal> message. The response will include the
presence state and, if set, a presence subtype and custom message.</para>
</description>
<see-also>
<ref type="managerEvent">PresenceStatus</ref>
</see-also>
</manager>
<manager name="AbsoluteTimeout" language="en_US">
<synopsis>
Set absolute timeout.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>Channel name to hangup.</para>
</parameter>
<parameter name="Timeout" required="true">
<para>Maximum duration of the call (sec).</para>
</parameter>
</syntax>
<description>
<para>Hangup a channel after a certain time. Acknowledges set time with
<literal>Timeout Set</literal> message.</para>
</description>
</manager>
<manager name="MailboxStatus" language="en_US">
<synopsis>
Check mailbox.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Mailbox" required="true">
<para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
</parameter>
</syntax>
<description>
<para>Checks a voicemail account for status.</para>
<para>Returns whether there are messages waiting.</para>
<para>Message: Mailbox Status.</para>
<para>Mailbox: <replaceable>mailboxid</replaceable>.</para>
<para>Waiting: <literal>0</literal> if messages waiting, <literal>1</literal>
if no messages waiting.</para>
</description>
<see-also>
<ref type="manager">MailboxCount</ref>
</see-also>
</manager>
<manager name="MailboxCount" language="en_US">
<synopsis>
Check Mailbox Message Count.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Mailbox" required="true">
<para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
</parameter>
</syntax>
<description>
<para>Checks a voicemail account for new messages.</para>
<para>Returns number of urgent, new and old messages.</para>
<para>Message: Mailbox Message Count</para>
<para>Mailbox: <replaceable>mailboxid</replaceable></para>
<para>UrgentMessages: <replaceable>count</replaceable></para>
<para>NewMessages: <replaceable>count</replaceable></para>
<para>OldMessages: <replaceable>count</replaceable></para>
</description>
<see-also>
<ref type="manager">MailboxStatus</ref>
</see-also>
</manager>
<manager name="ListCommands" language="en_US">
<synopsis>
List available manager commands.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
</syntax>
<description>
<para>Returns the action name and synopsis for every action that
is available to the user.</para>
</description>
</manager>
<manager name="SendText" language="en_US">
<synopsis>
Send text message to channel.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>Channel to send message to.</para>
</parameter>
<parameter name="Message" required="true">
<para>Message to send.</para>
</parameter>
</syntax>
<description>
<para>Sends A Text Message to a channel while in a call.</para>
</description>
</manager>
<manager name="UserEvent" language="en_US">
<synopsis>
Send an arbitrary event.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="UserEvent" required="true">
<para>Event string to send.</para>
</parameter>
<parameter name="Header1">
<para>Content1.</para>
</parameter>
<parameter name="HeaderN">
<para>ContentN.</para>
</parameter>
</syntax>
<description>
<para>Send an event to manager sessions.</para>
</description>
<see-also>
<ref type="managerEvent">UserEvent</ref>
<ref type="application">UserEvent</ref>
</see-also>
</manager>
<manager name="WaitEvent" language="en_US">
<synopsis>
Wait for an event to occur.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Timeout" required="true">
<para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
</parameter>
</syntax>
<description>
<para>This action will ellicit a <literal>Success</literal> response. Whenever
a manager event is queued. Once WaitEvent has been called on an HTTP manager
session, events will be generated and queued.</para>
</description>
</manager>
<manager name="CoreSettings" language="en_US">
<synopsis>
Show PBX core settings (version etc).
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
</syntax>
<description>
<para>Query for Core PBX settings.</para>
</description>
</manager>
<manager name="CoreStatus" language="en_US">
<synopsis>
Show PBX core status variables.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
</syntax>
<description>
<para>Query for Core PBX status.</para>
</description>
</manager>
<manager name="Reload" language="en_US">
<synopsis>
Send a reload event.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Module">
<para>Name of the module to reload.</para>
</parameter>
</syntax>
<description>
<para>Send a reload event.</para>
</description>
<see-also>
<ref type="manager">ModuleLoad</ref>
</see-also>
</manager>
<managerEvent language="en_US" name="CoreShowChannel">
<managerEventInstance class="EVENT_FLAG_CALL">
<synopsis>Raised in response to a CoreShowChannels command.</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<channel_snapshot/>
<parameter name="BridgeId">
<para>Identifier of the bridge the channel is in, may be empty if not in one</para>
</parameter>
<parameter name="Application">
<para>Application currently executing on the channel</para>
</parameter>
<parameter name="ApplicationData">
<para>Data given to the currently executing application</para>
</parameter>
<parameter name="Duration">
<para>The amount of time the channel has existed</para>
</parameter>
</syntax>
<see-also>
<ref type="manager">CoreShowChannels</ref>
<ref type="managerEvent">CoreShowChannelsComplete</ref>
</see-also>
</managerEventInstance>
</managerEvent>
<managerEvent language="en_US" name="CoreShowChannelsComplete">
<managerEventInstance class="EVENT_FLAG_CALL">
<synopsis>Raised at the end of the CoreShowChannel list produced by the CoreShowChannels command.</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="EventList">
<para>Conveys the status of the command reponse list</para>
</parameter>
<parameter name="ListItems">
<para>The total number of list items produced</para>
</parameter>
</syntax>
<see-also>
<ref type="manager">CoreShowChannels</ref>
<ref type="managerEvent">CoreShowChannel</ref>
</see-also>
</managerEventInstance>
</managerEvent>
<manager name="CoreShowChannels" language="en_US">
<synopsis>
List currently active channels.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
</syntax>
<description>
<para>List currently defined channels and some information about them.</para>
</description>
<responses>
<list-elements>
<xi:include xpointer="xpointer(/docs/managerEvent[@name='CoreShowChannel'])" />
</list-elements>
<xi:include xpointer="xpointer(/docs/managerEvent[@name='CoreShowChannelsComplete'])" />
</responses>
</manager>
<manager name="LoggerRotate" language="en_US">
<synopsis>
Reload and rotate the Asterisk logger.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
</syntax>
<description>
<para>Reload and rotate the logger. Analogous to the CLI command 'logger rotate'.</para>
</description>
</manager>
<manager name="ModuleLoad" language="en_US">
<synopsis>
Module management.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Module">
<para>Asterisk module name (including .so extension) or subsystem identifier:</para>
<enumlist>
<enum name="cdr" />
<enum name="dnsmgr" />
<enum name="extconfig" />
<enum name="enum" />
<enum name="acl" />
<enum name="manager" />
<enum name="http" />
<enum name="logger" />
<enum name="features" />
<enum name="dsp" />
<enum name="udptl" />
<enum name="indications" />
<enum name="cel" />
<enum name="plc" />
</enumlist>
</parameter>
<parameter name="LoadType" required="true">
<para>The operation to be done on module. Subsystem identifiers may only
be reloaded.</para>
<enumlist>
<enum name="load" />
<enum name="unload" />
<enum name="reload" />
</enumlist>
<para>If no module is specified for a <literal>reload</literal> loadtype,
all modules are reloaded.</para>
</parameter>
</syntax>
<description>
<para>Loads, unloads or reloads an Asterisk module in a running system.</para>
</description>
<see-also>
<ref type="manager">Reload</ref>
<ref type="manager">ModuleCheck</ref>
</see-also>
</manager>
<manager name="ModuleCheck" language="en_US">
<synopsis>
Check if module is loaded.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Module" required="true">
<para>Asterisk module name (not including extension).</para>
</parameter>
</syntax>
<description>
<para>Checks if Asterisk module is loaded. Will return Success/Failure.
For success returns, the module revision number is included.</para>
</description>
<see-also>
<ref type="manager">ModuleLoad</ref>
</see-also>
</manager>
<manager name="AOCMessage" language="en_US">
<synopsis>
Generate an Advice of Charge message on a channel.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>Channel name to generate the AOC message on.</para>
</parameter>
<parameter name="ChannelPrefix">
<para>Partial channel prefix. By using this option one can match the beginning part
of a channel name without having to put the entire name in. For example
if a channel name is SIP/snom-00000001 and this value is set to SIP/snom, then
that channel matches and the message will be sent. Note however that only
the first matched channel has the message sent on it. </para>
</parameter>
<parameter name="MsgType" required="true">
<para>Defines what type of AOC message to create, AOC-D or AOC-E</para>
<enumlist>
<enum name="D" />
<enum name="E" />
</enumlist>
</parameter>
<parameter name="ChargeType" required="true">
<para>Defines what kind of charge this message represents.</para>
<enumlist>
<enum name="NA" />
<enum name="FREE" />
<enum name="Currency" />
<enum name="Unit" />
</enumlist>
</parameter>
<parameter name="UnitAmount(0)">
<para>This represents the amount of units charged. The ETSI AOC standard specifies that
this value along with the optional UnitType value are entries in a list. To accommodate this
these values take an index value starting at 0 which can be used to generate this list of
unit entries. For Example, If two unit entires were required this could be achieved by setting the
paramter UnitAmount(0)=1234 and UnitAmount(1)=5678. Note that UnitAmount at index 0 is
required when ChargeType=Unit, all other entries in the list are optional.
</para>
</parameter>
<parameter name="UnitType(0)">
<para>Defines the type of unit. ETSI AOC standard specifies this as an integer
value between 1 and 16, but this value is left open to accept any positive
integer. Like the UnitAmount parameter, this value represents a list entry
and has an index parameter that starts at 0.
</para>
</parameter>
<parameter name="CurrencyName">
<para>Specifies the currency's name. Note that this value is truncated after 10 characters.</para>
</parameter>
<parameter name="CurrencyAmount">
<para>Specifies the charge unit amount as a positive integer. This value is required
when ChargeType==Currency.</para>
</parameter>
<parameter name="CurrencyMultiplier">
<para>Specifies the currency multiplier. This value is required when ChargeType==Currency.</para>
<enumlist>
<enum name="OneThousandth" />
<enum name="OneHundredth" />
<enum name="OneTenth" />
<enum name="One" />
<enum name="Ten" />
<enum name="Hundred" />
<enum name="Thousand" />
</enumlist>
</parameter>
<parameter name="TotalType" default="Total">
<para>Defines what kind of AOC-D total is represented.</para>
<enumlist>
<enum name="Total" />
<enum name="SubTotal" />
</enumlist>
</parameter>
<parameter name="AOCBillingId">
<para>Represents a billing ID associated with an AOC-D or AOC-E message. Note
that only the first 3 items of the enum are valid AOC-D billing IDs</para>
<enumlist>
<enum name="Normal" />
<enum name="ReverseCharge" />
<enum name="CreditCard" />
<enum name="CallFwdUnconditional" />
<enum name="CallFwdBusy" />
<enum name="CallFwdNoReply" />
<enum name="CallDeflection" />
<enum name="CallTransfer" />
</enumlist>
</parameter>
<parameter name="ChargingAssociationId">
<para>Charging association identifier. This is optional for AOC-E and can be
set to any value between -32768 and 32767</para>
</parameter>
<parameter name="ChargingAssociationNumber">
<para>Represents the charging association party number. This value is optional
for AOC-E.</para>
</parameter>
<parameter name="ChargingAssociationPlan">
<para>Integer representing the charging plan associated with the ChargingAssociationNumber.
The value is bits 7 through 1 of the Q.931 octet containing the type-of-number and
numbering-plan-identification fields.</para>
</parameter>
</syntax>
<description>
<para>Generates an AOC-D or AOC-E message on a channel.</para>
</description>
<see-also>
<ref type="managerEvent">AOC-D</ref>
<ref type="managerEvent">AOC-E</ref>
</see-also>
</manager>
<function name="AMI_CLIENT" language="en_US">
<synopsis>
Checks attributes of manager accounts
</synopsis>
<syntax>
<parameter name="loginname" required="true">
<para>Login name, specified in manager.conf</para>
</parameter>
<parameter name="field" required="true">
<para>The manager account attribute to return</para>
<enumlist>
<enum name="sessions"><para>The number of sessions for this AMI account</para></enum>
</enumlist>
</parameter>
</syntax>
<description>
<para>
Currently, the only supported parameter is "sessions" which will return the current number of
active sessions for this AMI account.
</para>
</description>
</function>
<manager name="Filter" language="en_US">
<synopsis>
Dynamically add filters for the current manager session.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Operation">
<enumlist>
<enum name="Add">
<para>Add a filter.</para>
</enum>
</enumlist>
</parameter>
<parameter name="Filter">
<para>Filters can be whitelist or blacklist</para>
<para>Example whitelist filter: "Event: Newchannel"</para>
<para>Example blacklist filter: "!Channel: DAHDI.*"</para>
<para>This filter option is used to whitelist or blacklist events per user to be
reported with regular expressions and are allowed if both the regex matches
and the user has read access as defined in manager.conf. Filters are assumed to be for whitelisting
unless preceeded by an exclamation point, which marks it as being black.
Evaluation of the filters is as follows:</para>
<para>- If no filters are configured all events are reported as normal.</para>
<para>- If there are white filters only: implied black all filter processed first, then white filters.</para>
<para>- If there are black filters only: implied white all filter processed first, then black filters.</para>
<para>- If there are both white and black filters: implied black all filter processed first, then white
filters, and lastly black filters.</para>
</parameter>
</syntax>
<description>
<para>The filters added are only used for the current session.
Once the connection is closed the filters are removed.</para>
<para>This comand requires the system permission because
this command can be used to create filters that may bypass
filters defined in manager.conf</para>
</description>
<see-also>
<ref type="manager">FilterList</ref>
</see-also>
</manager>
<manager name="FilterList" language="en_US">
<synopsis>
Show current event filters for this session
</synopsis>
<description>
<para>The filters displayed are for the current session. Only those filters defined in
manager.conf will be present upon starting a new session.</para>
</description>
<see-also>
<ref type="manager">Filter</ref>
</see-also>
</manager>
<manager name="BlindTransfer" language="en_US">
<synopsis>
Blind transfer channel(s) to the given destination
</synopsis>
<syntax>
<parameter name="Channel" required="true">
</parameter>
<parameter name="Context">
</parameter>
<parameter name="Exten">
</parameter>
</syntax>
<description>
<para>Redirect all channels currently bridged to the specified channel to the specified destination.</para>
</description>
<see-also>
<ref type="manager">Redirect</ref>
<ref type="managerEvent">BlindTransfer</ref>
</see-also>
</manager>
<managerEvent name="ExtensionStatus" language="en_US">
<managerEventInstance class="EVENT_FLAG_CALL">
<synopsis>Raised when a hint changes due to a device state change.</synopsis>
<syntax>
<parameter name="Exten">
<para>Name of the extension.</para>
</parameter>
<parameter name="Context">
<para>Context that owns the extension.</para>
</parameter>
<parameter name="Hint">
<para>Hint set for the extension</para>
</parameter>
<parameter name="Status">
<para>Numerical value of the extension status. Extension
status is determined by the combined device state of all items
contained in the hint.</para>
<enumlist>
<enum name="-2">
<para>The extension was removed from the dialplan.</para>
</enum>
<enum name="-1">
<para>The extension's hint was removed from the dialplan.</para>
</enum>
<enum name="0">
<para><literal>Idle</literal> - Related device(s) are in an idle
state.</para>
</enum>
<enum name="1">
<para><literal>InUse</literal> - Related device(s) are in active
calls but may take more calls.</para>
</enum>
<enum name="2">
<para><literal>Busy</literal> - Related device(s) are in active
calls and may not take any more calls.</para>
</enum>
<enum name="4">
<para><literal>Unavailable</literal> - Related device(s) are
not reachable.</para>
</enum>
<enum name="8">
<para><literal>Ringing</literal> - Related device(s) are
currently ringing.</para>
</enum>
<enum name="9">
<para><literal>InUse&Ringing</literal> - Related device(s)
are currently ringing and in active calls.</para>
</enum>
<enum name="16">
<para><literal>Hold</literal> - Related device(s) are
currently on hold.</para>
</enum>
<enum name="17">
<para><literal>InUse&Hold</literal> - Related device(s)
are currently on hold and in active calls.</para>
</enum>
</enumlist>
</parameter>
<parameter name="StatusText">
<para>Text representation of <literal>Status</literal>.</para>
<enumlist>
<enum name="Idle" />
<enum name="InUse" />
<enum name="Busy" />
<enum name="Unavailable" />
<enum name="Ringing" />
<enum name="InUse&Ringing" />
<enum name="Hold" />
<enum name="InUse&Hold" />
<enum name="Unknown">
<para>Status does not match any of the above values.</para>
</enum>
</enumlist>
</parameter>
</syntax>
<see-also>
<ref type="manager">ExtensionState</ref>
</see-also>
</managerEventInstance>
</managerEvent>
<managerEvent name="PresenceStatus" language="en_US">
<managerEventInstance class="EVENT_FLAG_CALL">
<synopsis>Raised when a hint changes due to a presence state change.</synopsis>
<syntax>
<parameter name="Exten" />
<parameter name="Context" />
<parameter name="Hint" />
<parameter name="Status" />
<parameter name="Subtype" />
<parameter name="Message" />
</syntax>
<see-also>
<ref type="manager">PresenceState</ref>
</see-also>
</managerEventInstance>
</managerEvent>
***/
/*! \addtogroup Group_AMI AMI functions
*/
/*! @{
Doxygen group */
enum error_type {
UNKNOWN_ACTION = 1,
UNKNOWN_CATEGORY,
UNSPECIFIED_CATEGORY,
UNSPECIFIED_ARGUMENT,
FAILURE_ALLOCATION,
FAILURE_NEWCAT,
FAILURE_DELCAT,
FAILURE_EMPTYCAT,
FAILURE_UPDATE,
FAILURE_DELETE,
FAILURE_APPEND,
FAILURE_TEMPLATE
};
enum add_filter_result {
FILTER_SUCCESS,
FILTER_ALLOC_FAILED,
FILTER_COMPILE_FAIL,
};
/*!
* Linked list of events.
* Global events are appended to the list by append_event().
* The usecount is the number of stored pointers to the element,
* excluding the list pointers. So an element that is only in
* the list has a usecount of 0, not 1.
*
* Clients have a pointer to the last event processed, and for each
* of these clients we track the usecount of the elements.
* If we have a pointer to an entry in the list, it is safe to navigate
* it forward because elements will not be deleted, but only appended.
* The worst that can happen is seeing the pointer still NULL.
*
* When the usecount of an element drops to 0, and the element is the
* first in the list, we can remove it. Removal is done within the
* main thread, which is woken up for the purpose.
*
* For simplicity of implementation, we make sure the list is never empty.
*/
struct eventqent {
int usecount; /*!< # of clients who still need the event */
int category;
unsigned int seq; /*!< sequence number */
struct timeval tv; /*!< When event was allocated */
AST_RWLIST_ENTRY(eventqent) eq_next;
char eventdata[1]; /*!< really variable size, allocated by append_event() */
};
static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
static int displayconnects = 1;
static int allowmultiplelogin = 1;
static int timestampevents;
static int httptimeout = 60;
static int broken_events_action = 0;
static int manager_enabled = 0;
static int subscribed = 0;
static int webmanager_enabled = 0;
static int manager_debug = 0; /*!< enable some debugging code in the manager */
static int authtimeout;
static int authlimit;
static char *manager_channelvars;
#define DEFAULT_REALM "asterisk"
static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
static int unauth_sessions = 0;
static struct stasis_subscription *acl_change_sub;
/*! \brief A \ref stasis_topic that all topics AMI cares about will be forwarded to */
static struct stasis_topic *manager_topic;
/*! \brief The \ref stasis_message_router for all \ref stasis messages */
static struct stasis_message_router *stasis_router;
/*! \brief The \ref stasis_subscription for forwarding the RTP topic to the AMI topic */
static struct stasis_forward *rtp_topic_forwarder;
/*! \brief The \ref stasis_subscription for forwarding the Security topic to the AMI topic */
static struct stasis_forward *security_topic_forwarder;
#ifdef TEST_FRAMEWORK
/*! \brief The \ref stasis_subscription for forwarding the Test topic to the AMI topic */
static struct stasis_forward *test_suite_forwarder;
#endif
#define MGR_SHOW_TERMINAL_WIDTH 80
#define MAX_VARS 128
/*! \brief Fake event class used to end sessions at shutdown */
#define EVENT_FLAG_SHUTDOWN -1
/*! \brief
* Descriptor for a manager session, either on the AMI socket or over HTTP.
*
* \note
* AMI session have managerid == 0; the entry is created upon a connect,
* and destroyed with the socket.
* HTTP sessions have managerid != 0, the value is used as a search key
* to lookup sessions (using the mansession_id cookie, or nonce key from
* Digest Authentication http header).
*/
#define MAX_BLACKLIST_CMD_LEN 2
static const struct {
const char *words[AST_MAX_CMD_LEN];
} command_blacklist[] = {
{{ "module", "load", NULL }},
{{ "module", "unload", NULL }},
{{ "restart", "gracefully", NULL }},
};
static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
static void acl_change_stasis_subscribe(void)
{
if (!acl_change_sub) {
acl_change_sub = stasis_subscribe(ast_security_topic(),
acl_change_stasis_cb, NULL);
stasis_subscription_accept_message_type(acl_change_sub, ast_named_acl_change_type());
stasis_subscription_set_filter(acl_change_sub, STASIS_SUBSCRIPTION_FILTER_SELECTIVE);
}
}
static void acl_change_stasis_unsubscribe(void)
{
acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
}
/* In order to understand what the heck is going on with the
* mansession_session and mansession structs, we need to have a bit of a history
* lesson.
*
* In the beginning, there was the mansession. The mansession contained data that was
* intrinsic to a manager session, such as the time that it started, the name of the logged-in
* user, etc. In addition to these parameters were the f and fd parameters. For typical manager
* sessions, these were used to represent the TCP socket over which the AMI session was taking
* place. It makes perfect sense for these fields to be a part of the session-specific data since
* the session actually defines this information.
*
* Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
* for every single action that occurs. Thus the f and fd fields aren't really specific to the session
* but rather to the action that is being executed. Because a single session may execute many commands
* at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
* leaks from one action overwriting the f and fd fields used by a previous action before the previous action
* has had a chance to properly close its handles.
*
* The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
* from being run at the same time in a single session. Some manager actions may block for a long time, thus
* creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
* issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
* part of the action instead.
*
* The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
* contain the action-specific information, such as which file to write to. In order to maintain expectations
* of action handlers and not have to change the public API of the manager code, we would need to name this
* new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
* We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
* is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
* data.
*/
struct mansession_session {
/*! \todo XXX need to document which fields it is protecting */
struct ast_sockaddr addr; /*!< address we are connecting from */
struct ast_iostream *stream; /*!< AMI stream */
int inuse; /*!< number of HTTP sessions using this entry */
int needdestroy; /*!< Whether an HTTP session should be destroyed */
pthread_t waiting_thread; /*!< Sleeping thread using this descriptor */
uint32_t managerid; /*!< Unique manager identifier, 0 for AMI sessions */
time_t sessionstart; /*!< Session start time */
struct timeval sessionstart_tv; /*!< Session start time */
time_t sessiontimeout; /*!< Session timeout if HTTP */
char username[80]; /*!< Logged in username */
char challenge[10]; /*!< Authentication challenge */
int authenticated; /*!< Authentication status */
int readperm; /*!< Authorization for reading */
int writeperm; /*!< Authorization for writing */
char inbuf[1025]; /*!< Buffer - we use the extra byte to add a '\\0' and simplify parsing */
int inlen; /*!< number of buffered bytes */
struct ao2_container *whitefilters; /*!< Manager event filters - white list */
struct ao2_container *blackfilters; /*!< Manager event filters - black list */
struct ast_variable *chanvars; /*!< Channel variables to set for originate */
int send_events; /*!< XXX what ? */
struct eventqent *last_ev; /*!< last event processed. */
int writetimeout; /*!< Timeout for ast_carefulwrite() */
time_t authstart;
int pending_event; /*!< Pending events indicator in case when waiting_thread is NULL */
time_t noncetime; /*!< Timer for nonce value expiration */
unsigned long oldnonce; /*!< Stale nonce value */
unsigned long nc; /*!< incremental nonce counter */
AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
AST_LIST_ENTRY(mansession_session) list;
};
enum mansession_message_parsing {
MESSAGE_OKAY,
MESSAGE_LINE_TOO_LONG
};
/*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
* \ref struct mansession is named this solely to keep the API the same in Asterisk. This structure really
* represents data that is different from Manager action to Manager action. The mansession_session pointer
* contained within points to session-specific data.
*/
struct mansession {
struct mansession_session *session;
struct ast_iostream *stream;
struct ast_tcptls_session_instance *tcptls_session;
enum mansession_message_parsing parsing;
int write_error:1;
struct manager_custom_hook *hook;
ast_mutex_t lock;
};
/*! Active manager connection sessions container. */
static AO2_GLOBAL_OBJ_STATIC(mgr_sessions);
/*! \brief user descriptor, as read from the config file.
*
* \note It is still missing some fields -- e.g. we can have multiple permit and deny
* lines which are not supported here, and readperm/writeperm/writetimeout
* are not stored.
*/
struct ast_manager_user {
char username[80];
char *secret; /*!< Secret for logging in */
int readperm; /*!< Authorization for reading */
int writeperm; /*!< Authorization for writing */
int writetimeout; /*!< Per user Timeout for ast_carefulwrite() */
int displayconnects; /*!< XXX unused */
int allowmultiplelogin; /*!< Per user option*/
int keep; /*!< mark entries created on a reload */
struct ao2_container *whitefilters; /*!< Manager event filters - white list */
struct ao2_container *blackfilters; /*!< Manager event filters - black list */
struct ast_acl_list *acl; /*!< ACL setting */
char *a1_hash; /*!< precalculated A1 for Digest auth */
struct ast_variable *chanvars; /*!< Channel variables to set for originate */
AST_RWLIST_ENTRY(ast_manager_user) list;
};
/*! \brief list of users found in the config file */
static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
/*! \brief list of actions registered */
static AST_RWLIST_HEAD_STATIC(actions, manager_action);
/*! \brief list of hooks registered */
static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
#ifdef AST_XML_DOCS
/*! \brief A container of event documentation nodes */
static AO2_GLOBAL_OBJ_STATIC(event_docs);
#endif
static int __attribute__((format(printf, 9, 0))) __manager_event_sessions(
struct ao2_container *sessions,
int category,
const char *event,
int chancount,
struct ast_channel **chans,
const char *file,
int line,
const char *func,
const char *fmt,
...);
static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
static int match_filter(struct mansession *s, char *eventdata);
/*!
* @{ \brief Define AMI message types.
*/
STASIS_MESSAGE_TYPE_DEFN(ast_manager_get_generic_type);
/*! @} */
/*!
* \internal
* \brief Find a registered action object.
*
* \param name Name of AMI action to find.
*
* \return Reffed action found or NULL
*/
static struct manager_action *action_find(const char *name)
{
struct manager_action *act;
AST_RWLIST_RDLOCK(&actions);
AST_RWLIST_TRAVERSE(&actions, act, list) {
if (!strcasecmp(name, act->action)) {
ao2_t_ref(act, +1, "found action object");
break;
}
}
AST_RWLIST_UNLOCK(&actions);
return act;
}
struct stasis_topic *ast_manager_get_topic(void)
{
return manager_topic;
}
struct stasis_message_router *ast_manager_get_message_router(void)
{
return stasis_router;
}
static void manager_json_value_str_append(struct ast_json *value, const char *key,
struct ast_str **res)
{
switch (ast_json_typeof(value)) {
case AST_JSON_STRING:
ast_str_append(res, 0, "%s: %s\r\n", key, ast_json_string_get(value));
break;
case AST_JSON_INTEGER:
ast_str_append(res, 0, "%s: %jd\r\n", key, ast_json_integer_get(value));
break;
case AST_JSON_TRUE:
ast_str_append(res, 0, "%s: True\r\n", key);
break;
case AST_JSON_FALSE:
ast_str_append(res, 0, "%s: False\r\n", key);
break;
default:
ast_str_append(res, 0, "%s: \r\n", key);
break;
}
}
static void manager_json_to_ast_str(struct ast_json *obj, const char *key,
struct ast_str **res, key_exclusion_cb exclusion_cb);
static void manager_json_array_with_key(struct ast_json *obj, const char* key,
size_t index, struct ast_str **res,
key_exclusion_cb exclusion_cb)
{
struct ast_str *key_str = ast_str_alloca(64);
ast_str_set(&key_str, 0, "%s(%zu)", key, index);
manager_json_to_ast_str(obj, ast_str_buffer(key_str),
res, exclusion_cb);
}
static void manager_json_obj_with_key(struct ast_json *obj, const char* key,
const char *parent_key, struct ast_str **res,
key_exclusion_cb exclusion_cb)
{
if (parent_key) {
struct ast_str *key_str = ast_str_alloca(64);
ast_str_set(&key_str, 0, "%s/%s", parent_key, key);
manager_json_to_ast_str(obj, ast_str_buffer(key_str),
res, exclusion_cb);
return;
}
manager_json_to_ast_str(obj, key, res, exclusion_cb);
}
void manager_json_to_ast_str(struct ast_json *obj, const char *key,
struct ast_str **res, key_exclusion_cb exclusion_cb)
{
struct ast_json_iter *i;
/* If obj or res is not given, just return */
if (!obj || !res) {
return;
}
if (!*res && !(*res = ast_str_create(1024))) {
return;
}
if (exclusion_cb && key && exclusion_cb(key)) {
return;
}
if (ast_json_typeof(obj) != AST_JSON_OBJECT &&
ast_json_typeof(obj) != AST_JSON_ARRAY) {
manager_json_value_str_append(obj, key, res);
return;
}
if (ast_json_typeof(obj) == AST_JSON_ARRAY) {
size_t j;
for (j = 0; j < ast_json_array_size(obj); ++j) {
manager_json_array_with_key(ast_json_array_get(obj, j),
key, j, res, exclusion_cb);
}
return;
}
for (i = ast_json_object_iter(obj); i;
i = ast_json_object_iter_next(obj, i)) {
manager_json_obj_with_key(ast_json_object_iter_value(i),
ast_json_object_iter_key(i),
key, res, exclusion_cb);
}
}
struct ast_str *ast_manager_str_from_json_object(struct ast_json *blob, key_exclusion_cb exclusion_cb)
{
struct ast_str *res = ast_str_create(1024);
if (!ast_json_is_null(blob)) {
manager_json_to_ast_str(blob, NULL, &res, exclusion_cb);
}
return res;
}
#define manager_event_sessions(sessions, category, event, contents , ...) \
__manager_event_sessions(sessions, category, event, 0, NULL, __FILE__, __LINE__, __PRETTY_FUNCTION__, contents , ## __VA_ARGS__)
#define any_manager_listeners(sessions) \
((sessions && ao2_container_count(sessions)) || !AST_RWLIST_EMPTY(&manager_hooks))
static void manager_default_msg_cb(void *data, struct stasis_subscription *sub,
struct stasis_message *message)
{
struct ao2_container *sessions;
struct ast_manager_event_blob *ev;
if (!stasis_message_can_be_ami(message)) {
/* Not an AMI message; disregard */
return;
}
sessions = ao2_global_obj_ref(mgr_sessions);
if (!any_manager_listeners(sessions)) {
/* Nobody is listening */
ao2_cleanup(sessions);
return;
}
ev = stasis_message_to_ami(message);
if (!ev) {
/* Conversion failure */
ao2_cleanup(sessions);
return;
}
manager_event_sessions(sessions, ev->event_flags, ev->manager_event,
"%s", ev->extra_fields);
ao2_ref(ev, -1);
ao2_cleanup(sessions);
}
static void manager_generic_msg_cb(void *data, struct stasis_subscription *sub,
struct stasis_message *message)
{
struct ast_json_payload *payload;
int class_type;
const char *type;
struct ast_json *event;
struct ast_str *event_buffer;
struct ao2_container *sessions;
sessions = ao2_global_obj_ref(mgr_sessions);
if (!any_manager_listeners(sessions)) {
/* Nobody is listening */
ao2_cleanup(sessions);
return;
}
payload = stasis_message_data(message);
class_type = ast_json_integer_get(ast_json_object_get(payload->json, "class_type"));
type = ast_json_string_get(ast_json_object_get(payload->json, "type"));
event = ast_json_object_get(payload->json, "event");
event_buffer = ast_manager_str_from_json_object(event, NULL);
if (!event_buffer) {
ast_log(AST_LOG_WARNING, "Error while creating payload for event %s\n", type);
ao2_cleanup(sessions);
return;
}
manager_event_sessions(sessions, class_type, type,
"%s", ast_str_buffer(event_buffer));
ast_free(event_buffer);
ao2_cleanup(sessions);
}
void ast_manager_publish_event(const char *type, int class_type, struct ast_json *obj)
{
RAII_VAR(struct ast_json *, event_info, NULL, ast_json_unref);
RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
if (!obj || !ast_manager_get_generic_type()) {
return;
}
ast_json_ref(obj);
event_info = ast_json_pack("{s: s, s: i, s: o}",
"type", type,
"class_type", class_type,
"event", obj);
if (!event_info) {
return;
}
payload = ast_json_payload_create(event_info);
if (!payload) {
return;
}
message = stasis_message_create(ast_manager_get_generic_type(), payload);
if (!message) {
return;
}
stasis_publish(ast_manager_get_topic(), message);
}
/*! \brief Add a custom hook to be called when an event is fired */
void ast_manager_register_hook(struct manager_custom_hook *hook)
{
AST_RWLIST_WRLOCK(&manager_hooks);
AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
AST_RWLIST_UNLOCK(&manager_hooks);
}
/*! \brief Delete a custom hook to be called when an event is fired */
void ast_manager_unregister_hook(struct manager_custom_hook *hook)
{
AST_RWLIST_WRLOCK(&manager_hooks);
AST_RWLIST_REMOVE(&manager_hooks, hook, list);
AST_RWLIST_UNLOCK(&manager_hooks);
}
int check_manager_enabled(void)
{
return manager_enabled;
}
int check_webmanager_enabled(void)
{
return (webmanager_enabled && manager_enabled);
}
/*!
* Grab a reference to the last event, update usecount as needed.
* Can handle a NULL pointer.
*/
static struct eventqent *grab_last(void)
{
struct eventqent *ret;
AST_RWLIST_WRLOCK(&all_events);
ret = AST_RWLIST_LAST(&all_events);
/* the list is never empty now, but may become so when
* we optimize it in the future, so be prepared.
*/
if (ret) {
ast_atomic_fetchadd_int(&ret->usecount, 1);
}
AST_RWLIST_UNLOCK(&all_events);
return ret;
}
/*!
* Purge unused events. Remove elements from the head
* as long as their usecount is 0 and there is a next element.
*/
static void purge_events(void)
{
struct eventqent *ev;
struct timeval now = ast_tvnow();
AST_RWLIST_WRLOCK(&all_events);
while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
ast_free(ev);
}
AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
/* Never release the last event */
if (!AST_RWLIST_NEXT(ev, eq_next)) {
break;
}
/* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
AST_RWLIST_REMOVE_CURRENT(eq_next);
ast_free(ev);
}
}
AST_RWLIST_TRAVERSE_SAFE_END;
AST_RWLIST_UNLOCK(&all_events);
}
/*!
* helper functions to convert back and forth between
* string and numeric representation of set of flags
*/
static const struct permalias {
int num;
const char *label;
} perms[] = {
{ EVENT_FLAG_SYSTEM, "system" },
{ EVENT_FLAG_CALL, "call" },
{ EVENT_FLAG_LOG, "log" },
{ EVENT_FLAG_VERBOSE, "verbose" },
{ EVENT_FLAG_COMMAND, "command" },
{ EVENT_FLAG_AGENT, "agent" },
{ EVENT_FLAG_USER, "user" },
{ EVENT_FLAG_CONFIG, "config" },
{ EVENT_FLAG_DTMF, "dtmf" },
{ EVENT_FLAG_REPORTING, "reporting" },
{ EVENT_FLAG_CDR, "cdr" },
{ EVENT_FLAG_DIALPLAN, "dialplan" },
{ EVENT_FLAG_ORIGINATE, "originate" },
{ EVENT_FLAG_AGI, "agi" },
{ EVENT_FLAG_CC, "cc" },
{ EVENT_FLAG_AOC, "aoc" },
{ EVENT_FLAG_TEST, "test" },
{ EVENT_FLAG_SECURITY, "security" },
{ EVENT_FLAG_MESSAGE, "message" },
{ INT_MAX, "all" },
{ 0, "none" },
};
/*! Maximum string length of the AMI authority permission string buildable from perms[]. */
#define MAX_AUTH_PERM_STRING 150
/*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
{
if (!(writepermlist & EVENT_FLAG_SYSTEM)
&& (
strstr(evaluating, "SHELL") || /* NoOp(${SHELL(rm -rf /)}) */
strstr(evaluating, "EVAL") /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
)) {
return 0;
}
return 1;
}
/*! \brief Convert authority code to a list of options for a user. This will only
* display those authority codes that have an explicit match on authority */
static const char *user_authority_to_str(int authority, struct ast_str **res)
{
int i;
char *sep = "";
ast_str_reset(*res);
for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
if ((authority & perms[i].num) == perms[i].num) {
ast_str_append(res, 0, "%s%s", sep, perms[i].label);
sep = ",";
}
}
if (ast_str_strlen(*res) == 0) {
/* replace empty string with something sensible */
ast_str_append(res, 0, "<none>");
}
return ast_str_buffer(*res);
}
/*! \brief Convert authority code to a list of options. Note that the EVENT_FLAG_ALL
* authority will always be returned. */
static const char *authority_to_str(int authority, struct ast_str **res)
{
int i;
char *sep = "";
ast_str_reset(*res);
if (authority != EVENT_FLAG_SHUTDOWN) {
for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
if (authority & perms[i].num) {
ast_str_append(res, 0, "%s%s", sep, perms[i].label);
sep = ",";
}
}
}
if (ast_str_strlen(*res) == 0) {
/* replace empty string with something sensible */
ast_str_append(res, 0, "<none>");
}
return ast_str_buffer(*res);
}
/*! Tells you if smallstr exists inside bigstr
which is delim by delim and uses no buf or stringsep
ast_instring("this|that|more","this",'|') == 1;
feel free to move this to app.c -anthm */
static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
{
const char *val = bigstr, *next;
do {
if ((next = strchr(val, delim))) {
if (!strncmp(val, smallstr, (next - val))) {
return 1;
} else {
continue;
}
} else {
return !strcmp(smallstr, val);
}
} while (*(val = (next + 1)));
return 0;
}
static int get_perm(const char *instr)
{
int x = 0, ret = 0;
if (!instr) {
return 0;
}
for (x = 0; x < ARRAY_LEN(perms); x++) {
if (ast_instring(instr, perms[x].label, ',')) {
ret |= perms[x].num;
}
}
return ret;
}
/*!
* A number returns itself, false returns 0, true returns all flags,
* other strings return the flags that are set.
*/
static int strings_to_mask(const char *string)
{
const char *p;
if (ast_strlen_zero(string)) {
return -1;
}
for (p = string; *p; p++) {
if (*p < '0' || *p > '9') {
break;
}
}
if (!*p) { /* all digits */
return atoi(string);
}
if (ast_false(string)) {
return 0;
}
if (ast_true(string)) { /* all permissions */
int x, ret = 0;
for (x = 0; x < ARRAY_LEN(perms); x++) {
ret |= perms[x].num;
}
return ret;
}
return get_perm(string);
}
/*! \brief Unreference manager session object.
If no more references, then go ahead and delete it */
static struct mansession_session *unref_mansession(struct mansession_session *s)
{
int refcount = ao2_ref(s, -1);
if (manager_debug) {
ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
}
return NULL;
}
static void event_filter_destructor(void *obj)
{
regex_t *regex_filter = obj;
regfree(regex_filter);
}
static void session_destructor(void *obj)
{
struct mansession_session *session = obj;
struct eventqent *eqe = session->last_ev;
struct ast_datastore *datastore;
/* Get rid of each of the data stores on the session */
while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
/* Free the data store */
ast_datastore_free(datastore);
}
if (eqe) {
ast_atomic_fetchadd_int(&eqe->usecount, -1);
}
if (session->chanvars) {
ast_variables_destroy(session->chanvars);
}
if (session->whitefilters) {
ao2_t_ref(session->whitefilters, -1, "decrement ref for white container, should be last one");
}
if (session->blackfilters) {
ao2_t_ref(session->blackfilters, -1, "decrement ref for black container, should be last one");
}
}
/*! \brief Allocate manager session structure and add it to the list of sessions */
static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
{
struct ao2_container *sessions;
struct mansession_session *newsession;
newsession = ao2_alloc(sizeof(*newsession), session_destructor);
if (!newsession) {
return NULL;
}
newsession->whitefilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
newsession->blackfilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
if (!newsession->whitefilters || !newsession->blackfilters) {
ao2_ref(newsession, -1);
return NULL;
}
newsession->waiting_thread = AST_PTHREADT_NULL;
newsession->writetimeout = 100;
newsession->send_events = -1;
ast_sockaddr_copy(&newsession->addr, addr);
sessions = ao2_global_obj_ref(mgr_sessions);
if (sessions) {
ao2_link(sessions, newsession);
ao2_ref(sessions, -1);
}
return newsession;
}
static int mansession_cmp_fn(void *obj, void *arg, int flags)
{
struct mansession_session *s = obj;
char *str = arg;
return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
}
static void session_destroy(struct mansession_session *s)
{
struct ao2_container *sessions;
sessions = ao2_global_obj_ref(mgr_sessions);
if (sessions) {
ao2_unlink(sessions, s);
ao2_ref(sessions, -1);
}
unref_mansession(s);
}
static int check_manager_session_inuse(const char *name)
{
struct ao2_container *sessions;
struct mansession_session *session;
int inuse = 0;
sessions = ao2_global_obj_ref(mgr_sessions);
if (sessions) {
session = ao2_find(sessions, (char *) name, 0);
ao2_ref(sessions, -1);
if (session) {
unref_mansession(session);
inuse = 1;
}
}
return inuse;
}
/*!
* lookup an entry in the list of registered users.
* must be called with the list lock held.
*/
static struct ast_manager_user *get_manager_by_name_locked(const char *name)
{
struct ast_manager_user *user = NULL;
AST_RWLIST_TRAVERSE(&users, user, list) {
if (!strcasecmp(user->username, name)) {
break;
}
}
return user;
}
/*! \brief Get displayconnects config option.
* \param session manager session to get parameter from.
* \return displayconnects config option value.
*/
static int manager_displayconnects(struct mansession_session *session)
{
struct ast_manager_user *user = NULL;
int ret = 0;
AST_RWLIST_RDLOCK(&users);
if ((user = get_manager_by_name_locked(session->username))) {
ret = user->displayconnects;
}
AST_RWLIST_UNLOCK(&users);
return ret;
}
#ifdef AST_XML_DOCS
static void print_event_instance(struct ast_cli_args *a, struct ast_xml_doc_item *instance);
#endif
static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct manager_action *cur;
struct ast_str *authority;
int num;
int l;
const char *auth_str;
#ifdef AST_XML_DOCS
char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64];
char arguments_title[64], privilege_title[64], final_response_title[64], list_responses_title[64];
#endif
switch (cmd) {
case CLI_INIT:
e->command = "manager show command";
e->usage =
"Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
" Shows the detailed description for a specific Asterisk manager interface command.\n";
return NULL;
case CLI_GENERATE:
l = strlen(a->word);
AST_RWLIST_RDLOCK(&actions);
AST_RWLIST_TRAVERSE(&actions, cur, list) {
if (!strncasecmp(a->word, cur->action, l)) {
if (ast_cli_completion_add(ast_strdup(cur->action))) {
break;
}
}
}
AST_RWLIST_UNLOCK(&actions);
return NULL;
}
if (a->argc < 4) {
return CLI_SHOWUSAGE;
}
authority = ast_str_alloca(MAX_AUTH_PERM_STRING);
#ifdef AST_XML_DOCS
/* setup the titles */
term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
term_color(privilege_title, "[Privilege]\n", COLOR_MAGENTA, 0, 40);
term_color(final_response_title, "[Final Response]\n", COLOR_MAGENTA, 0, 40);
term_color(list_responses_title, "[List Responses]\n", COLOR_MAGENTA, 0, 40);
#endif
AST_RWLIST_RDLOCK(&actions);
AST_RWLIST_TRAVERSE(&actions, cur, list) {
for (num = 3; num < a->argc; num++) {
if (!strcasecmp(cur->action, a->argv[num])) {
auth_str = authority_to_str(cur->authority, &authority);
#ifdef AST_XML_DOCS
if (cur->docsrc == AST_XML_DOC) {
char *syntax = ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1);
char *synopsis = ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1);
char *description = ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1);
char *arguments = ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1);
char *seealso = ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1);
char *privilege = ast_xmldoc_printable(S_OR(auth_str, "Not available"), 1);
char *responses = ast_xmldoc_printable("None", 1);
if (!syntax || !synopsis || !description || !arguments
|| !seealso || !privilege || !responses) {
ast_free(syntax);
ast_free(synopsis);
ast_free(description);
ast_free(arguments);
ast_free(seealso);
ast_free(privilege);
ast_free(responses);
ast_cli(a->fd, "Allocation failure.\n");
AST_RWLIST_UNLOCK(&actions);
return CLI_FAILURE;
}
ast_cli(a->fd, "%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s",
syntax_title, syntax,
synopsis_title, synopsis,
description_title, description,
arguments_title, arguments,
seealso_title, seealso,
privilege_title, privilege,
list_responses_title);
if (!cur->list_responses) {
ast_cli(a->fd, "%s\n\n", responses);
} else {
struct ast_xml_doc_item *temp;
for (temp = cur->list_responses; temp; temp = AST_LIST_NEXT(temp, next)) {
ast_cli(a->fd, "Event: %s\n", temp->name);
print_event_instance(a, temp);
}
}
ast_cli(a->fd, "%s", final_response_title);
if (!cur->final_response) {
ast_cli(a->fd, "%s\n\n", responses);
} else {
ast_cli(a->fd, "Event: %s\n", cur->final_response->name);
print_event_instance(a, cur->final_response);
}
ast_free(syntax);
ast_free(synopsis);
ast_free(description);
ast_free(arguments);
ast_free(seealso);
ast_free(privilege);
ast_free(responses);
} else
#endif
{
ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
cur->action, cur->synopsis,
auth_str,
S_OR(cur->description, ""));
}
}
}
}
AST_RWLIST_UNLOCK(&actions);
return CLI_SUCCESS;
}
static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
switch (cmd) {
case CLI_INIT:
e->command = "manager set debug [on|off]";
e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc == 3) {
ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
} else if (a->argc == 4) {
if (!strcasecmp(a->argv[3], "on")) {
manager_debug = 1;
} else if (!strcasecmp(a->argv[3], "off")) {
manager_debug = 0;
} else {
return CLI_SHOWUSAGE;
}
}
return CLI_SUCCESS;
}
static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_manager_user *user = NULL;
int l;
struct ast_str *rauthority = ast_str_alloca(MAX_AUTH_PERM_STRING);
struct ast_str *wauthority = ast_str_alloca(MAX_AUTH_PERM_STRING);
struct ast_variable *v;
switch (cmd) {
case CLI_INIT:
e->command = "manager show user";
e->usage =
" Usage: manager show user <user>\n"
" Display all information related to the manager user specified.\n";
return NULL;
case CLI_GENERATE:
l = strlen(a->word);
if (a->pos != 3) {
return NULL;
}
AST_RWLIST_RDLOCK(&users);
AST_RWLIST_TRAVERSE(&users, user, list) {
if (!strncasecmp(a->word, user->username, l)) {
if (ast_cli_completion_add(ast_strdup(user->username))) {
break;
}
}
}
AST_RWLIST_UNLOCK(&users);
return NULL;
}
if (a->argc != 4) {
return CLI_SHOWUSAGE;
}
AST_RWLIST_RDLOCK(&users);
if (!(user = get_manager_by_name_locked(a->argv[3]))) {
ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
AST_RWLIST_UNLOCK(&users);
return CLI_SUCCESS;
}
ast_cli(a->fd, "\n");
ast_cli(a->fd,
" username: %s\n"
" secret: %s\n"
" ACL: %s\n"
" read perm: %s\n"
" write perm: %s\n"
" displayconnects: %s\n"
"allowmultiplelogin: %s\n",
S_OR(user->username, "(N/A)"),
(user->secret ? "<Set>" : "(N/A)"),
((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
user_authority_to_str(user->readperm, &rauthority),
user_authority_to_str(user->writeperm, &wauthority),
(user->displayconnects ? "yes" : "no"),
(user->allowmultiplelogin ? "yes" : "no"));
ast_cli(a->fd, " Variables: \n");
for (v = user->chanvars ; v ; v = v->next) {
ast_cli(a->fd, " %s = %s\n", v->name, v->value);
}
AST_RWLIST_UNLOCK(&users);
return CLI_SUCCESS;
}
static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_manager_user *user = NULL;
int count_amu = 0;
switch (cmd) {
case CLI_INIT:
e->command = "manager show users";
e->usage =
"Usage: manager show users\n"
" Prints a listing of all managers that are currently configured on that\n"
" system.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc != 3) {
return CLI_SHOWUSAGE;
}
AST_RWLIST_RDLOCK(&users);
/* If there are no users, print out something along those lines */
if (AST_RWLIST_EMPTY(&users)) {
ast_cli(a->fd, "There are no manager users.\n");
AST_RWLIST_UNLOCK(&users);
return CLI_SUCCESS;
}
ast_cli(a->fd, "\nusername\n--------\n");
AST_RWLIST_TRAVERSE(&users, user, list) {
ast_cli(a->fd, "%s\n", user->username);
count_amu++;
}
AST_RWLIST_UNLOCK(&users);
ast_cli(a->fd,"-------------------\n"
"%d manager users configured.\n", count_amu);
return CLI_SUCCESS;
}
/*! \brief CLI command manager list commands */
static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct manager_action *cur;
int name_len = 1;
int space_remaining;
#define HSMC_FORMAT " %-*.*s %-.*s\n"
switch (cmd) {
case CLI_INIT:
e->command = "manager show commands";
e->usage =
"Usage: manager show commands\n"
" Prints a listing of all the available Asterisk manager interface commands.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
AST_RWLIST_RDLOCK(&actions);
AST_RWLIST_TRAVERSE(&actions, cur, list) {
int incoming_len = strlen(cur->action);
if (incoming_len > name_len) {
name_len = incoming_len;
}
}
space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
if (space_remaining < 0) {
space_remaining = 0;
}
ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
AST_RWLIST_TRAVERSE(&actions, cur, list) {
ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
}
AST_RWLIST_UNLOCK(&actions);
return CLI_SUCCESS;
}
/*! \brief CLI command manager list connected */
static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ao2_container *sessions;
struct mansession_session *session;
time_t now = time(NULL);
#define HSMCONN_FORMAT1 " %-15.15s %-55.55s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"
#define HSMCONN_FORMAT2 " %-15.15s %-55.55s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"
int count = 0;
struct ao2_iterator i;
switch (cmd) {
case CLI_INIT:
e->command = "manager show connected";
e->usage =
"Usage: manager show connected\n"
" Prints a listing of the users that are currently connected to the\n"
"Asterisk manager interface.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
sessions = ao2_global_obj_ref(mgr_sessions);
if (sessions) {
i = ao2_iterator_init(sessions, 0);
ao2_ref(sessions, -1);
while ((session = ao2_iterator_next(&i))) {
ao2_lock(session);
ast_cli(a->fd, HSMCONN_FORMAT2, session->username,
ast_sockaddr_stringify_addr(&session->addr),
(int) (session->sessionstart),
(int) (now - session->sessionstart),
session->stream ? ast_iostream_get_fd(session->stream) : -1,
session->inuse,
session->readperm,
session->writeperm);
count++;
ao2_unlock(session);
unref_mansession(session);
}
ao2_iterator_destroy(&i);
}
ast_cli(a->fd, "%d users connected.\n", count);
return CLI_SUCCESS;
}
/*! \brief CLI command manager list eventq */
/* Should change to "manager show connected" */
static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct eventqent *s;
switch (cmd) {
case CLI_INIT:
e->command = "manager show eventq";
e->usage =
"Usage: manager show eventq\n"
" Prints a listing of all events pending in the Asterisk manger\n"
"event queue.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
AST_RWLIST_RDLOCK(&all_events);
AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
ast_cli(a->fd, "Usecount: %d\n", s->usecount);
ast_cli(a->fd, "Category: %d\n", s->category);
ast_cli(a->fd, "Event:\n%s", s->eventdata);
}
AST_RWLIST_UNLOCK(&all_events);
return CLI_SUCCESS;
}
static int reload_module(void);
/*! \brief CLI command manager reload */
static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
switch (cmd) {
case CLI_INIT:
e->command = "manager reload";
e->usage =
"Usage: manager reload\n"
" Reloads the manager configuration.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc > 2) {
return CLI_SHOWUSAGE;
}
reload_module();
return CLI_SUCCESS;
}
static struct eventqent *advance_event(struct eventqent *e)
{
struct eventqent *next;
AST_RWLIST_RDLOCK(&all_events);
if ((next = AST_RWLIST_NEXT(e, eq_next))) {
ast_atomic_fetchadd_int(&next->usecount, 1);
ast_atomic_fetchadd_int(&e->usecount, -1);
}
AST_RWLIST_UNLOCK(&all_events);
return next;
}
#define GET_HEADER_FIRST_MATCH 0
#define GET_HEADER_LAST_MATCH 1
#define GET_HEADER_SKIP_EMPTY 2
/*!
* \brief Return a matching header value.
*
* \details
* Generic function to return either the first or the last
* matching header from a list of variables, possibly skipping
* empty strings.
*
* \note At the moment there is only one use of this function in
* this file, so we make it static.
*
* \note Never returns NULL.
*/
static const char *__astman_get_header(const struct message *m, char *var, int mode)
{
int x, l = strlen(var);
const char *result = "";
if (!m) {
return result;
}
for (x = 0; x < m->hdrcount; x++) {
const char *h = m->headers[x];
if (!strncasecmp(var, h, l) && h[l] == ':') {
const char *value = h + l + 1;
value = ast_skip_blanks(value); /* ignore leading spaces in the value */
/* found a potential candidate */
if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
continue; /* not interesting */
}
if (mode & GET_HEADER_LAST_MATCH) {
result = value; /* record the last match so far */
} else {
return value;
}
}
}
return result;
}
/*!
* \brief Return the first matching variable from an array.
*
* \note This is the legacy function and is implemented in
* therms of __astman_get_header().
*
* \note Never returns NULL.
*/
const char *astman_get_header(const struct message *m, char *var)
{
return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
}
/*!
* \brief Append additional headers into the message structure from params.
*
* \note You likely want to initialize m->hdrcount to 0 before calling this.
*/
static void astman_append_headers(struct message *m, const struct ast_variable *params)
{
const struct ast_variable *v;
for (v = params; v && m->hdrcount < ARRAY_LEN(m->headers); v = v->next) {
if (ast_asprintf((char**)&m->headers[m->hdrcount], "%s: %s", v->name, v->value) > -1) {
++m->hdrcount;
}
}
}
/*!
* \brief Free headers inside message structure, but not the message structure itself.
*/
static void astman_free_headers(struct message *m)
{
while (m->hdrcount) {
--m->hdrcount;
ast_free((void *) m->headers[m->hdrcount]);
m->headers[m->hdrcount] = NULL;
}
}
/*!
* \internal
* \brief Process one "Variable:" header value string.
*
* \param head Current list of AMI variables to get new values added.
* \param hdr_val Header value string to process.
*
* \return New variable list head.
*/
static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
{
char *parse;
AST_DECLARE_APP_ARGS(args,
AST_APP_ARG(vars)[64];
);
hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
parse = ast_strdupa(hdr_val);
/* Break the header value string into name=val pair items. */
AST_STANDARD_APP_ARGS(args, parse);
if (args.argc) {
int y;
/* Process each name=val pair item. */
for (y = 0; y < args.argc; y++) {
struct ast_variable *cur;
char *var;
char *val;
if (!args.vars[y]) {
continue;
}
var = val = args.vars[y];
strsep(&val, "=");
/* XXX We may wish to trim whitespace from the strings. */
if (!val || ast_strlen_zero(var)) {
continue;
}
/* Create new variable list node and prepend it to the list. */
cur = ast_variable_new(var, val, "");
if (cur) {
cur->next = head;
head = cur;
}
}
}
return head;
}
struct ast_variable *astman_get_variables(const struct message *m)
{
return astman_get_variables_order(m, ORDER_REVERSE);
}
struct ast_variable *astman_get_variables_order(const struct message *m,
enum variable_orders order)
{
int varlen;
int x;
struct ast_variable *head = NULL;
static const char var_hdr[] = "Variable:";
/* Process all "Variable:" headers. */
varlen = strlen(var_hdr);
for (x = 0; x < m->hdrcount; x++) {
if (strncasecmp(var_hdr, m->headers[x], varlen)) {
continue;
}
head = man_do_variable_value(head, m->headers[x] + varlen);
}
if (order == ORDER_NATURAL) {
head = ast_variables_reverse(head);
}
return head;
}
/*! \brief access for hooks to send action messages to ami */
int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
{
const char *action;
int ret = 0;
struct manager_action *act_found;
struct mansession s = {.session = NULL, };
struct message m = { 0 };
char *dup_str;
char *src;
int x = 0;
int curlen;
if (hook == NULL) {
return -1;
}
/* Create our own copy of the AMI action msg string. */
src = dup_str = ast_strdup(msg);
if (!dup_str) {
return -1;
}
/* convert msg string to message struct */
curlen = strlen(src);
for (x = 0; x < curlen; x++) {
int cr; /* set if we have \r */
if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
cr = 2; /* Found. Update length to include \r\n */
else if (src[x] == '\n')
cr = 1; /* also accept \n only */
else
continue;
/* don't keep empty lines */
if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
/* ... but trim \r\n and terminate the header string */
src[x] = '\0';
m.headers[m.hdrcount++] = src;
}
x += cr;
curlen -= x; /* remaining size */
src += x; /* update pointer */
x = -1; /* reset loop */
}
action = astman_get_header(&m, "Action");
do {
if (!strcasecmp(action, "login")) {
break;
}
act_found = action_find(action);
if (!act_found) {
break;
}
/*
* we have to simulate a session for this action request
* to be able to pass it down for processing
* This is necessary to meet the previous design of manager.c
*/
s.hook = hook;
ret = -1;
ao2_lock(act_found);
if (act_found->registered && act_found->func) {
struct ast_module *mod_ref = ast_module_running_ref(act_found->module);
ao2_unlock(act_found);
/* If the action is in a module it must be running. */
if (!act_found->module || mod_ref) {
ret = act_found->func(&s, &m);
ast_module_unref(mod_ref);
}
} else {
ao2_unlock(act_found);
}
ao2_t_ref(act_found, -1, "done with found action object");
} while (0);
ast_free(dup_str);
return ret;
}
/*!
* helper function to send a string to the socket.
* Return -1 on error (e.g. buffer full).
*/
static int send_string(struct mansession *s, char *string)
{
struct ast_iostream *stream;
int len, res;
/* It's a result from one of the hook's action invocation */
if (s->hook) {
/*
* to send responses, we're using the same function
* as for receiving events. We call the event "HookResponse"
*/
s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
return 0;
}
stream = s->stream ? s->stream : s->session->stream;
len = strlen(string);
ast_iostream_set_timeout_inactivity(stream, s->session->writetimeout);
res = ast_iostream_write(stream, string, len);
ast_iostream_set_timeout_disable(stream);
if (res < len) {
s->write_error = 1;
}
return res;
}
/*!
* \brief thread local buffer for astman_append
*
* \note This can not be defined within the astman_append() function
* because it declares a couple of functions that get used to
* initialize the thread local storage key.
*/
AST_THREADSTORAGE(astman_append_buf);
AST_THREADSTORAGE(userevent_buf);
/*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
#define ASTMAN_APPEND_BUF_INITSIZE 256
/*!
* utility functions for creating AMI replies
*/
void astman_append(struct mansession *s, const char *fmt, ...)
{
int res;
va_list ap;
struct ast_str *buf;
if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
return;
}
va_start(ap, fmt);
res = ast_str_set_va(&buf, 0, fmt, ap);
va_end(ap);
if (res == AST_DYNSTR_BUILD_FAILED) {
return;
}
if (s->hook || (s->tcptls_session != NULL && s->tcptls_session->stream != NULL)) {
send_string(s, ast_str_buffer(buf));
} else {
ast_verbose("No connection stream in astman_append, should not happen\n");
}
}
/*! \note NOTE: XXX this comment is unclear and possibly wrong.
Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
hold the session lock _or_ be running in an action callback (in which case s->session->busy will
be non-zero). In either of these cases, there is no need to lock-protect the session's
fd, since no other output will be sent (events will be queued), and no input will
be read until either the current action finishes or get_input() obtains the session
lock.
*/
/*! \todo XXX MSG_MOREDATA should go to a header file. */
#define MSG_MOREDATA ((char *)astman_send_response)
/*! \brief send a response with an optional message,
* and terminate it with an empty line.
* m is used only to grab the 'ActionID' field.
*
* Use the explicit constant MSG_MOREDATA to remove the empty line.
* XXX MSG_MOREDATA should go to a header file.
*/
static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
{
const char *id = astman_get_header(m, "ActionID");
astman_append(s, "Response: %s\r\n", resp);
if (!ast_strlen_zero(id)) {
astman_append(s, "ActionID: %s\r\n", id);
}
if (listflag) {
astman_append(s, "EventList: %s\r\n", listflag); /* Start, complete, cancelled */
}
if (msg == MSG_MOREDATA) {
return;
} else if (msg) {
astman_append(s, "Message: %s\r\n\r\n", msg);
} else {
astman_append(s, "\r\n");
}
}
void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
{
astman_send_response_full(s, m, resp, msg, NULL);
}
void astman_send_error(struct mansession *s, const struct message *m, char *error)
{
astman_send_response_full(s, m, "Error", error, NULL);
}
void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
{
int res;
va_list ap;
struct ast_str *buf;
char *msg;
if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
return;
}
va_start(ap, fmt);
res = ast_str_set_va(&buf, 0, fmt, ap);
va_end(ap);
if (res == AST_DYNSTR_BUILD_FAILED) {
return;
}
/* astman_append will use the same underlying buffer, so copy the message out
* before sending the response */
msg = ast_str_buffer(buf);
if (msg) {
msg = ast_strdupa(msg);
}
astman_send_response_full(s, m, "Error", msg, NULL);
}
void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
{
astman_send_response_full(s, m, "Success", msg, NULL);
}
static void astman_start_ack(struct mansession *s, const struct message *m)
{
astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
}
void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
{
astman_send_response_full(s, m, "Success", msg, listflag);
}
void astman_send_list_complete_start(struct mansession *s, const struct message *m, const char *event_name, int count)
{
const char *id = astman_get_header(m, "ActionID");
astman_append(s, "Event: %s\r\n", event_name);
if (!ast_strlen_zero(id)) {
astman_append(s, "ActionID: %s\r\n", id);
}
astman_append(s,
"EventList: Complete\r\n"
"ListItems: %d\r\n",
count);
}
void astman_send_list_complete_end(struct mansession *s)
{
astman_append(s, "\r\n");
}
/*! \brief Lock the 'mansession' structure. */
static void mansession_lock(struct mansession *s)
{
ast_mutex_lock(&s->lock);
}
/*! \brief Unlock the 'mansession' structure. */
static void mansession_unlock(struct mansession *s)
{
ast_mutex_unlock(&s->lock);
}
/*! \brief
Rather than braindead on,off this now can also accept a specific int mask value
or a ',' delim list of mask strings (the same as manager.conf) -anthm
*/
static int set_eventmask(struct mansession *s, const char *eventmask)
{
int maskint = strings_to_mask(eventmask);
ao2_lock(s->session);
if (maskint >= 0) {
s->session->send_events = maskint;
}
ao2_unlock(s->session);
return maskint;
}
static enum ast_transport mansession_get_transport(const struct mansession *s)
{
return s->tcptls_session->parent->tls_cfg ? AST_TRANSPORT_TLS :
AST_TRANSPORT_TCP;
}
static void report_invalid_user(const struct mansession *s, const char *username)
{
char session_id[32];
struct ast_security_event_inval_acct_id inval_acct_id = {
.common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
.common.version = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
.common.service = "AMI",
.common.account_id = username,
.common.session_tv = &s->session->sessionstart_tv,
.common.local_addr = {
.addr = &s->tcptls_session->parent->local_address,
.transport = mansession_get_transport(s),
},
.common.remote_addr = {
.addr = &s->session->addr,
.transport = mansession_get_transport(s),
},
.common.session_id = session_id,
};
snprintf(session_id, sizeof(session_id), "%p", s);
ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
}
static void report_failed_acl(const struct mansession *s, const char *username)
{
char session_id[32];
struct ast_security_event_failed_acl failed_acl_event = {
.common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
.common.version = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
.common.service = "AMI",
.common.account_id = username,
.common.session_tv = &s->session->sessionstart_tv,
.common.local_addr = {
.addr = &s->tcptls_session->parent->local_address,
.transport = mansession_get_transport(s),
},
.common.remote_addr = {
.addr = &s->session->addr,
.transport = mansession_get_transport(s),
},
.common.session_id = session_id,
};
snprintf(session_id, sizeof(session_id), "%p", s->session);
ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
}
static void report_inval_password(const struct mansession *s, const char *username)
{
char session_id[32];
struct ast_security_event_inval_password inval_password = {
.common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
.common.version = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
.common.service = "AMI",
.common.account_id = username,
.common.session_tv = &s->session->sessionstart_tv,
.common.local_addr = {
.addr = &s->tcptls_session->parent->local_address,
.transport = mansession_get_transport(s),
},
.common.remote_addr = {
.addr = &s->session->addr,
.transport = mansession_get_transport(s),
},
.common.session_id = session_id,
};
snprintf(session_id, sizeof(session_id), "%p", s->session);
ast_security_event_report(AST_SEC_EVT(&inval_password));
}
static void report_auth_success(const struct mansession *s)
{
char session_id[32];
struct ast_security_event_successful_auth successful_auth = {
.common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
.common.version = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
.common.service = "AMI",
.common.account_id = s->session->username,
.common.session_tv = &s->session->sessionstart_tv,
.common.local_addr = {
.addr = &s->tcptls_session->parent->local_address,
.transport = mansession_get_transport(s),
},
.common.remote_addr = {
.addr = &s->session->addr,
.transport = mansession_get_transport(s),
},
.common.session_id = session_id,
};
snprintf(session_id, sizeof(session_id), "%p", s->session);
ast_security_event_report(AST_SEC_EVT(&successful_auth));
}
static void report_req_not_allowed(const struct mansession *s, const char *action)
{
char session_id[32];
char request_type[64];
struct ast_security_event_req_not_allowed req_not_allowed = {
.common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
.common.version = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
.common.service = "AMI",
.common.account_id = s->session->username,
.common.session_tv = &s->session->sessionstart_tv,
.common.local_addr = {
.addr = &s->tcptls_session->parent->local_address,
.transport = mansession_get_transport(s),
},
.common.remote_addr = {
.addr = &s->session->addr,
.transport = mansession_get_transport(s),
},
.common.session_id = session_id,
.request_type = request_type,
};
snprintf(session_id, sizeof(session_id), "%p", s->session);
snprintf(request_type, sizeof(request_type), "Action: %s", action);
ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
}
static void report_req_bad_format(const struct mansession *s, const char *action)
{
char session_id[32];
char request_type[64];
struct ast_security_event_req_bad_format req_bad_format = {
.common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
.common.version = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
.common.service = "AMI",
.common.account_id = s->session->username,
.common.session_tv = &s->session->sessionstart_tv,
.common.local_addr = {
.addr = &s->tcptls_session->parent->local_address,
.transport = mansession_get_transport(s),
},
.common.remote_addr = {
.addr = &s->session->addr,
.transport = mansession_get_transport(s),
},
.common.session_id = session_id,
.request_type = request_type,
};
snprintf(session_id, sizeof(session_id), "%p", s->session);
snprintf(request_type, sizeof(request_type), "Action: %s", action);
ast_security_event_report(AST_SEC_EVT(&req_bad_format));
}
static void report_failed_challenge_response(const struct mansession *s,
const char *response, const char *expected_response)
{
char session_id[32];
struct ast_security_event_chal_resp_failed chal_resp_failed = {
.common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
.common.version = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
.common.service = "AMI",
.common.account_id = s->session->username,
.common.session_tv = &s->session->sessionstart_tv,
.common.local_addr = {
.addr = &s->tcptls_session->parent->local_address,
.transport = mansession_get_transport(s),
},
.common.remote_addr = {
.addr = &s->session->addr,
.transport = mansession_get_transport(s),
},
.common.session_id = session_id,
.challenge = s->session->challenge,
.response = response,
.expected_response = expected_response,
};
snprintf(session_id, sizeof(session_id), "%p", s->session);
ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
}
static void report_session_limit(const struct mansession *s)
{
char session_id[32];
struct ast_security_event_session_limit session_limit = {
.common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
.common.version = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
.common.service = "AMI",
.common.account_id = s->session->username,
.common.session_tv = &s->session->sessionstart_tv,
.common.local_addr = {
.addr = &s->tcptls_session->parent->local_address,
.transport = mansession_get_transport(s),
},
.common.remote_addr = {
.addr = &s->session->addr,
.transport = mansession_get_transport(s),
},
.common.session_id = session_id,
};
snprintf(session_id, sizeof(session_id), "%p", s->session);
ast_security_event_report(AST_SEC_EVT(&session_limit));
}
/*
* Here we start with action_ handlers for AMI actions,
* and the internal functions used by them.
* Generally, the handlers are called action_foo()
*/
/* helper function for action_login() */
static int authenticate(struct mansession *s, const struct message *m)
{
const char *username = astman_get_header(m, "Username");
const char *password = astman_get_header(m, "Secret");
int error = -1;
struct ast_manager_user *user = NULL;
regex_t *regex_filter;
struct ao2_iterator filter_iter;
if (ast_strlen_zero(username)) { /* missing username */
return -1;
}
/* locate user in locked state */
AST_RWLIST_WRLOCK(&users);
if (!(user = get_manager_by_name_locked(username))) {
report_invalid_user(s, username);
ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
} else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
report_failed_acl(s, username);
ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
} else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
const char *key = astman_get_header(m, "Key");
if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
int x;
int len = 0;
char md5key[256] = "";
struct MD5Context md5;
unsigned char digest[16];
MD5Init(&md5);
MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
MD5Final(digest, &md5);
for (x = 0; x < 16; x++)
len += sprintf(md5key + len, "%02hhx", digest[x]);
if (!strcmp(md5key, key)) {
error = 0;
} else {
report_failed_challenge_response(s, key, md5key);
}
} else {
ast_debug(1, "MD5 authentication is not possible. challenge: '%s'\n",
S_OR(s->session->challenge, ""));
}
} else if (user->secret) {
if (!strcmp(password, user->secret)) {
error = 0;
} else {
report_inval_password(s, username);
}
}
if (error) {
ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
AST_RWLIST_UNLOCK(&users);
return -1;
}
/* auth complete */
/* All of the user parameters are copied to the session so that in the event
* of a reload and a configuration change, the session parameters are not
* changed. */
ast_copy_string(s->session->username, username, sizeof(s->session->username));
s->session->readperm = user->readperm;
s->session->writeperm = user->writeperm;
s->session->writetimeout = user->writetimeout;
if (user->chanvars) {
s->session->chanvars = ast_variables_dup(user->chanvars);
}
filter_iter = ao2_iterator_init(user->whitefilters, 0);
while ((regex_filter = ao2_iterator_next(&filter_iter))) {
ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
ao2_t_ref(regex_filter, -1, "remove iterator ref");
}
ao2_iterator_destroy(&filter_iter);
filter_iter = ao2_iterator_init(user->blackfilters, 0);
while ((regex_filter = ao2_iterator_next(&filter_iter))) {
ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
ao2_t_ref(regex_filter, -1, "remove iterator ref");
}
ao2_iterator_destroy(&filter_iter);
s->session->sessionstart = time(NULL);
s->session->sessionstart_tv = ast_tvnow();
set_eventmask(s, astman_get_header(m, "Events"));
report_auth_success(s);
AST_RWLIST_UNLOCK(&users);
return 0;
}
static int action_ping(struct mansession *s, const struct message *m)
{
const char *actionid = astman_get_header(m, "ActionID");
struct timeval now = ast_tvnow();
astman_append(s, "Response: Success\r\n");
if (!ast_strlen_zero(actionid)){
astman_append(s, "ActionID: %s\r\n", actionid);
}
astman_append(
s,
"Ping: Pong\r\n"
"Timestamp: %ld.%06lu\r\n"
"\r\n",
(long) now.tv_sec, (unsigned long) now.tv_usec);
return 0;
}
static int action_getconfig(struct mansession *s, const struct message *m)
{
struct ast_config *cfg;
const char *fn = astman_get_header(m, "Filename");
const char *category = astman_get_header(m, "Category");
const char *filter = astman_get_header(m, "Filter");
const char *category_name;
int catcount = 0;
int lineno = 0;
struct ast_category *cur_category = NULL;
struct ast_variable *v;
struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
if (ast_strlen_zero(fn)) {
astman_send_error(s, m, "Filename not specified");
return 0;
}
cfg = ast_config_load2(fn, "manager", config_flags);
if (cfg == CONFIG_STATUS_FILEMISSING) {
astman_send_error(s, m, "Config file not found");
return 0;
} else if (cfg == CONFIG_STATUS_FILEINVALID) {
astman_send_error(s, m, "Config file has invalid format");
return 0;
}
astman_start_ack(s, m);
while ((cur_category = ast_category_browse_filtered(cfg, category, cur_category, filter))) {
struct ast_str *templates;
category_name = ast_category_get_name(cur_category);
lineno = 0;
astman_append(s, "Category-%06d: %s\r\n", catcount, category_name);
if (ast_category_is_template(cur_category)) {
astman_append(s, "IsTemplate-%06d: %d\r\n", catcount, 1);
}
if ((templates = ast_category_get_templates(cur_category))
&& ast_str_strlen(templates) > 0) {
astman_append(s, "Templates-%06d: %s\r\n", catcount, ast_str_buffer(templates));
ast_free(templates);
}
for (v = ast_category_first(cur_category); v; v = v->next) {
astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
}
catcount++;
}
if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
astman_append(s, "No categories found\r\n");
}
ast_config_destroy(cfg);
astman_append(s, "\r\n");
return 0;
}
static int action_listcategories(struct mansession *s, const struct message *m)
{
struct ast_config *cfg;
const char *fn = astman_get_header(m, "Filename");
const char *match = astman_get_header(m, "Match");
struct ast_category *category = NULL;
struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
int catcount = 0;
if (ast_strlen_zero(fn)) {
astman_send_error(s, m, "Filename not specified");
return 0;
}
if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
astman_send_error(s, m, "Config file not found");
return 0;
} else if (cfg == CONFIG_STATUS_FILEINVALID) {
astman_send_error(s, m, "Config file has invalid format");
return 0;
}
astman_start_ack(s, m);
while ((category = ast_category_browse_filtered(cfg, NULL, category, match))) {
astman_append(s, "Category-%06d: %s\r\n", catcount, ast_category_get_name(category));
catcount++;
}
if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
astman_append(s, "Error: no categories found\r\n");
}
ast_config_destroy(cfg);
astman_append(s, "\r\n");
return 0;
}
/*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
static void json_escape(char *out, const char *in)
{
for (; *in; in++) {
if (*in == '\\' || *in == '\"') {
*out++ = '\\';
}
*out++ = *in;
}
*out = '\0';
}
/*!
* \internal
* \brief Append a JSON escaped string to the manager stream.
*
* \param s AMI stream to append a string.
* \param str String to append to the stream after JSON escaping it.
*
* \return Nothing
*/
static void astman_append_json(struct mansession *s, const char *str)
{
char *buf;
buf = ast_alloca(2 * strlen(str) + 1);
json_escape(buf, str);
astman_append(s, "%s", buf);
}
static int action_getconfigjson(struct mansession *s, const struct message *m)
{
struct ast_config *cfg;
const char *fn = astman_get_header(m, "Filename");
const char *filter = astman_get_header(m, "Filter");
const char *category = astman_get_header(m, "Category");
struct ast_category *cur_category = NULL;
const char *category_name;
struct ast_variable *v;
int comma1 = 0;
struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
if (ast_strlen_zero(fn)) {
astman_send_error(s, m, "Filename not specified");
return 0;
}
if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
astman_send_error(s, m, "Config file not found");
return 0;
} else if (cfg == CONFIG_STATUS_FILEINVALID) {
astman_send_error(s, m, "Config file has invalid format");
return 0;
}
astman_start_ack(s, m);
astman_append(s, "JSON: {");
while ((cur_category = ast_category_browse_filtered(cfg, category, cur_category, filter))) {
int comma2 = 0;
struct ast_str *templates;
category_name = ast_category_get_name(cur_category);
astman_append(s, "%s\"", comma1 ? "," : "");
astman_append_json(s, category_name);
astman_append(s, "\":{");
comma1 = 1;
if (ast_category_is_template(cur_category)) {
astman_append(s, "\"istemplate\":1");
comma2 = 1;
}
if ((templates = ast_category_get_templates(cur_category))
&& ast_str_strlen(templates) > 0) {
astman_append(s, "%s", comma2 ? "," : "");
astman_append(s, "\"templates\":\"%s\"", ast_str_buffer(templates));
ast_free(templates);
comma2 = 1;
}
for (v = ast_category_first(cur_category); v; v = v->next) {
astman_append(s, "%s\"", comma2 ? "," : "");
astman_append_json(s, v->name);
astman_append(s, "\":\"");
astman_append_json(s, v->value);
astman_append(s, "\"");
comma2 = 1;
}
astman_append(s, "}");
}
astman_append(s, "}\r\n\r\n");
ast_config_destroy(cfg);
return 0;
}
/*! \brief helper function for action_updateconfig */
static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
{
int x;
char hdr[40];
const char *action, *cat, *var, *value, *match, *line, *options;
struct ast_variable *v;
struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
enum error_type result = 0;
for (x = 0; x < 100000; x++) { /* 100000 = the max number of allowed updates + 1 */
unsigned int object = 0;
char *dupoptions;
int allowdups = 0;
int istemplate = 0;
int ignoreerror = 0;
char *inherit = NULL;
char *catfilter = NULL;
char *token;
int foundvar = 0;
int foundcat = 0;
struct ast_category *category = NULL;
snprintf(hdr, sizeof(hdr), "Action-%06d", x);
action = astman_get_header(m, hdr);
if (ast_strlen_zero(action)) /* breaks the for loop if no action header */
break; /* this could cause problems if actions come in misnumbered */
snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
cat = astman_get_header(m, hdr);
if (ast_strlen_zero(cat)) { /* every action needs a category */
result = UNSPECIFIED_CATEGORY;
break;
}
snprintf(hdr, sizeof(hdr), "Var-%06d", x);
var = astman_get_header(m, hdr);
snprintf(hdr, sizeof(hdr), "Value-%06d", x);
value = astman_get_header(m, hdr);
if (!ast_strlen_zero(value) && *value == '>') {
object = 1;
value++;
}
snprintf(hdr, sizeof(hdr), "Match-%06d", x);
match = astman_get_header(m, hdr);
snprintf(hdr, sizeof(hdr), "Line-%06d", x);
line = astman_get_header(m, hdr);
snprintf(hdr, sizeof(hdr), "Options-%06d", x);
options = astman_get_header(m, hdr);
if (!ast_strlen_zero(options)) {
dupoptions = ast_strdupa(options);
while ((token = ast_strsep(&dupoptions, ',', AST_STRSEP_STRIP))) {
if (!strcasecmp("allowdups", token)) {
allowdups = 1;
continue;
}
if (!strcasecmp("template", token)) {
istemplate = 1;
continue;
}
if (!strcasecmp("ignoreerror", token)) {
ignoreerror = 1;
continue;
}
if (ast_begins_with(token, "inherit")) {
char *c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
if (c) {
inherit = ast_strdupa(c);
}
continue;
}
if (ast_begins_with(token, "catfilter")) {
char *c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
if (c) {
catfilter = ast_strdupa(c);
}
continue;
}
}
}
if (!strcasecmp(action, "newcat")) {
struct ast_category *template;
char *tmpl_name = NULL;
if (!allowdups) {
if (ast_category_get(cfg, cat, "TEMPLATES=include")) {
if (ignoreerror) {
continue;
} else {
result = FAILURE_NEWCAT; /* already exist */
break;
}
}
}
if (istemplate) {
category = ast_category_new_template(cat, dfn, -1);
} else {
category = ast_category_new(cat, dfn, -1);
}
if (!category) {
result = FAILURE_ALLOCATION;
break;
}
if (inherit) {
while ((tmpl_name = ast_strsep(&inherit, ',', AST_STRSEP_STRIP))) {
if ((template = ast_category_get(cfg, tmpl_name, "TEMPLATES=restrict"))) {
if (ast_category_inherit(category, template)) {
result = FAILURE_ALLOCATION;
break;
}
} else {
ast_category_destroy(category);
category = NULL;
result = FAILURE_TEMPLATE; /* template not found */
break;
}
}
}
if (category != NULL) {
if (ast_strlen_zero(match)) {
ast_category_append(cfg, category);
} else {
if (ast_category_insert(cfg, category, match)) {
ast_category_destroy(category);
result = FAILURE_NEWCAT;
break;
}
}
}
} else if (!strcasecmp(action, "renamecat")) {
if (ast_strlen_zero(value)) {
result = UNSPECIFIED_ARGUMENT;
break;
}
foundcat = 0;
while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
ast_category_rename(category, value);
foundcat = 1;
}
if (!foundcat) {
result = UNKNOWN_CATEGORY;
break;
}
} else if (!strcasecmp(action, "delcat")) {
foundcat = 0;
while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
category = ast_category_delete(cfg, category);
foundcat = 1;
}
if (!foundcat && !ignoreerror) {
result = UNKNOWN_CATEGORY;
break;
}
} else if (!strcasecmp(action, "emptycat")) {
foundcat = 0;
while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
ast_category_empty(category);
foundcat = 1;
}
if (!foundcat) {
result = UNKNOWN_CATEGORY;
break;
}
} else if (!strcasecmp(action, "update")) {
if (ast_strlen_zero(var)) {
result = UNSPECIFIED_ARGUMENT;
break;
}
foundcat = 0;
foundvar = 0;
while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
if (!ast_variable_update(category, var, value, match, object)) {
foundvar = 1;
}
foundcat = 1;
}
if (!foundcat) {
result = UNKNOWN_CATEGORY;
break;
}
if (!foundvar) {
result = FAILURE_UPDATE;
break;
}
} else if (!strcasecmp(action, "delete")) {
if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
result = UNSPECIFIED_ARGUMENT;
break;
}
foundcat = 0;
foundvar = 0;
while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
if (!ast_variable_delete(category, var, match, line)) {
foundvar = 1;
}
foundcat = 1;
}
if (!foundcat) {
result = UNKNOWN_CATEGORY;
break;
}
if (!foundvar && !ignoreerror) {
result = FAILURE_UPDATE;
break;
}
} else if (!strcasecmp(action, "append")) {
if (ast_strlen_zero(var)) {
result = UNSPECIFIED_ARGUMENT;
break;
}
foundcat = 0;
while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
if (!(v = ast_variable_new(var, value, dfn))) {
result = FAILURE_ALLOCATION;
break;
}
if (object || (match && !strcasecmp(match, "object"))) {
v->object = 1;
}
ast_variable_append(category, v);
foundcat = 1;
}
if (!foundcat) {
result = UNKNOWN_CATEGORY;
break;
}
} else if (!strcasecmp(action, "insert")) {
if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
result = UNSPECIFIED_ARGUMENT;
break;
}
foundcat = 0;
while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
if (!(v = ast_variable_new(var, value, dfn))) {
result = FAILURE_ALLOCATION;
break;
}
ast_variable_insert(category, v, line);
foundcat = 1;
}
if (!foundcat) {
result = UNKNOWN_CATEGORY;
break;
}
}
else {
ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
result = UNKNOWN_ACTION;
break;
}
}
ast_free(str1);
ast_free(str2);
return result;
}
static int action_updateconfig(struct mansession *s, const struct message *m)
{
struct ast_config *cfg;
const char *sfn = astman_get_header(m, "SrcFilename");
const char *dfn = astman_get_header(m, "DstFilename");
int res;
const char *rld = astman_get_header(m, "Reload");
int preserve_effective_context = CONFIG_SAVE_FLAG_PRESERVE_EFFECTIVE_CONTEXT;
const char *preserve_effective_context_string = astman_get_header(m, "PreserveEffectiveContext");
struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
enum error_type result;
if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
astman_send_error(s, m, "Filename not specified");
return 0;
}
if (!(cfg = ast_config_load2(sfn, "manager", config_flags))) {
astman_send_error(s, m, "Config file not found");
return 0;
} else if (cfg == CONFIG_STATUS_FILEINVALID) {
astman_send_error(s, m, "Config file has invalid format");
return 0;
}
result = handle_updates(s, m, cfg, dfn);
if (!result) {
ast_include_rename(cfg, sfn, dfn); /* change the include references from dfn to sfn, so things match up */
if (!ast_strlen_zero(preserve_effective_context_string) && !ast_true(preserve_effective_context_string)) {
preserve_effective_context = CONFIG_SAVE_FLAG_NONE;
}
res = ast_config_text_file_save2(dfn, cfg, "Manager", preserve_effective_context);
ast_config_destroy(cfg);
if (res) {
astman_send_error(s, m, "Save of config failed");
return 0;
}
astman_send_ack(s, m, NULL);
if (!ast_strlen_zero(rld)) {
if (ast_true(rld)) {
rld = NULL;
}
ast_module_reload(rld);
}
} else {
ast_config_destroy(cfg);
switch(result) {
case UNKNOWN_ACTION:
astman_send_error(s, m, "Unknown action command");
break;
case UNKNOWN_CATEGORY:
astman_send_error(s, m, "Given category does not exist");
break;
case UNSPECIFIED_CATEGORY:
astman_send_error(s, m, "Category not specified");
break;
case UNSPECIFIED_ARGUMENT:
astman_send_error(s, m, "Problem with category, value, or line (if required)");
break;
case FAILURE_ALLOCATION:
astman_send_error(s, m, "Memory allocation failure, this should not happen");
break;
case FAILURE_NEWCAT:
astman_send_error(s, m, "Create category did not complete successfully");
break;
case FAILURE_DELCAT:
astman_send_error(s, m, "Delete category did not complete successfully");
break;
case FAILURE_EMPTYCAT:
astman_send_error(s, m, "Empty category did not complete successfully");
break;
case FAILURE_UPDATE:
astman_send_error(s, m, "Update did not complete successfully");
break;
case FAILURE_DELETE:
astman_send_error(s, m, "Delete did not complete successfully");
break;
case FAILURE_APPEND:
astman_send_error(s, m, "Append did not complete successfully");
break;
case FAILURE_TEMPLATE:
astman_send_error(s, m, "Template category not found");
break;
}
}
return 0;
}
static int action_createconfig(struct mansession *s, const struct message *m)
{
int fd;
const char *fn = astman_get_header(m, "Filename");
struct ast_str *filepath = ast_str_alloca(PATH_MAX);
ast_str_set(&filepath, 0, "%s/", ast_config_AST_CONFIG_DIR);
ast_str_append(&filepath, 0, "%s", fn);
if ((fd = open(ast_str_buffer(filepath), O_CREAT | O_EXCL, AST_FILE_MODE)) != -1) {
close(fd);
astman_send_ack(s, m, "New configuration file created successfully");
} else {
astman_send_error(s, m, strerror(errno));
}
return 0;
}
static int action_waitevent(struct mansession *s, const struct message *m)
{
const char *timeouts = astman_get_header(m, "Timeout");
int timeout = -1;
int x;
int needexit = 0;
const char *id = astman_get_header(m, "ActionID");
char idText[256];
if (!ast_strlen_zero(id)) {
snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
} else {
idText[0] = '\0';
}
if (!ast_strlen_zero(timeouts)) {
sscanf(timeouts, "%30i", &timeout);
if (timeout < -1) {
timeout = -1;
}
/* XXX maybe put an upper bound, or prevent the use of 0 ? */
}
ao2_lock(s->session);
if (s->session->waiting_thread != AST_PTHREADT_NULL) {
pthread_kill(s->session->waiting_thread, SIGURG);
}
if (s->session->managerid) { /* AMI-over-HTTP session */
/*
* Make sure the timeout is within the expire time of the session,
* as the client will likely abort the request if it does not see
* data coming after some amount of time.
*/
time_t now = time(NULL);
int max = s->session->sessiontimeout - now - 10;
if (max < 0) { /* We are already late. Strange but possible. */
max = 0;
}
if (timeout < 0 || timeout > max) {
timeout = max;
}
if (!s->session->send_events) { /* make sure we record events */
s->session->send_events = -1;
}
}
ao2_unlock(s->session);
/* XXX should this go inside the lock ? */
s->session->waiting_thread = pthread_self(); /* let new events wake up this thread */
ast_debug(1, "Starting waiting for an event!\n");
for (x = 0; x < timeout || timeout < 0; x++) {
ao2_lock(s->session);
if (AST_RWLIST_NEXT(s->session->last_ev, eq_next)) {
needexit = 1;
}
/* We can have multiple HTTP session point to the same mansession entry.
* The way we deal with it is not very nice: newcomers kick out the previous
* HTTP session. XXX this needs to be improved.
*/
if (s->session->waiting_thread != pthread_self()) {
needexit = 1;
}
if (s->session->needdestroy) {
needexit = 1;
}
ao2_unlock(s->session);
if (needexit) {
break;
}
if (s->session->managerid == 0) { /* AMI session */
if (ast_wait_for_input(ast_iostream_get_fd(s->session->stream), 1000)) {
break;
}
} else { /* HTTP session */
sleep(1);
}
}
ast_debug(1, "Finished waiting for an event!\n");
ao2_lock(s->session);
if (s->session->waiting_thread == pthread_self()) {
struct eventqent *eqe = s->session->last_ev;
astman_send_response(s, m, "Success", "Waiting for Event completed.");
while ((eqe = advance_event(eqe))) {
if (((s->session->readperm & eqe->category) == eqe->category)
&& ((s->session->send_events & eqe->category) == eqe->category)
&& match_filter(s, eqe->eventdata)) {
astman_append(s, "%s", eqe->eventdata);
}
s->session->last_ev = eqe;
}
astman_append(s,
"Event: WaitEventComplete\r\n"
"%s"
"\r\n", idText);
s->session->waiting_thread = AST_PTHREADT_NULL;
} else {
ast_debug(1, "Abandoning event request!\n");
}
ao2_unlock(s->session);
return 0;
}
static int action_listcommands(struct mansession *s, const struct message *m)
{
struct manager_action *cur;
struct ast_str *temp = ast_str_alloca(MAX_AUTH_PERM_STRING);
astman_start_ack(s, m);
AST_RWLIST_RDLOCK(&actions);
AST_RWLIST_TRAVERSE(&actions, cur, list) {
if ((s->session->writeperm & cur->authority) || cur->authority == 0) {
astman_append(s, "%s: %s (Priv: %s)\r\n",
cur->action, cur->synopsis, authority_to_str(cur->authority, &temp));
}
}
AST_RWLIST_UNLOCK(&actions);
astman_append(s, "\r\n");
return 0;
}
static int action_events(struct mansession *s, const struct message *m)
{
const char *mask = astman_get_header(m, "EventMask");
int res, x;
const char *id = astman_get_header(m, "ActionID");
char id_text[256];
if (!ast_strlen_zero(id)) {
snprintf(id_text, sizeof(id_text), "ActionID: %s\r\n", id);
} else {
id_text[0] = '\0';
}
res = set_eventmask(s, mask);
if (broken_events_action) {
/* if this option is set we should not return a response on
* error, or when all events are set */
if (res > 0) {
for (x = 0; x < ARRAY_LEN(perms); x++) {
if (!strcasecmp(perms[x].label, "all") && res == perms[x].num) {
return 0;
}
}
astman_append(s, "Response: Success\r\n%s"
"Events: On\r\n\r\n", id_text);
} else if (res == 0)
astman_append(s, "Response: Success\r\n%s"
"Events: Off\r\n\r\n", id_text);
return 0;
}
if (res > 0)
astman_append(s, "Response: Success\r\n%s"
"Events: On\r\n\r\n", id_text);
else if (res == 0)
astman_append(s, "Response: Success\r\n%s"
"Events: Off\r\n\r\n", id_text);
else
astman_send_error(s, m, "Invalid event mask");
return 0;
}
static int action_logoff(struct mansession *s, const struct message *m)
{
astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
return -1;
}
static int action_login(struct mansession *s, const struct message *m)
{
/* still authenticated - don't process again */
if (s->session->authenticated) {
astman_send_ack(s, m, "Already authenticated");
return 0;
}
if (authenticate(s, m)) {
sleep(1);
astman_send_error(s, m, "Authentication failed");
return -1;
}
s->session->authenticated = 1;
ast_atomic_fetchadd_int(&unauth_sessions, -1);
if (manager_displayconnects(s->session)) {
ast_verb(2, "%sManager '%s' logged on from %s\n", (s->session->managerid ? "HTTP " : ""), s->session->username, ast_sockaddr_stringify_addr(&s->session->addr));
}
astman_send_ack(s, m, "Authentication accepted");
if ((s->session->send_events & EVENT_FLAG_SYSTEM)
&& (s->session->readperm & EVENT_FLAG_SYSTEM)
&& ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
struct ast_str *auth = ast_str_alloca(MAX_AUTH_PERM_STRING);
const char *cat_str = authority_to_str(EVENT_FLAG_SYSTEM, &auth);
long uptime = 0;
long lastreloaded = 0;
struct timeval tmp;
struct timeval curtime = ast_tvnow();
if (ast_startuptime.tv_sec) {
tmp = ast_tvsub(curtime, ast_startuptime);
uptime = tmp.tv_sec;
}
if (ast_lastreloadtime.tv_sec) {
tmp = ast_tvsub(curtime, ast_lastreloadtime);
lastreloaded = tmp.tv_sec;
}
astman_append(s, "Event: FullyBooted\r\n"
"Privilege: %s\r\n"
"Uptime: %ld\r\n"
"LastReload: %ld\r\n"
"Status: Fully Booted\r\n\r\n", cat_str, uptime, lastreloaded);
}
return 0;
}
static int action_challenge(struct mansession *s, const struct message *m)
{
const char *authtype = astman_get_header(m, "AuthType");
if (!strcasecmp(authtype, "MD5")) {
if (ast_strlen_zero(s->session->challenge)) {
snprintf(s->session->challenge, sizeof(s->session->challenge), "%ld", ast_random());
}
mansession_lock(s);
astman_start_ack(s, m);
astman_append(s, "Challenge: %s\r\n\r\n", s->session->challenge);
mansession_unlock(s);
} else {
astman_send_error(s, m, "Must specify AuthType");
}
return 0;
}
static int action_hangup(struct mansession *s, const struct message *m)
{
struct ast_channel *c = NULL;
int causecode = 0; /* all values <= 0 mean 'do not set hangupcause in channel' */
const char *id = astman_get_header(m, "ActionID");
const char *name_or_regex = astman_get_header(m, "Channel");
const char *cause = astman_get_header(m, "Cause");
char idText[256];
regex_t regexbuf;
struct ast_channel_iterator *iter = NULL;
struct ast_str *regex_string;
int channels_matched = 0;
if (ast_strlen_zero(name_or_regex)) {
astman_send_error(s, m, "No channel specified");
return 0;
}
if (!ast_strlen_zero(id)) {
snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
} else {
idText[0] = '\0';
}
if (!ast_strlen_zero(cause)) {
char *endptr;
causecode = strtol(cause, &endptr, 10);
if (causecode < 0 || causecode > 127 || *endptr != '\0') {
ast_log(LOG_NOTICE, "Invalid 'Cause: %s' in manager action Hangup\n", cause);
/* keep going, better to hangup without cause than to not hang up at all */
causecode = 0; /* do not set channel's hangupcause */
}
}
/************************************************/
/* Regular explicit match channel byname hangup */
if (name_or_regex[0] != '/') {
if (!(c = ast_channel_get_by_name(name_or_regex))) {
ast_log(LOG_NOTICE, "Request to hangup non-existent channel: %s\n",
name_or_regex);
astman_send_error(s, m, "No such channel");
return 0;
}
ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
(s->session->managerid ? "HTTP " : ""),
s->session->username,
ast_sockaddr_stringify_addr(&s->session->addr),
ast_channel_name(c));
ast_channel_softhangup_withcause_locked(c, causecode);
c = ast_channel_unref(c);
astman_send_ack(s, m, "Channel Hungup");
return 0;
}
/***********************************************/
/* find and hangup any channels matching regex */
regex_string = ast_str_create(strlen(name_or_regex));
if (!regex_string) {
astman_send_error(s, m, "Memory Allocation Failure");
return 0;
}
/* Make "/regex/" into "regex" */
if (ast_regex_string_to_regex_pattern(name_or_regex, ®ex_string) != 0) {
astman_send_error(s, m, "Regex format invalid, Channel param should be /regex/");
ast_free(regex_string);
return 0;
}
/* if regex compilation fails, hangup fails */
if (regcomp(®exbuf, ast_str_buffer(regex_string), REG_EXTENDED | REG_NOSUB)) {
astman_send_error_va(s, m, "Regex compile failed on: %s", name_or_regex);
ast_free(regex_string);
return 0;
}
astman_send_listack(s, m, "Channels hung up will follow", "start");
iter = ast_channel_iterator_all_new();
if (iter) {
for (; (c = ast_channel_iterator_next(iter)); ast_channel_unref(c)) {
if (regexec(®exbuf, ast_channel_name(c), 0, NULL, 0)) {
continue;
}
ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
(s->session->managerid ? "HTTP " : ""),
s->session->username,
ast_sockaddr_stringify_addr(&s->session->addr),
ast_channel_name(c));
ast_channel_softhangup_withcause_locked(c, causecode);
channels_matched++;
astman_append(s,
"Event: ChannelHungup\r\n"
"Channel: %s\r\n"
"%s"
"\r\n", ast_channel_name(c), idText);
}
ast_channel_iterator_destroy(iter);
}
regfree(®exbuf);
ast_free(regex_string);
astman_send_list_complete_start(s, m, "ChannelsHungupListComplete", channels_matched);
astman_send_list_complete_end(s);
return 0;
}
static int action_setvar(struct mansession *s, const struct message *m)
{
struct ast_channel *c = NULL;
const char *name = astman_get_header(m, "Channel");
const char *varname = astman_get_header(m, "Variable");
const char *varval = astman_get_header(m, "Value");
int res = 0;
if (ast_strlen_zero(varname)) {
astman_send_error(s, m, "No variable specified");
return 0;
}
if (!ast_strlen_zero(name)) {
if (!(c = ast_channel_get_by_name(name))) {
astman_send_error(s, m, "No such channel");
return 0;
}
}
res = pbx_builtin_setvar_helper(c, varname, S_OR(varval, ""));
if (c) {
c = ast_channel_unref(c);
}
if (res == 0) {
astman_send_ack(s, m, "Variable Set");
} else {
astman_send_error(s, m, "Variable not set");
}
return 0;
}
static int action_getvar(struct mansession *s, const struct message *m)
{
struct ast_channel *c = NULL;
const char *name = astman_get_header(m, "Channel");
const char *varname = astman_get_header(m, "Variable");
char *varval;
char workspace[1024];
if (ast_strlen_zero(varname)) {
astman_send_error(s, m, "No variable specified");
return 0;
}
/* We don't want users with insufficient permissions using certain functions. */
if (!(function_capable_string_allowed_with_auths(varname, s->session->writeperm))) {
astman_send_error(s, m, "GetVar Access Forbidden: Variable");
return 0;
}
if (!ast_strlen_zero(name)) {
if (!(c = ast_channel_get_by_name(name))) {
astman_send_error(s, m, "No such channel");
return 0;
}
}
workspace[0] = '\0';
if (varname[strlen(varname) - 1] == ')') {
if (!c) {
c = ast_dummy_channel_alloc();
if (c) {
ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
} else
ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n");
} else {
ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
}
varval = workspace;
} else {
pbx_retrieve_variable(c, varname, &varval, workspace, sizeof(workspace), NULL);
}
if (c) {
c = ast_channel_unref(c);
}
astman_start_ack(s, m);
astman_append(s, "Variable: %s\r\nValue: %s\r\n\r\n", varname, S_OR(varval, ""));
return 0;
}
static void generate_status(struct mansession *s, struct ast_channel *chan, char **vars, int varc, int all_variables, char *id_text, int *count)
{
struct timeval now;
long elapsed_seconds;
struct ast_bridge *bridge;
RAII_VAR(struct ast_str *, variable_str, NULL, ast_free);
struct ast_str *write_transpath = ast_str_alloca(256);
struct ast_str *read_transpath = ast_str_alloca(256);
struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
struct ast_party_id effective_id;
int i;
RAII_VAR(struct ast_channel_snapshot *, snapshot,
ast_channel_snapshot_get_latest(ast_channel_uniqueid(chan)),
ao2_cleanup);
RAII_VAR(struct ast_str *, snapshot_str, NULL, ast_free);
if (!snapshot) {
return;
}
snapshot_str = ast_manager_build_channel_state_string(snapshot);
if (!snapshot_str) {
return;
}
if (all_variables) {
variable_str = ast_str_create(2048);
} else {
variable_str = ast_str_create(1024);
}
if (!variable_str) {
return;
}
now = ast_tvnow();
elapsed_seconds = ast_tvdiff_sec(now, ast_channel_creationtime(chan));
/* Even if all_variables has been specified, explicitly requested variables
* may be global variables or dialplan functions */
for (i = 0; i < varc; i++) {
char valbuf[512], *ret = NULL;
if (vars[i][strlen(vars[i]) - 1] == ')') {
if (ast_func_read(chan, vars[i], valbuf, sizeof(valbuf)) < 0) {
valbuf[0] = '\0';
}
ret = valbuf;
} else {
pbx_retrieve_variable(chan, vars[i], &ret, valbuf, sizeof(valbuf), NULL);
}
ast_str_append(&variable_str, 0, "Variable: %s=%s\r\n", vars[i], ret);
}
/* Walk all channel variables and add them */
if (all_variables) {
struct ast_var_t *variables;
AST_LIST_TRAVERSE(ast_channel_varshead(chan), variables, entries) {
ast_str_append(&variable_str, 0, "Variable: %s=%s\r\n",
ast_var_name(variables), ast_var_value(variables));
}
}
bridge = ast_channel_get_bridge(chan);
effective_id = ast_channel_connected_effective_id(chan);
astman_append(s,
"Event: Status\r\n"
"Privilege: Call\r\n"
"%s"
"Type: %s\r\n"
"DNID: %s\r\n"
"EffectiveConnectedLineNum: %s\r\n"
"EffectiveConnectedLineName: %s\r\n"
"TimeToHangup: %ld\r\n"
"BridgeID: %s\r\n"
"Application: %s\r\n"
"Data: %s\r\n"
"Nativeformats: %s\r\n"
"Readformat: %s\r\n"
"Readtrans: %s\r\n"
"Writeformat: %s\r\n"
"Writetrans: %s\r\n"
"Callgroup: %llu\r\n"
"Pickupgroup: %llu\r\n"
"Seconds: %ld\r\n"
"%s"
"%s"
"\r\n",
ast_str_buffer(snapshot_str),
ast_channel_tech(chan)->type,
S_OR(ast_channel_dialed(chan)->number.str, ""),
S_COR(effective_id.number.valid, effective_id.number.str, "<unknown>"),
S_COR(effective_id.name.valid, effective_id.name.str, "<unknown>"),
(long)ast_channel_whentohangup(chan)->tv_sec,
bridge ? bridge->uniqueid : "",
ast_channel_appl(chan),
ast_channel_data(chan),
ast_format_cap_get_names(ast_channel_nativeformats(chan), &codec_buf),
ast_format_get_name(ast_channel_readformat(chan)),
ast_translate_path_to_str(ast_channel_readtrans(chan), &read_transpath),
ast_format_get_name(ast_channel_writeformat(chan)),
ast_translate_path_to_str(ast_channel_writetrans(chan), &write_transpath),
ast_channel_callgroup(chan),
ast_channel_pickupgroup(chan),
(long)elapsed_seconds,
ast_str_buffer(variable_str),
id_text);
++*count;
ao2_cleanup(bridge);
}
/*! \brief Manager "status" command to show channels */
static int action_status(struct mansession *s, const struct message *m)
{
const char *name = astman_get_header(m, "Channel");
const char *chan_variables = astman_get_header(m, "Variables");
const char *all_chan_variables = astman_get_header(m, "AllVariables");
int all_variables = 0;
const char *id = astman_get_header(m, "ActionID");
char *variables = ast_strdupa(S_OR(chan_variables, ""));
struct ast_channel *chan;
int channels = 0;
int all = ast_strlen_zero(name); /* set if we want all channels */
char id_text[256];
struct ast_channel_iterator *it_chans = NULL;
AST_DECLARE_APP_ARGS(vars,
AST_APP_ARG(name)[100];
);
if (!ast_strlen_zero(all_chan_variables)) {
all_variables = ast_true(all_chan_variables);
}
if (!(function_capable_string_allowed_with_auths(variables, s->session->writeperm))) {
astman_send_error(s, m, "Status Access Forbidden: Variables");
return 0;
}
if (all) {
if (!(it_chans = ast_channel_iterator_all_new())) {
astman_send_error(s, m, "Memory Allocation Failure");
return 1;
}
chan = ast_channel_iterator_next(it_chans);
} else {
chan = ast_channel_get_by_name(name);
if (!chan) {
astman_send_error(s, m, "No such channel");
return 0;
}
}
astman_send_listack(s, m, "Channel status will follow", "start");
if (!ast_strlen_zero(id)) {
snprintf(id_text, sizeof(id_text), "ActionID: %s\r\n", id);
} else {
id_text[0] = '\0';
}
if (!ast_strlen_zero(chan_variables)) {
AST_STANDARD_APP_ARGS(vars, variables);
}
/* if we look by name, we break after the first iteration */
for (; chan; all ? chan = ast_channel_iterator_next(it_chans) : 0) {
ast_channel_lock(chan);
generate_status(s, chan, vars.name, vars.argc, all_variables, id_text, &channels);
ast_channel_unlock(chan);
chan = ast_channel_unref(chan);
}
if (it_chans) {
ast_channel_iterator_destroy(it_chans);
}
astman_send_list_complete_start(s, m, "StatusComplete", channels);
astman_append(s, "Items: %d\r\n", channels);
astman_send_list_complete_end(s);
return 0;
}
static int action_sendtext(struct mansession *s, const struct message *m)
{
struct ast_channel *c;
const char *name = astman_get_header(m, "Channel");
const char *textmsg = astman_get_header(m, "Message");
struct ast_control_read_action_payload *frame_payload;
int payload_size;
int frame_size;
int res;
if (ast_strlen_zero(name)) {
astman_send_error(s, m, "No channel specified");
return 0;
}
if (ast_strlen_zero(textmsg)) {
astman_send_error(s, m, "No Message specified");
return 0;
}
c = ast_channel_get_by_name(name);
if (!c) {
astman_send_error(s, m, "No such channel");
return 0;
}
payload_size = strlen(textmsg) + 1;
frame_size = payload_size + sizeof(*frame_payload);
frame_payload = ast_malloc(frame_size);
if (!frame_payload) {
ast_channel_unref(c);
astman_send_error(s, m, "Failure");
return 0;
}
frame_payload->action = AST_FRAME_READ_ACTION_SEND_TEXT;
frame_payload->payload_size = payload_size;
memcpy(frame_payload->payload, textmsg, payload_size);
res = ast_queue_control_data(c, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
ast_free(frame_payload);
ast_channel_unref(c);
if (res >= 0) {
astman_send_ack(s, m, "Success");
} else {
astman_send_error(s, m, "Failure");
}
return 0;
}
/*! \brief action_redirect: The redirect manager command */
static int action_redirect(struct mansession *s, const struct message *m)
{
char buf[256];
const char *name = astman_get_header(m, "Channel");
const char *name2 = astman_get_header(m, "ExtraChannel");
const char *exten = astman_get_header(m, "Exten");
const char *exten2 = astman_get_header(m, "ExtraExten");
const char *context = astman_get_header(m, "Context");
const char *context2 = astman_get_header(m, "ExtraContext");
const char *priority = astman_get_header(m, "Priority");
const char *priority2 = astman_get_header(m, "ExtraPriority");
struct ast_channel *chan;
struct ast_channel *chan2;
int pi = 0;
int pi2 = 0;
int res;
int chan1_wait = 0;
int chan2_wait = 0;
if (ast_strlen_zero(name)) {
astman_send_error(s, m, "Channel not specified");
return 0;
}
if (ast_strlen_zero(context)) {
astman_send_error(s, m, "Context not specified");
return 0;
}
if (ast_strlen_zero(exten)) {
astman_send_error(s, m, "Exten not specified");
return 0;
}
if (ast_strlen_zero(priority)) {
astman_send_error(s, m, "Priority not specified");
return 0;
}
if (sscanf(priority, "%30d", &pi) != 1) {
pi = ast_findlabel_extension(NULL, context, exten, priority, NULL);
}
if (pi < 1) {
astman_send_error(s, m, "Priority is invalid");
return 0;
}
if (!ast_strlen_zero(name2) && !ast_strlen_zero(context2)) {
/* We have an ExtraChannel and an ExtraContext */
if (ast_strlen_zero(exten2)) {
astman_send_error(s, m, "ExtraExten not specified");
return 0;
}
if (ast_strlen_zero(priority2)) {
astman_send_error(s, m, "ExtraPriority not specified");
return 0;
}
if (sscanf(priority2, "%30d", &pi2) != 1) {
pi2 = ast_findlabel_extension(NULL, context2, exten2, priority2, NULL);
}
if (pi2 < 1) {
astman_send_error(s, m, "ExtraPriority is invalid");
return 0;
}
}
chan = ast_channel_get_by_name(name);
if (!chan) {
snprintf(buf, sizeof(buf), "Channel does not exist: %s", name);
astman_send_error(s, m, buf);
return 0;
}
if (ast_check_hangup_locked(chan)) {
astman_send_error(s, m, "Redirect failed, channel not up.");
chan = ast_channel_unref(chan);
return 0;
}
if (ast_strlen_zero(name2)) {
/* Single channel redirect in progress. */
res = ast_async_goto(chan, context, exten, pi);
if (!res) {
astman_send_ack(s, m, "Redirect successful");
} else {
astman_send_error(s, m, "Redirect failed");
}
chan = ast_channel_unref(chan);
return 0;
}
chan2 = ast_channel_get_by_name(name2);
if (!chan2) {
snprintf(buf, sizeof(buf), "ExtraChannel does not exist: %s", name2);
astman_send_error(s, m, buf);
chan = ast_channel_unref(chan);
return 0;
}
if (ast_check_hangup_locked(chan2)) {
astman_send_error(s, m, "Redirect failed, extra channel not up.");
chan2 = ast_channel_unref(chan2);
chan = ast_channel_unref(chan);
return 0;
}
/* Dual channel redirect in progress. */
ast_channel_lock(chan);
if (ast_channel_is_bridged(chan)) {
ast_set_flag(ast_channel_flags(chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT);
chan1_wait = 1;
}
ast_channel_unlock(chan);
ast_channel_lock(chan2);
if (ast_channel_is_bridged(chan2)) {
ast_set_flag(ast_channel_flags(chan2), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT);
chan2_wait = 1;
}
ast_channel_unlock(chan2);
res = ast_async_goto(chan, context, exten, pi);
if (!res) {
if (!ast_strlen_zero(context2)) {
res = ast_async_goto(chan2, context2, exten2, pi2);
} else {
res = ast_async_goto(chan2, context, exten, pi);
}
if (!res) {
astman_send_ack(s, m, "Dual Redirect successful");
} else {
astman_send_error(s, m, "Secondary redirect failed");
}
} else {
astman_send_error(s, m, "Redirect failed");
}
/* Release the bridge wait. */
if (chan1_wait) {
ast_channel_clear_flag(chan, AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT);
}
if (chan2_wait) {
ast_channel_clear_flag(chan2, AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT);
}
chan2 = ast_channel_unref(chan2);
chan = ast_channel_unref(chan);
return 0;
}
static int action_blind_transfer(struct mansession *s, const struct message *m)
{
const char *name = astman_get_header(m, "Channel");
const char *exten = astman_get_header(m, "Exten");
const char *context = astman_get_header(m, "Context");
struct ast_channel *chan;
if (ast_strlen_zero(name)) {
astman_send_error(s, m, "No channel specified");
return 0;
}
if (ast_strlen_zero(exten)) {
astman_send_error(s, m, "No extension specified");
return 0;
}
chan = ast_channel_get_by_name(name);
if (!chan) {
astman_send_error(s, m, "Channel specified does not exist");
return 0;
}
if (ast_strlen_zero(context)) {
context = ast_channel_context(chan);
}
switch (ast_bridge_transfer_blind(1, chan, exten, context, NULL, NULL)) {
case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
astman_send_error(s, m, "Transfer not permitted");
break;
case AST_BRIDGE_TRANSFER_INVALID:
astman_send_error(s, m, "Transfer invalid");
break;
case AST_BRIDGE_TRANSFER_FAIL:
astman_send_error(s, m, "Transfer failed");
break;
case AST_BRIDGE_TRANSFER_SUCCESS:
astman_send_ack(s, m, "Transfer succeeded");
break;
}
ast_channel_unref(chan);
return 0;
}
static int action_atxfer(struct mansession *s, const struct message *m)
{
const char *name = astman_get_header(m, "Channel");
const char *exten = astman_get_header(m, "Exten");
const char *context = astman_get_header(m, "Context");
struct ast_channel *chan = NULL;
char feature_code[AST_FEATURE_MAX_LEN];
const char *digit;
if (ast_strlen_zero(name)) {
astman_send_error(s, m, "No channel specified");
return 0;
}
if (ast_strlen_zero(exten)) {
astman_send_error(s, m, "No extension specified");
return 0;
}
if (!(chan = ast_channel_get_by_name(name))) {
astman_send_error(s, m, "Channel specified does not exist");
return 0;
}
ast_channel_lock(chan);
if (ast_get_builtin_feature(chan, "atxfer", feature_code, sizeof(feature_code)) ||
ast_strlen_zero(feature_code)) {
ast_channel_unlock(chan);
astman_send_error(s, m, "No attended transfer feature code found");
ast_channel_unref(chan);
return 0;
}
ast_channel_unlock(chan);
if (!ast_strlen_zero(context)) {
pbx_builtin_setvar_helper(chan, "TRANSFER_CONTEXT", context);
}
for (digit = feature_code; *digit; ++digit) {
struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = *digit };
ast_queue_frame(chan, &f);
}
for (digit = exten; *digit; ++digit) {
struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = *digit };
ast_queue_frame(chan, &f);
}
chan = ast_channel_unref(chan);
astman_send_ack(s, m, "Atxfer successfully queued");
return 0;
}
static int action_cancel_atxfer(struct mansession *s, const struct message *m)
{
const char *name = astman_get_header(m, "Channel");
struct ast_channel *chan = NULL;
char *feature_code;
const char *digit;
if (ast_strlen_zero(name)) {
astman_send_error(s, m, "No channel specified");
return 0;
}
if (!(chan = ast_channel_get_by_name(name))) {
astman_send_error(s, m, "Channel specified does not exist");
return 0;
}
ast_channel_lock(chan);
feature_code = ast_get_chan_features_atxferabort(chan);
ast_channel_unlock(chan);
if (!feature_code) {
astman_send_error(s, m, "No disconnect feature code found");
ast_channel_unref(chan);
return 0;
}
for (digit = feature_code; *digit; ++digit) {
struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = *digit };
ast_queue_frame(chan, &f);
}
ast_free(feature_code);
chan = ast_channel_unref(chan);
astman_send_ack(s, m, "CancelAtxfer successfully queued");
return 0;
}
static int check_blacklist(const char *cmd)
{
char *cmd_copy, *cur_cmd;
char *cmd_words[AST_MAX_CMD_LEN] = { NULL, };
int i;
cmd_copy = ast_strdupa(cmd);
for (i = 0; i < MAX_BLACKLIST_CMD_LEN && (cur_cmd = strsep(&cmd_copy, " ")); i++) {
cur_cmd = ast_strip(cur_cmd);
if (ast_strlen_zero(cur_cmd)) {
i--;
continue;
}
cmd_words[i] = cur_cmd;
}
for (i = 0; i < ARRAY_LEN(command_blacklist); i++) {
int j, match = 1;
for (j = 0; command_blacklist[i].words[j]; j++) {
if (ast_strlen_zero(cmd_words[j]) || strcasecmp(cmd_words[j], command_blacklist[i].words[j])) {
match = 0;
break;
}
}
if (match) {
return 1;
}
}
return 0;
}
/*! \brief Manager command "command" - execute CLI command */
static int action_command(struct mansession *s, const struct message *m)
{
const char *cmd = astman_get_header(m, "Command");
char *buf = NULL, *final_buf = NULL, *delim, *output;
char template[] = "/tmp/ast-ami-XXXXXX"; /* template for temporary file */
int fd, ret;
off_t len;
if (ast_strlen_zero(cmd)) {
astman_send_error(s, m, "No command provided");
return 0;
}
if (check_blacklist(cmd)) {
astman_send_error(s, m, "Command blacklisted");
return 0;
}
if ((fd = mkstemp(template)) < 0) {
astman_send_error_va(s, m, "Failed to create temporary file: %s", strerror(errno));
return 0;
}
ret = ast_cli_command(fd, cmd);
astman_send_response_full(s, m, ret == RESULT_SUCCESS ? "Success" : "Error", MSG_MOREDATA, NULL);
/* Determine number of characters available */
if ((len = lseek(fd, 0, SEEK_END)) < 0) {
astman_append(s, "Message: Failed to determine number of characters: %s\r\n", strerror(errno));
goto action_command_cleanup;
}
/* This has a potential to overflow the stack. Hence, use the heap. */
buf = ast_malloc(len + 1);
final_buf = ast_malloc(len + 1);
if (!buf || !final_buf) {
astman_append(s, "Message: Memory allocation failure\r\n");
goto action_command_cleanup;
}
if (lseek(fd, 0, SEEK_SET) < 0) {
astman_append(s, "Message: Failed to set position on temporary file: %s\r\n", strerror(errno));
goto action_command_cleanup;
}
if (read(fd, buf, len) < 0) {
astman_append(s, "Message: Failed to read from temporary file: %s\r\n", strerror(errno));
goto action_command_cleanup;
}
buf[len] = '\0';
term_strip(final_buf, buf, len);
final_buf[len] = '\0';
/* Trim trailing newline */
if (len && final_buf[len - 1] == '\n') {
final_buf[len - 1] = '\0';
}
astman_append(s, "Message: Command output follows\r\n");
delim = final_buf;
while ((output = strsep(&delim, "\n"))) {
astman_append(s, "Output: %s\r\n", output);
}
action_command_cleanup:
astman_append(s, "\r\n");
close(fd);
unlink(template);
ast_free(buf);
ast_free(final_buf);
return 0;
}
/*! \brief helper function for originate */
struct fast_originate_helper {
int timeout;
struct ast_format_cap *cap; /*!< Codecs used for a call */
int early_media;
AST_DECLARE_STRING_FIELDS (
AST_STRING_FIELD(tech);
/*! data can contain a channel name, extension number, username, password, etc. */
AST_STRING_FIELD(data);
AST_STRING_FIELD(app);
AST_STRING_FIELD(appdata);
AST_STRING_FIELD(cid_name);
AST_STRING_FIELD(cid_num);
AST_STRING_FIELD(context);
AST_STRING_FIELD(exten);
AST_STRING_FIELD(idtext);
AST_STRING_FIELD(account);
AST_STRING_FIELD(channelid);
AST_STRING_FIELD(otherchannelid);
);
int priority;
struct ast_variable *vars;
};
/*!
* \internal
*
* \param doomed Struct to destroy.
*
* \return Nothing
*/
static void destroy_fast_originate_helper(struct fast_originate_helper *doomed)
{
ao2_cleanup(doomed->cap);
ast_variables_destroy(doomed->vars);
ast_string_field_free_memory(doomed);
ast_free(doomed);
}
static void *fast_originate(void *data)
{
struct fast_originate_helper *in = data;
int res;
int reason = 0;
struct ast_channel *chan = NULL, *chans[1];
char requested_channel[AST_CHANNEL_NAME];
struct ast_assigned_ids assignedids = {
.uniqueid = in->channelid,
.uniqueid2 = in->otherchannelid
};
if (!ast_strlen_zero(in->app)) {
res = ast_pbx_outgoing_app(in->tech, in->cap, in->data,
in->timeout, in->app, in->appdata, &reason,
AST_OUTGOING_WAIT,
S_OR(in->cid_num, NULL),
S_OR(in->cid_name, NULL),
in->vars, in->account, &chan, &assignedids);
} else {
res = ast_pbx_outgoing_exten(in->tech, in->cap, in->data,
in->timeout, in->context, in->exten, in->priority, &reason,
AST_OUTGOING_WAIT,
S_OR(in->cid_num, NULL),
S_OR(in->cid_name, NULL),
in->vars, in->account, &chan, in->early_media, &assignedids);
}
if (!chan) {
snprintf(requested_channel, AST_CHANNEL_NAME, "%s/%s", in->tech, in->data);
}
/* Tell the manager what happened with the channel */
chans[0] = chan;
if (!ast_strlen_zero(in->app)) {
ast_manager_event_multichan(EVENT_FLAG_CALL, "OriginateResponse", chan ? 1 : 0, chans,
"%s"
"Response: %s\r\n"
"Channel: %s\r\n"
"Application: %s\r\n"
"Data: %s\r\n"
"Reason: %d\r\n"
"Uniqueid: %s\r\n"
"CallerIDNum: %s\r\n"
"CallerIDName: %s\r\n",
in->idtext, res ? "Failure" : "Success",
chan ? ast_channel_name(chan) : requested_channel,
in->app, in->appdata, reason,
chan ? ast_channel_uniqueid(chan) : S_OR(in->channelid, "<unknown>"),
S_OR(in->cid_num, "<unknown>"),
S_OR(in->cid_name, "<unknown>")
);
} else {
ast_manager_event_multichan(EVENT_FLAG_CALL, "OriginateResponse", chan ? 1 : 0, chans,
"%s"
"Response: %s\r\n"
"Channel: %s\r\n"
"Context: %s\r\n"
"Exten: %s\r\n"
"Reason: %d\r\n"
"Uniqueid: %s\r\n"
"CallerIDNum: %s\r\n"
"CallerIDName: %s\r\n",
in->idtext, res ? "Failure" : "Success",
chan ? ast_channel_name(chan) : requested_channel,
in->context, in->exten, reason,
chan ? ast_channel_uniqueid(chan) : S_OR(in->channelid, "<unknown>"),
S_OR(in->cid_num, "<unknown>"),
S_OR(in->cid_name, "<unknown>")
);
}
/* Locked and ref'd by ast_pbx_outgoing_exten or ast_pbx_outgoing_app */
if (chan) {
ast_channel_unlock(chan);
ast_channel_unref(chan);
}
destroy_fast_originate_helper(in);
return NULL;
}
static int aocmessage_get_unit_entry(const struct message *m, struct ast_aoc_unit_entry *entry, unsigned int entry_num)
{
const char *unitamount;
const char *unittype;
struct ast_str *str = ast_str_alloca(32);
memset(entry, 0, sizeof(*entry));
ast_str_set(&str, 0, "UnitAmount(%u)", entry_num);
unitamount = astman_get_header(m, ast_str_buffer(str));
ast_str_set(&str, 0, "UnitType(%u)", entry_num);
unittype = astman_get_header(m, ast_str_buffer(str));
if (!ast_strlen_zero(unitamount) && (sscanf(unitamount, "%30u", &entry->amount) == 1)) {
entry->valid_amount = 1;
}
if (!ast_strlen_zero(unittype) && sscanf(unittype, "%30u", &entry->type) == 1) {
entry->valid_type = 1;
}
return 0;
}
static int action_aocmessage(struct mansession *s, const struct message *m)
{
const char *channel = astman_get_header(m, "Channel");
const char *pchannel = astman_get_header(m, "ChannelPrefix");
const char *msgtype = astman_get_header(m, "MsgType");
const char *chargetype = astman_get_header(m, "ChargeType");
const char *currencyname = astman_get_header(m, "CurrencyName");
const char *currencyamount = astman_get_header(m, "CurrencyAmount");
const char *mult = astman_get_header(m, "CurrencyMultiplier");
const char *totaltype = astman_get_header(m, "TotalType");
const char *aocbillingid = astman_get_header(m, "AOCBillingId");
const char *association_id= astman_get_header(m, "ChargingAssociationId");
const char *association_num = astman_get_header(m, "ChargingAssociationNumber");
const char *association_plan = astman_get_header(m, "ChargingAssociationPlan");
enum ast_aoc_type _msgtype;
enum ast_aoc_charge_type _chargetype;
enum ast_aoc_currency_multiplier _mult = AST_AOC_MULT_ONE;
enum ast_aoc_total_type _totaltype = AST_AOC_TOTAL;
enum ast_aoc_billing_id _billingid = AST_AOC_BILLING_NA;
unsigned int _currencyamount = 0;
int _association_id = 0;
unsigned int _association_plan = 0;
struct ast_channel *chan = NULL;
struct ast_aoc_decoded *decoded = NULL;
struct ast_aoc_encoded *encoded = NULL;
size_t encoded_size = 0;
if (ast_strlen_zero(channel) && ast_strlen_zero(pchannel)) {
astman_send_error(s, m, "Channel and PartialChannel are not specified. Specify at least one of these.");
goto aocmessage_cleanup;
}
if (!(chan = ast_channel_get_by_name(channel)) && !ast_strlen_zero(pchannel)) {
chan = ast_channel_get_by_name_prefix(pchannel, strlen(pchannel));
}
if (!chan) {
astman_send_error(s, m, "No such channel");
goto aocmessage_cleanup;
}
if (ast_strlen_zero(msgtype) || (strcasecmp(msgtype, "d") && strcasecmp(msgtype, "e"))) {
astman_send_error(s, m, "Invalid MsgType");
goto aocmessage_cleanup;
}
if (ast_strlen_zero(chargetype)) {
astman_send_error(s, m, "ChargeType not specified");
goto aocmessage_cleanup;
}
_msgtype = strcasecmp(msgtype, "d") ? AST_AOC_E : AST_AOC_D;
if (!strcasecmp(chargetype, "NA")) {
_chargetype = AST_AOC_CHARGE_NA;
} else if (!strcasecmp(chargetype, "Free")) {
_chargetype = AST_AOC_CHARGE_FREE;
} else if (!strcasecmp(chargetype, "Currency")) {
_chargetype = AST_AOC_CHARGE_CURRENCY;
} else if (!strcasecmp(chargetype, "Unit")) {
_chargetype = AST_AOC_CHARGE_UNIT;
} else {
astman_send_error(s, m, "Invalid ChargeType");
goto aocmessage_cleanup;
}
if (_chargetype == AST_AOC_CHARGE_CURRENCY) {
if (ast_strlen_zero(currencyamount) || (sscanf(currencyamount, "%30u", &_currencyamount) != 1)) {
astman_send_error(s, m, "Invalid CurrencyAmount, CurrencyAmount is a required when ChargeType is Currency");
goto aocmessage_cleanup;
}
if (ast_strlen_zero(mult)) {
astman_send_error(s, m, "ChargeMultiplier unspecified, ChargeMultiplier is required when ChargeType is Currency.");
goto aocmessage_cleanup;
} else if (!strcasecmp(mult, "onethousandth")) {
_mult = AST_AOC_MULT_ONETHOUSANDTH;
} else if (!strcasecmp(mult, "onehundredth")) {
_mult = AST_AOC_MULT_ONEHUNDREDTH;
} else if (!strcasecmp(mult, "onetenth")) {
_mult = AST_AOC_MULT_ONETENTH;
} else if (!strcasecmp(mult, "one")) {
_mult = AST_AOC_MULT_ONE;
} else if (!strcasecmp(mult, "ten")) {
_mult = AST_AOC_MULT_TEN;
} else if (!strcasecmp(mult, "hundred")) {
_mult = AST_AOC_MULT_HUNDRED;
} else if (!strcasecmp(mult, "thousand")) {
_mult = AST_AOC_MULT_THOUSAND;
} else {
astman_send_error(s, m, "Invalid ChargeMultiplier");
goto aocmessage_cleanup;
}
}
/* create decoded object and start setting values */
if (!(decoded = ast_aoc_create(_msgtype, _chargetype, 0))) {
astman_send_error(s, m, "Message Creation Failed");
goto aocmessage_cleanup;
}
if (_msgtype == AST_AOC_D) {
if (!ast_strlen_zero(totaltype) && !strcasecmp(totaltype, "subtotal")) {
_totaltype = AST_AOC_SUBTOTAL;
}
if (ast_strlen_zero(aocbillingid)) {
/* ignore this is optional */
} else if (!strcasecmp(aocbillingid, "Normal")) {
_billingid = AST_AOC_BILLING_NORMAL;
} else if (!strcasecmp(aocbillingid, "ReverseCharge")) {
_billingid = AST_AOC_BILLING_REVERSE_CHARGE;
} else if (!strcasecmp(aocbillingid, "CreditCard")) {
_billingid = AST_AOC_BILLING_CREDIT_CARD;
} else {
astman_send_error(s, m, "Invalid AOC-D AOCBillingId");
goto aocmessage_cleanup;
}
} else {
if (ast_strlen_zero(aocbillingid)) {
/* ignore this is optional */
} else if (!strcasecmp(aocbillingid, "Normal")) {
_billingid = AST_AOC_BILLING_NORMAL;
} else if (!strcasecmp(aocbillingid, "ReverseCharge")) {
_billingid = AST_AOC_BILLING_REVERSE_CHARGE;
} else if (!strcasecmp(aocbillingid, "CreditCard")) {
_billingid = AST_AOC_BILLING_CREDIT_CARD;
} else if (!strcasecmp(aocbillingid, "CallFwdUnconditional")) {
_billingid = AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL;
} else if (!strcasecmp(aocbillingid, "CallFwdBusy")) {
_billingid = AST_AOC_BILLING_CALL_FWD_BUSY;
} else if (!strcasecmp(aocbillingid, "CallFwdNoReply")) {
_billingid = AST_AOC_BILLING_CALL_FWD_NO_REPLY;
} else if (!strcasecmp(aocbillingid, "CallDeflection")) {
_billingid = AST_AOC_BILLING_CALL_DEFLECTION;
} else if (!strcasecmp(aocbillingid, "CallTransfer")) {
_billingid = AST_AOC_BILLING_CALL_TRANSFER;
} else {
astman_send_error(s, m, "Invalid AOC-E AOCBillingId");
goto aocmessage_cleanup;
}
if (!ast_strlen_zero(association_id) && (sscanf(association_id, "%30d", &_association_id) != 1)) {
astman_send_error(s, m, "Invalid ChargingAssociationId");
goto aocmessage_cleanup;
}
if (!ast_strlen_zero(association_plan) && (sscanf(association_plan, "%30u", &_association_plan) != 1)) {
astman_send_error(s, m, "Invalid ChargingAssociationPlan");
goto aocmessage_cleanup;
}
if (_association_id) {
ast_aoc_set_association_id(decoded, _association_id);
} else if (!ast_strlen_zero(association_num)) {
ast_aoc_set_association_number(decoded, association_num, _association_plan);
}
}
if (_chargetype == AST_AOC_CHARGE_CURRENCY) {
ast_aoc_set_currency_info(decoded, _currencyamount, _mult, ast_strlen_zero(currencyname) ? NULL : currencyname);
} else if (_chargetype == AST_AOC_CHARGE_UNIT) {
struct ast_aoc_unit_entry entry;
int i;
/* multiple unit entries are possible, lets get them all */
for (i = 0; i < 32; i++) {
if (aocmessage_get_unit_entry(m, &entry, i)) {
break; /* that's the end then */
}
ast_aoc_add_unit_entry(decoded, entry.valid_amount, entry.amount, entry.valid_type, entry.type);
}
/* at least one unit entry is required */
if (!i) {
astman_send_error(s, m, "Invalid UnitAmount(0), At least one valid unit entry is required when ChargeType is set to Unit");
goto aocmessage_cleanup;
}
}
ast_aoc_set_billing_id(decoded, _billingid);
ast_aoc_set_total_type(decoded, _totaltype);
if ((encoded = ast_aoc_encode(decoded, &encoded_size, NULL)) && !ast_indicate_data(chan, AST_CONTROL_AOC, encoded, encoded_size)) {
astman_send_ack(s, m, "AOC Message successfully queued on channel");
} else {
astman_send_error(s, m, "Error encoding AOC message, could not queue onto channel");
}
aocmessage_cleanup:
ast_aoc_destroy_decoded(decoded);
ast_aoc_destroy_encoded(encoded);
if (chan) {
chan = ast_channel_unref(chan);
}
return 0;
}
static int action_originate(struct mansession *s, const struct message *m)
{
const char *name = astman_get_header(m, "Channel");
const char *exten = astman_get_header(m, "Exten");
const char *context = astman_get_header(m, "Context");
const char *priority = astman_get_header(m, "Priority");
const char *timeout = astman_get_header(m, "Timeout");
const char *callerid = astman_get_header(m, "CallerID");
const char *account = astman_get_header(m, "Account");
const char *app = astman_get_header(m, "Application");
const char *appdata = astman_get_header(m, "Data");
const char *async = astman_get_header(m, "Async");
const char *id = astman_get_header(m, "ActionID");
const char *codecs = astman_get_header(m, "Codecs");
const char *early_media = astman_get_header(m, "Earlymedia");
struct ast_assigned_ids assignedids = {
.uniqueid = astman_get_header(m, "ChannelId"),
.uniqueid2 = astman_get_header(m, "OtherChannelId"),
};
struct ast_variable *vars = NULL;
char *tech, *data;
char *l = NULL, *n = NULL;
int pi = 0;
int res;
int to = 30000;
int reason = 0;
char tmp[256];
char tmp2[256];
struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
pthread_t th;
int bridge_early = 0;
if (!cap) {
astman_send_error(s, m, "Internal Error. Memory allocation failure.");
return 0;
}
ast_format_cap_append(cap, ast_format_slin, 0);
if ((assignedids.uniqueid && AST_MAX_PUBLIC_UNIQUEID < strlen(assignedids.uniqueid))
|| (assignedids.uniqueid2 && AST_MAX_PUBLIC_UNIQUEID < strlen(assignedids.uniqueid2))) {
astman_send_error_va(s, m, "Uniqueid length exceeds maximum of %d\n",
AST_MAX_PUBLIC_UNIQUEID);
res = 0;
goto fast_orig_cleanup;
}
if (ast_strlen_zero(name)) {
astman_send_error(s, m, "Channel not specified");
res = 0;
goto fast_orig_cleanup;
}
if (!ast_strlen_zero(priority) && (sscanf(priority, "%30d", &pi) != 1)) {
if ((pi = ast_findlabel_extension(NULL, context, exten, priority, NULL)) < 1) {
astman_send_error(s, m, "Invalid priority");
res = 0;
goto fast_orig_cleanup;
}
}
if (!ast_strlen_zero(timeout) && (sscanf(timeout, "%30d", &to) != 1)) {
astman_send_error(s, m, "Invalid timeout");
res = 0;
goto fast_orig_cleanup;
}
ast_copy_string(tmp, name, sizeof(tmp));
tech = tmp;
data = strchr(tmp, '/');
if (!data) {
astman_send_error(s, m, "Invalid channel");
res = 0;
goto fast_orig_cleanup;
}
*data++ = '\0';
ast_copy_string(tmp2, callerid, sizeof(tmp2));
ast_callerid_parse(tmp2, &n, &l);
if (n) {
if (ast_strlen_zero(n)) {
n = NULL;
}
}
if (l) {
ast_shrink_phone_number(l);
if (ast_strlen_zero(l)) {
l = NULL;
}
}
if (!ast_strlen_zero(codecs)) {
ast_format_cap_remove_by_type(cap, AST_MEDIA_TYPE_UNKNOWN);
ast_format_cap_update_by_allow_disallow(cap, codecs, 1);
}
if (!ast_strlen_zero(app) && s->session) {
int bad_appdata = 0;
/* To run the System application (or anything else that goes to
* shell), you must have the additional System privilege */
if (!(s->session->writeperm & EVENT_FLAG_SYSTEM)
&& (
strcasestr(app, "system") || /* System(rm -rf /)
TrySystem(rm -rf /) */
strcasestr(app, "exec") || /* Exec(System(rm -rf /))
TryExec(System(rm -rf /)) */
strcasestr(app, "agi") || /* AGI(/bin/rm,-rf /)
EAGI(/bin/rm,-rf /) */
strcasestr(app, "mixmonitor") || /* MixMonitor(blah,,rm -rf) */
strcasestr(app, "externalivr") || /* ExternalIVR(rm -rf) */
strcasestr(app, "originate") || /* Originate(Local/1234,app,System,rm -rf) */
(strstr(appdata, "SHELL") && (bad_appdata = 1)) || /* NoOp(${SHELL(rm -rf /)}) */
(strstr(appdata, "EVAL") && (bad_appdata = 1)) /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
)) {
char error_buf[64];
snprintf(error_buf, sizeof(error_buf), "Originate Access Forbidden: %s", bad_appdata ? "Data" : "Application");
astman_send_error(s, m, error_buf);
res = 0;
goto fast_orig_cleanup;
}
}
/* Check early if the extension exists. If not, we need to bail out here. */
if (exten && context && pi) {
if (! ast_exists_extension(NULL, context, exten, pi, l)) {
/* The extension does not exist. */
astman_send_error(s, m, "Extension does not exist.");
res = 0;
goto fast_orig_cleanup;
}
}
/* Allocate requested channel variables */
vars = astman_get_variables(m);
if (s->session && s->session->chanvars) {
struct ast_variable *v, *old;
old = vars;
vars = NULL;
/* The variables in the AMI originate action are appended at the end of the list, to override any user variables that apply*/
vars = ast_variables_dup(s->session->chanvars);
if (old) {
for (v = vars; v->next; v = v->next );
if (v->next) {
v->next = old; /* Append originate variables at end of list */
}
}
}
/* For originate async - we can bridge in early media stage */
bridge_early = ast_true(early_media);
if (ast_true(async)) {
struct fast_originate_helper *fast;
fast = ast_calloc(1, sizeof(*fast));
if (!fast || ast_string_field_init(fast, 252)) {
ast_free(fast);
ast_variables_destroy(vars);
res = -1;
} else {
if (!ast_strlen_zero(id)) {
ast_string_field_build(fast, idtext, "ActionID: %s\r\n", id);
}
ast_string_field_set(fast, tech, tech);
ast_string_field_set(fast, data, data);
ast_string_field_set(fast, app, app);
ast_string_field_set(fast, appdata, appdata);
ast_string_field_set(fast, cid_num, l);
ast_string_field_set(fast, cid_name, n);
ast_string_field_set(fast, context, context);
ast_string_field_set(fast, exten, exten);
ast_string_field_set(fast, account, account);
ast_string_field_set(fast, channelid, assignedids.uniqueid);
ast_string_field_set(fast, otherchannelid, assignedids.uniqueid2);
fast->vars = vars;
fast->cap = cap;
cap = NULL; /* transfered originate helper the capabilities structure. It is now responsible for freeing it. */
fast->timeout = to;
fast->early_media = bridge_early;
fast->priority = pi;
if (ast_pthread_create_detached(&th, NULL, fast_originate, fast)) {
destroy_fast_originate_helper(fast);
res = -1;
} else {
res = 0;
}
}
} else if (!ast_strlen_zero(app)) {
res = ast_pbx_outgoing_app(tech, cap, data, to, app, appdata, &reason,
AST_OUTGOING_WAIT, l, n, vars, account, NULL,
assignedids.uniqueid ? &assignedids : NULL);
ast_variables_destroy(vars);
} else {
if (exten && context && pi) {
res = ast_pbx_outgoing_exten(tech, cap, data, to,
context, exten, pi, &reason, AST_OUTGOING_WAIT,
l, n, vars, account, NULL, bridge_early,
assignedids.uniqueid ? &assignedids : NULL);
ast_variables_destroy(vars);
} else {
astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
ast_variables_destroy(vars);
res = 0;
goto fast_orig_cleanup;
}
}
if (!res) {
astman_send_ack(s, m, "Originate successfully queued");
} else {
astman_send_error(s, m, "Originate failed");
}
fast_orig_cleanup:
ao2_cleanup(cap);
return 0;
}
static int action_mailboxstatus(struct mansession *s, const struct message *m)
{
const char *mailbox = astman_get_header(m, "Mailbox");
int ret;
if (ast_strlen_zero(mailbox)) {
astman_send_error(s, m, "Mailbox not specified");
return 0;
}
ret = ast_app_has_voicemail(mailbox, NULL);
astman_start_ack(s, m);
astman_append(s, "Message: Mailbox Status\r\n"
"Mailbox: %s\r\n"
"Waiting: %d\r\n\r\n", mailbox, ret);
return 0;
}
static int action_mailboxcount(struct mansession *s, const struct message *m)
{
const char *mailbox = astman_get_header(m, "Mailbox");
int newmsgs = 0, oldmsgs = 0, urgentmsgs = 0;;
if (ast_strlen_zero(mailbox)) {
astman_send_error(s, m, "Mailbox not specified");
return 0;
}
ast_app_inboxcount2(mailbox, &urgentmsgs, &newmsgs, &oldmsgs);
astman_start_ack(s, m);
astman_append(s, "Message: Mailbox Message Count\r\n"
"Mailbox: %s\r\n"
"UrgMessages: %d\r\n"
"NewMessages: %d\r\n"
"OldMessages: %d\r\n"
"\r\n",
mailbox, urgentmsgs, newmsgs, oldmsgs);
return 0;
}
static int action_extensionstate(struct mansession *s, const struct message *m)
{
const char *exten = astman_get_header(m, "Exten");
const char *context = astman_get_header(m, "Context");
char hint[256];
int status;
if (ast_strlen_zero(exten)) {
astman_send_error(s, m, "Extension not specified");
return 0;
}
if (ast_strlen_zero(context)) {
context = "default";
}
status = ast_extension_state(NULL, context, exten);
hint[0] = '\0';
ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten);
astman_start_ack(s, m);
astman_append(s, "Message: Extension Status\r\n"
"Exten: %s\r\n"
"Context: %s\r\n"
"Hint: %s\r\n"
"Status: %d\r\n"
"StatusText: %s\r\n"
"\r\n",
exten, context, hint, status,
ast_extension_state2str(status));
return 0;
}
static int action_presencestate(struct mansession *s, const struct message *m)
{
const char *provider = astman_get_header(m, "Provider");
enum ast_presence_state state;
char *subtype;
char *message;
if (ast_strlen_zero(provider)) {
astman_send_error(s, m, "No provider specified");
return 0;
}
state = ast_presence_state(provider, &subtype, &message);
if (state == AST_PRESENCE_INVALID) {
astman_send_error_va(s, m, "Invalid provider %s or provider in invalid state", provider);
return 0;
}
astman_start_ack(s, m);
astman_append(s, "Message: Presence State\r\n"
"State: %s\r\n", ast_presence_state2str(state));
if (!ast_strlen_zero(subtype)) {
astman_append(s, "Subtype: %s\r\n", subtype);
}
if (!ast_strlen_zero(message)) {
/* XXX The Message header here is deprecated as it
* duplicates the action response header 'Message'.
* Remove it in the next major revision of AMI.
*/
astman_append(s, "Message: %s\r\n"
"PresenceMessage: %s\r\n",
message, message);
}
astman_append(s, "\r\n");
return 0;
}
static int action_timeout(struct mansession *s, const struct message *m)
{
struct ast_channel *c;
const char *name = astman_get_header(m, "Channel");
double timeout = atof(astman_get_header(m, "Timeout"));
struct timeval when = { timeout, 0 };
if (ast_strlen_zero(name)) {
astman_send_error(s, m, "No channel specified");
return 0;
}
if (!timeout || timeout < 0) {
astman_send_error(s, m, "No timeout specified");
return 0;
}
if (!(c = ast_channel_get_by_name(name))) {
astman_send_error(s, m, "No such channel");
return 0;
}
when.tv_usec = (timeout - when.tv_sec) * 1000000.0;
ast_channel_lock(c);
ast_channel_setwhentohangup_tv(c, when);
ast_channel_unlock(c);
c = ast_channel_unref(c);
astman_send_ack(s, m, "Timeout Set");
return 0;
}
static int whitefilter_cmp_fn(void *obj, void *arg, void *data, int flags)
{
regex_t *regex_filter = obj;
const char *eventdata = arg;
int *result = data;
if (!regexec(regex_filter, eventdata, 0, NULL, 0)) {
*result = 1;
return (CMP_MATCH | CMP_STOP);
}
return 0;
}
static int blackfilter_cmp_fn(void *obj, void *arg, void *data, int flags)
{
regex_t *regex_filter = obj;
const char *eventdata = arg;
int *result = data;
if (!regexec(regex_filter, eventdata, 0, NULL, 0)) {
*result = 0;
return (CMP_MATCH | CMP_STOP);
}
*result = 1;
return 0;
}
/*!
* \brief Manager command to add an event filter to a manager session
* \see For more details look at manager_add_filter
*/
static int action_filter(struct mansession *s, const struct message *m)
{
const char *filter = astman_get_header(m, "Filter");
const char *operation = astman_get_header(m, "Operation");
int res;
if (!strcasecmp(operation, "Add")) {
res = manager_add_filter(filter, s->session->whitefilters, s->session->blackfilters);
if (res != FILTER_SUCCESS) {
if (res == FILTER_ALLOC_FAILED) {
astman_send_error(s, m, "Internal Error. Failed to allocate regex for filter");
return 0;
} else if (res == FILTER_COMPILE_FAIL) {
astman_send_error(s, m, "Filter did not compile. Check the syntax of the filter given.");
return 0;
} else {
astman_send_error(s, m, "Internal Error. Failed adding filter.");
return 0;
}
}
astman_send_ack(s, m, "Success");
return 0;
}
astman_send_error(s, m, "Unknown operation");
return 0;
}
/*!
* \brief Add an event filter to a manager session
*
* \param filter_pattern Filter syntax to add, see below for syntax
*
* \return FILTER_ALLOC_FAILED Memory allocation failure
* \return FILTER_COMPILE_FAIL If the filter did not compile
* \return FILTER_SUCCESS Success
*
* Filter will be used to match against each line of a manager event
* Filter can be any valid regular expression
* Filter can be a valid regular expression prefixed with !, which will add the filter as a black filter
*
* Examples:
* \code
* filter_pattern = "Event: Newchannel"
* filter_pattern = "Event: New.*"
* filter_pattern = "!Channel: DAHDI.*"
* \endcode
*
*/
static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters) {
regex_t *new_filter = ao2_t_alloc(sizeof(*new_filter), event_filter_destructor, "event_filter allocation");
int is_blackfilter;
if (!new_filter) {
return FILTER_ALLOC_FAILED;
}
if (filter_pattern[0] == '!') {
is_blackfilter = 1;
filter_pattern++;
} else {
is_blackfilter = 0;
}
if (regcomp(new_filter, filter_pattern, REG_EXTENDED | REG_NOSUB)) {
ao2_t_ref(new_filter, -1, "failed to make regex");
return FILTER_COMPILE_FAIL;
}
if (is_blackfilter) {
ao2_t_link(blackfilters, new_filter, "link new filter into black user container");
} else {
ao2_t_link(whitefilters, new_filter, "link new filter into white user container");
}
ao2_ref(new_filter, -1);
return FILTER_SUCCESS;
}
static int match_filter(struct mansession *s, char *eventdata)
{
int result = 0;
if (manager_debug) {
ast_verbose("<-- Examining AMI event: -->\n%s\n", eventdata);
} else {
ast_debug(3, "Examining AMI event:\n%s\n", eventdata);
}
if (!ao2_container_count(s->session->whitefilters) && !ao2_container_count(s->session->blackfilters)) {
return 1; /* no filtering means match all */
} else if (ao2_container_count(s->session->whitefilters) && !ao2_container_count(s->session->blackfilters)) {
/* white filters only: implied black all filter processed first, then white filters */
ao2_t_callback_data(s->session->whitefilters, OBJ_NODATA, whitefilter_cmp_fn, eventdata, &result, "find filter in session filter container");
} else if (!ao2_container_count(s->session->whitefilters) && ao2_container_count(s->session->blackfilters)) {
/* black filters only: implied white all filter processed first, then black filters */
ao2_t_callback_data(s->session->blackfilters, OBJ_NODATA, blackfilter_cmp_fn, eventdata, &result, "find filter in session filter container");
} else {
/* white and black filters: implied black all filter processed first, then white filters, and lastly black filters */
ao2_t_callback_data(s->session->whitefilters, OBJ_NODATA, whitefilter_cmp_fn, eventdata, &result, "find filter in session filter container");
if (result) {
result = 0;
ao2_t_callback_data(s->session->blackfilters, OBJ_NODATA, blackfilter_cmp_fn, eventdata, &result, "find filter in session filter container");
}
}
return result;
}
/*!
* Send any applicable events to the client listening on this socket.
* Wait only for a finite time on each event, and drop all events whether
* they are successfully sent or not.
*/
static int process_events(struct mansession *s)
{
int ret = 0;
ao2_lock(s->session);
if (s->session->stream != NULL) {
struct eventqent *eqe = s->session->last_ev;
while ((eqe = advance_event(eqe))) {
if (eqe->category == EVENT_FLAG_SHUTDOWN) {
ast_debug(3, "Received CloseSession event\n");
ret = -1;
}
if (!ret && s->session->authenticated &&
(s->session->readperm & eqe->category) == eqe->category &&
(s->session->send_events & eqe->category) == eqe->category) {
if (match_filter(s, eqe->eventdata)) {
if (send_string(s, eqe->eventdata) < 0)
ret = -1; /* don't send more */
}
}
s->session->last_ev = eqe;
}
}
ao2_unlock(s->session);
return ret;
}
static int action_userevent(struct mansession *s, const struct message *m)
{
const char *event = astman_get_header(m, "UserEvent");
struct ast_str *body = ast_str_thread_get(&userevent_buf, 16);
int x;
ast_str_reset(body);
for (x = 0; x < m->hdrcount; x++) {
if (strncasecmp("UserEvent:", m->headers[x], strlen("UserEvent:")) &&
strncasecmp("Action:", m->headers[x], strlen("Action:"))) {
ast_str_append(&body, 0, "%s\r\n", m->headers[x]);
}
}
astman_send_ack(s, m, "Event Sent");
manager_event(EVENT_FLAG_USER, "UserEvent", "UserEvent: %s\r\n%s", event, ast_str_buffer(body));
return 0;
}
/*! \brief Show PBX core settings information */
static int action_coresettings(struct mansession *s, const struct message *m)
{
const char *actionid = astman_get_header(m, "ActionID");
char idText[150];
if (!ast_strlen_zero(actionid)) {
snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
} else {
idText[0] = '\0';
}
astman_append(s, "Response: Success\r\n"
"%s"
"AMIversion: %s\r\n"
"AsteriskVersion: %s\r\n"
"SystemName: %s\r\n"
"CoreMaxCalls: %d\r\n"
"CoreMaxLoadAvg: %f\r\n"
"CoreRunUser: %s\r\n"
"CoreRunGroup: %s\r\n"
"CoreMaxFilehandles: %d\r\n"
"CoreRealTimeEnabled: %s\r\n"
"CoreCDRenabled: %s\r\n"
"CoreHTTPenabled: %s\r\n"
"\r\n",
idText,
AMI_VERSION,
ast_get_version(),
ast_config_AST_SYSTEM_NAME,
ast_option_maxcalls,
ast_option_maxload,
ast_config_AST_RUN_USER,
ast_config_AST_RUN_GROUP,
ast_option_maxfiles,
AST_CLI_YESNO(ast_realtime_enabled()),
AST_CLI_YESNO(ast_cdr_is_enabled()),
AST_CLI_YESNO(check_webmanager_enabled())
);
return 0;
}
/*! \brief Show PBX core status information */
static int action_corestatus(struct mansession *s, const struct message *m)
{
const char *actionid = astman_get_header(m, "ActionID");
char idText[150];
char startuptime[150], startupdate[150];
char reloadtime[150], reloaddate[150];
struct ast_tm tm;
if (!ast_strlen_zero(actionid)) {
snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
} else {
idText[0] = '\0';
}
ast_localtime(&ast_startuptime, &tm, NULL);
ast_strftime(startuptime, sizeof(startuptime), "%H:%M:%S", &tm);
ast_strftime(startupdate, sizeof(startupdate), "%Y-%m-%d", &tm);
ast_localtime(&ast_lastreloadtime, &tm, NULL);
ast_strftime(reloadtime, sizeof(reloadtime), "%H:%M:%S", &tm);
ast_strftime(reloaddate, sizeof(reloaddate), "%Y-%m-%d", &tm);
astman_append(s, "Response: Success\r\n"
"%s"
"CoreStartupDate: %s\r\n"
"CoreStartupTime: %s\r\n"
"CoreReloadDate: %s\r\n"
"CoreReloadTime: %s\r\n"
"CoreCurrentCalls: %d\r\n"
"\r\n",
idText,
startupdate,
startuptime,
reloaddate,
reloadtime,
ast_active_channels()
);
return 0;
}
/*! \brief Send a reload event */
static int action_reload(struct mansession *s, const struct message *m)
{
const char *module = astman_get_header(m, "Module");
enum ast_module_reload_result res = ast_module_reload(S_OR(module, NULL));
switch (res) {
case AST_MODULE_RELOAD_NOT_FOUND:
astman_send_error(s, m, "No such module");
break;
case AST_MODULE_RELOAD_NOT_IMPLEMENTED:
astman_send_error(s, m, "Module does not support reload");
break;
case AST_MODULE_RELOAD_ERROR:
astman_send_error(s, m, "An unknown error occurred");
break;
case AST_MODULE_RELOAD_IN_PROGRESS:
astman_send_error(s, m, "A reload is in progress");
break;
case AST_MODULE_RELOAD_UNINITIALIZED:
astman_send_error(s, m, "Module not initialized");
break;
case AST_MODULE_RELOAD_QUEUED:
case AST_MODULE_RELOAD_SUCCESS:
/* Treat a queued request as success */
astman_send_ack(s, m, "Module Reloaded");
break;
}
return 0;
}
/*! \brief Manager command "CoreShowChannels" - List currently defined channels
* and some information about them. */
static int action_coreshowchannels(struct mansession *s, const struct message *m)
{
const char *actionid = astman_get_header(m, "ActionID");
char idText[256];
int numchans = 0;
struct ao2_container *channels;
struct ao2_iterator it_chans;
struct stasis_message *msg;
if (!ast_strlen_zero(actionid)) {
snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
} else {
idText[0] = '\0';
}
channels = stasis_cache_dump(ast_channel_cache_by_name(), ast_channel_snapshot_type());
if (!channels) {
astman_send_error(s, m, "Could not get cached channels");
return 0;
}
astman_send_listack(s, m, "Channels will follow", "start");
it_chans = ao2_iterator_init(channels, 0);
for (; (msg = ao2_iterator_next(&it_chans)); ao2_ref(msg, -1)) {
struct ast_channel_snapshot *cs = stasis_message_data(msg);
struct ast_str *built = ast_manager_build_channel_state_string_prefix(cs, "");
char durbuf[16] = "";
if (!built) {
continue;
}
if (!ast_tvzero(cs->creationtime)) {
int duration, durh, durm, durs;
duration = (int)(ast_tvdiff_ms(ast_tvnow(), cs->creationtime) / 1000);
durh = duration / 3600;
durm = (duration % 3600) / 60;
durs = duration % 60;
snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
}
astman_append(s,
"Event: CoreShowChannel\r\n"
"%s"
"%s"
"Application: %s\r\n"
"ApplicationData: %s\r\n"
"Duration: %s\r\n"
"BridgeId: %s\r\n"
"\r\n",
idText,
ast_str_buffer(built),
cs->appl,
cs->data,
durbuf,
cs->bridgeid);
numchans++;
ast_free(built);
}
ao2_iterator_destroy(&it_chans);
astman_send_list_complete_start(s, m, "CoreShowChannelsComplete", numchans);
astman_send_list_complete_end(s);
ao2_ref(channels, -1);
return 0;
}
/*! \brief Manager command "LoggerRotate" - reloads and rotates the logger in
* the same manner as the CLI command 'logger rotate'. */
static int action_loggerrotate(struct mansession *s, const struct message *m)
{
if (ast_logger_rotate()) {
astman_send_error(s, m, "Failed to reload the logger and rotate log files");
return 0;
}
astman_send_ack(s, m, "Reloaded the logger and rotated log files");
return 0;
}
/*! \brief Manager function to check if module is loaded */
static int manager_modulecheck(struct mansession *s, const struct message *m)
{
int res;
const char *module = astman_get_header(m, "Module");
const char *id = astman_get_header(m, "ActionID");
char idText[256];
char filename[PATH_MAX];
char *cut;
ast_copy_string(filename, module, sizeof(filename));
if ((cut = strchr(filename, '.'))) {
*cut = '\0';
} else {
cut = filename + strlen(filename);
}
snprintf(cut, (sizeof(filename) - strlen(filename)) - 1, ".so");
ast_debug(1, "**** ModuleCheck .so file %s\n", filename);
res = ast_module_check(filename);
if (!res) {
astman_send_error(s, m, "Module not loaded");
return 0;
}
if (!ast_strlen_zero(id)) {
snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
} else {
idText[0] = '\0';
}
astman_append(s, "Response: Success\r\n%s", idText);
#if !defined(LOW_MEMORY)
astman_append(s, "Version: %s\r\n\r\n", "");
#endif
return 0;
}
static int manager_moduleload(struct mansession *s, const struct message *m)
{
int res;
const char *module = astman_get_header(m, "Module");
const char *loadtype = astman_get_header(m, "LoadType");
if (!loadtype || strlen(loadtype) == 0) {
astman_send_error(s, m, "Incomplete ModuleLoad action.");
}
if ((!module || strlen(module) == 0) && strcasecmp(loadtype, "reload") != 0) {
astman_send_error(s, m, "Need module name");
}
if (!strcasecmp(loadtype, "load")) {
res = ast_load_resource(module);
if (res) {
astman_send_error(s, m, "Could not load module.");
} else {
astman_send_ack(s, m, "Module loaded.");
}
} else if (!strcasecmp(loadtype, "unload")) {
res = ast_unload_resource(module, AST_FORCE_SOFT);
if (res) {
astman_send_error(s, m, "Could not unload module.");
} else {
astman_send_ack(s, m, "Module unloaded.");
}
} else if (!strcasecmp(loadtype, "reload")) {
/* TODO: Unify the ack/error messages here with action_reload */
if (!ast_strlen_zero(module)) {
enum ast_module_reload_result reload_res = ast_module_reload(module);
switch (reload_res) {
case AST_MODULE_RELOAD_NOT_FOUND:
astman_send_error(s, m, "No such module.");
break;
case AST_MODULE_RELOAD_NOT_IMPLEMENTED:
astman_send_error(s, m, "Module does not support reload action.");
break;
case AST_MODULE_RELOAD_ERROR:
astman_send_error(s, m, "An unknown error occurred");
break;
case AST_MODULE_RELOAD_IN_PROGRESS:
astman_send_error(s, m, "A reload is in progress");
break;
case AST_MODULE_RELOAD_UNINITIALIZED:
astman_send_error(s, m, "Module not initialized");
break;
case AST_MODULE_RELOAD_QUEUED:
case AST_MODULE_RELOAD_SUCCESS:
/* Treat a queued request as success */
astman_send_ack(s, m, "Module reloaded.");
break;
}
} else {
ast_module_reload(NULL); /* Reload all modules */
astman_send_ack(s, m, "All modules reloaded");
}
} else
astman_send_error(s, m, "Incomplete ModuleLoad action.");
return 0;
}
/*
* Done with the action handlers here, we start with the code in charge
* of accepting connections and serving them.
* accept_thread() forks a new thread for each connection, session_do(),
* which in turn calls get_input() repeatedly until a full message has
* been accumulated, and then invokes process_message() to pass it to
* the appropriate handler.
*/
/*! \brief
* Process an AMI message, performing desired action.
* Return 0 on success, -1 on error that require the session to be destroyed.
*/
static int process_message(struct mansession *s, const struct message *m)
{
int ret = 0;
struct manager_action *act_found;
struct ast_manager_user *user = NULL;
const char *username;
const char *action;
action = __astman_get_header(m, "Action", GET_HEADER_SKIP_EMPTY);
if (ast_strlen_zero(action)) {
report_req_bad_format(s, "NONE");
mansession_lock(s);
astman_send_error(s, m, "Missing action in request");
mansession_unlock(s);
return 0;
}
if (ast_shutting_down()) {
ast_log(LOG_ERROR, "Unable to process manager action '%s'. Asterisk is shutting down.\n", action);
mansession_lock(s);
astman_send_error(s, m, "Asterisk is shutting down");
mansession_unlock(s);
return 0;
}
if (!s->session->authenticated
&& strcasecmp(action, "Login")
&& strcasecmp(action, "Logoff")
&& strcasecmp(action, "Challenge")) {
if (!s->session->authenticated) {
report_req_not_allowed(s, action);
}
mansession_lock(s);
astman_send_error(s, m, "Permission denied");
mansession_unlock(s);
return 0;
}
if (!s->session->authenticated
&& (!strcasecmp(action, "Login")
|| !strcasecmp(action, "Challenge"))) {
username = astman_get_header(m, "Username");
if (!ast_strlen_zero(username) && check_manager_session_inuse(username)) {
AST_RWLIST_WRLOCK(&users);
user = get_manager_by_name_locked(username);
if (user && !user->allowmultiplelogin) {
AST_RWLIST_UNLOCK(&users);
report_session_limit(s);
sleep(1);
mansession_lock(s);
astman_send_error(s, m, "Login Already In Use");
mansession_unlock(s);
return -1;
}
AST_RWLIST_UNLOCK(&users);
}
}
act_found = action_find(action);
if (act_found) {
/* Found the requested AMI action. */
int acted = 0;
if ((s->session->writeperm & act_found->authority)
|| act_found->authority == 0) {
/* We have the authority to execute the action. */
ret = -1;
ao2_lock(act_found);
if (act_found->registered && act_found->func) {
struct ast_module *mod_ref = ast_module_running_ref(act_found->module);
ao2_unlock(act_found);
if (mod_ref || !act_found->module) {
ast_debug(1, "Running action '%s'\n", act_found->action);
ret = act_found->func(s, m);
acted = 1;
ast_module_unref(mod_ref);
}
} else {
ao2_unlock(act_found);
}
}
if (!acted) {
/*
* We did not execute the action because access was denied, it
* was no longer registered, or no action was really registered.
* Complain about it and leave.
*/
report_req_not_allowed(s, action);
mansession_lock(s);
astman_send_error(s, m, "Permission denied");
mansession_unlock(s);
}
ao2_t_ref(act_found, -1, "done with found action object");
} else {
char buf[512];
report_req_bad_format(s, action);
snprintf(buf, sizeof(buf), "Invalid/unknown command: %s. Use Action: ListCommands to show available commands.", action);
mansession_lock(s);
astman_send_error(s, m, buf);
mansession_unlock(s);
}
if (ret) {
return ret;
}
/* Once done with our message, deliver any pending events unless the
requester doesn't want them as part of this response.
*/
if (ast_strlen_zero(astman_get_header(m, "SuppressEvents"))) {
return process_events(s);
} else {
return ret;
}
}
/*!
* Read one full line (including crlf) from the manager socket.
* \note \verbatim
* \r\n is the only valid terminator for the line.
* (Note that, later, '\0' will be considered as the end-of-line marker,
* so everything between the '\0' and the '\r\n' will not be used).
* Also note that we assume output to have at least "maxlen" space.
* \endverbatim
*/
static int get_input(struct mansession *s, char *output)
{
int res, x;
int maxlen = sizeof(s->session->inbuf) - 1;
char *src = s->session->inbuf;
int timeout = -1;
time_t now;
/*
* Look for \r\n within the buffer. If found, copy to the output
* buffer and return, trimming the \r\n (not used afterwards).
*/
for (x = 0; x < s->session->inlen; x++) {
int cr; /* set if we have \r */
if (src[x] == '\r' && x+1 < s->session->inlen && src[x + 1] == '\n') {
cr = 2; /* Found. Update length to include \r\n */
} else if (src[x] == '\n') {
cr = 1; /* also accept \n only */
} else {
continue;
}
memmove(output, src, x); /*... but trim \r\n */
output[x] = '\0'; /* terminate the string */
x += cr; /* number of bytes used */
s->session->inlen -= x; /* remaining size */
memmove(src, src + x, s->session->inlen); /* remove used bytes */
return 1;
}
if (s->session->inlen >= maxlen) {
/* no crlf found, and buffer full - sorry, too long for us
* keep the last character in case we are in the middle of a CRLF. */
ast_log(LOG_WARNING, "Discarding message from %s. Line too long: %.25s...\n", ast_sockaddr_stringify_addr(&s->session->addr), src);
src[0] = src[s->session->inlen - 1];
s->session->inlen = 1;
s->parsing = MESSAGE_LINE_TOO_LONG;
}
res = 0;
while (res == 0) {
/* calculate a timeout if we are not authenticated */
if (!s->session->authenticated) {
if(time(&now) == -1) {
ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
return -1;
}
timeout = (authtimeout - (now - s->session->authstart)) * 1000;
if (timeout < 0) {
/* we have timed out */
return 0;
}
}
ao2_lock(s->session);
if (s->session->pending_event) {
s->session->pending_event = 0;
ao2_unlock(s->session);
return 0;
}
s->session->waiting_thread = pthread_self();
ao2_unlock(s->session);
res = ast_wait_for_input(ast_iostream_get_fd(s->session->stream), timeout);
ao2_lock(s->session);
s->session->waiting_thread = AST_PTHREADT_NULL;
ao2_unlock(s->session);
}
if (res < 0) {
/* If we get a signal from some other thread (typically because
* there are new events queued), return 0 to notify the caller.
*/
if (errno == EINTR || errno == EAGAIN) {
return 0;
}
ast_log(LOG_WARNING, "poll() returned error: %s\n", strerror(errno));
return -1;
}
ao2_lock(s->session);
res = ast_iostream_read(s->session->stream, src + s->session->inlen, maxlen - s->session->inlen);
if (res < 1) {
res = -1; /* error return */
} else {
s->session->inlen += res;
src[s->session->inlen] = '\0';
res = 0;
}
ao2_unlock(s->session);
return res;
}
/*!
* \internal
* \brief Error handling for sending parse errors. This function handles locking, and clearing the
* parse error flag.
*
* \param s AMI session to process action request.
* \param m Message that's in error.
* \param error Error message to send.
*/
static void handle_parse_error(struct mansession *s, struct message *m, char *error)
{
mansession_lock(s);
astman_send_error(s, m, error);
s->parsing = MESSAGE_OKAY;
mansession_unlock(s);
}
/*!
* \internal
* \brief Read and process an AMI action request.
*
* \param s AMI session to process action request.
*
* \retval 0 Retain AMI connection for next command.
* \retval -1 Drop AMI connection due to logoff or connection error.
*/
static int do_message(struct mansession *s)
{
struct message m = { 0 };
char header_buf[sizeof(s->session->inbuf)] = { '\0' };
int res;
int hdr_loss;
time_t now;
hdr_loss = 0;
for (;;) {
/* Check if any events are pending and do them if needed */
if (process_events(s)) {
res = -1;
break;
}
res = get_input(s, header_buf);
if (res == 0) {
/* No input line received. */
if (!s->session->authenticated) {
if (time(&now) == -1) {
ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
res = -1;
break;
}
if (now - s->session->authstart > authtimeout) {
if (displayconnects) {
ast_verb(2, "Client from %s, failed to authenticate in %d seconds\n", ast_sockaddr_stringify_addr(&s->session->addr), authtimeout);
}
res = -1;
break;
}
}
continue;
} else if (res > 0) {
/* Input line received. */
if (ast_strlen_zero(header_buf)) {
if (hdr_loss) {
mansession_lock(s);
astman_send_error(s, &m, "Too many lines in message or allocation failure");
mansession_unlock(s);
res = 0;
} else {
switch (s->parsing) {
case MESSAGE_OKAY:
res = process_message(s, &m) ? -1 : 0;
break;
case MESSAGE_LINE_TOO_LONG:
handle_parse_error(s, &m, "Failed to parse message: line too long");
res = 0;
break;
}
}
break;
} else if (m.hdrcount < ARRAY_LEN(m.headers)) {
m.headers[m.hdrcount] = ast_strdup(header_buf);
if (!m.headers[m.hdrcount]) {
/* Allocation failure. */
hdr_loss = 1;
} else {
++m.hdrcount;
}
} else {
/* Too many lines in message. */
hdr_loss = 1;
}
} else {
/* Input error. */
break;
}
}
astman_free_headers(&m);
return res;
}
/*! \brief The body of the individual manager session.
* Call get_input() to read one line at a time
* (or be woken up on new events), collect the lines in a
* message until found an empty line, and execute the request.
* In any case, deliver events asynchronously through process_events()
* (called from here if no line is available, or at the end of
* process_message(). )
*/
static void *session_do(void *data)
{
struct ast_tcptls_session_instance *ser = data;
struct mansession_session *session;
struct mansession s = {
.tcptls_session = data,
};
int res;
int arg = 1;
struct ast_sockaddr ser_remote_address_tmp;
if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
ast_atomic_fetchadd_int(&unauth_sessions, -1);
goto done;
}
ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
session = build_mansession(&ser_remote_address_tmp);
if (session == NULL) {
ast_atomic_fetchadd_int(&unauth_sessions, -1);
goto done;
}
/* here we set TCP_NODELAY on the socket to disable Nagle's algorithm.
* This is necessary to prevent delays (caused by buffering) as we
* write to the socket in bits and pieces. */
if (setsockopt(ast_iostream_get_fd(ser->stream), IPPROTO_TCP, TCP_NODELAY, (char *) &arg, sizeof(arg)) < 0) {
ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on manager connection: %s\n", strerror(errno));
}
ast_iostream_nonblock(ser->stream);
ao2_lock(session);
/* Hook to the tail of the event queue */
session->last_ev = grab_last();
ast_mutex_init(&s.lock);
/* these fields duplicate those in the 'ser' structure */
session->stream = s.stream = ser->stream;
ast_sockaddr_copy(&session->addr, &ser_remote_address_tmp);
s.session = session;
AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
if(time(&session->authstart) == -1) {
ast_log(LOG_ERROR, "error executing time(): %s; disconnecting client\n", strerror(errno));
ast_atomic_fetchadd_int(&unauth_sessions, -1);
ao2_unlock(session);
session_destroy(session);
goto done;
}
ao2_unlock(session);
/*
* We cannot let the stream exclusively wait for data to arrive.
* We have to wake up the task to send async events.
*/
ast_iostream_set_exclusive_input(ser->stream, 0);
ast_iostream_set_timeout_sequence(ser->stream,
ast_tvnow(), authtimeout * 1000);
astman_append(&s, "Asterisk Call Manager/%s\r\n", AMI_VERSION); /* welcome prompt */
for (;;) {
if ((res = do_message(&s)) < 0 || s.write_error) {
break;
}
if (session->authenticated) {
ast_iostream_set_timeout_disable(ser->stream);
}
}
/* session is over, explain why and terminate */
if (session->authenticated) {
if (manager_displayconnects(session)) {
ast_verb(2, "Manager '%s' logged off from %s\n", session->username, ast_sockaddr_stringify_addr(&session->addr));
}
} else {
ast_atomic_fetchadd_int(&unauth_sessions, -1);
if (displayconnects) {
ast_verb(2, "Connect attempt from '%s' unable to authenticate\n", ast_sockaddr_stringify_addr(&session->addr));
}
}
session_destroy(session);
ast_mutex_destroy(&s.lock);
done:
ao2_ref(ser, -1);
ser = NULL;
return NULL;
}
/*! \brief remove at most n_max stale session from the list. */
static void purge_sessions(int n_max)
{
struct ao2_container *sessions;
struct mansession_session *session;
time_t now = time(NULL);
struct ao2_iterator i;
sessions = ao2_global_obj_ref(mgr_sessions);
if (!sessions) {
return;
}
i = ao2_iterator_init(sessions, 0);
ao2_ref(sessions, -1);
while ((session = ao2_iterator_next(&i)) && n_max > 0) {
ao2_lock(session);
if (session->sessiontimeout && (now > session->sessiontimeout) && !session->inuse) {
if (session->authenticated
&& VERBOSITY_ATLEAST(2)
&& manager_displayconnects(session)) {
ast_verb(2, "HTTP Manager '%s' timed out from %s\n",
session->username, ast_sockaddr_stringify_addr(&session->addr));
}
ao2_unlock(session);
session_destroy(session);
n_max--;
} else {
ao2_unlock(session);
unref_mansession(session);
}
}
ao2_iterator_destroy(&i);
}
/*! \brief
* events are appended to a queue from where they
* can be dispatched to clients.
*/
static int append_event(const char *str, int category)
{
struct eventqent *tmp = ast_malloc(sizeof(*tmp) + strlen(str));
static int seq; /* sequence number */
if (!tmp) {
return -1;
}
/* need to init all fields, because ast_malloc() does not */
tmp->usecount = 0;
tmp->category = category;
tmp->seq = ast_atomic_fetchadd_int(&seq, 1);
tmp->tv = ast_tvnow();
AST_RWLIST_NEXT(tmp, eq_next) = NULL;
strcpy(tmp->eventdata, str);
AST_RWLIST_WRLOCK(&all_events);
AST_RWLIST_INSERT_TAIL(&all_events, tmp, eq_next);
AST_RWLIST_UNLOCK(&all_events);
return 0;
}
static void append_channel_vars(struct ast_str **pbuf, struct ast_channel *chan)
{
struct varshead *vars;
struct ast_var_t *var;
vars = ast_channel_get_manager_vars(chan);
if (!vars) {
return;
}
AST_LIST_TRAVERSE(vars, var, entries) {
ast_str_append(pbuf, 0, "ChanVariable(%s): %s=%s\r\n", ast_channel_name(chan), var->name, var->value);
}
ao2_ref(vars, -1);
}
/* XXX see if can be moved inside the function */
AST_THREADSTORAGE(manager_event_buf);
#define MANAGER_EVENT_BUF_INITSIZE 256
static int __attribute__((format(printf, 9, 0))) __manager_event_sessions_va(
struct ao2_container *sessions,
int category,
const char *event,
int chancount,
struct ast_channel **chans,
const char *file,
int line,
const char *func,
const char *fmt,
va_list ap)
{
struct ast_str *auth = ast_str_alloca(MAX_AUTH_PERM_STRING);
const char *cat_str;
struct timeval now;
struct ast_str *buf;
int i;
buf = ast_str_thread_get(&manager_event_buf, MANAGER_EVENT_BUF_INITSIZE);
if (!buf) {
return -1;
}
cat_str = authority_to_str(category, &auth);
ast_str_set(&buf, 0,
"Event: %s\r\n"
"Privilege: %s\r\n",
event, cat_str);
if (timestampevents) {
now = ast_tvnow();
ast_str_append(&buf, 0,
"Timestamp: %ld.%06lu\r\n",
(long)now.tv_sec, (unsigned long) now.tv_usec);
}
if (manager_debug) {
static int seq;
ast_str_append(&buf, 0,
"SequenceNumber: %d\r\n",
ast_atomic_fetchadd_int(&seq, 1));
ast_str_append(&buf, 0,
"File: %s\r\n"
"Line: %d\r\n"
"Func: %s\r\n",
file, line, func);
}
if (!ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
ast_str_append(&buf, 0,
"SystemName: %s\r\n",
ast_config_AST_SYSTEM_NAME);
}
ast_str_append_va(&buf, 0, fmt, ap);
for (i = 0; i < chancount; i++) {
append_channel_vars(&buf, chans[i]);
}
ast_str_append(&buf, 0, "\r\n");
append_event(ast_str_buffer(buf), category);
/* Wake up any sleeping sessions */
if (sessions) {
struct ao2_iterator iter;
struct mansession_session *session;
iter = ao2_iterator_init(sessions, 0);
while ((session = ao2_iterator_next(&iter))) {
ao2_lock(session);
if (session->waiting_thread != AST_PTHREADT_NULL) {
pthread_kill(session->waiting_thread, SIGURG);
} else {
/* We have an event to process, but the mansession is
* not waiting for it. We still need to indicate that there
* is an event waiting so that get_input processes the pending
* event instead of polling.
*/
session->pending_event = 1;
}
ao2_unlock(session);
unref_mansession(session);
}
ao2_iterator_destroy(&iter);
}
if (category != EVENT_FLAG_SHUTDOWN && !AST_RWLIST_EMPTY(&manager_hooks)) {
struct manager_custom_hook *hook;
AST_RWLIST_RDLOCK(&manager_hooks);
AST_RWLIST_TRAVERSE(&manager_hooks, hook, list) {
hook->helper(category, event, ast_str_buffer(buf));
}
AST_RWLIST_UNLOCK(&manager_hooks);
}
return 0;
}
static int __attribute__((format(printf, 9, 0))) __manager_event_sessions(
struct ao2_container *sessions,
int category,
const char *event,
int chancount,
struct ast_channel **chans,
const char *file,
int line,
const char *func,
const char *fmt,
...)
{
va_list ap;
int res;
va_start(ap, fmt);
res = __manager_event_sessions_va(sessions, category, event, chancount, chans,
file, line, func, fmt, ap);
va_end(ap);
return res;
}
int __ast_manager_event_multichan(int category, const char *event, int chancount,
struct ast_channel **chans, const char *file, int line, const char *func,
const char *fmt, ...)
{
struct ao2_container *sessions = ao2_global_obj_ref(mgr_sessions);
va_list ap;
int res;
if (!any_manager_listeners(sessions)) {
/* Nobody is listening */
ao2_cleanup(sessions);
return 0;
}
va_start(ap, fmt);
res = __manager_event_sessions_va(sessions, category, event, chancount, chans,
file, line, func, fmt, ap);
va_end(ap);
ao2_cleanup(sessions);
return res;
}
/*! \brief
* support functions to register/unregister AMI action handlers,
*/
int ast_manager_unregister(const char *action)
{
struct manager_action *cur;
AST_RWLIST_WRLOCK(&actions);
AST_RWLIST_TRAVERSE_SAFE_BEGIN(&actions, cur, list) {
if (!strcasecmp(action, cur->action)) {
AST_RWLIST_REMOVE_CURRENT(list);
break;
}
}
AST_RWLIST_TRAVERSE_SAFE_END;
AST_RWLIST_UNLOCK(&actions);
if (cur) {
/*
* We have removed the action object from the container so we
* are no longer in a hurry.
*/
ao2_lock(cur);
cur->registered = 0;
ao2_unlock(cur);
ao2_t_ref(cur, -1, "action object removed from list");
ast_verb(2, "Manager unregistered action %s\n", action);
}
return 0;
}
static int manager_state_cb(const char *context, const char *exten, struct ast_state_cb_info *info, void *data)
{
/* Notify managers of change */
char hint[512];
hint[0] = '\0';
ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten);
switch(info->reason) {
case AST_HINT_UPDATE_DEVICE:
manager_event(EVENT_FLAG_CALL, "ExtensionStatus",
"Exten: %s\r\n"
"Context: %s\r\n"
"Hint: %s\r\n"
"Status: %d\r\n"
"StatusText: %s\r\n",
exten,
context,
hint,
info->exten_state,
ast_extension_state2str(info->exten_state));
break;
case AST_HINT_UPDATE_PRESENCE:
manager_event(EVENT_FLAG_CALL, "PresenceStatus",
"Exten: %s\r\n"
"Context: %s\r\n"
"Hint: %s\r\n"
"Status: %s\r\n"
"Subtype: %s\r\n"
"Message: %s\r\n",
exten,
context,
hint,
ast_presence_state2str(info->presence_state),
info->presence_subtype,
info->presence_message);
break;
}
return 0;
}
static int ast_manager_register_struct(struct manager_action *act)
{
struct manager_action *cur, *prev = NULL;
AST_RWLIST_WRLOCK(&actions);
AST_RWLIST_TRAVERSE(&actions, cur, list) {
int ret;
ret = strcasecmp(cur->action, act->action);
if (ret == 0) {
ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", act->action);
AST_RWLIST_UNLOCK(&actions);
return -1;
}
if (ret > 0) { /* Insert these alphabetically */
break;
}
prev = cur;
}
ao2_t_ref(act, +1, "action object added to list");
act->registered = 1;
if (prev) {
AST_RWLIST_INSERT_AFTER(&actions, prev, act, list);
} else {
AST_RWLIST_INSERT_HEAD(&actions, act, list);
}
ast_verb(2, "Manager registered action %s\n", act->action);
AST_RWLIST_UNLOCK(&actions);
return 0;
}
/*!
* \internal
* \brief Destroy the registered AMI action object.
*
* \param obj Object to destroy.
*
* \return Nothing
*/
static void action_destroy(void *obj)
{
struct manager_action *doomed = obj;
if (doomed->synopsis) {
/* The string fields were initialized. */
ast_string_field_free_memory(doomed);
}
ao2_cleanup(doomed->final_response);
ao2_cleanup(doomed->list_responses);
}
/*! \brief register a new command with manager, including online help. This is
the preferred way to register a manager command */
int ast_manager_register2(const char *action, int auth, int (*func)(struct mansession *s, const struct message *m), struct ast_module *module, const char *synopsis, const char *description)
{
struct manager_action *cur;
cur = ao2_t_alloc(sizeof(*cur), action_destroy, action);
if (!cur) {
return -1;
}
if (ast_string_field_init(cur, 128)) {
ao2_t_ref(cur, -1, "action object creation failed");
return -1;
}
cur->action = action;
cur->authority = auth;
cur->func = func;
cur->module = module;
#ifdef AST_XML_DOCS
if (ast_strlen_zero(synopsis) && ast_strlen_zero(description)) {
char *tmpxml;
tmpxml = ast_xmldoc_build_synopsis("manager", action, NULL);
ast_string_field_set(cur, synopsis, tmpxml);
ast_free(tmpxml);
tmpxml = ast_xmldoc_build_syntax("manager", action, NULL);
ast_string_field_set(cur, syntax, tmpxml);
ast_free(tmpxml);
tmpxml = ast_xmldoc_build_description("manager", action, NULL);
ast_string_field_set(cur, description, tmpxml);
ast_free(tmpxml);
tmpxml = ast_xmldoc_build_seealso("manager", action, NULL);
ast_string_field_set(cur, seealso, tmpxml);
ast_free(tmpxml);
tmpxml = ast_xmldoc_build_arguments("manager", action, NULL);
ast_string_field_set(cur, arguments, tmpxml);
ast_free(tmpxml);
cur->final_response = ast_xmldoc_build_final_response("manager", action, NULL);
cur->list_responses = ast_xmldoc_build_list_responses("manager", action, NULL);
cur->docsrc = AST_XML_DOC;
} else
#endif
{
ast_string_field_set(cur, synopsis, synopsis);
ast_string_field_set(cur, description, description);
#ifdef AST_XML_DOCS
cur->docsrc = AST_STATIC_DOC;
#endif
}
if (ast_manager_register_struct(cur)) {
ao2_t_ref(cur, -1, "action object registration failed");
return -1;
}
ao2_t_ref(cur, -1, "action object registration successful");
return 0;
}
/*! @}
END Doxygen group */
/*
* The following are support functions for AMI-over-http.
* The common entry point is generic_http_callback(),
* which extracts HTTP header and URI fields and reformats
* them into AMI messages, locates a proper session
* (using the mansession_id Cookie or GET variable),
* and calls process_message() as for regular AMI clients.
* When done, the output (which goes to a temporary file)
* is read back into a buffer and reformatted as desired,
* then fed back to the client over the original socket.
*/
enum output_format {
FORMAT_RAW,
FORMAT_HTML,
FORMAT_XML,
};
static const char * const contenttype[] = {
[FORMAT_RAW] = "plain",
[FORMAT_HTML] = "html",
[FORMAT_XML] = "xml",
};
/*!
* locate an http session in the list. The search key (ident) is
* the value of the mansession_id cookie (0 is not valid and means
* a session on the AMI socket).
*/
static struct mansession_session *find_session(uint32_t ident, int incinuse)
{
struct ao2_container *sessions;
struct mansession_session *session;
struct ao2_iterator i;
if (ident == 0) {
return NULL;
}
sessions = ao2_global_obj_ref(mgr_sessions);
if (!sessions) {
return NULL;
}
i = ao2_iterator_init(sessions, 0);
ao2_ref(sessions, -1);
while ((session = ao2_iterator_next(&i))) {
ao2_lock(session);
if (session->managerid == ident && !session->needdestroy) {
ast_atomic_fetchadd_int(&session->inuse, incinuse ? 1 : 0);
break;
}
ao2_unlock(session);
unref_mansession(session);
}
ao2_iterator_destroy(&i);
return session;
}
/*!
* locate an http session in the list.
* The search keys (nonce) and (username) is value from received
* "Authorization" http header.
* As well as in find_session() function, the value of the nonce can't be zero.
* (0 meansi, that the session used for AMI socket connection).
* Flag (stale) is set, if client used valid, but old, nonce value.
*
*/
static struct mansession_session *find_session_by_nonce(const char *username, unsigned long nonce, int *stale)
{
struct mansession_session *session;
struct ao2_container *sessions;
struct ao2_iterator i;
if (nonce == 0 || username == NULL || stale == NULL) {
return NULL;
}
sessions = ao2_global_obj_ref(mgr_sessions);
if (!sessions) {
return NULL;
}
i = ao2_iterator_init(sessions, 0);
ao2_ref(sessions, -1);
while ((session = ao2_iterator_next(&i))) {
ao2_lock(session);
if (!strcasecmp(session->username, username) && session->managerid == nonce) {
*stale = 0;
break;
} else if (!strcasecmp(session->username, username) && session->oldnonce == nonce) {
*stale = 1;
break;
}
ao2_unlock(session);
unref_mansession(session);
}
ao2_iterator_destroy(&i);
return session;
}
int astman_is_authed(uint32_t ident)
{
int authed;
struct mansession_session *session;
if (!(session = find_session(ident, 0)))
return 0;
authed = (session->authenticated != 0);
ao2_unlock(session);
unref_mansession(session);
return authed;
}
int astman_verify_session_readpermissions(uint32_t ident, int perm)
{
int result = 0;
struct mansession_session *session;
struct ao2_container *sessions;
struct ao2_iterator i;
if (ident == 0) {
return 0;
}
sessions = ao2_global_obj_ref(mgr_sessions);
if (!sessions) {
return 0;
}
i = ao2_iterator_init(sessions, 0);
ao2_ref(sessions, -1);
while ((session = ao2_iterator_next(&i))) {
ao2_lock(session);
if ((session->managerid == ident) && (session->readperm & perm)) {
result = 1;
ao2_unlock(session);
unref_mansession(session);
break;
}
ao2_unlock(session);
unref_mansession(session);
}
ao2_iterator_destroy(&i);
return result;
}
int astman_verify_session_writepermissions(uint32_t ident, int perm)
{
int result = 0;
struct mansession_session *session;
struct ao2_container *sessions;
struct ao2_iterator i;
if (ident == 0) {
return 0;
}
sessions = ao2_global_obj_ref(mgr_sessions);
if (!sessions) {
return 0;
}
i = ao2_iterator_init(sessions, 0);
ao2_ref(sessions, -1);
while ((session = ao2_iterator_next(&i))) {
ao2_lock(session);
if ((session->managerid == ident) && (session->writeperm & perm)) {
result = 1;
ao2_unlock(session);
unref_mansession(session);
break;
}
ao2_unlock(session);
unref_mansession(session);
}
ao2_iterator_destroy(&i);
return result;
}
/*
* convert to xml with various conversion:
* mode & 1 -> lowercase;
* mode & 2 -> replace non-alphanumeric chars with underscore
*/
static void xml_copy_escape(struct ast_str **out, const char *src, int mode)
{
/* store in a local buffer to avoid calling ast_str_append too often */
char buf[256];
char *dst = buf;
int space = sizeof(buf);
/* repeat until done and nothing to flush */
for ( ; *src || dst != buf ; src++) {
if (*src == '\0' || space < 10) { /* flush */
*dst++ = '\0';
ast_str_append(out, 0, "%s", buf);
dst = buf;
space = sizeof(buf);
if (*src == '\0') {
break;
}
}
if ( (mode & 2) && !isalnum(*src)) {
*dst++ = '_';
space--;
continue;
}
switch (*src) {
case '<':
strcpy(dst, "<");
dst += 4;
space -= 4;
break;
case '>':
strcpy(dst, ">");
dst += 4;
space -= 4;
break;
case '\"':
strcpy(dst, """);
dst += 6;
space -= 6;
break;
case '\'':
strcpy(dst, "'");
dst += 6;
space -= 6;
break;
case '&':
strcpy(dst, "&");
dst += 5;
space -= 5;
break;
default:
*dst++ = mode ? tolower(*src) : *src;
space--;
}
}
}
struct variable_count {
char *varname;
int count;
};
static int variable_count_hash_fn(const void *vvc, const int flags)
{
const struct variable_count *vc = vvc;
return ast_str_hash(vc->varname);
}
static int variable_count_cmp_fn(void *obj, void *vstr, int flags)
{
/* Due to the simplicity of struct variable_count, it makes no difference
* if you pass in objects or strings, the same operation applies. This is
* due to the fact that the hash occurs on the first element, which means
* the address of both the struct and the string are exactly the same. */
struct variable_count *vc = obj;
char *str = vstr;
return !strcmp(vc->varname, str) ? CMP_MATCH | CMP_STOP : 0;
}
/*! \brief Convert the input into XML or HTML.
* The input is supposed to be a sequence of lines of the form
* Name: value
* optionally followed by a blob of unformatted text.
* A blank line is a section separator. Basically, this is a
* mixture of the format of Manager Interface and CLI commands.
* The unformatted text is considered as a single value of a field
* named 'Opaque-data'.
*
* At the moment the output format is the following (but it may
* change depending on future requirements so don't count too
* much on it when writing applications):
*
* General: the unformatted text is used as a value of
* XML output: to be completed
*
* \verbatim
* Each section is within <response type="object" id="xxx">
* where xxx is taken from ajaxdest variable or defaults to unknown
* Each row is reported as an attribute Name="value" of an XML
* entity named from the variable ajaxobjtype, default to "generic"
* \endverbatim
*
* HTML output:
* each Name-value pair is output as a single row of a two-column table.
* Sections (blank lines in the input) are separated by a <HR>
*
*/
static void xml_translate(struct ast_str **out, char *in, struct ast_variable *get_vars, enum output_format format)
{
struct ast_variable *v;
const char *dest = NULL;
char *var, *val;
const char *objtype = NULL;
int in_data = 0; /* parsing data */
int inobj = 0;
int xml = (format == FORMAT_XML);
struct variable_count *vc = NULL;
struct ao2_container *vco = NULL;
if (xml) {
/* dest and objtype need only for XML format */
for (v = get_vars; v; v = v->next) {
if (!strcasecmp(v->name, "ajaxdest")) {
dest = v->value;
} else if (!strcasecmp(v->name, "ajaxobjtype")) {
objtype = v->value;
}
}
if (ast_strlen_zero(dest)) {
dest = "unknown";
}
if (ast_strlen_zero(objtype)) {
objtype = "generic";
}
}
/* we want to stop when we find an empty line */
while (in && *in) {
val = strsep(&in, "\r\n"); /* mark start and end of line */
if (in && *in == '\n') { /* remove trailing \n if any */
in++;
}
ast_trim_blanks(val);
ast_debug(5, "inobj %d in_data %d line <%s>\n", inobj, in_data, val);
if (ast_strlen_zero(val)) {
/* empty line */
if (in_data) {
/* close data in Opaque mode */
ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
in_data = 0;
}
if (inobj) {
/* close block */
ast_str_append(out, 0, xml ? " /></response>\n" :
"<tr><td colspan=\"2\"><hr></td></tr>\r\n");
inobj = 0;
ao2_ref(vco, -1);
vco = NULL;
}
continue;
}
if (!inobj) {
/* start new block */
if (xml) {
ast_str_append(out, 0, "<response type='object' id='%s'><%s", dest, objtype);
}
vco = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, 37,
variable_count_hash_fn, NULL, variable_count_cmp_fn);
inobj = 1;
}
if (in_data) {
/* Process data field in Opaque mode. This is a
* followup, so we re-add line feeds. */
ast_str_append(out, 0, xml ? "\n" : "<br>\n");
xml_copy_escape(out, val, 0); /* data field */
continue;
}
/* We expect "Name: value" line here */
var = strsep(&val, ":");
if (val) {
/* found the field name */
val = ast_skip_blanks(val);
ast_trim_blanks(var);
} else {
/* field name not found, switch to opaque mode */
val = var;
var = "Opaque-data";
in_data = 1;
}
ast_str_append(out, 0, xml ? " " : "<tr><td>");
if ((vc = ao2_find(vco, var, 0))) {
vc->count++;
} else {
/* Create a new entry for this one */
vc = ao2_alloc(sizeof(*vc), NULL);
vc->varname = var;
vc->count = 1;
ao2_link(vco, vc);
}
xml_copy_escape(out, var, xml ? 1 | 2 : 0); /* data name */
if (vc->count > 1) {
ast_str_append(out, 0, "-%d", vc->count);
}
ao2_ref(vc, -1);
ast_str_append(out, 0, xml ? "='" : "</td><td>");
xml_copy_escape(out, val, 0); /* data field */
if (!in_data || !*in) {
ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
}
}
if (inobj) {
ast_str_append(out, 0, xml ? " /></response>\n" :
"<tr><td colspan=\"2\"><hr></td></tr>\r\n");
ao2_ref(vco, -1);
}
}
static void close_mansession_file(struct mansession *s)
{
if (s->stream) {
ast_iostream_close(s->stream);
s->stream = NULL;
} else {
ast_log(LOG_ERROR, "Attempted to close file/file descriptor on mansession without a valid file or file descriptor.\n");
}
}
static void process_output(struct mansession *s, struct ast_str **out, struct ast_variable *params, enum output_format format)
{
char *buf;
off_t l;
int fd;
if (!s->stream)
return;
/* Ensure buffer is NULL-terminated */
ast_iostream_write(s->stream, "", 1);
fd = ast_iostream_get_fd(s->stream);
l = lseek(fd, 0, SEEK_CUR);
if (l > 0) {
if (MAP_FAILED == (buf = mmap(NULL, l, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0))) {
ast_log(LOG_WARNING, "mmap failed. Manager output was not processed\n");
} else {
if (format == FORMAT_XML || format == FORMAT_HTML) {
xml_translate(out, buf, params, format);
} else {
ast_str_append(out, 0, "%s", buf);
}
munmap(buf, l);
}
} else if (format == FORMAT_XML || format == FORMAT_HTML) {
xml_translate(out, "", params, format);
}
close_mansession_file(s);
}
static int generic_http_callback(struct ast_tcptls_session_instance *ser,
enum ast_http_method method,
enum output_format format,
const struct ast_sockaddr *remote_address, const char *uri,
struct ast_variable *get_params,
struct ast_variable *headers)
{
struct mansession s = { .session = NULL, .tcptls_session = ser };
struct mansession_session *session = NULL;
uint32_t ident;
int fd;
int blastaway = 0;
struct ast_variable *params = get_params;
char template[] = "/tmp/ast-http-XXXXXX"; /* template for temporary file */
struct ast_str *http_header = NULL, *out = NULL;
struct message m = { 0 };
if (method != AST_HTTP_GET && method != AST_HTTP_HEAD && method != AST_HTTP_POST) {
ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
return 0;
}
ident = ast_http_manid_from_vars(headers);
if (!(session = find_session(ident, 1))) {
/**/
/* Create new session.
* While it is not in the list we don't need any locking
*/
if (!(session = build_mansession(remote_address))) {
ast_http_request_close_on_completion(ser);
ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)");
return 0;
}
ao2_lock(session);
session->send_events = 0;
session->inuse = 1;
/*!
* \note There is approximately a 1 in 1.8E19 chance that the following
* calculation will produce 0, which is an invalid ID, but due to the
* properties of the rand() function (and the constantcy of s), that
* won't happen twice in a row.
*/
while ((session->managerid = ast_random() ^ (unsigned long) session) == 0) {
}
session->last_ev = grab_last();
AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
}
ao2_unlock(session);
http_header = ast_str_create(128);
out = ast_str_create(2048);
ast_mutex_init(&s.lock);
if (http_header == NULL || out == NULL) {
ast_http_request_close_on_completion(ser);
ast_http_error(ser, 500, "Server Error", "Internal Server Error (ast_str_create() out of memory)");
goto generic_callback_out;
}
s.session = session;
fd = mkstemp(template); /* create a temporary file for command output */
unlink(template);
if (fd <= -1) {
ast_http_error(ser, 500, "Server Error", "Internal Server Error (mkstemp failed)");
goto generic_callback_out;
}
s.stream = ast_iostream_from_fd(&fd);
if (!s.stream) {
ast_log(LOG_WARNING, "HTTP Manager, fdopen failed: %s!\n", strerror(errno));
ast_http_error(ser, 500, "Server Error", "Internal Server Error (fdopen failed)");
close(fd);
goto generic_callback_out;
}
if (method == AST_HTTP_POST) {
params = ast_http_get_post_vars(ser, headers);
if (!params) {
switch (errno) {
case EFBIG:
ast_http_error(ser, 413, "Request Entity Too Large", "Body too large");
close_mansession_file(&s);
goto generic_callback_out;
case ENOMEM:
ast_http_request_close_on_completion(ser);
ast_http_error(ser, 500, "Server Error", "Out of memory");
close_mansession_file(&s);
goto generic_callback_out;
case EIO:
ast_http_error(ser, 400, "Bad Request", "Error parsing request body");
close_mansession_file(&s);
goto generic_callback_out;
}
}
}
astman_append_headers(&m, params);
if (process_message(&s, &m)) {
if (session->authenticated) {
if (manager_displayconnects(session)) {
ast_verb(2, "HTTP Manager '%s' logged off from %s\n", session->username, ast_sockaddr_stringify_addr(&session->addr));
}
} else {
if (displayconnects) {
ast_verb(2, "HTTP Connect attempt from '%s' unable to authenticate\n", ast_sockaddr_stringify_addr(&session->addr));
}
}
session->needdestroy = 1;
}
astman_free_headers(&m);
ast_str_append(&http_header, 0,
"Content-type: text/%s\r\n"
"Set-Cookie: mansession_id=\"%08x\"; Version=1; Max-Age=%d\r\n"
"Pragma: SuppressEvents\r\n",
contenttype[format],
session->managerid, httptimeout);
if (format == FORMAT_XML) {
ast_str_append(&out, 0, "<ajax-response>\n");
} else if (format == FORMAT_HTML) {
/*
* When handling AMI-over-HTTP in HTML format, we provide a simple form for
* debugging purposes. This HTML code should not be here, we
* should read from some config file...
*/
#define ROW_FMT "<tr><td colspan=\"2\" bgcolor=\"#f1f1ff\">%s</td></tr>\r\n"
#define TEST_STRING \
"<form action=\"manager\" method=\"post\">\n\
Action: <select name=\"action\">\n\
<option value=\"\">-----></option>\n\
<option value=\"login\">login</option>\n\
<option value=\"command\">Command</option>\n\
<option value=\"waitevent\">waitevent</option>\n\
<option value=\"listcommands\">listcommands</option>\n\
</select>\n\
or <input name=\"action\"><br/>\n\
CLI Command <input name=\"command\"><br>\n\
user <input name=\"username\"> pass <input type=\"password\" name=\"secret\"><br>\n\
<input type=\"submit\">\n</form>\n"
ast_str_append(&out, 0, "<title>Asterisk™ Manager Interface</title>");
ast_str_append(&out, 0, "<body bgcolor=\"#ffffff\"><table align=center bgcolor=\"#f1f1f1\" width=\"500\">\r\n");
ast_str_append(&out, 0, ROW_FMT, "<h1>Manager Tester</h1>");
ast_str_append(&out, 0, ROW_FMT, TEST_STRING);
}
process_output(&s, &out, params, format);
if (format == FORMAT_XML) {
ast_str_append(&out, 0, "</ajax-response>\n");
} else if (format == FORMAT_HTML) {
ast_str_append(&out, 0, "</table></body>\r\n");
}
ao2_lock(session);
/* Reset HTTP timeout. If we're not authenticated, keep it extremely short */
session->sessiontimeout = time(NULL) + ((session->authenticated || httptimeout < 5) ? httptimeout : 5);
if (session->needdestroy) {
if (session->inuse == 1) {
ast_debug(1, "Need destroy, doing it now!\n");
blastaway = 1;
} else {
ast_debug(1, "Need destroy, but can't do it yet!\n");
if (session->waiting_thread != AST_PTHREADT_NULL) {
pthread_kill(session->waiting_thread, SIGURG);
}
session->inuse--;
}
} else {
session->inuse--;
}
ao2_unlock(session);
ast_http_send(ser, method, 200, NULL, http_header, out, 0, 0);
http_header = NULL;
out = NULL;
generic_callback_out:
ast_mutex_destroy(&s.lock);
/* Clear resource */
if (method == AST_HTTP_POST && params) {
ast_variables_destroy(params);
}
ast_free(http_header);
ast_free(out);
if (session) {
if (blastaway) {
session_destroy(session);
} else {
if (session->stream) {
ast_iostream_close(session->stream);
session->stream = NULL;
}
unref_mansession(session);
}
}
return 0;
}
static int auth_http_callback(struct ast_tcptls_session_instance *ser,
enum ast_http_method method,
enum output_format format,
const struct ast_sockaddr *remote_address, const char *uri,
struct ast_variable *get_params,
struct ast_variable *headers)
{
struct mansession_session *session = NULL;
struct mansession s = { .session = NULL, .tcptls_session = ser };
struct ast_variable *v, *params = get_params;
char template[] = "/tmp/ast-http-XXXXXX"; /* template for temporary file */
struct ast_str *http_header = NULL, *out = NULL;
size_t result_size;
struct message m = { 0 };
int fd;
time_t time_now = time(NULL);
unsigned long nonce = 0, nc;
struct ast_http_digest d = { NULL, };
struct ast_manager_user *user = NULL;
int stale = 0;
char resp_hash[256]="";
/* Cache for user data */
char u_username[80];
int u_readperm;
int u_writeperm;
int u_writetimeout;
int u_displayconnects;
if (method != AST_HTTP_GET && method != AST_HTTP_HEAD && method != AST_HTTP_POST) {
ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
return 0;
}
/* Find "Authorization: " header */
for (v = headers; v; v = v->next) {
if (!strcasecmp(v->name, "Authorization")) {
break;
}
}
if (!v || ast_strlen_zero(v->value)) {
goto out_401; /* Authorization Header not present - send auth request */
}
/* Digest found - parse */
if (ast_string_field_init(&d, 128)) {
ast_http_request_close_on_completion(ser);
ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)");
return 0;
}
if (ast_parse_digest(v->value, &d, 0, 1)) {
/* Error in Digest - send new one */
nonce = 0;
goto out_401;
}
if (sscanf(d.nonce, "%30lx", &nonce) != 1) {
ast_log(LOG_WARNING, "Received incorrect nonce in Digest <%s>\n", d.nonce);
nonce = 0;
goto out_401;
}
AST_RWLIST_WRLOCK(&users);
user = get_manager_by_name_locked(d.username);
if(!user) {
AST_RWLIST_UNLOCK(&users);
ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&session->addr), d.username);
nonce = 0;
goto out_401;
}
/* --- We have User for this auth, now check ACL */
if (user->acl && !ast_apply_acl(user->acl, remote_address, "Manager User ACL:")) {
AST_RWLIST_UNLOCK(&users);
ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&session->addr), d.username);
ast_http_request_close_on_completion(ser);
ast_http_error(ser, 403, "Permission denied", "Permission denied");
return 0;
}
/* --- We have auth, so check it */
/* compute the expected response to compare with what we received */
{
char *a2;
/* ast_md5_hash outputs 32 characters plus NULL terminator. */
char a2_hash[33];
char resp[256];
/* XXX Now request method are hardcoded in A2 */
if (ast_asprintf(&a2, "%s:%s", ast_get_http_method(method), d.uri) < 0) {
AST_RWLIST_UNLOCK(&users);
ast_http_request_close_on_completion(ser);
ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)");
return 0;
}
ast_md5_hash(a2_hash, a2);
ast_free(a2);
if (d.qop) {
/* RFC 2617 */
snprintf(resp, sizeof(resp), "%s:%08lx:%s:%s:auth:%s", user->a1_hash, nonce, d.nc, d.cnonce, a2_hash);
} else {
/* RFC 2069 */
snprintf(resp, sizeof(resp), "%s:%08lx:%s", user->a1_hash, nonce, a2_hash);
}
ast_md5_hash(resp_hash, resp);
}
if (strncasecmp(d.response, resp_hash, strlen(resp_hash))) {
/* Something was wrong, so give the client to try with a new challenge */
AST_RWLIST_UNLOCK(&users);
nonce = 0;
goto out_401;
}
/*
* User are pass Digest authentication.
* Now, cache the user data and unlock user list.
*/
ast_copy_string(u_username, user->username, sizeof(u_username));
u_readperm = user->readperm;
u_writeperm = user->writeperm;
u_displayconnects = user->displayconnects;
u_writetimeout = user->writetimeout;
AST_RWLIST_UNLOCK(&users);
if (!(session = find_session_by_nonce(d.username, nonce, &stale))) {
/*
* Create new session.
* While it is not in the list we don't need any locking
*/
if (!(session = build_mansession(remote_address))) {
ast_http_request_close_on_completion(ser);
ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)");
return 0;
}
ao2_lock(session);
ast_copy_string(session->username, u_username, sizeof(session->username));
session->managerid = nonce;
session->last_ev = grab_last();
AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
session->readperm = u_readperm;
session->writeperm = u_writeperm;
session->writetimeout = u_writetimeout;
if (u_displayconnects) {
ast_verb(2, "HTTP Manager '%s' logged in from %s\n", session->username, ast_sockaddr_stringify_addr(&session->addr));
}
session->noncetime = session->sessionstart = time_now;
session->authenticated = 1;
} else if (stale) {
/*
* Session found, but nonce is stale.
*
* This could be because an old request (w/old nonce) arrived.
*
* This may be as the result of http proxy usage (separate delay or
* multipath) or in a situation where a page was refreshed too quickly
* (seen in Firefox).
*
* In this situation, we repeat the 401 auth with the current nonce
* value.
*/
nonce = session->managerid;
ao2_unlock(session);
stale = 1;
goto out_401;
} else {
sscanf(d.nc, "%30lx", &nc);
if (session->nc >= nc || ((time_now - session->noncetime) > 62) ) {
/*
* Nonce time expired (> 2 minutes) or something wrong with nonce
* counter.
*
* Create new nonce key and resend Digest auth request. Old nonce
* is saved for stale checking...
*/
session->nc = 0; /* Reset nonce counter */
session->oldnonce = session->managerid;
nonce = session->managerid = ast_random();
session->noncetime = time_now;
ao2_unlock(session);
stale = 1;
goto out_401;
} else {
session->nc = nc; /* All OK, save nonce counter */
}
}
/* Reset session timeout. */
session->sessiontimeout = time(NULL) + (httptimeout > 5 ? httptimeout : 5);
ao2_unlock(session);
ast_mutex_init(&s.lock);
s.session = session;
fd = mkstemp(template); /* create a temporary file for command output */
unlink(template);
if (fd <= -1) {
ast_http_error(ser, 500, "Server Error", "Internal Server Error (mkstemp failed)");
goto auth_callback_out;
}
s.stream = ast_iostream_from_fd(&fd);
if (!s.stream) {
ast_log(LOG_WARNING, "HTTP Manager, fdopen failed: %s!\n", strerror(errno));
ast_http_error(ser, 500, "Server Error", "Internal Server Error (fdopen failed)");
close(fd);
goto auth_callback_out;
}
if (method == AST_HTTP_POST) {
params = ast_http_get_post_vars(ser, headers);
if (!params) {
switch (errno) {
case EFBIG:
ast_http_error(ser, 413, "Request Entity Too Large", "Body too large");
close_mansession_file(&s);
goto auth_callback_out;
case ENOMEM:
ast_http_request_close_on_completion(ser);
ast_http_error(ser, 500, "Server Error", "Out of memory");
close_mansession_file(&s);
goto auth_callback_out;
case EIO:
ast_http_error(ser, 400, "Bad Request", "Error parsing request body");
close_mansession_file(&s);
goto auth_callback_out;
}
}
}
astman_append_headers(&m, params);
if (process_message(&s, &m)) {
if (u_displayconnects) {
ast_verb(2, "HTTP Manager '%s' logged off from %s\n", session->username, ast_sockaddr_stringify_addr(&session->addr));
}
session->needdestroy = 1;
}
astman_free_headers(&m);
result_size = lseek(ast_iostream_get_fd(s.stream), 0, SEEK_CUR); /* Calculate approx. size of result */
http_header = ast_str_create(80);
out = ast_str_create(result_size * 2 + 512);
if (http_header == NULL || out == NULL) {
ast_http_request_close_on_completion(ser);
ast_http_error(ser, 500, "Server Error", "Internal Server Error (ast_str_create() out of memory)");
close_mansession_file(&s);
goto auth_callback_out;
}
ast_str_append(&http_header, 0, "Content-type: text/%s\r\n", contenttype[format]);
if (format == FORMAT_XML) {
ast_str_append(&out, 0, "<ajax-response>\n");
} else if (format == FORMAT_HTML) {
ast_str_append(&out, 0,
"<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
"<html><head>\r\n"
"<title>Asterisk™ Manager Interface</title>\r\n"
"</head><body style=\"background-color: #ffffff;\">\r\n"
"<form method=\"POST\">\r\n"
"<table align=\"center\" style=\"background-color: #f1f1f1;\" width=\"500\">\r\n"
"<tr><th colspan=\"2\" style=\"background-color: #f1f1ff;\"><h1>Manager Tester</h1></th></tr>\r\n"
"<tr><th colspan=\"2\" style=\"background-color: #f1f1ff;\">Action: <input name=\"action\" /> Cmd: <input name=\"command\" /><br>"
"<input type=\"submit\" value=\"Send request\" /></th></tr>\r\n");
}
process_output(&s, &out, params, format);
if (format == FORMAT_XML) {
ast_str_append(&out, 0, "</ajax-response>\n");
} else if (format == FORMAT_HTML) {
ast_str_append(&out, 0, "</table></form></body></html>\r\n");
}
ast_http_send(ser, method, 200, NULL, http_header, out, 0, 0);
http_header = NULL;
out = NULL;
auth_callback_out:
ast_mutex_destroy(&s.lock);
/* Clear resources and unlock manager session */
if (method == AST_HTTP_POST && params) {
ast_variables_destroy(params);
}
ast_free(http_header);
ast_free(out);
ao2_lock(session);
if (session->stream) {
ast_iostream_close(session->stream);
session->stream = NULL;
}
ao2_unlock(session);
if (session->needdestroy) {
ast_debug(1, "Need destroy, doing it now!\n");
session_destroy(session);
}
ast_string_field_free_memory(&d);
return 0;
out_401:
if (!nonce) {
nonce = ast_random();
}
ast_http_auth(ser, global_realm, nonce, nonce, stale, NULL);
ast_string_field_free_memory(&d);
return 0;
}
static int manager_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
{
int retval;
struct ast_sockaddr ser_remote_address_tmp;
ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
retval = generic_http_callback(ser, method, FORMAT_HTML, &ser_remote_address_tmp, uri, get_params, headers);
ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
return retval;
}
static int mxml_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
{
int retval;
struct ast_sockaddr ser_remote_address_tmp;
ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
retval = generic_http_callback(ser, method, FORMAT_XML, &ser_remote_address_tmp, uri, get_params, headers);
ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
return retval;
}
static int rawman_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
{
int retval;
struct ast_sockaddr ser_remote_address_tmp;
ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
retval = generic_http_callback(ser, method, FORMAT_RAW, &ser_remote_address_tmp, uri, get_params, headers);
ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
return retval;
}
static struct ast_http_uri rawmanuri = {
.description = "Raw HTTP Manager Event Interface",
.uri = "rawman",
.callback = rawman_http_callback,
.data = NULL,
.key = __FILE__,
};
static struct ast_http_uri manageruri = {
.description = "HTML Manager Event Interface",
.uri = "manager",
.callback = manager_http_callback,
.data = NULL,
.key = __FILE__,
};
static struct ast_http_uri managerxmluri = {
.description = "XML Manager Event Interface",
.uri = "mxml",
.callback = mxml_http_callback,
.data = NULL,
.key = __FILE__,
};
/* Callback with Digest authentication */
static int auth_manager_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
{
int retval;
struct ast_sockaddr ser_remote_address_tmp;
ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
retval = auth_http_callback(ser, method, FORMAT_HTML, &ser_remote_address_tmp, uri, get_params, headers);
ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
return retval;
}
static int auth_mxml_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
{
int retval;
struct ast_sockaddr ser_remote_address_tmp;
ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
retval = auth_http_callback(ser, method, FORMAT_XML, &ser_remote_address_tmp, uri, get_params, headers);
ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
return retval;
}
static int auth_rawman_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
{
int retval;
struct ast_sockaddr ser_remote_address_tmp;
ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
retval = auth_http_callback(ser, method, FORMAT_RAW, &ser_remote_address_tmp, uri, get_params, headers);
ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
return retval;
}
static struct ast_http_uri arawmanuri = {
.description = "Raw HTTP Manager Event Interface w/Digest authentication",
.uri = "arawman",
.has_subtree = 0,
.callback = auth_rawman_http_callback,
.data = NULL,
.key = __FILE__,
};
static struct ast_http_uri amanageruri = {
.description = "HTML Manager Event Interface w/Digest authentication",
.uri = "amanager",
.has_subtree = 0,
.callback = auth_manager_http_callback,
.data = NULL,
.key = __FILE__,
};
static struct ast_http_uri amanagerxmluri = {
.description = "XML Manager Event Interface w/Digest authentication",
.uri = "amxml",
.has_subtree = 0,
.callback = auth_mxml_http_callback,
.data = NULL,
.key = __FILE__,
};
/*! \brief Get number of logged in sessions for a login name */
static int get_manager_sessions_cb(void *obj, void *arg, void *data, int flags)
{
struct mansession_session *session = obj;
const char *login = (char *)arg;
int *no_sessions = data;
if (strcasecmp(session->username, login) == 0) {
(*no_sessions)++;
}
return 0;
}
/*! \brief ${AMI_CLIENT()} Dialplan function - reads manager client data */
static int function_amiclient(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
{
struct ast_manager_user *user = NULL;
AST_DECLARE_APP_ARGS(args,
AST_APP_ARG(name);
AST_APP_ARG(param);
);
if (ast_strlen_zero(data) ) {
ast_log(LOG_WARNING, "AMI_CLIENT() requires two arguments: AMI_CLIENT(<name>[,<arg>])\n");
return -1;
}
AST_STANDARD_APP_ARGS(args, data);
args.name = ast_strip(args.name);
args.param = ast_strip(args.param);
AST_RWLIST_RDLOCK(&users);
if (!(user = get_manager_by_name_locked(args.name))) {
AST_RWLIST_UNLOCK(&users);
ast_log(LOG_ERROR, "There's no manager user called : \"%s\"\n", args.name);
return -1;
}
AST_RWLIST_UNLOCK(&users);
if (!strcasecmp(args.param, "sessions")) {
int no_sessions = 0;
struct ao2_container *sessions;
sessions = ao2_global_obj_ref(mgr_sessions);
if (sessions) {
ao2_callback_data(sessions, 0, get_manager_sessions_cb, /*login name*/ data, &no_sessions);
ao2_ref(sessions, -1);
}
snprintf(buf, len, "%d", no_sessions);
} else {
ast_log(LOG_ERROR, "Invalid arguments provided to function AMI_CLIENT: %s\n", args.param);
return -1;
}
return 0;
}
/*! \brief description of AMI_CLIENT dialplan function */
static struct ast_custom_function managerclient_function = {
.name = "AMI_CLIENT",
.read = function_amiclient,
.read_max = 12,
};
static int webregged = 0;
/*! \brief cleanup code called at each iteration of server_root,
* guaranteed to happen every 5 seconds at most
*/
static void purge_old_stuff(void *data)
{
purge_sessions(1);
purge_events();
}
static struct ast_tls_config ami_tls_cfg;
static struct ast_tcptls_session_args ami_desc = {
.accept_fd = -1,
.master = AST_PTHREADT_NULL,
.tls_cfg = NULL,
.poll_timeout = 5000, /* wake up every 5 seconds */
.periodic_fn = purge_old_stuff,
.name = "AMI server",
.accept_fn = ast_tcptls_server_root, /* thread doing the accept() */
.worker_fn = session_do, /* thread handling the session */
};
static struct ast_tcptls_session_args amis_desc = {
.accept_fd = -1,
.master = AST_PTHREADT_NULL,
.tls_cfg = &ami_tls_cfg,
.poll_timeout = -1, /* the other does the periodic cleanup */
.name = "AMI TLS server",
.accept_fn = ast_tcptls_server_root, /* thread doing the accept() */
.worker_fn = session_do, /* thread handling the session */
};
/*! \brief CLI command manager show settings */
static char *handle_manager_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
switch (cmd) {
case CLI_INIT:
e->command = "manager show settings";
e->usage =
"Usage: manager show settings\n"
" Provides detailed list of the configuration of the Manager.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
#define FORMAT " %-25.25s %-15.55s\n"
#define FORMAT2 " %-25.25s %-15d\n"
if (a->argc != 3) {
return CLI_SHOWUSAGE;
}
ast_cli(a->fd, "\nGlobal Settings:\n");
ast_cli(a->fd, "----------------\n");
ast_cli(a->fd, FORMAT, "Manager (AMI):", AST_CLI_YESNO(manager_enabled));
ast_cli(a->fd, FORMAT, "Web Manager (AMI/HTTP):", AST_CLI_YESNO(webmanager_enabled));
ast_cli(a->fd, FORMAT, "TCP Bindaddress:", manager_enabled != 0 ? ast_sockaddr_stringify(&ami_desc.local_address) : "Disabled");
ast_cli(a->fd, FORMAT2, "HTTP Timeout (seconds):", httptimeout);
ast_cli(a->fd, FORMAT, "TLS Enable:", AST_CLI_YESNO(ami_tls_cfg.enabled));
ast_cli(a->fd, FORMAT, "TLS Bindaddress:", ami_tls_cfg.enabled != 0 ? ast_sockaddr_stringify(&amis_desc.local_address) : "Disabled");
ast_cli(a->fd, FORMAT, "TLS Certfile:", ami_tls_cfg.certfile);
ast_cli(a->fd, FORMAT, "TLS Privatekey:", ami_tls_cfg.pvtfile);
ast_cli(a->fd, FORMAT, "TLS Cipher:", ami_tls_cfg.cipher);
ast_cli(a->fd, FORMAT, "Allow multiple login:", AST_CLI_YESNO(allowmultiplelogin));
ast_cli(a->fd, FORMAT, "Display connects:", AST_CLI_YESNO(displayconnects));
ast_cli(a->fd, FORMAT, "Timestamp events:", AST_CLI_YESNO(timestampevents));
ast_cli(a->fd, FORMAT, "Channel vars:", S_OR(manager_channelvars, ""));
ast_cli(a->fd, FORMAT, "Debug:", AST_CLI_YESNO(manager_debug));
#undef FORMAT
#undef FORMAT2
return CLI_SUCCESS;
}
#ifdef AST_XML_DOCS
static int ast_xml_doc_item_cmp_fn(const void *a, const void *b)
{
struct ast_xml_doc_item **item_a = (struct ast_xml_doc_item **)a;
struct ast_xml_doc_item **item_b = (struct ast_xml_doc_item **)b;
return strcmp((*item_a)->name, (*item_b)->name);
}
static char *handle_manager_show_events(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ao2_container *events;
struct ao2_iterator *it_events;
struct ast_xml_doc_item *item;
struct ast_xml_doc_item **items;
struct ast_str *buffer;
int i = 0, totalitems = 0;
switch (cmd) {
case CLI_INIT:
e->command = "manager show events";
e->usage =
"Usage: manager show events\n"
" Prints a listing of the available Asterisk manager interface events.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc != 3) {
return CLI_SHOWUSAGE;
}
buffer = ast_str_create(128);
if (!buffer) {
return CLI_SUCCESS;
}
events = ao2_global_obj_ref(event_docs);
if (!events) {
ast_cli(a->fd, "No manager event documentation loaded\n");
ast_free(buffer);
return CLI_SUCCESS;
}
ao2_lock(events);
if (!(it_events = ao2_callback(events, OBJ_MULTIPLE | OBJ_NOLOCK, NULL, NULL))) {
ao2_unlock(events);
ast_log(AST_LOG_ERROR, "Unable to create iterator for events container\n");
ast_free(buffer);
ao2_ref(events, -1);
return CLI_SUCCESS;
}
if (!(items = ast_calloc(sizeof(struct ast_xml_doc_item *), ao2_container_count(events)))) {
ao2_unlock(events);
ast_log(AST_LOG_ERROR, "Unable to create temporary sorting array for events\n");
ao2_iterator_destroy(it_events);
ast_free(buffer);
ao2_ref(events, -1);
return CLI_SUCCESS;
}
ao2_unlock(events);
while ((item = ao2_iterator_next(it_events))) {
items[totalitems++] = item;
ao2_ref(item, -1);
}
qsort(items, totalitems, sizeof(struct ast_xml_doc_item *), ast_xml_doc_item_cmp_fn);
ast_cli(a->fd, "Events:\n");
ast_cli(a->fd, " -------------------- -------------------- -------------------- \n");
for (i = 0; i < totalitems; i++) {
ast_str_append(&buffer, 0, " %-20.20s", items[i]->name);
if ((i + 1) % 3 == 0) {
ast_cli(a->fd, "%s\n", ast_str_buffer(buffer));
ast_str_set(&buffer, 0, "%s", "");
}
}
if ((i + 1) % 3 != 0) {
ast_cli(a->fd, "%s\n", ast_str_buffer(buffer));
}
ao2_iterator_destroy(it_events);
ast_free(items);
ao2_ref(events, -1);
ast_free(buffer);
return CLI_SUCCESS;
}
static void print_event_instance(struct ast_cli_args *a, struct ast_xml_doc_item *instance)
{
char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64];
term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
if (!ast_strlen_zero(ast_str_buffer(instance->synopsis))) {
char *synopsis = ast_xmldoc_printable(ast_str_buffer(instance->synopsis), 1);
ast_cli(a->fd, "%s%s\n\n", synopsis_title, synopsis);
ast_free(synopsis);
}
if (!ast_strlen_zero(ast_str_buffer(instance->syntax))) {
char *syntax = ast_xmldoc_printable(ast_str_buffer(instance->syntax), 1);
ast_cli(a->fd, "%s%s\n\n", syntax_title, syntax);
ast_free(syntax);
}
if (!ast_strlen_zero(ast_str_buffer(instance->description))) {
char *description = ast_xmldoc_printable(ast_str_buffer(instance->description), 1);
ast_cli(a->fd, "%s%s\n\n", description_title, description);
ast_free(description);
}
if (!ast_strlen_zero(ast_str_buffer(instance->arguments))) {
char *arguments = ast_xmldoc_printable(ast_str_buffer(instance->arguments), 1);
ast_cli(a->fd, "%s%s\n\n", arguments_title, arguments);
ast_free(arguments);
}
if (!ast_strlen_zero(ast_str_buffer(instance->seealso))) {
char *seealso = ast_xmldoc_printable(ast_str_buffer(instance->seealso), 1);
ast_cli(a->fd, "%s%s\n\n", seealso_title, seealso);
ast_free(seealso);
}
}
static char *handle_manager_show_event(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
RAII_VAR(struct ao2_container *, events, NULL, ao2_cleanup);
struct ao2_iterator it_events;
struct ast_xml_doc_item *item, *temp;
int length;
if (cmd == CLI_INIT) {
e->command = "manager show event";
e->usage =
"Usage: manager show event <eventname>\n"
" Provides a detailed description a Manager interface event.\n";
return NULL;
}
events = ao2_global_obj_ref(event_docs);
if (!events) {
ast_cli(a->fd, "No manager event documentation loaded\n");
return CLI_SUCCESS;
}
if (cmd == CLI_GENERATE) {
if (a->pos != 3) {
return NULL;
}
length = strlen(a->word);
it_events = ao2_iterator_init(events, 0);
while ((item = ao2_iterator_next(&it_events))) {
if (!strncasecmp(a->word, item->name, length)) {
if (ast_cli_completion_add(ast_strdup(item->name))) {
ao2_ref(item, -1);
break;
}
}
ao2_ref(item, -1);
}
ao2_iterator_destroy(&it_events);
return NULL;
}
if (a->argc != 4) {
return CLI_SHOWUSAGE;
}
if (!(item = ao2_find(events, a->argv[3], OBJ_KEY))) {
ast_cli(a->fd, "Could not find event '%s'\n", a->argv[3]);
return CLI_SUCCESS;
}
ast_cli(a->fd, "Event: %s\n", a->argv[3]);
for (temp = item; temp; temp = AST_LIST_NEXT(temp, next)) {
print_event_instance(a, temp);
}
ao2_ref(item, -1);
return CLI_SUCCESS;
}
#endif
static struct ast_cli_entry cli_manager[] = {
AST_CLI_DEFINE(handle_showmancmd, "Show a manager interface command"),
AST_CLI_DEFINE(handle_showmancmds, "List manager interface commands"),
AST_CLI_DEFINE(handle_showmanconn, "List connected manager interface users"),
AST_CLI_DEFINE(handle_showmaneventq, "List manager interface queued events"),
AST_CLI_DEFINE(handle_showmanagers, "List configured manager users"),
AST_CLI_DEFINE(handle_showmanager, "Display information on a specific manager user"),
AST_CLI_DEFINE(handle_mandebug, "Show, enable, disable debugging of the manager code"),
AST_CLI_DEFINE(handle_manager_reload, "Reload manager configurations"),
AST_CLI_DEFINE(handle_manager_show_settings, "Show manager global settings"),
#ifdef AST_XML_DOCS
AST_CLI_DEFINE(handle_manager_show_events, "List manager interface events"),
AST_CLI_DEFINE(handle_manager_show_event, "Show a manager interface event"),
#endif
};
/*!
* \internal
* \brief Load the config channelvars variable.
*
* \param var Config variable to load.
*
* \return Nothing
*/
static void load_channelvars(struct ast_variable *var)
{
char *parse = NULL;
AST_DECLARE_APP_ARGS(args,
AST_APP_ARG(vars)[MAX_VARS];
);
ast_free(manager_channelvars);
manager_channelvars = ast_strdup(var->value);
/* parse the setting */
parse = ast_strdupa(manager_channelvars);
AST_STANDARD_APP_ARGS(args, parse);
ast_channel_set_manager_vars(args.argc, args.vars);
}
/*!
* \internal
* \brief Free a user record. Should already be removed from the list
*/
static void manager_free_user(struct ast_manager_user *user)
{
ast_free(user->a1_hash);
ast_free(user->secret);
if (user->whitefilters) {
ao2_t_ref(user->whitefilters, -1, "decrement ref for white container, should be last one");
}
if (user->blackfilters) {
ao2_t_ref(user->blackfilters, -1, "decrement ref for black container, should be last one");
}
user->acl = ast_free_acl_list(user->acl);
ast_variables_destroy(user->chanvars);
ast_free(user);
}
/*!
* \internal
* \brief Clean up resources on Asterisk shutdown
*/
static void manager_shutdown(void)
{
struct ast_manager_user *user;
/* This event is not actually transmitted, but causes all TCP sessions to be closed */
manager_event(EVENT_FLAG_SHUTDOWN, "CloseSession", "CloseSession: true\r\n");
ast_manager_unregister("Ping");
ast_manager_unregister("Events");
ast_manager_unregister("Logoff");
ast_manager_unregister("Login");
ast_manager_unregister("Challenge");
ast_manager_unregister("Hangup");
ast_manager_unregister("Status");
ast_manager_unregister("Setvar");
ast_manager_unregister("Getvar");
ast_manager_unregister("GetConfig");
ast_manager_unregister("GetConfigJSON");
ast_manager_unregister("UpdateConfig");
ast_manager_unregister("CreateConfig");
ast_manager_unregister("ListCategories");
ast_manager_unregister("Redirect");
ast_manager_unregister("Atxfer");
ast_manager_unregister("CancelAtxfer");
ast_manager_unregister("Originate");
ast_manager_unregister("Command");
ast_manager_unregister("ExtensionState");
ast_manager_unregister("PresenceState");
ast_manager_unregister("AbsoluteTimeout");
ast_manager_unregister("MailboxStatus");
ast_manager_unregister("MailboxCount");
ast_manager_unregister("ListCommands");
ast_manager_unregister("SendText");
ast_manager_unregister("UserEvent");
ast_manager_unregister("WaitEvent");
ast_manager_unregister("CoreSettings");
ast_manager_unregister("CoreStatus");
ast_manager_unregister("Reload");
ast_manager_unregister("LoggerRotate");
ast_manager_unregister("CoreShowChannels");
ast_manager_unregister("ModuleLoad");
ast_manager_unregister("ModuleCheck");
ast_manager_unregister("AOCMessage");
ast_manager_unregister("Filter");
ast_manager_unregister("BlindTransfer");
ast_custom_function_unregister(&managerclient_function);
ast_cli_unregister_multiple(cli_manager, ARRAY_LEN(cli_manager));
#ifdef AST_XML_DOCS
ao2_t_global_obj_release(event_docs, "Dispose of event_docs");
#endif
#ifdef TEST_FRAMEWORK
stasis_forward_cancel(test_suite_forwarder);
test_suite_forwarder = NULL;
#endif
if (stasis_router) {
stasis_message_router_unsubscribe_and_join(stasis_router);
stasis_router = NULL;
}
stasis_forward_cancel(rtp_topic_forwarder);
rtp_topic_forwarder = NULL;
stasis_forward_cancel(security_topic_forwarder);
security_topic_forwarder = NULL;
ao2_cleanup(manager_topic);
manager_topic = NULL;
STASIS_MESSAGE_TYPE_CLEANUP(ast_manager_get_generic_type);
ast_tcptls_server_stop(&ami_desc);
ast_tcptls_server_stop(&amis_desc);
ast_free(ami_tls_cfg.certfile);
ami_tls_cfg.certfile = NULL;
ast_free(ami_tls_cfg.pvtfile);
ami_tls_cfg.pvtfile = NULL;
ast_free(ami_tls_cfg.cipher);
ami_tls_cfg.cipher = NULL;
ast_free(ami_tls_cfg.cafile);
ami_tls_cfg.cafile = NULL;
ast_free(ami_tls_cfg.capath);
ami_tls_cfg.capath = NULL;
ao2_global_obj_release(mgr_sessions);
while ((user = AST_LIST_REMOVE_HEAD(&users, list))) {
manager_free_user(user);
}
acl_change_stasis_unsubscribe();
ast_free(manager_channelvars);
}
/*! \brief Initialize all \ref stasis topics and routers used by the various
* sub-components of AMI
*/
static int manager_subscriptions_init(void)
{
int res = 0;
rtp_topic_forwarder = stasis_forward_all(ast_rtp_topic(), manager_topic);
if (!rtp_topic_forwarder) {
return -1;
}
security_topic_forwarder = stasis_forward_all(ast_security_topic(), manager_topic);
if (!security_topic_forwarder) {
return -1;
}
stasis_router = stasis_message_router_create(manager_topic);
if (!stasis_router) {
return -1;
}
stasis_message_router_set_congestion_limits(stasis_router, -1,
6 * AST_TASKPROCESSOR_HIGH_WATER_LEVEL);
stasis_message_router_set_formatters_default(stasis_router,
manager_default_msg_cb, NULL, STASIS_SUBSCRIPTION_FORMATTER_AMI);
res |= stasis_message_router_add(stasis_router,
ast_manager_get_generic_type(), manager_generic_msg_cb, NULL);
if (res != 0) {
return -1;
}
return 0;
}
static int subscribe_all(void)
{
if (manager_subscriptions_init()) {
ast_log(AST_LOG_ERROR, "Failed to initialize manager subscriptions\n");
return -1;
}
if (manager_system_init()) {
ast_log(AST_LOG_ERROR, "Failed to initialize manager system handling\n");
return -1;
}
if (manager_channels_init()) {
ast_log(AST_LOG_ERROR, "Failed to initialize manager channel handling\n");
return -1;
}
if (manager_mwi_init()) {
ast_log(AST_LOG_ERROR, "Failed to initialize manager MWI handling\n");
return -1;
}
if (manager_bridging_init()) {
return -1;
}
if (manager_endpoints_init()) {
ast_log(AST_LOG_ERROR, "Failed to initialize manager endpoints handling\n");
return -1;
}
subscribed = 1;
return 0;
}
static void manager_set_defaults(void)
{
manager_enabled = 0;
displayconnects = 1;
broken_events_action = 0;
authtimeout = 30;
authlimit = 50;
manager_debug = 0; /* Debug disabled by default */
/* default values */
ast_copy_string(global_realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM),
sizeof(global_realm));
ast_sockaddr_setnull(&ami_desc.local_address);
ast_sockaddr_setnull(&amis_desc.local_address);
ami_tls_cfg.enabled = 0;
ast_free(ami_tls_cfg.certfile);
ami_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
ast_free(ami_tls_cfg.pvtfile);
ami_tls_cfg.pvtfile = ast_strdup("");
ast_free(ami_tls_cfg.cipher);
ami_tls_cfg.cipher = ast_strdup("");
ast_free(ami_tls_cfg.cafile);
ami_tls_cfg.cafile = ast_strdup("");
ast_free(ami_tls_cfg.capath);
ami_tls_cfg.capath = ast_strdup("");
}
static int __init_manager(int reload, int by_external_config)
{
struct ast_config *ucfg = NULL, *cfg = NULL;
const char *val;
char *cat = NULL;
int newhttptimeout = 60;
struct ast_manager_user *user = NULL;
struct ast_variable *var;
struct ast_flags config_flags = { (reload && !by_external_config) ? CONFIG_FLAG_FILEUNCHANGED : 0 };
char a1[256];
char a1_hash[256];
struct ast_sockaddr ami_desc_local_address_tmp;
struct ast_sockaddr amis_desc_local_address_tmp;
int tls_was_enabled = 0;
int acl_subscription_flag = 0;
if (!reload) {
struct ao2_container *sessions;
#ifdef AST_XML_DOCS
struct ao2_container *temp_event_docs;
#endif
int res;
res = STASIS_MESSAGE_TYPE_INIT(ast_manager_get_generic_type);
if (res != 0) {
return -1;
}
manager_topic = stasis_topic_create("manager_topic");
if (!manager_topic) {
return -1;
}
/* Register default actions */
ast_manager_register_xml_core("Ping", 0, action_ping);
ast_manager_register_xml_core("Events", 0, action_events);
ast_manager_register_xml_core("Logoff", 0, action_logoff);
ast_manager_register_xml_core("Login", 0, action_login);
ast_manager_register_xml_core("Challenge", 0, action_challenge);
ast_manager_register_xml_core("Hangup", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_hangup);
ast_manager_register_xml_core("Status", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_status);
ast_manager_register_xml_core("Setvar", EVENT_FLAG_CALL, action_setvar);
ast_manager_register_xml_core("Getvar", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_getvar);
ast_manager_register_xml_core("GetConfig", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfig);
ast_manager_register_xml_core("GetConfigJSON", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfigjson);
ast_manager_register_xml_core("UpdateConfig", EVENT_FLAG_CONFIG, action_updateconfig);
ast_manager_register_xml_core("CreateConfig", EVENT_FLAG_CONFIG, action_createconfig);
ast_manager_register_xml_core("ListCategories", EVENT_FLAG_CONFIG, action_listcategories);
ast_manager_register_xml_core("Redirect", EVENT_FLAG_CALL, action_redirect);
ast_manager_register_xml_core("Atxfer", EVENT_FLAG_CALL, action_atxfer);
ast_manager_register_xml_core("CancelAtxfer", EVENT_FLAG_CALL, action_cancel_atxfer);
ast_manager_register_xml_core("Originate", EVENT_FLAG_ORIGINATE, action_originate);
ast_manager_register_xml_core("Command", EVENT_FLAG_COMMAND, action_command);
ast_manager_register_xml_core("ExtensionState", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_extensionstate);
ast_manager_register_xml_core("PresenceState", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_presencestate);
ast_manager_register_xml_core("AbsoluteTimeout", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_timeout);
ast_manager_register_xml_core("MailboxStatus", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxstatus);
ast_manager_register_xml_core("MailboxCount", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxcount);
ast_manager_register_xml_core("ListCommands", 0, action_listcommands);
ast_manager_register_xml_core("SendText", EVENT_FLAG_CALL, action_sendtext);
ast_manager_register_xml_core("UserEvent", EVENT_FLAG_USER, action_userevent);
ast_manager_register_xml_core("WaitEvent", 0, action_waitevent);
ast_manager_register_xml_core("CoreSettings", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coresettings);
ast_manager_register_xml_core("CoreStatus", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_corestatus);
ast_manager_register_xml_core("Reload", EVENT_FLAG_CONFIG | EVENT_FLAG_SYSTEM, action_reload);
ast_manager_register_xml_core("LoggerRotate", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_loggerrotate);
ast_manager_register_xml_core("CoreShowChannels", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coreshowchannels);
ast_manager_register_xml_core("ModuleLoad", EVENT_FLAG_SYSTEM, manager_moduleload);
ast_manager_register_xml_core("ModuleCheck", EVENT_FLAG_SYSTEM, manager_modulecheck);
ast_manager_register_xml_core("AOCMessage", EVENT_FLAG_AOC, action_aocmessage);
ast_manager_register_xml_core("Filter", EVENT_FLAG_SYSTEM, action_filter);
ast_manager_register_xml_core("BlindTransfer", EVENT_FLAG_CALL, action_blind_transfer);
#ifdef TEST_FRAMEWORK
test_suite_forwarder = stasis_forward_all(ast_test_suite_topic(), manager_topic);
#endif
ast_cli_register_multiple(cli_manager, ARRAY_LEN(cli_manager));
__ast_custom_function_register(&managerclient_function, NULL);
ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
/* Append placeholder event so master_eventq never runs dry */
if (append_event("Event: Placeholder\r\n\r\n", 0)) {
return -1;
}
#ifdef AST_XML_DOCS
temp_event_docs = ast_xmldoc_build_documentation("managerEvent");
if (temp_event_docs) {
ao2_t_global_obj_replace_unref(event_docs, temp_event_docs, "Toss old event docs");
ao2_t_ref(temp_event_docs, -1, "Remove creation ref - container holds only ref now");
}
#endif
/* If you have a NULL hash fn, you only need a single bucket */
sessions = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, mansession_cmp_fn);
if (!sessions) {
return -1;
}
ao2_global_obj_replace_unref(mgr_sessions, sessions);
ao2_ref(sessions, -1);
/* Initialize all settings before first configuration load. */
manager_set_defaults();
}
cfg = ast_config_load2("manager.conf", "manager", config_flags);
if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
return 0;
} else if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
ast_log(LOG_NOTICE, "Unable to open AMI configuration manager.conf, or configuration is invalid.\n");
return 0;
}
/* If this wasn't performed due to a forced reload (because those can be created by ACL change events, we need to unsubscribe to ACL change events. */
if (!by_external_config) {
acl_change_stasis_unsubscribe();
}
if (reload) {
/* Reset all settings before reloading configuration */
tls_was_enabled = ami_tls_cfg.enabled;
manager_set_defaults();
}
ast_sockaddr_parse(&ami_desc_local_address_tmp, "[::]", 0);
ast_sockaddr_set_port(&ami_desc_local_address_tmp, DEFAULT_MANAGER_PORT);
for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
val = var->value;
/* read tls config options while preventing unsupported options from being set */
if (strcasecmp(var->name, "tlscafile")
&& strcasecmp(var->name, "tlscapath")
&& strcasecmp(var->name, "tlscadir")
&& strcasecmp(var->name, "tlsverifyclient")
&& strcasecmp(var->name, "tlsdontverifyserver")
&& strcasecmp(var->name, "tlsclientmethod")
&& strcasecmp(var->name, "sslclientmethod")
&& !ast_tls_read_conf(&ami_tls_cfg, &amis_desc, var->name, val)) {
continue;
}
if (!strcasecmp(var->name, "enabled")) {
manager_enabled = ast_true(val);
} else if (!strcasecmp(var->name, "webenabled")) {
webmanager_enabled = ast_true(val);
} else if (!strcasecmp(var->name, "port")) {
int bindport;
if (ast_parse_arg(val, PARSE_UINT32|PARSE_IN_RANGE, &bindport, 1024, 65535)) {
ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
}
ast_sockaddr_set_port(&ami_desc_local_address_tmp, bindport);
} else if (!strcasecmp(var->name, "bindaddr")) {
/* remember port if it has already been set */
int setport = ast_sockaddr_port(&ami_desc_local_address_tmp);
if (ast_parse_arg(val, PARSE_ADDR|PARSE_PORT_IGNORE, NULL)) {
ast_log(LOG_WARNING, "Invalid address '%s' specified, default '%s' will be used\n", val,
ast_sockaddr_stringify_addr(&ami_desc_local_address_tmp));
} else {
ast_sockaddr_parse(&ami_desc_local_address_tmp, val, PARSE_PORT_IGNORE);
}
if (setport) {
ast_sockaddr_set_port(&ami_desc_local_address_tmp, setport);
}
} else if (!strcasecmp(var->name, "brokeneventsaction")) {
broken_events_action = ast_true(val);
} else if (!strcasecmp(var->name, "allowmultiplelogin")) {
allowmultiplelogin = ast_true(val);
} else if (!strcasecmp(var->name, "displayconnects")) {
displayconnects = ast_true(val);
} else if (!strcasecmp(var->name, "timestampevents")) {
timestampevents = ast_true(val);
} else if (!strcasecmp(var->name, "debug")) {
manager_debug = ast_true(val);
} else if (!strcasecmp(var->name, "httptimeout")) {
newhttptimeout = atoi(val);
} else if (!strcasecmp(var->name, "authtimeout")) {
int timeout = atoi(var->value);
if (timeout < 1) {
ast_log(LOG_WARNING, "Invalid authtimeout value '%s', using default value\n", var->value);
} else {
authtimeout = timeout;
}
} else if (!strcasecmp(var->name, "authlimit")) {
int limit = atoi(var->value);
if (limit < 1) {
ast_log(LOG_WARNING, "Invalid authlimit value '%s', using default value\n", var->value);
} else {
authlimit = limit;
}
} else if (!strcasecmp(var->name, "channelvars")) {
load_channelvars(var);
} else {
ast_log(LOG_NOTICE, "Invalid keyword <%s> = <%s> in manager.conf [general]\n",
var->name, val);
}
}
if (manager_enabled && !subscribed) {
if (subscribe_all() != 0) {
ast_log(LOG_ERROR, "Manager subscription error\n");
return -1;
}
}
ast_sockaddr_copy(&amis_desc_local_address_tmp, &amis_desc.local_address);
/* if the amis address has not been set, default is the same as non secure ami */
if (ast_sockaddr_isnull(&amis_desc_local_address_tmp)) {
ast_sockaddr_copy(&amis_desc_local_address_tmp, &ami_desc_local_address_tmp);
}
/* if the amis address was not set, it will have non-secure ami port set; if
amis address was set, we need to check that a port was set or not, if not
use the default tls port */
if (ast_sockaddr_port(&amis_desc_local_address_tmp) == 0 ||
(ast_sockaddr_port(&ami_desc_local_address_tmp) == ast_sockaddr_port(&amis_desc_local_address_tmp))) {
ast_sockaddr_set_port(&amis_desc_local_address_tmp, DEFAULT_MANAGER_TLS_PORT);
}
if (manager_enabled) {
ast_sockaddr_copy(&ami_desc.local_address, &ami_desc_local_address_tmp);
ast_sockaddr_copy(&amis_desc.local_address, &amis_desc_local_address_tmp);
}
AST_RWLIST_WRLOCK(&users);
/* First, get users from users.conf */
ucfg = ast_config_load2("users.conf", "manager", config_flags);
if (ucfg && (ucfg != CONFIG_STATUS_FILEUNCHANGED) && ucfg != CONFIG_STATUS_FILEINVALID) {
const char *hasmanager;
int genhasmanager = ast_true(ast_variable_retrieve(ucfg, "general", "hasmanager"));
while ((cat = ast_category_browse(ucfg, cat))) {
if (!strcasecmp(cat, "general")) {
continue;
}
hasmanager = ast_variable_retrieve(ucfg, cat, "hasmanager");
if ((!hasmanager && genhasmanager) || ast_true(hasmanager)) {
const char *user_secret = ast_variable_retrieve(ucfg, cat, "secret");
const char *user_read = ast_variable_retrieve(ucfg, cat, "read");
const char *user_write = ast_variable_retrieve(ucfg, cat, "write");
const char *user_displayconnects = ast_variable_retrieve(ucfg, cat, "displayconnects");
const char *user_allowmultiplelogin = ast_variable_retrieve(ucfg, cat, "allowmultiplelogin");
const char *user_writetimeout = ast_variable_retrieve(ucfg, cat, "writetimeout");
/* Look for an existing entry,
* if none found - create one and add it to the list
*/
if (!(user = get_manager_by_name_locked(cat))) {
if (!(user = ast_calloc(1, sizeof(*user)))) {
break;
}
/* Copy name over */
ast_copy_string(user->username, cat, sizeof(user->username));
/* Insert into list */
AST_LIST_INSERT_TAIL(&users, user, list);
user->acl = NULL;
user->keep = 1;
user->readperm = -1;
user->writeperm = -1;
/* Default displayconnect from [general] */
user->displayconnects = displayconnects;
/* Default allowmultiplelogin from [general] */
user->allowmultiplelogin = allowmultiplelogin;
user->writetimeout = 100;
}
if (!user_secret) {
user_secret = ast_variable_retrieve(ucfg, "general", "secret");
}
if (!user_read) {
user_read = ast_variable_retrieve(ucfg, "general", "read");
}
if (!user_write) {
user_write = ast_variable_retrieve(ucfg, "general", "write");
}
if (!user_displayconnects) {
user_displayconnects = ast_variable_retrieve(ucfg, "general", "displayconnects");
}
if (!user_allowmultiplelogin) {
user_allowmultiplelogin = ast_variable_retrieve(ucfg, "general", "allowmultiplelogin");
}
if (!user_writetimeout) {
user_writetimeout = ast_variable_retrieve(ucfg, "general", "writetimeout");
}
if (!ast_strlen_zero(user_secret)) {
ast_free(user->secret);
user->secret = ast_strdup(user_secret);
}
if (user_read) {
user->readperm = get_perm(user_read);
}
if (user_write) {
user->writeperm = get_perm(user_write);
}
if (user_displayconnects) {
user->displayconnects = ast_true(user_displayconnects);
}
if (user_allowmultiplelogin) {
user->allowmultiplelogin = ast_true(user_allowmultiplelogin);
}
if (user_writetimeout) {
int value = atoi(user_writetimeout);
if (value < 100) {
ast_log(LOG_WARNING, "Invalid writetimeout value '%d' in users.conf\n", value);
} else {
user->writetimeout = value;
}
}
}
}
ast_config_destroy(ucfg);
}
/* cat is NULL here in any case */
while ((cat = ast_category_browse(cfg, cat))) {
struct ast_acl_list *oldacl;
if (!strcasecmp(cat, "general")) {
continue;
}
/* Look for an existing entry, if none found - create one and add it to the list */
if (!(user = get_manager_by_name_locked(cat))) {
if (!(user = ast_calloc(1, sizeof(*user)))) {
break;
}
/* Copy name over */
ast_copy_string(user->username, cat, sizeof(user->username));
user->acl = NULL;
user->readperm = 0;
user->writeperm = 0;
/* Default displayconnect from [general] */
user->displayconnects = displayconnects;
/* Default allowmultiplelogin from [general] */
user->allowmultiplelogin = allowmultiplelogin;
user->writetimeout = 100;
user->whitefilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
user->blackfilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
if (!user->whitefilters || !user->blackfilters) {
manager_free_user(user);
break;
}
/* Insert into list */
AST_RWLIST_INSERT_TAIL(&users, user, list);
} else {
ao2_t_callback(user->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
ao2_t_callback(user->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
}
/* Make sure we keep this user and don't destroy it during cleanup */
user->keep = 1;
oldacl = user->acl;
user->acl = NULL;
ast_variables_destroy(user->chanvars);
var = ast_variable_browse(cfg, cat);
for (; var; var = var->next) {
if (!strcasecmp(var->name, "secret")) {
ast_free(user->secret);
user->secret = ast_strdup(var->value);
} else if (!strcasecmp(var->name, "deny") ||
!strcasecmp(var->name, "permit") ||
!strcasecmp(var->name, "acl")) {
int acl_error = 0;
ast_append_acl(var->name, var->value, &user->acl, &acl_error, &acl_subscription_flag);
if (acl_error) {
ast_log(LOG_ERROR, "Invalid ACL '%s' for manager user '%s' on line %d. Deleting user\n",
var->value, user->username, var->lineno);
user->keep = 0;
}
} else if (!strcasecmp(var->name, "read") ) {
user->readperm = get_perm(var->value);
} else if (!strcasecmp(var->name, "write") ) {
user->writeperm = get_perm(var->value);
} else if (!strcasecmp(var->name, "displayconnects") ) {
user->displayconnects = ast_true(var->value);
} else if (!strcasecmp(var->name, "allowmultiplelogin") ) {
user->allowmultiplelogin = ast_true(var->value);
} else if (!strcasecmp(var->name, "writetimeout")) {
int value = atoi(var->value);
if (value < 100) {
ast_log(LOG_WARNING, "Invalid writetimeout value '%s' at line %d\n", var->value, var->lineno);
} else {
user->writetimeout = value;
}
} else if (!strcasecmp(var->name, "setvar")) {
struct ast_variable *tmpvar;
char varbuf[256];
char *varval;
char *varname;
ast_copy_string(varbuf, var->value, sizeof(varbuf));
varname = varbuf;
if ((varval = strchr(varname,'='))) {
*varval++ = '\0';
if ((tmpvar = ast_variable_new(varname, varval, ""))) {
tmpvar->next = user->chanvars;
user->chanvars = tmpvar;
}
}
} else if (!strcasecmp(var->name, "eventfilter")) {
const char *value = var->value;
manager_add_filter(value, user->whitefilters, user->blackfilters);
} else {
ast_debug(1, "%s is an unknown option.\n", var->name);
}
}
oldacl = ast_free_acl_list(oldacl);
}
ast_config_destroy(cfg);
/* Check the flag for named ACL event subscription and if we need to, register a subscription. */
if (acl_subscription_flag && !by_external_config) {
acl_change_stasis_subscribe();
}
/* Perform cleanup - essentially prune out old users that no longer exist */
AST_RWLIST_TRAVERSE_SAFE_BEGIN(&users, user, list) {
if (user->keep) { /* valid record. clear flag for the next round */
user->keep = 0;
/* Calculate A1 for Digest auth */
snprintf(a1, sizeof(a1), "%s:%s:%s", user->username, global_realm, user->secret);
ast_md5_hash(a1_hash,a1);
ast_free(user->a1_hash);
user->a1_hash = ast_strdup(a1_hash);
continue;
}
/* We do not need to keep this user so take them out of the list */
AST_RWLIST_REMOVE_CURRENT(list);
ast_debug(4, "Pruning user '%s'\n", user->username);
manager_free_user(user);
}
AST_RWLIST_TRAVERSE_SAFE_END;
AST_RWLIST_UNLOCK(&users);
if (webmanager_enabled && manager_enabled) {
if (!webregged) {
ast_http_uri_link(&rawmanuri);
ast_http_uri_link(&manageruri);
ast_http_uri_link(&managerxmluri);
ast_http_uri_link(&arawmanuri);
ast_http_uri_link(&amanageruri);
ast_http_uri_link(&amanagerxmluri);
webregged = 1;
}
} else {
if (webregged) {
ast_http_uri_unlink(&rawmanuri);
ast_http_uri_unlink(&manageruri);
ast_http_uri_unlink(&managerxmluri);
ast_http_uri_unlink(&arawmanuri);
ast_http_uri_unlink(&amanageruri);
ast_http_uri_unlink(&amanagerxmluri);
webregged = 0;
}
}
if (newhttptimeout > 0) {
httptimeout = newhttptimeout;
}
ast_tcptls_server_start(&ami_desc);
if (tls_was_enabled && !ami_tls_cfg.enabled) {
ast_tcptls_server_stop(&amis_desc);
} else if (ast_ssl_setup(amis_desc.tls_cfg)) {
ast_tcptls_server_start(&amis_desc);
}
return 0;
}
static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
struct stasis_message *message)
{
if (stasis_message_type(message) != ast_named_acl_change_type()) {
return;
}
/* For now, this is going to be performed simply and just execute a forced reload. */
ast_log(LOG_NOTICE, "Reloading manager in response to ACL change event.\n");
__init_manager(1, 1);
}
static int unload_module(void)
{
return 0;
}
static int load_module(void)
{
ast_register_cleanup(manager_shutdown);
return __init_manager(0, 0) ? AST_MODULE_LOAD_FAILURE : AST_MODULE_LOAD_SUCCESS;
}
static int reload_module(void)
{
return __init_manager(1, 0);
}
int astman_datastore_add(struct mansession *s, struct ast_datastore *datastore)
{
AST_LIST_INSERT_HEAD(&s->session->datastores, datastore, entry);
return 0;
}
int astman_datastore_remove(struct mansession *s, struct ast_datastore *datastore)
{
return AST_LIST_REMOVE(&s->session->datastores, datastore, entry) ? 0 : -1;
}
struct ast_datastore *astman_datastore_find(struct mansession *s, const struct ast_datastore_info *info, const char *uid)
{
struct ast_datastore *datastore = NULL;
if (info == NULL)
return NULL;
AST_LIST_TRAVERSE_SAFE_BEGIN(&s->session->datastores, datastore, entry) {
if (datastore->info != info) {
continue;
}
if (uid == NULL) {
/* matched by type only */
break;
}
if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
/* Matched by type AND uid */
break;
}
}
AST_LIST_TRAVERSE_SAFE_END;
return datastore;
}
int ast_str_append_event_header(struct ast_str **fields_string,
const char *header, const char *value)
{
if (!*fields_string) {
*fields_string = ast_str_create(128);
if (!*fields_string) {
return -1;
}
}
return (ast_str_append(fields_string, 0, "%s: %s\r\n", header, value) < 0) ? -1 : 0;
}
static void manager_event_blob_dtor(void *obj)
{
struct ast_manager_event_blob *ev = obj;
ast_string_field_free_memory(ev);
}
struct ast_manager_event_blob *
__attribute__((format(printf, 3, 4)))
ast_manager_event_blob_create(
int event_flags,
const char *manager_event,
const char *extra_fields_fmt,
...)
{
struct ast_manager_event_blob *ev;
va_list argp;
ast_assert(extra_fields_fmt != NULL);
ast_assert(manager_event != NULL);
ev = ao2_alloc_options(sizeof(*ev), manager_event_blob_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK);
if (!ev) {
return NULL;
}
if (ast_string_field_init(ev, 20)) {
ao2_ref(ev, -1);
return NULL;
}
ev->manager_event = manager_event;
ev->event_flags = event_flags;
va_start(argp, extra_fields_fmt);
ast_string_field_ptr_build_va(ev, &ev->extra_fields, extra_fields_fmt, argp);
va_end(argp);
return ev;
}
AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Asterisk Manager Interface",
.support_level = AST_MODULE_SUPPORT_CORE,
.load = load_module,
.unload = unload_module,
.reload = reload_module,
.load_pri = AST_MODPRI_CORE,
.requires = "extconfig,acl,http",
);
|