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 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926
|
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 1999 - 2008, 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 Core PBX routines.
*
* \author Mark Spencer <markster@digium.com>
*/
#include "asterisk.h"
ASTERISK_FILE_VERSION(__FILE__, "$Revision: 361471 $")
#include "asterisk/_private.h"
#include "asterisk/paths.h" /* use ast_config_AST_SYSTEM_NAME */
#include <ctype.h>
#include <time.h>
#include <sys/time.h>
#if defined(HAVE_SYSINFO)
#include <sys/sysinfo.h>
#endif
#if defined(SOLARIS)
#include <sys/loadavg.h>
#endif
#include "asterisk/lock.h"
#include "asterisk/cli.h"
#include "asterisk/pbx.h"
#include "asterisk/channel.h"
#include "asterisk/file.h"
#include "asterisk/callerid.h"
#include "asterisk/cdr.h"
#include "asterisk/cel.h"
#include "asterisk/config.h"
#include "asterisk/term.h"
#include "asterisk/time.h"
#include "asterisk/manager.h"
#include "asterisk/ast_expr.h"
#include "asterisk/linkedlists.h"
#define SAY_STUBS /* generate declarations and stubs for say methods */
#include "asterisk/say.h"
#include "asterisk/utils.h"
#include "asterisk/causes.h"
#include "asterisk/musiconhold.h"
#include "asterisk/app.h"
#include "asterisk/devicestate.h"
#include "asterisk/event.h"
#include "asterisk/hashtab.h"
#include "asterisk/module.h"
#include "asterisk/indications.h"
#include "asterisk/taskprocessor.h"
#include "asterisk/xmldoc.h"
#include "asterisk/astobj2.h"
/*!
* \note I M P O R T A N T :
*
* The speed of extension handling will likely be among the most important
* aspects of this PBX. The switching scheme as it exists right now isn't
* terribly bad (it's O(N+M), where N is the # of extensions and M is the avg #
* of priorities, but a constant search time here would be great ;-)
*
* A new algorithm to do searching based on a 'compiled' pattern tree is introduced
* here, and shows a fairly flat (constant) search time, even for over
* 10000 patterns.
*
* Also, using a hash table for context/priority name lookup can help prevent
* the find_extension routines from absorbing exponential cpu cycles as the number
* of contexts/priorities grow. I've previously tested find_extension with red-black trees,
* which have O(log2(n)) speed. Right now, I'm using hash tables, which do
* searches (ideally) in O(1) time. While these techniques do not yield much
* speed in small dialplans, they are worth the trouble in large dialplans.
*
*/
/*** DOCUMENTATION
<application name="Answer" language="en_US">
<synopsis>
Answer a channel if ringing.
</synopsis>
<syntax>
<parameter name="delay">
<para>Asterisk will wait this number of milliseconds before returning to
the dialplan after answering the call.</para>
</parameter>
<parameter name="nocdr">
<para>Asterisk will send an answer signal to the calling phone, but will not
set the disposition or answer time in the CDR for this call.</para>
</parameter>
</syntax>
<description>
<para>If the call has not been answered, this application will
answer it. Otherwise, it has no effect on the call.</para>
</description>
<see-also>
<ref type="application">Hangup</ref>
</see-also>
</application>
<application name="BackGround" language="en_US">
<synopsis>
Play an audio file while waiting for digits of an extension to go to.
</synopsis>
<syntax>
<parameter name="filenames" required="true" argsep="&">
<argument name="filename1" required="true" />
<argument name="filename2" multiple="true" />
</parameter>
<parameter name="options">
<optionlist>
<option name="s">
<para>Causes the playback of the message to be skipped
if the channel is not in the <literal>up</literal> state (i.e. it
hasn't been answered yet). If this happens, the
application will return immediately.</para>
</option>
<option name="n">
<para>Don't answer the channel before playing the files.</para>
</option>
<option name="m">
<para>Only break if a digit hit matches a one digit
extension in the destination context.</para>
</option>
</optionlist>
</parameter>
<parameter name="langoverride">
<para>Explicitly specifies which language to attempt to use for the requested sound files.</para>
</parameter>
<parameter name="context">
<para>This is the dialplan context that this application will use when exiting
to a dialed extension.</para>
</parameter>
</syntax>
<description>
<para>This application will play the given list of files <emphasis>(do not put extension)</emphasis>
while waiting for an extension to be dialed by the calling channel. To continue waiting
for digits after this application has finished playing files, the <literal>WaitExten</literal>
application should be used.</para>
<para>If one of the requested sound files does not exist, call processing will be terminated.</para>
<para>This application sets the following channel variable upon completion:</para>
<variablelist>
<variable name="BACKGROUNDSTATUS">
<para>The status of the background attempt as a text string.</para>
<value name="SUCCESS" />
<value name="FAILED" />
</variable>
</variablelist>
</description>
<see-also>
<ref type="application">ControlPlayback</ref>
<ref type="application">WaitExten</ref>
<ref type="application">BackgroundDetect</ref>
<ref type="function">TIMEOUT</ref>
</see-also>
</application>
<application name="Busy" language="en_US">
<synopsis>
Indicate the Busy condition.
</synopsis>
<syntax>
<parameter name="timeout">
<para>If specified, the calling channel will be hung up after the specified number of seconds.
Otherwise, this application will wait until the calling channel hangs up.</para>
</parameter>
</syntax>
<description>
<para>This application will indicate the busy condition to the calling channel.</para>
</description>
<see-also>
<ref type="application">Congestion</ref>
<ref type="application">Progress</ref>
<ref type="application">Playtones</ref>
<ref type="application">Hangup</ref>
</see-also>
</application>
<application name="Congestion" language="en_US">
<synopsis>
Indicate the Congestion condition.
</synopsis>
<syntax>
<parameter name="timeout">
<para>If specified, the calling channel will be hung up after the specified number of seconds.
Otherwise, this application will wait until the calling channel hangs up.</para>
</parameter>
</syntax>
<description>
<para>This application will indicate the congestion condition to the calling channel.</para>
</description>
<see-also>
<ref type="application">Busy</ref>
<ref type="application">Progress</ref>
<ref type="application">Playtones</ref>
<ref type="application">Hangup</ref>
</see-also>
</application>
<application name="ExecIfTime" language="en_US">
<synopsis>
Conditional application execution based on the current time.
</synopsis>
<syntax argsep="?">
<parameter name="day_condition" required="true">
<argument name="times" required="true" />
<argument name="weekdays" required="true" />
<argument name="mdays" required="true" />
<argument name="months" required="true" />
<argument name="timezone" required="false" />
</parameter>
<parameter name="appname" required="true" hasparams="optional">
<argument name="appargs" required="true" />
</parameter>
</syntax>
<description>
<para>This application will execute the specified dialplan application, with optional
arguments, if the current time matches the given time specification.</para>
</description>
<see-also>
<ref type="application">Exec</ref>
<ref type="application">TryExec</ref>
</see-also>
</application>
<application name="Goto" language="en_US">
<synopsis>
Jump to a particular priority, extension, or context.
</synopsis>
<syntax>
<parameter name="context" />
<parameter name="extensions" />
<parameter name="priority" required="true" />
</syntax>
<description>
<para>This application will set the current context, extension, and priority in the channel structure.
After it completes, the pbx engine will continue dialplan execution at the specified location.
If no specific <replaceable>extension</replaceable>, or <replaceable>extension</replaceable> and
<replaceable>context</replaceable>, are specified, then this application will
just set the specified <replaceable>priority</replaceable> of the current extension.</para>
<para>At least a <replaceable>priority</replaceable> is required as an argument, or the goto will
return a <literal>-1</literal>, and the channel and call will be terminated.</para>
<para>If the location that is put into the channel information is bogus, and asterisk cannot
find that location in the dialplan, then the execution engine will try to find and execute the code in
the <literal>i</literal> (invalid) extension in the current context. If that does not exist, it will try to execute the
<literal>h</literal> extension. If neither the <literal>h</literal> nor <literal>i</literal> extensions
have been defined, the channel is hung up, and the execution of instructions on the channel is terminated.
What this means is that, for example, you specify a context that does not exist, then
it will not be possible to find the <literal>h</literal> or <literal>i</literal> extensions,
and the call will terminate!</para>
</description>
<see-also>
<ref type="application">GotoIf</ref>
<ref type="application">GotoIfTime</ref>
<ref type="application">Gosub</ref>
<ref type="application">Macro</ref>
</see-also>
</application>
<application name="GotoIf" language="en_US">
<synopsis>
Conditional goto.
</synopsis>
<syntax argsep="?">
<parameter name="condition" required="true" />
<parameter name="destination" required="true" argsep=":">
<argument name="labeliftrue">
<para>Continue at <replaceable>labeliftrue</replaceable> if the condition is true.</para>
</argument>
<argument name="labeliffalse">
<para>Continue at <replaceable>labeliffalse</replaceable> if the condition is false.</para>
</argument>
</parameter>
</syntax>
<description>
<para>This application will set the current context, extension, and priority in the channel structure
based on the evaluation of the given condition. After this application completes, the
pbx engine will continue dialplan execution at the specified location in the dialplan.
The labels are specified with the same syntax as used within the Goto application.
If the label chosen by the condition is omitted, no jump is performed, and the execution passes to the
next instruction. If the target location is bogus, and does not exist, the execution engine will try
to find and execute the code in the <literal>i</literal> (invalid) extension in the current context.
If that does not exist, it will try to execute the <literal>h</literal> extension.
If neither the <literal>h</literal> nor <literal>i</literal> extensions have been defined,
the channel is hung up, and the execution of instructions on the channel is terminated.
Remember that this command can set the current context, and if the context specified
does not exist, then it will not be able to find any 'h' or 'i' extensions there, and
the channel and call will both be terminated!.</para>
</description>
<see-also>
<ref type="application">Goto</ref>
<ref type="application">GotoIfTime</ref>
<ref type="application">GosubIf</ref>
<ref type="application">MacroIf</ref>
</see-also>
</application>
<application name="GotoIfTime" language="en_US">
<synopsis>
Conditional Goto based on the current time.
</synopsis>
<syntax argsep="?">
<parameter name="condition" required="true">
<argument name="times" required="true" />
<argument name="weekdays" required="true" />
<argument name="mdays" required="true" />
<argument name="months" required="true" />
<argument name="timezone" required="false" />
</parameter>
<parameter name="destination" required="true" argsep=":">
<argument name="labeliftrue" />
<argument name="labeliffalse" />
</parameter>
</syntax>
<description>
<para>This application will set the context, extension, and priority in the channel structure
based on the evaluation of the given time specification. After this application completes,
the pbx engine will continue dialplan execution at the specified location in the dialplan.
If the current time is within the given time specification, the channel will continue at
<replaceable>labeliftrue</replaceable>. Otherwise the channel will continue at <replaceable>labeliffalse</replaceable>.
If the label chosen by the condition is omitted, no jump is performed, and execution passes to the next
instruction. If the target jump location is bogus, the same actions would be taken as for <literal>Goto</literal>.
Further information on the time specification can be found in examples
illustrating how to do time-based context includes in the dialplan.</para>
</description>
<see-also>
<ref type="application">GotoIf</ref>
<ref type="function">IFTIME</ref>
<ref type="function">TESTTIME</ref>
</see-also>
</application>
<application name="ImportVar" language="en_US">
<synopsis>
Import a variable from a channel into a new variable.
</synopsis>
<syntax argsep="=">
<parameter name="newvar" required="true" />
<parameter name="vardata" required="true">
<argument name="channelname" required="true" />
<argument name="variable" required="true" />
</parameter>
</syntax>
<description>
<para>This application imports a <replaceable>variable</replaceable> from the specified
<replaceable>channel</replaceable> (as opposed to the current one) and stores it as a variable
(<replaceable>newvar</replaceable>) in the current channel (the channel that is calling this
application). Variables created by this application have the same inheritance properties as those
created with the <literal>Set</literal> application.</para>
</description>
<see-also>
<ref type="application">Set</ref>
</see-also>
</application>
<application name="Hangup" language="en_US">
<synopsis>
Hang up the calling channel.
</synopsis>
<syntax>
<parameter name="causecode">
<para>If a <replaceable>causecode</replaceable> is given the channel's
hangup cause will be set to the given value.</para>
</parameter>
</syntax>
<description>
<para>This application will hang up the calling channel.</para>
</description>
<see-also>
<ref type="application">Answer</ref>
<ref type="application">Busy</ref>
<ref type="application">Congestion</ref>
</see-also>
</application>
<application name="Incomplete" language="en_US">
<synopsis>
Returns AST_PBX_INCOMPLETE value.
</synopsis>
<syntax>
<parameter name="n">
<para>If specified, then Incomplete will not attempt to answer the channel first.</para>
<note><para>Most channel types need to be in Answer state in order to receive DTMF.</para></note>
</parameter>
</syntax>
<description>
<para>Signals the PBX routines that the previous matched extension is incomplete
and that further input should be allowed before matching can be considered
to be complete. Can be used within a pattern match when certain criteria warrants
a longer match.</para>
</description>
</application>
<application name="NoOp" language="en_US">
<synopsis>
Do Nothing (No Operation).
</synopsis>
<syntax>
<parameter name="text">
<para>Any text provided can be viewed at the Asterisk CLI.</para>
</parameter>
</syntax>
<description>
<para>This application does nothing. However, it is useful for debugging purposes.</para>
<para>This method can be used to see the evaluations of variables or functions without having any effect.</para>
</description>
<see-also>
<ref type="application">Verbose</ref>
<ref type="application">Log</ref>
</see-also>
</application>
<application name="Proceeding" language="en_US">
<synopsis>
Indicate proceeding.
</synopsis>
<syntax />
<description>
<para>This application will request that a proceeding message be provided to the calling channel.</para>
</description>
</application>
<application name="Progress" language="en_US">
<synopsis>
Indicate progress.
</synopsis>
<syntax />
<description>
<para>This application will request that in-band progress information be provided to the calling channel.</para>
</description>
<see-also>
<ref type="application">Busy</ref>
<ref type="application">Congestion</ref>
<ref type="application">Ringing</ref>
<ref type="application">Playtones</ref>
</see-also>
</application>
<application name="RaiseException" language="en_US">
<synopsis>
Handle an exceptional condition.
</synopsis>
<syntax>
<parameter name="reason" required="true" />
</syntax>
<description>
<para>This application will jump to the <literal>e</literal> extension in the current context, setting the
dialplan function EXCEPTION(). If the <literal>e</literal> extension does not exist, the call will hangup.</para>
</description>
<see-also>
<ref type="function">Exception</ref>
</see-also>
</application>
<application name="ResetCDR" language="en_US">
<synopsis>
Resets the Call Data Record.
</synopsis>
<syntax>
<parameter name="options">
<optionlist>
<option name="w">
<para>Store the current CDR record before resetting it.</para>
</option>
<option name="a">
<para>Store any stacked records.</para>
</option>
<option name="v">
<para>Save CDR variables.</para>
</option>
<option name="e">
<para>Enable CDR only (negate effects of NoCDR).</para>
</option>
</optionlist>
</parameter>
</syntax>
<description>
<para>This application causes the Call Data Record to be reset.</para>
</description>
<see-also>
<ref type="application">ForkCDR</ref>
<ref type="application">NoCDR</ref>
</see-also>
</application>
<application name="Ringing" language="en_US">
<synopsis>
Indicate ringing tone.
</synopsis>
<syntax />
<description>
<para>This application will request that the channel indicate a ringing tone to the user.</para>
</description>
<see-also>
<ref type="application">Busy</ref>
<ref type="application">Congestion</ref>
<ref type="application">Progress</ref>
<ref type="application">Playtones</ref>
</see-also>
</application>
<application name="SayAlpha" language="en_US">
<synopsis>
Say Alpha.
</synopsis>
<syntax>
<parameter name="string" required="true" />
</syntax>
<description>
<para>This application will play the sounds that correspond to the letters of the
given <replaceable>string</replaceable>.</para>
</description>
<see-also>
<ref type="application">SayDigits</ref>
<ref type="application">SayNumber</ref>
<ref type="application">SayPhonetic</ref>
<ref type="function">CHANNEL</ref>
</see-also>
</application>
<application name="SayDigits" language="en_US">
<synopsis>
Say Digits.
</synopsis>
<syntax>
<parameter name="digits" required="true" />
</syntax>
<description>
<para>This application will play the sounds that correspond to the digits of
the given number. This will use the language that is currently set for the channel.</para>
</description>
<see-also>
<ref type="application">SayAlpha</ref>
<ref type="application">SayNumber</ref>
<ref type="application">SayPhonetic</ref>
<ref type="function">CHANNEL</ref>
</see-also>
</application>
<application name="SayNumber" language="en_US">
<synopsis>
Say Number.
</synopsis>
<syntax>
<parameter name="digits" required="true" />
<parameter name="gender" />
</syntax>
<description>
<para>This application will play the sounds that correspond to the given <replaceable>digits</replaceable>.
Optionally, a <replaceable>gender</replaceable> may be specified. This will use the language that is currently
set for the channel. See the CHANNEL() function for more information on setting the language for the channel.</para>
</description>
<see-also>
<ref type="application">SayAlpha</ref>
<ref type="application">SayDigits</ref>
<ref type="application">SayPhonetic</ref>
<ref type="function">CHANNEL</ref>
</see-also>
</application>
<application name="SayPhonetic" language="en_US">
<synopsis>
Say Phonetic.
</synopsis>
<syntax>
<parameter name="string" required="true" />
</syntax>
<description>
<para>This application will play the sounds from the phonetic alphabet that correspond to the
letters in the given <replaceable>string</replaceable>.</para>
</description>
<see-also>
<ref type="application">SayAlpha</ref>
<ref type="application">SayDigits</ref>
<ref type="application">SayNumber</ref>
</see-also>
</application>
<application name="Set" language="en_US">
<synopsis>
Set channel variable or function value.
</synopsis>
<syntax argsep="=">
<parameter name="name" required="true" />
<parameter name="value" required="true" />
</syntax>
<description>
<para>This function can be used to set the value of channel variables or dialplan functions.
When setting variables, if the variable name is prefixed with <literal>_</literal>,
the variable will be inherited into channels created from the current channel.
If the variable name is prefixed with <literal>__</literal>, the variable will be
inherited into channels created from the current channel and all children channels.</para>
<note><para>If (and only if), in <filename>/etc/asterisk/asterisk.conf</filename>, you have
a <literal>[compat]</literal> category, and you have <literal>app_set = 1.4</literal> under that, then
the behavior of this app changes, and strips surrounding quotes from the right hand side as
it did previously in 1.4.
The advantages of not stripping out quoting, and not caring about the separator characters (comma and vertical bar)
were sufficient to make these changes in 1.6. Confusion about how many backslashes would be needed to properly
protect separators and quotes in various database access strings has been greatly
reduced by these changes.</para></note>
</description>
<see-also>
<ref type="application">MSet</ref>
<ref type="function">GLOBAL</ref>
<ref type="function">SET</ref>
<ref type="function">ENV</ref>
</see-also>
</application>
<application name="MSet" language="en_US">
<synopsis>
Set channel variable(s) or function value(s).
</synopsis>
<syntax>
<parameter name="set1" required="true" argsep="=">
<argument name="name1" required="true" />
<argument name="value1" required="true" />
</parameter>
<parameter name="set2" multiple="true" argsep="=">
<argument name="name2" required="true" />
<argument name="value2" required="true" />
</parameter>
</syntax>
<description>
<para>This function can be used to set the value of channel variables or dialplan functions.
When setting variables, if the variable name is prefixed with <literal>_</literal>,
the variable will be inherited into channels created from the current channel
If the variable name is prefixed with <literal>__</literal>, the variable will be
inherited into channels created from the current channel and all children channels.
MSet behaves in a similar fashion to the way Set worked in 1.2/1.4 and is thus
prone to doing things that you may not expect. For example, it strips surrounding
double-quotes from the right-hand side (value). If you need to put a separator
character (comma or vert-bar), you will need to escape them by inserting a backslash
before them. Avoid its use if possible.</para>
</description>
<see-also>
<ref type="application">Set</ref>
</see-also>
</application>
<application name="SetAMAFlags" language="en_US">
<synopsis>
Set the AMA Flags.
</synopsis>
<syntax>
<parameter name="flag" />
</syntax>
<description>
<para>This application will set the channel's AMA Flags for billing purposes.</para>
</description>
<see-also>
<ref type="function">CDR</ref>
</see-also>
</application>
<application name="Wait" language="en_US">
<synopsis>
Waits for some time.
</synopsis>
<syntax>
<parameter name="seconds" required="true">
<para>Can be passed with fractions of a second. For example, <literal>1.5</literal> will ask the
application to wait for 1.5 seconds.</para>
</parameter>
</syntax>
<description>
<para>This application waits for a specified number of <replaceable>seconds</replaceable>.</para>
</description>
</application>
<application name="WaitExten" language="en_US">
<synopsis>
Waits for an extension to be entered.
</synopsis>
<syntax>
<parameter name="seconds">
<para>Can be passed with fractions of a second. For example, <literal>1.5</literal> will ask the
application to wait for 1.5 seconds.</para>
</parameter>
<parameter name="options">
<optionlist>
<option name="m">
<para>Provide music on hold to the caller while waiting for an extension.</para>
<argument name="x">
<para>Specify the class for music on hold. <emphasis>CHANNEL(musicclass) will
be used instead if set</emphasis></para>
</argument>
</option>
</optionlist>
</parameter>
</syntax>
<description>
<para>This application waits for the user to enter a new extension for a specified number
of <replaceable>seconds</replaceable>.</para>
<xi:include xpointer="xpointer(/docs/application[@name='Macro']/description/warning[2])" />
</description>
<see-also>
<ref type="application">Background</ref>
<ref type="function">TIMEOUT</ref>
</see-also>
</application>
<function name="EXCEPTION" language="en_US">
<synopsis>
Retrieve the details of the current dialplan exception.
</synopsis>
<syntax>
<parameter name="field" required="true">
<para>The following fields are available for retrieval:</para>
<enumlist>
<enum name="reason">
<para>INVALID, ERROR, RESPONSETIMEOUT, ABSOLUTETIMEOUT, or custom
value set by the RaiseException() application</para>
</enum>
<enum name="context">
<para>The context executing when the exception occurred.</para>
</enum>
<enum name="exten">
<para>The extension executing when the exception occurred.</para>
</enum>
<enum name="priority">
<para>The numeric priority executing when the exception occurred.</para>
</enum>
</enumlist>
</parameter>
</syntax>
<description>
<para>Retrieve the details (specified <replaceable>field</replaceable>) of the current dialplan exception.</para>
</description>
<see-also>
<ref type="application">RaiseException</ref>
</see-also>
</function>
<function name="TESTTIME" language="en_US">
<synopsis>
Sets a time to be used with the channel to test logical conditions.
</synopsis>
<syntax>
<parameter name="date" required="true" argsep=" ">
<para>Date in ISO 8601 format</para>
</parameter>
<parameter name="time" required="true" argsep=" ">
<para>Time in HH:MM:SS format (24-hour time)</para>
</parameter>
<parameter name="zone" required="false">
<para>Timezone name</para>
</parameter>
</syntax>
<description>
<para>To test dialplan timing conditions at times other than the current time, use
this function to set an alternate date and time. For example, you may wish to evaluate
whether a location will correctly identify to callers that the area is closed on Christmas
Day, when Christmas would otherwise fall on a day when the office is normally open.</para>
</description>
<see-also>
<ref type="application">GotoIfTime</ref>
</see-also>
</function>
<manager name="ShowDialPlan" language="en_US">
<synopsis>
Show dialplan contexts and extensions
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Extension">
<para>Show a specific extension.</para>
</parameter>
<parameter name="Context">
<para>Show a specific context.</para>
</parameter>
</syntax>
<description>
<para>Show dialplan contexts and extensions. Be aware that showing the full dialplan
may take a lot of capacity.</para>
</description>
</manager>
***/
#ifdef LOW_MEMORY
#define EXT_DATA_SIZE 256
#else
#define EXT_DATA_SIZE 8192
#endif
#define SWITCH_DATA_LENGTH 256
#define VAR_BUF_SIZE 4096
#define VAR_NORMAL 1
#define VAR_SOFTTRAN 2
#define VAR_HARDTRAN 3
#define BACKGROUND_SKIP (1 << 0)
#define BACKGROUND_NOANSWER (1 << 1)
#define BACKGROUND_MATCHEXTEN (1 << 2)
#define BACKGROUND_PLAYBACK (1 << 3)
AST_APP_OPTIONS(background_opts, {
AST_APP_OPTION('s', BACKGROUND_SKIP),
AST_APP_OPTION('n', BACKGROUND_NOANSWER),
AST_APP_OPTION('m', BACKGROUND_MATCHEXTEN),
AST_APP_OPTION('p', BACKGROUND_PLAYBACK),
});
#define WAITEXTEN_MOH (1 << 0)
#define WAITEXTEN_DIALTONE (1 << 1)
AST_APP_OPTIONS(waitexten_opts, {
AST_APP_OPTION_ARG('m', WAITEXTEN_MOH, 0),
AST_APP_OPTION_ARG('d', WAITEXTEN_DIALTONE, 0),
});
struct ast_context;
struct ast_app;
static struct ast_taskprocessor *device_state_tps;
AST_THREADSTORAGE(switch_data);
AST_THREADSTORAGE(extensionstate_buf);
/*!
* \brief A thread local indicating whether the current thread can run
* 'dangerous' dialplan functions.
*/
AST_THREADSTORAGE(thread_inhibit_escalations_tl);
/*!
* \brief Set to true (non-zero) to globally allow all dangerous dialplan
* functions to run.
*/
static int live_dangerously;
/*!
\brief ast_exten: An extension
The dialplan is saved as a linked list with each context
having it's own linked list of extensions - one item per
priority.
*/
struct ast_exten {
char *exten; /*!< Extension name */
int matchcid; /*!< Match caller id ? */
const char *cidmatch; /*!< Caller id to match for this extension */
int priority; /*!< Priority */
const char *label; /*!< Label */
struct ast_context *parent; /*!< The context this extension belongs to */
const char *app; /*!< Application to execute */
struct ast_app *cached_app; /*!< Cached location of application */
void *data; /*!< Data to use (arguments) */
void (*datad)(void *); /*!< Data destructor */
struct ast_exten *peer; /*!< Next higher priority with our extension */
struct ast_hashtab *peer_table; /*!< Priorities list in hashtab form -- only on the head of the peer list */
struct ast_hashtab *peer_label_table; /*!< labeled priorities in the peers -- only on the head of the peer list */
const char *registrar; /*!< Registrar */
struct ast_exten *next; /*!< Extension with a greater ID */
char stuff[0];
};
/*! \brief ast_include: include= support in extensions.conf */
struct ast_include {
const char *name;
const char *rname; /*!< Context to include */
const char *registrar; /*!< Registrar */
int hastime; /*!< If time construct exists */
struct ast_timing timing; /*!< time construct */
struct ast_include *next; /*!< Link them together */
char stuff[0];
};
/*! \brief ast_sw: Switch statement in extensions.conf */
struct ast_sw {
char *name;
const char *registrar; /*!< Registrar */
char *data; /*!< Data load */
int eval;
AST_LIST_ENTRY(ast_sw) list;
char stuff[0];
};
/*! \brief ast_ignorepat: Ignore patterns in dial plan */
struct ast_ignorepat {
const char *registrar;
struct ast_ignorepat *next;
const char pattern[0];
};
/*! \brief match_char: forms a syntax tree for quick matching of extension patterns */
struct match_char
{
int is_pattern; /* the pattern started with '_' */
int deleted; /* if this is set, then... don't return it */
int specificity; /* simply the strlen of x, or 10 for X, 9 for Z, and 8 for N; and '.' and '!' will add 11 ? */
struct match_char *alt_char;
struct match_char *next_char;
struct ast_exten *exten; /* attached to last char of a pattern for exten */
char x[1]; /* the pattern itself-- matches a single char */
};
struct scoreboard /* make sure all fields are 0 before calling new_find_extension */
{
int total_specificity;
int total_length;
char last_char; /* set to ! or . if they are the end of the pattern */
int canmatch; /* if the string to match was just too short */
struct match_char *node;
struct ast_exten *canmatch_exten;
struct ast_exten *exten;
};
/*! \brief ast_context: An extension context */
struct ast_context {
ast_rwlock_t lock; /*!< A lock to prevent multiple threads from clobbering the context */
struct ast_exten *root; /*!< The root of the list of extensions */
struct ast_hashtab *root_table; /*!< For exact matches on the extensions in the pattern tree, and for traversals of the pattern_tree */
struct match_char *pattern_tree; /*!< A tree to speed up extension pattern matching */
struct ast_context *next; /*!< Link them together */
struct ast_include *includes; /*!< Include other contexts */
struct ast_ignorepat *ignorepats; /*!< Patterns for which to continue playing dialtone */
char *registrar; /*!< Registrar -- make sure you malloc this, as the registrar may have to survive module unloads */
int refcount; /*!< each module that would have created this context should inc/dec this as appropriate */
AST_LIST_HEAD_NOLOCK(, ast_sw) alts; /*!< Alternative switches */
ast_mutex_t macrolock; /*!< A lock to implement "exclusive" macros - held whilst a call is executing in the macro */
char name[0]; /*!< Name of the context */
};
/*! \brief ast_app: A registered application */
struct ast_app {
int (*execute)(struct ast_channel *chan, const char *data);
AST_DECLARE_STRING_FIELDS(
AST_STRING_FIELD(synopsis); /*!< Synopsis text for 'show applications' */
AST_STRING_FIELD(description); /*!< Description (help text) for 'show application <name>' */
AST_STRING_FIELD(syntax); /*!< Syntax text for 'core show applications' */
AST_STRING_FIELD(arguments); /*!< Arguments description */
AST_STRING_FIELD(seealso); /*!< See also */
);
#ifdef AST_XML_DOCS
enum ast_doc_src docsrc; /*!< Where the documentation come from. */
#endif
AST_RWLIST_ENTRY(ast_app) list; /*!< Next app in list */
struct ast_module *module; /*!< Module this app belongs to */
char name[0]; /*!< Name of the application */
};
/*! \brief ast_state_cb: An extension state notify register item */
struct ast_state_cb {
/*! Watcher ID returned when registered. */
int id;
/*! Arbitrary data passed for callbacks. */
void *data;
/*! Callback when state changes. */
ast_state_cb_type change_cb;
/*! Callback when destroyed so any resources given by the registerer can be freed. */
ast_state_cb_destroy_type destroy_cb;
/*! \note Only used by ast_merge_contexts_and_delete */
AST_LIST_ENTRY(ast_state_cb) entry;
};
/*!
* \brief Structure for dial plan hints
*
* \note Hints are pointers from an extension in the dialplan to
* one or more devices (tech/name)
*
* See \ref AstExtState
*/
struct ast_hint {
/*!
* \brief Hint extension
*
* \note
* Will never be NULL while the hint is in the hints container.
*/
struct ast_exten *exten;
struct ao2_container *callbacks; /*!< Callback container for this extension */
int laststate; /*!< Last known state */
char context_name[AST_MAX_CONTEXT];/*!< Context of destroyed hint extension. */
char exten_name[AST_MAX_EXTENSION];/*!< Extension of destroyed hint extension. */
};
/* --- Hash tables of various objects --------*/
#ifdef LOW_MEMORY
#define HASH_EXTENHINT_SIZE 17
#else
#define HASH_EXTENHINT_SIZE 563
#endif
static const struct cfextension_states {
int extension_state;
const char * const text;
} extension_states[] = {
{ AST_EXTENSION_NOT_INUSE, "Idle" },
{ AST_EXTENSION_INUSE, "InUse" },
{ AST_EXTENSION_BUSY, "Busy" },
{ AST_EXTENSION_UNAVAILABLE, "Unavailable" },
{ AST_EXTENSION_RINGING, "Ringing" },
{ AST_EXTENSION_INUSE | AST_EXTENSION_RINGING, "InUse&Ringing" },
{ AST_EXTENSION_ONHOLD, "Hold" },
{ AST_EXTENSION_INUSE | AST_EXTENSION_ONHOLD, "InUse&Hold" }
};
struct statechange {
AST_LIST_ENTRY(statechange) entry;
char dev[0];
};
struct pbx_exception {
AST_DECLARE_STRING_FIELDS(
AST_STRING_FIELD(context); /*!< Context associated with this exception */
AST_STRING_FIELD(exten); /*!< Exten associated with this exception */
AST_STRING_FIELD(reason); /*!< The exception reason */
);
int priority; /*!< Priority associated with this exception */
};
static int pbx_builtin_answer(struct ast_channel *, const char *);
static int pbx_builtin_goto(struct ast_channel *, const char *);
static int pbx_builtin_hangup(struct ast_channel *, const char *);
static int pbx_builtin_background(struct ast_channel *, const char *);
static int pbx_builtin_wait(struct ast_channel *, const char *);
static int pbx_builtin_waitexten(struct ast_channel *, const char *);
static int pbx_builtin_incomplete(struct ast_channel *, const char *);
static int pbx_builtin_resetcdr(struct ast_channel *, const char *);
static int pbx_builtin_setamaflags(struct ast_channel *, const char *);
static int pbx_builtin_ringing(struct ast_channel *, const char *);
static int pbx_builtin_proceeding(struct ast_channel *, const char *);
static int pbx_builtin_progress(struct ast_channel *, const char *);
static int pbx_builtin_congestion(struct ast_channel *, const char *);
static int pbx_builtin_busy(struct ast_channel *, const char *);
static int pbx_builtin_noop(struct ast_channel *, const char *);
static int pbx_builtin_gotoif(struct ast_channel *, const char *);
static int pbx_builtin_gotoiftime(struct ast_channel *, const char *);
static int pbx_builtin_execiftime(struct ast_channel *, const char *);
static int pbx_builtin_saynumber(struct ast_channel *, const char *);
static int pbx_builtin_saydigits(struct ast_channel *, const char *);
static int pbx_builtin_saycharacters(struct ast_channel *, const char *);
static int pbx_builtin_sayphonetic(struct ast_channel *, const char *);
static int matchcid(const char *cidpattern, const char *callerid);
#ifdef NEED_DEBUG
static void log_match_char_tree(struct match_char *node, char *prefix); /* for use anywhere */
#endif
static int pbx_builtin_importvar(struct ast_channel *, const char *);
static void set_ext_pri(struct ast_channel *c, const char *exten, int pri);
static void new_find_extension(const char *str, struct scoreboard *score,
struct match_char *tree, int length, int spec, const char *callerid,
const char *label, enum ext_match_t action);
static struct match_char *already_in_tree(struct match_char *current, char *pat, int is_pattern);
static struct match_char *add_exten_to_pattern_tree(struct ast_context *con,
struct ast_exten *e1, int findonly);
static void create_match_char_tree(struct ast_context *con);
static struct ast_exten *get_canmatch_exten(struct match_char *node);
static void destroy_pattern_tree(struct match_char *pattern_tree);
static int hashtab_compare_extens(const void *ha_a, const void *ah_b);
static int hashtab_compare_exten_numbers(const void *ah_a, const void *ah_b);
static int hashtab_compare_exten_labels(const void *ah_a, const void *ah_b);
static unsigned int hashtab_hash_extens(const void *obj);
static unsigned int hashtab_hash_priority(const void *obj);
static unsigned int hashtab_hash_labels(const void *obj);
static void __ast_internal_context_destroy( struct ast_context *con);
static int ast_add_extension_nolock(const char *context, int replace, const char *extension,
int priority, const char *label, const char *callerid,
const char *application, void *data, void (*datad)(void *), const char *registrar);
static int ast_add_extension2_lockopt(struct ast_context *con,
int replace, const char *extension, int priority, const char *label, const char *callerid,
const char *application, void *data, void (*datad)(void *),
const char *registrar, int lock_context);
static struct ast_context *find_context_locked(const char *context);
static struct ast_context *find_context(const char *context);
/*!
* \internal
* \brief Character array comparison function for qsort.
*
* \param a Left side object.
* \param b Right side object.
*
* \retval <0 if a < b
* \retval =0 if a = b
* \retval >0 if a > b
*/
static int compare_char(const void *a, const void *b)
{
const unsigned char *ac = a;
const unsigned char *bc = b;
return *ac - *bc;
}
/* labels, contexts are case sensitive priority numbers are ints */
int ast_hashtab_compare_contexts(const void *ah_a, const void *ah_b)
{
const struct ast_context *ac = ah_a;
const struct ast_context *bc = ah_b;
if (!ac || !bc) /* safety valve, but it might prevent a crash you'd rather have happen */
return 1;
/* assume context names are registered in a string table! */
return strcmp(ac->name, bc->name);
}
static int hashtab_compare_extens(const void *ah_a, const void *ah_b)
{
const struct ast_exten *ac = ah_a;
const struct ast_exten *bc = ah_b;
int x = strcmp(ac->exten, bc->exten);
if (x) { /* if exten names are diff, then return */
return x;
}
/* but if they are the same, do the cidmatch values match? */
if (ac->matchcid && bc->matchcid) {
return strcmp(ac->cidmatch,bc->cidmatch);
} else if (!ac->matchcid && !bc->matchcid) {
return 0; /* if there's no matchcid on either side, then this is a match */
} else {
return 1; /* if there's matchcid on one but not the other, they are different */
}
}
static int hashtab_compare_exten_numbers(const void *ah_a, const void *ah_b)
{
const struct ast_exten *ac = ah_a;
const struct ast_exten *bc = ah_b;
return ac->priority != bc->priority;
}
static int hashtab_compare_exten_labels(const void *ah_a, const void *ah_b)
{
const struct ast_exten *ac = ah_a;
const struct ast_exten *bc = ah_b;
return strcmp(S_OR(ac->label, ""), S_OR(bc->label, ""));
}
unsigned int ast_hashtab_hash_contexts(const void *obj)
{
const struct ast_context *ac = obj;
return ast_hashtab_hash_string(ac->name);
}
static unsigned int hashtab_hash_extens(const void *obj)
{
const struct ast_exten *ac = obj;
unsigned int x = ast_hashtab_hash_string(ac->exten);
unsigned int y = 0;
if (ac->matchcid)
y = ast_hashtab_hash_string(ac->cidmatch);
return x+y;
}
static unsigned int hashtab_hash_priority(const void *obj)
{
const struct ast_exten *ac = obj;
return ast_hashtab_hash_int(ac->priority);
}
static unsigned int hashtab_hash_labels(const void *obj)
{
const struct ast_exten *ac = obj;
return ast_hashtab_hash_string(S_OR(ac->label, ""));
}
AST_RWLOCK_DEFINE_STATIC(globalslock);
static struct varshead globals = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
static int autofallthrough = 1;
static int extenpatternmatchnew = 0;
static char *overrideswitch = NULL;
/*! \brief Subscription for device state change events */
static struct ast_event_sub *device_state_sub;
AST_MUTEX_DEFINE_STATIC(maxcalllock);
static int countcalls;
static int totalcalls;
static AST_RWLIST_HEAD_STATIC(acf_root, ast_custom_function);
/*!
* \brief Extra information for an \ref ast_custom_function holding privilege
* escalation information. Kept in a separate structure for ABI compatibility.
*/
struct ast_custom_escalating_function {
AST_RWLIST_ENTRY(ast_custom_escalating_function) list;
const struct ast_custom_function *acf;
unsigned int read_escalates:1;
unsigned int write_escalates:1;
};
static AST_RWLIST_HEAD_STATIC(escalation_root, ast_custom_escalating_function);
/*! \brief Declaration of builtin applications */
static struct pbx_builtin {
char name[AST_MAX_APP];
int (*execute)(struct ast_channel *chan, const char *data);
} builtins[] =
{
/* These applications are built into the PBX core and do not
need separate modules */
{ "Answer", pbx_builtin_answer },
{ "BackGround", pbx_builtin_background },
{ "Busy", pbx_builtin_busy },
{ "Congestion", pbx_builtin_congestion },
{ "ExecIfTime", pbx_builtin_execiftime },
{ "Goto", pbx_builtin_goto },
{ "GotoIf", pbx_builtin_gotoif },
{ "GotoIfTime", pbx_builtin_gotoiftime },
{ "ImportVar", pbx_builtin_importvar },
{ "Hangup", pbx_builtin_hangup },
{ "Incomplete", pbx_builtin_incomplete },
{ "NoOp", pbx_builtin_noop },
{ "Proceeding", pbx_builtin_proceeding },
{ "Progress", pbx_builtin_progress },
{ "RaiseException", pbx_builtin_raise_exception },
{ "ResetCDR", pbx_builtin_resetcdr },
{ "Ringing", pbx_builtin_ringing },
{ "SayAlpha", pbx_builtin_saycharacters },
{ "SayDigits", pbx_builtin_saydigits },
{ "SayNumber", pbx_builtin_saynumber },
{ "SayPhonetic", pbx_builtin_sayphonetic },
{ "Set", pbx_builtin_setvar },
{ "MSet", pbx_builtin_setvar_multiple },
{ "SetAMAFlags", pbx_builtin_setamaflags },
{ "Wait", pbx_builtin_wait },
{ "WaitExten", pbx_builtin_waitexten }
};
static struct ast_context *contexts;
static struct ast_hashtab *contexts_table = NULL;
/*!
* \brief Lock for the ast_context list
* \note
* This lock MUST be recursive, or a deadlock on reload may result. See
* https://issues.asterisk.org/view.php?id=17643
*/
AST_MUTEX_DEFINE_STATIC(conlock);
/*!
* \brief Lock to hold off restructuring of hints by ast_merge_contexts_and_delete.
*/
AST_MUTEX_DEFINE_STATIC(context_merge_lock);
static AST_RWLIST_HEAD_STATIC(apps, ast_app);
static AST_RWLIST_HEAD_STATIC(switches, ast_switch);
static int stateid = 1;
/*!
* \note When holding this container's lock, do _not_ do
* anything that will cause conlock to be taken, unless you
* _already_ hold it. The ast_merge_contexts_and_delete function
* will take the locks in conlock/hints order, so any other
* paths that require both locks must also take them in that
* order.
*/
static struct ao2_container *hints;
static struct ao2_container *statecbs;
#ifdef CONTEXT_DEBUG
/* these routines are provided for doing run-time checks
on the extension structures, in case you are having
problems, this routine might help you localize where
the problem is occurring. It's kinda like a debug memory
allocator's arena checker... It'll eat up your cpu cycles!
but you'll see, if you call it in the right places,
right where your problems began...
*/
/* you can break on the check_contexts_trouble()
routine in your debugger to stop at the moment
there's a problem */
void check_contexts_trouble(void);
void check_contexts_trouble(void)
{
int x = 1;
x = 2;
}
int check_contexts(char *, int);
int check_contexts(char *file, int line )
{
struct ast_hashtab_iter *t1;
struct ast_context *c1, *c2;
int found = 0;
struct ast_exten *e1, *e2, *e3;
struct ast_exten ex;
/* try to find inconsistencies */
/* is every context in the context table in the context list and vice-versa ? */
if (!contexts_table) {
ast_log(LOG_NOTICE,"Called from: %s:%d: No contexts_table!\n", file, line);
usleep(500000);
}
t1 = ast_hashtab_start_traversal(contexts_table);
while( (c1 = ast_hashtab_next(t1))) {
for(c2=contexts;c2;c2=c2->next) {
if (!strcmp(c1->name, c2->name)) {
found = 1;
break;
}
}
if (!found) {
ast_log(LOG_NOTICE,"Called from: %s:%d: Could not find the %s context in the linked list\n", file, line, c1->name);
check_contexts_trouble();
}
}
ast_hashtab_end_traversal(t1);
for(c2=contexts;c2;c2=c2->next) {
c1 = find_context_locked(c2->name);
if (!c1) {
ast_log(LOG_NOTICE,"Called from: %s:%d: Could not find the %s context in the hashtab\n", file, line, c2->name);
check_contexts_trouble();
} else
ast_unlock_contexts();
}
/* loop thru all contexts, and verify the exten structure compares to the
hashtab structure */
for(c2=contexts;c2;c2=c2->next) {
c1 = find_context_locked(c2->name);
if (c1) {
ast_unlock_contexts();
/* is every entry in the root list also in the root_table? */
for(e1 = c1->root; e1; e1=e1->next)
{
char dummy_name[1024];
ex.exten = dummy_name;
ex.matchcid = e1->matchcid;
ex.cidmatch = e1->cidmatch;
ast_copy_string(dummy_name, e1->exten, sizeof(dummy_name));
e2 = ast_hashtab_lookup(c1->root_table, &ex);
if (!e2) {
if (e1->matchcid) {
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context records the exten %s (CID match: %s) but it is not in its root_table\n", file, line, c2->name, dummy_name, e1->cidmatch );
} else {
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context records the exten %s but it is not in its root_table\n", file, line, c2->name, dummy_name );
}
check_contexts_trouble();
}
}
/* is every entry in the root_table also in the root list? */
if (!c2->root_table) {
if (c2->root) {
ast_log(LOG_NOTICE,"Called from: %s:%d: No c2->root_table for context %s!\n", file, line, c2->name);
usleep(500000);
}
} else {
t1 = ast_hashtab_start_traversal(c2->root_table);
while( (e2 = ast_hashtab_next(t1)) ) {
for(e1=c2->root;e1;e1=e1->next) {
if (!strcmp(e1->exten, e2->exten)) {
found = 1;
break;
}
}
if (!found) {
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context records the exten %s but it is not in its root_table\n", file, line, c2->name, e2->exten);
check_contexts_trouble();
}
}
ast_hashtab_end_traversal(t1);
}
}
/* is every priority reflected in the peer_table at the head of the list? */
/* is every entry in the root list also in the root_table? */
/* are the per-extension peer_tables in the right place? */
for(e1 = c2->root; e1; e1 = e1->next) {
for(e2=e1;e2;e2=e2->peer) {
ex.priority = e2->priority;
if (e2 != e1 && e2->peer_table) {
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority has a peer_table entry, and shouldn't!\n", file, line, c2->name, e1->exten, e2->priority );
check_contexts_trouble();
}
if (e2 != e1 && e2->peer_label_table) {
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority has a peer_label_table entry, and shouldn't!\n", file, line, c2->name, e1->exten, e2->priority );
check_contexts_trouble();
}
if (e2 == e1 && !e2->peer_table){
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority doesn't have a peer_table!\n", file, line, c2->name, e1->exten, e2->priority );
check_contexts_trouble();
}
if (e2 == e1 && !e2->peer_label_table) {
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority doesn't have a peer_label_table!\n", file, line, c2->name, e1->exten, e2->priority );
check_contexts_trouble();
}
e3 = ast_hashtab_lookup(e1->peer_table, &ex);
if (!e3) {
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority is not reflected in the peer_table\n", file, line, c2->name, e1->exten, e2->priority );
check_contexts_trouble();
}
}
if (!e1->peer_table){
ast_log(LOG_NOTICE,"Called from: %s:%d: No e1->peer_table!\n", file, line);
usleep(500000);
}
/* is every entry in the peer_table also in the peer list? */
t1 = ast_hashtab_start_traversal(e1->peer_table);
while( (e2 = ast_hashtab_next(t1)) ) {
for(e3=e1;e3;e3=e3->peer) {
if (e3->priority == e2->priority) {
found = 1;
break;
}
}
if (!found) {
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority is not reflected in the peer list\n", file, line, c2->name, e1->exten, e2->priority );
check_contexts_trouble();
}
}
ast_hashtab_end_traversal(t1);
}
}
return 0;
}
#endif
/*
\note This function is special. It saves the stack so that no matter
how many times it is called, it returns to the same place */
int pbx_exec(struct ast_channel *c, /*!< Channel */
struct ast_app *app, /*!< Application */
const char *data) /*!< Data for execution */
{
int res;
struct ast_module_user *u = NULL;
const char *saved_c_appl;
const char *saved_c_data;
if (c->cdr && !ast_check_hangup(c))
ast_cdr_setapp(c->cdr, app->name, data);
/* save channel values */
saved_c_appl= c->appl;
saved_c_data= c->data;
c->appl = app->name;
c->data = data;
ast_cel_report_event(c, AST_CEL_APP_START, NULL, NULL, NULL);
if (app->module)
u = __ast_module_user_add(app->module, c);
if (strcasecmp(app->name, "system") && !ast_strlen_zero(data) &&
strchr(data, '|') && !strchr(data, ',') && !ast_opt_dont_warn) {
ast_log(LOG_WARNING, "The application delimiter is now the comma, not "
"the pipe. Did you forget to convert your dialplan? (%s(%s))\n",
app->name, (char *) data);
}
res = app->execute(c, S_OR(data, ""));
if (app->module && u)
__ast_module_user_remove(app->module, u);
ast_cel_report_event(c, AST_CEL_APP_END, NULL, NULL, NULL);
/* restore channel values */
c->appl = saved_c_appl;
c->data = saved_c_data;
return res;
}
/*! Go no deeper than this through includes (not counting loops) */
#define AST_PBX_MAX_STACK 128
/*! \brief Find application handle in linked list
*/
struct ast_app *pbx_findapp(const char *app)
{
struct ast_app *tmp;
AST_RWLIST_RDLOCK(&apps);
AST_RWLIST_TRAVERSE(&apps, tmp, list) {
if (!strcasecmp(tmp->name, app))
break;
}
AST_RWLIST_UNLOCK(&apps);
return tmp;
}
static struct ast_switch *pbx_findswitch(const char *sw)
{
struct ast_switch *asw;
AST_RWLIST_RDLOCK(&switches);
AST_RWLIST_TRAVERSE(&switches, asw, list) {
if (!strcasecmp(asw->name, sw))
break;
}
AST_RWLIST_UNLOCK(&switches);
return asw;
}
static inline int include_valid(struct ast_include *i)
{
if (!i->hastime)
return 1;
return ast_check_timing(&(i->timing));
}
static void pbx_destroy(struct ast_pbx *p)
{
ast_free(p);
}
/* form a tree that fully describes all the patterns in a context's extensions
* in this tree, a "node" represents an individual character or character set
* meant to match the corresponding character in a dial string. The tree
* consists of a series of match_char structs linked in a chain
* via the alt_char pointers. More than one pattern can share the same parts of the
* tree as other extensions with the same pattern to that point.
* My first attempt to duplicate the finding of the 'best' pattern was flawed in that
* I misunderstood the general algorithm. I thought that the 'best' pattern
* was the one with lowest total score. This was not true. Thus, if you have
* patterns "1XXXXX" and "X11111", you would be tempted to say that "X11111" is
* the "best" match because it has fewer X's, and is therefore more specific,
* but this is not how the old algorithm works. It sorts matching patterns
* in a similar collating sequence as sorting alphabetic strings, from left to
* right. Thus, "1XXXXX" comes before "X11111", and would be the "better" match,
* because "1" is more specific than "X".
* So, to accomodate this philosophy, I sort the tree branches along the alt_char
* line so they are lowest to highest in specificity numbers. This way, as soon
* as we encounter our first complete match, we automatically have the "best"
* match and can stop the traversal immediately. Same for CANMATCH/MATCHMORE.
* If anyone would like to resurrect the "wrong" pattern trie searching algorithm,
* they are welcome to revert pbx to before 1 Apr 2008.
* As an example, consider these 4 extensions:
* (a) NXXNXXXXXX
* (b) 307754XXXX
* (c) fax
* (d) NXXXXXXXXX
*
* In the above, between (a) and (d), (a) is a more specific pattern than (d), and would win over
* most numbers. For all numbers beginning with 307754, (b) should always win.
*
* These pattern should form a (sorted) tree that looks like this:
* { "3" } --next--> { "0" } --next--> { "7" } --next--> { "7" } --next--> { "5" } ... blah ... --> { "X" exten_match: (b) }
* |
* |alt
* |
* { "f" } --next--> { "a" } --next--> { "x" exten_match: (c) }
* { "N" } --next--> { "X" } --next--> { "X" } --next--> { "N" } --next--> { "X" } ... blah ... --> { "X" exten_match: (a) }
* | |
* | |alt
* |alt |
* | { "X" } --next--> { "X" } ... blah ... --> { "X" exten_match: (d) }
* |
* NULL
*
* In the above, I could easily turn "N" into "23456789", but I think that a quick "if( *z >= '2' && *z <= '9' )" might take
* fewer CPU cycles than a call to strchr("23456789",*z), where *z is the char to match...
*
* traversal is pretty simple: one routine merely traverses the alt list, and for each matching char in the pattern, it calls itself
* on the corresponding next pointer, incrementing also the pointer of the string to be matched, and passing the total specificity and length.
* We pass a pointer to a scoreboard down through, also.
* The scoreboard isn't as necessary to the revised algorithm, but I kept it as a handy way to return the matched extension.
* The first complete match ends the traversal, which should make this version of the pattern matcher faster
* the previous. The same goes for "CANMATCH" or "MATCHMORE"; the first such match ends the traversal. In both
* these cases, the reason we can stop immediately, is because the first pattern match found will be the "best"
* according to the sort criteria.
* Hope the limit on stack depth won't be a problem... this routine should
* be pretty lean as far a stack usage goes. Any non-match terminates the recursion down a branch.
*
* In the above example, with the number "3077549999" as the pattern, the traversor could match extensions a, b and d. All are
* of length 10; they have total specificities of 24580, 10246, and 25090, respectively, not that this matters
* at all. (b) wins purely because the first character "3" is much more specific (lower specificity) than "N". I have
* left the specificity totals in the code as an artifact; at some point, I will strip it out.
*
* Just how much time this algorithm might save over a plain linear traversal over all possible patterns is unknown,
* because it's a function of how many extensions are stored in a context. With thousands of extensions, the speedup
* can be very noticeable. The new matching algorithm can run several hundreds of times faster, if not a thousand or
* more times faster in extreme cases.
*
* MatchCID patterns are also supported, and stored in the tree just as the extension pattern is. Thus, you
* can have patterns in your CID field as well.
*
* */
static void update_scoreboard(struct scoreboard *board, int length, int spec, struct ast_exten *exten, char last, const char *callerid, int deleted, struct match_char *node)
{
/* if this extension is marked as deleted, then skip this -- if it never shows
on the scoreboard, it will never be found, nor will halt the traversal. */
if (deleted)
return;
board->total_specificity = spec;
board->total_length = length;
board->exten = exten;
board->last_char = last;
board->node = node;
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Scoreboarding (LONGER) %s, len=%d, score=%d\n", exten->exten, length, spec);
#endif
}
#ifdef NEED_DEBUG
static void log_match_char_tree(struct match_char *node, char *prefix)
{
char extenstr[40];
struct ast_str *my_prefix = ast_str_alloca(1024);
extenstr[0] = '\0';
if (node && node->exten)
snprintf(extenstr, sizeof(extenstr), "(%p)", node->exten);
if (strlen(node->x) > 1) {
ast_debug(1, "%s[%s]:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y':'N',
node->deleted? 'D':'-', node->specificity, node->exten? "EXTEN:":"",
node->exten ? node->exten->exten : "", extenstr);
} else {
ast_debug(1, "%s%s:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y':'N',
node->deleted? 'D':'-', node->specificity, node->exten? "EXTEN:":"",
node->exten ? node->exten->exten : "", extenstr);
}
ast_str_set(&my_prefix, 0, "%s+ ", prefix);
if (node->next_char)
log_match_char_tree(node->next_char, ast_str_buffer(my_prefix));
if (node->alt_char)
log_match_char_tree(node->alt_char, prefix);
}
#endif
static void cli_match_char_tree(struct match_char *node, char *prefix, int fd)
{
char extenstr[40];
struct ast_str *my_prefix = ast_str_alloca(1024);
extenstr[0] = '\0';
if (node && node->exten)
snprintf(extenstr, sizeof(extenstr), "(%p)", node->exten);
if (strlen(node->x) > 1) {
ast_cli(fd, "%s[%s]:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y' : 'N',
node->deleted ? 'D' : '-', node->specificity, node->exten? "EXTEN:" : "",
node->exten ? node->exten->exten : "", extenstr);
} else {
ast_cli(fd, "%s%s:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y' : 'N',
node->deleted ? 'D' : '-', node->specificity, node->exten? "EXTEN:" : "",
node->exten ? node->exten->exten : "", extenstr);
}
ast_str_set(&my_prefix, 0, "%s+ ", prefix);
if (node->next_char)
cli_match_char_tree(node->next_char, ast_str_buffer(my_prefix), fd);
if (node->alt_char)
cli_match_char_tree(node->alt_char, prefix, fd);
}
static struct ast_exten *get_canmatch_exten(struct match_char *node)
{
/* find the exten at the end of the rope */
struct match_char *node2 = node;
for (node2 = node; node2; node2 = node2->next_char) {
if (node2->exten) {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"CanMatch_exten returns exten %s(%p)\n", node2->exten->exten, node2->exten);
#endif
return node2->exten;
}
}
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"CanMatch_exten returns NULL, match_char=%s\n", node->x);
#endif
return 0;
}
static struct ast_exten *trie_find_next_match(struct match_char *node)
{
struct match_char *m3;
struct match_char *m4;
struct ast_exten *e3;
if (node && node->x[0] == '.' && !node->x[1]) { /* dot and ! will ALWAYS be next match in a matchmore */
return node->exten;
}
if (node && node->x[0] == '!' && !node->x[1]) {
return node->exten;
}
if (!node || !node->next_char) {
return NULL;
}
m3 = node->next_char;
if (m3->exten) {
return m3->exten;
}
for (m4 = m3->alt_char; m4; m4 = m4->alt_char) {
if (m4->exten) {
return m4->exten;
}
}
for (m4 = m3; m4; m4 = m4->alt_char) {
e3 = trie_find_next_match(m3);
if (e3) {
return e3;
}
}
return NULL;
}
#ifdef DEBUG_THIS
static char *action2str(enum ext_match_t action)
{
switch (action) {
case E_MATCH:
return "MATCH";
case E_CANMATCH:
return "CANMATCH";
case E_MATCHMORE:
return "MATCHMORE";
case E_FINDLABEL:
return "FINDLABEL";
case E_SPAWN:
return "SPAWN";
default:
return "?ACTION?";
}
}
#endif
static void new_find_extension(const char *str, struct scoreboard *score, struct match_char *tree, int length, int spec, const char *callerid, const char *label, enum ext_match_t action)
{
struct match_char *p; /* note minimal stack storage requirements */
struct ast_exten pattern = { .label = label };
#ifdef DEBUG_THIS
if (tree)
ast_log(LOG_NOTICE,"new_find_extension called with %s on (sub)tree %s action=%s\n", str, tree->x, action2str(action));
else
ast_log(LOG_NOTICE,"new_find_extension called with %s on (sub)tree NULL action=%s\n", str, action2str(action));
#endif
for (p = tree; p; p = p->alt_char) {
if (p->is_pattern) {
if (p->x[0] == 'N') {
if (p->x[1] == 0 && *str >= '2' && *str <= '9' ) {
#define NEW_MATCHER_CHK_MATCH \
if (p->exten && !(*(str + 1))) { /* if a shorter pattern matches along the way, might as well report it */ \
if (action == E_MATCH || action == E_SPAWN || action == E_FINDLABEL) { /* if in CANMATCH/MATCHMORE, don't let matches get in the way */ \
update_scoreboard(score, length + 1, spec + p->specificity, p->exten, 0, callerid, p->deleted, p); \
if (!p->deleted) { \
if (action == E_FINDLABEL) { \
if (ast_hashtab_lookup(score->exten->peer_label_table, &pattern)) { \
ast_debug(4, "Found label in preferred extension\n"); \
return; \
} \
} else { \
ast_debug(4, "returning an exact match-- first found-- %s\n", p->exten->exten); \
return; /* the first match, by definition, will be the best, because of the sorted tree */ \
} \
} \
} \
}
#define NEW_MATCHER_RECURSE \
if (p->next_char && (*(str + 1) || (p->next_char->x[0] == '/' && p->next_char->x[1] == 0) \
|| p->next_char->x[0] == '!')) { \
if (*(str + 1) || p->next_char->x[0] == '!') { \
new_find_extension(str + 1, score, p->next_char, length + 1, spec + p->specificity, callerid, label, action); \
if (score->exten) { \
ast_debug(4 ,"returning an exact match-- %s\n", score->exten->exten); \
return; /* the first match is all we need */ \
} \
} else { \
new_find_extension("/", score, p->next_char, length + 1, spec + p->specificity, callerid, label, action); \
if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) { \
ast_debug(4,"returning a (can/more) match--- %s\n", score->exten ? score->exten->exten : \
"NULL"); \
return; /* the first match is all we need */ \
} \
} \
} else if ((p->next_char || action == E_CANMATCH) && !*(str + 1)) { \
score->canmatch = 1; \
score->canmatch_exten = get_canmatch_exten(p); \
if (action == E_CANMATCH || action == E_MATCHMORE) { \
ast_debug(4, "returning a canmatch/matchmore--- str=%s\n", str); \
return; \
} \
}
NEW_MATCHER_CHK_MATCH;
NEW_MATCHER_RECURSE;
}
} else if (p->x[0] == 'Z') {
if (p->x[1] == 0 && *str >= '1' && *str <= '9' ) {
NEW_MATCHER_CHK_MATCH;
NEW_MATCHER_RECURSE;
}
} else if (p->x[0] == 'X') {
if (p->x[1] == 0 && *str >= '0' && *str <= '9' ) {
NEW_MATCHER_CHK_MATCH;
NEW_MATCHER_RECURSE;
}
} else if (p->x[0] == '.' && p->x[1] == 0) {
/* how many chars will the . match against? */
int i = 0;
const char *str2 = str;
while (*str2 && *str2 != '/') {
str2++;
i++;
}
if (p->exten && *str2 != '/') {
update_scoreboard(score, length + i, spec + (i * p->specificity), p->exten, '.', callerid, p->deleted, p);
if (score->exten) {
ast_debug(4,"return because scoreboard has a match with '/'--- %s\n", score->exten->exten);
return; /* the first match is all we need */
}
}
if (p->next_char && p->next_char->x[0] == '/' && p->next_char->x[1] == 0) {
new_find_extension("/", score, p->next_char, length + i, spec+(p->specificity*i), callerid, label, action);
if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {
ast_debug(4, "return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set--- %s\n", score->exten ? score->exten->exten : "NULL");
return; /* the first match is all we need */
}
}
} else if (p->x[0] == '!' && p->x[1] == 0) {
/* how many chars will the . match against? */
int i = 1;
const char *str2 = str;
while (*str2 && *str2 != '/') {
str2++;
i++;
}
if (p->exten && *str2 != '/') {
update_scoreboard(score, length + 1, spec + (p->specificity * i), p->exten, '!', callerid, p->deleted, p);
if (score->exten) {
ast_debug(4, "return because scoreboard has a '!' match--- %s\n", score->exten->exten);
return; /* the first match is all we need */
}
}
if (p->next_char && p->next_char->x[0] == '/' && p->next_char->x[1] == 0) {
new_find_extension("/", score, p->next_char, length + i, spec + (p->specificity * i), callerid, label, action);
if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {
ast_debug(4, "return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set with '/' and '!'--- %s\n", score->exten ? score->exten->exten : "NULL");
return; /* the first match is all we need */
}
}
} else if (p->x[0] == '/' && p->x[1] == 0) {
/* the pattern in the tree includes the cid match! */
if (p->next_char && callerid && *callerid) {
new_find_extension(callerid, score, p->next_char, length + 1, spec, callerid, label, action);
if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {
ast_debug(4, "return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set with '/'--- %s\n", score->exten ? score->exten->exten : "NULL");
return; /* the first match is all we need */
}
}
} else if (strchr(p->x, *str)) {
ast_debug(4, "Nothing strange about this match\n");
NEW_MATCHER_CHK_MATCH;
NEW_MATCHER_RECURSE;
}
} else if (strchr(p->x, *str)) {
ast_debug(4, "Nothing strange about this match\n");
NEW_MATCHER_CHK_MATCH;
NEW_MATCHER_RECURSE;
}
}
ast_debug(4, "return at end of func\n");
}
/* the algorithm for forming the extension pattern tree is also a bit simple; you
* traverse all the extensions in a context, and for each char of the extension,
* you see if it exists in the tree; if it doesn't, you add it at the appropriate
* spot. What more can I say? At the end of each exten, you cap it off by adding the
* address of the extension involved. Duplicate patterns will be complained about.
*
* Ideally, this would be done for each context after it is created and fully
* filled. It could be done as a finishing step after extensions.conf or .ael is
* loaded, or it could be done when the first search is encountered. It should only
* have to be done once, until the next unload or reload.
*
* I guess forming this pattern tree would be analogous to compiling a regex. Except
* that a regex only handles 1 pattern, really. This trie holds any number
* of patterns. Well, really, it **could** be considered a single pattern,
* where the "|" (or) operator is allowed, I guess, in a way, sort of...
*/
static struct match_char *already_in_tree(struct match_char *current, char *pat, int is_pattern)
{
struct match_char *t;
if (!current) {
return 0;
}
for (t = current; t; t = t->alt_char) {
if (is_pattern == t->is_pattern && !strcmp(pat, t->x)) {/* uh, we may want to sort exploded [] contents to make matching easy */
return t;
}
}
return 0;
}
/* The first arg is the location of the tree ptr, or the
address of the next_char ptr in the node, so we can mess
with it, if we need to insert at the beginning of the list */
static void insert_in_next_chars_alt_char_list(struct match_char **parent_ptr, struct match_char *node)
{
struct match_char *curr, *lcurr;
/* insert node into the tree at "current", so the alt_char list from current is
sorted in increasing value as you go to the leaves */
if (!(*parent_ptr)) {
*parent_ptr = node;
return;
}
if ((*parent_ptr)->specificity > node->specificity) {
/* insert at head */
node->alt_char = (*parent_ptr);
*parent_ptr = node;
return;
}
lcurr = *parent_ptr;
for (curr = (*parent_ptr)->alt_char; curr; curr = curr->alt_char) {
if (curr->specificity > node->specificity) {
node->alt_char = curr;
lcurr->alt_char = node;
break;
}
lcurr = curr;
}
if (!curr) {
lcurr->alt_char = node;
}
}
struct pattern_node {
/*! Pattern node specificity */
int specif;
/*! Pattern node match characters. */
char buf[256];
};
static struct match_char *add_pattern_node(struct ast_context *con, struct match_char *current, const struct pattern_node *pattern, int is_pattern, int already, struct match_char **nextcharptr)
{
struct match_char *m;
if (!(m = ast_calloc(1, sizeof(*m) + strlen(pattern->buf)))) {
return NULL;
}
/* strcpy is safe here since we know its size and have allocated
* just enough space for when we allocated m
*/
strcpy(m->x, pattern->buf);
/* the specificity scores are the same as used in the old
pattern matcher. */
m->is_pattern = is_pattern;
if (pattern->specif == 1 && is_pattern && pattern->buf[0] == 'N') {
m->specificity = 0x0832;
} else if (pattern->specif == 1 && is_pattern && pattern->buf[0] == 'Z') {
m->specificity = 0x0931;
} else if (pattern->specif == 1 && is_pattern && pattern->buf[0] == 'X') {
m->specificity = 0x0a30;
} else if (pattern->specif == 1 && is_pattern && pattern->buf[0] == '.') {
m->specificity = 0x18000;
} else if (pattern->specif == 1 && is_pattern && pattern->buf[0] == '!') {
m->specificity = 0x28000;
} else {
m->specificity = pattern->specif;
}
if (!con->pattern_tree) {
insert_in_next_chars_alt_char_list(&con->pattern_tree, m);
} else {
if (already) { /* switch to the new regime (traversing vs appending)*/
insert_in_next_chars_alt_char_list(nextcharptr, m);
} else {
insert_in_next_chars_alt_char_list(¤t->next_char, m);
}
}
return m;
}
/*!
* \internal
* \brief Extract the next exten pattern node.
*
* \param node Pattern node to fill.
* \param src Next source character to read.
* \param pattern TRUE if the exten is a pattern.
* \param extenbuf Original exten buffer to use in diagnostic messages.
*
* \retval Ptr to next extenbuf pos to read.
*/
static const char *get_pattern_node(struct pattern_node *node, const char *src, int pattern, const char *extenbuf)
{
#define INC_DST_OVERFLOW_CHECK \
do { \
if (dst - node->buf < sizeof(node->buf) - 1) { \
++dst; \
} else { \
overflow = 1; \
} \
} while (0)
node->specif = 0;
node->buf[0] = '\0';
while (*src) {
if (*src == '[' && pattern) {
char *dst = node->buf;
const char *src_next;
int length;
int overflow = 0;
/* get past the '[' */
++src;
for (;;) {
if (*src == '\\') {
/* Escaped character. */
++src;
if (*src == '[' || *src == '\\' || *src == '-' || *src == ']') {
*dst = *src++;
INC_DST_OVERFLOW_CHECK;
}
} else if (*src == '-') {
unsigned char first;
unsigned char last;
src_next = src;
first = *(src_next - 1);
last = *++src_next;
if (last == '\\') {
/* Escaped character. */
last = *++src_next;
}
/* Possible char range. */
if (node->buf[0] && last) {
/* Expand the char range. */
while (++first <= last) {
*dst = first;
INC_DST_OVERFLOW_CHECK;
}
src = src_next + 1;
} else {
/*
* There was no left or right char for the range.
* It is just a '-'.
*/
*dst = *src++;
INC_DST_OVERFLOW_CHECK;
}
} else if (*src == '\0') {
ast_log(LOG_WARNING,
"A matching ']' was not found for '[' in exten pattern '%s'\n",
extenbuf);
break;
} else if (*src == ']') {
++src;
break;
} else {
*dst = *src++;
INC_DST_OVERFLOW_CHECK;
}
}
/* null terminate the exploded range */
*dst = '\0';
if (overflow) {
ast_log(LOG_ERROR,
"Expanded character set too large to deal with in exten pattern '%s'. Ignoring character set.\n",
extenbuf);
node->buf[0] = '\0';
continue;
}
/* Sort the characters in character set. */
length = strlen(node->buf);
if (!length) {
ast_log(LOG_WARNING, "Empty character set in exten pattern '%s'. Ignoring.\n",
extenbuf);
node->buf[0] = '\0';
continue;
}
qsort(node->buf, length, 1, compare_char);
/* Remove duplicate characters from character set. */
dst = node->buf;
src_next = node->buf;
while (*src_next++) {
if (*dst != *src_next) {
*++dst = *src_next;
}
}
length = strlen(node->buf);
length <<= 8;
node->specif = length | (unsigned char) node->buf[0];
break;
} else if (*src == '-') {
/* Skip dashes in all extensions. */
++src;
} else {
if (*src == '\\') {
/*
* XXX The escape character here does not remove any special
* meaning to characters except the '[', '\\', and '-'
* characters since they are special only in this function.
*/
node->buf[0] = *++src;
if (!node->buf[0]) {
break;
}
} else {
node->buf[0] = *src;
if (pattern) {
/* make sure n,x,z patterns are canonicalized to N,X,Z */
if (node->buf[0] == 'n') {
node->buf[0] = 'N';
} else if (node->buf[0] == 'x') {
node->buf[0] = 'X';
} else if (node->buf[0] == 'z') {
node->buf[0] = 'Z';
}
}
}
node->buf[1] = '\0';
node->specif = 1;
++src;
break;
}
}
return src;
#undef INC_DST_OVERFLOW_CHECK
}
static struct match_char *add_exten_to_pattern_tree(struct ast_context *con, struct ast_exten *e1, int findonly)
{
struct match_char *m1 = NULL;
struct match_char *m2 = NULL;
struct match_char **m0;
const char *pos;
int already;
int pattern = 0;
int idx_cur;
int idx_next;
char extenbuf[512];
struct pattern_node pat_node[2];
if (e1->matchcid) {
if (sizeof(extenbuf) < strlen(e1->exten) + strlen(e1->cidmatch) + 2) {
ast_log(LOG_ERROR,
"The pattern %s/%s is too big to deal with: it will be ignored! Disaster!\n",
e1->exten, e1->cidmatch);
return NULL;
}
sprintf(extenbuf, "%s/%s", e1->exten, e1->cidmatch);/* Safe. We just checked. */
} else {
ast_copy_string(extenbuf, e1->exten, sizeof(extenbuf));
}
#ifdef NEED_DEBUG
ast_log(LOG_DEBUG, "Adding exten %s to tree\n", extenbuf);
#endif
m1 = con->pattern_tree; /* each pattern starts over at the root of the pattern tree */
m0 = &con->pattern_tree;
already = 1;
pos = extenbuf;
if (*pos == '_') {
pattern = 1;
++pos;
}
idx_cur = 0;
pos = get_pattern_node(&pat_node[idx_cur], pos, pattern, extenbuf);
for (; pat_node[idx_cur].buf[0]; idx_cur = idx_next) {
idx_next = (idx_cur + 1) % ARRAY_LEN(pat_node);
pos = get_pattern_node(&pat_node[idx_next], pos, pattern, extenbuf);
/* See about adding node to tree. */
m2 = NULL;
if (already && (m2 = already_in_tree(m1, pat_node[idx_cur].buf, pattern))
&& m2->next_char) {
if (!pat_node[idx_next].buf[0]) {
/*
* This is the end of the pattern, but not the end of the tree.
* Mark this node with the exten... a shorter pattern might win
* if the longer one doesn't match.
*/
if (findonly) {
return m2;
}
if (m2->exten) {
ast_log(LOG_WARNING, "Found duplicate exten. Had %s found %s\n",
m2->deleted ? "(deleted/invalid)" : m2->exten->exten, e1->exten);
}
m2->exten = e1;
m2->deleted = 0;
}
m1 = m2->next_char; /* m1 points to the node to compare against */
m0 = &m2->next_char; /* m0 points to the ptr that points to m1 */
} else { /* not already OR not m2 OR nor m2->next_char */
if (m2) {
if (findonly) {
return m2;
}
m1 = m2; /* while m0 stays the same */
} else {
if (findonly) {
return m1;
}
m1 = add_pattern_node(con, m1, &pat_node[idx_cur], pattern, already, m0);
if (!m1) { /* m1 is the node just added */
return NULL;
}
m0 = &m1->next_char;
}
if (!pat_node[idx_next].buf[0]) {
if (m2 && m2->exten) {
ast_log(LOG_WARNING, "Found duplicate exten. Had %s found %s\n",
m2->deleted ? "(deleted/invalid)" : m2->exten->exten, e1->exten);
}
m1->deleted = 0;
m1->exten = e1;
}
/* The 'already' variable is a mini-optimization designed to make it so that we
* don't have to call already_in_tree when we know it will return false.
*/
already = 0;
}
}
return m1;
}
static void create_match_char_tree(struct ast_context *con)
{
struct ast_hashtab_iter *t1;
struct ast_exten *e1;
#ifdef NEED_DEBUG
int biggest_bucket, resizes, numobjs, numbucks;
ast_log(LOG_DEBUG,"Creating Extension Trie for context %s(%p)\n", con->name, con);
ast_hashtab_get_stats(con->root_table, &biggest_bucket, &resizes, &numobjs, &numbucks);
ast_log(LOG_DEBUG,"This tree has %d objects in %d bucket lists, longest list=%d objects, and has resized %d times\n",
numobjs, numbucks, biggest_bucket, resizes);
#endif
t1 = ast_hashtab_start_traversal(con->root_table);
while ((e1 = ast_hashtab_next(t1))) {
if (e1->exten) {
add_exten_to_pattern_tree(con, e1, 0);
} else {
ast_log(LOG_ERROR, "Attempt to create extension with no extension name.\n");
}
}
ast_hashtab_end_traversal(t1);
}
static void destroy_pattern_tree(struct match_char *pattern_tree) /* pattern tree is a simple binary tree, sort of, so the proper way to destroy it is... recursively! */
{
/* destroy all the alternates */
if (pattern_tree->alt_char) {
destroy_pattern_tree(pattern_tree->alt_char);
pattern_tree->alt_char = 0;
}
/* destroy all the nexts */
if (pattern_tree->next_char) {
destroy_pattern_tree(pattern_tree->next_char);
pattern_tree->next_char = 0;
}
pattern_tree->exten = 0; /* never hurts to make sure there's no pointers laying around */
ast_free(pattern_tree);
}
/*
* Special characters used in patterns:
* '_' underscore is the leading character of a pattern.
* In other position it is treated as a regular char.
* . one or more of any character. Only allowed at the end of
* a pattern.
* ! zero or more of anything. Also impacts the result of CANMATCH
* and MATCHMORE. Only allowed at the end of a pattern.
* In the core routine, ! causes a match with a return code of 2.
* In turn, depending on the search mode: (XXX check if it is implemented)
* - E_MATCH retuns 1 (does match)
* - E_MATCHMORE returns 0 (no match)
* - E_CANMATCH returns 1 (does match)
*
* / should not appear as it is considered the separator of the CID info.
* XXX at the moment we may stop on this char.
*
* X Z N match ranges 0-9, 1-9, 2-9 respectively.
* [ denotes the start of a set of character. Everything inside
* is considered literally. We can have ranges a-d and individual
* characters. A '[' and '-' can be considered literally if they
* are just before ']'.
* XXX currently there is no way to specify ']' in a range, nor \ is
* considered specially.
*
* When we compare a pattern with a specific extension, all characters in the extension
* itself are considered literally.
* XXX do we want to consider space as a separator as well ?
* XXX do we want to consider the separators in non-patterns as well ?
*/
/*!
* \brief helper functions to sort extensions and patterns in the desired way,
* so that more specific patterns appear first.
*
* ext_cmp1 compares individual characters (or sets of), returning
* an int where bits 0-7 are the ASCII code of the first char in the set,
* while bit 8-15 are the cardinality of the set minus 1.
* This way more specific patterns (smaller cardinality) appear first.
* Wildcards have a special value, so that we can directly compare them to
* sets by subtracting the two values. In particular:
* 0x000xx one character, xx
* 0x0yyxx yy character set starting with xx
* 0x10000 '.' (one or more of anything)
* 0x20000 '!' (zero or more of anything)
* 0x30000 NUL (end of string)
* 0x40000 error in set.
* The pointer to the string is advanced according to needs.
* NOTES:
* 1. the empty set is equivalent to NUL.
* 2. given that a full set has always 0 as the first element,
* we could encode the special cases as 0xffXX where XX
* is 1, 2, 3, 4 as used above.
*/
static int ext_cmp1(const char **p, unsigned char *bitwise)
{
int c, cmin = 0xff, count = 0;
const char *end;
/* load value and advance pointer */
c = *(*p)++;
/* always return unless we have a set of chars */
switch (toupper(c)) {
default: /* ordinary character */
bitwise[c / 8] = 1 << (c % 8);
return 0x0100 | (c & 0xff);
case 'N': /* 2..9 */
bitwise[6] = 0xfc;
bitwise[7] = 0x03;
return 0x0800 | '2';
case 'X': /* 0..9 */
bitwise[6] = 0xff;
bitwise[7] = 0x03;
return 0x0A00 | '0';
case 'Z': /* 1..9 */
bitwise[6] = 0xfe;
bitwise[7] = 0x03;
return 0x0900 | '1';
case '.': /* wildcard */
return 0x18000;
case '!': /* earlymatch */
return 0x28000; /* less specific than NULL */
case '\0': /* empty string */
*p = NULL;
return 0x30000;
case '[': /* pattern */
break;
}
/* locate end of set */
end = strchr(*p, ']');
if (end == NULL) {
ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");
return 0x40000; /* XXX make this entry go last... */
}
for (; *p < end ; (*p)++) {
unsigned char c1, c2; /* first-last char in range */
c1 = (unsigned char)((*p)[0]);
if (*p + 2 < end && (*p)[1] == '-') { /* this is a range */
c2 = (unsigned char)((*p)[2]);
*p += 2; /* skip a total of 3 chars */
} else { /* individual character */
c2 = c1;
}
if (c1 < cmin) {
cmin = c1;
}
for (; c1 <= c2; c1++) {
unsigned char mask = 1 << (c1 % 8);
/*!\note If two patterns score the same, the one with the lowest
* ascii values will compare as coming first. */
/* Flag the character as included (used) and count it. */
if (!(bitwise[ c1 / 8 ] & mask)) {
bitwise[ c1 / 8 ] |= mask;
count += 0x100;
}
}
}
(*p)++;
return count == 0 ? 0x30000 : (count | cmin);
}
/*!
* \brief the full routine to compare extensions in rules.
*/
static int ext_cmp(const char *a, const char *b)
{
/* make sure non-patterns come first.
* If a is not a pattern, it either comes first or
* we do a more complex pattern comparison.
*/
int ret = 0;
if (a[0] != '_')
return (b[0] == '_') ? -1 : strcmp(a, b);
/* Now we know a is a pattern; if b is not, a comes first */
if (b[0] != '_')
return 1;
/* ok we need full pattern sorting routine.
* skip past the underscores */
++a; ++b;
do {
unsigned char bitwise[2][32] = { { 0, } };
ret = ext_cmp1(&a, bitwise[0]) - ext_cmp1(&b, bitwise[1]);
if (ret == 0) {
/* Are the classes different, even though they score the same? */
ret = memcmp(bitwise[0], bitwise[1], 32);
}
} while (!ret && a && b);
if (ret == 0) {
return 0;
} else {
return (ret > 0) ? 1 : -1;
}
}
int ast_extension_cmp(const char *a, const char *b)
{
return ext_cmp(a, b);
}
/*!
* \internal
* \brief used ast_extension_{match|close}
* mode is as follows:
* E_MATCH success only on exact match
* E_MATCHMORE success only on partial match (i.e. leftover digits in pattern)
* E_CANMATCH either of the above.
* \retval 0 on no-match
* \retval 1 on match
* \retval 2 on early match.
*/
static int _extension_match_core(const char *pattern, const char *data, enum ext_match_t mode)
{
mode &= E_MATCH_MASK; /* only consider the relevant bits */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"match core: pat: '%s', dat: '%s', mode=%d\n", pattern, data, (int)mode);
#endif
if ( (mode == E_MATCH) && (pattern[0] == '_') && (!strcasecmp(pattern,data)) ) { /* note: if this test is left out, then _x. will not match _x. !!! */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (1) - pattern matches pattern\n");
#endif
return 1;
}
if (pattern[0] != '_') { /* not a pattern, try exact or partial match */
int ld = strlen(data), lp = strlen(pattern);
if (lp < ld) { /* pattern too short, cannot match */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (0) - pattern too short, cannot match\n");
#endif
return 0;
}
/* depending on the mode, accept full or partial match or both */
if (mode == E_MATCH) {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (!strcmp(%s,%s) when mode== E_MATCH)\n", pattern, data);
#endif
return !strcmp(pattern, data); /* 1 on match, 0 on fail */
}
if (ld == 0 || !strncasecmp(pattern, data, ld)) { /* partial or full match */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (mode(%d) == E_MATCHMORE ? lp(%d) > ld(%d) : 1)\n", mode, lp, ld);
#endif
return (mode == E_MATCHMORE) ? lp > ld : 1; /* XXX should consider '!' and '/' ? */
} else {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (0) when ld(%d) > 0 && pattern(%s) != data(%s)\n", ld, pattern, data);
#endif
return 0;
}
}
pattern++; /* skip leading _ */
/*
* XXX below we stop at '/' which is a separator for the CID info. However we should
* not store '/' in the pattern at all. When we insure it, we can remove the checks.
*/
while (*data && *pattern && *pattern != '/') {
const char *end;
if (*data == '-') { /* skip '-' in data (just a separator) */
data++;
continue;
}
switch (toupper(*pattern)) {
case '[': /* a range */
end = strchr(pattern+1, ']'); /* XXX should deal with escapes ? */
if (end == NULL) {
ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");
return 0; /* unconditional failure */
}
for (pattern++; pattern != end; pattern++) {
if (pattern+2 < end && pattern[1] == '-') { /* this is a range */
if (*data >= pattern[0] && *data <= pattern[2])
break; /* match found */
else {
pattern += 2; /* skip a total of 3 chars */
continue;
}
} else if (*data == pattern[0])
break; /* match found */
}
if (pattern == end) {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (0) when pattern==end\n");
#endif
return 0;
}
pattern = end; /* skip and continue */
break;
case 'N':
if (*data < '2' || *data > '9') {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (0) N is matched\n");
#endif
return 0;
}
break;
case 'X':
if (*data < '0' || *data > '9') {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (0) X is matched\n");
#endif
return 0;
}
break;
case 'Z':
if (*data < '1' || *data > '9') {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (0) Z is matched\n");
#endif
return 0;
}
break;
case '.': /* Must match, even with more digits */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "return (1) when '.' is matched\n");
#endif
return 1;
case '!': /* Early match */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "return (2) when '!' is matched\n");
#endif
return 2;
case ' ':
case '-': /* Ignore these in patterns */
data--; /* compensate the final data++ */
break;
default:
if (*data != *pattern) {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "return (0) when *data(%c) != *pattern(%c)\n", *data, *pattern);
#endif
return 0;
}
}
data++;
pattern++;
}
if (*data) /* data longer than pattern, no match */ {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "return (0) when data longer than pattern\n");
#endif
return 0;
}
/*
* match so far, but ran off the end of the data.
* Depending on what is next, determine match or not.
*/
if (*pattern == '\0' || *pattern == '/') { /* exact match */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "at end, return (%d) in 'exact match'\n", (mode==E_MATCHMORE) ? 0 : 1);
#endif
return (mode == E_MATCHMORE) ? 0 : 1; /* this is a failure for E_MATCHMORE */
} else if (*pattern == '!') { /* early match */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "at end, return (2) when '!' is matched\n");
#endif
return 2;
} else { /* partial match */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "at end, return (%d) which deps on E_MATCH\n", (mode == E_MATCH) ? 0 : 1);
#endif
return (mode == E_MATCH) ? 0 : 1; /* this is a failure for E_MATCH */
}
}
/*
* Wrapper around _extension_match_core() to do performance measurement
* using the profiling code.
*/
static int extension_match_core(const char *pattern, const char *data, enum ext_match_t mode)
{
int i;
static int prof_id = -2; /* marker for 'unallocated' id */
if (prof_id == -2) {
prof_id = ast_add_profile("ext_match", 0);
}
ast_mark(prof_id, 1);
i = _extension_match_core(ast_strlen_zero(pattern) ? "" : pattern, ast_strlen_zero(data) ? "" : data, mode);
ast_mark(prof_id, 0);
return i;
}
int ast_extension_match(const char *pattern, const char *data)
{
return extension_match_core(pattern, data, E_MATCH);
}
int ast_extension_close(const char *pattern, const char *data, int needmore)
{
if (needmore != E_MATCHMORE && needmore != E_CANMATCH)
ast_log(LOG_WARNING, "invalid argument %d\n", needmore);
return extension_match_core(pattern, data, needmore);
}
struct fake_context /* this struct is purely for matching in the hashtab */
{
ast_rwlock_t lock;
struct ast_exten *root;
struct ast_hashtab *root_table;
struct match_char *pattern_tree;
struct ast_context *next;
struct ast_include *includes;
struct ast_ignorepat *ignorepats;
const char *registrar;
int refcount;
AST_LIST_HEAD_NOLOCK(, ast_sw) alts;
ast_mutex_t macrolock;
char name[256];
};
struct ast_context *ast_context_find(const char *name)
{
struct ast_context *tmp;
struct fake_context item;
if (!name) {
return NULL;
}
ast_rdlock_contexts();
if (contexts_table) {
ast_copy_string(item.name, name, sizeof(item.name));
tmp = ast_hashtab_lookup(contexts_table, &item);
} else {
tmp = NULL;
while ((tmp = ast_walk_contexts(tmp))) {
if (!strcasecmp(name, tmp->name)) {
break;
}
}
}
ast_unlock_contexts();
return tmp;
}
#define STATUS_NO_CONTEXT 1
#define STATUS_NO_EXTENSION 2
#define STATUS_NO_PRIORITY 3
#define STATUS_NO_LABEL 4
#define STATUS_SUCCESS 5
static int matchcid(const char *cidpattern, const char *callerid)
{
/* If the Caller*ID pattern is empty, then we're matching NO Caller*ID, so
failing to get a number should count as a match, otherwise not */
if (ast_strlen_zero(callerid)) {
return ast_strlen_zero(cidpattern) ? 1 : 0;
}
return ast_extension_match(cidpattern, callerid);
}
struct ast_exten *pbx_find_extension(struct ast_channel *chan,
struct ast_context *bypass, struct pbx_find_info *q,
const char *context, const char *exten, int priority,
const char *label, const char *callerid, enum ext_match_t action)
{
int x, res;
struct ast_context *tmp = NULL;
struct ast_exten *e = NULL, *eroot = NULL;
struct ast_include *i = NULL;
struct ast_sw *sw = NULL;
struct ast_exten pattern = {NULL, };
struct scoreboard score = {0, };
struct ast_str *tmpdata = NULL;
pattern.label = label;
pattern.priority = priority;
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "Looking for cont/ext/prio/label/action = %s/%s/%d/%s/%d\n", context, exten, priority, label, (int) action);
#endif
/* Initialize status if appropriate */
if (q->stacklen == 0) {
q->status = STATUS_NO_CONTEXT;
q->swo = NULL;
q->data = NULL;
q->foundcontext = NULL;
} else if (q->stacklen >= AST_PBX_MAX_STACK) {
ast_log(LOG_WARNING, "Maximum PBX stack exceeded\n");
return NULL;
}
/* Check first to see if we've already been checked */
for (x = 0; x < q->stacklen; x++) {
if (!strcasecmp(q->incstack[x], context))
return NULL;
}
if (bypass) { /* bypass means we only look there */
tmp = bypass;
} else { /* look in contexts */
tmp = find_context(context);
if (!tmp) {
return NULL;
}
}
if (q->status < STATUS_NO_EXTENSION)
q->status = STATUS_NO_EXTENSION;
/* Do a search for matching extension */
eroot = NULL;
score.total_specificity = 0;
score.exten = 0;
score.total_length = 0;
if (!tmp->pattern_tree && tmp->root_table) {
create_match_char_tree(tmp);
#ifdef NEED_DEBUG
ast_log(LOG_DEBUG, "Tree Created in context %s:\n", context);
log_match_char_tree(tmp->pattern_tree," ");
#endif
}
#ifdef NEED_DEBUG
ast_log(LOG_NOTICE, "The Trie we are searching in:\n");
log_match_char_tree(tmp->pattern_tree, ":: ");
#endif
do {
if (!ast_strlen_zero(overrideswitch)) {
char *osw = ast_strdupa(overrideswitch), *name;
struct ast_switch *asw;
ast_switch_f *aswf = NULL;
char *datap;
int eval = 0;
name = strsep(&osw, "/");
asw = pbx_findswitch(name);
if (!asw) {
ast_log(LOG_WARNING, "No such switch '%s'\n", name);
break;
}
if (osw && strchr(osw, '$')) {
eval = 1;
}
if (eval && !(tmpdata = ast_str_thread_get(&switch_data, 512))) {
ast_log(LOG_WARNING, "Can't evaluate overrideswitch?!\n");
break;
} else if (eval) {
/* Substitute variables now */
pbx_substitute_variables_helper(chan, osw, ast_str_buffer(tmpdata), ast_str_size(tmpdata));
datap = ast_str_buffer(tmpdata);
} else {
datap = osw;
}
/* equivalent of extension_match_core() at the switch level */
if (action == E_CANMATCH)
aswf = asw->canmatch;
else if (action == E_MATCHMORE)
aswf = asw->matchmore;
else /* action == E_MATCH */
aswf = asw->exists;
if (!aswf) {
res = 0;
} else {
if (chan) {
ast_autoservice_start(chan);
}
res = aswf(chan, context, exten, priority, callerid, datap);
if (chan) {
ast_autoservice_stop(chan);
}
}
if (res) { /* Got a match */
q->swo = asw;
q->data = datap;
q->foundcontext = context;
/* XXX keep status = STATUS_NO_CONTEXT ? */
return NULL;
}
}
} while (0);
if (extenpatternmatchnew) {
new_find_extension(exten, &score, tmp->pattern_tree, 0, 0, callerid, label, action);
eroot = score.exten;
if (score.last_char == '!' && action == E_MATCHMORE) {
/* We match an extension ending in '!'.
* The decision in this case is final and is NULL (no match).
*/
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Returning MATCHMORE NULL with exclamation point.\n");
#endif
return NULL;
}
if (!eroot && (action == E_CANMATCH || action == E_MATCHMORE) && score.canmatch_exten) {
q->status = STATUS_SUCCESS;
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Returning CANMATCH exten %s\n", score.canmatch_exten->exten);
#endif
return score.canmatch_exten;
}
if ((action == E_MATCHMORE || action == E_CANMATCH) && eroot) {
if (score.node) {
struct ast_exten *z = trie_find_next_match(score.node);
if (z) {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE next_match exten %s\n", z->exten);
#endif
} else {
if (score.canmatch_exten) {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE canmatchmatch exten %s(%p)\n", score.canmatch_exten->exten, score.canmatch_exten);
#endif
return score.canmatch_exten;
} else {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE next_match exten NULL\n");
#endif
}
}
return z;
}
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "Returning CANMATCH/MATCHMORE NULL (no next_match)\n");
#endif
return NULL; /* according to the code, complete matches are null matches in MATCHMORE mode */
}
if (eroot) {
/* found entry, now look for the right priority */
if (q->status < STATUS_NO_PRIORITY)
q->status = STATUS_NO_PRIORITY;
e = NULL;
if (action == E_FINDLABEL && label ) {
if (q->status < STATUS_NO_LABEL)
q->status = STATUS_NO_LABEL;
e = ast_hashtab_lookup(eroot->peer_label_table, &pattern);
} else {
e = ast_hashtab_lookup(eroot->peer_table, &pattern);
}
if (e) { /* found a valid match */
q->status = STATUS_SUCCESS;
q->foundcontext = context;
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Returning complete match of exten %s\n", e->exten);
#endif
return e;
}
}
} else { /* the old/current default exten pattern match algorithm */
/* scan the list trying to match extension and CID */
eroot = NULL;
while ( (eroot = ast_walk_context_extensions(tmp, eroot)) ) {
int match = extension_match_core(eroot->exten, exten, action);
/* 0 on fail, 1 on match, 2 on earlymatch */
if (!match || (eroot->matchcid && !matchcid(eroot->cidmatch, callerid)))
continue; /* keep trying */
if (match == 2 && action == E_MATCHMORE) {
/* We match an extension ending in '!'.
* The decision in this case is final and is NULL (no match).
*/
return NULL;
}
/* found entry, now look for the right priority */
if (q->status < STATUS_NO_PRIORITY)
q->status = STATUS_NO_PRIORITY;
e = NULL;
if (action == E_FINDLABEL && label ) {
if (q->status < STATUS_NO_LABEL)
q->status = STATUS_NO_LABEL;
e = ast_hashtab_lookup(eroot->peer_label_table, &pattern);
} else {
e = ast_hashtab_lookup(eroot->peer_table, &pattern);
}
if (e) { /* found a valid match */
q->status = STATUS_SUCCESS;
q->foundcontext = context;
return e;
}
}
}
/* Check alternative switches */
AST_LIST_TRAVERSE(&tmp->alts, sw, list) {
struct ast_switch *asw = pbx_findswitch(sw->name);
ast_switch_f *aswf = NULL;
char *datap;
if (!asw) {
ast_log(LOG_WARNING, "No such switch '%s'\n", sw->name);
continue;
}
/* Substitute variables now */
if (sw->eval) {
if (!(tmpdata = ast_str_thread_get(&switch_data, 512))) {
ast_log(LOG_WARNING, "Can't evaluate switch?!\n");
continue;
}
pbx_substitute_variables_helper(chan, sw->data, ast_str_buffer(tmpdata), ast_str_size(tmpdata));
}
/* equivalent of extension_match_core() at the switch level */
if (action == E_CANMATCH)
aswf = asw->canmatch;
else if (action == E_MATCHMORE)
aswf = asw->matchmore;
else /* action == E_MATCH */
aswf = asw->exists;
datap = sw->eval ? ast_str_buffer(tmpdata) : sw->data;
if (!aswf)
res = 0;
else {
if (chan)
ast_autoservice_start(chan);
res = aswf(chan, context, exten, priority, callerid, datap);
if (chan)
ast_autoservice_stop(chan);
}
if (res) { /* Got a match */
q->swo = asw;
q->data = datap;
q->foundcontext = context;
/* XXX keep status = STATUS_NO_CONTEXT ? */
return NULL;
}
}
q->incstack[q->stacklen++] = tmp->name; /* Setup the stack */
/* Now try any includes we have in this context */
for (i = tmp->includes; i; i = i->next) {
if (include_valid(i)) {
if ((e = pbx_find_extension(chan, bypass, q, i->rname, exten, priority, label, callerid, action))) {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Returning recursive match of %s\n", e->exten);
#endif
return e;
}
if (q->swo)
return NULL;
}
}
return NULL;
}
/*!
* \brief extract offset:length from variable name.
* \return 1 if there is a offset:length part, which is
* trimmed off (values go into variables)
*/
static int parse_variable_name(char *var, int *offset, int *length, int *isfunc)
{
int parens = 0;
*offset = 0;
*length = INT_MAX;
*isfunc = 0;
for (; *var; var++) {
if (*var == '(') {
(*isfunc)++;
parens++;
} else if (*var == ')') {
parens--;
} else if (*var == ':' && parens == 0) {
*var++ = '\0';
sscanf(var, "%30d:%30d", offset, length);
return 1; /* offset:length valid */
}
}
return 0;
}
/*!
*\brief takes a substring. It is ok to call with value == workspace.
* \param value
* \param offset < 0 means start from the end of the string and set the beginning
* to be that many characters back.
* \param length is the length of the substring, a value less than 0 means to leave
* that many off the end.
* \param workspace
* \param workspace_len
* Always return a copy in workspace.
*/
static char *substring(const char *value, int offset, int length, char *workspace, size_t workspace_len)
{
char *ret = workspace;
int lr; /* length of the input string after the copy */
ast_copy_string(workspace, value, workspace_len); /* always make a copy */
lr = strlen(ret); /* compute length after copy, so we never go out of the workspace */
/* Quick check if no need to do anything */
if (offset == 0 && length >= lr) /* take the whole string */
return ret;
if (offset < 0) { /* translate negative offset into positive ones */
offset = lr + offset;
if (offset < 0) /* If the negative offset was greater than the length of the string, just start at the beginning */
offset = 0;
}
/* too large offset result in empty string so we know what to return */
if (offset >= lr)
return ret + lr; /* the final '\0' */
ret += offset; /* move to the start position */
if (length >= 0 && length < lr - offset) /* truncate if necessary */
ret[length] = '\0';
else if (length < 0) {
if (lr > offset - length) /* After we remove from the front and from the rear, is there anything left? */
ret[lr + length - offset] = '\0';
else
ret[0] = '\0';
}
return ret;
}
static const char *ast_str_substring(struct ast_str *value, int offset, int length)
{
int lr; /* length of the input string after the copy */
lr = ast_str_strlen(value); /* compute length after copy, so we never go out of the workspace */
/* Quick check if no need to do anything */
if (offset == 0 && length >= lr) /* take the whole string */
return ast_str_buffer(value);
if (offset < 0) { /* translate negative offset into positive ones */
offset = lr + offset;
if (offset < 0) /* If the negative offset was greater than the length of the string, just start at the beginning */
offset = 0;
}
/* too large offset result in empty string so we know what to return */
if (offset >= lr) {
ast_str_reset(value);
return ast_str_buffer(value);
}
if (offset > 0) {
/* Go ahead and chop off the beginning */
memmove(ast_str_buffer(value), ast_str_buffer(value) + offset, ast_str_strlen(value) - offset + 1);
lr -= offset;
}
if (length >= 0 && length < lr) { /* truncate if necessary */
char *tmp = ast_str_buffer(value);
tmp[length] = '\0';
ast_str_update(value);
} else if (length < 0) {
if (lr > -length) { /* After we remove from the front and from the rear, is there anything left? */
char *tmp = ast_str_buffer(value);
tmp[lr + length] = '\0';
ast_str_update(value);
} else {
ast_str_reset(value);
}
} else {
/* Nothing to do, but update the buffer length */
ast_str_update(value);
}
return ast_str_buffer(value);
}
/*! \brief Support for Asterisk built-in variables in the dialplan
\note See also
- \ref AstVar Channel variables
- \ref AstCauses The HANGUPCAUSE variable
*/
void pbx_retrieve_variable(struct ast_channel *c, const char *var, char **ret, char *workspace, int workspacelen, struct varshead *headp)
{
struct ast_str *str = ast_str_create(16);
const char *cret;
cret = ast_str_retrieve_variable(&str, 0, c, headp, var);
ast_copy_string(workspace, ast_str_buffer(str), workspacelen);
*ret = cret ? workspace : NULL;
ast_free(str);
}
const char *ast_str_retrieve_variable(struct ast_str **str, ssize_t maxlen, struct ast_channel *c, struct varshead *headp, const char *var)
{
const char not_found = '\0';
char *tmpvar;
const char *ret;
const char *s; /* the result */
int offset, length;
int i, need_substring;
struct varshead *places[2] = { headp, &globals }; /* list of places where we may look */
char workspace[20];
if (c) {
ast_channel_lock(c);
places[0] = &c->varshead;
}
/*
* Make a copy of var because parse_variable_name() modifies the string.
* Then if called directly, we might need to run substring() on the result;
* remember this for later in 'need_substring', 'offset' and 'length'
*/
tmpvar = ast_strdupa(var); /* parse_variable_name modifies the string */
need_substring = parse_variable_name(tmpvar, &offset, &length, &i /* ignored */);
/*
* Look first into predefined variables, then into variable lists.
* Variable 's' points to the result, according to the following rules:
* s == ¬_found (set at the beginning) means that we did not find a
* matching variable and need to look into more places.
* If s != ¬_found, s is a valid result string as follows:
* s = NULL if the variable does not have a value;
* you typically do this when looking for an unset predefined variable.
* s = workspace if the result has been assembled there;
* typically done when the result is built e.g. with an snprintf(),
* so we don't need to do an additional copy.
* s != workspace in case we have a string, that needs to be copied
* (the ast_copy_string is done once for all at the end).
* Typically done when the result is already available in some string.
*/
s = ¬_found; /* default value */
if (c) { /* This group requires a valid channel */
/* Names with common parts are looked up a piece at a time using strncmp. */
if (!strncmp(var, "CALL", 4)) {
if (!strncmp(var + 4, "ING", 3)) {
if (!strcmp(var + 7, "PRES")) { /* CALLINGPRES */
ast_str_set(str, maxlen, "%d",
ast_party_id_presentation(&c->caller.id));
s = ast_str_buffer(*str);
} else if (!strcmp(var + 7, "ANI2")) { /* CALLINGANI2 */
ast_str_set(str, maxlen, "%d", c->caller.ani2);
s = ast_str_buffer(*str);
} else if (!strcmp(var + 7, "TON")) { /* CALLINGTON */
ast_str_set(str, maxlen, "%d", c->caller.id.number.plan);
s = ast_str_buffer(*str);
} else if (!strcmp(var + 7, "TNS")) { /* CALLINGTNS */
ast_str_set(str, maxlen, "%d", c->dialed.transit_network_select);
s = ast_str_buffer(*str);
}
}
} else if (!strcmp(var, "HINT")) {
s = ast_str_get_hint(str, maxlen, NULL, 0, c, c->context, c->exten) ? ast_str_buffer(*str) : NULL;
} else if (!strcmp(var, "HINTNAME")) {
s = ast_str_get_hint(NULL, 0, str, maxlen, c, c->context, c->exten) ? ast_str_buffer(*str) : NULL;
} else if (!strcmp(var, "EXTEN")) {
s = c->exten;
} else if (!strcmp(var, "CONTEXT")) {
s = c->context;
} else if (!strcmp(var, "PRIORITY")) {
ast_str_set(str, maxlen, "%d", c->priority);
s = ast_str_buffer(*str);
} else if (!strcmp(var, "CHANNEL")) {
s = c->name;
} else if (!strcmp(var, "UNIQUEID")) {
s = c->uniqueid;
} else if (!strcmp(var, "HANGUPCAUSE")) {
ast_str_set(str, maxlen, "%d", c->hangupcause);
s = ast_str_buffer(*str);
}
}
if (s == ¬_found) { /* look for more */
if (!strcmp(var, "EPOCH")) {
ast_str_set(str, maxlen, "%u", (int) time(NULL));
s = ast_str_buffer(*str);
} else if (!strcmp(var, "SYSTEMNAME")) {
s = ast_config_AST_SYSTEM_NAME;
} else if (!strcmp(var, "ENTITYID")) {
ast_eid_to_str(workspace, sizeof(workspace), &ast_eid_default);
s = workspace;
}
}
/* if not found, look into chanvars or global vars */
for (i = 0; s == ¬_found && i < ARRAY_LEN(places); i++) {
struct ast_var_t *variables;
if (!places[i])
continue;
if (places[i] == &globals)
ast_rwlock_rdlock(&globalslock);
AST_LIST_TRAVERSE(places[i], variables, entries) {
if (!strcasecmp(ast_var_name(variables), var)) {
s = ast_var_value(variables);
break;
}
}
if (places[i] == &globals)
ast_rwlock_unlock(&globalslock);
}
if (s == ¬_found || s == NULL) {
ast_debug(5, "Result of '%s' is NULL\n", var);
ret = NULL;
} else {
ast_debug(5, "Result of '%s' is '%s'\n", var, s);
if (s != ast_str_buffer(*str)) {
ast_str_set(str, maxlen, "%s", s);
}
ret = ast_str_buffer(*str);
if (need_substring) {
ret = ast_str_substring(*str, offset, length);
ast_debug(2, "Final result of '%s' is '%s'\n", var, ret);
}
}
if (c) {
ast_channel_unlock(c);
}
return ret;
}
static void exception_store_free(void *data)
{
struct pbx_exception *exception = data;
ast_string_field_free_memory(exception);
ast_free(exception);
}
static struct ast_datastore_info exception_store_info = {
.type = "EXCEPTION",
.destroy = exception_store_free,
};
/*!
* \internal
* \brief Set the PBX to execute the exception extension.
*
* \param chan Channel to raise the exception on.
* \param reason Reason exception is raised.
* \param priority Dialplan priority to set.
*
* \retval 0 on success.
* \retval -1 on error.
*/
static int raise_exception(struct ast_channel *chan, const char *reason, int priority)
{
struct ast_datastore *ds = ast_channel_datastore_find(chan, &exception_store_info, NULL);
struct pbx_exception *exception = NULL;
if (!ds) {
ds = ast_datastore_alloc(&exception_store_info, NULL);
if (!ds)
return -1;
if (!(exception = ast_calloc_with_stringfields(1, struct pbx_exception, 128))) {
ast_datastore_free(ds);
return -1;
}
ds->data = exception;
ast_channel_datastore_add(chan, ds);
} else
exception = ds->data;
ast_string_field_set(exception, reason, reason);
ast_string_field_set(exception, context, chan->context);
ast_string_field_set(exception, exten, chan->exten);
exception->priority = chan->priority;
set_ext_pri(chan, "e", priority);
return 0;
}
int pbx_builtin_raise_exception(struct ast_channel *chan, const char *reason)
{
/* Priority will become 1, next time through the AUTOLOOP */
return raise_exception(chan, reason, 0);
}
static int acf_exception_read(struct ast_channel *chan, const char *name, char *data, char *buf, size_t buflen)
{
struct ast_datastore *ds = ast_channel_datastore_find(chan, &exception_store_info, NULL);
struct pbx_exception *exception = NULL;
if (!ds || !ds->data)
return -1;
exception = ds->data;
if (!strcasecmp(data, "REASON"))
ast_copy_string(buf, exception->reason, buflen);
else if (!strcasecmp(data, "CONTEXT"))
ast_copy_string(buf, exception->context, buflen);
else if (!strncasecmp(data, "EXTEN", 5))
ast_copy_string(buf, exception->exten, buflen);
else if (!strcasecmp(data, "PRIORITY"))
snprintf(buf, buflen, "%d", exception->priority);
else
return -1;
return 0;
}
static struct ast_custom_function exception_function = {
.name = "EXCEPTION",
.read = acf_exception_read,
};
static char *handle_show_functions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_custom_function *acf;
int count_acf = 0;
int like = 0;
switch (cmd) {
case CLI_INIT:
e->command = "core show functions [like]";
e->usage =
"Usage: core show functions [like <text>]\n"
" List builtin functions, optionally only those matching a given string\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc == 5 && (!strcmp(a->argv[3], "like")) ) {
like = 1;
} else if (a->argc != 3) {
return CLI_SHOWUSAGE;
}
ast_cli(a->fd, "%s Custom Functions:\n--------------------------------------------------------------------------------\n", like ? "Matching" : "Installed");
AST_RWLIST_RDLOCK(&acf_root);
AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) {
if (!like || strstr(acf->name, a->argv[4])) {
count_acf++;
ast_cli(a->fd, "%-20.20s %-35.35s %s\n",
S_OR(acf->name, ""),
S_OR(acf->syntax, ""),
S_OR(acf->synopsis, ""));
}
}
AST_RWLIST_UNLOCK(&acf_root);
ast_cli(a->fd, "%d %scustom functions installed.\n", count_acf, like ? "matching " : "");
return CLI_SUCCESS;
}
static char *handle_show_function(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_custom_function *acf;
/* Maximum number of characters added by terminal coloring is 22 */
char infotitle[64 + AST_MAX_APP + 22], syntitle[40], destitle[40], argtitle[40], seealsotitle[40];
char info[64 + AST_MAX_APP], *synopsis = NULL, *description = NULL, *seealso = NULL;
char stxtitle[40], *syntax = NULL, *arguments = NULL;
int syntax_size, description_size, synopsis_size, arguments_size, seealso_size;
char *ret = NULL;
int which = 0;
int wordlen;
switch (cmd) {
case CLI_INIT:
e->command = "core show function";
e->usage =
"Usage: core show function <function>\n"
" Describe a particular dialplan function.\n";
return NULL;
case CLI_GENERATE:
wordlen = strlen(a->word);
/* case-insensitive for convenience in this 'complete' function */
AST_RWLIST_RDLOCK(&acf_root);
AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) {
if (!strncasecmp(a->word, acf->name, wordlen) && ++which > a->n) {
ret = ast_strdup(acf->name);
break;
}
}
AST_RWLIST_UNLOCK(&acf_root);
return ret;
}
if (a->argc < 4) {
return CLI_SHOWUSAGE;
}
if (!(acf = ast_custom_function_find(a->argv[3]))) {
ast_cli(a->fd, "No function by that name registered.\n");
return CLI_FAILURE;
}
syntax_size = strlen(S_OR(acf->syntax, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
if (!(syntax = ast_malloc(syntax_size))) {
ast_cli(a->fd, "Memory allocation failure!\n");
return CLI_FAILURE;
}
snprintf(info, sizeof(info), "\n -= Info about function '%s' =- \n\n", acf->name);
term_color(infotitle, info, COLOR_MAGENTA, 0, sizeof(infotitle));
term_color(syntitle, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
term_color(destitle, "[Description]\n", COLOR_MAGENTA, 0, 40);
term_color(stxtitle, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
term_color(argtitle, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
term_color(seealsotitle, "[See Also]\n", COLOR_MAGENTA, 0, 40);
term_color(syntax, S_OR(acf->syntax, "Not available"), COLOR_CYAN, 0, syntax_size);
#ifdef AST_XML_DOCS
if (acf->docsrc == AST_XML_DOC) {
arguments = ast_xmldoc_printable(S_OR(acf->arguments, "Not available"), 1);
synopsis = ast_xmldoc_printable(S_OR(acf->synopsis, "Not available"), 1);
description = ast_xmldoc_printable(S_OR(acf->desc, "Not available"), 1);
seealso = ast_xmldoc_printable(S_OR(acf->seealso, "Not available"), 1);
} else
#endif
{
synopsis_size = strlen(S_OR(acf->synopsis, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
synopsis = ast_malloc(synopsis_size);
description_size = strlen(S_OR(acf->desc, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
description = ast_malloc(description_size);
arguments_size = strlen(S_OR(acf->arguments, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
arguments = ast_malloc(arguments_size);
seealso_size = strlen(S_OR(acf->seealso, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
seealso = ast_malloc(seealso_size);
/* check allocated memory. */
if (!synopsis || !description || !arguments || !seealso) {
ast_free(synopsis);
ast_free(description);
ast_free(arguments);
ast_free(seealso);
ast_free(syntax);
return CLI_FAILURE;
}
term_color(arguments, S_OR(acf->arguments, "Not available"), COLOR_CYAN, 0, arguments_size);
term_color(synopsis, S_OR(acf->synopsis, "Not available"), COLOR_CYAN, 0, synopsis_size);
term_color(description, S_OR(acf->desc, "Not available"), COLOR_CYAN, 0, description_size);
term_color(seealso, S_OR(acf->seealso, "Not available"), COLOR_CYAN, 0, seealso_size);
}
ast_cli(a->fd, "%s%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n",
infotitle, syntitle, synopsis, destitle, description,
stxtitle, syntax, argtitle, arguments, seealsotitle, seealso);
ast_free(arguments);
ast_free(synopsis);
ast_free(description);
ast_free(seealso);
ast_free(syntax);
return CLI_SUCCESS;
}
struct ast_custom_function *ast_custom_function_find(const char *name)
{
struct ast_custom_function *acf = NULL;
AST_RWLIST_RDLOCK(&acf_root);
AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) {
if (!strcmp(name, acf->name))
break;
}
AST_RWLIST_UNLOCK(&acf_root);
return acf;
}
int ast_custom_function_unregister(struct ast_custom_function *acf)
{
struct ast_custom_function *cur;
struct ast_custom_escalating_function *cur_escalation;
if (!acf) {
return -1;
}
AST_RWLIST_WRLOCK(&acf_root);
if ((cur = AST_RWLIST_REMOVE(&acf_root, acf, acflist))) {
#ifdef AST_XML_DOCS
if (cur->docsrc == AST_XML_DOC) {
ast_string_field_free_memory(acf);
}
#endif
ast_verb(2, "Unregistered custom function %s\n", cur->name);
}
AST_RWLIST_UNLOCK(&acf_root);
/* Remove from the escalation list */
AST_RWLIST_WRLOCK(&escalation_root);
AST_RWLIST_TRAVERSE_SAFE_BEGIN(&escalation_root, cur_escalation, list) {
if (cur_escalation->acf == acf) {
AST_RWLIST_REMOVE_CURRENT(list);
break;
}
}
AST_RWLIST_TRAVERSE_SAFE_END;
AST_RWLIST_UNLOCK(&escalation_root);
return cur ? 0 : -1;
}
/*!
* \brief Returns true if given custom function escalates privileges on read.
*
* \param acf Custom function to query.
* \return True (non-zero) if reads escalate privileges.
* \return False (zero) if reads just read.
*/
static int read_escalates(const struct ast_custom_function *acf) {
int res = 0;
struct ast_custom_escalating_function *cur_escalation;
AST_RWLIST_RDLOCK(&escalation_root);
AST_RWLIST_TRAVERSE(&escalation_root, cur_escalation, list) {
if (cur_escalation->acf == acf) {
res = cur_escalation->read_escalates;
break;
}
}
AST_RWLIST_UNLOCK(&escalation_root);
return res;
}
/*!
* \brief Returns true if given custom function escalates privileges on write.
*
* \param acf Custom function to query.
* \return True (non-zero) if writes escalate privileges.
* \return False (zero) if writes just write.
*/
static int write_escalates(const struct ast_custom_function *acf) {
int res = 0;
struct ast_custom_escalating_function *cur_escalation;
AST_RWLIST_RDLOCK(&escalation_root);
AST_RWLIST_TRAVERSE(&escalation_root, cur_escalation, list) {
if (cur_escalation->acf == acf) {
res = cur_escalation->write_escalates;
break;
}
}
AST_RWLIST_UNLOCK(&escalation_root);
return res;
}
/*! \internal
* \brief Retrieve the XML documentation of a specified ast_custom_function,
* and populate ast_custom_function string fields.
* \param acf ast_custom_function structure with empty 'desc' and 'synopsis'
* but with a function 'name'.
* \retval -1 On error.
* \retval 0 On succes.
*/
static int acf_retrieve_docs(struct ast_custom_function *acf)
{
#ifdef AST_XML_DOCS
char *tmpxml;
/* Let's try to find it in the Documentation XML */
if (!ast_strlen_zero(acf->desc) || !ast_strlen_zero(acf->synopsis)) {
return 0;
}
if (ast_string_field_init(acf, 128)) {
return -1;
}
/* load synopsis */
tmpxml = ast_xmldoc_build_synopsis("function", acf->name, ast_module_name(acf->mod));
ast_string_field_set(acf, synopsis, tmpxml);
ast_free(tmpxml);
/* load description */
tmpxml = ast_xmldoc_build_description("function", acf->name, ast_module_name(acf->mod));
ast_string_field_set(acf, desc, tmpxml);
ast_free(tmpxml);
/* load syntax */
tmpxml = ast_xmldoc_build_syntax("function", acf->name, ast_module_name(acf->mod));
ast_string_field_set(acf, syntax, tmpxml);
ast_free(tmpxml);
/* load arguments */
tmpxml = ast_xmldoc_build_arguments("function", acf->name, ast_module_name(acf->mod));
ast_string_field_set(acf, arguments, tmpxml);
ast_free(tmpxml);
/* load seealso */
tmpxml = ast_xmldoc_build_seealso("function", acf->name, ast_module_name(acf->mod));
ast_string_field_set(acf, seealso, tmpxml);
ast_free(tmpxml);
acf->docsrc = AST_XML_DOC;
#endif
return 0;
}
int __ast_custom_function_register(struct ast_custom_function *acf, struct ast_module *mod)
{
struct ast_custom_function *cur;
char tmps[80];
if (!acf) {
return -1;
}
acf->mod = mod;
#ifdef AST_XML_DOCS
acf->docsrc = AST_STATIC_DOC;
#endif
if (acf_retrieve_docs(acf)) {
return -1;
}
AST_RWLIST_WRLOCK(&acf_root);
AST_RWLIST_TRAVERSE(&acf_root, cur, acflist) {
if (!strcmp(acf->name, cur->name)) {
ast_log(LOG_ERROR, "Function %s already registered.\n", acf->name);
AST_RWLIST_UNLOCK(&acf_root);
return -1;
}
}
/* Store in alphabetical order */
AST_RWLIST_TRAVERSE_SAFE_BEGIN(&acf_root, cur, acflist) {
if (strcasecmp(acf->name, cur->name) < 0) {
AST_RWLIST_INSERT_BEFORE_CURRENT(acf, acflist);
break;
}
}
AST_RWLIST_TRAVERSE_SAFE_END;
if (!cur) {
AST_RWLIST_INSERT_TAIL(&acf_root, acf, acflist);
}
AST_RWLIST_UNLOCK(&acf_root);
ast_verb(2, "Registered custom function '%s'\n", term_color(tmps, acf->name, COLOR_BRCYAN, 0, sizeof(tmps)));
return 0;
}
int __ast_custom_function_register_escalating(struct ast_custom_function *acf, enum ast_custom_function_escalation escalation, struct ast_module *mod)
{
struct ast_custom_escalating_function *acf_escalation = NULL;
int res;
res = __ast_custom_function_register(acf, mod);
if (res != 0) {
return -1;
}
if (escalation == AST_CFE_NONE) {
/* No escalations; no need to do anything else */
return 0;
}
acf_escalation = ast_calloc(1, sizeof(*acf_escalation));
if (!acf_escalation) {
ast_custom_function_unregister(acf);
return -1;
}
acf_escalation->acf = acf;
switch (escalation) {
case AST_CFE_NONE:
break;
case AST_CFE_READ:
acf_escalation->read_escalates = 1;
break;
case AST_CFE_WRITE:
acf_escalation->write_escalates = 1;
break;
case AST_CFE_BOTH:
acf_escalation->read_escalates = 1;
acf_escalation->write_escalates = 1;
break;
}
AST_RWLIST_WRLOCK(&escalation_root);
AST_RWLIST_INSERT_TAIL(&escalation_root, acf_escalation, list);
AST_RWLIST_UNLOCK(&escalation_root);
return 0;
}
/*! \brief return a pointer to the arguments of the function,
* and terminates the function name with '\\0'
*/
static char *func_args(char *function)
{
char *args = strchr(function, '(');
if (!args) {
ast_log(LOG_WARNING, "Function '%s' doesn't contain parentheses. Assuming null argument.\n", function);
} else {
char *p;
*args++ = '\0';
if ((p = strrchr(args, ')'))) {
*p = '\0';
} else {
ast_log(LOG_WARNING, "Can't find trailing parenthesis for function '%s(%s'?\n", function, args);
}
}
return args;
}
void pbx_live_dangerously(int new_live_dangerously)
{
if (new_live_dangerously && !live_dangerously) {
ast_log(LOG_WARNING, "Privilege escalation protection disabled!\n"
"See https://wiki.asterisk.org/wiki/x/1gKfAQ for more details.\n");
}
if (!new_live_dangerously && live_dangerously) {
ast_log(LOG_NOTICE, "Privilege escalation protection enabled.\n");
}
live_dangerously = new_live_dangerously;
}
int ast_thread_inhibit_escalations(void)
{
int *thread_inhibit_escalations;
thread_inhibit_escalations = ast_threadstorage_get(
&thread_inhibit_escalations_tl, sizeof(*thread_inhibit_escalations));
if (thread_inhibit_escalations == NULL) {
ast_log(LOG_ERROR, "Error inhibiting privilege escalations for current thread\n");
return -1;
}
*thread_inhibit_escalations = 1;
return 0;
}
/*!
* \brief Indicates whether the current thread inhibits the execution of
* dangerous functions.
*
* \return True (non-zero) if dangerous function execution is inhibited.
* \return False (zero) if dangerous function execution is allowed.
*/
static int thread_inhibits_escalations(void)
{
int *thread_inhibit_escalations;
thread_inhibit_escalations = ast_threadstorage_get(
&thread_inhibit_escalations_tl, sizeof(*thread_inhibit_escalations));
if (thread_inhibit_escalations == NULL) {
ast_log(LOG_ERROR, "Error checking thread's ability to run dangerous functions\n");
/* On error, assume that we are inhibiting */
return 1;
}
return *thread_inhibit_escalations;
}
/*!
* \brief Determines whether execution of a custom function's read function
* is allowed.
*
* \param acfptr Custom function to check
* \return True (non-zero) if reading is allowed.
* \return False (zero) if reading is not allowed.
*/
static int is_read_allowed(struct ast_custom_function *acfptr)
{
if (!acfptr) {
return 1;
}
if (!read_escalates(acfptr)) {
return 1;
}
if (!thread_inhibits_escalations()) {
return 1;
}
if (live_dangerously) {
/* Global setting overrides the thread's preference */
ast_debug(2, "Reading %s from a dangerous context\n",
acfptr->name);
return 1;
}
/* We have no reason to allow this function to execute */
return 0;
}
/*!
* \brief Determines whether execution of a custom function's write function
* is allowed.
*
* \param acfptr Custom function to check
* \return True (non-zero) if writing is allowed.
* \return False (zero) if writing is not allowed.
*/
static int is_write_allowed(struct ast_custom_function *acfptr)
{
if (!acfptr) {
return 1;
}
if (!write_escalates(acfptr)) {
return 1;
}
if (!thread_inhibits_escalations()) {
return 1;
}
if (live_dangerously) {
/* Global setting overrides the thread's preference */
ast_debug(2, "Writing %s from a dangerous context\n",
acfptr->name);
return 1;
}
/* We have no reason to allow this function to execute */
return 0;
}
int ast_func_read(struct ast_channel *chan, const char *function, char *workspace, size_t len)
{
char *copy = ast_strdupa(function);
char *args = func_args(copy);
struct ast_custom_function *acfptr = ast_custom_function_find(copy);
int res;
struct ast_module_user *u = NULL;
if (acfptr == NULL) {
ast_log(LOG_ERROR, "Function %s not registered\n", copy);
} else if (!acfptr->read && !acfptr->read2) {
ast_log(LOG_ERROR, "Function %s cannot be read\n", copy);
} else if (!is_read_allowed(acfptr)) {
ast_log(LOG_ERROR, "Dangerous function %s read blocked\n", copy);
} else if (acfptr->read) {
if (acfptr->mod) {
u = __ast_module_user_add(acfptr->mod, chan);
}
res = acfptr->read(chan, copy, args, workspace, len);
if (acfptr->mod && u) {
__ast_module_user_remove(acfptr->mod, u);
}
return res;
} else {
struct ast_str *str = ast_str_create(16);
if (acfptr->mod) {
u = __ast_module_user_add(acfptr->mod, chan);
}
res = acfptr->read2(chan, copy, args, &str, 0);
if (acfptr->mod && u) {
__ast_module_user_remove(acfptr->mod, u);
}
ast_copy_string(workspace, ast_str_buffer(str), len > ast_str_size(str) ? ast_str_size(str) : len);
ast_free(str);
return res;
}
return -1;
}
int ast_func_read2(struct ast_channel *chan, const char *function, struct ast_str **str, ssize_t maxlen)
{
char *copy = ast_strdupa(function);
char *args = func_args(copy);
struct ast_custom_function *acfptr = ast_custom_function_find(copy);
int res;
struct ast_module_user *u = NULL;
if (acfptr == NULL) {
ast_log(LOG_ERROR, "Function %s not registered\n", copy);
} else if (!acfptr->read && !acfptr->read2) {
ast_log(LOG_ERROR, "Function %s cannot be read\n", copy);
} else if (!is_read_allowed(acfptr)) {
ast_log(LOG_ERROR, "Dangerous function %s read blocked\n", copy);
} else {
if (acfptr->mod) {
u = __ast_module_user_add(acfptr->mod, chan);
}
ast_str_reset(*str);
if (acfptr->read2) {
/* ast_str enabled */
res = acfptr->read2(chan, copy, args, str, maxlen);
} else {
/* Legacy function pointer, allocate buffer for result */
int maxsize = ast_str_size(*str);
if (maxlen > -1) {
if (maxlen == 0) {
if (acfptr->read_max) {
maxsize = acfptr->read_max;
} else {
maxsize = VAR_BUF_SIZE;
}
} else {
maxsize = maxlen;
}
ast_str_make_space(str, maxsize);
}
res = acfptr->read(chan, copy, args, ast_str_buffer(*str), maxsize);
}
if (acfptr->mod && u) {
__ast_module_user_remove(acfptr->mod, u);
}
return res;
}
return -1;
}
int ast_func_write(struct ast_channel *chan, const char *function, const char *value)
{
char *copy = ast_strdupa(function);
char *args = func_args(copy);
struct ast_custom_function *acfptr = ast_custom_function_find(copy);
if (acfptr == NULL) {
ast_log(LOG_ERROR, "Function %s not registered\n", copy);
} else if (!acfptr->write) {
ast_log(LOG_ERROR, "Function %s cannot be written to\n", copy);
} else if (!is_write_allowed(acfptr)) {
ast_log(LOG_ERROR, "Dangerous function %s write blocked\n", copy);
} else {
int res;
struct ast_module_user *u = NULL;
if (acfptr->mod)
u = __ast_module_user_add(acfptr->mod, chan);
res = acfptr->write(chan, copy, args, value);
if (acfptr->mod && u)
__ast_module_user_remove(acfptr->mod, u);
return res;
}
return -1;
}
void ast_str_substitute_variables_full(struct ast_str **buf, ssize_t maxlen, struct ast_channel *c, struct varshead *headp, const char *templ, size_t *used)
{
/* Substitutes variables into buf, based on string templ */
char *cp4 = NULL;
const char *tmp, *whereweare;
int orig_size = 0;
int offset, offset2, isfunction;
const char *nextvar, *nextexp, *nextthing;
const char *vars, *vare;
char *finalvars;
int pos, brackets, needsub, len;
struct ast_str *substr1 = ast_str_create(16), *substr2 = NULL, *substr3 = ast_str_create(16);
ast_str_reset(*buf);
whereweare = tmp = templ;
while (!ast_strlen_zero(whereweare)) {
/* reset our buffer */
ast_str_reset(substr3);
/* Assume we're copying the whole remaining string */
pos = strlen(whereweare);
nextvar = NULL;
nextexp = NULL;
nextthing = strchr(whereweare, '$');
if (nextthing) {
switch (nextthing[1]) {
case '{':
nextvar = nextthing;
pos = nextvar - whereweare;
break;
case '[':
nextexp = nextthing;
pos = nextexp - whereweare;
break;
default:
pos = 1;
}
}
if (pos) {
/* Copy that many bytes */
ast_str_append_substr(buf, maxlen, whereweare, pos);
templ += pos;
whereweare += pos;
}
if (nextvar) {
/* We have a variable. Find the start and end, and determine
if we are going to have to recursively call ourselves on the
contents */
vars = vare = nextvar + 2;
brackets = 1;
needsub = 0;
/* Find the end of it */
while (brackets && *vare) {
if ((vare[0] == '$') && (vare[1] == '{')) {
needsub++;
} else if (vare[0] == '{') {
brackets++;
} else if (vare[0] == '}') {
brackets--;
} else if ((vare[0] == '$') && (vare[1] == '['))
needsub++;
vare++;
}
if (brackets)
ast_log(LOG_WARNING, "Error in extension logic (missing '}')\n");
len = vare - vars - 1;
/* Skip totally over variable string */
whereweare += (len + 3);
/* Store variable name (and truncate) */
ast_str_set_substr(&substr1, 0, vars, len);
ast_debug(5, "Evaluating '%s' (from '%s' len %d)\n", ast_str_buffer(substr1), vars, len);
/* Substitute if necessary */
if (needsub) {
size_t used;
if (!substr2) {
substr2 = ast_str_create(16);
}
ast_str_substitute_variables_full(&substr2, 0, c, headp, ast_str_buffer(substr1), &used);
finalvars = ast_str_buffer(substr2);
} else {
finalvars = ast_str_buffer(substr1);
}
parse_variable_name(finalvars, &offset, &offset2, &isfunction);
if (isfunction) {
/* Evaluate function */
if (c || !headp) {
cp4 = ast_func_read2(c, finalvars, &substr3, 0) ? NULL : ast_str_buffer(substr3);
} else {
struct varshead old;
struct ast_channel *bogus = ast_dummy_channel_alloc();
if (bogus) {
memcpy(&old, &bogus->varshead, sizeof(old));
memcpy(&bogus->varshead, headp, sizeof(bogus->varshead));
cp4 = ast_func_read2(c, finalvars, &substr3, 0) ? NULL : ast_str_buffer(substr3);
/* Don't deallocate the varshead that was passed in */
memcpy(&bogus->varshead, &old, sizeof(bogus->varshead));
ast_channel_unref(bogus);
} else {
ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n");
}
}
ast_debug(2, "Function result is '%s'\n", cp4 ? cp4 : "(null)");
} else {
/* Retrieve variable value */
ast_str_retrieve_variable(&substr3, 0, c, headp, finalvars);
cp4 = ast_str_buffer(substr3);
}
if (cp4) {
ast_str_substring(substr3, offset, offset2);
ast_str_append(buf, maxlen, "%s", ast_str_buffer(substr3));
}
} else if (nextexp) {
/* We have an expression. Find the start and end, and determine
if we are going to have to recursively call ourselves on the
contents */
vars = vare = nextexp + 2;
brackets = 1;
needsub = 0;
/* Find the end of it */
while (brackets && *vare) {
if ((vare[0] == '$') && (vare[1] == '[')) {
needsub++;
brackets++;
vare++;
} else if (vare[0] == '[') {
brackets++;
} else if (vare[0] == ']') {
brackets--;
} else if ((vare[0] == '$') && (vare[1] == '{')) {
needsub++;
vare++;
}
vare++;
}
if (brackets)
ast_log(LOG_WARNING, "Error in extension logic (missing ']')\n");
len = vare - vars - 1;
/* Skip totally over expression */
whereweare += (len + 3);
/* Store variable name (and truncate) */
ast_str_set_substr(&substr1, 0, vars, len);
/* Substitute if necessary */
if (needsub) {
size_t used;
if (!substr2) {
substr2 = ast_str_create(16);
}
ast_str_substitute_variables_full(&substr2, 0, c, headp, ast_str_buffer(substr1), &used);
finalvars = ast_str_buffer(substr2);
} else {
finalvars = ast_str_buffer(substr1);
}
if (ast_str_expr(&substr3, 0, c, finalvars)) {
ast_debug(2, "Expression result is '%s'\n", ast_str_buffer(substr3));
}
ast_str_append(buf, maxlen, "%s", ast_str_buffer(substr3));
}
}
*used = ast_str_strlen(*buf) - orig_size;
ast_free(substr1);
ast_free(substr2);
ast_free(substr3);
}
void ast_str_substitute_variables(struct ast_str **buf, ssize_t maxlen, struct ast_channel *chan, const char *templ)
{
size_t used;
ast_str_substitute_variables_full(buf, maxlen, chan, NULL, templ, &used);
}
void ast_str_substitute_variables_varshead(struct ast_str **buf, ssize_t maxlen, struct varshead *headp, const char *templ)
{
size_t used;
ast_str_substitute_variables_full(buf, maxlen, NULL, headp, templ, &used);
}
void pbx_substitute_variables_helper_full(struct ast_channel *c, struct varshead *headp, const char *cp1, char *cp2, int count, size_t *used)
{
/* Substitutes variables into cp2, based on string cp1, cp2 NO LONGER NEEDS TO BE ZEROED OUT!!!! */
char *cp4 = NULL;
const char *tmp, *whereweare, *orig_cp2 = cp2;
int length, offset, offset2, isfunction;
char *workspace = NULL;
char *ltmp = NULL, *var = NULL;
char *nextvar, *nextexp, *nextthing;
char *vars, *vare;
int pos, brackets, needsub, len;
*cp2 = 0; /* just in case nothing ends up there */
whereweare=tmp=cp1;
while (!ast_strlen_zero(whereweare) && count) {
/* Assume we're copying the whole remaining string */
pos = strlen(whereweare);
nextvar = NULL;
nextexp = NULL;
nextthing = strchr(whereweare, '$');
if (nextthing) {
switch (nextthing[1]) {
case '{':
nextvar = nextthing;
pos = nextvar - whereweare;
break;
case '[':
nextexp = nextthing;
pos = nextexp - whereweare;
break;
default:
pos = 1;
}
}
if (pos) {
/* Can't copy more than 'count' bytes */
if (pos > count)
pos = count;
/* Copy that many bytes */
memcpy(cp2, whereweare, pos);
count -= pos;
cp2 += pos;
whereweare += pos;
*cp2 = 0;
}
if (nextvar) {
/* We have a variable. Find the start and end, and determine
if we are going to have to recursively call ourselves on the
contents */
vars = vare = nextvar + 2;
brackets = 1;
needsub = 0;
/* Find the end of it */
while (brackets && *vare) {
if ((vare[0] == '$') && (vare[1] == '{')) {
needsub++;
} else if (vare[0] == '{') {
brackets++;
} else if (vare[0] == '}') {
brackets--;
} else if ((vare[0] == '$') && (vare[1] == '['))
needsub++;
vare++;
}
if (brackets)
ast_log(LOG_WARNING, "Error in extension logic (missing '}')\n");
len = vare - vars - 1;
/* Skip totally over variable string */
whereweare += (len + 3);
if (!var)
var = alloca(VAR_BUF_SIZE);
/* Store variable name (and truncate) */
ast_copy_string(var, vars, len + 1);
/* Substitute if necessary */
if (needsub) {
size_t used;
if (!ltmp)
ltmp = alloca(VAR_BUF_SIZE);
pbx_substitute_variables_helper_full(c, headp, var, ltmp, VAR_BUF_SIZE - 1, &used);
vars = ltmp;
} else {
vars = var;
}
if (!workspace)
workspace = alloca(VAR_BUF_SIZE);
workspace[0] = '\0';
parse_variable_name(vars, &offset, &offset2, &isfunction);
if (isfunction) {
/* Evaluate function */
if (c || !headp)
cp4 = ast_func_read(c, vars, workspace, VAR_BUF_SIZE) ? NULL : workspace;
else {
struct varshead old;
struct ast_channel *c = ast_dummy_channel_alloc();
if (c) {
memcpy(&old, &c->varshead, sizeof(old));
memcpy(&c->varshead, headp, sizeof(c->varshead));
cp4 = ast_func_read(c, vars, workspace, VAR_BUF_SIZE) ? NULL : workspace;
/* Don't deallocate the varshead that was passed in */
memcpy(&c->varshead, &old, sizeof(c->varshead));
c = ast_channel_unref(c);
} else {
ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n");
}
}
ast_debug(2, "Function result is '%s'\n", cp4 ? cp4 : "(null)");
} else {
/* Retrieve variable value */
pbx_retrieve_variable(c, vars, &cp4, workspace, VAR_BUF_SIZE, headp);
}
if (cp4) {
cp4 = substring(cp4, offset, offset2, workspace, VAR_BUF_SIZE);
length = strlen(cp4);
if (length > count)
length = count;
memcpy(cp2, cp4, length);
count -= length;
cp2 += length;
*cp2 = 0;
}
} else if (nextexp) {
/* We have an expression. Find the start and end, and determine
if we are going to have to recursively call ourselves on the
contents */
vars = vare = nextexp + 2;
brackets = 1;
needsub = 0;
/* Find the end of it */
while (brackets && *vare) {
if ((vare[0] == '$') && (vare[1] == '[')) {
needsub++;
brackets++;
vare++;
} else if (vare[0] == '[') {
brackets++;
} else if (vare[0] == ']') {
brackets--;
} else if ((vare[0] == '$') && (vare[1] == '{')) {
needsub++;
vare++;
}
vare++;
}
if (brackets)
ast_log(LOG_WARNING, "Error in extension logic (missing ']')\n");
len = vare - vars - 1;
/* Skip totally over expression */
whereweare += (len + 3);
if (!var)
var = alloca(VAR_BUF_SIZE);
/* Store variable name (and truncate) */
ast_copy_string(var, vars, len + 1);
/* Substitute if necessary */
if (needsub) {
size_t used;
if (!ltmp)
ltmp = alloca(VAR_BUF_SIZE);
pbx_substitute_variables_helper_full(c, headp, var, ltmp, VAR_BUF_SIZE - 1, &used);
vars = ltmp;
} else {
vars = var;
}
length = ast_expr(vars, cp2, count, c);
if (length) {
ast_debug(1, "Expression result is '%s'\n", cp2);
count -= length;
cp2 += length;
*cp2 = 0;
}
}
}
*used = cp2 - orig_cp2;
}
void pbx_substitute_variables_helper(struct ast_channel *c, const char *cp1, char *cp2, int count)
{
size_t used;
pbx_substitute_variables_helper_full(c, (c) ? &c->varshead : NULL, cp1, cp2, count, &used);
}
void pbx_substitute_variables_varshead(struct varshead *headp, const char *cp1, char *cp2, int count)
{
size_t used;
pbx_substitute_variables_helper_full(NULL, headp, cp1, cp2, count, &used);
}
static void pbx_substitute_variables(char *passdata, int datalen, struct ast_channel *c, struct ast_exten *e)
{
const char *tmp;
/* Nothing more to do */
if (!e->data) {
*passdata = '\0';
return;
}
/* No variables or expressions in e->data, so why scan it? */
if ((!(tmp = strchr(e->data, '$'))) || (!strstr(tmp, "${") && !strstr(tmp, "$["))) {
ast_copy_string(passdata, e->data, datalen);
return;
}
pbx_substitute_variables_helper(c, e->data, passdata, datalen - 1);
}
/*!
* \brief The return value depends on the action:
*
* E_MATCH, E_CANMATCH, E_MATCHMORE require a real match,
* and return 0 on failure, -1 on match;
* E_FINDLABEL maps the label to a priority, and returns
* the priority on success, ... XXX
* E_SPAWN, spawn an application,
*
* \retval 0 on success.
* \retval -1 on failure.
*
* \note The channel is auto-serviced in this function, because doing an extension
* match may block for a long time. For example, if the lookup has to use a network
* dialplan switch, such as DUNDi or IAX2, it may take a while. However, the channel
* auto-service code will queue up any important signalling frames to be processed
* after this is done.
*/
static int pbx_extension_helper(struct ast_channel *c, struct ast_context *con,
const char *context, const char *exten, int priority,
const char *label, const char *callerid, enum ext_match_t action, int *found, int combined_find_spawn)
{
struct ast_exten *e;
struct ast_app *app;
int res;
struct pbx_find_info q = { .stacklen = 0 }; /* the rest is reset in pbx_find_extension */
char passdata[EXT_DATA_SIZE];
int matching_action = (action == E_MATCH || action == E_CANMATCH || action == E_MATCHMORE);
ast_rdlock_contexts();
if (found)
*found = 0;
e = pbx_find_extension(c, con, &q, context, exten, priority, label, callerid, action);
if (e) {
if (found)
*found = 1;
if (matching_action) {
ast_unlock_contexts();
return -1; /* success, we found it */
} else if (action == E_FINDLABEL) { /* map the label to a priority */
res = e->priority;
ast_unlock_contexts();
return res; /* the priority we were looking for */
} else { /* spawn */
if (!e->cached_app)
e->cached_app = pbx_findapp(e->app);
app = e->cached_app;
ast_unlock_contexts();
if (!app) {
ast_log(LOG_WARNING, "No application '%s' for extension (%s, %s, %d)\n", e->app, context, exten, priority);
return -1;
}
if (c->context != context)
ast_copy_string(c->context, context, sizeof(c->context));
if (c->exten != exten)
ast_copy_string(c->exten, exten, sizeof(c->exten));
c->priority = priority;
pbx_substitute_variables(passdata, sizeof(passdata), c, e);
#ifdef CHANNEL_TRACE
ast_channel_trace_update(c);
#endif
ast_debug(1, "Launching '%s'\n", app->name);
if (VERBOSITY_ATLEAST(3)) {
char tmp[80], tmp2[80], tmp3[EXT_DATA_SIZE];
ast_verb(3, "Executing [%s@%s:%d] %s(\"%s\", \"%s\") %s\n",
exten, context, priority,
term_color(tmp, app->name, COLOR_BRCYAN, 0, sizeof(tmp)),
term_color(tmp2, c->name, COLOR_BRMAGENTA, 0, sizeof(tmp2)),
term_color(tmp3, passdata, COLOR_BRMAGENTA, 0, sizeof(tmp3)),
"in new stack");
}
manager_event(EVENT_FLAG_DIALPLAN, "Newexten",
"Channel: %s\r\n"
"Context: %s\r\n"
"Extension: %s\r\n"
"Priority: %d\r\n"
"Application: %s\r\n"
"AppData: %s\r\n"
"Uniqueid: %s\r\n",
c->name, c->context, c->exten, c->priority, app->name, passdata, c->uniqueid);
return pbx_exec(c, app, passdata); /* 0 on success, -1 on failure */
}
} else if (q.swo) { /* not found here, but in another switch */
if (found)
*found = 1;
ast_unlock_contexts();
if (matching_action) {
return -1;
} else {
if (!q.swo->exec) {
ast_log(LOG_WARNING, "No execution engine for switch %s\n", q.swo->name);
res = -1;
}
return q.swo->exec(c, q.foundcontext ? q.foundcontext : context, exten, priority, callerid, q.data);
}
} else { /* not found anywhere, see what happened */
ast_unlock_contexts();
/* Using S_OR here because Solaris doesn't like NULL being passed to ast_log */
switch (q.status) {
case STATUS_NO_CONTEXT:
if (!matching_action && !combined_find_spawn)
ast_log(LOG_NOTICE, "Cannot find extension context '%s'\n", S_OR(context, ""));
break;
case STATUS_NO_EXTENSION:
if (!matching_action && !combined_find_spawn)
ast_log(LOG_NOTICE, "Cannot find extension '%s' in context '%s'\n", exten, S_OR(context, ""));
break;
case STATUS_NO_PRIORITY:
if (!matching_action && !combined_find_spawn)
ast_log(LOG_NOTICE, "No such priority %d in extension '%s' in context '%s'\n", priority, exten, S_OR(context, ""));
break;
case STATUS_NO_LABEL:
if (context && !combined_find_spawn)
ast_log(LOG_NOTICE, "No such label '%s' in extension '%s' in context '%s'\n", label, exten, S_OR(context, ""));
break;
default:
ast_debug(1, "Shouldn't happen!\n");
}
return (matching_action) ? 0 : -1;
}
}
/*! \brief Find hint for given extension in context */
static struct ast_exten *ast_hint_extension_nolock(struct ast_channel *c, const char *context, const char *exten)
{
struct pbx_find_info q = { .stacklen = 0 }; /* the rest is set in pbx_find_context */
return pbx_find_extension(c, NULL, &q, context, exten, PRIORITY_HINT, NULL, "", E_MATCH);
}
static struct ast_exten *ast_hint_extension(struct ast_channel *c, const char *context, const char *exten)
{
struct ast_exten *e;
ast_rdlock_contexts();
e = ast_hint_extension_nolock(c, context, exten);
ast_unlock_contexts();
return e;
}
enum ast_extension_states ast_devstate_to_extenstate(enum ast_device_state devstate)
{
switch (devstate) {
case AST_DEVICE_ONHOLD:
return AST_EXTENSION_ONHOLD;
case AST_DEVICE_BUSY:
return AST_EXTENSION_BUSY;
case AST_DEVICE_UNKNOWN:
return AST_EXTENSION_NOT_INUSE;
case AST_DEVICE_UNAVAILABLE:
case AST_DEVICE_INVALID:
return AST_EXTENSION_UNAVAILABLE;
case AST_DEVICE_RINGINUSE:
return (AST_EXTENSION_INUSE | AST_EXTENSION_RINGING);
case AST_DEVICE_RINGING:
return AST_EXTENSION_RINGING;
case AST_DEVICE_INUSE:
return AST_EXTENSION_INUSE;
case AST_DEVICE_NOT_INUSE:
return AST_EXTENSION_NOT_INUSE;
case AST_DEVICE_TOTAL: /* not a device state, included for completeness */
break;
}
return AST_EXTENSION_NOT_INUSE;
}
static int ast_extension_state3(struct ast_str *hint_app)
{
char *cur;
char *rest;
struct ast_devstate_aggregate agg;
/* One or more devices separated with a & character */
rest = ast_str_buffer(hint_app);
ast_devstate_aggregate_init(&agg);
while ((cur = strsep(&rest, "&"))) {
ast_devstate_aggregate_add(&agg, ast_device_state(cur));
}
return ast_devstate_to_extenstate(ast_devstate_aggregate_result(&agg));
}
/*! \brief Check state of extension by using hints */
static int ast_extension_state2(struct ast_exten *e)
{
struct ast_str *hint_app = ast_str_thread_get(&extensionstate_buf, 32);
if (!e || !hint_app) {
return -1;
}
ast_str_set(&hint_app, 0, "%s", ast_get_extension_app(e));
return ast_extension_state3(hint_app);
}
/*! \brief Return extension_state as string */
const char *ast_extension_state2str(int extension_state)
{
int i;
for (i = 0; (i < ARRAY_LEN(extension_states)); i++) {
if (extension_states[i].extension_state == extension_state)
return extension_states[i].text;
}
return "Unknown";
}
/*! \brief Check extension state for an extension by using hint */
int ast_extension_state(struct ast_channel *c, const char *context, const char *exten)
{
struct ast_exten *e;
if (!(e = ast_hint_extension(c, context, exten))) { /* Do we have a hint for this extension ? */
return -1; /* No hint, return -1 */
}
if (e->exten[0] == '_') {
/* Create this hint on-the-fly */
ast_add_extension(e->parent->name, 0, exten, e->priority, e->label,
e->matchcid ? e->cidmatch : NULL, e->app, ast_strdup(e->data), ast_free_ptr,
e->registrar);
if (!(e = ast_hint_extension(c, context, exten))) {
/* Improbable, but not impossible */
return -1;
}
}
return ast_extension_state2(e); /* Check all devices in the hint */
}
static int handle_statechange(void *datap)
{
struct ast_hint *hint;
struct ast_str *hint_app;
struct statechange *sc = datap;
struct ao2_iterator i;
struct ao2_iterator cb_iter;
char context_name[AST_MAX_CONTEXT];
char exten_name[AST_MAX_EXTENSION];
hint_app = ast_str_create(1024);
if (!hint_app) {
ast_free(sc);
return -1;
}
ast_mutex_lock(&context_merge_lock);/* Hold off ast_merge_contexts_and_delete */
i = ao2_iterator_init(hints, 0);
for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) {
struct ast_state_cb *state_cb;
char *cur, *parse;
int state;
ao2_lock(hint);
if (!hint->exten) {
/* The extension has already been destroyed */
ao2_unlock(hint);
continue;
}
/* Does this hint monitor the device that changed state? */
ast_str_set(&hint_app, 0, "%s", ast_get_extension_app(hint->exten));
parse = ast_str_buffer(hint_app);
while ((cur = strsep(&parse, "&"))) {
if (!strcasecmp(cur, sc->dev)) {
/* The hint monitors the device. */
break;
}
}
if (!cur) {
/* The hint does not monitor the device. */
ao2_unlock(hint);
continue;
}
/*
* Save off strings in case the hint extension gets destroyed
* while we are notifying the watchers.
*/
ast_copy_string(context_name,
ast_get_context_name(ast_get_extension_context(hint->exten)),
sizeof(context_name));
ast_copy_string(exten_name, ast_get_extension_name(hint->exten),
sizeof(exten_name));
ast_str_set(&hint_app, 0, "%s", ast_get_extension_app(hint->exten));
ao2_unlock(hint);
/*
* Get device state for this hint.
*
* NOTE: We cannot hold any locks while determining the hint
* device state or notifying the watchers without causing a
* deadlock. (conlock, hints, and hint)
*/
state = ast_extension_state3(hint_app);
if (state == hint->laststate) {
continue;
}
/* Device state changed since last check - notify the watchers. */
hint->laststate = state; /* record we saw the change */
/* For general callbacks */
cb_iter = ao2_iterator_init(statecbs, 0);
for (; (state_cb = ao2_iterator_next(&cb_iter)); ao2_ref(state_cb, -1)) {
state_cb->change_cb(context_name, exten_name, state, state_cb->data);
}
ao2_iterator_destroy(&cb_iter);
/* For extension callbacks */
cb_iter = ao2_iterator_init(hint->callbacks, 0);
for (; (state_cb = ao2_iterator_next(&cb_iter)); ao2_ref(state_cb, -1)) {
state_cb->change_cb(context_name, exten_name, state, state_cb->data);
}
ao2_iterator_destroy(&cb_iter);
}
ao2_iterator_destroy(&i);
ast_mutex_unlock(&context_merge_lock);
ast_free(hint_app);
ast_free(sc);
return 0;
}
/*!
* \internal
* \brief Destroy the given state callback object.
*
* \param doomed State callback to destroy.
*
* \return Nothing
*/
static void destroy_state_cb(void *doomed)
{
struct ast_state_cb *state_cb = doomed;
if (state_cb->destroy_cb) {
state_cb->destroy_cb(state_cb->id, state_cb->data);
}
}
/*! \brief Add watcher for extension states with destructor */
int ast_extension_state_add_destroy(const char *context, const char *exten,
ast_state_cb_type change_cb, ast_state_cb_destroy_type destroy_cb, void *data)
{
struct ast_hint *hint;
struct ast_state_cb *state_cb;
struct ast_exten *e;
int id;
/* If there's no context and extension: add callback to statecbs list */
if (!context && !exten) {
/* Prevent multiple adds from adding the same change_cb at the same time. */
ao2_lock(statecbs);
/* Remove any existing change_cb. */
ao2_find(statecbs, change_cb, OBJ_UNLINK | OBJ_NODATA);
/* Now insert the change_cb */
if (!(state_cb = ao2_alloc(sizeof(*state_cb), destroy_state_cb))) {
ao2_unlock(statecbs);
return -1;
}
state_cb->id = 0;
state_cb->change_cb = change_cb;
state_cb->destroy_cb = destroy_cb;
state_cb->data = data;
ao2_link(statecbs, state_cb);
ao2_ref(state_cb, -1);
ao2_unlock(statecbs);
return 0;
}
if (!context || !exten)
return -1;
/* This callback type is for only one hint, so get the hint */
e = ast_hint_extension(NULL, context, exten);
if (!e) {
return -1;
}
/* If this is a pattern, dynamically create a new extension for this
* particular match. Note that this will only happen once for each
* individual extension, because the pattern will no longer match first.
*/
if (e->exten[0] == '_') {
ast_add_extension(e->parent->name, 0, exten, e->priority, e->label,
e->matchcid ? e->cidmatch : NULL, e->app, ast_strdup(e->data), ast_free_ptr,
e->registrar);
e = ast_hint_extension(NULL, context, exten);
if (!e || e->exten[0] == '_') {
return -1;
}
}
/* Find the hint in the hints container */
ao2_lock(hints);/* Locked to hold off ast_merge_contexts_and_delete */
hint = ao2_find(hints, e, 0);
if (!hint) {
ao2_unlock(hints);
return -1;
}
/* Now insert the callback in the callback list */
if (!(state_cb = ao2_alloc(sizeof(*state_cb), destroy_state_cb))) {
ao2_ref(hint, -1);
ao2_unlock(hints);
return -1;
}
do {
id = stateid++; /* Unique ID for this callback */
/* Do not allow id to ever be -1 or 0. */
} while (id == -1 || id == 0);
state_cb->id = id;
state_cb->change_cb = change_cb; /* Pointer to callback routine */
state_cb->destroy_cb = destroy_cb;
state_cb->data = data; /* Data for the callback */
ao2_link(hint->callbacks, state_cb);
ao2_ref(state_cb, -1);
ao2_ref(hint, -1);
ao2_unlock(hints);
return id;
}
/*! \brief Add watcher for extension states */
int ast_extension_state_add(const char *context, const char *exten,
ast_state_cb_type change_cb, void *data)
{
return ast_extension_state_add_destroy(context, exten, change_cb, NULL, data);
}
/*! \brief Remove a watcher from the callback list */
static int find_hint_by_cb_id(void *obj, void *arg, int flags)
{
struct ast_state_cb *state_cb;
const struct ast_hint *hint = obj;
int *id = arg;
if ((state_cb = ao2_find(hint->callbacks, id, 0))) {
ao2_ref(state_cb, -1);
return CMP_MATCH | CMP_STOP;
}
return 0;
}
/*! \brief ast_extension_state_del: Remove a watcher from the callback list */
int ast_extension_state_del(int id, ast_state_cb_type change_cb)
{
struct ast_state_cb *p_cur;
int ret = -1;
if (!id) { /* id == 0 is a callback without extension */
if (!change_cb) {
return ret;
}
p_cur = ao2_find(statecbs, change_cb, OBJ_UNLINK);
if (p_cur) {
ret = 0;
ao2_ref(p_cur, -1);
}
} else { /* callback with extension, find the callback based on ID */
struct ast_hint *hint;
ao2_lock(hints);/* Locked to hold off ast_merge_contexts_and_delete */
hint = ao2_callback(hints, 0, find_hint_by_cb_id, &id);
if (hint) {
p_cur = ao2_find(hint->callbacks, &id, OBJ_UNLINK);
if (p_cur) {
ret = 0;
ao2_ref(p_cur, -1);
}
ao2_ref(hint, -1);
}
ao2_unlock(hints);
}
return ret;
}
static int hint_id_cmp(void *obj, void *arg, int flags)
{
const struct ast_state_cb *cb = obj;
int *id = arg;
return (cb->id == *id) ? CMP_MATCH | CMP_STOP : 0;
}
/*!
* \internal
* \brief Destroy the given hint object.
*
* \param obj Hint to destroy.
*
* \return Nothing
*/
static void destroy_hint(void *obj)
{
struct ast_hint *hint = obj;
if (hint->callbacks) {
struct ast_state_cb *state_cb;
const char *context_name;
const char *exten_name;
if (hint->exten) {
context_name = ast_get_context_name(ast_get_extension_context(hint->exten));
exten_name = ast_get_extension_name(hint->exten);
hint->exten = NULL;
} else {
/* The extension has already been destroyed */
context_name = hint->context_name;
exten_name = hint->exten_name;
}
while ((state_cb = ao2_callback(hint->callbacks, OBJ_UNLINK, NULL, NULL))) {
/* Notify with -1 and remove all callbacks */
/* NOTE: The casts will not be needed for v1.10 and later */
state_cb->change_cb((char *) context_name, (char *) exten_name,
AST_EXTENSION_DEACTIVATED, state_cb->data);
ao2_ref(state_cb, -1);
}
ao2_ref(hint->callbacks, -1);
}
}
/*! \brief Remove hint from extension */
static int ast_remove_hint(struct ast_exten *e)
{
/* Cleanup the Notifys if hint is removed */
struct ast_hint *hint;
if (!e) {
return -1;
}
hint = ao2_find(hints, e, OBJ_UNLINK);
if (!hint) {
return -1;
}
/*
* The extension is being destroyed so we must save some
* information to notify that the extension is deactivated.
*/
ao2_lock(hint);
ast_copy_string(hint->context_name,
ast_get_context_name(ast_get_extension_context(hint->exten)),
sizeof(hint->context_name));
ast_copy_string(hint->exten_name, ast_get_extension_name(hint->exten),
sizeof(hint->exten_name));
hint->exten = NULL;
ao2_unlock(hint);
ao2_ref(hint, -1);
return 0;
}
/*! \brief Add hint to hint list, check initial extension state */
static int ast_add_hint(struct ast_exten *e)
{
struct ast_hint *hint_new;
struct ast_hint *hint_found;
if (!e) {
return -1;
}
/*
* We must create the hint we wish to add before determining if
* it is already in the hints container to avoid possible
* deadlock when getting the current extension state.
*/
hint_new = ao2_alloc(sizeof(*hint_new), destroy_hint);
if (!hint_new) {
return -1;
}
/* Initialize new hint. */
hint_new->callbacks = ao2_container_alloc(1, NULL, hint_id_cmp);
if (!hint_new->callbacks) {
ao2_ref(hint_new, -1);
return -1;
}
hint_new->exten = e;
hint_new->laststate = ast_extension_state2(e);
/* Prevent multiple add hints from adding the same hint at the same time. */
ao2_lock(hints);
/* Search if hint exists, do nothing */
hint_found = ao2_find(hints, e, 0);
if (hint_found) {
ao2_ref(hint_found, -1);
ao2_unlock(hints);
ao2_ref(hint_new, -1);
ast_debug(2, "HINTS: Not re-adding existing hint %s: %s\n",
ast_get_extension_name(e), ast_get_extension_app(e));
return -1;
}
/* Add new hint to the hints container */
ast_debug(2, "HINTS: Adding hint %s: %s\n",
ast_get_extension_name(e), ast_get_extension_app(e));
ao2_link(hints, hint_new);
ao2_unlock(hints);
ao2_ref(hint_new, -1);
return 0;
}
/*! \brief Change hint for an extension */
static int ast_change_hint(struct ast_exten *oe, struct ast_exten *ne)
{
struct ast_hint *hint;
if (!oe || !ne) {
return -1;
}
ao2_lock(hints);/* Locked to hold off others while we move the hint around. */
/*
* Unlink the hint from the hints container as the extension
* name (which is the hash value) could change.
*/
hint = ao2_find(hints, oe, OBJ_UNLINK);
if (!hint) {
ao2_unlock(hints);
return -1;
}
/* Update the hint and put it back in the hints container. */
ao2_lock(hint);
hint->exten = ne;
ao2_unlock(hint);
ao2_link(hints, hint);
ao2_unlock(hints);
ao2_ref(hint, -1);
return 0;
}
/*! \brief Get hint for channel */
int ast_get_hint(char *hint, int hintsize, char *name, int namesize, struct ast_channel *c, const char *context, const char *exten)
{
struct ast_exten *e = ast_hint_extension(c, context, exten);
if (e) {
if (hint)
ast_copy_string(hint, ast_get_extension_app(e), hintsize);
if (name) {
const char *tmp = ast_get_extension_app_data(e);
if (tmp)
ast_copy_string(name, tmp, namesize);
}
return -1;
}
return 0;
}
/*! \brief Get hint for channel */
int ast_str_get_hint(struct ast_str **hint, ssize_t hintsize, struct ast_str **name, ssize_t namesize, struct ast_channel *c, const char *context, const char *exten)
{
struct ast_exten *e = ast_hint_extension(c, context, exten);
if (!e) {
return 0;
}
if (hint) {
ast_str_set(hint, hintsize, "%s", ast_get_extension_app(e));
}
if (name) {
const char *tmp = ast_get_extension_app_data(e);
if (tmp) {
ast_str_set(name, namesize, "%s", tmp);
}
}
return -1;
}
int ast_exists_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
{
return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_MATCH, 0, 0);
}
int ast_findlabel_extension(struct ast_channel *c, const char *context, const char *exten, const char *label, const char *callerid)
{
return pbx_extension_helper(c, NULL, context, exten, 0, label, callerid, E_FINDLABEL, 0, 0);
}
int ast_findlabel_extension2(struct ast_channel *c, struct ast_context *con, const char *exten, const char *label, const char *callerid)
{
return pbx_extension_helper(c, con, NULL, exten, 0, label, callerid, E_FINDLABEL, 0, 0);
}
int ast_canmatch_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
{
return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_CANMATCH, 0, 0);
}
int ast_matchmore_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
{
return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_MATCHMORE, 0, 0);
}
int ast_spawn_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid, int *found, int combined_find_spawn)
{
return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_SPAWN, found, combined_find_spawn);
}
/*! helper function to set extension and priority */
static void set_ext_pri(struct ast_channel *c, const char *exten, int pri)
{
ast_channel_lock(c);
ast_copy_string(c->exten, exten, sizeof(c->exten));
c->priority = pri;
ast_channel_unlock(c);
}
/*!
* \brief collect digits from the channel into the buffer.
* \param c, buf, buflen, pos
* \param waittime is in milliseconds
* \retval 0 on timeout or done.
* \retval -1 on error.
*/
static int collect_digits(struct ast_channel *c, int waittime, char *buf, int buflen, int pos)
{
int digit;
buf[pos] = '\0'; /* make sure it is properly terminated */
while (ast_matchmore_extension(c, c->context, buf, 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
/* As long as we're willing to wait, and as long as it's not defined,
keep reading digits until we can't possibly get a right answer anymore. */
digit = ast_waitfordigit(c, waittime);
if (c->_softhangup & AST_SOFTHANGUP_ASYNCGOTO) {
ast_channel_clear_softhangup(c, AST_SOFTHANGUP_ASYNCGOTO);
} else {
if (!digit) /* No entry */
break;
if (digit < 0) /* Error, maybe a hangup */
return -1;
if (pos < buflen - 1) { /* XXX maybe error otherwise ? */
buf[pos++] = digit;
buf[pos] = '\0';
}
waittime = c->pbx->dtimeoutms;
}
}
return 0;
}
static enum ast_pbx_result __ast_pbx_run(struct ast_channel *c,
struct ast_pbx_args *args)
{
int found = 0; /* set if we find at least one match */
int res = 0;
int autoloopflag;
int error = 0; /* set an error conditions */
/* A little initial setup here */
if (c->pbx) {
ast_log(LOG_WARNING, "%s already has PBX structure??\n", c->name);
/* XXX and now what ? */
ast_free(c->pbx);
}
if (!(c->pbx = ast_calloc(1, sizeof(*c->pbx))))
return -1;
/* Set reasonable defaults */
c->pbx->rtimeoutms = 10000;
c->pbx->dtimeoutms = 5000;
autoloopflag = ast_test_flag(c, AST_FLAG_IN_AUTOLOOP); /* save value to restore at the end */
ast_set_flag(c, AST_FLAG_IN_AUTOLOOP);
/* Start by trying whatever the channel is set to */
if (!ast_exists_extension(c, c->context, c->exten, c->priority,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
/* If not successful fall back to 's' */
ast_verb(2, "Starting %s at %s,%s,%d failed so falling back to exten 's'\n", c->name, c->context, c->exten, c->priority);
/* XXX the original code used the existing priority in the call to
* ast_exists_extension(), and reset it to 1 afterwards.
* I believe the correct thing is to set it to 1 immediately.
*/
set_ext_pri(c, "s", 1);
if (!ast_exists_extension(c, c->context, c->exten, c->priority,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
/* JK02: And finally back to default if everything else failed */
ast_verb(2, "Starting %s at %s,%s,%d still failed so falling back to context 'default'\n", c->name, c->context, c->exten, c->priority);
ast_copy_string(c->context, "default", sizeof(c->context));
}
}
ast_channel_lock(c);
if (c->cdr) {
/* allow CDR variables that have been collected after channel was created to be visible during call */
ast_cdr_update(c);
}
ast_channel_unlock(c);
for (;;) {
char dst_exten[256]; /* buffer to accumulate digits */
int pos = 0; /* XXX should check bounds */
int digit = 0;
int invalid = 0;
int timeout = 0;
/* loop on priorities in this context/exten */
while (!(res = ast_spawn_extension(c, c->context, c->exten, c->priority,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL),
&found, 1))) {
if (!ast_check_hangup(c)) {
++c->priority;
continue;
}
/* Check softhangup flags. */
if (c->_softhangup & AST_SOFTHANGUP_ASYNCGOTO) {
ast_channel_clear_softhangup(c, AST_SOFTHANGUP_ASYNCGOTO);
continue;
}
if (c->_softhangup & AST_SOFTHANGUP_TIMEOUT) {
if (ast_exists_extension(c, c->context, "T", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
set_ext_pri(c, "T", 1);
/* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */
memset(&c->whentohangup, 0, sizeof(c->whentohangup));
ast_channel_clear_softhangup(c, AST_SOFTHANGUP_TIMEOUT);
continue;
} else if (ast_exists_extension(c, c->context, "e", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
raise_exception(c, "ABSOLUTETIMEOUT", 1);
/* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */
memset(&c->whentohangup, 0, sizeof(c->whentohangup));
ast_channel_clear_softhangup(c, AST_SOFTHANGUP_TIMEOUT);
continue;
}
/* Call timed out with no special extension to jump to. */
error = 1;
break;
}
ast_debug(1, "Extension %s, priority %d returned normally even though call was hung up\n",
c->exten, c->priority);
error = 1;
break;
} /* end while - from here on we can use 'break' to go out */
if (found && res) {
/* Something bad happened, or a hangup has been requested. */
if (strchr("0123456789ABCDEF*#", res)) {
ast_debug(1, "Oooh, got something to jump out with ('%c')!\n", res);
pos = 0;
dst_exten[pos++] = digit = res;
dst_exten[pos] = '\0';
} else if (res == AST_PBX_INCOMPLETE) {
ast_debug(1, "Spawn extension (%s,%s,%d) exited INCOMPLETE on '%s'\n", c->context, c->exten, c->priority, c->name);
ast_verb(2, "Spawn extension (%s, %s, %d) exited INCOMPLETE on '%s'\n", c->context, c->exten, c->priority, c->name);
/* Don't cycle on incomplete - this will happen if the only extension that matches is our "incomplete" extension */
if (!ast_matchmore_extension(c, c->context, c->exten, 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
invalid = 1;
} else {
ast_copy_string(dst_exten, c->exten, sizeof(dst_exten));
digit = 1;
pos = strlen(dst_exten);
}
} else {
ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
if ((res == AST_PBX_ERROR)
&& ast_exists_extension(c, c->context, "e", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
/* if we are already on the 'e' exten, don't jump to it again */
if (!strcmp(c->exten, "e")) {
ast_verb(2, "Spawn extension (%s, %s, %d) exited ERROR while already on 'e' exten on '%s'\n", c->context, c->exten, c->priority, c->name);
error = 1;
} else {
raise_exception(c, "ERROR", 1);
continue;
}
}
if (c->_softhangup & AST_SOFTHANGUP_ASYNCGOTO) {
ast_channel_clear_softhangup(c, AST_SOFTHANGUP_ASYNCGOTO);
continue;
}
if (c->_softhangup & AST_SOFTHANGUP_TIMEOUT) {
if (ast_exists_extension(c, c->context, "T", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
set_ext_pri(c, "T", 1);
/* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */
memset(&c->whentohangup, 0, sizeof(c->whentohangup));
ast_channel_clear_softhangup(c, AST_SOFTHANGUP_TIMEOUT);
continue;
} else if (ast_exists_extension(c, c->context, "e", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
raise_exception(c, "ABSOLUTETIMEOUT", 1);
/* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */
memset(&c->whentohangup, 0, sizeof(c->whentohangup));
ast_channel_clear_softhangup(c, AST_SOFTHANGUP_TIMEOUT);
continue;
}
/* Call timed out with no special extension to jump to. */
}
ast_channel_lock(c);
if (c->cdr) {
ast_cdr_update(c);
}
ast_channel_unlock(c);
error = 1;
break;
}
}
if (error)
break;
/*!\note
* We get here on a failure of some kind: non-existing extension or
* hangup. We have options, here. We can either catch the failure
* and continue, or we can drop out entirely. */
if (invalid
|| !ast_exists_extension(c, c->context, c->exten, 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
/*!\note
* If there is no match at priority 1, it is not a valid extension anymore.
* Try to continue at "i" (for invalid) or "e" (for exception) or exit if
* neither exist.
*/
if (ast_exists_extension(c, c->context, "i", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
ast_verb(3, "Sent into invalid extension '%s' in context '%s' on %s\n", c->exten, c->context, c->name);
pbx_builtin_setvar_helper(c, "INVALID_EXTEN", c->exten);
set_ext_pri(c, "i", 1);
} else if (ast_exists_extension(c, c->context, "e", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
raise_exception(c, "INVALID", 1);
} else {
ast_log(LOG_WARNING, "Channel '%s' sent into invalid extension '%s' in context '%s', but no invalid handler\n",
c->name, c->exten, c->context);
error = 1; /* we know what to do with it */
break;
}
} else if (c->_softhangup & AST_SOFTHANGUP_TIMEOUT) {
/* If we get this far with AST_SOFTHANGUP_TIMEOUT, then we know that the "T" extension is next. */
ast_channel_clear_softhangup(c, AST_SOFTHANGUP_TIMEOUT);
} else { /* keypress received, get more digits for a full extension */
int waittime = 0;
if (digit)
waittime = c->pbx->dtimeoutms;
else if (!autofallthrough)
waittime = c->pbx->rtimeoutms;
if (!waittime) {
const char *status = pbx_builtin_getvar_helper(c, "DIALSTATUS");
if (!status)
status = "UNKNOWN";
ast_verb(3, "Auto fallthrough, channel '%s' status is '%s'\n", c->name, status);
if (!strcasecmp(status, "CONGESTION"))
res = pbx_builtin_congestion(c, "10");
else if (!strcasecmp(status, "CHANUNAVAIL"))
res = pbx_builtin_congestion(c, "10");
else if (!strcasecmp(status, "BUSY"))
res = pbx_builtin_busy(c, "10");
error = 1; /* XXX disable message */
break; /* exit from the 'for' loop */
}
if (collect_digits(c, waittime, dst_exten, sizeof(dst_exten), pos))
break;
if (res == AST_PBX_INCOMPLETE && ast_strlen_zero(&dst_exten[pos]))
timeout = 1;
if (!timeout
&& ast_exists_extension(c, c->context, dst_exten, 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { /* Prepare the next cycle */
set_ext_pri(c, dst_exten, 1);
} else {
/* No such extension */
if (!timeout && !ast_strlen_zero(dst_exten)) {
/* An invalid extension */
if (ast_exists_extension(c, c->context, "i", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
ast_verb(3, "Invalid extension '%s' in context '%s' on %s\n", dst_exten, c->context, c->name);
pbx_builtin_setvar_helper(c, "INVALID_EXTEN", dst_exten);
set_ext_pri(c, "i", 1);
} else if (ast_exists_extension(c, c->context, "e", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
raise_exception(c, "INVALID", 1);
} else {
ast_log(LOG_WARNING,
"Invalid extension '%s', but no rule 'i' or 'e' in context '%s'\n",
dst_exten, c->context);
found = 1; /* XXX disable message */
break;
}
} else {
/* A simple timeout */
if (ast_exists_extension(c, c->context, "t", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
ast_verb(3, "Timeout on %s\n", c->name);
set_ext_pri(c, "t", 1);
} else if (ast_exists_extension(c, c->context, "e", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
raise_exception(c, "RESPONSETIMEOUT", 1);
} else {
ast_log(LOG_WARNING,
"Timeout, but no rule 't' or 'e' in context '%s'\n",
c->context);
found = 1; /* XXX disable message */
break;
}
}
}
ast_channel_lock(c);
if (c->cdr) {
ast_verb(2, "CDR updated on %s\n",c->name);
ast_cdr_update(c);
}
ast_channel_unlock(c);
}
}
if (!found && !error) {
ast_log(LOG_WARNING, "Don't know what to do with '%s'\n", c->name);
}
if (!args || !args->no_hangup_chan) {
ast_softhangup(c, AST_SOFTHANGUP_APPUNLOAD);
}
if ((!args || !args->no_hangup_chan)
&& !ast_test_flag(c, AST_FLAG_BRIDGE_HANGUP_RUN)
&& ast_exists_extension(c, c->context, "h", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
set_ext_pri(c, "h", 1);
if (c->cdr && ast_opt_end_cdr_before_h_exten) {
ast_cdr_end(c->cdr);
}
while ((res = ast_spawn_extension(c, c->context, c->exten, c->priority,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL),
&found, 1)) == 0) {
c->priority++;
}
if (found && res) {
/* Something bad happened, or a hangup has been requested. */
ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
}
}
ast_set2_flag(c, autoloopflag, AST_FLAG_IN_AUTOLOOP);
ast_clear_flag(c, AST_FLAG_BRIDGE_HANGUP_RUN); /* from one round to the next, make sure this gets cleared */
pbx_destroy(c->pbx);
c->pbx = NULL;
if (!args || !args->no_hangup_chan) {
ast_hangup(c);
}
return 0;
}
/*!
* \brief Increase call count for channel
* \retval 0 on success
* \retval non-zero if a configured limit (maxcalls, maxload, minmemfree) was reached
*/
static int increase_call_count(const struct ast_channel *c)
{
int failed = 0;
double curloadavg;
#if defined(HAVE_SYSINFO)
long curfreemem;
struct sysinfo sys_info;
#endif
ast_mutex_lock(&maxcalllock);
if (option_maxcalls) {
if (countcalls >= option_maxcalls) {
ast_log(LOG_WARNING, "Maximum call limit of %d calls exceeded by '%s'!\n", option_maxcalls, c->name);
failed = -1;
}
}
if (option_maxload) {
getloadavg(&curloadavg, 1);
if (curloadavg >= option_maxload) {
ast_log(LOG_WARNING, "Maximum loadavg limit of %f load exceeded by '%s' (currently %f)!\n", option_maxload, c->name, curloadavg);
failed = -1;
}
}
#if defined(HAVE_SYSINFO)
if (option_minmemfree) {
if (!sysinfo(&sys_info)) {
/* make sure that the free system memory is above the configured low watermark
* convert the amount of freeram from mem_units to MB */
curfreemem = sys_info.freeram * sys_info.mem_unit;
curfreemem /= 1024 * 1024;
if (curfreemem < option_minmemfree) {
ast_log(LOG_WARNING, "Available system memory (~%ldMB) is below the configured low watermark (%ldMB)\n", curfreemem, option_minmemfree);
failed = -1;
}
}
}
#endif
if (!failed) {
countcalls++;
totalcalls++;
}
ast_mutex_unlock(&maxcalllock);
return failed;
}
static void decrease_call_count(void)
{
ast_mutex_lock(&maxcalllock);
if (countcalls > 0)
countcalls--;
ast_mutex_unlock(&maxcalllock);
}
static void destroy_exten(struct ast_exten *e)
{
if (e->priority == PRIORITY_HINT)
ast_remove_hint(e);
if (e->peer_table)
ast_hashtab_destroy(e->peer_table,0);
if (e->peer_label_table)
ast_hashtab_destroy(e->peer_label_table, 0);
if (e->datad)
e->datad(e->data);
ast_free(e);
}
static void *pbx_thread(void *data)
{
/* Oh joyeous kernel, we're a new thread, with nothing to do but
answer this channel and get it going.
*/
/* NOTE:
The launcher of this function _MUST_ increment 'countcalls'
before invoking the function; it will be decremented when the
PBX has finished running on the channel
*/
struct ast_channel *c = data;
__ast_pbx_run(c, NULL);
decrease_call_count();
pthread_exit(NULL);
return NULL;
}
enum ast_pbx_result ast_pbx_start(struct ast_channel *c)
{
pthread_t t;
if (!c) {
ast_log(LOG_WARNING, "Asked to start thread on NULL channel?\n");
return AST_PBX_FAILED;
}
if (!ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
ast_log(LOG_WARNING, "PBX requires Asterisk to be fully booted\n");
return AST_PBX_FAILED;
}
if (increase_call_count(c))
return AST_PBX_CALL_LIMIT;
/* Start a new thread, and get something handling this channel. */
if (ast_pthread_create_detached(&t, NULL, pbx_thread, c)) {
ast_log(LOG_WARNING, "Failed to create new channel thread\n");
decrease_call_count();
return AST_PBX_FAILED;
}
return AST_PBX_SUCCESS;
}
enum ast_pbx_result ast_pbx_run_args(struct ast_channel *c, struct ast_pbx_args *args)
{
enum ast_pbx_result res = AST_PBX_SUCCESS;
if (!ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
ast_log(LOG_WARNING, "PBX requires Asterisk to be fully booted\n");
return AST_PBX_FAILED;
}
if (increase_call_count(c)) {
return AST_PBX_CALL_LIMIT;
}
res = __ast_pbx_run(c, args);
decrease_call_count();
return res;
}
enum ast_pbx_result ast_pbx_run(struct ast_channel *c)
{
return ast_pbx_run_args(c, NULL);
}
int ast_active_calls(void)
{
return countcalls;
}
int ast_processed_calls(void)
{
return totalcalls;
}
int pbx_set_autofallthrough(int newval)
{
int oldval = autofallthrough;
autofallthrough = newval;
return oldval;
}
int pbx_set_extenpatternmatchnew(int newval)
{
int oldval = extenpatternmatchnew;
extenpatternmatchnew = newval;
return oldval;
}
void pbx_set_overrideswitch(const char *newval)
{
if (overrideswitch) {
ast_free(overrideswitch);
}
if (!ast_strlen_zero(newval)) {
overrideswitch = ast_strdup(newval);
} else {
overrideswitch = NULL;
}
}
/*!
* \brief lookup for a context with a given name,
* \retval found context or NULL if not found.
*/
static struct ast_context *find_context(const char *context)
{
struct fake_context item;
ast_copy_string(item.name, context, sizeof(item.name));
return ast_hashtab_lookup(contexts_table, &item);
}
/*!
* \brief lookup for a context with a given name,
* \retval with conlock held if found.
* \retval NULL if not found.
*/
static struct ast_context *find_context_locked(const char *context)
{
struct ast_context *c;
struct fake_context item;
ast_copy_string(item.name, context, sizeof(item.name));
ast_rdlock_contexts();
c = ast_hashtab_lookup(contexts_table, &item);
if (!c) {
ast_unlock_contexts();
}
return c;
}
/*!
* \brief Remove included contexts.
* This function locks contexts list by &conlist, search for the right context
* structure, leave context list locked and call ast_context_remove_include2
* which removes include, unlock contexts list and return ...
*/
int ast_context_remove_include(const char *context, const char *include, const char *registrar)
{
int ret = -1;
struct ast_context *c;
c = find_context_locked(context);
if (c) {
/* found, remove include from this context ... */
ret = ast_context_remove_include2(c, include, registrar);
ast_unlock_contexts();
}
return ret;
}
/*!
* \brief Locks context, remove included contexts, unlocks context.
* When we call this function, &conlock lock must be locked, because when
* we giving *con argument, some process can remove/change this context
* and after that there can be segfault.
*
* \retval 0 on success.
* \retval -1 on failure.
*/
int ast_context_remove_include2(struct ast_context *con, const char *include, const char *registrar)
{
struct ast_include *i, *pi = NULL;
int ret = -1;
ast_wrlock_context(con);
/* find our include */
for (i = con->includes; i; pi = i, i = i->next) {
if (!strcmp(i->name, include) &&
(!registrar || !strcmp(i->registrar, registrar))) {
/* remove from list */
ast_verb(3, "Removing inclusion of context '%s' in context '%s; registrar=%s'\n", include, ast_get_context_name(con), registrar);
if (pi)
pi->next = i->next;
else
con->includes = i->next;
/* free include and return */
ast_destroy_timing(&(i->timing));
ast_free(i);
ret = 0;
break;
}
}
ast_unlock_context(con);
return ret;
}
/*!
* \note This function locks contexts list by &conlist, search for the rigt context
* structure, leave context list locked and call ast_context_remove_switch2
* which removes switch, unlock contexts list and return ...
*/
int ast_context_remove_switch(const char *context, const char *sw, const char *data, const char *registrar)
{
int ret = -1; /* default error return */
struct ast_context *c;
c = find_context_locked(context);
if (c) {
/* remove switch from this context ... */
ret = ast_context_remove_switch2(c, sw, data, registrar);
ast_unlock_contexts();
}
return ret;
}
/*!
* \brief This function locks given context, removes switch, unlock context and
* return.
* \note When we call this function, &conlock lock must be locked, because when
* we giving *con argument, some process can remove/change this context
* and after that there can be segfault.
*
*/
int ast_context_remove_switch2(struct ast_context *con, const char *sw, const char *data, const char *registrar)
{
struct ast_sw *i;
int ret = -1;
ast_wrlock_context(con);
/* walk switches */
AST_LIST_TRAVERSE_SAFE_BEGIN(&con->alts, i, list) {
if (!strcmp(i->name, sw) && !strcmp(i->data, data) &&
(!registrar || !strcmp(i->registrar, registrar))) {
/* found, remove from list */
ast_verb(3, "Removing switch '%s' from context '%s; registrar=%s'\n", sw, ast_get_context_name(con), registrar);
AST_LIST_REMOVE_CURRENT(list);
ast_free(i); /* free switch and return */
ret = 0;
break;
}
}
AST_LIST_TRAVERSE_SAFE_END;
ast_unlock_context(con);
return ret;
}
/*! \note This function will lock conlock. */
int ast_context_remove_extension(const char *context, const char *extension, int priority, const char *registrar)
{
return ast_context_remove_extension_callerid(context, extension, priority, NULL, 0, registrar);
}
int ast_context_remove_extension_callerid(const char *context, const char *extension, int priority, const char *callerid, int matchcallerid, const char *registrar)
{
int ret = -1; /* default error return */
struct ast_context *c;
c = find_context_locked(context);
if (c) { /* ... remove extension ... */
ret = ast_context_remove_extension_callerid2(c, extension, priority, callerid,
matchcallerid, registrar, 0);
ast_unlock_contexts();
}
return ret;
}
/*!
* \brief This functionc locks given context, search for the right extension and
* fires out all peer in this extensions with given priority. If priority
* is set to 0, all peers are removed. After that, unlock context and
* return.
* \note When do you want to call this function, make sure that &conlock is locked,
* because some process can handle with your *con context before you lock
* it.
*
*/
int ast_context_remove_extension2(struct ast_context *con, const char *extension, int priority, const char *registrar, int already_locked)
{
return ast_context_remove_extension_callerid2(con, extension, priority, NULL, 0, registrar, already_locked);
}
int ast_context_remove_extension_callerid2(struct ast_context *con, const char *extension, int priority, const char *callerid, int matchcallerid, const char *registrar, int already_locked)
{
struct ast_exten *exten, *prev_exten = NULL;
struct ast_exten *peer;
struct ast_exten ex, *exten2, *exten3;
char dummy_name[1024];
struct ast_exten *previous_peer = NULL;
struct ast_exten *next_peer = NULL;
int found = 0;
if (!already_locked)
ast_wrlock_context(con);
/* Handle this is in the new world */
/* FIXME For backwards compatibility, if callerid==NULL, then remove ALL
* peers, not just those matching the callerid. */
#ifdef NEED_DEBUG
ast_verb(3,"Removing %s/%s/%d%s%s from trees, registrar=%s\n", con->name, extension, priority, matchcallerid ? "/" : "", matchcallerid ? callerid : "", registrar);
#endif
#ifdef CONTEXT_DEBUG
check_contexts(__FILE__, __LINE__);
#endif
/* find this particular extension */
ex.exten = dummy_name;
ex.matchcid = matchcallerid && !ast_strlen_zero(callerid); /* don't say match if there's no callerid */
ex.cidmatch = callerid;
ast_copy_string(dummy_name, extension, sizeof(dummy_name));
exten = ast_hashtab_lookup(con->root_table, &ex);
if (exten) {
if (priority == 0) {
exten2 = ast_hashtab_remove_this_object(con->root_table, exten);
if (!exten2)
ast_log(LOG_ERROR,"Trying to delete the exten %s from context %s, but could not remove from the root_table\n", extension, con->name);
if (con->pattern_tree) {
struct match_char *x = add_exten_to_pattern_tree(con, exten, 1);
if (x->exten) { /* this test for safety purposes */
x->deleted = 1; /* with this marked as deleted, it will never show up in the scoreboard, and therefore never be found */
x->exten = 0; /* get rid of what will become a bad pointer */
} else {
ast_log(LOG_WARNING,"Trying to delete an exten from a context, but the pattern tree node returned isn't a full extension\n");
}
}
} else {
ex.priority = priority;
exten2 = ast_hashtab_lookup(exten->peer_table, &ex);
if (exten2) {
if (exten2->label) { /* if this exten has a label, remove that, too */
exten3 = ast_hashtab_remove_this_object(exten->peer_label_table,exten2);
if (!exten3)
ast_log(LOG_ERROR,"Did not remove this priority label (%d/%s) from the peer_label_table of context %s, extension %s!\n", priority, exten2->label, con->name, exten2->exten);
}
exten3 = ast_hashtab_remove_this_object(exten->peer_table, exten2);
if (!exten3)
ast_log(LOG_ERROR,"Did not remove this priority (%d) from the peer_table of context %s, extension %s!\n", priority, con->name, exten2->exten);
if (exten2 == exten && exten2->peer) {
exten2 = ast_hashtab_remove_this_object(con->root_table, exten);
ast_hashtab_insert_immediate(con->root_table, exten2->peer);
}
if (ast_hashtab_size(exten->peer_table) == 0) {
/* well, if the last priority of an exten is to be removed,
then, the extension is removed, too! */
exten3 = ast_hashtab_remove_this_object(con->root_table, exten);
if (!exten3)
ast_log(LOG_ERROR,"Did not remove this exten (%s) from the context root_table (%s) (priority %d)\n", exten->exten, con->name, priority);
if (con->pattern_tree) {
struct match_char *x = add_exten_to_pattern_tree(con, exten, 1);
if (x->exten) { /* this test for safety purposes */
x->deleted = 1; /* with this marked as deleted, it will never show up in the scoreboard, and therefore never be found */
x->exten = 0; /* get rid of what will become a bad pointer */
}
}
}
} else {
ast_log(LOG_ERROR,"Could not find priority %d of exten %s in context %s!\n",
priority, exten->exten, con->name);
}
}
} else {
/* hmmm? this exten is not in this pattern tree? */
ast_log(LOG_WARNING,"Cannot find extension %s in root_table in context %s\n",
extension, con->name);
}
#ifdef NEED_DEBUG
if (con->pattern_tree) {
ast_log(LOG_NOTICE,"match char tree after exten removal:\n");
log_match_char_tree(con->pattern_tree, " ");
}
#endif
/* scan the extension list to find first matching extension-registrar */
for (exten = con->root; exten; prev_exten = exten, exten = exten->next) {
if (!strcmp(exten->exten, extension) &&
(!registrar || !strcmp(exten->registrar, registrar)) &&
(!matchcallerid || (!ast_strlen_zero(callerid) && !ast_strlen_zero(exten->cidmatch) && !strcmp(exten->cidmatch, callerid)) || (ast_strlen_zero(callerid) && ast_strlen_zero(exten->cidmatch))))
break;
}
if (!exten) {
/* we can't find right extension */
if (!already_locked)
ast_unlock_context(con);
return -1;
}
/* scan the priority list to remove extension with exten->priority == priority */
for (peer = exten, next_peer = exten->peer ? exten->peer : exten->next;
peer && !strcmp(peer->exten, extension) && (!matchcallerid || (!ast_strlen_zero(callerid) && !ast_strlen_zero(peer->cidmatch) && !strcmp(peer->cidmatch,callerid)) || (ast_strlen_zero(callerid) && ast_strlen_zero(peer->cidmatch)));
peer = next_peer, next_peer = next_peer ? (next_peer->peer ? next_peer->peer : next_peer->next) : NULL) {
if ((priority == 0 || peer->priority == priority) &&
(!callerid || !matchcallerid || (matchcallerid && !strcmp(peer->cidmatch, callerid))) &&
(!registrar || !strcmp(peer->registrar, registrar) )) {
found = 1;
/* we are first priority extension? */
if (!previous_peer) {
/*
* We are first in the priority chain, so must update the extension chain.
* The next node is either the next priority or the next extension
*/
struct ast_exten *next_node = peer->peer ? peer->peer : peer->next;
if (peer->peer) {
/* move the peer_table and peer_label_table down to the next peer, if
it is there */
peer->peer->peer_table = peer->peer_table;
peer->peer->peer_label_table = peer->peer_label_table;
peer->peer_table = NULL;
peer->peer_label_table = NULL;
}
if (!prev_exten) { /* change the root... */
con->root = next_node;
} else {
prev_exten->next = next_node; /* unlink */
}
if (peer->peer) { /* update the new head of the pri list */
peer->peer->next = peer->next;
}
} else { /* easy, we are not first priority in extension */
previous_peer->peer = peer->peer;
}
/* now, free whole priority extension */
destroy_exten(peer);
} else {
previous_peer = peer;
}
}
if (!already_locked)
ast_unlock_context(con);
return found ? 0 : -1;
}
/*!
* \note This function locks contexts list by &conlist, searches for the right context
* structure, and locks the macrolock mutex in that context.
* macrolock is used to limit a macro to be executed by one call at a time.
*/
int ast_context_lockmacro(const char *context)
{
struct ast_context *c;
int ret = -1;
c = find_context_locked(context);
if (c) {
ast_unlock_contexts();
/* if we found context, lock macrolock */
ret = ast_mutex_lock(&c->macrolock);
}
return ret;
}
/*!
* \note This function locks contexts list by &conlist, searches for the right context
* structure, and unlocks the macrolock mutex in that context.
* macrolock is used to limit a macro to be executed by one call at a time.
*/
int ast_context_unlockmacro(const char *context)
{
struct ast_context *c;
int ret = -1;
c = find_context_locked(context);
if (c) {
ast_unlock_contexts();
/* if we found context, unlock macrolock */
ret = ast_mutex_unlock(&c->macrolock);
}
return ret;
}
/*! \brief Dynamically register a new dial plan application */
int ast_register_application2(const char *app, int (*execute)(struct ast_channel *, const char *), const char *synopsis, const char *description, void *mod)
{
struct ast_app *tmp, *cur = NULL;
char tmps[80];
int length, res;
#ifdef AST_XML_DOCS
char *tmpxml;
#endif
AST_RWLIST_WRLOCK(&apps);
AST_RWLIST_TRAVERSE(&apps, tmp, list) {
if (!(res = strcasecmp(app, tmp->name))) {
ast_log(LOG_WARNING, "Already have an application '%s'\n", app);
AST_RWLIST_UNLOCK(&apps);
return -1;
} else if (res < 0)
break;
}
length = sizeof(*tmp) + strlen(app) + 1;
if (!(tmp = ast_calloc(1, length))) {
AST_RWLIST_UNLOCK(&apps);
return -1;
}
if (ast_string_field_init(tmp, 128)) {
AST_RWLIST_UNLOCK(&apps);
ast_free(tmp);
return -1;
}
strcpy(tmp->name, app);
tmp->execute = execute;
tmp->module = mod;
#ifdef AST_XML_DOCS
/* Try to lookup the docs in our XML documentation database */
if (ast_strlen_zero(synopsis) && ast_strlen_zero(description)) {
/* load synopsis */
tmpxml = ast_xmldoc_build_synopsis("application", app, ast_module_name(tmp->module));
ast_string_field_set(tmp, synopsis, tmpxml);
ast_free(tmpxml);
/* load description */
tmpxml = ast_xmldoc_build_description("application", app, ast_module_name(tmp->module));
ast_string_field_set(tmp, description, tmpxml);
ast_free(tmpxml);
/* load syntax */
tmpxml = ast_xmldoc_build_syntax("application", app, ast_module_name(tmp->module));
ast_string_field_set(tmp, syntax, tmpxml);
ast_free(tmpxml);
/* load arguments */
tmpxml = ast_xmldoc_build_arguments("application", app, ast_module_name(tmp->module));
ast_string_field_set(tmp, arguments, tmpxml);
ast_free(tmpxml);
/* load seealso */
tmpxml = ast_xmldoc_build_seealso("application", app, ast_module_name(tmp->module));
ast_string_field_set(tmp, seealso, tmpxml);
ast_free(tmpxml);
tmp->docsrc = AST_XML_DOC;
} else {
#endif
ast_string_field_set(tmp, synopsis, synopsis);
ast_string_field_set(tmp, description, description);
#ifdef AST_XML_DOCS
tmp->docsrc = AST_STATIC_DOC;
}
#endif
/* Store in alphabetical order */
AST_RWLIST_TRAVERSE_SAFE_BEGIN(&apps, cur, list) {
if (strcasecmp(tmp->name, cur->name) < 0) {
AST_RWLIST_INSERT_BEFORE_CURRENT(tmp, list);
break;
}
}
AST_RWLIST_TRAVERSE_SAFE_END;
if (!cur)
AST_RWLIST_INSERT_TAIL(&apps, tmp, list);
ast_verb(2, "Registered application '%s'\n", term_color(tmps, tmp->name, COLOR_BRCYAN, 0, sizeof(tmps)));
AST_RWLIST_UNLOCK(&apps);
return 0;
}
/*
* Append to the list. We don't have a tail pointer because we need
* to scan the list anyways to check for duplicates during insertion.
*/
int ast_register_switch(struct ast_switch *sw)
{
struct ast_switch *tmp;
AST_RWLIST_WRLOCK(&switches);
AST_RWLIST_TRAVERSE(&switches, tmp, list) {
if (!strcasecmp(tmp->name, sw->name)) {
AST_RWLIST_UNLOCK(&switches);
ast_log(LOG_WARNING, "Switch '%s' already found\n", sw->name);
return -1;
}
}
AST_RWLIST_INSERT_TAIL(&switches, sw, list);
AST_RWLIST_UNLOCK(&switches);
return 0;
}
void ast_unregister_switch(struct ast_switch *sw)
{
AST_RWLIST_WRLOCK(&switches);
AST_RWLIST_REMOVE(&switches, sw, list);
AST_RWLIST_UNLOCK(&switches);
}
/*
* Help for CLI commands ...
*/
static void print_app_docs(struct ast_app *aa, int fd)
{
/* Maximum number of characters added by terminal coloring is 22 */
char infotitle[64 + AST_MAX_APP + 22], syntitle[40], destitle[40], stxtitle[40], argtitle[40];
char seealsotitle[40];
char info[64 + AST_MAX_APP], *synopsis = NULL, *description = NULL, *syntax = NULL, *arguments = NULL;
char *seealso = NULL;
int syntax_size, synopsis_size, description_size, arguments_size, seealso_size;
snprintf(info, sizeof(info), "\n -= Info about application '%s' =- \n\n", aa->name);
term_color(infotitle, info, COLOR_MAGENTA, 0, sizeof(infotitle));
term_color(syntitle, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
term_color(destitle, "[Description]\n", COLOR_MAGENTA, 0, 40);
term_color(stxtitle, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
term_color(argtitle, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
term_color(seealsotitle, "[See Also]\n", COLOR_MAGENTA, 0, 40);
#ifdef AST_XML_DOCS
if (aa->docsrc == AST_XML_DOC) {
description = ast_xmldoc_printable(S_OR(aa->description, "Not available"), 1);
arguments = ast_xmldoc_printable(S_OR(aa->arguments, "Not available"), 1);
synopsis = ast_xmldoc_printable(S_OR(aa->synopsis, "Not available"), 1);
seealso = ast_xmldoc_printable(S_OR(aa->seealso, "Not available"), 1);
if (!synopsis || !description || !arguments || !seealso) {
goto return_cleanup;
}
} else
#endif
{
synopsis_size = strlen(S_OR(aa->synopsis, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
synopsis = ast_malloc(synopsis_size);
description_size = strlen(S_OR(aa->description, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
description = ast_malloc(description_size);
arguments_size = strlen(S_OR(aa->arguments, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
arguments = ast_malloc(arguments_size);
seealso_size = strlen(S_OR(aa->seealso, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
seealso = ast_malloc(seealso_size);
if (!synopsis || !description || !arguments || !seealso) {
goto return_cleanup;
}
term_color(synopsis, S_OR(aa->synopsis, "Not available"), COLOR_CYAN, 0, synopsis_size);
term_color(description, S_OR(aa->description, "Not available"), COLOR_CYAN, 0, description_size);
term_color(arguments, S_OR(aa->arguments, "Not available"), COLOR_CYAN, 0, arguments_size);
term_color(seealso, S_OR(aa->seealso, "Not available"), COLOR_CYAN, 0, seealso_size);
}
/* Handle the syntax the same for both XML and raw docs */
syntax_size = strlen(S_OR(aa->syntax, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
if (!(syntax = ast_malloc(syntax_size))) {
goto return_cleanup;
}
term_color(syntax, S_OR(aa->syntax, "Not available"), COLOR_CYAN, 0, syntax_size);
ast_cli(fd, "%s%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n",
infotitle, syntitle, synopsis, destitle, description,
stxtitle, syntax, argtitle, arguments, seealsotitle, seealso);
return_cleanup:
ast_free(description);
ast_free(arguments);
ast_free(synopsis);
ast_free(seealso);
ast_free(syntax);
}
/*
* \brief 'show application' CLI command implementation function...
*/
static char *handle_show_application(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_app *aa;
int app, no_registered_app = 1;
switch (cmd) {
case CLI_INIT:
e->command = "core show application";
e->usage =
"Usage: core show application <application> [<application> [<application> [...]]]\n"
" Describes a particular application.\n";
return NULL;
case CLI_GENERATE:
/*
* There is a possibility to show informations about more than one
* application at one time. You can type 'show application Dial Echo' and
* you will see informations about these two applications ...
*/
return ast_complete_applications(a->line, a->word, a->n);
}
if (a->argc < 4) {
return CLI_SHOWUSAGE;
}
AST_RWLIST_RDLOCK(&apps);
AST_RWLIST_TRAVERSE(&apps, aa, list) {
/* Check for each app that was supplied as an argument */
for (app = 3; app < a->argc; app++) {
if (strcasecmp(aa->name, a->argv[app])) {
continue;
}
/* We found it! */
no_registered_app = 0;
print_app_docs(aa, a->fd);
}
}
AST_RWLIST_UNLOCK(&apps);
/* we found at least one app? no? */
if (no_registered_app) {
ast_cli(a->fd, "Your application(s) is (are) not registered\n");
return CLI_FAILURE;
}
return CLI_SUCCESS;
}
/*! \brief handle_show_hints: CLI support for listing registered dial plan hints */
static char *handle_show_hints(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_hint *hint;
int num = 0;
int watchers;
struct ao2_iterator i;
switch (cmd) {
case CLI_INIT:
e->command = "core show hints";
e->usage =
"Usage: core show hints\n"
" List registered hints\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (ao2_container_count(hints) == 0) {
ast_cli(a->fd, "There are no registered dialplan hints\n");
return CLI_SUCCESS;
}
/* ... we have hints ... */
ast_cli(a->fd, "\n -= Registered Asterisk Dial Plan Hints =-\n");
i = ao2_iterator_init(hints, 0);
for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) {
ao2_lock(hint);
if (!hint->exten) {
/* The extension has already been destroyed */
ao2_unlock(hint);
continue;
}
watchers = ao2_container_count(hint->callbacks);
ast_cli(a->fd, " %20s@%-20.20s: %-20.20s State:%-15.15s Watchers %2d\n",
ast_get_extension_name(hint->exten),
ast_get_context_name(ast_get_extension_context(hint->exten)),
ast_get_extension_app(hint->exten),
ast_extension_state2str(hint->laststate), watchers);
ao2_unlock(hint);
num++;
}
ao2_iterator_destroy(&i);
ast_cli(a->fd, "----------------\n");
ast_cli(a->fd, "- %d hints registered\n", num);
return CLI_SUCCESS;
}
/*! \brief autocomplete for CLI command 'core show hint' */
static char *complete_core_show_hint(const char *line, const char *word, int pos, int state)
{
struct ast_hint *hint;
char *ret = NULL;
int which = 0;
int wordlen;
struct ao2_iterator i;
if (pos != 3)
return NULL;
wordlen = strlen(word);
/* walk through all hints */
i = ao2_iterator_init(hints, 0);
for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) {
ao2_lock(hint);
if (!hint->exten) {
/* The extension has already been destroyed */
ao2_unlock(hint);
continue;
}
if (!strncasecmp(word, ast_get_extension_name(hint->exten), wordlen) && ++which > state) {
ret = ast_strdup(ast_get_extension_name(hint->exten));
ao2_unlock(hint);
ao2_ref(hint, -1);
break;
}
ao2_unlock(hint);
}
ao2_iterator_destroy(&i);
return ret;
}
/*! \brief handle_show_hint: CLI support for listing registered dial plan hint */
static char *handle_show_hint(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_hint *hint;
int watchers;
int num = 0, extenlen;
struct ao2_iterator i;
switch (cmd) {
case CLI_INIT:
e->command = "core show hint";
e->usage =
"Usage: core show hint <exten>\n"
" List registered hint\n";
return NULL;
case CLI_GENERATE:
return complete_core_show_hint(a->line, a->word, a->pos, a->n);
}
if (a->argc < 4)
return CLI_SHOWUSAGE;
if (ao2_container_count(hints) == 0) {
ast_cli(a->fd, "There are no registered dialplan hints\n");
return CLI_SUCCESS;
}
extenlen = strlen(a->argv[3]);
i = ao2_iterator_init(hints, 0);
for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) {
ao2_lock(hint);
if (!hint->exten) {
/* The extension has already been destroyed */
ao2_unlock(hint);
continue;
}
if (!strncasecmp(ast_get_extension_name(hint->exten), a->argv[3], extenlen)) {
watchers = ao2_container_count(hint->callbacks);
ast_cli(a->fd, " %20s@%-20.20s: %-20.20s State:%-15.15s Watchers %2d\n",
ast_get_extension_name(hint->exten),
ast_get_context_name(ast_get_extension_context(hint->exten)),
ast_get_extension_app(hint->exten),
ast_extension_state2str(hint->laststate), watchers);
num++;
}
ao2_unlock(hint);
}
ao2_iterator_destroy(&i);
if (!num)
ast_cli(a->fd, "No hints matching extension %s\n", a->argv[3]);
else
ast_cli(a->fd, "%d hint%s matching extension %s\n", num, (num!=1 ? "s":""), a->argv[3]);
return CLI_SUCCESS;
}
/*! \brief handle_show_switches: CLI support for listing registered dial plan switches */
static char *handle_show_switches(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_switch *sw;
switch (cmd) {
case CLI_INIT:
e->command = "core show switches";
e->usage =
"Usage: core show switches\n"
" List registered switches\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
AST_RWLIST_RDLOCK(&switches);
if (AST_RWLIST_EMPTY(&switches)) {
AST_RWLIST_UNLOCK(&switches);
ast_cli(a->fd, "There are no registered alternative switches\n");
return CLI_SUCCESS;
}
ast_cli(a->fd, "\n -= Registered Asterisk Alternative Switches =-\n");
AST_RWLIST_TRAVERSE(&switches, sw, list)
ast_cli(a->fd, "%s: %s\n", sw->name, sw->description);
AST_RWLIST_UNLOCK(&switches);
return CLI_SUCCESS;
}
static char *handle_show_applications(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_app *aa;
int like = 0, describing = 0;
int total_match = 0; /* Number of matches in like clause */
int total_apps = 0; /* Number of apps registered */
static const char * const choices[] = { "like", "describing", NULL };
switch (cmd) {
case CLI_INIT:
e->command = "core show applications [like|describing]";
e->usage =
"Usage: core show applications [{like|describing} <text>]\n"
" List applications which are currently available.\n"
" If 'like', <text> will be a substring of the app name\n"
" If 'describing', <text> will be a substring of the description\n";
return NULL;
case CLI_GENERATE:
return (a->pos != 3) ? NULL : ast_cli_complete(a->word, choices, a->n);
}
AST_RWLIST_RDLOCK(&apps);
if (AST_RWLIST_EMPTY(&apps)) {
ast_cli(a->fd, "There are no registered applications\n");
AST_RWLIST_UNLOCK(&apps);
return CLI_SUCCESS;
}
/* core list applications like <keyword> */
if ((a->argc == 5) && (!strcmp(a->argv[3], "like"))) {
like = 1;
} else if ((a->argc > 4) && (!strcmp(a->argv[3], "describing"))) {
describing = 1;
}
/* core list applications describing <keyword1> [<keyword2>] [...] */
if ((!like) && (!describing)) {
ast_cli(a->fd, " -= Registered Asterisk Applications =-\n");
} else {
ast_cli(a->fd, " -= Matching Asterisk Applications =-\n");
}
AST_RWLIST_TRAVERSE(&apps, aa, list) {
int printapp = 0;
total_apps++;
if (like) {
if (strcasestr(aa->name, a->argv[4])) {
printapp = 1;
total_match++;
}
} else if (describing) {
if (aa->description) {
/* Match all words on command line */
int i;
printapp = 1;
for (i = 4; i < a->argc; i++) {
if (!strcasestr(aa->description, a->argv[i])) {
printapp = 0;
} else {
total_match++;
}
}
}
} else {
printapp = 1;
}
if (printapp) {
ast_cli(a->fd," %20s: %s\n", aa->name, aa->synopsis ? aa->synopsis : "<Synopsis not available>");
}
}
if ((!like) && (!describing)) {
ast_cli(a->fd, " -= %d Applications Registered =-\n",total_apps);
} else {
ast_cli(a->fd, " -= %d Applications Matching =-\n",total_match);
}
AST_RWLIST_UNLOCK(&apps);
return CLI_SUCCESS;
}
/*
* 'show dialplan' CLI command implementation functions ...
*/
static char *complete_show_dialplan_context(const char *line, const char *word, int pos,
int state)
{
struct ast_context *c = NULL;
char *ret = NULL;
int which = 0;
int wordlen;
/* we are do completion of [exten@]context on second position only */
if (pos != 2)
return NULL;
ast_rdlock_contexts();
wordlen = strlen(word);
/* walk through all contexts and return the n-th match */
while ( (c = ast_walk_contexts(c)) ) {
if (!strncasecmp(word, ast_get_context_name(c), wordlen) && ++which > state) {
ret = ast_strdup(ast_get_context_name(c));
break;
}
}
ast_unlock_contexts();
return ret;
}
/*! \brief Counters for the show dialplan manager command */
struct dialplan_counters {
int total_items;
int total_context;
int total_exten;
int total_prio;
int context_existence;
int extension_existence;
};
/*! \brief helper function to print an extension */
static void print_ext(struct ast_exten *e, char * buf, int buflen)
{
int prio = ast_get_extension_priority(e);
if (prio == PRIORITY_HINT) {
snprintf(buf, buflen, "hint: %s",
ast_get_extension_app(e));
} else {
snprintf(buf, buflen, "%d. %s(%s)",
prio, ast_get_extension_app(e),
(!ast_strlen_zero(ast_get_extension_app_data(e)) ? (char *)ast_get_extension_app_data(e) : ""));
}
}
/* XXX not verified */
static int show_dialplan_helper(int fd, const char *context, const char *exten, struct dialplan_counters *dpc, struct ast_include *rinclude, int includecount, const char *includes[])
{
struct ast_context *c = NULL;
int res = 0, old_total_exten = dpc->total_exten;
ast_rdlock_contexts();
/* walk all contexts ... */
while ( (c = ast_walk_contexts(c)) ) {
struct ast_exten *e;
struct ast_include *i;
struct ast_ignorepat *ip;
char buf[256], buf2[256];
int context_info_printed = 0;
if (context && strcmp(ast_get_context_name(c), context))
continue; /* skip this one, name doesn't match */
dpc->context_existence = 1;
ast_rdlock_context(c);
/* are we looking for exten too? if yes, we print context
* only if we find our extension.
* Otherwise print context even if empty ?
* XXX i am not sure how the rinclude is handled.
* I think it ought to go inside.
*/
if (!exten) {
dpc->total_context++;
ast_cli(fd, "[ Context '%s' created by '%s' ]\n",
ast_get_context_name(c), ast_get_context_registrar(c));
context_info_printed = 1;
}
/* walk extensions ... */
e = NULL;
while ( (e = ast_walk_context_extensions(c, e)) ) {
struct ast_exten *p;
if (exten && !ast_extension_match(ast_get_extension_name(e), exten))
continue; /* skip, extension match failed */
dpc->extension_existence = 1;
/* may we print context info? */
if (!context_info_printed) {
dpc->total_context++;
if (rinclude) { /* TODO Print more info about rinclude */
ast_cli(fd, "[ Included context '%s' created by '%s' ]\n",
ast_get_context_name(c), ast_get_context_registrar(c));
} else {
ast_cli(fd, "[ Context '%s' created by '%s' ]\n",
ast_get_context_name(c), ast_get_context_registrar(c));
}
context_info_printed = 1;
}
dpc->total_prio++;
/* write extension name and first peer */
if (e->matchcid)
snprintf(buf, sizeof(buf), "'%s' (CID match '%s') => ", ast_get_extension_name(e), e->cidmatch);
else
snprintf(buf, sizeof(buf), "'%s' =>", ast_get_extension_name(e));
print_ext(e, buf2, sizeof(buf2));
ast_cli(fd, " %-17s %-45s [%s]\n", buf, buf2,
ast_get_extension_registrar(e));
dpc->total_exten++;
/* walk next extension peers */
p = e; /* skip the first one, we already got it */
while ( (p = ast_walk_extension_priorities(e, p)) ) {
const char *el = ast_get_extension_label(p);
dpc->total_prio++;
if (el)
snprintf(buf, sizeof(buf), " [%s]", el);
else
buf[0] = '\0';
print_ext(p, buf2, sizeof(buf2));
ast_cli(fd," %-17s %-45s [%s]\n", buf, buf2,
ast_get_extension_registrar(p));
}
}
/* walk included and write info ... */
i = NULL;
while ( (i = ast_walk_context_includes(c, i)) ) {
snprintf(buf, sizeof(buf), "'%s'", ast_get_include_name(i));
if (exten) {
/* Check all includes for the requested extension */
if (includecount >= AST_PBX_MAX_STACK) {
ast_log(LOG_WARNING, "Maximum include depth exceeded!\n");
} else {
int dupe = 0;
int x;
for (x = 0; x < includecount; x++) {
if (!strcasecmp(includes[x], ast_get_include_name(i))) {
dupe++;
break;
}
}
if (!dupe) {
includes[includecount] = ast_get_include_name(i);
show_dialplan_helper(fd, ast_get_include_name(i), exten, dpc, i, includecount + 1, includes);
} else {
ast_log(LOG_WARNING, "Avoiding circular include of %s within %s\n", ast_get_include_name(i), context);
}
}
} else {
ast_cli(fd, " Include => %-45s [%s]\n",
buf, ast_get_include_registrar(i));
}
}
/* walk ignore patterns and write info ... */
ip = NULL;
while ( (ip = ast_walk_context_ignorepats(c, ip)) ) {
const char *ipname = ast_get_ignorepat_name(ip);
char ignorepat[AST_MAX_EXTENSION];
snprintf(buf, sizeof(buf), "'%s'", ipname);
snprintf(ignorepat, sizeof(ignorepat), "_%s.", ipname);
if (!exten || ast_extension_match(ignorepat, exten)) {
ast_cli(fd, " Ignore pattern => %-45s [%s]\n",
buf, ast_get_ignorepat_registrar(ip));
}
}
if (!rinclude) {
struct ast_sw *sw = NULL;
while ( (sw = ast_walk_context_switches(c, sw)) ) {
snprintf(buf, sizeof(buf), "'%s/%s'",
ast_get_switch_name(sw),
ast_get_switch_data(sw));
ast_cli(fd, " Alt. Switch => %-45s [%s]\n",
buf, ast_get_switch_registrar(sw));
}
}
ast_unlock_context(c);
/* if we print something in context, make an empty line */
if (context_info_printed)
ast_cli(fd, "\n");
}
ast_unlock_contexts();
return (dpc->total_exten == old_total_exten) ? -1 : res;
}
static int show_debug_helper(int fd, const char *context, const char *exten, struct dialplan_counters *dpc, struct ast_include *rinclude, int includecount, const char *includes[])
{
struct ast_context *c = NULL;
int res = 0, old_total_exten = dpc->total_exten;
ast_cli(fd,"\n In-mem exten Trie for Fast Extension Pattern Matching:\n\n");
ast_cli(fd,"\n Explanation: Node Contents Format = <char(s) to match>:<pattern?>:<specif>:[matched extension]\n");
ast_cli(fd, " Where <char(s) to match> is a set of chars, any one of which should match the current character\n");
ast_cli(fd, " <pattern?>: Y if this a pattern match (eg. _XZN[5-7]), N otherwise\n");
ast_cli(fd, " <specif>: an assigned 'exactness' number for this matching char. The lower the number, the more exact the match\n");
ast_cli(fd, " [matched exten]: If all chars matched to this point, which extension this matches. In form: EXTEN:<exten string>\n");
ast_cli(fd, " In general, you match a trie node to a string character, from left to right. All possible matching chars\n");
ast_cli(fd, " are in a string vertically, separated by an unbroken string of '+' characters.\n\n");
ast_rdlock_contexts();
/* walk all contexts ... */
while ( (c = ast_walk_contexts(c)) ) {
int context_info_printed = 0;
if (context && strcmp(ast_get_context_name(c), context))
continue; /* skip this one, name doesn't match */
dpc->context_existence = 1;
if (!c->pattern_tree)
ast_exists_extension(NULL, c->name, "s", 1, ""); /* do this to force the trie to built, if it is not already */
ast_rdlock_context(c);
dpc->total_context++;
ast_cli(fd, "[ Context '%s' created by '%s' ]\n",
ast_get_context_name(c), ast_get_context_registrar(c));
context_info_printed = 1;
if (c->pattern_tree)
{
cli_match_char_tree(c->pattern_tree, " ", fd);
} else {
ast_cli(fd,"\n No Pattern Trie present. Perhaps the context is empty...or there is trouble...\n\n");
}
ast_unlock_context(c);
/* if we print something in context, make an empty line */
if (context_info_printed)
ast_cli(fd, "\n");
}
ast_unlock_contexts();
return (dpc->total_exten == old_total_exten) ? -1 : res;
}
static char *handle_show_dialplan(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
char *exten = NULL, *context = NULL;
/* Variables used for different counters */
struct dialplan_counters counters;
const char *incstack[AST_PBX_MAX_STACK];
switch (cmd) {
case CLI_INIT:
e->command = "dialplan show";
e->usage =
"Usage: dialplan show [[exten@]context]\n"
" Show dialplan\n";
return NULL;
case CLI_GENERATE:
return complete_show_dialplan_context(a->line, a->word, a->pos, a->n);
}
memset(&counters, 0, sizeof(counters));
if (a->argc != 2 && a->argc != 3)
return CLI_SHOWUSAGE;
/* we obtain [exten@]context? if yes, split them ... */
if (a->argc == 3) {
if (strchr(a->argv[2], '@')) { /* split into exten & context */
context = ast_strdupa(a->argv[2]);
exten = strsep(&context, "@");
/* change empty strings to NULL */
if (ast_strlen_zero(exten))
exten = NULL;
} else { /* no '@' char, only context given */
context = ast_strdupa(a->argv[2]);
}
if (ast_strlen_zero(context))
context = NULL;
}
/* else Show complete dial plan, context and exten are NULL */
show_dialplan_helper(a->fd, context, exten, &counters, NULL, 0, incstack);
/* check for input failure and throw some error messages */
if (context && !counters.context_existence) {
ast_cli(a->fd, "There is no existence of '%s' context\n", context);
return CLI_FAILURE;
}
if (exten && !counters.extension_existence) {
if (context)
ast_cli(a->fd, "There is no existence of %s@%s extension\n",
exten, context);
else
ast_cli(a->fd,
"There is no existence of '%s' extension in all contexts\n",
exten);
return CLI_FAILURE;
}
ast_cli(a->fd,"-= %d %s (%d %s) in %d %s. =-\n",
counters.total_exten, counters.total_exten == 1 ? "extension" : "extensions",
counters.total_prio, counters.total_prio == 1 ? "priority" : "priorities",
counters.total_context, counters.total_context == 1 ? "context" : "contexts");
/* everything ok */
return CLI_SUCCESS;
}
/*! \brief Send ack once */
static char *handle_debug_dialplan(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
char *exten = NULL, *context = NULL;
/* Variables used for different counters */
struct dialplan_counters counters;
const char *incstack[AST_PBX_MAX_STACK];
switch (cmd) {
case CLI_INIT:
e->command = "dialplan debug";
e->usage =
"Usage: dialplan debug [context]\n"
" Show dialplan context Trie(s). Usually only useful to folks debugging the deep internals of the fast pattern matcher\n";
return NULL;
case CLI_GENERATE:
return complete_show_dialplan_context(a->line, a->word, a->pos, a->n);
}
memset(&counters, 0, sizeof(counters));
if (a->argc != 2 && a->argc != 3)
return CLI_SHOWUSAGE;
/* we obtain [exten@]context? if yes, split them ... */
/* note: we ignore the exten totally here .... */
if (a->argc == 3) {
if (strchr(a->argv[2], '@')) { /* split into exten & context */
context = ast_strdupa(a->argv[2]);
exten = strsep(&context, "@");
/* change empty strings to NULL */
if (ast_strlen_zero(exten))
exten = NULL;
} else { /* no '@' char, only context given */
context = ast_strdupa(a->argv[2]);
}
if (ast_strlen_zero(context))
context = NULL;
}
/* else Show complete dial plan, context and exten are NULL */
show_debug_helper(a->fd, context, exten, &counters, NULL, 0, incstack);
/* check for input failure and throw some error messages */
if (context && !counters.context_existence) {
ast_cli(a->fd, "There is no existence of '%s' context\n", context);
return CLI_FAILURE;
}
ast_cli(a->fd,"-= %d %s. =-\n",
counters.total_context, counters.total_context == 1 ? "context" : "contexts");
/* everything ok */
return CLI_SUCCESS;
}
/*! \brief Send ack once */
static void manager_dpsendack(struct mansession *s, const struct message *m)
{
astman_send_listack(s, m, "DialPlan list will follow", "start");
}
/*! \brief Show dialplan extensions
* XXX this function is similar but not exactly the same as the CLI's
* show dialplan. Must check whether the difference is intentional or not.
*/
static int manager_show_dialplan_helper(struct mansession *s, const struct message *m,
const char *actionidtext, const char *context,
const char *exten, struct dialplan_counters *dpc,
struct ast_include *rinclude)
{
struct ast_context *c;
int res = 0, old_total_exten = dpc->total_exten;
if (ast_strlen_zero(exten))
exten = NULL;
if (ast_strlen_zero(context))
context = NULL;
ast_debug(3, "manager_show_dialplan: Context: -%s- Extension: -%s-\n", context, exten);
/* try to lock contexts */
if (ast_rdlock_contexts()) {
astman_send_error(s, m, "Failed to lock contexts");
ast_log(LOG_WARNING, "Failed to lock contexts list for manager: listdialplan\n");
return -1;
}
c = NULL; /* walk all contexts ... */
while ( (c = ast_walk_contexts(c)) ) {
struct ast_exten *e;
struct ast_include *i;
struct ast_ignorepat *ip;
if (context && strcmp(ast_get_context_name(c), context) != 0)
continue; /* not the name we want */
dpc->context_existence = 1;
ast_debug(3, "manager_show_dialplan: Found Context: %s \n", ast_get_context_name(c));
if (ast_rdlock_context(c)) { /* failed to lock */
ast_debug(3, "manager_show_dialplan: Failed to lock context\n");
continue;
}
/* XXX note- an empty context is not printed */
e = NULL; /* walk extensions in context */
while ( (e = ast_walk_context_extensions(c, e)) ) {
struct ast_exten *p;
/* looking for extension? is this our extension? */
if (exten && !ast_extension_match(ast_get_extension_name(e), exten)) {
/* not the one we are looking for, continue */
ast_debug(3, "manager_show_dialplan: Skipping extension %s\n", ast_get_extension_name(e));
continue;
}
ast_debug(3, "manager_show_dialplan: Found Extension: %s \n", ast_get_extension_name(e));
dpc->extension_existence = 1;
/* may we print context info? */
dpc->total_context++;
dpc->total_exten++;
p = NULL; /* walk next extension peers */
while ( (p = ast_walk_extension_priorities(e, p)) ) {
int prio = ast_get_extension_priority(p);
dpc->total_prio++;
if (!dpc->total_items++)
manager_dpsendack(s, m);
astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
astman_append(s, "Context: %s\r\nExtension: %s\r\n", ast_get_context_name(c), ast_get_extension_name(e) );
/* XXX maybe make this conditional, if p != e ? */
if (ast_get_extension_label(p))
astman_append(s, "ExtensionLabel: %s\r\n", ast_get_extension_label(p));
if (prio == PRIORITY_HINT) {
astman_append(s, "Priority: hint\r\nApplication: %s\r\n", ast_get_extension_app(p));
} else {
astman_append(s, "Priority: %d\r\nApplication: %s\r\nAppData: %s\r\n", prio, ast_get_extension_app(p), (char *) ast_get_extension_app_data(p));
}
astman_append(s, "Registrar: %s\r\n\r\n", ast_get_extension_registrar(e));
}
}
i = NULL; /* walk included and write info ... */
while ( (i = ast_walk_context_includes(c, i)) ) {
if (exten) {
/* Check all includes for the requested extension */
manager_show_dialplan_helper(s, m, actionidtext, ast_get_include_name(i), exten, dpc, i);
} else {
if (!dpc->total_items++)
manager_dpsendack(s, m);
astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
astman_append(s, "Context: %s\r\nIncludeContext: %s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ast_get_include_name(i), ast_get_include_registrar(i));
astman_append(s, "\r\n");
ast_debug(3, "manager_show_dialplan: Found Included context: %s \n", ast_get_include_name(i));
}
}
ip = NULL; /* walk ignore patterns and write info ... */
while ( (ip = ast_walk_context_ignorepats(c, ip)) ) {
const char *ipname = ast_get_ignorepat_name(ip);
char ignorepat[AST_MAX_EXTENSION];
snprintf(ignorepat, sizeof(ignorepat), "_%s.", ipname);
if (!exten || ast_extension_match(ignorepat, exten)) {
if (!dpc->total_items++)
manager_dpsendack(s, m);
astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
astman_append(s, "Context: %s\r\nIgnorePattern: %s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ipname, ast_get_ignorepat_registrar(ip));
astman_append(s, "\r\n");
}
}
if (!rinclude) {
struct ast_sw *sw = NULL;
while ( (sw = ast_walk_context_switches(c, sw)) ) {
if (!dpc->total_items++)
manager_dpsendack(s, m);
astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
astman_append(s, "Context: %s\r\nSwitch: %s/%s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ast_get_switch_name(sw), ast_get_switch_data(sw), ast_get_switch_registrar(sw));
astman_append(s, "\r\n");
ast_debug(3, "manager_show_dialplan: Found Switch : %s \n", ast_get_switch_name(sw));
}
}
ast_unlock_context(c);
}
ast_unlock_contexts();
if (dpc->total_exten == old_total_exten) {
ast_debug(3, "manager_show_dialplan: Found nothing new\n");
/* Nothing new under the sun */
return -1;
} else {
return res;
}
}
/*! \brief Manager listing of dial plan */
static int manager_show_dialplan(struct mansession *s, const struct message *m)
{
const char *exten, *context;
const char *id = astman_get_header(m, "ActionID");
char idtext[256];
/* Variables used for different counters */
struct dialplan_counters counters;
if (!ast_strlen_zero(id))
snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
else
idtext[0] = '\0';
memset(&counters, 0, sizeof(counters));
exten = astman_get_header(m, "Extension");
context = astman_get_header(m, "Context");
manager_show_dialplan_helper(s, m, idtext, context, exten, &counters, NULL);
if (context && !counters.context_existence) {
char errorbuf[BUFSIZ];
snprintf(errorbuf, sizeof(errorbuf), "Did not find context %s", context);
astman_send_error(s, m, errorbuf);
return 0;
}
if (exten && !counters.extension_existence) {
char errorbuf[BUFSIZ];
if (context)
snprintf(errorbuf, sizeof(errorbuf), "Did not find extension %s@%s", exten, context);
else
snprintf(errorbuf, sizeof(errorbuf), "Did not find extension %s in any context", exten);
astman_send_error(s, m, errorbuf);
return 0;
}
astman_append(s, "Event: ShowDialPlanComplete\r\n"
"EventList: Complete\r\n"
"ListItems: %d\r\n"
"ListExtensions: %d\r\n"
"ListPriorities: %d\r\n"
"ListContexts: %d\r\n"
"%s"
"\r\n", counters.total_items, counters.total_exten, counters.total_prio, counters.total_context, idtext);
/* everything ok */
return 0;
}
/*! \brief CLI support for listing global variables in a parseable way */
static char *handle_show_globals(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
int i = 0;
struct ast_var_t *newvariable;
switch (cmd) {
case CLI_INIT:
e->command = "dialplan show globals";
e->usage =
"Usage: dialplan show globals\n"
" List current global dialplan variables and their values\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
ast_rwlock_rdlock(&globalslock);
AST_LIST_TRAVERSE (&globals, newvariable, entries) {
i++;
ast_cli(a->fd, " %s=%s\n", ast_var_name(newvariable), ast_var_value(newvariable));
}
ast_rwlock_unlock(&globalslock);
ast_cli(a->fd, "\n -- %d variable(s)\n", i);
return CLI_SUCCESS;
}
#ifdef AST_DEVMODE
static char *handle_show_device2extenstate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_devstate_aggregate agg;
int i, j, exten, combined;
switch (cmd) {
case CLI_INIT:
e->command = "core show device2extenstate";
e->usage =
"Usage: core show device2extenstate\n"
" Lists device state to extension state combinations.\n";
case CLI_GENERATE:
return NULL;
}
for (i = 0; i < AST_DEVICE_TOTAL; i++) {
for (j = 0; j < AST_DEVICE_TOTAL; j++) {
ast_devstate_aggregate_init(&agg);
ast_devstate_aggregate_add(&agg, i);
ast_devstate_aggregate_add(&agg, j);
combined = ast_devstate_aggregate_result(&agg);
exten = ast_devstate_to_extenstate(combined);
ast_cli(a->fd, "\n Exten:%14s CombinedDevice:%12s Dev1:%12s Dev2:%12s", ast_extension_state2str(exten), ast_devstate_str(combined), ast_devstate_str(j), ast_devstate_str(i));
}
}
ast_cli(a->fd, "\n");
return CLI_SUCCESS;
}
#endif
/*! \brief CLI support for listing chanvar's variables in a parseable way */
static char *handle_show_chanvar(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_channel *chan = NULL;
struct ast_str *vars = ast_str_alloca(BUFSIZ * 4); /* XXX large because we might have lots of channel vars */
switch (cmd) {
case CLI_INIT:
e->command = "dialplan show chanvar";
e->usage =
"Usage: dialplan show chanvar <channel>\n"
" List current channel variables and their values\n";
return NULL;
case CLI_GENERATE:
return ast_complete_channels(a->line, a->word, a->pos, a->n, 3);
}
if (a->argc != e->args + 1)
return CLI_SHOWUSAGE;
if (!(chan = ast_channel_get_by_name(a->argv[e->args]))) {
ast_cli(a->fd, "Channel '%s' not found\n", a->argv[e->args]);
return CLI_FAILURE;
}
pbx_builtin_serialize_variables(chan, &vars);
if (ast_str_strlen(vars)) {
ast_cli(a->fd, "\nVariables for channel %s:\n%s\n", a->argv[e->args], ast_str_buffer(vars));
}
chan = ast_channel_unref(chan);
return CLI_SUCCESS;
}
static char *handle_set_global(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
switch (cmd) {
case CLI_INIT:
e->command = "dialplan set global";
e->usage =
"Usage: dialplan set global <name> <value>\n"
" Set global dialplan variable <name> to <value>\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc != e->args + 2)
return CLI_SHOWUSAGE;
pbx_builtin_setvar_helper(NULL, a->argv[3], a->argv[4]);
ast_cli(a->fd, "\n -- Global variable '%s' set to '%s'\n", a->argv[3], a->argv[4]);
return CLI_SUCCESS;
}
static char *handle_set_chanvar(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_channel *chan;
const char *chan_name, *var_name, *var_value;
switch (cmd) {
case CLI_INIT:
e->command = "dialplan set chanvar";
e->usage =
"Usage: dialplan set chanvar <channel> <varname> <value>\n"
" Set channel variable <varname> to <value>\n";
return NULL;
case CLI_GENERATE:
return ast_complete_channels(a->line, a->word, a->pos, a->n, 3);
}
if (a->argc != e->args + 3)
return CLI_SHOWUSAGE;
chan_name = a->argv[e->args];
var_name = a->argv[e->args + 1];
var_value = a->argv[e->args + 2];
if (!(chan = ast_channel_get_by_name(chan_name))) {
ast_cli(a->fd, "Channel '%s' not found\n", chan_name);
return CLI_FAILURE;
}
pbx_builtin_setvar_helper(chan, var_name, var_value);
chan = ast_channel_unref(chan);
ast_cli(a->fd, "\n -- Channel variable '%s' set to '%s' for '%s'\n", var_name, var_value, chan_name);
return CLI_SUCCESS;
}
static char *handle_set_extenpatternmatchnew(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
int oldval = 0;
switch (cmd) {
case CLI_INIT:
e->command = "dialplan set extenpatternmatchnew true";
e->usage =
"Usage: dialplan set extenpatternmatchnew true|false\n"
" Use the NEW extension pattern matching algorithm, true or false.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc != 4)
return CLI_SHOWUSAGE;
oldval = pbx_set_extenpatternmatchnew(1);
if (oldval)
ast_cli(a->fd, "\n -- Still using the NEW pattern match algorithm for extension names in the dialplan.\n");
else
ast_cli(a->fd, "\n -- Switched to using the NEW pattern match algorithm for extension names in the dialplan.\n");
return CLI_SUCCESS;
}
static char *handle_unset_extenpatternmatchnew(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
int oldval = 0;
switch (cmd) {
case CLI_INIT:
e->command = "dialplan set extenpatternmatchnew false";
e->usage =
"Usage: dialplan set extenpatternmatchnew true|false\n"
" Use the NEW extension pattern matching algorithm, true or false.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc != 4)
return CLI_SHOWUSAGE;
oldval = pbx_set_extenpatternmatchnew(0);
if (!oldval)
ast_cli(a->fd, "\n -- Still using the OLD pattern match algorithm for extension names in the dialplan.\n");
else
ast_cli(a->fd, "\n -- Switched to using the OLD pattern match algorithm for extension names in the dialplan.\n");
return CLI_SUCCESS;
}
/*
* CLI entries for upper commands ...
*/
static struct ast_cli_entry pbx_cli[] = {
AST_CLI_DEFINE(handle_show_applications, "Shows registered dialplan applications"),
AST_CLI_DEFINE(handle_show_functions, "Shows registered dialplan functions"),
AST_CLI_DEFINE(handle_show_switches, "Show alternative switches"),
AST_CLI_DEFINE(handle_show_hints, "Show dialplan hints"),
AST_CLI_DEFINE(handle_show_hint, "Show dialplan hint"),
AST_CLI_DEFINE(handle_show_globals, "Show global dialplan variables"),
#ifdef AST_DEVMODE
AST_CLI_DEFINE(handle_show_device2extenstate, "Show expected exten state from multiple device states"),
#endif
AST_CLI_DEFINE(handle_show_chanvar, "Show channel variables"),
AST_CLI_DEFINE(handle_show_function, "Describe a specific dialplan function"),
AST_CLI_DEFINE(handle_show_application, "Describe a specific dialplan application"),
AST_CLI_DEFINE(handle_set_global, "Set global dialplan variable"),
AST_CLI_DEFINE(handle_set_chanvar, "Set a channel variable"),
AST_CLI_DEFINE(handle_show_dialplan, "Show dialplan"),
AST_CLI_DEFINE(handle_debug_dialplan, "Show fast extension pattern matching data structures"),
AST_CLI_DEFINE(handle_unset_extenpatternmatchnew, "Use the Old extension pattern matching algorithm."),
AST_CLI_DEFINE(handle_set_extenpatternmatchnew, "Use the New extension pattern matching algorithm."),
};
static void unreference_cached_app(struct ast_app *app)
{
struct ast_context *context = NULL;
struct ast_exten *eroot = NULL, *e = NULL;
ast_rdlock_contexts();
while ((context = ast_walk_contexts(context))) {
while ((eroot = ast_walk_context_extensions(context, eroot))) {
while ((e = ast_walk_extension_priorities(eroot, e))) {
if (e->cached_app == app)
e->cached_app = NULL;
}
}
}
ast_unlock_contexts();
return;
}
int ast_unregister_application(const char *app)
{
struct ast_app *tmp;
AST_RWLIST_WRLOCK(&apps);
AST_RWLIST_TRAVERSE_SAFE_BEGIN(&apps, tmp, list) {
if (!strcasecmp(app, tmp->name)) {
unreference_cached_app(tmp);
AST_RWLIST_REMOVE_CURRENT(list);
ast_verb(2, "Unregistered application '%s'\n", tmp->name);
ast_string_field_free_memory(tmp);
ast_free(tmp);
break;
}
}
AST_RWLIST_TRAVERSE_SAFE_END;
AST_RWLIST_UNLOCK(&apps);
return tmp ? 0 : -1;
}
struct ast_context *ast_context_find_or_create(struct ast_context **extcontexts, struct ast_hashtab *exttable, const char *name, const char *registrar)
{
struct ast_context *tmp, **local_contexts;
struct fake_context search;
int length = sizeof(struct ast_context) + strlen(name) + 1;
if (!contexts_table) {
/* Protect creation of contexts_table from reentrancy. */
ast_wrlock_contexts();
if (!contexts_table) {
contexts_table = ast_hashtab_create(17,
ast_hashtab_compare_contexts,
ast_hashtab_resize_java,
ast_hashtab_newsize_java,
ast_hashtab_hash_contexts,
0);
}
ast_unlock_contexts();
}
ast_copy_string(search.name, name, sizeof(search.name));
if (!extcontexts) {
ast_rdlock_contexts();
local_contexts = &contexts;
tmp = ast_hashtab_lookup(contexts_table, &search);
ast_unlock_contexts();
if (tmp) {
tmp->refcount++;
return tmp;
}
} else { /* local contexts just in a linked list; search there for the new context; slow, linear search, but not frequent */
local_contexts = extcontexts;
tmp = ast_hashtab_lookup(exttable, &search);
if (tmp) {
tmp->refcount++;
return tmp;
}
}
if ((tmp = ast_calloc(1, length))) {
ast_rwlock_init(&tmp->lock);
ast_mutex_init(&tmp->macrolock);
strcpy(tmp->name, name);
tmp->root = NULL;
tmp->root_table = NULL;
tmp->registrar = ast_strdup(registrar);
tmp->includes = NULL;
tmp->ignorepats = NULL;
tmp->refcount = 1;
} else {
ast_log(LOG_ERROR, "Danger! We failed to allocate a context for %s!\n", name);
return NULL;
}
if (!extcontexts) {
ast_wrlock_contexts();
tmp->next = *local_contexts;
*local_contexts = tmp;
ast_hashtab_insert_safe(contexts_table, tmp); /*put this context into the tree */
ast_unlock_contexts();
ast_debug(1, "Registered context '%s'(%p) in table %p registrar: %s\n", tmp->name, tmp, contexts_table, registrar);
ast_verb(3, "Registered extension context '%s'; registrar: %s\n", tmp->name, registrar);
} else {
tmp->next = *local_contexts;
if (exttable)
ast_hashtab_insert_immediate(exttable, tmp); /*put this context into the tree */
*local_contexts = tmp;
ast_debug(1, "Registered context '%s'(%p) in local table %p; registrar: %s\n", tmp->name, tmp, exttable, registrar);
ast_verb(3, "Registered extension context '%s'; registrar: %s\n", tmp->name, registrar);
}
return tmp;
}
void __ast_context_destroy(struct ast_context *list, struct ast_hashtab *contexttab, struct ast_context *con, const char *registrar);
struct store_hint {
char *context;
char *exten;
AST_LIST_HEAD_NOLOCK(, ast_state_cb) callbacks;
int laststate;
AST_LIST_ENTRY(store_hint) list;
char data[1];
};
AST_LIST_HEAD_NOLOCK(store_hints, store_hint);
static void context_merge_incls_swits_igps_other_registrars(struct ast_context *new, struct ast_context *old, const char *registrar)
{
struct ast_include *i;
struct ast_ignorepat *ip;
struct ast_sw *sw;
ast_verb(3, "merging incls/swits/igpats from old(%s) to new(%s) context, registrar = %s\n", ast_get_context_name(old), ast_get_context_name(new), registrar);
/* copy in the includes, switches, and ignorepats */
/* walk through includes */
for (i = NULL; (i = ast_walk_context_includes(old, i)) ; ) {
if (strcmp(ast_get_include_registrar(i), registrar) == 0)
continue; /* not mine */
ast_context_add_include2(new, ast_get_include_name(i), ast_get_include_registrar(i));
}
/* walk through switches */
for (sw = NULL; (sw = ast_walk_context_switches(old, sw)) ; ) {
if (strcmp(ast_get_switch_registrar(sw), registrar) == 0)
continue; /* not mine */
ast_context_add_switch2(new, ast_get_switch_name(sw), ast_get_switch_data(sw), ast_get_switch_eval(sw), ast_get_switch_registrar(sw));
}
/* walk thru ignorepats ... */
for (ip = NULL; (ip = ast_walk_context_ignorepats(old, ip)); ) {
if (strcmp(ast_get_ignorepat_registrar(ip), registrar) == 0)
continue; /* not mine */
ast_context_add_ignorepat2(new, ast_get_ignorepat_name(ip), ast_get_ignorepat_registrar(ip));
}
}
/* the purpose of this routine is to duplicate a context, with all its substructure,
except for any extens that have a matching registrar */
static void context_merge(struct ast_context **extcontexts, struct ast_hashtab *exttable, struct ast_context *context, const char *registrar)
{
struct ast_context *new = ast_hashtab_lookup(exttable, context); /* is there a match in the new set? */
struct ast_exten *exten_item, *prio_item, *new_exten_item, *new_prio_item;
struct ast_hashtab_iter *exten_iter;
struct ast_hashtab_iter *prio_iter;
int insert_count = 0;
int first = 1;
/* We'll traverse all the extensions/prios, and see which are not registrar'd with
the current registrar, and copy them to the new context. If the new context does not
exist, we'll create it "on demand". If no items are in this context to copy, then we'll
only create the empty matching context if the old one meets the criteria */
if (context->root_table) {
exten_iter = ast_hashtab_start_traversal(context->root_table);
while ((exten_item=ast_hashtab_next(exten_iter))) {
if (new) {
new_exten_item = ast_hashtab_lookup(new->root_table, exten_item);
} else {
new_exten_item = NULL;
}
prio_iter = ast_hashtab_start_traversal(exten_item->peer_table);
while ((prio_item=ast_hashtab_next(prio_iter))) {
int res1;
char *dupdstr;
if (new_exten_item) {
new_prio_item = ast_hashtab_lookup(new_exten_item->peer_table, prio_item);
} else {
new_prio_item = NULL;
}
if (strcmp(prio_item->registrar,registrar) == 0) {
continue;
}
/* make sure the new context exists, so we have somewhere to stick this exten/prio */
if (!new) {
new = ast_context_find_or_create(extcontexts, exttable, context->name, prio_item->registrar); /* a new context created via priority from a different context in the old dialplan, gets its registrar from the prio's registrar */
}
/* copy in the includes, switches, and ignorepats */
if (first) { /* but, only need to do this once */
context_merge_incls_swits_igps_other_registrars(new, context, registrar);
first = 0;
}
if (!new) {
ast_log(LOG_ERROR,"Could not allocate a new context for %s in merge_and_delete! Danger!\n", context->name);
return; /* no sense continuing. */
}
/* we will not replace existing entries in the new context with stuff from the old context.
but, if this is because of some sort of registrar conflict, we ought to say something... */
dupdstr = ast_strdup(prio_item->data);
res1 = ast_add_extension2(new, 0, prio_item->exten, prio_item->priority, prio_item->label,
prio_item->matchcid ? prio_item->cidmatch : NULL, prio_item->app, dupdstr, prio_item->datad, prio_item->registrar);
if (!res1 && new_exten_item && new_prio_item){
ast_verb(3,"Dropping old dialplan item %s/%s/%d [%s(%s)] (registrar=%s) due to conflict with new dialplan\n",
context->name, prio_item->exten, prio_item->priority, prio_item->app, (char*)prio_item->data, prio_item->registrar);
} else {
/* we do NOT pass the priority data from the old to the new -- we pass a copy of it, so no changes to the current dialplan take place,
and no double frees take place, either! */
insert_count++;
}
}
ast_hashtab_end_traversal(prio_iter);
}
ast_hashtab_end_traversal(exten_iter);
}
if (!insert_count && !new && (strcmp(context->registrar, registrar) != 0 ||
(strcmp(context->registrar, registrar) == 0 && context->refcount > 1))) {
/* we could have given it the registrar of the other module who incremented the refcount,
but that's not available, so we give it the registrar we know about */
new = ast_context_find_or_create(extcontexts, exttable, context->name, context->registrar);
/* copy in the includes, switches, and ignorepats */
context_merge_incls_swits_igps_other_registrars(new, context, registrar);
}
}
/* XXX this does not check that multiple contexts are merged */
void ast_merge_contexts_and_delete(struct ast_context **extcontexts, struct ast_hashtab *exttable, const char *registrar)
{
double ft;
struct ast_context *tmp;
struct ast_context *oldcontextslist;
struct ast_hashtab *oldtable;
struct store_hints hints_stored = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
struct store_hints hints_removed = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
struct store_hint *saved_hint;
struct ast_hint *hint;
struct ast_exten *exten;
int length;
struct ast_state_cb *thiscb;
struct ast_hashtab_iter *iter;
struct ao2_iterator i;
struct timeval begintime;
struct timeval writelocktime;
struct timeval endlocktime;
struct timeval enddeltime;
/*
* It is very important that this function hold the hints
* container lock _and_ the conlock during its operation; not
* only do we need to ensure that the list of contexts and
* extensions does not change, but also that no hint callbacks
* (watchers) are added or removed during the merge/delete
* process
*
* In addition, the locks _must_ be taken in this order, because
* there are already other code paths that use this order
*/
begintime = ast_tvnow();
ast_mutex_lock(&context_merge_lock);/* Serialize ast_merge_contexts_and_delete */
ast_wrlock_contexts();
iter = ast_hashtab_start_traversal(contexts_table);
while ((tmp = ast_hashtab_next(iter))) {
context_merge(extcontexts, exttable, tmp, registrar);
}
ast_hashtab_end_traversal(iter);
ao2_lock(hints);
writelocktime = ast_tvnow();
/* preserve all watchers for hints */
i = ao2_iterator_init(hints, AO2_ITERATOR_DONTLOCK);
for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) {
if (ao2_container_count(hint->callbacks)) {
ao2_lock(hint);
if (!hint->exten) {
/* The extension has already been destroyed. (Should never happen here) */
ao2_unlock(hint);
continue;
}
length = strlen(hint->exten->exten) + strlen(hint->exten->parent->name) + 2
+ sizeof(*saved_hint);
if (!(saved_hint = ast_calloc(1, length))) {
ao2_unlock(hint);
continue;
}
/* This removes all the callbacks from the hint into saved_hint. */
while ((thiscb = ao2_callback(hint->callbacks, OBJ_UNLINK, NULL, NULL))) {
AST_LIST_INSERT_TAIL(&saved_hint->callbacks, thiscb, entry);
/*
* We intentionally do not unref thiscb to account for the
* non-ao2 reference in saved_hint->callbacks
*/
}
saved_hint->laststate = hint->laststate;
saved_hint->context = saved_hint->data;
strcpy(saved_hint->data, hint->exten->parent->name);
saved_hint->exten = saved_hint->data + strlen(saved_hint->context) + 1;
strcpy(saved_hint->exten, hint->exten->exten);
ao2_unlock(hint);
AST_LIST_INSERT_HEAD(&hints_stored, saved_hint, list);
}
}
ao2_iterator_destroy(&i);
/* save the old table and list */
oldtable = contexts_table;
oldcontextslist = contexts;
/* move in the new table and list */
contexts_table = exttable;
contexts = *extcontexts;
/*
* Restore the watchers for hints that can be found; notify
* those that cannot be restored.
*/
while ((saved_hint = AST_LIST_REMOVE_HEAD(&hints_stored, list))) {
struct pbx_find_info q = { .stacklen = 0 };
exten = pbx_find_extension(NULL, NULL, &q, saved_hint->context, saved_hint->exten,
PRIORITY_HINT, NULL, "", E_MATCH);
/*
* If this is a pattern, dynamically create a new extension for this
* particular match. Note that this will only happen once for each
* individual extension, because the pattern will no longer match first.
*/
if (exten && exten->exten[0] == '_') {
ast_add_extension_nolock(exten->parent->name, 0, saved_hint->exten,
PRIORITY_HINT, NULL, 0, exten->app, ast_strdup(exten->data), ast_free_ptr,
exten->registrar);
/* rwlocks are not recursive locks */
exten = ast_hint_extension_nolock(NULL, saved_hint->context,
saved_hint->exten);
}
/* Find the hint in the hints container */
hint = exten ? ao2_find(hints, exten, 0) : NULL;
if (!hint) {
/*
* Notify watchers of this removed hint later when we aren't
* encumberd by so many locks.
*/
AST_LIST_INSERT_HEAD(&hints_removed, saved_hint, list);
} else {
ao2_lock(hint);
while ((thiscb = AST_LIST_REMOVE_HEAD(&saved_hint->callbacks, entry))) {
ao2_link(hint->callbacks, thiscb);
/* Ref that we added when putting into saved_hint->callbacks */
ao2_ref(thiscb, -1);
}
hint->laststate = saved_hint->laststate;
ao2_unlock(hint);
ao2_ref(hint, -1);
ast_free(saved_hint);
}
}
ao2_unlock(hints);
ast_unlock_contexts();
/*
* Notify watchers of all removed hints with the same lock
* environment as handle_statechange().
*/
while ((saved_hint = AST_LIST_REMOVE_HEAD(&hints_removed, list))) {
/* this hint has been removed, notify the watchers */
while ((thiscb = AST_LIST_REMOVE_HEAD(&saved_hint->callbacks, entry))) {
thiscb->change_cb(saved_hint->context, saved_hint->exten,
AST_EXTENSION_REMOVED, thiscb->data);
/* Ref that we added when putting into saved_hint->callbacks */
ao2_ref(thiscb, -1);
}
ast_free(saved_hint);
}
ast_mutex_unlock(&context_merge_lock);
endlocktime = ast_tvnow();
/*
* The old list and hashtab no longer are relevant, delete them
* while the rest of asterisk is now freely using the new stuff
* instead.
*/
ast_hashtab_destroy(oldtable, NULL);
for (tmp = oldcontextslist; tmp; ) {
struct ast_context *next; /* next starting point */
next = tmp->next;
__ast_internal_context_destroy(tmp);
tmp = next;
}
enddeltime = ast_tvnow();
ft = ast_tvdiff_us(writelocktime, begintime);
ft /= 1000000.0;
ast_verb(3,"Time to scan old dialplan and merge leftovers back into the new: %8.6f sec\n", ft);
ft = ast_tvdiff_us(endlocktime, writelocktime);
ft /= 1000000.0;
ast_verb(3,"Time to restore hints and swap in new dialplan: %8.6f sec\n", ft);
ft = ast_tvdiff_us(enddeltime, endlocktime);
ft /= 1000000.0;
ast_verb(3,"Time to delete the old dialplan: %8.6f sec\n", ft);
ft = ast_tvdiff_us(enddeltime, begintime);
ft /= 1000000.0;
ast_verb(3,"Total time merge_contexts_delete: %8.6f sec\n", ft);
}
/*
* errno values
* EBUSY - can't lock
* ENOENT - no existence of context
*/
int ast_context_add_include(const char *context, const char *include, const char *registrar)
{
int ret = -1;
struct ast_context *c;
c = find_context_locked(context);
if (c) {
ret = ast_context_add_include2(c, include, registrar);
ast_unlock_contexts();
}
return ret;
}
/*! \brief Helper for get_range.
* return the index of the matching entry, starting from 1.
* If names is not supplied, try numeric values.
*/
static int lookup_name(const char *s, const char * const names[], int max)
{
int i;
if (names && *s > '9') {
for (i = 0; names[i]; i++) {
if (!strcasecmp(s, names[i])) {
return i;
}
}
}
/* Allow months and weekdays to be specified as numbers, as well */
if (sscanf(s, "%2d", &i) == 1 && i >= 1 && i <= max) {
/* What the array offset would have been: "1" would be at offset 0 */
return i - 1;
}
return -1; /* error return */
}
/*! \brief helper function to return a range up to max (7, 12, 31 respectively).
* names, if supplied, is an array of names that should be mapped to numbers.
*/
static unsigned get_range(char *src, int max, const char * const names[], const char *msg)
{
int start, end; /* start and ending position */
unsigned int mask = 0;
char *part;
/* Check for whole range */
if (ast_strlen_zero(src) || !strcmp(src, "*")) {
return (1 << max) - 1;
}
while ((part = strsep(&src, "&"))) {
/* Get start and ending position */
char *endpart = strchr(part, '-');
if (endpart) {
*endpart++ = '\0';
}
/* Find the start */
if ((start = lookup_name(part, names, max)) < 0) {
ast_log(LOG_WARNING, "Invalid %s '%s', skipping element\n", msg, part);
continue;
}
if (endpart) { /* find end of range */
if ((end = lookup_name(endpart, names, max)) < 0) {
ast_log(LOG_WARNING, "Invalid end %s '%s', skipping element\n", msg, endpart);
continue;
}
} else {
end = start;
}
/* Fill the mask. Remember that ranges are cyclic */
mask |= (1 << end); /* initialize with last element */
while (start != end) {
mask |= (1 << start);
if (++start >= max) {
start = 0;
}
}
}
return mask;
}
/*! \brief store a bitmask of valid times, one bit each 1 minute */
static void get_timerange(struct ast_timing *i, char *times)
{
char *endpart, *part;
int x;
int st_h, st_m;
int endh, endm;
int minute_start, minute_end;
/* start disabling all times, fill the fields with 0's, as they may contain garbage */
memset(i->minmask, 0, sizeof(i->minmask));
/* 1-minute per bit */
/* Star is all times */
if (ast_strlen_zero(times) || !strcmp(times, "*")) {
/* 48, because each hour takes 2 integers; 30 bits each */
for (x = 0; x < 48; x++) {
i->minmask[x] = 0x3fffffff; /* 30 bits */
}
return;
}
/* Otherwise expect a range */
while ((part = strsep(×, "&"))) {
if (!(endpart = strchr(part, '-'))) {
if (sscanf(part, "%2d:%2d", &st_h, &st_m) != 2 || st_h < 0 || st_h > 23 || st_m < 0 || st_m > 59) {
ast_log(LOG_WARNING, "%s isn't a valid time.\n", part);
continue;
}
i->minmask[st_h * 2 + (st_m >= 30 ? 1 : 0)] |= (1 << (st_m % 30));
continue;
}
*endpart++ = '\0';
/* why skip non digits? Mostly to skip spaces */
while (*endpart && !isdigit(*endpart)) {
endpart++;
}
if (!*endpart) {
ast_log(LOG_WARNING, "Invalid time range starting with '%s-'.\n", part);
continue;
}
if (sscanf(part, "%2d:%2d", &st_h, &st_m) != 2 || st_h < 0 || st_h > 23 || st_m < 0 || st_m > 59) {
ast_log(LOG_WARNING, "'%s' isn't a valid start time.\n", part);
continue;
}
if (sscanf(endpart, "%2d:%2d", &endh, &endm) != 2 || endh < 0 || endh > 23 || endm < 0 || endm > 59) {
ast_log(LOG_WARNING, "'%s' isn't a valid end time.\n", endpart);
continue;
}
minute_start = st_h * 60 + st_m;
minute_end = endh * 60 + endm;
/* Go through the time and enable each appropriate bit */
for (x = minute_start; x != minute_end; x = (x + 1) % (24 * 60)) {
i->minmask[x / 30] |= (1 << (x % 30));
}
/* Do the last one */
i->minmask[x / 30] |= (1 << (x % 30));
}
/* All done */
return;
}
static const char * const days[] =
{
"sun",
"mon",
"tue",
"wed",
"thu",
"fri",
"sat",
NULL,
};
static const char * const months[] =
{
"jan",
"feb",
"mar",
"apr",
"may",
"jun",
"jul",
"aug",
"sep",
"oct",
"nov",
"dec",
NULL,
};
int ast_build_timing(struct ast_timing *i, const char *info_in)
{
char *info;
int j, num_fields, last_sep = -1;
/* Check for empty just in case */
if (ast_strlen_zero(info_in)) {
return 0;
}
/* make a copy just in case we were passed a static string */
info = ast_strdupa(info_in);
/* count the number of fields in the timespec */
for (j = 0, num_fields = 1; info[j] != '\0'; j++) {
if (info[j] == ',') {
last_sep = j;
num_fields++;
}
}
/* save the timezone, if it is specified */
if (num_fields == 5) {
i->timezone = ast_strdup(info + last_sep + 1);
} else {
i->timezone = NULL;
}
/* Assume everything except time */
i->monthmask = 0xfff; /* 12 bits */
i->daymask = 0x7fffffffU; /* 31 bits */
i->dowmask = 0x7f; /* 7 bits */
/* on each call, use strsep() to move info to the next argument */
get_timerange(i, strsep(&info, "|,"));
if (info)
i->dowmask = get_range(strsep(&info, "|,"), 7, days, "day of week");
if (info)
i->daymask = get_range(strsep(&info, "|,"), 31, NULL, "day");
if (info)
i->monthmask = get_range(strsep(&info, "|,"), 12, months, "month");
return 1;
}
int ast_check_timing(const struct ast_timing *i)
{
return ast_check_timing2(i, ast_tvnow());
}
int ast_check_timing2(const struct ast_timing *i, const struct timeval tv)
{
struct ast_tm tm;
ast_localtime(&tv, &tm, i->timezone);
/* If it's not the right month, return */
if (!(i->monthmask & (1 << tm.tm_mon)))
return 0;
/* If it's not that time of the month.... */
/* Warning, tm_mday has range 1..31! */
if (!(i->daymask & (1 << (tm.tm_mday-1))))
return 0;
/* If it's not the right day of the week */
if (!(i->dowmask & (1 << tm.tm_wday)))
return 0;
/* Sanity check the hour just to be safe */
if ((tm.tm_hour < 0) || (tm.tm_hour > 23)) {
ast_log(LOG_WARNING, "Insane time...\n");
return 0;
}
/* Now the tough part, we calculate if it fits
in the right time based on min/hour */
if (!(i->minmask[tm.tm_hour * 2 + (tm.tm_min >= 30 ? 1 : 0)] & (1 << (tm.tm_min >= 30 ? tm.tm_min - 30 : tm.tm_min))))
return 0;
/* If we got this far, then we're good */
return 1;
}
int ast_destroy_timing(struct ast_timing *i)
{
if (i->timezone) {
ast_free(i->timezone);
i->timezone = NULL;
}
return 0;
}
/*
* errno values
* ENOMEM - out of memory
* EBUSY - can't lock
* EEXIST - already included
* EINVAL - there is no existence of context for inclusion
*/
int ast_context_add_include2(struct ast_context *con, const char *value,
const char *registrar)
{
struct ast_include *new_include;
char *c;
struct ast_include *i, *il = NULL; /* include, include_last */
int length;
char *p;
length = sizeof(struct ast_include);
length += 2 * (strlen(value) + 1);
/* allocate new include structure ... */
if (!(new_include = ast_calloc(1, length)))
return -1;
/* Fill in this structure. Use 'p' for assignments, as the fields
* in the structure are 'const char *'
*/
p = new_include->stuff;
new_include->name = p;
strcpy(p, value);
p += strlen(value) + 1;
new_include->rname = p;
strcpy(p, value);
/* Strip off timing info, and process if it is there */
if ( (c = strchr(p, ',')) ) {
*c++ = '\0';
new_include->hastime = ast_build_timing(&(new_include->timing), c);
}
new_include->next = NULL;
new_include->registrar = registrar;
ast_wrlock_context(con);
/* ... go to last include and check if context is already included too... */
for (i = con->includes; i; i = i->next) {
if (!strcasecmp(i->name, new_include->name)) {
ast_destroy_timing(&(new_include->timing));
ast_free(new_include);
ast_unlock_context(con);
errno = EEXIST;
return -1;
}
il = i;
}
/* ... include new context into context list, unlock, return */
if (il)
il->next = new_include;
else
con->includes = new_include;
ast_verb(3, "Including context '%s' in context '%s'\n", new_include->name, ast_get_context_name(con));
ast_unlock_context(con);
return 0;
}
/*
* errno values
* EBUSY - can't lock
* ENOENT - no existence of context
*/
int ast_context_add_switch(const char *context, const char *sw, const char *data, int eval, const char *registrar)
{
int ret = -1;
struct ast_context *c;
c = find_context_locked(context);
if (c) { /* found, add switch to this context */
ret = ast_context_add_switch2(c, sw, data, eval, registrar);
ast_unlock_contexts();
}
return ret;
}
/*
* errno values
* ENOMEM - out of memory
* EBUSY - can't lock
* EEXIST - already included
* EINVAL - there is no existence of context for inclusion
*/
int ast_context_add_switch2(struct ast_context *con, const char *value,
const char *data, int eval, const char *registrar)
{
struct ast_sw *new_sw;
struct ast_sw *i;
int length;
char *p;
length = sizeof(struct ast_sw);
length += strlen(value) + 1;
if (data)
length += strlen(data);
length++;
/* allocate new sw structure ... */
if (!(new_sw = ast_calloc(1, length)))
return -1;
/* ... fill in this structure ... */
p = new_sw->stuff;
new_sw->name = p;
strcpy(new_sw->name, value);
p += strlen(value) + 1;
new_sw->data = p;
if (data) {
strcpy(new_sw->data, data);
p += strlen(data) + 1;
} else {
strcpy(new_sw->data, "");
p++;
}
new_sw->eval = eval;
new_sw->registrar = registrar;
/* ... try to lock this context ... */
ast_wrlock_context(con);
/* ... go to last sw and check if context is already swd too... */
AST_LIST_TRAVERSE(&con->alts, i, list) {
if (!strcasecmp(i->name, new_sw->name) && !strcasecmp(i->data, new_sw->data)) {
ast_free(new_sw);
ast_unlock_context(con);
errno = EEXIST;
return -1;
}
}
/* ... sw new context into context list, unlock, return */
AST_LIST_INSERT_TAIL(&con->alts, new_sw, list);
ast_verb(3, "Including switch '%s/%s' in context '%s'\n", new_sw->name, new_sw->data, ast_get_context_name(con));
ast_unlock_context(con);
return 0;
}
/*
* EBUSY - can't lock
* ENOENT - there is not context existence
*/
int ast_context_remove_ignorepat(const char *context, const char *ignorepat, const char *registrar)
{
int ret = -1;
struct ast_context *c;
c = find_context_locked(context);
if (c) {
ret = ast_context_remove_ignorepat2(c, ignorepat, registrar);
ast_unlock_contexts();
}
return ret;
}
int ast_context_remove_ignorepat2(struct ast_context *con, const char *ignorepat, const char *registrar)
{
struct ast_ignorepat *ip, *ipl = NULL;
ast_wrlock_context(con);
for (ip = con->ignorepats; ip; ip = ip->next) {
if (!strcmp(ip->pattern, ignorepat) &&
(!registrar || (registrar == ip->registrar))) {
if (ipl) {
ipl->next = ip->next;
ast_free(ip);
} else {
con->ignorepats = ip->next;
ast_free(ip);
}
ast_unlock_context(con);
return 0;
}
ipl = ip;
}
ast_unlock_context(con);
errno = EINVAL;
return -1;
}
/*
* EBUSY - can't lock
* ENOENT - there is no existence of context
*/
int ast_context_add_ignorepat(const char *context, const char *value, const char *registrar)
{
int ret = -1;
struct ast_context *c;
c = find_context_locked(context);
if (c) {
ret = ast_context_add_ignorepat2(c, value, registrar);
ast_unlock_contexts();
}
return ret;
}
int ast_context_add_ignorepat2(struct ast_context *con, const char *value, const char *registrar)
{
struct ast_ignorepat *ignorepat, *ignorepatc, *ignorepatl = NULL;
int length;
char *pattern;
length = sizeof(struct ast_ignorepat);
length += strlen(value) + 1;
if (!(ignorepat = ast_calloc(1, length)))
return -1;
/* The cast to char * is because we need to write the initial value.
* The field is not supposed to be modified otherwise. Also, gcc 4.2
* sees the cast as dereferencing a type-punned pointer and warns about
* it. This is the workaround (we're telling gcc, yes, that's really
* what we wanted to do).
*/
pattern = (char *) ignorepat->pattern;
strcpy(pattern, value);
ignorepat->next = NULL;
ignorepat->registrar = registrar;
ast_wrlock_context(con);
for (ignorepatc = con->ignorepats; ignorepatc; ignorepatc = ignorepatc->next) {
ignorepatl = ignorepatc;
if (!strcasecmp(ignorepatc->pattern, value)) {
/* Already there */
ast_unlock_context(con);
errno = EEXIST;
return -1;
}
}
if (ignorepatl)
ignorepatl->next = ignorepat;
else
con->ignorepats = ignorepat;
ast_unlock_context(con);
return 0;
}
int ast_ignore_pattern(const char *context, const char *pattern)
{
struct ast_context *con = ast_context_find(context);
if (con) {
struct ast_ignorepat *pat;
for (pat = con->ignorepats; pat; pat = pat->next) {
if (ast_extension_match(pat->pattern, pattern))
return 1;
}
}
return 0;
}
/*
* ast_add_extension_nolock -- use only in situations where the conlock is already held
* ENOENT - no existence of context
*
*/
static int ast_add_extension_nolock(const char *context, int replace, const char *extension,
int priority, const char *label, const char *callerid,
const char *application, void *data, void (*datad)(void *), const char *registrar)
{
int ret = -1;
struct ast_context *c;
c = find_context(context);
if (c) {
ret = ast_add_extension2_lockopt(c, replace, extension, priority, label, callerid,
application, data, datad, registrar, 1);
}
return ret;
}
/*
* EBUSY - can't lock
* ENOENT - no existence of context
*
*/
int ast_add_extension(const char *context, int replace, const char *extension,
int priority, const char *label, const char *callerid,
const char *application, void *data, void (*datad)(void *), const char *registrar)
{
int ret = -1;
struct ast_context *c;
c = find_context_locked(context);
if (c) {
ret = ast_add_extension2(c, replace, extension, priority, label, callerid,
application, data, datad, registrar);
ast_unlock_contexts();
}
return ret;
}
int ast_explicit_goto(struct ast_channel *chan, const char *context, const char *exten, int priority)
{
if (!chan)
return -1;
ast_channel_lock(chan);
if (!ast_strlen_zero(context))
ast_copy_string(chan->context, context, sizeof(chan->context));
if (!ast_strlen_zero(exten))
ast_copy_string(chan->exten, exten, sizeof(chan->exten));
if (priority > -1) {
chan->priority = priority;
/* see flag description in channel.h for explanation */
if (ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP))
chan->priority--;
}
ast_channel_unlock(chan);
return 0;
}
int ast_async_goto(struct ast_channel *chan, const char *context, const char *exten, int priority)
{
int res = 0;
struct ast_channel *tmpchan;
struct {
char *accountcode;
char *exten;
char *context;
char *linkedid;
char *name;
struct ast_cdr *cdr;
int amaflags;
int state;
format_t readformat;
format_t writeformat;
} tmpvars = { 0, };
ast_channel_lock(chan);
if (chan->pbx) { /* This channel is currently in the PBX */
ast_explicit_goto(chan, context, exten, priority + 1);
ast_softhangup_nolock(chan, AST_SOFTHANGUP_ASYNCGOTO);
ast_channel_unlock(chan);
return res;
}
/* In order to do it when the channel doesn't really exist within
* the PBX, we have to make a new channel, masquerade, and start the PBX
* at the new location */
tmpvars.accountcode = ast_strdupa(chan->accountcode);
tmpvars.exten = ast_strdupa(chan->exten);
tmpvars.context = ast_strdupa(chan->context);
tmpvars.linkedid = ast_strdupa(chan->linkedid);
tmpvars.name = ast_strdupa(chan->name);
tmpvars.amaflags = chan->amaflags;
tmpvars.state = chan->_state;
tmpvars.writeformat = chan->writeformat;
tmpvars.readformat = chan->readformat;
tmpvars.cdr = chan->cdr ? ast_cdr_dup(chan->cdr) : NULL;
ast_channel_unlock(chan);
/* Do not hold any channel locks while calling channel_alloc() since the function
* locks the channel container when linking the new channel in. */
if (!(tmpchan = ast_channel_alloc(0, tmpvars.state, 0, 0, tmpvars.accountcode, tmpvars.exten, tmpvars.context, tmpvars.linkedid, tmpvars.amaflags, "AsyncGoto/%s", tmpvars.name))) {
ast_cdr_discard(tmpvars.cdr);
return -1;
}
/* copy the cdr info over */
if (tmpvars.cdr) {
ast_cdr_discard(tmpchan->cdr);
tmpchan->cdr = tmpvars.cdr;
tmpvars.cdr = NULL;
}
/* Make formats okay */
tmpchan->readformat = tmpvars.readformat;
tmpchan->writeformat = tmpvars.writeformat;
/* Setup proper location. Never hold another channel lock while calling this function. */
ast_explicit_goto(tmpchan, S_OR(context, tmpvars.context), S_OR(exten, tmpvars.exten), priority);
/* Masquerade into tmp channel */
if (ast_channel_masquerade(tmpchan, chan)) {
/* Failed to set up the masquerade. It's probably chan_local
* in the middle of optimizing itself out. Sad. :( */
ast_hangup(tmpchan);
tmpchan = NULL;
res = -1;
} else {
ast_do_masquerade(tmpchan);
/* Start the PBX going on our stolen channel */
if (ast_pbx_start(tmpchan)) {
ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmpchan->name);
ast_hangup(tmpchan);
res = -1;
}
}
return res;
}
int ast_async_goto_by_name(const char *channame, const char *context, const char *exten, int priority)
{
struct ast_channel *chan;
int res = -1;
if ((chan = ast_channel_get_by_name(channame))) {
res = ast_async_goto(chan, context, exten, priority);
chan = ast_channel_unref(chan);
}
return res;
}
/*! \brief copy a string skipping whitespace */
static int ext_strncpy(char *dst, const char *src, int len)
{
int count = 0;
int insquares = 0;
while (*src && (count < len - 1)) {
if (*src == '[') {
insquares = 1;
} else if (*src == ']') {
insquares = 0;
} else if (*src == ' ' && !insquares) {
src++;
continue;
}
*dst = *src;
dst++;
src++;
count++;
}
*dst = '\0';
return count;
}
/*!
* \brief add the extension in the priority chain.
* \retval 0 on success.
* \retval -1 on failure.
*/
static int add_priority(struct ast_context *con, struct ast_exten *tmp,
struct ast_exten *el, struct ast_exten *e, int replace)
{
struct ast_exten *ep;
struct ast_exten *eh=e;
int repeated_label = 0; /* Track if this label is a repeat, assume no. */
for (ep = NULL; e ; ep = e, e = e->peer) {
if (e->label && tmp->label && e->priority != tmp->priority && !strcmp(e->label, tmp->label)) {
ast_log(LOG_WARNING, "Extension '%s', priority %d in '%s', label '%s' already in use at "
"priority %d\n", tmp->exten, tmp->priority, con->name, tmp->label, e->priority);
repeated_label = 1;
}
if (e->priority >= tmp->priority) {
break;
}
}
if (repeated_label) { /* Discard the label since it's a repeat. */
tmp->label = NULL;
}
if (!e) { /* go at the end, and ep is surely set because the list is not empty */
ast_hashtab_insert_safe(eh->peer_table, tmp);
if (tmp->label) {
ast_hashtab_insert_safe(eh->peer_label_table, tmp);
}
ep->peer = tmp;
return 0; /* success */
}
if (e->priority == tmp->priority) {
/* Can't have something exactly the same. Is this a
replacement? If so, replace, otherwise, bonk. */
if (!replace) {
ast_log(LOG_WARNING, "Unable to register extension '%s', priority %d in '%s', already in use\n", tmp->exten, tmp->priority, con->name);
if (tmp->datad) {
tmp->datad(tmp->data);
/* if you free this, null it out */
tmp->data = NULL;
}
ast_free(tmp);
return -1;
}
/* we are replacing e, so copy the link fields and then update
* whoever pointed to e to point to us
*/
tmp->next = e->next; /* not meaningful if we are not first in the peer list */
tmp->peer = e->peer; /* always meaningful */
if (ep) { /* We're in the peer list, just insert ourselves */
ast_hashtab_remove_object_via_lookup(eh->peer_table,e);
if (e->label) {
ast_hashtab_remove_object_via_lookup(eh->peer_label_table,e);
}
ast_hashtab_insert_safe(eh->peer_table,tmp);
if (tmp->label) {
ast_hashtab_insert_safe(eh->peer_label_table,tmp);
}
ep->peer = tmp;
} else if (el) { /* We're the first extension. Take over e's functions */
struct match_char *x = add_exten_to_pattern_tree(con, e, 1);
tmp->peer_table = e->peer_table;
tmp->peer_label_table = e->peer_label_table;
ast_hashtab_remove_object_via_lookup(tmp->peer_table,e);
ast_hashtab_insert_safe(tmp->peer_table,tmp);
if (e->label) {
ast_hashtab_remove_object_via_lookup(tmp->peer_label_table, e);
}
if (tmp->label) {
ast_hashtab_insert_safe(tmp->peer_label_table, tmp);
}
ast_hashtab_remove_object_via_lookup(con->root_table, e);
ast_hashtab_insert_safe(con->root_table, tmp);
el->next = tmp;
/* The pattern trie points to this exten; replace the pointer,
and all will be well */
if (x) { /* if the trie isn't formed yet, don't sweat this */
if (x->exten) { /* this test for safety purposes */
x->exten = tmp; /* replace what would become a bad pointer */
} else {
ast_log(LOG_ERROR,"Trying to delete an exten from a context, but the pattern tree node returned isn't an extension\n");
}
}
} else { /* We're the very first extension. */
struct match_char *x = add_exten_to_pattern_tree(con, e, 1);
ast_hashtab_remove_object_via_lookup(con->root_table, e);
ast_hashtab_insert_safe(con->root_table, tmp);
tmp->peer_table = e->peer_table;
tmp->peer_label_table = e->peer_label_table;
ast_hashtab_remove_object_via_lookup(tmp->peer_table, e);
ast_hashtab_insert_safe(tmp->peer_table, tmp);
if (e->label) {
ast_hashtab_remove_object_via_lookup(tmp->peer_label_table, e);
}
if (tmp->label) {
ast_hashtab_insert_safe(tmp->peer_label_table, tmp);
}
ast_hashtab_remove_object_via_lookup(con->root_table, e);
ast_hashtab_insert_safe(con->root_table, tmp);
con->root = tmp;
/* The pattern trie points to this exten; replace the pointer,
and all will be well */
if (x) { /* if the trie isn't formed yet; no problem */
if (x->exten) { /* this test for safety purposes */
x->exten = tmp; /* replace what would become a bad pointer */
} else {
ast_log(LOG_ERROR,"Trying to delete an exten from a context, but the pattern tree node returned isn't an extension\n");
}
}
}
if (tmp->priority == PRIORITY_HINT)
ast_change_hint(e,tmp);
/* Destroy the old one */
if (e->datad)
e->datad(e->data);
ast_free(e);
} else { /* Slip ourselves in just before e */
tmp->peer = e;
tmp->next = e->next; /* extension chain, or NULL if e is not the first extension */
if (ep) { /* Easy enough, we're just in the peer list */
if (tmp->label) {
ast_hashtab_insert_safe(eh->peer_label_table, tmp);
}
ast_hashtab_insert_safe(eh->peer_table, tmp);
ep->peer = tmp;
} else { /* we are the first in some peer list, so link in the ext list */
tmp->peer_table = e->peer_table;
tmp->peer_label_table = e->peer_label_table;
e->peer_table = 0;
e->peer_label_table = 0;
ast_hashtab_insert_safe(tmp->peer_table, tmp);
if (tmp->label) {
ast_hashtab_insert_safe(tmp->peer_label_table, tmp);
}
ast_hashtab_remove_object_via_lookup(con->root_table, e);
ast_hashtab_insert_safe(con->root_table, tmp);
if (el)
el->next = tmp; /* in the middle... */
else
con->root = tmp; /* ... or at the head */
e->next = NULL; /* e is no more at the head, so e->next must be reset */
}
/* And immediately return success. */
if (tmp->priority == PRIORITY_HINT) {
ast_add_hint(tmp);
}
}
return 0;
}
/*! \brief
* Main interface to add extensions to the list for out context.
*
* We sort extensions in order of matching preference, so that we can
* stop the search as soon as we find a suitable match.
* This ordering also takes care of wildcards such as '.' (meaning
* "one or more of any character") and '!' (which is 'earlymatch',
* meaning "zero or more of any character" but also impacts the
* return value from CANMATCH and EARLYMATCH.
*
* The extension match rules defined in the devmeeting 2006.05.05 are
* quite simple: WE SELECT THE LONGEST MATCH.
* In detail, "longest" means the number of matched characters in
* the extension. In case of ties (e.g. _XXX and 333) in the length
* of a pattern, we give priority to entries with the smallest cardinality
* (e.g, [5-9] comes before [2-8] before the former has only 5 elements,
* while the latter has 7, etc.
* In case of same cardinality, the first element in the range counts.
* If we still have a tie, any final '!' will make this as a possibly
* less specific pattern.
*
* EBUSY - can't lock
* EEXIST - extension with the same priority exist and no replace is set
*
*/
int ast_add_extension2(struct ast_context *con,
int replace, const char *extension, int priority, const char *label, const char *callerid,
const char *application, void *data, void (*datad)(void *),
const char *registrar)
{
return ast_add_extension2_lockopt(con, replace, extension, priority, label, callerid,
application, data, datad, registrar, 1);
}
/*!
* \brief Same as ast_add_extension2() but controls the context locking.
*
* \details
* Does all the work of ast_add_extension2, but adds an arg to
* determine if context locking should be done.
*/
static int ast_add_extension2_lockopt(struct ast_context *con,
int replace, const char *extension, int priority, const char *label, const char *callerid,
const char *application, void *data, void (*datad)(void *),
const char *registrar, int lock_context)
{
/*
* Sort extensions (or patterns) according to the rules indicated above.
* These are implemented by the function ext_cmp()).
* All priorities for the same ext/pattern/cid are kept in a list,
* using the 'peer' field as a link field..
*/
struct ast_exten *tmp, *tmp2, *e, *el = NULL;
int res;
int length;
char *p;
char expand_buf[VAR_BUF_SIZE];
struct ast_exten dummy_exten = {0};
char dummy_name[1024];
if (ast_strlen_zero(extension)) {
ast_log(LOG_ERROR,"You have to be kidding-- add exten '' to context %s? Figure out a name and call me back. Action ignored.\n",
con->name);
return -1;
}
/* If we are adding a hint evalulate in variables and global variables */
if (priority == PRIORITY_HINT && strstr(application, "${") && !strstr(extension, "_")) {
struct ast_channel *c = ast_dummy_channel_alloc();
if (c) {
ast_copy_string(c->exten, extension, sizeof(c->exten));
ast_copy_string(c->context, con->name, sizeof(c->context));
}
pbx_substitute_variables_helper(c, application, expand_buf, sizeof(expand_buf));
application = expand_buf;
if (c) {
ast_channel_unref(c);
}
}
length = sizeof(struct ast_exten);
length += strlen(extension) + 1;
length += strlen(application) + 1;
if (label)
length += strlen(label) + 1;
if (callerid)
length += strlen(callerid) + 1;
else
length ++; /* just the '\0' */
/* Be optimistic: Build the extension structure first */
if (!(tmp = ast_calloc(1, length)))
return -1;
if (ast_strlen_zero(label)) /* let's turn empty labels to a null ptr */
label = 0;
/* use p as dst in assignments, as the fields are const char * */
p = tmp->stuff;
if (label) {
tmp->label = p;
strcpy(p, label);
p += strlen(label) + 1;
}
tmp->exten = p;
p += ext_strncpy(p, extension, strlen(extension) + 1) + 1;
tmp->priority = priority;
tmp->cidmatch = p; /* but use p for assignments below */
/* Blank callerid and NULL callerid are two SEPARATE things. Do NOT confuse the two!!! */
if (callerid) {
p += ext_strncpy(p, callerid, strlen(callerid) + 1) + 1;
tmp->matchcid = 1;
} else {
*p++ = '\0';
tmp->matchcid = 0;
}
tmp->app = p;
strcpy(p, application);
tmp->parent = con;
tmp->data = data;
tmp->datad = datad;
tmp->registrar = registrar;
if (lock_context) {
ast_wrlock_context(con);
}
if (con->pattern_tree) { /* usually, on initial load, the pattern_tree isn't formed until the first find_exten; so if we are adding
an extension, and the trie exists, then we need to incrementally add this pattern to it. */
ast_copy_string(dummy_name, extension, sizeof(dummy_name));
dummy_exten.exten = dummy_name;
dummy_exten.matchcid = 0;
dummy_exten.cidmatch = 0;
tmp2 = ast_hashtab_lookup(con->root_table, &dummy_exten);
if (!tmp2) {
/* hmmm, not in the trie; */
add_exten_to_pattern_tree(con, tmp, 0);
ast_hashtab_insert_safe(con->root_table, tmp); /* for the sake of completeness */
}
}
res = 0; /* some compilers will think it is uninitialized otherwise */
for (e = con->root; e; el = e, e = e->next) { /* scan the extension list */
res = ext_cmp(e->exten, tmp->exten);
if (res == 0) { /* extension match, now look at cidmatch */
if (!e->matchcid && !tmp->matchcid)
res = 0;
else if (tmp->matchcid && !e->matchcid)
res = 1;
else if (e->matchcid && !tmp->matchcid)
res = -1;
else
res = ext_cmp(e->cidmatch, tmp->cidmatch);
}
if (res >= 0)
break;
}
if (e && res == 0) { /* exact match, insert in the priority chain */
res = add_priority(con, tmp, el, e, replace);
if (lock_context) {
ast_unlock_context(con);
}
if (res < 0) {
errno = EEXIST; /* XXX do we care ? */
return 0; /* XXX should we return -1 maybe ? */
}
} else {
/*
* not an exact match, this is the first entry with this pattern,
* so insert in the main list right before 'e' (if any)
*/
tmp->next = e;
if (el) { /* there is another exten already in this context */
el->next = tmp;
tmp->peer_table = ast_hashtab_create(13,
hashtab_compare_exten_numbers,
ast_hashtab_resize_java,
ast_hashtab_newsize_java,
hashtab_hash_priority,
0);
tmp->peer_label_table = ast_hashtab_create(7,
hashtab_compare_exten_labels,
ast_hashtab_resize_java,
ast_hashtab_newsize_java,
hashtab_hash_labels,
0);
if (label) {
ast_hashtab_insert_safe(tmp->peer_label_table, tmp);
}
ast_hashtab_insert_safe(tmp->peer_table, tmp);
} else { /* this is the first exten in this context */
if (!con->root_table)
con->root_table = ast_hashtab_create(27,
hashtab_compare_extens,
ast_hashtab_resize_java,
ast_hashtab_newsize_java,
hashtab_hash_extens,
0);
con->root = tmp;
con->root->peer_table = ast_hashtab_create(13,
hashtab_compare_exten_numbers,
ast_hashtab_resize_java,
ast_hashtab_newsize_java,
hashtab_hash_priority,
0);
con->root->peer_label_table = ast_hashtab_create(7,
hashtab_compare_exten_labels,
ast_hashtab_resize_java,
ast_hashtab_newsize_java,
hashtab_hash_labels,
0);
if (label) {
ast_hashtab_insert_safe(con->root->peer_label_table, tmp);
}
ast_hashtab_insert_safe(con->root->peer_table, tmp);
}
ast_hashtab_insert_safe(con->root_table, tmp);
if (lock_context) {
ast_unlock_context(con);
}
if (tmp->priority == PRIORITY_HINT) {
ast_add_hint(tmp);
}
}
if (option_debug) {
if (tmp->matchcid) {
ast_debug(1, "Added extension '%s' priority %d (CID match '%s') to %s (%p)\n",
tmp->exten, tmp->priority, tmp->cidmatch, con->name, con);
} else {
ast_debug(1, "Added extension '%s' priority %d to %s (%p)\n",
tmp->exten, tmp->priority, con->name, con);
}
}
if (tmp->matchcid) {
ast_verb(3, "Added extension '%s' priority %d (CID match '%s') to %s\n",
tmp->exten, tmp->priority, tmp->cidmatch, con->name);
} else {
ast_verb(3, "Added extension '%s' priority %d to %s\n",
tmp->exten, tmp->priority, con->name);
}
return 0;
}
struct async_stat {
pthread_t p;
struct ast_channel *chan;
char context[AST_MAX_CONTEXT];
char exten[AST_MAX_EXTENSION];
int priority;
int timeout;
char app[AST_MAX_EXTENSION];
char appdata[1024];
};
static void *async_wait(void *data)
{
struct async_stat *as = data;
struct ast_channel *chan = as->chan;
int timeout = as->timeout;
int res;
struct ast_frame *f;
struct ast_app *app;
while (timeout && (chan->_state != AST_STATE_UP)) {
res = ast_waitfor(chan, timeout);
if (res < 1)
break;
if (timeout > -1)
timeout = res;
f = ast_read(chan);
if (!f)
break;
if (f->frametype == AST_FRAME_CONTROL) {
if ((f->subclass.integer == AST_CONTROL_BUSY) ||
(f->subclass.integer == AST_CONTROL_CONGESTION) ) {
ast_frfree(f);
break;
}
}
ast_frfree(f);
}
if (chan->_state == AST_STATE_UP) {
if (!ast_strlen_zero(as->app)) {
app = pbx_findapp(as->app);
if (app) {
ast_verb(3, "Launching %s(%s) on %s\n", as->app, as->appdata, chan->name);
pbx_exec(chan, app, as->appdata);
} else
ast_log(LOG_WARNING, "No such application '%s'\n", as->app);
} else {
if (!ast_strlen_zero(as->context))
ast_copy_string(chan->context, as->context, sizeof(chan->context));
if (!ast_strlen_zero(as->exten))
ast_copy_string(chan->exten, as->exten, sizeof(chan->exten));
if (as->priority > 0)
chan->priority = as->priority;
/* Run the PBX */
if (ast_pbx_run(chan)) {
ast_log(LOG_ERROR, "Failed to start PBX on %s\n", chan->name);
} else {
/* PBX will have taken care of this */
chan = NULL;
}
}
}
ast_free(as);
if (chan)
ast_hangup(chan);
return NULL;
}
/*!
* \brief Function to post an empty cdr after a spool call fails.
* \note This function posts an empty cdr for a failed spool call
*/
static int ast_pbx_outgoing_cdr_failed(void)
{
/* allocate a channel */
struct ast_channel *chan = ast_dummy_channel_alloc();
if (!chan)
return -1; /* failure */
chan->cdr = ast_cdr_alloc();
if (!chan->cdr) {
/* allocation of the cdr failed */
chan = ast_channel_unref(chan); /* free the channel */
return -1; /* return failure */
}
/* allocation of the cdr was successful */
ast_cdr_init(chan->cdr, chan); /* initialize our channel's cdr */
ast_cdr_start(chan->cdr); /* record the start and stop time */
ast_cdr_end(chan->cdr);
ast_cdr_failed(chan->cdr); /* set the status to failed */
ast_cdr_detach(chan->cdr); /* post and free the record */
chan->cdr = NULL;
chan = ast_channel_unref(chan); /* free the channel */
return 0; /* success */
}
int ast_pbx_outgoing_exten(const char *type, format_t format, void *data, int timeout, const char *context, const char *exten, int priority, int *reason, int synchronous, const char *cid_num, const char *cid_name, struct ast_variable *vars, const char *account, struct ast_channel **channel)
{
struct ast_channel *chan;
struct async_stat *as;
int res = -1, cdr_res = -1;
struct outgoing_helper oh;
if (synchronous) {
oh.context = context;
oh.exten = exten;
oh.priority = priority;
oh.cid_num = cid_num;
oh.cid_name = cid_name;
oh.account = account;
oh.vars = vars;
oh.parent_channel = NULL;
chan = __ast_request_and_dial(type, format, NULL, data, timeout, reason, cid_num, cid_name, &oh);
if (channel) {
*channel = chan;
if (chan)
ast_channel_lock(chan);
}
if (chan) {
if (chan->_state == AST_STATE_UP) {
res = 0;
ast_verb(4, "Channel %s was answered.\n", chan->name);
if (synchronous > 1) {
if (channel)
ast_channel_unlock(chan);
if (ast_pbx_run(chan)) {
ast_log(LOG_ERROR, "Unable to run PBX on %s\n", chan->name);
if (channel)
*channel = NULL;
ast_hangup(chan);
chan = NULL;
res = -1;
}
} else {
if (ast_pbx_start(chan)) {
ast_log(LOG_ERROR, "Unable to start PBX on %s\n", chan->name);
if (channel) {
*channel = NULL;
ast_channel_unlock(chan);
}
ast_hangup(chan);
res = -1;
}
chan = NULL;
}
} else {
ast_verb(4, "Channel %s was never answered.\n", chan->name);
if (chan->cdr) { /* update the cdr */
/* here we update the status of the call, which sould be busy.
* if that fails then we set the status to failed */
if (ast_cdr_disposition(chan->cdr, chan->hangupcause))
ast_cdr_failed(chan->cdr);
}
if (channel) {
*channel = NULL;
ast_channel_unlock(chan);
}
ast_hangup(chan);
chan = NULL;
}
}
if (res < 0) { /* the call failed for some reason */
if (*reason == 0) { /* if the call failed (not busy or no answer)
* update the cdr with the failed message */
cdr_res = ast_pbx_outgoing_cdr_failed();
if (cdr_res != 0) {
res = cdr_res;
goto outgoing_exten_cleanup;
}
}
/* create a fake channel and execute the "failed" extension (if it exists) within the requested context */
/* check if "failed" exists */
if (ast_exists_extension(chan, context, "failed", 1, NULL)) {
chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", NULL, 0, "OutgoingSpoolFailed");
if (chan) {
char failed_reason[4] = "";
if (!ast_strlen_zero(context))
ast_copy_string(chan->context, context, sizeof(chan->context));
set_ext_pri(chan, "failed", 1);
ast_set_variables(chan, vars);
snprintf(failed_reason, sizeof(failed_reason), "%d", *reason);
pbx_builtin_setvar_helper(chan, "REASON", failed_reason);
if (account)
ast_cdr_setaccount(chan, account);
if (ast_pbx_run(chan)) {
ast_log(LOG_ERROR, "Unable to run PBX on %s\n", chan->name);
ast_hangup(chan);
}
chan = NULL;
}
}
}
} else {
if (!(as = ast_calloc(1, sizeof(*as)))) {
res = -1;
goto outgoing_exten_cleanup;
}
chan = ast_request_and_dial(type, format, NULL, data, timeout, reason, cid_num, cid_name);
if (channel) {
*channel = chan;
if (chan)
ast_channel_lock(chan);
}
if (!chan) {
ast_free(as);
res = -1;
goto outgoing_exten_cleanup;
}
as->chan = chan;
ast_copy_string(as->context, context, sizeof(as->context));
set_ext_pri(as->chan, exten, priority);
as->timeout = timeout;
ast_set_variables(chan, vars);
if (account)
ast_cdr_setaccount(chan, account);
if (ast_pthread_create_detached(&as->p, NULL, async_wait, as)) {
ast_log(LOG_WARNING, "Failed to start async wait\n");
ast_free(as);
if (channel) {
*channel = NULL;
ast_channel_unlock(chan);
}
ast_hangup(chan);
res = -1;
goto outgoing_exten_cleanup;
}
res = 0;
}
outgoing_exten_cleanup:
ast_variables_destroy(vars);
return res;
}
struct app_tmp {
struct ast_channel *chan;
pthread_t t;
AST_DECLARE_STRING_FIELDS (
AST_STRING_FIELD(app);
AST_STRING_FIELD(data);
);
};
/*! \brief run the application and free the descriptor once done */
static void *ast_pbx_run_app(void *data)
{
struct app_tmp *tmp = data;
struct ast_app *app;
app = pbx_findapp(tmp->app);
if (app) {
ast_verb(4, "Launching %s(%s) on %s\n", tmp->app, tmp->data, tmp->chan->name);
pbx_exec(tmp->chan, app, tmp->data);
} else
ast_log(LOG_WARNING, "No such application '%s'\n", tmp->app);
ast_hangup(tmp->chan);
ast_string_field_free_memory(tmp);
ast_free(tmp);
return NULL;
}
int ast_pbx_outgoing_app(const char *type, format_t format, void *data, int timeout, const char *app, const char *appdata, int *reason, int synchronous, const char *cid_num, const char *cid_name, struct ast_variable *vars, const char *account, struct ast_channel **locked_channel)
{
struct ast_channel *chan;
struct app_tmp *tmp;
int res = -1, cdr_res = -1;
struct outgoing_helper oh;
memset(&oh, 0, sizeof(oh));
oh.vars = vars;
oh.account = account;
if (locked_channel)
*locked_channel = NULL;
if (ast_strlen_zero(app)) {
res = -1;
goto outgoing_app_cleanup;
}
if (synchronous) {
chan = __ast_request_and_dial(type, format, NULL, data, timeout, reason, cid_num, cid_name, &oh);
if (chan) {
ast_set_variables(chan, vars);
if (account)
ast_cdr_setaccount(chan, account);
if (chan->_state == AST_STATE_UP) {
res = 0;
ast_verb(4, "Channel %s was answered.\n", chan->name);
tmp = ast_calloc(1, sizeof(*tmp));
if (!tmp || ast_string_field_init(tmp, 252)) {
if (tmp) {
ast_free(tmp);
}
res = -1;
} else {
ast_string_field_set(tmp, app, app);
ast_string_field_set(tmp, data, appdata);
tmp->chan = chan;
if (synchronous > 1) {
if (locked_channel)
ast_channel_unlock(chan);
ast_pbx_run_app(tmp);
} else {
if (locked_channel)
ast_channel_lock(chan);
if (ast_pthread_create_detached(&tmp->t, NULL, ast_pbx_run_app, tmp)) {
ast_log(LOG_WARNING, "Unable to spawn execute thread on %s: %s\n", chan->name, strerror(errno));
ast_string_field_free_memory(tmp);
ast_free(tmp);
if (locked_channel)
ast_channel_unlock(chan);
ast_hangup(chan);
res = -1;
} else {
if (locked_channel)
*locked_channel = chan;
}
}
}
} else {
ast_verb(4, "Channel %s was never answered.\n", chan->name);
if (chan->cdr) { /* update the cdr */
/* here we update the status of the call, which sould be busy.
* if that fails then we set the status to failed */
if (ast_cdr_disposition(chan->cdr, chan->hangupcause))
ast_cdr_failed(chan->cdr);
}
ast_hangup(chan);
}
}
if (res < 0) { /* the call failed for some reason */
if (*reason == 0) { /* if the call failed (not busy or no answer)
* update the cdr with the failed message */
cdr_res = ast_pbx_outgoing_cdr_failed();
if (cdr_res != 0) {
res = cdr_res;
goto outgoing_app_cleanup;
}
}
}
} else {
struct async_stat *as;
if (!(as = ast_calloc(1, sizeof(*as)))) {
res = -1;
goto outgoing_app_cleanup;
}
chan = __ast_request_and_dial(type, format, NULL, data, timeout, reason, cid_num, cid_name, &oh);
if (!chan) {
ast_free(as);
res = -1;
goto outgoing_app_cleanup;
}
as->chan = chan;
ast_copy_string(as->app, app, sizeof(as->app));
if (appdata)
ast_copy_string(as->appdata, appdata, sizeof(as->appdata));
as->timeout = timeout;
ast_set_variables(chan, vars);
if (account)
ast_cdr_setaccount(chan, account);
/* Start a new thread, and get something handling this channel. */
if (locked_channel)
ast_channel_lock(chan);
if (ast_pthread_create_detached(&as->p, NULL, async_wait, as)) {
ast_log(LOG_WARNING, "Failed to start async wait\n");
ast_free(as);
if (locked_channel)
ast_channel_unlock(chan);
ast_hangup(chan);
res = -1;
goto outgoing_app_cleanup;
} else {
if (locked_channel)
*locked_channel = chan;
}
res = 0;
}
outgoing_app_cleanup:
ast_variables_destroy(vars);
return res;
}
/* this is the guts of destroying a context --
freeing up the structure, traversing and destroying the
extensions, switches, ignorepats, includes, etc. etc. */
static void __ast_internal_context_destroy( struct ast_context *con)
{
struct ast_include *tmpi;
struct ast_sw *sw;
struct ast_exten *e, *el, *en;
struct ast_ignorepat *ipi;
struct ast_context *tmp = con;
for (tmpi = tmp->includes; tmpi; ) { /* Free includes */
struct ast_include *tmpil = tmpi;
tmpi = tmpi->next;
ast_free(tmpil);
}
for (ipi = tmp->ignorepats; ipi; ) { /* Free ignorepats */
struct ast_ignorepat *ipl = ipi;
ipi = ipi->next;
ast_free(ipl);
}
if (tmp->registrar)
ast_free(tmp->registrar);
/* destroy the hash tabs */
if (tmp->root_table) {
ast_hashtab_destroy(tmp->root_table, 0);
}
/* and destroy the pattern tree */
if (tmp->pattern_tree)
destroy_pattern_tree(tmp->pattern_tree);
while ((sw = AST_LIST_REMOVE_HEAD(&tmp->alts, list)))
ast_free(sw);
for (e = tmp->root; e;) {
for (en = e->peer; en;) {
el = en;
en = en->peer;
destroy_exten(el);
}
el = e;
e = e->next;
destroy_exten(el);
}
tmp->root = NULL;
ast_rwlock_destroy(&tmp->lock);
ast_free(tmp);
}
void __ast_context_destroy(struct ast_context *list, struct ast_hashtab *contexttab, struct ast_context *con, const char *registrar)
{
struct ast_context *tmp, *tmpl=NULL;
struct ast_exten *exten_item, *prio_item;
for (tmp = list; tmp; ) {
struct ast_context *next = NULL; /* next starting point */
/* The following code used to skip forward to the next
context with matching registrar, but this didn't
make sense; individual priorities registrar'd to
the matching registrar could occur in any context! */
ast_debug(1, "Investigate ctx %s %s\n", tmp->name, tmp->registrar);
if (con) {
for (; tmp; tmpl = tmp, tmp = tmp->next) { /* skip to the matching context */
ast_debug(1, "check ctx %s %s\n", tmp->name, tmp->registrar);
if ( !strcasecmp(tmp->name, con->name) ) {
break; /* found it */
}
}
}
if (!tmp) /* not found, we are done */
break;
ast_wrlock_context(tmp);
if (registrar) {
/* then search thru and remove any extens that match registrar. */
struct ast_hashtab_iter *exten_iter;
struct ast_hashtab_iter *prio_iter;
struct ast_ignorepat *ip, *ipl = NULL, *ipn = NULL;
struct ast_include *i, *pi = NULL, *ni = NULL;
struct ast_sw *sw = NULL;
/* remove any ignorepats whose registrar matches */
for (ip = tmp->ignorepats; ip; ip = ipn) {
ipn = ip->next;
if (!strcmp(ip->registrar, registrar)) {
if (ipl) {
ipl->next = ip->next;
ast_free(ip);
continue; /* don't change ipl */
} else {
tmp->ignorepats = ip->next;
ast_free(ip);
continue; /* don't change ipl */
}
}
ipl = ip;
}
/* remove any includes whose registrar matches */
for (i = tmp->includes; i; i = ni) {
ni = i->next;
if (strcmp(i->registrar, registrar) == 0) {
/* remove from list */
if (pi) {
pi->next = i->next;
/* free include */
ast_free(i);
continue; /* don't change pi */
} else {
tmp->includes = i->next;
/* free include */
ast_free(i);
continue; /* don't change pi */
}
}
pi = i;
}
/* remove any switches whose registrar matches */
AST_LIST_TRAVERSE_SAFE_BEGIN(&tmp->alts, sw, list) {
if (strcmp(sw->registrar,registrar) == 0) {
AST_LIST_REMOVE_CURRENT(list);
ast_free(sw);
}
}
AST_LIST_TRAVERSE_SAFE_END;
if (tmp->root_table) { /* it is entirely possible that the context is EMPTY */
exten_iter = ast_hashtab_start_traversal(tmp->root_table);
while ((exten_item=ast_hashtab_next(exten_iter))) {
int end_traversal = 1;
prio_iter = ast_hashtab_start_traversal(exten_item->peer_table);
while ((prio_item=ast_hashtab_next(prio_iter))) {
char extension[AST_MAX_EXTENSION];
char cidmatch[AST_MAX_EXTENSION];
if (!prio_item->registrar || strcmp(prio_item->registrar, registrar) != 0) {
continue;
}
ast_verb(3, "Remove %s/%s/%d, registrar=%s; con=%s(%p); con->root=%p\n",
tmp->name, prio_item->exten, prio_item->priority, registrar, con? con->name : "<nil>", con, con? con->root_table: NULL);
/* set matchcid to 1 to insure we get a direct match, and NULL registrar to make sure no wildcarding is done */
ast_copy_string(extension, prio_item->exten, sizeof(extension));
if (prio_item->cidmatch) {
ast_copy_string(cidmatch, prio_item->cidmatch, sizeof(cidmatch));
}
end_traversal &= ast_context_remove_extension_callerid2(tmp, extension, prio_item->priority, prio_item->cidmatch ? cidmatch : NULL, 1, NULL, 1);
}
/* Explanation:
* ast_context_remove_extension_callerid2 will destroy the extension that it comes across. This
* destruction includes destroying the exten's peer_table, which we are currently traversing. If
* ast_context_remove_extension_callerid2 ever should return '0' then this means we have destroyed
* the hashtable which we are traversing, and thus calling ast_hashtab_end_traversal will result
* in reading invalid memory. Thus, if we detect that we destroyed the hashtable, then we will simply
* free the iterator
*/
if (end_traversal) {
ast_hashtab_end_traversal(prio_iter);
} else {
ast_free(prio_iter);
}
}
ast_hashtab_end_traversal(exten_iter);
}
/* delete the context if it's registrar matches, is empty, has refcount of 1, */
/* it's not empty, if it has includes, ignorepats, or switches that are registered from
another registrar. It's not empty if there are any extensions */
if (strcmp(tmp->registrar, registrar) == 0 && tmp->refcount < 2 && !tmp->root && !tmp->ignorepats && !tmp->includes && AST_LIST_EMPTY(&tmp->alts)) {
ast_debug(1, "delete ctx %s %s\n", tmp->name, tmp->registrar);
ast_hashtab_remove_this_object(contexttab, tmp);
next = tmp->next;
if (tmpl)
tmpl->next = next;
else
contexts = next;
/* Okay, now we're safe to let it go -- in a sense, we were
ready to let it go as soon as we locked it. */
ast_unlock_context(tmp);
__ast_internal_context_destroy(tmp);
} else {
ast_debug(1,"Couldn't delete ctx %s/%s; refc=%d; tmp.root=%p\n", tmp->name, tmp->registrar,
tmp->refcount, tmp->root);
ast_unlock_context(tmp);
next = tmp->next;
tmpl = tmp;
}
} else if (con) {
ast_verb(3, "Deleting context %s registrar=%s\n", tmp->name, tmp->registrar);
ast_debug(1, "delete ctx %s %s\n", tmp->name, tmp->registrar);
ast_hashtab_remove_this_object(contexttab, tmp);
next = tmp->next;
if (tmpl)
tmpl->next = next;
else
contexts = next;
/* Okay, now we're safe to let it go -- in a sense, we were
ready to let it go as soon as we locked it. */
ast_unlock_context(tmp);
__ast_internal_context_destroy(tmp);
}
/* if we have a specific match, we are done, otherwise continue */
tmp = con ? NULL : next;
}
}
void ast_context_destroy(struct ast_context *con, const char *registrar)
{
ast_wrlock_contexts();
__ast_context_destroy(contexts, contexts_table, con,registrar);
ast_unlock_contexts();
}
static void wait_for_hangup(struct ast_channel *chan, const void *data)
{
int res;
struct ast_frame *f;
double waitsec;
int waittime;
if (ast_strlen_zero(data) || (sscanf(data, "%30lg", &waitsec) != 1) || (waitsec < 0))
waitsec = -1;
if (waitsec > -1) {
waittime = waitsec * 1000.0;
ast_safe_sleep(chan, waittime);
} else do {
res = ast_waitfor(chan, -1);
if (res < 0)
return;
f = ast_read(chan);
if (f)
ast_frfree(f);
} while(f);
}
/*!
* \ingroup applications
*/
static int pbx_builtin_proceeding(struct ast_channel *chan, const char *data)
{
ast_indicate(chan, AST_CONTROL_PROCEEDING);
return 0;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_progress(struct ast_channel *chan, const char *data)
{
ast_indicate(chan, AST_CONTROL_PROGRESS);
return 0;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_ringing(struct ast_channel *chan, const char *data)
{
ast_indicate(chan, AST_CONTROL_RINGING);
return 0;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_busy(struct ast_channel *chan, const char *data)
{
ast_indicate(chan, AST_CONTROL_BUSY);
/* Don't change state of an UP channel, just indicate
busy in audio */
if (chan->_state != AST_STATE_UP) {
ast_setstate(chan, AST_STATE_BUSY);
ast_cdr_busy(chan->cdr);
}
wait_for_hangup(chan, data);
return -1;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_congestion(struct ast_channel *chan, const char *data)
{
ast_indicate(chan, AST_CONTROL_CONGESTION);
/* Don't change state of an UP channel, just indicate
congestion in audio */
if (chan->_state != AST_STATE_UP)
ast_setstate(chan, AST_STATE_BUSY);
wait_for_hangup(chan, data);
return -1;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_answer(struct ast_channel *chan, const char *data)
{
int delay = 0;
int answer_cdr = 1;
char *parse;
AST_DECLARE_APP_ARGS(args,
AST_APP_ARG(delay);
AST_APP_ARG(answer_cdr);
);
if (ast_strlen_zero(data)) {
return __ast_answer(chan, 0, 1);
}
parse = ast_strdupa(data);
AST_STANDARD_APP_ARGS(args, parse);
if (!ast_strlen_zero(args.delay) && (chan->_state != AST_STATE_UP))
delay = atoi(data);
if (delay < 0) {
delay = 0;
}
if (!ast_strlen_zero(args.answer_cdr) && !strcasecmp(args.answer_cdr, "nocdr")) {
answer_cdr = 0;
}
return __ast_answer(chan, delay, answer_cdr);
}
static int pbx_builtin_incomplete(struct ast_channel *chan, const char *data)
{
const char *options = data;
int answer = 1;
/* Some channels can receive DTMF in unanswered state; some cannot */
if (!ast_strlen_zero(options) && strchr(options, 'n')) {
answer = 0;
}
/* If the channel is hungup, stop waiting */
if (ast_check_hangup(chan)) {
return -1;
} else if (chan->_state != AST_STATE_UP && answer) {
__ast_answer(chan, 0, 1);
}
ast_indicate(chan, AST_CONTROL_INCOMPLETE);
return AST_PBX_INCOMPLETE;
}
AST_APP_OPTIONS(resetcdr_opts, {
AST_APP_OPTION('w', AST_CDR_FLAG_POSTED),
AST_APP_OPTION('a', AST_CDR_FLAG_LOCKED),
AST_APP_OPTION('v', AST_CDR_FLAG_KEEP_VARS),
AST_APP_OPTION('e', AST_CDR_FLAG_POST_ENABLE),
});
/*!
* \ingroup applications
*/
static int pbx_builtin_resetcdr(struct ast_channel *chan, const char *data)
{
char *args;
struct ast_flags flags = { 0 };
if (!ast_strlen_zero(data)) {
args = ast_strdupa(data);
ast_app_parse_options(resetcdr_opts, &flags, NULL, args);
}
ast_cdr_reset(chan->cdr, &flags);
return 0;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_setamaflags(struct ast_channel *chan, const char *data)
{
/* Copy the AMA Flags as specified */
ast_channel_lock(chan);
ast_cdr_setamaflags(chan, data ? data : "");
ast_channel_unlock(chan);
return 0;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_hangup(struct ast_channel *chan, const char *data)
{
ast_set_hangupsource(chan, "dialplan/builtin", 0);
if (!ast_strlen_zero(data)) {
int cause;
char *endptr;
if ((cause = ast_str2cause(data)) > -1) {
chan->hangupcause = cause;
return -1;
}
cause = strtol((const char *) data, &endptr, 10);
if (cause != 0 || (data != endptr)) {
chan->hangupcause = cause;
return -1;
}
ast_log(LOG_WARNING, "Invalid cause given to Hangup(): \"%s\"\n", (char *) data);
}
if (!chan->hangupcause) {
chan->hangupcause = AST_CAUSE_NORMAL_CLEARING;
}
return -1;
}
/*!
* \ingroup functions
*/
static int testtime_write(struct ast_channel *chan, const char *cmd, char *var, const char *value)
{
struct ast_tm tm;
struct timeval tv;
char *remainder, result[30], timezone[80];
/* Turn off testing? */
if (!pbx_checkcondition(value)) {
pbx_builtin_setvar_helper(chan, "TESTTIME", NULL);
return 0;
}
/* Parse specified time */
if (!(remainder = ast_strptime(value, "%Y/%m/%d %H:%M:%S", &tm))) {
return -1;
}
sscanf(remainder, "%79s", timezone);
tv = ast_mktime(&tm, S_OR(timezone, NULL));
snprintf(result, sizeof(result), "%ld", (long) tv.tv_sec);
pbx_builtin_setvar_helper(chan, "__TESTTIME", result);
return 0;
}
static struct ast_custom_function testtime_function = {
.name = "TESTTIME",
.write = testtime_write,
};
/*!
* \ingroup applications
*/
static int pbx_builtin_gotoiftime(struct ast_channel *chan, const char *data)
{
char *s, *ts, *branch1, *branch2, *branch;
struct ast_timing timing;
const char *ctime;
struct timeval tv = ast_tvnow();
long timesecs;
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "GotoIfTime requires an argument:\n <time range>,<days of week>,<days of month>,<months>[,<timezone>]?'labeliftrue':'labeliffalse'\n");
return -1;
}
ts = s = ast_strdupa(data);
if (chan) {
ast_channel_lock(chan);
if ((ctime = pbx_builtin_getvar_helper(chan, "TESTTIME")) && sscanf(ctime, "%ld", ×ecs) == 1) {
tv.tv_sec = timesecs;
} else if (ctime) {
ast_log(LOG_WARNING, "Using current time to evaluate\n");
/* Reset when unparseable */
pbx_builtin_setvar_helper(chan, "TESTTIME", NULL);
}
ast_channel_unlock(chan);
}
/* Separate the Goto path */
strsep(&ts, "?");
branch1 = strsep(&ts,":");
branch2 = strsep(&ts,"");
/* struct ast_include include contained garbage here, fixed by zeroing it on get_timerange */
if (ast_build_timing(&timing, s) && ast_check_timing2(&timing, tv)) {
branch = branch1;
} else {
branch = branch2;
}
ast_destroy_timing(&timing);
if (ast_strlen_zero(branch)) {
ast_debug(1, "Not taking any branch\n");
return 0;
}
return pbx_builtin_goto(chan, branch);
}
/*!
* \ingroup applications
*/
static int pbx_builtin_execiftime(struct ast_channel *chan, const char *data)
{
char *s, *appname;
struct ast_timing timing;
struct ast_app *app;
static const char * const usage = "ExecIfTime requires an argument:\n <time range>,<days of week>,<days of month>,<months>[,<timezone>]?<appname>[(<appargs>)]";
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "%s\n", usage);
return -1;
}
appname = ast_strdupa(data);
s = strsep(&appname, "?"); /* Separate the timerange and application name/data */
if (!appname) { /* missing application */
ast_log(LOG_WARNING, "%s\n", usage);
return -1;
}
if (!ast_build_timing(&timing, s)) {
ast_log(LOG_WARNING, "Invalid Time Spec: %s\nCorrect usage: %s\n", s, usage);
ast_destroy_timing(&timing);
return -1;
}
if (!ast_check_timing(&timing)) { /* outside the valid time window, just return */
ast_destroy_timing(&timing);
return 0;
}
ast_destroy_timing(&timing);
/* now split appname(appargs) */
if ((s = strchr(appname, '('))) {
char *e;
*s++ = '\0';
if ((e = strrchr(s, ')')))
*e = '\0';
else
ast_log(LOG_WARNING, "Failed to find closing parenthesis\n");
}
if ((app = pbx_findapp(appname))) {
return pbx_exec(chan, app, S_OR(s, ""));
} else {
ast_log(LOG_WARNING, "Cannot locate application %s\n", appname);
return -1;
}
}
/*!
* \ingroup applications
*/
static int pbx_builtin_wait(struct ast_channel *chan, const char *data)
{
int ms;
/* Wait for "n" seconds */
if (!ast_app_parse_timelen(data, &ms, TIMELEN_SECONDS) && ms > 0) {
return ast_safe_sleep(chan, ms);
}
return 0;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_waitexten(struct ast_channel *chan, const char *data)
{
int ms, res;
struct ast_flags flags = {0};
char *opts[1] = { NULL };
char *parse;
AST_DECLARE_APP_ARGS(args,
AST_APP_ARG(timeout);
AST_APP_ARG(options);
);
if (!ast_strlen_zero(data)) {
parse = ast_strdupa(data);
AST_STANDARD_APP_ARGS(args, parse);
} else
memset(&args, 0, sizeof(args));
if (args.options)
ast_app_parse_options(waitexten_opts, &flags, opts, args.options);
if (ast_test_flag(&flags, WAITEXTEN_MOH) && !opts[0] ) {
ast_log(LOG_WARNING, "The 'm' option has been specified for WaitExten without a class.\n");
} else if (ast_test_flag(&flags, WAITEXTEN_MOH)) {
ast_indicate_data(chan, AST_CONTROL_HOLD, S_OR(opts[0], NULL), strlen(opts[0]));
} else if (ast_test_flag(&flags, WAITEXTEN_DIALTONE)) {
struct ast_tone_zone_sound *ts = ast_get_indication_tone(chan->zone, "dial");
if (ts) {
ast_playtones_start(chan, 0, ts->data, 0);
ts = ast_tone_zone_sound_unref(ts);
} else {
ast_tonepair_start(chan, 350, 440, 0, 0);
}
}
/* Wait for "n" seconds */
if (!ast_app_parse_timelen(args.timeout, &ms, TIMELEN_SECONDS) && ms > 0) {
/* Yay! */
} else if (chan->pbx) {
ms = chan->pbx->rtimeoutms;
} else {
ms = 10000;
}
res = ast_waitfordigit(chan, ms);
if (!res) {
if (ast_check_hangup(chan)) {
/* Call is hungup for some reason. */
res = -1;
} else if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 1,
S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
ast_verb(3, "Timeout on %s, continuing...\n", chan->name);
} else if (ast_exists_extension(chan, chan->context, "t", 1,
S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
ast_verb(3, "Timeout on %s, going to 't'\n", chan->name);
set_ext_pri(chan, "t", 0); /* 0 will become 1, next time through the loop */
} else if (ast_exists_extension(chan, chan->context, "e", 1,
S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
raise_exception(chan, "RESPONSETIMEOUT", 0); /* 0 will become 1, next time through the loop */
} else {
ast_log(LOG_WARNING, "Timeout but no rule 't' or 'e' in context '%s'\n",
chan->context);
res = -1;
}
}
if (ast_test_flag(&flags, WAITEXTEN_MOH))
ast_indicate(chan, AST_CONTROL_UNHOLD);
else if (ast_test_flag(&flags, WAITEXTEN_DIALTONE))
ast_playtones_stop(chan);
return res;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_background(struct ast_channel *chan, const char *data)
{
int res = 0;
int mres = 0;
struct ast_flags flags = {0};
char *parse, exten[2] = "";
AST_DECLARE_APP_ARGS(args,
AST_APP_ARG(filename);
AST_APP_ARG(options);
AST_APP_ARG(lang);
AST_APP_ARG(context);
);
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "Background requires an argument (filename)\n");
return -1;
}
parse = ast_strdupa(data);
AST_STANDARD_APP_ARGS(args, parse);
if (ast_strlen_zero(args.lang))
args.lang = (char *)chan->language; /* XXX this is const */
if (ast_strlen_zero(args.context)) {
const char *context;
ast_channel_lock(chan);
if ((context = pbx_builtin_getvar_helper(chan, "MACRO_CONTEXT"))) {
args.context = ast_strdupa(context);
} else {
args.context = chan->context;
}
ast_channel_unlock(chan);
}
if (args.options) {
if (!strcasecmp(args.options, "skip"))
flags.flags = BACKGROUND_SKIP;
else if (!strcasecmp(args.options, "noanswer"))
flags.flags = BACKGROUND_NOANSWER;
else
ast_app_parse_options(background_opts, &flags, NULL, args.options);
}
/* Answer if need be */
if (chan->_state != AST_STATE_UP) {
if (ast_test_flag(&flags, BACKGROUND_SKIP)) {
goto done;
} else if (!ast_test_flag(&flags, BACKGROUND_NOANSWER)) {
res = ast_answer(chan);
}
}
if (!res) {
char *back = ast_strip(args.filename);
char *front;
ast_stopstream(chan); /* Stop anything playing */
/* Stream the list of files */
while (!res && (front = strsep(&back, "&")) ) {
if ( (res = ast_streamfile(chan, front, args.lang)) ) {
ast_log(LOG_WARNING, "ast_streamfile failed on %s for %s\n", chan->name, (char*)data);
res = 0;
mres = 1;
break;
}
if (ast_test_flag(&flags, BACKGROUND_PLAYBACK)) {
res = ast_waitstream(chan, "");
} else if (ast_test_flag(&flags, BACKGROUND_MATCHEXTEN)) {
res = ast_waitstream_exten(chan, args.context);
} else {
res = ast_waitstream(chan, AST_DIGIT_ANY);
}
ast_stopstream(chan);
}
}
/*
* If the single digit DTMF is an extension in the specified context, then
* go there and signal no DTMF. Otherwise, we should exit with that DTMF.
* If we're in Macro, we'll exit and seek that DTMF as the beginning of an
* extension in the Macro's calling context. If we're not in Macro, then
* we'll simply seek that extension in the calling context. Previously,
* someone complained about the behavior as it related to the interior of a
* Gosub routine, and the fix (#14011) inadvertently broke FreePBX
* (#14940). This change should fix both of these situations, but with the
* possible incompatibility that if a single digit extension does not exist
* (but a longer extension COULD have matched), it would have previously
* gone immediately to the "i" extension, but will now need to wait for a
* timeout.
*
* Later, we had to add a flag to disable this workaround, because AGI
* users can EXEC Background and reasonably expect that the DTMF code will
* be returned (see #16434).
*/
if (!ast_test_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS)
&& (exten[0] = res)
&& ast_canmatch_extension(chan, args.context, exten, 1,
S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))
&& !ast_matchmore_extension(chan, args.context, exten, 1,
S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
snprintf(chan->exten, sizeof(chan->exten), "%c", res);
ast_copy_string(chan->context, args.context, sizeof(chan->context));
chan->priority = 0;
res = 0;
}
done:
pbx_builtin_setvar_helper(chan, "BACKGROUNDSTATUS", mres ? "FAILED" : "SUCCESS");
return res;
}
/*! Goto
* \ingroup applications
*/
static int pbx_builtin_goto(struct ast_channel *chan, const char *data)
{
int res = ast_parseable_goto(chan, data);
if (!res)
ast_verb(3, "Goto (%s,%s,%d)\n", chan->context, chan->exten, chan->priority + 1);
return res;
}
int pbx_builtin_serialize_variables(struct ast_channel *chan, struct ast_str **buf)
{
struct ast_var_t *variables;
const char *var, *val;
int total = 0;
if (!chan)
return 0;
ast_str_reset(*buf);
ast_channel_lock(chan);
AST_LIST_TRAVERSE(&chan->varshead, variables, entries) {
if ((var = ast_var_name(variables)) && (val = ast_var_value(variables))
/* && !ast_strlen_zero(var) && !ast_strlen_zero(val) */
) {
if (ast_str_append(buf, 0, "%s=%s\n", var, val) < 0) {
ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
break;
} else
total++;
} else
break;
}
ast_channel_unlock(chan);
return total;
}
const char *pbx_builtin_getvar_helper(struct ast_channel *chan, const char *name)
{
struct ast_var_t *variables;
const char *ret = NULL;
int i;
struct varshead *places[2] = { NULL, &globals };
if (!name)
return NULL;
if (chan) {
ast_channel_lock(chan);
places[0] = &chan->varshead;
}
for (i = 0; i < 2; i++) {
if (!places[i])
continue;
if (places[i] == &globals)
ast_rwlock_rdlock(&globalslock);
AST_LIST_TRAVERSE(places[i], variables, entries) {
if (!strcmp(name, ast_var_name(variables))) {
ret = ast_var_value(variables);
break;
}
}
if (places[i] == &globals)
ast_rwlock_unlock(&globalslock);
if (ret)
break;
}
if (chan)
ast_channel_unlock(chan);
return ret;
}
void pbx_builtin_pushvar_helper(struct ast_channel *chan, const char *name, const char *value)
{
struct ast_var_t *newvariable;
struct varshead *headp;
if (name[strlen(name)-1] == ')') {
char *function = ast_strdupa(name);
ast_log(LOG_WARNING, "Cannot push a value onto a function\n");
ast_func_write(chan, function, value);
return;
}
if (chan) {
ast_channel_lock(chan);
headp = &chan->varshead;
} else {
ast_rwlock_wrlock(&globalslock);
headp = &globals;
}
if (value) {
if (headp == &globals)
ast_verb(2, "Setting global variable '%s' to '%s'\n", name, value);
newvariable = ast_var_assign(name, value);
AST_LIST_INSERT_HEAD(headp, newvariable, entries);
}
if (chan)
ast_channel_unlock(chan);
else
ast_rwlock_unlock(&globalslock);
}
int pbx_builtin_setvar_helper(struct ast_channel *chan, const char *name, const char *value)
{
struct ast_var_t *newvariable;
struct varshead *headp;
const char *nametail = name;
if (name[strlen(name) - 1] == ')') {
char *function = ast_strdupa(name);
return ast_func_write(chan, function, value);
}
if (chan) {
ast_channel_lock(chan);
headp = &chan->varshead;
} else {
ast_rwlock_wrlock(&globalslock);
headp = &globals;
}
/* For comparison purposes, we have to strip leading underscores */
if (*nametail == '_') {
nametail++;
if (*nametail == '_')
nametail++;
}
AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
if (strcmp(ast_var_name(newvariable), nametail) == 0) {
/* there is already such a variable, delete it */
AST_LIST_REMOVE_CURRENT(entries);
ast_var_delete(newvariable);
break;
}
}
AST_LIST_TRAVERSE_SAFE_END;
if (value) {
if (headp == &globals)
ast_verb(2, "Setting global variable '%s' to '%s'\n", name, value);
newvariable = ast_var_assign(name, value);
AST_LIST_INSERT_HEAD(headp, newvariable, entries);
manager_event(EVENT_FLAG_DIALPLAN, "VarSet",
"Channel: %s\r\n"
"Variable: %s\r\n"
"Value: %s\r\n"
"Uniqueid: %s\r\n",
chan ? chan->name : "none", name, value,
chan ? chan->uniqueid : "none");
}
if (chan)
ast_channel_unlock(chan);
else
ast_rwlock_unlock(&globalslock);
return 0;
}
int pbx_builtin_setvar(struct ast_channel *chan, const char *data)
{
char *name, *value, *mydata;
if (ast_compat_app_set) {
return pbx_builtin_setvar_multiple(chan, data);
}
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "Set requires one variable name/value pair.\n");
return 0;
}
mydata = ast_strdupa(data);
name = strsep(&mydata, "=");
value = mydata;
if (!value) {
ast_log(LOG_WARNING, "Set requires an '=' to be a valid assignment.\n");
return 0;
}
if (strchr(name, ' ')) {
ast_log(LOG_WARNING, "Please avoid unnecessary spaces on variables as it may lead to unexpected results ('%s' set to '%s').\n", name, mydata);
}
pbx_builtin_setvar_helper(chan, name, value);
return 0;
}
int pbx_builtin_setvar_multiple(struct ast_channel *chan, const char *vdata)
{
char *data;
int x;
AST_DECLARE_APP_ARGS(args,
AST_APP_ARG(pair)[24];
);
AST_DECLARE_APP_ARGS(pair,
AST_APP_ARG(name);
AST_APP_ARG(value);
);
if (ast_strlen_zero(vdata)) {
ast_log(LOG_WARNING, "MSet requires at least one variable name/value pair.\n");
return 0;
}
data = ast_strdupa(vdata);
AST_STANDARD_APP_ARGS(args, data);
for (x = 0; x < args.argc; x++) {
AST_NONSTANDARD_APP_ARGS(pair, args.pair[x], '=');
if (pair.argc == 2) {
pbx_builtin_setvar_helper(chan, pair.name, pair.value);
if (strchr(pair.name, ' '))
ast_log(LOG_WARNING, "Please avoid unnecessary spaces on variables as it may lead to unexpected results ('%s' set to '%s').\n", pair.name, pair.value);
} else if (!chan) {
ast_log(LOG_WARNING, "MSet: ignoring entry '%s' with no '='\n", pair.name);
} else {
ast_log(LOG_WARNING, "MSet: ignoring entry '%s' with no '=' (in %s@%s:%d\n", pair.name, chan->exten, chan->context, chan->priority);
}
}
return 0;
}
int pbx_builtin_importvar(struct ast_channel *chan, const char *data)
{
char *name;
char *value;
char *channel;
char tmp[VAR_BUF_SIZE];
static int deprecation_warning = 0;
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "Ignoring, since there is no variable to set\n");
return 0;
}
tmp[0] = 0;
if (!deprecation_warning) {
ast_log(LOG_WARNING, "ImportVar is deprecated. Please use Set(varname=${IMPORT(channel,variable)}) instead.\n");
deprecation_warning = 1;
}
value = ast_strdupa(data);
name = strsep(&value,"=");
channel = strsep(&value,",");
if (channel && value && name) { /*! \todo XXX should do !ast_strlen_zero(..) of the args ? */
struct ast_channel *chan2 = ast_channel_get_by_name(channel);
if (chan2) {
char *s = alloca(strlen(value) + 4);
if (s) {
sprintf(s, "${%s}", value);
pbx_substitute_variables_helper(chan2, s, tmp, sizeof(tmp) - 1);
}
chan2 = ast_channel_unref(chan2);
}
pbx_builtin_setvar_helper(chan, name, tmp);
}
return(0);
}
static int pbx_builtin_noop(struct ast_channel *chan, const char *data)
{
return 0;
}
void pbx_builtin_clear_globals(void)
{
struct ast_var_t *vardata;
ast_rwlock_wrlock(&globalslock);
while ((vardata = AST_LIST_REMOVE_HEAD(&globals, entries)))
ast_var_delete(vardata);
ast_rwlock_unlock(&globalslock);
}
int pbx_checkcondition(const char *condition)
{
int res;
if (ast_strlen_zero(condition)) { /* NULL or empty strings are false */
return 0;
} else if (sscanf(condition, "%30d", &res) == 1) { /* Numbers are evaluated for truth */
return res;
} else { /* Strings are true */
return 1;
}
}
static int pbx_builtin_gotoif(struct ast_channel *chan, const char *data)
{
char *condition, *branch1, *branch2, *branch;
char *stringp;
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "Ignoring, since there is no variable to check\n");
return 0;
}
stringp = ast_strdupa(data);
condition = strsep(&stringp,"?");
branch1 = strsep(&stringp,":");
branch2 = strsep(&stringp,"");
branch = pbx_checkcondition(condition) ? branch1 : branch2;
if (ast_strlen_zero(branch)) {
ast_debug(1, "Not taking any branch\n");
return 0;
}
return pbx_builtin_goto(chan, branch);
}
static int pbx_builtin_saynumber(struct ast_channel *chan, const char *data)
{
char tmp[256];
char *number = tmp;
char *options;
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "SayNumber requires an argument (number)\n");
return -1;
}
ast_copy_string(tmp, data, sizeof(tmp));
strsep(&number, ",");
options = strsep(&number, ",");
if (options) {
if ( strcasecmp(options, "f") && strcasecmp(options, "m") &&
strcasecmp(options, "c") && strcasecmp(options, "n") ) {
ast_log(LOG_WARNING, "SayNumber gender option is either 'f', 'm', 'c' or 'n'\n");
return -1;
}
}
if (ast_say_number(chan, atoi(tmp), "", chan->language, options)) {
ast_log(LOG_WARNING, "We were unable to say the number %s, is it too large?\n", tmp);
}
return 0;
}
static int pbx_builtin_saydigits(struct ast_channel *chan, const char *data)
{
int res = 0;
if (data)
res = ast_say_digit_str(chan, data, "", chan->language);
return res;
}
static int pbx_builtin_saycharacters(struct ast_channel *chan, const char *data)
{
int res = 0;
if (data)
res = ast_say_character_str(chan, data, "", chan->language);
return res;
}
static int pbx_builtin_sayphonetic(struct ast_channel *chan, const char *data)
{
int res = 0;
if (data)
res = ast_say_phonetic_str(chan, data, "", chan->language);
return res;
}
static void device_state_cb(const struct ast_event *event, void *unused)
{
const char *device;
struct statechange *sc;
device = ast_event_get_ie_str(event, AST_EVENT_IE_DEVICE);
if (ast_strlen_zero(device)) {
ast_log(LOG_ERROR, "Received invalid event that had no device IE\n");
return;
}
if (!(sc = ast_calloc(1, sizeof(*sc) + strlen(device) + 1)))
return;
strcpy(sc->dev, device);
if (ast_taskprocessor_push(device_state_tps, handle_statechange, sc) < 0) {
ast_free(sc);
}
}
/*!
* \internal
* \brief Implements the hints data provider.
*/
static int hints_data_provider_get(const struct ast_data_search *search,
struct ast_data *data_root)
{
struct ast_data *data_hint;
struct ast_hint *hint;
int watchers;
struct ao2_iterator i;
if (ao2_container_count(hints) == 0) {
return 0;
}
i = ao2_iterator_init(hints, 0);
for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) {
watchers = ao2_container_count(hint->callbacks);
data_hint = ast_data_add_node(data_root, "hint");
if (!data_hint) {
continue;
}
ast_data_add_str(data_hint, "extension", ast_get_extension_name(hint->exten));
ast_data_add_str(data_hint, "context", ast_get_context_name(ast_get_extension_context(hint->exten)));
ast_data_add_str(data_hint, "application", ast_get_extension_app(hint->exten));
ast_data_add_str(data_hint, "state", ast_extension_state2str(hint->laststate));
ast_data_add_int(data_hint, "watchers", watchers);
if (!ast_data_search_match(search, data_hint)) {
ast_data_remove_node(data_root, data_hint);
}
}
ao2_iterator_destroy(&i);
return 0;
}
static const struct ast_data_handler hints_data_provider = {
.version = AST_DATA_HANDLER_VERSION,
.get = hints_data_provider_get
};
static const struct ast_data_entry pbx_data_providers[] = {
AST_DATA_ENTRY("asterisk/core/hints", &hints_data_provider),
};
int load_pbx(void)
{
int x;
/* Initialize the PBX */
ast_verb(1, "Asterisk PBX Core Initializing\n");
if (!(device_state_tps = ast_taskprocessor_get("pbx-core", 0))) {
ast_log(LOG_WARNING, "failed to create pbx-core taskprocessor\n");
}
ast_verb(1, "Registering builtin applications:\n");
ast_cli_register_multiple(pbx_cli, ARRAY_LEN(pbx_cli));
ast_data_register_multiple_core(pbx_data_providers, ARRAY_LEN(pbx_data_providers));
__ast_custom_function_register(&exception_function, NULL);
__ast_custom_function_register(&testtime_function, NULL);
/* Register builtin applications */
for (x = 0; x < ARRAY_LEN(builtins); x++) {
ast_verb(1, "[%s]\n", builtins[x].name);
if (ast_register_application2(builtins[x].name, builtins[x].execute, NULL, NULL, NULL)) {
ast_log(LOG_ERROR, "Unable to register builtin application '%s'\n", builtins[x].name);
return -1;
}
}
/* Register manager application */
ast_manager_register_xml("ShowDialPlan", EVENT_FLAG_CONFIG | EVENT_FLAG_REPORTING, manager_show_dialplan);
if (!(device_state_sub = ast_event_subscribe(AST_EVENT_DEVICE_STATE, device_state_cb, "pbx Device State Change", NULL,
AST_EVENT_IE_END))) {
return -1;
}
return 0;
}
/*
* Lock context list functions ...
*/
int ast_wrlock_contexts(void)
{
return ast_mutex_lock(&conlock);
}
int ast_rdlock_contexts(void)
{
return ast_mutex_lock(&conlock);
}
int ast_unlock_contexts(void)
{
return ast_mutex_unlock(&conlock);
}
/*
* Lock context ...
*/
int ast_wrlock_context(struct ast_context *con)
{
return ast_rwlock_wrlock(&con->lock);
}
int ast_rdlock_context(struct ast_context *con)
{
return ast_rwlock_rdlock(&con->lock);
}
int ast_unlock_context(struct ast_context *con)
{
return ast_rwlock_unlock(&con->lock);
}
/*
* Name functions ...
*/
const char *ast_get_context_name(struct ast_context *con)
{
return con ? con->name : NULL;
}
struct ast_context *ast_get_extension_context(struct ast_exten *exten)
{
return exten ? exten->parent : NULL;
}
const char *ast_get_extension_name(struct ast_exten *exten)
{
return exten ? exten->exten : NULL;
}
const char *ast_get_extension_label(struct ast_exten *exten)
{
return exten ? exten->label : NULL;
}
const char *ast_get_include_name(struct ast_include *inc)
{
return inc ? inc->name : NULL;
}
const char *ast_get_ignorepat_name(struct ast_ignorepat *ip)
{
return ip ? ip->pattern : NULL;
}
int ast_get_extension_priority(struct ast_exten *exten)
{
return exten ? exten->priority : -1;
}
/*
* Registrar info functions ...
*/
const char *ast_get_context_registrar(struct ast_context *c)
{
return c ? c->registrar : NULL;
}
const char *ast_get_extension_registrar(struct ast_exten *e)
{
return e ? e->registrar : NULL;
}
const char *ast_get_include_registrar(struct ast_include *i)
{
return i ? i->registrar : NULL;
}
const char *ast_get_ignorepat_registrar(struct ast_ignorepat *ip)
{
return ip ? ip->registrar : NULL;
}
int ast_get_extension_matchcid(struct ast_exten *e)
{
return e ? e->matchcid : 0;
}
const char *ast_get_extension_cidmatch(struct ast_exten *e)
{
return e ? e->cidmatch : NULL;
}
const char *ast_get_extension_app(struct ast_exten *e)
{
return e ? e->app : NULL;
}
void *ast_get_extension_app_data(struct ast_exten *e)
{
return e ? e->data : NULL;
}
const char *ast_get_switch_name(struct ast_sw *sw)
{
return sw ? sw->name : NULL;
}
const char *ast_get_switch_data(struct ast_sw *sw)
{
return sw ? sw->data : NULL;
}
int ast_get_switch_eval(struct ast_sw *sw)
{
return sw->eval;
}
const char *ast_get_switch_registrar(struct ast_sw *sw)
{
return sw ? sw->registrar : NULL;
}
/*
* Walking functions ...
*/
struct ast_context *ast_walk_contexts(struct ast_context *con)
{
return con ? con->next : contexts;
}
struct ast_exten *ast_walk_context_extensions(struct ast_context *con,
struct ast_exten *exten)
{
if (!exten)
return con ? con->root : NULL;
else
return exten->next;
}
struct ast_sw *ast_walk_context_switches(struct ast_context *con,
struct ast_sw *sw)
{
if (!sw)
return con ? AST_LIST_FIRST(&con->alts) : NULL;
else
return AST_LIST_NEXT(sw, list);
}
struct ast_exten *ast_walk_extension_priorities(struct ast_exten *exten,
struct ast_exten *priority)
{
return priority ? priority->peer : exten;
}
struct ast_include *ast_walk_context_includes(struct ast_context *con,
struct ast_include *inc)
{
if (!inc)
return con ? con->includes : NULL;
else
return inc->next;
}
struct ast_ignorepat *ast_walk_context_ignorepats(struct ast_context *con,
struct ast_ignorepat *ip)
{
if (!ip)
return con ? con->ignorepats : NULL;
else
return ip->next;
}
int ast_context_verify_includes(struct ast_context *con)
{
struct ast_include *inc = NULL;
int res = 0;
while ( (inc = ast_walk_context_includes(con, inc)) ) {
if (ast_context_find(inc->rname))
continue;
res = -1;
ast_log(LOG_WARNING, "Context '%s' tries to include nonexistent context '%s'\n",
ast_get_context_name(con), inc->rname);
break;
}
return res;
}
static int __ast_goto_if_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, int async)
{
int (*goto_func)(struct ast_channel *chan, const char *context, const char *exten, int priority);
if (!chan)
return -2;
if (context == NULL)
context = chan->context;
if (exten == NULL)
exten = chan->exten;
goto_func = (async) ? ast_async_goto : ast_explicit_goto;
if (ast_exists_extension(chan, context, exten, priority,
S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL)))
return goto_func(chan, context, exten, priority);
else {
return AST_PBX_GOTO_FAILED;
}
}
int ast_goto_if_exists(struct ast_channel *chan, const char* context, const char *exten, int priority)
{
return __ast_goto_if_exists(chan, context, exten, priority, 0);
}
int ast_async_goto_if_exists(struct ast_channel *chan, const char * context, const char *exten, int priority)
{
return __ast_goto_if_exists(chan, context, exten, priority, 1);
}
static int pbx_parseable_goto(struct ast_channel *chan, const char *goto_string, int async)
{
char *exten, *pri, *context;
char *stringp;
int ipri;
int mode = 0;
if (ast_strlen_zero(goto_string)) {
ast_log(LOG_WARNING, "Goto requires an argument ([[context,]extension,]priority)\n");
return -1;
}
stringp = ast_strdupa(goto_string);
context = strsep(&stringp, ","); /* guaranteed non-null */
exten = strsep(&stringp, ",");
pri = strsep(&stringp, ",");
if (!exten) { /* Only a priority in this one */
pri = context;
exten = NULL;
context = NULL;
} else if (!pri) { /* Only an extension and priority in this one */
pri = exten;
exten = context;
context = NULL;
}
if (*pri == '+') {
mode = 1;
pri++;
} else if (*pri == '-') {
mode = -1;
pri++;
}
if (sscanf(pri, "%30d", &ipri) != 1) {
ipri = ast_findlabel_extension(chan, context ? context : chan->context,
exten ? exten : chan->exten, pri,
S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL));
if (ipri < 1) {
ast_log(LOG_WARNING, "Priority '%s' must be a number > 0, or valid label\n", pri);
return -1;
} else
mode = 0;
}
/* At this point we have a priority and maybe an extension and a context */
if (mode)
ipri = chan->priority + (ipri * mode);
if (async)
ast_async_goto(chan, context, exten, ipri);
else
ast_explicit_goto(chan, context, exten, ipri);
return 0;
}
int ast_parseable_goto(struct ast_channel *chan, const char *goto_string)
{
return pbx_parseable_goto(chan, goto_string, 0);
}
int ast_async_parseable_goto(struct ast_channel *chan, const char *goto_string)
{
return pbx_parseable_goto(chan, goto_string, 1);
}
char *ast_complete_applications(const char *line, const char *word, int state)
{
struct ast_app *app = NULL;
int which = 0;
char *ret = NULL;
size_t wordlen = strlen(word);
AST_RWLIST_RDLOCK(&apps);
AST_RWLIST_TRAVERSE(&apps, app, list) {
if (!strncasecmp(word, app->name, wordlen) && ++which > state) {
ret = ast_strdup(app->name);
break;
}
}
AST_RWLIST_UNLOCK(&apps);
return ret;
}
static int hint_hash(const void *obj, const int flags)
{
const struct ast_hint *hint = obj;
const char *exten_name;
int res;
exten_name = ast_get_extension_name(hint->exten);
if (ast_strlen_zero(exten_name)) {
/*
* If the exten or extension name isn't set, return 0 so that
* the ao2_find() search will start in the first bucket.
*/
res = 0;
} else {
res = ast_str_case_hash(exten_name);
}
return res;
}
static int hint_cmp(void *obj, void *arg, int flags)
{
const struct ast_hint *hint = obj;
const struct ast_exten *exten = arg;
return (hint->exten == exten) ? CMP_MATCH | CMP_STOP : 0;
}
static int statecbs_cmp(void *obj, void *arg, int flags)
{
const struct ast_state_cb *state_cb = obj;
ast_state_cb_type change_cb = arg;
return (state_cb->change_cb == change_cb) ? CMP_MATCH | CMP_STOP : 0;
}
int ast_pbx_init(void)
{
hints = ao2_container_alloc(HASH_EXTENHINT_SIZE, hint_hash, hint_cmp);
statecbs = ao2_container_alloc(1, NULL, statecbs_cmp);
return (hints && statecbs) ? 0 : -1;
}
|