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 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586
|
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 1999 - 2006, Digium, Inc.
*
* Mark Spencer <markster@digium.com>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*!
* \file
* \brief Implementation of Session Initiation Protocol
*
* Implementation of RFC 3261 - without S/MIME, TCP and TLS support
* Configuration file \link Config_sip sip.conf \endlink
*
* \todo SIP over TCP
* \todo SIP over TLS
* \todo Better support of forking
*/
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <errno.h>
#include <stdlib.h>
#include <fcntl.h>
#include <netdb.h>
#include <signal.h>
#include <sys/signal.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <regex.h>
#include "asterisk.h"
ASTERISK_FILE_VERSION(__FILE__, "$Revision: 45380 $")
#include "asterisk/lock.h"
#include "asterisk/channel.h"
#include "asterisk/config.h"
#include "asterisk/logger.h"
#include "asterisk/module.h"
#include "asterisk/pbx.h"
#include "asterisk/options.h"
#include "asterisk/lock.h"
#include "asterisk/sched.h"
#include "asterisk/io.h"
#include "asterisk/rtp.h"
#include "asterisk/acl.h"
#include "asterisk/manager.h"
#include "asterisk/callerid.h"
#include "asterisk/cli.h"
#include "asterisk/app.h"
#include "asterisk/musiconhold.h"
#include "asterisk/dsp.h"
#include "asterisk/features.h"
#include "asterisk/acl.h"
#include "asterisk/srv.h"
#include "asterisk/astdb.h"
#include "asterisk/causes.h"
#include "asterisk/utils.h"
#include "asterisk/file.h"
#include "asterisk/astobj.h"
#include "asterisk/dnsmgr.h"
#include "asterisk/devicestate.h"
#include "asterisk/linkedlists.h"
#ifdef OSP_SUPPORT
#include "asterisk/astosp.h"
#endif
#ifndef DEFAULT_USERAGENT
#define DEFAULT_USERAGENT "Asterisk PBX"
#endif
#define VIDEO_CODEC_MASK 0x1fc0000 /* Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
#ifndef IPTOS_MINCOST
#define IPTOS_MINCOST 0x02
#endif
/* #define VOCAL_DATA_HACK */
#define SIPDUMPER
#define DEFAULT_DEFAULT_EXPIRY 120
#define DEFAULT_MAX_EXPIRY 3600
#define DEFAULT_REGISTRATION_TIMEOUT 20
#define DEFAULT_MAX_FORWARDS "70"
/* guard limit must be larger than guard secs */
/* guard min must be < 1000, and should be >= 250 */
#define EXPIRY_GUARD_SECS 15 /* How long before expiry do we reregister */
#define EXPIRY_GUARD_LIMIT 30 /* Below here, we use EXPIRY_GUARD_PCT instead of
EXPIRY_GUARD_SECS */
#define EXPIRY_GUARD_MIN 500 /* This is the minimum guard time applied. If
GUARD_PCT turns out to be lower than this, it
will use this time instead.
This is in milliseconds. */
#define EXPIRY_GUARD_PCT 0.20 /* Percentage of expires timeout to use when
below EXPIRY_GUARD_LIMIT */
#define SIP_LEN_CONTACT 256
static int max_expiry = DEFAULT_MAX_EXPIRY;
static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
#ifndef MAX
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#endif
#define CALLERID_UNKNOWN "Unknown"
#define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
#define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
#define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
#define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
/* 2 * 500 ms in RFC 3261 */
#define MAX_RETRANS 6 /* Try only 6 times for retransmissions, a total of 7 transmissions */
#define MAX_AUTHTRIES 3 /* Try authentication three times, then fail */
#define DEBUG_READ 0 /* Recieved data */
#define DEBUG_SEND 1 /* Transmit data */
static const char desc[] = "Session Initiation Protocol (SIP)";
static const char channeltype[] = "SIP";
static const char config[] = "sip.conf";
static const char notify_config[] = "sip_notify.conf";
#define RTP 1
#define NO_RTP 0
/* Do _NOT_ make any changes to this enum, or the array following it;
if you think you are doing the right thing, you are probably
not doing the right thing. If you think there are changes
needed, get someone else to review them first _before_
submitting a patch. If these two lists do not match properly
bad things will happen.
*/
enum subscriptiontype {
NONE = 0,
TIMEOUT,
XPIDF_XML,
DIALOG_INFO_XML,
CPIM_PIDF_XML,
PIDF_XML
};
static const struct cfsubscription_types {
enum subscriptiontype type;
const char * const event;
const char * const mediatype;
const char * const text;
} subscription_types[] = {
{ NONE, "-", "unknown", "unknown" },
/* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
{ DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
{ CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
{ PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
{ XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" } /* Pre-RFC 3863 with MS additions */
};
enum sipmethod {
SIP_UNKNOWN,
SIP_RESPONSE,
SIP_REGISTER,
SIP_OPTIONS,
SIP_NOTIFY,
SIP_INVITE,
SIP_ACK,
SIP_PRACK,
SIP_BYE,
SIP_REFER,
SIP_SUBSCRIBE,
SIP_MESSAGE,
SIP_UPDATE,
SIP_INFO,
SIP_CANCEL,
SIP_PUBLISH,
} sip_method_list;
enum sip_auth_type {
PROXY_AUTH,
WWW_AUTH,
};
/*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
static const struct cfsip_methods {
enum sipmethod id;
int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
char * const text;
int can_create;
} sip_methods[] = {
{ SIP_UNKNOWN, RTP, "-UNKNOWN-", 0 },
{ SIP_RESPONSE, NO_RTP, "SIP/2.0", 0 },
{ SIP_REGISTER, NO_RTP, "REGISTER", 1 },
{ SIP_OPTIONS, NO_RTP, "OPTIONS", 1 },
{ SIP_NOTIFY, NO_RTP, "NOTIFY", 0 },
{ SIP_INVITE, RTP, "INVITE", 1 },
{ SIP_ACK, NO_RTP, "ACK", 0 },
{ SIP_PRACK, NO_RTP, "PRACK", 0 },
{ SIP_BYE, NO_RTP, "BYE", 0 },
{ SIP_REFER, NO_RTP, "REFER", 0 },
{ SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", 1 },
{ SIP_MESSAGE, NO_RTP, "MESSAGE", 1 },
{ SIP_UPDATE, NO_RTP, "UPDATE", 0 },
{ SIP_INFO, NO_RTP, "INFO", 0 },
{ SIP_CANCEL, NO_RTP, "CANCEL", 0 },
{ SIP_PUBLISH, NO_RTP, "PUBLISH", 1 }
};
/*! \brief Structure for conversion between compressed SIP and "normal" SIP */
static const struct cfalias {
char * const fullname;
char * const shortname;
} aliases[] = {
{ "Content-Type", "c" },
{ "Content-Encoding", "e" },
{ "From", "f" },
{ "Call-ID", "i" },
{ "Contact", "m" },
{ "Content-Length", "l" },
{ "Subject", "s" },
{ "To", "t" },
{ "Supported", "k" },
{ "Refer-To", "r" },
{ "Referred-By", "b" },
{ "Allow-Events", "u" },
{ "Event", "o" },
{ "Via", "v" },
{ "Accept-Contact", "a" },
{ "Reject-Contact", "j" },
{ "Request-Disposition", "d" },
{ "Session-Expires", "x" },
};
/*! Define SIP option tags, used in Require: and Supported: headers
We need to be aware of these properties in the phones to use
the replace: header. We should not do that without knowing
that the other end supports it...
This is nothing we can configure, we learn by the dialog
Supported: header on the REGISTER (peer) or the INVITE
(other devices)
We are not using many of these today, but will in the future.
This is documented in RFC 3261
*/
#define SUPPORTED 1
#define NOT_SUPPORTED 0
#define SIP_OPT_REPLACES (1 << 0)
#define SIP_OPT_100REL (1 << 1)
#define SIP_OPT_TIMER (1 << 2)
#define SIP_OPT_EARLY_SESSION (1 << 3)
#define SIP_OPT_JOIN (1 << 4)
#define SIP_OPT_PATH (1 << 5)
#define SIP_OPT_PREF (1 << 6)
#define SIP_OPT_PRECONDITION (1 << 7)
#define SIP_OPT_PRIVACY (1 << 8)
#define SIP_OPT_SDP_ANAT (1 << 9)
#define SIP_OPT_SEC_AGREE (1 << 10)
#define SIP_OPT_EVENTLIST (1 << 11)
#define SIP_OPT_GRUU (1 << 12)
#define SIP_OPT_TARGET_DIALOG (1 << 13)
/*! \brief List of well-known SIP options. If we get this in a require,
we should check the list and answer accordingly. */
static const struct cfsip_options {
int id; /*!< Bitmap ID */
int supported; /*!< Supported by Asterisk ? */
char * const text; /*!< Text id, as in standard */
} sip_options[] = {
/* Replaces: header for transfer */
{ SIP_OPT_REPLACES, SUPPORTED, "replaces" },
/* RFC3262: PRACK 100% reliability */
{ SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
/* SIP Session Timers */
{ SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
/* RFC3959: SIP Early session support */
{ SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
/* SIP Join header support */
{ SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
/* RFC3327: Path support */
{ SIP_OPT_PATH, NOT_SUPPORTED, "path" },
/* RFC3840: Callee preferences */
{ SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
/* RFC3312: Precondition support */
{ SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
/* RFC3323: Privacy with proxies*/
{ SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
/* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
{ SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
/* RFC3329: Security agreement mechanism */
{ SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
/* SIMPLE events: draft-ietf-simple-event-list-07.txt */
{ SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
/* GRUU: Globally Routable User Agent URI's */
{ SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
/* Target-dialog: draft-ietf-sip-target-dialog-00.txt */
{ SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "target-dialog" },
};
/*! \brief SIP Methods we support */
#define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
/*! \brief SIP Extensions we support */
#define SUPPORTED_EXTENSIONS "replaces"
#define DEFAULT_SIP_PORT 5060 /*!< From RFC 3261 (former 2543) */
#define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
static char default_useragent[AST_MAX_EXTENSION] = DEFAULT_USERAGENT;
#define DEFAULT_CONTEXT "default"
static char default_context[AST_MAX_CONTEXT] = DEFAULT_CONTEXT;
static char default_subscribecontext[AST_MAX_CONTEXT];
#define DEFAULT_VMEXTEN "asterisk"
static char global_vmexten[AST_MAX_EXTENSION] = DEFAULT_VMEXTEN;
static char default_language[MAX_LANGUAGE] = "";
#define DEFAULT_CALLERID "asterisk"
static char default_callerid[AST_MAX_EXTENSION] = DEFAULT_CALLERID;
static char default_fromdomain[AST_MAX_EXTENSION] = "";
#define DEFAULT_NOTIFYMIME "application/simple-message-summary"
static char default_notifymime[AST_MAX_EXTENSION] = DEFAULT_NOTIFYMIME;
static int global_notifyringing = 1; /*!< Send notifications on ringing */
static int global_alwaysauthreject = 0; /*!< Send 401 Unauthorized for all failing requests */
static int default_qualify = 0; /*!< Default Qualify= setting */
static struct ast_flags global_flags = {0}; /*!< global SIP_ flags */
static struct ast_flags global_flags_page2 = {0}; /*!< more global SIP_ flags */
static int srvlookup = 0; /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
static int pedanticsipchecking = 0; /*!< Extra checking ? Default off */
static int autocreatepeer = 0; /*!< Auto creation of peers at registration? Default off. */
static int relaxdtmf = 0;
static int global_rtptimeout = 0;
static int global_rtpholdtimeout = 0;
static int global_rtpkeepalive = 0;
static int global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
static int global_regattempts_max = 0;
/* Object counters */
static int suserobjs = 0;
static int ruserobjs = 0;
static int speerobjs = 0;
static int rpeerobjs = 0;
static int apeerobjs = 0;
static int regobjs = 0;
static int global_allowguest = 1; /*!< allow unauthenticated users/peers to connect? */
#define DEFAULT_MWITIME 10
static int global_mwitime = DEFAULT_MWITIME; /*!< Time between MWI checks for peers */
static int usecnt =0;
AST_MUTEX_DEFINE_STATIC(usecnt_lock);
AST_MUTEX_DEFINE_STATIC(rand_lock);
/*! \brief Protect the interface list (of sip_pvt's) */
AST_MUTEX_DEFINE_STATIC(iflock);
/*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
when it's doing something critical. */
AST_MUTEX_DEFINE_STATIC(netlock);
AST_MUTEX_DEFINE_STATIC(monlock);
/*! \brief This is the thread for the monitor which checks for input on the channels
which are not currently in use. */
static pthread_t monitor_thread = AST_PTHREADT_NULL;
static int restart_monitor(void);
/*! \brief Codecs that we support by default: */
static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
static int noncodeccapability = AST_RTP_DTMF;
static struct in_addr __ourip;
static struct sockaddr_in outboundproxyip;
static int ourport;
#define SIP_DEBUG_CONFIG 1 << 0
#define SIP_DEBUG_CONSOLE 1 << 1
static int sipdebug = 0;
static struct sockaddr_in debugaddr;
static int tos = 0;
static int videosupport = 0;
static int compactheaders = 0; /*!< send compact sip headers */
static int recordhistory = 0; /*!< Record SIP history. Off by default */
static int dumphistory = 0; /*!< Dump history to verbose before destroying SIP dialog */
static char global_musicclass[MAX_MUSICCLASS] = ""; /*!< Global music on hold class */
#define DEFAULT_REALM "asterisk"
static char global_realm[MAXHOSTNAMELEN] = DEFAULT_REALM; /*!< Default realm */
static char regcontext[AST_MAX_CONTEXT] = ""; /*!< Context for auto-extensions */
#define DEFAULT_EXPIRY 900 /*!< Expire slowly */
static int expiry = DEFAULT_EXPIRY;
static struct sched_context *sched;
static struct io_context *io;
static int *sipsock_read_id;
#define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
#define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
#define DEC_CALL_LIMIT 0
#define INC_CALL_LIMIT 1
static struct ast_codec_pref prefs;
/*! \brief sip_request: The data grabbed from the UDP socket */
struct sip_request {
char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
char *rlPart2; /*!< The Request URI or Response Status */
int len; /*!< Length */
int headers; /*!< # of SIP Headers */
int method; /*!< Method of this request */
char *header[SIP_MAX_HEADERS];
int lines; /*!< Body Content */
char *line[SIP_MAX_LINES];
char data[SIP_MAX_PACKET];
int debug; /*!< Debug flag for this packet */
unsigned int flags; /*!< SIP_PKT Flags for this packet */
unsigned int sdp_start; /*!< the line number where the SDP begins */
unsigned int sdp_end; /*!< the line number where the SDP ends */
};
struct sip_pkt;
/*! \brief Parameters to the transmit_invite function */
struct sip_invite_param {
char *distinctive_ring; /*!< Distinctive ring header */
char *osptoken; /*!< OSP token for this call */
int addsipheaders; /*!< Add extra SIP headers */
char *uri_options; /*!< URI options to add to the URI */
char *vxml_url; /*!< VXML url for Cisco phones */
char *auth; /*!< Authentication */
char *authheader; /*!< Auth header */
enum sip_auth_type auth_type; /*!< Authentication type */
};
struct sip_route {
struct sip_route *next;
char hop[0];
};
enum domain_mode {
SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
};
struct domain {
char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
enum domain_mode mode; /*!< How did we find this domain? */
AST_LIST_ENTRY(domain) list; /*!< List mechanics */
};
static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
int allow_external_domains; /*!< Accept calls to external SIP domains? */
/*! \brief sip_history: Structure for saving transactions within a SIP dialog */
struct sip_history {
char event[80];
struct sip_history *next;
};
/*! \brief sip_auth: Creadentials for authentication to other SIP services */
struct sip_auth {
char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
char username[256]; /*!< Username */
char secret[256]; /*!< Secret */
char md5secret[256]; /*!< MD5Secret */
struct sip_auth *next; /*!< Next auth structure in list */
};
#define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
#define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed */
#define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
#define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
#define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
#define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
#define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
#define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
#define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
#define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
#define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
#define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
#define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
#define SIP_OUTGOING (1 << 13) /*!< Is this an outgoing call? */
#define SIP_SELFDESTRUCT (1 << 14) /*!< This is an autocreated peer */
#define SIP_CAN_BYE (1 << 15) /*!< Can we send BYE for this dialog? */
/* --- Choices for DTMF support in SIP channel */
#define SIP_DTMF (3 << 16) /*!< three settings, uses two bits */
#define SIP_DTMF_RFC2833 (0 << 16) /*!< RTP DTMF */
#define SIP_DTMF_INBAND (1 << 16) /*!< Inband audio, only for ULAW/ALAW */
#define SIP_DTMF_INFO (2 << 16) /*!< SIP Info messages */
#define SIP_DTMF_AUTO (3 << 16) /*!< AUTO switch between rfc2833 and in-band DTMF */
/* NAT settings */
#define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
#define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
#define SIP_NAT_RFC3581 (1 << 18)
#define SIP_NAT_ROUTE (2 << 18)
#define SIP_NAT_ALWAYS (3 << 18)
/* re-INVITE related settings */
#define SIP_REINVITE (3 << 20) /*!< two bits used */
#define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
#define SIP_REINVITE_UPDATE (2 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
/* "insecure" settings */
#define SIP_INSECURE_PORT (1 << 22) /*!< don't require matching port for incoming requests */
#define SIP_INSECURE_INVITE (1 << 23) /*!< don't require authentication for incoming INVITEs */
/* Sending PROGRESS in-band settings */
#define SIP_PROG_INBAND (3 << 24) /*!< three settings, uses two bits */
#define SIP_PROG_INBAND_NEVER (0 << 24)
#define SIP_PROG_INBAND_NO (1 << 24)
#define SIP_PROG_INBAND_YES (2 << 24)
/* Open Settlement Protocol authentication */
#define SIP_OSPAUTH (3 << 26) /*!< four settings, uses two bits */
#define SIP_OSPAUTH_NO (0 << 26)
#define SIP_OSPAUTH_GATEWAY (1 << 26)
#define SIP_OSPAUTH_PROXY (2 << 26)
#define SIP_OSPAUTH_EXCLUSIVE (3 << 26)
/* Call states */
#define SIP_CALL_ONHOLD (1 << 28)
#define SIP_CALL_LIMIT (1 << 29)
/* Remote Party-ID Support */
#define SIP_SENDRPID (1 << 30)
/* Did this connection increment the counter of in-use calls? */
#define SIP_INC_COUNT (1 << 31)
#define SIP_FLAGS_TO_COPY \
(SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
SIP_PROG_INBAND | SIP_OSPAUTH | SIP_USECLIENTCODE | SIP_NAT | \
SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
/* a new page of flags for peer */
#define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
#define SIP_PAGE2_RTUPDATE (1 << 1)
#define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
#define SIP_PAGE2_IGNOREREGEXPIRE (1 << 3)
#define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
#define SIP_PAGE2_DYNAMIC (1 << 5) /*!< Is this a dynamic peer? */
/* SIP packet flags */
#define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
#define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
static int global_rtautoclear;
/*! \brief sip_pvt: PVT structures are used for each SIP conversation, ie. a call */
static struct sip_pvt {
ast_mutex_t lock; /*!< Channel private lock */
int method; /*!< SIP method of this packet */
char callid[128]; /*!< Global CallID */
char randdata[80]; /*!< Random data */
struct ast_codec_pref prefs; /*!< codec prefs */
unsigned int ocseq; /*!< Current outgoing seqno */
unsigned int icseq; /*!< Current incoming seqno */
ast_group_t callgroup; /*!< Call group */
ast_group_t pickupgroup; /*!< Pickup group */
int lastinvite; /*!< Last Cseq of invite */
unsigned int flags; /*!< SIP_ flags */
int timer_t1; /*!< SIP timer T1, ms rtt */
unsigned int sipoptions; /*!< Supported SIP sipoptions on the other end */
int capability; /*!< Special capability (codec) */
int jointcapability; /*!< Supported capability at both ends (codecs ) */
int peercapability; /*!< Supported peer capability */
int prefcodec; /*!< Preferred codec (outbound only) */
int noncodeccapability;
int callingpres; /*!< Calling presentation */
int authtries; /*!< Times we've tried to authenticate */
int expiry; /*!< How long we take to expire */
int branch; /*!< One random number */
char tag[11]; /*!< Another random number */
int sessionid; /*!< SDP Session ID */
int sessionversion; /*!< SDP Session Version */
struct sockaddr_in sa; /*!< Our peer */
struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
int redircodecs; /*!< Redirect codecs */
struct sockaddr_in recv; /*!< Received as */
struct in_addr ourip; /*!< Our IP */
struct ast_channel *owner; /*!< Who owns us */
char exten[AST_MAX_EXTENSION]; /*!< Extension where to start */
char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
char refer_contact[SIP_LEN_CONTACT]; /*!< Place to store Contact info from a REFER extension */
struct sip_pvt *refer_call; /*!< Call we are referring */
struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
int route_persistant; /*!< Is this the "real" route? */
char from[256]; /*!< The From: header */
char useragent[256]; /*!< User agent in SIP request */
char context[AST_MAX_CONTEXT]; /*!< Context for this call */
char subscribecontext[AST_MAX_CONTEXT]; /*!< Subscribecontext */
char fromdomain[MAXHOSTNAMELEN]; /*!< Domain to show in the from field */
char fromuser[AST_MAX_EXTENSION]; /*!< User to show in the user field */
char fromname[AST_MAX_EXTENSION]; /*!< Name to show in the user field */
char tohost[MAXHOSTNAMELEN]; /*!< Host we should put in the "to" field */
char language[MAX_LANGUAGE]; /*!< Default language for this call */
char musicclass[MAX_MUSICCLASS]; /*!< Music on Hold class */
char rdnis[256]; /*!< Referring DNIS */
char theirtag[256]; /*!< Their tag */
char username[256]; /*!< [user] name */
char peername[256]; /*!< [peer] name, not set if [user] */
char authname[256]; /*!< Who we use for authentication */
char uri[256]; /*!< Original requested URI */
char okcontacturi[SIP_LEN_CONTACT]; /*!< URI from the 200 OK on INVITE */
char peersecret[256]; /*!< Password */
char peermd5secret[256];
struct sip_auth *peerauth; /*!< Realm authentication */
char cid_num[256]; /*!< Caller*ID */
char cid_name[256]; /*!< Caller*ID */
char via[256]; /*!< Via: header */
char fullcontact[SIP_LEN_CONTACT]; /*!< The Contact: that the UA registers with us */
char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
char our_contact[SIP_LEN_CONTACT]; /*!< Our contact header */
char *rpid; /*!< Our RPID header */
char *rpid_from; /*!< Our RPID From header */
char realm[MAXHOSTNAMELEN]; /*!< Authorization realm */
char nonce[256]; /*!< Authorization nonce */
int noncecount; /*!< Nonce-count */
char opaque[256]; /*!< Opaque nonsense */
char qop[80]; /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
char domain[MAXHOSTNAMELEN]; /*!< Authorization domain */
char lastmsg[256]; /*!< Last Message sent/received */
int amaflags; /*!< AMA Flags */
int pendinginvite; /*!< Any pending invite */
#ifdef OSP_SUPPORT
int osphandle; /*!< OSP Handle for call */
time_t ospstart; /*!< OSP Start time */
unsigned int osptimelimit; /*!< OSP call duration limit */
#endif
struct sip_request initreq; /*!< Initial request */
int maxtime; /*!< Max time for first response */
int initid; /*!< Auto-congest ID if appropriate */
int autokillid; /*!< Auto-kill ID */
time_t lastrtprx; /*!< Last RTP received */
time_t lastrtptx; /*!< Last RTP sent */
int rtptimeout; /*!< RTP timeout time */
int rtpholdtimeout; /*!< RTP timeout when on hold */
int rtpkeepalive; /*!< Send RTP packets for keepalive */
enum subscriptiontype subscribed; /*!< Is this call a subscription? */
int stateid;
int laststate; /*!< Last known extension state */
int dialogver;
struct ast_dsp *vad; /*!< Voice Activation Detection dsp */
struct sip_peer *peerpoke; /*!< If this calls is to poke a peer, which one */
struct sip_registry *registry; /*!< If this is a REGISTER call, to which registry */
struct ast_rtp *rtp; /*!< RTP Session */
struct ast_rtp *vrtp; /*!< Video RTP session */
struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
struct sip_history *history; /*!< History of this SIP dialog */
struct ast_variable *chanvars; /*!< Channel variables to set for call */
struct sip_pvt *next; /*!< Next call in chain */
struct sip_invite_param *options; /*!< Options for INVITE */
} *iflist = NULL;
#define FLAG_RESPONSE (1 << 0)
#define FLAG_FATAL (1 << 1)
/*! \brief sip packet - read in sipsock_read, transmitted in send_request */
struct sip_pkt {
struct sip_pkt *next; /*!< Next packet */
int retrans; /*!< Retransmission number */
int method; /*!< SIP method for this packet */
int seqno; /*!< Sequence number */
unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
struct sip_pvt *owner; /*!< Owner call */
int retransid; /*!< Retransmission ID */
int timer_a; /*!< SIP timer A, retransmission timer */
int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
int packetlen; /*!< Length of packet */
char data[0];
};
/*! \brief Structure for SIP user data. User's place calls to us */
struct sip_user {
/* Users who can access various contexts */
ASTOBJ_COMPONENTS(struct sip_user);
char secret[80]; /*!< Password */
char md5secret[80]; /*!< Password in md5 */
char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
char cid_num[80]; /*!< Caller ID num */
char cid_name[80]; /*!< Caller ID name */
char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
char language[MAX_LANGUAGE]; /*!< Default language for this user */
char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */
char useragent[256]; /*!< User agent in SIP request */
struct ast_codec_pref prefs; /*!< codec prefs */
ast_group_t callgroup; /*!< Call group */
ast_group_t pickupgroup; /*!< Pickup Group */
unsigned int flags; /*!< SIP flags */
unsigned int sipoptions; /*!< Supported SIP options */
struct ast_flags flags_page2; /*!< SIP_PAGE2 flags */
int amaflags; /*!< AMA flags for billing */
int callingpres; /*!< Calling id presentation */
int capability; /*!< Codec capability */
int inUse; /*!< Number of calls in use */
int call_limit; /*!< Limit of concurrent calls */
struct ast_ha *ha; /*!< ACL setting */
struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
};
/* Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
struct sip_peer {
ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
/*!< peer->name is the unique name of this object */
char secret[80]; /*!< Password */
char md5secret[80]; /*!< Password in MD5 */
struct sip_auth *auth; /*!< Realm authentication list */
char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
char username[80]; /*!< Temporary username until registration */
char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
int amaflags; /*!< AMA Flags (for billing) */
char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
char fromuser[80]; /*!< From: user when calling this peer */
char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
char fullcontact[SIP_LEN_CONTACT]; /*!< Contact registered with us (not in sip.conf) */
char cid_num[80]; /*!< Caller ID num */
char cid_name[80]; /*!< Caller ID name */
int callingpres; /*!< Calling id presentation */
int inUse; /*!< Number of calls in use */
int call_limit; /*!< Limit of concurrent calls */
char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
char language[MAX_LANGUAGE]; /*!< Default language for prompts */
char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */
char useragent[256]; /*!< User agent in SIP request (saved from registration) */
struct ast_codec_pref prefs; /*!< codec prefs */
int lastmsgssent;
time_t lastmsgcheck; /*!< Last time we checked for MWI */
unsigned int flags; /*!< SIP flags */
unsigned int sipoptions; /*!< Supported SIP options */
struct ast_flags flags_page2; /*!< SIP_PAGE2 flags */
int expire; /*!< When to expire this peer registration */
int capability; /*!< Codec capability */
int rtptimeout; /*!< RTP timeout */
int rtpholdtimeout; /*!< RTP Hold Timeout */
int rtpkeepalive; /*!< Send RTP packets for keepalive */
ast_group_t callgroup; /*!< Call group */
ast_group_t pickupgroup; /*!< Pickup group */
struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
struct sockaddr_in addr; /*!< IP address of peer */
/* Qualification */
struct sip_pvt *call; /*!< Call pointer */
int pokeexpire; /*!< When to expire poke (qualify= checking) */
int lastms; /*!< How long last response took (in ms), or -1 for no response */
int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
struct timeval ps; /*!< Ping send time */
struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
struct ast_ha *ha; /*!< Access control list */
struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
int lastmsg;
};
AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
static int sip_reloading = 0;
/* States for outbound registrations (with register= lines in sip.conf */
#define REG_STATE_UNREGISTERED 0
#define REG_STATE_REGSENT 1
#define REG_STATE_AUTHSENT 2
#define REG_STATE_REGISTERED 3
#define REG_STATE_REJECTED 4
#define REG_STATE_TIMEOUT 5
#define REG_STATE_NOAUTH 6
#define REG_STATE_FAILED 7
/*! \brief sip_registry: Registrations with other SIP proxies */
struct sip_registry {
ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
int portno; /*!< Optional port override */
char username[80]; /*!< Who we are registering as */
char authuser[80]; /*!< Who we *authenticate* as */
char hostname[MAXHOSTNAMELEN]; /*!< Domain or host we register to */
char secret[80]; /*!< Password in clear text */
char md5secret[80]; /*!< Password in md5 */
char contact[SIP_LEN_CONTACT]; /*!< Contact extension */
char random[80];
int expire; /*!< Sched ID of expiration */
int regattempts; /*!< Number of attempts (since the last success) */
int timeout; /*!< sched id of sip_reg_timeout */
int refresh; /*!< How often to refresh */
struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration call" in progress */
int regstate; /*!< Registration state (see above) */
int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
char callid[128]; /*!< Global CallID for this registry */
unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
struct sockaddr_in us; /*!< Who the server thinks we are */
/* Saved headers */
char realm[MAXHOSTNAMELEN]; /*!< Authorization realm */
char nonce[256]; /*!< Authorization nonce */
char domain[MAXHOSTNAMELEN]; /*!< Authorization domain */
char opaque[256]; /*!< Opaque nonsense */
char qop[80]; /*!< Quality of Protection. */
int noncecount; /*!< Nonce-count */
char lastmsg[256]; /*!< Last Message sent/received */
};
/*! \brief The user list: Users and friends ---*/
static struct ast_user_list {
ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
} userl;
/*! \brief The peer list: Peers and Friends ---*/
static struct ast_peer_list {
ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
} peerl;
/*! \brief The register list: Other SIP proxys we register with and call ---*/
static struct ast_register_list {
ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
int recheck;
} regl;
static int __sip_do_register(struct sip_registry *r);
static int sipsock = -1;
static struct sockaddr_in bindaddr = { 0, };
static struct sockaddr_in externip;
static char externhost[MAXHOSTNAMELEN] = "";
static time_t externexpire = 0;
static int externrefresh = 10;
static struct ast_ha *localaddr;
/* The list of manual NOTIFY types we know how to send */
struct ast_config *notify_types;
static struct sip_auth *authl; /*!< Authentication list */
static int transmit_response_using_temp(char *callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, struct sip_request *req, char *msg);
static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
static int transmit_response_with_unsupported(struct sip_pvt *p, char *msg, struct sip_request *req, char *unsupported);
static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable, char *header, int stale);
static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch);
static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch);
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sendsdp, int init);
static int transmit_reinvite_with_sdp(struct sip_pvt *p);
static int transmit_info_with_digit(struct sip_pvt *p, char digit);
static int transmit_info_with_vidupdate(struct sip_pvt *p);
static int transmit_message_with_text(struct sip_pvt *p, const char *text);
static int transmit_refer(struct sip_pvt *p, const char *dest);
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
static struct sip_peer *temp_peer(const char *name);
static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
static void free_old_route(struct sip_route *route);
static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
static int update_call_counter(struct sip_pvt *fup, int event);
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
static int sip_do_reload(void);
static int expire_register(void *data);
static int callevents = 0;
static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
static int sip_devicestate(void *data);
static int sip_sendtext(struct ast_channel *ast, const char *text);
static int sip_call(struct ast_channel *ast, char *dest, int timeout);
static int sip_hangup(struct ast_channel *ast);
static int sip_answer(struct ast_channel *ast);
static struct ast_frame *sip_read(struct ast_channel *ast);
static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
static int sip_indicate(struct ast_channel *ast, int condition);
static int sip_transfer(struct ast_channel *ast, const char *dest);
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
static int sip_senddigit(struct ast_channel *ast, char digit);
static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno); /* Add realm authentication in list */
static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, char *realm); /* Find authentication for a specific realm */
static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
static void append_date(struct sip_request *req); /* Append date to SIP packet */
static int determine_firstline_parts(struct sip_request *req);
static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
static int transmit_state_notify(struct sip_pvt *p, int state, int full, int substate);
static char *gettag(struct sip_request *req, char *header, char *tagbuf, int tagbufsize);
/*! \brief Definition of this channel for PBX channel registration */
static const struct ast_channel_tech sip_tech = {
.type = channeltype,
.description = "Session Initiation Protocol (SIP)",
.capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
.properties = AST_CHAN_TP_WANTSJITTER,
.requester = sip_request_call,
.devicestate = sip_devicestate,
.call = sip_call,
.hangup = sip_hangup,
.answer = sip_answer,
.read = sip_read,
.write = sip_write,
.write_video = sip_write,
.indicate = sip_indicate,
.transfer = sip_transfer,
.fixup = sip_fixup,
.send_digit = sip_senddigit,
.bridge = ast_rtp_bridge,
.send_text = sip_sendtext,
};
#ifdef __AST_DEBUG_MALLOC
static void FREE(void *ptr)
{
free(ptr);
}
#else
#define FREE free
#endif
/*!
\brief Thread-safe random number generator
\return a random number
This function uses a mutex lock to guarantee that no
two threads will receive the same random number.
*/
static force_inline int thread_safe_rand(void)
{
int val;
ast_mutex_lock(&rand_lock);
val = rand();
ast_mutex_unlock(&rand_lock);
return val;
}
/*! \brief find_sip_method: Find SIP method from header
* Strictly speaking, SIP methods are case SENSITIVE, but we don't check
* following Jon Postel's rule: Be gentle in what you accept, strict with what you send */
static int find_sip_method(char *msg)
{
int i, res = 0;
if (ast_strlen_zero(msg))
return 0;
for (i = 1; (i < (sizeof(sip_methods) / sizeof(sip_methods[0]))) && !res; i++) {
if (!strcasecmp(sip_methods[i].text, msg))
res = sip_methods[i].id;
}
return res;
}
/*! \brief parse_sip_options: Parse supported header in incoming packet */
static unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported)
{
char *next = NULL;
char *sep = NULL;
char *temp = ast_strdupa(supported);
int i;
unsigned int profile = 0;
if (ast_strlen_zero(supported) )
return 0;
if (option_debug > 2 && sipdebug)
ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
next = temp;
while (next) {
char res=0;
if ( (sep = strchr(next, ',')) != NULL) {
*sep = '\0';
sep++;
}
while (*next == ' ') /* Skip spaces */
next++;
if (option_debug > 2 && sipdebug)
ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
for (i=0; (i < (sizeof(sip_options) / sizeof(sip_options[0]))) && !res; i++) {
if (!strcasecmp(next, sip_options[i].text)) {
profile |= sip_options[i].id;
res = 1;
if (option_debug > 2 && sipdebug)
ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
}
}
if (!res)
if (option_debug > 2 && sipdebug)
ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
next = sep;
}
if (pvt) {
pvt->sipoptions = profile;
if (option_debug)
ast_log(LOG_DEBUG, "* SIP extension value: %d for call %s\n", profile, pvt->callid);
}
return profile;
}
/*! \brief sip_debug_test_addr: See if we pass debug IP filter */
static inline int sip_debug_test_addr(struct sockaddr_in *addr)
{
if (sipdebug == 0)
return 0;
if (debugaddr.sin_addr.s_addr) {
if (((ntohs(debugaddr.sin_port) != 0)
&& (debugaddr.sin_port != addr->sin_port))
|| (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
return 0;
}
return 1;
}
/*! \brief sip_debug_test_pvt: Test PVT for debugging output */
static inline int sip_debug_test_pvt(struct sip_pvt *p)
{
if (sipdebug == 0)
return 0;
return sip_debug_test_addr(((ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ? &p->recv : &p->sa));
}
/*! \brief __sip_xmit: Transmit SIP message ---*/
static int __sip_xmit(struct sip_pvt *p, char *data, int len)
{
int res;
char iabuf[INET_ADDRSTRLEN];
if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
else
res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
if (res != len) {
ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), res, strerror(errno));
}
return res;
}
static void sip_destroy(struct sip_pvt *p);
/*! \brief build_via: Build a Via header for a request ---*/
static void build_via(struct sip_pvt *p, char *buf, int len)
{
char iabuf[INET_ADDRSTRLEN];
/* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
if (ast_test_flag(p, SIP_NAT) & SIP_NAT_RFC3581)
snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
else /* Work around buggy UNIDEN UIP200 firmware */
snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
}
/*! \brief ast_sip_ouraddrfor: NAT fix - decide which IP address to use for ASterisk server? ---*/
/* Only used for outbound registrations */
static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
{
/*
* Using the localaddr structure built up with localnet statements
* apply it to their address to see if we need to substitute our
* externip or can get away with our internal bindaddr
*/
struct sockaddr_in theirs;
theirs.sin_addr = *them;
if (localaddr && externip.sin_addr.s_addr &&
ast_apply_ha(localaddr, &theirs)) {
char iabuf[INET_ADDRSTRLEN];
if (externexpire && (time(NULL) >= externexpire)) {
struct ast_hostent ahp;
struct hostent *hp;
time(&externexpire);
externexpire += externrefresh;
if ((hp = ast_gethostbyname(externhost, &ahp))) {
memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
} else
ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
}
memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
}
else if (bindaddr.sin_addr.s_addr)
memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
else
return ast_ouraddrfor(them, us);
return 0;
}
/*! \brief append_history: Append to SIP dialog history */
/* Always returns 0 */
static int append_history(struct sip_pvt *p, const char *event, const char *data)
{
struct sip_history *hist, *prev;
char *c;
if (!recordhistory || !p)
return 0;
if(!(hist = malloc(sizeof(struct sip_history)))) {
ast_log(LOG_WARNING, "Can't allocate memory for history\n");
return 0;
}
memset(hist, 0, sizeof(struct sip_history));
snprintf(hist->event, sizeof(hist->event), "%-15s %s", event, data);
/* Trim up nicely */
c = hist->event;
while(*c) {
if ((*c == '\r') || (*c == '\n')) {
*c = '\0';
break;
}
c++;
}
/* Enqueue into history */
prev = p->history;
if (prev) {
while(prev->next)
prev = prev->next;
prev->next = hist;
} else {
p->history = hist;
}
return 0;
}
/*! \brief retrans_pkt: Retransmit SIP message if no answer ---*/
static int retrans_pkt(void *data)
{
struct sip_pkt *pkt=data, *prev, *cur = NULL;
char iabuf[INET_ADDRSTRLEN];
int reschedule = DEFAULT_RETRANS;
/* Lock channel */
ast_mutex_lock(&pkt->owner->lock);
if (pkt->retrans < MAX_RETRANS) {
char buf[80];
pkt->retrans++;
if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
if (sipdebug && option_debug > 3)
ast_log(LOG_DEBUG, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
} else {
int siptimer_a;
if (sipdebug && option_debug > 3)
ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
if (!pkt->timer_a)
pkt->timer_a = 2 ;
else
pkt->timer_a = 2 * pkt->timer_a;
/* For non-invites, a maximum of 4 secs */
siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
if (pkt->method != SIP_INVITE && siptimer_a > 4000)
siptimer_a = 4000;
/* Reschedule re-transmit */
reschedule = siptimer_a;
if (option_debug > 3)
ast_log(LOG_DEBUG, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
}
if (pkt->owner && sip_debug_test_pvt(pkt->owner)) {
if (ast_test_flag(pkt->owner, SIP_NAT) & SIP_NAT_ROUTE)
ast_verbose("Retransmitting #%d (NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port), pkt->data);
else
ast_verbose("Retransmitting #%d (no NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port), pkt->data);
}
snprintf(buf, sizeof(buf), "ReTx %d", reschedule);
append_history(pkt->owner, buf, pkt->data);
__sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
ast_mutex_unlock(&pkt->owner->lock);
return reschedule;
}
/* Too many retries */
if (pkt->owner && pkt->method != SIP_OPTIONS) {
if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (ast_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (ast_test_flag(pkt, FLAG_RESPONSE)) ? "Response" : "Request");
} else {
if (pkt->method == SIP_OPTIONS && sipdebug)
ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
}
append_history(pkt->owner, "MaxRetries", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
pkt->retransid = -1;
if (ast_test_flag(pkt, FLAG_FATAL)) {
while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
ast_mutex_unlock(&pkt->owner->lock);
usleep(1);
ast_mutex_lock(&pkt->owner->lock);
}
if (pkt->owner->owner) {
ast_set_flag(pkt->owner, SIP_ALREADYGONE);
ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
ast_queue_hangup(pkt->owner->owner);
ast_mutex_unlock(&pkt->owner->owner->lock);
} else {
/* If no channel owner, destroy now */
ast_set_flag(pkt->owner, SIP_NEEDDESTROY);
}
}
/* In any case, go ahead and remove the packet */
prev = NULL;
cur = pkt->owner->packets;
while(cur) {
if (cur == pkt)
break;
prev = cur;
cur = cur->next;
}
if (cur) {
if (prev)
prev->next = cur->next;
else
pkt->owner->packets = cur->next;
ast_mutex_unlock(&pkt->owner->lock);
free(cur);
pkt = NULL;
} else
ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
if (pkt)
ast_mutex_unlock(&pkt->owner->lock);
return 0;
}
/*! \brief __sip_reliable_xmit: transmit packet with retransmits ---*/
static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
{
struct sip_pkt *pkt;
int siptimer_a = DEFAULT_RETRANS;
pkt = malloc(sizeof(struct sip_pkt) + len + 1);
if (!pkt)
return -1;
memset(pkt, 0, sizeof(struct sip_pkt));
memcpy(pkt->data, data, len);
pkt->method = sipmethod;
pkt->packetlen = len;
pkt->next = p->packets;
pkt->owner = p;
pkt->seqno = seqno;
pkt->flags = resp;
pkt->data[len] = '\0';
pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
if (fatal)
ast_set_flag(pkt, FLAG_FATAL);
if (pkt->timer_t1)
siptimer_a = pkt->timer_t1 * 2;
/* Schedule retransmission */
pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
if (option_debug > 3 && sipdebug)
ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid);
pkt->next = p->packets;
p->packets = pkt;
__sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
if (sipmethod == SIP_INVITE) {
/* Note this is a pending invite */
p->pendinginvite = seqno;
}
return 0;
}
/*! \brief __sip_autodestruct: Kill a call (called by scheduler) ---*/
static int __sip_autodestruct(void *data)
{
struct sip_pvt *p = data;
/* If this is a subscription, tell the phone that we got a timeout */
if (p->subscribed) {
p->subscribed = TIMEOUT;
transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, 1); /* Send first notification */
p->subscribed = NONE;
append_history(p, "Subscribestatus", "timeout");
return 10000; /* Reschedule this destruction so that we know that it's gone */
}
/* This scheduled event is now considered done. */
p->autokillid = -1;
ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
append_history(p, "AutoDestroy", "");
if (p->owner) {
ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
ast_queue_hangup(p->owner);
} else {
sip_destroy(p);
}
return 0;
}
/*! \brief sip_scheddestroy: Schedule destruction of SIP call ---*/
static int sip_scheddestroy(struct sip_pvt *p, int ms)
{
char tmp[80];
if (sip_debug_test_pvt(p))
ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms);
if (recordhistory) {
snprintf(tmp, sizeof(tmp), "%d ms", ms);
append_history(p, "SchedDestroy", tmp);
}
if (p->autokillid > -1)
ast_sched_del(sched, p->autokillid);
p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
return 0;
}
/*! \brief sip_cancel_destroy: Cancel destruction of SIP call ---*/
static int sip_cancel_destroy(struct sip_pvt *p)
{
if (p->autokillid > -1)
ast_sched_del(sched, p->autokillid);
append_history(p, "CancelDestroy", "");
p->autokillid = -1;
return 0;
}
/*! \brief __sip_ack: Acknowledges receipt of a packet and stops retransmission ---*/
static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
{
struct sip_pkt *cur, *prev = NULL;
int res = -1;
int resetinvite = 0;
/* Just in case... */
char *msg;
msg = sip_methods[sipmethod].text;
ast_mutex_lock(&p->lock);
cur = p->packets;
while(cur) {
if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
((ast_test_flag(cur, FLAG_RESPONSE)) ||
(!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
if (!resp && (seqno == p->pendinginvite)) {
ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
p->pendinginvite = 0;
resetinvite = 1;
}
/* this is our baby */
if (prev)
prev->next = cur->next;
else
p->packets = cur->next;
if (cur->retransid > -1) {
if (sipdebug && option_debug > 3)
ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
ast_sched_del(sched, cur->retransid);
}
free(cur);
res = 0;
break;
}
prev = cur;
cur = cur->next;
}
ast_mutex_unlock(&p->lock);
ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
return res;
}
/* Pretend to ack all packets */
static int __sip_pretend_ack(struct sip_pvt *p)
{
struct sip_pkt *cur=NULL;
while(p->packets) {
if (cur == p->packets) {
ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
return -1;
}
cur = p->packets;
if (cur->method)
__sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), cur->method);
else { /* Unknown packet type */
char *c;
char method[128];
ast_copy_string(method, p->packets->data, sizeof(method));
c = ast_skip_blanks(method); /* XXX what ? */
*c = '\0';
__sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), find_sip_method(method));
}
}
return 0;
}
/*! \brief __sip_semi_ack: Acks receipt of packet, keep it around (used for provisional responses) ---*/
static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
{
struct sip_pkt *cur;
int res = -1;
char *msg = sip_methods[sipmethod].text;
cur = p->packets;
while(cur) {
if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
((ast_test_flag(cur, FLAG_RESPONSE)) ||
(!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
/* this is our baby */
if (cur->retransid > -1) {
if (option_debug > 3 && sipdebug)
ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, msg);
ast_sched_del(sched, cur->retransid);
}
cur->retransid = -1;
res = 0;
break;
}
cur = cur->next;
}
ast_log(LOG_DEBUG, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
return res;
}
static void parse_request(struct sip_request *req);
static char *get_header(struct sip_request *req, char *name);
static void copy_request(struct sip_request *dst,struct sip_request *src);
/*! \brief parse_copy: Copy SIP request, parse it */
static void parse_copy(struct sip_request *dst, struct sip_request *src)
{
memset(dst, 0, sizeof(*dst));
memcpy(dst->data, src->data, sizeof(dst->data));
dst->len = src->len;
parse_request(dst);
}
/*! \brief send_response: Transmit response on SIP request---*/
static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
{
int res;
char iabuf[INET_ADDRSTRLEN];
struct sip_request tmp;
char tmpmsg[80];
if (sip_debug_test_pvt(p)) {
if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
else
ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
}
if (reliable) {
if (recordhistory) {
parse_copy(&tmp, req);
snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
append_history(p, "TxRespRel", tmpmsg);
}
res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1), req->method);
} else {
if (recordhistory) {
parse_copy(&tmp, req);
snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
append_history(p, "TxResp", tmpmsg);
}
res = __sip_xmit(p, req->data, req->len);
}
if (res > 0)
return 0;
return res;
}
/*! \brief send_request: Send SIP Request to the other part of the dialogue ---*/
static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
{
int res;
char iabuf[INET_ADDRSTRLEN];
struct sip_request tmp;
char tmpmsg[80];
if (sip_debug_test_pvt(p)) {
if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
else
ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
}
if (reliable) {
if (recordhistory) {
parse_copy(&tmp, req);
snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
append_history(p, "TxReqRel", tmpmsg);
}
res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method);
} else {
if (recordhistory) {
parse_copy(&tmp, req);
snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
append_history(p, "TxReq", tmpmsg);
}
res = __sip_xmit(p, req->data, req->len);
}
return res;
}
/*! \brief get_in_brackets: Pick out text in brackets from character string ---*/
/* returns pointer to terminated stripped string. modifies input string. */
static char *get_in_brackets(char *tmp)
{
char *parse;
char *first_quote;
char *first_bracket;
char *second_bracket;
char last_char;
parse = tmp;
while (1) {
first_quote = strchr(parse, '"');
first_bracket = strchr(parse, '<');
if (first_quote && first_bracket && (first_quote < first_bracket)) {
last_char = '\0';
for (parse = first_quote + 1; *parse; parse++) {
if ((*parse == '"') && (last_char != '\\'))
break;
last_char = *parse;
}
if (!*parse) {
ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
return tmp;
}
parse++;
continue;
}
if (first_bracket) {
second_bracket = strchr(first_bracket + 1, '>');
if (second_bracket) {
*second_bracket = '\0';
return first_bracket + 1;
} else {
ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
return tmp;
}
}
return tmp;
}
}
/*! \brief sip_sendtext: Send SIP MESSAGE text within a call ---*/
/* Called from PBX core text message functions */
static int sip_sendtext(struct ast_channel *ast, const char *text)
{
struct sip_pvt *p = ast->tech_pvt;
int debug=sip_debug_test_pvt(p);
if (debug)
ast_verbose("Sending text %s on %s\n", text, ast->name);
if (!p)
return -1;
if (ast_strlen_zero(text))
return 0;
if (debug)
ast_verbose("Really sending text %s on %s\n", text, ast->name);
transmit_message_with_text(p, text);
return 0;
}
/*! \brief realtime_update_peer: Update peer object in realtime storage ---*/
static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
{
char port[10];
char ipaddr[20];
char regseconds[20];
time_t nowtime;
time(&nowtime);
nowtime += expirey;
snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
if (fullcontact)
ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, "fullcontact", fullcontact, NULL);
else
ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, NULL);
}
/*! \brief register_peer_exten: Automatically add peer extension to dial plan ---*/
static void register_peer_exten(struct sip_peer *peer, int onoff)
{
char multi[256];
char *stringp, *ext;
if (!ast_strlen_zero(regcontext)) {
ast_copy_string(multi, ast_strlen_zero(peer->regexten) ? peer->name : peer->regexten, sizeof(multi));
stringp = multi;
while((ext = strsep(&stringp, "&"))) {
if (onoff)
ast_add_extension(regcontext, 1, ext, 1, NULL, NULL, "Noop", strdup(peer->name), FREE, channeltype);
else
ast_context_remove_extension(regcontext, ext, 1, NULL);
}
}
}
/*! \brief sip_destroy_peer: Destroy peer object from memory */
static void sip_destroy_peer(struct sip_peer *peer)
{
/* Delete it, it needs to disappear */
if (peer->call)
sip_destroy(peer->call);
if (peer->chanvars) {
ast_variables_destroy(peer->chanvars);
peer->chanvars = NULL;
}
if (peer->expire > -1)
ast_sched_del(sched, peer->expire);
if (peer->pokeexpire > -1)
ast_sched_del(sched, peer->pokeexpire);
register_peer_exten(peer, 0);
ast_free_ha(peer->ha);
if (ast_test_flag(peer, SIP_SELFDESTRUCT))
apeerobjs--;
else if (ast_test_flag(peer, SIP_REALTIME))
rpeerobjs--;
else
speerobjs--;
clear_realm_authentication(peer->auth);
peer->auth = (struct sip_auth *) NULL;
if (peer->dnsmgr)
ast_dnsmgr_release(peer->dnsmgr);
free(peer);
}
/*! \brief update_peer: Update peer data in database (if used) ---*/
static void update_peer(struct sip_peer *p, int expiry)
{
int rtcachefriends = ast_test_flag(&(p->flags_page2), SIP_PAGE2_RTCACHEFRIENDS);
if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTUPDATE) &&
(ast_test_flag(p, SIP_REALTIME) || rtcachefriends)) {
realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
}
}
/*! \brief realtime_peer: Get peer from realtime storage
* Checks the "sippeers" realtime family from extconfig.conf */
static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
{
struct sip_peer *peer=NULL;
struct ast_variable *var;
struct ast_variable *tmp;
char *newpeername = (char *) peername;
char iabuf[80];
/* First check on peer name */
if (newpeername)
var = ast_load_realtime("sippeers", "name", peername, NULL);
else if (sin) { /* Then check on IP address */
ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
var = ast_load_realtime("sippeers", "host", iabuf, NULL); /* First check for fixed IP hosts */
if (!var)
var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL); /* Then check for registred hosts */
} else
return NULL;
if (!var)
return NULL;
tmp = var;
/* If this is type=user, then skip this object. */
while(tmp) {
if (!strcasecmp(tmp->name, "type") &&
!strcasecmp(tmp->value, "user")) {
ast_variables_destroy(var);
return NULL;
} else if (!newpeername && !strcasecmp(tmp->name, "name")) {
newpeername = tmp->value;
}
tmp = tmp->next;
}
if (!newpeername) { /* Did not find peer in realtime */
ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
ast_variables_destroy(var);
return (struct sip_peer *) NULL;
}
/* Peer found in realtime, now build it in memory */
peer = build_peer(newpeername, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
if (!peer) {
ast_variables_destroy(var);
return (struct sip_peer *) NULL;
}
if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
/* Cache peer */
ast_copy_flags((&peer->flags_page2),(&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR)) {
if (peer->expire > -1) {
ast_sched_del(sched, peer->expire);
}
peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
}
ASTOBJ_CONTAINER_LINK(&peerl,peer);
} else {
ast_set_flag(peer, SIP_REALTIME);
}
ast_variables_destroy(var);
return peer;
}
/*! \brief sip_addrcmp: Support routine for find_peer ---*/
static int sip_addrcmp(char *name, struct sockaddr_in *sin)
{
/* We know name is the first field, so we can cast */
struct sip_peer *p = (struct sip_peer *)name;
return !(!inaddrcmp(&p->addr, sin) ||
(ast_test_flag(p, SIP_INSECURE_PORT) &&
(p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
}
/*! \brief find_peer: Locate peer by name or ip address
* This is used on incoming SIP message to find matching peer on ip
or outgoing message to find matching peer on name */
static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
{
struct sip_peer *p = NULL;
if (peer)
p = ASTOBJ_CONTAINER_FIND(&peerl,peer);
else
p = ASTOBJ_CONTAINER_FIND_FULL(&peerl,sin,name,sip_addr_hashfunc,1,sip_addrcmp);
if (!p && realtime) {
p = realtime_peer(peer, sin);
}
return p;
}
/*! \brief sip_destroy_user: Remove user object from in-memory storage ---*/
static void sip_destroy_user(struct sip_user *user)
{
ast_free_ha(user->ha);
if (user->chanvars) {
ast_variables_destroy(user->chanvars);
user->chanvars = NULL;
}
if (ast_test_flag(user, SIP_REALTIME))
ruserobjs--;
else
suserobjs--;
free(user);
}
/*! \brief realtime_user: Load user from realtime storage
* Loads user from "sipusers" category in realtime (extconfig.conf)
* Users are matched on From: user name (the domain in skipped) */
static struct sip_user *realtime_user(const char *username)
{
struct ast_variable *var;
struct ast_variable *tmp;
struct sip_user *user = NULL;
var = ast_load_realtime("sipusers", "name", username, NULL);
if (!var)
return NULL;
tmp = var;
while (tmp) {
if (!strcasecmp(tmp->name, "type") &&
!strcasecmp(tmp->value, "peer")) {
ast_variables_destroy(var);
return NULL;
}
tmp = tmp->next;
}
user = build_user(username, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
if (!user) { /* No user found */
ast_variables_destroy(var);
return NULL;
}
if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
ast_set_flag((&user->flags_page2), SIP_PAGE2_RTCACHEFRIENDS);
suserobjs++;
ASTOBJ_CONTAINER_LINK(&userl,user);
} else {
/* Move counter from s to r... */
suserobjs--;
ruserobjs++;
ast_set_flag(user, SIP_REALTIME);
}
ast_variables_destroy(var);
return user;
}
/*! \brief find_user: Locate user by name
* Locates user by name (From: sip uri user name part) first
* from in-memory list (static configuration) then from
* realtime storage (defined in extconfig.conf) */
static struct sip_user *find_user(const char *name, int realtime)
{
struct sip_user *u = NULL;
u = ASTOBJ_CONTAINER_FIND(&userl,name);
if (!u && realtime) {
u = realtime_user(name);
}
return u;
}
/*! \brief create_addr_from_peer: create address structure from peer reference ---*/
static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer)
{
char *callhost;
if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
(!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
if (peer->addr.sin_addr.s_addr) {
r->sa.sin_family = peer->addr.sin_family;
r->sa.sin_addr = peer->addr.sin_addr;
r->sa.sin_port = peer->addr.sin_port;
} else {
r->sa.sin_family = peer->defaddr.sin_family;
r->sa.sin_addr = peer->defaddr.sin_addr;
r->sa.sin_port = peer->defaddr.sin_port;
}
memcpy(&r->recv, &r->sa, sizeof(r->recv));
} else {
return -1;
}
ast_copy_flags(r, peer, SIP_FLAGS_TO_COPY);
r->capability = peer->capability;
r->prefs = peer->prefs;
if (r->rtp) {
ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
ast_rtp_setnat(r->rtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
}
if (r->vrtp) {
ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
ast_rtp_setnat(r->vrtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
}
ast_copy_string(r->peername, peer->username, sizeof(r->peername));
ast_copy_string(r->authname, peer->username, sizeof(r->authname));
ast_copy_string(r->username, peer->username, sizeof(r->username));
ast_copy_string(r->peersecret, peer->secret, sizeof(r->peersecret));
ast_copy_string(r->peermd5secret, peer->md5secret, sizeof(r->peermd5secret));
ast_copy_string(r->tohost, peer->tohost, sizeof(r->tohost));
ast_copy_string(r->fullcontact, peer->fullcontact, sizeof(r->fullcontact));
if (!r->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
if ((callhost = strchr(r->callid, '@'))) {
strncpy(callhost + 1, peer->fromdomain, sizeof(r->callid) - (callhost - r->callid) - 2);
}
}
if (ast_strlen_zero(r->tohost)) {
if (peer->addr.sin_addr.s_addr)
ast_inet_ntoa(r->tohost, sizeof(r->tohost), peer->addr.sin_addr);
else
ast_inet_ntoa(r->tohost, sizeof(r->tohost), peer->defaddr.sin_addr);
}
if (!ast_strlen_zero(peer->fromdomain))
ast_copy_string(r->fromdomain, peer->fromdomain, sizeof(r->fromdomain));
if (!ast_strlen_zero(peer->fromuser))
ast_copy_string(r->fromuser, peer->fromuser, sizeof(r->fromuser));
r->maxtime = peer->maxms;
r->callgroup = peer->callgroup;
r->pickupgroup = peer->pickupgroup;
/* Set timer T1 to RTT for this peer (if known by qualify=) */
if (peer->maxms && peer->lastms)
r->timer_t1 = peer->lastms;
if ((ast_test_flag(r, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(r, SIP_DTMF) == SIP_DTMF_AUTO))
r->noncodeccapability |= AST_RTP_DTMF;
else
r->noncodeccapability &= ~AST_RTP_DTMF;
ast_copy_string(r->context, peer->context,sizeof(r->context));
r->rtptimeout = peer->rtptimeout;
r->rtpholdtimeout = peer->rtpholdtimeout;
r->rtpkeepalive = peer->rtpkeepalive;
if (peer->call_limit)
ast_set_flag(r, SIP_CALL_LIMIT);
return 0;
}
/*! \brief create_addr: create address structure from peer name
* Or, if peer not found, find it in the global DNS
* returns TRUE (-1) on failure, FALSE on success */
static int create_addr(struct sip_pvt *dialog, char *opeer)
{
struct hostent *hp;
struct ast_hostent ahp;
struct sip_peer *p;
int found=0;
char *port;
int portno;
char host[MAXHOSTNAMELEN], *hostn;
char peer[256];
ast_copy_string(peer, opeer, sizeof(peer));
port = strchr(peer, ':');
if (port) {
*port = '\0';
port++;
}
dialog->sa.sin_family = AF_INET;
dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
p = find_peer(peer, NULL, 1);
if (p) {
found++;
if (create_addr_from_peer(dialog, p))
ASTOBJ_UNREF(p, sip_destroy_peer);
}
if (!p) {
if (found)
return -1;
hostn = peer;
if (port)
portno = atoi(port);
else
portno = DEFAULT_SIP_PORT;
if (srvlookup) {
char service[MAXHOSTNAMELEN];
int tportno;
int ret;
snprintf(service, sizeof(service), "_sip._udp.%s", peer);
ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
if (ret > 0) {
hostn = host;
portno = tportno;
}
}
hp = ast_gethostbyname(hostn, &ahp);
if (hp) {
ast_copy_string(dialog->tohost, peer, sizeof(dialog->tohost));
memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
dialog->sa.sin_port = htons(portno);
memcpy(&dialog->recv, &dialog->sa, sizeof(dialog->recv));
return 0;
} else {
ast_log(LOG_WARNING, "No such host: %s\n", peer);
return -1;
}
} else {
ASTOBJ_UNREF(p, sip_destroy_peer);
return 0;
}
}
/*! \brief auto_congest: Scheduled congestion on a call ---*/
static int auto_congest(void *nothing)
{
struct sip_pvt *p = nothing;
ast_mutex_lock(&p->lock);
p->initid = -1;
if (p->owner) {
if (!ast_mutex_trylock(&p->owner->lock)) {
ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
ast_mutex_unlock(&p->owner->lock);
}
}
ast_mutex_unlock(&p->lock);
return 0;
}
/*! \brief sip_call: Initiate SIP call from PBX
* used from the dial() application */
static int sip_call(struct ast_channel *ast, char *dest, int timeout)
{
int res;
struct sip_pvt *p;
#ifdef OSP_SUPPORT
char *osphandle = NULL;
#endif
struct varshead *headp;
struct ast_var_t *current;
p = ast->tech_pvt;
if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
return -1;
}
/* Check whether there is vxml_url, distinctive ring variables */
headp=&ast->varshead;
AST_LIST_TRAVERSE(headp,current,entries) {
/* Check whether there is a VXML_URL variable */
if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
p->options->vxml_url = ast_var_value(current);
} else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
p->options->uri_options = ast_var_value(current);
} else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
/* Check whether there is a ALERT_INFO variable */
p->options->distinctive_ring = ast_var_value(current);
} else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
/* Check whether there is a variable with a name starting with SIPADDHEADER */
p->options->addsipheaders = 1;
}
#ifdef OSP_SUPPORT
else if (!p->options->osptoken && !strcasecmp(ast_var_name(current), "OSPTOKEN")) {
p->options->osptoken = ast_var_value(current);
} else if (!osphandle && !strcasecmp(ast_var_name(current), "OSPHANDLE")) {
osphandle = ast_var_value(current);
}
#endif
}
res = 0;
ast_set_flag(p, SIP_OUTGOING);
#ifdef OSP_SUPPORT
if (!p->options->osptoken || !osphandle || (sscanf(osphandle, "%d", &p->osphandle) != 1)) {
/* Force Disable OSP support */
ast_log(LOG_DEBUG, "Disabling OSP support for this call. osptoken = %s, osphandle = %s\n", p->options->osptoken, osphandle);
p->options->osptoken = NULL;
osphandle = NULL;
p->osphandle = -1;
}
#endif
ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
res = update_call_counter(p, INC_CALL_LIMIT);
if ( res != -1 ) {
p->callingpres = ast->cid.cid_pres;
p->jointcapability = p->capability;
transmit_invite(p, SIP_INVITE, 1, 2);
if (p->maxtime) {
/* Initialize auto-congest time */
p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
}
}
return res;
}
/*! \brief sip_registry_destroy: Destroy registry object ---*/
/* Objects created with the register= statement in static configuration */
static void sip_registry_destroy(struct sip_registry *reg)
{
/* Really delete */
if (reg->call) {
/* Clear registry before destroying to ensure
we don't get reentered trying to grab the registry lock */
reg->call->registry = NULL;
sip_destroy(reg->call);
}
if (reg->expire > -1)
ast_sched_del(sched, reg->expire);
if (reg->timeout > -1)
ast_sched_del(sched, reg->timeout);
regobjs--;
free(reg);
}
/*! \brief __sip_destroy: Execute destrucion of call structure, release memory---*/
static void __sip_destroy(struct sip_pvt *p, int lockowner)
{
struct sip_pvt *cur, *prev = NULL;
struct sip_pkt *cp;
struct sip_history *hist;
if (sip_debug_test_pvt(p))
ast_verbose("Destroying call '%s'\n", p->callid);
if (dumphistory)
sip_dump_history(p);
if (p->options)
free(p->options);
if (p->stateid > -1)
ast_extension_state_del(p->stateid, NULL);
if (p->initid > -1)
ast_sched_del(sched, p->initid);
if (p->autokillid > -1)
ast_sched_del(sched, p->autokillid);
if (p->rtp) {
ast_rtp_destroy(p->rtp);
}
if (p->vrtp) {
ast_rtp_destroy(p->vrtp);
}
if (p->route) {
free_old_route(p->route);
p->route = NULL;
}
if (p->registry) {
if (p->registry->call == p)
p->registry->call = NULL;
ASTOBJ_UNREF(p->registry,sip_registry_destroy);
}
if (p->rpid)
free(p->rpid);
if (p->rpid_from)
free(p->rpid_from);
/* Unlink us from the owner if we have one */
if (p->owner) {
if (lockowner)
ast_mutex_lock(&p->owner->lock);
ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
p->owner->tech_pvt = NULL;
if (lockowner)
ast_mutex_unlock(&p->owner->lock);
}
/* Clear history */
while(p->history) {
hist = p->history;
p->history = p->history->next;
free(hist);
}
cur = iflist;
while(cur) {
if (cur == p) {
if (prev)
prev->next = cur->next;
else
iflist = cur->next;
break;
}
prev = cur;
cur = cur->next;
}
if (!cur) {
ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
return;
}
while((cp = p->packets)) {
p->packets = p->packets->next;
if (cp->retransid > -1) {
ast_sched_del(sched, cp->retransid);
}
free(cp);
}
if (p->chanvars) {
ast_variables_destroy(p->chanvars);
p->chanvars = NULL;
}
ast_mutex_destroy(&p->lock);
free(p);
}
/*! \brief update_call_counter: Handle call_limit for SIP users
* Note: This is going to be replaced by app_groupcount
* Thought: For realtime, we should propably update storage with inuse counter... */
static int update_call_counter(struct sip_pvt *fup, int event)
{
char name[256];
int *inuse, *call_limit;
int outgoing = ast_test_flag(fup, SIP_OUTGOING);
struct sip_user *u = NULL;
struct sip_peer *p = NULL;
if (option_debug > 2)
ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
/* Test if we need to check call limits, in order to avoid
realtime lookups if we do not need it */
if (!ast_test_flag(fup, SIP_CALL_LIMIT))
return 0;
ast_copy_string(name, fup->username, sizeof(name));
/* Check the list of users */
u = find_user(name, 1);
if (u) {
inuse = &u->inUse;
call_limit = &u->call_limit;
p = NULL;
} else {
/* Try to find peer */
if (!p)
p = find_peer(fup->peername, NULL, 1);
if (p) {
inuse = &p->inUse;
call_limit = &p->call_limit;
ast_copy_string(name, fup->peername, sizeof(name));
} else {
if (option_debug > 1)
ast_log(LOG_DEBUG, "%s is not a local user, no call limit\n", name);
return 0;
}
}
switch(event) {
/* incoming and outgoing affects the inUse counter */
case DEC_CALL_LIMIT:
if ( *inuse > 0 ) {
if (ast_test_flag(fup,SIP_INC_COUNT))
(*inuse)--;
} else {
*inuse = 0;
}
if (option_debug > 1 || sipdebug) {
ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
}
break;
case INC_CALL_LIMIT:
if (*call_limit > 0 ) {
if (*inuse >= *call_limit) {
ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
if (u)
ASTOBJ_UNREF(u,sip_destroy_user);
else
ASTOBJ_UNREF(p,sip_destroy_peer);
return -1;
}
}
(*inuse)++;
ast_set_flag(fup,SIP_INC_COUNT);
if (option_debug > 1 || sipdebug) {
ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
}
break;
default:
ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
}
if (u)
ASTOBJ_UNREF(u,sip_destroy_user);
else
ASTOBJ_UNREF(p,sip_destroy_peer);
return 0;
}
/*! \brief sip_destroy: Destroy SIP call structure ---*/
static void sip_destroy(struct sip_pvt *p)
{
ast_mutex_lock(&iflock);
__sip_destroy(p, 1);
ast_mutex_unlock(&iflock);
}
static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
/*! \brief hangup_sip2cause: Convert SIP hangup causes to Asterisk hangup causes ---*/
static int hangup_sip2cause(int cause)
{
/* Possible values taken from causes.h */
switch(cause) {
case 603: /* Declined */
case 403: /* Not found */
case 487: /* Call cancelled */
return AST_CAUSE_CALL_REJECTED;
case 404: /* Not found */
return AST_CAUSE_UNALLOCATED;
case 408: /* No reaction */
return AST_CAUSE_NO_USER_RESPONSE;
case 480: /* No answer */
return AST_CAUSE_FAILURE;
case 483: /* Too many hops */
return AST_CAUSE_NO_ANSWER;
case 486: /* Busy everywhere */
return AST_CAUSE_BUSY;
case 488: /* No codecs approved */
return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
case 500: /* Server internal failure */
return AST_CAUSE_FAILURE;
case 501: /* Call rejected */
return AST_CAUSE_FACILITY_REJECTED;
case 502:
return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
case 503: /* Service unavailable */
return AST_CAUSE_CONGESTION;
default:
return AST_CAUSE_NORMAL;
}
/* Never reached */
return 0;
}
/*! \brief hangup_cause2sip: Convert Asterisk hangup causes to SIP codes
\verbatim
Possible values from causes.h
AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
In addition to these, a lot of PRI codes is defined in causes.h
...should we take care of them too ?
Quote RFC 3398
ISUP Cause value SIP response
---------------- ------------
1 unallocated number 404 Not Found
2 no route to network 404 Not found
3 no route to destination 404 Not found
16 normal call clearing --- (*)
17 user busy 486 Busy here
18 no user responding 408 Request Timeout
19 no answer from the user 480 Temporarily unavailable
20 subscriber absent 480 Temporarily unavailable
21 call rejected 403 Forbidden (+)
22 number changed (w/o diagnostic) 410 Gone
22 number changed (w/ diagnostic) 301 Moved Permanently
23 redirection to new destination 410 Gone
26 non-selected user clearing 404 Not Found (=)
27 destination out of order 502 Bad Gateway
28 address incomplete 484 Address incomplete
29 facility rejected 501 Not implemented
31 normal unspecified 480 Temporarily unavailable
\endverbatim
*/
static char *hangup_cause2sip(int cause)
{
switch(cause)
{
case AST_CAUSE_UNALLOCATED: /* 1 */
case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
return "404 Not Found";
case AST_CAUSE_CONGESTION: /* 34 */
case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
return "503 Service Unavailable";
case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
return "408 Request Timeout";
case AST_CAUSE_NO_ANSWER: /* 19 */
return "480 Temporarily unavailable";
case AST_CAUSE_CALL_REJECTED: /* 21 */
return "403 Forbidden";
case AST_CAUSE_NUMBER_CHANGED: /* 22 */
return "410 Gone";
case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
return "480 Temporarily unavailable";
case AST_CAUSE_INVALID_NUMBER_FORMAT:
return "484 Address incomplete";
case AST_CAUSE_USER_BUSY:
return "486 Busy here";
case AST_CAUSE_FAILURE:
return "500 Server internal failure";
case AST_CAUSE_FACILITY_REJECTED: /* 29 */
return "501 Not Implemented";
case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
return "503 Service Unavailable";
/* Used in chan_iax2 */
case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
return "502 Bad Gateway";
case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
return "488 Not Acceptable Here";
case AST_CAUSE_NOTDEFINED:
default:
ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
return NULL;
}
/* Never reached */
return 0;
}
/*! \brief sip_hangup: Hangup SIP call
* Part of PBX interface, called from ast_hangup */
static int sip_hangup(struct ast_channel *ast)
{
struct sip_pvt *p = ast->tech_pvt;
int needcancel = 0;
int needdestroy = 0;
if (!p) {
ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
return 0;
}
if (option_debug)
ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
ast_mutex_lock(&p->lock);
#ifdef OSP_SUPPORT
if ((p->osphandle > -1) && (ast->_state == AST_STATE_UP)) {
ast_osp_terminate(p->osphandle, AST_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart);
}
#endif
ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter\n", p->username);
update_call_counter(p, DEC_CALL_LIMIT);
/* Determine how to disconnect */
if (p->owner != ast) {
ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
ast_mutex_unlock(&p->lock);
return 0;
}
/* If the call is not UP, we need to send CANCEL instead of BYE */
if (ast->_state != AST_STATE_UP)
needcancel = 1;
/* Disconnect */
if (p->vad) {
ast_dsp_free(p->vad);
}
p->owner = NULL;
ast->tech_pvt = NULL;
ast_mutex_lock(&usecnt_lock);
usecnt--;
ast_mutex_unlock(&usecnt_lock);
ast_update_use_count();
/* Do not destroy this pvt until we have timeout or
get an answer to the BYE or INVITE/CANCEL
If we get no answer during retransmit period, drop the call anyway.
(Sorry, mother-in-law, you can't deny a hangup by sending
603 declined to BYE...)
*/
if (ast_test_flag(p, SIP_ALREADYGONE))
needdestroy = 1; /* Set destroy flag at end of this function */
else
sip_scheddestroy(p, 32000);
/* Start the process if it's not already started */
if (!ast_test_flag(p, SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
if (needcancel) { /* Outgoing call, not up */
if (ast_test_flag(p, SIP_OUTGOING)) {
/* stop retransmitting an INVITE that has not received a response */
__sip_pretend_ack(p);
/* are we allowed to send CANCEL yet? if not, mark
it pending */
if (!ast_test_flag(p, SIP_CAN_BYE)) {
ast_set_flag(p, SIP_PENDINGBYE);
/* Do we need a timer here if we don't hear from them at all? */
} else {
/* Send a new request: CANCEL */
transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, 1, 0);
/* Actually don't destroy us yet, wait for the 487 on our original
INVITE, but do set an autodestruct just in case we never get it. */
}
if ( p->initid != -1 ) {
/* channel still up - reverse dec of inUse counter
only if the channel is not auto-congested */
update_call_counter(p, INC_CALL_LIMIT);
}
} else { /* Incoming call, not up */
char *res;
if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
transmit_response_reliable(p, res, &p->initreq, 1);
} else
transmit_response_reliable(p, "603 Declined", &p->initreq, 1);
}
} else { /* Call is in UP state, send BYE */
if (!p->pendinginvite) {
/* Send a hangup */
transmit_request_with_auth(p, SIP_BYE, 0, 1, 1);
} else {
/* Note we will need a BYE when this all settles out
but we can't send one while we have "INVITE" outstanding. */
ast_set_flag(p, SIP_PENDINGBYE);
ast_clear_flag(p, SIP_NEEDREINVITE);
}
}
}
if (needdestroy)
ast_set_flag(p, SIP_NEEDDESTROY);
ast_mutex_unlock(&p->lock);
return 0;
}
/*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
static void try_suggested_sip_codec(struct sip_pvt *p)
{
int fmt;
char *codec;
codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
if (!codec)
return;
fmt = ast_getformatbyname(codec);
if (fmt) {
ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
if (p->jointcapability & fmt) {
p->jointcapability &= fmt;
p->capability &= fmt;
} else
ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
} else
ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
return;
}
/*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
* Part of PBX interface */
static int sip_answer(struct ast_channel *ast)
{
int res = 0;
struct sip_pvt *p = ast->tech_pvt;
ast_mutex_lock(&p->lock);
if (ast->_state != AST_STATE_UP) {
#ifdef OSP_SUPPORT
time(&p->ospstart);
#endif
try_suggested_sip_codec(p);
ast_setstate(ast, AST_STATE_UP);
if (option_debug)
ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
}
ast_mutex_unlock(&p->lock);
return res;
}
/*! \brief sip_write: Send frame to media channel (rtp) ---*/
static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
{
struct sip_pvt *p = ast->tech_pvt;
int res = 0;
switch (frame->frametype) {
case AST_FRAME_VOICE:
if (!(frame->subclass & ast->nativeformats)) {
ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
return 0;
}
if (p) {
ast_mutex_lock(&p->lock);
if (p->rtp) {
/* If channel is not up, activate early media session */
if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
ast_set_flag(p, SIP_PROGRESS_SENT);
}
time(&p->lastrtptx);
res = ast_rtp_write(p->rtp, frame);
}
ast_mutex_unlock(&p->lock);
}
break;
case AST_FRAME_VIDEO:
if (p) {
ast_mutex_lock(&p->lock);
if (p->vrtp) {
/* Activate video early media */
if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
ast_set_flag(p, SIP_PROGRESS_SENT);
}
time(&p->lastrtptx);
res = ast_rtp_write(p->vrtp, frame);
}
ast_mutex_unlock(&p->lock);
}
break;
case AST_FRAME_IMAGE:
return 0;
break;
default:
ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
return 0;
}
return res;
}
/*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
Basically update any ->owner links ----*/
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
{
struct sip_pvt *p = newchan->tech_pvt;
ast_mutex_lock(&p->lock);
if (p->owner != oldchan) {
ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
ast_mutex_unlock(&p->lock);
return -1;
}
p->owner = newchan;
ast_mutex_unlock(&p->lock);
return 0;
}
/*! \brief sip_senddigit: Send DTMF character on SIP channel */
/* within one call, we're able to transmit in many methods simultaneously */
static int sip_senddigit(struct ast_channel *ast, char digit)
{
struct sip_pvt *p = ast->tech_pvt;
int res = 0;
ast_mutex_lock(&p->lock);
switch (ast_test_flag(p, SIP_DTMF)) {
case SIP_DTMF_INFO:
transmit_info_with_digit(p, digit);
break;
case SIP_DTMF_RFC2833:
if (p->rtp)
ast_rtp_senddigit(p->rtp, digit);
break;
case SIP_DTMF_INBAND:
res = -1;
break;
}
ast_mutex_unlock(&p->lock);
return res;
}
/*! \brief sip_transfer: Transfer SIP call */
static int sip_transfer(struct ast_channel *ast, const char *dest)
{
struct sip_pvt *p = ast->tech_pvt;
int res;
ast_mutex_lock(&p->lock);
if (ast->_state == AST_STATE_RING)
res = sip_sipredirect(p, dest);
else
res = transmit_refer(p, dest);
ast_mutex_unlock(&p->lock);
return res;
}
/*! \brief sip_indicate: Play indication to user
* With SIP a lot of indications is sent as messages, letting the device play
the indication - busy signal, congestion etc */
static int sip_indicate(struct ast_channel *ast, int condition)
{
struct sip_pvt *p = ast->tech_pvt;
int res = 0;
ast_mutex_lock(&p->lock);
switch(condition) {
case AST_CONTROL_RINGING:
if (ast->_state == AST_STATE_RING) {
if (!ast_test_flag(p, SIP_PROGRESS_SENT) ||
(ast_test_flag(p, SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
/* Send 180 ringing if out-of-band seems reasonable */
transmit_response(p, "180 Ringing", &p->initreq);
ast_set_flag(p, SIP_RINGING);
if (ast_test_flag(p, SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
break;
} else {
/* Well, if it's not reasonable, just send in-band */
}
}
res = -1;
break;
case AST_CONTROL_BUSY:
if (ast->_state != AST_STATE_UP) {
transmit_response(p, "486 Busy Here", &p->initreq);
ast_set_flag(p, SIP_ALREADYGONE);
ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
break;
}
res = -1;
break;
case AST_CONTROL_CONGESTION:
if (ast->_state != AST_STATE_UP) {
transmit_response(p, "503 Service Unavailable", &p->initreq);
ast_set_flag(p, SIP_ALREADYGONE);
ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
break;
}
res = -1;
break;
case AST_CONTROL_PROCEEDING:
if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
transmit_response(p, "100 Trying", &p->initreq);
break;
}
res = -1;
break;
case AST_CONTROL_PROGRESS:
if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
ast_set_flag(p, SIP_PROGRESS_SENT);
break;
}
res = -1;
break;
case AST_CONTROL_HOLD: /* The other part of the bridge are put on hold */
if (sipdebug)
ast_log(LOG_DEBUG, "Bridged channel now on hold%s\n", p->callid);
res = -1;
break;
case AST_CONTROL_UNHOLD: /* The other part of the bridge are back from hold */
if (sipdebug)
ast_log(LOG_DEBUG, "Bridged channel is back from hold, let's talk! : %s\n", p->callid);
res = -1;
break;
case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
if (p->vrtp && !ast_test_flag(p, SIP_NOVIDEO)) {
transmit_info_with_vidupdate(p);
res = 0;
} else
res = -1;
break;
case -1:
res = -1;
break;
default:
ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
res = -1;
break;
}
ast_mutex_unlock(&p->lock);
return res;
}
/*! \brief sip_new: Initiate a call in the SIP channel */
/* called from sip_request_call (calls from the pbx ) */
static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
{
struct ast_channel *tmp;
struct ast_variable *v = NULL;
int fmt;
#ifdef OSP_SUPPORT
char iabuf[INET_ADDRSTRLEN];
char peer[MAXHOSTNAMELEN];
#endif
ast_mutex_unlock(&i->lock);
/* Don't hold a sip pvt lock while we allocate a channel */
tmp = ast_channel_alloc(1);
ast_mutex_lock(&i->lock);
if (!tmp) {
ast_log(LOG_WARNING, "Unable to allocate SIP channel structure\n");
return NULL;
}
tmp->tech = &sip_tech;
/* Select our native format based on codec preference until we receive
something from another device to the contrary. */
if (i->jointcapability)
tmp->nativeformats = ast_codec_choose(&i->prefs, i->jointcapability, 1);
else if (i->capability)
tmp->nativeformats = ast_codec_choose(&i->prefs, i->capability, 1);
else
tmp->nativeformats = ast_codec_choose(&i->prefs, global_capability, 1);
fmt = ast_best_codec(tmp->nativeformats);
if (title)
snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", title, (int)(long) i);
else if (strchr(i->fromdomain,':'))
snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':') + 1, (int)(long) i);
else
snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(long) i);
tmp->type = channeltype;
if (ast_test_flag(i, SIP_DTMF) == SIP_DTMF_INBAND) {
i->vad = ast_dsp_new();
ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
if (relaxdtmf)
ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
}
if (i->rtp) {
tmp->fds[0] = ast_rtp_fd(i->rtp);
tmp->fds[1] = ast_rtcp_fd(i->rtp);
}
if (i->vrtp) {
tmp->fds[2] = ast_rtp_fd(i->vrtp);
tmp->fds[3] = ast_rtcp_fd(i->vrtp);
}
if (state == AST_STATE_RING)
tmp->rings = 1;
tmp->adsicpe = AST_ADSI_UNAVAILABLE;
tmp->writeformat = fmt;
tmp->rawwriteformat = fmt;
tmp->readformat = fmt;
tmp->rawreadformat = fmt;
tmp->tech_pvt = i;
tmp->callgroup = i->callgroup;
tmp->pickupgroup = i->pickupgroup;
tmp->cid.cid_pres = i->callingpres;
if (!ast_strlen_zero(i->accountcode))
ast_copy_string(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode));
if (i->amaflags)
tmp->amaflags = i->amaflags;
if (!ast_strlen_zero(i->language))
ast_copy_string(tmp->language, i->language, sizeof(tmp->language));
if (!ast_strlen_zero(i->musicclass))
ast_copy_string(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass));
i->owner = tmp;
ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
if (!ast_strlen_zero(i->cid_num))
tmp->cid.cid_num = strdup(i->cid_num);
if (!ast_strlen_zero(i->cid_name))
tmp->cid.cid_name = strdup(i->cid_name);
if (!ast_strlen_zero(i->rdnis))
tmp->cid.cid_rdnis = strdup(i->rdnis);
if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
tmp->cid.cid_dnid = strdup(i->exten);
tmp->priority = 1;
if (!ast_strlen_zero(i->uri)) {
pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
}
if (!ast_strlen_zero(i->domain)) {
pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
}
if (!ast_strlen_zero(i->useragent)) {
pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
}
if (!ast_strlen_zero(i->callid)) {
pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
}
#ifdef OSP_SUPPORT
snprintf(peer, sizeof(peer), "[%s]:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), i->sa.sin_addr), ntohs(i->sa.sin_port));
pbx_builtin_setvar_helper(tmp, "OSPPEER", peer);
#endif
ast_setstate(tmp, state);
if (state != AST_STATE_DOWN) {
if (ast_pbx_start(tmp)) {
ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
ast_hangup(tmp);
tmp = NULL;
}
}
/* Set channel variables for this call from configuration */
for (v = i->chanvars ; v ; v = v->next)
pbx_builtin_setvar_helper(tmp,v->name,v->value);
ast_mutex_lock(&usecnt_lock);
usecnt++;
ast_mutex_unlock(&usecnt_lock);
ast_update_use_count();
return tmp;
}
/*! \brief get_body_by_line: Reads one line of message body */
static char *get_body_by_line(char *line, char *name, int nameLen)
{
if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
return ast_skip_blanks(line + nameLen + 1);
}
return "";
}
/*! \brief get_sdp: get a specific line from the SDP */
static char *get_sdp(struct sip_request *req, char *name)
{
int x;
int len = strlen(name);
char *r;
for (x = req->sdp_start; x < req->sdp_end; x++) {
r = get_body_by_line(req->line[x], name, len);
if (r[0] != '\0')
return r;
}
return "";
}
static void sdpLineNum_iterator_init(int *iterator, struct sip_request *req)
{
*iterator = req->sdp_start;
}
static char *get_sdp_iterate(int *iterator,
struct sip_request *req, char *name)
{
int len = strlen(name);
char *r;
while (*iterator < req->sdp_end) {
r = get_body_by_line(req->line[(*iterator)++], name, len);
if (r[0] != '\0')
return r;
}
return "";
}
/*! \brief get_body: get a specific line from the message body */
static char *get_body(struct sip_request *req, char *name)
{
int x;
int len = strlen(name);
char *r;
for (x = 0; x < req->lines; x++) {
r = get_body_by_line(req->line[x], name, len);
if (r[0] != '\0')
return r;
}
return "";
}
static char *find_alias(const char *name, char *_default)
{
int x;
for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
if (!strcasecmp(aliases[x].fullname, name))
return aliases[x].shortname;
return _default;
}
static char *__get_header(struct sip_request *req, char *name, int *start)
{
int pass;
/*
* Technically you can place arbitrary whitespace both before and after the ':' in
* a header, although RFC3261 clearly says you shouldn't before, and place just
* one afterwards. If you shouldn't do it, what absolute idiot decided it was
* a good idea to say you can do it, and if you can do it, why in the hell would.
* you say you shouldn't.
* Anyways, pedanticsipchecking controls whether we allow spaces before ':',
* and we always allow spaces after that for compatibility.
*/
for (pass = 0; name && pass < 2;pass++) {
int x, len = strlen(name);
for (x=*start; x<req->headers; x++) {
if (!strncasecmp(req->header[x], name, len)) {
char *r = req->header[x] + len; /* skip name */
if (pedanticsipchecking)
r = ast_skip_blanks(r);
if (*r == ':') {
*start = x+1;
return ast_skip_blanks(r+1);
}
}
}
if (pass == 0) /* Try aliases */
name = find_alias(name, NULL);
}
/* Don't return NULL, so get_header is always a valid pointer */
return "";
}
/*! \brief get_header: Get header from SIP request ---*/
static char *get_header(struct sip_request *req, char *name)
{
int start = 0;
return __get_header(req, name, &start);
}
/*! \brief sip_rtp_read: Read RTP from network ---*/
static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
{
/* Retrieve audio/etc from channel. Assumes p->lock is already held. */
struct ast_frame *f;
static struct ast_frame null_frame = { AST_FRAME_NULL, };
if (!p->rtp) {
/* We have no RTP allocated for this channel */
return &null_frame;
}
switch(ast->fdno) {
case 0:
f = ast_rtp_read(p->rtp); /* RTP Audio */
break;
case 1:
f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
break;
case 2:
f = ast_rtp_read(p->vrtp); /* RTP Video */
break;
case 3:
f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
break;
default:
f = &null_frame;
}
/* Don't forward RFC2833 if we're not supposed to */
if (f && (f->frametype == AST_FRAME_DTMF) && (ast_test_flag(p, SIP_DTMF) != SIP_DTMF_RFC2833))
return &null_frame;
if (p->owner) {
/* We already hold the channel lock */
if (f->frametype == AST_FRAME_VOICE) {
if (f->subclass != p->owner->nativeformats) {
ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
p->owner->nativeformats = f->subclass;
ast_set_read_format(p->owner, p->owner->readformat);
ast_set_write_format(p->owner, p->owner->writeformat);
}
if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
f = ast_dsp_process(p->owner, p->vad, f);
if (f && (f->frametype == AST_FRAME_DTMF))
ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
}
}
}
return f;
}
/*! \brief sip_read: Read SIP RTP from channel */
static struct ast_frame *sip_read(struct ast_channel *ast)
{
struct ast_frame *fr;
struct sip_pvt *p = ast->tech_pvt;
ast_mutex_lock(&p->lock);
fr = sip_rtp_read(ast, p);
time(&p->lastrtprx);
ast_mutex_unlock(&p->lock);
return fr;
}
/*! \brief build_callid: Build SIP CALLID header ---*/
static void build_callid(char *callid, int len, struct in_addr ourip, char *fromdomain)
{
int res;
int val;
int x;
char iabuf[INET_ADDRSTRLEN];
for (x=0; x<4; x++) {
val = thread_safe_rand();
res = snprintf(callid, len, "%08x", val);
len -= res;
callid += res;
}
if (!ast_strlen_zero(fromdomain))
snprintf(callid, len, "@%s", fromdomain);
else
/* It's not important that we really use our right IP here... */
snprintf(callid, len, "@%s", ast_inet_ntoa(iabuf, sizeof(iabuf), ourip));
}
static void make_our_tag(char *tagbuf, size_t len)
{
snprintf(tagbuf, len, "as%08x", thread_safe_rand());
}
/*! \brief sip_alloc: Allocate SIP_PVT structure and set defaults ---*/
static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method)
{
struct sip_pvt *p;
if (!(p = calloc(1, sizeof(*p))))
return NULL;
ast_mutex_init(&p->lock);
p->method = intended_method;
p->initid = -1;
p->autokillid = -1;
p->subscribed = NONE;
p->stateid = -1;
p->prefs = prefs;
if (intended_method != SIP_OPTIONS) /* Peerpoke has it's own system */
p->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
#ifdef OSP_SUPPORT
p->osphandle = -1;
p->osptimelimit = 0;
#endif
if (sin) {
memcpy(&p->sa, sin, sizeof(p->sa));
if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
} else {
memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
}
p->branch = thread_safe_rand();
make_our_tag(p->tag, sizeof(p->tag));
/* Start with 101 instead of 1 */
p->ocseq = 101;
if (sip_methods[intended_method].need_rtp) {
p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
if (videosupport)
p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
if (!p->rtp || (videosupport && !p->vrtp)) {
ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n", videosupport ? "and video" : "", strerror(errno));
ast_mutex_destroy(&p->lock);
if (p->chanvars) {
ast_variables_destroy(p->chanvars);
p->chanvars = NULL;
}
free(p);
return NULL;
}
ast_rtp_settos(p->rtp, tos);
if (p->vrtp)
ast_rtp_settos(p->vrtp, tos);
p->rtptimeout = global_rtptimeout;
p->rtpholdtimeout = global_rtpholdtimeout;
p->rtpkeepalive = global_rtpkeepalive;
}
if (useglobal_nat && sin) {
/* Setup NAT structure according to global settings if we have an address */
ast_copy_flags(p, &global_flags, SIP_NAT);
memcpy(&p->recv, sin, sizeof(p->recv));
if (p->rtp)
ast_rtp_setnat(p->rtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
if (p->vrtp)
ast_rtp_setnat(p->vrtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
}
if (p->method != SIP_REGISTER)
ast_copy_string(p->fromdomain, default_fromdomain, sizeof(p->fromdomain));
build_via(p, p->via, sizeof(p->via));
if (!callid)
build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
else
ast_copy_string(p->callid, callid, sizeof(p->callid));
ast_copy_flags(p, &global_flags, SIP_FLAGS_TO_COPY);
/* Assign default music on hold class */
strcpy(p->musicclass, global_musicclass);
p->capability = global_capability;
if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO))
p->noncodeccapability |= AST_RTP_DTMF;
strcpy(p->context, default_context);
/* Add to active dialog list */
ast_mutex_lock(&iflock);
p->next = iflist;
iflist = p;
ast_mutex_unlock(&iflock);
if (option_debug)
ast_log(LOG_DEBUG, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : "(No Call-ID)", sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
return p;
}
/*! \brief find_call: Connect incoming SIP message to current dialog or create new dialog structure */
/* Called by handle_request, sipsock_read */
static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
{
struct sip_pvt *p = NULL;
char *callid;
char *tag = "";
char totag[128];
char fromtag[128];
callid = get_header(req, "Call-ID");
if (pedanticsipchecking) {
/* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
we need more to identify a branch - so we have to check branch, from
and to tags to identify a call leg.
For Asterisk to behave correctly, you need to turn on pedanticsipchecking
in sip.conf
*/
if (gettag(req, "To", totag, sizeof(totag)))
ast_set_flag(req, SIP_PKT_WITH_TOTAG); /* Used in handle_request/response */
gettag(req, "From", fromtag, sizeof(fromtag));
if (req->method == SIP_RESPONSE)
tag = totag;
else
tag = fromtag;
if (option_debug > 4 )
ast_log(LOG_DEBUG, "= Looking for Call ID: %s (Checking %s) --From tag %s --To-tag %s \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);
}
ast_mutex_lock(&iflock);
p = iflist;
while(p) { /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
int found = 0;
if (req->method == SIP_REGISTER)
found = (!strcmp(p->callid, callid));
else
found = (!strcmp(p->callid, callid) &&
(!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
if (option_debug > 4)
ast_log(LOG_DEBUG, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match", p->callid, p->theirtag, p->tag);
/* If we get a new request within an existing to-tag - check the to tag as well */
if (pedanticsipchecking && found && req->method != SIP_RESPONSE) { /* SIP Request */
if (p->tag[0] == '\0' && totag[0]) {
/* We have no to tag, but they have. Wrong dialog */
found = 0;
} else if (totag[0]) { /* Both have tags, compare them */
if (strcmp(totag, p->tag)) {
found = 0; /* This is not our packet */
}
}
if (!found && option_debug > 4)
ast_log(LOG_DEBUG, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n", p->callid, totag, sip_methods[req->method].text);
}
if (found) {
/* Found the call */
ast_mutex_lock(&p->lock);
ast_mutex_unlock(&iflock);
return p;
}
p = p->next;
}
ast_mutex_unlock(&iflock);
/* If this is a response and we have ignoring of out of dialog responses turned on, then drop it */
if (!sip_methods[intended_method].can_create) {
if (intended_method != SIP_RESPONSE)
transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
} else {
p = sip_alloc(callid, sin, 1, intended_method);
if (p)
ast_mutex_lock(&p->lock);
}
return p;
}
/*! \brief sip_register: Parse register=> line in sip.conf and add to registry */
static int sip_register(char *value, int lineno)
{
struct sip_registry *reg;
char copy[256];
char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
char *porta=NULL;
char *contact=NULL;
char *stringp=NULL;
if (!value)
return -1;
ast_copy_string(copy, value, sizeof(copy));
stringp=copy;
username = stringp;
hostname = strrchr(stringp, '@');
if (hostname) {
*hostname = '\0';
hostname++;
}
if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
return -1;
}
stringp=username;
username = strsep(&stringp, ":");
if (username) {
secret = strsep(&stringp, ":");
if (secret)
authuser = strsep(&stringp, ":");
}
stringp = hostname;
hostname = strsep(&stringp, "/");
if (hostname)
contact = strsep(&stringp, "/");
if (ast_strlen_zero(contact))
contact = "s";
stringp=hostname;
hostname = strsep(&stringp, ":");
porta = strsep(&stringp, ":");
if (porta && !atoi(porta)) {
ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
return -1;
}
reg = malloc(sizeof(struct sip_registry));
if (!reg) {
ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
return -1;
}
memset(reg, 0, sizeof(struct sip_registry));
regobjs++;
ASTOBJ_INIT(reg);
ast_copy_string(reg->contact, contact, sizeof(reg->contact));
if (username)
ast_copy_string(reg->username, username, sizeof(reg->username));
if (hostname)
ast_copy_string(reg->hostname, hostname, sizeof(reg->hostname));
if (authuser)
ast_copy_string(reg->authuser, authuser, sizeof(reg->authuser));
if (secret)
ast_copy_string(reg->secret, secret, sizeof(reg->secret));
reg->expire = -1;
reg->timeout = -1;
reg->refresh = default_expiry;
reg->portno = porta ? atoi(porta) : 0;
reg->callid_valid = 0;
reg->ocseq = 101;
ASTOBJ_CONTAINER_LINK(®l, reg);
ASTOBJ_UNREF(reg,sip_registry_destroy);
return 0;
}
/*! \brief lws2sws: Parse multiline SIP headers into one header */
/* This is enabled if pedanticsipchecking is enabled */
static int lws2sws(char *msgbuf, int len)
{
int h = 0, t = 0;
int lws = 0;
for (; h < len;) {
/* Eliminate all CRs */
if (msgbuf[h] == '\r') {
h++;
continue;
}
/* Check for end-of-line */
if (msgbuf[h] == '\n') {
/* Check for end-of-message */
if (h + 1 == len)
break;
/* Check for a continuation line */
if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
/* Merge continuation line */
h++;
continue;
}
/* Propagate LF and start new line */
msgbuf[t++] = msgbuf[h++];
lws = 0;
continue;
}
if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
if (lws) {
h++;
continue;
}
msgbuf[t++] = msgbuf[h++];
lws = 1;
continue;
}
msgbuf[t++] = msgbuf[h++];
if (lws)
lws = 0;
}
msgbuf[t] = '\0';
return t;
}
/*! \brief parse_request: Parse a SIP message ----*/
static void parse_request(struct sip_request *req)
{
/* Divide fields by NULL's */
char *c;
int f = 0;
c = req->data;
/* First header starts immediately */
req->header[f] = c;
while(*c) {
if (*c == '\n') {
/* We've got a new header */
*c = 0;
if (sipdebug && option_debug > 3)
ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
if (ast_strlen_zero(req->header[f])) {
/* Line by itself means we're now in content */
c++;
break;
}
if (f >= SIP_MAX_HEADERS - 1) {
ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
} else
f++;
req->header[f] = c + 1;
} else if (*c == '\r') {
/* Ignore but eliminate \r's */
*c = 0;
}
c++;
}
/* Check for last header */
if (!ast_strlen_zero(req->header[f])) {
if (sipdebug && option_debug > 3)
ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
f++;
}
req->headers = f;
/* Now we process any mime content */
f = 0;
req->line[f] = c;
while(*c) {
if (*c == '\n') {
/* We've got a new line */
*c = 0;
if (sipdebug && option_debug > 3)
ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
if (f >= SIP_MAX_LINES - 1) {
ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
} else
f++;
req->line[f] = c + 1;
} else if (*c == '\r') {
/* Ignore and eliminate \r's */
*c = 0;
}
c++;
}
/* Check for last line */
if (!ast_strlen_zero(req->line[f]))
f++;
req->lines = f;
if (*c)
ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
/* Split up the first line parts */
determine_firstline_parts(req);
}
/*!
\brief Determine whether a SIP message contains an SDP in its body
\param req the SIP request to process
\return 1 if SDP found, 0 if not found
Also updates req->sdp_start and req->sdp_end to indicate where the SDP
lives in the message body.
*/
static int find_sdp(struct sip_request *req)
{
char *content_type;
char *search;
char *boundary;
unsigned int x;
content_type = get_header(req, "Content-Type");
/* if the body contains only SDP, this is easy */
if (!strcasecmp(content_type, "application/sdp")) {
req->sdp_start = 0;
req->sdp_end = req->lines;
return 1;
}
/* if it's not multipart/mixed, there cannot be an SDP */
if (strncasecmp(content_type, "multipart/mixed", 15))
return 0;
/* if there is no boundary marker, it's invalid */
if (!(search = strcasestr(content_type, ";boundary=")))
return 0;
search += 10;
if (ast_strlen_zero(search))
return 0;
/* make a duplicate of the string, with two extra characters
at the beginning */
boundary = ast_strdupa(search - 2);
boundary[0] = boundary[1] = '-';
/* search for the boundary marker, but stop when there are not enough
lines left for it, the Content-Type header and at least one line of
body */
for (x = 0; x < (req->lines - 2); x++) {
if (!strncasecmp(req->line[x], boundary, strlen(boundary)) &&
!strcasecmp(req->line[x + 1], "Content-Type: application/sdp")) {
req->sdp_start = x + 2;
/* search for the end of the body part */
for ( ; x < req->lines; x++) {
if (!strncasecmp(req->line[x], boundary, strlen(boundary)))
break;
}
req->sdp_end = x;
return 1;
}
}
return 0;
}
/*! \brief process_sdp: Process SIP SDP and activate RTP channels---*/
static int process_sdp(struct sip_pvt *p, struct sip_request *req)
{
char *m;
char *c;
char *a;
char host[258];
char iabuf[INET_ADDRSTRLEN];
int len = -1;
int portno = -1;
int vportno = -1;
int peercapability, peernoncodeccapability;
int vpeercapability=0, vpeernoncodeccapability=0;
struct sockaddr_in sin;
char *codecs;
struct hostent *hp;
struct ast_hostent ahp;
int codec;
int destiterator = 0;
int iterator;
int sendonly = 0;
int x,y;
int debug=sip_debug_test_pvt(p);
struct ast_channel *bridgepeer = NULL;
if (!p->rtp) {
ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
return -1;
}
/* Update our last rtprx when we receive an SDP, too */
time(&p->lastrtprx);
time(&p->lastrtptx);
m = get_sdp(req, "m");
sdpLineNum_iterator_init(&destiterator, req);
c = get_sdp_iterate(&destiterator, req, "c");
if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
return -1;
}
if (sscanf(c, "IN IP4 %256s", host) != 1) {
ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
return -1;
}
/* XXX This could block for a long time, and block the main thread! XXX */
hp = ast_gethostbyname(host, &ahp);
if (!hp) {
ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
return -1;
}
sdpLineNum_iterator_init(&iterator, req);
ast_set_flag(p, SIP_NOVIDEO);
while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
int found = 0;
if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &y, &len) == 2) ||
(sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
found = 1;
portno = x;
/* Scan through the RTP payload types specified in a "m=" line: */
ast_rtp_pt_clear(p->rtp);
codecs = m + len;
while(!ast_strlen_zero(codecs)) {
if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
return -1;
}
if (debug)
ast_verbose("Found RTP audio format %d\n", codec);
ast_rtp_set_m_type(p->rtp, codec);
codecs = ast_skip_blanks(codecs + len);
}
}
if (p->vrtp)
ast_rtp_pt_clear(p->vrtp); /* Must be cleared in case no m=video line exists */
if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
found = 1;
ast_clear_flag(p, SIP_NOVIDEO);
vportno = x;
/* Scan through the RTP payload types specified in a "m=" line: */
codecs = m + len;
while(!ast_strlen_zero(codecs)) {
if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
return -1;
}
if (debug)
ast_verbose("Found RTP video format %d\n", codec);
ast_rtp_set_m_type(p->vrtp, codec);
codecs = ast_skip_blanks(codecs + len);
}
}
if (!found )
ast_log(LOG_WARNING, "Unknown SDP media type in offer: %s\n", m);
}
if (portno == -1 && vportno == -1) {
/* No acceptable offer found in SDP */
return -2;
}
/* Check for Media-description-level-address for audio */
c = get_sdp_iterate(&destiterator, req, "c");
if (!ast_strlen_zero(c)) {
if (sscanf(c, "IN IP4 %256s", host) != 1) {
ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
} else {
/* XXX This could block for a long time, and block the main thread! XXX */
hp = ast_gethostbyname(host, &ahp);
if (!hp) {
ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
}
}
}
/* RTP addresses and ports for audio and video */
sin.sin_family = AF_INET;
memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
/* Setup audio port number */
sin.sin_port = htons(portno);
if (p->rtp && sin.sin_port) {
ast_rtp_set_peer(p->rtp, &sin);
if (debug) {
ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
ast_log(LOG_DEBUG,"Peer audio RTP is at port %s:%d\n",ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
}
}
/* Check for Media-description-level-address for video */
c = get_sdp_iterate(&destiterator, req, "c");
if (!ast_strlen_zero(c)) {
if (sscanf(c, "IN IP4 %256s", host) != 1) {
ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
} else {
/* XXX This could block for a long time, and block the main thread! XXX */
hp = ast_gethostbyname(host, &ahp);
if (!hp) {
ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
}
}
}
/* Setup video port number */
sin.sin_port = htons(vportno);
if (p->vrtp && sin.sin_port) {
ast_rtp_set_peer(p->vrtp, &sin);
if (debug) {
ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
ast_log(LOG_DEBUG,"Peer video RTP is at port %s:%d\n",ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
}
}
/* Next, scan through each "a=rtpmap:" line, noting each
* specified RTP payload type (with corresponding MIME subtype):
*/
sdpLineNum_iterator_init(&iterator, req);
while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
if (!strcasecmp(a, "sendonly") || !strcasecmp(a, "inactive")) {
sendonly = 1;
continue;
}
if (!strcasecmp(a, "sendrecv")) {
sendonly = 0;
}
if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
if (debug)
ast_verbose("Found description format %s\n", mimeSubtype);
/* Note: should really look at the 'freq' and '#chans' params too */
ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
if (p->vrtp)
ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
}
/* Now gather all of the codecs that were asked for: */
ast_rtp_get_current_formats(p->rtp,
&peercapability, &peernoncodeccapability);
if (p->vrtp)
ast_rtp_get_current_formats(p->vrtp,
&vpeercapability, &vpeernoncodeccapability);
p->jointcapability = p->capability & (peercapability | vpeercapability);
p->peercapability = (peercapability | vpeercapability);
p->noncodeccapability = noncodeccapability & peernoncodeccapability;
if (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO) {
ast_clear_flag(p, SIP_DTMF);
if (p->noncodeccapability & AST_RTP_DTMF) {
/* XXX Would it be reasonable to drop the DSP at this point? XXX */
ast_set_flag(p, SIP_DTMF_RFC2833);
} else {
ast_set_flag(p, SIP_DTMF_INBAND);
}
}
if (debug) {
/* shame on whoever coded this.... */
const unsigned slen=512;
char s1[slen], s2[slen], s3[slen], s4[slen];
ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
ast_getformatname_multiple(s1, slen, p->capability),
ast_getformatname_multiple(s2, slen, peercapability),
ast_getformatname_multiple(s3, slen, vpeercapability),
ast_getformatname_multiple(s4, slen, p->jointcapability));
ast_verbose("Non-codec capabilities: us - %s, peer - %s, combined - %s\n",
ast_rtp_lookup_mime_multiple(s1, slen, noncodeccapability, 0),
ast_rtp_lookup_mime_multiple(s2, slen, peernoncodeccapability, 0),
ast_rtp_lookup_mime_multiple(s3, slen, p->noncodeccapability, 0));
}
if (!p->jointcapability) {
ast_log(LOG_NOTICE, "No compatible codecs!\n");
return -1;
}
if (!p->owner) /* There's no open channel owning us */
return 0;
if (!(p->owner->nativeformats & p->jointcapability)) {
const unsigned slen=512;
char s1[slen], s2[slen];
ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %s and not %s\n",
ast_getformatname_multiple(s1, slen, p->jointcapability),
ast_getformatname_multiple(s2, slen, p->owner->nativeformats));
p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1);
ast_set_read_format(p->owner, p->owner->readformat);
ast_set_write_format(p->owner, p->owner->writeformat);
}
if ((bridgepeer=ast_bridged_channel(p->owner))) {
/* We have a bridge */
/* Turn on/off music on hold if we are holding/unholding */
struct ast_frame af = { AST_FRAME_NULL, };
if (sin.sin_addr.s_addr && !sendonly) {
ast_moh_stop(bridgepeer);
/* Activate a re-invite */
ast_queue_frame(p->owner, &af);
} else {
/* No address for RTP, we're on hold */
ast_moh_start(bridgepeer, NULL);
if (sendonly)
ast_rtp_stop(p->rtp);
/* Activate a re-invite */
ast_queue_frame(p->owner, &af);
}
}
/* Manager Hold and Unhold events must be generated, if necessary */
if (sin.sin_addr.s_addr && !sendonly) {
append_history(p, "Unhold", req->data);
if (callevents && ast_test_flag(p, SIP_CALL_ONHOLD)) {
manager_event(EVENT_FLAG_CALL, "Unhold",
"Channel: %s\r\n"
"Uniqueid: %s\r\n",
p->owner->name,
p->owner->uniqueid);
}
ast_clear_flag(p, SIP_CALL_ONHOLD);
} else {
/* No address for RTP, we're on hold */
append_history(p, "Hold", req->data);
if (callevents && !ast_test_flag(p, SIP_CALL_ONHOLD)) {
manager_event(EVENT_FLAG_CALL, "Hold",
"Channel: %s\r\n"
"Uniqueid: %s\r\n",
p->owner->name,
p->owner->uniqueid);
}
ast_set_flag(p, SIP_CALL_ONHOLD);
}
return 0;
}
/*! \brief add_header: Add header to SIP message */
static int add_header(struct sip_request *req, const char *var, const char *value)
{
int x = 0;
if (req->headers == SIP_MAX_HEADERS) {
ast_log(LOG_WARNING, "Out of SIP header space\n");
return -1;
}
if (req->lines) {
ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
return -1;
}
if (req->len >= sizeof(req->data) - 4) {
ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
return -1;
}
req->header[req->headers] = req->data + req->len;
if (compactheaders) {
for (x = 0; x < (sizeof(aliases) / sizeof(aliases[0])); x++)
if (!strcasecmp(aliases[x].fullname, var))
var = aliases[x].shortname;
}
snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
req->len += strlen(req->header[req->headers]);
req->headers++;
return 0;
}
/*! \brief add_header_contentLen: Add 'Content-Length' header to SIP message */
static int add_header_contentLength(struct sip_request *req, int len)
{
char clen[10];
snprintf(clen, sizeof(clen), "%d", len);
return add_header(req, "Content-Length", clen);
}
/*! \brief add_blank_header: Add blank header to SIP message */
static int add_blank_header(struct sip_request *req)
{
if (req->headers == SIP_MAX_HEADERS) {
ast_log(LOG_WARNING, "Out of SIP header space\n");
return -1;
}
if (req->lines) {
ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
return -1;
}
if (req->len >= sizeof(req->data) - 4) {
ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
return -1;
}
req->header[req->headers] = req->data + req->len;
snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
req->len += strlen(req->header[req->headers]);
req->headers++;
return 0;
}
/*! \brief add_line: Add content (not header) to SIP message */
static int add_line(struct sip_request *req, const char *line)
{
if (req->lines == SIP_MAX_LINES) {
ast_log(LOG_WARNING, "Out of SIP line space\n");
return -1;
}
if (!req->lines) {
/* Add extra empty return */
snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
req->len += strlen(req->data + req->len);
}
if (req->len >= sizeof(req->data) - 4) {
ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
return -1;
}
req->line[req->lines] = req->data + req->len;
snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
req->len += strlen(req->line[req->lines]);
req->lines++;
return 0;
}
/*! \brief copy_header: Copy one header field from one request to another */
static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
{
char *tmp;
tmp = get_header(orig, field);
if (!ast_strlen_zero(tmp)) {
/* Add what we're responding to */
return add_header(req, field, tmp);
}
ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
return -1;
}
/*! \brief copy_all_header: Copy all headers from one request to another ---*/
static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
{
char *tmp;
int start = 0;
int copied = 0;
for (;;) {
tmp = __get_header(orig, field, &start);
if (!ast_strlen_zero(tmp)) {
/* Add what we're responding to */
add_header(req, field, tmp);
copied++;
} else
break;
}
return copied ? 0 : -1;
}
/*! \brief copy_via_headers: Copy SIP VIA Headers from the request to the response ---*/
/* If the client indicates that it wishes to know the port we received from,
it adds ;rport without an argument to the topmost via header. We need to
add the port number (from our point of view) to that parameter.
We always add ;received=<ip address> to the topmost via header.
Received: RFC 3261, rport RFC 3581 */
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
{
char tmp[256], *oh, *end;
int start = 0;
int copied = 0;
char iabuf[INET_ADDRSTRLEN];
for (;;) {
oh = __get_header(orig, field, &start);
if (!ast_strlen_zero(oh)) {
if (!copied) { /* Only check for empty rport in topmost via header */
char *rport;
char new[256];
/* Find ;rport; (empty request) */
rport = strstr(oh, ";rport");
if (rport && *(rport+6) == '=')
rport = NULL; /* We already have a parameter to rport */
if (rport && (ast_test_flag(p, SIP_NAT) == SIP_NAT_ALWAYS)) {
/* We need to add received port - rport */
ast_copy_string(tmp, oh, sizeof(tmp));
rport = strstr(tmp, ";rport");
if (rport) {
end = strchr(rport + 1, ';');
if (end)
memmove(rport, end, strlen(end) + 1);
else
*rport = '\0';
}
/* Add rport to first VIA header if requested */
/* Whoo hoo! Now we can indicate port address translation too! Just
another RFC (RFC3581). I'll leave the original comments in for
posterity. */
snprintf(new, sizeof(new), "%s;received=%s;rport=%d", tmp, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
} else {
/* We should *always* add a received to the topmost via */
snprintf(new, sizeof(new), "%s;received=%s", oh, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr));
}
add_header(req, field, new);
} else {
/* Add the following via headers untouched */
add_header(req, field, oh);
}
copied++;
} else
break;
}
if (!copied) {
ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
return -1;
}
return 0;
}
/*! \brief add_route: Add route header into request per learned route ---*/
static void add_route(struct sip_request *req, struct sip_route *route)
{
char r[BUFSIZ*2], *p;
int n, rem = sizeof(r);
if (!route) return;
p = r;
while (route) {
n = strlen(route->hop);
if ((n+3)>rem) break;
if (p != r) {
*p++ = ',';
--rem;
}
*p++ = '<';
ast_copy_string(p, route->hop, rem); p += n;
*p++ = '>';
rem -= (n+2);
route = route->next;
}
*p = '\0';
add_header(req, "Route", r);
}
/*! \brief set_destination: Set destination from SIP URI ---*/
static void set_destination(struct sip_pvt *p, char *uri)
{
char *h, *maddr, hostname[256];
char iabuf[INET_ADDRSTRLEN];
int port, hn;
struct hostent *hp;
struct ast_hostent ahp;
int debug=sip_debug_test_pvt(p);
/* Parse uri to h (host) and port - uri is already just the part inside the <> */
/* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
if (debug)
ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
/* Find and parse hostname */
h = strchr(uri, '@');
if (h)
++h;
else {
h = uri;
if (strncmp(h, "sip:", 4) == 0)
h += 4;
else if (strncmp(h, "sips:", 5) == 0)
h += 5;
}
hn = strcspn(h, ":;>") + 1;
if (hn > sizeof(hostname))
hn = sizeof(hostname);
ast_copy_string(hostname, h, hn);
h += hn - 1;
/* Is "port" present? if not default to DEFAULT_SIP_PORT */
if (*h == ':') {
/* Parse port */
++h;
port = strtol(h, &h, 10);
}
else
port = DEFAULT_SIP_PORT;
/* Got the hostname:port - but maybe there's a "maddr=" to override address? */
maddr = strstr(h, "maddr=");
if (maddr) {
maddr += 6;
hn = strspn(maddr, "0123456789.") + 1;
if (hn > sizeof(hostname)) hn = sizeof(hostname);
ast_copy_string(hostname, maddr, hn);
}
hp = ast_gethostbyname(hostname, &ahp);
if (hp == NULL) {
ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
return;
}
p->sa.sin_family = AF_INET;
memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
p->sa.sin_port = htons(port);
if (debug)
ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), port);
}
/*! \brief init_resp: Initialize SIP response, based on SIP request ---*/
static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
{
/* Initialize a response */
if (req->headers || req->len) {
ast_log(LOG_WARNING, "Request already initialized?!?\n");
return -1;
}
req->method = SIP_RESPONSE;
req->header[req->headers] = req->data + req->len;
snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
req->len += strlen(req->header[req->headers]);
req->headers++;
return 0;
}
/*! \brief init_req: Initialize SIP request ---*/
static int init_req(struct sip_request *req, int sipmethod, char *recip)
{
/* Initialize a response */
if (req->headers || req->len) {
ast_log(LOG_WARNING, "Request already initialized?!?\n");
return -1;
}
req->header[req->headers] = req->data + req->len;
snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
req->len += strlen(req->header[req->headers]);
req->headers++;
req->method = sipmethod;
return 0;
}
/*! \brief respprep: Prepare SIP response packet ---*/
static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
{
char newto[256], *ot;
memset(resp, 0, sizeof(*resp));
init_resp(resp, msg, req);
copy_via_headers(p, resp, req, "Via");
if (msg[0] == '2')
copy_all_header(resp, req, "Record-Route");
copy_header(resp, req, "From");
ot = get_header(req, "To");
if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
/* Add the proper tag if we don't have it already. If they have specified
their tag, use it. Otherwise, use our own tag */
if (!ast_strlen_zero(p->theirtag) && ast_test_flag(p, SIP_OUTGOING))
snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
else if (p->tag && !ast_test_flag(p, SIP_OUTGOING))
snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
else {
ast_copy_string(newto, ot, sizeof(newto));
newto[sizeof(newto) - 1] = '\0';
}
ot = newto;
}
add_header(resp, "To", ot);
copy_header(resp, req, "Call-ID");
copy_header(resp, req, "CSeq");
add_header(resp, "User-Agent", default_useragent);
add_header(resp, "Allow", ALLOWED_METHODS);
if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
/* For registration responses, we also need expiry and
contact info */
char tmp[256];
snprintf(tmp, sizeof(tmp), "%d", p->expiry);
add_header(resp, "Expires", tmp);
if (p->expiry) { /* Only add contact if we have an expiry time */
char contact[SIP_LEN_CONTACT];
snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
add_header(resp, "Contact", contact); /* Not when we unregister */
}
} else if (msg[0] != '4' && p->our_contact[0]) {
add_header(resp, "Contact", p->our_contact);
}
return 0;
}
/*! \brief reqprep: Initialize a SIP request response packet ---*/
static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
{
struct sip_request *orig = &p->initreq;
char stripped[80];
char tmp[80];
char newto[256];
char *c, *n;
char *ot, *of;
int is_strict = 0; /* Strict routing flag */
memset(req, 0, sizeof(struct sip_request));
snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
if (!seqno) {
p->ocseq++;
seqno = p->ocseq;
}
if (newbranch) {
p->branch ^= thread_safe_rand();
build_via(p, p->via, sizeof(p->via));
}
/* Check for strict or loose router */
if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop,";lr") == NULL)
is_strict = 1;
if (sipmethod == SIP_CANCEL) {
c = p->initreq.rlPart2; /* Use original URI */
} else if (sipmethod == SIP_ACK) {
/* Use URI from Contact: in 200 OK (if INVITE)
(we only have the contacturi on INVITEs) */
if (!ast_strlen_zero(p->okcontacturi))
c = is_strict ? p->route->hop : p->okcontacturi;
else
c = p->initreq.rlPart2;
} else if (!ast_strlen_zero(p->okcontacturi)) {
c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
} else if (!ast_strlen_zero(p->uri)) {
c = p->uri;
} else {
/* We have no URI, use To: or From: header as URI (depending on direction) */
c = get_header(orig, (ast_test_flag(p, SIP_OUTGOING)) ? "To" : "From");
ast_copy_string(stripped, c, sizeof(stripped));
c = get_in_brackets(stripped);
n = strchr(c, ';');
if (n)
*n = '\0';
}
init_req(req, sipmethod, c);
snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
add_header(req, "Via", p->via);
if (p->route) {
set_destination(p, p->route->hop);
if (is_strict)
add_route(req, p->route->next);
else
add_route(req, p->route);
}
ot = get_header(orig, "To");
of = get_header(orig, "From");
/* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
as our original request, including tag (or presumably lack thereof) */
if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
/* Add the proper tag if we don't have it already. If they have specified
their tag, use it. Otherwise, use our own tag */
if (ast_test_flag(p, SIP_OUTGOING) && !ast_strlen_zero(p->theirtag))
snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
else if (!ast_test_flag(p, SIP_OUTGOING))
snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
else
snprintf(newto, sizeof(newto), "%s", ot);
ot = newto;
}
if (ast_test_flag(p, SIP_OUTGOING)) {
add_header(req, "From", of);
add_header(req, "To", ot);
} else {
add_header(req, "From", ot);
add_header(req, "To", of);
}
add_header(req, "Contact", p->our_contact);
copy_header(req, orig, "Call-ID");
add_header(req, "CSeq", tmp);
add_header(req, "User-Agent", default_useragent);
add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
if (p->rpid)
add_header(req, "Remote-Party-ID", p->rpid);
return 0;
}
/*! \brief __transmit_response: Base transmit response function */
static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
{
struct sip_request resp;
int seqno = 0;
if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
return -1;
}
respprep(&resp, p, msg, req);
add_header_contentLength(&resp, 0);
/* If we are cancelling an incoming invite for some reason, add information
about the reason why we are doing this in clear text */
if (msg[0] != '1' && p->owner && p->owner->hangupcause) {
add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
}
add_blank_header(&resp);
return send_response(p, &resp, reliable, seqno);
}
/*! \brief transmit_response_using_temp: Transmit response, no retransmits, using temporary pvt */
static int transmit_response_using_temp(char *callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, struct sip_request *req, char *msg)
{
struct sip_pvt *p = alloca(sizeof(*p));
memset(p, 0, sizeof(*p));
p->method = intended_method;
if (sin) {
p->sa = *sin;
if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
p->ourip = __ourip;
} else
p->ourip = __ourip;
p->branch = thread_safe_rand();
make_our_tag(p->tag, sizeof(p->tag));
p->ocseq = 101;
if (useglobal_nat && sin) {
ast_copy_flags(p, &global_flags, SIP_NAT);
memcpy(&p->recv, sin, sizeof(p->recv));
}
ast_copy_string(p->fromdomain, default_fromdomain, sizeof(p->fromdomain));
build_via(p, p->via, sizeof(p->via));
ast_copy_string(p->callid, callid, sizeof(p->callid));
__transmit_response(p, msg, req, 0);
return 0;
}
/*! \brief transmit_response: Transmit response, no retransmits */
static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
{
return __transmit_response(p, msg, req, 0);
}
/*! \brief transmit_response_with_unsupported: Transmit response, no retransmits */
static int transmit_response_with_unsupported(struct sip_pvt *p, char *msg, struct sip_request *req, char *unsupported)
{
struct sip_request resp;
respprep(&resp, p, msg, req);
append_date(&resp);
add_header(&resp, "Unsupported", unsupported);
return send_response(p, &resp, 0, 0);
}
/*! \brief transmit_response_reliable: Transmit response, Make sure you get a reply */
static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal)
{
return __transmit_response(p, msg, req, fatal ? 2 : 1);
}
/*! \brief append_date: Append date to SIP message ---*/
static void append_date(struct sip_request *req)
{
char tmpdat[256];
struct tm tm;
time_t t;
time(&t);
gmtime_r(&t, &tm);
strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
add_header(req, "Date", tmpdat);
}
/*! \brief transmit_response_with_date: Append date and content length before transmitting response ---*/
static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
{
struct sip_request resp;
respprep(&resp, p, msg, req);
append_date(&resp);
add_header_contentLength(&resp, 0);
add_blank_header(&resp);
return send_response(p, &resp, 0, 0);
}
/*! \brief transmit_response_with_allow: Append Accept header, content length before transmitting response ---*/
static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
{
struct sip_request resp;
respprep(&resp, p, msg, req);
add_header(&resp, "Accept", "application/sdp");
add_header_contentLength(&resp, 0);
add_blank_header(&resp);
return send_response(p, &resp, reliable, 0);
}
/* transmit_response_with_auth: Respond with authorization request */
static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable, char *header, int stale)
{
struct sip_request resp;
char tmp[512];
int seqno = 0;
if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
return -1;
}
/* Stale means that they sent us correct authentication, but
based it on an old challenge (nonce) */
snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
respprep(&resp, p, msg, req);
add_header(&resp, header, tmp);
add_header_contentLength(&resp, 0);
add_blank_header(&resp);
return send_response(p, &resp, reliable, seqno);
}
/*! \brief add_text: Add text body to SIP message ---*/
static int add_text(struct sip_request *req, const char *text)
{
/* XXX Convert \n's to \r\n's XXX */
add_header(req, "Content-Type", "text/plain");
add_header_contentLength(req, strlen(text));
add_line(req, text);
return 0;
}
/*! \brief add_digit: add DTMF INFO tone to sip message ---*/
/* Always adds default duration 250 ms, regardless of what came in over the line */
static int add_digit(struct sip_request *req, char digit)
{
char tmp[256];
snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
add_header(req, "Content-Type", "application/dtmf-relay");
add_header_contentLength(req, strlen(tmp));
add_line(req, tmp);
return 0;
}
/*! \brief add_vidupdate: add XML encoded media control with update ---*/
/* XML: The only way to turn 0 bits of information into a few hundred. */
static int add_vidupdate(struct sip_request *req)
{
const char *xml_is_a_huge_waste_of_space =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
" <media_control>\r\n"
" <vc_primitive>\r\n"
" <to_encoder>\r\n"
" <picture_fast_update>\r\n"
" </picture_fast_update>\r\n"
" </to_encoder>\r\n"
" </vc_primitive>\r\n"
" </media_control>\r\n";
add_header(req, "Content-Type", "application/media_control+xml");
add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
add_line(req, xml_is_a_huge_waste_of_space);
return 0;
}
static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
int debug)
{
int rtp_code;
if (debug)
ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
return;
ast_build_string(m_buf, m_size, " %d", rtp_code);
ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
ast_rtp_lookup_mime_subtype(1, codec),
sample_rate);
if (codec == AST_FORMAT_G729A)
/* Indicate that we don't support VAD (G.729 annex B) */
ast_build_string(a_buf, a_size, "a=fmtp:%d annexb=no\r\n", rtp_code);
}
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
int debug)
{
int rtp_code;
if (debug)
ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format));
if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
return;
ast_build_string(m_buf, m_size, " %d", rtp_code);
ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
ast_rtp_lookup_mime_subtype(0, format),
sample_rate);
if (format == AST_RTP_DTMF)
/* Indicate we support DTMF and FLASH... */
ast_build_string(a_buf, a_size, "a=fmtp:%d 0-16\r\n", rtp_code);
}
/*! \brief add_sdp: Add Session Description Protocol message ---*/
static int add_sdp(struct sip_request *resp, struct sip_pvt *p)
{
int len = 0;
int pref_codec;
int alreadysent = 0;
struct sockaddr_in sin;
struct sockaddr_in vsin;
char v[256];
char s[256];
char o[256];
char c[256];
char t[256];
char m_audio[256];
char m_video[256];
char a_audio[1024];
char a_video[1024];
char *m_audio_next = m_audio;
char *m_video_next = m_video;
size_t m_audio_left = sizeof(m_audio);
size_t m_video_left = sizeof(m_video);
char *a_audio_next = a_audio;
char *a_video_next = a_video;
size_t a_audio_left = sizeof(a_audio);
size_t a_video_left = sizeof(a_video);
char iabuf[INET_ADDRSTRLEN];
int x;
int capability;
struct sockaddr_in dest;
struct sockaddr_in vdest = { 0, };
int debug;
debug = sip_debug_test_pvt(p);
len = 0;
if (!p->rtp) {
ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
return -1;
}
capability = p->jointcapability;
if (!p->sessionid) {
p->sessionid = getpid();
p->sessionversion = p->sessionid;
} else
p->sessionversion++;
ast_rtp_get_us(p->rtp, &sin);
if (p->vrtp)
ast_rtp_get_us(p->vrtp, &vsin);
if (p->redirip.sin_addr.s_addr) {
dest.sin_port = p->redirip.sin_port;
dest.sin_addr = p->redirip.sin_addr;
if (p->redircodecs)
capability = p->redircodecs;
} else {
dest.sin_addr = p->ourip;
dest.sin_port = sin.sin_port;
}
/* Determine video destination */
if (p->vrtp) {
if (p->vredirip.sin_addr.s_addr) {
vdest.sin_port = p->vredirip.sin_port;
vdest.sin_addr = p->vredirip.sin_addr;
} else {
vdest.sin_addr = p->ourip;
vdest.sin_port = vsin.sin_port;
}
}
if (debug){
ast_verbose("We're at %s port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ntohs(sin.sin_port));
if (p->vrtp)
ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ntohs(vsin.sin_port));
}
/* We break with the "recommendation" and send our IP, in order that our
peer doesn't have to ast_gethostbyname() us */
snprintf(v, sizeof(v), "v=0\r\n");
snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(iabuf, sizeof(iabuf), dest.sin_addr));
snprintf(s, sizeof(s), "s=session\r\n");
snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(iabuf, sizeof(iabuf), dest.sin_addr));
snprintf(t, sizeof(t), "t=0 0\r\n");
ast_build_string(&m_audio_next, &m_audio_left, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
ast_build_string(&m_video_next, &m_video_left, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
/* Prefer the codec we were requested to use, first, no matter what */
if (capability & p->prefcodec) {
if (p->prefcodec <= AST_FORMAT_MAX_AUDIO)
add_codec_to_sdp(p, p->prefcodec, 8000,
&m_audio_next, &m_audio_left,
&a_audio_next, &a_audio_left,
debug);
else
add_codec_to_sdp(p, p->prefcodec, 90000,
&m_video_next, &m_video_left,
&a_video_next, &a_video_left,
debug);
alreadysent |= p->prefcodec;
}
/* Start by sending our preferred codecs */
for (x = 0; x < 32; x++) {
if (!(pref_codec = ast_codec_pref_index(&p->prefs, x)))
break;
if (!(capability & pref_codec))
continue;
if (alreadysent & pref_codec)
continue;
if (pref_codec <= AST_FORMAT_MAX_AUDIO)
add_codec_to_sdp(p, pref_codec, 8000,
&m_audio_next, &m_audio_left,
&a_audio_next, &a_audio_left,
debug);
else
add_codec_to_sdp(p, pref_codec, 90000,
&m_video_next, &m_video_left,
&a_video_next, &a_video_left,
debug);
alreadysent |= pref_codec;
}
/* Now send any other common codecs, and non-codec formats: */
for (x = 1; x <= ((videosupport && p->vrtp) ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
if (!(capability & x))
continue;
if (alreadysent & x)
continue;
if (x <= AST_FORMAT_MAX_AUDIO)
add_codec_to_sdp(p, x, 8000,
&m_audio_next, &m_audio_left,
&a_audio_next, &a_audio_left,
debug);
else
add_codec_to_sdp(p, x, 90000,
&m_video_next, &m_video_left,
&a_video_next, &a_video_left,
debug);
}
for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
if (!(p->noncodeccapability & x))
continue;
add_noncodec_to_sdp(p, x, 8000,
&m_audio_next, &m_audio_left,
&a_audio_next, &a_audio_left,
debug);
}
ast_build_string(&a_audio_next, &a_audio_left, "a=silenceSupp:off - - - -\r\n");
if ((m_audio_left < 2) || (m_video_left < 2) || (a_audio_left == 0) || (a_video_left == 0))
ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
ast_build_string(&m_audio_next, &m_audio_left, "\r\n");
ast_build_string(&m_video_next, &m_video_left, "\r\n");
len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m_audio) + strlen(a_audio);
if ((p->vrtp) && (!ast_test_flag(p, SIP_NOVIDEO)) && (capability & VIDEO_CODEC_MASK)) /* only if video response is appropriate */
len += strlen(m_video) + strlen(a_video);
add_header(resp, "Content-Type", "application/sdp");
add_header_contentLength(resp, len);
add_line(resp, v);
add_line(resp, o);
add_line(resp, s);
add_line(resp, c);
add_line(resp, t);
add_line(resp, m_audio);
add_line(resp, a_audio);
if ((p->vrtp) && (!ast_test_flag(p, SIP_NOVIDEO)) && (capability & VIDEO_CODEC_MASK)) { /* only if video response is appropriate */
add_line(resp, m_video);
add_line(resp, a_video);
}
/* Update lastrtprx when we send our SDP */
time(&p->lastrtprx);
time(&p->lastrtptx);
return 0;
}
/*! \brief copy_request: copy SIP request (mostly used to save request for responses) ---*/
static void copy_request(struct sip_request *dst, struct sip_request *src)
{
long offset;
int x;
offset = ((void *)dst) - ((void *)src);
/* First copy stuff */
memcpy(dst, src, sizeof(*dst));
/* Now fix pointer arithmetic */
for (x=0; x < src->headers; x++)
dst->header[x] += offset;
for (x=0; x < src->lines; x++)
dst->line[x] += offset;
}
/*! \brief transmit_response_with_sdp: Used for 200 OK and 183 early media ---*/
static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
{
struct sip_request resp;
int seqno;
if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
return -1;
}
respprep(&resp, p, msg, req);
if (p->rtp) {
ast_rtp_offered_from_local(p->rtp, 0);
try_suggested_sip_codec(p);
add_sdp(&resp, p);
} else {
ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
}
return send_response(p, &resp, retrans, seqno);
}
/*! \brief determine_firstline_parts: parse first line of incoming SIP request */
static int determine_firstline_parts( struct sip_request *req )
{
char *e, *cmd;
int len;
cmd = ast_skip_blanks(req->header[0]);
if (!*cmd)
return -1;
req->rlPart1 = cmd;
e = ast_skip_nonblanks(cmd);
/* Get the command */
if (*e)
*e++ = '\0';
e = ast_skip_blanks(e);
if ( !*e )
return -1;
if ( !strcasecmp(cmd, "SIP/2.0") ) {
/* We have a response */
req->rlPart2 = e;
len = strlen( req->rlPart2 );
if ( len < 2 ) {
return -1;
}
ast_trim_blanks(e);
} else {
/* We have a request */
if ( *e == '<' ) {
e++;
if ( !*e ) {
return -1;
}
}
req->rlPart2 = e; /* URI */
if ( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
return -1;
}
/* XXX maybe trim_blanks() ? */
while( isspace( *(--e) ) ) {}
if ( *e == '>' ) {
*e = '\0';
} else {
*(++e)= '\0';
}
}
return 1;
}
/*! \brief transmit_reinvite_with_sdp: Transmit reinvite with SDP :-) ---*/
/* A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
INVITE that opened the SIP dialogue
We reinvite so that the audio stream (RTP) go directly between
the SIP UAs. SIP Signalling stays with * in the path.
*/
static int transmit_reinvite_with_sdp(struct sip_pvt *p)
{
struct sip_request req;
if (ast_test_flag(p, SIP_REINVITE_UPDATE))
reqprep(&req, p, SIP_UPDATE, 0, 1);
else
reqprep(&req, p, SIP_INVITE, 0, 1);
add_header(&req, "Allow", ALLOWED_METHODS);
if (sipdebug)
add_header(&req, "X-asterisk-info", "SIP re-invite (RTP bridge)");
ast_rtp_offered_from_local(p->rtp, 1);
add_sdp(&req, p);
/* Use this as the basis */
copy_request(&p->initreq, &req);
parse_request(&p->initreq);
if (sip_debug_test_pvt(p))
ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
p->lastinvite = p->ocseq;
ast_set_flag(p, SIP_OUTGOING);
return send_request(p, &req, 1, p->ocseq);
}
/*! \brief extract_uri: Check Contact: URI of SIP message ---*/
static void extract_uri(struct sip_pvt *p, struct sip_request *req)
{
char stripped[256];
char *c, *n;
ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
c = get_in_brackets(stripped);
n = strchr(c, ';');
if (n)
*n = '\0';
if (!ast_strlen_zero(c))
ast_copy_string(p->uri, c, sizeof(p->uri));
}
/*! \brief build_contact: Build contact header - the contact header we send out ---*/
static void build_contact(struct sip_pvt *p)
{
char iabuf[INET_ADDRSTRLEN];
/* Construct Contact: header */
if (ourport != 5060) /* Needs to be 5060, according to the RFC */
snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s%s%s:%d>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport);
else
snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip));
}
/*! \brief build_rpid: Build the Remote Party-ID & From using callingpres options ---*/
static void build_rpid(struct sip_pvt *p)
{
int send_pres_tags = 1;
const char *privacy = NULL;
const char *screen = NULL;
char buf[256];
const char *clid = default_callerid;
const char *clin = NULL;
char iabuf[INET_ADDRSTRLEN];
const char *fromdomain;
if (p->rpid || p->rpid_from)
return;
if (p->owner && p->owner->cid.cid_num)
clid = p->owner->cid.cid_num;
if (p->owner && p->owner->cid.cid_name)
clin = p->owner->cid.cid_name;
if (ast_strlen_zero(clin))
clin = clid;
switch (p->callingpres) {
case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
privacy = "off";
screen = "no";
break;
case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
privacy = "off";
screen = "yes";
break;
case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
privacy = "off";
screen = "no";
break;
case AST_PRES_ALLOWED_NETWORK_NUMBER:
privacy = "off";
screen = "yes";
break;
case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
privacy = "full";
screen = "no";
break;
case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
privacy = "full";
screen = "yes";
break;
case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
privacy = "full";
screen = "no";
break;
case AST_PRES_PROHIB_NETWORK_NUMBER:
privacy = "full";
screen = "yes";
break;
case AST_PRES_NUMBER_NOT_AVAILABLE:
send_pres_tags = 0;
break;
default:
ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
privacy = "full";
else
privacy = "off";
screen = "no";
break;
}
fromdomain = ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain;
snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
if (send_pres_tags)
snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
p->rpid = strdup(buf);
snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>;tag=%s", clin,
ast_strlen_zero(p->fromuser) ? clid : p->fromuser,
fromdomain, p->tag);
p->rpid_from = strdup(buf);
}
/*! \brief initreqprep: Initiate new SIP request to peer/user ---*/
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
{
char invite_buf[256] = "";
char *invite = invite_buf;
size_t invite_max = sizeof(invite_buf);
char from[256];
char to[256];
char tmp[BUFSIZ/2];
char tmp2[BUFSIZ/2];
char iabuf[INET_ADDRSTRLEN];
char *l = NULL, *n = NULL;
int x;
char urioptions[256]="";
if (ast_test_flag(p, SIP_USEREQPHONE)) {
char onlydigits = 1;
x=0;
/* Test p->username against allowed characters in AST_DIGIT_ANY
If it matches the allowed characters list, then sipuser = ";user=phone"
If not, then sipuser = ""
*/
/* + is allowed in first position in a tel: uri */
if (p->username && p->username[0] == '+')
x=1;
for (; x < strlen(p->username); x++) {
if (!strchr(AST_DIGIT_ANYNUM, p->username[x])) {
onlydigits = 0;
break;
}
}
/* If we have only digits, add ;user=phone to the uri */
if (onlydigits)
strcpy(urioptions, ";user=phone");
}
snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
if (p->owner) {
l = p->owner->cid.cid_num;
n = p->owner->cid.cid_name;
}
/* if we are not sending RPID and user wants his callerid restricted */
if (!ast_test_flag(p, SIP_SENDRPID) && ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
l = CALLERID_UNKNOWN;
n = l;
}
if (ast_strlen_zero(l))
l = default_callerid;
if (ast_strlen_zero(n))
n = l;
/* Allow user to be overridden */
if (!ast_strlen_zero(p->fromuser))
l = p->fromuser;
else /* Save for any further attempts */
ast_copy_string(p->fromuser, l, sizeof(p->fromuser));
/* Allow user to be overridden */
if (!ast_strlen_zero(p->fromname))
n = p->fromname;
else /* Save for any further attempts */
ast_copy_string(p->fromname, n, sizeof(p->fromname));
if (pedanticsipchecking) {
ast_uri_encode(n, tmp, sizeof(tmp), 0);
n = tmp;
ast_uri_encode(l, tmp2, sizeof(tmp2), 0);
l = tmp2;
}
if ((ourport != 5060) && ast_strlen_zero(p->fromdomain)) /* Needs to be 5060 */
snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain, ourport, p->tag);
else
snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain, p->tag);
/* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
if (!ast_strlen_zero(p->fullcontact)) {
/* If we have full contact, trust it */
ast_build_string(&invite, &invite_max, "%s", p->fullcontact);
} else {
/* Otherwise, use the username while waiting for registration */
ast_build_string(&invite, &invite_max, "sip:");
if (!ast_strlen_zero(p->username)) {
n = p->username;
if (pedanticsipchecking) {
ast_uri_encode(n, tmp, sizeof(tmp), 0);
n = tmp;
}
ast_build_string(&invite, &invite_max, "%s@", n);
}
ast_build_string(&invite, &invite_max, "%s", p->tohost);
if (ntohs(p->sa.sin_port) != 5060) /* Needs to be 5060 */
ast_build_string(&invite, &invite_max, ":%d", ntohs(p->sa.sin_port));
ast_build_string(&invite, &invite_max, "%s", urioptions);
}
/* If custom URI options have been provided, append them */
if (p->options && p->options->uri_options)
ast_build_string(&invite, &invite_max, ";%s", p->options->uri_options);
ast_copy_string(p->uri, invite_buf, sizeof(p->uri));
if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
/* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
snprintf(to, sizeof(to), "<sip:%s>;tag=%s", p->uri, p->theirtag);
} else if (p->options && p->options->vxml_url) {
/* If there is a VXML URL append it to the SIP URL */
snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
} else {
snprintf(to, sizeof(to), "<%s>", p->uri);
}
memset(req, 0, sizeof(struct sip_request));
init_req(req, sipmethod, p->uri);
snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
add_header(req, "Via", p->via);
/* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
* OTOH, then we won't have anything in p->route anyway */
/* Build Remote Party-ID and From */
if (ast_test_flag(p, SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
build_rpid(p);
add_header(req, "From", p->rpid_from);
} else {
add_header(req, "From", from);
}
add_header(req, "To", to);
ast_copy_string(p->exten, l, sizeof(p->exten));
build_contact(p);
add_header(req, "Contact", p->our_contact);
add_header(req, "Call-ID", p->callid);
add_header(req, "CSeq", tmp);
add_header(req, "User-Agent", default_useragent);
add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
if (p->rpid)
add_header(req, "Remote-Party-ID", p->rpid);
}
/*! \brief transmit_invite: Build REFER/INVITE/OPTIONS message and transmit it ---*/
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
{
struct sip_request req;
req.method = sipmethod;
if (init) {
/* Bump branch even on initial requests */
p->branch ^= thread_safe_rand();
build_via(p, p->via, sizeof(p->via));
if (init > 1)
initreqprep(&req, p, sipmethod);
else
reqprep(&req, p, sipmethod, 0, 1);
} else
reqprep(&req, p, sipmethod, 0, 1);
if (p->options && p->options->auth)
add_header(&req, p->options->authheader, p->options->auth);
append_date(&req);
if (sipmethod == SIP_REFER) { /* Call transfer */
if (!ast_strlen_zero(p->refer_to))
add_header(&req, "Refer-To", p->refer_to);
if (!ast_strlen_zero(p->referred_by))
add_header(&req, "Referred-By", p->referred_by);
}
#ifdef OSP_SUPPORT
if ((req.method != SIP_OPTIONS) && p->options && !ast_strlen_zero(p->options->osptoken)) {
ast_log(LOG_DEBUG,"Adding OSP Token: %s\n", p->options->osptoken);
add_header(&req, "P-OSP-Auth-Token", p->options->osptoken);
}
#endif
if (p->options && !ast_strlen_zero(p->options->distinctive_ring))
{
add_header(&req, "Alert-Info", p->options->distinctive_ring);
}
add_header(&req, "Allow", ALLOWED_METHODS);
if (p->options && p->options->addsipheaders ) {
struct ast_channel *ast;
char *header = (char *) NULL;
char *content = (char *) NULL;
char *end = (char *) NULL;
struct varshead *headp = (struct varshead *) NULL;
struct ast_var_t *current;
ast = p->owner; /* The owner channel */
if (ast) {
char *headdup;
headp = &ast->varshead;
if (!headp)
ast_log(LOG_WARNING,"No Headp for the channel...ooops!\n");
else {
AST_LIST_TRAVERSE(headp, current, entries) {
/* SIPADDHEADER: Add SIP header to outgoing call */
if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
header = ast_var_value(current);
headdup = ast_strdupa(header);
/* Strip of the starting " (if it's there) */
if (*headdup == '"')
headdup++;
if ((content = strchr(headdup, ':'))) {
*content = '\0';
content++; /* Move pointer ahead */
/* Skip white space */
while (*content == ' ')
content++;
/* Strip the ending " (if it's there) */
end = content + strlen(content) -1;
if (*end == '"')
*end = '\0';
add_header(&req, headdup, content);
if (sipdebug)
ast_log(LOG_DEBUG, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
}
}
}
}
}
}
if (sdp && p->rtp) {
ast_rtp_offered_from_local(p->rtp, 1);
add_sdp(&req, p);
} else {
add_header_contentLength(&req, 0);
add_blank_header(&req);
}
if (!p->initreq.headers) {
/* Use this as the basis */
copy_request(&p->initreq, &req);
parse_request(&p->initreq);
if (sip_debug_test_pvt(p))
ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
}
p->lastinvite = p->ocseq;
return send_request(p, &req, init ? 2 : 1, p->ocseq);
}
/*! \brief transmit_state_notify: Used in the SUBSCRIBE notification subsystem ----*/
static int transmit_state_notify(struct sip_pvt *p, int state, int full, int substate)
{
char tmp[4000], from[256], to[256];
char *t = tmp, *c, *a, *mfrom, *mto;
size_t maxbytes = sizeof(tmp);
struct sip_request req;
char hint[AST_MAX_EXTENSION];
char *statestring = "terminated";
const struct cfsubscription_types *subscriptiontype;
enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
char *pidfstate = "--";
char *pidfnote= "Ready";
memset(from, 0, sizeof(from));
memset(to, 0, sizeof(to));
memset(tmp, 0, sizeof(tmp));
switch (state) {
case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
if (global_notifyringing)
statestring = "early";
else
statestring = "confirmed";
local_state = NOTIFY_INUSE;
pidfstate = "busy";
pidfnote = "Ringing";
break;
case AST_EXTENSION_RINGING:
statestring = "early";
local_state = NOTIFY_INUSE;
pidfstate = "busy";
pidfnote = "Ringing";
break;
case AST_EXTENSION_INUSE:
statestring = "confirmed";
local_state = NOTIFY_INUSE;
pidfstate = "busy";
pidfnote = "On the phone";
break;
case AST_EXTENSION_BUSY:
statestring = "confirmed";
local_state = NOTIFY_CLOSED;
pidfstate = "busy";
pidfnote = "On the phone";
break;
case AST_EXTENSION_UNAVAILABLE:
statestring = "confirmed";
local_state = NOTIFY_CLOSED;
pidfstate = "away";
pidfnote = "Unavailable";
break;
case AST_EXTENSION_NOT_INUSE:
default:
/* Default setting */
break;
}
subscriptiontype = find_subscription_type(p->subscribed);
/* Check which device/devices we are watching and if they are registered */
if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
/* If they are not registered, we will override notification and show no availability */
if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
local_state = NOTIFY_CLOSED;
pidfstate = "away";
pidfnote = "Not online";
}
}
ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
c = get_in_brackets(from);
if (strncmp(c, "sip:", 4)) {
ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
return -1;
}
if ((a = strchr(c, ';')))
*a = '\0';
mfrom = c;
ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
c = get_in_brackets(to);
if (strncmp(c, "sip:", 4)) {
ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
return -1;
}
if ((a = strchr(c, ';')))
*a = '\0';
mto = c;
reqprep(&req, p, SIP_NOTIFY, 0, 1);
add_header(&req, "Event", subscriptiontype->event);
add_header(&req, "Content-Type", subscriptiontype->mediatype);
switch(state) {
case AST_EXTENSION_DEACTIVATED:
if (p->subscribed == TIMEOUT)
add_header(&req, "Subscription-State", "terminated;reason=timeout");
else {
add_header(&req, "Subscription-State", "terminated;reason=probation");
add_header(&req, "Retry-After", "60");
}
break;
case AST_EXTENSION_REMOVED:
add_header(&req, "Subscription-State", "terminated;reason=noresource");
break;
break;
default:
if (p->expiry)
add_header(&req, "Subscription-State", "active");
else /* Expired */
add_header(&req, "Subscription-State", "terminated;reason=timeout");
}
switch (p->subscribed) {
case XPIDF_XML:
case CPIM_PIDF_XML:
ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
ast_build_string(&t, &maxbytes, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
ast_build_string(&t, &maxbytes, "<presence>\n");
ast_build_string(&t, &maxbytes, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
ast_build_string(&t, &maxbytes, "<atom id=\"%s\">\n", p->exten);
ast_build_string(&t, &maxbytes, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
ast_build_string(&t, &maxbytes, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
ast_build_string(&t, &maxbytes, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
ast_build_string(&t, &maxbytes, "</address>\n</atom>\n</presence>\n");
break;
case PIDF_XML: /* Eyebeam supports this format */
ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
ast_build_string(&t, &maxbytes, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" \nxmlns:pp=\"urn:ietf:params:xml:ns:pidf:person\"\nxmlns:es=\"urn:ietf:params:xml:ns:pidf:rpid:status:rpid-status\"\nxmlns:ep=\"urn:ietf:params:xml:ns:pidf:rpid:rpid-person\"\nentity=\"%s\">\n", mfrom);
ast_build_string(&t, &maxbytes, "<pp:person><status>\n");
if (pidfstate[0] != '-')
ast_build_string(&t, &maxbytes, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
ast_build_string(&t, &maxbytes, "</status></pp:person>\n");
ast_build_string(&t, &maxbytes, "<note>%s</note>\n", pidfnote); /* Note */
ast_build_string(&t, &maxbytes, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
ast_build_string(&t, &maxbytes, "<contact priority=\"1\">%s</contact>\n", mto);
if (pidfstate[0] == 'b') /* Busy? Still open ... */
ast_build_string(&t, &maxbytes, "<status><basic>open</basic></status>\n");
else
ast_build_string(&t, &maxbytes, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
ast_build_string(&t, &maxbytes, "</tuple>\n</presence>\n");
break;
case DIALOG_INFO_XML: /* SNOM subscribes in this format */
ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
ast_build_string(&t, &maxbytes, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full":"partial", mto);
if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
ast_build_string(&t, &maxbytes, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
else
ast_build_string(&t, &maxbytes, "<dialog id=\"%s\">\n", p->exten);
ast_build_string(&t, &maxbytes, "<state>%s</state>\n", statestring);
ast_build_string(&t, &maxbytes, "</dialog>\n</dialog-info>\n");
break;
case NONE:
default:
break;
}
if (t > tmp + sizeof(tmp))
ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
add_header_contentLength(&req, strlen(tmp));
add_line(&req, tmp);
return send_request(p, &req, 1, p->ocseq);
}
/*! \brief transmit_notify_with_mwi: Notify user of messages waiting in voicemail ---*/
/* Notification only works for registered peers with mailbox= definitions
* in sip.conf
* We use the SIP Event package message-summary
* MIME type defaults to "application/simple-message-summary";
*/
static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
{
struct sip_request req;
char tmp[500];
char *t = tmp;
size_t maxbytes = sizeof(tmp);
char iabuf[INET_ADDRSTRLEN];
initreqprep(&req, p, SIP_NOTIFY);
add_header(&req, "Event", "message-summary");
add_header(&req, "Content-Type", default_notifymime);
ast_build_string(&t, &maxbytes, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
ast_build_string(&t, &maxbytes, "Message-Account: sip:%s@%s\r\n", !ast_strlen_zero(vmexten) ? vmexten : global_vmexten, ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain);
ast_build_string(&t, &maxbytes, "Voice-Message: %d/%d (0/0)\r\n", newmsgs, oldmsgs);
if (t > tmp + sizeof(tmp))
ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
add_header_contentLength(&req, strlen(tmp));
add_line(&req, tmp);
if (!p->initreq.headers) { /* Use this as the basis */
copy_request(&p->initreq, &req);
parse_request(&p->initreq);
if (sip_debug_test_pvt(p))
ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
determine_firstline_parts(&p->initreq);
}
return send_request(p, &req, 1, p->ocseq);
}
/*! \brief transmit_sip_request: Transmit SIP request */
static int transmit_sip_request(struct sip_pvt *p,struct sip_request *req)
{
if (!p->initreq.headers) {
/* Use this as the basis */
copy_request(&p->initreq, req);
parse_request(&p->initreq);
if (sip_debug_test_pvt(p))
ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
determine_firstline_parts(&p->initreq);
}
return send_request(p, req, 0, p->ocseq);
}
/*! \brief transmit_notify_with_sipfrag: Notify a transferring party of the status of trasnfer ---*/
/* Apparently the draft SIP REFER structure was too simple, so it was decided that the
* status of transfers also needed to be sent via NOTIFY instead of just the 202 Accepted
* that had worked heretofore.
*/
static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq)
{
struct sip_request req;
char tmp[20];
reqprep(&req, p, SIP_NOTIFY, 0, 1);
snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
add_header(&req, "Event", tmp);
add_header(&req, "Subscription-state", "terminated;reason=noresource");
add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
strcpy(tmp, "SIP/2.0 200 OK");
add_header_contentLength(&req, strlen(tmp));
add_line(&req, tmp);
if (!p->initreq.headers) {
/* Use this as the basis */
copy_request(&p->initreq, &req);
parse_request(&p->initreq);
if (sip_debug_test_pvt(p))
ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
determine_firstline_parts(&p->initreq);
}
return send_request(p, &req, 1, p->ocseq);
}
static char *regstate2str(int regstate)
{
switch(regstate) {
case REG_STATE_FAILED:
return "Failed";
case REG_STATE_UNREGISTERED:
return "Unregistered";
case REG_STATE_REGSENT:
return "Request Sent";
case REG_STATE_AUTHSENT:
return "Auth. Sent";
case REG_STATE_REGISTERED:
return "Registered";
case REG_STATE_REJECTED:
return "Rejected";
case REG_STATE_TIMEOUT:
return "Timeout";
case REG_STATE_NOAUTH:
return "No Authentication";
default:
return "Unknown";
}
}
static int transmit_register(struct sip_registry *r, int sipmethod, char *auth, char *authheader);
/*! \brief sip_reregister: Update registration with SIP Proxy---*/
static int sip_reregister(void *data)
{
/* if we are here, we know that we need to reregister. */
struct sip_registry *r= ASTOBJ_REF((struct sip_registry *) data);
/* if we couldn't get a reference to the registry object, punt */
if (!r)
return 0;
if (r->call && recordhistory) {
char tmp[80];
snprintf(tmp, sizeof(tmp), "Account: %s@%s", r->username, r->hostname);
append_history(r->call, "RegistryRenew", tmp);
}
/* Since registry's are only added/removed by the the monitor thread, this
may be overkill to reference/dereference at all here */
if (sipdebug)
ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
r->expire = -1;
__sip_do_register(r);
ASTOBJ_UNREF(r, sip_registry_destroy);
return 0;
}
/*! \brief __sip_do_register: Register with SIP proxy ---*/
static int __sip_do_register(struct sip_registry *r)
{
int res;
res = transmit_register(r, SIP_REGISTER, NULL, NULL);
return res;
}
/*! \brief sip_reg_timeout: Registration timeout, register again */
static int sip_reg_timeout(void *data)
{
/* if we are here, our registration timed out, so we'll just do it over */
struct sip_registry *r = ASTOBJ_REF((struct sip_registry *) data);
struct sip_pvt *p;
int res;
/* if we couldn't get a reference to the registry object, punt */
if (!r)
return 0;
ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
if (r->call) {
/* Unlink us, destroy old call. Locking is not relevant here because all this happens
in the single SIP manager thread. */
p = r->call;
if (p->registry)
ASTOBJ_UNREF(p->registry, sip_registry_destroy);
r->call = NULL;
ast_set_flag(p, SIP_NEEDDESTROY);
/* Pretend to ACK anything just in case */
__sip_pretend_ack(p);
}
/* If we have a limit, stop registration and give up */
if (global_regattempts_max && (r->regattempts > global_regattempts_max)) {
/* Ok, enough is enough. Don't try any more */
/* We could add an external notification here...
steal it from app_voicemail :-) */
ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
r->regstate=REG_STATE_FAILED;
} else {
r->regstate=REG_STATE_UNREGISTERED;
r->timeout = -1;
res=transmit_register(r, SIP_REGISTER, NULL, NULL);
}
manager_event(EVENT_FLAG_SYSTEM, "Registry", "Channel: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
ASTOBJ_UNREF(r,sip_registry_destroy);
return 0;
}
/*! \brief transmit_register: Transmit register to SIP proxy or UA ---*/
static int transmit_register(struct sip_registry *r, int sipmethod, char *auth, char *authheader)
{
struct sip_request req;
char from[256];
char to[256];
char tmp[80];
char via[80];
char addr[80];
struct sip_pvt *p;
/* exit if we are already in process with this registrar ?*/
if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
return 0;
}
if (r->call) { /* We have a registration */
if (!auth) {
ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
return 0;
} else {
p = r->call;
make_our_tag(p->tag, sizeof(p->tag)); /* create a new local tag for every register attempt */
p->theirtag[0]='\0'; /* forget their old tag, so we don't match tags when getting response */
}
} else {
/* Build callid for registration if we haven't registered before */
if (!r->callid_valid) {
build_callid(r->callid, sizeof(r->callid), __ourip, default_fromdomain);
r->callid_valid = 1;
}
/* Allocate SIP packet for registration */
p=sip_alloc( r->callid, NULL, 0, SIP_REGISTER);
if (!p) {
ast_log(LOG_WARNING, "Unable to allocate registration call\n");
return 0;
}
if (recordhistory) {
char tmp[80];
snprintf(tmp, sizeof(tmp), "Account: %s@%s", r->username, r->hostname);
append_history(p, "RegistryInit", tmp);
}
/* Find address to hostname */
if (create_addr(p, r->hostname)) {
/* we have what we hope is a temporary network error,
* probably DNS. We need to reschedule a registration try */
sip_destroy(p);
if (r->timeout > -1) {
ast_sched_del(sched, r->timeout);
r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
} else {
r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
ast_log(LOG_WARNING, "Probably a DNS error for registration to %s@%s, trying REGISTER again (after %d seconds)\n", r->username, r->hostname, global_reg_timeout);
}
r->regattempts++;
return 0;
}
/* Copy back Call-ID in case create_addr changed it */
ast_copy_string(r->callid, p->callid, sizeof(r->callid));
if (r->portno)
p->sa.sin_port = htons(r->portno);
else /* Set registry port to the port set from the peer definition/srv or default */
r->portno = ntohs(p->sa.sin_port);
ast_set_flag(p, SIP_OUTGOING); /* Registration is outgoing call */
r->call=p; /* Save pointer to SIP packet */
p->registry=ASTOBJ_REF(r); /* Add pointer to registry in packet */
if (!ast_strlen_zero(r->secret)) /* Secret (password) */
ast_copy_string(p->peersecret, r->secret, sizeof(p->peersecret));
if (!ast_strlen_zero(r->md5secret))
ast_copy_string(p->peermd5secret, r->md5secret, sizeof(p->peermd5secret));
/* User name in this realm
- if authuser is set, use that, otherwise use username */
if (!ast_strlen_zero(r->authuser)) {
ast_copy_string(p->peername, r->authuser, sizeof(p->peername));
ast_copy_string(p->authname, r->authuser, sizeof(p->authname));
} else {
if (!ast_strlen_zero(r->username)) {
ast_copy_string(p->peername, r->username, sizeof(p->peername));
ast_copy_string(p->authname, r->username, sizeof(p->authname));
ast_copy_string(p->fromuser, r->username, sizeof(p->fromuser));
}
}
if (!ast_strlen_zero(r->username))
ast_copy_string(p->username, r->username, sizeof(p->username));
/* Save extension in packet */
ast_copy_string(p->exten, r->contact, sizeof(p->exten));
/*
check which address we should use in our contact header
based on whether the remote host is on the external or
internal network so we can register through nat
*/
if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
memcpy(&p->ourip, &bindaddr.sin_addr, sizeof(p->ourip));
build_contact(p);
}
/* set up a timeout */
if (auth == NULL) {
if (r->timeout > -1) {
ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
ast_sched_del(sched, r->timeout);
}
r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
ast_log(LOG_DEBUG, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
}
if (strchr(r->username, '@')) {
snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
if (!ast_strlen_zero(p->theirtag))
snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
else
snprintf(to, sizeof(to), "<sip:%s>", r->username);
} else {
snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
if (!ast_strlen_zero(p->theirtag))
snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
else
snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
}
/* Fromdomain is what we are registering to, regardless of actual
host name from SRV */
if (!ast_strlen_zero(p->fromdomain))
snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
else
snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
ast_copy_string(p->uri, addr, sizeof(p->uri));
p->branch ^= thread_safe_rand();
memset(&req, 0, sizeof(req));
init_req(&req, sipmethod, addr);
/* Add to CSEQ */
snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
p->ocseq = r->ocseq;
build_via(p, via, sizeof(via));
add_header(&req, "Via", via);
add_header(&req, "From", from);
add_header(&req, "To", to);
add_header(&req, "Call-ID", p->callid);
add_header(&req, "CSeq", tmp);
add_header(&req, "User-Agent", default_useragent);
add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
if (auth) /* Add auth header */
add_header(&req, authheader, auth);
else if (!ast_strlen_zero(r->nonce)) {
char digest[1024];
/* We have auth data to reuse, build a digest header! */
if (sipdebug)
ast_log(LOG_DEBUG, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
ast_copy_string(p->realm, r->realm, sizeof(p->realm));
ast_copy_string(p->nonce, r->nonce, sizeof(p->nonce));
ast_copy_string(p->domain, r->domain, sizeof(p->domain));
ast_copy_string(p->opaque, r->opaque, sizeof(p->opaque));
ast_copy_string(p->qop, r->qop, sizeof(p->qop));
p->noncecount = r->noncecount++;
memset(digest,0,sizeof(digest));
if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
add_header(&req, "Authorization", digest);
else
ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
}
snprintf(tmp, sizeof(tmp), "%d", default_expiry);
add_header(&req, "Expires", tmp);
add_header(&req, "Contact", p->our_contact);
add_header(&req, "Event", "registration");
add_header_contentLength(&req, 0);
add_blank_header(&req);
copy_request(&p->initreq, &req);
parse_request(&p->initreq);
if (sip_debug_test_pvt(p)) {
ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
}
determine_firstline_parts(&p->initreq);
r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
r->regattempts++; /* Another attempt */
if (option_debug > 3)
ast_verbose("REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
return send_request(p, &req, 2, p->ocseq);
}
/*! \brief transmit_message_with_text: Transmit text with SIP MESSAGE method ---*/
static int transmit_message_with_text(struct sip_pvt *p, const char *text)
{
struct sip_request req;
reqprep(&req, p, SIP_MESSAGE, 0, 1);
add_text(&req, text);
return send_request(p, &req, 1, p->ocseq);
}
/*! \brief transmit_refer: Transmit SIP REFER message ---*/
static int transmit_refer(struct sip_pvt *p, const char *dest)
{
struct sip_request req;
char from[256];
char *of, *c;
char referto[256];
if (ast_test_flag(p, SIP_OUTGOING))
of = get_header(&p->initreq, "To");
else
of = get_header(&p->initreq, "From");
ast_copy_string(from, of, sizeof(from));
of = get_in_brackets(from);
ast_copy_string(p->from,of,sizeof(p->from));
if (strncmp(of, "sip:", 4)) {
ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
} else
of += 4;
/* Get just the username part */
if ((c = strchr(dest, '@'))) {
c = NULL;
} else if ((c = strchr(of, '@'))) {
*c = '\0';
c++;
}
if (c) {
snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
} else {
snprintf(referto, sizeof(referto), "<sip:%s>", dest);
}
/* save in case we get 407 challenge */
ast_copy_string(p->refer_to, referto, sizeof(p->refer_to));
ast_copy_string(p->referred_by, p->our_contact, sizeof(p->referred_by));
reqprep(&req, p, SIP_REFER, 0, 1);
add_header(&req, "Refer-To", referto);
if (!ast_strlen_zero(p->our_contact))
add_header(&req, "Referred-By", p->our_contact);
add_blank_header(&req);
return send_request(p, &req, 1, p->ocseq);
}
/*! \brief transmit_info_with_digit: Send SIP INFO dtmf message, see Cisco documentation on cisco.co
m ---*/
static int transmit_info_with_digit(struct sip_pvt *p, char digit)
{
struct sip_request req;
reqprep(&req, p, SIP_INFO, 0, 1);
add_digit(&req, digit);
return send_request(p, &req, 1, p->ocseq);
}
/*! \brief transmit_info_with_vidupdate: Send SIP INFO with video update request ---*/
static int transmit_info_with_vidupdate(struct sip_pvt *p)
{
struct sip_request req;
reqprep(&req, p, SIP_INFO, 0, 1);
add_vidupdate(&req);
return send_request(p, &req, 1, p->ocseq);
}
/*! \brief transmit_request: transmit generic SIP request ---*/
static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, int reliable, int newbranch)
{
struct sip_request resp;
reqprep(&resp, p, sipmethod, seqno, newbranch);
add_header_contentLength(&resp, 0);
add_blank_header(&resp);
return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
}
/*! \brief transmit_request_with_auth: Transmit SIP request, auth added ---*/
static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, int reliable, int newbranch)
{
struct sip_request resp;
reqprep(&resp, p, sipmethod, seqno, newbranch);
if (*p->realm) {
char digest[1024];
memset(digest, 0, sizeof(digest));
if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
if (p->options && p->options->auth_type == PROXY_AUTH)
add_header(&resp, "Proxy-Authorization", digest);
else if (p->options && p->options->auth_type == WWW_AUTH)
add_header(&resp, "Authorization", digest);
else /* Default, to be backwards compatible (maybe being too careful, but leaving it for now) */
add_header(&resp, "Proxy-Authorization", digest);
} else
ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
}
/* If we are hanging up and know a cause for that, send it in clear text to make
debugging easier. */
if (sipmethod == SIP_BYE) {
if (p->owner && p->owner->hangupcause) {
add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
}
}
add_header_contentLength(&resp, 0);
add_blank_header(&resp);
return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
}
static void destroy_association(struct sip_peer *peer)
{
if (!ast_test_flag((&global_flags_page2), SIP_PAGE2_IGNOREREGEXPIRE)) {
if (ast_test_flag(&(peer->flags_page2), SIP_PAGE2_RT_FROMCONTACT)) {
ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", NULL);
} else {
ast_db_del("SIP/Registry", peer->name);
}
}
}
/*! \brief expire_register: Expire registration of SIP peer ---*/
static int expire_register(void *data)
{
struct sip_peer *peer = data;
if (!peer) /* Hmmm. We have no peer. Weird. */
return 0;
memset(&peer->addr, 0, sizeof(peer->addr));
destroy_association(peer);
manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
register_peer_exten(peer, 0); /* Remove regexten */
peer->expire = -1;
ast_device_state_changed("SIP/%s", peer->name);
/* Do we need to release this peer from memory?
Only for realtime peers and autocreated peers
*/
if (ast_test_flag(peer, SIP_SELFDESTRUCT) || ast_test_flag((&peer->flags_page2), SIP_PAGE2_RTAUTOCLEAR)) {
peer = ASTOBJ_CONTAINER_UNLINK(&peerl, peer); /* Remove from peer list */
ASTOBJ_UNREF(peer, sip_destroy_peer);
}
return 0;
}
static int sip_poke_peer(struct sip_peer *peer);
static int sip_poke_peer_s(void *data)
{
struct sip_peer *peer = data;
peer->pokeexpire = -1;
sip_poke_peer(peer);
return 0;
}
/*! \brief reg_source_db: Get registration details from Asterisk DB ---*/
static void reg_source_db(struct sip_peer *peer)
{
char data[256];
char iabuf[INET_ADDRSTRLEN];
struct in_addr in;
int expiry;
int port;
char *scan, *addr, *port_str, *expiry_str, *username, *contact;
if (ast_test_flag(&(peer->flags_page2), SIP_PAGE2_RT_FROMCONTACT))
return;
if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
return;
scan = data;
addr = strsep(&scan, ":");
port_str = strsep(&scan, ":");
expiry_str = strsep(&scan, ":");
username = strsep(&scan, ":");
contact = scan; /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
if (!inet_aton(addr, &in))
return;
if (port_str)
port = atoi(port_str);
else
return;
if (expiry_str)
expiry = atoi(expiry_str);
else
return;
if (username)
ast_copy_string(peer->username, username, sizeof(peer->username));
if (contact)
ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
if (option_verbose > 2)
ast_verbose(VERBOSE_PREFIX_3 "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
peer->name, peer->username, ast_inet_ntoa(iabuf, sizeof(iabuf), in), port, expiry);
memset(&peer->addr, 0, sizeof(peer->addr));
peer->addr.sin_family = AF_INET;
peer->addr.sin_addr = in;
peer->addr.sin_port = htons(port);
if (sipsock < 0) {
/* SIP isn't up yet, so schedule a poke only, pretty soon */
if (peer->pokeexpire > -1)
ast_sched_del(sched, peer->pokeexpire);
peer->pokeexpire = ast_sched_add(sched, thread_safe_rand() % 5000 + 1, sip_poke_peer_s, peer);
} else
sip_poke_peer(peer);
if (peer->expire > -1)
ast_sched_del(sched, peer->expire);
peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
register_peer_exten(peer, 1);
}
/*! \brief parse_ok_contact: Parse contact header for 200 OK on INVITE ---*/
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
{
char contact[SIP_LEN_CONTACT];
char *c, *n, *pt;
int port;
struct hostent *hp;
struct ast_hostent ahp;
struct sockaddr_in oldsin;
/* Look for brackets */
ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
c = get_in_brackets(contact);
/* Save full contact to call pvt for later bye or re-invite */
ast_copy_string(pvt->fullcontact, c, sizeof(pvt->fullcontact));
/* Save URI for later ACKs, BYE or RE-invites */
ast_copy_string(pvt->okcontacturi, c, sizeof(pvt->okcontacturi));
/* Make sure it's a SIP URL */
if (strncasecmp(c, "sip:", 4)) {
ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
} else
c += 4;
/* Ditch arguments */
n = strchr(c, ';');
if (n)
*n = '\0';
/* Grab host */
n = strchr(c, '@');
if (!n) {
n = c;
c = NULL;
} else {
*n = '\0';
n++;
}
pt = strchr(n, ':');
if (pt) {
*pt = '\0';
pt++;
port = atoi(pt);
} else
port = DEFAULT_SIP_PORT;
memcpy(&oldsin, &pvt->sa, sizeof(oldsin));
if (!(ast_test_flag(pvt, SIP_NAT) & SIP_NAT_ROUTE)) {
/* XXX This could block for a long time XXX */
/* We should only do this if it's a name, not an IP */
hp = ast_gethostbyname(n, &ahp);
if (!hp) {
ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
return -1;
}
pvt->sa.sin_family = AF_INET;
memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
pvt->sa.sin_port = htons(port);
} else {
/* Don't trust the contact field. Just use what they came to us
with. */
memcpy(&pvt->sa, &pvt->recv, sizeof(pvt->sa));
}
return 0;
}
enum parse_register_result {
PARSE_REGISTER_FAILED,
PARSE_REGISTER_UPDATE,
PARSE_REGISTER_QUERY,
};
/*! \brief parse_register_contact: Parse contact header and save registration ---*/
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
{
char contact[BUFSIZ];
char data[BUFSIZ];
char iabuf[INET_ADDRSTRLEN];
char *expires = get_header(req, "Expires");
int expiry = atoi(expires);
char *c, *n, *pt;
int port;
char *useragent;
struct hostent *hp;
struct ast_hostent ahp;
struct sockaddr_in oldsin;
if (ast_strlen_zero(expires)) { /* No expires header */
expires = strcasestr(get_header(req, "Contact"), ";expires=");
if (expires) {
char *ptr;
if ((ptr = strchr(expires, ';')))
*ptr = '\0';
if (sscanf(expires + 9, "%d", &expiry) != 1)
expiry = default_expiry;
} else {
/* Nothing has been specified */
expiry = default_expiry;
}
}
/* Look for brackets */
ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
if (strchr(contact, '<') == NULL) { /* No <, check for ; and strip it */
char *ptr = strchr(contact, ';'); /* This is Header options, not URI options */
if (ptr)
*ptr = '\0';
}
c = get_in_brackets(contact);
/* if they did not specify Contact: or Expires:, they are querying
what we currently have stored as their contact address, so return
it
*/
if (ast_strlen_zero(c) && ast_strlen_zero(expires)) {
/* If we have an active registration, tell them when the registration is going to expire */
if ((p->expire > -1) && !ast_strlen_zero(p->fullcontact)) {
pvt->expiry = ast_sched_when(sched, p->expire);
}
return PARSE_REGISTER_QUERY;
} else if (!strcasecmp(c, "*") || !expiry) { /* Unregister this peer */
/* This means remove all registrations and return OK */
memset(&p->addr, 0, sizeof(p->addr));
if (p->expire > -1)
ast_sched_del(sched, p->expire);
p->expire = -1;
destroy_association(p);
register_peer_exten(p, 0);
p->fullcontact[0] = '\0';
p->useragent[0] = '\0';
p->sipoptions = 0;
p->lastms = 0;
if (option_verbose > 2)
ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->name);
manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", p->name);
return PARSE_REGISTER_UPDATE;
}
ast_copy_string(p->fullcontact, c, sizeof(p->fullcontact));
/* For the 200 OK, we should use the received contact */
snprintf(pvt->our_contact, sizeof(pvt->our_contact) - 1, "<%s>", c);
/* Make sure it's a SIP URL */
if (strncasecmp(c, "sip:", 4)) {
ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
} else
c += 4;
/* Ditch q */
n = strchr(c, ';');
if (n) {
*n = '\0';
}
/* Grab host */
n = strchr(c, '@');
if (!n) {
n = c;
c = NULL;
} else {
*n = '\0';
n++;
}
pt = strchr(n, ':');
if (pt) {
*pt = '\0';
pt++;
port = atoi(pt);
} else
port = DEFAULT_SIP_PORT;
memcpy(&oldsin, &p->addr, sizeof(oldsin));
if (!(ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)) {
/* XXX This could block for a long time XXX */
hp = ast_gethostbyname(n, &ahp);
if (!hp) {
ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
return PARSE_REGISTER_FAILED;
}
p->addr.sin_family = AF_INET;
memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
p->addr.sin_port = htons(port);
} else {
/* Don't trust the contact field. Just use what they came to us
with */
memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
}
if (c) /* Overwrite the default username from config at registration */
ast_copy_string(p->username, c, sizeof(p->username));
else
p->username[0] = '\0';
if (p->expire > -1)
ast_sched_del(sched, p->expire);
if ((expiry < 1) || (expiry > max_expiry))
expiry = max_expiry;
if (!ast_test_flag(p, SIP_REALTIME))
p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, p);
else
p->expire = -1;
pvt->expiry = expiry;
snprintf(data, sizeof(data), "%s:%d:%d:%s:%s", ast_inet_ntoa(iabuf, sizeof(iabuf), p->addr.sin_addr), ntohs(p->addr.sin_port), expiry, p->username, p->fullcontact);
if (!ast_test_flag((&p->flags_page2), SIP_PAGE2_RT_FROMCONTACT))
ast_db_put("SIP/Registry", p->name, data);
manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", p->name);
if (inaddrcmp(&p->addr, &oldsin)) {
sip_poke_peer(p);
if (option_verbose > 2)
ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d expires %d\n", p->name, ast_inet_ntoa(iabuf, sizeof(iabuf), p->addr.sin_addr), ntohs(p->addr.sin_port), expiry);
register_peer_exten(p, 1);
}
/* Save SIP options profile */
p->sipoptions = pvt->sipoptions;
/* Save User agent */
useragent = get_header(req, "User-Agent");
if (useragent && strcasecmp(useragent, p->useragent)) {
ast_copy_string(p->useragent, useragent, sizeof(p->useragent));
if (option_verbose > 3) {
ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n",p->useragent,p->name);
}
}
return PARSE_REGISTER_UPDATE;
}
/*! \brief free_old_route: Remove route from route list ---*/
static void free_old_route(struct sip_route *route)
{
struct sip_route *next;
while (route) {
next = route->next;
free(route);
route = next;
}
}
/*! \brief list_route: List all routes - mostly for debugging ---*/
static void list_route(struct sip_route *route)
{
if (!route) {
ast_verbose("list_route: no route\n");
return;
}
while (route) {
ast_verbose("list_route: hop: <%s>\n", route->hop);
route = route->next;
}
}
/*! \brief build_route: Build route list from Record-Route header ---*/
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
{
struct sip_route *thishop, *head, *tail;
int start = 0;
int len;
char *rr, *contact, *c;
/* Once a persistant route is set, don't fool with it */
if (p->route && p->route_persistant) {
ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop);
return;
}
if (p->route) {
free_old_route(p->route);
p->route = NULL;
}
p->route_persistant = backwards;
/* We build up head, then assign it to p->route when we're done */
head = NULL; tail = head;
/* 1st we pass through all the hops in any Record-Route headers */
for (;;) {
/* Each Record-Route header */
rr = __get_header(req, "Record-Route", &start);
if (*rr == '\0') break;
for (;;) {
/* Each route entry */
/* Find < */
rr = strchr(rr, '<');
if (!rr) break; /* No more hops */
++rr;
len = strcspn(rr, ">") + 1;
/* Make a struct route */
thishop = malloc(sizeof(*thishop) + len);
if (thishop) {
ast_copy_string(thishop->hop, rr, len);
ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
/* Link in */
if (backwards) {
/* Link in at head so they end up in reverse order */
thishop->next = head;
head = thishop;
/* If this was the first then it'll be the tail */
if (!tail) tail = thishop;
} else {
thishop->next = NULL;
/* Link in at the end */
if (tail)
tail->next = thishop;
else
head = thishop;
tail = thishop;
}
}
rr += len;
}
}
/* Only append the contact if we are dealing with a strict router */
if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop,";lr") == NULL) ) {
/* 2nd append the Contact: if there is one */
/* Can be multiple Contact headers, comma separated values - we just take the first */
contact = get_header(req, "Contact");
if (!ast_strlen_zero(contact)) {
ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
/* Look for <: delimited address */
c = strchr(contact, '<');
if (c) {
/* Take to > */
++c;
len = strcspn(c, ">") + 1;
} else {
/* No <> - just take the lot */
c = contact;
len = strlen(contact) + 1;
}
thishop = malloc(sizeof(*thishop) + len);
if (thishop) {
ast_copy_string(thishop->hop, c, len);
thishop->next = NULL;
/* Goes at the end */
if (tail)
tail->next = thishop;
else
head = thishop;
}
}
}
/* Store as new route */
p->route = head;
/* For debugging dump what we ended up with */
if (sip_debug_test_pvt(p))
list_route(p->route);
}
#ifdef OSP_SUPPORT
/*! \brief check_osptoken: Validate OSP token for user authrroization ---*/
static int check_osptoken (struct sip_pvt *p, char *token)
{
char tmp[80];
if (ast_osp_validate (NULL, token, &p->osphandle, &p->osptimelimit, p->cid_num, p->sa.sin_addr, p->exten) < 1) {
return (-1);
} else {
snprintf (tmp, sizeof (tmp), "%d", p->osphandle);
pbx_builtin_setvar_helper (p->owner, "_OSPHANDLE", tmp);
return (0);
}
}
#endif
/*! \brief check_auth: Check user authorization from peer definition ---*/
/* Some actions, like REGISTER and INVITEs from peers require
authentication (if peer have secret set) */
static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *md5secret, int sipmethod, char *uri, int reliable, int ignore)
{
int res = -1;
char *response = "407 Proxy Authentication Required";
char *reqheader = "Proxy-Authorization";
char *respheader = "Proxy-Authenticate";
char *authtoken;
#ifdef OSP_SUPPORT
char *osptoken;
#endif
/* Always OK if no secret */
if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret)
#ifdef OSP_SUPPORT
&& !ast_test_flag(p, SIP_OSPAUTH)
&& global_allowguest != 2
#endif
)
return 0;
if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
/* On a REGISTER, we have to use 401 and its family of headers instead of 407 and its family
of headers -- GO SIP! Whoo hoo! Two things that do the same thing but are used in
different circumstances! What a surprise. */
response = "401 Unauthorized";
reqheader = "Authorization";
respheader = "WWW-Authenticate";
}
#ifdef OSP_SUPPORT
else {
ast_log (LOG_DEBUG, "Checking OSP Authentication!\n");
osptoken = get_header (req, "P-OSP-Auth-Token");
switch (ast_test_flag (p, SIP_OSPAUTH)) {
case SIP_OSPAUTH_NO:
break;
case SIP_OSPAUTH_GATEWAY:
if (ast_strlen_zero (osptoken)) {
if (ast_strlen_zero (secret) && ast_strlen_zero (md5secret)) {
return (0);
}
}
else {
return (check_osptoken (p, osptoken));
}
break;
case SIP_OSPAUTH_PROXY:
if (ast_strlen_zero (osptoken)) {
return (0);
}
else {
return (check_osptoken (p, osptoken));
}
break;
case SIP_OSPAUTH_EXCLUSIVE:
if (ast_strlen_zero (osptoken)) {
return (-1);
}
else {
return (check_osptoken (p, osptoken));
}
break;
default:
return (-1);
}
}
#endif
authtoken = get_header(req, reqheader);
if (ignore && !ast_strlen_zero(randdata) && ast_strlen_zero(authtoken)) {
/* This is a retransmitted invite/register/etc, don't reconstruct authentication
information */
if (!ast_strlen_zero(randdata)) {
if (!reliable) {
/* Resend message if this was NOT a reliable delivery. Otherwise the
retransmission should get it */
transmit_response_with_auth(p, response, req, randdata, reliable, respheader, 0);
/* Schedule auto destroy in 15 seconds */
sip_scheddestroy(p, 15000);
}
res = 1;
}
} else if (ast_strlen_zero(randdata) || ast_strlen_zero(authtoken)) {
snprintf(randdata, randlen, "%08x", thread_safe_rand());
transmit_response_with_auth(p, response, req, randdata, reliable, respheader, 0);
/* Schedule auto destroy in 15 seconds */
sip_scheddestroy(p, 15000);
res = 1;
} else {
/* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
an example in the spec of just what it is you're doing a hash on. */
char a1[256];
char a2[256];
char a1_hash[256];
char a2_hash[256];
char resp[256];
char resp_hash[256]="";
char tmp[256];
char *c;
char *z;
char *ua_hash ="";
char *resp_uri ="";
char *nonce = "";
char *digestusername = "";
int wrongnonce = 0;
char *usednonce = randdata;
/* Find their response among the mess that we'r sent for comparison */
ast_copy_string(tmp, authtoken, sizeof(tmp));
c = tmp;
while(c) {
c = ast_skip_blanks(c);
if (!*c)
break;
if (!strncasecmp(c, "response=", strlen("response="))) {
c+= strlen("response=");
if ((*c == '\"')) {
ua_hash=++c;
if ((c = strchr(c,'\"')))
*c = '\0';
} else {
ua_hash=c;
if ((c = strchr(c,',')))
*c = '\0';
}
} else if (!strncasecmp(c, "uri=", strlen("uri="))) {
c+= strlen("uri=");
if ((*c == '\"')) {
resp_uri=++c;
if ((c = strchr(c,'\"')))
*c = '\0';
} else {
resp_uri=c;
if ((c = strchr(c,',')))
*c = '\0';
}
} else if (!strncasecmp(c, "username=", strlen("username="))) {
c+= strlen("username=");
if ((*c == '\"')) {
digestusername=++c;
if((c = strchr(c,'\"')))
*c = '\0';
} else {
digestusername=c;
if((c = strchr(c,',')))
*c = '\0';
}
} else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
c+= strlen("nonce=");
if ((*c == '\"')) {
nonce=++c;
if ((c = strchr(c,'\"')))
*c = '\0';
} else {
nonce=c;
if ((c = strchr(c,',')))
*c = '\0';
}
} else
if ((z = strchr(c,' ')) || (z = strchr(c,','))) c=z;
if (c)
c++;
}
/* Verify that digest username matches the username we auth as */
if (strcmp(username, digestusername)) {
/* Oops, we're trying something here */
return -2;
}
/* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
if (strncasecmp(randdata, nonce, randlen)) {
wrongnonce = 1;
usednonce = nonce;
}
snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
if (!ast_strlen_zero(resp_uri))
snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text, resp_uri);
else
snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text, uri);
if (!ast_strlen_zero(md5secret))
snprintf(a1_hash, sizeof(a1_hash), "%s", md5secret);
else
ast_md5_hash(a1_hash, a1);
ast_md5_hash(a2_hash, a2);
snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
ast_md5_hash(resp_hash, resp);
if (wrongnonce) {
snprintf(randdata, randlen, "%08x", thread_safe_rand());
if (ua_hash && !strncasecmp(ua_hash, resp_hash, strlen(resp_hash))) {
if (sipdebug)
ast_log(LOG_NOTICE, "stale nonce received from '%s'\n", get_header(req, "To"));
/* We got working auth token, based on stale nonce . */
transmit_response_with_auth(p, response, req, randdata, reliable, respheader, 1);
} else {
/* Everything was wrong, so give the device one more try with a new challenge */
if (sipdebug)
ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
transmit_response_with_auth(p, response, req, randdata, reliable, respheader, 0);
}
/* Schedule auto destroy in 15 seconds */
sip_scheddestroy(p, 15000);
return 1;
}
/* resp_hash now has the expected response, compare the two */
if (ua_hash && !strncasecmp(ua_hash, resp_hash, strlen(resp_hash))) {
/* Auth is OK */
res = 0;
}
}
/* Failure */
return res;
}
/*! \brief cb_extensionstate: Callback for the devicestate notification (SUBSCRIBE) support subsystem ---*/
/* If you add an "hint" priority to the extension in the dial plan,
you will get notifications on device state changes */
static int cb_extensionstate(char *context, char* exten, int state, void *data)
{
struct sip_pvt *p = data;
switch(state) {
case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
case AST_EXTENSION_REMOVED: /* Extension is gone */
if (p->autokillid > -1)
sip_cancel_destroy(p); /* Remove subscription expiry for renewals */
sip_scheddestroy(p, 15000); /* Delete subscription in 15 secs */
ast_verbose(VERBOSE_PREFIX_2 "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
p->stateid = -1;
p->subscribed = NONE;
append_history(p, "Subscribestatus", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
break;
default: /* Tell user */
p->laststate = state;
break;
}
transmit_state_notify(p, state, 1, 1);
if (option_verbose > 1)
ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %s for Notify User %s\n", exten, ast_extension_state2str(state), p->username);
return 0;
}
/*! \brief Send a fake 401 Unauthorized response when the administrator
wants to hide the names of local users/peers from fishers
*/
static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, int reliable)
{
snprintf(randdata, randlen, "%08x", thread_safe_rand());
transmit_response_with_auth(p, "401 Unauthorized", req, randdata, reliable, "WWW-Authenticate", 0);
}
/*! \brief register_verify: Verify registration of user */
static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri, int ignore)
{
int res = -3;
struct sip_peer *peer;
char tmp[256];
char iabuf[INET_ADDRSTRLEN];
char *name, *c;
char *t;
char *domain;
/* Terminate URI */
t = uri;
while(*t && (*t > 32) && (*t != ';'))
t++;
*t = '\0';
ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
if (pedanticsipchecking)
ast_uri_decode(tmp);
c = get_in_brackets(tmp);
/* Ditch ;user=phone */
name = strchr(c, ';');
if (name)
*name = '\0';
if (!strncmp(c, "sip:", 4)) {
name = c + 4;
} else {
name = c;
ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
}
/* Strip off the domain name */
if ((c = strchr(name, '@'))) {
*c++ = '\0';
domain = c;
if ((c = strchr(domain, ':'))) /* Remove :port */
*c = '\0';
if (!AST_LIST_EMPTY(&domain_list)) {
if (!check_sip_domain(domain, NULL, 0)) {
transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
return -3;
}
}
}
ast_copy_string(p->exten, name, sizeof(p->exten));
build_contact(p);
peer = find_peer(name, NULL, 1);
if (!(peer && ast_apply_ha(peer->ha, sin))) {
if (peer)
ASTOBJ_UNREF(peer,sip_destroy_peer);
}
if (peer) {
if (!ast_test_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC)) {
ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
} else {
ast_copy_flags(p, peer, SIP_NAT);
transmit_response(p, "100 Trying", req);
if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, 0, ignore))) {
sip_cancel_destroy(p);
switch (parse_register_contact(p, peer, req)) {
case PARSE_REGISTER_FAILED:
ast_log(LOG_WARNING, "Failed to parse contact info\n");
transmit_response_with_date(p, "400 Bad Request", req);
peer->lastmsgssent = -1;
res = 0;
break;
case PARSE_REGISTER_QUERY:
transmit_response_with_date(p, "200 OK", req);
peer->lastmsgssent = -1;
res = 0;
break;
case PARSE_REGISTER_UPDATE:
update_peer(peer, p->expiry);
/* Say OK and ask subsystem to retransmit msg counter */
transmit_response_with_date(p, "200 OK", req);
peer->lastmsgssent = -1;
res = 0;
break;
}
}
}
}
if (!peer && autocreatepeer) {
/* Create peer if we have autocreate mode enabled */
peer = temp_peer(name);
if (peer) {
ASTOBJ_CONTAINER_LINK(&peerl, peer);
sip_cancel_destroy(p);
switch (parse_register_contact(p, peer, req)) {
case PARSE_REGISTER_FAILED:
ast_log(LOG_WARNING, "Failed to parse contact info\n");
transmit_response_with_date(p, "400 Bad Request", req);
peer->lastmsgssent = -1;
res = 0;
break;
case PARSE_REGISTER_QUERY:
transmit_response_with_date(p, "200 OK", req);
peer->lastmsgssent = -1;
res = 0;
break;
case PARSE_REGISTER_UPDATE:
/* Say OK and ask subsystem to retransmit msg counter */
transmit_response_with_date(p, "200 OK", req);
manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
peer->lastmsgssent = -1;
res = 0;
break;
}
}
}
if (!res) {
ast_device_state_changed("SIP/%s", peer->name);
}
if (res < 0) {
switch (res) {
case -1:
/* Wrong password in authentication. Go away, don't try again until you fixed it */
transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
break;
case -2:
/* Username and digest username does not match.
Asterisk uses the From: username for authentication. We need the
users to use the same authentication user name until we support
proper authentication by digest auth name */
transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
break;
case -3:
if (global_alwaysauthreject) {
transmit_fake_auth_response(p, &p->initreq, p->randdata, sizeof(p->randdata), 1);
} else {
/* URI not found */
transmit_response(p, "404 Not found", &p->initreq);
}
/* Set res back to -2 because we don't want to return an invalid domain message. That check already happened up above. */
res = -2;
break;
}
if (option_debug > 1) {
ast_log(LOG_DEBUG, "SIP REGISTER attempt failed for %s : %s\n",
peer->name,
(res == -1) ? "Bad password" : ((res == -2 ) ? "Bad digest user" : "Peer not found"));
}
}
if (peer)
ASTOBJ_UNREF(peer,sip_destroy_peer);
return res;
}
/*! \brief get_rdnis: get referring dnis ---*/
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
{
char tmp[256], *c, *a;
struct sip_request *req;
req = oreq;
if (!req)
req = &p->initreq;
ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
if (ast_strlen_zero(tmp))
return 0;
c = get_in_brackets(tmp);
if (strncmp(c, "sip:", 4)) {
ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
return -1;
}
c += 4;
if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
*a = '\0';
}
if (sip_debug_test_pvt(p))
ast_verbose("RDNIS is %s\n", c);
ast_copy_string(p->rdnis, c, sizeof(p->rdnis));
return 0;
}
/*! \brief get_destination: Find out who the call is for --*/
static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
{
char tmp[256] = "", *uri, *a, *user, *domain, *opts;
char tmpf[256], *from;
struct sip_request *req;
char *colon;
req = oreq;
if (!req)
req = &p->initreq;
if (req->rlPart2)
ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
uri = get_in_brackets(tmp);
ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
from = get_in_brackets(tmpf);
if (strncmp(uri, "sip:", 4)) {
ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
return -1;
}
uri += 4;
if (!ast_strlen_zero(from)) {
if (strncmp(from, "sip:", 4)) {
ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
return -1;
}
from += 4;
} else
from = NULL;
if (pedanticsipchecking) {
ast_uri_decode(uri);
ast_uri_decode(from);
}
/* Get the target domain first and user */
if ((domain = strchr(uri, '@'))) {
*domain++ = '\0';
user = uri;
} else {
/* No user portion present */
domain = uri;
user = "s";
}
/* Strip port from domain if present */
if ((colon = strchr(domain, ':'))) {
*colon = '\0';
}
/* Strip any params or options from user */
if ((opts = strchr(user, ';'))) {
*opts = '\0';
}
ast_copy_string(p->domain, domain, sizeof(p->domain));
if (!AST_LIST_EMPTY(&domain_list)) {
char domain_context[AST_MAX_EXTENSION];
domain_context[0] = '\0';
if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
ast_log(LOG_DEBUG, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
return -2;
}
}
/* If we have a context defined, overwrite the original context */
if (!ast_strlen_zero(domain_context))
ast_copy_string(p->context, domain_context, sizeof(p->context));
}
if (from) {
if ((a = strchr(from, ';')))
*a = '\0';
if ((a = strchr(from, '@'))) {
*a = '\0';
ast_copy_string(p->fromdomain, a + 1, sizeof(p->fromdomain));
} else
ast_copy_string(p->fromdomain, from, sizeof(p->fromdomain));
}
if (sip_debug_test_pvt(p))
ast_verbose("Looking for %s in %s (domain %s)\n", user, p->context, p->domain);
/* Return 0 if we have a matching extension */
if (ast_exists_extension(NULL, p->context, user, 1, from) ||
!strcmp(uri, ast_pickup_ext())) {
if (!oreq)
ast_copy_string(p->exten, user, sizeof(p->exten));
return 0;
}
/* Return 1 for overlap dialling support */
if (ast_canmatch_extension(NULL, p->context, user, 1, from) ||
!strncmp(user, ast_pickup_ext(),strlen(user))) {
return 1;
}
return -1;
}
/*! \brief get_sip_pvt_byid_locked: Lock interface lock and find matching pvt lock ---*/
static struct sip_pvt *get_sip_pvt_byid_locked(char *callid)
{
struct sip_pvt *sip_pvt_ptr = NULL;
/* Search interfaces and find the match */
ast_mutex_lock(&iflock);
sip_pvt_ptr = iflist;
while(sip_pvt_ptr) {
if (!strcmp(sip_pvt_ptr->callid, callid)) {
/* Go ahead and lock it (and its owner) before returning */
ast_mutex_lock(&sip_pvt_ptr->lock);
if (sip_pvt_ptr->owner) {
while(ast_mutex_trylock(&sip_pvt_ptr->owner->lock)) {
ast_mutex_unlock(&sip_pvt_ptr->lock);
usleep(1);
ast_mutex_lock(&sip_pvt_ptr->lock);
if (!sip_pvt_ptr->owner)
break;
}
}
break;
}
sip_pvt_ptr = sip_pvt_ptr->next;
}
ast_mutex_unlock(&iflock);
return sip_pvt_ptr;
}
/*! \brief get_refer_info: Call transfer support (the REFER method) ---*/
static int get_refer_info(struct sip_pvt *sip_pvt, struct sip_request *outgoing_req, char **transfercontext)
{
char *p_refer_to = NULL, *p_referred_by = NULL, *h_refer_to = NULL, *h_referred_by = NULL, *h_contact = NULL;
char *replace_callid = "", *refer_to = NULL, *referred_by = NULL, *ptr = NULL;
struct sip_request *req = NULL;
struct sip_pvt *sip_pvt_ptr = NULL;
struct ast_channel *chan = NULL, *peer = NULL;
req = outgoing_req;
if (!req) {
req = &sip_pvt->initreq;
}
if (!( (p_refer_to = get_header(req, "Refer-To")) && (h_refer_to = ast_strdupa(p_refer_to)) )) {
ast_log(LOG_WARNING, "No Refer-To Header That's illegal\n");
return -1;
}
refer_to = get_in_brackets(h_refer_to);
if (!( (p_referred_by = get_header(req, "Referred-By")) && (h_referred_by = ast_strdupa(p_referred_by)) )) {
ast_log(LOG_WARNING, "No Referrred-By Header That's not illegal\n");
return -1;
} else {
if (pedanticsipchecking) {
ast_uri_decode(h_referred_by);
}
referred_by = get_in_brackets(h_referred_by);
}
h_contact = get_header(req, "Contact");
if (strncmp(refer_to, "sip:", 4)) {
ast_log(LOG_WARNING, "Refer-to: Huh? Not a SIP header (%s)?\n", refer_to);
return -1;
}
if (strncmp(referred_by, "sip:", 4)) {
ast_log(LOG_WARNING, "Referred-by: Huh? Not a SIP header (%s) Ignoring?\n", referred_by);
referred_by = NULL;
}
if (refer_to)
refer_to += 4;
if (referred_by)
referred_by += 4;
if ((ptr = strchr(refer_to, '?'))) {
/* Search for arguments */
*ptr = '\0';
ptr++;
if (!strncasecmp(ptr, "REPLACES=", 9)) {
char *p;
replace_callid = ast_strdupa(ptr + 9);
/* someday soon to support invite/replaces properly!
replaces_header = ast_strdupa(replace_callid);
-anthm
*/
ast_uri_decode(replace_callid);
if ((ptr = strchr(replace_callid, '%')))
*ptr = '\0';
if ((ptr = strchr(replace_callid, ';')))
*ptr = '\0';
/* Skip leading whitespace XXX memmove behaviour with overlaps ? */
p = ast_skip_blanks(replace_callid);
if (p != replace_callid)
memmove(replace_callid, p, strlen(p));
}
}
if ((ptr = strchr(refer_to, '@'))) /* Skip domain (should be saved in SIPDOMAIN) */
*ptr = '\0';
if ((ptr = strchr(refer_to, ';')))
*ptr = '\0';
if (referred_by) {
if ((ptr = strchr(referred_by, '@')))
*ptr = '\0';
if ((ptr = strchr(referred_by, ';')))
*ptr = '\0';
}
*transfercontext = pbx_builtin_getvar_helper(sip_pvt->owner, "TRANSFER_CONTEXT");
if (ast_strlen_zero(*transfercontext))
*transfercontext = sip_pvt->context;
if (sip_debug_test_pvt(sip_pvt)) {
ast_verbose("Transfer to %s in %s\n", refer_to, *transfercontext);
if (referred_by)
ast_verbose("Transfer from %s in %s\n", referred_by, sip_pvt->context);
}
if (!ast_strlen_zero(replace_callid)) {
/* This is a supervised transfer */
ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",replace_callid);
ast_copy_string(sip_pvt->refer_to, "", sizeof(sip_pvt->refer_to));
ast_copy_string(sip_pvt->referred_by, "", sizeof(sip_pvt->referred_by));
ast_copy_string(sip_pvt->refer_contact, "", sizeof(sip_pvt->refer_contact));
sip_pvt->refer_call = NULL;
if ((sip_pvt_ptr = get_sip_pvt_byid_locked(replace_callid))) {
sip_pvt->refer_call = sip_pvt_ptr;
if (sip_pvt->refer_call == sip_pvt) {
ast_log(LOG_NOTICE, "Supervised transfer attempted to transfer into same call id (%s == %s)!\n", replace_callid, sip_pvt->callid);
sip_pvt->refer_call = NULL;
} else
return 0;
} else {
ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'. Both legs must reside on Asterisk box to transfer at this time.\n", replace_callid);
/* XXX The refer_to could contain a call on an entirely different machine, requiring an
INVITE with a replaces header -anthm XXX */
/* The only way to find out is to use the dialplan - oej */
}
} else if (ast_exists_extension(NULL, *transfercontext, refer_to, 1, NULL) || !strcmp(refer_to, ast_parking_ext())) {
/* This is an unsupervised transfer (blind transfer) */
ast_log(LOG_DEBUG,"Unsupervised transfer to (Refer-To): %s\n", refer_to);
if (referred_by)
ast_log(LOG_DEBUG,"Transferred by (Referred-by: ) %s \n", referred_by);
ast_log(LOG_DEBUG,"Transfer Contact Info %s (REFER_CONTACT)\n", h_contact);
ast_copy_string(sip_pvt->refer_to, refer_to, sizeof(sip_pvt->refer_to));
if (referred_by)
ast_copy_string(sip_pvt->referred_by, referred_by, sizeof(sip_pvt->referred_by));
if (h_contact) {
ast_copy_string(sip_pvt->refer_contact, h_contact, sizeof(sip_pvt->refer_contact));
}
sip_pvt->refer_call = NULL;
if ((chan = sip_pvt->owner) && (peer = ast_bridged_channel(sip_pvt->owner))) {
pbx_builtin_setvar_helper(chan, "BLINDTRANSFER", peer->name);
pbx_builtin_setvar_helper(peer, "BLINDTRANSFER", chan->name);
}
return 0;
} else if (ast_canmatch_extension(NULL, *transfercontext, refer_to, 1, NULL)) {
return 1;
}
return -1;
}
/*! \brief get_also_info: Call transfer support (old way, depreciated)--*/
static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
{
char tmp[256], *c, *a;
struct sip_request *req;
req = oreq;
if (!req)
req = &p->initreq;
ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
c = get_in_brackets(tmp);
if (strncmp(c, "sip:", 4)) {
ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
return -1;
}
c += 4;
if ((a = strchr(c, '@')))
*a = '\0';
if ((a = strchr(c, ';')))
*a = '\0';
if (sip_debug_test_pvt(p)) {
ast_verbose("Looking for %s in %s\n", c, p->context);
}
if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
/* This is an unsupervised transfer */
ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
ast_copy_string(p->refer_to, c, sizeof(p->refer_to));
ast_copy_string(p->referred_by, "", sizeof(p->referred_by));
ast_copy_string(p->refer_contact, "", sizeof(p->refer_contact));
p->refer_call = NULL;
return 0;
} else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
return 1;
}
return -1;
}
/*! \brief check Via: header for hostname, port and rport request/answer */
static int check_via(struct sip_pvt *p, struct sip_request *req)
{
char via[256];
char iabuf[INET_ADDRSTRLEN];
char *c, *pt;
struct hostent *hp;
struct ast_hostent ahp;
ast_copy_string(via, get_header(req, "Via"), sizeof(via));
/* Check for rport */
c = strstr(via, ";rport");
if (c && (c[6] != '=')) /* rport query, not answer */
ast_set_flag(p, SIP_NAT_ROUTE);
c = strchr(via, ';');
if (c)
*c = '\0';
c = strchr(via, ' ');
if (c) {
*c = '\0';
c = ast_skip_blanks(c+1);
if (strcasecmp(via, "SIP/2.0/UDP")) {
ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
return -1;
}
pt = strchr(c, ':');
if (pt)
*pt++ = '\0'; /* remember port pointer */
hp = ast_gethostbyname(c, &ahp);
if (!hp) {
ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
return -1;
}
memset(&p->sa, 0, sizeof(p->sa));
p->sa.sin_family = AF_INET;
memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
if (sip_debug_test_pvt(p)) {
c = (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ? "NAT" : "non-NAT";
ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), c);
}
}
return 0;
}
/*! \brief get_calleridname: Get caller id name from SIP headers ---*/
static char *get_calleridname(char *input, char *output, size_t outputsize)
{
char *end = strchr(input,'<');
char *tmp = strchr(input,'\"');
int bytes = 0;
int maxbytes = outputsize - 1;
if (!end || (end == input)) return NULL;
/* move away from "<" */
end--;
/* we found "name" */
if (tmp && tmp < end) {
end = strchr(tmp+1, '\"');
if (!end) return NULL;
bytes = (int) (end - tmp);
/* protect the output buffer */
if (bytes > maxbytes)
bytes = maxbytes;
ast_copy_string(output, tmp + 1, bytes);
} else {
/* we didn't find "name" */
/* clear the empty characters in the begining*/
input = ast_skip_blanks(input);
/* clear the empty characters in the end */
while(*end && (*end < 33) && end > input)
end--;
if (end >= input) {
bytes = (int) (end - input) + 2;
/* protect the output buffer */
if (bytes > maxbytes) {
bytes = maxbytes;
}
ast_copy_string(output, input, bytes);
}
else
return NULL;
}
return output;
}
/*! \brief get_rpid_num: Get caller id number from Remote-Party-ID header field
* Returns true if number should be restricted (privacy setting found)
* output is set to NULL if no number found
*/
static int get_rpid_num(char *input,char *output, int maxlen)
{
char *start;
char *end;
start = strchr(input,':');
if (!start) {
output[0] = '\0';
return 0;
}
start++;
/* we found "number" */
ast_copy_string(output,start,maxlen);
output[maxlen-1] = '\0';
end = strchr(output,'@');
if (end)
*end = '\0';
else
output[0] = '\0';
if (strstr(input,"privacy=full") || strstr(input,"privacy=uri"))
return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
return 0;
}
/*! \brief check_user_full: Check if matching user or peer is defined ---*/
/* Match user on From: user name and peer on IP/port */
/* This is used on first invite (not re-invites) and subscribe requests */
static int check_user_full(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, int reliable, struct sockaddr_in *sin, int ignore, char *mailbox, int mailboxlen)
{
struct sip_user *user = NULL;
struct sip_peer *peer;
char *of, from[256], *c;
char *rpid,rpid_num[50];
char iabuf[INET_ADDRSTRLEN];
int res = 0;
char *t;
char calleridname[50];
int debug=sip_debug_test_addr(sin);
struct ast_variable *tmpvar = NULL, *v = NULL;
char *uri2 = ast_strdupa(uri);
/* Terminate URI */
t = uri2;
while(*t && (*t > 32) && (*t != ';'))
t++;
*t = '\0';
of = get_header(req, "From");
if (pedanticsipchecking)
ast_uri_decode(of);
ast_copy_string(from, of, sizeof(from));
memset(calleridname,0,sizeof(calleridname));
get_calleridname(from, calleridname, sizeof(calleridname));
if (calleridname[0])
ast_copy_string(p->cid_name, calleridname, sizeof(p->cid_name));
rpid = get_header(req, "Remote-Party-ID");
memset(rpid_num, 0, sizeof(rpid_num));
if (!ast_strlen_zero(rpid))
p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
of = get_in_brackets(from);
if (ast_strlen_zero(p->exten)) {
t = uri2;
if (!strncmp(t, "sip:", 4))
t+= 4;
ast_copy_string(p->exten, t, sizeof(p->exten));
t = strchr(p->exten, '@');
if (t)
*t = '\0';
if (ast_strlen_zero(p->our_contact))
build_contact(p);
}
/* save the URI part of the From header */
ast_copy_string(p->from, of, sizeof(p->from));
if (strncmp(of, "sip:", 4)) {
ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
} else
of += 4;
/* Get just the username part */
if ((c = strchr(of, '@'))) {
*c = '\0';
if ((c = strchr(of, ':')))
*c = '\0';
ast_copy_string(p->cid_num, of, sizeof(p->cid_num));
ast_shrink_phone_number(p->cid_num);
}
if (ast_strlen_zero(of))
return 0;
if (!mailbox) /* If it's a mailbox SUBSCRIBE, don't check users */
user = find_user(of, 1);
/* Find user based on user name in the from header */
if (user && ast_apply_ha(user->ha, sin)) {
ast_copy_flags(p, user, SIP_FLAGS_TO_COPY);
/* copy channel vars */
for (v = user->chanvars ; v ; v = v->next) {
if ((tmpvar = ast_variable_new(v->name, v->value))) {
tmpvar->next = p->chanvars;
p->chanvars = tmpvar;
}
}
p->prefs = user->prefs;
/* replace callerid if rpid found, and not restricted */
if (!ast_strlen_zero(rpid_num) && ast_test_flag(p, SIP_TRUSTRPID)) {
if (*calleridname)
ast_copy_string(p->cid_name, calleridname, sizeof(p->cid_name));
ast_copy_string(p->cid_num, rpid_num, sizeof(p->cid_num));
ast_shrink_phone_number(p->cid_num);
}
if (p->rtp) {
ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
ast_rtp_setnat(p->rtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
}
if (p->vrtp) {
ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
ast_rtp_setnat(p->vrtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
}
if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, user->md5secret, sipmethod, uri2, reliable, ignore))) {
sip_cancel_destroy(p);
ast_copy_flags(p, user, SIP_FLAGS_TO_COPY);
/* Copy SIP extensions profile from INVITE */
if (p->sipoptions)
user->sipoptions = p->sipoptions;
/* If we have a call limit, set flag */
if (user->call_limit)
ast_set_flag(p, SIP_CALL_LIMIT);
if (!ast_strlen_zero(user->context))
ast_copy_string(p->context, user->context, sizeof(p->context));
if (!ast_strlen_zero(user->cid_num) && !ast_strlen_zero(p->cid_num)) {
ast_copy_string(p->cid_num, user->cid_num, sizeof(p->cid_num));
ast_shrink_phone_number(p->cid_num);
}
if (!ast_strlen_zero(user->cid_name) && !ast_strlen_zero(p->cid_num))
ast_copy_string(p->cid_name, user->cid_name, sizeof(p->cid_name));
ast_copy_string(p->peername, user->name, sizeof(p->peername));
ast_copy_string(p->username, user->name, sizeof(p->username));
ast_copy_string(p->peersecret, user->secret, sizeof(p->peersecret));
ast_copy_string(p->subscribecontext, user->subscribecontext, sizeof(p->subscribecontext));
ast_copy_string(p->peermd5secret, user->md5secret, sizeof(p->peermd5secret));
ast_copy_string(p->accountcode, user->accountcode, sizeof(p->accountcode));
ast_copy_string(p->language, user->language, sizeof(p->language));
ast_copy_string(p->musicclass, user->musicclass, sizeof(p->musicclass));
p->amaflags = user->amaflags;
p->callgroup = user->callgroup;
p->pickupgroup = user->pickupgroup;
p->callingpres = user->callingpres;
p->capability = user->capability;
p->jointcapability = user->capability;
if (p->peercapability)
p->jointcapability &= p->peercapability;
if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO))
p->noncodeccapability |= AST_RTP_DTMF;
else
p->noncodeccapability &= ~AST_RTP_DTMF;
}
if (user && debug)
ast_verbose("Found user '%s'\n", user->name);
} else {
if (user) {
if (!mailbox && debug)
ast_verbose("Found user '%s', but fails host access\n", user->name);
ASTOBJ_UNREF(user,sip_destroy_user);
}
user = NULL;
}
if (!user) {
/* If we didn't find a user match, check for peers */
if (sipmethod == SIP_SUBSCRIBE)
/* For subscribes, match on peer name only */
peer = find_peer(of, NULL, 1);
else
/* Look for peer based on the IP address we received data from */
/* If peer is registered from this IP address or have this as a default
IP address, this call is from the peer
*/
peer = find_peer(NULL, &p->recv, 1);
if (peer) {
if (debug)
ast_verbose("Found peer '%s'\n", peer->name);
/* Take the peer */
ast_copy_flags(p, peer, SIP_FLAGS_TO_COPY);
/* Copy SIP extensions profile to peer */
if (p->sipoptions)
peer->sipoptions = p->sipoptions;
/* replace callerid if rpid found, and not restricted */
if (!ast_strlen_zero(rpid_num) && ast_test_flag(p, SIP_TRUSTRPID)) {
if (*calleridname)
ast_copy_string(p->cid_name, calleridname, sizeof(p->cid_name));
ast_copy_string(p->cid_num, rpid_num, sizeof(p->cid_num));
ast_shrink_phone_number(p->cid_num);
}
if (p->rtp) {
ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
ast_rtp_setnat(p->rtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
}
if (p->vrtp) {
ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
ast_rtp_setnat(p->vrtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
}
ast_copy_string(p->peersecret, peer->secret, sizeof(p->peersecret));
p->peersecret[sizeof(p->peersecret)-1] = '\0';
ast_copy_string(p->subscribecontext, peer->subscribecontext, sizeof(p->subscribecontext));
ast_copy_string(p->peermd5secret, peer->md5secret, sizeof(p->peermd5secret));
p->peermd5secret[sizeof(p->peermd5secret)-1] = '\0';
p->callingpres = peer->callingpres;
if (peer->maxms && peer->lastms)
p->timer_t1 = peer->lastms;
if (ast_test_flag(peer, SIP_INSECURE_INVITE)) {
/* Pretend there is no required authentication */
p->peersecret[0] = '\0';
p->peermd5secret[0] = '\0';
}
if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, ignore))) {
ast_copy_flags(p, peer, SIP_FLAGS_TO_COPY);
/* If we have a call limit, set flag */
if (peer->call_limit)
ast_set_flag(p, SIP_CALL_LIMIT);
ast_copy_string(p->peername, peer->name, sizeof(p->peername));
ast_copy_string(p->authname, peer->name, sizeof(p->authname));
/* copy channel vars */
for (v = peer->chanvars ; v ; v = v->next) {
if ((tmpvar = ast_variable_new(v->name, v->value))) {
tmpvar->next = p->chanvars;
p->chanvars = tmpvar;
}
}
if (mailbox)
snprintf(mailbox, mailboxlen, ",%s,", peer->mailbox);
if (!ast_strlen_zero(peer->username)) {
ast_copy_string(p->username, peer->username, sizeof(p->username));
/* Use the default username for authentication on outbound calls */
ast_copy_string(p->authname, peer->username, sizeof(p->authname));
}
if (!ast_strlen_zero(peer->cid_num) && !ast_strlen_zero(p->cid_num)) {
ast_copy_string(p->cid_num, peer->cid_num, sizeof(p->cid_num));
ast_shrink_phone_number(p->cid_num);
}
if (!ast_strlen_zero(peer->cid_name) && !ast_strlen_zero(p->cid_name))
ast_copy_string(p->cid_name, peer->cid_name, sizeof(p->cid_name));
ast_copy_string(p->fullcontact, peer->fullcontact, sizeof(p->fullcontact));
if (!ast_strlen_zero(peer->context))
ast_copy_string(p->context, peer->context, sizeof(p->context));
ast_copy_string(p->peersecret, peer->secret, sizeof(p->peersecret));
ast_copy_string(p->peermd5secret, peer->md5secret, sizeof(p->peermd5secret));
ast_copy_string(p->language, peer->language, sizeof(p->language));
ast_copy_string(p->accountcode, peer->accountcode, sizeof(p->accountcode));
p->amaflags = peer->amaflags;
p->callgroup = peer->callgroup;
p->pickupgroup = peer->pickupgroup;
p->capability = peer->capability;
p->prefs = peer->prefs;
p->jointcapability = peer->capability;
if (p->peercapability)
p->jointcapability &= p->peercapability;
if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO))
p->noncodeccapability |= AST_RTP_DTMF;
else
p->noncodeccapability &= ~AST_RTP_DTMF;
}
ASTOBJ_UNREF(peer,sip_destroy_peer);
} else {
if (debug)
ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
/* do we allow guests? */
if (!global_allowguest) {
if (global_alwaysauthreject)
res = -4; /* reject with fake authorization request */
else
res = -1; /* we don't want any guests, authentication will fail */
#ifdef OSP_SUPPORT
} else if (global_allowguest == 2) {
ast_copy_flags(p, &global_flags, SIP_OSPAUTH);
res = check_auth(p, req, p->randdata, sizeof(p->randdata), "", "", "", sipmethod, uri2, reliable, ignore);
#endif
}
}
}
if (user)
ASTOBJ_UNREF(user,sip_destroy_user);
return res;
}
/*! \brief check_user: Find user ---*/
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, int reliable, struct sockaddr_in *sin, int ignore)
{
return check_user_full(p, req, sipmethod, uri, reliable, sin, ignore, NULL, 0);
}
/*! \brief get_msg_text: Get text out of a SIP MESSAGE packet ---*/
static int get_msg_text(char *buf, int len, struct sip_request *req)
{
int x;
int y;
buf[0] = '\0';
y = len - strlen(buf) - 5;
if (y < 0)
y = 0;
for (x=0;x<req->lines;x++) {
strncat(buf, req->line[x], y); /* safe */
y -= strlen(req->line[x]) + 1;
if (y < 0)
y = 0;
if (y != 0)
strcat(buf, "\n"); /* safe */
}
return 0;
}
/*! \brief receive_message: Receive SIP MESSAGE method messages ---*/
/* We only handle messages within current calls currently */
/* Reference: RFC 3428 */
static void receive_message(struct sip_pvt *p, struct sip_request *req)
{
char buf[1024];
struct ast_frame f;
char *content_type;
content_type = get_header(req, "Content-Type");
if (strcmp(content_type, "text/plain")) { /* No text/plain attachment */
transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
ast_set_flag(p, SIP_NEEDDESTROY);
return;
}
if (get_msg_text(buf, sizeof(buf), req)) {
ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
transmit_response(p, "202 Accepted", req);
ast_set_flag(p, SIP_NEEDDESTROY);
return;
}
if (p->owner) {
if (sip_debug_test_pvt(p))
ast_verbose("Message received: '%s'\n", buf);
memset(&f, 0, sizeof(f));
f.frametype = AST_FRAME_TEXT;
f.subclass = 0;
f.offset = 0;
f.data = buf;
f.datalen = strlen(buf);
ast_queue_frame(p->owner, &f);
transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
} else { /* Message outside of a call, we do not support that */
ast_log(LOG_WARNING,"Received message to %s from %s, dropped it...\n Content-Type:%s\n Message: %s\n", get_header(req,"To"), get_header(req,"From"), content_type, buf);
transmit_response(p, "405 Method Not Allowed", req); /* Good enough, or? */
}
ast_set_flag(p, SIP_NEEDDESTROY);
return;
}
/*! \brief sip_show_inuse: CLI Command to show calls within limits set by
call_limit ---*/
static int sip_show_inuse(int fd, int argc, char *argv[]) {
#define FORMAT "%-25.25s %-15.15s %-15.15s \n"
#define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
char ilimits[40];
char iused[40];
int showall = 0;
if (argc < 3)
return RESULT_SHOWUSAGE;
if (argc == 4 && !strcmp(argv[3],"all"))
showall = 1;
ast_cli(fd, FORMAT, "* User name", "In use", "Limit");
ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
ASTOBJ_RDLOCK(iterator);
if (iterator->call_limit)
snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
else
ast_copy_string(ilimits, "N/A", sizeof(ilimits));
snprintf(iused, sizeof(iused), "%d", iterator->inUse);
if (showall || iterator->call_limit)
ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
ASTOBJ_UNLOCK(iterator);
} while (0) );
ast_cli(fd, FORMAT, "* Peer name", "In use", "Limit");
ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
ASTOBJ_RDLOCK(iterator);
if (iterator->call_limit)
snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
else
ast_copy_string(ilimits, "N/A", sizeof(ilimits));
snprintf(iused, sizeof(iused), "%d", iterator->inUse);
if (showall || iterator->call_limit)
ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
ASTOBJ_UNLOCK(iterator);
} while (0) );
return RESULT_SUCCESS;
#undef FORMAT
#undef FORMAT2
}
/*! \brief nat2str: Convert NAT setting to text string */
static char *nat2str(int nat)
{
switch(nat) {
case SIP_NAT_NEVER:
return "No";
case SIP_NAT_ROUTE:
return "Route";
case SIP_NAT_ALWAYS:
return "Always";
case SIP_NAT_RFC3581:
return "RFC3581";
default:
return "Unknown";
}
}
/*! \brief peer_status: Report Peer status in character string */
/* returns 1 if peer is online, -1 if unmonitored */
static int peer_status(struct sip_peer *peer, char *status, int statuslen)
{
int res = 0;
if (peer->maxms) {
if (peer->lastms < 0) {
ast_copy_string(status, "UNREACHABLE", statuslen);
} else if (peer->lastms > peer->maxms) {
snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
res = 1;
} else if (peer->lastms) {
snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
res = 1;
} else {
ast_copy_string(status, "UNKNOWN", statuslen);
}
} else {
ast_copy_string(status, "Unmonitored", statuslen);
/* Checking if port is 0 */
res = -1;
}
return res;
}
/*! \brief sip_show_users: CLI Command 'SIP Show Users' ---*/
static int sip_show_users(int fd, int argc, char *argv[])
{
regex_t regexbuf;
int havepattern = 0;
#define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
switch (argc) {
case 5:
if (!strcasecmp(argv[3], "like")) {
if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
return RESULT_SHOWUSAGE;
havepattern = 1;
} else
return RESULT_SHOWUSAGE;
case 3:
break;
default:
return RESULT_SHOWUSAGE;
}
ast_cli(fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
ASTOBJ_RDLOCK(iterator);
if (havepattern && regexec(®exbuf, iterator->name, 0, NULL, 0)) {
ASTOBJ_UNLOCK(iterator);
continue;
}
ast_cli(fd, FORMAT, iterator->name,
iterator->secret,
iterator->accountcode,
iterator->context,
iterator->ha ? "Yes" : "No",
nat2str(ast_test_flag(iterator, SIP_NAT)));
ASTOBJ_UNLOCK(iterator);
} while (0)
);
if (havepattern)
regfree(®exbuf);
return RESULT_SUCCESS;
#undef FORMAT
}
static char mandescr_show_peers[] =
"Description: Lists SIP peers in text format with details on current status.\n"
"Variables: \n"
" ActionID: <id> Action ID for this transaction. Will be returned.\n";
static int _sip_show_peers(int fd, int *total, struct mansession *s, struct message *m, int argc, char *argv[]);
/*! \brief manager_sip_show_peers: Show SIP peers in the manager API ---*/
/* Inspired from chan_iax2 */
static int manager_sip_show_peers( struct mansession *s, struct message *m )
{
char *id = astman_get_header(m,"ActionID");
char *a[] = { "sip", "show", "peers" };
char idtext[256] = "";
int total = 0;
if (!ast_strlen_zero(id))
snprintf(idtext,256,"ActionID: %s\r\n",id);
astman_send_ack(s, m, "Peer status list will follow");
/* List the peers in separate manager events */
_sip_show_peers(s->fd, &total, s, m, 3, a);
/* Send final confirmation */
ast_cli(s->fd,
"Event: PeerlistComplete\r\n"
"ListItems: %d\r\n"
"%s"
"\r\n", total, idtext);
return 0;
}
/*! \brief sip_show_peers: CLI Show Peers command */
static int sip_show_peers(int fd, int argc, char *argv[])
{
return _sip_show_peers(fd, NULL, NULL, NULL, argc, argv);
}
/*! \brief _sip_show_peers: Execute sip show peers command */
static int _sip_show_peers(int fd, int *total, struct mansession *s, struct message *m, int argc, char *argv[])
{
regex_t regexbuf;
int havepattern = 0;
#define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s\n"
#define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s\n"
char name[256];
char iabuf[INET_ADDRSTRLEN];
int total_peers = 0;
int peers_online = 0;
int peers_offline = 0;
char *id;
char idtext[256] = "";
if (s) { /* Manager - get ActionID */
id = astman_get_header(m,"ActionID");
if (!ast_strlen_zero(id))
snprintf(idtext,256,"ActionID: %s\r\n",id);
}
switch (argc) {
case 5:
if (!strcasecmp(argv[3], "like")) {
if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
return RESULT_SHOWUSAGE;
havepattern = 1;
} else
return RESULT_SHOWUSAGE;
case 3:
break;
default:
return RESULT_SHOWUSAGE;
}
if (!s) { /* Normal list */
ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status");
}
ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
char status[20] = "";
char srch[2000];
char pstatus;
ASTOBJ_RDLOCK(iterator);
if (havepattern && regexec(®exbuf, iterator->name, 0, NULL, 0)) {
ASTOBJ_UNLOCK(iterator);
continue;
}
if (!ast_strlen_zero(iterator->username) && !s)
snprintf(name, sizeof(name), "%s/%s", iterator->name, iterator->username);
else
ast_copy_string(name, iterator->name, sizeof(name));
pstatus = peer_status(iterator, status, sizeof(status));
if (pstatus)
peers_online++;
else {
if (pstatus == 0)
peers_offline++;
else { /* Unmonitored */
/* Checking if port is 0 */
if ( ntohs(iterator->addr.sin_port) == 0 ) {
peers_offline++;
} else {
peers_online++;
}
}
}
snprintf(srch, sizeof(srch), FORMAT, name,
iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), iterator->addr.sin_addr) : "(Unspecified)",
ast_test_flag(&iterator->flags_page2, SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
(ast_test_flag(iterator, SIP_NAT) & SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
iterator->ha ? " A " : " ", /* permit/deny */
ntohs(iterator->addr.sin_port), status);
if (!s) {/* Normal CLI list */
ast_cli(fd, FORMAT, name,
iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), iterator->addr.sin_addr) : "(Unspecified)",
ast_test_flag(&iterator->flags_page2, SIP_PAGE2_DYNAMIC) ? " D " : " ", /* Dynamic or not? */
(ast_test_flag(iterator, SIP_NAT) & SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
iterator->ha ? " A " : " ", /* permit/deny */
ntohs(iterator->addr.sin_port), status);
} else { /* Manager format */
/* The names here need to be the same as other channels */
ast_cli(fd,
"Event: PeerEntry\r\n%s"
"Channeltype: SIP\r\n"
"ObjectName: %s\r\n"
"ChanObjectType: peer\r\n" /* "peer" or "user" */
"IPaddress: %s\r\n"
"IPport: %d\r\n"
"Dynamic: %s\r\n"
"Natsupport: %s\r\n"
"ACL: %s\r\n"
"Status: %s\r\n\r\n",
idtext,
iterator->name,
iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), iterator->addr.sin_addr) : "-none-",
ntohs(iterator->addr.sin_port),
ast_test_flag(&iterator->flags_page2, SIP_PAGE2_DYNAMIC) ? "yes" : "no", /* Dynamic or not? */
(ast_test_flag(iterator, SIP_NAT) & SIP_NAT_ROUTE) ? "yes" : "no", /* NAT=yes? */
iterator->ha ? "yes" : "no", /* permit/deny */
status);
}
ASTOBJ_UNLOCK(iterator);
total_peers++;
} while(0) );
if (!s) {
ast_cli(fd,"%d sip peers [%d online , %d offline]\n",total_peers,peers_online,peers_offline);
}
if (havepattern)
regfree(®exbuf);
if (total)
*total = total_peers;
return RESULT_SUCCESS;
#undef FORMAT
#undef FORMAT2
}
/*! \brief sip_show_objects: List all allocated SIP Objects ---*/
static int sip_show_objects(int fd, int argc, char *argv[])
{
char tmp[256];
if (argc != 3)
return RESULT_SHOWUSAGE;
ast_cli(fd, "-= User objects: %d static, %d realtime =-\n\n", suserobjs, ruserobjs);
ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &userl);
ast_cli(fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &peerl);
ast_cli(fd, "-= Registry objects: %d =-\n\n", regobjs);
ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), ®l);
return RESULT_SUCCESS;
}
/*! \brief print_group: Print call group and pickup group ---*/
static void print_group(int fd, ast_group_t group, int crlf)
{
char buf[256];
ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
}
/*! \brief dtmfmode2str: Convert DTMF mode to printable string ---*/
static const char *dtmfmode2str(int mode)
{
switch (mode) {
case SIP_DTMF_RFC2833:
return "rfc2833";
case SIP_DTMF_INFO:
return "info";
case SIP_DTMF_INBAND:
return "inband";
case SIP_DTMF_AUTO:
return "auto";
}
return "<error>";
}
/*! \brief insecure2str: Convert Insecure setting to printable string ---*/
static const char *insecure2str(int port, int invite)
{
if (port && invite)
return "port,invite";
else if (port)
return "port";
else if (invite)
return "invite";
else
return "no";
}
/*! \brief sip_prune_realtime: Remove temporary realtime objects from memory (CLI) ---*/
static int sip_prune_realtime(int fd, int argc, char *argv[])
{
struct sip_peer *peer;
struct sip_user *user;
int pruneuser = 0;
int prunepeer = 0;
int multi = 0;
char *name = NULL;
regex_t regexbuf;
switch (argc) {
case 4:
if (!strcasecmp(argv[3], "user"))
return RESULT_SHOWUSAGE;
if (!strcasecmp(argv[3], "peer"))
return RESULT_SHOWUSAGE;
if (!strcasecmp(argv[3], "like"))
return RESULT_SHOWUSAGE;
if (!strcasecmp(argv[3], "all")) {
multi = 1;
pruneuser = prunepeer = 1;
} else {
pruneuser = prunepeer = 1;
name = argv[3];
}
break;
case 5:
if (!strcasecmp(argv[4], "like"))
return RESULT_SHOWUSAGE;
if (!strcasecmp(argv[3], "all"))
return RESULT_SHOWUSAGE;
if (!strcasecmp(argv[3], "like")) {
multi = 1;
name = argv[4];
pruneuser = prunepeer = 1;
} else if (!strcasecmp(argv[3], "user")) {
pruneuser = 1;
if (!strcasecmp(argv[4], "all"))
multi = 1;
else
name = argv[4];
} else if (!strcasecmp(argv[3], "peer")) {
prunepeer = 1;
if (!strcasecmp(argv[4], "all"))
multi = 1;
else
name = argv[4];
} else
return RESULT_SHOWUSAGE;
break;
case 6:
if (strcasecmp(argv[4], "like"))
return RESULT_SHOWUSAGE;
if (!strcasecmp(argv[3], "user")) {
pruneuser = 1;
name = argv[5];
} else if (!strcasecmp(argv[3], "peer")) {
prunepeer = 1;
name = argv[5];
} else
return RESULT_SHOWUSAGE;
break;
default:
return RESULT_SHOWUSAGE;
}
if (multi && name) {
if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB))
return RESULT_SHOWUSAGE;
}
if (multi) {
if (prunepeer) {
int pruned = 0;
ASTOBJ_CONTAINER_WRLOCK(&peerl);
ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
ASTOBJ_RDLOCK(iterator);
if (name && regexec(®exbuf, iterator->name, 0, NULL, 0)) {
ASTOBJ_UNLOCK(iterator);
continue;
};
if (ast_test_flag((&iterator->flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
ASTOBJ_MARK(iterator);
pruned++;
}
ASTOBJ_UNLOCK(iterator);
} while (0) );
if (pruned) {
ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
ast_cli(fd, "%d peers pruned.\n", pruned);
} else
ast_cli(fd, "No peers found to prune.\n");
ASTOBJ_CONTAINER_UNLOCK(&peerl);
}
if (pruneuser) {
int pruned = 0;
ASTOBJ_CONTAINER_WRLOCK(&userl);
ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
ASTOBJ_RDLOCK(iterator);
if (name && regexec(®exbuf, iterator->name, 0, NULL, 0)) {
ASTOBJ_UNLOCK(iterator);
continue;
};
if (ast_test_flag((&iterator->flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
ASTOBJ_MARK(iterator);
pruned++;
}
ASTOBJ_UNLOCK(iterator);
} while (0) );
if (pruned) {
ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, sip_destroy_user);
ast_cli(fd, "%d users pruned.\n", pruned);
} else
ast_cli(fd, "No users found to prune.\n");
ASTOBJ_CONTAINER_UNLOCK(&userl);
}
} else {
if (prunepeer) {
if ((peer = ASTOBJ_CONTAINER_FIND_UNLINK(&peerl, name))) {
if (!ast_test_flag((&peer->flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
ast_cli(fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
ASTOBJ_CONTAINER_LINK(&peerl, peer);
} else
ast_cli(fd, "Peer '%s' pruned.\n", name);
ASTOBJ_UNREF(peer, sip_destroy_peer);
} else
ast_cli(fd, "Peer '%s' not found.\n", name);
}
if (pruneuser) {
if ((user = ASTOBJ_CONTAINER_FIND_UNLINK(&userl, name))) {
if (!ast_test_flag((&user->flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
ast_cli(fd, "User '%s' is not a Realtime user, cannot be pruned.\n", name);
ASTOBJ_CONTAINER_LINK(&userl, user);
} else
ast_cli(fd, "User '%s' pruned.\n", name);
ASTOBJ_UNREF(user, sip_destroy_user);
} else
ast_cli(fd, "User '%s' not found.\n", name);
}
}
return RESULT_SUCCESS;
}
/*! \brief print_codec_to_cli: Print codec list from preference to CLI/manager */
static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
{
int x, codec;
for(x = 0; x < 32 ; x++) {
codec = ast_codec_pref_index(pref, x);
if (!codec)
break;
ast_cli(fd, "%s", ast_getformatname(codec));
if (x < 31 && ast_codec_pref_index(pref, x + 1))
ast_cli(fd, ",");
}
if (!x)
ast_cli(fd, "none");
}
static const char *domain_mode_to_text(const enum domain_mode mode)
{
switch (mode) {
case SIP_DOMAIN_AUTO:
return "[Automatic]";
case SIP_DOMAIN_CONFIG:
return "[Configured]";
}
return "";
}
/*! \brief sip_show_domains: CLI command to list local domains */
#define FORMAT "%-40.40s %-20.20s %-16.16s\n"
static int sip_show_domains(int fd, int argc, char *argv[])
{
struct domain *d;
if (AST_LIST_EMPTY(&domain_list)) {
ast_cli(fd, "SIP Domain support not enabled.\n\n");
return RESULT_SUCCESS;
} else {
ast_cli(fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
AST_LIST_LOCK(&domain_list);
AST_LIST_TRAVERSE(&domain_list, d, list)
ast_cli(fd, FORMAT, d->domain, ast_strlen_zero(d->context) ? "(default)": d->context,
domain_mode_to_text(d->mode));
AST_LIST_UNLOCK(&domain_list);
ast_cli(fd, "\n");
return RESULT_SUCCESS;
}
}
#undef FORMAT
static char mandescr_show_peer[] =
"Description: Show one SIP peer with details on current status.\n"
" The XML format is under development, feedback welcome! /oej\n"
"Variables: \n"
" Peer: <name> The peer name you want to check.\n"
" ActionID: <id> Optional action ID for this AMI transaction.\n";
static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[]);
/*! \brief manager_sip_show_peer: Show SIP peers in the manager API ---*/
static int manager_sip_show_peer( struct mansession *s, struct message *m )
{
char *id = astman_get_header(m,"ActionID");
char *a[4];
char *peer;
int ret;
peer = astman_get_header(m,"Peer");
if (ast_strlen_zero(peer)) {
astman_send_error(s, m, "Peer: <name> missing.\n");
return 0;
}
a[0] = "sip";
a[1] = "show";
a[2] = "peer";
a[3] = peer;
if (!ast_strlen_zero(id))
ast_cli(s->fd, "ActionID: %s\r\n",id);
ret = _sip_show_peer(1, s->fd, s, m, 4, a );
ast_cli( s->fd, "\r\n\r\n" );
return ret;
}
/*! \brief sip_show_peer: Show one peer in detail ---*/
static int sip_show_peer(int fd, int argc, char *argv[])
{
return _sip_show_peer(0, fd, NULL, NULL, argc, argv);
}
static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[])
{
char status[30] = "";
char cbuf[256];
char iabuf[INET_ADDRSTRLEN];
struct sip_peer *peer;
char codec_buf[512];
struct ast_codec_pref *pref;
struct ast_variable *v;
struct sip_auth *auth;
int x = 0, codec = 0, load_realtime = 0;
if (argc < 4)
return RESULT_SHOWUSAGE;
load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
peer = find_peer(argv[3], NULL, load_realtime);
if (s) { /* Manager */
if (peer)
ast_cli(s->fd, "Response: Success\r\n");
else {
snprintf (cbuf, sizeof(cbuf), "Peer %s not found.\n", argv[3]);
astman_send_error(s, m, cbuf);
return 0;
}
}
if (peer && type==0 ) { /* Normal listing */
ast_cli(fd,"\n\n");
ast_cli(fd, " * Name : %s\n", peer->name);
ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
auth = peer->auth;
while(auth) {
ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
auth = auth->next;
}
ast_cli(fd, " Context : %s\n", peer->context);
ast_cli(fd, " Subscr.Cont. : %s\n", ast_strlen_zero(peer->subscribecontext)?"<Not set>":peer->subscribecontext);
ast_cli(fd, " Language : %s\n", peer->language);
if (!ast_strlen_zero(peer->accountcode))
ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
if (!ast_strlen_zero(peer->fromuser))
ast_cli(fd, " FromUser : %s\n", peer->fromuser);
if (!ast_strlen_zero(peer->fromdomain))
ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
ast_cli(fd, " Callgroup : ");
print_group(fd, peer->callgroup, 0);
ast_cli(fd, " Pickupgroup : ");
print_group(fd, peer->pickupgroup, 0);
ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
ast_cli(fd, " LastMsgsSent : %d\n", peer->lastmsgssent);
ast_cli(fd, " Call limit : %d\n", peer->call_limit);
ast_cli(fd, " Dynamic : %s\n", (ast_test_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC)?"Yes":"No"));
ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(peer, SIP_INSECURE_PORT), ast_test_flag(peer, SIP_INSECURE_INVITE)));
ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(peer, SIP_NAT)));
ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
ast_cli(fd, " CanReinvite : %s\n", (ast_test_flag(peer, SIP_CAN_REINVITE)?"Yes":"No"));
ast_cli(fd, " PromiscRedir : %s\n", (ast_test_flag(peer, SIP_PROMISCREDIR)?"Yes":"No"));
ast_cli(fd, " User=Phone : %s\n", (ast_test_flag(peer, SIP_USEREQPHONE)?"Yes":"No"));
ast_cli(fd, " Trust RPID : %s\n", (ast_test_flag(peer, SIP_TRUSTRPID) ? "Yes" : "No"));
ast_cli(fd, " Send RPID : %s\n", (ast_test_flag(peer, SIP_SENDRPID) ? "Yes" : "No"));
/* - is enumerated */
ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(peer, SIP_DTMF)));
ast_cli(fd, " LastMsg : %d\n", peer->lastmsg);
ast_cli(fd, " ToHost : %s\n", peer->tohost);
ast_cli(fd, " Addr->IP : %s Port %d\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
ast_cli(fd, " Def. Username: %s\n", peer->username);
ast_cli(fd, " SIP Options : ");
if (peer->sipoptions) {
for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
if (peer->sipoptions & sip_options[x].id)
ast_cli(fd, "%s ", sip_options[x].text);
}
} else
ast_cli(fd, "(none)");
ast_cli(fd, "\n");
ast_cli(fd, " Codecs : ");
ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
ast_cli(fd, "%s\n", codec_buf);
ast_cli(fd, " Codec Order : (");
print_codec_to_cli(fd, &peer->prefs);
ast_cli(fd, ")\n");
ast_cli(fd, " Status : ");
peer_status(peer, status, sizeof(status));
ast_cli(fd, "%s\n",status);
ast_cli(fd, " Useragent : %s\n", peer->useragent);
ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
if (peer->chanvars) {
ast_cli(fd, " Variables :\n");
for (v = peer->chanvars ; v ; v = v->next)
ast_cli(fd, " %s = %s\n", v->name, v->value);
}
ast_cli(fd,"\n");
ASTOBJ_UNREF(peer,sip_destroy_peer);
} else if (peer && type == 1) { /* manager listing */
ast_cli(fd, "Channeltype: SIP\r\n");
ast_cli(fd, "ObjectName: %s\r\n", peer->name);
ast_cli(fd, "ChanObjectType: peer\r\n");
ast_cli(fd, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
ast_cli(fd, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
ast_cli(fd, "Context: %s\r\n", peer->context);
ast_cli(fd, "Language: %s\r\n", peer->language);
if (!ast_strlen_zero(peer->accountcode))
ast_cli(fd, "Accountcode: %s\r\n", peer->accountcode);
ast_cli(fd, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
ast_cli(fd, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
if (!ast_strlen_zero(peer->fromuser))
ast_cli(fd, "SIP-FromUser: %s\r\n", peer->fromuser);
if (!ast_strlen_zero(peer->fromdomain))
ast_cli(fd, "SIP-FromDomain: %s\r\n", peer->fromdomain);
ast_cli(fd, "Callgroup: ");
print_group(fd, peer->callgroup, 1);
ast_cli(fd, "Pickupgroup: ");
print_group(fd, peer->pickupgroup, 1);
ast_cli(fd, "VoiceMailbox: %s\r\n", peer->mailbox);
ast_cli(fd, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
ast_cli(fd, "Call limit: %d\r\n", peer->call_limit);
ast_cli(fd, "Dynamic: %s\r\n", (ast_test_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC)?"Y":"N"));
ast_cli(fd, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
ast_cli(fd, "RegExpire: %ld seconds\r\n", ast_sched_when(sched,peer->expire));
ast_cli(fd, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(peer, SIP_INSECURE_PORT), ast_test_flag(peer, SIP_INSECURE_INVITE)));
ast_cli(fd, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(peer, SIP_NAT)));
ast_cli(fd, "ACL: %s\r\n", (peer->ha?"Y":"N"));
ast_cli(fd, "SIP-CanReinvite: %s\r\n", (ast_test_flag(peer, SIP_CAN_REINVITE)?"Y":"N"));
ast_cli(fd, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(peer, SIP_PROMISCREDIR)?"Y":"N"));
ast_cli(fd, "SIP-UserPhone: %s\r\n", (ast_test_flag(peer, SIP_USEREQPHONE)?"Y":"N"));
/* - is enumerated */
ast_cli(fd, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(peer, SIP_DTMF)));
ast_cli(fd, "SIPLastMsg: %d\r\n", peer->lastmsg);
ast_cli(fd, "ToHost: %s\r\n", peer->tohost);
ast_cli(fd, "Address-IP: %s\r\nAddress-Port: %d\r\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "", ntohs(peer->addr.sin_port));
ast_cli(fd, "Default-addr-IP: %s\r\nDefault-addr-port: %d\r\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
ast_cli(fd, "Default-Username: %s\r\n", peer->username);
ast_cli(fd, "Codecs: ");
ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
ast_cli(fd, "%s\r\n", codec_buf);
ast_cli(fd, "CodecOrder: ");
pref = &peer->prefs;
for(x = 0; x < 32 ; x++) {
codec = ast_codec_pref_index(pref,x);
if (!codec)
break;
ast_cli(fd, "%s", ast_getformatname(codec));
if (x < 31 && ast_codec_pref_index(pref,x+1))
ast_cli(fd, ",");
}
ast_cli(fd, "\r\n");
ast_cli(fd, "Status: ");
peer_status(peer, status, sizeof(status));
ast_cli(fd, "%s\r\n", status);
ast_cli(fd, "SIP-Useragent: %s\r\n", peer->useragent);
ast_cli(fd, "Reg-Contact : %s\r\n", peer->fullcontact);
if (peer->chanvars) {
for (v = peer->chanvars ; v ; v = v->next) {
ast_cli(fd, "ChanVariable:\n");
ast_cli(fd, " %s,%s\r\n", v->name, v->value);
}
}
ASTOBJ_UNREF(peer,sip_destroy_peer);
} else {
ast_cli(fd,"Peer %s not found.\n", argv[3]);
ast_cli(fd,"\n");
}
return RESULT_SUCCESS;
}
/*! \brief sip_show_user: Show one user in detail ---*/
static int sip_show_user(int fd, int argc, char *argv[])
{
char cbuf[256];
struct sip_user *user;
struct ast_codec_pref *pref;
struct ast_variable *v;
int x = 0, codec = 0, load_realtime = 0;
if (argc < 4)
return RESULT_SHOWUSAGE;
/* Load from realtime storage? */
load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
user = find_user(argv[3], load_realtime);
if (user) {
ast_cli(fd,"\n\n");
ast_cli(fd, " * Name : %s\n", user->name);
ast_cli(fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
ast_cli(fd, " Context : %s\n", user->context);
ast_cli(fd, " Language : %s\n", user->language);
if (!ast_strlen_zero(user->accountcode))
ast_cli(fd, " Accountcode : %s\n", user->accountcode);
ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
ast_cli(fd, " Call limit : %d\n", user->call_limit);
ast_cli(fd, " Callgroup : ");
print_group(fd, user->callgroup, 0);
ast_cli(fd, " Pickupgroup : ");
print_group(fd, user->pickupgroup, 0);
ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
ast_cli(fd, " ACL : %s\n", (user->ha?"Yes":"No"));
ast_cli(fd, " Codec Order : (");
pref = &user->prefs;
for(x = 0; x < 32 ; x++) {
codec = ast_codec_pref_index(pref,x);
if (!codec)
break;
ast_cli(fd, "%s", ast_getformatname(codec));
if (x < 31 && ast_codec_pref_index(pref,x+1))
ast_cli(fd, "|");
}
if (!x)
ast_cli(fd, "none");
ast_cli(fd, ")\n");
if (user->chanvars) {
ast_cli(fd, " Variables :\n");
for (v = user->chanvars ; v ; v = v->next)
ast_cli(fd, " %s = %s\n", v->name, v->value);
}
ast_cli(fd,"\n");
ASTOBJ_UNREF(user,sip_destroy_user);
} else {
ast_cli(fd,"User %s not found.\n", argv[3]);
ast_cli(fd,"\n");
}
return RESULT_SUCCESS;
}
/*! \brief sip_show_registry: Show SIP Registry (registrations with other SIP proxies ---*/
static int sip_show_registry(int fd, int argc, char *argv[])
{
#define FORMAT2 "%-30.30s %-12.12s %8.8s %-20.20s\n"
#define FORMAT "%-30.30s %-12.12s %8d %-20.20s\n"
char host[80];
if (argc != 3)
return RESULT_SHOWUSAGE;
ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
ASTOBJ_RDLOCK(iterator);
snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : DEFAULT_SIP_PORT);
ast_cli(fd, FORMAT, host, iterator->username, iterator->refresh, regstate2str(iterator->regstate));
ASTOBJ_UNLOCK(iterator);
} while(0));
return RESULT_SUCCESS;
#undef FORMAT
#undef FORMAT2
}
/*! \brief sip_show_settings: List global settings for the SIP channel ---*/
static int sip_show_settings(int fd, int argc, char *argv[])
{
char tmp[BUFSIZ];
int realtimepeers = 0;
int realtimeusers = 0;
realtimepeers = ast_check_realtime("sippeers");
realtimeusers = ast_check_realtime("sipusers");
if (argc != 3)
return RESULT_SHOWUSAGE;
ast_cli(fd, "\n\nGlobal Settings:\n");
ast_cli(fd, "----------------\n");
ast_cli(fd, " SIP Port: %d\n", ntohs(bindaddr.sin_port));
ast_cli(fd, " Bindaddress: %s\n", ast_inet_ntoa(tmp, sizeof(tmp), bindaddr.sin_addr));
ast_cli(fd, " Videosupport: %s\n", videosupport ? "Yes" : "No");
ast_cli(fd, " AutoCreatePeer: %s\n", autocreatepeer ? "Yes" : "No");
ast_cli(fd, " Allow unknown access: %s\n", global_allowguest ? "Yes" : "No");
ast_cli(fd, " Promsic. redir: %s\n", ast_test_flag(&global_flags, SIP_PROMISCREDIR) ? "Yes" : "No");
ast_cli(fd, " SIP domain support: %s\n", AST_LIST_EMPTY(&domain_list) ? "No" : "Yes");
ast_cli(fd, " Call to non-local dom.: %s\n", allow_external_domains ? "Yes" : "No");
ast_cli(fd, " URI user is phone no: %s\n", ast_test_flag(&global_flags, SIP_USEREQPHONE) ? "Yes" : "No");
ast_cli(fd, " Our auth realm %s\n", global_realm);
ast_cli(fd, " Realm. auth: %s\n", authl ? "Yes": "No");
ast_cli(fd, " Always auth rejects: %s\n", global_alwaysauthreject ? "Yes" : "No");
ast_cli(fd, " User Agent: %s\n", default_useragent);
ast_cli(fd, " MWI checking interval: %d secs\n", global_mwitime);
ast_cli(fd, " Reg. context: %s\n", ast_strlen_zero(regcontext) ? "(not set)" : regcontext);
ast_cli(fd, " Caller ID: %s\n", default_callerid);
ast_cli(fd, " From: Domain: %s\n", default_fromdomain);
ast_cli(fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
ast_cli(fd, " Call Events: %s\n", callevents ? "On" : "Off");
ast_cli(fd, " IP ToS: 0x%x\n", tos);
#ifdef OSP_SUPPORT
ast_cli(fd, " OSP Support: Yes\n");
#else
ast_cli(fd, " OSP Support: No\n");
#endif
if (!realtimepeers && !realtimeusers)
ast_cli(fd, " SIP realtime: Disabled\n" );
else
ast_cli(fd, " SIP realtime: Enabled\n" );
ast_cli(fd, "\nGlobal Signalling Settings:\n");
ast_cli(fd, "---------------------------\n");
ast_cli(fd, " Codecs: ");
print_codec_to_cli(fd, &prefs);
ast_cli(fd, "\n");
ast_cli(fd, " Relax DTMF: %s\n", relaxdtmf ? "Yes" : "No");
ast_cli(fd, " Compact SIP headers: %s\n", compactheaders ? "Yes" : "No");
ast_cli(fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
ast_cli(fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
ast_cli(fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
ast_cli(fd, " DNS SRV lookup: %s\n", srvlookup ? "Yes" : "No");
ast_cli(fd, " Pedantic SIP support: %s\n", pedanticsipchecking ? "Yes" : "No");
ast_cli(fd, " Reg. max duration: %d secs\n", max_expiry);
ast_cli(fd, " Reg. default duration: %d secs\n", default_expiry);
ast_cli(fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
ast_cli(fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
ast_cli(fd, " Notify ringing state: %s\n", global_notifyringing ? "Yes" : "No");
ast_cli(fd, "\nDefault Settings:\n");
ast_cli(fd, "-----------------\n");
ast_cli(fd, " Context: %s\n", default_context);
ast_cli(fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags, SIP_NAT)));
ast_cli(fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags, SIP_DTMF)));
ast_cli(fd, " Qualify: %d\n", default_qualify);
ast_cli(fd, " Use ClientCode: %s\n", ast_test_flag(&global_flags, SIP_USECLIENTCODE) ? "Yes" : "No");
ast_cli(fd, " Progress inband: %s\n", (ast_test_flag(&global_flags, SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER) ? "Never" : (ast_test_flag(&global_flags, SIP_PROG_INBAND) == SIP_PROG_INBAND_NO) ? "No" : "Yes" );
ast_cli(fd, " Language: %s\n", ast_strlen_zero(default_language) ? "(Defaults to English)" : default_language);
ast_cli(fd, " Musicclass: %s\n", global_musicclass);
ast_cli(fd, " Voice Mail Extension: %s\n", global_vmexten);
if (realtimepeers || realtimeusers) {
ast_cli(fd, "\nRealtime SIP Settings:\n");
ast_cli(fd, "----------------------\n");
ast_cli(fd, " Realtime Peers: %s\n", realtimepeers ? "Yes" : "No");
ast_cli(fd, " Realtime Users: %s\n", realtimeusers ? "Yes" : "No");
ast_cli(fd, " Cache Friends: %s\n", ast_test_flag(&global_flags_page2, SIP_PAGE2_RTCACHEFRIENDS) ? "Yes" : "No");
ast_cli(fd, " Update: %s\n", ast_test_flag(&global_flags_page2, SIP_PAGE2_RTUPDATE) ? "Yes" : "No");
ast_cli(fd, " Ignore Reg. Expire: %s\n", ast_test_flag(&global_flags_page2, SIP_PAGE2_IGNOREREGEXPIRE) ? "Yes" : "No");
ast_cli(fd, " Auto Clear: %d\n", global_rtautoclear);
}
ast_cli(fd, "\n----\n");
return RESULT_SUCCESS;
}
/*! \brief subscription_type2str: Show subscription type in string format */
static const char *subscription_type2str(enum subscriptiontype subtype) {
int i;
for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
if (subscription_types[i].type == subtype) {
return subscription_types[i].text;
}
}
return subscription_types[0].text;
}
/*! \brief find_subscription_type: Find subscription type in array */
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype) {
int i;
for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
if (subscription_types[i].type == subtype) {
return &subscription_types[i];
}
}
return &subscription_types[0];
}
/* Forward declaration */
static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
/*! \brief sip_show_channels: Show active SIP channels ---*/
static int sip_show_channels(int fd, int argc, char *argv[])
{
return __sip_show_channels(fd, argc, argv, 0);
}
/*! \brief sip_show_subscriptions: Show active SIP subscriptions ---*/
static int sip_show_subscriptions(int fd, int argc, char *argv[])
{
return __sip_show_channels(fd, argc, argv, 1);
}
static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions)
{
#define FORMAT3 "%-15.15s %-10.10s %-11.11s %-15.15s %-13.13s %-15.15s\n"
#define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-4.4s %-7.7s %-15.15s\n"
#define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-4.4s %-3.3s %-3.3s %-15.15s\n"
struct sip_pvt *cur;
char iabuf[INET_ADDRSTRLEN];
int numchans = 0;
if (argc != 3)
return RESULT_SHOWUSAGE;
ast_mutex_lock(&iflock);
cur = iflist;
if (!subscriptions)
ast_cli(fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format", "Hold", "Last Message");
else
ast_cli(fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type");
while (cur) {
if (cur->subscribed == NONE && !subscriptions) {
ast_cli(fd, FORMAT, ast_inet_ntoa(iabuf, sizeof(iabuf), cur->sa.sin_addr),
ast_strlen_zero(cur->username) ? ( ast_strlen_zero(cur->cid_num) ? "(None)" : cur->cid_num ) : cur->username,
cur->callid,
cur->ocseq, cur->icseq,
ast_getformatname(cur->owner ? cur->owner->nativeformats : 0),
ast_test_flag(cur, SIP_CALL_ONHOLD) ? "Yes" : "No",
ast_test_flag(cur, SIP_NEEDDESTROY) ? "(d)" : "",
cur->lastmsg );
numchans++;
}
if (cur->subscribed != NONE && subscriptions) {
ast_cli(fd, FORMAT3, ast_inet_ntoa(iabuf, sizeof(iabuf), cur->sa.sin_addr),
ast_strlen_zero(cur->username) ? ( ast_strlen_zero(cur->cid_num) ? "(None)" : cur->cid_num ) : cur->username,
cur->callid, cur->exten, ast_extension_state2str(cur->laststate),
subscription_type2str(cur->subscribed));
numchans++;
}
cur = cur->next;
}
ast_mutex_unlock(&iflock);
if (!subscriptions)
ast_cli(fd, "%d active SIP channel%s\n", numchans, (numchans != 1) ? "s" : "");
else
ast_cli(fd, "%d active SIP subscription%s\n", numchans, (numchans != 1) ? "s" : "");
return RESULT_SUCCESS;
#undef FORMAT
#undef FORMAT2
#undef FORMAT3
}
/*! \brief complete_sipch: Support routine for 'sip show channel' CLI ---*/
static char *complete_sipch(char *line, char *word, int pos, int state)
{
int which=0;
struct sip_pvt *cur;
char *c = NULL;
ast_mutex_lock(&iflock);
cur = iflist;
while(cur) {
if (!strncasecmp(word, cur->callid, strlen(word))) {
if (++which > state) {
c = strdup(cur->callid);
break;
}
}
cur = cur->next;
}
ast_mutex_unlock(&iflock);
return c;
}
/*! \brief complete_sip_peer: Do completion on peer name ---*/
static char *complete_sip_peer(char *word, int state, int flags2)
{
char *result = NULL;
int wordlen = strlen(word);
int which = 0;
ASTOBJ_CONTAINER_TRAVERSE(&peerl, !result, do {
/* locking of the object is not required because only the name and flags are being compared */
if (!strncasecmp(word, iterator->name, wordlen)) {
if (flags2 && !ast_test_flag((&iterator->flags_page2), flags2))
continue;
if (++which > state) {
result = strdup(iterator->name);
}
}
} while(0) );
return result;
}
/*! \brief complete_sip_show_peer: Support routine for 'sip show peer' CLI ---*/
static char *complete_sip_show_peer(char *line, char *word, int pos, int state)
{
if (pos == 3)
return complete_sip_peer(word, state, 0);
return NULL;
}
/*! \brief complete_sip_debug_peer: Support routine for 'sip debug peer' CLI ---*/
static char *complete_sip_debug_peer(char *line, char *word, int pos, int state)
{
if (pos == 3)
return complete_sip_peer(word, state, 0);
return NULL;
}
/*! \brief complete_sip_user: Do completion on user name ---*/
static char *complete_sip_user(char *word, int state, int flags2)
{
char *result = NULL;
int wordlen = strlen(word);
int which = 0;
ASTOBJ_CONTAINER_TRAVERSE(&userl, !result, do {
/* locking of the object is not required because only the name and flags are being compared */
if (!strncasecmp(word, iterator->name, wordlen)) {
if (flags2 && !ast_test_flag(&(iterator->flags_page2), flags2))
continue;
if (++which > state) {
result = strdup(iterator->name);
}
}
} while(0) );
return result;
}
/*! \brief complete_sip_show_user: Support routine for 'sip show user' CLI ---*/
static char *complete_sip_show_user(char *line, char *word, int pos, int state)
{
if (pos == 3)
return complete_sip_user(word, state, 0);
return NULL;
}
/*! \brief complete_sipnotify: Support routine for 'sip notify' CLI ---*/
static char *complete_sipnotify(char *line, char *word, int pos, int state)
{
char *c = NULL;
if (pos == 2) {
int which = 0;
char *cat;
/* do completion for notify type */
if (!notify_types)
return NULL;
cat = ast_category_browse(notify_types, NULL);
while(cat) {
if (!strncasecmp(word, cat, strlen(word))) {
if (++which > state) {
c = strdup(cat);
break;
}
}
cat = ast_category_browse(notify_types, cat);
}
return c;
}
if (pos > 2)
return complete_sip_peer(word, state, 0);
return NULL;
}
/*! \brief complete_sip_prune_realtime_peer: Support routine for 'sip prune realtime peer' CLI ---*/
static char *complete_sip_prune_realtime_peer(char *line, char *word, int pos, int state)
{
if (pos == 4)
return complete_sip_peer(word, state, SIP_PAGE2_RTCACHEFRIENDS);
return NULL;
}
/*! \brief complete_sip_prune_realtime_user: Support routine for 'sip prune realtime user' CLI ---*/
static char *complete_sip_prune_realtime_user(char *line, char *word, int pos, int state)
{
if (pos == 4)
return complete_sip_user(word, state, SIP_PAGE2_RTCACHEFRIENDS);
return NULL;
}
/*! \brief sip_show_channel: Show details of one call ---*/
static int sip_show_channel(int fd, int argc, char *argv[])
{
struct sip_pvt *cur;
char iabuf[INET_ADDRSTRLEN];
size_t len;
int found = 0;
if (argc != 4)
return RESULT_SHOWUSAGE;
len = strlen(argv[3]);
ast_mutex_lock(&iflock);
cur = iflist;
while(cur) {
if (!strncasecmp(cur->callid, argv[3],len)) {
ast_cli(fd,"\n");
if (cur->subscribed != NONE)
ast_cli(fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
else
ast_cli(fd, " * SIP Call\n");
ast_cli(fd, " Direction: %s\n", ast_test_flag(cur, SIP_OUTGOING)?"Outgoing":"Incoming");
ast_cli(fd, " Call-ID: %s\n", cur->callid);
ast_cli(fd, " Our Codec Capability: %d\n", cur->capability);
ast_cli(fd, " Non-Codec Capability: %d\n", cur->noncodeccapability);
ast_cli(fd, " Their Codec Capability: %d\n", cur->peercapability);
ast_cli(fd, " Joint Codec Capability: %d\n", cur->jointcapability);
ast_cli(fd, " Format %s\n", ast_getformatname(cur->owner ? cur->owner->nativeformats : 0) );
ast_cli(fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), cur->sa.sin_addr), ntohs(cur->sa.sin_port));
ast_cli(fd, " Received Address: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), cur->recv.sin_addr), ntohs(cur->recv.sin_port));
ast_cli(fd, " NAT Support: %s\n", nat2str(ast_test_flag(cur, SIP_NAT)));
ast_cli(fd, " Audio IP: %s %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), cur->redirip.sin_addr.s_addr ? cur->redirip.sin_addr : cur->ourip), cur->redirip.sin_addr.s_addr ? "(Outside bridge)" : "(local)" );
ast_cli(fd, " Our Tag: %s\n", cur->tag);
ast_cli(fd, " Their Tag: %s\n", cur->theirtag);
ast_cli(fd, " SIP User agent: %s\n", cur->useragent);
if (!ast_strlen_zero(cur->username))
ast_cli(fd, " Username: %s\n", cur->username);
if (!ast_strlen_zero(cur->peername))
ast_cli(fd, " Peername: %s\n", cur->peername);
if (!ast_strlen_zero(cur->uri))
ast_cli(fd, " Original uri: %s\n", cur->uri);
if (!ast_strlen_zero(cur->cid_num))
ast_cli(fd, " Caller-ID: %s\n", cur->cid_num);
ast_cli(fd, " Need Destroy: %d\n", ast_test_flag(cur, SIP_NEEDDESTROY));
ast_cli(fd, " Last Message: %s\n", cur->lastmsg);
ast_cli(fd, " Promiscuous Redir: %s\n", ast_test_flag(cur, SIP_PROMISCREDIR) ? "Yes" : "No");
ast_cli(fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
ast_cli(fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(cur, SIP_DTMF)));
ast_cli(fd, " SIP Options: ");
if (cur->sipoptions) {
int x;
for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
if (cur->sipoptions & sip_options[x].id)
ast_cli(fd, "%s ", sip_options[x].text);
}
} else
ast_cli(fd, "(none)\n");
ast_cli(fd, "\n\n");
found++;
}
cur = cur->next;
}
ast_mutex_unlock(&iflock);
if (!found)
ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
return RESULT_SUCCESS;
}
/*! \brief sip_show_history: Show history details of one call ---*/
static int sip_show_history(int fd, int argc, char *argv[])
{
struct sip_pvt *cur;
struct sip_history *hist;
size_t len;
int x;
int found = 0;
if (argc != 4)
return RESULT_SHOWUSAGE;
if (!recordhistory)
ast_cli(fd, "\n***Note: History recording is currently DISABLED. Use 'sip history' to ENABLE.\n");
len = strlen(argv[3]);
ast_mutex_lock(&iflock);
cur = iflist;
while(cur) {
if (!strncasecmp(cur->callid, argv[3], len)) {
ast_cli(fd,"\n");
if (cur->subscribed != NONE)
ast_cli(fd, " * Subscription\n");
else
ast_cli(fd, " * SIP Call\n");
x = 0;
hist = cur->history;
while(hist) {
x++;
ast_cli(fd, "%d. %s\n", x, hist->event);
hist = hist->next;
}
if (!x)
ast_cli(fd, "Call '%s' has no history\n", cur->callid);
found++;
}
cur = cur->next;
}
ast_mutex_unlock(&iflock);
if (!found)
ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
return RESULT_SUCCESS;
}
/*! \brief dump_history: Dump SIP history to debug log file at end of
lifespan for SIP dialog */
void sip_dump_history(struct sip_pvt *dialog)
{
int x;
struct sip_history *hist;
if (!dialog)
return;
ast_log(LOG_DEBUG, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
if (dialog->subscribed)
ast_log(LOG_DEBUG, " * Subscription\n");
else
ast_log(LOG_DEBUG, " * SIP Call\n");
x = 0;
hist = dialog->history;
while(hist) {
x++;
ast_log(LOG_DEBUG, " %d. %s\n", x, hist->event);
hist = hist->next;
}
if (!x)
ast_log(LOG_DEBUG, "Call '%s' has no history\n", dialog->callid);
ast_log(LOG_DEBUG, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
}
/*! \brief handle_request_info: Receive SIP INFO Message ---*/
/* Doesn't read the duration of the DTMF signal */
static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
{
char buf[1024];
unsigned int event;
char *c;
/* Need to check the media/type */
if (!strcasecmp(get_header(req, "Content-Type"), "application/dtmf-relay") ||
!strcasecmp(get_header(req, "Content-Type"), "application/vnd.nortelnetworks.digits")) {
/* Try getting the "signal=" part */
if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
transmit_response(p, "200 OK", req); /* Should return error */
return;
} else {
ast_copy_string(buf, c, sizeof(buf));
}
if (!p->owner) { /* not a PBX call */
transmit_response(p, "481 Call leg/transaction does not exist", req);
ast_set_flag(p, SIP_NEEDDESTROY);
return;
}
if (ast_strlen_zero(buf)) {
transmit_response(p, "200 OK", req);
return;
}
if (buf[0] == '*')
event = 10;
else if (buf[0] == '#')
event = 11;
else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
event = 12 + buf[0] - 'A';
else
event = atoi(buf);
if (event == 16) {
/* send a FLASH event */
struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
ast_queue_frame(p->owner, &f);
if (sipdebug)
ast_verbose("* DTMF-relay event received: FLASH\n");
} else {
/* send a DTMF event */
struct ast_frame f = { AST_FRAME_DTMF, };
if (event < 10) {
f.subclass = '0' + event;
} else if (event < 11) {
f.subclass = '*';
} else if (event < 12) {
f.subclass = '#';
} else if (event < 16) {
f.subclass = 'A' + (event - 12);
}
ast_queue_frame(p->owner, &f);
if (sipdebug)
ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
}
transmit_response(p, "200 OK", req);
return;
} else if (!strcasecmp(get_header(req, "Content-Type"), "application/media_control+xml")) {
/* Eh, we'll just assume it's a fast picture update for now */
if (p->owner)
ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
transmit_response(p, "200 OK", req);
return;
} else if ((c = get_header(req, "X-ClientCode"))) {
/* Client code (from SNOM phone) */
if (ast_test_flag(p, SIP_USECLIENTCODE)) {
if (p->owner && p->owner->cdr)
ast_cdr_setuserfield(p->owner, c);
if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
transmit_response(p, "200 OK", req);
} else {
transmit_response(p, "403 Unauthorized", req);
}
return;
}
/* Other type of INFO message, not really understood by Asterisk */
/* if (get_msg_text(buf, sizeof(buf), req)) { */
ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
transmit_response(p, "415 Unsupported media type", req);
return;
}
/*! \brief sip_do_debug: Enable SIP Debugging in CLI ---*/
static int sip_do_debug_ip(int fd, int argc, char *argv[])
{
struct hostent *hp;
struct ast_hostent ahp;
char iabuf[INET_ADDRSTRLEN];
int port = 0;
char *p, *arg;
if (argc != 4)
return RESULT_SHOWUSAGE;
arg = argv[3];
p = strstr(arg, ":");
if (p) {
*p = '\0';
p++;
port = atoi(p);
}
hp = ast_gethostbyname(arg, &ahp);
if (hp == NULL) {
return RESULT_SHOWUSAGE;
}
debugaddr.sin_family = AF_INET;
memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
debugaddr.sin_port = htons(port);
if (port == 0)
ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), debugaddr.sin_addr));
else
ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), debugaddr.sin_addr), port);
sipdebug |= SIP_DEBUG_CONSOLE;
return RESULT_SUCCESS;
}
/*! \brief sip_do_debug_peer: Turn on SIP debugging with peer mask */
static int sip_do_debug_peer(int fd, int argc, char *argv[])
{
struct sip_peer *peer;
char iabuf[INET_ADDRSTRLEN];
if (argc != 4)
return RESULT_SHOWUSAGE;
peer = find_peer(argv[3], NULL, 1);
if (peer) {
if (peer->addr.sin_addr.s_addr) {
debugaddr.sin_family = AF_INET;
memcpy(&debugaddr.sin_addr, &peer->addr.sin_addr, sizeof(debugaddr.sin_addr));
debugaddr.sin_port = peer->addr.sin_port;
ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), debugaddr.sin_addr), ntohs(debugaddr.sin_port));
sipdebug |= SIP_DEBUG_CONSOLE;
} else
ast_cli(fd, "Unable to get IP address of peer '%s'\n", argv[3]);
ASTOBJ_UNREF(peer,sip_destroy_peer);
} else
ast_cli(fd, "No such peer '%s'\n", argv[3]);
return RESULT_SUCCESS;
}
/*! \brief sip_do_debug: Turn on SIP debugging (CLI command) */
static int sip_do_debug(int fd, int argc, char *argv[])
{
int oldsipdebug = sipdebug & SIP_DEBUG_CONSOLE;
if (argc != 2) {
if (argc != 4)
return RESULT_SHOWUSAGE;
else if (strncmp(argv[2], "ip\0", 3) == 0)
return sip_do_debug_ip(fd, argc, argv);
else if (strncmp(argv[2], "peer\0", 5) == 0)
return sip_do_debug_peer(fd, argc, argv);
else return RESULT_SHOWUSAGE;
}
sipdebug |= SIP_DEBUG_CONSOLE;
memset(&debugaddr, 0, sizeof(debugaddr));
if (oldsipdebug)
ast_cli(fd, "SIP Debugging re-enabled\n");
else
ast_cli(fd, "SIP Debugging enabled\n");
return RESULT_SUCCESS;
}
/*! \brief sip_notify: Send SIP notify to peer */
static int sip_notify(int fd, int argc, char *argv[])
{
struct ast_variable *varlist;
int i;
if (argc < 4)
return RESULT_SHOWUSAGE;
if (!notify_types) {
ast_cli(fd, "No %s file found, or no types listed there\n", notify_config);
return RESULT_FAILURE;
}
varlist = ast_variable_browse(notify_types, argv[2]);
if (!varlist) {
ast_cli(fd, "Unable to find notify type '%s'\n", argv[2]);
return RESULT_FAILURE;
}
for (i = 3; i < argc; i++) {
struct sip_pvt *p;
struct sip_request req;
struct ast_variable *var;
p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY);
if (!p) {
ast_log(LOG_WARNING, "Unable to build sip pvt data for notify\n");
return RESULT_FAILURE;
}
if (create_addr(p, argv[i])) {
/* Maybe they're not registered, etc. */
sip_destroy(p);
ast_cli(fd, "Could not create address for '%s'\n", argv[i]);
continue;
}
initreqprep(&req, p, SIP_NOTIFY);
for (var = varlist; var; var = var->next)
add_header(&req, var->name, var->value);
add_blank_header(&req);
/* Recalculate our side, and recalculate Call ID */
if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
build_via(p, p->via, sizeof(p->via));
build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
ast_cli(fd, "Sending NOTIFY of type '%s' to '%s'\n", argv[2], argv[i]);
transmit_sip_request(p, &req);
sip_scheddestroy(p, 15000);
}
return RESULT_SUCCESS;
}
/*! \brief sip_do_history: Enable SIP History logging (CLI) ---*/
static int sip_do_history(int fd, int argc, char *argv[])
{
if (argc != 2) {
return RESULT_SHOWUSAGE;
}
recordhistory = 1;
ast_cli(fd, "SIP History Recording Enabled (use 'sip show history')\n");
return RESULT_SUCCESS;
}
/*! \brief sip_no_history: Disable SIP History logging (CLI) ---*/
static int sip_no_history(int fd, int argc, char *argv[])
{
if (argc != 3) {
return RESULT_SHOWUSAGE;
}
recordhistory = 0;
ast_cli(fd, "SIP History Recording Disabled\n");
return RESULT_SUCCESS;
}
/*! \brief sip_no_debug: Disable SIP Debugging in CLI ---*/
static int sip_no_debug(int fd, int argc, char *argv[])
{
if (argc != 3)
return RESULT_SHOWUSAGE;
sipdebug &= ~SIP_DEBUG_CONSOLE;
ast_cli(fd, "SIP Debugging Disabled\n");
return RESULT_SUCCESS;
}
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
/*! \brief do_register_auth: Authenticate for outbound registration ---*/
static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader)
{
char digest[1024];
p->authtries++;
memset(digest,0,sizeof(digest));
if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
/* There's nothing to use for authentication */
/* No digest challenge in request */
if (sip_debug_test_pvt(p) && p->registry)
ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
/* No old challenge */
return -1;
}
if (recordhistory) {
char tmp[80];
snprintf(tmp, sizeof(tmp), "Try: %d", p->authtries);
append_history(p, "RegistryAuth", tmp);
}
if (sip_debug_test_pvt(p) && p->registry)
ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
}
/*! \brief do_proxy_auth: Add authentication on outbound SIP packet ---*/
static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init)
{
char digest[1024];
if (!p->options) {
p->options = calloc(1, sizeof(*p->options));
if (!p->options) {
ast_log(LOG_ERROR, "Out of memory\n");
return -2;
}
}
p->authtries++;
if (option_debug > 1)
ast_log(LOG_DEBUG, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
memset(digest, 0, sizeof(digest));
if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
/* No way to authenticate */
return -1;
}
/* Now we have a reply digest */
p->options->auth = digest;
p->options->authheader = respheader;
return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
}
/*! \brief reply_digest: reply to authentication for outbound registrations ---*/
/* This is used for register= servers in sip.conf, SIP proxies we register
with for receiving calls from. */
/* Returns -1 if we have no auth */
static int reply_digest(struct sip_pvt *p, struct sip_request *req,
char *header, int sipmethod, char *digest, int digest_len)
{
char tmp[512];
char *c;
char oldnonce[256];
/* table of recognised keywords, and places where they should be copied */
const struct x {
const char *key;
char *dst;
int dstlen;
} *i, keys[] = {
{ "realm=", p->realm, sizeof(p->realm) },
{ "nonce=", p->nonce, sizeof(p->nonce) },
{ "opaque=", p->opaque, sizeof(p->opaque) },
{ "qop=", p->qop, sizeof(p->qop) },
{ "domain=", p->domain, sizeof(p->domain) },
{ NULL, NULL, 0 },
};
ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
if (ast_strlen_zero(tmp))
return -1;
if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
ast_log(LOG_WARNING, "missing Digest.\n");
return -1;
}
c = tmp + strlen("Digest ");
for (i = keys; i->key != NULL; i++)
i->dst[0] = '\0'; /* init all to empty strings */
ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
for (i = keys; i->key != NULL; i++) {
char *src, *separator;
if (strncasecmp(c, i->key, strlen(i->key)) != 0)
continue;
/* Found. Skip keyword, take text in quotes or up to the separator. */
c += strlen(i->key);
if (*c == '\"') {
src = ++c;
separator = "\"";
} else {
src = c;
separator = ",";
}
strsep(&c, separator); /* clear separator and move ptr */
ast_copy_string(i->dst, src, i->dstlen);
break;
}
if (i->key == NULL) /* not found, try ',' */
strsep(&c, ",");
}
/* Reset nonce count */
if (strcmp(p->nonce, oldnonce))
p->noncecount = 0;
/* Save auth data for following registrations */
if (p->registry) {
struct sip_registry *r = p->registry;
if (strcmp(r->nonce, p->nonce)) {
ast_copy_string(r->realm, p->realm, sizeof(r->realm));
ast_copy_string(r->nonce, p->nonce, sizeof(r->nonce));
ast_copy_string(r->domain, p->domain, sizeof(r->domain));
ast_copy_string(r->opaque, p->opaque, sizeof(r->opaque));
ast_copy_string(r->qop, p->qop, sizeof(r->qop));
r->noncecount = 0;
}
}
return build_reply_digest(p, sipmethod, digest, digest_len);
}
/*! \brief build_reply_digest: Build reply digest ---*/
/* Build digest challenge for authentication of peers (for registration)
and users (for calls). Also used for authentication of CANCEL and BYE */
/* Returns -1 if we have no auth */
static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
{
char a1[256];
char a2[256];
char a1_hash[256];
char a2_hash[256];
char resp[256];
char resp_hash[256];
char uri[256];
char cnonce[80];
char iabuf[INET_ADDRSTRLEN];
char *username;
char *secret;
char *md5secret;
struct sip_auth *auth = (struct sip_auth *) NULL; /* Realm authentication */
if (!ast_strlen_zero(p->domain))
ast_copy_string(uri, p->domain, sizeof(uri));
else if (!ast_strlen_zero(p->uri))
ast_copy_string(uri, p->uri, sizeof(uri));
else
snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr));
snprintf(cnonce, sizeof(cnonce), "%08x", thread_safe_rand());
/* Check if we have separate auth credentials */
if ((auth = find_realm_authentication(authl, p->realm))) {
username = auth->username;
secret = auth->secret;
md5secret = auth->md5secret;
if (sipdebug)
ast_log(LOG_DEBUG,"Using realm %s authentication for call %s\n", p->realm, p->callid);
} else {
/* No authentication, use peer or register= config */
username = p->authname;
secret = p->peersecret;
md5secret = p->peermd5secret;
}
if (ast_strlen_zero(username)) /* We have no authentication */
return -1;
/* Calculate SIP digest response */
snprintf(a1,sizeof(a1),"%s:%s:%s", username, p->realm, secret);
snprintf(a2,sizeof(a2),"%s:%s", sip_methods[method].text, uri);
if (!ast_strlen_zero(md5secret))
ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
else
ast_md5_hash(a1_hash,a1);
ast_md5_hash(a2_hash,a2);
p->noncecount++;
if (!ast_strlen_zero(p->qop))
snprintf(resp,sizeof(resp),"%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
else
snprintf(resp,sizeof(resp),"%s:%s:%s", a1_hash, p->nonce, a2_hash);
ast_md5_hash(resp_hash, resp);
/* XXX We hard code our qop to "auth" for now. XXX */
if (!ast_strlen_zero(p->qop))
snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\", qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, p->opaque, cnonce, p->noncecount);
else
snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\"", username, p->realm, uri, p->nonce, resp_hash, p->opaque);
return 0;
}
static char show_domains_usage[] =
"Usage: sip show domains\n"
" Lists all configured SIP local domains.\n"
" Asterisk only responds to SIP messages to local domains.\n";
static char notify_usage[] =
"Usage: sip notify <type> <peer> [<peer>...]\n"
" Send a NOTIFY message to a SIP peer or peers\n"
" Message types are defined in sip_notify.conf\n";
static char show_users_usage[] =
"Usage: sip show users [like <pattern>]\n"
" Lists all known SIP users.\n"
" Optional regular expression pattern is used to filter the user list.\n";
static char show_user_usage[] =
"Usage: sip show user <name> [load]\n"
" Lists all details on one SIP user and the current status.\n"
" Option \"load\" forces lookup of peer in realtime storage.\n";
static char show_inuse_usage[] =
"Usage: sip show inuse [all]\n"
" List all SIP users and peers usage counters and limits.\n"
" Add option \"all\" to show all devices, not only those with a limit.\n";
static char show_channels_usage[] =
"Usage: sip show channels\n"
" Lists all currently active SIP channels.\n";
static char show_channel_usage[] =
"Usage: sip show channel <channel>\n"
" Provides detailed status on a given SIP channel.\n";
static char show_history_usage[] =
"Usage: sip show history <channel>\n"
" Provides detailed dialog history on a given SIP channel.\n";
static char show_peers_usage[] =
"Usage: sip show peers [like <pattern>]\n"
" Lists all known SIP peers.\n"
" Optional regular expression pattern is used to filter the peer list.\n";
static char show_peer_usage[] =
"Usage: sip show peer <name> [load]\n"
" Lists all details on one SIP peer and the current status.\n"
" Option \"load\" forces lookup of peer in realtime storage.\n";
static char prune_realtime_usage[] =
"Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
" Prunes object(s) from the cache.\n"
" Optional regular expression pattern is used to filter the objects.\n";
static char show_reg_usage[] =
"Usage: sip show registry\n"
" Lists all registration requests and status.\n";
static char debug_usage[] =
"Usage: sip debug\n"
" Enables dumping of SIP packets for debugging purposes\n\n"
" sip debug ip <host[:PORT]>\n"
" Enables dumping of SIP packets to and from host.\n\n"
" sip debug peer <peername>\n"
" Enables dumping of SIP packets to and from host.\n"
" Require peer to be registered.\n";
static char no_debug_usage[] =
"Usage: sip no debug\n"
" Disables dumping of SIP packets for debugging purposes\n";
static char no_history_usage[] =
"Usage: sip no history\n"
" Disables recording of SIP dialog history for debugging purposes\n";
static char history_usage[] =
"Usage: sip history\n"
" Enables recording of SIP dialog history for debugging purposes.\n"
"Use 'sip show history' to view the history of a call number.\n";
static char sip_reload_usage[] =
"Usage: sip reload\n"
" Reloads SIP configuration from sip.conf\n";
static char show_subscriptions_usage[] =
"Usage: sip show subscriptions\n"
" Shows active SIP subscriptions for extension states\n";
static char show_objects_usage[] =
"Usage: sip show objects\n"
" Shows status of known SIP objects\n";
static char show_settings_usage[] =
"Usage: sip show settings\n"
" Provides detailed list of the configuration of the SIP channel.\n";
/*! \brief func_header_read: Read SIP header (dialplan function) */
static char *func_header_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
{
struct sip_pvt *p;
char *content;
if (!data) {
ast_log(LOG_WARNING, "This function requires a header name.\n");
return NULL;
}
ast_mutex_lock(&chan->lock);
if (chan->type != channeltype) {
ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
ast_mutex_unlock(&chan->lock);
return NULL;
}
p = chan->tech_pvt;
/* If there is no private structure, this channel is no longer alive */
if (!p) {
ast_mutex_unlock(&chan->lock);
return NULL;
}
content = get_header(&p->initreq, data);
if (ast_strlen_zero(content)) {
ast_mutex_unlock(&chan->lock);
return NULL;
}
ast_copy_string(buf, content, len);
ast_mutex_unlock(&chan->lock);
return buf;
}
static struct ast_custom_function sip_header_function = {
.name = "SIP_HEADER",
.synopsis = "Gets the specified SIP header",
.syntax = "SIP_HEADER(<name>)",
.read = func_header_read,
};
/*! \brief function_check_sipdomain: Dial plan function to check if domain is local */
static char *func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
{
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
return buf;
}
if (check_sip_domain(data, NULL, 0))
ast_copy_string(buf, data, len);
else
buf[0] = '\0';
return buf;
}
static struct ast_custom_function checksipdomain_function = {
.name = "CHECKSIPDOMAIN",
.synopsis = "Checks if domain is a local domain",
.syntax = "CHECKSIPDOMAIN(<domain|IP>)",
.read = func_check_sipdomain,
.desc = "This function checks if the domain in the argument is configured\n"
"as a local SIP domain that this Asterisk server is configured to handle.\n"
"Returns the domain name if it is locally handled, otherwise an empty string.\n"
"Check the domain= configuration in sip.conf\n",
};
/*! \brief function_sippeer: ${SIPPEER()} Dialplan function - reads peer data */
static char *function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
{
char *ret = NULL;
struct sip_peer *peer;
char *peername, *colname;
char iabuf[INET_ADDRSTRLEN];
if (!(peername = ast_strdupa(data))) {
ast_log(LOG_ERROR, "Memory Error!\n");
return ret;
}
if ((colname = strchr(peername, ':'))) {
*colname = '\0';
colname++;
} else {
colname = "ip";
}
if (!(peer = find_peer(peername, NULL, 1)))
return ret;
if (!strcasecmp(colname, "ip")) {
ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "", len);
} else if (!strcasecmp(colname, "status")) {
peer_status(peer, buf, len);
} else if (!strcasecmp(colname, "language")) {
ast_copy_string(buf, peer->language, len);
} else if (!strcasecmp(colname, "regexten")) {
ast_copy_string(buf, peer->regexten, len);
} else if (!strcasecmp(colname, "limit")) {
snprintf(buf, len, "%d", peer->call_limit);
} else if (!strcasecmp(colname, "curcalls")) {
snprintf(buf, len, "%d", peer->inUse);
} else if (!strcasecmp(colname, "accountcode")) {
ast_copy_string(buf, peer->accountcode, len);
} else if (!strcasecmp(colname, "useragent")) {
ast_copy_string(buf, peer->useragent, len);
} else if (!strcasecmp(colname, "mailbox")) {
ast_copy_string(buf, peer->mailbox, len);
} else if (!strcasecmp(colname, "context")) {
ast_copy_string(buf, peer->context, len);
} else if (!strcasecmp(colname, "expire")) {
snprintf(buf, len, "%d", peer->expire);
} else if (!strcasecmp(colname, "dynamic")) {
ast_copy_string(buf, (ast_test_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC) ? "yes" : "no"), len);
} else if (!strcasecmp(colname, "callerid_name")) {
ast_copy_string(buf, peer->cid_name, len);
} else if (!strcasecmp(colname, "callerid_num")) {
ast_copy_string(buf, peer->cid_num, len);
} else if (!strcasecmp(colname, "codecs")) {
ast_getformatname_multiple(buf, len -1, peer->capability);
} else if (!strncasecmp(colname, "codec[", 6)) {
char *codecnum, *ptr;
int index = 0, codec = 0;
codecnum = strchr(colname, '[');
*codecnum = '\0';
codecnum++;
if ((ptr = strchr(codecnum, ']'))) {
*ptr = '\0';
}
index = atoi(codecnum);
if((codec = ast_codec_pref_index(&peer->prefs, index))) {
ast_copy_string(buf, ast_getformatname(codec), len);
}
}
ret = buf;
ASTOBJ_UNREF(peer, sip_destroy_peer);
return ret;
}
/* Structure to declare a dialplan function: SIPPEER */
struct ast_custom_function sippeer_function = {
.name = "SIPPEER",
.synopsis = "Gets SIP peer information",
.syntax = "SIPPEER(<peername>[:item])",
.read = function_sippeer,
.desc = "Valid items are:\n"
"- ip (default) The IP address.\n"
"- mailbox The configured mailbox.\n"
"- context The configured context.\n"
"- expire The epoch time of the next expire.\n"
"- dynamic Is it dynamic? (yes/no).\n"
"- callerid_name The configured Caller ID name.\n"
"- callerid_num The configured Caller ID number.\n"
"- codecs The configured codecs.\n"
"- status Status (if qualify=yes).\n"
"- regexten Registration extension\n"
"- limit Call limit (call-limit)\n"
"- curcalls Current amount of calls \n"
" Only available if call-limit is set\n"
"- language Default language for peer\n"
"- accountcode Account code for this peer\n"
"- useragent Current user agent id for peer\n"
"- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
"\n"
};
/*! \brief function_sipchaninfo_read: ${SIPCHANINFO()} Dialplan function - reads sip channel data */
static char *function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
{
struct sip_pvt *p;
char iabuf[INET_ADDRSTRLEN];
*buf = 0;
if (!data) {
ast_log(LOG_WARNING, "This function requires a parameter name.\n");
return NULL;
}
ast_mutex_lock(&chan->lock);
if (chan->type != channeltype) {
ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
ast_mutex_unlock(&chan->lock);
return NULL;
}
/* ast_verbose("function_sipchaninfo_read: %s\n", data); */
p = chan->tech_pvt;
/* If there is no private structure, this channel is no longer alive */
if (!p) {
ast_mutex_unlock(&chan->lock);
return NULL;
}
if (!strcasecmp(data, "peerip")) {
ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr) : "", len);
} else if (!strcasecmp(data, "recvip")) {
ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr) : "", len);
} else if (!strcasecmp(data, "from")) {
ast_copy_string(buf, p->from, len);
} else if (!strcasecmp(data, "uri")) {
ast_copy_string(buf, p->uri, len);
} else if (!strcasecmp(data, "useragent")) {
ast_copy_string(buf, p->useragent, len);
} else if (!strcasecmp(data, "peername")) {
ast_copy_string(buf, p->peername, len);
} else {
ast_mutex_unlock(&chan->lock);
return NULL;
}
ast_mutex_unlock(&chan->lock);
return buf;
}
/* Structure to declare a dialplan function: SIPCHANINFO */
static struct ast_custom_function sipchaninfo_function = {
.name = "SIPCHANINFO",
.synopsis = "Gets the specified SIP parameter from the current channel",
.syntax = "SIPCHANINFO(item)",
.read = function_sipchaninfo_read,
.desc = "Valid items are:\n"
"- peerip The IP address of the peer.\n"
"- recvip The source IP address of the peer.\n"
"- from The URI from the From: header.\n"
"- uri The URI from the Contact: header.\n"
"- useragent The useragent.\n"
"- peername The name of the peer.\n"
};
/*! \brief parse_moved_contact: Parse 302 Moved temporalily response */
static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
{
char tmp[256];
char *s, *e;
ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
s = get_in_brackets(tmp);
e = strchr(s, ';');
if (e)
*e = '\0';
if (ast_test_flag(p, SIP_PROMISCREDIR)) {
if (!strncasecmp(s, "sip:", 4))
s += 4;
e = strchr(s, '/');
if (e)
*e = '\0';
ast_log(LOG_DEBUG, "Found promiscuous redirection to 'SIP/%s'\n", s);
if (p->owner)
snprintf(p->owner->call_forward, sizeof(p->owner->call_forward), "SIP/%s", s);
} else {
e = strchr(tmp, '@');
if (e)
*e = '\0';
e = strchr(tmp, '/');
if (e)
*e = '\0';
if (!strncasecmp(s, "sip:", 4))
s += 4;
ast_log(LOG_DEBUG, "Found 302 Redirect to extension '%s'\n", s);
if (p->owner)
ast_copy_string(p->owner->call_forward, s, sizeof(p->owner->call_forward));
}
}
/*! \brief check_pendings: Check pending actions on SIP call ---*/
static void check_pendings(struct sip_pvt *p)
{
if (ast_test_flag(p, SIP_PENDINGBYE)) {
/* if we can't BYE, then this is really a pending CANCEL */
if (!ast_test_flag(p, SIP_CAN_BYE))
transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, 1, 0);
/* Actually don't destroy us yet, wait for the 487 on our original
INVITE, but do set an autodestruct just in case we never get it. */
else
transmit_request_with_auth(p, SIP_BYE, 0, 1, 1);
ast_clear_flag(p, SIP_PENDINGBYE);
sip_scheddestroy(p, 32000);
} else if (ast_test_flag(p, SIP_NEEDREINVITE)) {
ast_log(LOG_DEBUG, "Sending pending reinvite on '%s'\n", p->callid);
/* Didn't get to reinvite yet, so do it now */
transmit_reinvite_with_sdp(p);
ast_clear_flag(p, SIP_NEEDREINVITE);
}
}
/*! \brief handle_response_invite: Handle SIP response in dialogue ---*/
static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
{
int outgoing = ast_test_flag(p, SIP_OUTGOING);
if (option_debug > 3) {
int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
if (reinvite)
ast_log(LOG_DEBUG, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
else
ast_log(LOG_DEBUG, "SIP response %d to standard invite\n", resp);
}
if (ast_test_flag(p, SIP_ALREADYGONE)) { /* This call is already gone */
ast_log(LOG_DEBUG, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
return;
}
/* RFC3261 says we must treat every 1xx response (but not 100)
that we don't recognize as if it was 183.
*/
if ((resp > 100) &&
(resp < 200) &&
(resp != 180) &&
(resp != 183))
resp = 183;
switch (resp) {
case 100: /* Trying */
if (!ignore)
sip_cancel_destroy(p);
check_pendings(p);
break;
case 180: /* 180 Ringing */
if (!ignore)
sip_cancel_destroy(p);
if (!ignore && p->owner) {
ast_queue_control(p->owner, AST_CONTROL_RINGING);
if (p->owner->_state != AST_STATE_UP)
ast_setstate(p->owner, AST_STATE_RINGING);
}
if (find_sdp(req)) {
process_sdp(p, req);
if (!ignore && p->owner) {
/* Queue a progress frame only if we have SDP in 180 */
ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
}
}
ast_set_flag(p, SIP_CAN_BYE);
check_pendings(p);
break;
case 183: /* Session progress */
if (!ignore)
sip_cancel_destroy(p);
/* Ignore 183 Session progress without SDP */
if (find_sdp(req)) {
process_sdp(p, req);
if (!ignore && p->owner) {
/* Queue a progress frame */
ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
}
}
ast_set_flag(p, SIP_CAN_BYE);
check_pendings(p);
break;
case 200: /* 200 OK on invite - someone's answering our call */
if (!ignore)
sip_cancel_destroy(p);
p->authtries = 0;
if (find_sdp(req)) {
process_sdp(p, req);
}
/* Parse contact header for continued conversation */
/* When we get 200 OK, we know which device (and IP) to contact for this call */
/* This is important when we have a SIP proxy between us and the phone */
if (outgoing) {
parse_ok_contact(p, req);
/* Save Record-Route for any later requests we make on this dialogue */
build_route(p, req, 1);
}
if (!ignore && p->owner) {
if (p->owner->_state != AST_STATE_UP) {
#ifdef OSP_SUPPORT
time(&p->ospstart);
#endif
ast_queue_control(p->owner, AST_CONTROL_ANSWER);
} else { /* RE-invite */
struct ast_frame af = { AST_FRAME_NULL, };
ast_queue_frame(p->owner, &af);
}
} else {
/* It's possible we're getting an ACK after we've tried to disconnect
by sending CANCEL */
/* THIS NEEDS TO BE CHECKED: OEJ */
if (!ignore)
ast_set_flag(p, SIP_PENDINGBYE);
}
/* If I understand this right, the branch is different for a non-200 ACK only */
transmit_request(p, SIP_ACK, seqno, 0, 1);
ast_set_flag(p, SIP_CAN_BYE);
check_pendings(p);
break;
case 407: /* Proxy authentication */
case 401: /* Www auth */
/* First we ACK */
transmit_request(p, SIP_ACK, seqno, 0, 0);
if (p->options)
p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
/* Then we AUTH */
p->theirtag[0]='\0'; /* forget their old tag, so we don't match tags when getting response */
if (!ignore) {
char *authenticate = (resp == 401 ? "WWW-Authenticate" : "Proxy-Authenticate");
char *authorization = (resp == 401 ? "Authorization" : "Proxy-Authorization");
if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, authenticate, authorization, SIP_INVITE, 1)) {
ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
ast_set_flag(p, SIP_NEEDDESTROY);
ast_set_flag(p, SIP_ALREADYGONE);
if (p->owner)
ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
}
}
break;
case 403: /* Forbidden */
/* First we ACK */
transmit_request(p, SIP_ACK, seqno, 0, 0);
ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for INVITE to '%s'\n", get_header(&p->initreq, "From"));
if (!ignore && p->owner)
ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
ast_set_flag(p, SIP_NEEDDESTROY);
ast_set_flag(p, SIP_ALREADYGONE);
break;
case 404: /* Not found */
transmit_request(p, SIP_ACK, seqno, 0, 0);
if (p->owner && !ignore)
ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
ast_set_flag(p, SIP_ALREADYGONE);
break;
case 481: /* Call leg does not exist */
/* Could be REFER or INVITE */
ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
transmit_request(p, SIP_ACK, seqno, 0, 0);
break;
case 491: /* Pending */
/* we have to wait a while, then retransmit */
/* Transmission is rescheduled, so everything should be taken care of.
We should support the retry-after at some point */
break;
case 501: /* Not implemented */
if (p->owner)
ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
break;
}
}
/*! \brief handle_response_register: Handle responses on REGISTER to services ---*/
static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
{
int expires, expires_ms;
struct sip_registry *r;
r=p->registry;
switch (resp) {
case 401: /* Unauthorized */
if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "WWW-Authenticate", "Authorization")) {
ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
ast_set_flag(p, SIP_NEEDDESTROY);
}
break;
case 403: /* Forbidden */
ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
if (global_regattempts_max)
p->registry->regattempts = global_regattempts_max+1;
ast_sched_del(sched, r->timeout);
ast_set_flag(p, SIP_NEEDDESTROY);
break;
case 404: /* Not found */
ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username,p->registry->hostname);
if (global_regattempts_max)
p->registry->regattempts = global_regattempts_max+1;
ast_set_flag(p, SIP_NEEDDESTROY);
r->call = NULL;
ast_sched_del(sched, r->timeout);
break;
case 407: /* Proxy auth */
if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization")) {
ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
ast_set_flag(p, SIP_NEEDDESTROY);
}
break;
case 479: /* SER: Not able to process the URI - address is wrong in register*/
ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username,p->registry->hostname);
if (global_regattempts_max)
p->registry->regattempts = global_regattempts_max+1;
ast_set_flag(p, SIP_NEEDDESTROY);
r->call = NULL;
ast_sched_del(sched, r->timeout);
break;
case 200: /* 200 OK */
if (!r) {
ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
ast_set_flag(p, SIP_NEEDDESTROY);
return 0;
}
r->regstate=REG_STATE_REGISTERED;
manager_event(EVENT_FLAG_SYSTEM, "Registry", "Channel: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
r->regattempts = 0;
ast_log(LOG_DEBUG, "Registration successful\n");
if (r->timeout > -1) {
ast_log(LOG_DEBUG, "Cancelling timeout %d\n", r->timeout);
ast_sched_del(sched, r->timeout);
}
r->timeout=-1;
r->call = NULL;
p->registry = NULL;
/* Let this one hang around until we have all the responses */
sip_scheddestroy(p, 32000);
/* ast_set_flag(p, SIP_NEEDDESTROY); */
/* set us up for re-registering */
/* figure out how long we got registered for */
if (r->expire > -1)
ast_sched_del(sched, r->expire);
/* according to section 6.13 of RFC, contact headers override
expires headers, so check those first */
expires = 0;
if (!ast_strlen_zero(get_header(req, "Contact"))) {
char *contact = NULL;
char *tmptmp = NULL;
int start = 0;
for(;;) {
contact = __get_header(req, "Contact", &start);
/* this loop ensures we get a contact header about our register request */
if(!ast_strlen_zero(contact)) {
if( (tmptmp=strstr(contact, p->our_contact))) {
contact=tmptmp;
break;
}
} else
break;
}
tmptmp = strcasestr(contact, "expires=");
if (tmptmp) {
if (sscanf(tmptmp + 8, "%d;", &expires) != 1)
expires = 0;
}
}
if (!expires)
expires=atoi(get_header(req, "expires"));
if (!expires)
expires=default_expiry;
expires_ms = expires * 1000;
if (expires <= EXPIRY_GUARD_LIMIT)
expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT),EXPIRY_GUARD_MIN);
else
expires_ms -= EXPIRY_GUARD_SECS * 1000;
if (sipdebug)
ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
r->refresh= (int) expires_ms / 1000;
/* Schedule re-registration before we expire */
r->expire=ast_sched_add(sched, expires_ms, sip_reregister, r);
ASTOBJ_UNREF(r, sip_registry_destroy);
}
return 1;
}
/*! \brief handle_response_peerpoke: Handle qualification responses (OPTIONS) */
static int handle_response_peerpoke(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno, int sipmethod)
{
struct sip_peer *peer;
int pingtime;
struct timeval tv;
if (resp != 100) {
int statechanged = 0;
int newstate = 0;
peer = p->peerpoke;
gettimeofday(&tv, NULL);
pingtime = ast_tvdiff_ms(tv, peer->ps);
if (pingtime < 1)
pingtime = 1;
if ((peer->lastms < 0) || (peer->lastms > peer->maxms)) {
if (pingtime <= peer->maxms) {
ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! (%dms / %dms)\n", peer->name, pingtime, peer->maxms);
statechanged = 1;
newstate = 1;
}
} else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
if (pingtime > peer->maxms) {
ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED! (%dms / %dms)\n", peer->name, pingtime, peer->maxms);
statechanged = 1;
newstate = 2;
}
}
if (!peer->lastms)
statechanged = 1;
peer->lastms = pingtime;
peer->call = NULL;
if (statechanged) {
ast_device_state_changed("SIP/%s", peer->name);
if (newstate == 2) {
manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer->name, pingtime);
} else {
manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer->name, pingtime);
}
}
if (peer->pokeexpire > -1)
ast_sched_del(sched, peer->pokeexpire);
if (sipmethod == SIP_INVITE) /* Does this really happen? */
transmit_request(p, SIP_ACK, seqno, 0, 0);
ast_set_flag(p, SIP_NEEDDESTROY);
/* Try again eventually */
if ((peer->lastms < 0) || (peer->lastms > peer->maxms))
peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
else
peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, sip_poke_peer_s, peer);
}
return 1;
}
/*! \brief handle_response: Handle SIP response in dialogue ---*/
static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
{
char *msg, *c;
struct ast_channel *owner;
char iabuf[INET_ADDRSTRLEN];
int sipmethod;
int res = 1;
c = get_header(req, "Cseq");
msg = strchr(c, ' ');
if (!msg)
msg = "";
else
msg++;
sipmethod = find_sip_method(msg);
owner = p->owner;
if (owner)
owner->hangupcause = hangup_sip2cause(resp);
/* Acknowledge whatever it is destined for */
if ((resp >= 100) && (resp <= 199))
__sip_semi_ack(p, seqno, 0, sipmethod);
else
__sip_ack(p, seqno, 0, sipmethod);
/* Get their tag if we haven't already */
if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
gettag(req, "To", p->theirtag, sizeof(p->theirtag));
}
if (p->peerpoke) {
/* We don't really care what the response is, just that it replied back.
Well, as long as it's not a 100 response... since we might
need to hang around for something more "definitive" */
res = handle_response_peerpoke(p, resp, rest, req, ignore, seqno, sipmethod);
} else if (ast_test_flag(p, SIP_OUTGOING)) {
/* Acknowledge sequence number */
if (p->initid > -1) {
/* Don't auto congest anymore since we've gotten something useful back */
ast_sched_del(sched, p->initid);
p->initid = -1;
}
switch(resp) {
case 100: /* 100 Trying */
if (sipmethod == SIP_INVITE)
handle_response_invite(p, resp, rest, req, ignore, seqno);
break;
case 183: /* 183 Session Progress */
if (sipmethod == SIP_INVITE)
handle_response_invite(p, resp, rest, req, ignore, seqno);
break;
case 180: /* 180 Ringing */
if (sipmethod == SIP_INVITE)
handle_response_invite(p, resp, rest, req, ignore, seqno);
break;
case 200: /* 200 OK */
p->authtries = 0; /* Reset authentication counter */
if (sipmethod == SIP_MESSAGE) {
/* We successfully transmitted a message */
ast_set_flag(p, SIP_NEEDDESTROY);
} else if (sipmethod == SIP_NOTIFY) {
/* They got the notify, this is the end */
if (p->owner) {
ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
ast_queue_hangup(p->owner);
} else {
if (p->subscribed == NONE) {
ast_set_flag(p, SIP_NEEDDESTROY);
}
}
} else if (sipmethod == SIP_INVITE) {
handle_response_invite(p, resp, rest, req, ignore, seqno);
} else if (sipmethod == SIP_REGISTER) {
res = handle_response_register(p, resp, rest, req, ignore, seqno);
} else if (sipmethod == SIP_BYE) {
/* Ok, we're ready to go */
ast_set_flag(p, SIP_NEEDDESTROY);
}
break;
case 401: /* Not www-authorized on SIP method */
if (sipmethod == SIP_INVITE) {
handle_response_invite(p, resp, rest, req, ignore, seqno);
} else if (p->registry && sipmethod == SIP_REGISTER) {
res = handle_response_register(p, resp, rest, req, ignore, seqno);
} else {
ast_log(LOG_WARNING, "Got authentication request (401) on unknown %s to '%s'\n", sip_methods[sipmethod].text, get_header(req, "To"));
ast_set_flag(p, SIP_NEEDDESTROY);
}
break;
case 403: /* Forbidden - we failed authentication */
if (sipmethod == SIP_INVITE) {
handle_response_invite(p, resp, rest, req, ignore, seqno);
} else if (p->registry && sipmethod == SIP_REGISTER) {
res = handle_response_register(p, resp, rest, req, ignore, seqno);
} else {
ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for %s\n", msg);
}
break;
case 404: /* Not found */
if (p->registry && sipmethod == SIP_REGISTER) {
res = handle_response_register(p, resp, rest, req, ignore, seqno);
} else if (sipmethod == SIP_INVITE) {
handle_response_invite(p, resp, rest, req, ignore, seqno);
} else if (owner)
ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
break;
case 407: /* Proxy auth required */
if (sipmethod == SIP_INVITE) {
handle_response_invite(p, resp, rest, req, ignore, seqno);
} else if (sipmethod == SIP_BYE || sipmethod == SIP_REFER) {
if (ast_strlen_zero(p->authname))
ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
msg, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
ast_set_flag(p, SIP_NEEDDESTROY);
if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", sipmethod, 0)) {
ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
ast_set_flag(p, SIP_NEEDDESTROY);
}
} else if (p->registry && sipmethod == SIP_REGISTER) {
res = handle_response_register(p, resp, rest, req, ignore, seqno);
} else /* We can't handle this, giving up in a bad way */
ast_set_flag(p, SIP_NEEDDESTROY);
break;
case 491: /* Pending */
if (sipmethod == SIP_INVITE) {
handle_response_invite(p, resp, rest, req, ignore, seqno);
}
case 501: /* Not Implemented */
if (sipmethod == SIP_INVITE) {
handle_response_invite(p, resp, rest, req, ignore, seqno);
} else
ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), msg);
break;
default:
if ((resp >= 300) && (resp < 700)) {
if ((option_verbose > 2) && (resp != 487))
ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr));
ast_set_flag(p, SIP_ALREADYGONE);
if (p->rtp) {
/* Immediately stop RTP */
ast_rtp_stop(p->rtp);
}
if (p->vrtp) {
/* Immediately stop VRTP */
ast_rtp_stop(p->vrtp);
}
/* XXX Locking issues?? XXX */
switch(resp) {
case 300: /* Multiple Choices */
case 301: /* Moved permenantly */
case 302: /* Moved temporarily */
case 305: /* Use Proxy */
parse_moved_contact(p, req);
/* Fall through */
case 486: /* Busy here */
case 600: /* Busy everywhere */
case 603: /* Decline */
if (p->owner)
ast_queue_control(p->owner, AST_CONTROL_BUSY);
break;
case 487:
/* channel now destroyed - dec the inUse counter */
if (owner)
ast_queue_hangup(p->owner);
update_call_counter(p, DEC_CALL_LIMIT);
break;
case 482: /* SIP is incapable of performing a hairpin call, which
is yet another failure of not having a layer 2 (again, YAY
IETF for thinking ahead). So we treat this as a call
forward and hope we end up at the right place... */
ast_log(LOG_DEBUG, "Hairpin detected, setting up call forward for what it's worth\n");
if (p->owner)
snprintf(p->owner->call_forward, sizeof(p->owner->call_forward), "Local/%s@%s", p->username, p->context);
/* Fall through */
case 488: /* Not acceptable here - codec error */
case 480: /* Temporarily Unavailable */
case 404: /* Not Found */
case 410: /* Gone */
case 400: /* Bad Request */
case 500: /* Server error */
case 503: /* Service Unavailable */
if (owner)
ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
break;
default:
/* Send hangup */
if (owner)
ast_queue_hangup(p->owner);
break;
}
/* ACK on invite */
if (sipmethod == SIP_INVITE)
transmit_request(p, SIP_ACK, seqno, 0, 0);
ast_set_flag(p, SIP_ALREADYGONE);
if (!p->owner)
ast_set_flag(p, SIP_NEEDDESTROY);
} else if ((resp >= 100) && (resp < 200)) {
if (sipmethod == SIP_INVITE) {
if (!ignore)
sip_cancel_destroy(p);
if (find_sdp(req))
process_sdp(p, req);
if (p->owner) {
/* Queue a progress frame */
ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
}
}
} else
ast_log(LOG_NOTICE, "Dont know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr));
}
} else {
/* Responses to OUTGOING SIP requests on INCOMING calls
get handled here. As well as out-of-call message responses */
if (req->debug)
ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
if (resp == 200) {
/* Tags in early session is replaced by the tag in 200 OK, which is
the final reply to our INVITE */
gettag(req, "To", p->theirtag, sizeof(p->theirtag));
}
switch(resp) {
case 200:
if (sipmethod == SIP_INVITE) {
handle_response_invite(p, resp, rest, req, ignore, seqno);
} else if (sipmethod == SIP_CANCEL) {
ast_log(LOG_DEBUG, "Got 200 OK on CANCEL\n");
} else if (sipmethod == SIP_MESSAGE)
/* We successfully transmitted a message */
ast_set_flag(p, SIP_NEEDDESTROY);
else if (sipmethod == SIP_BYE)
/* Ok, we're ready to go */
ast_set_flag(p, SIP_NEEDDESTROY);
break;
case 401: /* www-auth */
case 407:
if (sipmethod == SIP_BYE || sipmethod == SIP_REFER) {
char *auth, *auth2;
if (resp == 407) {
auth = "Proxy-Authenticate";
auth2 = "Proxy-Authorization";
} else {
auth = "WWW-Authenticate";
auth2 = "Authorization";
}
if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, auth, auth2, sipmethod, 0)) {
ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
ast_set_flag(p, SIP_NEEDDESTROY);
}
} else if (sipmethod == SIP_INVITE) {
handle_response_invite(p, resp, rest, req, ignore, seqno);
}
break;
case 481: /* Call leg does not exist */
if (sipmethod == SIP_INVITE) {
/* Re-invite failed */
handle_response_invite(p, resp, rest, req, ignore, seqno);
}
break;
default: /* Errors without handlers */
if ((resp >= 100) && (resp < 200)) {
if (sipmethod == SIP_INVITE && !ignore) /* re-invite */
sip_cancel_destroy(p);
}
if ((resp >= 300) && (resp < 700)) {
if ((option_verbose > 2) && (resp != 487))
ast_verbose(VERBOSE_PREFIX_3 "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr));
switch(resp) {
case 488: /* Not acceptable here - codec error */
case 603: /* Decline */
case 500: /* Server error */
case 503: /* Service Unavailable */
if (sipmethod == SIP_INVITE && !ignore) { /* re-invite failed */
sip_cancel_destroy(p);
}
break;
}
}
break;
}
}
}
struct sip_dual {
struct ast_channel *chan1;
struct ast_channel *chan2;
struct sip_request req;
};
/*! \brief sip_park_thread: Park SIP call support function */
static void *sip_park_thread(void *stuff)
{
struct ast_channel *chan1, *chan2;
struct sip_dual *d;
struct sip_request req;
int ext;
int res;
d = stuff;
chan1 = d->chan1;
chan2 = d->chan2;
copy_request(&req, &d->req);
free(d);
ast_mutex_lock(&chan1->lock);
ast_do_masquerade(chan1);
ast_mutex_unlock(&chan1->lock);
res = ast_park_call(chan1, chan2, 0, &ext);
/* Then hangup */
ast_hangup(chan2);
ast_log(LOG_DEBUG, "Parked on extension '%d'\n", ext);
return NULL;
}
/*! \brief sip_park: Park a call ---*/
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req)
{
struct sip_dual *d;
struct ast_channel *chan1m, *chan2m;
pthread_t th;
chan1m = ast_channel_alloc(0);
chan2m = ast_channel_alloc(0);
if ((!chan2m) || (!chan1m)) {
if (chan1m)
ast_hangup(chan1m);
if (chan2m)
ast_hangup(chan2m);
return -1;
}
snprintf(chan1m->name, sizeof(chan1m->name), "Parking/%s", chan1->name);
/* Make formats okay */
chan1m->readformat = chan1->readformat;
chan1m->writeformat = chan1->writeformat;
ast_channel_masquerade(chan1m, chan1);
/* Setup the extensions and such */
ast_copy_string(chan1m->context, chan1->context, sizeof(chan1m->context));
ast_copy_string(chan1m->exten, chan1->exten, sizeof(chan1m->exten));
chan1m->priority = chan1->priority;
/* We make a clone of the peer channel too, so we can play
back the announcement */
snprintf(chan2m->name, sizeof (chan2m->name), "SIPPeer/%s",chan2->name);
/* Make formats okay */
chan2m->readformat = chan2->readformat;
chan2m->writeformat = chan2->writeformat;
ast_channel_masquerade(chan2m, chan2);
/* Setup the extensions and such */
ast_copy_string(chan2m->context, chan2->context, sizeof(chan2m->context));
ast_copy_string(chan2m->exten, chan2->exten, sizeof(chan2m->exten));
chan2m->priority = chan2->priority;
ast_mutex_lock(&chan2m->lock);
if (ast_do_masquerade(chan2m)) {
ast_log(LOG_WARNING, "Masquerade failed :(\n");
ast_mutex_unlock(&chan2m->lock);
ast_hangup(chan2m);
return -1;
}
ast_mutex_unlock(&chan2m->lock);
d = malloc(sizeof(struct sip_dual));
if (d) {
memset(d, 0, sizeof(*d));
/* Save original request for followup */
copy_request(&d->req, req);
d->chan1 = chan1m;
d->chan2 = chan2m;
if (!ast_pthread_create(&th, NULL, sip_park_thread, d))
return 0;
free(d);
}
return -1;
}
/*! \brief ast_quiet_chan: Turn off generator data */
static void ast_quiet_chan(struct ast_channel *chan)
{
if (chan && chan->_state == AST_STATE_UP) {
if (chan->generatordata)
ast_deactivate_generator(chan);
}
}
/*! \brief attempt_transfer: Attempt transfer of SIP call ---*/
static int attempt_transfer(struct sip_pvt *p1, struct sip_pvt *p2)
{
int res = 0;
struct ast_channel
*chana = NULL,
*chanb = NULL,
*bridgea = NULL,
*bridgeb = NULL,
*peera = NULL,
*peerb = NULL,
*peerc = NULL,
*peerd = NULL;
if (!p1->owner || !p2->owner) {
ast_log(LOG_WARNING, "Transfer attempted without dual ownership?\n");
return -1;
}
chana = p1->owner;
chanb = p2->owner;
bridgea = ast_bridged_channel(chana);
bridgeb = ast_bridged_channel(chanb);
if (bridgea) {
peera = chana;
peerb = chanb;
peerc = bridgea;
peerd = bridgeb;
} else if (bridgeb) {
peera = chanb;
peerb = chana;
peerc = bridgeb;
peerd = bridgea;
}
if (peera && peerb && peerc && (peerb != peerc)) {
ast_quiet_chan(peera);
ast_quiet_chan(peerb);
ast_quiet_chan(peerc);
ast_quiet_chan(peerd);
if (peera->cdr && peerb->cdr) {
peerb->cdr = ast_cdr_append(peerb->cdr, peera->cdr);
} else if (peera->cdr) {
peerb->cdr = peera->cdr;
}
peera->cdr = NULL;
if (peerb->cdr && peerc->cdr) {
peerb->cdr = ast_cdr_append(peerb->cdr, peerc->cdr);
} else if (peerc->cdr) {
peerb->cdr = peerc->cdr;
}
peerc->cdr = NULL;
if (ast_channel_masquerade(peerb, peerc)) {
ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
res = -1;
}
return res;
} else {
ast_log(LOG_NOTICE, "Transfer attempted with no appropriate bridged calls to transfer\n");
if (chana)
ast_softhangup_nolock(chana, AST_SOFTHANGUP_DEV);
if (chanb)
ast_softhangup_nolock(chanb, AST_SOFTHANGUP_DEV);
return -1;
}
return 0;
}
/*! \brief gettag: Get tag from packet */
static char *gettag(struct sip_request *req, char *header, char *tagbuf, int tagbufsize)
{
char *thetag, *sep;
if (!tagbuf)
return NULL;
tagbuf[0] = '\0'; /* reset the buffer */
thetag = get_header(req, header);
thetag = strcasestr(thetag, ";tag=");
if (thetag) {
thetag += 5;
ast_copy_string(tagbuf, thetag, tagbufsize);
sep = strchr(tagbuf, ';');
if (sep)
*sep = '\0';
}
return thetag;
}
/*! \brief handle_request_options: Handle incoming OPTIONS request */
static int handle_request_options(struct sip_pvt *p, struct sip_request *req, int debug)
{
int res;
res = get_destination(p, req);
build_contact(p);
/* XXX Should we authenticate OPTIONS? XXX */
if (ast_strlen_zero(p->context))
strcpy(p->context, default_context);
if (res < 0)
transmit_response_with_allow(p, "404 Not Found", req, 0);
else if (res > 0)
transmit_response_with_allow(p, "484 Address Incomplete", req, 0);
else
transmit_response_with_allow(p, "200 OK", req, 0);
/* Destroy if this OPTIONS was the opening request, but not if
it's in the middle of a normal call flow. */
if (!p->lastinvite)
ast_set_flag(p, SIP_NEEDDESTROY);
return res;
}
/*! \brief handle_request_invite: Handle incoming INVITE request */
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin, int *recount, char *e)
{
int res = 1;
struct ast_channel *c=NULL;
int gotdest;
struct ast_frame af = { AST_FRAME_NULL, };
char *supported;
char *required;
unsigned int required_profile = 0;
/* Find out what they support */
if (!p->sipoptions) {
supported = get_header(req, "Supported");
if (supported)
parse_sip_options(p, supported);
}
required = get_header(req, "Require");
if (!ast_strlen_zero(required)) {
required_profile = parse_sip_options(NULL, required);
if (required_profile) { /* They require something */
/* At this point we support no extensions, so fail */
transmit_response_with_unsupported(p, "420 Bad extension", req, required);
if (!p->lastinvite)
ast_set_flag(p, SIP_NEEDDESTROY);
return -1;
}
}
/* Check if this is a loop */
/* This happens since we do not properly support SIP domain
handling yet... -oej */
if (ast_test_flag(p, SIP_OUTGOING) && p->owner && (p->owner->_state != AST_STATE_UP)) {
/* This is a call to ourself. Send ourselves an error code and stop
processing immediately, as SIP really has no good mechanism for
being able to call yourself */
transmit_response(p, "482 Loop Detected", req);
/* We do NOT destroy p here, so that our response will be accepted */
return 0;
}
if (!ignore) {
/* Use this as the basis */
if (debug)
ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
sip_cancel_destroy(p);
/* This call is no longer outgoing if it ever was */
ast_clear_flag(p, SIP_OUTGOING);
/* This also counts as a pending invite */
p->pendinginvite = seqno;
copy_request(&p->initreq, req);
check_via(p, req);
if (p->owner) {
/* Handle SDP here if we already have an owner */
if (find_sdp(req)) {
if (process_sdp(p, req)) {
transmit_response(p, "488 Not acceptable here", req);
if (!p->lastinvite)
ast_set_flag(p, SIP_NEEDDESTROY);
return -1;
}
} else {
p->jointcapability = p->capability;
ast_log(LOG_DEBUG, "Hm.... No sdp for the moment\n");
}
}
} else if (debug)
ast_verbose("Ignoring this INVITE request\n");
if (!p->lastinvite && !ignore && !p->owner) {
/* Handle authentication if this is our first invite */
res = check_user(p, req, SIP_INVITE, e, 1, sin, ignore);
/* if an authentication challenge was sent, we are done here */
if (res > 0)
return 0;
if (res < 0) {
if (res == -4) {
ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
transmit_fake_auth_response(p, req, p->randdata, sizeof(p->randdata), 1);
} else {
ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
if (ignore)
transmit_response(p, "403 Forbidden", req);
else
transmit_response_reliable(p, "403 Forbidden", req, 1);
}
ast_set_flag(p, SIP_NEEDDESTROY);
p->theirtag[0] = '\0'; /* Forget their to-tag, we'll get a new one */
return 0;
}
/* Process the SDP portion */
if (find_sdp(req)) {
if (process_sdp(p, req)) {
transmit_response(p, "488 Not acceptable here", req);
ast_set_flag(p, SIP_NEEDDESTROY);
return -1;
}
} else {
p->jointcapability = p->capability;
ast_log(LOG_DEBUG, "Hm.... No sdp for the moment\n");
}
/* Queue NULL frame to prod ast_rtp_bridge if appropriate */
if (p->owner)
ast_queue_frame(p->owner, &af);
/* Initialize the context if it hasn't been already */
if (ast_strlen_zero(p->context))
strcpy(p->context, default_context);
/* Check number of concurrent calls -vs- incoming limit HERE */
ast_log(LOG_DEBUG, "Checking SIP call limits for device %s\n", p->username);
res = update_call_counter(p, INC_CALL_LIMIT);
if (res) {
if (res < 0) {
ast_log(LOG_NOTICE, "Failed to place call for user %s, too many calls\n", p->username);
if (ignore)
transmit_response(p, "480 Temporarily Unavailable (Call limit)", req);
else
transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req, 1);
ast_set_flag(p, SIP_NEEDDESTROY);
}
return 0;
}
/* Get destination right away */
gotdest = get_destination(p, NULL);
get_rdnis(p, NULL);
extract_uri(p, req);
build_contact(p);
if (gotdest) {
if (gotdest < 0) {
if (ignore)
transmit_response(p, "404 Not Found", req);
else
transmit_response_reliable(p, "404 Not Found", req, 1);
update_call_counter(p, DEC_CALL_LIMIT);
} else {
if (ignore)
transmit_response(p, "484 Address Incomplete", req);
else
transmit_response_reliable(p, "484 Address Incomplete", req, 1);
update_call_counter(p, DEC_CALL_LIMIT);
}
ast_set_flag(p, SIP_NEEDDESTROY);
} else {
/* If no extension was specified, use the s one */
if (ast_strlen_zero(p->exten))
ast_copy_string(p->exten, "s", sizeof(p->exten));
/* Initialize tag */
make_our_tag(p->tag, sizeof(p->tag));
/* First invitation */
c = sip_new(p, AST_STATE_DOWN, ast_strlen_zero(p->username) ? NULL : p->username );
*recount = 1;
/* Save Record-Route for any later requests we make on this dialogue */
build_route(p, req, 0);
if (c) {
/* Pre-lock the call */
ast_mutex_lock(&c->lock);
}
}
} else {
if (option_debug > 1 && sipdebug)
ast_log(LOG_DEBUG, "Got a SIP re-invite for call %s\n", p->callid);
c = p->owner;
}
if (!ignore && p)
p->lastinvite = seqno;
if (c) {
#ifdef OSP_SUPPORT
ast_channel_setwhentohangup (c, p->osptimelimit);
#endif
switch(c->_state) {
case AST_STATE_DOWN:
transmit_response(p, "100 Trying", req);
ast_setstate(c, AST_STATE_RING);
if (strcmp(p->exten, ast_pickup_ext())) {
enum ast_pbx_result res;
res = ast_pbx_start(c);
switch (res) {
case AST_PBX_FAILED:
ast_log(LOG_WARNING, "Failed to start PBX :(\n");
if (ignore)
transmit_response(p, "503 Unavailable", req);
else
transmit_response_reliable(p, "503 Unavailable", req, 1);
break;
case AST_PBX_CALL_LIMIT:
ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
if (ignore)
transmit_response(p, "480 Temporarily Unavailable", req);
else
transmit_response_reliable(p, "480 Temporarily Unavailable", req, 1);
break;
case AST_PBX_SUCCESS:
/* nothing to do */
break;
}
if (res) {
ast_log(LOG_WARNING, "Failed to start PBX :(\n");
/* Unlock locks so ast_hangup can do its magic */
ast_mutex_unlock(&c->lock);
ast_mutex_unlock(&p->lock);
ast_hangup(c);
ast_mutex_lock(&p->lock);
c = NULL;
}
} else {
ast_mutex_unlock(&c->lock);
if (ast_pickup_call(c)) {
ast_log(LOG_NOTICE, "Nothing to pick up\n");
if (ignore)
transmit_response(p, "503 Unavailable", req);
else
transmit_response_reliable(p, "503 Unavailable", req, 1);
ast_set_flag(p, SIP_ALREADYGONE);
/* Unlock locks so ast_hangup can do its magic */
ast_mutex_unlock(&p->lock);
ast_hangup(c);
ast_mutex_lock(&p->lock);
c = NULL;
} else {
ast_mutex_unlock(&p->lock);
ast_setstate(c, AST_STATE_DOWN);
ast_hangup(c);
ast_mutex_lock(&p->lock);
c = NULL;
}
}
break;
case AST_STATE_RING:
transmit_response(p, "100 Trying", req);
break;
case AST_STATE_RINGING:
transmit_response(p, "180 Ringing", req);
break;
case AST_STATE_UP:
transmit_response_with_sdp(p, "200 OK", req, 1);
break;
default:
ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
transmit_response(p, "100 Trying", req);
}
} else {
if (p && !ast_test_flag(p, SIP_NEEDDESTROY) && !ignore) {
if (!p->jointcapability) {
if (ignore)
transmit_response(p, "488 Not Acceptable Here (codec error)", req);
else
transmit_response_reliable(p, "488 Not Acceptable Here (codec error)", req, 1);
ast_set_flag(p, SIP_NEEDDESTROY);
} else {
ast_log(LOG_NOTICE, "Unable to create/find channel\n");
if (ignore)
transmit_response(p, "503 Unavailable", req);
else
transmit_response_reliable(p, "503 Unavailable", req, 1);
ast_set_flag(p, SIP_NEEDDESTROY);
}
}
}
return res;
}
/*! \brief handle_request_refer: Handle incoming REFER request ---*/
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock)
{
struct ast_channel *c=NULL;
int res;
struct ast_channel *transfer_to;
char *transfercontext = NULL;
if (option_debug > 2)
ast_log(LOG_DEBUG, "SIP call transfer received for call %s (REFER)!\n", p->callid);
res = get_refer_info(p, req, &transfercontext);
if (ast_strlen_zero(p->context))
strcpy(p->context, default_context);
if (ast_strlen_zero(transfercontext))
transfercontext = p->context;
if (res < 0)
transmit_response(p, "603 Declined", req);
else if (res > 0)
transmit_response(p, "484 Address Incomplete", req);
else {
int nobye = 0;
if (!ignore) {
if (p->refer_call) {
ast_log(LOG_DEBUG,"202 Accepted (supervised)\n");
attempt_transfer(p, p->refer_call);
if (p->refer_call->owner)
ast_mutex_unlock(&p->refer_call->owner->lock);
ast_mutex_unlock(&p->refer_call->lock);
p->refer_call = NULL;
ast_set_flag(p, SIP_GOTREFER);
} else {
ast_log(LOG_DEBUG,"202 Accepted (blind)\n");
c = p->owner;
if (c) {
transfer_to = ast_bridged_channel(c);
if (transfer_to) {
ast_log(LOG_DEBUG, "Got SIP blind transfer, applying to '%s'\n", transfer_to->name);
ast_moh_stop(transfer_to);
if (!strcmp(p->refer_to, ast_parking_ext())) {
/* Must release c's lock now, because it will not longer
be accessible after the transfer! */
*nounlock = 1;
ast_mutex_unlock(&c->lock);
sip_park(transfer_to, c, req);
nobye = 1;
} else {
/* Must release c's lock now, because it will not longer
be accessible after the transfer! */
*nounlock = 1;
ast_mutex_unlock(&c->lock);
ast_async_goto(transfer_to, transfercontext, p->refer_to,1);
}
} else {
ast_log(LOG_DEBUG, "Got SIP blind transfer but nothing to transfer to.\n");
ast_queue_hangup(p->owner);
}
}
ast_set_flag(p, SIP_GOTREFER);
}
transmit_response(p, "202 Accepted", req);
transmit_notify_with_sipfrag(p, seqno);
/* Always increment on a BYE */
if (!nobye) {
transmit_request_with_auth(p, SIP_BYE, 0, 1, 1);
ast_set_flag(p, SIP_ALREADYGONE);
}
}
}
return res;
}
/*! \brief handle_request_cancel: Handle incoming CANCEL request ---*/
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req, int debug, int ignore)
{
check_via(p, req);
ast_set_flag(p, SIP_ALREADYGONE);
if (p->rtp) {
/* Immediately stop RTP */
ast_rtp_stop(p->rtp);
}
if (p->vrtp) {
/* Immediately stop VRTP */
ast_rtp_stop(p->vrtp);
}
if (p->owner)
ast_queue_hangup(p->owner);
else
ast_set_flag(p, SIP_NEEDDESTROY);
if (p->initreq.len > 0) {
if (!ignore)
transmit_response_reliable(p, "487 Request Terminated", &p->initreq, 1);
transmit_response(p, "200 OK", req);
return 1;
} else {
transmit_response(p, "481 Call Leg Does Not Exist", req);
return 0;
}
}
/*! \brief handle_request_bye: Handle incoming BYE request ---*/
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req, int debug, int ignore)
{
struct ast_channel *c=NULL;
int res;
struct ast_channel *bridged_to;
char iabuf[INET_ADDRSTRLEN];
if (p->pendinginvite && !ast_test_flag(p, SIP_OUTGOING) && !ignore)
transmit_response_reliable(p, "487 Request Terminated", &p->initreq, 1);
copy_request(&p->initreq, req);
check_via(p, req);
ast_set_flag(p, SIP_ALREADYGONE);
if (p->rtp) {
/* Immediately stop RTP */
ast_rtp_stop(p->rtp);
}
if (p->vrtp) {
/* Immediately stop VRTP */
ast_rtp_stop(p->vrtp);
}
if (!ast_strlen_zero(get_header(req, "Also"))) {
ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr));
if (ast_strlen_zero(p->context))
strcpy(p->context, default_context);
res = get_also_info(p, req);
if (!res) {
c = p->owner;
if (c) {
bridged_to = ast_bridged_channel(c);
if (bridged_to) {
/* Don't actually hangup here... */
ast_moh_stop(bridged_to);
ast_async_goto(bridged_to, p->context, p->refer_to,1);
} else
ast_queue_hangup(p->owner);
}
} else {
ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr));
if (p->owner)
ast_queue_hangup(p->owner);
}
} else if (p->owner) {
ast_queue_hangup(p->owner);
if (option_debug > 2)
ast_log(LOG_DEBUG, "Received bye, issuing owner hangup\n.");
} else {
ast_set_flag(p, SIP_NEEDDESTROY);
if (option_debug > 2)
ast_log(LOG_DEBUG, "Received bye, no owner, selfdestruct soon.\n.");
}
transmit_response(p, "200 OK", req);
return 1;
}
/*! \brief handle_request_message: Handle incoming MESSAGE request ---*/
static int handle_request_message(struct sip_pvt *p, struct sip_request *req, int debug, int ignore)
{
if (!ignore) {
if (debug)
ast_verbose("Receiving message!\n");
receive_message(p, req);
} else {
transmit_response(p, "202 Accepted", req);
}
return 1;
}
/*! \brief handle_request_subscribe: Handle incoming SUBSCRIBE request ---*/
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, struct sockaddr_in *sin, int seqno, char *e)
{
int gotdest;
int res = 0;
int firststate = AST_EXTENSION_REMOVED;
if (p->initreq.headers) {
/* We already have a dialog */
if (p->initreq.method != SIP_SUBSCRIBE) {
/* This is a SUBSCRIBE within another SIP dialog, which we do not support */
/* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
transmit_response(p, "403 Forbidden (within dialog)", req);
/* Do not destroy session, since we will break the call if we do */
ast_log(LOG_DEBUG, "Got a subscription within the context of another call, can't handle that - %s (Method %s)\n", p->callid, sip_methods[p->initreq.method].text);
return 0;
} else {
if (debug)
ast_log(LOG_DEBUG, "Got a re-subscribe on existing subscription %s\n", p->callid);
}
}
if (!ignore && !p->initreq.headers) {
/* Use this as the basis */
if (debug)
ast_verbose("Using latest SUBSCRIBE request as basis request\n");
/* This call is no longer outgoing if it ever was */
ast_clear_flag(p, SIP_OUTGOING);
copy_request(&p->initreq, req);
check_via(p, req);
} else if (debug && ignore)
ast_verbose("Ignoring this SUBSCRIBE request\n");
if (!p->lastinvite) {
char mailboxbuf[256]="";
int found = 0;
char *mailbox = NULL;
int mailboxsize = 0;
char *eventparam;
char *event = get_header(req, "Event"); /* Get Event package name */
char *accept = get_header(req, "Accept");
/* Find parameters to Event: header value and remove them for now */
eventparam = strchr(event, ';');
if (eventparam) {
*eventparam = '\0';
eventparam++;
}
if (!strcmp(event, "message-summary") && !strcmp(accept, "application/simple-message-summary")) {
mailbox = mailboxbuf;
mailboxsize = sizeof(mailboxbuf);
}
/* Handle authentication if this is our first subscribe */
res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, ignore, mailbox, mailboxsize);
/* if an authentication challenge was sent, we are done here */
if (res > 0)
return 0;
if (res < 0) {
if (res == -4) {
ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
transmit_fake_auth_response(p, req, p->randdata, sizeof(p->randdata), 1);
} else {
ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
if (ignore)
transmit_response(p, "403 Forbidden", req);
else
transmit_response_reliable(p, "403 Forbidden", req, 1);
}
ast_set_flag(p, SIP_NEEDDESTROY);
return 0;
}
gotdest = get_destination(p, NULL);
/* Initialize the context if it hasn't been already;
note this is done _after_ handling any domain lookups,
because the context specified there is for calls, not
subscriptions
*/
if (!ast_strlen_zero(p->subscribecontext))
ast_copy_string(p->context, p->subscribecontext, sizeof(p->context));
else if (ast_strlen_zero(p->context))
strcpy(p->context, default_context);
/* Get destination right away */
build_contact(p);
if (gotdest) {
if (gotdest < 0)
transmit_response(p, "404 Not Found", req);
else
transmit_response(p, "484 Address Incomplete", req); /* Overlap dialing on SUBSCRIBE?? */
ast_set_flag(p, SIP_NEEDDESTROY);
} else {
/* Initialize tag for new subscriptions */
if (ast_strlen_zero(p->tag))
make_our_tag(p->tag, sizeof(p->tag));
if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
/* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
/* Polycom phones only handle xpidf+xml, even if they say they can
handle pidf+xml as well
*/
if (strstr(p->useragent, "Polycom")) {
p->subscribed = XPIDF_XML;
} else if (strstr(accept, "application/pidf+xml")) {
p->subscribed = PIDF_XML; /* RFC 3863 format */
} else if (strstr(accept, "application/dialog-info+xml")) {
p->subscribed = DIALOG_INFO_XML;
/* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
} else if (strstr(accept, "application/cpim-pidf+xml")) {
p->subscribed = CPIM_PIDF_XML; /* RFC 3863 format */
} else if (strstr(accept, "application/xpidf+xml")) {
p->subscribed = XPIDF_XML; /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
} else {
/* Can't find a format for events that we know about */
transmit_response(p, "489 Bad Event", req);
ast_set_flag(p, SIP_NEEDDESTROY);
return 0;
}
} else if (!strcmp(event, "message-summary") && !strcmp(accept, "application/simple-message-summary")) {
/* Looks like they actually want a mailbox status */
/* At this point, we should check if they subscribe to a mailbox that
has the same extension as the peer or the mailbox id. If we configure
the context to be the same as a SIP domain, we could check mailbox
context as well. To be able to securely accept subscribes on mailbox
IDs, not extensions, we need to check the digest auth user to make
sure that the user has access to the mailbox.
Since we do not act on this subscribe anyway, we might as well
accept any authenticated peer with a mailbox definition in their
config section.
*/
if (!ast_strlen_zero(mailbox)) {
found++;
}
if (found){
transmit_response(p, "200 OK", req);
ast_set_flag(p, SIP_NEEDDESTROY);
} else {
transmit_response(p, "404 Not found", req);
ast_set_flag(p, SIP_NEEDDESTROY);
}
return 0;
} else { /* At this point, Asterisk does not understand the specified event */
transmit_response(p, "489 Bad Event", req);
if (option_debug > 1)
ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: %s\n", event);
ast_set_flag(p, SIP_NEEDDESTROY);
return 0;
}
if (p->subscribed != NONE)
p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);
}
}
if (!ignore && p)
p->lastinvite = seqno;
if (p && !ast_test_flag(p, SIP_NEEDDESTROY)) {
p->expiry = atoi(get_header(req, "Expires"));
/* The next 4 lines can be removed if the SNOM Expires bug is fixed */
if (p->subscribed == DIALOG_INFO_XML) {
if (p->expiry > max_expiry)
p->expiry = max_expiry;
}
if (sipdebug || option_debug > 1)
ast_log(LOG_DEBUG, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
if (p->autokillid > -1)
sip_cancel_destroy(p); /* Remove subscription expiry for renewals */
sip_scheddestroy(p, (p->expiry + 10) * 1000); /* Set timer for destruction of call at expiration */
if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
char iabuf[INET_ADDRSTRLEN];
ast_log(LOG_ERROR, "Got SUBSCRIBE for extension %s@%s from %s, but there is no hint for that extension\n", p->exten, p->context, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr));
transmit_response(p, "404 Not found", req);
ast_set_flag(p, SIP_NEEDDESTROY);
return 0;
} else {
struct sip_pvt *p_old;
transmit_response(p, "200 OK", req);
transmit_state_notify(p, firststate, 1, 1); /* Send first notification */
append_history(p, "Subscribestatus", ast_extension_state2str(firststate));
/* remove any old subscription from this peer for the same exten/context,
as the peer has obviously forgotten about it and it's wasteful to wait
for it to expire and send NOTIFY messages to the peer only to have them
ignored (or generate errors)
*/
ast_mutex_lock(&iflock);
for (p_old = iflist; p_old; p_old = p_old->next) {
if (p_old == p)
continue;
if (p_old->initreq.method != SIP_SUBSCRIBE)
continue;
if (p_old->subscribed == NONE)
continue;
ast_mutex_lock(&p_old->lock);
if (!strcmp(p_old->username, p->username)) {
if (!strcmp(p_old->exten, p->exten) &&
!strcmp(p_old->context, p->context)) {
ast_set_flag(p_old, SIP_NEEDDESTROY);
ast_mutex_unlock(&p_old->lock);
break;
}
}
ast_mutex_unlock(&p_old->lock);
}
ast_mutex_unlock(&iflock);
}
if (!p->expiry)
ast_set_flag(p, SIP_NEEDDESTROY);
}
return 1;
}
/*! \brief handle_request_register: Handle incoming REGISTER request ---*/
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, struct sockaddr_in *sin, char *e)
{
int res = 0;
char iabuf[INET_ADDRSTRLEN];
/* Use this as the basis */
if (debug)
ast_verbose("Using latest REGISTER request as basis request\n");
copy_request(&p->initreq, req);
check_via(p, req);
if ((res = register_verify(p, sin, req, e, ignore)) < 0)
ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n", get_header(req, "To"), ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), (res == -1) ? "Wrong password" : (res == -2 ? "Username/auth name mismatch" : "Not a local SIP domain"));
if (res < 1) {
/* Destroy the session, but keep us around for just a bit in case they don't
get our 200 OK */
sip_scheddestroy(p, 15*1000);
}
return res;
}
/*! \brief handle_request: Handle SIP requests (methods) ---*/
/* this is where all incoming requests go first */
static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
{
/* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
relatively static */
struct sip_request resp;
char *cmd;
char *cseq;
char *useragent;
int seqno;
int len;
int ignore=0;
int respid;
int res = 0;
char iabuf[INET_ADDRSTRLEN];
int debug = sip_debug_test_pvt(p);
char *e;
int error = 0;
/* Clear out potential response */
memset(&resp, 0, sizeof(resp));
/* Get Method and Cseq */
cseq = get_header(req, "Cseq");
cmd = req->header[0];
/* Must have Cseq */
if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
error = 1;
}
if (!error && sscanf(cseq, "%d%n", &seqno, &len) != 1) {
ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
error = 1;
}
if (error) {
if (!p->initreq.header) /* New call */
ast_set_flag(p, SIP_NEEDDESTROY); /* Make sure we destroy this dialog */
return -1;
}
/* Get the command XXX */
cmd = req->rlPart1;
e = req->rlPart2;
/* Save useragent of the client */
useragent = get_header(req, "User-Agent");
if (!ast_strlen_zero(useragent))
ast_copy_string(p->useragent, useragent, sizeof(p->useragent));
/* Find out SIP method for incoming request */
if (req->method == SIP_RESPONSE) { /* Response to our request */
/* Response to our request -- Do some sanity checks */
if (!p->initreq.headers) {
ast_log(LOG_DEBUG, "That's odd... Got a response on a call we dont know about. Cseq %d Cmd %s\n", seqno, cmd);
ast_set_flag(p, SIP_NEEDDESTROY);
return 0;
} else if (p->ocseq && (p->ocseq < seqno)) {
ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
return -1;
} else if (p->ocseq && (p->ocseq != seqno)) {
/* ignore means "don't do anything with it" but still have to
respond appropriately */
ignore=1;
}
e = ast_skip_blanks(e);
if (sscanf(e, "%d %n", &respid, &len) != 1) {
ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
} else {
/* More SIP ridiculousness, we have to ignore bogus contacts in 100 etc responses */
if ((respid == 200) || ((respid >= 300) && (respid <= 399)))
extract_uri(p, req);
handle_response(p, respid, e + len, req, ignore, seqno);
}
return 0;
}
/* New SIP request coming in
(could be new request in existing SIP dialog as well...)
*/
p->method = req->method; /* Find out which SIP method they are using */
if (option_debug > 2)
ast_log(LOG_DEBUG, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
if (p->icseq && (p->icseq > seqno)) {
if (option_debug)
ast_log(LOG_DEBUG, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
if (req->method != SIP_ACK)
transmit_response(p, "503 Server error", req); /* We must respond according to RFC 3261 sec 12.2 */
return -1;
} else if (p->icseq && (p->icseq == seqno) && req->method != SIP_ACK &&(p->method != SIP_CANCEL|| ast_test_flag(p, SIP_ALREADYGONE))) {
/* ignore means "don't do anything with it" but still have to
respond appropriately. We do this if we receive a repeat of
the last sequence number */
ignore=2;
if (option_debug > 2)
ast_log(LOG_DEBUG, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
}
if (seqno >= p->icseq)
/* Next should follow monotonically (but not necessarily
incrementally -- thanks again to the genius authors of SIP --
increasing */
p->icseq = seqno;
/* Find their tag if we haven't got it */
if (ast_strlen_zero(p->theirtag)) {
gettag(req, "From", p->theirtag, sizeof(p->theirtag));
}
snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
if (pedanticsipchecking) {
/* If this is a request packet without a from tag, it's not
correct according to RFC 3261 */
/* Check if this a new request in a new dialog with a totag already attached to it,
RFC 3261 - section 12.2 - and we don't want to mess with recovery */
if (!p->initreq.headers && ast_test_flag(req, SIP_PKT_WITH_TOTAG)) {
/* If this is a first request and it got a to-tag, it is not for us */
if (!ignore && req->method == SIP_INVITE) {
transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req, 1);
/* Will cease to exist after ACK */
} else if (req->method != SIP_ACK) {
transmit_response(p, "481 Call/Transaction Does Not Exist", req);
ast_set_flag(p, SIP_NEEDDESTROY);
}
return res;
}
}
/* Handle various incoming SIP methods in requests */
switch (p->method) {
case SIP_OPTIONS:
res = handle_request_options(p, req, debug);
break;
case SIP_INVITE:
res = handle_request_invite(p, req, debug, ignore, seqno, sin, recount, e);
break;
case SIP_REFER:
res = handle_request_refer(p, req, debug, ignore, seqno, nounlock);
break;
case SIP_CANCEL:
res = handle_request_cancel(p, req, debug, ignore);
break;
case SIP_BYE:
res = handle_request_bye(p, req, debug, ignore);
break;
case SIP_MESSAGE:
res = handle_request_message(p, req, debug, ignore);
break;
case SIP_SUBSCRIBE:
res = handle_request_subscribe(p, req, debug, ignore, sin, seqno, e);
break;
case SIP_REGISTER:
res = handle_request_register(p, req, debug, ignore, sin, e);
break;
case SIP_INFO:
if (!ignore) {
if (debug)
ast_verbose("Receiving INFO!\n");
handle_request_info(p, req);
} else { /* if ignoring, transmit response */
transmit_response(p, "200 OK", req);
}
break;
case SIP_NOTIFY:
/* XXX we get NOTIFY's from some servers. WHY?? Maybe we should
look into this someday XXX */
transmit_response(p, "200 OK", req);
if (!p->lastinvite)
ast_set_flag(p, SIP_NEEDDESTROY);
break;
case SIP_ACK:
/* Make sure we don't ignore this */
if (seqno == p->pendinginvite) {
p->pendinginvite = 0;
__sip_ack(p, seqno, FLAG_RESPONSE, 0);
if (find_sdp(req)) {
if (process_sdp(p, req))
return -1;
}
check_pendings(p);
}
if (!p->lastinvite && ast_strlen_zero(p->randdata))
ast_set_flag(p, SIP_NEEDDESTROY);
break;
default:
transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
cmd, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr));
/* If this is some new method, and we don't have a call, destroy it now */
if (!p->initreq.headers)
ast_set_flag(p, SIP_NEEDDESTROY);
break;
}
return res;
}
/*! \brief sipsock_read: Read data from SIP socket ---*/
/* Successful messages is connected to SIP call and forwarded to handle_request() */
static int sipsock_read(int *id, int fd, short events, void *ignore)
{
struct sip_request req;
struct sockaddr_in sin = { 0, };
struct sip_pvt *p;
int res;
socklen_t len;
int nounlock;
int recount = 0;
char iabuf[INET_ADDRSTRLEN];
unsigned int lockretry = 100;
len = sizeof(sin);
memset(&req, 0, sizeof(req));
res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
if (res < 0) {
#if !defined(__FreeBSD__)
if (errno == EAGAIN)
ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
else
#endif
if (errno != ECONNREFUSED)
ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
return 1;
}
if (res == sizeof(req.data)) {
ast_log(LOG_DEBUG, "Received packet exceeds buffer. Data is possibly lost\n");
req.data[sizeof(req.data) - 1] = '\0';
} else
req.data[res] = '\0';
req.len = res;
if(sip_debug_test_addr(&sin))
ast_set_flag(&req, SIP_PKT_DEBUG);
if (pedanticsipchecking)
req.len = lws2sws(req.data, req.len); /* Fix multiline headers */
if (ast_test_flag(&req, SIP_PKT_DEBUG)) {
ast_verbose("\n<-- SIP read from %s:%d: \n%s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), req.data);
}
parse_request(&req);
req.method = find_sip_method(req.rlPart1);
if (ast_test_flag(&req, SIP_PKT_DEBUG)) {
ast_verbose("--- (%d headers %d lines)%s ---\n", req.headers, req.lines, (req.headers + req.lines == 0) ? " Nat keepalive" : "");
}
if (req.headers < 2) {
/* Must have at least two headers */
return 1;
}
/* Process request, with netlock held */
retrylock:
ast_mutex_lock(&netlock);
p = find_call(&req, &sin, req.method);
if (p) {
/* Go ahead and lock the owner if it has one -- we may need it */
if (p->owner && ast_mutex_trylock(&p->owner->lock)) {
ast_log(LOG_DEBUG, "Failed to grab lock, trying again...\n");
ast_mutex_unlock(&p->lock);
ast_mutex_unlock(&netlock);
/* Sleep for a very short amount of time */
usleep(1);
if (--lockretry)
goto retrylock;
}
if (!lockretry) {
ast_log(LOG_ERROR, "We could NOT get the channel lock for %s! \n", p->owner->name);
ast_log(LOG_ERROR, "SIP MESSAGE JUST IGNORED: %s \n", req.data);
ast_log(LOG_ERROR, "BAD! BAD! BAD!\n");
return 1;
}
memcpy(&p->recv, &sin, sizeof(p->recv));
if (recordhistory) {
char tmp[80];
/* This is a response, note what it was for */
snprintf(tmp, sizeof(tmp), "%s / %s /%s", req.data, get_header(&req, "CSeq"), req.rlPart2);
append_history(p, "Rx", tmp);
}
nounlock = 0;
if (handle_request(p, &req, &sin, &recount, &nounlock) == -1) {
/* Request failed */
ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
}
if (p->owner && !nounlock)
ast_mutex_unlock(&p->owner->lock);
ast_mutex_unlock(&p->lock);
}
ast_mutex_unlock(&netlock);
if (recount)
ast_update_use_count();
return 1;
}
/*! \brief sip_send_mwi_to_peer: Send message waiting indication ---*/
static int sip_send_mwi_to_peer(struct sip_peer *peer)
{
/* Called with peerl lock, but releases it */
struct sip_pvt *p;
int newmsgs, oldmsgs;
/* Check for messages */
ast_app_messagecount(peer->mailbox, &newmsgs, &oldmsgs);
time(&peer->lastmsgcheck);
/* Return now if it's the same thing we told them last time */
if (((newmsgs << 8) | (oldmsgs)) == peer->lastmsgssent) {
return 0;
}
p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY);
if (!p) {
ast_log(LOG_WARNING, "Unable to build sip pvt data for MWI\n");
return -1;
}
peer->lastmsgssent = ((newmsgs << 8) | (oldmsgs));
if (create_addr_from_peer(p, peer)) {
/* Maybe they're not registered, etc. */
sip_destroy(p);
return 0;
}
/* Recalculate our side, and recalculate Call ID */
if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
build_via(p, p->via, sizeof(p->via));
build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
/* Send MWI */
ast_set_flag(p, SIP_OUTGOING);
transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
sip_scheddestroy(p, 15000);
return 0;
}
/*! \brief do_monitor: The SIP monitoring thread ---*/
static void *do_monitor(void *data)
{
int res;
struct sip_pvt *sip;
struct sip_peer *peer = NULL;
time_t t;
int fastrestart =0;
int lastpeernum = -1;
int curpeernum;
int reloading;
/* Add an I/O event to our UDP socket */
if (sipsock > -1)
sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
/* This thread monitors all the frame relay interfaces which are not yet in use
(and thus do not have a separate thread) indefinitely */
/* From here on out, we die whenever asked */
for(;;) {
/* Check for a reload request */
ast_mutex_lock(&sip_reload_lock);
reloading = sip_reloading;
sip_reloading = 0;
ast_mutex_unlock(&sip_reload_lock);
if (reloading) {
if (option_verbose > 0)
ast_verbose(VERBOSE_PREFIX_1 "Reloading SIP\n");
sip_do_reload();
/* Change the I/O fd of our UDP socket */
if (sipsock > -1)
sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
}
/* Check for interfaces needing to be killed */
ast_mutex_lock(&iflock);
restartsearch:
time(&t);
sip = iflist;
/* don't scan the interface list if it hasn't been a reasonable period
of time since the last time we did it (when MWI is being sent, we can
get back to this point every millisecond or less)
*/
while(!fastrestart && sip) {
ast_mutex_lock(&sip->lock);
if (sip->rtp && sip->owner && (sip->owner->_state == AST_STATE_UP) && !sip->redirip.sin_addr.s_addr) {
if (sip->lastrtptx && sip->rtpkeepalive && t > sip->lastrtptx + sip->rtpkeepalive) {
/* Need to send an empty RTP packet */
time(&sip->lastrtptx);
ast_rtp_sendcng(sip->rtp, 0);
}
if (sip->lastrtprx && (sip->rtptimeout || sip->rtpholdtimeout) && t > sip->lastrtprx + sip->rtptimeout) {
/* Might be a timeout now -- see if we're on hold */
struct sockaddr_in sin;
ast_rtp_get_peer(sip->rtp, &sin);
if (sin.sin_addr.s_addr ||
(sip->rtpholdtimeout &&
(t > sip->lastrtprx + sip->rtpholdtimeout))) {
/* Needs a hangup */
if (sip->rtptimeout) {
while(sip->owner && ast_mutex_trylock(&sip->owner->lock)) {
ast_mutex_unlock(&sip->lock);
usleep(1);
ast_mutex_lock(&sip->lock);
}
if (sip->owner) {
ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n", sip->owner->name, (long)(t - sip->lastrtprx));
/* Issue a softhangup */
ast_softhangup_nolock(sip->owner, AST_SOFTHANGUP_DEV);
ast_mutex_unlock(&sip->owner->lock);
/* forget the timeouts for this call, since a hangup
has already been requested and we don't want to
repeatedly request hangups
*/
sip->rtptimeout = 0;
sip->rtpholdtimeout = 0;
}
}
}
}
}
if (ast_test_flag(sip, SIP_NEEDDESTROY) && !sip->packets && !sip->owner) {
ast_mutex_unlock(&sip->lock);
__sip_destroy(sip, 1);
goto restartsearch;
}
ast_mutex_unlock(&sip->lock);
sip = sip->next;
}
ast_mutex_unlock(&iflock);
/* Don't let anybody kill us right away. Nobody should lock the interface list
and wait for the monitor list, but the other way around is okay. */
ast_mutex_lock(&monlock);
/* Lock the network interface */
ast_mutex_lock(&netlock);
/* Okay, now that we know what to do, release the network lock */
ast_mutex_unlock(&netlock);
/* And from now on, we're okay to be killed, so release the monitor lock as well */
ast_mutex_unlock(&monlock);
pthread_testcancel();
/* Wait for sched or io */
res = ast_sched_wait(sched);
if ((res < 0) || (res > 1000))
res = 1000;
/* If we might need to send more mailboxes, don't wait long at all.*/
if (fastrestart)
res = 1;
res = ast_io_wait(io, res);
if (res > 20)
ast_log(LOG_DEBUG, "chan_sip: ast_io_wait ran %d all at once\n", res);
ast_mutex_lock(&monlock);
if (res >= 0) {
res = ast_sched_runq(sched);
if (res >= 20)
ast_log(LOG_DEBUG, "chan_sip: ast_sched_runq ran %d all at once\n", res);
}
/* needs work to send mwi to realtime peers */
time(&t);
fastrestart = 0;
curpeernum = 0;
peer = NULL;
ASTOBJ_CONTAINER_TRAVERSE(&peerl, !peer, do {
if ((curpeernum > lastpeernum) && !ast_strlen_zero(iterator->mailbox) && ((t - iterator->lastmsgcheck) > global_mwitime)) {
fastrestart = 1;
lastpeernum = curpeernum;
peer = ASTOBJ_REF(iterator);
};
curpeernum++;
} while (0)
);
if (peer) {
ASTOBJ_WRLOCK(peer);
sip_send_mwi_to_peer(peer);
ASTOBJ_UNLOCK(peer);
ASTOBJ_UNREF(peer,sip_destroy_peer);
} else {
/* Reset where we come from */
lastpeernum = -1;
}
ast_mutex_unlock(&monlock);
}
/* Never reached */
return NULL;
}
/*! \brief restart_monitor: Start the channel monitor thread ---*/
static int restart_monitor(void)
{
/* If we're supposed to be stopped -- stay stopped */
if (monitor_thread == AST_PTHREADT_STOP)
return 0;
if (ast_mutex_lock(&monlock)) {
ast_log(LOG_WARNING, "Unable to lock monitor\n");
return -1;
}
if (monitor_thread == pthread_self()) {
ast_mutex_unlock(&monlock);
ast_log(LOG_WARNING, "Cannot kill myself\n");
return -1;
}
if (monitor_thread != AST_PTHREADT_NULL) {
/* Wake up the thread */
pthread_kill(monitor_thread, SIGURG);
} else {
/* Start a new monitor */
if (ast_pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
ast_mutex_unlock(&monlock);
ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
return -1;
}
}
ast_mutex_unlock(&monlock);
return 0;
}
/*! \brief sip_poke_noanswer: No answer to Qualify poke ---*/
static int sip_poke_noanswer(void *data)
{
struct sip_peer *peer = data;
peer->pokeexpire = -1;
if (peer->lastms > -1) {
ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
}
if (peer->call)
sip_destroy(peer->call);
peer->call = NULL;
peer->lastms = -1;
ast_device_state_changed("SIP/%s", peer->name);
/* Try again quickly */
peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
return 0;
}
/*! \brief sip_poke_peer: Check availability of peer, also keep NAT open ---*/
/* This is done with the interval in qualify= option in sip.conf */
/* Default is 2 seconds */
static int sip_poke_peer(struct sip_peer *peer)
{
struct sip_pvt *p;
if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
/* IF we have no IP, or this isn't to be monitored, return
imeediately after clearing things out */
if (peer->pokeexpire > -1)
ast_sched_del(sched, peer->pokeexpire);
peer->lastms = 0;
peer->pokeexpire = -1;
peer->call = NULL;
return 0;
}
if (peer->call > 0) {
if (sipdebug)
ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
sip_destroy(peer->call);
}
p = peer->call = sip_alloc(NULL, NULL, 0, SIP_OPTIONS);
if (!peer->call) {
ast_log(LOG_WARNING, "Unable to allocate dialog for poking peer '%s'\n", peer->name);
return -1;
}
memcpy(&p->sa, &peer->addr, sizeof(p->sa));
memcpy(&p->recv, &peer->addr, sizeof(p->sa));
ast_copy_flags(p, peer, SIP_FLAGS_TO_COPY);
/* Send OPTIONs to peer's fullcontact */
if (!ast_strlen_zero(peer->fullcontact)) {
ast_copy_string (p->fullcontact, peer->fullcontact, sizeof(p->fullcontact));
}
if (!ast_strlen_zero(peer->tohost))
ast_copy_string(p->tohost, peer->tohost, sizeof(p->tohost));
else
ast_inet_ntoa(p->tohost, sizeof(p->tohost), peer->addr.sin_addr);
/* Recalculate our side, and recalculate Call ID */
if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
build_via(p, p->via, sizeof(p->via));
build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
if (peer->pokeexpire > -1)
ast_sched_del(sched, peer->pokeexpire);
p->peerpoke = peer;
ast_set_flag(p, SIP_OUTGOING);
#ifdef VOCAL_DATA_HACK
ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
transmit_invite(p, SIP_INVITE, 0, 2);
#else
transmit_invite(p, SIP_OPTIONS, 0, 2);
#endif
gettimeofday(&peer->ps, NULL);
peer->pokeexpire = ast_sched_add(sched, DEFAULT_MAXMS * 2, sip_poke_noanswer, peer);
return 0;
}
/*! \brief sip_devicestate: Part of PBX channel interface ---*/
/* Return values:---
If we have qualify on and the device is not reachable, regardless of registration
state we return AST_DEVICE_UNAVAILABLE
For peers with call limit:
not registered AST_DEVICE_UNAVAILABLE
registered, no call AST_DEVICE_NOT_INUSE
registered, calls possible AST_DEVICE_INUSE
registered, call limit reached AST_DEVICE_BUSY
For peers without call limit:
not registered AST_DEVICE_UNAVAILABLE
registered AST_DEVICE_UNKNOWN
*/
static int sip_devicestate(void *data)
{
char *host;
char *tmp;
struct hostent *hp;
struct ast_hostent ahp;
struct sip_peer *p;
int res = AST_DEVICE_INVALID;
host = ast_strdupa(data);
if ((tmp = strchr(host, '@')))
host = tmp + 1;
if (option_debug > 2)
ast_log(LOG_DEBUG, "Checking device state for peer %s\n", host);
if ((p = find_peer(host, NULL, 1))) {
if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
/* we have an address for the peer */
/* if qualify is turned on, check the status */
if (p->maxms && (p->lastms > p->maxms)) {
res = AST_DEVICE_UNAVAILABLE;
} else {
/* qualify is not on, or the peer is responding properly */
/* check call limit */
if (p->call_limit && (p->inUse == p->call_limit))
res = AST_DEVICE_BUSY;
else if (p->call_limit && p->inUse)
res = AST_DEVICE_INUSE;
else if (p->call_limit)
res = AST_DEVICE_NOT_INUSE;
else
res = AST_DEVICE_UNKNOWN;
}
} else {
/* there is no address, it's unavailable */
res = AST_DEVICE_UNAVAILABLE;
}
ASTOBJ_UNREF(p,sip_destroy_peer);
} else {
hp = ast_gethostbyname(host, &ahp);
if (hp)
res = AST_DEVICE_UNKNOWN;
}
return res;
}
/*! \brief sip_request: PBX interface function -build SIP pvt structure ---*/
/* SIP calls initiated by the PBX arrive here */
static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
{
int oldformat;
struct sip_pvt *p;
struct ast_channel *tmpc = NULL;
char *ext, *host;
char tmp[256];
char *dest = data;
oldformat = format;
format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1);
if (!format) {
ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n", ast_getformatname(oldformat), ast_getformatname(global_capability));
*cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL; /* Can't find codec to connect to host */
return NULL;
}
p = sip_alloc(NULL, NULL, 0, SIP_INVITE);
if (!p) {
ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory)\n", (char *)data);
*cause = AST_CAUSE_SWITCH_CONGESTION;
return NULL;
}
p->options = calloc(1, sizeof(*p->options));
if (!p->options) {
sip_destroy(p);
ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
*cause = AST_CAUSE_SWITCH_CONGESTION;
return NULL;
}
ast_copy_string(tmp, dest, sizeof(tmp));
host = strchr(tmp, '@');
if (host) {
*host = '\0';
host++;
ext = tmp;
} else {
ext = strchr(tmp, '/');
if (ext) {
*ext++ = '\0';
host = tmp;
}
else {
host = tmp;
ext = NULL;
}
}
if (create_addr(p, host)) {
*cause = AST_CAUSE_UNREGISTERED;
sip_destroy(p);
return NULL;
}
if (ast_strlen_zero(p->peername) && ext)
ast_copy_string(p->peername, ext, sizeof(p->peername));
/* Recalculate our side, and recalculate Call ID */
if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
build_via(p, p->via, sizeof(p->via));
build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
/* We have an extension to call, don't use the full contact here */
/* This to enable dialling registered peers with extension dialling,
like SIP/peername/extension
SIP/peername will still use the full contact */
if (ext) {
ast_copy_string(p->username, ext, sizeof(p->username));
p->fullcontact[0] = 0;
}
#if 0
printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
#endif
p->prefcodec = format;
ast_mutex_lock(&p->lock);
tmpc = sip_new(p, AST_STATE_DOWN, host); /* Place the call */
ast_mutex_unlock(&p->lock);
if (!tmpc)
sip_destroy(p);
ast_update_use_count();
restart_monitor();
return tmpc;
}
/*! \brief handle_common_options: Handle flag-type options common to users and peers ---*/
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
{
int res = 0;
if (!strcasecmp(v->name, "trustrpid")) {
ast_set_flag(mask, SIP_TRUSTRPID);
ast_set2_flag(flags, ast_true(v->value), SIP_TRUSTRPID);
res = 1;
} else if (!strcasecmp(v->name, "sendrpid")) {
ast_set_flag(mask, SIP_SENDRPID);
ast_set2_flag(flags, ast_true(v->value), SIP_SENDRPID);
res = 1;
} else if (!strcasecmp(v->name, "useclientcode")) {
ast_set_flag(mask, SIP_USECLIENTCODE);
ast_set2_flag(flags, ast_true(v->value), SIP_USECLIENTCODE);
res = 1;
} else if (!strcasecmp(v->name, "dtmfmode")) {
ast_set_flag(mask, SIP_DTMF);
ast_clear_flag(flags, SIP_DTMF);
if (!strcasecmp(v->value, "inband"))
ast_set_flag(flags, SIP_DTMF_INBAND);
else if (!strcasecmp(v->value, "rfc2833"))
ast_set_flag(flags, SIP_DTMF_RFC2833);
else if (!strcasecmp(v->value, "info"))
ast_set_flag(flags, SIP_DTMF_INFO);
else if (!strcasecmp(v->value, "auto"))
ast_set_flag(flags, SIP_DTMF_AUTO);
else {
ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
ast_set_flag(flags, SIP_DTMF_RFC2833);
}
} else if (!strcasecmp(v->name, "nat")) {
ast_set_flag(mask, SIP_NAT);
ast_clear_flag(flags, SIP_NAT);
if (!strcasecmp(v->value, "never"))
ast_set_flag(flags, SIP_NAT_NEVER);
else if (!strcasecmp(v->value, "route"))
ast_set_flag(flags, SIP_NAT_ROUTE);
else if (ast_true(v->value))
ast_set_flag(flags, SIP_NAT_ALWAYS);
else
ast_set_flag(flags, SIP_NAT_RFC3581);
} else if (!strcasecmp(v->name, "canreinvite")) {
ast_set_flag(mask, SIP_REINVITE);
ast_clear_flag(flags, SIP_REINVITE);
if (!strcasecmp(v->value, "update"))
ast_set_flag(flags, SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
else
ast_set2_flag(flags, ast_true(v->value), SIP_CAN_REINVITE);
} else if (!strcasecmp(v->name, "insecure")) {
ast_set_flag(mask, SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
ast_clear_flag(flags, SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
if (!strcasecmp(v->value, "very"))
ast_set_flag(flags, SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
else if (ast_true(v->value))
ast_set_flag(flags, SIP_INSECURE_PORT);
else if (!ast_false(v->value)) {
char buf[64];
char *word, *next;
ast_copy_string(buf, v->value, sizeof(buf));
next = buf;
while ((word = strsep(&next, ","))) {
if (!strcasecmp(word, "port"))
ast_set_flag(flags, SIP_INSECURE_PORT);
else if (!strcasecmp(word, "invite"))
ast_set_flag(flags, SIP_INSECURE_INVITE);
else
ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", v->value, v->lineno);
}
}
} else if (!strcasecmp(v->name, "progressinband")) {
ast_set_flag(mask, SIP_PROG_INBAND);
ast_clear_flag(flags, SIP_PROG_INBAND);
if (ast_true(v->value))
ast_set_flag(flags, SIP_PROG_INBAND_YES);
else if (strcasecmp(v->value, "never"))
ast_set_flag(flags, SIP_PROG_INBAND_NO);
} else if (!strcasecmp(v->name, "allowguest")) {
#ifdef OSP_SUPPORT
if (!strcasecmp(v->value, "osp"))
global_allowguest = 2;
else
#endif
if (ast_true(v->value))
global_allowguest = 1;
else
global_allowguest = 0;
#ifdef OSP_SUPPORT
} else if (!strcasecmp(v->name, "ospauth")) {
ast_set_flag(mask, SIP_OSPAUTH);
ast_clear_flag(flags, SIP_OSPAUTH);
if (!strcasecmp(v->value, "proxy"))
ast_set_flag(flags, SIP_OSPAUTH_PROXY);
else if (!strcasecmp(v->value, "gateway"))
ast_set_flag(flags, SIP_OSPAUTH_GATEWAY);
else if(!strcasecmp (v->value, "exclusive"))
ast_set_flag(flags, SIP_OSPAUTH_EXCLUSIVE);
#endif
} else if (!strcasecmp(v->name, "promiscredir")) {
ast_set_flag(mask, SIP_PROMISCREDIR);
ast_set2_flag(flags, ast_true(v->value), SIP_PROMISCREDIR);
res = 1;
}
return res;
}
/*! \brief add_sip_domain: Add SIP domain to list of domains we are responsible for */
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
{
struct domain *d;
if (ast_strlen_zero(domain)) {
ast_log(LOG_WARNING, "Zero length domain.\n");
return 1;
}
d = calloc(1, sizeof(*d));
if (!d) {
ast_log(LOG_ERROR, "Allocation of domain structure failed, Out of memory\n");
return 0;
}
ast_copy_string(d->domain, domain, sizeof(d->domain));
if (!ast_strlen_zero(context))
ast_copy_string(d->context, context, sizeof(d->context));
d->mode = mode;
AST_LIST_LOCK(&domain_list);
AST_LIST_INSERT_TAIL(&domain_list, d, list);
AST_LIST_UNLOCK(&domain_list);
if (sipdebug)
ast_log(LOG_DEBUG, "Added local SIP domain '%s'\n", domain);
return 1;
}
/*! \brief check_sip_domain: Check if domain part of uri is local to our server */
static int check_sip_domain(const char *domain, char *context, size_t len)
{
struct domain *d;
int result = 0;
AST_LIST_LOCK(&domain_list);
AST_LIST_TRAVERSE(&domain_list, d, list) {
if (strcasecmp(d->domain, domain))
continue;
if (len && !ast_strlen_zero(d->context))
ast_copy_string(context, d->context, len);
result = 1;
break;
}
AST_LIST_UNLOCK(&domain_list);
return result;
}
/*! \brief clear_sip_domains: Clear our domain list (at reload) */
static void clear_sip_domains(void)
{
struct domain *d;
AST_LIST_LOCK(&domain_list);
while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
free(d);
AST_LIST_UNLOCK(&domain_list);
}
/*! \brief add_realm_authentication: Add realm authentication in list ---*/
static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno)
{
char authcopy[256];
char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
char *stringp;
struct sip_auth *auth;
struct sip_auth *b = NULL, *a = authlist;
if (ast_strlen_zero(configuration))
return authlist;
ast_log(LOG_DEBUG, "Auth config :: %s\n", configuration);
ast_copy_string(authcopy, configuration, sizeof(authcopy));
stringp = authcopy;
username = stringp;
realm = strrchr(stringp, '@');
if (realm) {
*realm = '\0';
realm++;
}
if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
return authlist;
}
stringp = username;
username = strsep(&stringp, ":");
if (username) {
secret = strsep(&stringp, ":");
if (!secret) {
stringp = username;
md5secret = strsep(&stringp,"#");
}
}
auth = malloc(sizeof(struct sip_auth));
if (auth) {
memset(auth, 0, sizeof(struct sip_auth));
ast_copy_string(auth->realm, realm, sizeof(auth->realm));
ast_copy_string(auth->username, username, sizeof(auth->username));
if (secret)
ast_copy_string(auth->secret, secret, sizeof(auth->secret));
if (md5secret)
ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
} else {
ast_log(LOG_ERROR, "Allocation of auth structure failed, Out of memory\n");
return authlist;
}
/* Add authentication to authl */
if (!authlist) { /* No existing list */
return auth;
}
while(a) {
b = a;
a = a->next;
}
b->next = auth; /* Add structure add end of list */
if (option_verbose > 2)
ast_verbose("Added authentication for realm %s\n", realm);
return authlist;
}
/*! \brief clear_realm_authentication: Clear realm authentication list (at reload) ---*/
static int clear_realm_authentication(struct sip_auth *authlist)
{
struct sip_auth *a = authlist;
struct sip_auth *b;
while (a) {
b = a;
a = a->next;
free(b);
}
return 1;
}
/*! \brief find_realm_authentication: Find authentication for a specific realm ---*/
static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, char *realm)
{
struct sip_auth *a = authlist; /* First entry in auth list */
while (a) {
if (!strcasecmp(a->realm, realm)){
break;
}
a = a->next;
}
return a;
}
/*! \brief build_user: Initiate a SIP user structure from sip.conf ---*/
static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime)
{
struct sip_user *user;
int format;
struct ast_ha *oldha = NULL;
char *varname = NULL, *varval = NULL;
struct ast_variable *tmpvar = NULL;
struct ast_flags userflags = {(0)};
struct ast_flags mask = {(0)};
user = (struct sip_user *)malloc(sizeof(struct sip_user));
if (!user) {
return NULL;
}
memset(user, 0, sizeof(struct sip_user));
suserobjs++;
ASTOBJ_INIT(user);
ast_copy_string(user->name, name, sizeof(user->name));
oldha = user->ha;
user->ha = NULL;
ast_copy_flags(user, &global_flags, SIP_FLAGS_TO_COPY);
user->capability = global_capability;
user->prefs = prefs;
/* set default context */
strcpy(user->context, default_context);
strcpy(user->language, default_language);
strcpy(user->musicclass, global_musicclass);
while(v) {
if (handle_common_options(&userflags, &mask, v)) {
v = v->next;
continue;
}
if (!strcasecmp(v->name, "context")) {
ast_copy_string(user->context, v->value, sizeof(user->context));
} else if (!strcasecmp(v->name, "subscribecontext")) {
ast_copy_string(user->subscribecontext, v->value, sizeof(user->subscribecontext));
} else if (!strcasecmp(v->name, "setvar")) {
varname = ast_strdupa(v->value);
if (varname && (varval = strchr(varname,'='))) {
*varval = '\0';
varval++;
if ((tmpvar = ast_variable_new(varname, varval))) {
tmpvar->next = user->chanvars;
user->chanvars = tmpvar;
}
}
} else if (!strcasecmp(v->name, "permit") ||
!strcasecmp(v->name, "deny")) {
user->ha = ast_append_ha(v->name, v->value, user->ha);
} else if (!strcasecmp(v->name, "secret")) {
ast_copy_string(user->secret, v->value, sizeof(user->secret));
} else if (!strcasecmp(v->name, "md5secret")) {
ast_copy_string(user->md5secret, v->value, sizeof(user->md5secret));
} else if (!strcasecmp(v->name, "callerid")) {
ast_callerid_split(v->value, user->cid_name, sizeof(user->cid_name), user->cid_num, sizeof(user->cid_num));
} else if (!strcasecmp(v->name, "callgroup")) {
user->callgroup = ast_get_group(v->value);
} else if (!strcasecmp(v->name, "pickupgroup")) {
user->pickupgroup = ast_get_group(v->value);
} else if (!strcasecmp(v->name, "language")) {
ast_copy_string(user->language, v->value, sizeof(user->language));
} else if (!strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
ast_copy_string(user->musicclass, v->value, sizeof(user->musicclass));
} else if (!strcasecmp(v->name, "accountcode")) {
ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
} else if (!strcasecmp(v->name, "call-limit") || !strcasecmp(v->name, "incominglimit")) {
user->call_limit = atoi(v->value);
if (user->call_limit < 0)
user->call_limit = 0;
} else if (!strcasecmp(v->name, "amaflags")) {
format = ast_cdr_amaflags2int(v->value);
if (format < 0) {
ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
} else {
user->amaflags = format;
}
} else if (!strcasecmp(v->name, "allow")) {
ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
} else if (!strcasecmp(v->name, "disallow")) {
ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 0);
} else if (!strcasecmp(v->name, "callingpres")) {
user->callingpres = ast_parse_caller_presentation(v->value);
if (user->callingpres == -1)
user->callingpres = atoi(v->value);
}
/*else if (strcasecmp(v->name,"type"))
* ast_log(LOG_WARNING, "Ignoring %s\n", v->name);
*/
v = v->next;
}
ast_copy_flags(user, &userflags, mask.flags);
ast_free_ha(oldha);
return user;
}
/*! \brief temp_peer: Create temporary peer (used in autocreatepeer mode) ---*/
static struct sip_peer *temp_peer(const char *name)
{
struct sip_peer *peer;
peer = malloc(sizeof(*peer));
if (!peer)
return NULL;
memset(peer, 0, sizeof(*peer));
apeerobjs++;
ASTOBJ_INIT(peer);
peer->expire = -1;
peer->pokeexpire = -1;
ast_copy_string(peer->name, name, sizeof(peer->name));
ast_copy_flags(peer, &global_flags, SIP_FLAGS_TO_COPY);
strcpy(peer->context, default_context);
strcpy(peer->subscribecontext, default_subscribecontext);
strcpy(peer->language, default_language);
strcpy(peer->musicclass, global_musicclass);
peer->addr.sin_port = htons(DEFAULT_SIP_PORT);
peer->addr.sin_family = AF_INET;
peer->capability = global_capability;
peer->rtptimeout = global_rtptimeout;
peer->rtpholdtimeout = global_rtpholdtimeout;
peer->rtpkeepalive = global_rtpkeepalive;
ast_set_flag(peer, SIP_SELFDESTRUCT);
ast_set_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC);
peer->prefs = prefs;
reg_source_db(peer);
return peer;
}
/*! \brief build_peer: Build peer from config file ---*/
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime)
{
struct sip_peer *peer = NULL;
struct ast_ha *oldha = NULL;
int obproxyfound=0;
int found=0;
int format=0; /* Ama flags */
time_t regseconds;
char *varname = NULL, *varval = NULL;
struct ast_variable *tmpvar = NULL;
struct ast_flags peerflags = {(0)};
struct ast_flags mask = {(0)};
if (!realtime)
/* Note we do NOT use find_peer here, to avoid realtime recursion */
/* We also use a case-sensitive comparison (unlike find_peer) so
that case changes made to the peer name will be properly handled
during reload
*/
peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
if (peer) {
/* Already in the list, remove it and it will be added back (or FREE'd) */
found++;
} else {
peer = malloc(sizeof(*peer));
if (peer) {
memset(peer, 0, sizeof(*peer));
if (realtime)
rpeerobjs++;
else
speerobjs++;
ASTOBJ_INIT(peer);
peer->expire = -1;
peer->pokeexpire = -1;
} else {
ast_log(LOG_WARNING, "Can't allocate SIP peer memory\n");
}
}
/* Note that our peer HAS had its reference count incrased */
if (!peer)
return NULL;
peer->lastmsgssent = -1;
if (!found) {
if (name)
ast_copy_string(peer->name, name, sizeof(peer->name));
peer->addr.sin_port = htons(DEFAULT_SIP_PORT);
peer->addr.sin_family = AF_INET;
peer->defaddr.sin_family = AF_INET;
}
/* If we have channel variables, remove them (reload) */
if (peer->chanvars) {
ast_variables_destroy(peer->chanvars);
peer->chanvars = NULL;
}
strcpy(peer->context, default_context);
strcpy(peer->subscribecontext, default_subscribecontext);
strcpy(peer->vmexten, global_vmexten);
strcpy(peer->language, default_language);
strcpy(peer->musicclass, global_musicclass);
ast_copy_flags(peer, &global_flags, SIP_USEREQPHONE);
peer->secret[0] = '\0';
peer->md5secret[0] = '\0';
peer->cid_num[0] = '\0';
peer->cid_name[0] = '\0';
peer->fromdomain[0] = '\0';
peer->fromuser[0] = '\0';
peer->regexten[0] = '\0';
peer->mailbox[0] = '\0';
peer->callgroup = 0;
peer->pickupgroup = 0;
peer->rtpkeepalive = global_rtpkeepalive;
peer->maxms = default_qualify;
peer->prefs = prefs;
oldha = peer->ha;
peer->ha = NULL;
peer->addr.sin_family = AF_INET;
ast_copy_flags(peer, &global_flags, SIP_FLAGS_TO_COPY);
peer->capability = global_capability;
peer->rtptimeout = global_rtptimeout;
peer->rtpholdtimeout = global_rtpholdtimeout;
while(v) {
if (handle_common_options(&peerflags, &mask, v)) {
v = v->next;
continue;
}
if (realtime && !strcasecmp(v->name, "regseconds")) {
if (sscanf(v->value, "%ld", (time_t *)®seconds) != 1)
regseconds = 0;
} else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
inet_aton(v->value, &(peer->addr.sin_addr));
} else if (realtime && !strcasecmp(v->name, "name"))
ast_copy_string(peer->name, v->value, sizeof(peer->name));
else if (realtime && !strcasecmp(v->name, "fullcontact")) {
ast_copy_string(peer->fullcontact, v->value, sizeof(peer->fullcontact));
ast_set_flag((&peer->flags_page2), SIP_PAGE2_RT_FROMCONTACT);
} else if (!strcasecmp(v->name, "secret"))
ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
else if (!strcasecmp(v->name, "md5secret"))
ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
else if (!strcasecmp(v->name, "auth"))
peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
else if (!strcasecmp(v->name, "callerid")) {
ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
} else if (!strcasecmp(v->name, "context")) {
ast_copy_string(peer->context, v->value, sizeof(peer->context));
} else if (!strcasecmp(v->name, "subscribecontext")) {
ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
} else if (!strcasecmp(v->name, "fromdomain"))
ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
else if (!strcasecmp(v->name, "usereqphone"))
ast_set2_flag(peer, ast_true(v->value), SIP_USEREQPHONE);
else if (!strcasecmp(v->name, "fromuser"))
ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
else if (!strcasecmp(v->name, "host") || !strcasecmp(v->name, "outboundproxy")) {
if (!strcasecmp(v->value, "dynamic")) {
if (!strcasecmp(v->name, "outboundproxy") || obproxyfound) {
ast_log(LOG_WARNING, "You can't have a dynamic outbound proxy, you big silly head at line %d.\n", v->lineno);
} else {
/* They'll register with us */
ast_set_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC);
if (!found) {
/* Initialize stuff iff we're not found, otherwise
we keep going with what we had */
memset(&peer->addr.sin_addr, 0, 4);
if (peer->addr.sin_port) {
/* If we've already got a port, make it the default rather than absolute */
peer->defaddr.sin_port = peer->addr.sin_port;
peer->addr.sin_port = 0;
}
}
}
} else {
/* Non-dynamic. Make sure we become that way if we're not */
if (peer->expire > -1)
ast_sched_del(sched, peer->expire);
peer->expire = -1;
ast_clear_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC);
if (!obproxyfound || !strcasecmp(v->name, "outboundproxy")) {
if (ast_get_ip_or_srv(&peer->addr, v->value, srvlookup ? "_sip._udp" : NULL)) {
ASTOBJ_UNREF(peer, sip_destroy_peer);
return NULL;
}
}
if (!strcasecmp(v->name, "outboundproxy"))
obproxyfound=1;
else {
ast_copy_string(peer->tohost, v->value, sizeof(peer->tohost));
if (!peer->addr.sin_port)
peer->addr.sin_port = htons(DEFAULT_SIP_PORT);
}
}
} else if (!strcasecmp(v->name, "defaultip")) {
if (ast_get_ip(&peer->defaddr, v->value)) {
ASTOBJ_UNREF(peer, sip_destroy_peer);
return NULL;
}
} else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
peer->ha = ast_append_ha(v->name, v->value, peer->ha);
} else if (!strcasecmp(v->name, "port")) {
if (!realtime && ast_test_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC))
peer->defaddr.sin_port = htons(atoi(v->value));
else
peer->addr.sin_port = htons(atoi(v->value));
} else if (!strcasecmp(v->name, "callingpres")) {
peer->callingpres = ast_parse_caller_presentation(v->value);
if (peer->callingpres == -1)
peer->callingpres = atoi(v->value);
} else if (!strcasecmp(v->name, "username")) {
ast_copy_string(peer->username, v->value, sizeof(peer->username));
} else if (!strcasecmp(v->name, "language")) {
ast_copy_string(peer->language, v->value, sizeof(peer->language));
} else if (!strcasecmp(v->name, "regexten")) {
ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
} else if (!strcasecmp(v->name, "call-limit") || !strcasecmp(v->name, "incominglimit")) {
peer->call_limit = atoi(v->value);
if (peer->call_limit < 0)
peer->call_limit = 0;
} else if (!strcasecmp(v->name, "amaflags")) {
format = ast_cdr_amaflags2int(v->value);
if (format < 0) {
ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
} else {
peer->amaflags = format;
}
} else if (!strcasecmp(v->name, "accountcode")) {
ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
} else if (!strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
ast_copy_string(peer->musicclass, v->value, sizeof(peer->musicclass));
} else if (!strcasecmp(v->name, "mailbox")) {
ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
} else if (!strcasecmp(v->name, "vmexten")) {
ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
} else if (!strcasecmp(v->name, "callgroup")) {
peer->callgroup = ast_get_group(v->value);
} else if (!strcasecmp(v->name, "pickupgroup")) {
peer->pickupgroup = ast_get_group(v->value);
} else if (!strcasecmp(v->name, "allow")) {
ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
} else if (!strcasecmp(v->name, "disallow")) {
ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
} else if (!strcasecmp(v->name, "rtptimeout")) {
if ((sscanf(v->value, "%d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
peer->rtptimeout = global_rtptimeout;
}
} else if (!strcasecmp(v->name, "rtpholdtimeout")) {
if ((sscanf(v->value, "%d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
peer->rtpholdtimeout = global_rtpholdtimeout;
}
} else if (!strcasecmp(v->name, "rtpkeepalive")) {
if ((sscanf(v->value, "%d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
peer->rtpkeepalive = global_rtpkeepalive;
}
} else if (!strcasecmp(v->name, "setvar")) {
/* Set peer channel variable */
varname = ast_strdupa(v->value);
if (varname && (varval = strchr(varname,'='))) {
*varval = '\0';
varval++;
if ((tmpvar = ast_variable_new(varname, varval))) {
tmpvar->next = peer->chanvars;
peer->chanvars = tmpvar;
}
}
} else if (!strcasecmp(v->name, "qualify")) {
if (!strcasecmp(v->value, "no")) {
peer->maxms = 0;
} else if (!strcasecmp(v->value, "yes")) {
peer->maxms = DEFAULT_MAXMS;
} else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer->name, v->lineno);
peer->maxms = 0;
}
}
/* else if (strcasecmp(v->name,"type"))
* ast_log(LOG_WARNING, "Ignoring %s\n", v->name);
*/
v=v->next;
}
if (!ast_test_flag((&global_flags_page2), SIP_PAGE2_IGNOREREGEXPIRE) && ast_test_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC) && realtime) {
time_t nowtime;
time(&nowtime);
if ((nowtime - regseconds) > 0) {
destroy_association(peer);
memset(&peer->addr, 0, sizeof(peer->addr));
if (option_debug)
ast_log(LOG_DEBUG, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
}
}
ast_copy_flags(peer, &peerflags, mask.flags);
if (!found && ast_test_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC) && !ast_test_flag(peer, SIP_REALTIME))
reg_source_db(peer);
ASTOBJ_UNMARK(peer);
ast_free_ha(oldha);
return peer;
}
/*! \brief reload_config: Re-read SIP.conf config file ---*/
/* This function reloads all config data, except for
active peers (with registrations). They will only
change configuration data at restart, not at reload.
SIP debug and recordhistory state will not change
*/
static int reload_config(void)
{
struct ast_config *cfg;
struct ast_variable *v;
struct sip_peer *peer;
struct sip_user *user;
struct ast_hostent ahp;
char *cat;
char *utype;
struct hostent *hp;
int format;
char iabuf[INET_ADDRSTRLEN];
struct ast_flags dummy;
int auto_sip_domains = 0;
struct sockaddr_in old_bindaddr = bindaddr;
cfg = ast_config_load(config);
/* We *must* have a config file otherwise stop immediately */
if (!cfg) {
ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
return -1;
}
/* Reset IP addresses */
memset(&bindaddr, 0, sizeof(bindaddr));
memset(&localaddr, 0, sizeof(localaddr));
memset(&externip, 0, sizeof(externip));
memset(&prefs, 0 , sizeof(prefs));
sipdebug &= ~SIP_DEBUG_CONFIG;
/* Initialize some reasonable defaults at SIP reload */
ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
default_subscribecontext[0] = '\0';
default_language[0] = '\0';
default_fromdomain[0] = '\0';
default_qualify = 0;
allow_external_domains = 1; /* Allow external invites */
externhost[0] = '\0';
externexpire = 0;
externrefresh = 10;
ast_copy_string(default_useragent, DEFAULT_USERAGENT, sizeof(default_useragent));
ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
global_notifyringing = 1;
global_alwaysauthreject = 0;
ast_copy_string(global_realm, DEFAULT_REALM, sizeof(global_realm));
ast_copy_string(global_musicclass, "default", sizeof(global_musicclass));
ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
memset(&outboundproxyip, 0, sizeof(outboundproxyip));
outboundproxyip.sin_port = htons(DEFAULT_SIP_PORT);
outboundproxyip.sin_family = AF_INET; /* Type of address: IPv4 */
videosupport = 0;
compactheaders = 0;
dumphistory = 0;
recordhistory = 0;
relaxdtmf = 0;
callevents = 0;
ourport = DEFAULT_SIP_PORT;
global_rtptimeout = 0;
global_rtpholdtimeout = 0;
global_rtpkeepalive = 0;
global_rtautoclear = 120;
pedanticsipchecking = 0;
global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
global_regattempts_max = 0;
ast_clear_flag(&global_flags, AST_FLAGS_ALL);
ast_clear_flag(&global_flags_page2, AST_FLAGS_ALL);
ast_set_flag(&global_flags, SIP_DTMF_RFC2833);
ast_set_flag(&global_flags, SIP_NAT_RFC3581);
ast_set_flag(&global_flags, SIP_CAN_REINVITE);
ast_set_flag(&global_flags_page2, SIP_PAGE2_RTUPDATE);
global_mwitime = DEFAULT_MWITIME;
strcpy(global_vmexten, DEFAULT_VMEXTEN);
srvlookup = 0;
autocreatepeer = 0;
regcontext[0] = '\0';
tos = 0;
expiry = DEFAULT_EXPIRY;
global_allowguest = 1;
/* Read the [general] config section of sip.conf (or from realtime config) */
v = ast_variable_browse(cfg, "general");
while(v) {
if (handle_common_options(&global_flags, &dummy, v)) {
v = v->next;
continue;
}
/* Create the interface list */
if (!strcasecmp(v->name, "context")) {
ast_copy_string(default_context, v->value, sizeof(default_context));
} else if (!strcasecmp(v->name, "realm")) {
ast_copy_string(global_realm, v->value, sizeof(global_realm));
} else if (!strcasecmp(v->name, "useragent")) {
ast_copy_string(default_useragent, v->value, sizeof(default_useragent));
ast_log(LOG_DEBUG, "Setting User Agent Name to %s\n",
default_useragent);
} else if (!strcasecmp(v->name, "rtcachefriends")) {
ast_set2_flag((&global_flags_page2), ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
} else if (!strcasecmp(v->name, "rtupdate")) {
ast_set2_flag((&global_flags_page2), ast_true(v->value), SIP_PAGE2_RTUPDATE);
} else if (!strcasecmp(v->name, "ignoreregexpire")) {
ast_set2_flag((&global_flags_page2), ast_true(v->value), SIP_PAGE2_IGNOREREGEXPIRE);
} else if (!strcasecmp(v->name, "rtautoclear")) {
int i = atoi(v->value);
if (i > 0)
global_rtautoclear = i;
else
i = 0;
ast_set2_flag((&global_flags_page2), i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
} else if (!strcasecmp(v->name, "usereqphone")) {
ast_set2_flag((&global_flags), ast_true(v->value), SIP_USEREQPHONE);
} else if (!strcasecmp(v->name, "relaxdtmf")) {
relaxdtmf = ast_true(v->value);
} else if (!strcasecmp(v->name, "checkmwi")) {
if ((sscanf(v->value, "%d", &global_mwitime) != 1) || (global_mwitime < 0)) {
ast_log(LOG_WARNING, "'%s' is not a valid MWI time setting at line %d. Using default (10).\n", v->value, v->lineno);
global_mwitime = DEFAULT_MWITIME;
}
} else if (!strcasecmp(v->name, "vmexten")) {
ast_copy_string(global_vmexten, v->value, sizeof(global_vmexten));
} else if (!strcasecmp(v->name, "rtptimeout")) {
if ((sscanf(v->value, "%d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
global_rtptimeout = 0;
}
} else if (!strcasecmp(v->name, "rtpholdtimeout")) {
if ((sscanf(v->value, "%d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
global_rtpholdtimeout = 0;
}
} else if (!strcasecmp(v->name, "rtpkeepalive")) {
if ((sscanf(v->value, "%d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
global_rtpkeepalive = 0;
}
} else if (!strcasecmp(v->name, "videosupport")) {
videosupport = ast_true(v->value);
} else if (!strcasecmp(v->name, "compactheaders")) {
compactheaders = ast_true(v->value);
} else if (!strcasecmp(v->name, "notifymimetype")) {
ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
} else if (!strcasecmp(v->name, "notifyringing")) {
global_notifyringing = ast_true(v->value);
} else if (!strcasecmp(v->name, "alwaysauthreject")) {
global_alwaysauthreject = ast_true(v->value);
} else if (!strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
ast_copy_string(global_musicclass, v->value, sizeof(global_musicclass));
} else if (!strcasecmp(v->name, "language")) {
ast_copy_string(default_language, v->value, sizeof(default_language));
} else if (!strcasecmp(v->name, "regcontext")) {
ast_copy_string(regcontext, v->value, sizeof(regcontext));
/* Create context if it doesn't exist already */
if (!ast_context_find(regcontext))
ast_context_create(NULL, regcontext, channeltype);
} else if (!strcasecmp(v->name, "callerid")) {
ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
} else if (!strcasecmp(v->name, "fromdomain")) {
ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
} else if (!strcasecmp(v->name, "outboundproxy")) {
if (ast_get_ip_or_srv(&outboundproxyip, v->value, srvlookup ? "_sip._udp" : NULL) < 0)
ast_log(LOG_WARNING, "Unable to locate host '%s'\n", v->value);
} else if (!strcasecmp(v->name, "outboundproxyport")) {
/* Port needs to be after IP */
sscanf(v->value, "%d", &format);
outboundproxyip.sin_port = htons(format);
} else if (!strcasecmp(v->name, "autocreatepeer")) {
autocreatepeer = ast_true(v->value);
} else if (!strcasecmp(v->name, "srvlookup")) {
srvlookup = ast_true(v->value);
} else if (!strcasecmp(v->name, "pedantic")) {
pedanticsipchecking = ast_true(v->value);
} else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
max_expiry = atoi(v->value);
if (max_expiry < 1)
max_expiry = DEFAULT_MAX_EXPIRY;
} else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
default_expiry = atoi(v->value);
if (default_expiry < 1)
default_expiry = DEFAULT_DEFAULT_EXPIRY;
} else if (!strcasecmp(v->name, "sipdebug")) {
if (ast_true(v->value))
sipdebug |= SIP_DEBUG_CONFIG;
} else if (!strcasecmp(v->name, "dumphistory")) {
dumphistory = ast_true(v->value);
} else if (!strcasecmp(v->name, "recordhistory")) {
recordhistory = ast_true(v->value);
} else if (!strcasecmp(v->name, "registertimeout")) {
global_reg_timeout = atoi(v->value);
if (global_reg_timeout < 1)
global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
} else if (!strcasecmp(v->name, "registerattempts")) {
global_regattempts_max = atoi(v->value);
} else if (!strcasecmp(v->name, "bindaddr")) {
if (!(hp = ast_gethostbyname(v->value, &ahp))) {
ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
} else {
memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
}
} else if (!strcasecmp(v->name, "localnet")) {
struct ast_ha *na;
if (!(na = ast_append_ha("d", v->value, localaddr)))
ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
else
localaddr = na;
} else if (!strcasecmp(v->name, "localmask")) {
ast_log(LOG_WARNING, "Use of localmask is no long supported -- use localnet with mask syntax\n");
} else if (!strcasecmp(v->name, "externip")) {
if (!(hp = ast_gethostbyname(v->value, &ahp)))
ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
else
memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
externexpire = 0;
} else if (!strcasecmp(v->name, "externhost")) {
ast_copy_string(externhost, v->value, sizeof(externhost));
if (!(hp = ast_gethostbyname(externhost, &ahp)))
ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
else
memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
time(&externexpire);
} else if (!strcasecmp(v->name, "externrefresh")) {
if (sscanf(v->value, "%d", &externrefresh) != 1) {
ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
externrefresh = 10;
}
} else if (!strcasecmp(v->name, "allow")) {
ast_parse_allow_disallow(&prefs, &global_capability, v->value, 1);
} else if (!strcasecmp(v->name, "disallow")) {
ast_parse_allow_disallow(&prefs, &global_capability, v->value, 0);
} else if (!strcasecmp(v->name, "allowexternaldomains")) {
allow_external_domains = ast_true(v->value);
} else if (!strcasecmp(v->name, "autodomain")) {
auto_sip_domains = ast_true(v->value);
} else if (!strcasecmp(v->name, "domain")) {
char *domain = ast_strdupa(v->value);
char *context = strchr(domain, ',');
if (context)
*context++ = '\0';
if (option_debug && ast_strlen_zero(context))
ast_log(LOG_DEBUG, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
if (ast_strlen_zero(domain))
ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
else
add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
} else if (!strcasecmp(v->name, "register")) {
sip_register(v->value, v->lineno);
} else if (!strcasecmp(v->name, "tos")) {
if (ast_str2tos(v->value, &tos))
ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
} else if (!strcasecmp(v->name, "bindport")) {
if (sscanf(v->value, "%d", &ourport) == 1) {
bindaddr.sin_port = htons(ourport);
} else {
ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
}
} else if (!strcasecmp(v->name, "qualify")) {
if (!strcasecmp(v->value, "no")) {
default_qualify = 0;
} else if (!strcasecmp(v->value, "yes")) {
default_qualify = DEFAULT_MAXMS;
} else if (sscanf(v->value, "%d", &default_qualify) != 1) {
ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
default_qualify = 0;
}
} else if (!strcasecmp(v->name, "callevents")) {
callevents = ast_true(v->value);
}
/* else if (strcasecmp(v->name,"type"))
* ast_log(LOG_WARNING, "Ignoring %s\n", v->name);
*/
v = v->next;
}
if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
allow_external_domains = 1;
}
/* Build list of authentication to various SIP realms, i.e. service providers */
v = ast_variable_browse(cfg, "authentication");
while(v) {
/* Format for authentication is auth = username:password@realm */
if (!strcasecmp(v->name, "auth")) {
authl = add_realm_authentication(authl, v->value, v->lineno);
}
v = v->next;
}
/* Load peers, users and friends */
cat = ast_category_browse(cfg, NULL);
while(cat) {
if (strcasecmp(cat, "general") && strcasecmp(cat, "authentication")) {
utype = ast_variable_retrieve(cfg, cat, "type");
if (utype) {
if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
user = build_user(cat, ast_variable_browse(cfg, cat), 0);
if (user) {
ASTOBJ_CONTAINER_LINK(&userl,user);
ASTOBJ_UNREF(user, sip_destroy_user);
}
}
if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
peer = build_peer(cat, ast_variable_browse(cfg, cat), 0);
if (peer) {
ASTOBJ_CONTAINER_LINK(&peerl,peer);
ASTOBJ_UNREF(peer, sip_destroy_peer);
}
} else if (strcasecmp(utype, "user")) {
ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
}
} else
ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
}
cat = ast_category_browse(cfg, cat);
}
if (ast_find_ourip(&__ourip, bindaddr)) {
ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
return 0;
}
if (!ntohs(bindaddr.sin_port))
bindaddr.sin_port = ntohs(DEFAULT_SIP_PORT);
bindaddr.sin_family = AF_INET;
ast_mutex_lock(&netlock);
if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
close(sipsock);
sipsock = -1;
}
if (sipsock < 0) {
sipsock = socket(AF_INET, SOCK_DGRAM, 0);
if (sipsock < 0) {
ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
} else {
/* Allow SIP clients on the same host to access us: */
const int reuseFlag = 1;
setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
(const char*)&reuseFlag,
sizeof reuseFlag);
ast_enable_packet_fragmentation(sipsock);
if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
ast_inet_ntoa(iabuf, sizeof(iabuf), bindaddr.sin_addr), ntohs(bindaddr.sin_port),
strerror(errno));
close(sipsock);
sipsock = -1;
} else {
if (option_verbose > 1) {
ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on %s:%d\n",
ast_inet_ntoa(iabuf, sizeof(iabuf), bindaddr.sin_addr), ntohs(bindaddr.sin_port));
ast_verbose(VERBOSE_PREFIX_2 "Using TOS bits %d\n", tos);
}
if (setsockopt(sipsock, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)))
ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
}
}
}
ast_mutex_unlock(&netlock);
/* Add default domains - host name, IP address and IP:port */
/* Only do this if user added any sip domain with "localdomains" */
/* In order to *not* break backwards compatibility */
/* Some phones address us at IP only, some with additional port number */
if (auto_sip_domains) {
char temp[MAXHOSTNAMELEN];
/* First our default IP address */
if (bindaddr.sin_addr.s_addr) {
ast_inet_ntoa(temp, sizeof(temp), bindaddr.sin_addr);
add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
} else {
ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
}
/* Our extern IP address, if configured */
if (externip.sin_addr.s_addr) {
ast_inet_ntoa(temp, sizeof(temp), externip.sin_addr);
add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
}
/* Extern host name (NAT traversal support) */
if (!ast_strlen_zero(externhost))
add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
/* Our host name */
if (!gethostname(temp, sizeof(temp)))
add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
}
/* Release configuration from memory */
ast_config_destroy(cfg);
/* Load the list of manual NOTIFY types to support */
if (notify_types)
ast_config_destroy(notify_types);
notify_types = ast_config_load(notify_config);
return 0;
}
/*! \brief sip_get_rtp_peer: Returns null if we can't reinvite (part of RTP interface) */
static struct ast_rtp *sip_get_rtp_peer(struct ast_channel *chan)
{
struct sip_pvt *p;
struct ast_rtp *rtp = NULL;
p = chan->tech_pvt;
if (!p)
return NULL;
ast_mutex_lock(&p->lock);
if (p->rtp && ast_test_flag(p, SIP_CAN_REINVITE))
rtp = p->rtp;
ast_mutex_unlock(&p->lock);
return rtp;
}
/*! \brief sip_get_vrtp_peer: Returns null if we can't reinvite video (part of RTP interface) */
static struct ast_rtp *sip_get_vrtp_peer(struct ast_channel *chan)
{
struct sip_pvt *p;
struct ast_rtp *rtp = NULL;
p = chan->tech_pvt;
if (!p)
return NULL;
ast_mutex_lock(&p->lock);
if (p->vrtp && ast_test_flag(p, SIP_CAN_REINVITE))
rtp = p->vrtp;
ast_mutex_unlock(&p->lock);
return rtp;
}
/*! \brief sip_set_rtp_peer: Set the RTP peer for this call ---*/
static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
{
struct sip_pvt *p;
int changed = 0;
p = chan->tech_pvt;
if (!p)
return -1;
ast_mutex_lock(&p->lock);
if (rtp) {
changed |= ast_rtp_get_peer(rtp, &p->redirip);
} else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
memset(&p->redirip, 0, sizeof(p->redirip));
changed = 1;
}
if (vrtp) {
changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
} else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
memset(&p->vredirip, 0, sizeof(p->vredirip));
changed = 1;
}
if (codecs && (p->redircodecs != codecs)) {
p->redircodecs = codecs;
changed = 1;
}
if (changed && !ast_test_flag(p, SIP_GOTREFER)) {
if (!p->pendinginvite) {
if (option_debug > 2) {
char iabuf[INET_ADDRSTRLEN];
ast_log(LOG_DEBUG, "Sending reinvite on SIP '%s' - It's audio soon redirected to IP %s\n", p->callid, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp ? p->redirip.sin_addr : p->ourip));
}
transmit_reinvite_with_sdp(p);
} else if (!ast_test_flag(p, SIP_PENDINGBYE)) {
if (option_debug > 2) {
char iabuf[INET_ADDRSTRLEN];
ast_log(LOG_DEBUG, "Deferring reinvite on SIP '%s' - It's audio will be redirected to IP %s\n", p->callid, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp ? p->redirip.sin_addr : p->ourip));
}
ast_set_flag(p, SIP_NEEDREINVITE);
}
}
/* Reset lastrtprx timer */
time(&p->lastrtprx);
time(&p->lastrtptx);
ast_mutex_unlock(&p->lock);
return 0;
}
static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
static char *descrip_dtmfmode = "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
static char *app_dtmfmode = "SIPDtmfMode";
static char *app_sipaddheader = "SIPAddHeader";
static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
static char *descrip_sipaddheader = ""
" SIPAddHeader(Header: Content)\n"
"Adds a header to a SIP call placed with DIAL.\n"
"Remember to user the X-header if you are adding non-standard SIP\n"
"headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
"Adding the wrong headers may jeopardize the SIP dialog.\n"
"Always returns 0\n";
static char *app_sipgetheader = "SIPGetHeader";
static char *synopsis_sipgetheader = "Get a SIP header from an incoming call";
static char *descrip_sipgetheader = ""
" SIPGetHeader(var=headername[|options]): \n"
"Sets a channel variable to the content of a SIP header\n"
" Options:\n"
" j - Jump to priority n+101 if the requested header isn't found.\n"
" This application sets the following channel variable upon completion:\n"
" SIPGETSTATUS - This variable will contain the status of the attempt\n"
" FOUND | NOTFOUND\n"
" This application has been deprecated in favor of the SIP_HEADER function.\n";
/*! \brief sip_dtmfmode: change the DTMFmode for a SIP call (application) ---*/
static int sip_dtmfmode(struct ast_channel *chan, void *data)
{
struct sip_pvt *p;
char *mode;
if (data)
mode = (char *)data;
else {
ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
return 0;
}
ast_mutex_lock(&chan->lock);
if (chan->type != channeltype) {
ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
ast_mutex_unlock(&chan->lock);
return 0;
}
p = chan->tech_pvt;
if (!p) {
ast_mutex_unlock(&chan->lock);
return 0;
}
ast_mutex_lock(&p->lock);
if (!strcasecmp(mode,"info")) {
ast_clear_flag(p, SIP_DTMF);
ast_set_flag(p, SIP_DTMF_INFO);
} else if (!strcasecmp(mode,"rfc2833")) {
ast_clear_flag(p, SIP_DTMF);
ast_set_flag(p, SIP_DTMF_RFC2833);
} else if (!strcasecmp(mode,"inband")) {
ast_clear_flag(p, SIP_DTMF);
ast_set_flag(p, SIP_DTMF_INBAND);
} else
ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n",mode);
if (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) {
if (!p->vad) {
p->vad = ast_dsp_new();
ast_dsp_set_features(p->vad, DSP_FEATURE_DTMF_DETECT);
}
} else {
if (p->vad) {
ast_dsp_free(p->vad);
p->vad = NULL;
}
}
ast_mutex_unlock(&p->lock);
ast_mutex_unlock(&chan->lock);
return 0;
}
/*! \brief sip_addheader: Add a SIP header ---*/
static int sip_addheader(struct ast_channel *chan, void *data)
{
int no = 0;
int ok = 0;
char varbuf[128];
if (ast_strlen_zero((char *)data)) {
ast_log(LOG_WARNING, "This application requires the argument: Header\n");
return 0;
}
ast_mutex_lock(&chan->lock);
/* Check for headers */
while (!ok && no <= 50) {
no++;
snprintf(varbuf, sizeof(varbuf), "_SIPADDHEADER%02d", no);
if (ast_strlen_zero(pbx_builtin_getvar_helper(chan, varbuf + 1)))
ok = 1;
}
if (ok) {
pbx_builtin_setvar_helper (chan, varbuf, (char *)data);
if (sipdebug)
ast_log(LOG_DEBUG,"SIP Header added \"%s\" as %s\n", (char *) data, varbuf);
} else {
ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
}
ast_mutex_unlock(&chan->lock);
return 0;
}
/*! \brief sip_getheader: Get a SIP header (dialplan app) ---*/
static int sip_getheader(struct ast_channel *chan, void *data)
{
char *argv, *varname = NULL, *header = NULL, *content, *options = NULL;
static int dep_warning = 0;
struct sip_pvt *p;
int priority_jump = 0;
if (!dep_warning) {
ast_log(LOG_WARNING, "SIPGetHeader is deprecated, use the SIP_HEADER function instead.\n");
dep_warning = 1;
}
argv = ast_strdupa(data);
if (!argv) {
ast_log(LOG_DEBUG, "Memory allocation failed\n");
return 0;
}
if (strchr (argv, '=') ) { /* Pick out argument */
varname = strsep (&argv, "=");
if (strchr(argv, '|')) {
header = strsep (&argv, "|");
options = strsep (&argv, "\0");
} else {
header = strsep (&argv, "\0");
}
}
if (!varname || !header) {
ast_log(LOG_DEBUG, "SIPGetHeader: Ignoring command, Syntax error in argument\n");
return 0;
}
if (options) {
if (strchr(options, 'j'))
priority_jump = 1;
}
ast_mutex_lock(&chan->lock);
if (chan->type != channeltype) {
ast_log(LOG_WARNING, "Call this application only on incoming SIP calls\n");
ast_mutex_unlock(&chan->lock);
return 0;
}
p = chan->tech_pvt;
content = get_header(&p->initreq, header); /* Get the header */
if (!ast_strlen_zero(content)) {
pbx_builtin_setvar_helper(chan, varname, content);
if (option_verbose > 2)
ast_verbose(VERBOSE_PREFIX_3 "SIPGetHeader: set variable %s to %s\n", varname, content);
pbx_builtin_setvar_helper(chan, "SIPGETSTATUS", "FOUND");
} else {
ast_log(LOG_WARNING,"SIP Header %s not found for channel variable %s\n", header, varname);
if (priority_jump || option_priority_jumping) {
/* Goto priority n+101 if it exists, where n is the current priority number */
ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101);
}
pbx_builtin_setvar_helper(chan, "SIPGETSTATUS", "NOTFOUND");
}
ast_mutex_unlock(&chan->lock);
return 0;
}
/*! \brief sip_sipredirect: Transfer call before connect with a 302 redirect ---*/
/* Called by the transfer() dialplan application through the sip_transfer() */
/* pbx interface function if the call is in ringing state */
/* coded by Martin Pycko (m78pl@yahoo.com) */
static int sip_sipredirect(struct sip_pvt *p, const char *dest)
{
char *cdest;
char *extension, *host, *port;
char tmp[80];
cdest = ast_strdupa(dest);
if (!cdest) {
ast_log(LOG_ERROR, "Problem allocating the memory\n");
return 0;
}
extension = strsep(&cdest, "@");
host = strsep(&cdest, ":");
port = strsep(&cdest, ":");
if (!extension) {
ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
return 0;
}
/* we'll issue the redirect message here */
if (!host) {
char *localtmp;
ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
if (!strlen(tmp)) {
ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
return 0;
}
if ((localtmp = strstr(tmp, "sip:")) && (localtmp = strchr(localtmp, '@'))) {
char lhost[80], lport[80];
memset(lhost, 0, sizeof(lhost));
memset(lport, 0, sizeof(lport));
localtmp++;
/* This is okey because lhost and lport are as big as tmp */
sscanf(localtmp, "%[^<>:; ]:%[^<>:; ]", lhost, lport);
if (!strlen(lhost)) {
ast_log(LOG_ERROR, "Can't find the host address\n");
return 0;
}
host = ast_strdupa(lhost);
if (!host) {
ast_log(LOG_ERROR, "Problem allocating the memory\n");
return 0;
}
if (!ast_strlen_zero(lport)) {
port = ast_strdupa(lport);
if (!port) {
ast_log(LOG_ERROR, "Problem allocating the memory\n");
return 0;
}
}
}
}
snprintf(p->our_contact, sizeof(p->our_contact), "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq, 1);
/* this is all that we want to send to that SIP device */
ast_set_flag(p, SIP_ALREADYGONE);
/* hangup here */
return -1;
}
/*! \brief sip_get_codec: Return SIP UA's codec (part of the RTP interface) ---*/
static int sip_get_codec(struct ast_channel *chan)
{
struct sip_pvt *p = chan->tech_pvt;
return p->peercapability;
}
/*! \brief sip_rtp: Interface structure with callbacks used to connect to rtp module --*/
static struct ast_rtp_protocol sip_rtp = {
type: channeltype,
get_rtp_info: sip_get_rtp_peer,
get_vrtp_info: sip_get_vrtp_peer,
set_rtp_peer: sip_set_rtp_peer,
get_codec: sip_get_codec,
};
/*! \brief sip_poke_all_peers: Send a poke to all known peers */
static void sip_poke_all_peers(void)
{
ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
ASTOBJ_WRLOCK(iterator);
sip_poke_peer(iterator);
ASTOBJ_UNLOCK(iterator);
} while (0)
);
}
/*! \brief sip_send_all_registers: Send all known registrations */
static void sip_send_all_registers(void)
{
int ms;
int regspacing;
if (!regobjs)
return;
regspacing = default_expiry * 1000/regobjs;
if (regspacing > 100)
regspacing = 100;
ms = regspacing;
ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
ASTOBJ_WRLOCK(iterator);
if (iterator->expire > -1)
ast_sched_del(sched, iterator->expire);
ms += regspacing;
iterator->expire = ast_sched_add(sched, ms, sip_reregister, iterator);
ASTOBJ_UNLOCK(iterator);
} while (0)
);
}
/*! \brief sip_do_reload: Reload module */
static int sip_do_reload(void)
{
clear_realm_authentication(authl);
clear_sip_domains();
authl = NULL;
/* First, destroy all outstanding registry calls */
/* This is needed, since otherwise active registry entries will not be destroyed */
ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
ASTOBJ_RDLOCK(iterator);
if (iterator->call) {
if (option_debug > 2)
ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
/* This will also remove references to the registry */
sip_destroy(iterator->call);
}
ASTOBJ_UNLOCK(iterator);
} while(0));
ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
ASTOBJ_CONTAINER_MARKALL(&peerl);
reload_config();
/* Prune peers who still are supposed to be deleted */
ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
sip_poke_all_peers();
sip_send_all_registers();
return 0;
}
/*! \brief sip_reload: Force reload of module from cli ---*/
static int sip_reload(int fd, int argc, char *argv[])
{
ast_mutex_lock(&sip_reload_lock);
if (sip_reloading) {
ast_verbose("Previous SIP reload not yet done\n");
} else
sip_reloading = 1;
ast_mutex_unlock(&sip_reload_lock);
restart_monitor();
return 0;
}
/*! \brief reload: Part of Asterisk module interface ---*/
int reload(void)
{
return sip_reload(0, 0, NULL);
}
static struct ast_cli_entry my_clis[] = {
{ { "sip", "notify", NULL }, sip_notify, "Send a notify packet to a SIP peer", notify_usage, complete_sipnotify },
{ { "sip", "show", "objects", NULL }, sip_show_objects, "Show all SIP object allocations", show_objects_usage },
{ { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage },
{ { "sip", "show", "user", NULL }, sip_show_user, "Show details on specific SIP user", show_user_usage, complete_sip_show_user },
{ { "sip", "show", "subscriptions", NULL }, sip_show_subscriptions, "Show active SIP subscriptions", show_subscriptions_usage},
{ { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage},
{ { "sip", "show", "channel", NULL }, sip_show_channel, "Show detailed SIP channel info", show_channel_usage, complete_sipch },
{ { "sip", "show", "history", NULL }, sip_show_history, "Show SIP dialog history", show_history_usage, complete_sipch },
{ { "sip", "show", "domains", NULL }, sip_show_domains, "List our local SIP domains.", show_domains_usage },
{ { "sip", "show", "settings", NULL }, sip_show_settings, "Show SIP global settings", show_settings_usage },
{ { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage },
{ { "sip", "debug", "ip", NULL }, sip_do_debug, "Enable SIP debugging on IP", debug_usage },
{ { "sip", "debug", "peer", NULL }, sip_do_debug, "Enable SIP debugging on Peername", debug_usage, complete_sip_debug_peer },
{ { "sip", "show", "peer", NULL }, sip_show_peer, "Show details on specific SIP peer", show_peer_usage, complete_sip_show_peer },
{ { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage },
{ { "sip", "prune", "realtime", NULL }, sip_prune_realtime,
"Prune cached Realtime object(s)", prune_realtime_usage },
{ { "sip", "prune", "realtime", "peer", NULL }, sip_prune_realtime,
"Prune cached Realtime peer(s)", prune_realtime_usage, complete_sip_prune_realtime_peer },
{ { "sip", "prune", "realtime", "user", NULL }, sip_prune_realtime,
"Prune cached Realtime user(s)", prune_realtime_usage, complete_sip_prune_realtime_user },
{ { "sip", "show", "inuse", NULL }, sip_show_inuse, "List all inuse/limits", show_inuse_usage },
{ { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage },
{ { "sip", "history", NULL }, sip_do_history, "Enable SIP history", history_usage },
{ { "sip", "no", "history", NULL }, sip_no_history, "Disable SIP history", no_history_usage },
{ { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage },
{ { "sip", "reload", NULL }, sip_reload, "Reload SIP configuration", sip_reload_usage },
};
/*! \brief load_module: PBX load module - initialization ---*/
int load_module()
{
ASTOBJ_CONTAINER_INIT(&userl); /* User object list */
ASTOBJ_CONTAINER_INIT(&peerl); /* Peer object list */
ASTOBJ_CONTAINER_INIT(®l); /* Registry object list */
sched = sched_context_create();
if (!sched) {
ast_log(LOG_WARNING, "Unable to create schedule context\n");
}
io = io_context_create();
if (!io) {
ast_log(LOG_WARNING, "Unable to create I/O context\n");
}
reload_config(); /* Load the configuration from sip.conf */
/* Make sure we can register our sip channel type */
if (ast_channel_register(&sip_tech)) {
ast_log(LOG_ERROR, "Unable to register channel type %s\n", channeltype);
return -1;
}
/* Register all CLI functions for SIP */
ast_cli_register_multiple(my_clis, sizeof(my_clis)/ sizeof(my_clis[0]));
/* Tell the RTP subdriver that we're here */
ast_rtp_proto_register(&sip_rtp);
/* Register dialplan applications */
ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
/* These will be removed soon */
ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
ast_register_application(app_sipgetheader, sip_getheader, synopsis_sipgetheader, descrip_sipgetheader);
/* Register dialplan functions */
ast_custom_function_register(&sip_header_function);
ast_custom_function_register(&sippeer_function);
ast_custom_function_register(&sipchaninfo_function);
ast_custom_function_register(&checksipdomain_function);
/* Register manager commands */
ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM, manager_sip_show_peers,
"List SIP peers (text format)", mandescr_show_peers);
ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM, manager_sip_show_peer,
"Show SIP peer (text format)", mandescr_show_peer);
sip_poke_all_peers();
sip_send_all_registers();
/* And start the monitor for the first time */
restart_monitor();
return 0;
}
int unload_module()
{
struct sip_pvt *p, *pl;
/* First, take us out of the channel type list */
ast_channel_unregister(&sip_tech);
ast_custom_function_unregister(&sipchaninfo_function);
ast_custom_function_unregister(&sippeer_function);
ast_custom_function_unregister(&sip_header_function);
ast_custom_function_unregister(&checksipdomain_function);
ast_unregister_application(app_dtmfmode);
ast_unregister_application(app_sipaddheader);
ast_unregister_application(app_sipgetheader);
ast_cli_unregister_multiple(my_clis, sizeof(my_clis) / sizeof(my_clis[0]));
ast_rtp_proto_unregister(&sip_rtp);
ast_manager_unregister("SIPpeers");
ast_manager_unregister("SIPshowpeer");
if (!ast_mutex_lock(&iflock)) {
/* Hangup all interfaces if they have an owner */
p = iflist;
while (p) {
if (p->owner)
ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
p = p->next;
}
ast_mutex_unlock(&iflock);
} else {
ast_log(LOG_WARNING, "Unable to lock the interface list\n");
return -1;
}
if (!ast_mutex_lock(&monlock)) {
if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
pthread_cancel(monitor_thread);
pthread_kill(monitor_thread, SIGURG);
pthread_join(monitor_thread, NULL);
}
monitor_thread = AST_PTHREADT_STOP;
ast_mutex_unlock(&monlock);
} else {
ast_log(LOG_WARNING, "Unable to lock the monitor\n");
return -1;
}
if (!ast_mutex_lock(&iflock)) {
/* Destroy all the interfaces and free their memory */
p = iflist;
while (p) {
pl = p;
p = p->next;
/* Free associated memory */
ast_mutex_destroy(&pl->lock);
if (pl->chanvars) {
ast_variables_destroy(pl->chanvars);
pl->chanvars = NULL;
}
free(pl);
}
iflist = NULL;
ast_mutex_unlock(&iflock);
} else {
ast_log(LOG_WARNING, "Unable to lock the interface list\n");
return -1;
}
/* Free memory for local network address mask */
ast_free_ha(localaddr);
ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
ASTOBJ_CONTAINER_DESTROY(&userl);
ASTOBJ_CONTAINER_DESTROYALL(&peerl, sip_destroy_peer);
ASTOBJ_CONTAINER_DESTROY(&peerl);
ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
ASTOBJ_CONTAINER_DESTROY(®l);
clear_realm_authentication(authl);
clear_sip_domains();
close(sipsock);
sched_context_destroy(sched);
return 0;
}
int usecount()
{
return usecnt;
}
char *key()
{
return ASTERISK_GPL_KEY;
}
char *description()
{
return (char *) desc;
}
|