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 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729
|
/*
* %CopyrightBegin%
*
* Copyright Ericsson AB 1997-2022. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* %CopyrightEnd%
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* If we HAVE_SCTP_H and Solaris, we need to define the following in
* order to get SCTP working:
*/
#if (defined(HAVE_SCTP_H) && defined(__sun) && defined(__SVR4))
#define SOLARIS10 1
/* WARNING: This is not quite correct, it may also be Solaris 11! */
#define _XPG4_2
#define __EXTENSIONS__
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <ctype.h>
#include <sys/types.h>
#include <errno.h>
#include <stdint.h>
#define IDENTITY(c) c
#define STRINGIFY_1(b) IDENTITY(#b)
#define STRINGIFY(a) STRINGIFY_1(a)
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_UIO_H
#include <sys/uio.h>
#endif
#ifdef HAVE_NET_IF_DL_H
#include <net/if_dl.h>
#endif
#ifdef HAVE_IFADDRS_H
#include <ifaddrs.h>
#endif
#ifdef HAVE_NETPACKET_PACKET_H
#include <netpacket/packet.h>
#endif
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#ifdef HAVE_SENDFILE
#if defined(__linux__) || (defined(__sun) && defined(__SVR4))
#include <sys/sendfile.h>
#elif defined(__FreeBSD__) || defined(__DragonFly__)
/* Need to define __BSD_VISIBLE in order to expose prototype of sendfile */
#define __BSD_VISIBLE 1
#include <sys/socket.h>
#endif
#endif
#if defined(__APPLE__) && defined(__MACH__) && !defined(__DARWIN__)
#define __DARWIN__ 1
#endif
/* All platforms fail on malloc errors. */
#define FATAL_MALLOC
/* The linux kernel sctp include files have an alignment bug
that causes warnings of this type to appear:
drivers/common/inet_drv.c:3196:47: error: taking address of packed member of 'struct sctp_paddr_change' may result in an unaligned pointer value [-Werror=address-of-packed-member]
3196 | i = load_inet_get_address(spec, i, desc, &sptr->spc_aaddr);
So we need to suppress those, without disabling all warning
diagnostics of that type.
See https://lore.kernel.org/patchwork/patch/1108122/ for the
patch that fixes this bug. In a few years we should be able to
remove this suppression. */
#ifdef HAVE_GCC_DIAG_IGNORE_WADDRESS_OF_PACKED_MEMBER
#define PUSH_SUPPRESS_ADDRESS_OF_PACKED_MEMBER() \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Waddress-of-packed-member\"") \
do { } while(0)
#define POP_SUPPRESS_ADDRESS_OF_PACKED_MEMBER() \
_Pragma("GCC diagnostic pop") \
do { } while(0)
#else
#define PUSH_SUPPRESS_ADDRESS_OF_PACKED_MEMBER() \
do { } while(0)
#define POP_SUPPRESS_ADDRESS_OF_PACKED_MEMBER() \
do { } while(0)
#endif
#include "erl_driver.h"
#if !defined(TRUE)
#define TRUE 1
#endif
#if !defined(FALSE)
#define FALSE 0
#endif
/* Descriptor debug */
#ifdef INET_DRV_DEBUG
#define DDBG_DEFAULT TRUE
#else
#define DDBG_DEFAULT FALSE
#endif
#define DDBG(__D__, __ARG__) if ( (__D__)->debug ) erts_printf __ARG__
#define B2S(__B__) ((__B__) ? "true" : "false")
#define SH2S(__H__) (((__H__) == TCP_SHUT_WR) ? "write" : \
(((__H__) == TCP_SHUT_RD) ? "read" : \
(((__H__) == TCP_SHUT_RDWR) ? "read-write" : \
"undefined")))
#define A2S(__A__) (((__A__) == INET_PASSIVE) ? "passive" : \
(((__A__) == INET_ACTIVE) ? "active" : \
(((__A__) == INET_ONCE) ? "once" : \
(((__A__) == INET_MULTI) ? "multi" : \
"undefined"))))
#define M2S(__M__) (((__M__) == INET_MODE_LIST) ? "list" : \
(((__M__) == INET_MODE_BINARY) ? "binary" : \
"undefined"))
#define D2S(__D__) (((__D__) == INET_DELIVER_PORT) ? "port" : \
(((__D__) == INET_DELIVER_TERM) ? "term" : \
"undefined"))
#define DOM2S(__D__) (((__D__) == INET_AF_INET) ? "inet" : \
(((__D__) == INET_AF_INET6) ? "inet6" : \
(((__D__) == INET_AF_LOCAL) ? "local" : \
"undefined")))
#if defined(__WIN32__) && defined(ARCH_64)
#define SOCKET_FSTR "%lld"
#else
#define SOCKET_FSTR "%d"
#endif
/* The IS_SOCKET_ERROR macro below is used for portability reasons. While
POSIX specifies that errors from socket-related system calls should be
indicated with a -1 return value, some users have experienced non-Windows
OS kernels that return negative values other than -1. While one can argue
that such kernels are technically broken, comparing against values less
than 0 covers their out-of-spec return values without imposing incorrect
semantics on systems that manage to correctly return -1 for errors, thus
increasing Erlang's portability.
*/
#ifdef __WIN32__
#define IS_SOCKET_ERROR(val) ((val) == SOCKET_ERROR)
#else
#define IS_SOCKET_ERROR(val) ((val) < 0)
#endif
#ifdef __WIN32__
#define LLU "%I64u"
#else
#define LLU "%llu"
#endif
typedef unsigned long long llu_t;
#ifndef INT16_MIN
#define INT16_MIN (-32768)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifdef __WIN32__
#define STRNCASECMP strncasecmp
#define INCL_WINSOCK_API_TYPEDEFS 1
#ifndef WINDOWS_H_INCLUDES_WINSOCK2_H
#include <winsock2.h>
#endif
#include <windows.h>
#include <Ws2tcpip.h> /* NEED VC 6.0 or higher */
/* Visual studio 2008+: NTDDI_VERSION needs to be set for iphlpapi.h
to define the right structures. It needs to be set to WINXP (or LONGHORN)
for IPV6 to work and it's set lower by default, so we need to change it. */
#ifdef HAVE_SDKDDKVER_H
# include <sdkddkver.h>
# ifdef NTDDI_VERSION
# undef NTDDI_VERSION
# endif
# define NTDDI_VERSION NTDDI_WINXP
#endif
#include <iphlpapi.h>
#undef WANT_NONBLOCKING
#include "sys.h"
#undef EWOULDBLOCK
#undef ETIMEDOUT
#ifdef EINPROGRESS
#undef EINPROGRESS
#endif
#ifdef EALREADY
#undef EALREADY
#endif
#ifdef ENOTSOCK
#undef ENOTSOCK
#endif
#ifdef EDESTADDRREQ
#undef EDESTADDRREQ
#endif
#ifdef EMSGSIZE
#undef EMSGSIZE
#endif
#ifdef EPROTOTYPE
#undef EPROTOTYPE
#endif
#ifdef ENOPROTOOPT
#undef ENOPROTOOPT
#endif
#ifdef EPROTONOSUPPORT
#undef EPROTONOSUPPORT
#endif
#ifdef EOPNOTSUPP
#undef EOPNOTSUPP
#endif
#ifdef EAFNOSUPPORT
#undef EAFNOSUPPORT
#endif
#ifdef EADDRINUSE
#undef EADDRINUSE
#endif
#ifdef EADDRNOTAVAIL
#undef EADDRNOTAVAIL
#endif
#ifdef ENETDOWN
#undef ENETDOWN
#endif
#ifdef ENETUNREACH
#undef ENETUNREACH
#endif
#ifdef ENETRESET
#undef ENETRESET
#endif
#ifdef ECONNABORTED
#undef ECONNABORTED
#endif
#ifdef ECONNRESET
#undef ECONNRESET
#endif
#ifdef ENOBUFS
#undef ENOBUFS
#endif
#ifdef EISCONN
#undef EISCONN
#endif
#ifdef ENOTCONN
#undef ENOTCONN
#endif
#ifdef ECONNREFUSED
#undef ECONNREFUSED
#endif
#ifdef ELOOP
#undef ELOOP
#endif
#ifdef EHOSTUNREACH
#undef EHOSTUNREACH
#endif
#define HAVE_MULTICAST_SUPPORT
#define HAVE_UDP
#define ERRNO_BLOCK WSAEWOULDBLOCK
#define EWOULDBLOCK WSAEWOULDBLOCK
#define EINPROGRESS WSAEINPROGRESS
#define EALREADY WSAEALREADY
#define ENOTSOCK WSAENOTSOCK
#define EDESTADDRREQ WSAEDESTADDRREQ
#define EMSGSIZE WSAEMSGSIZE
#define EPROTOTYPE WSAEPROTOTYPE
#define ENOPROTOOPT WSAENOPROTOOPT
#define EPROTONOSUPPORT WSAEPROTONOSUPPORT
#define ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT
#define EOPNOTSUPP WSAEOPNOTSUPP
#define EPFNOSUPPORT WSAEPFNOSUPPORT
#define EAFNOSUPPORT WSAEAFNOSUPPORT
#define EADDRINUSE WSAEADDRINUSE
#define EADDRNOTAVAIL WSAEADDRNOTAVAIL
#define ENETDOWN WSAENETDOWN
#define ENETUNREACH WSAENETUNREACH
#define ENETRESET WSAENETRESET
#define ECONNABORTED WSAECONNABORTED
#define ECONNRESET WSAECONNRESET
#define ENOBUFS WSAENOBUFS
#define EISCONN WSAEISCONN
#define ENOTCONN WSAENOTCONN
#define ESHUTDOWN WSAESHUTDOWN
#define ETOOMANYREFS WSAETOOMANYREFS
#define ETIMEDOUT WSAETIMEDOUT
#define ECONNREFUSED WSAECONNREFUSED
#define ELOOP WSAELOOP
#undef ENAMETOOLONG
#define ENAMETOOLONG WSAENAMETOOLONG
#define EHOSTDOWN WSAEHOSTDOWN
#define EHOSTUNREACH WSAEHOSTUNREACH
#undef ENOTEMPTY
#define ENOTEMPTY WSAENOTEMPTY
#define EPROCLIM WSAEPROCLIM
#define EUSERS WSAEUSERS
#define EDQUOT WSAEDQUOT
#define ESTALE WSAESTALE
#define EREMOTE WSAEREMOTE
#define INVALID_EVENT WSA_INVALID_EVENT
static BOOL (WINAPI *fpSetHandleInformation)(HANDLE,DWORD,DWORD);
#define sock_open(af, type, proto) \
make_noninheritable_handle(socket((af), (type), (proto)))
#define sock_close(s) closesocket((s))
#define sock_shutdown(s, how) shutdown((s), (how))
#define sock_accept(s, addr, len) \
make_noninheritable_handle(accept((s), (addr), (len)))
#define sock_connect(s, addr, len) connect((s), (addr), (len))
#define sock_listen(s, b) listen((s), (b))
#define sock_bind(s, addr, len) bind((s), (addr), (len))
#define sock_getopt(s,t,n,v,l) getsockopt((s),(t),(n),(v),(l))
#define sock_setopt(s,t,n,v,l) setsockopt((s),(t),(n),(v),(l))
#define sock_name(s, addr, len) getsockname((s), (addr), (len))
#define sock_peer(s, addr, len) getpeername((s), (addr), (len))
#define sock_ntohs(x) ntohs((x))
#define sock_ntohl(x) ntohl((x))
#define sock_htons(x) htons((x))
#define sock_htonl(x) htonl((x))
#define sock_send(s,buf,len,flag) send((s),(buf),(len),(flag))
#define sock_sendv(s, vec, size, np, flag) \
WSASend((s),(WSABUF*)(vec),(size),(np),(flag),NULL,NULL)
#define sock_recv(s,buf,len,flag) recv((s),(buf),(len),(flag))
#define sock_recvfrom(s,buf,blen,flag,addr,alen) \
recvfrom((s),(buf),(blen),(flag),(addr),(alen))
#define sock_sendto(s,buf,blen,flag,addr,alen) \
sendto((s),(buf),(blen),(flag),(addr),(alen))
#define sock_hostname(buf, len) gethostname((buf), (len))
#define sock_getservbyname(name,proto) getservbyname((name),(proto))
#define sock_getservbyport(port,proto) getservbyport((port),(proto))
#define sock_errno() WSAGetLastError()
#define sock_create_event(d) WSACreateEvent()
#define sock_close_event(e) WSACloseEvent(e)
#define sock_select(D, Flags, OnOff) winsock_event_select(D, Flags, OnOff)
#define SET_BLOCKING(s) ioctlsocket(s, FIONBIO, &zero_value)
#define SET_NONBLOCKING(s) ioctlsocket(s, FIONBIO, &one_value)
static unsigned long zero_value = 0;
static unsigned long one_value = 1;
#define TCP_SHUT_WR SD_SEND
#define TCP_SHUT_RD SD_RECEIVE
#define TCP_SHUT_RDWR SD_BOTH
#else /* !__WIN32__ */
#include <sys/time.h>
#ifdef NETDB_H_NEEDS_IN_H
#include <netinet/in.h>
#endif
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#ifdef DEF_INADDR_LOOPBACK_IN_RPC_TYPES_H
#include <rpc/types.h>
#endif
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <sys/param.h>
#ifdef HAVE_ARPA_NAMESER_H
#include <arpa/nameser.h>
#endif
#ifdef HAVE_SYS_SOCKIO_H
#include <sys/sockio.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#include <net/if.h>
#ifdef HAVE_SCHED_H
#include <sched.h>
#endif
#ifdef HAVE_SETNS_H
#include <setns.h>
#endif
#define HAVE_UDP
/* SCTP support -- currently for UNIX platforms only: */
#undef HAVE_SCTP
#if defined(HAVE_SCTP_H)
#include <netinet/sctp.h>
/* SCTP Socket API Draft from version 11 on specifies that netinet/sctp.h must
explicitly define HAVE_SCTP in case when SCTP is supported, but Solaris 10
still apparently uses Draft 10, and does not define that symbol, so we have
to define it explicitly:
*/
#ifndef HAVE_SCTP
# define HAVE_SCTP
#endif
/* These changed in draft 11, so SOLARIS10 uses the old MSG_* */
#if ! HAVE_DECL_SCTP_UNORDERED
# define SCTP_UNORDERED MSG_UNORDERED
#endif
#if ! HAVE_DECL_SCTP_ADDR_OVER
# define SCTP_ADDR_OVER MSG_ADDR_OVER
#endif
#if ! HAVE_DECL_SCTP_ABORT
# define SCTP_ABORT MSG_ABORT
#endif
#if ! HAVE_DECL_SCTP_EOF
# define SCTP_EOF MSG_EOF
#endif
/* More Solaris 10 fixes: */
#if ! HAVE_DECL_SCTP_CLOSED && HAVE_DECL_SCTPS_IDLE
# define SCTP_CLOSED SCTPS_IDLE
# undef HAVE_DECL_SCTP_CLOSED
# define HAVE_DECL_SCTP_CLOSED 1
#endif
#if ! HAVE_DECL_SCTP_BOUND && HAVE_DECL_SCTPS_BOUND
# define SCTP_BOUND SCTPS_BOUND
# undef HAVE_DECL_SCTP_BOUND
# define HAVE_DECL_SCTP_BOUND 1
#endif
#if ! HAVE_DECL_SCTP_LISTEN && HAVE_DECL_SCTPS_LISTEN
# define SCTP_LISTEN SCTPS_LISTEN
# undef HAVE_DECL_SCTP_LISTEN
# define HAVE_DECL_SCTP_LISTEN 1
#endif
#if ! HAVE_DECL_SCTP_COOKIE_WAIT && HAVE_DECL_SCTPS_COOKIE_WAIT
# define SCTP_COOKIE_WAIT SCTPS_COOKIE_WAIT
# undef HAVE_DECL_SCTP_COOKIE_WAIT
# define HAVE_DECL_SCTP_COOKIE_WAIT 1
#endif
#if ! HAVE_DECL_SCTP_COOKIE_ECHOED && HAVE_DECL_SCTPS_COOKIE_ECHOED
# define SCTP_COOKIE_ECHOED SCTPS_COOKIE_ECHOED
# undef HAVE_DECL_SCTP_COOKIE_ECHOED
# define HAVE_DECL_SCTP_COOKIE_ECHOED 1
#endif
#if ! HAVE_DECL_SCTP_ESTABLISHED && HAVE_DECL_SCTPS_ESTABLISHED
# define SCTP_ESTABLISHED SCTPS_ESTABLISHED
# undef HAVE_DECL_SCTP_ESTABLISHED
# define HAVE_DECL_SCTP_ESTABLISHED 1
#endif
#if ! HAVE_DECL_SCTP_SHUTDOWN_PENDING && HAVE_DECL_SCTPS_SHUTDOWN_PENDING
# define SCTP_SHUTDOWN_PENDING SCTPS_SHUTDOWN_PENDING
# undef HAVE_DECL_SCTP_SHUTDOWN_PENDING
# define HAVE_DECL_SCTP_SHUTDOWN_PENDING 1
#endif
#if ! HAVE_DECL_SCTP_SHUTDOWN_SENT && HAVE_DECL_SCTPS_SHUTDOWN_SENT
# define SCTP_SHUTDOWN_SENT SCTPS_SHUTDOWN_SENT
# undef HAVE_DECL_SCTP_SHUTDOWN_SENT
# define HAVE_DECL_SCTP_SHUTDOWN_SENT 1
#endif
#if ! HAVE_DECL_SCTP_SHUTDOWN_RECEIVED && HAVE_DECL_SCTPS_SHUTDOWN_RECEIVED
# define SCTP_SHUTDOWN_RECEIVED SCTPS_SHUTDOWN_RECEIVED
# undef HAVE_DECL_SCTP_SHUTDOWN_RECEIVED
# define HAVE_DECL_SCTP_SHUTDOWN_RECEIVED 1
#endif
#if ! HAVE_DECL_SCTP_SHUTDOWN_ACK_SENT && HAVE_DECL_SCTPS_SHUTDOWN_ACK_SENT
# define SCTP_SHUTDOWN_ACK_SENT SCTPS_SHUTDOWN_ACK_SENT
# undef HAVE_DECL_SCTP_SHUTDOWN_ACK_SENT
# define HAVE_DECL_SCTP_SHUTDOWN_ACK_SENT 1
#endif
/* New spelling in lksctp 2.6.22 or maybe even earlier:
* adaption -> adaptation
*/
#if !defined(SCTP_ADAPTATION_LAYER) && defined (SCTP_ADAPTION_LAYER)
# define SCTP_ADAPTATION_LAYER SCTP_ADAPTION_LAYER
# define SCTP_ADAPTATION_INDICATION SCTP_ADAPTION_INDICATION
# define sctp_adaptation_event sctp_adaption_event
# define sctp_setadaptation sctp_setadaption
# define sn_adaptation_event sn_adaption_event
# define sai_adaptation_ind sai_adaption_ind
# define ssb_adaptation_ind ssb_adaption_ind
# define sctp_adaptation_layer_event sctp_adaption_layer_event
#endif
#if defined(__GNUC__) && defined(HAVE_SCTP_BINDX)
static typeof(sctp_bindx) *p_sctp_bindx = NULL;
#else
static int (*p_sctp_bindx)
(int sd, struct sockaddr *addrs, int addrcnt, int flags) = NULL;
#endif
#if defined(__GNUC__) && defined(HAVE_SCTP_PEELOFF)
static typeof(sctp_peeloff) *p_sctp_peeloff = NULL;
#else
static int (*p_sctp_peeloff)
(int sd, sctp_assoc_t assoc_id) = NULL;
#endif
#if defined(__GNUC__) && defined(HAVE_SCTP_GETLADDRS)
static typeof(sctp_getladdrs) *p_sctp_getladdrs = NULL;
#else
static int (*p_sctp_getladdrs)
(int sd, sctp_assoc_t assoc_id, struct sockaddr **ss) = NULL;
#endif
#if defined(__GNUC__) && defined(HAVE_SCTP_FREELADDRS)
static typeof(sctp_freeladdrs) *p_sctp_freeladdrs = NULL;
#else
static void (*p_sctp_freeladdrs)(struct sockaddr *addrs) = NULL;
#endif
#if defined(__GNUC__) && defined(HAVE_SCTP_GETPADDRS)
static typeof(sctp_getpaddrs) *p_sctp_getpaddrs = NULL;
#else
static int (*p_sctp_getpaddrs)
(int sd, sctp_assoc_t assoc_id, struct sockaddr **ss) = NULL;
#endif
#if defined(__GNUC__) && defined(HAVE_SCTP_FREEPADDRS)
static typeof(sctp_freepaddrs) *p_sctp_freepaddrs = NULL;
#else
static void (*p_sctp_freepaddrs)(struct sockaddr *addrs) = NULL;
#endif
#if defined(__GNUC__) && defined(HAVE_SCTP_CONNECTX)
static typeof(sctp_connectx) *p_sctp_connectx = NULL;
#else
static int (*p_sctp_connectx)
(int sd, struct sockaddr * addrs, int addrcnt, sctp_assoc_t * assoc_id) = NULL;
#endif
#endif /* #if defined(HAVE_SCTP_H) */
#ifndef WANT_NONBLOCKING
#define WANT_NONBLOCKING
#endif
#include "sys.h"
/* #define INET_DRV_DEBUG 1 */
#ifdef INET_DRV_DEBUG
#define DEBUG 1
#undef DEBUGF
#define DEBUGF(__X__) erts_printf __X__
#endif
#if !defined(HAVE_STRNCASECMP)
#define STRNCASECMP my_strncasecmp
static int my_strncasecmp(const char *s1, const char *s2, size_t n)
{
int i;
for (i=0;i<n-1 && s1[i] && s2[i] && toupper(s1[i]) == toupper(s2[i]);++i)
;
return (toupper(s1[i]) - toupper(s2[i]));
}
#else
#define STRNCASECMP strncasecmp
#endif
#define INVALID_SOCKET -1
#define INVALID_EVENT -1
#define SOCKET_ERROR -1
#define SOCKET int
#define HANDLE long int
#define FD_READ ERL_DRV_READ
#define FD_WRITE ERL_DRV_WRITE
#define FD_CLOSE 0
#define FD_CONNECT ERL_DRV_WRITE
#define FD_ACCEPT ERL_DRV_READ
#define sock_connect(s, addr, len) connect((s), (addr), (len))
#define sock_listen(s, b) listen((s), (b))
#define sock_bind(s, addr, len) bind((s), (addr), (len))
#define sock_getopt(s,t,n,v,l) getsockopt((s),(t),(n),(v),(l))
#define sock_setopt(s,t,n,v,l) setsockopt((s),(t),(n),(v),(l))
#define sock_name(s, addr, len) getsockname((s), (addr), (len))
#define sock_peer(s, addr, len) getpeername((s), (addr), (len))
#define sock_ntohs(x) ntohs((x))
#define sock_ntohl(x) ntohl((x))
#define sock_htons(x) htons((x))
#define sock_htonl(x) htonl((x))
#define sock_accept(s, addr, len) accept((s), (addr), (len))
#define sock_send(s,buf,len,flag) send((s),(buf),(len),(flag))
#define sock_sendto(s,buf,blen,flag,addr,alen) \
sendto((s),(buf),(blen),(flag),(addr),(alen))
#define sock_sendv(s, vec, size, np, flag) \
(*(np) = writev((s), (struct iovec*)(vec), (size)))
#define sock_sendmsg(s,msghdr,flag) sendmsg((s),(msghdr),(flag))
#define sock_open(af, type, proto) socket((af), (type), (proto))
#define sock_close(s) close((s))
#define sock_shutdown(s, how) shutdown((s), (how))
#define sock_hostname(buf, len) gethostname((buf), (len))
#define sock_getservbyname(name,proto) getservbyname((name), (proto))
#define sock_getservbyport(port,proto) getservbyport((port), (proto))
#define sock_recv(s,buf,len,flag) recv((s),(buf),(len),(flag))
#define sock_recvfrom(s,buf,blen,flag,addr,alen) \
recvfrom((s),(buf),(blen),(flag),(addr),(alen))
#define sock_recvmsg(s,msghdr,flag) recvmsg((s),(msghdr),(flag))
#define sock_errno() errno
#define sock_create_event(d) ((d)->s) /* return file descriptor */
#define sock_close_event(e) /* do nothing */
#define inet_driver_select(port, e, mode, on) \
driver_select(port, e, mode | (on?ERL_DRV_USE:0), on)
#define sock_select(d, flags, onoff) do { \
ASSERT(!INET_IGNORED(d)); \
(d)->event_mask = (onoff) ? \
((d)->event_mask | (flags)) : \
((d)->event_mask & ~(flags)); \
DEBUGF(("(%s / %d) sock_select(%p): flags=%02X, onoff=%d, event_mask=%02lX\r\n", \
__FILE__, __LINE__, (d)->port, (flags), (onoff), (unsigned long) (d)->event_mask)); \
inet_driver_select((d)->port, (ErlDrvEvent)(long)(d)->event, (flags), (onoff)); \
} while(0)
#define TCP_SHUT_WR SHUT_WR
#define TCP_SHUT_RD SHUT_RD
#define TCP_SHUT_RDWR SHUT_RDWR
#endif /* !__WIN32__ */
#ifdef HAVE_SOCKLEN_T
# define SOCKLEN_T socklen_t
#elif defined(__WIN32__)
# define SOCKLEN_T int
#else
# warning "Non-Windows OS without type 'socklen_t'"
# define SOCKLEN_T size_t
#endif
#include "packet_parser.h"
#if defined(HAVE_SYS_UN_H) || defined(SO_BINDTODEVICE)
/* strnlen doesn't exist everywhere */
static size_t my_strnlen(const char *s, size_t maxlen)
{
size_t i = 0;
while (i < maxlen && s[i] != '\0')
i++;
return i;
}
#endif
#ifdef VALGRIND
# include <valgrind/memcheck.h>
#else
# define VALGRIND_MAKE_MEM_DEFINED(ptr,size)
#endif
#ifndef __WIN32__
/* Calculate CMSG_NXTHDR without having a struct msghdr*.
* CMSG_LEN only caters for alignment for start of data.
* To get how much to advance we need to use CMSG_SPACE
* on the payload length. To get the payload length we
* take the calculated cmsg->cmsg_len and subtract the
* header length. To get the header length we use
* the pointer difference from the cmsg start pointer
* to the CMSG_DATA(cmsg) pointer.
*
* Some platforms (seen on ppc Linux 2.6.29-3.ydl61.3)
* may return 0 as the cmsg_len if the cmsg is to be ignored.
*/
#define LEN_CMSG_DATA(cmsg) \
((cmsg)->cmsg_len < sizeof (struct cmsghdr) ? 0 : \
(cmsg)->cmsg_len - ((char*)CMSG_DATA(cmsg) - (char*)(cmsg)))
#define NXT_CMSG_HDR(cmsg) \
((struct cmsghdr*)(((char*)(cmsg)) + CMSG_SPACE(LEN_CMSG_DATA(cmsg))))
#endif
#if !defined(IPV6_PKTOPTIONS) && defined(IPV6_2292PKTOPTIONS)
#define IPV6_PKTOPTIONS IPV6_2292PKTOPTIONS
#endif
/*
Magic errno value used locally for return of {error, system_limit}
- the emulator definition of SYSTEM_LIMIT is not available here.
*/
#define INET_ERRNO_SYSTEM_LIMIT (15 << 8)
/*----------------------------------------------------------------------------
** Interface constants.
**
** This section must be "identical" to the corresponding inet_int.hrl
*/
/* general address encode/decode tag */
#define INET_AF_UNSPEC 0
#define INET_AF_INET 1
#define INET_AF_INET6 2
#define INET_AF_ANY 3 /* INADDR_ANY or IN6ADDR_ANY_INIT */
#define INET_AF_LOOPBACK 4 /* INADDR_LOOPBACK or IN6ADDR_LOOPBACK_INIT */
#define INET_AF_LOCAL 5
#define INET_AF_UNDEFINED 6 /* Unknown */
#define INET_AF_LIST 7 /* List of addresses for sctp connectx */
/* open and INET_REQ_GETTYPE enumeration */
#define INET_TYPE_STREAM 1
#define INET_TYPE_DGRAM 2
#define INET_TYPE_SEQPACKET 3
/* INET_LOPT_MODE options */
#define INET_MODE_LIST 0
#define INET_MODE_BINARY 1
/* INET_LOPT_DELIVER options */
#define INET_DELIVER_PORT 0
#define INET_DELIVER_TERM 1
/* INET_LOPT_ACTIVE options */
#define INET_PASSIVE 0 /* false */
#define INET_ACTIVE 1 /* true */
#define INET_ONCE 2 /* true; active once then passive */
#define INET_MULTI 3 /* true; active N then passive */
/* INET_REQ_GETSTATUS enumeration */
#define INET_F_OPEN 0x0001
/* INET_F_BOUND removed - renumber when there comes a bigger rewrite */
#define INET_F_ACTIVE 0x0004
#define INET_F_LISTEN 0x0008
#define INET_F_CON 0x0010
#define INET_F_ACC 0x0020
#define INET_F_LST 0x0040
#define INET_F_BUSY 0x0080
#define INET_F_MULTI_CLIENT 0x0100 /* Multiple clients for one descriptor, i.e. multi-accept */
/* One numberspace for *_REQ_* so if an e.g UDP request is issued
** for a TCP socket, the driver can protest.
*/
#define INET_REQ_OPEN 1
#define INET_REQ_CLOSE 2
#define INET_REQ_CONNECT 3
#define INET_REQ_PEER 4
#define INET_REQ_NAME 5
#define INET_REQ_BIND 6
#define INET_REQ_SETOPTS 7
#define INET_REQ_GETOPTS 8
/* #define INET_REQ_GETIX 9 NOT USED ANY MORE */
/* #define INET_REQ_GETIF 10 REPLACE BY NEW STUFF */
#define INET_REQ_GETSTAT 11
#define INET_REQ_GETHOSTNAME 12
#define INET_REQ_FDOPEN 13
#define INET_REQ_GETFD 14
#define INET_REQ_GETTYPE 15
#define INET_REQ_GETSTATUS 16
#define INET_REQ_GETSERVBYNAME 17
#define INET_REQ_GETSERVBYPORT 18
#define INET_REQ_SETNAME 19
#define INET_REQ_SETPEER 20
#define INET_REQ_GETIFLIST 21
#define INET_REQ_IFGET 22
#define INET_REQ_IFSET 23
#define INET_REQ_SUBSCRIBE 24
#define INET_REQ_GETIFADDRS 25
#define INET_REQ_ACCEPT 26
#define INET_REQ_LISTEN 27
#define INET_REQ_IGNOREFD 28
#define INET_REQ_GETLADDRS 29
#define INET_REQ_GETPADDRS 30
/* TCP requests */
/* #define TCP_REQ_ACCEPT 40 MOVED */
/* #define TCP_REQ_LISTEN 41 MERGED */
#define TCP_REQ_RECV 42
#define TCP_REQ_UNRECV 43
#define TCP_REQ_SHUTDOWN 44
#define TCP_REQ_SENDFILE 45
/* UDP and SCTP requests */
#define PACKET_REQ_RECV 60 /* Common for UDP and SCTP */
/* #define SCTP_REQ_LISTEN 61 MERGED Different from TCP; not for UDP */
#define SCTP_REQ_BINDX 62 /* Multi-home SCTP bind */
#define SCTP_REQ_PEELOFF 63
/* INET_REQ_SUBSCRIBE sub-requests */
#define INET_SUBS_EMPTY_OUT_Q 1
/* TCP additional flags */
#define TCP_ADDF_DELAY_SEND 1
#define TCP_ADDF_CLOSE_SENT 2 /* Close sent (active mode only) */
#define TCP_ADDF_DELAYED_CLOSE_RECV 4 /* If receive fails, report {error,closed} (passive mode) */
#define TCP_ADDF_DELAYED_CLOSE_SEND 8 /* If send fails, report {error,closed} (passive mode) */
#define TCP_ADDF_PENDING_SHUT_WR 16 /* Call shutdown(sock, SHUT_WR) when queue empties */
#define TCP_ADDF_PENDING_SHUT_RDWR 32 /* Call shutdown(sock, SHUT_RDWR) when queue empties */
#define TCP_ADDF_PENDING_SHUTDOWN \
(TCP_ADDF_PENDING_SHUT_WR | TCP_ADDF_PENDING_SHUT_RDWR)
#define TCP_ADDF_SHOW_ECONNRESET 64 /* Tell user about incoming RST */
#define TCP_ADDF_DELAYED_ECONNRESET 128 /* An ECONNRESET error occurred on send or shutdown */
#define TCP_ADDF_SHUTDOWN_WR_DONE 256 /* A shutdown(sock, SHUT_WR) or SHUT_RDWR was made */
#define TCP_ADDF_LINGER_ZERO 512 /* Discard driver queue on port close */
#define TCP_ADDF_SENDFILE 1024 /* Send from an fd instead of the driver queue */
/* *_REQ_* replies */
#define INET_REP_ERROR 0
#define INET_REP_OK 1
#define INET_REP 2
/* INET_REQ_SETOPTS and INET_REQ_GETOPTS options */
#define INET_OPT_REUSEADDR 0 /* enable/disable local address reuse */
#define INET_OPT_KEEPALIVE 1 /* enable/disable keep connections alive */
#define INET_OPT_DONTROUTE 2 /* enable/disable routing for messages */
#define INET_OPT_LINGER 3 /* linger on close if data is present */
#define INET_OPT_BROADCAST 4 /* enable/disable transmission of broadcast */
#define INET_OPT_OOBINLINE 5 /* enable/disable out-of-band data in band */
#define INET_OPT_SNDBUF 6 /* set send buffer size */
#define INET_OPT_RCVBUF 7 /* set receive buffer size */
#define INET_OPT_PRIORITY 8 /* set priority */
#define INET_OPT_TOS 9 /* Set type of service */
#define TCP_OPT_NODELAY 10 /* don't delay send to coalesce packets */
#define UDP_OPT_MULTICAST_IF 11 /* set/get IP multicast interface */
#define UDP_OPT_MULTICAST_TTL 12 /* set/get IP multicast timetolive */
#define UDP_OPT_MULTICAST_LOOP 13 /* set/get IP multicast loopback */
#define UDP_OPT_ADD_MEMBERSHIP 14 /* add an IP group membership */
#define UDP_OPT_DROP_MEMBERSHIP 15 /* drop an IP group membership */
#define INET_OPT_IPV6_V6ONLY 16 /* IPv6 only socket, no mapped v4 addrs */
/* LOPT is local options */
#define INET_LOPT_BUFFER 20 /* min buffer size hint */
#define INET_LOPT_HEADER 21 /* list header size */
#define INET_LOPT_ACTIVE 22 /* enable/disable active receive */
#define INET_LOPT_PACKET 23 /* packet header type (TCP) */
#define INET_LOPT_MODE 24 /* list or binary mode */
#define INET_LOPT_DELIVER 25 /* port or term delivery */
#define INET_LOPT_EXITONCLOSE 26 /* exit port on active close or not ! */
#define INET_LOPT_TCP_HIWTRMRK 27 /* set local high watermark */
#define INET_LOPT_TCP_LOWTRMRK 28 /* set local low watermark */
/* 29 unused */
#define INET_LOPT_TCP_SEND_TIMEOUT 30 /* set send timeout */
#define INET_LOPT_TCP_DELAY_SEND 31 /* Delay sends until next poll */
#define INET_LOPT_PACKET_SIZE 32 /* Max packet size */
#define INET_LOPT_UDP_READ_PACKETS 33 /* Number of packets to read */
#define INET_OPT_RAW 34 /* Raw socket options */
#define INET_LOPT_TCP_SEND_TIMEOUT_CLOSE 35 /* auto-close on send timeout or not */
#define INET_LOPT_MSGQ_HIWTRMRK 36 /* set local msgq high watermark */
#define INET_LOPT_MSGQ_LOWTRMRK 37 /* set local msgq low watermark */
#define INET_LOPT_NETNS 38 /* Network namespace pathname */
#define INET_LOPT_TCP_SHOW_ECONNRESET 39 /* tell user about incoming RST */
#define INET_LOPT_LINE_DELIM 40 /* Line delimiting char */
#define INET_OPT_TCLASS 41 /* IPv6 transport class */
#define INET_OPT_BIND_TO_DEVICE 42 /* get/set network device the socket is bound to */
#define INET_OPT_RECVTOS 43 /* IP_RECVTOS ancillary data */
#define INET_OPT_RECVTCLASS 44 /* IPV6_RECVTCLASS ancillary data */
#define INET_OPT_PKTOPTIONS 45 /* IP(V6)_PKTOPTIONS get ancillary data */
#define INET_OPT_TTL 46 /* IP_TTL */
#define INET_OPT_RECVTTL 47 /* IP_RECVTTL ancillary data */
#define TCP_OPT_NOPUSH 48 /* super-Nagle, aka TCP_CORK */
#define INET_LOPT_DEBUG 99 /* Enable/disable DEBUG for a socket */
/* SCTP options: a separate range, from 100: */
#define SCTP_OPT_RTOINFO 100
#define SCTP_OPT_ASSOCINFO 101
#define SCTP_OPT_INITMSG 102
#define SCTP_OPT_AUTOCLOSE 103
#define SCTP_OPT_NODELAY 104
#define SCTP_OPT_DISABLE_FRAGMENTS 105
#define SCTP_OPT_I_WANT_MAPPED_V4_ADDR 106
#define SCTP_OPT_MAXSEG 107
#define SCTP_OPT_SET_PEER_PRIMARY_ADDR 108
#define SCTP_OPT_PRIMARY_ADDR 109
#define SCTP_OPT_ADAPTATION_LAYER 110
#define SCTP_OPT_PEER_ADDR_PARAMS 111
#define SCTP_OPT_DEFAULT_SEND_PARAM 112
#define SCTP_OPT_EVENTS 113
#define SCTP_OPT_DELAYED_ACK_TIME 114
#define SCTP_OPT_STATUS 115
#define SCTP_OPT_GET_PEER_ADDR_INFO 116
/* INET_REQ_IFGET and INET_REQ_IFSET options */
#define INET_IFOPT_ADDR 1
#define INET_IFOPT_BROADADDR 2
#define INET_IFOPT_DSTADDR 3
#define INET_IFOPT_MTU 4
#define INET_IFOPT_NETMASK 5
#define INET_IFOPT_FLAGS 6
#define INET_IFOPT_HWADDR 7
/* INET_REQ_GETSTAT enumeration */
#define INET_STAT_RECV_CNT 1
#define INET_STAT_RECV_MAX 2
#define INET_STAT_RECV_AVG 3
#define INET_STAT_RECV_DVI 4
#define INET_STAT_SEND_CNT 5
#define INET_STAT_SEND_MAX 6
#define INET_STAT_SEND_AVG 7
#define INET_STAT_SEND_PND 8
#define INET_STAT_RECV_OCT 9 /* received octets */
#define INET_STAT_SEND_OCT 10 /* sent octets */
/* INET_IFOPT_FLAGS enumeration */
#define INET_IFF_UP 0x0001
#define INET_IFF_BROADCAST 0x0002
#define INET_IFF_LOOPBACK 0x0004
#define INET_IFF_POINTTOPOINT 0x0008
#define INET_IFF_RUNNING 0x0010
#define INET_IFF_MULTICAST 0x0020
/* Complement flags for turning them off */
#define INET_IFF_DOWN 0x0100
#define INET_IFF_NBROADCAST 0x0200
/* #define INET_IFF_NLOOPBACK 0x0400 */
#define INET_IFF_NPOINTTOPOINT 0x0800
/* #define INET_IFF_NRUNNING 0x1000 */
/* #define INET_IFF_NMULTICAST 0x2000 */
/* Flags for "sctp_sndrcvinfo". Used in a bitmask -- must be powers of 2:
** INET_REQ_SETOPTS:SCTP_OPT_DEFAULT_SEND_PARAM
*/
#define SCTP_FLAG_UNORDERED (1 /* am_unordered */)
#define SCTP_FLAG_ADDR_OVER (2 /* am_addr_over */)
#define SCTP_FLAG_ABORT (4 /* am_abort */)
#define SCTP_FLAG_EOF (8 /* am_eof */)
#define SCTP_FLAG_SNDALL (16 /* am_sndall, NOT YET IMPLEMENTED */)
/* Flags for "sctp_set_opts" (actually for SCTP_OPT_PEER_ADDR_PARAMS).
** These flags are also used in a bitmask, so they must be powers of 2:
*/
#define SCTP_FLAG_HB_ENABLE (1 /* am_hb_enable */)
#define SCTP_FLAG_HB_DISABLE (2 /* am_hb_disable */)
#define SCTP_FLAG_HB_DEMAND (4 /* am_hb_demand */)
#define SCTP_FLAG_PMTUD_ENABLE (8 /* am_pmtud_enable */)
#define SCTP_FLAG_PMTUD_DISABLE (16 /* am_pmtud_disable */)
#define SCTP_FLAG_SACDELAY_ENABLE (32 /* am_sackdelay_enable */)
#define SCTP_FLAG_SACDELAY_DISABLE (64 /* am_sackdelay_disable */)
/* Flags for recv_cmsgflags */
#define INET_CMSG_RECVTOS (1 << 0) /* am_recvtos, am_tos */
#define INET_CMSG_RECVTCLASS (1 << 1) /* am_recvtclass, am_tclass */
#define INET_CMSG_RECVTTL (1 << 2) /* am_recvttl, am_ttl */
/* Inet flags */
#define INET_FLG_BUFFER_SET (1 << 0) /* am_buffer has been set by user */
#define INET_FLG_IS_IGNORED (1 << 1) /* If a fd is ignored by the inet_drv.
This flag should be set to true when
the fd is used outside of inet_drv. */
#define INET_FLG_IS_IGNORED_RD (1 << 2)
#define INET_FLG_IS_IGNORED_WR (1 << 3)
#define INET_FLG_IS_IGNORED_PASS (1 << 4)
/*
** End of interface constants.
**--------------------------------------------------------------------------*/
#define INET_STATE_CLOSED (0)
#define INET_STATE_OPEN (INET_F_OPEN)
#define INET_STATE_CONNECTED (INET_STATE_OPEN | INET_F_ACTIVE)
#define INET_STATE_LISTENING (INET_STATE_OPEN | INET_F_LISTEN)
#define INET_STATE_CONNECTING (INET_STATE_OPEN | INET_F_CON)
#define INET_STATE_ACCEPTING (INET_STATE_LISTENING | INET_F_ACC)
#define INET_STATE_MULTI_ACCEPTING (INET_STATE_ACCEPTING | INET_F_MULTI_CLIENT)
#define IS_OPEN(d) \
(((d)->state & INET_F_OPEN) == INET_F_OPEN)
#define IS_CONNECTED(d) \
(((d)->state & INET_STATE_CONNECTED) == INET_STATE_CONNECTED)
#define IS_CONNECTING(d) \
(((d)->state & INET_F_CON) == INET_F_CON)
#define IS_BUSY(d) \
(((d)->state & INET_F_BUSY) == INET_F_BUSY)
#define INET_MAX_OPT_BUFFER (64*1024)
#define INET_DEF_BUFFER 1460 /* default buffer size */
#define INET_MIN_BUFFER 1 /* internal min buffer */
#define INET_HIGH_WATERMARK (1024*8) /* 8k pending high => busy */
#define INET_LOW_WATERMARK (1024*4) /* 4k pending => allow more */
#define INET_HIGH_MSGQ_WATERMARK (1024*8) /* 8k pending high => busy */
#define INET_LOW_MSGQ_WATERMARK (1024*4) /* 4k pending => allow more */
#define INET_INFINITY 0xffffffff /* infinity value */
#define INET_MAX_ASYNC 1 /* max number of async queue ops */
/* INET_LOPT_UDP_PACKETS */
#define INET_PACKET_POLL 5 /* maximum number of packets to poll */
/* Max interface name */
#define INET_IFNAMSIZ 16
/* INET Ignore states */
#define INET_IGNORE_CLEAR(desc) ((desc)->flags & ~(INET_IGNORE_READ|INET_IGNORE_WRITE|INET_IGNORE_PASSIVE))
#define INET_IGNORED(desc) ((desc)->flags & INET_FLG_IS_IGNORED)
#define INET_IGNORE_READ (INET_FLG_IS_IGNORED|INET_FLG_IS_IGNORED_RD)
#define INET_IGNORE_WRITE (INET_FLG_IS_IGNORED|INET_FLG_IS_IGNORED_WR)
#define INET_IGNORE_PASSIVE (INET_FLG_IS_IGNORED|INET_FLG_IS_IGNORED_PASS)
/* Max length of Erlang Term Buffer (for outputting structured terms): */
#ifdef HAVE_SCTP
#define PACKET_ERL_DRV_TERM_DATA_LEN 512
#else
#ifndef __WIN32__
/* Assume we have recvmsg() and might need room for ancillary data */
#define PACKET_ERL_DRV_TERM_DATA_LEN 64
#else
#define PACKET_ERL_DRV_TERM_DATA_LEN 32
#endif
#endif
typedef struct _tcp_descriptor tcp_descriptor;
#if defined(TCP_CORK)
#define INET_TCP_NOPUSH TCP_CORK
#elif defined(TCP_NOPUSH) && !defined(__DARWIN__)
#define INET_TCP_NOPUSH TCP_NOPUSH
#endif
#define BIN_REALLOC_MARGIN(x) ((x)/4) /* 25% */
/* The general purpose sockaddr */
typedef union {
struct sockaddr sa;
struct sockaddr_in sai;
#ifdef HAVE_IN6
struct sockaddr_in6 sai6;
#endif
#ifdef HAVE_SYS_UN_H
struct sockaddr_un sal;
#endif
} inet_address;
/* On some platforms, for instance FreeBSD, this option is instead
* called IPV6_JOIN_GROUP and IPV6_JOIN_GROUP. */
#if defined(HAVE_IN6)
#if defined(IPV6_ADD_MEMBERSHIP)
#define INET_ADD_MEMBERSHIP IPV6_ADD_MEMBERSHIP
#elif defined(IPV6_JOIN_GROUP)
#define INET_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#endif
#if defined(IPV6_DROP_MEMBERSHIP)
#define INET_DROP_MEMBERSHIP IPV6_DROP_MEMBERSHIP
#elif defined(IPV6_LEAVE_GROUP)
#define INET_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
#endif
#endif
#define inet_address_port(x) \
((((x)->sai.sin_family == AF_INET) || \
((x)->sai.sin_family == AF_INET6)) ? \
((x)->sai.sin_port) : -1)
#ifdef HAVE_SYS_UN_H
#define localaddrlen(data) \
((((unsigned char*)(data))[0] == INET_AF_LOCAL) ? \
(1 + 1 + ((unsigned char*)(data))[1]) : 1)
#else
#define localaddrlen(data) (1)
#endif
#if defined(HAVE_IN6) && defined(AF_INET6)
#define addrlen(data) \
((((unsigned char*)(data))[0] == INET_AF_INET) ? \
(1 + 2 + 4) : \
((((unsigned char*)(data))[0] == INET_AF_INET6) ? \
(1 + 2 + 16) : localaddrlen(data)))
#else
#define addrlen(data) \
((((unsigned char*)(data))[0] == INET_AF_INET) ? \
(1 + 2 + 4) : localaddrlen(data))
#endif
typedef int (MultiTimerFunction)(ErlDrvData drv_data, ErlDrvTermData caller);
typedef struct _multi_timer_data {
ErlDrvTime when;
ErlDrvTermData caller;
MultiTimerFunction *timeout_function;
struct _multi_timer_data *next;
struct _multi_timer_data *prev;
} MultiTimerData;
static MultiTimerData *add_multi_timer(tcp_descriptor *desc, ErlDrvPort port,
ErlDrvTermData caller, unsigned timeout,
MultiTimerFunction *timeout_fun);
static void fire_multi_timers(tcp_descriptor *desc, ErlDrvPort port,
ErlDrvData data);
static void remove_multi_timer(tcp_descriptor *desc, ErlDrvPort port, MultiTimerData *p);
static void cancel_multi_timer(tcp_descriptor *desc, ErlDrvPort port,
MultiTimerFunction *timeout_fun);
static int tcp_inet_multi_timeout(ErlDrvData e, ErlDrvTermData caller);
static void clean_multi_timers(tcp_descriptor *desc, ErlDrvPort port);
typedef struct {
int id; /* id used to identify reply */
ErlDrvTermData caller; /* recipient of async reply */
int req; /* Request id (CONNECT/ACCEPT/RECV) */
union {
unsigned value; /* Request timeout (since op issued,not started) */
MultiTimerData *mtd;
} tmo;
ErlDrvMonitor monitor;
} inet_async_op;
typedef struct inet_async_multi_op_ {
inet_async_op op;
struct inet_async_multi_op_ *next;
} inet_async_multi_op;
typedef struct subs_list_ {
ErlDrvTermData subscriber;
struct subs_list_ *next;
} subs_list;
#define NO_PROCESS 0
#define NO_SUBSCRIBERS(SLP) ((SLP)->subscriber == NO_PROCESS)
static void send_to_subscribers(ErlDrvTermData, subs_list *, int,
ErlDrvTermData [], int);
static void free_subscribers(subs_list*);
static int save_subscriber(subs_list *, ErlDrvTermData);
typedef struct {
SOCKET s; /* the socket or INVALID_SOCKET if not open */
HANDLE event; /* Event handle (same as s in unix) */
long event_mask; /* current FD events */
#ifdef __WIN32__
long forced_events; /* Mask of events that are forcefully signalled
on windows see winsock_event_select
for details */
int err; /* Keeps error code for closed socket */
int send_would_block; /* Last send attempt failed with "WOULDBLOCK" */
#endif
ErlDrvPort port; /* the port identifier */
ErlDrvTermData dport; /* the port identifier as DriverTermData */
int state; /* status */
int prebound; /* only set when opened with inet_fdopen */
int mode; /* BINARY | LIST
(affect how to interpret hsz) */
int exitf; /* exit port on close or not */
int deliver; /* Delivery mode, TERM or PORT */
ErlDrvTermData caller; /* recipient of sync reply */
ErlDrvTermData busy_caller; /* recipient of sync reply when caller busy.
* Only valid while INET_F_BUSY. */
inet_async_op* oph; /* queue head or NULL */
inet_async_op* opt; /* queue tail or NULL */
inet_async_op op_queue[INET_MAX_ASYNC]; /* call queue */
int op_ref; /* queue reference generator */
int active; /* 0 = passive, 1 = active, 2 = active once */
Sint16 active_count; /* counter for {active,N} */
int stype; /* socket type:
SOCK_STREAM/SOCK_DGRAM/SOCK_SEQPACKET */
int sprotocol; /* socket protocol:
IPPROTO_TCP|IPPROTO_UDP|IPPROTO_SCTP */
int sfamily; /* address family */
enum PacketParseType htype; /* header type (TCP only?) */
unsigned int psize; /* max packet size (TCP only?) */
inet_address remote; /* remote address for connected sockets */
inet_address peer_addr; /* fake peer address */
inet_address name_addr; /* fake local address */
inet_address* peer_ptr; /* fake peername or NULL */
inet_address* name_ptr; /* fake sockname or NULL */
unsigned int peer_addr_len; /* fake peername size */
unsigned int name_addr_len; /* fake sockname size */
int bufsz; /* minimum buffer constraint */
unsigned int hsz; /* the list header size, -1 is large !!! */
/* statistics */
#ifdef ARCH_64
Uint64 recv_oct; /* number of received octets, 64 bits */
#else
Uint32 recv_oct[2]; /* number of received octets, 64 bits */
#endif
unsigned long recv_cnt; /* number of packets received */
unsigned long recv_max; /* maximum packet size received */
double recv_avg; /* average packet size received */
double recv_dvi; /* average deviation from avg_size */
#ifdef ARCH_64
Uint64 send_oct; /* number of octets sent, 64 bits */
#else
Uint32 send_oct[2]; /* number of octets sent, 64 bits */
#endif
char delimiter; /* Line delimiting character (def: '\n') */
unsigned long send_cnt; /* number of packets sent */
unsigned long send_max; /* maximum packet send */
double send_avg; /* average packet size sent */
subs_list empty_out_q_subs; /* Empty out queue subscribers */
int flags;
#ifdef HAVE_SETNS
char *netns; /* Socket network namespace name
as full file path */
#endif
int recv_cmsgflags; /* Which ancillary data to expect */
int debug; /* debug enabled or not */
} inet_descriptor;
#define TCP_MAX_PACKET_SIZE 0x4000000 /* 64 M */
/* Max number of entries allowed in an I/O vector sock_sendv(). */
#if defined(__WIN32__)
/*
* Windows 95, 98, and ME is limited to 16, but we do not
* support those. Documentation unfortunately does not say
* anything about newer windows, so we guess 1024 which
* seems to be what most systems use...
*/
#define MAX_VSIZE 1024
#elif !defined(NO_SYSCONF)
static int iov_max;
#define MAX_VSIZE iov_max
#elif defined(IOV_MAX)
#define MAX_VSIZE IOV_MAX
#else
/* POSIX require at least 16 */
#define MAX_VSIZE 16
#endif
static int tcp_inet_init(void);
static void tcp_inet_stop(ErlDrvData);
static void tcp_inet_command(ErlDrvData, char*, ErlDrvSizeT);
static void tcp_inet_commandv(ErlDrvData, ErlIOVec*);
static void tcp_inet_flush(ErlDrvData drv_data);
static void tcp_inet_drv_input(ErlDrvData, ErlDrvEvent);
static void tcp_inet_drv_output(ErlDrvData data, ErlDrvEvent event);
static ErlDrvData tcp_inet_start(ErlDrvPort, char* command);
static ErlDrvSSizeT tcp_inet_ctl(ErlDrvData, unsigned int,
char*, ErlDrvSizeT, char**, ErlDrvSizeT);
static void tcp_inet_timeout(ErlDrvData);
static void tcp_inet_process_exit(ErlDrvData, ErlDrvMonitor *);
static void inet_stop_select(ErlDrvEvent, void*);
static void inet_emergency_close(ErlDrvData);
#ifdef __WIN32__
static void tcp_inet_event(ErlDrvData, ErlDrvEvent);
static void find_dynamic_functions(void);
#endif
static struct erl_drv_entry tcp_inet_driver_entry =
{
tcp_inet_init, /* inet_init will add this driver !! */
tcp_inet_start,
tcp_inet_stop,
tcp_inet_command,
#ifdef __WIN32__
tcp_inet_event,
NULL,
#else
tcp_inet_drv_input,
tcp_inet_drv_output,
#endif
"tcp_inet",
NULL,
NULL,
tcp_inet_ctl,
tcp_inet_timeout,
tcp_inet_commandv,
NULL,
tcp_inet_flush,
NULL,
NULL,
ERL_DRV_EXTENDED_MARKER,
ERL_DRV_EXTENDED_MAJOR_VERSION,
ERL_DRV_EXTENDED_MINOR_VERSION,
ERL_DRV_FLAG_USE_PORT_LOCKING|ERL_DRV_FLAG_SOFT_BUSY,
NULL,
tcp_inet_process_exit,
inet_stop_select,
inet_emergency_close
};
#ifdef HAVE_UDP
static int packet_inet_init(void);
static void packet_inet_stop(ErlDrvData);
static void packet_inet_command(ErlDrvData, char*, ErlDrvSizeT);
static void packet_inet_drv_input(ErlDrvData data, ErlDrvEvent event);
static ErlDrvData udp_inet_start(ErlDrvPort, char* command);
#ifdef HAVE_SCTP
static ErlDrvData sctp_inet_start(ErlDrvPort, char* command);
#endif
static ErlDrvSSizeT packet_inet_ctl(ErlDrvData, unsigned int, char*,
ErlDrvSizeT, char**, ErlDrvSizeT);
static void packet_inet_timeout(ErlDrvData);
#ifdef __WIN32__
static void packet_inet_event(ErlDrvData, ErlDrvEvent);
static SOCKET make_noninheritable_handle(SOCKET s);
static int winsock_event_select(inet_descriptor *, int, int);
#endif
static struct erl_drv_entry udp_inet_driver_entry =
{
packet_inet_init, /* inet_init will add this driver !! */
udp_inet_start,
packet_inet_stop,
packet_inet_command,
#ifdef __WIN32__
packet_inet_event,
NULL,
#else
packet_inet_drv_input,
NULL,
#endif
"udp_inet",
NULL,
NULL,
packet_inet_ctl,
packet_inet_timeout,
NULL,
NULL,
NULL,
NULL,
NULL,
ERL_DRV_EXTENDED_MARKER,
ERL_DRV_EXTENDED_MAJOR_VERSION,
ERL_DRV_EXTENDED_MINOR_VERSION,
ERL_DRV_FLAG_USE_PORT_LOCKING,
NULL,
NULL,
inet_stop_select,
inet_emergency_close
};
#endif
#ifdef HAVE_SCTP
static struct erl_drv_entry sctp_inet_driver_entry =
{
packet_inet_init, /* inet_init will add this driver !! */
sctp_inet_start,
packet_inet_stop,
packet_inet_command,
#ifdef __WIN32__
packet_inet_event,
NULL,
#else
packet_inet_drv_input,
NULL,
#endif
"sctp_inet",
NULL,
NULL,
packet_inet_ctl,
packet_inet_timeout,
NULL,
NULL,
NULL,
NULL,
NULL,
ERL_DRV_EXTENDED_MARKER,
ERL_DRV_EXTENDED_MAJOR_VERSION,
ERL_DRV_EXTENDED_MINOR_VERSION,
ERL_DRV_FLAG_USE_PORT_LOCKING,
NULL,
NULL, /* process_exit */
inet_stop_select,
inet_emergency_close
};
#endif
struct _tcp_descriptor {
inet_descriptor inet; /* common data structure (DON'T MOVE) */
int high; /* high watermark */
int low; /* low watermark */
int send_timeout; /* timeout to use in send */
int send_timeout_close; /* auto-close socket on send_timeout */
int busy_on_send; /* busy on send with timeout! */
int i_bufsz; /* current input buffer size (<= bufsz) */
ErlDrvBinary* i_buf; /* current binary buffer */
char* i_ptr; /* current pos in buf */
char* i_ptr_start; /* packet start pos in buf */
int i_remain; /* remaining chars to read */
int tcp_add_flags;/* Additional TCP descriptor flags */
int http_state; /* 0 = response|request 1=headers fields */
inet_async_multi_op *multi_first;/* NULL == no multi-accept-queue, op is in ordinary queue */
inet_async_multi_op *multi_last;
MultiTimerData *mtd; /* Timer structures for multiple accept */
MultiTimerData *mtd_cache; /* A cache for timer allocations */
#ifdef HAVE_SENDFILE
struct {
ErlDrvSizeT ioq_skip; /* The number of bytes in the queue at the time
* sendfile was issued, which must be sent
* before issuing the sendfile call itself. */
int dup_file_fd; /* The file handle to send from; this is
* duplicated when sendfile is issued to
* reduce (but not eliminate) the impact of a
* nasty race, so we have to remember to close
* it. */
Uint64 bytes_sent;
Uint64 offset;
Uint64 length;
} sendfile;
#endif
};
/* send function */
static int tcp_send(tcp_descriptor* desc, char* ptr, ErlDrvSizeT len);
static int tcp_sendv(tcp_descriptor* desc, ErlIOVec* ev);
static int tcp_recv(tcp_descriptor* desc, int request_len);
static int tcp_deliver(tcp_descriptor* desc, int len);
static int tcp_shutdown_error(tcp_descriptor* desc, int err);
#ifdef HAVE_SENDFILE
static int tcp_inet_sendfile(tcp_descriptor* desc);
static int tcp_sendfile_aborted(tcp_descriptor* desc, int socket_error);
#endif
static int tcp_inet_output(tcp_descriptor* desc, HANDLE event);
static int tcp_inet_input(tcp_descriptor* desc, HANDLE event);
static void tcp_desc_close(tcp_descriptor*);
#ifdef HAVE_UDP
typedef struct {
inet_descriptor inet; /* common data structure (DON'T MOVE) */
int read_packets; /* Number of packets to read per invocation */
int i_bufsz; /* current input buffer size */
ErlDrvBinary* i_buf; /* current binary buffer */
char* i_ptr; /* current pos in buf */
} udp_descriptor;
static int packet_inet_input(udp_descriptor* udesc, HANDLE event);
#endif
/* convert descriptor pointer to inet_descriptor pointer */
#define INETP(d) (&(d)->inet)
#define NEW_ASYNC_ID(desc) ((desc)->op_ref++ & 0xffff)
/* check for transition from active to passive */
#define INET_CHECK_ACTIVE_TO_PASSIVE(inet) \
do { \
if ((inet)->active == INET_ONCE) \
(inet)->active = INET_PASSIVE; \
else if ((inet)->active == INET_MULTI && --((inet)->active_count) == 0) { \
(inet)->active = INET_PASSIVE; \
packet_passive_message(inet); \
} \
} while (0)
static ErlDrvTermData am_ok;
static ErlDrvTermData am_undefined;
static ErlDrvTermData am_unspec;
static ErlDrvTermData am_tcp;
static ErlDrvTermData am_error;
static ErlDrvTermData am_einval;
static ErlDrvTermData am_inet_async;
static ErlDrvTermData am_inet_reply;
static ErlDrvTermData am_timeout;
static ErlDrvTermData am_closed;
static ErlDrvTermData am_tcp_passive;
static ErlDrvTermData am_tcp_closed;
static ErlDrvTermData am_tcp_error;
static ErlDrvTermData am_empty_out_q;
static ErlDrvTermData am_ssl_tls;
#ifdef HAVE_UDP
static ErlDrvTermData am_udp;
static ErlDrvTermData am_udp_passive;
static ErlDrvTermData am_udp_error;
#endif
#ifdef HAVE_SYS_UN_H
static ErlDrvTermData am_local;
#endif
#ifndef __WIN32__
static ErlDrvTermData am_tos;
static ErlDrvTermData am_tclass;
static ErlDrvTermData am_ttl;
#endif
#ifdef HAVE_SCTP
static ErlDrvTermData am_sctp;
static ErlDrvTermData am_sctp_passive;
static ErlDrvTermData am_sctp_error;
static ErlDrvTermData am_true;
static ErlDrvTermData am_false;
static ErlDrvTermData am_buffer;
static ErlDrvTermData am_mode;
static ErlDrvTermData am_list;
static ErlDrvTermData am_binary;
static ErlDrvTermData am_active;
static ErlDrvTermData am_once;
static ErlDrvTermData am_multi;
static ErlDrvTermData am_buffer;
static ErlDrvTermData am_linger;
static ErlDrvTermData am_recbuf;
static ErlDrvTermData am_sndbuf;
static ErlDrvTermData am_reuseaddr;
static ErlDrvTermData am_dontroute;
static ErlDrvTermData am_priority;
static ErlDrvTermData am_recvtos;
static ErlDrvTermData am_recvtclass;
static ErlDrvTermData am_recvttl;
static ErlDrvTermData am_ipv6_v6only;
static ErlDrvTermData am_netns;
static ErlDrvTermData am_bind_to_device;
#endif
#ifdef HAVE_SENDFILE
static ErlDrvTermData am_sendfile;
#endif
static char str_eafnosupport[] = "eafnosupport";
static char str_einval[] = "einval";
/* special errors for bad ports and sequences */
#define EXBADPORT "exbadport"
#define EXBADSEQ "exbadseq"
static int inet_init(void);
static ErlDrvSSizeT ctl_reply(int, char*, ErlDrvSizeT, char**, ErlDrvSizeT);
struct erl_drv_entry inet_driver_entry =
{
inet_init, /* inet_init will add TCP, UDP and SCTP drivers */
NULL, /* start */
NULL, /* stop */
NULL, /* output */
NULL, /* ready_input */
NULL, /* ready_output */
"inet",
NULL,
NULL, /* handle */
NULL, /* control */
NULL, /* timeout */
NULL, /* outputv */
NULL, /* ready_async */
NULL, /* flush */
NULL, /* call */
NULL, /* event */
ERL_DRV_EXTENDED_MARKER,
ERL_DRV_EXTENDED_MAJOR_VERSION,
ERL_DRV_EXTENDED_MINOR_VERSION,
0,
NULL,
NULL,
NULL,
};
#if HAVE_IN6
# if ! defined(HAVE_IN6ADDR_ANY) || ! HAVE_IN6ADDR_ANY
# if HAVE_DECL_IN6ADDR_ANY_INIT
static const struct in6_addr in6addr_any = { { IN6ADDR_ANY_INIT } };
# else
static const struct in6_addr in6addr_any =
{ { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } };
# endif /* HAVE_IN6ADDR_ANY_INIT */
# endif /* ! HAVE_DECL_IN6ADDR_ANY */
# if ! defined(HAVE_IN6ADDR_LOOPBACK) || ! HAVE_IN6ADDR_LOOPBACK
# if HAVE_DECL_IN6ADDR_LOOPBACK_INIT
static const struct in6_addr in6addr_loopback =
{ { IN6ADDR_LOOPBACK_INIT } };
# else
static const struct in6_addr in6addr_loopback =
{ { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } };
# endif /* HAVE_IN6ADDR_LOOPBACk_INIT */
# endif /* ! HAVE_DECL_IN6ADDR_LOOPBACK */
#endif /* HAVE_IN6 */
/* XXX: is this a driver interface function ??? */
void erts_exit(int n, const char*, ...);
/*
* Malloc wrapper,
* we would like to change the behaviour for different
* systems here.
*/
#ifdef FATAL_MALLOC
static void *alloc_wrapper(ErlDrvSizeT size){
void *ret = driver_alloc(size);
if(ret == NULL)
erts_exit(ERTS_ERROR_EXIT,"Out of virtual memory in malloc (%s)", __FILE__);
return ret;
}
#define ALLOC(X) alloc_wrapper(X)
static void *realloc_wrapper(void *current, ErlDrvSizeT size){
void *ret = driver_realloc(current,size);
if(ret == NULL)
erts_exit(ERTS_ERROR_EXIT,"Out of virtual memory in realloc (%s)", __FILE__);
return ret;
}
#define REALLOC(X,Y) realloc_wrapper(X,Y)
#define FREE(P) driver_free((P))
#else /* FATAL_MALLOC */
#define ALLOC(X) driver_alloc((X))
#define REALLOC(X,Y) driver_realloc((X), (Y))
#define FREE(P) driver_free((P))
#endif /* FATAL_MALLOC */
#define INIT_ATOM(NAME) am_ ## NAME = driver_mk_atom(#NAME)
#define LOAD_ATOM_CNT 2
#define LOAD_ATOM(vec, i, atom) \
(((vec)[(i)] = ERL_DRV_ATOM), \
((vec)[(i)+1] = (atom)), \
((i)+LOAD_ATOM_CNT))
#define LOAD_INT_CNT 2
#define LOAD_INT(vec, i, val) \
(((vec)[(i)] = ERL_DRV_INT), \
((vec)[(i)+1] = (ErlDrvTermData)(val)), \
((i)+LOAD_INT_CNT))
#define LOAD_UINT_CNT 2
#define LOAD_UINT(vec, i, val) \
(((vec)[(i)] = ERL_DRV_UINT), \
((vec)[(i)+1] = (ErlDrvTermData)(val)), \
((i)+LOAD_UINT_CNT))
#define LOAD_PORT_CNT 2
#define LOAD_PORT(vec, i, port) \
(((vec)[(i)] = ERL_DRV_PORT), \
((vec)[(i)+1] = (port)), \
((i)+LOAD_PORT_CNT))
#define LOAD_PID_CNT 2
#define LOAD_PID(vec, i, pid) \
(((vec)[(i)] = ERL_DRV_PID), \
((vec)[(i)+1] = (pid)), \
((i)+LOAD_PID_CNT))
#define LOAD_BINARY_CNT 4
#define LOAD_BINARY(vec, i, bin, offs, len) \
(((vec)[(i)] = ERL_DRV_BINARY), \
((vec)[(i)+1] = (ErlDrvTermData)(bin)), \
((vec)[(i)+2] = (len)), \
((vec)[(i)+3] = (offs)), \
((i)+LOAD_BINARY_CNT))
#define LOAD_BUF2BINARY_CNT 3
#define LOAD_BUF2BINARY(vec, i, buf, len) \
(((vec)[(i)] = ERL_DRV_BUF2BINARY), \
((vec)[(i)+1] = (ErlDrvTermData)(buf)), \
((vec)[(i)+2] = (len)), \
((i)+LOAD_BUF2BINARY_CNT))
#define LOAD_STRING_CNT 3
#define LOAD_STRING(vec, i, str, len) \
(((vec)[(i)] = ERL_DRV_STRING), \
((vec)[(i)+1] = (ErlDrvTermData)(str)), \
((vec)[(i)+2] = (len)), \
((i)+LOAD_STRING_CNT))
#define LOAD_STRING_CONS_CNT 3
#define LOAD_STRING_CONS(vec, i, str, len) \
(((vec)[(i)] = ERL_DRV_STRING_CONS), \
((vec)[(i)+1] = (ErlDrvTermData)(str)), \
((vec)[(i)+2] = (len)), \
((i)+LOAD_STRING_CONS_CNT))
#define LOAD_TUPLE_CNT 2
#define LOAD_TUPLE(vec, i, size) \
(((vec)[(i)] = ERL_DRV_TUPLE), \
((vec)[(i)+1] = (size)), \
((i)+LOAD_TUPLE_CNT))
#define LOAD_NIL_CNT 1
#define LOAD_NIL(vec, i) \
(((vec)[(i)] = ERL_DRV_NIL), \
((i)+LOAD_NIL_CNT))
#define LOAD_LIST_CNT 2
#define LOAD_LIST(vec, i, size) \
(((vec)[(i)] = ERL_DRV_LIST), \
((vec)[(i)+1] = (size)), \
((i)+LOAD_LIST_CNT))
#ifdef HAVE_SCTP
/* "IS_SCTP": tells the difference between a UDP and an SCTP socket: */
# define IS_SCTP(desc)((desc)->sprotocol==IPPROTO_SCTP)
/* For AssocID, 4 bytes should be enough -- checked by "init": */
# define GET_ASSOC_ID get_int32
# define ASSOC_ID_LEN 4
# define LOAD_ASSOC_ID LOAD_UINT
# define LOAD_ASSOC_ID_CNT LOAD_UINT_CNT
#else
# define IS_SCTP(desc) 0
#endif
# define ANC_BUFF_SIZE INET_DEF_BUFFER/2 /* XXX: not very good... */
#ifdef HAVE_UDP
static int load_address(ErlDrvTermData* spec, int i, char* buf)
{
int n;
switch (*buf++) { /* Family */
case INET_AF_INET: {
for (n = 2; n < 2+4; n++) {
spec[i++] = ERL_DRV_INT;
spec[i++] = (ErlDrvTermData) ((unsigned char)buf[n]);
}
spec[i++] = ERL_DRV_TUPLE;
spec[i++] = 4;
spec[i++] = ERL_DRV_INT;
spec[i++] = (ErlDrvTermData) get_int16(buf);
break;
}
#if defined(HAVE_IN6) && defined(AF_INET6)
case INET_AF_INET6: {
for (n = 2; n < 2+16; n += 2) {
spec[i++] = ERL_DRV_INT;
spec[i++] = (ErlDrvTermData) get_int16(buf+n);
}
spec[i++] = ERL_DRV_TUPLE;
spec[i++] = 8;
spec[i++] = ERL_DRV_INT;
spec[i++] = (ErlDrvTermData) get_int16(buf);
break;
}
#endif
#ifdef HAVE_SYS_UN_H
case INET_AF_LOCAL: {
int len = *(unsigned char*)buf++;
i = LOAD_ATOM(spec, i, am_local);
i = LOAD_BUF2BINARY(spec, i, buf, len);
spec[i++] = ERL_DRV_TUPLE;
spec[i++] = 2;
spec[i++] = ERL_DRV_INT;
spec[i++] = 0;
break;
}
#endif
case INET_AF_UNSPEC: {
i = LOAD_ATOM(spec, i, am_unspec);
i = LOAD_BUF2BINARY(spec, i, buf, 0);
spec[i++] = ERL_DRV_TUPLE;
spec[i++] = 2;
spec[i++] = ERL_DRV_INT;
spec[i++] = 0;
break;
}
default: { /* INET_AF_UNDEFINED */
i = LOAD_ATOM(spec, i, am_undefined);
i = LOAD_BUF2BINARY(spec, i, buf, 0);
spec[i++] = ERL_DRV_TUPLE;
spec[i++] = 2;
spec[i++] = ERL_DRV_INT;
spec[i++] = 0;
break;
}
}
return i;
}
static struct sockaddr disassoc_sa;
static size_t disassoc_sa_size;
#endif /* #ifdef HAVE_UDP */
#ifdef HAVE_SCTP
/* For SCTP, we often need to return {IP, Port} tuples: */
static int inet_get_address(char* dst, inet_address* src, unsigned int* len);
/* Max of {{int()*8},int()} | {{int()*4},int()} |
* {{'local',binary()},int()}
*/
#define LOAD_INET_GET_ADDRESS_CNT \
(8*LOAD_INT_CNT + LOAD_TUPLE_CNT + LOAD_INT_CNT + LOAD_TUPLE_CNT)
static int load_inet_get_address
(ErlDrvTermData* spec, int i, inet_descriptor* desc,
struct sockaddr_storage* addr)
{
/* The size of the buffer used to stringify the addr is the same as
that of "sockaddr_storage" itself: only their layout is different:
*/
unsigned int len = sizeof(struct sockaddr_storage);
unsigned int alen = len;
char abuf [len];
int res = inet_get_address(abuf, (inet_address*) addr, &alen);
ASSERT(res==0); (void)res;
/* Now "abuf" contains: Family(1b), Port(2b), IP(4|16b) */
/* NB: the following functions are safe to use, as they create tuples
of copied Ints on the "spec", and do not install any String pts --
a ptr to "abuf" would be dangling upon exiting this function: */
i = load_address(spec, i, abuf); /* IP,Port | Family,Addr */
i = LOAD_TUPLE (spec, i, 2);
return i;
}
/* Loading Boolean flags as Atoms: */
#define LOAD_BOOL_CNT LOAD_ATOM_CNT
#define LOAD_BOOL(spec, i, flag) \
LOAD_ATOM((spec), (i), (flag) ? am_true : am_false);
#endif /* HAVE_SCTP */
/* Assume a cache line size of 64 bytes */
#define INET_DRV_CACHE_LINE_SIZE ((ErlDrvUInt) 64)
#define INET_DRV_CACHE_LINE_MASK (INET_DRV_CACHE_LINE_SIZE - 1)
/*
** Binary Buffer Management
** We keep a stack of usable buffers
*/
#define BUFFER_STACK_SIZE 14
#define BUFFER_STACK_MAX_MEM_SIZE (1024*1024)
ErlDrvTSDKey buffer_stack_key;
typedef struct {
int mem_size;
int pos;
ErlDrvBinary* stk[BUFFER_STACK_SIZE];
} InetDrvBufStkBase;
typedef struct {
InetDrvBufStkBase buf;
char align[(((sizeof(InetDrvBufStkBase) - 1) / INET_DRV_CACHE_LINE_SIZE) + 1)
* INET_DRV_CACHE_LINE_SIZE];
} InetDrvBufStk;
static InetDrvBufStk *get_bufstk(void)
{
InetDrvBufStk *bs = erl_drv_tsd_get(buffer_stack_key);
if (bs)
return bs;
bs = driver_alloc(sizeof(InetDrvBufStk)
+ INET_DRV_CACHE_LINE_SIZE - 1);
if (!bs)
return NULL;
if ((((ErlDrvUInt) bs) & INET_DRV_CACHE_LINE_MASK) != 0)
bs = ((InetDrvBufStk *)
((((ErlDrvUInt) bs) & ~INET_DRV_CACHE_LINE_MASK)
+ INET_DRV_CACHE_LINE_SIZE));
erl_drv_tsd_set(buffer_stack_key, bs);
bs->buf.pos = 0;
bs->buf.mem_size = 0;
ASSERT(bs == erl_drv_tsd_get(buffer_stack_key));
return bs;
}
static ErlDrvBinary* alloc_buffer(ErlDrvSizeT minsz)
{
InetDrvBufStk *bs = get_bufstk();
DEBUGF(("alloc_buffer: "LLU"\r\n", (llu_t)minsz));
if (bs && bs->buf.pos > 0) {
long size;
ErlDrvBinary* buf = bs->buf.stk[--bs->buf.pos];
size = buf->orig_size;
bs->buf.mem_size -= size;
ASSERT(0 <= bs->buf.mem_size
&& bs->buf.mem_size <= BUFFER_STACK_MAX_MEM_SIZE);
if (size >= minsz)
return buf;
driver_free_binary(buf);
}
ASSERT(!bs || bs->buf.pos != 0 || bs->buf.mem_size == 0);
return driver_alloc_binary(minsz);
}
/*#define CHECK_DOUBLE_RELEASE 1*/
#ifdef CHECK_DOUBLE_RELEASE
static void
check_double_release(InetDrvBufStk *bs, ErlDrvBinary* buf)
{
#ifdef __GNUC__
#warning CHECK_DOUBLE_RELEASE is enabled, this is a custom build emulator
#endif
int i;
for (i = 0; i < bs->buf.pos; ++i) {
if (bs->buf.stk[i] == buf) {
erts_exit(ERTS_ABORT_EXIT,
"Multiple buffer release in inet_drv, this "
"is a bug, save the core and send it to "
"support@erlang.ericsson.se!");
}
}
}
#endif
static void release_buffer(ErlDrvBinary* buf)
{
InetDrvBufStk *bs;
long size;
DEBUGF(("release_buffer: %ld\r\n", (buf==NULL) ? 0 : buf->orig_size));
if (!buf)
return;
size = buf->orig_size;
if (size > BUFFER_STACK_MAX_MEM_SIZE)
goto free_binary;
bs = get_bufstk();
if (!bs
|| (bs->buf.mem_size + size > BUFFER_STACK_MAX_MEM_SIZE)
|| (bs->buf.pos >= BUFFER_STACK_SIZE)) {
free_binary:
driver_free_binary(buf);
}
else {
#ifdef CHECK_DOUBLE_RELEASE
check_double_release(bs, buf);
#endif
ASSERT(bs->buf.pos != 0 || bs->buf.mem_size == 0);
bs->buf.mem_size += size;
bs->buf.stk[bs->buf.pos++] = buf;
ASSERT(0 <= bs->buf.mem_size
&& bs->buf.mem_size <= BUFFER_STACK_MAX_MEM_SIZE);
}
}
#ifdef HAVE_UDP
static ErlDrvBinary* realloc_buffer(ErlDrvBinary* buf, ErlDrvSizeT newsz)
{
DEBUGF(("realloc_buffer: %ld -> %ld\r\n", (buf==NULL) ? 0 : buf->orig_size, newsz));
return driver_realloc_binary(buf, newsz);
}
#endif
/* use a TRICK, access the refc field to see if any one else has
* a ref to this buffer then call driver_free_binary else
* release_buffer instead
*/
static void free_buffer(ErlDrvBinary* buf)
{
DEBUGF(("free_buffer: %ld\r\n", (buf==NULL) ? 0 : buf->orig_size));
if (buf != NULL) {
if (driver_binary_get_refc(buf) == 1)
release_buffer(buf);
else
driver_free_binary(buf);
}
}
#ifdef __WIN32__
static ErlDrvData dummy_start(ErlDrvPort port, char* command)
{
return (ErlDrvData)port;
}
static ErlDrvSSizeT dummy_ctl(ErlDrvData data, unsigned int cmd,
char* buf, ErlDrvSizeT len, char** rbuf,
ErlDrvSizeT rsize)
{
static char error[] = "no_winsock2";
driver_failure_atom((ErlDrvPort)data, error);
return ctl_reply(INET_REP_ERROR, error, sizeof(error), rbuf, rsize);
}
static void dummy_command(ErlDrvData data, char* buf, ErlDrvSizeT len)
{
}
static struct erl_drv_entry dummy_tcp_driver_entry =
{
NULL, /* init */
dummy_start, /* start */
NULL, /* stop */
dummy_command, /* command */
NULL, /* input */
NULL, /* output */
"tcp_inet", /* name */
NULL,
NULL,
dummy_ctl,
NULL,
NULL
};
static struct erl_drv_entry dummy_udp_driver_entry =
{
NULL, /* init */
dummy_start, /* start */
NULL, /* stop */
dummy_command, /* command */
NULL, /* input */
NULL, /* output */
"udp_inet", /* name */
NULL,
NULL,
dummy_ctl,
NULL,
NULL
};
#ifdef HAVE_SCTP
static struct erl_drv_entry dummy_sctp_driver_entry =
{ /* Though there is no SCTP for Win32 yet... */
NULL, /* init */
dummy_start, /* start */
NULL, /* stop */
dummy_command, /* command */
NULL, /* input */
NULL, /* output */
"sctp_inet", /* name */
NULL,
NULL,
dummy_ctl,
NULL,
NULL
};
#endif
#endif
/* return lowercase string form of errno value */
static char *errno_str(int err)
{
switch (err) {
case INET_ERRNO_SYSTEM_LIMIT:
return "system_limit";
default:
return erl_errno_id(err);
}
}
/* general control reply function */
static ErlDrvSSizeT ctl_reply(int rep, char* buf, ErlDrvSizeT len,
char** rbuf, ErlDrvSizeT rsize)
{
char* ptr;
if ((len+1) > rsize) {
ptr = ALLOC(len+1);
*rbuf = ptr;
}
else
ptr = *rbuf;
*ptr++ = rep;
if (buf) {
memcpy(ptr, buf, len);
} else {
ASSERT(len == 0);
}
return len+1;
}
/* general control error reply function */
static ErlDrvSSizeT ctl_error(int err, char** rbuf, ErlDrvSizeT rsize)
{
char* s = errno_str(err);
return ctl_reply(INET_REP_ERROR, s, strlen(s), rbuf, rsize);
}
static ErlDrvSSizeT ctl_xerror(char* xerr, char** rbuf, ErlDrvSizeT rsize)
{
int n = strlen(xerr);
return ctl_reply(INET_REP_ERROR, xerr, n, rbuf, rsize);
}
static ErlDrvTermData error_atom(int err)
{
return driver_mk_atom(errno_str(err));
}
static void enq_old_multi_op(tcp_descriptor *desc, int id, int req,
ErlDrvTermData caller, MultiTimerData *timeout,
ErlDrvMonitor *monitorp)
{
inet_async_multi_op *opp;
opp = ALLOC(sizeof(inet_async_multi_op));
opp->op.id = id;
opp->op.caller = caller;
opp->op.req = req;
opp->op.tmo.mtd = timeout;
memcpy(&(opp->op.monitor), monitorp, sizeof(ErlDrvMonitor));
opp->next = NULL;
if (desc->multi_first == NULL) {
desc->multi_first = opp;
} else {
desc->multi_last->next = opp;
}
desc->multi_last = opp;
}
static void enq_multi_op(tcp_descriptor *desc, char *buf, int req,
ErlDrvTermData caller, MultiTimerData *timeout,
ErlDrvMonitor *monitorp)
{
int id = NEW_ASYNC_ID(INETP(desc));
enq_old_multi_op(desc,id,req,caller,timeout,monitorp);
if (buf != NULL)
put_int16(id, buf);
}
static int deq_multi_op(tcp_descriptor *desc, int *id_p, int *req_p,
ErlDrvTermData *caller_p, MultiTimerData **timeout_p,
ErlDrvMonitor *monitorp)
{
inet_async_multi_op *opp;
opp = desc->multi_first;
if (!opp) {
return -1;
}
desc->multi_first = opp->next;
if (desc->multi_first == NULL) {
desc->multi_last = NULL;
}
*id_p = opp->op.id;
*req_p = opp->op.req;
*caller_p = opp->op.caller;
if (timeout_p != NULL) {
*timeout_p = opp->op.tmo.mtd;
}
if (monitorp != NULL) {
memcpy(monitorp,&(opp->op.monitor),sizeof(ErlDrvMonitor));
}
FREE(opp);
return 0;
}
static int remove_multi_op(tcp_descriptor *desc, int *id_p, int *req_p,
ErlDrvTermData caller, MultiTimerData **timeout_p,
ErlDrvMonitor *monitorp)
{
inet_async_multi_op *opp, *slap;
for (opp = desc->multi_first, slap = NULL;
opp != NULL && opp->op.caller != caller;
slap = opp, opp = opp->next)
;
if (!opp) {
return -1;
}
if (slap == NULL) {
desc->multi_first = opp->next;
} else {
slap->next = opp->next;
}
if (desc->multi_last == opp) {
desc->multi_last = slap;
}
*id_p = opp->op.id;
*req_p = opp->op.req;
if (timeout_p != NULL) {
*timeout_p = opp->op.tmo.mtd;
}
if (monitorp != NULL) {
memcpy(monitorp,&(opp->op.monitor),sizeof(ErlDrvMonitor));
}
FREE(opp);
return 0;
}
/* setup a new async id + caller (format async_id into buf) */
static int enq_async_w_tmo(inet_descriptor* desc, char* buf, int req, unsigned timeout,
ErlDrvMonitor *monitorp)
{
int id = NEW_ASYNC_ID(desc);
inet_async_op* opp;
if ((opp = desc->oph) == NULL) /* queue empty */
opp = desc->oph = desc->opt = desc->op_queue;
else if (desc->oph == desc->opt) { /* queue full */
DEBUGF(("enq(%p): queue full\r\n", desc->port));
return -1;
}
opp->id = id;
opp->caller = driver_caller(desc->port);
opp->req = req;
opp->tmo.value = timeout;
if (monitorp != NULL) {
memcpy(&(opp->monitor),monitorp,sizeof(ErlDrvMonitor));
}
DEBUGF(("enq(%p): %d %ld %d\r\n",
desc->port, opp->id, opp->caller, opp->req));
opp++;
if (opp >= desc->op_queue + INET_MAX_ASYNC)
desc->oph = desc->op_queue;
else
desc->oph = opp;
if (buf != NULL)
put_int16(id, buf);
return 0;
}
static int enq_async(inet_descriptor* desc, char* buf, int req)
{
return enq_async_w_tmo(desc,buf,req,INET_INFINITY, NULL);
}
static int deq_async_w_tmo(inet_descriptor* desc, int* ap, ErlDrvTermData* cp,
int* rp, unsigned *tp, ErlDrvMonitor *monitorp)
{
inet_async_op* opp;
if ((opp = desc->opt) == NULL) { /* queue empty */
DEBUGF(("deq(%p): queue empty\r\n", desc->port));
return -1;
}
*ap = opp->id;
*cp = opp->caller;
*rp = opp->req;
if (tp != NULL) {
*tp = opp->tmo.value;
}
if (monitorp != NULL) {
memcpy(monitorp,&(opp->monitor),sizeof(ErlDrvMonitor));
}
DEBUGF(("deq(%p): %d %ld %d\r\n",
desc->port, opp->id, opp->caller, opp->req));
opp++;
if (opp >= desc->op_queue + INET_MAX_ASYNC)
desc->opt = desc->op_queue;
else
desc->opt = opp;
if (desc->opt == desc->oph)
desc->opt = desc->oph = NULL;
return 0;
}
static int deq_async(inet_descriptor* desc, int* ap, ErlDrvTermData* cp, int* rp)
{
return deq_async_w_tmo(desc,ap,cp,rp,NULL,NULL);
}
/* send message:
** {inet_async, Port, Ref, ok}
*/
static int
send_async_ok(ErlDrvTermData Port, int Ref,ErlDrvTermData recipient)
{
ErlDrvTermData spec[2*LOAD_ATOM_CNT + LOAD_PORT_CNT +
LOAD_INT_CNT + LOAD_TUPLE_CNT];
int i = 0;
i = LOAD_ATOM(spec, i, am_inet_async);
i = LOAD_PORT(spec, i, Port);
i = LOAD_INT(spec, i, Ref);
i = LOAD_ATOM(spec, i, am_ok);
i = LOAD_TUPLE(spec, i, 4);
ASSERT(i == sizeof(spec)/sizeof(*spec));
return erl_drv_send_term(Port, recipient, spec, i);
}
/* send message:
** {inet_async, Port, Ref, {ok,Port2}}
*/
static int
send_async_ok_port(ErlDrvTermData Port, int Ref,
ErlDrvTermData recipient, ErlDrvTermData Port2)
{
ErlDrvTermData spec[2*LOAD_ATOM_CNT + 2*LOAD_PORT_CNT +
LOAD_INT_CNT + 2*LOAD_TUPLE_CNT];
int i = 0;
i = LOAD_ATOM(spec, i, am_inet_async);
i = LOAD_PORT(spec, i, Port);
i = LOAD_INT(spec, i, Ref);
{
i = LOAD_ATOM(spec, i, am_ok);
i = LOAD_PORT(spec, i, Port2);
i = LOAD_TUPLE(spec, i, 2);
}
i = LOAD_TUPLE(spec, i, 4);
ASSERT(i == sizeof(spec)/sizeof(*spec));
return erl_drv_send_term(Port, recipient, spec, i);
}
/* send message:
** {inet_async, Port, Ref, {error,Reason}}
*/
static int
send_async_error(ErlDrvTermData Port, int Ref,
ErlDrvTermData recipient, ErlDrvTermData Reason)
{
ErlDrvTermData spec[3*LOAD_ATOM_CNT + LOAD_PORT_CNT +
LOAD_INT_CNT + 2*LOAD_TUPLE_CNT];
int i = 0;
i = LOAD_ATOM(spec, i, am_inet_async);
i = LOAD_PORT(spec, i, Port);
i = LOAD_INT(spec, i, Ref);
{
i = LOAD_ATOM(spec, i, am_error);
i = LOAD_ATOM(spec, i, Reason);
i = LOAD_TUPLE(spec, i, 2);
}
i = LOAD_TUPLE(spec, i, 4);
ASSERT(i == sizeof(spec)/sizeof(*spec));
DEBUGF(("send_async_error %ld %ld\r\n", recipient, Reason));
return erl_drv_send_term(Port, recipient, spec, i);
}
static int async_ok(inet_descriptor* desc)
{
int req;
int aid;
ErlDrvTermData caller;
if (deq_async(desc, &aid, &caller, &req) < 0)
return -1;
return send_async_ok(desc->dport, aid, caller);
}
#ifdef HAVE_SCTP
static int async_ok_assoc_id(inet_descriptor* desc, sctp_assoc_t assoc_id)
{
int req;
int aid;
int i = 0;
ErlDrvTermData caller;
ErlDrvTermData spec[2*LOAD_ATOM_CNT + LOAD_PORT_CNT + LOAD_INT_CNT +
LOAD_ASSOC_ID_CNT + 2*LOAD_TUPLE_CNT];
if (deq_async(desc, &aid, &caller, &req) < 0)
return -1;
i = LOAD_ATOM(spec, i, am_inet_async);
i = LOAD_PORT(spec, i, desc->dport);
i = LOAD_INT(spec, i, aid);
{
i = LOAD_ATOM(spec, i, am_ok);
i = LOAD_ASSOC_ID(spec, i, assoc_id);
i = LOAD_TUPLE(spec, i, 2);
}
i = LOAD_TUPLE(spec, i, 4);
ASSERT(i == sizeof(spec)/sizeof(*spec));
return erl_drv_send_term(desc->dport, caller, spec, i);
}
static int async_ok_maybe_assoc_id(inet_descriptor* desc, sctp_assoc_t *p_assoc_id)
{
if (p_assoc_id)
return async_ok_assoc_id(desc, *p_assoc_id);
else
return async_ok(desc);
}
#endif
static int async_ok_port(inet_descriptor* desc, ErlDrvTermData Port2)
{
int req;
int aid;
ErlDrvTermData caller;
if (deq_async(desc, &aid, &caller, &req) < 0)
return -1;
return send_async_ok_port(desc->dport, aid, caller, Port2);
}
static int async_error_am(inet_descriptor* desc, ErlDrvTermData reason)
{
int req;
int aid;
ErlDrvTermData caller;
if (deq_async(desc, &aid, &caller, &req) < 0)
return -1;
return send_async_error(desc->dport, aid, caller, reason);
}
/* dequeue all operations */
static int async_error_am_all(inet_descriptor* desc, ErlDrvTermData reason)
{
int req;
int aid;
ErlDrvTermData caller;
while (deq_async(desc, &aid, &caller, &req) == 0) {
send_async_error(desc->dport, aid, caller, reason);
}
return 0;
}
static int async_error(inet_descriptor* desc, int err)
{
return async_error_am(desc, error_atom(err));
}
/* send:
** {inet_reply, S, ok}
*/
static int inet_reply_ok(inet_descriptor* desc)
{
ErlDrvTermData spec[2*LOAD_ATOM_CNT + LOAD_PORT_CNT + LOAD_TUPLE_CNT];
ErlDrvTermData caller = desc->caller;
int i = 0;
desc->caller = 0;
if (is_not_internal_pid(caller))
return 0;
i = LOAD_ATOM(spec, i, am_inet_reply);
i = LOAD_PORT(spec, i, desc->dport);
i = LOAD_ATOM(spec, i, am_ok);
i = LOAD_TUPLE(spec, i, 3);
ASSERT(i == sizeof(spec)/sizeof(*spec));
return erl_drv_send_term(desc->dport, caller, spec, i);
}
#ifdef HAVE_SCTP
static int inet_reply_ok_port(inet_descriptor* desc, ErlDrvTermData dport)
{
ErlDrvTermData spec[2*LOAD_ATOM_CNT + 2*LOAD_PORT_CNT + 2*LOAD_TUPLE_CNT];
ErlDrvTermData caller = desc->caller;
int i = 0;
i = LOAD_ATOM(spec, i, am_inet_reply);
i = LOAD_PORT(spec, i, desc->dport);
i = LOAD_ATOM(spec, i, am_ok);
i = LOAD_PORT(spec, i, dport);
i = LOAD_TUPLE(spec, i, 2);
i = LOAD_TUPLE(spec, i, 3);
ASSERT(i == sizeof(spec)/sizeof(*spec));
desc->caller = 0;
return erl_drv_send_term(desc->dport, caller, spec, i);
}
#endif
/* send:
** {inet_reply, S, {error, Reason}}
*/
static int inet_reply_error_am(inet_descriptor* desc, ErlDrvTermData reason)
{
ErlDrvTermData spec[3*LOAD_ATOM_CNT + LOAD_PORT_CNT + 2*LOAD_TUPLE_CNT];
ErlDrvTermData caller = desc->caller;
int i = 0;
i = LOAD_ATOM(spec, i, am_inet_reply);
i = LOAD_PORT(spec, i, desc->dport);
i = LOAD_ATOM(spec, i, am_error);
i = LOAD_ATOM(spec, i, reason);
i = LOAD_TUPLE(spec, i, 2);
i = LOAD_TUPLE(spec, i, 3);
ASSERT(i == sizeof(spec)/sizeof(*spec));
desc->caller = 0;
DEBUGF(("inet_reply_error_am %ld %ld\r\n", caller, reason));
return erl_drv_send_term(desc->dport, caller, spec, i);
}
/* send:
** {inet_reply, S, {error, Reason}}
*/
static int inet_reply_error(inet_descriptor* desc, int err)
{
return inet_reply_error_am(desc, error_atom(err));
}
/*
** Deliver port data from buffer
*/
static int inet_port_data(inet_descriptor* desc, const char* buf, int len)
{
unsigned int hsz = desc->hsz;
DEBUGF(("inet_port_data(%p): len = %d\r\n",
desc->port, len));
if ((desc->mode == INET_MODE_LIST) || (hsz > len))
return driver_output2(desc->port, (char*)buf, len, NULL, 0);
else if (hsz > 0)
return driver_output2(desc->port, (char*)buf, hsz, (char*)buf+hsz, len-hsz);
else
return driver_output(desc->port, (char*)buf, len);
}
/*
** Deliver port data from binary (for an active mode socket)
*/
static int
inet_port_binary_data(inet_descriptor* desc, ErlDrvBinary* bin, int offs, int len)
{
unsigned int hsz = desc->hsz;
DEBUGF(("inet_port_binary_data(%p): offs=%d, len = %d\r\n",
desc->port, offs, len));
if ((desc->mode == INET_MODE_LIST) || (hsz > len))
return driver_output2(desc->port, bin->orig_bytes+offs, len, NULL, 0);
else
return driver_output_binary(desc->port, bin->orig_bytes+offs, hsz,
bin, offs+hsz, len-hsz);
}
static ErlDrvTermData am_http_eoh;
static ErlDrvTermData am_http_header;
static ErlDrvTermData am_http_request;
static ErlDrvTermData am_http_response;
static ErlDrvTermData am_http_error;
static ErlDrvTermData am_abs_path;
static ErlDrvTermData am_absoluteURI;
static ErlDrvTermData am_star;
static ErlDrvTermData am_http;
static ErlDrvTermData am_https;
static ErlDrvTermData am_scheme;
static int http_load_string(tcp_descriptor* desc, ErlDrvTermData* spec, int i,
const char* str, int len)
{
if (desc->inet.htype >= TCP_PB_HTTP_BIN) {
ASSERT(desc->inet.htype == TCP_PB_HTTP_BIN ||
desc->inet.htype == TCP_PB_HTTPH_BIN);
i = LOAD_BUF2BINARY(spec, i, str, len);
} else {
i = LOAD_STRING(spec, i, str, len);
}
return i;
}
static int http_response_inetdrv(void *arg, int major, int minor,
int status, const char* phrase, int phrase_len)
{
tcp_descriptor* desc = (tcp_descriptor*) arg;
int i = 0;
ErlDrvTermData spec[27];
ErlDrvTermData caller = ERL_DRV_NIL;
if (desc->inet.active == INET_PASSIVE) {
/* {inet_async,S,Ref,{ok,{http_response,Version,Status,Phrase}}} */
int req;
int aid;
if (deq_async(INETP(desc), &aid, &caller, &req) < 0)
return -1;
i = LOAD_ATOM(spec, i, am_inet_async);
i = LOAD_PORT(spec, i, desc->inet.dport);
i = LOAD_INT(spec, i, aid);
i = LOAD_ATOM(spec, i, am_ok);
}
else {
/* {http, S, {http_response,Version,Status,Phrase}} */
i = LOAD_ATOM(spec, i, am_http);
i = LOAD_PORT(spec, i, desc->inet.dport);
}
i = LOAD_ATOM(spec, i, am_http_response);
i = LOAD_INT(spec, i, major);
i = LOAD_INT(spec, i, minor);
i = LOAD_TUPLE(spec, i, 2);
i = LOAD_INT(spec, i, status);
i = http_load_string(desc, spec, i, phrase, phrase_len);
i = LOAD_TUPLE(spec, i, 4);
if (desc->inet.active == INET_PASSIVE) {
i = LOAD_TUPLE(spec, i, 2);
i = LOAD_TUPLE(spec, i, 4);
ASSERT(i<=27);
return erl_drv_send_term(desc->inet.dport, caller, spec, i);
}
else {
i = LOAD_TUPLE(spec, i, 3);
ASSERT(i<=27);
return erl_drv_output_term(desc->inet.dport, spec, i);
}
}
static int http_load_uri(tcp_descriptor* desc, ErlDrvTermData* spec, int i,
const PacketHttpURI* uri)
{
ErlDrvTermData scheme;
switch (uri->type) {
case URI_STAR:
i = LOAD_ATOM(spec, i, am_star);
break;
case URI_ABS_PATH:
i = LOAD_ATOM(spec, i, am_abs_path);
i = http_load_string(desc, spec, i, uri->s1_ptr, uri->s1_len);
i = LOAD_TUPLE(spec, i, 2);
break;
case URI_HTTP:
scheme = am_http;
goto http_common;
case URI_HTTPS:
scheme = am_https;
http_common:
i = LOAD_ATOM(spec, i, am_absoluteURI);
i = LOAD_ATOM(spec, i, scheme);
i = http_load_string(desc, spec, i, uri->s1_ptr, uri->s1_len);
if (uri->port == 0) {
i = LOAD_ATOM(spec, i, am_undefined);
} else {
i = LOAD_INT(spec, i, uri->port);
}
i = http_load_string(desc, spec, i, uri->s2_ptr, uri->s2_len);
i = LOAD_TUPLE(spec, i, 5);
break;
case URI_STRING:
i = http_load_string(desc, spec, i, uri->s1_ptr, uri->s1_len);
break;
case URI_SCHEME:
i = LOAD_ATOM(spec, i, am_scheme);
i = http_load_string(desc, spec, i, uri->s1_ptr, uri->s1_len);
i = http_load_string(desc, spec, i, uri->s2_ptr, uri->s2_len);
i = LOAD_TUPLE(spec, i, 3);
}
return i;
}
static int
http_request_inetdrv(void* arg, const http_atom_t* meth, const char* meth_ptr,
int meth_len, const PacketHttpURI* uri,
int major, int minor)
{
tcp_descriptor* desc = (tcp_descriptor*) arg;
int i = 0;
ErlDrvTermData spec[43];
ErlDrvTermData caller = ERL_DRV_NIL;
if (desc->inet.active == INET_PASSIVE) {
/* {inet_async, S, Ref, {ok,{http_request,Meth,Uri,Version}}} */
int req;
int aid;
if (deq_async(INETP(desc), &aid, &caller, &req) < 0)
return -1;
i = LOAD_ATOM(spec, i, am_inet_async);
i = LOAD_PORT(spec, i, desc->inet.dport);
i = LOAD_INT(spec, i, aid);
i = LOAD_ATOM(spec, i, am_ok);
}
else {
/* {http, S, {http_request,Meth,Uri,Version}}} */
i = LOAD_ATOM(spec, i, am_http);
i = LOAD_PORT(spec, i, desc->inet.dport);
}
i = LOAD_ATOM(spec, i, am_http_request);
if (meth != NULL)
i = LOAD_ATOM(spec, i, meth->atom);
else
i = http_load_string(desc, spec, i, meth_ptr, meth_len);
i = http_load_uri(desc, spec, i, uri);
i = LOAD_INT(spec, i, major);
i = LOAD_INT(spec, i, minor);
i = LOAD_TUPLE(spec, i, 2);
i = LOAD_TUPLE(spec, i, 4);
if (desc->inet.active == INET_PASSIVE) {
i = LOAD_TUPLE(spec, i, 2);
i = LOAD_TUPLE(spec, i, 4);
ASSERT(i <= 43);
return erl_drv_send_term(desc->inet.dport, caller, spec, i);
}
else {
i = LOAD_TUPLE(spec, i, 3);
ASSERT(i <= 43);
return erl_drv_output_term(desc->inet.dport, spec, i);
}
}
static int
http_header_inetdrv(void* arg, const http_atom_t* name,
const char* name_ptr, int name_len,
const char* oname_ptr, int oname_len,
const char* value_ptr, int value_len)
{
tcp_descriptor* desc = (tcp_descriptor*) arg;
int i = 0;
ErlDrvTermData spec[27];
ErlDrvTermData caller = ERL_DRV_NIL;
if (desc->inet.active == INET_PASSIVE) {
/* {inet_async,S,Ref,{ok,{http_header,Bit,Name,Oname,Value}} */
int req;
int aid;
if (deq_async(INETP(desc), &aid, &caller, &req) < 0)
return -1;
i = LOAD_ATOM(spec, i, am_inet_async);
i = LOAD_PORT(spec, i, desc->inet.dport);
i = LOAD_INT(spec, i, aid);
i = LOAD_ATOM(spec, i, am_ok);
}
else {
/* {http, S, {http_header,Bit,Name,Oname,Value}} */
i = LOAD_ATOM(spec, i, am_http);
i = LOAD_PORT(spec, i, desc->inet.dport);
}
i = LOAD_ATOM(spec, i, am_http_header);
if (name != NULL) {
i = LOAD_INT(spec, i, name->index+1);
i = LOAD_ATOM(spec, i, name->atom);
}
else {
i = LOAD_INT(spec, i, 0);
i = http_load_string(desc, spec, i, name_ptr, name_len);
}
i = http_load_string(desc, spec, i, oname_ptr, oname_len);
i = http_load_string(desc, spec, i, value_ptr, value_len);
i = LOAD_TUPLE(spec, i, 5);
if (desc->inet.active == INET_PASSIVE) {
i = LOAD_TUPLE(spec, i, 2);
i = LOAD_TUPLE(spec, i, 4);
ASSERT(i <= 27);
return erl_drv_send_term(desc->inet.dport, caller, spec, i);
}
else {
i = LOAD_TUPLE(spec, i, 3);
ASSERT(i <= 27);
return erl_drv_output_term(desc->inet.dport, spec, i);
}
}
static int http_eoh_inetdrv(void* arg)
{
tcp_descriptor* desc = (tcp_descriptor*) arg;
int i = 0;
ErlDrvTermData spec[14];
if (desc->inet.active == INET_PASSIVE) {
/* {inet_async,S,Ref,{ok,http_eoh}} */
int req;
int aid;
ErlDrvTermData caller;
if (deq_async(INETP(desc), &aid, &caller, &req) < 0)
return -1;
i = LOAD_ATOM(spec, i, am_inet_async);
i = LOAD_PORT(spec, i, desc->inet.dport);
i = LOAD_INT(spec, i, aid);
i = LOAD_ATOM(spec, i, am_ok);
i = LOAD_ATOM(spec, i, am_http_eoh);
i = LOAD_TUPLE(spec, i, 2);
i = LOAD_TUPLE(spec, i, 4);
ASSERT(i <= 14);
return erl_drv_send_term(desc->inet.dport, caller, spec, i);
}
else {
/* {http, S, http_eoh} */
i = LOAD_ATOM(spec, i, am_http);
i = LOAD_PORT(spec, i, desc->inet.dport);
i = LOAD_ATOM(spec, i, am_http_eoh);
i = LOAD_TUPLE(spec, i, 3);
ASSERT(i <= 14);
return erl_drv_output_term(desc->inet.dport, spec, i);
}
}
static int http_error_inetdrv(void* arg, const char* buf, int len)
{
tcp_descriptor* desc = (tcp_descriptor*) arg;
int i = 0;
ErlDrvTermData spec[19];
if (desc->inet.active == INET_PASSIVE) {
/* {inet_async,S,Ref,{ok,{http_error,Line}}} */
int req;
int aid;
ErlDrvTermData caller;
if (deq_async(INETP(desc), &aid, &caller, &req) < 0)
return -1;
i = LOAD_ATOM(spec, i, am_inet_async);
i = LOAD_PORT(spec, i, desc->inet.dport);
i = LOAD_INT(spec, i, aid);
i = LOAD_ATOM(spec, i, am_ok);
i = LOAD_ATOM(spec, i, am_http_error);
i = http_load_string(desc, spec, i, buf, len);
i = LOAD_TUPLE(spec, i, 2);
i = LOAD_TUPLE(spec, i, 2);
i = LOAD_TUPLE(spec, i, 4);
ASSERT(i <= 19);
return erl_drv_send_term(desc->inet.dport, caller, spec, i);
}
else {
/* {http, S, {http_error,Line} */
i = LOAD_ATOM(spec, i, am_http);
i = LOAD_PORT(spec, i, desc->inet.dport);
i = LOAD_ATOM(spec, i, am_http_error);
i = http_load_string(desc, spec, i, buf, len);
i = LOAD_TUPLE(spec, i, 2);
i = LOAD_TUPLE(spec, i, 3);
ASSERT(i <= 19);
return erl_drv_output_term(desc->inet.dport, spec, i);
}
}
static
int ssl_tls_inetdrv(void* arg, unsigned type, unsigned major, unsigned minor,
const char* buf, int len, const char* prefix, int plen)
{
tcp_descriptor* desc = (tcp_descriptor*) arg;
int i = 0;
ErlDrvTermData spec[30];
ErlDrvTermData caller = ERL_DRV_NIL;
ErlDrvBinary* bin;
int ret;
if ((bin = driver_alloc_binary(plen+len)) == NULL)
return async_error(&desc->inet, ENOMEM);
memcpy(bin->orig_bytes+plen, buf, len);
if (plen) {
memcpy(bin->orig_bytes, prefix, plen);
len += plen;
}
if (desc->inet.active == INET_PASSIVE) {
/* {inet_async,S,Ref,{ok,{ssl_tls,...}}} */
int req;
int aid;
if (deq_async(INETP(desc), &aid, &caller, &req) < 0) {
ret = -1;
goto done;
}
i = LOAD_ATOM(spec, i, am_inet_async);
i = LOAD_PORT(spec, i, desc->inet.dport);
i = LOAD_INT(spec, i, aid);
i = LOAD_ATOM(spec, i, am_ok);
}
/* {ssl_tls,S,ContentType,{Major,Minor},Bin} */
i = LOAD_ATOM(spec, i, am_ssl_tls);
i = LOAD_PORT(spec, i, desc->inet.dport);
i = LOAD_INT(spec, i, type);
i = LOAD_INT(spec, i, major);
i = LOAD_INT(spec, i, minor);
i = LOAD_TUPLE(spec, i, 2);
i = LOAD_BINARY(spec, i, bin, 0, len);
i = LOAD_TUPLE(spec, i, 5);
if (desc->inet.active == INET_PASSIVE) {
i = LOAD_TUPLE(spec, i, 2);
i = LOAD_TUPLE(spec, i, 4);
ASSERT(i <= sizeof(spec)/sizeof(*spec));
ret = erl_drv_send_term(desc->inet.dport, caller, spec, i);
}
else {
ASSERT(i <= sizeof(spec)/sizeof(*spec));
ret = erl_drv_output_term(desc->inet.dport, spec, i);
}
done:
driver_free_binary(bin);
return ret;
}
static PacketCallbacks packet_callbacks =
{
http_response_inetdrv,
http_request_inetdrv,
http_eoh_inetdrv,
http_header_inetdrv,
http_error_inetdrv,
ssl_tls_inetdrv
};
/*
** passive mode reply:
** {inet_async, S, Ref, {ok,[H1,...Hsz | Data]}}
** NB: this is for TCP only;
** UDP and SCTP use inet_async_binary_data .
*/
static int inet_async_data(inet_descriptor* desc, const char* buf, int len)
{
unsigned int hsz = desc->hsz;
ErlDrvTermData spec[20];
ErlDrvTermData caller;
int req;
int aid;
int i = 0;
DEBUGF(("inet_async_data(%p): len = %d\r\n",
desc->port, len));
if (deq_async(desc, &aid, &caller, &req) < 0)
return -1;
i = LOAD_ATOM(spec, i, am_inet_async);
i = LOAD_PORT(spec, i, desc->dport);
i = LOAD_INT(spec, i, aid);
i = LOAD_ATOM(spec, i, am_ok);
if ((desc->mode == INET_MODE_LIST) || (hsz > len)) {
i = LOAD_STRING(spec, i, buf, len); /* => [H1,H2,...Hn] */
i = LOAD_TUPLE(spec, i, 2);
i = LOAD_TUPLE(spec, i, 4);
ASSERT(i == 15);
desc->caller = 0;
return erl_drv_send_term(desc->dport, caller, spec, i);
}
else {
/* INET_MODE_BINARY => [H1,H2,...HSz | Binary] */
int sz = len - hsz;
int code;
i = LOAD_BUF2BINARY(spec, i, buf+hsz, sz);
if (hsz > 0)
i = LOAD_STRING_CONS(spec, i, buf, hsz);
i = LOAD_TUPLE(spec, i, 2);
i = LOAD_TUPLE(spec, i, 4);
ASSERT(i <= 20);
desc->caller = 0;
code = erl_drv_send_term(desc->dport, caller, spec, i);
return code;
}
}
#ifndef __WIN32__
static int load_cmsg_int(ErlDrvTermData *spec, int i,
struct cmsghdr *cmsg) {
union u {
byte uint8;
Uint16 uint16;
Uint32 uint32;
Uint64 uint64;
} *p;
p = (union u*) CMSG_DATA(cmsg);
switch (LEN_CMSG_DATA(cmsg) * CHAR_BIT) {
case 8:
return LOAD_INT(spec, i, p->uint8);
case 16:
return LOAD_INT(spec, i, p->uint16);
case 32:
return LOAD_INT(spec, i, p->uint32);
case 64:
return LOAD_INT(spec, i, p->uint64);
}
return LOAD_INT(spec, i, 0);
}
static int parse_ancillary_data_item(ErlDrvTermData *spec, int i,
struct cmsghdr *cmsg, int *n) {
#define LOAD_CMSG_INT(proto, type, am) \
if (cmsg->cmsg_level == (proto) && \
cmsg->cmsg_type == (type)) { \
i = LOAD_ATOM(spec, i, (am)); \
i = load_cmsg_int(spec, i, cmsg); \
i = LOAD_TUPLE(spec, i, 2); \
(*n)++; \
return i; \
}
#if defined(IPPROTO_IP) && defined(IP_TOS)
LOAD_CMSG_INT(IPPROTO_IP, IP_TOS, am_tos);
#endif
#if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS)
LOAD_CMSG_INT(IPPROTO_IPV6, IPV6_TCLASS, am_tclass);
#endif
#if defined(IPPROTO_IP) && defined(IP_TTL)
LOAD_CMSG_INT(IPPROTO_IP, IP_TTL, am_ttl);
#endif
/* BSD uses the RECV* names in CMSG fields */
#if defined(IPPROTO_IP) && defined(IP_RECVTOS)
LOAD_CMSG_INT(IPPROTO_IP, IP_RECVTOS, am_tos);
#endif
#if defined(IPPROTO_IPV6) && defined(IPV6_RECVTCLASS)
LOAD_CMSG_INT(IPPROTO_IPV6, IPV6_RECVTCLASS, am_tclass);
#endif
#if defined(IPPROTO_IP) && defined(IP_RECVTTL)
LOAD_CMSG_INT(IPPROTO_IP, IP_RECVTTL, am_ttl);
#endif
#undef LOAD_CMSG_INT
return i;
}
#endif /* #ifndef __WIN32__ */
#ifdef HAVE_SCTP
/*
** SCTP-related atoms:
*/
static ErlDrvTermData am_sctp_rtoinfo, /* Option names */
am_sctp_associnfo, am_sctp_initmsg,
am_sctp_autoclose, am_sctp_nodelay,
am_sctp_disable_fragments, am_sctp_i_want_mapped_v4_addr,
am_sctp_maxseg, am_sctp_set_peer_primary_addr,
am_sctp_primary_addr, am_sctp_adaptation_layer,
am_sctp_peer_addr_params, am_sctp_default_send_param,
am_sctp_events, am_sctp_delayed_ack_time,
am_sctp_status, am_sctp_get_peer_addr_info,
/* Record names */
am_sctp_sndrcvinfo, am_sctp_assoc_change,
am_sctp_paddr_change, am_sctp_remote_error,
am_sctp_send_failed, am_sctp_shutdown_event,
am_sctp_adaptation_event, am_sctp_pdapi_event,
am_sctp_assocparams, am_sctp_prim,
am_sctp_setpeerprim, am_sctp_setadaptation,
am_sctp_paddrparams, am_sctp_event_subscribe,
am_sctp_assoc_value, am_sctp_paddrinfo,
/* For #sctp_sndrcvinfo{}: */
am_unordered, am_addr_over,
am_abort, am_eof,
/* For #sctp_assoc_change{}: */
am_comm_up, am_comm_lost,
am_restart, am_shutdown_comp,
am_cant_assoc,
/* For #sctp_paddr_change{}: */
am_addr_available, am_addr_unreachable,
am_addr_removed, am_addr_added,
am_addr_made_prim, am_addr_confirmed,
/* For #sctp_remote_error{}: */
am_short_recv, am_wrong_anc_data,
/* For #sctp_pdap_event{}: */
am_partial_delivery_aborted,
/* For #sctp_paddrparams{}: */
am_hb_enable, am_hb_disable,
am_hb_demand, am_pmtud_enable,
am_pmtud_disable, am_sackdelay_enable,
am_sackdelay_disable,
/* For #sctp_paddrinfo{}: */
am_active, am_inactive,
# if HAVE_DECL_SCTP_UNCONFIRMED
am_unconfirmed,
# endif
/* For #sctp_status{}: */
# if HAVE_DECL_SCTP_EMPTY
am_empty,
# endif
# if HAVE_DECL_SCTP_BOUND
am_bound,
# endif
# if HAVE_DECL_SCTP_LISTEN
am_listen,
# endif
am_cookie_wait, am_cookie_echoed,
am_established, am_shutdown_pending,
am_shutdown_sent, am_shutdown_received,
am_shutdown_ack_sent;
/*
** Parsing of "sctp_sndrcvinfo": ancillary data coming with received msgs.
** This function is mainly used by "sctp_parse_ancillary_data", but also
** by "sctp_parse_async_event" in case of SCTP_SEND_FAILED:
*/
#define SCTP_PARSE_SNDRCVINFO_CNT \
(5*LOAD_ATOM_CNT + 5*LOAD_INT_CNT + 2*LOAD_UINT_CNT + \
LOAD_NIL_CNT + LOAD_LIST_CNT + LOAD_ASSOC_ID_CNT + LOAD_TUPLE_CNT)
static int sctp_parse_sndrcvinfo
(ErlDrvTermData * spec, int i, struct sctp_sndrcvinfo * sri)
{
int n;
i = LOAD_ATOM (spec, i, am_sctp_sndrcvinfo);
i = LOAD_INT (spec, i, sri->sinfo_stream);
i = LOAD_INT (spec, i, sri->sinfo_ssn);
/* Now Flags, as a list: */
n = 0;
if (sri->sinfo_flags & SCTP_UNORDERED)
{ i = LOAD_ATOM (spec, i, am_unordered); n++; }
if (sri->sinfo_flags & SCTP_ADDR_OVER)
{ i = LOAD_ATOM (spec, i, am_addr_over); n++; }
if (sri->sinfo_flags & SCTP_ABORT)
{ i = LOAD_ATOM (spec, i, am_abort); n++; }
if (sri->sinfo_flags & SCTP_EOF)
{ i = LOAD_ATOM (spec, i, am_eof); n++; }
/* SCTP_SENDALL is not yet supported by the Linux kernel */
i = LOAD_NIL (spec, i);
i = LOAD_LIST (spec, i, n+1);
/* Continue with other top-level fields: */
i = LOAD_INT (spec, i, sock_ntohl(sri->sinfo_ppid));
i = LOAD_INT (spec, i, sri->sinfo_context);
i = LOAD_INT (spec, i, sri->sinfo_timetolive);
i = LOAD_UINT (spec, i, sri->sinfo_tsn);
i = LOAD_UINT (spec, i, sri->sinfo_cumtsn);
i = LOAD_ASSOC_ID (spec, i, sri->sinfo_assoc_id);
/* Close up the record: */
i = LOAD_TUPLE (spec, i, 10);
return i;
}
/*
** This function skips non-SCTP ancillary data, returns SCTP-specific anc.data
** (currently "sctp_sndrcvinfo" only) as a list of records:
*/
static int sctp_parse_ancillary_data
(ErlDrvTermData * spec, int i, struct msghdr * mptr)
{
/* First of all, check for ancillary data: */
struct cmsghdr * cmsg, * frst_msg = CMSG_FIRSTHDR(mptr);
int s = 0;
for (cmsg = frst_msg; cmsg != NULL; cmsg = CMSG_NXTHDR(mptr,cmsg))
{
struct sctp_sndrcvinfo * sri;
#ifndef __WIN32
int old_s;
/* Parse ancillary data common to UDP */
old_s = s;
i = parse_ancillary_data_item(spec, i, cmsg, &s);
if (s > old_s) continue;
/* Skip other possible ancillary data, e.g. from IPv6: */
if (cmsg->cmsg_level != IPPROTO_SCTP ||
cmsg->cmsg_type != SCTP_SNDRCV)
continue;
#endif
if (((char*)cmsg + cmsg->cmsg_len) - (char*)frst_msg >
mptr->msg_controllen)
/* MUST check this in Linux -- the returned "cmsg" may actually
go too far! */
break;
/* The ONLY kind of ancillary SCTP data which can occur on receiving
is "sctp_sndrcvinfo" (on sending, "sctp_initmsg" can be specified
by the user). So parse this type:
*/
sri = (struct sctp_sndrcvinfo*) CMSG_DATA(cmsg);
i = sctp_parse_sndrcvinfo (spec, i, sri);
s ++;
}
/* Now make the list of tuples created above. Normally, it will be [] or
a singleton list. The list must first be closed with NIL, otherwise
traversing it in Erlang would be problematic:
*/
i = LOAD_NIL (spec, i);
i = LOAD_LIST(spec, i, s+1);
return i;
}
/*
** Parsing of ERROR and ABORT SCTP chunks. The function returns a list of error
** causes (as atoms). The chunks also contain some extended cause info, but it
** is not very detailed anyway, and of no interest at the user level (it only
** concerns the protocol implementation), so we omit it:
*/
static int sctp_parse_error_chunk
(ErlDrvTermData * spec, int i, char * chunk, int chlen)
{
/* The "chunk" itself contains its length, which must not be greater than
the "chlen" derived from the over-all msg size:
*/
char *causes, *cause;
int coff, /* Cause offset */
ccode, /* Cause code */
clen, /* cause length */
s;
int len = sock_ntohs (*((uint16_t*)(chunk+2)));
ASSERT(len >= 4 && len <= chlen);
causes = chunk + 4;
coff = 0;
len -= 4; /* Total length of the "causes" fields */
cause = causes;
s = 0;
while (coff < len)
{
ccode = sock_ntohs (*((uint16_t*)(cause)));
clen = sock_ntohs (*((uint16_t*)(cause + 2)));
if (clen <= 0)
/* Strange, but must guard against that! */
break;
/* Install the corresp atom for this "ccode": */
i = LOAD_INT (spec, i, ccode);
cause += clen;
coff += clen;
s ++;
}
i = LOAD_NIL (spec, i);
i = LOAD_LIST(spec, i, s+1);
return i;
}
/*
** Parsing of SCTP notification events. NB: they are NOT ancillary data: they
** are sent IN PLACE OF, not in conjunction with, the normal data:
*/
static int sctp_parse_async_event
(ErlDrvTermData * spec, int i, int ok_pos,
ErlDrvTermData error_atom, inet_descriptor* desc,
ErlDrvBinary * bin, int offs, int sz)
{
char* body = bin->orig_bytes + offs;
union sctp_notification * nptr = (union sctp_notification *) body;
switch (nptr->sn_header.sn_type)
{
case SCTP_ASSOC_CHANGE:
{ /* {sctp_assoc_change,
State : Atom(),
Error : Atom(),
OutBoundStreams : Int(),
InBoundStreams : Int(),
AssocID : Int(),
// AbortCauses : [Atom()] // NOT YET IMPLEMENTED
}
*/
struct sctp_assoc_change* sptr = &(nptr->sn_assoc_change);
ASSERT(sptr->sac_length <= sz); /* No buffer overrun */
i = LOAD_ATOM (spec, i, am_sctp_assoc_change);
switch (sptr->sac_state)
{
case SCTP_COMM_UP:
i = LOAD_ATOM (spec, i, am_comm_up);
break;
case SCTP_COMM_LOST:
i = LOAD_ATOM (spec, i, am_comm_lost);
break;
case SCTP_RESTART:
i = LOAD_ATOM (spec, i, am_restart);
break;
case SCTP_SHUTDOWN_COMP:
i = LOAD_ATOM (spec, i, am_shutdown_comp);
break;
case SCTP_CANT_STR_ASSOC:
i = LOAD_ATOM (spec, i, am_cant_assoc);
break;
default:
ASSERT(0);
}
i = LOAD_INT (spec, i, sptr->sac_error);
i = LOAD_INT (spec, i, sptr->sac_outbound_streams);
i = LOAD_INT (spec, i, sptr->sac_inbound_streams);
i = LOAD_INT (spec, i, sptr->sac_assoc_id);
/* The ABORT chunk may or may not be present at the end, depending
on whether there was really an ABORT. In the Linux Kernel SCTP
implementation, this chunk is not delivered anyway, so we leave
it out. Just close up the tuple:
*/
i = LOAD_TUPLE (spec, i, 6);
break;
}
case SCTP_PEER_ADDR_CHANGE:
{ /* {sctp_paddr_change,
AffectedAddr : String(),
State : Atom(),
Error : Atom(),
AssocID : Int()
}
*/
struct sctp_paddr_change* sptr = &(nptr->sn_paddr_change);
ASSERT(sptr->spc_length <= sz); /* No buffer overrun */
i = LOAD_ATOM (spec, i, am_sctp_paddr_change);
PUSH_SUPPRESS_ADDRESS_OF_PACKED_MEMBER();
i = load_inet_get_address(spec, i, desc, &sptr->spc_aaddr);
POP_SUPPRESS_ADDRESS_OF_PACKED_MEMBER();
switch (sptr->spc_state)
{
case SCTP_ADDR_AVAILABLE:
i = LOAD_ATOM (spec, i, am_addr_available);
break;
case SCTP_ADDR_UNREACHABLE:
i = LOAD_ATOM (spec, i, am_addr_unreachable);
break;
case SCTP_ADDR_REMOVED:
i = LOAD_ATOM (spec, i, am_addr_removed);
break;
case SCTP_ADDR_ADDED:
i = LOAD_ATOM (spec, i, am_addr_added);
break;
case SCTP_ADDR_MADE_PRIM:
i = LOAD_ATOM (spec, i, am_addr_made_prim);
break;
#if HAVE_DECL_SCTP_ADDR_CONFIRMED
case SCTP_ADDR_CONFIRMED:
i = LOAD_ATOM (spec, i, am_addr_confirmed);
break;
#endif
default:
ASSERT(0);
}
i = LOAD_INT (spec, i, sptr->spc_error);
i = LOAD_INT (spec, i, sptr->spc_assoc_id);
i = LOAD_TUPLE (spec, i, 5);
break;
}
case SCTP_REMOTE_ERROR:
{ /* This is an error condition, so we return an error term
{sctp_remote_error,
Error : Int(),
AssocID : Int(),
RemoteCauses : [Atom()] // Remote Error flags
}
*/
char *chunk;
int chlen;
struct sctp_remote_error * sptr = &(nptr->sn_remote_error);
ASSERT(sptr->sre_length <= sz); /* No buffer overrun */
/* Over-write the prev part of the response with an error: */
(void)LOAD_ATOM(spec, ok_pos, error_atom);
/* Continue from the curr pos: */
i = LOAD_ATOM (spec, i, am_sctp_remote_error);
i = LOAD_INT (spec, i, sock_ntohs(sptr->sre_error));
i = LOAD_INT (spec, i, sptr->sre_assoc_id);
# ifdef HAVE_STRUCT_SCTP_REMOTE_ERROR_SRE_DATA
chunk = (char*) (&(sptr->sre_data));
# else
chunk = ((char*) &(sptr->sre_assoc_id))
+ sizeof(sptr->sre_assoc_id);
# endif
chlen = sptr->sre_length - (chunk - (char *)sptr);
i = sctp_parse_error_chunk(spec, i, chunk, chlen);
i = LOAD_TUPLE (spec, i, 4);
/* The {error, {...}} will be closed by the caller */
break;
}
case SCTP_SEND_FAILED:
{ /* {sctp_send_failed,
DataSent : Atom() // true or false
Error : Atom(),
OrigInfo : Tuple(),
AssocID : Int(),
OrigData : Binary()
}
This is also an ERROR condition -- overwrite the 'ok':
*/
char *chunk;
int chlen, choff;
struct sctp_send_failed * sptr = &(nptr->sn_send_failed);
ASSERT(sptr->ssf_length <= sz); /* No buffer overrun */
/* Over-write 'ok' with 'error', continue from curr "i": */
(void)LOAD_ATOM(spec, ok_pos, error_atom);
i = LOAD_ATOM (spec, i, am_sctp_send_failed);
switch (sptr->ssf_flags) {
case SCTP_DATA_SENT:
i = LOAD_ATOM (spec, i, am_true);
break;
case SCTP_DATA_UNSENT:
i = LOAD_ATOM (spec, i, am_false);
break;
default:
ASSERT(0);
}
i = LOAD_INT (spec, i, sptr->ssf_error);
/* Now parse the orig SCTP_SNDRCV info */
i = sctp_parse_sndrcvinfo (spec, i, &sptr->ssf_info);
i = LOAD_ASSOC_ID (spec, i, sptr->ssf_assoc_id);
/* Load the orig data chunk, as an unparsed binary. Note that
in LOAD_BINARY below, we must specify the offset wrt bin->
orig_bytes. In Solaris 10, we don't have ssf_data:
*/
# ifdef HAVE_STRUCT_SCTP_SEND_FAILED_SSF_DATA
chunk = (char*) (&(sptr->ssf_data));
# else
chunk = ((char*) &(sptr->ssf_assoc_id))
+ sizeof(sptr->ssf_assoc_id);
# endif
chlen = sptr->ssf_length - (chunk - (char*) sptr);
choff = chunk - bin->orig_bytes;
i = LOAD_BINARY(spec, i, bin, choff, chlen);
i = LOAD_TUPLE (spec, i, 6);
/* The {error, {...}} tuple is not yet closed */
break;
}
case SCTP_SHUTDOWN_EVENT:
{ /* {sctp_shutdown_event,
AssocID : Int()
}
*/
struct sctp_shutdown_event * sptr = &(nptr->sn_shutdown_event);
ASSERT (sptr->sse_length == sizeof(struct sctp_shutdown_event) &&
sptr->sse_length <= sz); /* No buffer overrun */
i = LOAD_ATOM (spec, i, am_sctp_shutdown_event);
i = LOAD_INT (spec, i, sptr->sse_assoc_id);
i = LOAD_TUPLE (spec, i, 2);
break;
}
case SCTP_ADAPTATION_INDICATION:
{ /* {sctp_adaptation_event,
Indication : Atom(),
AssocID : Int()
}
*/
struct sctp_adaptation_event * sptr =
&(nptr->sn_adaptation_event);
ASSERT (sptr->sai_length == sizeof(struct sctp_adaptation_event)
&& sptr->sai_length <= sz); /* No buffer overrun */
i = LOAD_ATOM (spec, i, am_sctp_adaptation_event);
i = LOAD_INT (spec, i, sock_ntohl(sptr->sai_adaptation_ind));
i = LOAD_INT (spec, i, sptr->sai_assoc_id);
i = LOAD_TUPLE (spec, i, 3);
break;
}
case SCTP_PARTIAL_DELIVERY_EVENT:
{ /* It is not clear whether this event is sent to the sender
(when the receiver gets only a part of a message), or to
the receiver itself. In any case, we do not support partial
delivery of msgs in this implementation, so this is an error
condition:
{sctp_pdapi_event, sctp_partial_delivery_aborted, AssocID}:
*/
struct sctp_pdapi_event * sptr;
(void) LOAD_ATOM (spec, ok_pos, error_atom);
sptr = &(nptr->sn_pdapi_event);
ASSERT (sptr->pdapi_length == sizeof(struct sctp_pdapi_event) &&
sptr->pdapi_length <= sz); /* No buffer overrun */
i = LOAD_ATOM (spec, i, am_sctp_pdapi_event);
/* Currently, there is only one indication possible: */
ASSERT (sptr->pdapi_indication == SCTP_PARTIAL_DELIVERY_ABORTED);
i = LOAD_ATOM (spec, i, am_partial_delivery_aborted);
i = LOAD_INT (spec, i, sptr->pdapi_assoc_id);
i = LOAD_TUPLE (spec, i, 3);
/* The {error, {...}} tuple is not yet closed */
break;
}
/* XXX: No more supported SCTP Event types. The standard also provides
SCTP_AUTHENTICATION_EVENT, but it is not implemented in the Linux
kernel, hence not supported here either. It is not possible to
request delivery of such events in this implementation, so they
cannot occur:
*/
default: ASSERT(0);
}
return i;
}
#endif /* HAVE_SCTP */
#ifndef __WIN32__
static int udp_parse_ancillary_data(ErlDrvTermData *spec, int i,
struct msghdr *mptr) {
struct cmsghdr *cmsg;
int n;
n = 0;
for (cmsg = CMSG_FIRSTHDR(mptr);
cmsg != NULL;
cmsg = CMSG_NXTHDR(mptr, cmsg)) {
i = parse_ancillary_data_item(spec, i, cmsg, &n);
}
i = LOAD_NIL(spec, i);
return LOAD_LIST(spec, i, n+1);
}
static int compile_ancillary_data(struct msghdr *mhdr,
char *ptr, ErlDrvSizeT anc_len) {
struct cmsghdr *cmsg;
size_t controllen = 0;
cmsg = CMSG_FIRSTHDR(mhdr);
for (;;) {
if (anc_len == 0) {
/* End of options to compile */
mhdr->msg_controllen = controllen;
return 0;
}
if (cmsg == NULL) {
/* End of destination before end of options */
return 1;
}
#define COMPILE_ANCILLARY_DATA_ITEM(Level, Opt, Type, Get, Size) \
do { \
if (anc_len < (Size)) return 1; \
sys_memset(cmsg, '\0', CMSG_SPACE(sizeof(Type))); \
cmsg->cmsg_level = Level; \
cmsg->cmsg_type = Opt; \
cmsg->cmsg_len = CMSG_LEN(sizeof(Type)); \
*((Type *) CMSG_DATA(cmsg)) = Get(ptr); \
controllen += CMSG_SPACE(sizeof(Type)); \
cmsg = CMSG_NXTHDR(mhdr, cmsg); \
ptr += 4; \
anc_len -= 4; \
} while (0)
#define SIZEOF_ANCILLARY_DATA (2 * CMSG_SPACE(sizeof(int)))
/* (IP_TOS | IPV6_TCLASS) + IP_TTL */
switch (anc_len--, *ptr++) {
case INET_OPT_TOS: {
#if defined(IPPROTO_IP) && defined(IP_TOS)
COMPILE_ANCILLARY_DATA_ITEM(IPPROTO_IP, IP_TOS, int, get_int32, 4);
#else
return 1; /* Socket option not implemented */
#endif
break;
}
case INET_OPT_TTL: {
#if defined(IPPROTO_IP) && defined(IP_TTL)
COMPILE_ANCILLARY_DATA_ITEM(IPPROTO_IP, IP_TTL, int, get_int32, 4);
#else
return 1; /* Socket option not implemented */
#endif
break;
}
case INET_OPT_TCLASS: {
#if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS)
COMPILE_ANCILLARY_DATA_ITEM(IPPROTO_IPV6, IPV6_TCLASS, int, get_int32, 4);
#else
return 1; /* Socket option not implemented */
#endif
break;
}
default:
/* Unknown socket option */
return 1;
}
#undef COMPILE_ANCILLARY_DATA_ITEM
}
}
#endif /* ifndef __WIN32__ */
/*
** passive mode reply:
** for UDP:
** {inet_async, S, Ref, {ok, Data=[H1,...,Hsz | BinData]}}
** or (in the list mode)
** {inet_async, S, Ref, {ok, Data=[H1,...,Hsz]}}
**
** for SCTP:
** {inet_async, S, Ref, {ok, {[H1,...,HSz], [AncilData], Data_OR_Event}}}
** where each AncilDatum:Tuple();
** Data:List() or Binary(), but if List(), then without the Addr part,
** which is moved in front;
** Event:Tuple();
** or
** {inet_async, S, Ref, {error, {[H1,...,HSz], [AncilData], ErrorTerm}}}
**
** Cf: the output of send_async_error() is
** {inet_async, S, Ref, {error, Cause:Atom()}}
*/
static int
inet_async_binary_data
(inet_descriptor* desc, unsigned int phsz,
ErlDrvBinary * bin, int offs, int len, void *mp)
{
unsigned int hsz = desc->hsz + phsz;
ErlDrvTermData spec [PACKET_ERL_DRV_TERM_DATA_LEN];
ErlDrvTermData caller = desc->caller;
int aid;
int req;
int i = 0;
#ifdef HAVE_SCTP
int ok_pos;
#endif
DEBUGF(("inet_async_binary_data(%p): offs=%d, len=%d\r\n",
desc->port, offs, len));
if (deq_async(desc, &aid, &caller, &req) < 0)
return -1;
i = LOAD_ATOM(spec, i, am_inet_async); /* 'inet_async' */
i = LOAD_PORT(spec, i, desc->dport); /* S */
i = LOAD_INT (spec, i, aid); /* Ref */
#ifdef HAVE_SCTP
/* Need to memoise the position of the 'ok' atom written, as it may
later be overridden by an 'error': */
ok_pos = i;
#endif
i = LOAD_ATOM(spec, i, am_ok);
#ifdef HAVE_SCTP
if (IS_SCTP(desc))
{ /* For SCTP we always have desc->hsz==0 (i.e., no application-level
headers are used), so hsz==phsz (see above): */
int sz;
struct msghdr *mptr;
mptr = mp;
ASSERT (mptr);
ASSERT (hsz == phsz && hsz != 0);
sz = len - hsz; /* Size of the msg data proper, w/o the addr */
/* We always put the Addr as a list in front */
i = LOAD_STRING(spec, i, bin->orig_bytes+offs, hsz);
/* Put in the list (possibly empty) of Ancillary Data: */
i = sctp_parse_ancillary_data (spec, i, mptr);
/* Then: Data or Event (Notification)? */
if (mptr->msg_flags & MSG_NOTIFICATION)
/* This is an Event, parse it. It may indicate a normal or an error
condition; in the latter case, the 'ok' above is overridden by
an 'error', and the Event we receive contains the error term: */
i = sctp_parse_async_event
(spec, i, ok_pos, am_error, desc, bin, offs+hsz, sz);
else
/* This is SCTP data, not a notification event. The data can be
returned as a List or as a Binary, similar to the generic case:
*/
if (desc->mode == INET_MODE_LIST)
/* INET_MODE_LIST => [H1,H2,...Hn], addr and data together,
butthe Addr has already been parsed, so start at offs+hsz:
*/
i = LOAD_STRING(spec, i, bin->orig_bytes+offs+hsz, sz);
else
/* INET_MODE_BINARY => Binary */
i = LOAD_BINARY(spec, i, bin, offs+hsz, sz);
/* Close up the {[H1,...,HSz], [AncilData], Event_OR_Data} tuple. This
is valid even in the case when Event is a error notification: */
i = LOAD_TUPLE (spec, i, 3);
}
else
#endif /* HAVE_SCTP */
{
/* Generic case. Both Addr and Data
* (or a single list of them together) are returned: */
if ((desc->mode == INET_MODE_LIST) || (hsz > len)) {
/* INET_MODE_LIST => [H1,H2,...Hn] */
i = LOAD_STRING(spec, i, bin->orig_bytes+offs, len);
}
else {
/* INET_MODE_BINARY => [H1,H2,...HSz | Binary] or [Binary]: */
int sz = len - hsz;
i = LOAD_BINARY(spec, i, bin, offs+hsz, sz);
if (hsz > 0)
i = LOAD_STRING_CONS(spec, i, bin->orig_bytes+offs, hsz);
}
#ifndef __WIN32__
if (mp) {
/* We got ancillary data from an UDP recvmsg.
* Insert an additional tuple level {[F|AddrData],AncData} */
i = udp_parse_ancillary_data(spec, i, (struct msghdr*)mp);
i = LOAD_TUPLE(spec, i, 2);
}
#endif
}
/* Close up the {ok, ...} or {error, ...} tuple: */
i = LOAD_TUPLE(spec, i, 2);
/* Close up the outer {inet_async, S, Ref, {ok|error, ...}} tuple: */
i = LOAD_TUPLE(spec, i, 4);
ASSERT(i <= PACKET_ERL_DRV_TERM_DATA_LEN);
desc->caller = 0;
return erl_drv_send_term(desc->dport, caller, spec, i);
}
/*
** active mode message:
** {tcp, S, [H1,...Hsz | Data]}
*/
static int tcp_message(inet_descriptor* desc, const char* buf, int len)
{
unsigned int hsz = desc->hsz;
ErlDrvTermData spec[20];
int i = 0;
DEBUGF(("tcp_message(%p): len = %d\r\n",
desc->port, len));
/* XXX fprintf(stderr,"tcp_message send.\r\n"); */
i = LOAD_ATOM(spec, i, am_tcp);
i = LOAD_PORT(spec, i, desc->dport);
if ((desc->mode == INET_MODE_LIST) || (hsz > len)) {
i = LOAD_STRING(spec, i, buf, len); /* => [H1,H2,...Hn] */
i = LOAD_TUPLE(spec, i, 3);
ASSERT(i <= 20);
return erl_drv_output_term(desc->dport, spec, i);
}
else {
/* INET_MODE_BINARY => [H1,H2,...HSz | Binary] */
int sz = len - hsz;
int code;
i = LOAD_BUF2BINARY(spec, i, buf+hsz, sz);
if (hsz > 0)
i = LOAD_STRING_CONS(spec, i, buf, hsz);
i = LOAD_TUPLE(spec, i, 3);
ASSERT(i <= 20);
code = erl_drv_output_term(desc->dport, spec, i);
return code;
}
}
/*
** active mode message:
** {tcp, S, [H1,...Hsz | Data]}
*/
static int
tcp_binary_message(inet_descriptor* desc, ErlDrvBinary* bin, int offs, int len)
{
unsigned int hsz = desc->hsz;
ErlDrvTermData spec[20];
int i = 0;
DEBUGF(("tcp_binary_message(%p): len = %d\r\n",
desc->port, len));
i = LOAD_ATOM(spec, i, am_tcp);
i = LOAD_PORT(spec, i, desc->dport);
if ((desc->mode == INET_MODE_LIST) || (hsz > len)) {
/* INET_MODE_LIST => [H1,H2,...Hn] */
i = LOAD_STRING(spec, i, bin->orig_bytes+offs, len);
}
else {
/* INET_MODE_BINARY => [H1,H2,...HSz | Binary] */
int sz = len - hsz;
i = LOAD_BINARY(spec, i, bin, offs+hsz, sz);
if (hsz > 0)
i = LOAD_STRING_CONS(spec, i, bin->orig_bytes+offs, hsz);
}
i = LOAD_TUPLE(spec, i, 3);
ASSERT(i <= 20);
return erl_drv_output_term(desc->dport, spec, i);
}
/*
** send: active mode {tcp_closed, S}
*/
static int tcp_closed_message(tcp_descriptor* desc)
{
ErlDrvTermData spec[6];
int i = 0;
DEBUGF(("tcp_closed_message(%p):\r\n", desc->inet.port));
if (!(desc->tcp_add_flags & TCP_ADDF_CLOSE_SENT)) {
desc->tcp_add_flags |= TCP_ADDF_CLOSE_SENT;
i = LOAD_ATOM(spec, i, am_tcp_closed);
i = LOAD_PORT(spec, i, desc->inet.dport);
i = LOAD_TUPLE(spec, i, 2);
ASSERT(i <= 6);
return erl_drv_output_term(desc->inet.dport, spec, i);
}
return 0;
}
/*
** send active message {tcp_error, S, Error}
*/
static int tcp_error_message(tcp_descriptor* desc, int err)
{
ErlDrvTermData spec[8];
ErlDrvTermData am_err = error_atom(err);
int i = 0;
DEBUGF(("tcp_error_message(%p): %d\r\n",
desc->inet.port, err));
i = LOAD_ATOM(spec, i, am_tcp_error);
i = LOAD_PORT(spec, i, desc->inet.dport);
i = LOAD_ATOM(spec, i, am_err);
i = LOAD_TUPLE(spec, i, 3);
ASSERT(i <= 8);
return erl_drv_output_term(desc->inet.dport, spec, i);
}
#ifdef HAVE_UDP
/*
** active mode message:
** {udp, S, IP, Port, [H1,...Hsz | Data]} or
** {sctp, S, IP, Port, {[AncilData], Event_or_Data}}
** where
** [H1,...,HSz] are msg headers (without IP/Port, UDP only),
** [AddrLen, H2,...,HSz] are msg headers for UDP AF_UNIX only
** Data : List() | Binary()
*/
static int packet_binary_message(inet_descriptor* desc,
ErlDrvBinary* bin, int offs, int len,
void *mp)
{
unsigned int hsz = desc->hsz;
ErlDrvTermData spec [PACKET_ERL_DRV_TERM_DATA_LEN];
int i = 0;
int alen;
char* data = bin->orig_bytes+offs;
DEBUGF(("packet_binary_message(%p): len = %d\r\n",
desc->port, len));
# ifdef HAVE_SCTP
i = LOAD_ATOM(spec, i, IS_SCTP(desc) ? am_sctp : am_udp); /* UDP|SCTP */
# else
i = LOAD_ATOM(spec, i, am_udp ); /* UDP only */
# endif
i = LOAD_PORT(spec, i, desc->dport); /* S */
alen = addrlen(data);
i = load_address(spec, i, data); /* IP,Port | Family,Addr */
offs += alen;
len -= alen;
# ifdef HAVE_SCTP
if (!IS_SCTP(desc))
# endif
{
#ifndef __WIN32__
if (mp) i = udp_parse_ancillary_data(spec, i, (struct msghdr*)mp);
#endif
/* We got ancillary data from an UDP recvmsg.
* Insert an additional tuple level {AncData,[F|AddrData]}
*/
if ((desc->mode == INET_MODE_LIST) || (hsz > len))
/* INET_MODE_LIST, or only headers => [H1,H2,...Hn] */
i = LOAD_STRING(spec, i, bin->orig_bytes+offs, len);
else {
/* INET_MODE_BINARY => [H1,H2,...HSz | Binary] */
int sz = len - hsz;
i = LOAD_BINARY(spec, i, bin, offs+hsz, sz);
if (hsz > 0)
i = LOAD_STRING_CONS(spec, i, bin->orig_bytes+offs, hsz);
}
/* Close up the outer 5-or-6-tuple */
#ifndef __WIN32__
if (mp) i = LOAD_TUPLE(spec, i, 6);
else
#endif
i = LOAD_TUPLE(spec, i, 5);
}
# ifdef HAVE_SCTP
else
{
struct msghdr *mptr;
mptr = mp;
/* For SCTP we always have desc->hsz==0 (i.e., no application-level
headers are used): */
ASSERT(hsz == 0);
/* Put in the list (possibly empty) of Ancillary Data: */
i = sctp_parse_ancillary_data (spec, i, mptr);
/* Then: Data or Event (Notification)? */
if (mptr->msg_flags & MSG_NOTIFICATION)
/* This is an Event, parse it. It may indicate a normal or an error
condition; in the latter case, the initial 'sctp' atom is over-
ridden by 'sctp_error', and the Event we receive contains the
error term: */
i = sctp_parse_async_event
(spec, i, 0, am_sctp_error, desc, bin, offs, len);
else
/* This is SCTP data, not a notification event. The data can be
returned as a List or as a Binary, similar to the generic case:
*/
if (desc->mode == INET_MODE_LIST)
/* INET_MODE_LIST => [H1,H2,...Hn], addr and data together,
but the Addr has already been parsed, so start at offs:
*/
i = LOAD_STRING(spec, i, bin->orig_bytes+offs, len);
else
/* INET_MODE_BINARY => Binary */
i = LOAD_BINARY(spec, i, bin, offs, len);
/* Close up the {[AncilData], Event_OR_Data} tuple: */
i = LOAD_TUPLE (spec, i, 2);
/* Close up the outer 5-tuple: */
i = LOAD_TUPLE(spec, i, 5);
}
# endif /* HAVE_SCTP */
ASSERT(i <= PACKET_ERL_DRV_TERM_DATA_LEN);
return erl_drv_output_term(desc->dport, spec, i);
}
#endif
/*
** active mode message: send active-to-passive transition message
** {tcp_passive, S} or
** {udp_passive, S} or
** {sctp_passive, S}
*/
static int packet_passive_message(inet_descriptor* desc)
{
ErlDrvTermData spec[6];
int i = 0;
DEBUGF(("packet_passive_message(%p):\r\n", desc->port));
#if !defined(HAVE_UDP) && !defined(HAVE_SCTP)
i = LOAD_ATOM(spec, i, am_tcp_passive);
#else
if (desc->sprotocol == IPPROTO_TCP)
i = LOAD_ATOM(spec, i, am_tcp_passive);
else {
#ifdef HAVE_SCTP
i = LOAD_ATOM(spec, i, IS_SCTP(desc) ? am_sctp_passive : am_udp_passive);
#else
i = LOAD_ATOM(spec, i, am_udp_passive);
#endif
}
#endif
i = LOAD_PORT(spec, i, desc->dport);
i = LOAD_TUPLE(spec, i, 2);
ASSERT(i <= 6);
return erl_drv_output_term(desc->dport, spec, i);
}
#ifdef HAVE_UDP
/*
** send active message {udp_error|sctp_error, S, Error}
*/
static int packet_error_message(udp_descriptor* udesc, int err)
{
inet_descriptor* desc = INETP(udesc);
ErlDrvTermData spec[2*LOAD_ATOM_CNT + LOAD_PORT_CNT + LOAD_TUPLE_CNT];
ErlDrvTermData am_err = error_atom(err);
int i = 0;
DEBUGF(("packet_error_message(%p): %d\r\n",
desc->port, err));
# ifdef HAVE_SCTP
if (IS_SCTP(desc) )
i = LOAD_ATOM(spec, i, am_sctp_error);
else
# endif
i = LOAD_ATOM(spec, i, am_udp_error);
i = LOAD_PORT(spec, i, desc->dport);
i = LOAD_ATOM(spec, i, am_err);
i = LOAD_TUPLE(spec, i, 3);
ASSERT(i == sizeof(spec)/sizeof(*spec));
return erl_drv_output_term(desc->dport, spec, i);
}
#endif
/*
** active=TRUE:
** (NOTE! distribution MUST use active=TRUE, deliver=PORT)
** deliver=PORT {S, {data, [H1,..Hsz | Data]}}
** deliver=TERM {tcp, S, [H1..Hsz | Data]}
**
** active=FALSE:
** {async, S, Ref, {ok,[H1,...Hsz | Data]}}
*/
static int tcp_reply_data(tcp_descriptor* desc, char* buf, int len)
{
int code;
const char* body = buf;
int bodylen = len;
packet_get_body(desc->inet.htype, &body, &bodylen);
if (desc->inet.deliver == INET_DELIVER_PORT) {
code = inet_port_data(INETP(desc), body, bodylen);
}
else if ((code=packet_parse(desc->inet.htype, buf, len,
&desc->http_state, &packet_callbacks,
desc)) == 0) {
/* No body parsing, return raw binary */
if (desc->inet.active == INET_PASSIVE)
return inet_async_data(INETP(desc), body, bodylen);
else
code = tcp_message(INETP(desc), body, bodylen);
}
if (code < 0)
return code;
INET_CHECK_ACTIVE_TO_PASSIVE(INETP(desc));
return code;
}
static int
tcp_reply_binary_data(tcp_descriptor* desc, ErlDrvBinary* bin, int offs, int len)
{
int code;
const char* buf = bin->orig_bytes + offs;
const char* body = buf;
int bodylen = len;
packet_get_body(desc->inet.htype, &body, &bodylen);
offs = body - bin->orig_bytes; /* body offset now */
if (desc->inet.deliver == INET_DELIVER_PORT)
code = inet_port_binary_data(INETP(desc), bin, offs, bodylen);
else if ((code=packet_parse(desc->inet.htype, buf, len, &desc->http_state,
&packet_callbacks,desc)) == 0) {
/* No body parsing, return raw data */
if (desc->inet.active == INET_PASSIVE)
return inet_async_binary_data(INETP(desc), 0, bin, offs, bodylen, NULL);
else
code = tcp_binary_message(INETP(desc), bin, offs, bodylen);
}
if (code < 0)
return code;
INET_CHECK_ACTIVE_TO_PASSIVE(INETP(desc));
return code;
}
#ifdef HAVE_UDP
static int
packet_reply_binary_data(inet_descriptor* desc, unsigned int hsz,
ErlDrvBinary * bin, int offs, int len,
void *mp)
{
int code;
if (desc->active == INET_PASSIVE)
/* "inet" is actually for both UDP and SCTP, as well as TCP! */
return inet_async_binary_data(desc, hsz, bin, offs, len, mp);
else
{ /* INET_ACTIVE or INET_ONCE: */
if (desc->deliver == INET_DELIVER_PORT)
code = inet_port_binary_data(desc, bin, offs, len);
else
code = packet_binary_message(desc, bin, offs, len, mp);
if (code < 0)
return code;
INET_CHECK_ACTIVE_TO_PASSIVE(desc);
return code;
}
}
#endif
/* ----------------------------------------------------------------------------
INET
---------------------------------------------------------------------------- */
static int
sock_init(void) /* May be called multiple times. */
{
#ifdef __WIN32__
WORD wVersionRequested;
WSADATA wsaData;
static int res = -1; /* res < 0 == initialization never attempted */
if (res >= 0)
return res;
wVersionRequested = MAKEWORD(2,0);
if (WSAStartup(wVersionRequested, &wsaData) != 0)
goto error;
if ((LOBYTE(wsaData.wVersion) != 2) || (HIBYTE(wsaData.wVersion) != 0))
goto error;
find_dynamic_functions();
return res = 1;
error:
WSACleanup();
return res = 0;
#else
return 1;
#endif
}
#ifdef HAVE_SCTP
static void inet_init_sctp(void) {
INIT_ATOM(sctp);
INIT_ATOM(sctp_passive);
INIT_ATOM(sctp_error);
INIT_ATOM(true);
INIT_ATOM(false);
INIT_ATOM(buffer);
INIT_ATOM(mode);
INIT_ATOM(list);
INIT_ATOM(binary);
INIT_ATOM(active);
INIT_ATOM(once);
INIT_ATOM(multi);
INIT_ATOM(buffer);
INIT_ATOM(linger);
INIT_ATOM(recbuf);
INIT_ATOM(sndbuf);
INIT_ATOM(reuseaddr);
INIT_ATOM(dontroute);
INIT_ATOM(priority);
INIT_ATOM(recvtos);
INIT_ATOM(recvtclass);
INIT_ATOM(recvttl);
INIT_ATOM(ipv6_v6only);
INIT_ATOM(netns);
INIT_ATOM(bind_to_device);
/* Option names */
INIT_ATOM(sctp_rtoinfo);
INIT_ATOM(sctp_associnfo);
INIT_ATOM(sctp_initmsg);
INIT_ATOM(sctp_autoclose);
INIT_ATOM(sctp_nodelay);
INIT_ATOM(sctp_disable_fragments);
INIT_ATOM(sctp_i_want_mapped_v4_addr);
INIT_ATOM(sctp_maxseg);
INIT_ATOM(sctp_set_peer_primary_addr);
INIT_ATOM(sctp_primary_addr);
INIT_ATOM(sctp_adaptation_layer);
INIT_ATOM(sctp_peer_addr_params);
INIT_ATOM(sctp_default_send_param);
INIT_ATOM(sctp_events);
INIT_ATOM(sctp_delayed_ack_time);
INIT_ATOM(sctp_status);
INIT_ATOM(sctp_get_peer_addr_info);
/* Record names */
INIT_ATOM(sctp_sndrcvinfo);
INIT_ATOM(sctp_assoc_change);
INIT_ATOM(sctp_paddr_change);
INIT_ATOM(sctp_remote_error);
INIT_ATOM(sctp_send_failed);
INIT_ATOM(sctp_shutdown_event);
INIT_ATOM(sctp_adaptation_event);
INIT_ATOM(sctp_pdapi_event);
INIT_ATOM(sctp_assocparams);
INIT_ATOM(sctp_prim);
INIT_ATOM(sctp_setpeerprim);
INIT_ATOM(sctp_setadaptation);
INIT_ATOM(sctp_paddrparams);
INIT_ATOM(sctp_event_subscribe);
INIT_ATOM(sctp_assoc_value);
INIT_ATOM(sctp_paddrinfo);
/* For #sctp_sndrcvinfo{}: */
INIT_ATOM(unordered);
INIT_ATOM(addr_over);
INIT_ATOM(abort);
INIT_ATOM(eof);
/* For #sctp_assoc_change{}: */
INIT_ATOM(comm_up);
INIT_ATOM(comm_lost);
INIT_ATOM(restart);
INIT_ATOM(shutdown_comp);
INIT_ATOM(cant_assoc);
/* For #sctp_paddr_change{}: */
INIT_ATOM(addr_available);
INIT_ATOM(addr_unreachable);
INIT_ATOM(addr_removed);
INIT_ATOM(addr_added);
INIT_ATOM(addr_made_prim);
INIT_ATOM(addr_confirmed);
INIT_ATOM(short_recv);
INIT_ATOM(wrong_anc_data);
/* For #sctp_pdap_event{}: */
INIT_ATOM(partial_delivery_aborted);
/* For #sctp_paddrparams{}: */
INIT_ATOM(hb_enable);
INIT_ATOM(hb_disable);
INIT_ATOM(hb_demand);
INIT_ATOM(pmtud_enable);
INIT_ATOM(pmtud_disable);
INIT_ATOM(sackdelay_enable);
INIT_ATOM(sackdelay_disable);
/* For #sctp_paddrinfo{}: */
INIT_ATOM(active);
INIT_ATOM(inactive);
# if HAVE_DECL_SCTP_UNCONFIRMED
INIT_ATOM(unconfirmed);
# endif
/* For #sctp_status{}: */
# if HAVE_DECL_SCTP_EMPTY
INIT_ATOM(empty);
# endif
# if HAVE_DECL_SCTP_BOUND
INIT_ATOM(bound);
# endif
# if HAVE_DECL_SCTP_LISTEN
INIT_ATOM(listen);
# endif
INIT_ATOM(cookie_wait);
INIT_ATOM(cookie_echoed);
INIT_ATOM(established);
INIT_ATOM(shutdown_pending);
INIT_ATOM(shutdown_sent);
INIT_ATOM(shutdown_received);
INIT_ATOM(shutdown_ack_sent);
}
#endif /* HAVE_SCTP */
static int inet_init()
{
if (!sock_init())
goto error;
#if !defined(__WIN32__) && !defined(NO_SYSCONF)
iov_max = (int) sysconf(_SC_IOV_MAX);
if (iov_max < 0) {
#ifdef IOV_MAX
iov_max = IOV_MAX;
#else
iov_max = 16; /* min value required by POSIX */
#endif
}
ASSERT(iov_max >= 16);
#endif
if (0 != erl_drv_tsd_key_create("inet_buffer_stack_key", &buffer_stack_key))
goto error;
ERTS_CT_ASSERT(sizeof(struct in_addr) == 4);
# if defined(HAVE_IN6) && defined(AF_INET6)
ERTS_CT_ASSERT(sizeof(struct in6_addr) == 16);
# endif
INIT_ATOM(ok);
INIT_ATOM(undefined);
INIT_ATOM(unspec);
INIT_ATOM(tcp);
#ifdef HAVE_UDP
INIT_ATOM(udp);
#endif
INIT_ATOM(error);
INIT_ATOM(einval);
INIT_ATOM(inet_async);
INIT_ATOM(inet_reply);
INIT_ATOM(timeout);
INIT_ATOM(closed);
INIT_ATOM(tcp_passive);
INIT_ATOM(tcp_closed);
INIT_ATOM(tcp_error);
#ifdef HAVE_UDP
INIT_ATOM(udp_passive);
INIT_ATOM(udp_error);
#endif
#ifdef HAVE_SYS_UN_H
INIT_ATOM(local);
#endif
INIT_ATOM(empty_out_q);
INIT_ATOM(ssl_tls);
#ifndef __WIN32__
INIT_ATOM(tos);
INIT_ATOM(tclass);
INIT_ATOM(ttl);
#endif
INIT_ATOM(http_eoh);
INIT_ATOM(http_header);
INIT_ATOM(http_request);
INIT_ATOM(http_response);
INIT_ATOM(http_error);
INIT_ATOM(abs_path);
INIT_ATOM(absoluteURI);
am_star = driver_mk_atom("*");
INIT_ATOM(http);
INIT_ATOM(https);
INIT_ATOM(scheme);
#ifdef HAVE_SENDFILE
INIT_ATOM(sendfile);
#endif
/* add TCP, UDP and SCTP drivers */
add_driver_entry(&tcp_inet_driver_entry);
#ifdef HAVE_UDP
add_driver_entry(&udp_inet_driver_entry);
#endif
#ifdef HAVE_SCTP
/* Check the size of SCTP AssocID -- currently both this driver and the
Erlang part require 32 bit: */
ERTS_CT_ASSERT(sizeof(sctp_assoc_t)==ASSOC_ID_LEN);
# if defined(HAVE_SCTP_BINDX)
p_sctp_bindx = sctp_bindx;
# if defined(HAVE_SCTP_PEELOFF)
p_sctp_peeloff = sctp_peeloff;
# else
p_sctp_peeloff = NULL;
# endif
# if defined(HAVE_SCTP_GETLADDRS) && defined(HAVE_SCTP_FREELADDRS)
p_sctp_getladdrs = sctp_getladdrs;
p_sctp_freeladdrs = sctp_freeladdrs;
# else
p_sctp_getladdrs = NULL;
p_sctp_freeladdrs = NULL;
# endif
# if defined(HAVE_SCTP_GETPADDRS) && defined(HAVE_SCTP_FREEPADDRS)
p_sctp_getpaddrs = sctp_getpaddrs;
p_sctp_freepaddrs = sctp_freepaddrs;
# else
p_sctp_getpaddrs = NULL;
p_sctp_freepaddrs = NULL;
# endif
# if defined(HAVE_SCTP_CONNECTX)
p_sctp_connectx = sctp_connectx;
# else
p_sctp_connectx = NULL;
# endif
inet_init_sctp();
add_driver_entry(&sctp_inet_driver_entry);
# else
# ifndef LIBSCTP
# error LIBSCTP not defined
# endif
{
static void *h_libsctp = NULL;
if (erts_sys_ddll_open_noext(STRINGIFY(LIBSCTP), &h_libsctp, NULL)
== 0) {
void *ptr;
if (erts_sys_ddll_sym(h_libsctp, "sctp_bindx", &ptr) == 0) {
p_sctp_bindx = ptr;
if (erts_sys_ddll_sym(h_libsctp, "sctp_peeloff", &ptr) == 0) {
p_sctp_peeloff = ptr;
}
else p_sctp_peeloff = NULL;
if (erts_sys_ddll_sym(h_libsctp, "sctp_getladdrs", &ptr) == 0) {
p_sctp_getladdrs = ptr;
}
else p_sctp_getladdrs = NULL;
if (erts_sys_ddll_sym(h_libsctp, "sctp_freeladdrs", &ptr) == 0) {
p_sctp_freeladdrs = ptr;
}
else {
p_sctp_freeladdrs = NULL;
p_sctp_getladdrs = NULL;
}
if (erts_sys_ddll_sym(h_libsctp, "sctp_getpaddrs", &ptr) == 0) {
p_sctp_getpaddrs = ptr;
}
else p_sctp_getpaddrs = NULL;
if (erts_sys_ddll_sym(h_libsctp, "sctp_freepaddrs", &ptr) == 0) {
p_sctp_freepaddrs = ptr;
}
else {
p_sctp_freepaddrs = NULL;
p_sctp_getpaddrs = NULL;
}
if (erts_sys_ddll_vsym(h_libsctp, "sctp_connectx", "VERS_3", &ptr) == 0) {
p_sctp_connectx = ptr;
}
else p_sctp_connectx = NULL;
inet_init_sctp();
add_driver_entry(&sctp_inet_driver_entry);
}
else p_sctp_bindx = NULL;
}
}
# endif
#endif
/* remove the dummy inet driver */
remove_driver_entry(&inet_driver_entry);
return 0;
error:
remove_driver_entry(&inet_driver_entry);
return -1;
}
/*
** Set an inaddr structure:
** *src = [P1,P0,X1,X2,.....]
** dst points to a structure large enugh to keep any kind
** of inaddr.
** *len is set to length of src on call
** and is set to actual length of dst on return
** return NULL if ok or ptr to errno string for error
*/
static char* inet_set_address(int family, inet_address* dst,
char* *src, ErlDrvSizeT* len)
{
short port;
switch (family) {
case AF_INET: {
if (*len < 2+4) return str_einval;
sys_memzero((char*)dst, sizeof(struct sockaddr_in));
port = get_int16(*src);
#ifndef NO_SA_LEN
dst->sai.sin_len = sizeof(struct sockaddr_in);
#endif
dst->sai.sin_family = family;
dst->sai.sin_port = sock_htons(port);
sys_memcpy(&dst->sai.sin_addr, (*src)+2, 4);
*len = sizeof(struct sockaddr_in);
*src += 2 + 4;
return NULL;
}
#if defined(HAVE_IN6) && defined(AF_INET6)
case AF_INET6: {
if (*len < 2+16) return str_einval;
sys_memzero((char*)dst, sizeof(struct sockaddr_in6));
port = get_int16(*src);
*src += 2;
#ifndef NO_SA_LEN
dst->sai6.sin6_len = sizeof(struct sockaddr_in6);
#endif
dst->sai6.sin6_family = family;
dst->sai6.sin6_port = sock_htons(port);
sys_memcpy(&dst->sai6.sin6_addr, *src, 16);
*src += 16;
dst->sai6.sin6_flowinfo = get_int32(*src);
*src += 4;
dst->sai6.sin6_scope_id = get_int32(*src);
*src += 4;
*len = sizeof(struct sockaddr_in6);
return NULL;
}
#endif
#ifdef HAVE_SYS_UN_H
case AF_UNIX: {
int n;
if (*len == 0) return str_einval;
n = *((unsigned char*)(*src)); /* Length field */
if (*len < 1+n) return str_einval;
if (n +
#ifdef __linux__
/* Make sure the address gets zero terminated
* except when the first byte is \0 because then it is
* sort of zero terminated although the zero termination
* comes before the address...
* This fix handles Linux's nonportable
* abstract socket address extension.
*/
((*len) > 1 && (*src)[1] == '\0' ? 0 : 1)
#else
1
#endif
> sizeof(dst->sal.sun_path)) {
return str_einval;
}
sys_memzero((char*)dst, sizeof(struct sockaddr_un));
dst->sal.sun_family = family;
sys_memcpy(dst->sal.sun_path, (*src)+1, n);
*len = offsetof(struct sockaddr_un, sun_path) + n;
#ifndef NO_SA_LEN
dst->sal.sun_len = *len;
#endif
*src += 1 + n;
return NULL;
}
#endif
}
return str_eafnosupport;
}
/*
** Set an inaddr structure, address family comes from source data,
** or from argument if source data specifies constant address.
**
** *src = [TAG,P1,P0]
** when TAG = INET_AF_ANY | INET_AF_LOOPBACK
** *src = [TAG,P1,P0,X1,X2,...]
** when TAG = INET_AF_INET | INET_AF_INET6 | INET_AF_LOCAL
** *src = [TAG,Len,...]
** when TAG = INET_AF_LOCAL
*/
static char *inet_set_faddress(int family, inet_address* dst,
char* *src, ErlDrvSizeT* len) {
int tag;
if (*len < 1) return str_einval;
(*len) --;
tag = *((*src) ++);
switch (tag) {
case INET_AF_INET:
family = AF_INET;
break;
# if defined(HAVE_IN6) && defined(AF_INET6)
case INET_AF_INET6:
family = AF_INET6;
break;
# endif
# ifdef HAVE_SYS_UN_H
case INET_AF_LOCAL: {
family = AF_UNIX;
break;
}
# endif
case INET_AF_ANY:
case INET_AF_LOOPBACK: {
int port;
if (*len < 2) return str_einval;
port = get_int16(*src);
switch (family) {
case AF_INET: {
struct in_addr addr;
switch (tag) {
case INET_AF_ANY:
addr.s_addr = sock_htonl(INADDR_ANY);
break;
case INET_AF_LOOPBACK:
addr.s_addr = sock_htonl(INADDR_LOOPBACK);
break;
default:
return str_einval;
}
sys_memzero((char*)dst, sizeof(struct sockaddr_in));
#ifndef NO_SA_LEN
dst->sai.sin_len = sizeof(struct sockaddr_in6);
#endif
dst->sai.sin_family = family;
dst->sai.sin_port = sock_htons(port);
dst->sai.sin_addr.s_addr = addr.s_addr;
*len = sizeof(struct sockaddr_in);
} break;
# if defined(HAVE_IN6) && defined(AF_INET6)
case AF_INET6: {
const struct in6_addr* paddr;
switch (tag) {
case INET_AF_ANY:
paddr = &in6addr_any;
break;
case INET_AF_LOOPBACK:
paddr = &in6addr_loopback;
break;
default:
return str_einval;
}
sys_memzero((char*)dst, sizeof(struct sockaddr_in6));
#ifndef NO_SA_LEN
dst->sai6.sin6_len = sizeof(struct sockaddr_in6);
#endif
dst->sai6.sin6_family = family;
dst->sai6.sin6_port = sock_htons(port);
dst->sai6.sin6_flowinfo = 0; /* XXX this may be set as well ?? */
dst->sai6.sin6_scope_id = 0; /* XXX this may be set as well ?? */
dst->sai6.sin6_addr = *paddr;
*len = sizeof(struct sockaddr_in6);
} break;
# endif
default:
return str_einval;
}
*src += 2;
return NULL;
} break;
default:
return str_eafnosupport;
}
return inet_set_address(family, dst, src, len);
}
/* Get a inaddr structure
** src = inaddr structure
** dst is filled with [F,P1,P0,X1,....]
** *len is the length of structure
** where F is the family code (coded)
** and *len is the length of dst on return
** (suitable to deliver to erlang)
*/
static int inet_get_address(char* dst, inet_address* src, unsigned int* len)
{
/* Compare the code with inet_address_to_erlang() */
int family;
short port;
family = src->sa.sa_family;
if ((family == AF_INET) && (*len >= sizeof(struct sockaddr_in))) {
dst[0] = INET_AF_INET;
port = sock_ntohs(src->sai.sin_port);
put_int16(port, dst+1);
sys_memcpy(dst+3, (char*)&src->sai.sin_addr, sizeof(struct in_addr));
*len = 3 + sizeof(struct in_addr);
return 0;
}
#if defined(HAVE_IN6) && defined(AF_INET6)
else if ((family == AF_INET6) && (*len >= sizeof(struct sockaddr_in6))) {
dst[0] = INET_AF_INET6;
port = sock_ntohs(src->sai6.sin6_port);
put_int16(port, dst+1);
sys_memcpy(dst+3, (char*)&src->sai6.sin6_addr,sizeof(struct in6_addr));
*len = 3 + sizeof(struct in6_addr);
return 0;
}
#endif
#ifdef HAVE_SYS_UN_H
else if (family == AF_UNIX) {
size_t n, m;
if (*len < offsetof(struct sockaddr_un, sun_path)) return -1;
n = *len - offsetof(struct sockaddr_un, sun_path);
if (255 < n) return -1;
m = my_strnlen(src->sal.sun_path, n);
#ifdef __linux__
/* Assume that the address is a zero terminated string,
* except when the first byte is \0 i.e the string length is 0,
* then use the reported length instead.
* This fix handles Linux's nonportable
* abstract socket address extension.
*/
if (m == 0) m = n;
#endif
dst[0] = INET_AF_LOCAL;
dst[1] = (char) ((unsigned char) m);
sys_memcpy(dst+2, src->sal.sun_path, m);
*len = 1 + 1 + m;
return 0;
}
#endif
else if (family == AF_UNSPEC) {
dst[0] = INET_AF_UNSPEC;
*len = 1;
}
else {
dst[0] = INET_AF_UNDEFINED;
*len = 1;
}
return -1;
}
/* Same as the above, but take family from the address structure,
** and advance the address pointer to the next address
** according to the size of the current,
** and return the resulting encoded size
*/
static int
inet_address_to_erlang(char *dst, inet_address **src, SOCKLEN_T sz) {
/* Compare the code with inet_get_address() */
short port;
switch ((*src)->sa.sa_family) {
case AF_INET:
if (dst) {
dst[0] = INET_AF_INET;
port = sock_ntohs((*src)->sai.sin_port);
put_int16(port, dst+1);
sys_memcpy(dst+1+2, (char *) &(*src)->sai.sin_addr, 4);
}
(*src) = (inet_address *) (&(*src)->sai + 1);
return 1 + 2 + 4;
#if defined(HAVE_IN6) && defined(AF_INET6)
case AF_INET6:
if (dst) {
dst[0] = INET_AF_INET6;
port = sock_ntohs((*src)->sai6.sin6_port);
put_int16(port, dst+1);
VALGRIND_MAKE_MEM_DEFINED(&(*src)->sai6.sin6_addr,16); /* false undefs from syscall sctp_get[lp]addrs */
sys_memcpy(dst+1+2, (char *) &(*src)->sai6.sin6_addr, 16);
}
(*src) = (inet_address *) (&(*src)->sai6 + 1);
return 1 + 2 + 16;
#endif
#ifdef HAVE_SYS_UN_H
case AF_UNIX: {
size_t n, m;
if (sz < offsetof(struct sockaddr_un, sun_path)) return -1;
n = sz - offsetof(struct sockaddr_un, sun_path);
if (255 < n) return -1;
m = my_strnlen((*src)->sal.sun_path, n);
#ifdef __linux__
/* Assume that the address is a zero terminated string,
* except when the first byte is \0 i.e the string length is 0,
* Then use the reported length instead.
* This fix handles Linux's nonportable
* abstract socket address extension.
*/
if (m == 0) m = n;
#endif
if (dst) {
dst[0] = INET_AF_LOCAL;
dst[1] = (char) ((unsigned char) m);
sys_memcpy(dst+2, (*src)->sal.sun_path, m);
}
(*src) = (inet_address *) (&(*src)->sal + 1);
return 1 + 1 + m;
}
#endif
default:
return -1;
}
}
/* Encode n encoded addresses from addrs in the result buffer
*/
static ErlDrvSizeT reply_inet_addrs
(int n, inet_address *addrs, char **rbuf, ErlDrvSizeT rsize, SOCKLEN_T sz) {
inet_address *ia;
int i, s;
ErlDrvSizeT rlen;
if (IS_SOCKET_ERROR(n)) return ctl_error(sock_errno(), rbuf, rsize);
if (n == 0) return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
/* The sz argument is only used when we have got an actual size
* of addrs[0] from e.g getsockname() and then n == 1
* so we will loop over 1 element below. Otherwise sz
* would be expected to differ between addresses but that
* can only happen for AF_UNIX and we will only be called with
* n > 1 for SCTP and that will never (?) happen with AF_UNIX
*/
/* Calculate result length */
rlen = 1;
ia = addrs;
for (i = 0; i < n; i++) {
s = inet_address_to_erlang(NULL, &ia, sz);
if (s < 0) break;
rlen += s;
}
if (rlen > rsize) (*rbuf) = ALLOC(rlen);
(*rbuf)[0] = INET_REP_OK;
rlen = 1;
ia = addrs;
for (i = 0; i < n; i++) {
s = inet_address_to_erlang((*rbuf)+rlen, &ia, sz);
if (s < 0) break;
rlen += s;
}
return rlen;
}
static void desc_close(inet_descriptor* desc)
{
if (desc->s != INVALID_SOCKET) {
#ifdef __WIN32__
winsock_event_select(desc, FD_READ|FD_WRITE|FD_CLOSE, 0);
sock_close(desc->s);
desc->forced_events = 0;
desc->send_would_block = 0;
#endif
/*
* We should close the fd here, but the other driver might still
* be selecting on it.
*/
if (!INET_IGNORED(desc))
driver_select(desc->port,(ErlDrvEvent)(SWord)desc->event,
ERL_DRV_USE, 0);
else
inet_stop_select((ErlDrvEvent)(SWord)desc->event,NULL);
desc->event = INVALID_EVENT; /* closed by stop_select callback */
desc->s = INVALID_SOCKET;
desc->event_mask = 0;
/* mark as disconnected in case when socket is left lingering due to
* {exit_on_close, false} option in gen_tcp socket creation. Next
* write to socket should produce {error, enotconn} and send a
* message {tcp_error,#Port<>,econnreset} */
desc->state &= ~INET_STATE_CONNECTED;
}
}
static void desc_close_read(inet_descriptor* desc)
{
if (desc->s != INVALID_SOCKET) {
#ifdef __WIN32__
/* This call cannot be right???
* We want to turn off read events but keep any write events.
* But on windows driver_select(...,READ,1) is only used as a
* way to hook into the pollset. sock_select is used to control
* which events to wait for.
* It seems we used to disabled all events for the socket here.
*
driver_select(desc->port, desc->event, DO_READ, 0); REMOVED */
#endif
sock_select(desc, FD_READ | FD_CLOSE, 0);
}
}
static int erl_inet_close(inet_descriptor* desc)
{
free_subscribers(&desc->empty_out_q_subs);
if ((desc->prebound == 0) && (desc->state & INET_F_OPEN)) {
desc_close(desc);
desc->state = INET_STATE_CLOSED;
} else if (desc->prebound && (desc->s != INVALID_SOCKET)) {
sock_select(desc, FD_READ | FD_WRITE | FD_CLOSE | ERL_DRV_USE_NO_CALLBACK, 0);
desc->event_mask = 0;
#ifdef __WIN32__
desc->forced_events = 0;
desc->send_would_block = 0;
#endif
}
return 0;
}
static ErlDrvSSizeT inet_ctl_open(inet_descriptor* desc, int domain, int type,
char** rbuf, ErlDrvSizeT rsize)
{
int save_errno;
int protocol;
#ifdef HAVE_SETNS
int current_ns, new_ns;
current_ns = new_ns = 0;
#endif
save_errno = 0;
if (desc->state != INET_STATE_CLOSED)
return ctl_xerror(EXBADSEQ, rbuf, rsize);
#ifdef HAVE_SETNS
if (desc->netns != NULL) {
/* Temporarily change network namespace for this thread
* while creating the socket
*/
current_ns = open("/proc/self/ns/net", O_RDONLY);
if (current_ns == INVALID_SOCKET)
return ctl_error(sock_errno(), rbuf, rsize);
new_ns = open(desc->netns, O_RDONLY);
if (new_ns == INVALID_SOCKET) {
save_errno = sock_errno();
while (close(current_ns) == INVALID_SOCKET &&
sock_errno() == EINTR)
;
return ctl_error(save_errno, rbuf, rsize);
}
if (setns(new_ns, CLONE_NEWNET) != 0) {
save_errno = sock_errno();
while (close(new_ns) == INVALID_SOCKET &&
sock_errno() == EINTR)
;
while (close(current_ns) == INVALID_SOCKET &&
sock_errno() == EINTR)
;
return ctl_error(save_errno, rbuf, rsize);
}
else {
while (close(new_ns) == INVALID_SOCKET &&
sock_errno() == EINTR)
;
}
}
#endif
protocol = desc->sprotocol;
#ifdef HAVE_SYS_UN_H
if (domain == AF_UNIX) protocol = 0;
#endif
if ((desc->s = sock_open(domain, type, protocol)) == INVALID_SOCKET)
save_errno = sock_errno();
#ifdef HAVE_SETNS
if (desc->netns != NULL) {
/* Restore network namespace */
if (setns(current_ns, CLONE_NEWNET) != 0) {
/* XXX Failed to restore network namespace.
* What to do? Tidy up and return an error...
* Note that the thread now might still be in the namespace.
* Can this even happen? Should the emulator be aborted?
*/
if (desc->s != INVALID_SOCKET)
save_errno = sock_errno();
while (close(desc->s) == INVALID_SOCKET &&
sock_errno() == EINTR)
;
desc->s = INVALID_SOCKET;
while (close(current_ns) == INVALID_SOCKET &&
sock_errno() == EINTR)
;
return ctl_error(save_errno, rbuf, rsize);
}
else {
while (close(current_ns) == INVALID_SOCKET &&
sock_errno() == EINTR)
;
}
}
#endif
if (desc->s == INVALID_SOCKET)
return ctl_error(save_errno, rbuf, rsize);
if ((desc->event = sock_create_event(desc)) == INVALID_EVENT) {
save_errno = sock_errno();
while (close(desc->s) == INVALID_SOCKET &&
sock_errno() == EINTR)
;
desc->s = INVALID_SOCKET;
return ctl_error(save_errno, rbuf, rsize);
}
SET_NONBLOCKING(desc->s);
#ifdef __WIN32__
driver_select(desc->port, desc->event, ERL_DRV_READ, 1);
#endif
desc->state = INET_STATE_OPEN;
desc->stype = type;
desc->sfamily = domain;
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
/* as inet_open but pass in an open socket (MUST BE OF RIGHT TYPE) */
static ErlDrvSSizeT inet_ctl_fdopen(inet_descriptor* desc, int domain, int type,
SOCKET s, Uint32 bound,
char** rbuf, ErlDrvSizeT rsize)
{
inet_address name;
SOCKLEN_T sz;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_ctl_fdopen -> entry with"
"\r\n socket: %d"
"\r\n bound: %s"
"\r\n domain: %d"
"\r\n type: %d"
"\r\n",
__LINE__,
desc->s, driver_caller(desc->port),
s, B2S(bound), domain, type) );
if (bound) {
/* check that it is a socket and that the socket is bound */
sz = sizeof(name);
sys_memzero((char *) &name, sz);
if (IS_SOCKET_ERROR(sock_name(s, (struct sockaddr*) &name, &sz)))
return ctl_error(sock_errno(), rbuf, rsize);
if (name.sa.sa_family != domain)
return ctl_error(EINVAL, rbuf, rsize);
}
desc->s = s;
if ((desc->event = sock_create_event(desc)) == INVALID_EVENT)
return ctl_error(sock_errno(), rbuf, rsize);
SET_NONBLOCKING(desc->s);
#ifdef __WIN32__
driver_select(desc->port, desc->event, ERL_DRV_READ, 1);
#endif
desc->state = INET_STATE_OPEN;
if (type == SOCK_STREAM) { /* check if connected */
sz = sizeof(name);
if (!IS_SOCKET_ERROR(sock_peer(s, (struct sockaddr*) &name, &sz))) {
desc->state = INET_STATE_CONNECTED;
}
}
desc->prebound = 1; /* used to prevent a real close since
* the fd probably comes from an
* external wrapper program, so it is
* not certain that we can open it again */
desc->stype = type;
desc->sfamily = domain;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_ctl_fdopen -> done\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
/*
** store interface info as: (bytes)
** [Len] Name(Len) Flags(1) addr(4) baddr(4) mask(4) bw(4)
*/
struct addr_if {
char name[INET_IFNAMSIZ];
long flags; /* coded flags */
struct in_addr addr; /* interface address */
struct in_addr baddr; /* broadcast address */
struct in_addr mask; /* netmask */
};
#ifndef SIOCGIFNETMASK
static struct in_addr net_mask(struct in_addr in)
{
register u_long i = sock_ntohl(in.s_addr);
if (IN_CLASSA(i))
in.s_addr = sock_htonl(IN_CLASSA_NET);
else if (IN_CLASSB(i))
in.s_addr = sock_htonl(IN_CLASSB_NET);
else
in.s_addr = sock_htonl(IN_CLASSC_NET);
return in;
}
#endif
#if defined(__WIN32__) && defined(SIO_GET_INTERFACE_LIST)
/* format address in dot notation */
static char* fmt_addr(unsigned long x, char* ptr)
{
int i;
for (i = 0; i < 4; i++) {
int nb[3];
int y = (x >> 24) & 0xff;
x <<= 8;
nb[0] = y % 10; y /= 10;
nb[1] = y % 10; y /= 10;
nb[2] = y % 10; y /= 10;
switch((nb[2] ? 3 : (nb[1] ? 2 : 1))) {
case 3: *ptr++ = nb[2] + '0';
case 2: *ptr++ = nb[1] + '0';
case 1: *ptr++ = nb[0] + '0';
}
*ptr++ = '.';
}
*(ptr-1) = '\0';
return ptr;
}
static int parse_addr(char* ptr, int n, long* x)
{
long addr = 0;
int dots = 0;
int digs = 0;
int v = 0;
while(n--) {
switch(*ptr) {
case '0': case '1': case '2':case '3':case '4':case '5':
case '6': case '7': case '8':case '9':
v = v*10 + *ptr - '0';
if (++digs > 3) return -1;
break;
case '.':
if ((dots>2) || (digs==0) || (digs > 3) || (v > 0xff)) return -1;
dots++;
digs = 0;
addr = (addr << 8) | v;
v = 0;
break;
default:
return -1;
}
ptr++;
}
if ((dots!=3) || (digs==0) || (digs > 3) || (v > 0xff)) return -1;
addr = (addr << 8) | v;
*x = addr;
return 0;
}
#ifdef __GNU__
#warning "Undefined AF_LINK for GNU/Hurd"
#undef AF_LINK
#endif
#endif
#define buf_check(ptr, end, n) \
do { if ((end)-(ptr) < (n)) goto error; } while(0)
static char* sockaddr_to_buf(struct sockaddr* addr, char* ptr, char* end)
{
if (addr->sa_family == AF_INET || addr->sa_family == 0) {
struct in_addr *p = &(((struct sockaddr_in*) addr)->sin_addr);
buf_check(ptr, end, 1 + sizeof(struct in_addr));
*ptr = INET_AF_INET;
sys_memcpy(ptr+1, (char*)p, sizeof(struct in_addr));
return ptr + 1 + sizeof(struct in_addr);
}
#if defined(HAVE_IN6) && defined(AF_INET6)
else if (addr->sa_family == AF_INET6) {
struct in6_addr *p = &(((struct sockaddr_in6*) addr)->sin6_addr);
buf_check(ptr, end, 1 + sizeof(struct in6_addr));
*ptr = INET_AF_INET6;
sys_memcpy(ptr+1, (char*)p, sizeof(struct in6_addr));
return ptr + 1 + sizeof(struct in6_addr);
}
#endif
#if defined(AF_LINK)
else if (addr->sa_family == AF_LINK) {
struct sockaddr_dl *sdl_p = (struct sockaddr_dl*) addr;
buf_check(ptr, end, 2 + sdl_p->sdl_alen);
put_int16(sdl_p->sdl_alen, ptr); ptr += 2;
sys_memcpy(ptr, sdl_p->sdl_data + sdl_p->sdl_nlen, sdl_p->sdl_alen);
return ptr + sdl_p->sdl_alen;
}
#endif
#if defined(AF_PACKET) && defined(HAVE_NETPACKET_PACKET_H)
else if(addr->sa_family == AF_PACKET) {
struct sockaddr_ll *sll_p = (struct sockaddr_ll*) addr;
buf_check(ptr, end, 2 + sll_p->sll_halen);
put_int16(sll_p->sll_halen, ptr); ptr += 2;
sys_memcpy(ptr, sll_p->sll_addr, sll_p->sll_halen);
return ptr + sll_p->sll_halen;
}
#endif
return ptr;
error:
return NULL;
}
/* sockaddr_bufsz_need
* Returns the number of bytes needed to store the information
* through sockaddr_to_buf
*/
static size_t sockaddr_bufsz_need(struct sockaddr* addr)
{
if (addr->sa_family == AF_INET || addr->sa_family == 0) {
return 1 + sizeof(struct in_addr);
}
#if defined(HAVE_IN6) && defined(AF_INET6)
else if (addr->sa_family == AF_INET6) {
return 1 + sizeof(struct in6_addr);
}
#endif
#if defined(AF_LINK)
if (addr->sa_family == AF_LINK) {
struct sockaddr_dl *sdl_p = (struct sockaddr_dl*) addr;
return 2 + sdl_p->sdl_alen;
}
#endif
#if defined(AF_PACKET) && defined(HAVE_NETPACKET_PACKET_H)
else if(addr->sa_family == AF_PACKET) {
struct sockaddr_ll *sll_p = (struct sockaddr_ll*) addr;
return 2 + sll_p->sll_halen;
}
#endif
return 0;
}
static char* buf_to_sockaddr(char* ptr, char* end, struct sockaddr* addr)
{
buf_check(ptr,end,1);
switch (*ptr++) {
case INET_AF_INET: {
struct in_addr *p = &((struct sockaddr_in*)addr)->sin_addr;
buf_check(ptr,end,sizeof(struct in_addr));
sys_memcpy((char*) p, ptr, sizeof(struct in_addr));
addr->sa_family = AF_INET;
return ptr + sizeof(struct in_addr);
}
#if defined(HAVE_IN6) && defined(AF_INET6)
case INET_AF_INET6: {
struct in6_addr *p = &((struct sockaddr_in6*)addr)->sin6_addr;
buf_check(ptr,end,sizeof(struct in6_addr));
sys_memcpy((char*) p, ptr, sizeof(struct in6_addr));
addr->sa_family = AF_INET6;
return ptr + sizeof(struct in6_addr);
}
#endif
}
error:
return NULL;
}
#if defined (IFF_POINTOPOINT)
#define IFGET_FLAGS(cflags) IFGET_FLAGS_P2P(cflags, IFF_POINTOPOINT)
#elif defined IFF_POINTTOPOINT
#define IFGET_FLAGS(cflags) IFGET_FLAGS_P2P(cflags, IFF_POINTTOPOINT)
#endif
#define IFGET_FLAGS_P2P(cflags, iff_ptp) \
((((cflags) & IFF_UP) ? INET_IFF_UP : 0) | \
(((cflags) & IFF_BROADCAST) ? INET_IFF_BROADCAST : 0) | \
(((cflags) & IFF_LOOPBACK) ? INET_IFF_LOOPBACK : 0) | \
(((cflags) & iff_ptp) ? INET_IFF_POINTTOPOINT : 0) | \
(((cflags) & IFF_UP) ? INET_IFF_RUNNING : 0) | /* emulate running ? */ \
(((cflags) & IFF_MULTICAST) ? INET_IFF_MULTICAST : 0))
#if defined(__WIN32__) && defined(SIO_GET_INTERFACE_LIST)
static ErlDrvSSizeT inet_ctl_getiflist(inet_descriptor* desc,
char** rbuf, ErlDrvSizeT rsize)
{
char ifbuf[BUFSIZ];
char sbuf[BUFSIZ];
char* sptr;
INTERFACE_INFO* ifp;
DWORD len;
ErlDrvSizeT n;
int err;
ifp = (INTERFACE_INFO*) ifbuf;
len = 0;
err = WSAIoctl(desc->s, SIO_GET_INTERFACE_LIST, NULL, 0,
(LPVOID) ifp, BUFSIZ, (LPDWORD) &len,
NULL, NULL);
if (err == SOCKET_ERROR)
return ctl_error(sock_errno(), rbuf, rsize);
n = (len + sizeof(INTERFACE_INFO) - 1) / sizeof(INTERFACE_INFO);
sptr = sbuf;
while(n--) {
if (((struct sockaddr*)&ifp->iiAddress)->sa_family == desc->sfamily) {
struct in_addr sina = ((struct sockaddr_in*)&ifp->iiAddress)->sin_addr;
/* discard INADDR_ANY interface address */
if (sina.s_addr != INADDR_ANY)
sptr = fmt_addr(sock_ntohl(sina.s_addr), sptr);
}
ifp++;
}
return ctl_reply(INET_REP_OK, sbuf, sptr - sbuf, rbuf, rsize);
}
/* input is an ip-address in string format i.e A.B.C.D
** scan the INTERFACE_LIST to get the options
*/
static ErlDrvSSizeT inet_ctl_ifget(inet_descriptor* desc, char* buf,
ErlDrvSizeT len, char** rbuf, ErlDrvSizeT rsize)
{
char ifbuf[BUFSIZ];
int n;
char sbuf[BUFSIZ];
char* sptr;
char* s_end = sbuf + BUFSIZ;
int namlen;
int err;
INTERFACE_INFO* ifp;
long namaddr;
if ((len == 0) || ((namlen = get_int8(buf)) > len))
goto error;
if (parse_addr(buf+1, namlen, &namaddr) < 0)
goto error;
namaddr = sock_ntohl(namaddr);
buf += (namlen+1);
len -= (namlen+1);
ifp = (INTERFACE_INFO*) ifbuf;
err = WSAIoctl(desc->s, SIO_GET_INTERFACE_LIST, NULL, 0,
(LPVOID) ifp, BUFSIZ, (LPDWORD) &n,
NULL, NULL);
if (err == SOCKET_ERROR) {
return ctl_error(sock_errno(), rbuf, rsize);
}
n = (n + sizeof(INTERFACE_INFO) - 1) / sizeof(INTERFACE_INFO);
/* find interface */
while(n) {
if (((struct sockaddr_in*)&ifp->iiAddress)->sin_addr.s_addr == namaddr)
break;
ifp++;
n--;
}
if (n == 0)
goto error;
sptr = sbuf;
while (len--) {
switch(*buf++) {
case INET_IFOPT_ADDR:
buf_check(sptr, s_end, 1);
*sptr++ = INET_IFOPT_ADDR;
if ((sptr = sockaddr_to_buf((struct sockaddr *)&ifp->iiAddress,
sptr, s_end)) == NULL)
goto error;
break;
case INET_IFOPT_HWADDR:
break;
case INET_IFOPT_BROADADDR:
#ifdef SIOCGIFBRDADDR
buf_check(sptr, s_end, 1);
*sptr++ = INET_IFOPT_BROADADDR;
if ((sptr=sockaddr_to_buf((struct sockaddr *)
&ifp->iiBroadcastAddress,sptr,s_end))
== NULL)
goto error;
#endif
break;
case INET_IFOPT_DSTADDR:
break;
case INET_IFOPT_NETMASK:
buf_check(sptr, s_end, 1);
*sptr++ = INET_IFOPT_NETMASK;
if ((sptr = sockaddr_to_buf((struct sockaddr *)
&ifp->iiNetmask,sptr,s_end)) == NULL)
goto error;
break;
case INET_IFOPT_MTU:
break;
case INET_IFOPT_FLAGS: {
int flags = ifp->iiFlags;
/* just enumerate the interfaces (no names) */
buf_check(sptr, s_end, 5);
*sptr++ = INET_IFOPT_FLAGS;
put_int32(IFGET_FLAGS(flags), sptr);
sptr += 4;
break;
}
default:
goto error;
}
}
return ctl_reply(INET_REP_OK, sbuf, sptr - sbuf, rbuf, rsize);
error:
return ctl_error(EINVAL, rbuf, rsize);
}
/* not supported */
static ErlDrvSSizeT inet_ctl_ifset(inet_descriptor* desc,
char* buf, ErlDrvSizeT len,
char** rbuf, ErlDrvSizeT rsize)
{
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
#elif defined(SIOCGIFCONF) && defined(SIOCSIFFLAGS)
/* cygwin has SIOCGIFCONF but not SIOCSIFFLAGS (Nov 2002) */
#define VOIDP(x) ((void*)(x))
#if defined(AF_LINK) && !defined(NO_SA_LEN)
#define SIZEA(p) (((p).sa_len > sizeof(p)) ? (p).sa_len : sizeof(p))
#else
#define SIZEA(p) (sizeof (p))
#endif
static int get_ifconf(SOCKET s, struct ifconf *ifcp) {
int ifc_len = 0;
int buflen = 100 * sizeof(struct ifreq);
char *buf = ALLOC(buflen);
for (;;) {
ifcp->ifc_len = buflen;
ifcp->ifc_buf = buf;
if (ioctl(s, SIOCGIFCONF, (char *)ifcp) < 0) {
int res = sock_errno();
if (res != EINVAL || ifc_len) {
FREE(buf);
return -1;
}
} else {
if (ifcp->ifc_len == ifc_len) break; /* buf large enough */
ifc_len = ifcp->ifc_len;
}
buflen += 10 * sizeof(struct ifreq);
buf = (char *)REALLOC(buf, buflen);
}
return 0;
}
static void free_ifconf(struct ifconf *ifcp) {
FREE(ifcp->ifc_buf);
}
static ErlDrvSSizeT inet_ctl_getiflist(inet_descriptor* desc,
char** rbuf, ErlDrvSizeT rsize)
{
struct ifconf ifc;
struct ifreq *ifrp;
char *sbuf, *sp;
ErlDrvSizeT i;
/* Courtesy of Per Bergqvist and W. Richard Stevens */
if (get_ifconf(desc->s, &ifc) < 0) {
return ctl_error(sock_errno(), rbuf, rsize);
}
sp = sbuf = ALLOC(ifc.ifc_len+1);
*sp++ = INET_REP_OK;
i = 0;
for (;;) {
ErlDrvSizeT n;
ifrp = (struct ifreq *) VOIDP(ifc.ifc_buf + i);
n = sizeof(ifrp->ifr_name) + SIZEA(ifrp->ifr_addr);
if (n < sizeof(*ifrp)) n = sizeof(*ifrp);
if (i+n > ifc.ifc_len) break;
i += n;
switch (ifrp->ifr_addr.sa_family) {
#if defined(HAVE_IN6) && defined(AF_INET6)
case AF_INET6:
#endif
case AF_INET:
ASSERT(sp+IFNAMSIZ+1 < sbuf+ifc.ifc_len+1);
strncpy(sp, ifrp->ifr_name, IFNAMSIZ);
sp[IFNAMSIZ] = '\0';
sp += strlen(sp), ++sp;
}
if (i >= ifc.ifc_len) break;
}
free_ifconf(&ifc);
*rbuf = sbuf;
return sp - sbuf;
}
#ifdef HAVE_LIBDLPI_H
#include <libdlpi.h>
static int hwaddr_libdlpi_lookup(const char *ifnm,
uchar_t *addr, size_t *alen)
{
dlpi_handle_t handle;
dlpi_info_t linkinfo;
int ret = -1;
if (dlpi_open(ifnm, &handle, 0) != DLPI_SUCCESS) {
return -1;
}
if (dlpi_get_physaddr(handle, DL_CURR_PHYS_ADDR,
addr, alen) == DLPI_SUCCESS &&
dlpi_info(handle, &linkinfo, 0) == DLPI_SUCCESS)
{
ret = 0;
}
dlpi_close(handle);
return ret;
}
#endif
#ifdef HAVE_GETIFADDRS
/* Returns 0 for success and errno() for failure */
static int call_getifaddrs(inet_descriptor* desc_p, struct ifaddrs **ifa_pp)
{
int result, save_errno;
#ifdef HAVE_SETNS
int current_ns;
current_ns = 0;
if (desc_p->netns != NULL) {
int new_ns;
/* Temporarily change network namespace for this thread
* over the getifaddrs() call
*/
current_ns = open("/proc/self/ns/net", O_RDONLY);
if (current_ns == INVALID_SOCKET) {
save_errno = sock_errno();
ASSERT(save_errno != 0);
return save_errno;
}
new_ns = open(desc_p->netns, O_RDONLY);
if (new_ns == INVALID_SOCKET) {
save_errno = sock_errno();
while (close(current_ns) == INVALID_SOCKET &&
sock_errno() == EINTR)
;
ASSERT(save_errno != 0);
return save_errno;
}
if (setns(new_ns, CLONE_NEWNET) != 0) {
save_errno = sock_errno();
while (close(new_ns) == INVALID_SOCKET &&
sock_errno() == EINTR)
;
while (close(current_ns) == INVALID_SOCKET &&
sock_errno() == EINTR)
;
ASSERT(save_errno != 0);
return save_errno;
}
else {
while (close(new_ns) == INVALID_SOCKET &&
sock_errno() == EINTR)
;
}
}
#endif
save_errno = 0;
result = getifaddrs(ifa_pp);
if (result < 0)
save_errno = sock_errno();
#ifdef HAVE_SETNS
if (desc_p->netns != NULL) {
/* Restore network namespace */
if (setns(current_ns, CLONE_NEWNET) != 0) {
/* XXX Failed to restore network namespace.
* What to do? Tidy up and return an error...
* Note that the thread now might still be in the set namespace.
* Can this even happen? Should the emulator be aborted?
*/
if (result >= 0) {
/* We got a result but have to waste it */
save_errno = sock_errno();
ASSERT(save_errno != 0);
freeifaddrs(*ifa_pp);
}
}
while (close(current_ns) == INVALID_SOCKET &&
sock_errno() == EINTR)
;
}
#endif
return save_errno;
}
#endif /* #ifdef HAVE_GETIFADDRS */
/* FIXME: temporary hack */
#ifndef IFHWADDRLEN
#define IFHWADDRLEN 6
#endif
static ErlDrvSSizeT inet_ctl_ifget(inet_descriptor* desc,
char* buf, ErlDrvSizeT len,
char** rbuf, ErlDrvSizeT rsize)
{
char sbuf[BUFSIZ];
char* sptr;
char* s_end = sbuf + BUFSIZ;
struct ifreq ifreq;
int namlen;
if ((len == 0) || ((namlen = get_int8(buf)) > len))
goto error;
sys_memset(ifreq.ifr_name, '\0', IFNAMSIZ);
sys_memcpy(ifreq.ifr_name, buf+1,
(namlen >= IFNAMSIZ) ? IFNAMSIZ-1 : namlen);
buf += (namlen+1);
len -= (namlen+1);
sptr = sbuf;
while (len--) {
switch(*buf++) {
case INET_IFOPT_ADDR:
if (ioctl(desc->s, SIOCGIFADDR, (char *)&ifreq) < 0)
break;
buf_check(sptr, s_end, 1);
*sptr++ = INET_IFOPT_ADDR;
if ((sptr = sockaddr_to_buf(&ifreq.ifr_addr, sptr, s_end)) == NULL)
goto error;
break;
case INET_IFOPT_HWADDR: {
#ifdef HAVE_LIBDLPI_H
/*
** OpenSolaris have SIGCGIFHWADDR, but no ifr_hwaddr member..
** The proper way to get the mac address would be to
** use libdlpi...
*/
uchar_t addr[DLPI_PHYSADDR_MAX];
size_t alen = sizeof(addr);
if (hwaddr_libdlpi_lookup(ifreq.ifr_name, addr, &alen) == 0) {
buf_check(sptr, s_end, 1+2+alen);
*sptr++ = INET_IFOPT_HWADDR;
put_int16(alen, sptr);
sptr += 2;
sys_memcpy(sptr, addr, alen);
sptr += alen;
}
#elif defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
if (ioctl(desc->s, SIOCGIFHWADDR, (char *)&ifreq) < 0)
break;
buf_check(sptr, s_end, 1+2+IFHWADDRLEN);
*sptr++ = INET_IFOPT_HWADDR;
put_int16(IFHWADDRLEN, sptr); sptr += 2;
/* raw memcpy (fix include autoconf later) */
sys_memcpy(sptr, (char*)(&ifreq.ifr_hwaddr.sa_data), IFHWADDRLEN);
sptr += IFHWADDRLEN;
#elif defined(SIOCGENADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ENADDR)
if (ioctl(desc->s, SIOCGENADDR, (char *)&ifreq) < 0)
break;
buf_check(sptr, s_end, 1+2+sizeof(ifreq.ifr_enaddr));
*sptr++ = INET_IFOPT_HWADDR;
put_int16(sizeof(ifreq.ifr_enaddr), sptr); sptr += 2;
/* raw memcpy (fix include autoconf later) */
sys_memcpy(sptr, (char*)(&ifreq.ifr_enaddr),
sizeof(ifreq.ifr_enaddr));
sptr += sizeof(ifreq.ifr_enaddr);
#elif defined(HAVE_GETIFADDRS) && defined(AF_LINK)
struct ifaddrs *ifa, *ifp;
struct sockaddr_dl *sdlp;
int found = 0;
if (call_getifaddrs(desc, &ifa) != 0)
goto error;
for (ifp = ifa; ifp; ifp = ifp->ifa_next) {
if ((ifp->ifa_addr->sa_family == AF_LINK) &&
(sys_strcmp(ifp->ifa_name, ifreq.ifr_name) == 0)) {
found = 1;
break;
}
}
if (found == 0) {
freeifaddrs(ifa);
break;
}
sdlp = (struct sockaddr_dl *)ifp->ifa_addr;
buf_check(sptr, s_end, 1+2+sdlp->sdl_alen);
*sptr++ = INET_IFOPT_HWADDR;
put_int16(sdlp->sdl_alen, sptr); sptr += 2;
sys_memcpy(sptr,
sdlp->sdl_data + sdlp->sdl_nlen,
sdlp->sdl_alen);
sptr += sdlp->sdl_alen;
freeifaddrs(ifa);
#endif
break;
}
case INET_IFOPT_BROADADDR:
#ifdef SIOCGIFBRDADDR
if (ioctl(desc->s, SIOCGIFBRDADDR, (char *)&ifreq) < 0)
break;
buf_check(sptr, s_end, 1);
*sptr++ = INET_IFOPT_BROADADDR;
if ((sptr=sockaddr_to_buf(&ifreq.ifr_broadaddr,sptr,s_end)) == NULL)
goto error;
#endif
break;
case INET_IFOPT_DSTADDR:
#ifdef SIOCGIFDSTADDR
if (ioctl(desc->s, SIOCGIFDSTADDR, (char *)&ifreq) < 0)
break;
buf_check(sptr, s_end, 1);
*sptr++ = INET_IFOPT_DSTADDR;
if ((sptr = sockaddr_to_buf(&ifreq.ifr_dstaddr,sptr,s_end)) == NULL)
goto error;
#endif
break;
case INET_IFOPT_NETMASK:
#if defined(SIOCGIFNETMASK)
if (ioctl(desc->s, SIOCGIFNETMASK, (char *)&ifreq) < 0)
break;
buf_check(sptr, s_end, 1);
*sptr++ = INET_IFOPT_NETMASK;
#if defined(ifr_netmask)
sptr = sockaddr_to_buf(&ifreq.ifr_netmask,sptr,s_end);
#else
/* SIOCGNETMASK exist but not macro ??? */
sptr = sockaddr_to_buf(&ifreq.ifr_addr,sptr,s_end);
#endif
if (sptr == NULL)
goto error;
#else
if (ioctl(desc->s, SIOCGIFADDR, (char *)&ifreq) < 0)
break;
else {
struct sockadd_in* ap;
/* emulate netmask,
* (wasted stuff since no one uses classes)
*/
buf_check(sptr, s_end, 1);
*sptr++ = INET_IFOPT_NETMASK;
ap = (struct sockaddr_in*) VOIDP(&ifreq.ifr_addr);
ap->sin_addr = net_mask(ap->sin_addr);
if ((sptr = sockaddr_to_buf(&ifreq.ifr_addr,sptr,s_end)) == NULL)
goto error;
}
#endif
break;
case INET_IFOPT_MTU: {
#if defined(SIOCGIFMTU) && defined(ifr_mtu)
int n;
if (ioctl(desc->s, SIOCGIFMTU, (char *)&ifreq) < 0)
break;
buf_check(sptr, s_end, 5);
*sptr++ = INET_IFOPT_MTU;
n = ifreq.ifr_mtu;
put_int32(n, sptr);
sptr += 4;
#endif
break;
}
case INET_IFOPT_FLAGS: {
int flags;
if (ioctl(desc->s, SIOCGIFFLAGS, (char*)&ifreq) < 0)
flags = 0;
else
flags = ifreq.ifr_flags;
buf_check(sptr, s_end, 5);
*sptr++ = INET_IFOPT_FLAGS;
put_int32(IFGET_FLAGS(flags), sptr);
sptr += 4;
break;
}
default:
goto error;
}
}
return ctl_reply(INET_REP_OK, sbuf, sptr - sbuf, rbuf, rsize);
error:
return ctl_error(EINVAL, rbuf, rsize);
}
static ErlDrvSSizeT inet_ctl_ifset(inet_descriptor* desc,
char* buf, ErlDrvSizeT len,
char** rbuf, ErlDrvSizeT rsize)
{
struct ifreq ifreq;
int namlen;
char* b_end = buf + len;
if ((len == 0) || ((namlen = get_int8(buf)) > len))
goto error;
sys_memset(ifreq.ifr_name, '\0', IFNAMSIZ);
sys_memcpy(ifreq.ifr_name, buf+1,
(namlen >= IFNAMSIZ) ? IFNAMSIZ-1 : namlen);
buf += (namlen+1);
len -= (namlen+1);
while(buf < b_end) {
switch(*buf++) {
case INET_IFOPT_ADDR:
if ((buf = buf_to_sockaddr(buf, b_end, &ifreq.ifr_addr)) == NULL)
goto error;
(void) ioctl(desc->s, SIOCSIFADDR, (char*)&ifreq);
break;
case INET_IFOPT_HWADDR: {
unsigned int hwalen;
buf_check(buf, b_end, 2);
hwalen = get_int16(buf); buf += 2;
buf_check(buf, b_end, hwalen);
#ifdef SIOCSIFHWADDR
/* raw memcpy (fix include autoconf later) */
sys_memset((char*)(&ifreq.ifr_hwaddr.sa_data),
'\0', sizeof(ifreq.ifr_hwaddr.sa_data));
sys_memcpy((char*)(&ifreq.ifr_hwaddr.sa_data), buf, hwalen);
(void) ioctl(desc->s, SIOCSIFHWADDR, (char *)&ifreq);
#endif
buf += hwalen;
break;
}
case INET_IFOPT_BROADADDR:
#ifdef SIOCSIFBRDADDR
if ((buf = buf_to_sockaddr(buf, b_end, &ifreq.ifr_broadaddr)) == NULL)
goto error;
(void) ioctl(desc->s, SIOCSIFBRDADDR, (char *)&ifreq);
#endif
break;
case INET_IFOPT_DSTADDR:
#ifdef SIOCSIFDSTADDR
if ((buf = buf_to_sockaddr(buf, b_end, &ifreq.ifr_dstaddr)) == NULL)
goto error;
(void) ioctl(desc->s, SIOCSIFDSTADDR, (char *)&ifreq);
#endif
break;
case INET_IFOPT_NETMASK:
#ifdef SIOCSIFNETMASK
#if defined(ifr_netmask)
buf = buf_to_sockaddr(buf,b_end, &ifreq.ifr_netmask);
#else
buf = buf_to_sockaddr(buf,b_end, &ifreq.ifr_addr);
#endif
if (buf == NULL)
goto error;
(void) ioctl(desc->s, SIOCSIFNETMASK, (char *)&ifreq);
#endif
break;
case INET_IFOPT_MTU:
buf_check(buf, b_end, 4);
#if defined(SIOCSIFMTU) && defined(ifr_mtu)
ifreq.ifr_mtu = get_int32(buf);
(void) ioctl(desc->s, SIOCSIFMTU, (char *)&ifreq);
#endif
buf += 4;
break;
case INET_IFOPT_FLAGS: {
int flags0;
int flags;
int eflags;
buf_check(buf, b_end, 4);
eflags = get_int32(buf);
/* read current flags */
if (ioctl(desc->s, SIOCGIFFLAGS, (char*)&ifreq) < 0)
flags0 = flags = 0;
else
flags0 = flags = ifreq.ifr_flags;
/* update flags */
if (eflags & INET_IFF_UP) flags |= IFF_UP;
if (eflags & INET_IFF_DOWN) flags &= ~IFF_UP;
if (eflags & INET_IFF_BROADCAST) flags |= IFF_BROADCAST;
if (eflags & INET_IFF_NBROADCAST) flags &= ~IFF_BROADCAST;
if (eflags & INET_IFF_POINTTOPOINT) flags |= IFF_POINTOPOINT;
if (eflags & INET_IFF_NPOINTTOPOINT) flags &= ~IFF_POINTOPOINT;
if (flags != flags0) {
ifreq.ifr_flags = flags;
(void) ioctl(desc->s, SIOCSIFFLAGS, (char*)&ifreq);
}
buf += 4;
break;
}
default:
goto error;
}
}
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
error:
return ctl_error(EINVAL, rbuf, rsize);
}
#else
static ErlDrvSSizeT inet_ctl_getiflist(inet_descriptor* desc,
char** rbuf, ErlDrvSizeT rsize)
{
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
static ErlDrvSSizeT inet_ctl_ifget(inet_descriptor* desc,
char* buf, ErlDrvSizeT len,
char** rbuf, ErlDrvSizeT rsize)
{
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
static ErlDrvSSizeT inet_ctl_ifset(inet_descriptor* desc,
char* buf, ErlDrvSizeT len,
char** rbuf, ErlDrvSizeT rsize)
{
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
#endif
#if defined(__WIN32__) || defined(HAVE_GETIFADDRS)
/* Latin-1 to utf8 */
static int utf8_len(const char *c, int m) {
int l;
for (l = 0; m; c++, l++, m--) {
if (*c == '\0') break;
if ((*c & 0x7f) != *c) l++;
}
return l;
}
static void utf8_encode(const char *c, int m, char *p) {
for (; m; c++, m--) {
if (*c == '\0') break;
if ((*c & 0x7f) != *c) {
*p++ = (char) (0xC0 | (0x03 & (*c >> 6)));
*p++ = (char) (0x80 | (0x3F & *c));
} else {
*p++ = (char) *c;
}
}
}
#endif
#if defined(__WIN32__)
static void set_netmask_bytes(char *c, int len, int pref_len) {
int i, m;
for (i = 0, m = pref_len >> 3; i < m && i < len; i++) c[i] = '\xFF';
if (i < len) c[i++] = 0xFF << (8 - (pref_len & 7));
for (; i < len; i++) c[i] = '\0';
}
int eq_masked_bytes(char *a, char *b, int pref_len) {
int i, m;
for (i = 0, m = pref_len >> 3; i < m; i++) {
if (a[i] != b[i]) return 0;
}
m = pref_len & 7;
if (m) {
m = 0xFF & (0xFF << (8 - m));
if ((a[i] & m) != (b[i] & m)) return 0;
}
return !0;
}
static ErlDrvSSizeT inet_ctl_getifaddrs(inet_descriptor* desc_p,
char **rbuf_pp, ErlDrvSizeT rsize)
{
int i;
DWORD ret, n;
IP_INTERFACE_INFO *info_p = NULL;
MIB_IPADDRTABLE *ip_addrs_p = NULL;
IP_ADAPTER_ADDRESSES *ip_adaddrs_p = NULL;
IP_ADAPTER_ADDRESSES *ia_p = NULL;
char *buf_p;
char *buf_alloc_p;
ErlDrvSizeT buf_size = 512;
# define BUF_ENSURE(Size) \
do { \
int NEED_, GOT_ = buf_p - buf_alloc_p; \
NEED_ = GOT_ + (Size); \
if (NEED_ > buf_size) { \
buf_size = NEED_ + 512; \
buf_alloc_p = REALLOC(buf_alloc_p, buf_size); \
buf_p = buf_alloc_p + GOT_; \
} \
} while(0)
# define SOCKADDR_TO_BUF(opt, sa) \
do { \
if (sa) { \
char *P_; \
*buf_p++ = (opt); \
while (! (P_ = sockaddr_to_buf((sa), buf_p, \
buf_alloc_p+buf_size))) { \
int GOT_ = buf_p - buf_alloc_p; \
buf_size += 512; \
buf_alloc_p = REALLOC(buf_alloc_p, buf_size); \
buf_p = buf_alloc_p + GOT_; \
} \
if (P_ == buf_p) { \
buf_p--; \
} else { \
buf_p = P_; \
} \
} \
} while (0)
{
/* Try GetAdaptersAddresses, if it is available */
unsigned long ip_adaddrs_size = 16 * 1024;
ULONG family = AF_UNSPEC;
ULONG flags =
GAA_FLAG_INCLUDE_PREFIX | GAA_FLAG_SKIP_ANYCAST |
GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME |
GAA_FLAG_SKIP_MULTICAST;
ULONG (WINAPI *fpGetAdaptersAddresses)
(ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
HMODULE iphlpapi = GetModuleHandle("iphlpapi");
fpGetAdaptersAddresses = (void *)
(iphlpapi ?
GetProcAddress(iphlpapi, "GetAdaptersAddresses") :
NULL);
if (fpGetAdaptersAddresses) {
ip_adaddrs_p = ALLOC(ip_adaddrs_size);
for (i = 17; i; i--) {
ret = fpGetAdaptersAddresses(
family, flags, NULL, ip_adaddrs_p, &ip_adaddrs_size);
ip_adaddrs_p = REALLOC(ip_adaddrs_p, ip_adaddrs_size);
if (ret == NO_ERROR) break;
if (ret == ERROR_BUFFER_OVERFLOW) continue;
i = 0;
break;
}
if (! i) {
FREE(ip_adaddrs_p);
ip_adaddrs_p = NULL;
}
} else ip_adaddrs_p = NULL;
}
{
/* Load the IP_INTERFACE_INFO table (only IPv4 interfaces),
* reliable source of interface names on XP
*/
unsigned long info_size = 4 * 1024;
info_p = ALLOC(info_size);
for (i = 17; i; i--) {
ret = GetInterfaceInfo(info_p, &info_size);
info_p = REALLOC(info_p, info_size);
if (ret == NO_ERROR) break;
if (ret == ERROR_INSUFFICIENT_BUFFER) continue;
i = 0;
break;
}
if (! i) {
FREE(info_p);
info_p = NULL;
}
}
if (! ip_adaddrs_p) {
/* If GetAdaptersAddresses gave nothing we fall back to
* MIB_IPADDRTABLE (only IPv4 interfaces)
*/
unsigned long ip_addrs_size = 16 * sizeof(*ip_addrs_p);
ip_addrs_p = ALLOC(ip_addrs_size);
for (i = 17; i; i--) {
ret = GetIpAddrTable(ip_addrs_p, &ip_addrs_size, FALSE);
ip_addrs_p = REALLOC(ip_addrs_p, ip_addrs_size);
if (ret == NO_ERROR) break;
if (ret == ERROR_INSUFFICIENT_BUFFER) continue;
i = 0;
break;
}
if (! i) {
if (info_p) FREE(info_p);
FREE(ip_addrs_p);
return ctl_reply(INET_REP_OK, NULL, 0, rbuf_pp, rsize);
}
} else ip_addrs_p = NULL;
buf_p = buf_alloc_p = ALLOC(buf_size);
*buf_p++ = INET_REP_OK;
/* Iterate over MIB_IPADDRTABLE or IP_ADAPTER_ADDRESSES */
ia_p = NULL;
for (ip_addrs_p ? (void)(i = 0) : (void)(ia_p = ip_adaddrs_p);
ip_addrs_p ? (i < ip_addrs_p->dwNumEntries) : (ia_p != NULL);
ip_addrs_p ? (void)(i++) : (void)(ia_p = ia_p->Next)) {
MIB_IPADDRROW *ipaddrrow_p = NULL;
DWORD flags = INET_IFF_MULTICAST;
DWORD index = 0;
WCHAR *wname_p = NULL;
MIB_IFROW ifrow;
if (ip_addrs_p) {
ipaddrrow_p = ip_addrs_p->table + i;
index = ipaddrrow_p->dwIndex;
} else {
index = ia_p->IfIndex;
if (ia_p->Flags & IP_ADAPTER_NO_MULTICAST) {
flags &= ~INET_IFF_MULTICAST;
}
}
index:
if (! index) goto done;
sys_memzero(&ifrow, sizeof(ifrow));
ifrow.dwIndex = index;
if (GetIfEntry(&ifrow) != NO_ERROR) break;
/* Find the interface name - first try MIB_IFROW.wzname */
if (ifrow.wszName[0] != 0) {
wname_p = ifrow.wszName;
} else {
/* Then try IP_ADAPTER_INDEX_MAP.Name (only IPv4 adapters) */
int j;
if (info_p) {
for (j = 0; j < info_p->NumAdapters; j++) {
if (info_p->Adapter[j].Index == (ULONG) ifrow.dwIndex) {
if (info_p->Adapter[j].Name[0] != 0) {
wname_p = info_p->Adapter[j].Name;
}
break;
}
}
}
}
if (wname_p) {
int len;
/* Convert interface name to UTF-8 */
len =
WideCharToMultiByte(
CP_UTF8, 0, wname_p, -1, NULL, 0, NULL, NULL);
if (! len) break;
BUF_ENSURE(len);
WideCharToMultiByte(
CP_UTF8, 0, wname_p, -1, buf_p, len, NULL, NULL);
buf_p += len;
} else {
/* Found no name -
* use "MIB_IFROW.dwIndex: MIB_IFROW.bDescr" as name instead */
int l;
l = utf8_len(ifrow.bDescr, ifrow.dwDescrLen);
BUF_ENSURE(9 + l+1);
buf_p +=
erts_sprintf(
buf_p, "%lu: ", (unsigned long) ifrow.dwIndex);
utf8_encode(ifrow.bDescr, ifrow.dwDescrLen, buf_p);
buf_p += l;
*buf_p++ = '\0';
}
/* Interface flags, often make up broadcast and multicast flags */
switch (ifrow.dwType) {
case IF_TYPE_ETHERNET_CSMACD:
flags |= INET_IFF_BROADCAST;
break;
case IF_TYPE_SOFTWARE_LOOPBACK:
flags |= INET_IFF_LOOPBACK;
flags &= ~INET_IFF_MULTICAST;
break;
default:
flags &= ~INET_IFF_MULTICAST;
break;
}
if (ifrow.dwAdminStatus) {
flags |= INET_IFF_UP;
switch (ifrow.dwOperStatus) {
case IF_OPER_STATUS_CONNECTING:
flags |= INET_IFF_POINTTOPOINT;
break;
case IF_OPER_STATUS_CONNECTED:
flags |= INET_IFF_RUNNING | INET_IFF_POINTTOPOINT;
break;
case IF_OPER_STATUS_OPERATIONAL:
flags |= INET_IFF_RUNNING;
break;
}
}
BUF_ENSURE(1 + 4);
*buf_p++ = INET_IFOPT_FLAGS;
put_int32(flags, buf_p); buf_p += 4;
if (ipaddrrow_p) {
/* Legacy implementation through GetIpAddrTable */
struct sockaddr_in sin;
/* IP Address */
sys_memzero(&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = ipaddrrow_p->dwAddr;
BUF_ENSURE(1);
/* Netmask */
SOCKADDR_TO_BUF(INET_IFOPT_ADDR, (struct sockaddr *) &sin);
sin.sin_addr.s_addr = ipaddrrow_p->dwMask;
BUF_ENSURE(1);
SOCKADDR_TO_BUF(INET_IFOPT_NETMASK, (struct sockaddr *) &sin);
if (flags & INET_IFF_BROADCAST) {
/* Broadcast address - fake it*/
sin.sin_addr.s_addr = ipaddrrow_p->dwAddr;
sin.sin_addr.s_addr |= ~ipaddrrow_p->dwMask;
BUF_ENSURE(1);
SOCKADDR_TO_BUF(
INET_IFOPT_BROADADDR, (struct sockaddr *) &sin);
}
} else {
IP_ADAPTER_UNICAST_ADDRESS *p;
/* IP Address(es) */
for (p = ia_p->FirstUnicastAddress;
p;
p = p->Next)
{
IP_ADAPTER_PREFIX *q;
ULONG shortest_length;
struct sockaddr *shortest_p, *sa_p = p->Address.lpSockaddr;
BUF_ENSURE(1);
SOCKADDR_TO_BUF(INET_IFOPT_ADDR, sa_p);
shortest_p = NULL;
shortest_length = 0;
for (q = ia_p->FirstPrefix;
q;
q = q->Next) {
struct sockaddr *sp_p = q->Address.lpSockaddr;
if (sa_p->sa_family != sp_p->sa_family) continue;
switch (sa_p->sa_family) {
case AF_INET: {
struct sockaddr_in sin;
DWORD sa, sp, mask;
sa = ntohl((DWORD)
((struct sockaddr_in *)
sa_p)->sin_addr.s_addr);
sp = ntohl((DWORD)
((struct sockaddr_in *)
sp_p)->sin_addr.s_addr);
mask = 0xFFFFFFFF << (32 - q->PrefixLength);
if ((sa & mask) != (sp & mask)) continue;
if ((! shortest_p)
|| q->PrefixLength < shortest_length) {
shortest_p = sp_p;
shortest_length = q->PrefixLength;
}
} break;
case AF_INET6: {
struct sockaddr_in6 sin6;
if (!eq_masked_bytes((char *)
&((struct sockaddr_in6 *)
sa_p)->sin6_addr,
(char *)
&((struct sockaddr_in6 *)
sp_p)->sin6_addr,
q->PrefixLength)) {
continue;
}
if ((! shortest_p)
|| q->PrefixLength < shortest_length) {
shortest_p = sp_p;
shortest_length = q->PrefixLength;
}
} break;
}
}
if (! shortest_p) {
/* Found no shortest prefix */
shortest_p = sa_p;
switch (shortest_p->sa_family) {
case AF_INET: {
/* Fall back to old classfull network addresses */
DWORD addr = ntohl(((struct sockaddr_in *)shortest_p)
->sin_addr.s_addr);
if (! (addr & 0x800000)) {
/* Class A */
shortest_length = 8;
} else if (! (addr & 0x400000)) {
/* Class B */
shortest_length = 16;
} else if (! (addr & 0x200000)) {
/* Class C */
shortest_length = 24;
} else {
shortest_length = 32;
}
} break;
case AF_INET6: {
/* Just play it safe */
shortest_length = 128;
} break;
}
}
switch (shortest_p->sa_family) {
case AF_INET: {
struct sockaddr_in sin;
DWORD mask = 0xFFFFFFFF << (32 - shortest_length);
sys_memzero(&sin, sizeof(sin));
sin.sin_family = shortest_p->sa_family;
sin.sin_addr.s_addr = htonl(mask);
BUF_ENSURE(1);
SOCKADDR_TO_BUF(INET_IFOPT_NETMASK,
(struct sockaddr *) &sin);
if (flags & INET_IFF_BROADCAST) {
DWORD sp =
ntohl((DWORD)
((struct sockaddr_in *)shortest_p)
-> sin_addr.s_addr);
sin.sin_addr.s_addr = htonl(sp | ~mask);
BUF_ENSURE(1);
SOCKADDR_TO_BUF(INET_IFOPT_BROADADDR,
(struct sockaddr *) &sin);
}
} break;
case AF_INET6: {
struct sockaddr_in6 sin6;
sys_memzero(&sin6, sizeof(sin6));
sin6.sin6_family = shortest_p->sa_family;
set_netmask_bytes((char *) &sin6.sin6_addr,
16,
shortest_length);
BUF_ENSURE(1);
SOCKADDR_TO_BUF(INET_IFOPT_NETMASK,
(struct sockaddr *) &sin6);
} break;
}
}
}
if (ifrow.dwPhysAddrLen) {
/* Hardware Address */
BUF_ENSURE(1 + 2 + ifrow.dwPhysAddrLen);
*buf_p++ = INET_IFOPT_HWADDR;
put_int16(ifrow.dwPhysAddrLen, buf_p); buf_p += 2;
sys_memcpy(buf_p, ifrow.bPhysAddr, ifrow.dwPhysAddrLen);
buf_p += ifrow.dwPhysAddrLen;
}
done:
/* That is all for this interface */
BUF_ENSURE(1);
*buf_p++ = '\0';
if (ia_p &&
ia_p->Ipv6IfIndex &&
ia_p->Ipv6IfIndex != index)
{
/* Oops, there was another interface for IPv6. Possible? XXX */
index = ia_p->Ipv6IfIndex;
goto index;
}
}
if (ip_adaddrs_p) FREE(ip_adaddrs_p);
if (info_p) FREE(info_p);
if (ip_addrs_p) FREE(ip_addrs_p);
buf_size = buf_p - buf_alloc_p;
buf_alloc_p = REALLOC(buf_alloc_p, buf_size);
/* buf_p is now unreliable */
*rbuf_pp = buf_alloc_p;
return buf_size;
# undef BUF_ENSURE
}
#elif defined(HAVE_GETIFADDRS)
#ifdef DEBUG
#define GETIFADDRS_BUFSZ (1)
#else
#define GETIFADDRS_BUFSZ (512)
#endif
static ErlDrvSSizeT inet_ctl_getifaddrs(inet_descriptor* desc_p,
char **rbuf_pp, ErlDrvSizeT rsize)
{
struct ifaddrs *ifa_p, *ifa_free_p;
ErlDrvSizeT buf_size;
char *buf_p;
char *buf_alloc_p;
int save_errno;
buf_size = GETIFADDRS_BUFSZ;
buf_alloc_p = ALLOC(GETIFADDRS_BUFSZ);
buf_p = buf_alloc_p;
# define BUF_ENSURE(Size) \
do { \
int NEED_, GOT_ = buf_p - buf_alloc_p; \
NEED_ = GOT_ + (Size); \
if (NEED_ > buf_size) { \
buf_size = NEED_ + GETIFADDRS_BUFSZ; \
buf_alloc_p = REALLOC(buf_alloc_p, buf_size); \
buf_p = buf_alloc_p + GOT_; \
} \
} while (0)
# define SOCKADDR_TO_BUF(opt, sa) \
do { \
if (sa) { \
char *P_; \
*buf_p++ = (opt); \
while (! (P_ = sockaddr_to_buf((sa), buf_p, \
buf_alloc_p+buf_size))) { \
int GOT_ = buf_p - buf_alloc_p; \
buf_size += GETIFADDRS_BUFSZ; \
buf_alloc_p = REALLOC(buf_alloc_p, buf_size); \
buf_p = buf_alloc_p + GOT_; \
} \
if (P_ == buf_p) { \
buf_p--; \
} else { \
buf_p = P_; \
} \
} \
} while (0)
if ((save_errno = call_getifaddrs(desc_p, &ifa_p)) != 0)
return ctl_error(save_errno, rbuf_pp, rsize);
ifa_free_p = ifa_p;
*buf_p++ = INET_REP_OK;
for (; ifa_p; ifa_p = ifa_p->ifa_next) {
int len = utf8_len(ifa_p->ifa_name, -1);
BUF_ENSURE(len+1 + 1+4 + 1);
utf8_encode(ifa_p->ifa_name, -1, buf_p);
buf_p += len;
*buf_p++ = '\0';
*buf_p++ = INET_IFOPT_FLAGS;
put_int32(IFGET_FLAGS(ifa_p->ifa_flags), buf_p); buf_p += 4;
if (ifa_p->ifa_addr) {
if (ifa_p->ifa_addr->sa_family == AF_INET
#if defined(AF_INET6)
|| ifa_p->ifa_addr->sa_family == AF_INET6
#endif
) {
SOCKADDR_TO_BUF(INET_IFOPT_ADDR, ifa_p->ifa_addr);
if (ifa_p->ifa_netmask) {
BUF_ENSURE(1);
SOCKADDR_TO_BUF(INET_IFOPT_NETMASK, ifa_p->ifa_netmask);
}
if (ifa_p->ifa_dstaddr &&
(ifa_p->ifa_flags & IFF_POINTOPOINT)) {
BUF_ENSURE(1);
SOCKADDR_TO_BUF(INET_IFOPT_DSTADDR, ifa_p->ifa_dstaddr);
} else if (ifa_p->ifa_broadaddr &&
(ifa_p->ifa_flags & IFF_BROADCAST)) {
BUF_ENSURE(1);
SOCKADDR_TO_BUF(INET_IFOPT_BROADADDR, ifa_p->ifa_broadaddr);
}
}
#if defined(AF_LINK) || defined(AF_PACKET)
else if (
#if defined(AF_LINK)
ifa_p->ifa_addr->sa_family == AF_LINK
#else
0
#endif
#if defined(AF_PACKET)
|| ifa_p->ifa_addr->sa_family == AF_PACKET
#endif
) {
size_t need = sockaddr_bufsz_need(ifa_p->ifa_addr);
if (need > 3) {
BUF_ENSURE(1 + need);
SOCKADDR_TO_BUF(INET_IFOPT_HWADDR, ifa_p->ifa_addr);
}
}
#endif
}
BUF_ENSURE(1);
*buf_p++ = '\0';
}
buf_size = buf_p - buf_alloc_p;
buf_alloc_p = REALLOC(buf_alloc_p, buf_size);
/* buf_p is now unreliable */
freeifaddrs(ifa_free_p);
*rbuf_pp = buf_alloc_p;
return buf_size;
# undef BUF_ENSURE
}
#undef GETIFADDRS_BUFSZ
#else
static ErlDrvSSizeT inet_ctl_getifaddrs(inet_descriptor* desc_p,
char **rbuf_pp, ErlDrvSizeT rsize)
{
return ctl_error(ENOTSUP, rbuf_pp, rsize);
}
#endif
/* Per H @ Tail-f: The original code here had problems that possibly
only occur if you abuse it for non-INET sockets, but anyway:
a) If the getsockopt for SO_PRIORITY or IP_TOS failed, the actual
requested setsockopt was never even attempted.
b) If {get,set}sockopt for one of IP_TOS and SO_PRIORITY failed,
but ditto for the other worked and that was actually the requested
option, failure was still reported to erlang. */
#if defined(IP_TOS) && defined(IPPROTO_IP) \
&& defined(SO_PRIORITY) && !defined(__WIN32__)
static int setopt_prio_tos_trick
(int fd, int proto, int type, char* arg_ptr, int arg_sz, int propagate)
{
/* The relations between SO_PRIORITY, TOS and other options
is not what you (or at least I) would expect...:
If TOS is set after priority, priority is zeroed.
If any other option is set after tos, tos might be zeroed.
Therefore, save tos and priority. If something else is set,
restore both after setting, if tos is set, restore only
prio and if prio is set restore none... All to keep the
user feeling socket options are independent. /PaN */
int tmp_ival_prio;
int tmp_ival_tos;
int res;
int res_prio;
int res_tos;
SOCKLEN_T tmp_arg_sz_prio = sizeof(tmp_ival_prio);
SOCKLEN_T tmp_arg_sz_tos = sizeof(tmp_ival_tos);
res_prio = sock_getopt(fd, SOL_SOCKET, SO_PRIORITY,
(char *) &tmp_ival_prio, &tmp_arg_sz_prio);
res_tos = sock_getopt(fd, IPPROTO_IP, IP_TOS,
(char *) &tmp_ival_tos, &tmp_arg_sz_tos);
res = sock_setopt(fd, proto, type, arg_ptr, arg_sz);
if (res == 0) {
if (type != SO_PRIORITY) {
if (type != IP_TOS && res_tos == 0) {
res_tos = sock_setopt(fd,
IPPROTO_IP,
IP_TOS,
(char *) &tmp_ival_tos,
tmp_arg_sz_tos);
if (propagate)
res = res_tos;
}
if (res == 0 && res_prio == 0) {
res_prio = sock_setopt(fd,
SOL_SOCKET,
SO_PRIORITY,
(char *) &tmp_ival_prio,
tmp_arg_sz_prio);
if (propagate) {
/* Some kernels set a SO_PRIORITY by default that you are not permitted to reset,
silently ignore this error condition */
if (res_prio != 0 && sock_errno() == EPERM) {
res = 0;
} else {
res = res_prio;
}
}
}
}
}
return (res);
}
#endif
static
int inet_setopt(int fd,
int proto, int type,
char* arg_ptr, int arg_sz,
int propagate)
{
int res;
#if defined(IP_TOS) && defined(IPPROTO_IP) \
&& defined(SO_PRIORITY) && !defined(__WIN32__)
DEBUGF(("inet_setopt -> try trick setopt with"
"\r\n fd: %d"
"\r\n proto: %d"
"\r\n type: %d"
"\r\n sz: %d"
"\r\n propagate: %d"
"\r\n", fd, proto, type, arg_sz, propagate));
res = setopt_prio_tos_trick (fd, proto, type, arg_ptr, arg_sz, propagate);
#else
DEBUGF(("inet_setopt -> try std setopt with"
"\r\n fd: %d"
"\r\n proto: %d"
"\r\n type: %d"
"\r\n sz: %d"
"\r\n", fd, proto, type, arg_sz));
res = sock_setopt (fd, proto, type, arg_ptr, arg_sz);
#endif
return res;
}
/* set socket options:
** return -1 on error
** 0 if ok
** 1 if ok force deliver of queued data
*/
#ifdef HAVE_SCTP
static int sctp_set_opts(inet_descriptor* desc, char* ptr, int len);
#endif
static int inet_set_opts(inet_descriptor* desc, char* ptr, int len)
{
int type;
int proto;
int opt;
struct linger li_val;
#if defined(HAVE_MULTICAST_SUPPORT)
#if defined(IPPROTO_IP)
#if defined(HAVE_STRUCT_IP_MREQN)
struct ip_mreqn mreq4;
#else
struct ip_mreq mreq4;
#endif
#endif
#if defined(HAVE_IN6) && defined(AF_INET6) && defined(IPPROTO_IPV6)
struct ipv6_mreq mreq6;
#endif
unsigned int mreqSz = 0;
#endif
int ival;
char* arg_ptr;
int arg_sz;
#ifdef SO_BINDTODEVICE
char ifname[IFNAMSIZ];
#endif
enum PacketParseType old_htype = desc->htype;
int old_active = desc->active;
int propagate; /* Set to 1 if failure to set this option
should be propagated to erlang (not all
errors can be propagated for BC reasons) */
int res;
#ifdef HAVE_SCTP
/* SCTP sockets are treated completely separately: */
if (IS_SCTP(desc))
return sctp_set_opts(desc, ptr, len);
#endif
while(len >= 5) {
int recv_cmsgflags;
opt = *ptr++;
ival = get_int32(ptr);
ptr += 4;
len -= 5;
arg_ptr = (char*) &ival;
arg_sz = sizeof(ival);
proto = SOL_SOCKET;
propagate = 0;
recv_cmsgflags = desc->recv_cmsgflags;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts -> opt: %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), opt) );
switch(opt) {
case INET_LOPT_HEADER:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(header) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
desc->hsz = ival;
continue;
case INET_LOPT_MODE:
/* List or Binary: */
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(mode) -> %s (%d)\r\n",
__LINE__, desc->s, driver_caller(desc->port),
M2S(ival), ival) );
desc->mode = ival;
continue;
case INET_LOPT_DELIVER:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(deliver) -> %s (%d)\r\n",
__LINE__, desc->s, driver_caller(desc->port),
D2S(ival), ival) );
desc->deliver = ival;
continue;
case INET_LOPT_BUFFER:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(buffer) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
if (ival < INET_MIN_BUFFER) ival = INET_MIN_BUFFER;
desc->bufsz = ival;
desc->flags |= INET_FLG_BUFFER_SET;
continue;
case INET_LOPT_ACTIVE:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(active) -> active (ival): %s (%d)\r\n",
__LINE__, desc->s, driver_caller(desc->port),
A2S(ival), ival) );
desc->active = ival;
if (desc->active == INET_MULTI) {
long ac = desc->active_count;
Sint16 nval = get_int16(ptr);
ptr += 2;
len -= 2;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(active) -> nval: %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), nval) );
ac += nval;
if (ac > INT16_MAX || ac < INT16_MIN)
return -1;
desc->active_count += nval;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(active) -> count => %d\r\n",
__LINE__, desc->s, driver_caller(desc->port),
desc->active_count) );
if (desc->active_count < 0)
desc->active_count = 0;
if (desc->active_count == 0) {
desc->active = INET_PASSIVE;
packet_passive_message(desc);
}
} else
desc->active_count = 0;
if ((desc->stype == SOCK_STREAM) && (desc->active != INET_PASSIVE) &&
(desc->state == INET_STATE_CLOSED)) {
tcp_descriptor *tdesc = (tcp_descriptor *) desc;
if (tdesc->tcp_add_flags & TCP_ADDF_DELAYED_ECONNRESET) {
tdesc->tcp_add_flags &= ~TCP_ADDF_DELAYED_ECONNRESET;
tcp_error_message(tdesc, ECONNRESET);
}
tcp_closed_message(tdesc);
if (desc->exitf) {
driver_exit(desc->port, 0);
return 0; /* Give up on this socket, descriptor lost */
} else {
desc_close_read(desc);
}
}
continue;
case INET_LOPT_PACKET:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(packet) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
desc->htype = ival;
continue;
case INET_LOPT_PACKET_SIZE:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(packet-size) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
desc->psize = (unsigned int)ival;
continue;
case INET_LOPT_EXITONCLOSE:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(exit-on-close) -> %d (%s)\r\n",
__LINE__,
desc->s, driver_caller(desc->port), ival, B2S(ival)) );
desc->exitf = ival;
continue;
case INET_LOPT_TCP_HIWTRMRK:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(hiwtrmrk) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
if (desc->stype == SOCK_STREAM) {
tcp_descriptor* tdesc = (tcp_descriptor*) desc;
if (ival < 0) ival = 0;
if (tdesc->low > ival)
tdesc->low = ival;
tdesc->high = ival;
}
continue;
case INET_LOPT_TCP_LOWTRMRK:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(lowtrmrk) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
if (desc->stype == SOCK_STREAM) {
tcp_descriptor* tdesc = (tcp_descriptor*) desc;
if (ival < 0) ival = 0;
if (tdesc->high < ival)
tdesc->high = ival;
tdesc->low = ival;
}
continue;
case INET_LOPT_MSGQ_HIWTRMRK: {
ErlDrvSizeT high;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(msgq-hiwtrmrk) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
if (ival < ERL_DRV_BUSY_MSGQ_LIM_MIN
|| ERL_DRV_BUSY_MSGQ_LIM_MAX < ival)
return -1;
high = (ErlDrvSizeT) ival;
erl_drv_busy_msgq_limits(desc->port, NULL, &high);
continue;
}
case INET_LOPT_MSGQ_LOWTRMRK: {
ErlDrvSizeT low;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(msgq-lowtrmrk) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
if (ival < ERL_DRV_BUSY_MSGQ_LIM_MIN
|| ERL_DRV_BUSY_MSGQ_LIM_MAX < ival)
return -1;
low = (ErlDrvSizeT) ival;
erl_drv_busy_msgq_limits(desc->port, &low, NULL);
continue;
}
case INET_LOPT_TCP_SEND_TIMEOUT:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(send-timeout) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
if (desc->stype == SOCK_STREAM) {
tcp_descriptor* tdesc = (tcp_descriptor*) desc;
tdesc->send_timeout = ival;
}
continue;
case INET_LOPT_TCP_SEND_TIMEOUT_CLOSE:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(send-timeout-close) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
if (desc->stype == SOCK_STREAM) {
tcp_descriptor* tdesc = (tcp_descriptor*) desc;
tdesc->send_timeout_close = ival;
}
continue;
case INET_LOPT_TCP_DELAY_SEND:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(delay-send) -> %d (%s)\r\n",
__LINE__,
desc->s, driver_caller(desc->port), ival, B2S(ival)) );
if (desc->stype == SOCK_STREAM) {
tcp_descriptor* tdesc = (tcp_descriptor*) desc;
if (ival)
tdesc->tcp_add_flags |= TCP_ADDF_DELAY_SEND;
else
tdesc->tcp_add_flags &= ~TCP_ADDF_DELAY_SEND;
}
continue;
#ifdef HAVE_UDP
case INET_LOPT_UDP_READ_PACKETS:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(read-packets) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
if (desc->stype == SOCK_DGRAM) {
udp_descriptor* udesc = (udp_descriptor*) desc;
if (ival <= 0) return -1;
udesc->read_packets = ival;
}
continue;
#endif
#ifdef HAVE_SETNS
case INET_LOPT_NETNS:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(netns) -> %d, %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival, len) );
/* It is annoying that ival and len are both (signed) int */
if (ival < 0) return -1;
if (len < ival) return -1;
if (desc->netns != NULL) FREE(desc->netns);
desc->netns = ALLOC(((unsigned int) ival) + 1);
memcpy(desc->netns, ptr, ival);
desc->netns[ival] = '\0';
ptr += ival;
len -= ival;
continue;
#endif
case INET_LOPT_TCP_SHOW_ECONNRESET:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(show-econnreset) -> %d (%s)\r\n",
__LINE__,
desc->s, driver_caller(desc->port), ival, B2S(ival)) );
if (desc->sprotocol == IPPROTO_TCP) {
tcp_descriptor* tdesc = (tcp_descriptor*) desc;
if (ival)
tdesc->tcp_add_flags |= TCP_ADDF_SHOW_ECONNRESET;
else
tdesc->tcp_add_flags &= ~TCP_ADDF_SHOW_ECONNRESET;
}
continue;
case INET_LOPT_LINE_DELIM:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(line-delimiter) -> %c (%d)\r\n",
__LINE__,
desc->s, driver_caller(desc->port), (char) ival, ival) );
desc->delimiter = (char)ival;
continue;
case INET_OPT_REUSEADDR:
#ifdef __WIN32__
/* The behaviour changed in Windows Server 2003.
* Now it works as the combo of `SO_REUSEADDR` and
* `SO_REUSEPORT` does on *BSD.
*/
if (desc->stype != SOCK_DGRAM) {
/*
* We refuse usage of SO_REUSEADDR on non-UDP sockets since it
* mostly (perhaps only) opens up for socket collisions and
* probably hasn't got any useful use-cases. There are useful
* use-cases for multicast sockets, though. For more
* information see:
* https://learn.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse
*
* Prior to OTP 25 we also refused to use SO_REUSEADDR on any
* sockets on Windows. See
* 2a6ac6f3f027fcab6d607599e82714e930d9fde2
*
* We certainly do not want to use it for the Erlang
* distribution TCP sockets since we can end up reusing our
* own active sockets as demonstrated in the issue:
* https://github.com/erlang/otp/issues/6461
*
* We probably want to expose the Windows specific
* SO_EXCLUSIVEADDRUSE in the API as well...
*/
continue;
}
#endif
type = SO_REUSEADDR;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(reuseaddr) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(ival)) );
break;
case INET_OPT_KEEPALIVE: type = SO_KEEPALIVE;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(keepalive) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(ival)) );
break;
case INET_OPT_DONTROUTE: type = SO_DONTROUTE;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(dontroute) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(ival)) );
break;
case INET_OPT_BROADCAST: type = SO_BROADCAST;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(broadcast) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(ival)) );
break;
case INET_OPT_OOBINLINE: type = SO_OOBINLINE;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(oobinline) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(ival)) );
break;
case INET_OPT_SNDBUF: type = SO_SNDBUF; DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(sndbuf) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
break;
case INET_OPT_RCVBUF: type = SO_RCVBUF;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(rcvbuf) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
if (!(desc->flags & INET_FLG_BUFFER_SET)) {
/* make sure we have desc->bufsz >= SO_RCVBUF */
if (ival > (1 << 16) && desc->stype == SOCK_DGRAM && !IS_SCTP(desc))
/* For UDP we don't want to automatically
set the buffer size to be larger than
the theoretical max MTU */
desc->bufsz = 1 << 16;
else if (ival > desc->bufsz)
desc->bufsz = ival;
}
break;
case INET_OPT_LINGER: type = SO_LINGER;
if (len < 4)
return -1;
li_val.l_onoff = ival;
li_val.l_linger = get_int32(ptr);
ptr += 4;
len -= 4;
arg_ptr = (char*) &li_val;
arg_sz = sizeof(li_val);
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(linger) -> %d, %d\r\n",
__LINE__,
desc->s, driver_caller(desc->port),
li_val.l_onoff, li_val.l_linger) );
if (desc->sprotocol == IPPROTO_TCP) {
tcp_descriptor* tdesc = (tcp_descriptor*) desc;
if (li_val.l_onoff && li_val.l_linger == 0)
tdesc->tcp_add_flags |= TCP_ADDF_LINGER_ZERO;
else
tdesc->tcp_add_flags &= ~TCP_ADDF_LINGER_ZERO;
}
break;
case INET_OPT_PRIORITY:
#ifdef SO_PRIORITY
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(prio) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
type = SO_PRIORITY;
propagate = 1; /* We do want to know if this fails */
break;
#else
/* inet_fill_opts always returns a value for this option,
* so we need to ignore it if not implemented */
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(prio) -> SKIP\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
continue;
#endif
case INET_OPT_TOS:
#if defined(IP_TOS) && defined(IPPROTO_IP)
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(tos) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
proto = IPPROTO_IP;
type = IP_TOS;
propagate = 1;
break;
#else
/* inet_fill_opts always returns a value for this option,
* so we need to ignore it if not implemented. */
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(tos) -> SKIP\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
continue;
#endif
#if defined(IPV6_TCLASS) && defined(IPPROTO_IPV6)
case INET_OPT_TCLASS:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(tclass) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
proto = IPPROTO_IPV6;
type = IPV6_TCLASS;
propagate = 1;
break;
#endif
#if defined(IP_TTL) && defined(IPPROTO_IP)
case INET_OPT_TTL:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(ttl) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
proto = IPPROTO_IP;
type = IP_TTL;
propagate = 1;
break;
#endif
#if defined(IP_RECVTOS) && defined(IPPROTO_IP)
case INET_OPT_RECVTOS:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(recvtos) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
proto = IPPROTO_IP;
type = IP_RECVTOS;
propagate = 1;
recv_cmsgflags =
ival ?
(desc->recv_cmsgflags | INET_CMSG_RECVTOS) :
(desc->recv_cmsgflags & ~INET_CMSG_RECVTOS);
break;
#endif
#if defined(IPV6_RECVTCLASS) && defined(IPPROTO_IPV6)
case INET_OPT_RECVTCLASS:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(recvtclass) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
proto = IPPROTO_IPV6;
type = IPV6_RECVTCLASS;
propagate = 1;
recv_cmsgflags =
ival ?
(desc->recv_cmsgflags | INET_CMSG_RECVTCLASS) :
(desc->recv_cmsgflags & ~INET_CMSG_RECVTCLASS);
break;
#endif
#if defined(IP_RECVTTL) && defined(IPPROTO_IP)
case INET_OPT_RECVTTL:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(recvttl) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
proto = IPPROTO_IP;
type = IP_RECVTTL;
propagate = 1;
recv_cmsgflags =
ival ?
(desc->recv_cmsgflags | INET_CMSG_RECVTTL) :
(desc->recv_cmsgflags & ~INET_CMSG_RECVTTL);
break;
#endif
case TCP_OPT_NODELAY:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(nodelay) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(ival)) );
proto = IPPROTO_TCP;
type = TCP_NODELAY;
break;
case TCP_OPT_NOPUSH:
#if defined(INET_TCP_NOPUSH)
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(nopush) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
proto = IPPROTO_TCP;
type = INET_TCP_NOPUSH;
break;
#else
/* inet_fill_opts always returns a value for this option,
* so we need to ignore it if not implemented, just in case */
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(nopush) -> SKIP\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
continue;
#endif
#if defined(HAVE_MULTICAST_SUPPORT) && defined(IPPROTO_IP)
case UDP_OPT_MULTICAST_TTL:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(multicast-ttl) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
proto = IPPROTO_IP;
type = IP_MULTICAST_TTL;
break;
case UDP_OPT_MULTICAST_LOOP:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(multicast-loop) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(ival)) );
proto = IPPROTO_IP;
type = IP_MULTICAST_LOOP;
break;
case UDP_OPT_MULTICAST_IF:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(multicast-if) -> %d (%d)\r\n",
__LINE__,
desc->s, driver_caller(desc->port), ival, sock_htonl(ival)) );
if (desc->sfamily == AF_INET) {
proto = IPPROTO_IP;
type = IP_MULTICAST_IF;
DEBUGF(("inet_set_opts(%p): s=%d, IP_MULTICAST_IF = %x\r\n",
desc->port, desc->s, ival));
ival = sock_htonl(ival);
}
#if defined(HAVE_IN6) && defined(AF_INET6) && defined(IPPROTO_IPV6)
else if (desc->sfamily == AF_INET6) {
proto = IPPROTO_IPV6;
type = IPV6_MULTICAST_IF;
DEBUGF(("inet_set_opts(%p): s=%d, IPV6_MULTICAST_IF = %x\r\n",
desc->port, desc->s, ival));
ival = sock_htonl(ival);
} else {
return -1;
}
#else
else {
return -1;
}
#endif
break;
case UDP_OPT_ADD_MEMBERSHIP:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(add-membership) -> domain: %d (%s)\r\n",
__LINE__, desc->s, driver_caller(desc->port),
ival, DOM2S(ival)) );
if (ival == INET_AF_INET) {
proto = IPPROTO_IP;
type = IP_ADD_MEMBERSHIP;
}
#if defined(HAVE_IN6) && defined(AF_INET6) && defined(IPPROTO_IPV6)
else if (ival == INET_AF_INET6) {
proto = IPPROTO_IPV6;
#if defined(INET_ADD_MEMBERSHIP)
type = INET_DROP_MEMBERSHIP;
#else
return -1;
#endif
}
#endif
else {
return -1;
}
goto L_init_mreq;
case UDP_OPT_DROP_MEMBERSHIP:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(drop-membership) -> %d (%s)\r\n",
__LINE__, desc->s, driver_caller(desc->port),
ival, DOM2S(ival)) );
if (ival == INET_AF_INET) {
proto = IPPROTO_IP;
type = IP_DROP_MEMBERSHIP;
}
#if defined(HAVE_IN6) && defined(AF_INET6) && defined(IPPROTO_IPV6)
else if (ival == INET_AF_INET6) {
proto = IPPROTO_IPV6;
#if defined(INET_DROP_MEMBERSHIP)
type = INET_DROP_MEMBERSHIP;
#else
return -1;
#endif
}
#endif
else {
return -1;
}
L_init_mreq:
{
int domain = ival;
ival = get_int32(ptr); // Interface | Ifindex
ptr += 4;
len -= 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(L_init_mreq) -> "
"\r\n proto: %d"
"\r\n type: %d"
"\r\n domain: %d (%s)"
"\r\n if: %d"
"\r\n",
__LINE__, desc->s, driver_caller(desc->port),
proto, type, domain, DOM2S(domain), ival));
if ((domain == INET_AF_INET) && (desc->sfamily == AF_INET)) {
mreqSz = sizeof(mreq4);
/* 0) Read out the ifindex (see above)
* 1) Read out the multiaddr
* 2) Read out the local address
*/
#if defined(HAVE_STRUCT_IP_MREQN)
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(L_init_mreq,inet) -> mreqn\r\n",
__LINE__, desc->s, driver_caller(desc->port)));
mreq4.imr_ifindex = sock_htonl(ival);
ival = get_int32(ptr);
ptr += 4;
len -= 4;
mreq4.imr_multiaddr.s_addr = sock_htonl(ival);
ival = get_int32(ptr);
ptr += 4;
len -= 4;
mreq4.imr_address.s_addr = sock_htonl(ival);
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(L_init_mreq,inet) -> "
"try setopt: "
"\r\n maddr: %x"
"\r\n addr: %x"
"\r\n if: %d"
"\r\n sz: %d"
"\r\n",
__LINE__, desc->s, driver_caller(desc->port),
mreq4.imr_multiaddr.s_addr,
mreq4.imr_address.s_addr,
mreq4.imr_ifindex,
mreqSz));
#else
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(L_init_mreq,inet) -> mreq\r\n",
__LINE__, desc->s, driver_caller(desc->port)));
ival = get_int32(ptr);
ptr += 4;
len -= 4;
mreq4.imr_multiaddr.s_addr = sock_htonl(ival);
ival = get_int32(ptr);
ptr += 4;
len -= 4;
mreq4.imr_interface.s_addr = sock_htonl(ival);
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(L_init_mreq,inet) -> "
"try setopt: "
"\r\n maddr: %x"
"\r\n if: %x"
"\r\n sz: %d"
"\r\n",
__LINE__, desc->s, driver_caller(desc->port),
mreq4.imr_multiaddr.s_addr,
mreq4.imr_interface.s_addr,
mreqSz));
#endif
arg_ptr = (char*)&mreq4;
arg_sz = mreqSz;
}
#if defined(HAVE_IN6) && defined(AF_INET6) && defined(IPPROTO_IPV6)
else if ((domain == INET_AF_INET6) &&
(desc->sfamily == AF_INET6)) {
mreqSz = sizeof(mreq6);
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(L_init_mreq,inet6) -> mreq\r\n",
__LINE__, desc->s, driver_caller(desc->port)));
/* 0) Read out the ifindex
* 1) Read out the multiaddr
*/
sys_memcpy(&mreq6.ipv6mr_multiaddr, ptr, 16);
ptr += 16;
len -= len;
mreq6.ipv6mr_interface = ival;
arg_ptr = (char*)&mreq6;
arg_sz = mreqSz;
}
#endif
else {
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(L_init_mreq) -> "
"invalid domain: "
"\r\n domain: %d (%d, %d)"
"\r\n sfmaily: %d (%d, %d)"
"\r\n",
__LINE__, desc->s, driver_caller(desc->port),
domain, INET_AF_INET, INET_AF_INET6,
desc->sfamily, AF_INET, AF_INET6));
return -1;
}
}
break;
#endif /* defined(HAVE_MULTICAST_SUPPORT) && defined(IPPROTO_IP) */
case INET_OPT_IPV6_V6ONLY:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(ipv6-v6only) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(ival)) );
#if HAVE_DECL_IPV6_V6ONLY && defined(IPPROTO_IPV6)
proto = IPPROTO_IPV6;
type = IPV6_V6ONLY;
propagate = 1;
break;
#elif defined(__WIN32__) && defined(HAVE_IN6) && defined(AF_INET6)
/* Fake a'la OpenBSD; set to 'true' is fine but 'false' invalid. */
if (ival != 0) continue;
else return -1;
break;
#else
continue;
#endif
case INET_OPT_RAW:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(raw) -> %d, %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival, len) );
if (len < 8) {
return -1;
}
proto = ival;
type = get_int32(ptr);
ptr += 4;
arg_sz = get_int32(ptr);
ptr += 4;
len -= 8;
if (len < arg_sz) {
return -1;
}
arg_ptr = ptr;
ptr += arg_sz;
len -= arg_sz;
break;
#ifdef SO_BINDTODEVICE
case INET_OPT_BIND_TO_DEVICE:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(bindtodevice) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
if (ival < 0) return -1;
if (len < ival) return -1;
if (ival > sizeof(ifname)) {
return -1;
}
memcpy(ifname, ptr, ival);
ifname[ival] = '\0';
ptr += ival;
len -= ival;
proto = SOL_SOCKET;
type = SO_BINDTODEVICE;
arg_ptr = (char*)&ifname;
arg_sz = sizeof(ifname);
propagate = 1; /* We do want to know if this fails */
break;
#endif
case INET_LOPT_DEBUG:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts(debug) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(ival)) );
if (ival) {
desc->debug = TRUE;
} else {
desc->debug = FALSE;
}
continue; /* take care of next option */
default:
return -1;
}
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts -> try set opt (%d) %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), proto, type) );
res = inet_setopt(desc->s, proto, type, arg_ptr, arg_sz, propagate);
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_set_opts -> set opt result: %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), res) );
if (res == 0) desc->recv_cmsgflags = recv_cmsgflags;
if (propagate && res != 0) {
return -1;
}
}
if ( ((desc->stype == SOCK_STREAM) && IS_CONNECTED(desc)) ||
((desc->stype == SOCK_DGRAM) && IS_OPEN(desc))) {
int trigger_recv;
/* XXX: UDP sockets could also trigger immediate read here NIY */
trigger_recv =
(desc->stype==SOCK_STREAM) &&
!old_active &&
(desc->active == INET_ONCE || desc->active == INET_MULTI) &&
(desc->htype == old_htype);
if (trigger_recv) {
return 2;
}
if (desc->active != old_active) {
/* Need to cancel the read_packet timer *
* if we go from active to passive. */
if (desc->active == INET_PASSIVE && desc->stype == SOCK_DGRAM)
driver_cancel_timer(desc->port);
sock_select(desc, (FD_READ|FD_CLOSE), (desc->active>0));
}
/* XXX: UDP sockets could also trigger immediate read here NIY */
if ((desc->stype==SOCK_STREAM) && desc->active) {
if (!old_active || (desc->htype != old_htype)) {
/* passive => active change OR header type change in active mode */
return 1;
}
return 0;
}
}
return 0;
}
#ifdef HAVE_SCTP
/* "sctp_get_initmsg":
** Used by both "send*" and "setsockopt". Gets the 4 fields of "sctp_initmsg"
** from the input buffer:
*/
#define SCTP_GET_INITMSG_LEN (4*2)
static char* sctp_get_initmsg(struct sctp_initmsg* ini, char* curr)
{
ini->sinit_num_ostreams = get_int16 (curr); curr += 2;
ini->sinit_max_instreams = get_int16 (curr); curr += 2;
ini->sinit_max_attempts = get_int16 (curr); curr += 2;
ini->sinit_max_init_timeo = get_int16 (curr); curr += 2;
return curr;
}
/* "sctp_get_sendparams":
** Parses (from the command buffer) the 6 user-specified params of
** "sctp_sndrcvinfo":
** stream(u16), flags(u16), ppid(u32), context(u32),
** timetoleave(u32), assoc_id
** Is used by both "send*" and "setsockopt":
*/
#define SCTP_GET_SENDPARAMS_LEN (2*2 + 3*4 + ASSOC_ID_LEN)
static char* sctp_get_sendparams (struct sctp_sndrcvinfo* sri, char* curr)
{
int eflags;
int cflags;
sri->sinfo_stream = get_int16(curr); curr += 2;
sri->sinfo_ssn = 0;
/* The "flags" are already ORed at the Erlang side, here we
reconstruct the real SCTP flags:
*/
eflags = get_int16(curr); curr += 2;
cflags = 0;
if (eflags & SCTP_FLAG_UNORDERED) cflags |= SCTP_UNORDERED;
if (eflags & SCTP_FLAG_ADDR_OVER) cflags |= SCTP_ADDR_OVER;
if (eflags & SCTP_FLAG_ABORT) cflags |= SCTP_ABORT;
if (eflags & SCTP_FLAG_EOF) cflags |= SCTP_EOF;
sri->sinfo_flags = cflags;
sri->sinfo_ppid = sock_htonl(get_int32(curr));
curr += 4;
sri->sinfo_context = get_int32(curr); curr += 4;
sri->sinfo_timetolive = get_int32(curr); curr += 4;
sri->sinfo_tsn = 0;
sri->sinfo_cumtsn = 0;
sri->sinfo_assoc_id = GET_ASSOC_ID (curr); curr += ASSOC_ID_LEN;
return curr;
}
/* Set SCTP options:
** return -1 on error
** 0 if ok
** NB: unlike inet_set_opts(), we don't have an active mode here, so there is no
** mode change which could force data delivery on setting an option.
** Arg: "ptr": [(erlang_encoded_opt(u8), value(...)), ...]; thus, multiple opts
** can be set at a time.
*/
static int sctp_set_opts(inet_descriptor* desc, char* ptr, int len)
{
# define CHKLEN(Ptr, Len) \
do { \
if ((Ptr) + (Len) > ptr + len) return -1; \
} while (0)
char * curr = ptr;
int proto, type, res;
/* The following union is used to hold any arg to "setsockopt": */
union opts_union
{
int ival;
struct sctp_rtoinfo rtoi;
struct sctp_assocparams ap;
struct sctp_initmsg im;
struct linger lin;
struct sctp_setpeerprim prim;
struct sctp_setadaptation ad;
struct sctp_paddrparams pap;
struct sctp_sndrcvinfo sri;
struct sctp_event_subscribe es;
#if defined(HAVE_DECL_SCTP_DELAYED_ACK_TIME) && defined(SCTP_ASSOC_VALUE_ASSOC_ID)
struct sctp_assoc_value av; /* Not in SOLARIS10 */
#endif
# ifdef SO_BINDTODEVICE
char ifname[IFNAMSIZ];
# endif
}
arg;
char * arg_ptr = NULL;
int arg_sz = 0;
int old_active = desc->active;
while (curr < ptr + len)
{
int recv_cmsgflags;
/* Get the Erlang-encoded option type -- always 1 byte: */
int eopt;
eopt = *curr;
curr++;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts -> eopt: %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), eopt) );
recv_cmsgflags = desc->recv_cmsgflags;
/* Get the option value. XXX: The condition (curr < ptr + len)
does not preclude us from reading from beyond the buffer end,
if the Erlang part of the driver specifies its input wrongly!
*/
CHKLEN(curr, 4); /* All options need at least 4 bytes */
switch(eopt)
{
/* Local INET options: */
case INET_LOPT_BUFFER:
{
int ival = get_int32(curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(buffer) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
desc->bufsz = ival;
if (desc->bufsz < INET_MIN_BUFFER)
desc->bufsz = INET_MIN_BUFFER;
desc->flags |= INET_FLG_BUFFER_SET;
res = 0; /* This does not affect the kernel buffer size */
}
continue;
case INET_LOPT_MODE:
{
int ival = get_int32(curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(mode) -> %s (%d)\r\n",
__LINE__, desc->s, driver_caller(desc->port),
M2S(ival), ival) );
desc->mode = ival;
res = 0;
}
continue;
case INET_LOPT_ACTIVE:
{
int ival = get_int32(curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(active) -> %s (%d)\r\n",
__LINE__, desc->s, driver_caller(desc->port),
A2S(ival), ival) );
desc->active = ival;
if (desc->active == INET_MULTI) {
long ac = desc->active_count;
Sint16 nval = get_int16(curr); curr += 2;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(active) -> nval: %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), nval) );
ac += nval;
if (ac > INT16_MAX || ac < INT16_MIN)
return -1;
desc->active_count += nval;
if (desc->active_count < 0)
desc->active_count = 0;
if (desc->active_count == 0) {
desc->active = INET_PASSIVE;
packet_passive_message(desc);
}
} else
desc->active_count = 0;
res = 0;
}
continue;
#ifdef HAVE_SETNS
case INET_LOPT_NETNS:
{
size_t ns_len;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts -> NETNS\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
ns_len = get_int32(curr); curr += 4;
CHKLEN(curr, ns_len);
if (desc->netns != NULL) FREE(desc->netns);
desc->netns = ALLOC(ns_len + 1);
memcpy(desc->netns, curr, ns_len);
desc->netns[ns_len] = '\0';
curr += ns_len;
}
continue;
#endif
/* SCTP options and applicable generic INET options: */
case SCTP_OPT_RTOINFO:
{
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts -> RTOINFO\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
CHKLEN(curr, ASSOC_ID_LEN + 3*4);
arg.rtoi.srto_assoc_id = GET_ASSOC_ID(curr); curr += ASSOC_ID_LEN;
arg.rtoi.srto_initial = get_int32 (curr); curr += 4;
arg.rtoi.srto_max = get_int32 (curr); curr += 4;
arg.rtoi.srto_min = get_int32 (curr); curr += 4;
proto = IPPROTO_SCTP;
type = SCTP_RTOINFO;
arg_ptr = (char*) (&arg.rtoi);
arg_sz = sizeof ( arg.rtoi);
break;
}
case SCTP_OPT_ASSOCINFO:
{
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts -> ASSOCINFO\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
CHKLEN(curr, ASSOC_ID_LEN + 2*2 + 3*4);
arg.ap.sasoc_assoc_id = GET_ASSOC_ID(curr); curr += ASSOC_ID_LEN;
arg.ap.sasoc_asocmaxrxt = get_int16 (curr); curr += 2;
arg.ap.sasoc_number_peer_destinations =
get_int16 (curr); curr += 2;
arg.ap.sasoc_peer_rwnd = get_int32 (curr); curr += 4;
arg.ap.sasoc_local_rwnd = get_int32 (curr); curr += 4;
arg.ap.sasoc_cookie_life = get_int32 (curr); curr += 4;
proto = IPPROTO_SCTP;
type = SCTP_ASSOCINFO;
arg_ptr = (char*) (&arg.ap);
arg_sz = sizeof ( arg.ap);
break;
}
case SCTP_OPT_INITMSG:
{
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts -> INITMSG\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
CHKLEN(curr, SCTP_GET_INITMSG_LEN);
curr = sctp_get_initmsg (&arg.im, curr);
proto = IPPROTO_SCTP;
type = SCTP_INITMSG;
arg_ptr = (char*) (&arg.im);
arg_sz = sizeof ( arg.im);
break;
}
case INET_OPT_LINGER:
{
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts -> LINGER\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
CHKLEN(curr, 2*4);
arg.lin.l_onoff = get_int32 (curr); curr += 4;
arg.lin.l_linger = get_int32 (curr); curr += 4;
proto = SOL_SOCKET;
type = SO_LINGER;
arg_ptr = (char*) (&arg.lin);
arg_sz = sizeof ( arg.lin);
break;
}
case SCTP_OPT_NODELAY:
{
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts -> NODELAY\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
arg.ival= get_int32 (curr); curr += 4;
proto = IPPROTO_SCTP;
type = SCTP_NODELAY;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
break;
}
case INET_OPT_RCVBUF:
{
int ival = get_int32 (curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(rcvbuf) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
arg.ival= ival;
proto = SOL_SOCKET;
type = SO_RCVBUF;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
/* Adjust the size of the user-level recv buffer, so it's not
smaller than the kernel one: */
if (desc->bufsz <= arg.ival)
desc->bufsz = arg.ival;
desc->flags |= INET_FLG_BUFFER_SET;
break;
}
case INET_OPT_SNDBUF:
{
int ival = get_int32 (curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(sndbuf) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
arg.ival= ival;
proto = SOL_SOCKET;
type = SO_SNDBUF;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
break;
}
case INET_OPT_REUSEADDR:
{
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts -> REUSEADDR\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
arg.ival= get_int32 (curr); curr += 4;
proto = SOL_SOCKET;
type = SO_REUSEADDR;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
break;
}
case INET_OPT_DONTROUTE:
{
int ival = get_int32 (curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(dontroute) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(ival)) );
arg.ival = ival;
proto = SOL_SOCKET;
type = SO_DONTROUTE;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
break;
}
case INET_OPT_PRIORITY:
# ifdef SO_PRIORITY
{
int ival = get_int32 (curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(prio) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
arg.ival = ival;
proto = SOL_SOCKET;
type = SO_PRIORITY;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
break;
}
# else
/* inet_fill_opts always returns a value for this option,
* so we need to ignore it if not implemented, just in case */
continue;
# endif
case INET_OPT_TOS:
# if defined(IP_TOS) && defined(IPPROTO_IP)
{
int ival = get_int32 (curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(tos) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
arg.ival = ival;
proto = IPPROTO_IP;
type = IP_TOS;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
break;
}
# else
/* inet_fill_opts always returns a value for this option,
* so we need to ignore it if not implemented, just in case */
continue;
# endif
# if defined(IPV6_TCLASS) && defined(IPPROTO_IPV6)
case INET_OPT_TCLASS:
{
int ival = get_int32 (curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(tclass) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
arg.ival = ival;
proto = IPPROTO_IPV6;
type = IPV6_TCLASS;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
break;
}
# endif
# if defined(IP_TTL) && defined(IPPROTO_IP)
case INET_OPT_TTL:
{
int ival = get_int32 (curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(ttl) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
arg.ival = ival;
proto = IPPROTO_IP;
type = IP_TTL;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
break;
}
# endif
# if defined(IP_RECVTOS) && defined(IPPROTO_IP)
case INET_OPT_RECVTOS:
{
int ival = get_int32 (curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(recvtos) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(ival)) );
arg.ival = ival;
proto = IPPROTO_IP;
type = IP_RECVTOS;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
recv_cmsgflags =
arg.ival ?
(desc->recv_cmsgflags | INET_CMSG_RECVTOS) :
(desc->recv_cmsgflags & ~INET_CMSG_RECVTOS);
break;
}
# endif
# if defined(IPV6_RECVTCLASS) && defined(IPPROTO_IPV6)
case INET_OPT_RECVTCLASS:
{
int ival = get_int32 (curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(recvtclass) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(ival)) );
arg.ival = ival;
proto = IPPROTO_IPV6;
type = IPV6_RECVTCLASS;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
recv_cmsgflags =
arg.ival ?
(desc->recv_cmsgflags | INET_CMSG_RECVTCLASS) :
(desc->recv_cmsgflags & ~INET_CMSG_RECVTCLASS);
break;
}
# endif
# if defined(IP_RECVTTL) && defined(IPPROTO_IP)
case INET_OPT_RECVTTL:
{
int ival = get_int32 (curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(recvttl) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(ival)) );
arg.ival = ival;
proto = IPPROTO_IP;
type = IP_RECVTTL;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
recv_cmsgflags =
arg.ival ?
(desc->recv_cmsgflags | INET_CMSG_RECVTTL) :
(desc->recv_cmsgflags & ~INET_CMSG_RECVTTL);
break;
}
# endif
case INET_OPT_IPV6_V6ONLY:
# if HAVE_DECL_IPV6_V6ONLY && defined(IPPROTO_IPV6)
{
int ival = get_int32 (curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(ipv6_v6only) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(ival)) );
arg.ival = ival;
proto = IPPROTO_IPV6;
type = IPV6_V6ONLY;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
break;
}
# elif defined(__WIN32__) && defined(HAVE_IN6) && defined(AF_INET6)
# error Here is a fix for Win IPv6 SCTP missing
# else
continue; /* Option not supported -- ignore it */
# endif
#ifdef SO_BINDTODEVICE
case INET_OPT_BIND_TO_DEVICE:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts -> BIND_TO_DEVICE\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
arg_sz = get_int32(curr); curr += 4;
CHKLEN(curr, arg_sz);
if (arg_sz >= sizeof(arg.ifname))
return -1;
memcpy(arg.ifname, curr, arg_sz);
arg.ifname[arg_sz] = '\0';
curr += arg_sz;
proto = SOL_SOCKET;
type = SO_BINDTODEVICE;
arg_ptr = (char*) (&arg.ifname);
arg_sz = sizeof ( arg.ifname);
break;
#endif
case SCTP_OPT_AUTOCLOSE:
{
int ival = get_int32 (curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(autoclose) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
arg.ival = ival;
proto = IPPROTO_SCTP;
type = SCTP_AUTOCLOSE;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
break;
}
case SCTP_OPT_DISABLE_FRAGMENTS:
{
int ival = get_int32 (curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(disable_fragments) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(ival)) );
arg.ival = ival;
proto = IPPROTO_SCTP;
type = SCTP_DISABLE_FRAGMENTS;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
break;
}
case SCTP_OPT_I_WANT_MAPPED_V4_ADDR:
{
int ival = get_int32 (curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(i_want_mapped_v4_addr) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(ival)) );
arg.ival = ival;
proto = IPPROTO_SCTP;
type = SCTP_I_WANT_MAPPED_V4_ADDR;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
break;
}
case SCTP_OPT_MAXSEG:
{
int ival = get_int32 (curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(maxseg) -> %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), ival) );
arg.ival = ival;
proto = IPPROTO_SCTP;
type = SCTP_MAXSEG;
arg_ptr = (char*) (&arg.ival);
arg_sz = sizeof ( arg.ival);
break;
}
case SCTP_OPT_PRIMARY_ADDR:
case SCTP_OPT_SET_PEER_PRIMARY_ADDR:
{
ErlDrvSizeT alen;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts -> PRIMARY_ADDR | SET_PEER_PRIMARY_ADDR\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
CHKLEN(curr, ASSOC_ID_LEN);
/* XXX: These 2 opts have isomorphic value data structures,
"sctp_setpeerprim" and "sctp_prim" (in Solaris 10, the latter
is called "sctp_setprim"), so we grouped them together:
*/
arg.prim.sspp_assoc_id = GET_ASSOC_ID(curr); curr += ASSOC_ID_LEN;
/* Fill in "arg.prim.sspp_addr": */
alen = ptr + len - curr;
if (inet_set_faddress
(desc->sfamily, (inet_address*) (&arg.prim.sspp_addr),
&curr, &alen) != NULL) return -1;
proto = IPPROTO_SCTP;
if (eopt == SCTP_OPT_PRIMARY_ADDR)
type = SCTP_PRIMARY_ADDR;
else
type = SCTP_SET_PEER_PRIMARY_ADDR;
arg_ptr = (char*) (&arg.prim);
arg_sz = sizeof ( arg.prim);
break;
}
case SCTP_OPT_ADAPTATION_LAYER:
{
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts -> ADAPTATION_LAYER\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
/* XXX: do we need to convert the Ind into network byte order??? */
arg.ad.ssb_adaptation_ind = sock_htonl (get_int32(curr)); curr += 4;
proto = IPPROTO_SCTP;
type = SCTP_ADAPTATION_LAYER;
arg_ptr = (char*) (&arg.ad);
arg_sz = sizeof ( arg.ad);
break;
}
case SCTP_OPT_PEER_ADDR_PARAMS:
{
ErlDrvSizeT alen;
# ifdef HAVE_STRUCT_SCTP_PADDRPARAMS_SPP_FLAGS
int eflags, cflags, hb_enable, hb_disable,
pmtud_enable, pmtud_disable;
# ifdef HAVE_STRUCT_SCTP_PADDRPARAMS_SPP_SACKDELAY
int
sackdelay_enable, sackdelay_disable;
# endif
# endif
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts -> PEER_ADDR_PARAMS\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
CHKLEN(curr, ASSOC_ID_LEN);
arg.pap.spp_assoc_id = GET_ASSOC_ID(curr); curr += ASSOC_ID_LEN;
/* Fill in "pap.spp_address": */
alen = ptr + len - curr;
if (inet_set_faddress
(desc->sfamily, (inet_address*) (&arg.pap.spp_address),
&curr, &alen) != NULL) return -1;
CHKLEN(curr, 4 + 2 + 3*4);
arg.pap.spp_hbinterval = get_int32(curr); curr += 4;
arg.pap.spp_pathmaxrxt = get_int16(curr); curr += 2;
/* The following are missing in Solaris 10: */
# ifdef HAVE_STRUCT_SCTP_PADDRPARAMS_SPP_PATHMTU
arg.pap.spp_pathmtu = get_int32(curr);
# endif
curr += 4;
# ifdef HAVE_STRUCT_SCTP_PADDRPARAMS_SPP_SACKDELAY
arg.pap.spp_sackdelay = get_int32(curr);
# endif
curr += 4;
# ifdef HAVE_STRUCT_SCTP_PADDRPARAMS_SPP_FLAGS
/* Now re-construct the flags: */
eflags = get_int32(curr);
cflags = 0;
hb_enable = eflags & SCTP_FLAG_HB_ENABLE;
hb_disable = eflags & SCTP_FLAG_HB_DISABLE;
if (hb_enable && hb_disable)
return -1;
if (hb_enable) cflags |= SPP_HB_ENABLE;
if (hb_disable) cflags |= SPP_HB_DISABLE;
if (eflags & SCTP_FLAG_HB_DEMAND) cflags |= SPP_HB_DEMAND;
pmtud_enable = eflags & SCTP_FLAG_PMTUD_ENABLE;
pmtud_disable = eflags & SCTP_FLAG_PMTUD_DISABLE;
if (pmtud_enable && pmtud_disable)
return -1;
if (pmtud_enable) cflags |= SPP_PMTUD_ENABLE;
if (pmtud_disable) cflags |= SPP_PMTUD_DISABLE;
# ifdef HAVE_STRUCT_SCTP_PADDRPARAMS_SPP_SACKDELAY
/* The following are missing in FreeBSD 7.1 */
sackdelay_enable =eflags& SCTP_FLAG_SACDELAY_ENABLE;
sackdelay_disable=eflags& SCTP_FLAG_SACDELAY_DISABLE;
if (sackdelay_enable && sackdelay_disable)
return -1;
if (sackdelay_enable) cflags |= SPP_SACKDELAY_ENABLE;
if (sackdelay_disable) cflags |= SPP_SACKDELAY_DISABLE;
# endif
arg.pap.spp_flags = cflags;
# endif
curr += 4;
proto = IPPROTO_SCTP;
type = SCTP_PEER_ADDR_PARAMS;
arg_ptr = (char*) (&arg.pap);
arg_sz = sizeof ( arg.pap);
break;
}
case SCTP_OPT_DEFAULT_SEND_PARAM:
{
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts -> DEFAULT_SEND_PARAM\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
CHKLEN(curr, SCTP_GET_SENDPARAMS_LEN);
curr = sctp_get_sendparams (&arg.sri, curr);
proto = IPPROTO_SCTP;
type = SCTP_DEFAULT_SEND_PARAM;
arg_ptr = (char*) (&arg.sri);
arg_sz = sizeof ( arg.sri);
VALGRIND_MAKE_MEM_DEFINED(arg_ptr, arg_sz); /*suppress "uninitialised bytes"*/
break;
}
case SCTP_OPT_EVENTS:
{
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts -> EVENTS\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
CHKLEN(curr, 9);
/* We do not support "sctp_authentication_event" -- it is not
implemented in Linux Kernel SCTP anyway. Just in case if
the above structure has more fields than we support, zero
it out -- the extraneous events will NOT be used:
*/
memset (&arg.es, 0, sizeof(arg.es));
/* The input "buf" must contain the full definition of all the
supported event fields, 1 byte per each, as each event is
either explicitly subscribed or cleared:
*/
arg.es.sctp_data_io_event = get_int8(curr); curr++;
arg.es.sctp_association_event = get_int8(curr); curr++;
arg.es.sctp_address_event = get_int8(curr); curr++;
arg.es.sctp_send_failure_event = get_int8(curr); curr++;
arg.es.sctp_peer_error_event = get_int8(curr); curr++;
arg.es.sctp_shutdown_event = get_int8(curr); curr++;
arg.es.sctp_partial_delivery_event = get_int8(curr); curr++;
arg.es.sctp_adaptation_layer_event = get_int8(curr); curr++;
/* sctp_authentication_event not implemented */ curr++;
proto = IPPROTO_SCTP;
type = SCTP_EVENTS;
arg_ptr = (char*) (&arg.es);
arg_sz = sizeof ( arg.es);
break;
}
/* The following is not available on
* Solaris 10 or NetBSD or ... */
#if defined(HAVE_DECL_SCTP_DELAYED_ACK_TIME) && defined(SCTP_ASSOC_VALUE_ASSOC_ID)
case SCTP_OPT_DELAYED_ACK_TIME:
{
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts -> DELAYED_ACK_TIME\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
CHKLEN(curr, ASSOC_ID_LEN + 4);
arg.av.assoc_id = GET_ASSOC_ID(curr); curr += ASSOC_ID_LEN;
arg.av.assoc_value = get_int32(curr); curr += 4;
proto = IPPROTO_SCTP;
type = SCTP_DELAYED_ACK_TIME;
arg_ptr = (char*) (&arg.av);
arg_sz = sizeof ( arg.av);
break;
}
#endif
case INET_LOPT_DEBUG:
{
int ival = get_int32(curr); curr += 4;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"sctp_set_opts(debug) -> %s\r\n",
__LINE__, desc->s, driver_caller(desc->port),
B2S(ival)) );
if (ival) {
desc->debug = TRUE;
} else {
desc->debug = FALSE;
}
res = 0;
}
continue; /* take care of next option */
default:
/* XXX: No more supported SCTP options. In particular, authentica-
tion options (SCTP_AUTH_CHUNK, SCTP_AUTH_KEY, SCTP_PEER_AUTH_
CHUNKS, SCTP_LOCAL_AUTH_CHUNKS, SCTP_AUTH_SETKEY_ACTIVE) are
not yet implemented in the Linux kernel, hence not supported
here. Also not supported are SCTP_HMAC_IDENT, as well as any
"generic" options except "INET_LOPT_MODE". Raise an error:
*/
return -1;
}
res = inet_setopt(desc->s, proto, type, arg_ptr, arg_sz, 1);
/* The return values of "sock_setopt" can only be 0 or -1: */
ASSERT(res == 0 || res == -1);
if (res == 0) desc->recv_cmsgflags = recv_cmsgflags;
if (res == -1)
{ /* Got an error, DO NOT continue with other options. However, on
Solaris 10, we DO allow SO_SNDBUF and SO_RCVBUF to fail, assu-
min that the default kernel versions are good enough:
*/
# ifdef SOLARIS10
if (type != SO_SNDBUF && type != SO_RCVBUF)
# endif
return res;
}
}
/* If we got here, all "sock_setopt"s above were successful: */
if (IS_OPEN(desc) && desc->active != old_active) {
sock_select(desc, (FD_READ|FD_CLOSE), (desc->active > 0));
}
return 0;
# undef CHKLEN
}
#endif /* HAVE_SCTP */
#ifndef __WIN32__
static void put_cmsg_int32(struct cmsghdr *cmsg, char *ptr) {
union u {
byte uint8;
Uint16 uint16;
Uint32 uint32;
Uint64 uint64;
} *p;
p = (union u*) CMSG_DATA(cmsg);
switch (LEN_CMSG_DATA(cmsg) * CHAR_BIT) {
case 8:
put_int32((Uint32) p->uint8, ptr);
break;
case 16:
put_int32((Uint32) p->uint16, ptr);
break;
case 32:
put_int32(p->uint32, ptr);
break;
case 64:
put_int32((Uint32) p->uint64, ptr);
break;
default:
put_int32(0, ptr);
}
return;
}
#endif
/* load all option values into the buf and reply
** return total length of reply filled into ptr
** ptr should point to a buffer with 9*len +1 to be safe!!
*/
static ErlDrvSSizeT inet_fill_opts(inet_descriptor* desc,
char* buf, ErlDrvSizeT len,
char** dest, ErlDrvSizeT destlen)
{
int type;
int proto;
int opt;
struct linger li_val;
int ival;
char* arg_ptr;
unsigned int arg_sz;
char *ptr = NULL;
ErlDrvSizeT dest_used = 0;
ErlDrvSizeT dest_allocated = destlen;
char *orig_dest = *dest;
#ifdef SO_BINDTODEVICE
char ifname[IFNAMSIZ];
#endif
/* Ptr is a name parameter */
#define RETURN_ERROR() \
do { \
if (dest_allocated > destlen) { \
FREE(*dest); \
*dest = orig_dest; \
} \
return -1; \
} while(0)
#define PLACE_FOR(Size,Ptr) \
do { \
ErlDrvSizeT need = dest_used + (Size); \
if (need > INET_MAX_OPT_BUFFER) { \
RETURN_ERROR(); \
} \
if (need > dest_allocated) { \
char *new_buffer; \
if (dest_allocated == destlen) { \
new_buffer = ALLOC((dest_allocated = need + 10)); \
memcpy(new_buffer,*dest,dest_used); \
} else { \
new_buffer = REALLOC(*dest, (dest_allocated = need + 10)); \
} \
*dest = new_buffer; \
} \
(Ptr) = (*dest) + dest_used; \
dest_used = need; \
} while (0)
/* Ptr is a name parameter */
#define TRUNCATE_TO(Size,Ptr) \
do { \
ErlDrvSizeT new_need = ((Ptr) - (*dest)) + (Size); \
if (new_need > dest_used) { \
erts_exit(ERTS_ERROR_EXIT,"Internal error in inet_drv, " \
"miscalculated buffer size"); \
} \
dest_used = new_need; \
} while(0)
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_fill_opts -> entry\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
PLACE_FOR(1,ptr);
*ptr = INET_REP_OK;
while(len--) {
opt = *buf++;
proto = SOL_SOCKET;
ival = 0; /* Windows Vista needs this (only writes part of it) */
arg_sz = sizeof(ival);
arg_ptr = (char*) &ival;
PLACE_FOR(5,ptr);
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_fill_opts -> opt %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), opt) );
switch(opt) {
case INET_LOPT_BUFFER:
*ptr++ = opt;
put_int32(desc->bufsz, ptr);
continue;
case INET_LOPT_HEADER:
*ptr++ = opt;
put_int32(desc->hsz, ptr);
continue;
case INET_LOPT_MODE:
*ptr++ = opt;
put_int32(desc->mode, ptr);
continue;
case INET_LOPT_DELIVER:
*ptr++ = opt;
put_int32(desc->deliver, ptr);
continue;
case INET_LOPT_ACTIVE:
*ptr++ = opt;
put_int32(desc->active, ptr);
if (desc->active == INET_MULTI) {
PLACE_FOR(2,ptr);
put_int16(desc->active_count, ptr);
ptr += 2;
}
continue;
case INET_LOPT_PACKET:
*ptr++ = opt;
put_int32(desc->htype, ptr);
continue;
case INET_LOPT_PACKET_SIZE:
*ptr++ = opt;
put_int32(desc->psize, ptr);
continue;
case INET_LOPT_EXITONCLOSE:
*ptr++ = opt;
put_int32(desc->exitf, ptr);
continue;
case INET_LOPT_TCP_HIWTRMRK:
if (desc->stype == SOCK_STREAM) {
*ptr++ = opt;
ival = ((tcp_descriptor*)desc)->high;
put_int32(ival, ptr);
} else {
TRUNCATE_TO(0,ptr);
}
continue;
case INET_LOPT_TCP_LOWTRMRK:
if (desc->stype == SOCK_STREAM) {
*ptr++ = opt;
ival = ((tcp_descriptor*)desc)->low;
put_int32(ival, ptr);
} else {
TRUNCATE_TO(0,ptr);
}
continue;
case INET_LOPT_MSGQ_HIWTRMRK: {
ErlDrvSizeT high = ERL_DRV_BUSY_MSGQ_READ_ONLY;
*ptr++ = opt;
erl_drv_busy_msgq_limits(desc->port, NULL, &high);
ival = high > INT_MAX ? INT_MAX : (int) high;
put_int32(ival, ptr);
continue;
}
case INET_LOPT_MSGQ_LOWTRMRK: {
ErlDrvSizeT low = ERL_DRV_BUSY_MSGQ_READ_ONLY;
*ptr++ = opt;
erl_drv_busy_msgq_limits(desc->port, &low, NULL);
ival = low > INT_MAX ? INT_MAX : (int) low;
put_int32(ival, ptr);
continue;
}
case INET_LOPT_TCP_SEND_TIMEOUT:
if (desc->stype == SOCK_STREAM) {
*ptr++ = opt;
ival = ((tcp_descriptor*)desc)->send_timeout;
put_int32(ival, ptr);
} else {
TRUNCATE_TO(0,ptr);
}
continue;
case INET_LOPT_TCP_SEND_TIMEOUT_CLOSE:
if (desc->stype == SOCK_STREAM) {
*ptr++ = opt;
ival = ((tcp_descriptor*)desc)->send_timeout_close;
put_int32(ival, ptr);
} else {
TRUNCATE_TO(0,ptr);
}
continue;
case INET_LOPT_TCP_DELAY_SEND:
if (desc->stype == SOCK_STREAM) {
*ptr++ = opt;
ival = !!(((tcp_descriptor*)desc)->tcp_add_flags & TCP_ADDF_DELAY_SEND);
put_int32(ival, ptr);
} else {
TRUNCATE_TO(0,ptr);
}
continue;
#ifdef HAVE_UDP
case INET_LOPT_UDP_READ_PACKETS:
if (desc->stype == SOCK_DGRAM) {
*ptr++ = opt;
ival = ((udp_descriptor*)desc)->read_packets;
put_int32(ival, ptr);
} else {
TRUNCATE_TO(0,ptr);
}
continue;
#endif
#ifdef HAVE_SETNS
case INET_LOPT_NETNS:
if (desc->netns != NULL) {
size_t netns_len;
netns_len = strlen(desc->netns);
*ptr++ = opt;
put_int32(netns_len, ptr);
PLACE_FOR(netns_len, ptr);
memcpy(ptr, desc->netns, netns_len);
ptr += netns_len;
} else {
TRUNCATE_TO(0,ptr);
}
continue;
#endif
case INET_LOPT_TCP_SHOW_ECONNRESET:
if (desc->sprotocol == IPPROTO_TCP) {
tcp_descriptor* tdesc = (tcp_descriptor*) desc;
*ptr++ = opt;
ival = !!(tdesc->tcp_add_flags & TCP_ADDF_SHOW_ECONNRESET);
put_int32(ival, ptr);
} else {
TRUNCATE_TO(0,ptr);
}
continue;
case INET_OPT_PRIORITY:
#ifdef SO_PRIORITY
type = SO_PRIORITY;
break;
#else
*ptr++ = opt;
put_int32(0, ptr);
continue;
#endif
case INET_OPT_TOS:
#if defined(IP_TOS) && defined(IPPROTO_IP)
proto = IPPROTO_IP;
type = IP_TOS;
break;
#else
*ptr++ = opt;
put_int32(0, ptr);
continue;
#endif
case INET_OPT_TCLASS:
#if defined(IPV6_TCLASS) && defined(IPPROTO_IPV6)
proto = IPPROTO_IPV6;
type = IPV6_TCLASS;
break;
#else
TRUNCATE_TO(0,ptr);
continue;
#endif
case INET_OPT_TTL:
#if defined(IP_TTL) && defined(IPPROTO_IP)
proto = IPPROTO_IP;
type = IP_TTL;
break;
#else
TRUNCATE_TO(0,ptr);
continue;
#endif
case INET_OPT_RECVTOS:
#if defined(IP_RECVTOS) && defined(IPPROTO_IP)
proto = IPPROTO_IP;
type = IP_RECVTOS;
break;
#else
TRUNCATE_TO(0,ptr);
continue;
#endif
case INET_OPT_RECVTCLASS:
#if defined(IPV6_RECVTCLASS) && defined(IPPROTO_IPV6)
proto = IPPROTO_IPV6;
type = IPV6_RECVTCLASS;
break;
#else
TRUNCATE_TO(0,ptr);
continue;
#endif
case INET_OPT_RECVTTL:
#if defined(IP_RECVTTL) && defined(IPPROTO_IP)
proto = IPPROTO_IP;
type = IP_RECVTTL;
break;
#else
TRUNCATE_TO(0,ptr);
continue;
#endif
case INET_OPT_REUSEADDR:
type = SO_REUSEADDR;
break;
case INET_OPT_KEEPALIVE:
type = SO_KEEPALIVE;
break;
case INET_OPT_DONTROUTE:
type = SO_DONTROUTE;
break;
case INET_OPT_BROADCAST:
type = SO_BROADCAST;
break;
case INET_OPT_OOBINLINE:
type = SO_OOBINLINE;
break;
case INET_OPT_SNDBUF:
type = SO_SNDBUF;
break;
case INET_OPT_RCVBUF:
type = SO_RCVBUF;
break;
case TCP_OPT_NODELAY:
proto = IPPROTO_TCP;
type = TCP_NODELAY;
break;
case TCP_OPT_NOPUSH:
#if defined(INET_TCP_NOPUSH)
proto = IPPROTO_TCP;
type = INET_TCP_NOPUSH;
break;
#else
*ptr++ = opt;
put_int32(0, ptr);
continue;
#endif
#if defined(HAVE_MULTICAST_SUPPORT) && defined(IPPROTO_IP)
case UDP_OPT_MULTICAST_TTL:
proto = IPPROTO_IP;
type = IP_MULTICAST_TTL;
break;
case UDP_OPT_MULTICAST_LOOP:
proto = IPPROTO_IP;
type = IP_MULTICAST_LOOP;
break;
case UDP_OPT_MULTICAST_IF:
{
int mif = 0;
unsigned int mifSz = sizeof(mif);
*ptr++ = opt;
/* We use up the 4 (value) places for the domain/family
* So we need to allocate 4 more */
PLACE_FOR(4,ptr);
if (desc->sfamily == AF_INET) {
put_int32(INET_AF_INET, ptr);
ptr += 4;
proto = IPPROTO_IP;
type = IP_MULTICAST_IF;
} else if (desc->sfamily == AF_INET6) {
put_int32(INET_AF_INET6, ptr);
ptr += 4;
proto = IPPROTO_IPV6;
type = IPV6_MULTICAST_IF;
} else {
RETURN_ERROR();
}
if (IS_SOCKET_ERROR(sock_getopt(desc->s,
proto, type,
&mif, &mifSz))) {
TRUNCATE_TO(0,ptr);
continue;
}
put_int32(mif, ptr);
}
continue;
case INET_OPT_LINGER:
arg_sz = sizeof(li_val);
sys_memzero((void *) &li_val, sizeof(li_val));
arg_ptr = (char*) &li_val;
type = SO_LINGER;
break;
#endif /* defined(HAVE_MULTICAST_SUPPORT) && defined(IPPROTO_IP) */
case INET_OPT_IPV6_V6ONLY:
#if HAVE_DECL_IPV6_V6ONLY && defined(IPPROTO_IPV6)
proto = IPPROTO_IPV6;
type = IPV6_V6ONLY;
break;
#elif defined(__WIN32__) && defined(HAVE_IN6) && defined(AF_INET6)
/* Fake reading 'true' */
*ptr++ = opt;
put_int32(1, ptr);
ptr += 4;
continue;
#else
TRUNCATE_TO(0,ptr);
continue; /* skip - no result */
#endif
case INET_OPT_RAW:
{
int data_provided;
/* Raw options are icky, handle directly... */
if (len < 13) {
RETURN_ERROR();
}
len -= 13;
proto = get_int32(buf);
buf += 4;
type = get_int32(buf);
buf += 4;
data_provided = (int) *buf++;
arg_sz = get_int32(buf);
if (arg_sz > INET_MAX_OPT_BUFFER) {
RETURN_ERROR();
}
buf += 4;
TRUNCATE_TO(0,ptr);
PLACE_FOR(13 + arg_sz,ptr);
arg_ptr = ptr + 13;
if (data_provided) {
if (len < arg_sz) {
RETURN_ERROR();
}
memcpy(arg_ptr,buf,arg_sz);
buf += arg_sz;
len -= arg_sz;
}
if (IS_SOCKET_ERROR(sock_getopt(desc->s,proto,type,
arg_ptr,&arg_sz))) {
TRUNCATE_TO(0,ptr);
continue;
}
TRUNCATE_TO(arg_sz + 13,ptr);
*ptr++ = opt;
put_int32(proto,ptr);
ptr += 4;
put_int32(type,ptr);
ptr += 4;
put_int32(arg_sz,ptr);
continue;
}
#ifdef SO_BINDTODEVICE
case INET_OPT_BIND_TO_DEVICE:
arg_sz = sizeof(ifname);
TRUNCATE_TO(0,ptr);
PLACE_FOR(5 + arg_sz,ptr);
arg_ptr = ptr + 5;
if (IS_SOCKET_ERROR(sock_getopt(desc->s,SOL_SOCKET,SO_BINDTODEVICE,
arg_ptr,&arg_sz))) {
TRUNCATE_TO(0,ptr);
continue;
}
arg_sz = my_strnlen(arg_ptr, arg_sz);
TRUNCATE_TO(arg_sz + 5,ptr);
*ptr++ = opt;
put_int32(arg_sz,ptr);
ptr += arg_sz;
continue;
#endif
#ifndef __WIN32__
/* Winsock does not have struct cmsghdr */
case INET_OPT_PKTOPTIONS: {
struct cmsghdr *cmsg, *cmsg_top;
SOCKLEN_T cmsg_sz;
union {
/* Ensure alignment */
struct cmsghdr hdr;
/* Room for (IP_TOS | IPV6_TCLASS) + IP_TTL */
char buf[2*CMSG_SPACE(sizeof(int))];
} cmsgbuf;
/* Select between IPv4 or IPv6 PKTOPTIONS
* depending on the socket protocol family
*/
switch (desc->sfamily) {
#if defined(IPPROTO_IP) && defined(IP_PKTOPTIONS)
case AF_INET: {
proto = IPPROTO_IP;
type = IP_PKTOPTIONS;
}
break;
#endif
#if defined(IPPROTO_IPV6) && defined(IPV6_PKTOPTIONS) && defined(AF_INET6)
case AF_INET6: {
proto = IPPROTO_IPV6;
type = IPV6_PKTOPTIONS;
}
break;
#endif
default: {
RETURN_ERROR();
}
} /* switch */
TRUNCATE_TO(0, ptr);
/* Fetch a cmsg buffer from the socket */
cmsg_sz = sizeof(cmsgbuf.buf);
if (IS_SOCKET_ERROR(sock_getopt(desc->s, proto, type,
cmsgbuf.buf, &cmsg_sz))) {
continue;
}
/* Reply with Opt/8, Length/32, [COpt/8, Value/32]*
* i.e opt, total length and then all returned
* cmsg options and values
*/
PLACE_FOR(1+4, ptr);
*ptr++ = opt;
arg_ptr = ptr; /* Where to put total length */
arg_sz = 0; /* Total length */
for (cmsg_top = (struct cmsghdr*)(cmsgbuf.buf + cmsg_sz),
cmsg = (struct cmsghdr*)cmsgbuf.buf;
cmsg < cmsg_top;
cmsg = NXT_CMSG_HDR(cmsg)) {
#define PUT_CMSG_INT32(CMSG_LEVEL, CMSG_TYPE, OPT) \
if ((cmsg->cmsg_level == CMSG_LEVEL) && \
(cmsg->cmsg_type == CMSG_TYPE)) { \
PLACE_FOR(1+4, ptr); \
*ptr++ = OPT; \
put_cmsg_int32(cmsg, ptr); \
arg_sz += 1+4; \
continue; \
}
#if defined(IPPROTO_IP) && defined(IP_TOS)
PUT_CMSG_INT32(IPPROTO_IP, IP_TOS, INET_OPT_TOS);
#endif
#if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS)
PUT_CMSG_INT32(IPPROTO_IPV6, IPV6_TCLASS, INET_OPT_TCLASS);
#endif
#if defined(IPPROTO_IP) && defined(IP_TTL)
PUT_CMSG_INT32(IPPROTO_IP, IP_TTL, INET_OPT_TTL);
#endif
/* BSD uses the RECV* names in CMSG fields */
#if defined(IPPROTO_IP) && defined(IP_RECVTOS)
PUT_CMSG_INT32(IPPROTO_IP, IP_RECVTOS, INET_OPT_TOS);
#endif
#if defined(IPPROTO_IPV6) && defined(IPV6_RECVTCLASS)
PUT_CMSG_INT32(IPPROTO_IPV6, IPV6_RECVTCLASS, INET_OPT_TCLASS);
#endif
#if defined(IPPROTO_IP) && defined(IP_RECVTTL)
PUT_CMSG_INT32(IPPROTO_IP, IP_RECVTTL, INET_OPT_TTL);
#endif
#undef PUT_CMSG_INT32
}
put_int32(arg_sz, arg_ptr); /* Put total length */
continue;
}
#endif /* #ifdef __WIN32__ */
case INET_LOPT_DEBUG:
*ptr++ = opt;
ival = desc->debug;
put_int32(ival, ptr);
continue;
default:
RETURN_ERROR();
}
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_fill_opts -> try get opt (proto %d, type %d)\r\n",
__LINE__, desc->s, driver_caller(desc->port), proto, type) );
/* We have 5 bytes allocated to ptr */
if (IS_SOCKET_ERROR(sock_getopt(desc->s,proto,type,arg_ptr,&arg_sz))) {
int save_errno = sock_errno();
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_fill_opts -> failed get option (%d) %d: "
"\r\n errno: %d\r\n",
__LINE__, desc->s, driver_caller(desc->port),
proto, type, save_errno) );
TRUNCATE_TO(0,ptr);
continue;
}
*ptr++ = opt;
if (arg_ptr == (char*)&ival) {
put_int32(ival, ptr);
}
else {
put_int32(((Uint32) li_val.l_onoff), ptr);
PLACE_FOR(4,ptr);
put_int32(((Uint32) li_val.l_linger), ptr);
}
}
return (dest_used);
#undef PLACE_FOR
#undef TRUNCATE_TO
#undef RETURN_ERROR
}
#ifdef HAVE_SCTP
#define LOAD_PADDRINFO_CNT \
(2*LOAD_ATOM_CNT + LOAD_ASSOC_ID_CNT + LOAD_INET_GET_ADDRESS_CNT + \
4*LOAD_INT_CNT + LOAD_TUPLE_CNT)
static int load_paddrinfo (ErlDrvTermData * spec, int i,
inet_descriptor* desc, struct sctp_paddrinfo* pai)
{
i = LOAD_ATOM (spec, i, am_sctp_paddrinfo);
i = LOAD_ASSOC_ID (spec, i, pai->spinfo_assoc_id);
PUSH_SUPPRESS_ADDRESS_OF_PACKED_MEMBER();
i = load_inet_get_address(spec, i, desc, &pai->spinfo_address);
POP_SUPPRESS_ADDRESS_OF_PACKED_MEMBER();
switch(pai->spinfo_state)
{
case SCTP_ACTIVE:
i = LOAD_ATOM (spec, i, am_active);
break;
case SCTP_INACTIVE:
i = LOAD_ATOM (spec, i, am_inactive);
break;
# if HAVE_DECL_SCTP_UNCONFIRMED
case SCTP_UNCONFIRMED:
i = LOAD_ATOM (spec, i, am_unconfirmed);
break;
# endif
default:
i = LOAD_ATOM (spec, i, am_undefined);
}
i = LOAD_INT (spec, i, pai->spinfo_cwnd);
i = LOAD_INT (spec, i, pai->spinfo_srtt);
i = LOAD_INT (spec, i, pai->spinfo_rto );
i = LOAD_INT (spec, i, pai->spinfo_mtu );
/* Close up the record: */
i = LOAD_TUPLE (spec, i, 8);
return i;
}
/*
** "sctp_fill_opts": Returns {ok, Results}, or an error:
*/
static ErlDrvSSizeT sctp_fill_opts(inet_descriptor* desc,
char* buf, ErlDrvSizeT buflen,
char** dest, ErlDrvSizeT destlen)
{
/* In contrast to the generic "inet_fill_opts", the output here is
represented by tuples/records, which are formed in the "spec":
*/
ErlDrvTermData *spec;
int i = 0;
int length = 0; /* Number of result list entries */
int spec_allocated = PACKET_ERL_DRV_TERM_DATA_LEN;
spec = ALLOC(sizeof(* spec) * spec_allocated);
# define RETURN_ERROR(Spec, Errno) \
do { \
FREE(Spec); \
return (Errno); \
} while(0)
/* Spec is a name parameter */
# define PLACE_FOR(Spec, Index, N) \
do { \
int need; \
if ((Index) > spec_allocated) { \
erts_exit(ERTS_ERROR_EXIT,"Internal error in inet_drv, " \
"miscalculated buffer size"); \
} \
need = (Index) + (N); \
if (need > INET_MAX_OPT_BUFFER/sizeof(ErlDrvTermData)) {\
RETURN_ERROR((Spec), -ENOMEM); \
} \
if (need > spec_allocated) { \
(Spec) = REALLOC((Spec), \
sizeof(* (Spec)) \
* (spec_allocated = need + 20)); \
} \
} while (0)
PLACE_FOR(spec, i, 2*LOAD_ATOM_CNT + LOAD_PORT_CNT);
i = LOAD_ATOM (spec, i, am_inet_reply);
i = LOAD_PORT (spec, i, desc->dport);
i = LOAD_ATOM (spec, i, am_ok);
while (buflen > 0) {
int eopt = *buf; /* "eopt" is 1-byte encoded */
buf ++; buflen --;
switch(eopt)
{
/* Local options allowed for SCTP. For TCP and UDP, the values of
these options are returned via "res" using integer encoding,
but here, we encode them as proper terms the same way as we do
it for all other SCTP options:
*/
case INET_LOPT_BUFFER:
{
PLACE_FOR(spec, i, LOAD_ATOM_CNT + LOAD_INT_CNT + LOAD_TUPLE_CNT);
i = LOAD_ATOM (spec, i, am_buffer);
i = LOAD_INT (spec, i, desc->bufsz);
i = LOAD_TUPLE(spec, i, 2);
break;
}
case INET_LOPT_MODE:
{
PLACE_FOR(spec, i, 2*LOAD_ATOM_CNT + LOAD_TUPLE_CNT);
i = LOAD_ATOM (spec, i, am_mode);
switch (desc->mode)
{
case INET_MODE_LIST :
{ i = LOAD_ATOM (spec, i, am_list); break; }
case INET_MODE_BINARY:
{ i = LOAD_ATOM (spec, i, am_binary); break; }
default: ASSERT (0);
}
i = LOAD_TUPLE (spec, i, 2);
break;
}
case INET_LOPT_ACTIVE:
{
if (desc->active == INET_MULTI)
PLACE_FOR(spec, i, LOAD_ATOM_CNT + LOAD_INT_CNT + LOAD_TUPLE_CNT);
else
PLACE_FOR(spec, i, 2*LOAD_ATOM_CNT + LOAD_TUPLE_CNT);
i = LOAD_ATOM (spec, i, am_active);
switch (desc->active)
{
case INET_ACTIVE :
{ i = LOAD_ATOM (spec, i, am_true); break; }
case INET_PASSIVE:
{ i = LOAD_ATOM (spec, i, am_false); break; }
case INET_ONCE :
{ i = LOAD_ATOM (spec, i, am_once); break; }
case INET_MULTI :
{ i = LOAD_INT(spec, i, desc->active_count); break; }
default: ASSERT (0);
}
i = LOAD_TUPLE (spec, i, 2);
break;
}
#ifdef HAVE_SETNS
case INET_LOPT_NETNS:
if (desc->netns != NULL) {
PLACE_FOR
(spec, i,
LOAD_ATOM_CNT + LOAD_BUF2BINARY_CNT + LOAD_TUPLE_CNT);
i = LOAD_ATOM (spec, i, am_netns);
i = LOAD_BUF2BINARY
(spec, i, desc->netns, strlen(desc->netns));
i = LOAD_TUPLE (spec, i, 2);
break;
}
else
continue; /* Ignore */
#endif
/* SCTP and generic INET options: */
case SCTP_OPT_RTOINFO:
{
struct sctp_rtoinfo rti;
unsigned int sz = sizeof(rti);
if (buflen < ASSOC_ID_LEN) RETURN_ERROR(spec, -EINVAL);
rti.srto_assoc_id = GET_ASSOC_ID(buf);
buf += ASSOC_ID_LEN;
buflen -= ASSOC_ID_LEN;
if (sock_getopt(desc->s, IPPROTO_SCTP, SCTP_RTOINFO,
&rti, &sz) < 0) continue;
/* Fill in the response: */
PLACE_FOR(spec, i,
2*LOAD_ATOM_CNT + LOAD_ASSOC_ID_CNT +
3*LOAD_INT_CNT + 2*LOAD_TUPLE_CNT);
i = LOAD_ATOM (spec, i, am_sctp_rtoinfo);
i = LOAD_ATOM (spec, i, am_sctp_rtoinfo);
i = LOAD_ASSOC_ID (spec, i, rti.srto_assoc_id);
i = LOAD_INT (spec, i, rti.srto_initial);
i = LOAD_INT (spec, i, rti.srto_max);
i = LOAD_INT (spec, i, rti.srto_min);
i = LOAD_TUPLE (spec, i, 5);
i = LOAD_TUPLE (spec, i, 2);
break;
}
case SCTP_OPT_ASSOCINFO:
{
struct sctp_assocparams ap;
unsigned int sz = sizeof(ap);
if (buflen < ASSOC_ID_LEN) RETURN_ERROR(spec, -EINVAL);
ap.sasoc_assoc_id = GET_ASSOC_ID(buf);
buf += ASSOC_ID_LEN;
buflen -= ASSOC_ID_LEN;
if (sock_getopt(desc->s, IPPROTO_SCTP, SCTP_ASSOCINFO,
&ap, &sz) < 0) continue;
/* Fill in the response: */
PLACE_FOR(spec, i,
2*LOAD_ATOM_CNT + LOAD_ASSOC_ID_CNT +
5*LOAD_INT_CNT + 2*LOAD_TUPLE_CNT);
i = LOAD_ATOM (spec, i, am_sctp_associnfo);
i = LOAD_ATOM (spec, i, am_sctp_assocparams);
i = LOAD_ASSOC_ID (spec, i, ap.sasoc_assoc_id);
i = LOAD_INT (spec, i, ap.sasoc_asocmaxrxt);
i = LOAD_INT (spec, i, ap.sasoc_number_peer_destinations);
i = LOAD_INT (spec, i, ap.sasoc_peer_rwnd);
i = LOAD_INT (spec, i, ap.sasoc_local_rwnd);
i = LOAD_INT (spec, i, ap.sasoc_cookie_life);
i = LOAD_TUPLE (spec, i, 7);
i = LOAD_TUPLE (spec, i, 2);
break;
}
case SCTP_OPT_INITMSG:
{
struct sctp_initmsg im;
unsigned int sz = sizeof(im);
if (sock_getopt(desc->s, IPPROTO_SCTP, SCTP_INITMSG,
&im, &sz) < 0) continue;
/* Fill in the response: */
PLACE_FOR(spec, i,
2*LOAD_ATOM_CNT +
4*LOAD_INT_CNT + 2*LOAD_TUPLE_CNT);
i = LOAD_ATOM (spec, i, am_sctp_initmsg);
i = LOAD_ATOM (spec, i, am_sctp_initmsg);
i = LOAD_INT (spec, i, im.sinit_num_ostreams);
i = LOAD_INT (spec, i, im.sinit_max_instreams);
i = LOAD_INT (spec, i, im.sinit_max_attempts);
i = LOAD_INT (spec, i, im.sinit_max_init_timeo);
i = LOAD_TUPLE (spec, i, 5);
i = LOAD_TUPLE (spec, i, 2);
break;
}
/* The following option returns a tuple {bool, int}: */
case INET_OPT_LINGER:
{
struct linger lg;
unsigned int sz = sizeof(lg);
if (sock_getopt(desc->s, SOL_SOCKET, SO_LINGER,
&lg, &sz) < 0) continue;
/* Fill in the response: */
PLACE_FOR(spec, i,
LOAD_ATOM_CNT + LOAD_BOOL_CNT +
LOAD_INT_CNT + 2*LOAD_TUPLE_CNT);
i = LOAD_ATOM (spec, i, am_linger);
i = LOAD_BOOL (spec, i, lg.l_onoff);
i = LOAD_INT (spec, i, lg.l_linger);
i = LOAD_TUPLE (spec, i, 2);
i = LOAD_TUPLE (spec, i, 2);
break;
}
#ifdef SO_BINDTODEVICE
/* The following option returns a binary: */
case INET_OPT_BIND_TO_DEVICE: {
char ifname[IFNAMSIZ];
unsigned int sz = sizeof(ifname);
if (sock_getopt(desc->s, SOL_SOCKET, SO_BINDTODEVICE,
&ifname, &sz) < 0) continue;
/* Fill in the response: */
PLACE_FOR(spec, i,
LOAD_ATOM_CNT + LOAD_BUF2BINARY_CNT + LOAD_TUPLE_CNT);
i = LOAD_ATOM (spec, i, am_bind_to_device);
i = LOAD_BUF2BINARY(spec, i, ifname, my_strnlen(ifname, sz));
i = LOAD_TUPLE (spec, i, 2);
break;
}
#endif
/* The following options just return an integer value: */
case INET_OPT_RCVBUF :
case INET_OPT_SNDBUF :
case INET_OPT_REUSEADDR:
case INET_OPT_DONTROUTE:
case INET_OPT_PRIORITY :
case INET_OPT_TOS :
case INET_OPT_TCLASS :
case INET_OPT_TTL :
case INET_OPT_IPV6_V6ONLY:
case SCTP_OPT_AUTOCLOSE:
case SCTP_OPT_MAXSEG :
/* The following options return true or false: */
case SCTP_OPT_NODELAY :
case SCTP_OPT_DISABLE_FRAGMENTS:
case SCTP_OPT_I_WANT_MAPPED_V4_ADDR:
case INET_OPT_RECVTOS :
case INET_OPT_RECVTCLASS :
case INET_OPT_RECVTTL :
{
int res = 0;
unsigned int sz = sizeof(res);
int proto = 0, type = 0, is_int = 0;
ErlDrvTermData tag = am_sctp_error;
switch(eopt)
{
case INET_OPT_RCVBUF :
{
proto = SOL_SOCKET;
type = SO_RCVBUF;
is_int = 1;
tag = am_recbuf;
break;
}
case INET_OPT_SNDBUF :
{
proto = SOL_SOCKET;
type = SO_SNDBUF;
is_int = 1;
tag = am_sndbuf;
break;
}
case INET_OPT_REUSEADDR:
{
proto = SOL_SOCKET;
type = SO_REUSEADDR;
is_int = 0;
tag = am_reuseaddr;
break;
}
case INET_OPT_DONTROUTE:
{
proto = SOL_SOCKET;
type = SO_DONTROUTE;
is_int = 0;
tag = am_dontroute;
break;
}
case INET_OPT_PRIORITY:
{
# if defined(SO_PRIORITY)
proto = SOL_SOCKET;
type = SO_PRIORITY;
is_int = 1;
tag = am_priority;
break;
# else
/* Not supported -- ignore */
continue;
# endif
}
case INET_OPT_TOS:
{
# if defined(IP_TOS) && defined(IPPROTO_IP)
proto = IPPROTO_IP;
type = IP_TOS;
is_int = 1;
tag = am_tos;
break;
# else
/* Not supported -- ignore */
continue;
# endif
}
case INET_OPT_TCLASS:
{
# if defined(IPV6_TCLASS) && defined(IPPROTO_IPV6)
proto = IPPROTO_IPV6;
type = IPV6_TCLASS;
is_int = 1;
tag = am_tclass;
break;
# else
/* Not supported -- ignore */
continue;
# endif
}
case INET_OPT_TTL:
{
# if defined(IP_TTL) && defined(IPPROTO_IP)
proto = IPPROTO_IP;
type = IP_TTL;
is_int = 1;
tag = am_ttl;
break;
# else
/* Not supported -- ignore */
continue;
# endif
}
case INET_OPT_RECVTOS:
{
# if defined(IP_RECVTOS) && defined(IPPROTO_IP)
proto = IPPROTO_IP;
type = IP_RECVTOS;
is_int = 0;
tag = am_recvtos;
break;
# else
/* Not supported -- ignore */
continue;
# endif
}
case INET_OPT_RECVTCLASS:
{
# if defined(IPV6_RECVTCLASS) && defined(IPPROTO_IPV6)
proto = IPPROTO_IPV6;
type = IPV6_RECVTCLASS;
is_int = 0;
tag = am_recvtclass;
break;
# else
/* Not supported -- ignore */
continue;
# endif
}
case INET_OPT_RECVTTL:
{
# if defined(IP_RECVTTL) && defined(IPPROTO_IP)
proto = IPPROTO_IP;
type = IP_RECVTTL;
is_int = 0;
tag = am_recvttl;
break;
# else
/* Not supported -- ignore */
continue;
# endif
}
case INET_OPT_IPV6_V6ONLY:
# if HAVE_DECL_IPV6_V6ONLY && defined(IPPROTO_IPV6)
{
proto = IPPROTO_IPV6;
type = IPV6_V6ONLY;
tag = am_ipv6_v6only;
break;
}
# elif defined(__WIN32__) && defined(HAVE_IN6) && defined(AF_INET6)
# error Here is a fix for Win IPv6 SCTP needed
# else
/* Not supported -- ignore */
continue;
# endif
case SCTP_OPT_AUTOCLOSE:
{
proto = IPPROTO_SCTP;
type = SCTP_AUTOCLOSE;
is_int = 1;
tag = am_sctp_autoclose;
break;
}
case SCTP_OPT_MAXSEG :
{
proto = IPPROTO_SCTP;
type = SCTP_MAXSEG;
is_int = 1;
tag = am_sctp_maxseg;
break;
}
case SCTP_OPT_NODELAY :
{
proto = IPPROTO_SCTP;
type = SCTP_NODELAY;
is_int = 0;
tag = am_sctp_nodelay;
break;
}
case SCTP_OPT_DISABLE_FRAGMENTS:
{
proto = IPPROTO_SCTP;
type = SCTP_DISABLE_FRAGMENTS;
is_int = 0;
tag = am_sctp_disable_fragments;
break;
}
case SCTP_OPT_I_WANT_MAPPED_V4_ADDR:
{
proto = IPPROTO_SCTP;
type = SCTP_I_WANT_MAPPED_V4_ADDR;
is_int = 0;
tag = am_sctp_i_want_mapped_v4_addr;
break;
}
default: ASSERT(0);
}
if (sock_getopt (desc->s, proto, type, &res, &sz) < 0) continue;
/* Form the result: */
PLACE_FOR(spec, i, LOAD_ATOM_CNT +
(is_int ? LOAD_INT_CNT : LOAD_BOOL_CNT) +
LOAD_TUPLE_CNT);
i = LOAD_ATOM (spec, i, tag);
if (is_int)
i = LOAD_INT (spec, i, res);
else
i = LOAD_BOOL (spec, i, res);
i = LOAD_TUPLE (spec, i, 2);
break;
}
case SCTP_OPT_PRIMARY_ADDR:
case SCTP_OPT_SET_PEER_PRIMARY_ADDR:
{
/* These 2 options use completely isomorphic data structures: */
struct sctp_setpeerprim sp;
unsigned int sz = sizeof(sp);
if (buflen < ASSOC_ID_LEN) RETURN_ERROR(spec, -EINVAL);
sp.sspp_assoc_id = GET_ASSOC_ID(buf);
buf += ASSOC_ID_LEN;
buflen -= ASSOC_ID_LEN;
if (sock_getopt(desc->s, IPPROTO_SCTP,
(eopt == SCTP_OPT_PRIMARY_ADDR) ?
SCTP_PRIMARY_ADDR : SCTP_SET_PEER_PRIMARY_ADDR,
&sp, &sz) < 0) continue;
/* Fill in the response: */
PLACE_FOR(spec, i,
2*LOAD_ATOM_CNT + LOAD_ASSOC_ID_CNT +
LOAD_INET_GET_ADDRESS_CNT + 2*LOAD_TUPLE_CNT);
switch (eopt) {
case SCTP_OPT_PRIMARY_ADDR:
i = LOAD_ATOM(spec, i, am_sctp_primary_addr);
i = LOAD_ATOM(spec, i, am_sctp_prim);
break;
case SCTP_OPT_SET_PEER_PRIMARY_ADDR:
i = LOAD_ATOM(spec, i, am_sctp_set_peer_primary_addr);
i = LOAD_ATOM(spec, i, am_sctp_setpeerprim);
break;
default:
ASSERT(0);
}
i = LOAD_ASSOC_ID (spec, i, sp.sspp_assoc_id);
PUSH_SUPPRESS_ADDRESS_OF_PACKED_MEMBER();
i = load_inet_get_address(spec, i, desc, &sp.sspp_addr);
POP_SUPPRESS_ADDRESS_OF_PACKED_MEMBER();
i = LOAD_TUPLE (spec, i, 3);
i = LOAD_TUPLE (spec, i, 2);
break;
}
case SCTP_OPT_ADAPTATION_LAYER:
{
struct sctp_setadaptation ad;
unsigned int sz = sizeof (ad);
if (sock_getopt(desc->s, IPPROTO_SCTP, SCTP_ADAPTATION_LAYER,
&ad, &sz) < 0) continue;
/* Fill in the response: */
PLACE_FOR(spec, i,
2*LOAD_ATOM_CNT + LOAD_INT_CNT + 2*LOAD_TUPLE_CNT);
i = LOAD_ATOM (spec, i, am_sctp_adaptation_layer);
i = LOAD_ATOM (spec, i, am_sctp_setadaptation);
i = LOAD_INT (spec, i, sock_ntohl(ad.ssb_adaptation_ind));
i = LOAD_TUPLE (spec, i, 2);
i = LOAD_TUPLE (spec, i, 2);
break;
}
case SCTP_OPT_PEER_ADDR_PARAMS:
{
struct sctp_paddrparams ap;
unsigned int sz = sizeof(ap);
int n;
char *before, *xerror;
ErlDrvSizeT alen;
if (buflen < ASSOC_ID_LEN) RETURN_ERROR(spec, -EINVAL);
ap.spp_assoc_id = GET_ASSOC_ID(buf);
buf += ASSOC_ID_LEN;
buflen -= ASSOC_ID_LEN;
alen = buflen;
before = buf;
xerror =
inet_set_faddress
(desc->sfamily, (inet_address*) (&ap.spp_address),
&buf, &alen);
if (xerror != NULL) {
#ifdef EAFNOSUPPORT
if (xerror == str_eafnosupport) {
RETURN_ERROR(spec, -EAFNOSUPPORT);
}
#else
RETURN_ERROR(spec, -EINVAL);
#endif
}
buflen -= buf - before;
if (sock_getopt(desc->s, IPPROTO_SCTP, SCTP_PEER_ADDR_PARAMS,
&ap, &sz) < 0) continue;
/* Fill in the response: */
PLACE_FOR(spec, i,
2*LOAD_ATOM_CNT + LOAD_ASSOC_ID_CNT +
LOAD_INET_GET_ADDRESS_CNT + 4*LOAD_INT_CNT);
i = LOAD_ATOM (spec, i, am_sctp_peer_addr_params);
i = LOAD_ATOM (spec, i, am_sctp_paddrparams);
i = LOAD_ASSOC_ID (spec, i, ap.spp_assoc_id);
PUSH_SUPPRESS_ADDRESS_OF_PACKED_MEMBER();
i = load_inet_get_address(spec, i, desc, &ap.spp_address);
POP_SUPPRESS_ADDRESS_OF_PACKED_MEMBER();
i = LOAD_INT (spec, i, ap.spp_hbinterval);
i = LOAD_INT (spec, i, ap.spp_pathmaxrxt);
/* The following fields are not supported in SOLARIS10,
** so put 0s for "spp_pathmtu", "spp_sackdelay",
** and empty list for "spp_flags":
*/
# ifdef HAVE_STRUCT_SCTP_PADDRPARAMS_SPP_PATHMTU
i = LOAD_INT (spec, i, ap.spp_pathmtu);
# else
i = LOAD_INT (spec, i, 0);
# endif
# ifdef HAVE_STRUCT_SCTP_PADDRPARAMS_SPP_SACKDELAY
i = LOAD_INT (spec, i, ap.spp_sackdelay);
# else
i = LOAD_INT (spec, i, 0);
# endif
n = 0;
# ifdef HAVE_STRUCT_SCTP_PADDRPARAMS_SPP_FLAGS
PLACE_FOR(spec, i, 7*LOAD_ATOM_CNT);
/* Now Flags, as a list: */
if (ap.spp_flags & SPP_HB_ENABLE)
{ i = LOAD_ATOM (spec, i, am_hb_enable); n++; }
if (ap.spp_flags & SPP_HB_DISABLE)
{ i = LOAD_ATOM (spec, i, am_hb_disable); n++; }
if (ap.spp_flags & SPP_HB_DEMAND)
{ i = LOAD_ATOM (spec, i, am_hb_demand); n++; }
if (ap.spp_flags & SPP_PMTUD_ENABLE)
{ i = LOAD_ATOM (spec, i, am_pmtud_enable); n++; }
if (ap.spp_flags & SPP_PMTUD_DISABLE)
{ i = LOAD_ATOM (spec, i, am_pmtud_disable); n++; }
# ifdef HAVE_STRUCT_SCTP_PADDRPARAMS_SPP_SACKDELAY
/* SPP_SACKDELAY_* not in FreeBSD 7.1 */
if (ap.spp_flags & SPP_SACKDELAY_ENABLE)
{ i = LOAD_ATOM (spec, i, am_sackdelay_enable); n++; }
if (ap.spp_flags & SPP_SACKDELAY_DISABLE)
{ i = LOAD_ATOM (spec, i, am_sackdelay_disable); n++; }
# endif
# endif
PLACE_FOR(spec, i,
LOAD_NIL_CNT + LOAD_LIST_CNT + 2*LOAD_TUPLE_CNT);
/* Close up the Flags list: */
i = LOAD_NIL (spec, i);
i = LOAD_LIST (spec, i, n+1);
/* Close up the record: */
i = LOAD_TUPLE (spec, i, 8);
/* Close up the result tuple: */
i = LOAD_TUPLE (spec, i, 2);
break;
}
case SCTP_OPT_DEFAULT_SEND_PARAM:
{
struct sctp_sndrcvinfo sri;
unsigned int sz = sizeof(sri);
if (buflen < ASSOC_ID_LEN) RETURN_ERROR(spec, -EINVAL);
sri.sinfo_assoc_id = GET_ASSOC_ID(buf);
buf += ASSOC_ID_LEN;
buflen -= ASSOC_ID_LEN;
if (sock_getopt(desc->s, IPPROTO_SCTP, SCTP_DEFAULT_SEND_PARAM,
&sri, &sz) < 0) continue;
/* Fill in the response: */
PLACE_FOR(spec, i, LOAD_ATOM_CNT +
SCTP_PARSE_SNDRCVINFO_CNT + LOAD_TUPLE_CNT);
i = LOAD_ATOM(spec, i, am_sctp_default_send_param);
i = sctp_parse_sndrcvinfo(spec, i, &sri);
i = LOAD_TUPLE(spec, i, 2);
break;
}
case SCTP_OPT_EVENTS:
{
struct sctp_event_subscribe evs;
unsigned int sz = sizeof(evs);
if (sock_getopt(desc->s, IPPROTO_SCTP, SCTP_EVENTS,
&evs, &sz) < 0) continue;
/* Fill in the response: */
PLACE_FOR(spec, i,
2*LOAD_ATOM_CNT + 9*LOAD_BOOL_CNT + 2*LOAD_TUPLE_CNT);
i = LOAD_ATOM (spec, i, am_sctp_events);
i = LOAD_ATOM (spec, i, am_sctp_event_subscribe);
i = LOAD_BOOL (spec, i, evs.sctp_data_io_event);
i = LOAD_BOOL (spec, i, evs.sctp_association_event);
i = LOAD_BOOL (spec, i, evs.sctp_address_event);
i = LOAD_BOOL (spec, i, evs.sctp_send_failure_event);
i = LOAD_BOOL (spec, i, evs.sctp_peer_error_event);
i = LOAD_BOOL (spec, i, evs.sctp_shutdown_event);
i = LOAD_BOOL (spec, i, evs.sctp_partial_delivery_event);
i = LOAD_BOOL (spec, i, evs.sctp_adaptation_layer_event);
i = LOAD_BOOL (spec, i, 0);/* NB: sctp_authentication_event
* is not yet supported in Linux
*/
i = LOAD_TUPLE (spec, i, 10);
i = LOAD_TUPLE (spec, i, 2);
break;
}
/* The following option is not available on:
* Solaris 10 or NetBSD or ... */
#if defined(HAVE_DECL_SCTP_DELAYED_ACK_TIME) && defined(SCTP_ASSOC_VALUE_ASSOC_ID)
case SCTP_OPT_DELAYED_ACK_TIME:
{
struct sctp_assoc_value av;
unsigned int sz = sizeof(av);
if (buflen < ASSOC_ID_LEN) RETURN_ERROR(spec, -EINVAL);
av.assoc_id = GET_ASSOC_ID(buf);
buf += ASSOC_ID_LEN;
buflen -= ASSOC_ID_LEN;
if (sock_getopt(desc->s, IPPROTO_SCTP, SCTP_DELAYED_ACK_TIME,
&av, &sz) < 0) continue;
/* Fill in the response: */
PLACE_FOR(spec, i, 2*LOAD_ATOM_CNT + LOAD_ASSOC_ID_CNT +
LOAD_INT_CNT + 2*LOAD_TUPLE_CNT);
i = LOAD_ATOM (spec, i, am_sctp_delayed_ack_time);
i = LOAD_ATOM (spec, i, am_sctp_assoc_value);
i = LOAD_ASSOC_ID (spec, i, av.assoc_id);
i = LOAD_INT (spec, i, av.assoc_value);
i = LOAD_TUPLE (spec, i, 3);
i = LOAD_TUPLE (spec, i, 2);
break;
}
# endif
case SCTP_OPT_STATUS:
{
struct sctp_status st;
unsigned int sz = sizeof(st);
if (buflen < ASSOC_ID_LEN) RETURN_ERROR(spec, -EINVAL);
st.sstat_assoc_id = GET_ASSOC_ID(buf);
buf += ASSOC_ID_LEN;
buflen -= ASSOC_ID_LEN;
if (sock_getopt(desc->s, IPPROTO_SCTP, SCTP_STATUS,
&st, &sz) < 0) continue;
/* Fill in the response: */
PLACE_FOR(spec, i, 3*LOAD_ATOM_CNT + LOAD_ASSOC_ID_CNT +
6*LOAD_INT_CNT + LOAD_PADDRINFO_CNT +
2*LOAD_TUPLE_CNT);
i = LOAD_ATOM (spec, i, am_sctp_status);
i = LOAD_ATOM (spec, i, am_sctp_status);
i = LOAD_ASSOC_ID (spec, i, st.sstat_assoc_id);
switch(st.sstat_state)
{
/* SCTP_EMPTY is not supported on SOLARIS10: */
# if HAVE_DECL_SCTP_EMPTY
case SCTP_EMPTY:
i = LOAD_ATOM (spec, i, am_empty);
break;
# endif
case SCTP_CLOSED:
i = LOAD_ATOM (spec, i, am_closed);
break;
# if HAVE_DECL_SCTP_BOUND
case SCTP_BOUND:
i = LOAD_ATOM (spec, i, am_bound);
break;
# endif
# if HAVE_DECL_SCTP_LISTEN
case SCTP_LISTEN:
i = LOAD_ATOM (spec, i, am_listen);
break;
# endif
case SCTP_COOKIE_WAIT:
i = LOAD_ATOM (spec, i, am_cookie_wait);
break;
case SCTP_COOKIE_ECHOED:
i = LOAD_ATOM (spec, i, am_cookie_echoed);
break;
case SCTP_ESTABLISHED:
i = LOAD_ATOM (spec, i, am_established);
break;
case SCTP_SHUTDOWN_PENDING:
i = LOAD_ATOM (spec, i, am_shutdown_pending);
break;
case SCTP_SHUTDOWN_SENT:
i = LOAD_ATOM (spec, i, am_shutdown_sent);
break;
case SCTP_SHUTDOWN_RECEIVED:
i = LOAD_ATOM (spec, i, am_shutdown_received);
break;
case SCTP_SHUTDOWN_ACK_SENT:
i = LOAD_ATOM (spec, i, am_shutdown_ack_sent);
break;
default:
i = LOAD_ATOM (spec, i, am_undefined);
break;
}
i = LOAD_INT (spec, i, st.sstat_rwnd);
i = LOAD_INT (spec, i, st.sstat_unackdata);
i = LOAD_INT (spec, i, st.sstat_penddata);
i = LOAD_INT (spec, i, st.sstat_instrms);
i = LOAD_INT (spec, i, st.sstat_outstrms);
i = LOAD_INT (spec, i, st.sstat_fragmentation_point);
i = load_paddrinfo (spec, i, desc, &st.sstat_primary);
/* Close up the record: */
i = LOAD_TUPLE (spec, i, 10);
/* Close up the result tuple: */
i = LOAD_TUPLE (spec, i, 2);
break;
}
case SCTP_OPT_GET_PEER_ADDR_INFO:
{
struct sctp_paddrinfo pai;
unsigned int sz = sizeof(pai);
char *before, *xerror;
ErlDrvSizeT alen;
if (buflen < ASSOC_ID_LEN) RETURN_ERROR(spec, -EINVAL);
pai.spinfo_assoc_id = GET_ASSOC_ID(buf);
buf += ASSOC_ID_LEN;
buflen -= ASSOC_ID_LEN;
alen = buflen;
before = buf;
xerror =
inet_set_faddress
(desc->sfamily, (inet_address*) (&pai.spinfo_address),
&buf, &alen);
if (xerror != NULL) {
#ifdef EAFNOSUPPORT
if (xerror == str_eafnosupport) {
RETURN_ERROR(spec, -EAFNOSUPPORT);
}
#else
RETURN_ERROR(spec, -EINVAL);
#endif
}
buflen -= buf - before;
if (sock_getopt(desc->s, IPPROTO_SCTP, SCTP_GET_PEER_ADDR_INFO,
&pai, &sz) < 0) continue;
/* Fill in the response: */
PLACE_FOR(spec, i,
LOAD_ATOM_CNT + LOAD_PADDRINFO_CNT + LOAD_TUPLE_CNT);
i = LOAD_ATOM (spec, i, am_sctp_get_peer_addr_info);
i = load_paddrinfo (spec, i, desc, &pai);
i = LOAD_TUPLE (spec, i, 2);
break;
}
default:
RETURN_ERROR(spec, -EINVAL); /* No more valid options */
}
/* If we get here one result has been successfully loaded */
length ++;
}
if (buflen != 0) RETURN_ERROR(spec, -EINVAL); /* Optparam mismatch */
PLACE_FOR(spec, i, LOAD_NIL_CNT + LOAD_LIST_CNT + 2*LOAD_TUPLE_CNT);
/* If we get here, we have "length" options: */
i = LOAD_NIL (spec, i);
i = LOAD_LIST (spec, i, length+1);
/* Close up the {ok, List} response: */
i = LOAD_TUPLE(spec, i, 2);
/* Close up the {inet_reply, S, {ok, List}} response: */
i = LOAD_TUPLE(spec, i, 3);
/* Now, convert "spec" into the returnable term: */
erl_drv_send_term(desc->dport, driver_caller(desc->port), spec, i);
FREE(spec);
(*dest)[0] = INET_REP;
return 1; /* Response length */
# undef PLACE_FOR
# undef RETURN_ERROR
}
#endif
/* fill statistics reply, op codes from src and result in dest
** dst area must be a least 5*len + 1 bytes
*/
static ErlDrvSSizeT inet_fill_stat(inet_descriptor* desc,
char* src, ErlDrvSizeT len, char* dst)
{
unsigned long val;
int op;
char* dst_start = dst;
*dst++ = INET_REP_OK; /* put reply code */
while (len--) {
op = *src++;
*dst++ = op; /* copy op code */
switch(op) {
case INET_STAT_RECV_CNT:
val = desc->recv_cnt;
break;
case INET_STAT_RECV_MAX:
val = (unsigned long) desc->recv_max;
break;
case INET_STAT_RECV_AVG:
val = (unsigned long) desc->recv_avg;
break;
case INET_STAT_RECV_DVI:
val = (unsigned long) fabs(desc->recv_dvi);
break;
case INET_STAT_SEND_CNT:
val = desc->send_cnt;
break;
case INET_STAT_SEND_MAX:
val = desc->send_max;
break;
case INET_STAT_SEND_AVG:
val = (unsigned long) desc->send_avg;
break;
case INET_STAT_SEND_PND:
val = (unsigned long) driver_sizeq(desc->port);
break;
case INET_STAT_RECV_OCT:
#ifdef ARCH_64
put_int64(desc->recv_oct, dst); /* write it all */
#else
put_int32(desc->recv_oct[1], dst); /* write high 32bit */
put_int32(desc->recv_oct[0], dst+4); /* write low 32bit */
#endif
dst += 8;
continue;
case INET_STAT_SEND_OCT:
#ifdef ARCH_64
put_int64(desc->send_oct, dst); /* write it all */
#else
put_int32(desc->send_oct[1], dst); /* write high 32bit */
put_int32(desc->send_oct[0], dst+4); /* write low 32bit */
#endif
dst += 8;
continue;
default: return -1; /* invalid argument */
}
put_int32(val, dst); /* write 32bit value */
dst += 4;
}
return dst - dst_start; /* actual length */
}
static void
send_empty_out_q_msgs(inet_descriptor* desc)
{
ErlDrvTermData msg[6];
int msg_len = 0;
if(NO_SUBSCRIBERS(&desc->empty_out_q_subs))
return;
msg_len = LOAD_ATOM(msg, msg_len, am_empty_out_q);
msg_len = LOAD_PORT(msg, msg_len, desc->dport);
msg_len = LOAD_TUPLE(msg, msg_len, 2);
ASSERT(msg_len == sizeof(msg)/sizeof(*msg));
send_to_subscribers(desc->dport,
&desc->empty_out_q_subs,
1,
msg,
msg_len);
}
/* subscribe and fill subscription reply, op codes from src and
** result in dest dst area must be a least 5*len + 1 bytes
*/
static ErlDrvSSizeT inet_subscribe(inet_descriptor* desc,
char* src, ErlDrvSizeT len, char* dst)
{
unsigned long val;
int op;
char* dst_start = dst;
*dst++ = INET_REP_OK; /* put reply code */
while (len--) {
op = *src++;
*dst++ = op; /* copy op code */
switch(op) {
case INET_SUBS_EMPTY_OUT_Q:
val = driver_sizeq(desc->port);
if(val > 0)
if(!save_subscriber(&desc->empty_out_q_subs,
driver_caller(desc->port)))
return 0;
break;
default: return -1; /* invalid argument */
}
put_int32(val, dst); /* write 32bit value */
dst += 4;
}
return dst - dst_start; /* actual length */
}
/* Terminate socket */
static void inet_stop(inet_descriptor* desc)
{
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR "] "
"inet_stop -> entry\r\n",
__LINE__, desc->s) );
erl_inet_close(desc);
#ifdef HAVE_SETNS
if (desc->netns != NULL)
FREE(desc->netns);
#endif
FREE(desc);
}
static void inet_emergency_close(ErlDrvData data)
{
/* valid for any (UDP, TCP or SCTP) descriptor */
tcp_descriptor* tcp_desc = (tcp_descriptor*)data;
inet_descriptor* desc = INETP(tcp_desc);
DEBUGF(("inet_emergency_close(%p) {s=%d\r\n",
desc->port, desc->s));
if (desc->s != INVALID_SOCKET) {
sock_close(desc->s);
}
}
static void set_default_msgq_limits(ErlDrvPort port)
{
ErlDrvSizeT q_high = INET_HIGH_MSGQ_WATERMARK;
ErlDrvSizeT q_low = INET_LOW_MSGQ_WATERMARK;
if (q_low < ERL_DRV_BUSY_MSGQ_LIM_MIN)
q_low = ERL_DRV_BUSY_MSGQ_LIM_MIN;
else if (q_low > ERL_DRV_BUSY_MSGQ_LIM_MAX)
q_low = ERL_DRV_BUSY_MSGQ_LIM_MAX;
if (q_high < ERL_DRV_BUSY_MSGQ_LIM_MIN)
q_high = ERL_DRV_BUSY_MSGQ_LIM_MIN;
else if (q_high > ERL_DRV_BUSY_MSGQ_LIM_MAX)
q_high = ERL_DRV_BUSY_MSGQ_LIM_MAX;
erl_drv_busy_msgq_limits(port, &q_low, &q_high);
}
/* Allocate descriptor */
static ErlDrvData inet_start(ErlDrvPort port, int size, int protocol)
{
inet_descriptor* desc;
if ((desc = (inet_descriptor*) ALLOC(size)) == NULL)
return NULL;
desc->s = INVALID_SOCKET;
desc->event = INVALID_EVENT;
desc->event_mask = 0;
#ifdef __WIN32__
desc->forced_events = 0;
desc->err = 0;
desc->send_would_block = 0;
#endif
desc->port = port;
desc->dport = driver_mk_port(port);
desc->state = INET_STATE_CLOSED;
desc->prebound = 0;
desc->bufsz = INET_DEF_BUFFER;
desc->hsz = 0; /* list header size */
desc->htype = TCP_PB_RAW; /* default packet type */
desc->psize = 0; /* no size check */
desc->stype = -1; /* bad stype */
desc->sfamily = -1;
desc->sprotocol = protocol;
desc->mode = INET_MODE_LIST; /* list mode */
desc->exitf = 1; /* exit port when close on active
socket */
desc->deliver = INET_DELIVER_TERM; /* standard term format */
desc->active = INET_PASSIVE; /* start passive */
desc->active_count = 0;
desc->delimiter = '\n'; /* line delimiting char */
desc->oph = NULL;
desc->opt = NULL;
desc->op_ref = 0;
desc->peer_ptr = NULL;
desc->name_ptr = NULL;
#ifdef ARCH_64
desc->recv_oct = 0;
#else
desc->recv_oct[0] = desc->recv_oct[1] = 0;
#endif
desc->recv_cnt = 0;
desc->recv_max = 0;
desc->recv_avg = 0.0;
desc->recv_dvi = 0.0;
#ifdef ARCH_64
desc->send_oct = 0;
#else
desc->send_oct[0] = desc->send_oct[1] = 0;
#endif
desc->send_cnt = 0;
desc->send_max = 0;
desc->send_avg = 0.0;
desc->empty_out_q_subs.subscriber = NO_PROCESS;
desc->empty_out_q_subs.next = NULL;
sys_memzero((char *)&desc->remote,sizeof(desc->remote));
desc->flags = 0;
#ifdef HAVE_SETNS
desc->netns = NULL;
#endif
desc->recv_cmsgflags = 0;
desc->debug = DDBG_DEFAULT;
return (ErlDrvData)desc;
}
/* MAXHOSTNAMELEN could be 64 or 255 depending
on the platform. Instead, use INET_MAXHOSTNAMELEN
which is always 255 across all platforms */
#define INET_MAXHOSTNAMELEN 255
/*
** common TCP/UDP/SCTP control command
*/
static ErlDrvSSizeT inet_ctl(inet_descriptor* desc, int cmd, char* buf,
ErlDrvSizeT len, char** rbuf, ErlDrvSizeT rsize)
{
switch (cmd) {
case INET_REQ_GETSTAT: {
char* dst;
ErlDrvSizeT i;
int dstlen = 1; /* Reply code */
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_ctl -> GETSTAT\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
for (i = 0; i < len; i++) {
switch(buf[i]) {
case INET_STAT_SEND_OCT: dstlen += 9; break;
case INET_STAT_RECV_OCT: dstlen += 9; break;
default: dstlen += 5; break;
}
}
if (dstlen > INET_MAX_OPT_BUFFER) /* sanity check */
return 0;
if (dstlen > rsize) {
if ((dst = (char*) ALLOC(dstlen)) == NULL)
return 0;
*rbuf = dst; /* call will free this buffer */
}
else
dst = *rbuf; /* ok we fit in buffer given */
return inet_fill_stat(desc, buf, len, dst);
}
case INET_REQ_SUBSCRIBE: {
char* dst;
int dstlen = 1 /* Reply code */ + len*5;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_ctl -> SUBSCRIBE\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
if (dstlen > INET_MAX_OPT_BUFFER) /* sanity check */
return 0;
if (dstlen > rsize) {
if ((dst = (char*) ALLOC(dstlen)) == NULL)
return 0;
*rbuf = dst; /* call will free this buffer */
}
else
dst = *rbuf; /* ok we fit in buffer given */
return inet_subscribe(desc, buf, len, dst);
}
case INET_REQ_GETOPTS: { /* get options */
ErlDrvSSizeT replen;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"inet_ctl -> GETOPTS\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
#ifdef HAVE_SCTP
if (IS_SCTP(desc))
{
if ((replen = sctp_fill_opts(desc, buf, len, rbuf, rsize)) < 0)
return ctl_error(-replen, rbuf, rsize);
} else
#endif
if ((replen = inet_fill_opts(desc, buf, len, rbuf, rsize)) < 0) {
return ctl_error(EINVAL, rbuf, rsize);
}
return replen;
}
case INET_REQ_GETIFLIST: {
DDBG(desc,
("INET-DRV-DBG[%d][%T] inet_ctl -> GETIFLIST\r\n",
__LINE__, driver_caller(desc->port)) );
if (!IS_OPEN(desc))
return ctl_xerror(EXBADPORT, rbuf, rsize);
return inet_ctl_getiflist(desc, rbuf, rsize);
}
case INET_REQ_GETIFADDRS: {
DDBG(desc,
("INET-DRV-DBG[%d][%T] inet_ctl -> GETIFADDRS\r\n",
__LINE__, driver_caller(desc->port)) );
if (!IS_OPEN(desc))
return ctl_xerror(EXBADPORT, rbuf, rsize);
return inet_ctl_getifaddrs(desc, rbuf, rsize);
}
case INET_REQ_IFGET: {
DDBG(desc,
("INET-DRV-DBG[%d][%T] inet_ctl -> IFGET\r\n",
__LINE__, driver_caller(desc->port)) );
if (!IS_OPEN(desc))
return ctl_xerror(EXBADPORT, rbuf, rsize);
return inet_ctl_ifget(desc, buf, len, rbuf, rsize);
}
case INET_REQ_IFSET: {
DDBG(desc,
("INET-DRV-DBG[%d][%T] inet_ctl -> IFSET\r\n",
__LINE__, driver_caller(desc->port)) );
if (!IS_OPEN(desc))
return ctl_xerror(EXBADPORT, rbuf, rsize);
return inet_ctl_ifset(desc, buf, len, rbuf, rsize);
}
case INET_REQ_SETOPTS: { /* set options */
int sres;
DDBG(desc,
("INET-DRV-DBG[%d][%d,%T] inet_ctl -> SETOPTS\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
sres = inet_set_opts(desc, buf, len);
/* We cannot debug-print if sres == 0 since we have then actually *
* completed a driver_exit => we have no longer a descriptor! */
if (sres != 0)
DDBG(desc,
("INET-DRV-DBG[%d][%d,%T] inet_ctl(setopts) -> sres: %d\r\n",
__LINE__, desc->s, driver_caller(desc->port), sres) );
switch(sres) {
case -1:
return ctl_error(EINVAL, rbuf, rsize);
case 0:
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
case 1:
/*
* Let's hope that the descriptor really is a tcp_descriptor here.
*/
/* fprintf(stderr,"Triggered tcp_deliver by setopt.\r\n"); */
tcp_deliver((tcp_descriptor *) desc, 0);
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
default:
/* fprintf(stderr,"Triggered tcp_recv by setopt.\r\n"); */
/*
* Same as above, but active changed to once w/o header type
* change, so try a read instead of just deliver.
*/
if ((tcp_recv((tcp_descriptor *) desc, 0) >= 0) && desc->active) {
sock_select(desc, (FD_READ|FD_CLOSE), 1);
}
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
}
case INET_REQ_GETSTATUS: {
char tbuf[4];
DDBG(desc,
("INET-DRV-DBG[%d][%T] inet_ctl -> GETSTATUS\r\n",
__LINE__, driver_caller(desc->port)) );
put_int32(desc->state, tbuf);
return ctl_reply(INET_REP_OK, tbuf, 4, rbuf, rsize);
}
case INET_REQ_GETTYPE: {
char tbuf[8];
DDBG(desc,
("INET-DRV-DBG[%d][%T] inet_ctl -> GETTYPE\r\n",
__LINE__, driver_caller(desc->port)) );
if (desc->sfamily == AF_INET) {
put_int32(INET_AF_INET, &tbuf[0]);
}
#if defined(HAVE_IN6) && defined(AF_INET6)
else if (desc->sfamily == AF_INET6) {
put_int32(INET_AF_INET6, &tbuf[0]);
}
#endif
#ifdef HAVE_SYS_UN_H
else if (desc->sfamily == AF_UNIX) {
put_int32(INET_AF_LOCAL, &tbuf[0]);
}
#endif
else
return ctl_error(EINVAL, rbuf, rsize);
if (desc->stype == SOCK_STREAM) {
put_int32(INET_TYPE_STREAM, &tbuf[4]);
}
else if (desc->stype == SOCK_DGRAM) {
put_int32(INET_TYPE_DGRAM, &tbuf[4]);
}
#ifdef HAVE_SCTP
else if (desc->stype == SOCK_SEQPACKET) {
put_int32(INET_TYPE_SEQPACKET, &tbuf[4]);
}
#endif
else
return ctl_error(EINVAL, rbuf, rsize);
return ctl_reply(INET_REP_OK, tbuf, 8, rbuf, rsize);
}
case INET_REQ_GETFD: {
char tbuf[4];
DDBG(desc,
("INET-DRV-DBG[%d][%d,%T] inet_ctl -> GETFD\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
if (!IS_OPEN(desc))
return ctl_error(EINVAL, rbuf, rsize);
put_int32((long)desc->s, tbuf);
return ctl_reply(INET_REP_OK, tbuf, 4, rbuf, rsize);
}
case INET_REQ_GETHOSTNAME: { /* get host name */
char tbuf[INET_MAXHOSTNAMELEN + 1];
DDBG(desc,
("INET-DRV-DBG[%d][%T] inet_ctl -> GETHOSTNAME\r\n",
__LINE__, driver_caller(desc->port)) );
if (len != 0)
return ctl_error(EINVAL, rbuf, rsize);
/* gethostname requires len to be max(hostname) + 1 */
if (IS_SOCKET_ERROR(sock_hostname(tbuf, INET_MAXHOSTNAMELEN + 1)))
return ctl_error(sock_errno(), rbuf, rsize);
return ctl_reply(INET_REP_OK, tbuf, strlen(tbuf), rbuf, rsize);
}
case INET_REQ_GETPADDRS: {
DDBG(desc,
("INET-DRV-DBG[%d][%T] inet_ctl -> GETPADDRS\r\n",
__LINE__, driver_caller(desc->port)) );
if (len != 4) return ctl_error(EINVAL, rbuf, rsize);
if (! IS_OPEN(desc)) return ctl_xerror(EXBADPORT, rbuf, rsize);
#ifdef HAVE_SCTP
if (IS_SCTP(desc) && p_sctp_getpaddrs) {
struct sockaddr *sa;
Uint32 assoc_id;
int n;
ErlDrvSizeT rlen;
assoc_id = get_int32(buf);
n = p_sctp_getpaddrs(desc->s, assoc_id, &sa);
rlen = reply_inet_addrs(n, (inet_address *) sa, rbuf, rsize, 0);
if (n > 0) p_sctp_freepaddrs(sa);
return rlen;
}
#endif
{ /* Fallback to sock_peer */
inet_address addr;
SOCKLEN_T sz;
int i;
sz = sizeof(addr);
i = sock_peer(desc->s, (struct sockaddr *) &addr, &sz);
return reply_inet_addrs(i >= 0 ? 1 : i, &addr, rbuf, rsize, sz);
}
}
case INET_REQ_PEER: { /* get peername */
char tbuf[sizeof(inet_address)];
inet_address peer;
inet_address* ptr;
unsigned int sz;
DDBG(desc,
("INET-DRV-DBG[%d][%T] inet_ctl -> PEER\r\n",
__LINE__, driver_caller(desc->port)) );
if (!(desc->state & INET_F_ACTIVE))
return ctl_error(ENOTCONN, rbuf, rsize);
if ((ptr = desc->peer_ptr) != NULL) {
sz = desc->peer_addr_len;
}
else {
ptr = &peer;
sz = sizeof(peer);
sys_memzero((char *) &peer, sz);
if (IS_SOCKET_ERROR
(sock_peer
(desc->s, (struct sockaddr*)ptr, &sz)))
return ctl_error(sock_errno(), rbuf, rsize);
}
if (inet_get_address(tbuf, ptr, &sz) < 0)
return ctl_error(EINVAL, rbuf, rsize);
return ctl_reply(INET_REP_OK, tbuf, sz, rbuf, rsize);
}
case INET_REQ_SETPEER: { /* set fake peername Port Address */
char *xerror;
DDBG(desc,
("INET-DRV-DBG[%d][%T] inet_ctl -> SETPEER\r\n",
__LINE__, driver_caller(desc->port)) );
if (len == 0) {
desc->peer_ptr = NULL;
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
else if (len < 2)
return ctl_error(EINVAL, rbuf, rsize);
else if ((xerror = inet_set_faddress
(desc->sfamily, &desc->peer_addr, &buf, &len)) != NULL)
return ctl_xerror(xerror, rbuf, rsize);
else {
desc->peer_ptr = &desc->peer_addr;
desc->peer_addr_len = (unsigned int) len;
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
}
case INET_REQ_GETLADDRS: {
DDBG(desc,
("INET-DRV-DBG[%d][%T] inet_ctl -> GETLADDRS\r\n",
__LINE__, driver_caller(desc->port)) );
if (len != 4) return ctl_error(EINVAL, rbuf, rsize);
if (! IS_OPEN(desc)) return ctl_xerror(EXBADPORT, rbuf, rsize);
#ifdef HAVE_SCTP
if (IS_SCTP(desc) && p_sctp_getladdrs) {
struct sockaddr *sa;
Uint32 assoc_id;
int n;
ErlDrvSizeT rlen;
assoc_id = get_int32(buf);
n = p_sctp_getladdrs(desc->s, assoc_id, &sa);
rlen = reply_inet_addrs(n, (inet_address *) sa, rbuf, rsize, 0);
if (n > 0) p_sctp_freeladdrs(sa);
return rlen;
}
#endif
{ /* Fallback to sock_name */
inet_address addr;
SOCKLEN_T sz;
int i;
sz = sizeof(addr);
sys_memzero((char *) &addr, sz);
i = sock_name(desc->s, (struct sockaddr *) &addr, &sz);
return reply_inet_addrs(i >= 0 ? 1 : i, &addr, rbuf, rsize, sz);
}
}
case INET_REQ_NAME: { /* get sockname */
char tbuf[sizeof(inet_address)];
inet_address name;
inet_address* ptr;
unsigned int sz;
DDBG(desc,
("INET-DRV-DBG[%d][%d,%T] inet_ctl -> NAME\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
if ((ptr = desc->name_ptr) != NULL) {
sz = desc->name_addr_len;
}
else {
ptr = &name;
sz = sizeof(name);
sys_memzero((char *) &name, sz);
if (IS_SOCKET_ERROR
(sock_name(desc->s, (struct sockaddr*)ptr, &sz)))
return ctl_error(sock_errno(), rbuf, rsize);
}
if (inet_get_address(tbuf, ptr, &sz) < 0)
return ctl_error(EINVAL, rbuf, rsize);
return ctl_reply(INET_REP_OK, tbuf, sz, rbuf, rsize);
}
case INET_REQ_SETNAME: { /* set fake sockname Port Address */
char *xerror;
DDBG(desc,
("INET-DRV-DBG[%d][%T] inet_ctl -> SETNAME\r\n",
__LINE__, driver_caller(desc->port)) );
if (len == 0) {
desc->name_ptr = NULL;
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
else if (len < 2)
return ctl_error(EINVAL, rbuf, rsize);
else if ((xerror = inet_set_faddress
(desc->sfamily, &desc->name_addr, &buf, &len)) != NULL)
return ctl_xerror(xerror, rbuf, rsize);
else {
desc->name_ptr = &desc->name_addr;
desc->name_addr_len = (unsigned int) len;
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
}
case INET_REQ_BIND: { /* bind socket */
char tbuf[2], *xerror;
inet_address local;
int port;
DDBG(desc,
("INET-DRV-DBG[%d][%d,%T] inet_ctl -> BIND\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
if (len < 2)
return ctl_error(EINVAL, rbuf, rsize);
if (desc->state != INET_STATE_OPEN)
return ctl_xerror(EXBADPORT, rbuf, rsize);
if ((xerror = inet_set_faddress
(desc->sfamily, &local, &buf, &len)) != NULL)
return ctl_xerror(xerror, rbuf, rsize);
if (IS_SOCKET_ERROR(sock_bind(desc->s,(struct sockaddr*) &local, len))) {
return ctl_error(sock_errno(), rbuf, rsize);
}
desc->state = INET_STATE_OPEN;
port = inet_address_port(&local);
if (port == 0) {
SOCKLEN_T adrlen = sizeof(local);
sys_memzero((char *) &local, adrlen);
sock_name(desc->s, &local.sa, &adrlen);
port = inet_address_port(&local);
}
else if (port == -1) port = 0;
put_int16(sock_ntohs((Uint16) port), tbuf);
return ctl_reply(INET_REP_OK, tbuf, 2, rbuf, rsize);
}
case INET_REQ_IGNOREFD: {
DDBG(desc,
("INET-DRV-DBG[%d][%d,%T] inet_ctl -> IGNOREFD: %s\r\n",
__LINE__, desc->s, driver_caller(desc->port), B2S(*buf)) );
/*
* FD can only be ignored for connected TCP connections for now,
* possible to add UDP and SCTP support if needed.
*/
if (!IS_CONNECTED(desc))
return ctl_error(ENOTCONN, rbuf, rsize);
if (desc->stype != SOCK_STREAM)
return ctl_error(EINVAL, rbuf, rsize);
if (*buf == 1 && !INET_IGNORED(desc)) {
sock_select(desc, (FD_READ|FD_WRITE|FD_CLOSE|ERL_DRV_USE_NO_CALLBACK), 0);
if (desc->active)
desc->flags |= INET_IGNORE_READ;
else
desc->flags |= INET_IGNORE_PASSIVE;
} else if (*buf == 0 && INET_IGNORED(desc)) {
int flags = FD_CLOSE;
if (desc->flags & INET_IGNORE_READ)
flags |= FD_READ;
if (desc->flags & INET_IGNORE_WRITE)
flags |= FD_WRITE;
desc->flags = INET_IGNORE_CLEAR(desc);
if (flags != FD_CLOSE)
sock_select(desc, flags, 1);
} else
return ctl_error(EINVAL, rbuf, rsize);
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
case INET_REQ_GETSERVBYNAME: { /* L1 Name-String L2 Proto-String */
char namebuf[256];
char protobuf[256];
char tbuf[2];
struct servent* srv;
short port;
int n;
DDBG(desc,
("INET-DRV-DBG[%d][%T] inet_ctl -> GETSERVBYNAME\r\n",
__LINE__, driver_caller(desc->port)) );
if (len < 2)
return ctl_error(EINVAL, rbuf, rsize);
n = get_int8(buf); buf++; len--;
if (n >= len) /* the = sign makes the test inklude next length byte */
return ctl_error(EINVAL, rbuf, rsize);
memcpy(namebuf, buf, n);
namebuf[n] = '\0';
len -= n; buf += n;
n = get_int8(buf); buf++; len--;
if (n > len)
return ctl_error(EINVAL, rbuf, rsize);
memcpy(protobuf, buf, n);
protobuf[n] = '\0';
if ((srv = sock_getservbyname(namebuf, protobuf)) == NULL)
return ctl_error(EINVAL, rbuf, rsize);
port = sock_ntohs(srv->s_port);
put_int16(port, tbuf);
return ctl_reply(INET_REP_OK, tbuf, 2, rbuf, rsize);
}
case INET_REQ_GETSERVBYPORT: { /* P1 P0 L1 Proto-String */
char protobuf[256];
unsigned short port;
int n;
struct servent* srv;
DDBG(desc,
("INET-DRV-DBG[%d][%T] inet_ctl -> GETSERVBYPORT\r\n",
__LINE__, driver_caller(desc->port)) );
if (len < 3)
return ctl_error(EINVAL, rbuf, rsize);
port = get_int16(buf);
port = sock_htons(port);
buf += 2;
n = get_int8(buf); buf++; len -= 3;
if (n > len)
return ctl_error(EINVAL, rbuf, rsize);
memcpy(protobuf, buf, n);
protobuf[n] = '\0';
if ((srv = sock_getservbyport(port, protobuf)) == NULL)
return ctl_error(EINVAL, rbuf, rsize);
len = strlen(srv->s_name);
return ctl_reply(INET_REP_OK, srv->s_name, len, rbuf, rsize);
}
default:
DDBG(desc,
("INET-DRV-DBG[%d][%T] inet_ctl -> unknown command\r\n",
__LINE__, driver_caller(desc->port)) );
return ctl_xerror(EXBADPORT, rbuf, rsize);
}
}
/* update statistics on output packets */
static void inet_output_count(inet_descriptor* desc, ErlDrvSizeT len)
{
unsigned long n = desc->send_cnt + 1;
#ifndef ARCH_64
Uint32 t = desc->send_oct[0] + len;
int c = (t < desc->send_oct[0]);
#endif
double avg = desc->send_avg;
#ifdef ARCH_64
desc->send_oct += len;
#else
/* 64 bit octet count in 32 bit words */
desc->send_oct[0] = t;
desc->send_oct[1] += c;
#endif
if (n == 0) /* WRAP, use old avg as input to a new sequence */
n = 1;
desc->send_avg += (len - avg) / n;
if (len > desc->send_max)
desc->send_max = len;
desc->send_cnt = n;
}
/* update statistics on input packets */
static void inet_input_count(inet_descriptor* desc, ErlDrvSizeT len)
{
unsigned long n = desc->recv_cnt + 1;
#ifndef ARCH_64
Uint32 t = (desc->recv_oct[0] + len);
int c = (t < desc->recv_oct[0]);
#endif
double avg = desc->recv_avg;
double dvi;
#ifdef ARCH_64
desc->recv_oct += len;
#else
/* 64 bit octet count in 32 bit words */
desc->recv_oct[0] = t;
desc->recv_oct[1] += c;
#endif
if (n == 0) /* WRAP */
n = 1;
/* average packet length */
avg = avg + (len - avg) / n;
desc->recv_avg = avg;
if (len > desc->recv_max)
desc->recv_max = len;
/* average deviation from average packet length */
dvi = desc->recv_dvi;
desc->recv_dvi = dvi + ((len - avg) - dvi) / n;
desc->recv_cnt = n;
}
/*----------------------------------------------------------------------------
TCP
-----------------------------------------------------------------------------*/
/*
** Set new size on buffer, used when packet size is determined
** and the buffer is to small.
** buffer must have a size of at least len bytes (counting from ptr_start!)
*/
static int tcp_expand_buffer(tcp_descriptor* desc, int len)
{
ErlDrvBinary* bin;
int offs1;
int offs2;
int used = desc->i_ptr_start - desc->i_buf->orig_bytes;
int ulen = used + len;
if (desc->i_bufsz >= ulen) /* packet will fit */
return 0;
else if (desc->i_buf->orig_size >= ulen) { /* buffer is large enough */
desc->i_bufsz = ulen; /* set "virtual" size */
return 0;
}
DEBUGF(("tcp_expand_buffer(%p): s=%d, from %ld to %d\r\n",
desc->inet.port, desc->inet.s,
desc->i_buf->orig_size, ulen));
offs1 = desc->i_ptr_start - desc->i_buf->orig_bytes;
offs2 = desc->i_ptr - desc->i_ptr_start;
if ((bin = driver_realloc_binary(desc->i_buf, ulen)) == NULL)
return -1;
desc->i_buf = bin;
desc->i_ptr_start = bin->orig_bytes + offs1;
desc->i_ptr = desc->i_ptr_start + offs2;
desc->i_bufsz = ulen;
return 0;
}
/* push data into i_buf */
static int tcp_push_buffer(tcp_descriptor* desc, char* buf, int len)
{
ErlDrvBinary* bin;
if (desc->i_buf == NULL) {
bin = alloc_buffer(len);
sys_memcpy(bin->orig_bytes, buf, len);
desc->i_buf = bin;
desc->i_bufsz = len;
desc->i_ptr_start = desc->i_buf->orig_bytes;
desc->i_ptr = desc->i_ptr_start + len;
}
else {
char* start = desc->i_buf->orig_bytes;
int sz_before = desc->i_ptr_start - start;
int sz_filled = desc->i_ptr - desc->i_ptr_start;
if (len <= sz_before) {
sys_memcpy(desc->i_ptr_start - len, buf, len);
desc->i_ptr_start -= len;
}
else {
bin = alloc_buffer(desc->i_bufsz+len);
sys_memcpy(bin->orig_bytes, buf, len);
sys_memcpy(bin->orig_bytes+len, desc->i_ptr_start, sz_filled);
free_buffer(desc->i_buf);
desc->i_bufsz += len;
desc->i_buf = bin;
desc->i_ptr_start = bin->orig_bytes;
desc->i_ptr = desc->i_ptr_start + sz_filled + len;
}
}
desc->i_remain = 0;
return 0;
}
/* clear CURRENT input buffer */
static void tcp_clear_input(tcp_descriptor* desc)
{
if (desc->i_buf != NULL)
free_buffer(desc->i_buf);
desc->i_buf = NULL;
desc->i_remain = 0;
desc->i_ptr = NULL;
desc->i_ptr_start = NULL;
desc->i_bufsz = 0;
}
/* clear QUEUED output */
static void tcp_clear_output(tcp_descriptor* desc)
{
ErlDrvPort ix = desc->inet.port;
ErlDrvSizeT qsz = driver_sizeq(ix);
driver_deq(ix, qsz);
send_empty_out_q_msgs(INETP(desc));
}
/* Move data so that ptr_start point at buf->orig_bytes */
static void tcp_restart_input(tcp_descriptor* desc)
{
if (desc->i_ptr_start != desc->i_buf->orig_bytes) {
int n = desc->i_ptr - desc->i_ptr_start;
DEBUGF(("tcp_restart_input: move %d bytes\r\n", n));
sys_memmove(desc->i_buf->orig_bytes, desc->i_ptr_start, n);
desc->i_ptr_start = desc->i_buf->orig_bytes;
desc->i_ptr = desc->i_ptr_start + n;
}
}
static int tcp_inet_init(void)
{
DEBUGF(("tcp_inet_init() {}\r\n"));
return 0;
}
/* initialize the TCP descriptor */
static ErlDrvData prep_tcp_inet_start(ErlDrvPort port, char* args)
{
tcp_descriptor* desc;
DEBUGF(("tcp_inet_start(%p) {\r\n", port));
desc = (tcp_descriptor*)
inet_start(port, sizeof(tcp_descriptor), IPPROTO_TCP);
if (desc == NULL)
return ERL_DRV_ERROR_ERRNO;
desc->high = INET_HIGH_WATERMARK;
desc->low = INET_LOW_WATERMARK;
desc->send_timeout = INET_INFINITY;
desc->send_timeout_close = 0;
desc->busy_on_send = 0;
desc->i_buf = NULL;
desc->i_ptr = NULL;
desc->i_ptr_start = NULL;
desc->i_remain = 0;
desc->i_bufsz = 0;
desc->tcp_add_flags = 0;
desc->http_state = 0;
desc->mtd = NULL;
desc->mtd_cache = NULL;
desc->multi_first = desc->multi_last = NULL;
DEBUGF(("tcp_inet_start(%p) }\r\n", port));
return (ErlDrvData) desc;
}
static ErlDrvData tcp_inet_start(ErlDrvPort port, char* args)
{
ErlDrvData data = prep_tcp_inet_start(port, args);
set_default_msgq_limits(port);
return data;
}
/* Copy a descriptor, by creating a new port with same settings
* as the descriptor desc.
* return NULL on error (SYSTEM_LIMIT no ports avail)
*/
static tcp_descriptor* tcp_inet_copy(tcp_descriptor* desc,SOCKET s,
ErlDrvTermData owner, int* err)
{
ErlDrvSizeT q_low, q_high;
ErlDrvPort port = desc->inet.port;
tcp_descriptor* copy_desc;
copy_desc = (tcp_descriptor*) prep_tcp_inet_start(port, NULL);
/* Setup event if needed */
if ((copy_desc->inet.s = s) != INVALID_SOCKET) {
if ((copy_desc->inet.event = sock_create_event(INETP(copy_desc))) ==
INVALID_EVENT) {
*err = sock_errno();
FREE(copy_desc);
return NULL;
}
}
/* Some flags must be inherited at this point */
copy_desc->inet.mode = desc->inet.mode;
copy_desc->inet.exitf = desc->inet.exitf;
copy_desc->inet.deliver = desc->inet.deliver;
copy_desc->inet.htype = desc->inet.htype;
copy_desc->inet.psize = desc->inet.psize;
copy_desc->inet.stype = desc->inet.stype;
copy_desc->inet.sfamily = desc->inet.sfamily;
copy_desc->inet.hsz = desc->inet.hsz;
copy_desc->inet.bufsz = desc->inet.bufsz;
copy_desc->high = desc->high;
copy_desc->low = desc->low;
copy_desc->send_timeout = desc->send_timeout;
copy_desc->send_timeout_close = desc->send_timeout_close;
copy_desc->tcp_add_flags = desc->tcp_add_flags
& (TCP_ADDF_SHOW_ECONNRESET | TCP_ADDF_LINGER_ZERO);
/* The new port will be linked and connected to the original caller */
port = driver_create_port(port, owner, "tcp_inet", (ErlDrvData) copy_desc);
if ((SWord)port == -1) {
*err = INET_ERRNO_SYSTEM_LIMIT;
FREE(copy_desc);
return NULL;
}
/* Read busy msgq limits of parent */
q_low = q_high = ERL_DRV_BUSY_MSGQ_READ_ONLY;
erl_drv_busy_msgq_limits(desc->inet.port, &q_low, &q_high);
/* Write same busy msgq limits to child */
erl_drv_busy_msgq_limits(port, &q_low, &q_high);
copy_desc->inet.port = port;
copy_desc->inet.dport = driver_mk_port(port);
*err = 0;
return copy_desc;
}
/*
** Check Special cases:
** 1. we are a listener doing nb accept -> report error on accept !
** 2. we are doing accept -> restore listener state
*/
static void tcp_close_check(tcp_descriptor* desc)
{
/* XXX:PaN - multiple clients to handle! */
if (desc->inet.state == INET_STATE_ACCEPTING) {
inet_async_op *this_op = desc->inet.opt;
sock_select(INETP(desc), FD_ACCEPT, 0);
desc->inet.state = INET_STATE_LISTENING;
if (this_op != NULL) {
driver_demonitor_process(desc->inet.port, &(this_op->monitor));
}
async_error_am(INETP(desc), am_closed);
}
else if (desc->inet.state == INET_STATE_MULTI_ACCEPTING) {
int id,req;
ErlDrvTermData caller;
ErlDrvMonitor monitor;
sock_select(INETP(desc), FD_ACCEPT, 0);
desc->inet.state = INET_STATE_LISTENING;
while (deq_multi_op(desc,&id,&req,&caller,NULL,&monitor) == 0) {
driver_demonitor_process(desc->inet.port, &monitor);
send_async_error(desc->inet.dport, id, caller, am_closed);
}
}
else if (desc->inet.state == INET_STATE_CONNECTING) {
async_error_am(INETP(desc), am_closed);
}
else if (desc->inet.state == INET_STATE_CONNECTED) {
async_error_am_all(INETP(desc), am_closed);
}
clean_multi_timers(desc, desc->inet.port);
}
/*
** Cleanup & Free
*/
static void tcp_inet_stop(ErlDrvData e)
{
tcp_descriptor* desc = (tcp_descriptor*)e;
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR "] tcp_inet_stop -> entry\r\n",
__LINE__, desc->inet.s) );
tcp_close_check(desc);
tcp_clear_input(desc);
#ifdef HAVE_SENDFILE
if(desc->tcp_add_flags & TCP_ADDF_SENDFILE) {
desc->tcp_add_flags &= ~TCP_ADDF_SENDFILE;
close(desc->sendfile.dup_file_fd);
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR "] "
"tcp_inet_stop -> SENDFILE dup closed %d\r\n",
__LINE__, desc->inet.s, desc->sendfile.dup_file_fd) );
}
#endif
inet_stop(INETP(desc));
}
/* Closes a tcp descriptor without leaving things hanging; the VM keeps trying
* to flush IO queues as long as it contains anything even after the port has
* been closed from the erlang side, which is desired behavior (Think escripts
* writing to files) but pretty hopeless if the underlying fd has been set to
* INVALID_SOCKET through desc_close.
*
* This function should be used in place of desc_close/erl_inet_close in all
* TCP-related operations. Note that this only closes the desc cleanly; it
* will be freed through tcp_inet_stop later on. */
static void tcp_desc_close(tcp_descriptor* desc)
{
tcp_clear_input(desc);
tcp_clear_output(desc);
erl_inet_close(INETP(desc));
}
static int tcp_inet_recv_timeout(ErlDrvData e, ErlDrvTermData dummy)
{
tcp_descriptor* desc = (tcp_descriptor*)e;
ASSERT(!desc->inet.active);
sock_select(INETP(desc),(FD_READ|FD_CLOSE),0);
desc->i_remain = 0;
async_error_am(INETP(desc), am_timeout);
return 1;
}
/* TCP requests from Erlang */
static ErlDrvSSizeT tcp_inet_ctl(ErlDrvData e, unsigned int cmd,
char* buf, ErlDrvSizeT len,
char** rbuf, ErlDrvSizeT rsize)
{
tcp_descriptor* desc = (tcp_descriptor*)e;
cmd -= ERTS_INET_DRV_CONTROL_MAGIC_NUMBER;
switch(cmd) {
case INET_REQ_OPEN: { /* open socket and return internal index */
int domain;
DDBG(INETP(desc),
("INET-DRV-DBG[%d][%T] tcp_inet_ctl -> OPEN\r\n",
__LINE__, driver_caller(desc->inet.port)) );
if (len != 2) return ctl_error(EINVAL, rbuf, rsize);
switch(buf[0]) {
case INET_AF_INET:
domain = AF_INET;
break;
#if defined(HAVE_IN6) && defined(AF_INET6)
case INET_AF_INET6:
domain = AF_INET6;
break;
#endif
#ifdef HAVE_SYS_UN_H
case INET_AF_LOCAL:
domain = AF_UNIX;
break;
#endif
default:
return ctl_xerror(str_eafnosupport, rbuf, rsize);
}
if (buf[1] != INET_TYPE_STREAM) return ctl_error(EINVAL, rbuf, rsize);
return inet_ctl_open(INETP(desc), domain, SOCK_STREAM, rbuf, rsize);
break;
}
case INET_REQ_FDOPEN: { /* pass in an open (and optionally bound) socket */
int domain;
int bound;
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"tcp_inet_ctl -> FDOPEN\r\n",
__LINE__, desc->inet.s, driver_caller(desc->inet.port)) );
if (len != 6 && len != 10) return ctl_error(EINVAL, rbuf, rsize);
switch(buf[0]) {
case INET_AF_INET:
domain = AF_INET;
break;
#if defined(HAVE_IN6) && defined(AF_INET6)
case INET_AF_INET6:
domain = AF_INET6;
break;
#endif
#ifdef HAVE_SYS_UN_H
case INET_AF_LOCAL:
domain = AF_UNIX;
break;
#endif
default:
return ctl_xerror(str_eafnosupport, rbuf, rsize);
}
if (buf[1] != INET_TYPE_STREAM) return ctl_error(EINVAL, rbuf, rsize);
if (len == 6) bound = 1;
else bound = get_int32(buf+2+4);
return inet_ctl_fdopen(INETP(desc), domain, SOCK_STREAM,
(SOCKET) get_int32(buf+2),
bound, rbuf, rsize);
break;
}
case INET_REQ_LISTEN: { /* argument backlog */
int backlog;
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"tcp_inet_ctl -> LISTEN\r\n",
__LINE__, desc->inet.s, driver_caller(desc->inet.port)) );
if (desc->inet.state == INET_STATE_CLOSED)
return ctl_xerror(EXBADPORT, rbuf, rsize);
if (!IS_OPEN(INETP(desc)))
return ctl_xerror(EXBADPORT, rbuf, rsize);
if (len != 2)
return ctl_error(EINVAL, rbuf, rsize);
backlog = get_int16(buf);
if (IS_SOCKET_ERROR(sock_listen(desc->inet.s, backlog)))
return ctl_error(sock_errno(), rbuf, rsize);
desc->inet.state = INET_STATE_LISTENING;
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
case INET_REQ_CONNECT: { /* do async connect */
int code;
char tbuf[2], *xerror;
unsigned timeout;
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"tcp_inet_ctl -> CONNECT\r\n",
__LINE__, desc->inet.s, driver_caller(desc->inet.port)) );
/* INPUT: Timeout(4), Port(2), Address(N) */
if (!IS_OPEN(INETP(desc)))
return ctl_xerror(EXBADPORT, rbuf, rsize);
if (IS_CONNECTED(INETP(desc)))
return ctl_error(EISCONN, rbuf, rsize);
if (IS_CONNECTING(INETP(desc)))
return ctl_error(EINVAL, rbuf, rsize);
if (len < 6)
return ctl_error(EINVAL, rbuf, rsize);
timeout = get_int32(buf);
buf += 4;
len -= 4;
if ((xerror = inet_set_faddress
(desc->inet.sfamily, &desc->inet.remote, &buf, &len)) != NULL)
return ctl_xerror(xerror, rbuf, rsize);
code = sock_connect(desc->inet.s,
(struct sockaddr*) &desc->inet.remote, len);
/* We *cannot* have debug printouts here since it resets the
* 'errno' value (printf).
*/
if (IS_SOCKET_ERROR(code) &&
((sock_errno() == ERRNO_BLOCK) || /* Winsock2 */
(sock_errno() == EINPROGRESS))) { /* Unix & OSE!! */
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"tcp_inet_ctl(connect) -> would block => select\r\n",
__LINE__,
desc->inet.s, driver_caller(desc->inet.port)) );
sock_select(INETP(desc), FD_CONNECT, 1);
desc->inet.state = INET_STATE_CONNECTING;
if (timeout != INET_INFINITY)
driver_set_timer(desc->inet.port, timeout);
enq_async(INETP(desc), tbuf, INET_REQ_CONNECT);
}
else if (code == 0) { /* ok we are connected */
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"tcp_inet_ctl(connect) -> connected\r\n",
__LINE__,
desc->inet.s, driver_caller(desc->inet.port)) );
desc->inet.state = INET_STATE_CONNECTED;
if (desc->inet.active)
sock_select(INETP(desc), (FD_READ|FD_CLOSE), 1);
enq_async(INETP(desc), tbuf, INET_REQ_CONNECT);
async_ok(INETP(desc));
}
else {
int save_errno = sock_errno();
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"tcp_inet_ctl(connect) -> error: %s (%d)\r\n",
__LINE__,
desc->inet.s, driver_caller(desc->inet.port),
errno_str(save_errno), save_errno) );
return ctl_error(save_errno, rbuf, rsize);
}
return ctl_reply(INET_REP_OK, tbuf, 2, rbuf, rsize);
}
case INET_REQ_ACCEPT: { /* do async accept */
char tbuf[2];
unsigned timeout;
inet_address remote;
unsigned int n;
SOCKET s;
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"tcp_inet_ctl -> ACCEPT\r\n",
__LINE__, desc->inet.s, driver_caller(desc->inet.port)) );
/* INPUT: Timeout(4) */
if ((desc->inet.state != INET_STATE_LISTENING && desc->inet.state != INET_STATE_ACCEPTING &&
desc->inet.state != INET_STATE_MULTI_ACCEPTING) || len != 4) {
return ctl_error(EINVAL, rbuf, rsize);
}
timeout = get_int32(buf);
if (desc->inet.state == INET_STATE_ACCEPTING) {
unsigned long time_left = 0;
int oid = 0;
ErlDrvTermData ocaller = ERL_DRV_NIL;
int oreq = 0;
unsigned otimeout = 0;
ErlDrvTermData caller = driver_caller(desc->inet.port);
MultiTimerData *mtd = NULL,*omtd = NULL;
ErlDrvMonitor monitor, omonitor;
if (driver_monitor_process(desc->inet.port, caller ,&monitor) != 0) {
return ctl_xerror("noproc", rbuf, rsize);
}
deq_async_w_tmo(INETP(desc),&oid,&ocaller,&oreq,&otimeout,&omonitor);
if (otimeout != INET_INFINITY) {
driver_read_timer(desc->inet.port, &time_left);
driver_cancel_timer(desc->inet.port);
if (time_left <= 0) {
time_left = 1;
}
omtd = add_multi_timer(desc, desc->inet.port, ocaller,
time_left, &tcp_inet_multi_timeout);
}
enq_old_multi_op(desc, oid, oreq, ocaller, omtd, &omonitor);
if (timeout != INET_INFINITY) {
mtd = add_multi_timer(desc, desc->inet.port, caller,
timeout, &tcp_inet_multi_timeout);
}
enq_multi_op(desc, tbuf, INET_REQ_ACCEPT, caller, mtd, &monitor);
desc->inet.state = INET_STATE_MULTI_ACCEPTING;
return ctl_reply(INET_REP_OK, tbuf, 2, rbuf, rsize);
} else if (desc->inet.state == INET_STATE_MULTI_ACCEPTING) {
ErlDrvTermData caller = driver_caller(desc->inet.port);
MultiTimerData *mtd = NULL;
ErlDrvMonitor monitor;
if (driver_monitor_process(desc->inet.port, caller ,&monitor) != 0) {
return ctl_xerror("noproc", rbuf, rsize);
}
if (timeout != INET_INFINITY) {
mtd = add_multi_timer(desc, desc->inet.port, caller,
timeout, &tcp_inet_multi_timeout);
}
enq_multi_op(desc, tbuf, INET_REQ_ACCEPT, caller, mtd, &monitor);
return ctl_reply(INET_REP_OK, tbuf, 2, rbuf, rsize);
} else {
n = sizeof(desc->inet.remote);
sys_memzero((char *) &remote, n);
s = sock_accept(desc->inet.s, (struct sockaddr*) &remote, &n);
if (s == INVALID_SOCKET) {
if (sock_errno() == ERRNO_BLOCK) {
ErlDrvMonitor monitor;
if (driver_monitor_process(desc->inet.port, driver_caller(desc->inet.port),
&monitor) != 0) {
return ctl_xerror("noproc", rbuf, rsize);
}
enq_async_w_tmo(INETP(desc), tbuf, INET_REQ_ACCEPT, timeout, &monitor);
desc->inet.state = INET_STATE_ACCEPTING;
sock_select(INETP(desc),FD_ACCEPT,1);
if (timeout != INET_INFINITY) {
driver_set_timer(desc->inet.port, timeout);
}
} else {
return ctl_error(sock_errno(), rbuf, rsize);
}
} else {
ErlDrvTermData caller = driver_caller(desc->inet.port);
tcp_descriptor* accept_desc;
int err;
if ((accept_desc = tcp_inet_copy(desc,s,caller,&err)) == NULL) {
sock_close(s);
return ctl_error(err, rbuf, rsize);
}
/* FIXME: may MUST lock access_port
* 1 - Port is accessible via the erlang:ports()
* 2 - Port is accessible via callers process_info(links)
*/
accept_desc->inet.remote = remote;
SET_NONBLOCKING(accept_desc->inet.s);
#ifdef __WIN32__
driver_select(accept_desc->inet.port, accept_desc->inet.event,
ERL_DRV_READ, 1);
#endif
accept_desc->inet.state = INET_STATE_CONNECTED;
enq_async(INETP(desc), tbuf, INET_REQ_ACCEPT);
async_ok_port(INETP(desc), accept_desc->inet.dport);
}
return ctl_reply(INET_REP_OK, tbuf, 2, rbuf, rsize);
}
}
case INET_REQ_CLOSE:
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] tcp_inet_ctl -> CLOSE\r\n",
__LINE__, desc->inet.s, driver_caller(desc->inet.port)) );
tcp_close_check(desc);
tcp_desc_close(desc);
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
case TCP_REQ_RECV: {
unsigned timeout;
char tbuf[2];
int n;
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] tcp_inet_ctl -> RECV\r\n",
__LINE__, desc->inet.s, driver_caller(desc->inet.port)) );
/* INPUT: Timeout(4), Length(4) */
if (!IS_CONNECTED(INETP(desc))) {
if (desc->tcp_add_flags & TCP_ADDF_DELAYED_CLOSE_RECV) {
desc->tcp_add_flags &= ~(TCP_ADDF_DELAYED_CLOSE_RECV|
TCP_ADDF_DELAYED_CLOSE_SEND);
if (desc->tcp_add_flags & TCP_ADDF_DELAYED_ECONNRESET) {
desc->tcp_add_flags &= ~TCP_ADDF_DELAYED_ECONNRESET;
return ctl_reply(INET_REP_ERROR, "econnreset", 10, rbuf, rsize);
} else
return ctl_reply(INET_REP_ERROR, "closed", 6, rbuf, rsize);
}
return ctl_error(ENOTCONN, rbuf, rsize);
}
if (desc->inet.active || (len != 8))
return ctl_error(EINVAL, rbuf, rsize);
timeout = get_int32(buf);
buf += 4;
n = get_int32(buf);
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"tcp_inet_ctl(recv) -> timeout: %d, n: %d\r\n",
__LINE__,
desc->inet.s, driver_caller(desc->inet.port), timeout, n) );
if ((desc->inet.htype != TCP_PB_RAW) && (n != 0))
return ctl_error(EINVAL, rbuf, rsize);
if (n > TCP_MAX_PACKET_SIZE)
return ctl_error(ENOMEM, rbuf, rsize);
if (enq_async(INETP(desc), tbuf, TCP_REQ_RECV) < 0)
return ctl_error(EALREADY, rbuf, rsize);
if (INET_IGNORED(INETP(desc)) || tcp_recv(desc, n) == 0) {
if (timeout == 0)
async_error_am(INETP(desc), am_timeout);
else {
if (timeout != INET_INFINITY)
add_multi_timer(desc, INETP(desc)->port, 0,
timeout, &tcp_inet_recv_timeout);
if (!INET_IGNORED(INETP(desc)))
sock_select(INETP(desc),(FD_READ|FD_CLOSE),1);
else
INETP(desc)->flags |= INET_IGNORE_READ;
}
}
return ctl_reply(INET_REP_OK, tbuf, 2, rbuf, rsize);
}
case TCP_REQ_UNRECV: {
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] tcp_inet_ctl -> UNRECV\r\n",
__LINE__, desc->inet.s, driver_caller(desc->inet.port)) );
if (!IS_CONNECTED(INETP(desc)))
return ctl_error(ENOTCONN, rbuf, rsize);
tcp_push_buffer(desc, buf, len);
if (desc->inet.active)
tcp_deliver(desc, 0);
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
case TCP_REQ_SHUTDOWN: {
int how;
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"tcp_inet_ctl -> SHUTDOWN\r\n",
__LINE__, desc->inet.s, driver_caller(desc->inet.port)) );
if (!IS_CONNECTED(INETP(desc))) {
return ctl_error(ENOTCONN, rbuf, rsize);
}
if (len != 1) {
return ctl_error(EINVAL, rbuf, rsize);
}
how = buf[0];
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"tcp_inet_ctl(shutdown) -> how: %s (%d)\r\n",
__LINE__,
desc->inet.s, driver_caller(desc->inet.port), SH2S(how), how) );
if (how != TCP_SHUT_RD && driver_sizeq(desc->inet.port) > 0) {
if (how == TCP_SHUT_WR) {
desc->tcp_add_flags |= TCP_ADDF_PENDING_SHUT_WR;
} else if (how == TCP_SHUT_RDWR) {
desc->tcp_add_flags |= TCP_ADDF_PENDING_SHUT_RDWR;
}
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
if (IS_SOCKET_ERROR(sock_shutdown(INETP(desc)->s, how))) {
if (how != TCP_SHUT_RD)
desc->tcp_add_flags |= TCP_ADDF_SHUTDOWN_WR_DONE;
return ctl_error(sock_errno(), rbuf, rsize);
} else {
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
}
case TCP_REQ_SENDFILE: {
#ifdef HAVE_SENDFILE
const ErlDrvSizeT required_len =
sizeof(desc->sendfile.dup_file_fd) +
sizeof(Uint64) * 2;
int raw_file_fd;
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"tcp_inet_ctl -> SENDFILE\r\n",
__LINE__, desc->inet.s, driver_caller(desc->inet.port)) );
if (len != required_len) {
return ctl_error(EINVAL, rbuf, rsize);
} else if (!IS_CONNECTED(INETP(desc))) {
return ctl_error(ENOTCONN, rbuf, rsize);
} else if (desc->tcp_add_flags & TCP_ADDF_SENDFILE) {
/* This should not happen as prim_inet.erl makes
sure that only the controlling process can
use the sendfile operation. But we add this
check here anyways just in case that prim_inet
is changed... */
return ctl_error(EINVAL, rbuf, rsize);
}
sys_memcpy(&raw_file_fd, buf, sizeof(raw_file_fd));
buf += sizeof(raw_file_fd);
desc->sendfile.dup_file_fd = dup(raw_file_fd);
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"tcp_inet_ctl(sendfile) -> dup: %d\r\n",
__LINE__,
desc->inet.s, driver_caller(desc->inet.port),
desc->sendfile.dup_file_fd) );
if(desc->sendfile.dup_file_fd == -1) {
return ctl_error(errno, rbuf, rsize);
}
desc->sendfile.offset = get_int64(buf);
buf += sizeof(Uint64);
desc->sendfile.length = get_int64(buf);
buf += sizeof(Uint64);
ASSERT(desc->sendfile.offset >= 0);
ASSERT(desc->sendfile.length >= 0);
desc->sendfile.ioq_skip = driver_sizeq(desc->inet.port);
desc->sendfile.bytes_sent = 0;
desc->inet.caller = driver_caller(desc->inet.port);
desc->tcp_add_flags |= TCP_ADDF_SENDFILE;
/* See if we can finish sending without selecting & rescheduling. */
if (tcp_inet_sendfile(desc) == 0) {
if(desc->sendfile.length > 0) {
sock_select(INETP(desc), FD_WRITE, 1);
}
}
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
#else
return ctl_error(ENOTSUP, rbuf, rsize);
#endif
}
default:
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"tcp_inet_ctl -> (maybe) general command %u\r\n",
__LINE__,
desc->inet.s, driver_caller(desc->inet.port), cmd) );
return inet_ctl(INETP(desc), cmd, buf, len, rbuf, rsize);
}
}
static int tcp_inet_send_timeout(ErlDrvData e, ErlDrvTermData dummy)
{
tcp_descriptor* desc = (tcp_descriptor*)e;
ASSERT(IS_BUSY(INETP(desc)));
ASSERT(desc->busy_on_send);
desc->inet.caller = desc->inet.busy_caller;
desc->inet.state &= ~INET_F_BUSY;
desc->busy_on_send = 0;
set_busy_port(desc->inet.port, 0);
inet_reply_error_am(INETP(desc), am_timeout);
if (desc->send_timeout_close) {
tcp_desc_close(desc);
}
return 1;
/* Q: Why not keep port busy as send queue may still be full (ERL-1390)?
*
* A: If kept busy, a following send call would hang without a timeout
* as it would get suspended in erlang:port_command waiting on busy port.
*/
}
/*
** tcp_inet_timeout:
** called when timer expire:
** TCP socket may be:
**
** a) receiving -- send timeout
** b) connecting -- close socket
** c) accepting -- reset listener
**
*/
static void tcp_inet_timeout(ErlDrvData e)
{
tcp_descriptor* desc = (tcp_descriptor*)e;
int state = desc->inet.state;
DEBUGF(("tcp_inet_timeout(%p) {s=%d\r\n",
desc->inet.port, desc->inet.s));
if ((state & INET_F_MULTI_CLIENT)) { /* Multi-client always means multi-timers */
fire_multi_timers(desc, desc->inet.port, e);
} else if ((state & INET_STATE_CONNECTED) == INET_STATE_CONNECTED) {
fire_multi_timers(desc, desc->inet.port, e);
}
else if ((state & INET_STATE_CONNECTING) == INET_STATE_CONNECTING) {
/* assume connect timeout */
/* close the socket since it's not usable (see man pages) */
tcp_desc_close(desc);
async_error_am(INETP(desc), am_timeout);
}
else if ((state & INET_STATE_ACCEPTING) == INET_STATE_ACCEPTING) {
inet_async_op *this_op = desc->inet.opt;
/* timer is set on accept */
sock_select(INETP(desc), FD_ACCEPT, 0);
if (this_op != NULL) {
driver_demonitor_process(desc->inet.port, &(this_op->monitor));
}
desc->inet.state = INET_STATE_LISTENING;
async_error_am(INETP(desc), am_timeout);
}
DEBUGF(("tcp_inet_timeout(%p) }\r\n", desc->inet.port));
}
static int tcp_inet_multi_timeout(ErlDrvData e, ErlDrvTermData caller)
{
tcp_descriptor* desc = (tcp_descriptor*)e;
int id,req;
ErlDrvMonitor monitor;
if (remove_multi_op(desc, &id, &req, caller, NULL, &monitor) != 0) {
return 1;
}
driver_demonitor_process(desc->inet.port, &monitor);
if (desc->multi_first == NULL) {
sock_select(INETP(desc),FD_ACCEPT,0);
desc->inet.state = INET_STATE_LISTENING; /* restore state */
}
send_async_error(desc->inet.dport, id, caller, am_timeout);
return 1;
}
/*
** command:
** output on a socket only !
** a reply code will be sent to connected (caller later)
** {inet_reply, S, Status}
** NOTE! normal sockets use the tcp_inet_commandv
** but distribution still uses the tcp_inet_command!!
*/
static void tcp_inet_command(ErlDrvData e, char *buf, ErlDrvSizeT len)
{
tcp_descriptor* desc = (tcp_descriptor*)e;
ErlDrvTermData caller = driver_caller(desc->inet.port);
desc->inet.caller = caller;
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"tcp_inet_command -> entry\r\n",
__LINE__, desc->inet.s, caller) );
if (!IS_CONNECTED(INETP(desc)))
inet_reply_error(INETP(desc), ENOTCONN);
else if (tcp_send(desc, buf, len) == 0)
inet_reply_ok(INETP(desc));
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"tcp_inet_command -> done\r\n",
__LINE__, desc->inet.s, caller) );
}
static void tcp_inet_commandv(ErlDrvData e, ErlIOVec* ev)
{
tcp_descriptor* desc = (tcp_descriptor*)e;
ErlDrvTermData caller = driver_caller(desc->inet.port);
desc->inet.caller = caller;
#ifdef INET_DRV_DEBUG
/* This function is just called to much to be part of this *
* by default. Atleast as long as there are no 'debug levels'. */
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"tcp_inet_commandv -> entry\r\n",
__LINE__, desc->inet.s, caller) );
#endif
if (!IS_CONNECTED(INETP(desc))) {
if (desc->tcp_add_flags & TCP_ADDF_DELAYED_CLOSE_SEND) {
desc->tcp_add_flags &= ~TCP_ADDF_DELAYED_CLOSE_SEND;
if (desc->tcp_add_flags & TCP_ADDF_DELAYED_ECONNRESET) {
/* Don't clear flag. Leave it enabled for the next receive
* operation.
*/
inet_reply_error(INETP(desc), ECONNRESET);
} else
inet_reply_error_am(INETP(desc), am_closed);
}
else
inet_reply_error(INETP(desc), ENOTCONN);
}
else if (desc->tcp_add_flags & TCP_ADDF_PENDING_SHUTDOWN)
tcp_shutdown_error(desc, EPIPE);
else if (tcp_sendv(desc, ev) == 0)
inet_reply_ok(INETP(desc));
#ifdef INET_DRV_DEBUG
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] tcp_inet_commandv -> done\r\n",
__LINE__, desc->inet.s, caller) );
#endif
}
static void tcp_inet_flush(ErlDrvData e)
{
tcp_descriptor* desc = (tcp_descriptor*)e;
int discard_output;
/* Discard send queue to avoid hanging port (OTP-7615) */
discard_output = !(desc->inet.event_mask & FD_WRITE);
discard_output |= desc->tcp_add_flags & TCP_ADDF_LINGER_ZERO;
#ifdef HAVE_SENDFILE
/* The old file driver aborted when it was stopped during sendfile, so
* we'll clear the flag and discard all output. It is the job of
* tcp_inet_stop to close the extra sendfile fd. */
if(desc->tcp_add_flags & TCP_ADDF_SENDFILE) {
discard_output = 1;
}
#endif
if (discard_output) {
tcp_clear_output(desc);
}
}
static void tcp_inet_process_exit(ErlDrvData e, ErlDrvMonitor *monitorp)
{
tcp_descriptor* desc = (tcp_descriptor*)e;
ErlDrvTermData who = driver_get_monitored_process(desc->inet.port,monitorp);
int state = desc->inet.state;
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%p] "
"tcp_inet_process_exit -> entry with"
"\r\n who: %T\r\n",
__LINE__, desc->inet.s, desc->inet.port, who) );
if ((state & INET_STATE_MULTI_ACCEPTING) == INET_STATE_MULTI_ACCEPTING) {
int id,req;
MultiTimerData *timeout;
if (remove_multi_op(desc, &id, &req, who, &timeout, NULL) != 0) {
return;
}
if (timeout != NULL) {
remove_multi_timer(desc, desc->inet.port, timeout);
}
if (desc->multi_first == NULL) {
sock_select(INETP(desc),FD_ACCEPT,0);
desc->inet.state = INET_STATE_LISTENING; /* restore state */
}
} else if ((state & INET_STATE_ACCEPTING) == INET_STATE_ACCEPTING) {
int did,drid;
ErlDrvTermData dcaller;
deq_async(INETP(desc), &did, &dcaller, &drid);
driver_cancel_timer(desc->inet.port);
sock_select(INETP(desc),FD_ACCEPT,0);
desc->inet.state = INET_STATE_LISTENING; /* restore state */
}
DDBG(INETP(desc),
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%p] "
"tcp_inet_process_exit -> done\r\n",
__LINE__, desc->inet.s, desc->inet.port) );
}
static void inet_stop_select(ErlDrvEvent event, void* _)
{
#ifdef __WIN32__
WSACloseEvent((HANDLE)event);
#else
sock_close((SOCKET)(long)event);
#endif
}
/* The peer socket has closed, cleanup and send event */
static int tcp_recv_closed(tcp_descriptor* desc)
{
#ifdef DEBUG
ErlDrvPort port = desc->inet.port; /* Used after driver_exit() */
#endif
int blocking_send = 0;
DEBUGF(("tcp_recv_closed(%p): s=%d, in %s, line %d\r\n",
port, desc->inet.s, __LINE__));
if (IS_BUSY(INETP(desc))) {
/* A send is blocked */
desc->inet.caller = desc->inet.busy_caller;
tcp_clear_output(desc);
if (desc->busy_on_send) {
cancel_multi_timer(desc, INETP(desc)->port, &tcp_inet_send_timeout);
desc->busy_on_send = 0;
DEBUGF(("tcp_recv_closed(%p): busy on send\r\n", port));
}
desc->inet.state &= ~INET_F_BUSY;
set_busy_port(desc->inet.port, 0);
inet_reply_error_am(INETP(desc), am_closed);
DEBUGF(("tcp_recv_closed(%p): busy reply 'closed'\r\n", port));
blocking_send = 1;
}
#ifdef HAVE_SENDFILE
if (desc->tcp_add_flags & TCP_ADDF_SENDFILE) {
tcp_sendfile_aborted(desc, ENOTCONN);
blocking_send = 1;
}
#endif
if (!blocking_send) {
/* No blocking send op to reply to right now.
* If next op is a send, make sure it returns {error,closed}
* rather than {error,enotconn}.
*/
desc->tcp_add_flags |= TCP_ADDF_DELAYED_CLOSE_SEND;
}
if (!desc->inet.active) {
/* We must cancel any timer here ! */
clean_multi_timers(desc, INETP(desc)->port);
/* passive mode do not terminate port ! */
tcp_clear_input(desc);
if (desc->inet.exitf) {
tcp_desc_close(desc);
} else {
desc_close_read(INETP(desc));
}
async_error_am_all(INETP(desc), am_closed);
/* next time EXBADSEQ will be delivered */
DEBUGF(("tcp_recv_closed(%p): passive reply all 'closed'\r\n",
port));
} else {
tcp_clear_input(desc);
tcp_closed_message(desc);
if (desc->inet.exitf) {
driver_exit(desc->inet.port, 0);
} else {
desc_close_read(INETP(desc));
}
DEBUGF(("tcp_recv_closed(%p): active close\r\n", port));
}
DEBUGF(("tcp_recv_closed(%p): done\r\n", port));
return -1;
}
/* We have a read error determine the action */
static int tcp_recv_error(tcp_descriptor* desc, int err)
{
if (err != ERRNO_BLOCK) {
if (IS_BUSY(INETP(desc))) {
/* A send is blocked */
desc->inet.caller = desc->inet.busy_caller;
tcp_clear_output(desc);
if (desc->busy_on_send) {
cancel_multi_timer(desc, INETP(desc)->port, &tcp_inet_send_timeout);
desc->busy_on_send = 0;
}
desc->inet.state &= ~INET_F_BUSY;
set_busy_port(desc->inet.port, 0);
inet_reply_error_am(INETP(desc), am_closed);
}
#ifdef HAVE_SENDFILE
if (desc->tcp_add_flags & TCP_ADDF_SENDFILE) {
tcp_sendfile_aborted(desc, err);
}
#endif
if (!desc->inet.active) {
/* We must cancel any timer here ! */
clean_multi_timers(desc, INETP(desc)->port);
tcp_clear_input(desc);
if (desc->inet.exitf) {
tcp_desc_close(desc);
} else {
desc_close_read(INETP(desc));
}
async_error_am_all(INETP(desc), error_atom(err));
} else {
tcp_clear_input(desc);
tcp_error_message(desc, err); /* first error */
tcp_closed_message(desc); /* then closed */
if (desc->inet.exitf)
driver_exit(desc->inet.port, err);
else
desc_close_read(INETP(desc));
}
return -1;
}
return 0;
}
/*
** Calculate number of bytes that remain to read before deliver
** Assume buf, ptr_start, ptr has been setup
**
** return > 0 if more to read
** = 0 if holding complete packet
** < 0 on error
**
** if return value == 0 then *len will hold the length of the first packet
** return value > 0 then if *len == 0 then value means upperbound
** *len > 0 then value means exact
**
*/
static int tcp_remain(tcp_descriptor* desc, int* len)
{
char* ptr = desc->i_ptr_start;
int nfill = (desc->i_ptr - desc->i_buf->orig_bytes); /* filled */
int nsz = desc->i_bufsz - nfill; /* remain */
int n = desc->i_ptr - ptr; /* number of bytes read */
int tlen;
tlen = packet_get_length(desc->inet.htype, ptr, n,
desc->inet.psize, desc->i_bufsz,
desc->inet.delimiter, &desc->http_state);
DEBUGF(("tcp_remain(%p): s=%d, n=%d, nfill=%d nsz=%d, tlen %d\r\n",
desc->inet.port, desc->inet.s, n, nfill, nsz, tlen));
if (tlen > 0) {
if (tlen <= n) { /* got a packet */
*len = tlen;
DEBUGF((" => nothing remain packet=%d\r\n", tlen));
return 0;
}
else { /* need known more */
if (tcp_expand_buffer(desc, tlen) < 0)
return -1;
*len = tlen - n;
DEBUGF((" => remain=%d\r\n", *len));
return *len;
}
}
else if (tlen == 0) { /* need unknown more */
*len = 0;
if (nsz == 0) {
if (nfill == n) {
if (desc->inet.psize != 0 && desc->inet.psize > nfill) {
if (tcp_expand_buffer(desc, desc->inet.psize) < 0)
return -1;
return desc->inet.psize;
}
else
goto error;
}
DEBUGF((" => restart more=%d\r\n", nfill - n));
return nfill - n;
}
else {
DEBUGF((" => more=%d \r\n", nsz));
return nsz;
}
}
error:
DEBUGF((" => packet error\r\n"));
return -1;
}
/*
** Deliver all packets ready
** if len == 0 then check start with a check for ready packet
*/
static int tcp_deliver(tcp_descriptor* desc, int len)
{
int count = 0;
int n;
/* Poll for ready packet */
if (len == 0) {
/* empty buffer or waiting for more input */
if ((desc->i_buf == NULL) || (desc->i_remain > 0))
return 0;
if ((n = tcp_remain(desc, &len)) != 0) {
if (n < 0) /* packet error */
return n;
if (len > 0) /* more data pending */
desc->i_remain = len;
return 0;
}
}
while (len > 0) {
int code;
inet_input_count(INETP(desc), len);
/* deliver binary? */
if (len*4 >= desc->i_buf->orig_size*3) { /* >=75% */
code = tcp_reply_binary_data(desc, desc->i_buf,
(desc->i_ptr_start -
desc->i_buf->orig_bytes),
len);
if (code < 0)
return code;
/* something after? */
if (desc->i_ptr_start + len == desc->i_ptr) { /* no */
tcp_clear_input(desc);
}
else { /* move trail to beginning of a new buffer */
ErlDrvBinary* bin = alloc_buffer(desc->i_bufsz);
char* ptr_end = desc->i_ptr_start + len;
int sz = desc->i_ptr - ptr_end;
memcpy(bin->orig_bytes, ptr_end, sz);
free_buffer(desc->i_buf);
desc->i_buf = bin;
desc->i_ptr_start = desc->i_buf->orig_bytes;
desc->i_ptr = desc->i_ptr_start + sz;
desc->i_remain = 0;
}
}
else {
code = tcp_reply_data(desc, desc->i_ptr_start, len);
/* XXX The buffer gets thrown away on error (code < 0) */
/* Windows needs workaround for this in tcp_inet_event... */
if (code < 0)
return code;
desc->i_ptr_start += len;
if (desc->i_ptr_start == desc->i_ptr)
tcp_clear_input(desc);
else
desc->i_remain = 0;
}
count++;
len = 0;
if (!desc->inet.active) {
cancel_multi_timer(desc, INETP(desc)->port, &tcp_inet_recv_timeout);
sock_select(INETP(desc),(FD_READ|FD_CLOSE),0);
if (desc->i_buf != NULL)
tcp_restart_input(desc);
}
else if (desc->i_buf != NULL) {
if ((n = tcp_remain(desc, &len)) != 0) {
if (n < 0) /* packet error */
return n;
tcp_restart_input(desc);
if (len > 0)
desc->i_remain = len;
len = 0;
}
}
}
return count;
}
static int tcp_recv(tcp_descriptor* desc, int request_len)
{
int n;
int len;
int nread;
if (desc->i_buf == NULL) { /* allocate a read buffer */
int sz = (request_len > 0) ? request_len : desc->inet.bufsz;
if ((desc->i_buf = alloc_buffer(sz)) == NULL)
return -1;
/* XXX: changing bufsz during recv SHOULD/MAY? affect
* ongoing operation but is not now
*/
desc->i_bufsz = sz; /* use i_bufsz not i_buf->orig_size ! */
desc->i_ptr_start = desc->i_buf->orig_bytes;
desc->i_ptr = desc->i_ptr_start;
nread = sz;
if (request_len > 0)
desc->i_remain = request_len;
else
desc->i_remain = 0;
}
else if (request_len > 0) { /* we have a data in buffer and a request */
n = desc->i_ptr - desc->i_ptr_start;
if (n >= request_len)
return tcp_deliver(desc, request_len);
else if (tcp_expand_buffer(desc, request_len) < 0)
return tcp_recv_error(desc, ENOMEM);
else
desc->i_remain = nread = request_len - n;
}
else if (desc->i_remain == 0) { /* poll remain from buffer data */
if ((nread = tcp_remain(desc, &len)) < 0)
return tcp_recv_error(desc, EMSGSIZE);
else if (nread == 0)
return tcp_deliver(desc, len);
else if (len > 0)
desc->i_remain = len; /* set remain */
}
else /* remain already set use it */
nread = desc->i_remain;
DEBUGF(("tcp_recv(%p): s=%d about to read %d bytes...\r\n",
desc->inet.port, desc->inet.s, nread));
n = sock_recv(desc->inet.s, desc->i_ptr, nread, 0);
if (IS_SOCKET_ERROR(n)) {
int err = sock_errno();
if (err == ECONNRESET) {
DEBUGF((" => detected close (connreset)\r\n"));
if (desc->tcp_add_flags & TCP_ADDF_SHOW_ECONNRESET)
return tcp_recv_error(desc, err);
else
return tcp_recv_closed(desc);
}
if (err == ERRNO_BLOCK) {
DEBUGF((" => would block\r\n"));
return 0;
}
else {
DEBUGF((" => error: %d\r\n", err));
return tcp_recv_error(desc, err);
}
}
else if (n == 0) {
DEBUGF((" => detected close\r\n"));
return tcp_recv_closed(desc);
}
DEBUGF((" => got %d bytes\r\n", n));
desc->i_ptr += n;
if (desc->i_remain > 0) {
desc->i_remain -= n;
if (desc->i_remain == 0)
return tcp_deliver(desc, desc->i_ptr - desc->i_ptr_start);
}
else {
nread = tcp_remain(desc, &len);
if (nread < 0)
return tcp_recv_error(desc, EMSGSIZE);
else if (nread == 0)
return tcp_deliver(desc, len);
else if (len > 0)
desc->i_remain = len; /* set remain */
}
return 0;
}
#ifdef __WIN32__
static int winsock_event_select(inet_descriptor *desc, int flags, int on)
{
int save_event_mask = desc->event_mask;
desc->forced_events &= FD_CLOSE;
if (on)
desc->event_mask |= flags;
else
desc->event_mask &= (~flags);
DEBUGF(("port %d: winsock_event_select: "
"flags=%02X, on=%d, event_mask=%02X\n",
desc->port, flags, on, desc->event_mask));
/* The RIGHT WAY (TM) to do this is to make sure:
A) The cancelling of all network events is done with
NULL as the event parameter (bug in NT's winsock),
B) The actual event handle is reset so that it is only
raised if one of the requested network events is active,
C) Avoid race conditions by making sure that the event cannot be set
while we are preparing to set the correct network event mask.
The simplest way to do it is to turn off all events, reset the
event handle and then, if event_mask != 0, turn on the appropriate
events again. */
if (WSAEventSelect(desc->s, NULL, 0) != 0) {
DEBUGF(("port %d: winsock_event_select: "
"WSAEventSelect returned error, code %d.\n",
sock_errno()));
desc->event_mask = save_event_mask;
return -1;
}
if (!ResetEvent(desc->event)) {
DEBUGF(("port %d: winsock_event_select: "
"ResetEvent returned error, code %d.\n",
GetLastError()));
desc->event_mask = 0;
return -1;
}
if (desc->event_mask != 0) {
if (WSAEventSelect(desc->s,
desc->event,
desc->event_mask) != 0) {
DEBUGF(("port %d: winsock_event_select: "
"WSAEventSelect returned error, code %d.\n",
sock_errno()));
desc->event_mask = 0;
return -1;
}
/* Now, WSAEventSelect() is triggered only when the queue goes from
full to empty or from empty to full; therefore we need an extra test
to see whether it is writeable, readable or closed... */
if ((desc->event_mask & FD_WRITE)) {
int do_force = 1;
if (desc->send_would_block) {
TIMEVAL tmo = {0,0};
FD_SET fds;
int ret;
FD_ZERO(&fds);
FD_SET(desc->s,&fds);
do_force = (select(desc->s+1,0,&fds,0,&tmo) > 0);
}
if (do_force) {
SetEvent(desc->event);
desc->forced_events |= FD_WRITE;
}
}
if ((desc->event_mask & (FD_READ|FD_CLOSE))) {
int readable = 0;
int closed = 0;
TIMEVAL tmo = {0,0};
FD_SET fds;
int ret;
unsigned long arg;
FD_ZERO(&fds);
FD_SET(desc->s,&fds);
ret = select(desc->s+1,&fds,0,0,&tmo);
if (ret > 0) {
++readable;
if (ioctlsocket(desc->s,FIONREAD,&arg) != 0) {
++closed; /* Which gives a FD_CLOSE event */
} else {
closed = (arg == 0);
}
}
if ((desc->event_mask & FD_READ) && readable && !closed) {
SetEvent(desc->event);
desc->forced_events |= FD_READ;
}
if ((desc->event_mask & FD_CLOSE) && closed) {
SetEvent(desc->event);
desc->forced_events |= FD_CLOSE;
}
}
}
return 0;
}
static void tcp_inet_event(ErlDrvData e, ErlDrvEvent event)
{
tcp_descriptor* desc = (tcp_descriptor*)e;
WSANETWORKEVENTS netEv;
int err;
DEBUGF(("tcp_inet_event(%p) {s=%d\r\n",
desc->inet.port, desc->inet.s));
if (WSAEnumNetworkEvents(desc->inet.s, desc->inet.event,
&netEv) != 0) {
DEBUGF((" => EnumNetworkEvents = %d\r\n", sock_errno() ));
goto error;
}
DEBUGF((" => event=%02X, mask=%02X, forced=%02X\r\n",
netEv.lNetworkEvents, desc->inet.event_mask,
desc->inet.forced_events));
/* Add the forced events. */
netEv.lNetworkEvents |= desc->inet.forced_events;
if (desc->inet.forced_events & FD_CLOSE)
netEv.iErrorCode[FD_CLOSE_BIT] = desc->inet.err;
/*
* Calling WSAEventSelect() with a mask of 0 doesn't always turn off
* all events. To avoid acting on events we don't want, we mask
* the events with mask for the events we really want.
*/
#ifdef DEBUG
if ((netEv.lNetworkEvents & ~(desc->inet.event_mask)) != 0) {
DEBUGF(("port %d: ... unexpected event: %d\r\n",
desc->inet.port, netEv.lNetworkEvents & ~(desc->inet.event_mask)));
}
#endif
netEv.lNetworkEvents &= desc->inet.event_mask;
if (netEv.lNetworkEvents & FD_READ) {
if (tcp_inet_input(desc, event) < 0) {
goto error;
}
if (netEv.lNetworkEvents & FD_CLOSE) {
/* We may not get any more FD_CLOSE events so we
keep this event and always signal it from
this moment on. */
if ((desc->inet.forced_events & FD_CLOSE) == 0) {
desc->inet.forced_events |= FD_CLOSE;
desc->inet.err = netEv.iErrorCode[FD_CLOSE_BIT];
}
/*
* We must loop to read out the remaining packets (if any).
*/
for (;;) {
/* if passive and no subscribers, break loop */
if (!desc->inet.active && desc->inet.opt == NULL) {
/* do not trigger close event when socket is
transitioned to passive */
netEv.lNetworkEvents &= ~FD_CLOSE;
break;
}
DEBUGF(("Retrying read due to FD_CLOSE\r\n"));
if (tcp_inet_input(desc, event) < 0) {
goto error;
}
}
}
}
if (netEv.lNetworkEvents & FD_WRITE) {
desc->inet.send_would_block = 0;
if (tcp_inet_output(desc, event) < 0)
goto error;
}
if (netEv.lNetworkEvents & FD_CONNECT) {
if ((err = netEv.iErrorCode[FD_CONNECT_BIT]) != 0) {
async_error(INETP(desc), err);
} else {
tcp_inet_output(desc, event);
}
} else if (netEv.lNetworkEvents & FD_ACCEPT) {
if ((err = netEv.iErrorCode[FD_ACCEPT_BIT]) != 0)
async_error(INETP(desc), err);
else
tcp_inet_input(desc, event);
}
if (netEv.lNetworkEvents & FD_CLOSE) {
/* error in err = netEv.iErrorCode[FD_CLOSE_BIT] */
DEBUGF(("Detected close in %s, line %d\r\n", __LINE__));
if (desc->tcp_add_flags & TCP_ADDF_SHOW_ECONNRESET) {
err = netEv.iErrorCode[FD_CLOSE_BIT];
if (err == ECONNRESET)
tcp_recv_error(desc, err);
else if (err == ECONNABORTED && IS_CONNECTED(INETP(desc))) {
/* translate this error to ECONNRESET */
tcp_recv_error(desc, ECONNRESET);
}
else
tcp_recv_closed(desc);
}
else
tcp_recv_closed(desc);
}
DEBUGF(("tcp_inet_event(%p) }\r\n", desc->inet.port));
return;
error:
DEBUGF(("tcp_inet_event(%p) error}\r\n",
desc->inet.port));
return;
}
#endif /* __WIN32__ */
/* socket has input:
** 1. INET_STATE_ACCEPTING => non block accept ?
** 2. INET_STATE_CONNECTED => read input
*/
static int tcp_inet_input(tcp_descriptor* desc, HANDLE event)
{
int ret = 0;
#ifdef DEBUG
long port = (long) desc->inet.port; /* Used after driver_exit() */
#endif
ASSERT(!INET_IGNORED(INETP(desc)));
DEBUGF(("tcp_inet_input(%p) {s=%d\r\n", port, desc->inet.s));
/* XXX fprintf(stderr,"tcp_inet_input(%p) {s=%d}\r\n",(long) desc->inet.port, desc->inet.s); */
if (desc->inet.state == INET_STATE_ACCEPTING) {
SOCKET s;
unsigned int len;
inet_address remote;
inet_async_op *this_op = desc->inet.opt;
len = sizeof(desc->inet.remote);
sys_memzero((char *) &remote, len);
s = sock_accept(desc->inet.s, (struct sockaddr*) &remote, &len);
if (s == INVALID_SOCKET && sock_errno() == ERRNO_BLOCK) {
/* Just try again, no real error, just a ghost trigger from poll,
keep the default return code and everything else as is */
goto done;
}
sock_select(INETP(desc),FD_ACCEPT,0);
desc->inet.state = INET_STATE_LISTENING; /* restore state */
if (this_op != NULL) {
driver_demonitor_process(desc->inet.port, &(this_op->monitor));
}
driver_cancel_timer(desc->inet.port); /* posssibly cancel a timer */
if (s == INVALID_SOCKET) {
ret = async_error(INETP(desc), sock_errno());
goto done;
}
else {
ErlDrvTermData caller;
tcp_descriptor* accept_desc;
int err;
if (desc->inet.opt == NULL) {
/* No caller setup */
sock_close(s);
ret = async_error(INETP(desc), EINVAL);
goto done;
}
caller = desc->inet.opt->caller;
if ((accept_desc = tcp_inet_copy(desc,s,caller,&err)) == NULL) {
sock_close(s);
ret = async_error(INETP(desc), err);
goto done;
}
/* FIXME: may MUST lock port
* 1 - Port is accessible via the erlang:ports()
* 2 - Port is accessible via callers process_info(links)
*/
accept_desc->inet.remote = remote;
SET_NONBLOCKING(accept_desc->inet.s);
#ifdef __WIN32__
driver_select(accept_desc->inet.port, accept_desc->inet.event,
ERL_DRV_READ, 1);
#endif
accept_desc->inet.state = INET_STATE_CONNECTED;
ret = async_ok_port(INETP(desc), accept_desc->inet.dport);
goto done;
}
} else if (desc->inet.state == INET_STATE_MULTI_ACCEPTING) {
SOCKET s;
unsigned int len;
inet_address remote;
int id,req;
ErlDrvTermData caller;
MultiTimerData *timeout;
ErlDrvMonitor monitor;
#ifdef HARDDEBUG
int times = 0;
#endif
while (desc->inet.state == INET_STATE_MULTI_ACCEPTING) {
len = sizeof(desc->inet.remote);
sys_memzero((char *) &remote, len);
s = sock_accept(desc->inet.s, (struct sockaddr*) &remote, &len);
if (s == INVALID_SOCKET && sock_errno() == ERRNO_BLOCK) {
/* Just try again, no real error, keep the last return code */
goto done;
}
#ifdef HARDDEBUG
if (++times > 1) {
erts_fprintf(stderr,"Accepts in one suite: %d :-)\r\n",times);
}
#endif
if (deq_multi_op(desc,&id,&req,&caller,&timeout,&monitor) != 0) {
ret = -1;
goto done;
}
if (desc->multi_first == NULL) {
sock_select(INETP(desc),FD_ACCEPT,0);
desc->inet.state = INET_STATE_LISTENING; /* restore state */
}
if (timeout != NULL) {
remove_multi_timer(desc, desc->inet.port, timeout);
}
driver_demonitor_process(desc->inet.port, &monitor);
if (s == INVALID_SOCKET) { /* Not ERRNO_BLOCK, that's handled right away */
ret = send_async_error(desc->inet.dport,
id, caller, error_atom(sock_errno()));
goto done;
}
else {
tcp_descriptor* accept_desc;
int err;
if ((accept_desc = tcp_inet_copy(desc,s,caller,&err)) == NULL) {
sock_close(s);
ret = send_async_error(desc->inet.dport,
id, caller, error_atom(err));
goto done;
}
accept_desc->inet.remote = remote;
SET_NONBLOCKING(accept_desc->inet.s);
#ifdef __WIN32__
driver_select(accept_desc->inet.port, accept_desc->inet.event,
ERL_DRV_READ, 1);
#endif
accept_desc->inet.state = INET_STATE_CONNECTED;
ret = send_async_ok_port(desc->inet.dport,
id, caller, accept_desc->inet.dport);
}
}
}
else if (IS_CONNECTED(INETP(desc))) {
ret = tcp_recv(desc, 0);
goto done;
}
else {
/* maybe a close op from connection attempt?? */
sock_select(INETP(desc),FD_ACCEPT,0);
DEBUGF(("tcp_inet_input(%p): s=%d bad state: %04x\r\n",
port, desc->inet.s, desc->inet.state));
}
done:
DEBUGF(("tcp_inet_input(%p) }\r\n", port));
return ret;
}
static int tcp_send_or_shutdown_error(tcp_descriptor* desc, int err)
{
int show_econnreset = (err == ECONNRESET
&& desc->tcp_add_flags & TCP_ADDF_SHOW_ECONNRESET);
/*
* If the port is busy, we must do some clean-up before proceeding.
*/
if (IS_BUSY(INETP(desc))) {
desc->inet.caller = desc->inet.busy_caller;
if (desc->busy_on_send) {
cancel_multi_timer(desc, INETP(desc)->port, &tcp_inet_send_timeout);
desc->busy_on_send = 0;
}
desc->inet.state &= ~INET_F_BUSY;
set_busy_port(desc->inet.port, 0);
}
/*
* We used to handle "expected errors" differently from unexpected ones.
* Now we handle all errors in the same way (unless the show_econnreset
* socket option is enabled). We just have to distinguish between passive
* and active sockets.
*/
DEBUGF(("driver_failure_eof(%p) in %s, line %d\r\n",
desc->inet.port, __LINE__));
if (desc->inet.active) {
ErlDrvTermData err_atom;
if (show_econnreset) {
tcp_error_message(desc, err);
err_atom = error_atom(err);
} else {
err_atom = am_closed;
}
tcp_closed_message(desc);
if (!(desc->tcp_add_flags & TCP_ADDF_SENDFILE))
inet_reply_error_am(INETP(desc), err_atom);
if (desc->inet.exitf)
driver_exit(desc->inet.port, 0);
else
tcp_desc_close(desc);
} else {
tcp_close_check(desc);
if (desc->inet.caller) {
if (!(desc->tcp_add_flags & TCP_ADDF_SENDFILE)) {
if (show_econnreset)
inet_reply_error(INETP(desc), err);
else
inet_reply_error_am(INETP(desc), am_closed);
}
}
else {
/* No blocking send op to reply to right now.
* If next op is a send, make sure it returns {error,closed}
* rather than {error,enotconn}.
*/
desc->tcp_add_flags |= TCP_ADDF_DELAYED_CLOSE_SEND;
}
tcp_desc_close(desc);
/*
* Make sure that the next receive operation gets an {error,closed}
* result rather than {error,enotconn}. That means that the caller
* can safely ignore errors in the send operations and handle them
* in the receive operation.
*/
desc->tcp_add_flags |= TCP_ADDF_DELAYED_CLOSE_RECV;
if (show_econnreset) {
/* Return {error, econnreset} instead of {error, closed}
* on send or receive operations.
*/
desc->tcp_add_flags |= TCP_ADDF_DELAYED_ECONNRESET;
}
}
return -1;
}
static int tcp_send_error(tcp_descriptor* desc, int err)
{
/* EPIPE errors usually occur in one of three ways:
* 1. We write to a socket when we've already shutdown() the write side. On
* Windows the error returned for this is ESHUTDOWN rather than EPIPE.
* 2. The TCP peer sends us an RST through no fault of our own (perhaps
* by aborting the connection using SO_LINGER) and we then attempt
* to write to the socket. On Linux and Windows we would actually
* receive an ECONNRESET error for this, but on the BSDs, Darwin,
* Illumos and presumably Solaris, it's an EPIPE.
* 3. We cause the TCP peer to send us an RST by writing to a socket
* after we receive a FIN from them. Our first write will be
* successful, but if the they have closed the connection (rather
* than just shutting down the write side of it) this will cause their
* OS to send us an RST. Then, when we attempt to write to the socket
* a second time, we will get an EPIPE error. On Windows we get an
* ECONNABORTED.
*
* What we are going to do here is to treat all EPIPE messages that aren't
* of type 1 as ECONNRESET errors. This will allow users who have the
* show_econnreset socket option enabled to receive {error, econnreset} on
* both send and recv operations to indicate that an RST has been received.
*/
#ifdef __WIN_32__
if (err == ECONNABORTED)
err = ECONNRESET;
#endif
if (err == EPIPE && !(desc->tcp_add_flags & TCP_ADDF_SHUTDOWN_WR_DONE))
err = ECONNRESET;
return tcp_send_or_shutdown_error(desc, err);
}
static int tcp_shutdown_error(tcp_descriptor* desc, int err)
{
return tcp_send_or_shutdown_error(desc, err);
}
static int tcp_inet_delay_send(ErlDrvData data, ErlDrvTermData dummy)
{
tcp_descriptor *desc = (tcp_descriptor*)data;
return tcp_inet_output(desc, (HANDLE) INETP(desc)->s);
}
/*
** Send non-blocking vector data
*/
static int tcp_sendv(tcp_descriptor* desc, ErlIOVec* ev)
{
ErlDrvSizeT sz;
char buf[4];
ErlDrvSizeT h_len;
ssize_t n;
ErlDrvPort ix = desc->inet.port;
ErlDrvSizeT len = ev->size;
switch(desc->inet.htype) {
case TCP_PB_1:
put_int8(len, buf);
h_len = 1;
break;
case TCP_PB_2:
put_int16(len, buf);
h_len = 2;
break;
case TCP_PB_4:
put_int32(len, buf);
h_len = 4;
break;
default:
h_len = 0;
break;
}
inet_output_count(INETP(desc), len+h_len);
if (h_len > 0) {
ev->iov[0].iov_base = buf;
ev->iov[0].iov_len = h_len;
ev->size += h_len;
}
sz = driver_sizeq(ix);
if ((desc->tcp_add_flags & TCP_ADDF_SENDFILE) || sz > 0) {
driver_enqv(ix, ev, 0);
if (sz+ev->size >= desc->high) {
if (desc->send_timeout == 0) {
/* Shortcut to speed up polling of high water mark */
inet_reply_error_am(INETP(desc), am_timeout);
return 1;
}
DEBUGF(("tcp_sendv(%p): s=%d, sender forced busy\r\n",
desc->inet.port, desc->inet.s));
desc->inet.state |= INET_F_BUSY; /* mark for low-watermark */
desc->inet.busy_caller = desc->inet.caller;
set_busy_port(desc->inet.port, 1);
if (desc->send_timeout != INET_INFINITY) {
desc->busy_on_send = 1;
add_multi_timer(desc, INETP(desc)->port,
0 /* arg */, desc->send_timeout /* timeout */,
&tcp_inet_send_timeout);
}
return 1;
}
}
else {
int vsize;
if ((h_len == 0) && (len == 0)) /* Shortcut for empty send */
return 0;
vsize = (ev->vsize > MAX_VSIZE) ? MAX_VSIZE : ev->vsize;
DEBUGF(("tcp_sendv(%p): s=%d, "
"about to send "LLU","LLU" bytes\r\n",
desc->inet.port, desc->inet.s,
(llu_t)h_len, (llu_t)len));
if (INET_IGNORED(INETP(desc))) {
INETP(desc)->flags |= INET_IGNORE_WRITE;
n = 0;
} else if (desc->tcp_add_flags & TCP_ADDF_DELAY_SEND) {
driver_enqv(ix, ev, 0);
add_multi_timer(desc, INETP(desc)->port, 0,
0, &tcp_inet_delay_send);
return 0;
} else if (IS_SOCKET_ERROR(sock_sendv(desc->inet.s, ev->iov,
vsize, &n, 0))) {
if ((sock_errno() != ERRNO_BLOCK) && (sock_errno() != EINTR)) {
int err = sock_errno();
DEBUGF(("tcp_sendv(%p): s=%d, "
"sock_sendv(size=2) errno = %d\r\n",
desc->inet.port, desc->inet.s, err));
return tcp_send_error(desc, err);
}
#ifdef __WIN32__
desc->inet.send_would_block = 1;
#endif
n = 0;
}
else if (n == ev->size) {
ASSERT(NO_SUBSCRIBERS(&INETP(desc)->empty_out_q_subs));
return 0;
}
else {
DEBUGF(("tcp_sendv(%p): s=%d, only sent "
LLU"/%d of "LLU"/%d bytes/items\r\n",
desc->inet.port, desc->inet.s,
(llu_t)n, vsize, (llu_t)ev->size, ev->vsize));
}
DEBUGF(("tcp_sendv(%p): s=%d, Send failed, queuing\r\n",
desc->inet.port, desc->inet.s));
driver_enqv(ix, ev, n);
if (!INET_IGNORED(INETP(desc)))
sock_select(INETP(desc),(FD_WRITE|FD_CLOSE), 1);
}
return 0;
}
/*
** Send non blocking data
*/
static int tcp_send(tcp_descriptor* desc, char* ptr, ErlDrvSizeT len)
{
ErlDrvSizeT sz;
char buf[4];
int h_len;
int n;
ErlDrvPort ix = desc->inet.port;
SysIOVec iov[2];
switch(desc->inet.htype) {
case TCP_PB_1:
put_int8(len, buf);
h_len = 1;
break;
case TCP_PB_2:
put_int16(len, buf);
h_len = 2;
break;
case TCP_PB_4:
put_int32(len, buf);
h_len = 4;
break;
default:
h_len = 0;
break;
}
inet_output_count(INETP(desc), len+h_len);
sz = driver_sizeq(ix);
if ((desc->tcp_add_flags & TCP_ADDF_SENDFILE) || sz > 0) {
if (h_len > 0)
driver_enq(ix, buf, h_len);
driver_enq(ix, ptr, len);
if (sz+h_len+len >= desc->high) {
if (desc->send_timeout == 0) {
/* Shortcut to speed up polling of high water mark */
inet_reply_error_am(INETP(desc), am_timeout);
return 1;
}
DEBUGF(("tcp_send(%p): s=%d, sender forced busy\r\n",
desc->inet.port, desc->inet.s));
desc->inet.state |= INET_F_BUSY; /* mark for low-watermark */
desc->inet.busy_caller = desc->inet.caller;
set_busy_port(desc->inet.port, 1);
if (desc->send_timeout != INET_INFINITY) {
desc->busy_on_send = 1;
add_multi_timer(desc, INETP(desc)->port,
0 /* arg */, desc->send_timeout /* timeout */,
&tcp_inet_send_timeout);
}
return 1;
}
}
else {
if ((h_len == 0) && (len == 0)) /* Shortcut for empty send */
return 0;
iov[0].iov_base = buf;
iov[0].iov_len = h_len;
iov[1].iov_base = ptr;
iov[1].iov_len = len;
DEBUGF(("tcp_send(%p): s=%d, "
"about to send "LLU","LLU" bytes\r\n",
desc->inet.port, desc->inet.s,
(llu_t)h_len, (llu_t)len));
if (INET_IGNORED(INETP(desc))) {
INETP(desc)->flags |= INET_IGNORE_WRITE;
n = 0;
} else if (desc->tcp_add_flags & TCP_ADDF_DELAY_SEND) {
sock_send(desc->inet.s, buf, 0, 0);
n = 0;
} else if (IS_SOCKET_ERROR(sock_sendv(desc->inet.s,iov,2,&n,0))) {
if ((sock_errno() != ERRNO_BLOCK) && (sock_errno() != EINTR)) {
int err = sock_errno();
DEBUGF(("tcp_send(%p): s=%d, "
"sock_sendv(size=2) errno = %d\r\n",
desc->inet.port, desc->inet.s, err));
return tcp_send_error(desc, err);
}
#ifdef __WIN32__
desc->inet.send_would_block = 1;
#endif
n = 0;
}
else if (n == len+h_len) {
ASSERT(NO_SUBSCRIBERS(&INETP(desc)->empty_out_q_subs));
return 0;
}
DEBUGF(("tcp_send(%p): s=%d, Send failed, queuing",
desc->inet.port, desc->inet.s));
if (n < h_len) {
driver_enq(ix, buf+n, h_len-n);
driver_enq(ix, ptr, len);
}
else {
n -= h_len;
driver_enq(ix, ptr+n, len-n);
}
if (!INET_IGNORED(INETP(desc)))
sock_select(INETP(desc),(FD_WRITE|FD_CLOSE), 1);
}
return 0;
}
/* shutdown on the socket:
** Assume caller has confirmed TCP_ADDF_PENDING_SHUTDOWN is set.
*/
static void tcp_shutdown_async(tcp_descriptor* desc)
{
int how;
how = (desc->tcp_add_flags & TCP_ADDF_PENDING_SHUT_WR) ?
TCP_SHUT_WR : TCP_SHUT_RDWR;
if (IS_SOCKET_ERROR(sock_shutdown(INETP(desc)->s, how)))
tcp_shutdown_error(desc, sock_errno());
else
desc->tcp_add_flags |= TCP_ADDF_SHUTDOWN_WR_DONE;
}
static void tcp_inet_drv_output(ErlDrvData data, ErlDrvEvent event)
{
(void)tcp_inet_output((tcp_descriptor*)data, (HANDLE)event);
}
static void tcp_inet_drv_input(ErlDrvData data, ErlDrvEvent event)
{
(void)tcp_inet_input((tcp_descriptor*)data, (HANDLE)event);
}
#ifdef HAVE_SENDFILE
static int tcp_sendfile_completed(tcp_descriptor* desc) {
ErlDrvTermData spec[LOAD_PORT_CNT + LOAD_TUPLE_CNT * 2 +
LOAD_ATOM_CNT * 2 + LOAD_UINT_CNT * 2];
Uint32 sent_low, sent_high;
int i;
desc->tcp_add_flags &= ~TCP_ADDF_SENDFILE;
close(desc->sendfile.dup_file_fd);
DEBUGF(("tcp_sendfile_completed(%p): SENDFILE dup closed %d\r\n",
desc->inet.port, desc->sendfile.dup_file_fd));
/* While we flushed the output queue prior to sending the file, we've
* deferred clearing busy status until now as there's no point in doing so
* while we still have a file to send.
*
* The watermark is checked since more data may have been added while we
* were sending the file. */
if (driver_sizeq(desc->inet.port) <= desc->low) {
if (IS_BUSY(INETP(desc))) {
desc->inet.caller = desc->inet.busy_caller;
desc->inet.state &= ~INET_F_BUSY;
set_busy_port(desc->inet.port, 0);
/* if we have a timer then cancel and send ok to client */
if (desc->busy_on_send) {
cancel_multi_timer(desc, INETP(desc)->port,
&tcp_inet_send_timeout);
desc->busy_on_send = 0;
}
inet_reply_ok(INETP(desc));
}
}
if (driver_sizeq(desc->inet.port) == 0) {
sock_select(INETP(desc), FD_WRITE, 0);
send_empty_out_q_msgs(INETP(desc));
if (desc->tcp_add_flags & TCP_ADDF_PENDING_SHUTDOWN) {
tcp_shutdown_async(desc);
}
}
sent_low = ((Uint64)desc->sendfile.bytes_sent >> 0) & 0xFFFFFFFF;
sent_high = ((Uint64)desc->sendfile.bytes_sent >> 32) & 0xFFFFFFFF;
i = LOAD_ATOM(spec, 0, am_sendfile);
i = LOAD_PORT(spec, i, desc->inet.dport);
i = LOAD_ATOM(spec, i, am_ok);
i = LOAD_UINT(spec, i, sent_low);
i = LOAD_UINT(spec, i, sent_high);
i = LOAD_TUPLE(spec, i, 3);
i = LOAD_TUPLE(spec, i, 3);
ASSERT(i == sizeof(spec)/sizeof(*spec));
return erl_drv_output_term(desc->inet.dport, spec, i);
}
static int tcp_sendfile_aborted(tcp_descriptor* desc, int socket_error) {
ErlDrvTermData spec[LOAD_PORT_CNT + LOAD_TUPLE_CNT * 2 + LOAD_ATOM_CNT * 3];
int i;
/* We don't clean up sendfile state here, as that's done in tcp_desc_close
* following normal error handling. All we do here is report the failure. */
i = LOAD_ATOM(spec, 0, am_sendfile);
i = LOAD_PORT(spec, i, desc->inet.dport);
i = LOAD_ATOM(spec, i, am_error);
switch (socket_error) {
case ECONNRESET:
case ENOTCONN:
case EPIPE:
i = LOAD_ATOM(spec, i, am_closed);
break;
default:
i = LOAD_ATOM(spec, i, error_atom(socket_error));
}
i = LOAD_TUPLE(spec, i, 2);
i = LOAD_TUPLE(spec, i, 3);
ASSERT(i == sizeof(spec)/sizeof(*spec));
return erl_drv_output_term(desc->inet.dport, spec, i);
}
static int tcp_inet_sendfile(tcp_descriptor* desc) {
ErlDrvPort ix = desc->inet.port;
int result = 0;
ssize_t n;
DEBUGF(("tcp_inet_sendfile(%p) {s=%d\r\n",
ix, desc->inet.s));
/* If there was any data in the queue by the time sendfile was issued,
* we'll need to skip it first. Note that we don't clear busy status until
* we're finished sending the file. */
while (desc->sendfile.ioq_skip > 0) {
ssize_t bytes_to_send;
SysIOVec* iov;
int vsize;
ASSERT(driver_sizeq(ix) >= desc->sendfile.ioq_skip);
if ((iov = driver_peekq(ix, &vsize)) == NULL) {
ERTS_INTERNAL_ERROR("ioq empty when sendfile.ioq_skip > 0");
}
bytes_to_send = MIN(desc->sendfile.ioq_skip, iov[0].iov_len);
n = sock_send(desc->inet.s, iov[0].iov_base, bytes_to_send, 0);
if (!IS_SOCKET_ERROR(n)) {
desc->sendfile.ioq_skip -= n;
driver_deq(ix, n);
} else if (sock_errno() == ERRNO_BLOCK) {
#ifdef __WIN32__
desc->inet.send_would_block = 1;
#endif
goto done;
} else if (sock_errno() != EINTR) {
goto socket_error;
}
}
while (desc->sendfile.length > 0) {
/* For some reason the maximum ssize_t cannot be used as the max size.
* 1GB seems to work on all platforms */
const Sint64 SENDFILE_CHUNK_SIZE = ((1UL << 30) - 1);
ssize_t bytes_to_send = MIN(SENDFILE_CHUNK_SIZE, desc->sendfile.length);
off_t offset = desc->sendfile.offset;
#if defined(__linux__)
n = sendfile(desc->inet.s, desc->sendfile.dup_file_fd, &offset,
bytes_to_send);
#elif defined(__FreeBSD__) || defined(__DragonFly__) || defined(__DARWIN__)
{
off_t bytes_sent;
int error;
#if defined(__DARWIN__)
bytes_sent = bytes_to_send;
error = sendfile(desc->sendfile.dup_file_fd, desc->inet.s, offset,
&bytes_sent, NULL, 0);
n = bytes_sent;
#else
error = sendfile(desc->sendfile.dup_file_fd, desc->inet.s, offset,
bytes_to_send, NULL, &bytes_sent, 0);
n = bytes_sent;
#endif
if(error < 0) {
/* EAGAIN/EINTR report partial success by setting bytes_sent,
* so we have to skip error handling if nonzero, and skip EOF
* handling if zero, as it's possible that we didn't manage to
* send anything at all before being interrupted by a
* signal. */
if((errno != EAGAIN && errno != EINTR) || bytes_sent == 0) {
n = -1;
}
}
}
#elif defined(__sun) && defined(__SVR4) && defined(HAVE_SENDFILEV)
{
sendfilevec_t sfvec[1];
size_t bytes_sent;
ssize_t error;
sfvec[0].sfv_fd = desc->sendfile.dup_file_fd;
sfvec[0].sfv_len = bytes_to_send;
sfvec[0].sfv_off = offset;
sfvec[0].sfv_flag = 0;
error = sendfilev(desc->inet.s, sfvec, 1, &bytes_sent);
n = bytes_sent;
if(error < 0) {
if(errno == EINVAL) {
/* On some solaris versions (I've seen it on SunOS 5.10),
* using a sfv_len larger than the filesize will result in
* a (-1 && errno == EINVAL). We translate this to a
* successful send of the data.*/
} else {
/* EAGAIN/EINTR behavior is identical to *BSD. */
if((errno != EAGAIN && errno != EINTR) || bytes_sent == 0) {
n = -1;
}
}
}
}
#else
#error "Unsupported sendfile syscall; update configure test."
#endif
if (n > 0) {
desc->sendfile.bytes_sent += n;
desc->sendfile.offset += n;
desc->sendfile.length -= n;
} else if (n == 0) {
/* EOF. */
desc->sendfile.length = 0;
break;
} else if (IS_SOCKET_ERROR(n) && sock_errno() != EINTR) {
if (sock_errno() != ERRNO_BLOCK) {
goto socket_error;
}
#ifdef __WIN32__
desc->inet.send_would_block = 1;
#endif
break;
}
}
if (desc->sendfile.length == 0) {
tcp_sendfile_completed(desc);
}
goto done;
socket_error: {
int socket_errno = sock_errno();
DEBUGF(("tcp_inet_sendfile(%p): send errno = %d (errno %d)\r\n",
desc->inet.port, socket_errno, errno));
tcp_sendfile_aborted(desc, socket_errno);
result = tcp_send_error(desc, socket_errno);
goto done;
}
done:
DEBUGF(("tcp_inet_sendfile(%p) }\r\n", desc->inet.port));
return result;
}
#endif /* HAVE_SENDFILE */
/* socket ready for output:
** 1. INET_STATE_CONNECTING => non block connect ?
** 2. INET_STATE_CONNECTED => write output
*/
static int tcp_inet_output(tcp_descriptor* desc, HANDLE event)
{
int ret = 0;
ErlDrvPort ix = desc->inet.port;
ASSERT(!INET_IGNORED(INETP(desc)));
DEBUGF(("tcp_inet_output(%p) {s=%d\r\n",
desc->inet.port, desc->inet.s));
if (desc->inet.state == INET_STATE_CONNECTING) {
sock_select(INETP(desc),FD_CONNECT,0);
driver_cancel_timer(ix); /* posssibly cancel a timer */
#ifndef __WIN32__
/*
* XXX This is strange. This *should* work on Windows NT too,
* but doesn't. An bug in Winsock 2.0 for Windows NT?
*
* See "Unix Netwok Programming", W.R.Stevens, p 412 for a
* discussion about Unix portability and non blocking connect.
*/
#ifndef SO_ERROR
{
int sz, code;
sz = sizeof(desc->inet.remote);
sys_memzero((char *) &desc->inet.remote, sz);
code = sock_peer(desc->inet.s,
(struct sockaddr*) &desc->inet.remote, &sz);
if (IS_SOCKET_ERROR(code)) {
desc->inet.state = INET_STATE_OPEN; /* restore state */
ret = async_error(INETP(desc), sock_errno());
goto done;
}
}
#else
{
int error = 0; /* Has to be initiated, we check it */
unsigned int sz = sizeof(error); /* even if we get -1 */
int code = sock_getopt(desc->inet.s, SOL_SOCKET, SO_ERROR,
(void *)&error, &sz);
if ((code < 0) || error) {
desc->inet.state = INET_STATE_OPEN; /* restore state */
ret = async_error(INETP(desc), error);
goto done;
}
}
#endif /* SO_ERROR */
#endif /* !__WIN32__ */
desc->inet.state = INET_STATE_CONNECTED;
if (desc->inet.active)
sock_select(INETP(desc),(FD_READ|FD_CLOSE),1);
async_ok(INETP(desc));
}
else if (IS_CONNECTED(INETP(desc))) {
#ifdef HAVE_SENDFILE
if(desc->tcp_add_flags & TCP_ADDF_SENDFILE) {
return tcp_inet_sendfile(desc);
}
#endif
for (;;) {
int vsize;
ssize_t n;
SysIOVec* iov;
if ((iov = driver_peekq(ix, &vsize)) == NULL) {
sock_select(INETP(desc), FD_WRITE, 0);
send_empty_out_q_msgs(INETP(desc));
if (desc->tcp_add_flags & TCP_ADDF_PENDING_SHUTDOWN)
tcp_shutdown_async(desc);
goto done;
}
vsize = vsize > MAX_VSIZE ? MAX_VSIZE : vsize;
DEBUGF(("tcp_inet_output(%p): s=%d, "
"About to send %d items\r\n",
desc->inet.port, desc->inet.s, vsize));
if (IS_SOCKET_ERROR(sock_sendv(desc->inet.s, iov, vsize, &n, 0))) {
write_error:
if ((sock_errno() != ERRNO_BLOCK) && (sock_errno() != EINTR)) {
DEBUGF(("tcp_inet_output(%p): "
"sock_sendv(%d) errno = %d (errno %d)\r\n",
desc->inet.port, vsize,
sock_errno(), errno));
ret = tcp_send_error(desc, sock_errno());
goto done;
}
#ifdef __WIN32__
desc->inet.send_would_block = 1;
#endif
/* If DELAY_SEND is set ready_output may have
been called without doing select so we do
a select in order to get into the correct
state */
if (desc->tcp_add_flags & TCP_ADDF_DELAY_SEND)
sock_select(INETP(desc), FD_WRITE, 1);
goto done;
} else if (n == 0) { /* Workaround for redhat/CentOS 6.3 returning
0 when sending packets with
sizes > (max 32 bit signed int) */
size_t howmuch = 0x7FFFFFFF; /* max signed 32 bit */
int x;
for(x = 0; x < vsize && iov[x].iov_len == 0; ++x)
;
if (x < vsize) {
if (howmuch > iov[x].iov_len) {
howmuch = iov[x].iov_len;
}
n = sock_send(desc->inet.s, iov[x].iov_base,howmuch,0);
if (IS_SOCKET_ERROR(n)) {
goto write_error;
}
}
}
if (driver_deq(ix, n) <= desc->low) {
if (IS_BUSY(INETP(desc))) {
desc->inet.caller = desc->inet.busy_caller;
desc->inet.state &= ~INET_F_BUSY;
set_busy_port(desc->inet.port, 0);
/* if we have a timer then cancel and send ok to client */
if (desc->busy_on_send) {
cancel_multi_timer(desc, INETP(desc)->port, &tcp_inet_send_timeout);
desc->busy_on_send = 0;
}
inet_reply_ok(INETP(desc));
}
}
}
}
else {
sock_select(INETP(desc),FD_CONNECT,0);
DEBUGF(("tcp_inet_output(%p): bad state: %04x\r\n",
desc->inet.port, desc->inet.state));
}
done:
DEBUGF(("tcp_inet_output(%p) }\r\n", desc->inet.port));
return ret;
}
/*-----------------------------------------------------------------------------
UDP & SCTP (the latter in a 1<->M Mode)
-----------------------------------------------------------------------------*/
#if defined(HAVE_SO_BSDCOMPAT)
#if defined(__linux__)
#include <sys/utsname.h>
static int should_use_so_bsdcompat(void)
{
/* SMP: FIXME this is probably not SMP safe but may be ok anyway? */
static int init_done;
static int so_bsdcompat_is_obsolete;
if (!init_done) {
struct utsname utsname;
unsigned int version, patchlevel;
init_done = 1;
if (uname(&utsname) < 0) {
fprintf(stderr, "uname: %s\r\n", strerror(sock_errno()));
return 1;
}
/* Format is <version>.<patchlevel>.<sublevel><extraversion>
where the first three are unsigned integers and the last
is an arbitrary string. We only care about the first two. */
if (sscanf(utsname.release, "%u.%u", &version, &patchlevel) != 2) {
fprintf(stderr, "uname: unexpected release '%s'\r\n",
utsname.release);
return 1;
}
/* SO_BSDCOMPAT is deprecated and triggers warnings in 2.5
kernels. It is a no-op in 2.4 but not in 2.2 kernels. */
if (version > 2 || (version == 2 && patchlevel >= 5))
so_bsdcompat_is_obsolete = 1;
}
return !so_bsdcompat_is_obsolete;
}
#else /* __linux__ */
#define should_use_so_bsdcompat() 1
#endif /* __linux__ */
#endif /* HAVE_SO_BSDCOMPAT */
#ifdef HAVE_SCTP
/* Copy a descriptor, by creating a new port with same settings
* as the descriptor desc.
* return NULL on error (ENFILE no ports avail)
*/
static ErlDrvData packet_inet_start(ErlDrvPort port, char* args, int protocol);
static udp_descriptor* sctp_inet_copy(udp_descriptor* desc, SOCKET s, int* err)
{
ErlDrvSizeT q_low, q_high;
ErlDrvPort port = desc->inet.port;
udp_descriptor* copy_desc;
copy_desc = (udp_descriptor*) packet_inet_start(port, NULL, IPPROTO_SCTP);
/* Setup event if needed */
if ((copy_desc->inet.s = s) != INVALID_SOCKET) {
if ((copy_desc->inet.event = sock_create_event(INETP(copy_desc))) ==
INVALID_EVENT) {
*err = sock_errno();
FREE(copy_desc);
return NULL;
}
}
/* Some flags must be inherited at this point */
copy_desc->inet.mode = desc->inet.mode;
copy_desc->inet.exitf = desc->inet.exitf;
copy_desc->inet.deliver = desc->inet.deliver;
copy_desc->inet.htype = desc->inet.htype;
copy_desc->inet.psize = desc->inet.psize;
copy_desc->inet.stype = desc->inet.stype;
copy_desc->inet.sfamily = desc->inet.sfamily;
copy_desc->inet.hsz = desc->inet.hsz;
copy_desc->inet.bufsz = desc->inet.bufsz;
/* The new port will be linked and connected to the caller */
port = driver_create_port(port, desc->inet.caller, "sctp_inet",
(ErlDrvData) copy_desc);
if ((long)port == -1) {
*err = ENFILE;
FREE(copy_desc);
return NULL;
}
/* Read busy msgq limits of parent */
q_low = q_high = ERL_DRV_BUSY_MSGQ_READ_ONLY;
erl_drv_busy_msgq_limits(desc->inet.port, &q_low, &q_high);
/* Write same busy msgq limits to child */
erl_drv_busy_msgq_limits(port, &q_low, &q_high);
copy_desc->inet.port = port;
copy_desc->inet.dport = driver_mk_port(port);
*err = 0;
return copy_desc;
}
#endif
#ifdef HAVE_UDP
static int packet_inet_init()
{
sys_memzero((char *)&disassoc_sa, sizeof(disassoc_sa));
#ifdef AF_UNSPEC
disassoc_sa.sa_family = AF_UNSPEC;
#endif /* #ifdef AF_UNSPEC */
disassoc_sa_size = disassoc_sa.sa_data - (char *)&disassoc_sa;
return 0;
}
static ErlDrvData packet_inet_start(ErlDrvPort port, char* args, int protocol)
{
/* "inet_start" returns "ErlDrvData", but in fact it is "inet_descriptor*",
so we can preserve it as "ErlDrvData":
*/
ErlDrvData drvd = inet_start(port, sizeof(udp_descriptor),
protocol);
udp_descriptor* desc = (udp_descriptor*) drvd;
if (desc == NULL)
return ERL_DRV_ERROR_ERRNO;
desc->read_packets = INET_PACKET_POLL;
desc->i_bufsz = 0;
desc->i_buf = NULL;
desc->i_ptr = NULL;
return drvd;
}
static ErlDrvData udp_inet_start(ErlDrvPort port, char *args)
{
ErlDrvData data = packet_inet_start(port, args, IPPROTO_UDP);
set_default_msgq_limits(port);
return data;
}
#endif
#ifdef HAVE_SCTP
static ErlDrvData sctp_inet_start(ErlDrvPort port, char *args)
{
ErlDrvData data = packet_inet_start(port, args, IPPROTO_SCTP);
set_default_msgq_limits(port);
return data;
}
#endif
#ifdef HAVE_UDP
static void packet_inet_stop(ErlDrvData e)
{
/* There should *never* be any "empty out q" subscribers on
an UDP or SCTP socket!
NB: as in "inet_start", we can always cast "ErlDRvData"
into "udp_descriptor*" or "inet_descriptor*":
*/
udp_descriptor * udesc = (udp_descriptor*) e;
inet_descriptor* desc = INETP(udesc);
if (udesc->i_buf != NULL) {
release_buffer(udesc->i_buf);
udesc->i_buf = NULL;
}
ASSERT(NO_SUBSCRIBERS(&(desc->empty_out_q_subs)));
async_error_am_all(desc, am_closed);
inet_stop(desc);
}
static int packet_error(udp_descriptor* udesc, int err)
{
inet_descriptor * desc = INETP(udesc);
if (!desc->active)
async_error(desc, err);
driver_failure_posix(desc->port, err);
return -1;
}
/*
** Various functions accessible via "port_control" on the Erlang side:
*/
static ErlDrvSSizeT packet_inet_ctl(ErlDrvData e, unsigned int cmd, char* buf,
ErlDrvSizeT len, char** rbuf, ErlDrvSizeT rsize)
{
ErlDrvSSizeT replen;
udp_descriptor * udesc = (udp_descriptor *) e;
inet_descriptor* desc = INETP(udesc);
int type = SOCK_DGRAM;
int af = AF_INET;
cmd -= ERTS_INET_DRV_CONTROL_MAGIC_NUMBER;
switch(cmd) {
case INET_REQ_OPEN: /* open socket and return internal index */
DDBG(desc,
("INET-DRV-DBG[%d][%T] packet_inet_ctl -> OPEN\r\n",
__LINE__, driver_caller(desc->port)) );
if (len != 2) {
return ctl_error(EINVAL, rbuf, rsize);
}
switch (buf[0]) {
case INET_AF_INET: af = AF_INET; break;
#if defined(HAVE_IN6) && defined(AF_INET6)
case INET_AF_INET6: af = AF_INET6; break;
#endif
#ifdef HAVE_SYS_UN_H
case INET_AF_LOCAL: af = AF_UNIX; break;
#endif
default:
return ctl_xerror(str_eafnosupport, rbuf, rsize);
}
switch (buf[1]) {
case INET_TYPE_STREAM: type = SOCK_STREAM; break;
case INET_TYPE_DGRAM: type = SOCK_DGRAM; break;
#ifdef HAVE_SCTP
case INET_TYPE_SEQPACKET: type = SOCK_SEQPACKET; break;
#endif
default:
return ctl_error(EINVAL, rbuf, rsize);
}
replen = inet_ctl_open(desc, af, type, rbuf, rsize);
if ((*rbuf)[0] != INET_REP_ERROR) {
if (desc->active)
sock_select(desc,FD_READ,1);
#ifdef HAVE_SO_BSDCOMPAT
/*
* Make sure that sending UDP packets to a non existing port on an
* existing machine doesn't close the socket. (Linux behaves this
* way)
*/
if (should_use_so_bsdcompat()) {
int one = 1;
/* Ignore errors */
sock_setopt(desc->s, SOL_SOCKET, SO_BSDCOMPAT, &one,
sizeof(one));
}
#endif
}
return replen;
case INET_REQ_FDOPEN: { /* pass in an open (and optionally bound) socket */
SOCKET s;
int bound;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"packet_inet_ctl -> FDOPEN\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
if (len != 6 && len != 10) {
return ctl_error(EINVAL, rbuf, rsize);
}
switch (buf[0]) {
case INET_AF_INET: af = AF_INET; break;
#if defined(HAVE_IN6) && defined(AF_INET6)
case INET_AF_INET6: af = AF_INET6; break;
#endif
#ifdef HAVE_SYS_UN_H
case INET_AF_LOCAL: af = AF_UNIX; break;
#endif
default:
return ctl_xerror(str_eafnosupport, rbuf, rsize);
}
switch (buf[1]) {
case INET_TYPE_STREAM: type = SOCK_STREAM; break;
case INET_TYPE_DGRAM: type = SOCK_DGRAM; break;
#ifdef HAVE_SCTP
case INET_TYPE_SEQPACKET: type = SOCK_SEQPACKET; break;
#endif
default:
return ctl_error(EINVAL, rbuf, rsize);
}
s = (SOCKET)get_int32(buf+2);
if (len == 6) bound = 1;
else bound = get_int32(buf+2+4);
replen = inet_ctl_fdopen(desc, af, type, s, bound, rbuf, rsize);
if ((*rbuf)[0] != INET_REP_ERROR) {
if (desc->active)
sock_select(desc,FD_READ,1);
#ifdef HAVE_SO_BSDCOMPAT
/*
* Make sure that sending UDP packets to a non existing port on an
* existing machine doesn't close the socket. (Linux behaves this
* way)
*/
if (should_use_so_bsdcompat()) {
int one = 1;
/* Ignore errors */
sock_setopt(desc->s, SOL_SOCKET, SO_BSDCOMPAT, &one,
sizeof(one));
}
#endif
}
return replen;
}
case INET_REQ_CLOSE:
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"packet_inet_ctl -> CLOSE\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
erl_inet_close(desc);
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
case INET_REQ_CONNECT: {
/* UDP and SCTP connect operations are completely different. UDP
connect means only setting the default peer addr locally, so
it is always synchronous. SCTP connect means actual establish-
ing of an SCTP association with a remote peer, so it is async-
ronous, and similar to TCP connect. However, unlike TCP, SCTP
allows the socket to have multiple simultaneous associations:
*/
int code;
char tbuf[2];
#ifdef HAVE_SCTP
unsigned timeout;
sctp_assoc_t assoc_id = 0;
sctp_assoc_t *p_assoc_id = NULL;
#endif
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"packet_inet_ctl -> CONNECT\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
/* INPUT: [ Timeout(4), Port(2), Address(N) ] */
if (!IS_OPEN(desc))
return ctl_xerror(EXBADPORT, rbuf, rsize);
#ifdef HAVE_SCTP
if (IS_SCTP(desc)) {
inet_address remote;
char *xerror;
if (IS_CONNECTING(desc))
return ctl_error(EINVAL, rbuf, rsize);
if (len < 6)
return ctl_error(EINVAL, rbuf, rsize);
timeout = get_int32(buf);
buf += 4;
len -= 4;
/* For SCTP, we do not set the peer's addr in desc->remote, as
multiple peers are possible: */
if ((*buf) == INET_AF_LIST) {
/* called as gen_sctp:connectx... */
int addrcnt = 0;
buf++; len--;
addrcnt = get_int8(buf),
buf++; len--;
if (! p_sctp_connectx)
return ctl_error(ENOTSUP, rbuf, rsize);
if (addrcnt > 0) {
char *rabuf = ALLOC(sizeof(inet_address) * addrcnt);
struct sockaddr *addrs = (struct sockaddr *) rabuf;
ErlDrvSizeT remote_size;
char *ep = buf + len;
for(int ai=0; ai < addrcnt; ai++) {
remote_size = ep - buf;
if ((xerror = inet_set_faddress
(desc->sfamily, &remote, &buf, &remote_size)) != NULL) {
FREE((char *)addrs);
return ctl_xerror(xerror, rbuf, rsize);
}
memcpy(rabuf, &remote, remote_size);
rabuf += remote_size;
}
p_assoc_id = &assoc_id;
code = p_sctp_connectx(desc->s, addrs, addrcnt, p_assoc_id);
FREE((char *)addrs);
} else {
return ctl_error(EINVAL, rbuf, rsize);
}
} else {
/* called as gen_sctp:connect... */
if ((xerror = inet_set_faddress
(desc->sfamily, &remote, &buf, &len)) != NULL)
return ctl_xerror(xerror, rbuf, rsize);
code = sock_connect(desc->s, &remote.sa, len);
}
if (IS_SOCKET_ERROR(code) && (sock_errno() == EINPROGRESS)) {
/* XXX: Unix only -- WinSock would have a different cond! */
if (timeout != INET_INFINITY)
driver_set_timer(desc->port, timeout);
enq_async(desc, tbuf, INET_REQ_CONNECT);
async_ok_maybe_assoc_id(desc, p_assoc_id);
}
else if (code == 0) { /* OK we are connected */
enq_async(desc, tbuf, INET_REQ_CONNECT);
async_ok_maybe_assoc_id(desc, p_assoc_id);
}
else {
return ctl_error(sock_errno(), rbuf, rsize);
}
return ctl_reply(INET_REP_OK, tbuf, 2, rbuf, rsize);
}
#endif
/* UDP */
if (len == 0) {
sock_connect(desc->s, &disassoc_sa, disassoc_sa_size);
desc->state &= ~INET_F_ACTIVE;
enq_async(desc, tbuf, INET_REQ_CONNECT);
async_ok (desc);
}
else if (len < 6)
return ctl_error(EINVAL, rbuf, rsize);
else {
char *xerror;
/* Ignore timeout */
buf += 4;
len -= 4;
if ((xerror = inet_set_faddress
(desc->sfamily, &desc->remote, &buf, &len)) != NULL)
return ctl_xerror(xerror, rbuf, rsize);
#ifdef __linux__
/* Workaround for Linux's misbehaviour to not
* change the source address when connecting
* a datagram socket to a new destination
*/
if (IS_CONNECTED(desc)) {
/* Dissolve association */
(void) sock_connect(desc->s, &disassoc_sa, disassoc_sa_size);
}
#endif /* #ifdef __linux__ */
code = sock_connect(desc->s,
(struct sockaddr*) &desc->remote, len);
if (IS_SOCKET_ERROR(code)) {
code = sock_errno(),
(void) sock_connect(desc->s, &disassoc_sa, disassoc_sa_size);
desc->state &= ~INET_F_ACTIVE;
return ctl_error(code, rbuf, rsize);
}
else /* ok we are connected */ {
enq_async(desc, tbuf, INET_REQ_CONNECT);
desc->state |= INET_F_ACTIVE;
async_ok (desc);
}
}
return ctl_reply(INET_REP_OK, tbuf, 2, rbuf, rsize);
}
#ifdef HAVE_SCTP
case INET_REQ_LISTEN:
{ /* LISTEN is only for SCTP sockets, not UDP. This code is borrowed
from the TCP section. Returns: {ok,[]} on success.
*/
int backlog;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"packet_inet_ctl -> LISTEN\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
if (!IS_SCTP(desc))
return ctl_xerror(EXBADPORT, rbuf, rsize);
if (!IS_OPEN(desc))
return ctl_xerror(EXBADPORT, rbuf, rsize);
if (len != 2)
return ctl_error(EINVAL, rbuf, rsize);
backlog = get_int16(buf);
if (IS_SOCKET_ERROR(sock_listen(desc->s, backlog)))
return ctl_error(sock_errno(), rbuf, rsize);
desc->state = INET_STATE_LISTENING; /* XXX: not used? */
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
case SCTP_REQ_BINDX:
{ /* Multi-homing bind for SCTP: */
/* Add additional addresses by calling sctp_bindx with one address
at a time, since this is what some OSes promise will work.
Buff structure: Flags(1), ListItem,...:
*/
inet_address addr;
char* curr;
int add_flag, rflag;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"packet_inet_ctl -> BINDX\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
if (!IS_SCTP(desc))
return ctl_xerror(EXBADPORT, rbuf, rsize);
curr = buf;
add_flag = get_int8(curr);
curr++;
/* Make the real flags: */
rflag = add_flag ? SCTP_BINDX_ADD_ADDR : SCTP_BINDX_REM_ADDR;
while (curr < buf+len)
{
char *xerror;
/* List item format: see "inet_set_faddress": */
ErlDrvSizeT alen = buf + len - curr;
xerror = inet_set_faddress
(desc->sfamily, &addr, &curr, &alen);
if (xerror != NULL)
return ctl_xerror(xerror, rbuf, rsize);
/* Invoke the call: */
if (p_sctp_bindx(desc->s, (struct sockaddr *)&addr, 1,
rflag) < 0)
return ctl_error(sock_errno(), rbuf, rsize);
}
desc->state = INET_STATE_OPEN;
return ctl_reply(INET_REP_OK, NULL, 0, rbuf, rsize);
}
case SCTP_REQ_PEELOFF:
{
Uint32 assoc_id;
udp_descriptor* new_udesc;
int err;
SOCKET new_socket;
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"packet_inet_ctl -> PEELOFF\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
if (!IS_SCTP(desc))
return ctl_xerror(EXBADPORT, rbuf, rsize);
if (!IS_OPEN(desc))
return ctl_xerror(EXBADPORT, rbuf, rsize);
if (! p_sctp_peeloff)
return ctl_error(ENOTSUP, rbuf, rsize);
if (len != 4)
return ctl_error(EINVAL, rbuf, rsize);
assoc_id = get_int32(buf);
new_socket = p_sctp_peeloff(desc->s, assoc_id);
if (IS_SOCKET_ERROR(new_socket)) {
return ctl_error(sock_errno(), rbuf, rsize);
}
desc->caller = driver_caller(desc->port);
if ((new_udesc = sctp_inet_copy(udesc, new_socket, &err)) == NULL) {
sock_close(new_socket);
desc->caller = 0;
return ctl_error(err, rbuf, rsize);
}
new_udesc->inet.state = INET_STATE_CONNECTED;
new_udesc->inet.stype = SOCK_STREAM;
SET_NONBLOCKING(new_udesc->inet.s);
inet_reply_ok_port(desc, new_udesc->inet.dport);
(*rbuf)[0] = INET_REP;
return 1;
}
#endif /* HAVE_SCTP */
case PACKET_REQ_RECV:
{ /* THIS IS A FRONT-END for "recv*" requests. It only enqueues the
request and possibly returns the data immediately available.
The actual data returning function is the back-end ("*input"):
*/
unsigned timeout;
char tbuf[2];
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%T] "
"packet_inet_ctl -> RECV\r\n",
__LINE__, desc->s, driver_caller(desc->port)) );
/* INPUT: Timeout(4), Length(4) */
if (!IS_OPEN(desc))
return ctl_xerror(EXBADPORT, rbuf, rsize);
if (desc->active || (len != 8))
return ctl_error(EINVAL, rbuf, rsize);
timeout = get_int32(buf);
/* The 2nd arg, Length(4), is ignored for both UDP and SCTP protocols,
since they are msg-oriented. */
if (enq_async(desc, tbuf, PACKET_REQ_RECV) < 0)
return ctl_error(EALREADY, rbuf, rsize);
if (packet_inet_input(udesc, desc->event) == 0) {
if (timeout != INET_INFINITY)
driver_set_timer(desc->port, timeout);
}
return ctl_reply(INET_REP_OK, tbuf, 2, rbuf, rsize);
}
default:
/* Delegate the request to the INET layer. In particular,
INET_REQ_BIND goes here. If the req is not recognised
there either, an error is returned:
*/
return inet_ctl(desc, cmd, buf, len, rbuf, rsize);
}
}
static void packet_inet_timeout(ErlDrvData e)
{
udp_descriptor * udesc = (udp_descriptor*) e;
inet_descriptor * desc = INETP(udesc);
DDBG(desc,
("INET-DRV-DBG[%d][" SOCKET_FSTR ",%p] "
"packet_inet_timeout -> entry\r\n",
__LINE__, desc->s, desc->port) );
if (!(desc->active)) {
sock_select(desc, FD_READ, 0);
async_error_am (desc, am_timeout);
} else {
(void)packet_inet_input(udesc, (HANDLE) desc->s);
}
}
/* THIS IS A "send*" REQUEST; on the Erlang side: "port_command".
** input should be: Family Address buffer .
** For UDP, buffer (after Address) is just data to be sent.
** For SCTP, buffer contains a list representing 2 items:
** (1) 6 params for sctp_sndrcvinfo, as in sctp_get_sendparams();
** (2) 0+ real data bytes.
** There is no destination address -- SCTP send is performed over
** an existing association, using "sctp_sndrcvinfo" specified.
*/
static void packet_inet_command(ErlDrvData e, char* buf, ErlDrvSizeT len)
{
udp_descriptor * udesc= (udp_descriptor*) e;
inet_descriptor* desc = INETP(udesc);
char* ptr = buf;
char* qtr;
char* xerror;
ErlDrvSizeT sz;
int code;
inet_address other;
desc->caller = driver_caller(desc->port);
if (!IS_OPEN(desc)) {
inet_reply_error(desc, EINVAL);
return;
}
#ifdef HAVE_SCTP
if (IS_SCTP(desc))
{
ErlDrvSizeT data_len;
struct iovec iov[1]; /* For real data */
struct msghdr mhdr; /* Message wrapper */
struct sctp_sndrcvinfo *sri; /* The actual ancillary data */
union { /* For ancillary data */
struct cmsghdr hdr;
char ancd[CMSG_SPACE(sizeof(*sri))];
} cmsg;
if (len < SCTP_GET_SENDPARAMS_LEN) goto return_einval;
/* The ancillary data */
sri = (struct sctp_sndrcvinfo *) (CMSG_DATA(&cmsg.hdr));
/* Get the "sndrcvinfo" from the buffer, advancing the "ptr": */
ptr = sctp_get_sendparams(sri, ptr);
/* The ancillary data wrapper */
cmsg.hdr.cmsg_level = IPPROTO_SCTP;
cmsg.hdr.cmsg_type = SCTP_SNDRCV;
cmsg.hdr.cmsg_len = CMSG_LEN(sizeof(*sri));
data_len = (buf + len) - ptr;
/* The whole msg.
* Solaris (XPG 4.2) requires iovlen >= 1 even for data_len == 0.
*/
mhdr.msg_name = NULL; /* Already connected */
mhdr.msg_namelen = 0;
iov[0].iov_len = data_len;
iov[0].iov_base = ptr; /* The real data */
mhdr.msg_iov = iov;
mhdr.msg_iovlen = 1;
mhdr.msg_control = cmsg.ancd; /* For ancillary data */
mhdr.msg_controllen = cmsg.hdr.cmsg_len;
VALGRIND_MAKE_MEM_DEFINED(mhdr.msg_control, mhdr.msg_controllen); /*suppress "uninitialised bytes"*/
mhdr.msg_flags = 0; /* Not used with "sendmsg" */
inet_output_count(desc, data_len);
/* Now do the actual sending. NB: "flags" in "sendmsg" itself are NOT
used: */
code = sock_sendmsg(desc->s, &mhdr, 0);
goto check_result_code;
}
#endif
{
ErlDrvSizeT anc_len;
/* UDP socket. Even if it is connected, there is an address prefix
here -- ignored for connected sockets: */
sz = len;
qtr = ptr;
xerror = inet_set_faddress(desc->sfamily, &other, &qtr, &sz);
if (xerror != NULL) {
inet_reply_error_am(desc, driver_mk_atom(xerror));
return;
}
len -= (qtr - ptr);
ptr = qtr;
/* Here comes ancillary data */
if (len < 4) goto return_einval;
anc_len = get_int32(ptr);
len -= 4; ptr += 4;
if (len < anc_len) goto return_einval;
if (anc_len == 0) {
/* Empty ancillary data */
/* Now "ptr" is the user data ptr, "len" is data length: */
inet_output_count(desc, len);
if (desc->state & INET_F_ACTIVE) {
/* connected (ignore address) */
code = sock_send(desc->s, ptr, len, 0);
}
else {
code = sock_sendto(desc->s, ptr, len, 0, &other.sa, sz);
}
}
else {
#ifdef __WIN32__
goto return_einval; /* Can not send ancillary data on Windows */
#else
struct iovec iov[1];
struct msghdr mhdr;
union { /* For ancillary data */
struct cmsghdr hdr;
char ancd[SIZEOF_ANCILLARY_DATA];
} cmsg;
sys_memset(&iov, '\0', sizeof(iov));
sys_memset(&mhdr, '\0', sizeof(mhdr));
sys_memset(&cmsg, '\0', sizeof(cmsg));
if (desc->state & INET_F_ACTIVE) {
/* connected (ignore address) */
mhdr.msg_name = NULL;
mhdr.msg_namelen = 0;
}
else {
mhdr.msg_name = &other;
mhdr.msg_namelen = sz;
}
mhdr.msg_control = cmsg.ancd;
mhdr.msg_controllen = sizeof(cmsg.ancd);
if (compile_ancillary_data(&mhdr, ptr, anc_len) != 0) {
goto return_einval;
}
ASSERT(mhdr.msg_controllen != 0);
len -= anc_len;
ptr += anc_len;
/* Now "ptr" is the user data ptr, "len" is data length: */
iov[0].iov_len = len;
iov[0].iov_base = ptr;
mhdr.msg_iov = iov;
mhdr.msg_iovlen = 1;
mhdr.msg_flags = 0;
inet_output_count(desc, len);
code = sock_sendmsg(desc->s, &mhdr, 0);
#endif
}
}
#ifdef HAVE_SCTP
check_result_code:
/* "code" analysis is the same for both SCTP and UDP cases above: */
#endif
if (IS_SOCKET_ERROR(code)) {
int err = sock_errno();
inet_reply_error(desc, err);
}
else
inet_reply_ok(desc);
return;
return_einval:
inet_reply_error(desc, EINVAL);
return;
}
#endif /* HAVE_UDP */
#ifdef __WIN32__
static void packet_inet_event(ErlDrvData e, ErlDrvEvent event)
{
udp_descriptor * udesc = (udp_descriptor*)e;
inet_descriptor* desc = INETP(udesc);
WSANETWORKEVENTS netEv;
if ((WSAEnumNetworkEvents)(desc->s, desc->event, &netEv) != 0) {
DEBUGF(( "port %d: EnumNetwrokEvents = %d\r\n",
desc->port, sock_errno() ));
return; /* -1; */
}
netEv.lNetworkEvents |= desc->forced_events;
if (netEv.lNetworkEvents & FD_READ) {
packet_inet_input(udesc, (HANDLE)event);
}
}
#endif
#ifdef HAVE_UDP
static void packet_inet_drv_input(ErlDrvData e, ErlDrvEvent event)
{
(void) packet_inet_input((udp_descriptor*)e, (HANDLE)event);
}
/*
** THIS IS A BACK-END FOR "recv*" REQUEST, which actually receives the
** data requested, and delivers them to the caller:
*/
static int packet_inet_input(udp_descriptor* udesc, HANDLE event)
{
inet_descriptor* desc = INETP(udesc);
int n;
inet_address other;
char abuf[sizeof(inet_address)]; /* buffer address; enough??? */
int packet_count = udesc->read_packets;
int count = 0; /* number of packets delivered to owner */
#ifndef __WIN32__
struct msghdr mhdr; /* Top-level msg structure */
struct iovec iov[1]; /* Data or Notification Event */
char ancd[ANC_BUFF_SIZE]; /* Ancillary Data */
#endif
#ifdef HAVE_SCTP
int short_recv = 0;
#endif
while(packet_count--) {
unsigned int len = sizeof(other);
sys_memzero((char *) &other, sizeof(other));
/* udesc->i_buf is only kept between SCTP fragments */
#ifdef HAVE_SCTP
if (udesc->i_buf != NULL) {
ErlDrvBinary* tmp;
int bufsz;
ASSERT(IS_SCTP(desc));
bufsz = desc->bufsz + (udesc->i_ptr - udesc->i_buf->orig_bytes);
if ((tmp = realloc_buffer(udesc->i_buf, bufsz)) == NULL) {
release_buffer(udesc->i_buf);
udesc->i_buf = NULL;
return packet_error(udesc, ENOMEM);
} else {
udesc->i_ptr =
tmp->orig_bytes + (udesc->i_ptr - udesc->i_buf->orig_bytes);
udesc->i_buf = tmp;
udesc->i_bufsz = bufsz;
}
} else
#endif
{
ASSERT(udesc->i_buf == NULL);
udesc->i_bufsz = desc->bufsz + len;
if ((udesc->i_buf = alloc_buffer(udesc->i_bufsz)) == NULL)
return packet_error(udesc, ENOMEM);
/* pointer to message start */
udesc->i_ptr = udesc->i_buf->orig_bytes + len;
}
/* Note: On Windows NT, recvfrom() fails if the socket is connected. */
#ifdef HAVE_SCTP
/* For SCTP we must use recvmsg() */
if (IS_SCTP(desc)) {
iov->iov_base = udesc->i_ptr; /* Data will come here */
iov->iov_len = desc->bufsz; /* Remaining buffer space */
mhdr.msg_name = &other; /* Peer addr comes into "other" */
mhdr.msg_namelen = len;
mhdr.msg_iov = iov;
mhdr.msg_iovlen = 1;
mhdr.msg_control = ancd;
mhdr.msg_controllen = ANC_BUFF_SIZE;
mhdr.msg_flags = 0; /* To be filled by "recvmsg" */
/* Do the actual SCTP receive: */
n = sock_recvmsg(desc->s, &mhdr, 0);
len = mhdr.msg_namelen;
goto check_result;
}
#endif
/* Use recv() instead on connected sockets. */
if ((desc->state & INET_F_ACTIVE)) {
n = sock_recv(desc->s, udesc->i_ptr, desc->bufsz, 0);
other = desc->remote;
goto check_result;
}
#ifndef __WIN32__
/* recvmsg() does not exist in the Winsock API */
if (desc->recv_cmsgflags) {
/* Use recvmsg() */
iov->iov_base = udesc->i_ptr;
iov->iov_len = desc->bufsz;
mhdr.msg_name = &other;
mhdr.msg_namelen = len;
mhdr.msg_iov = iov;
mhdr.msg_iovlen = 1;
mhdr.msg_control = ancd;
mhdr.msg_controllen = ANC_BUFF_SIZE;
mhdr.msg_flags = 0;
n = sock_recvmsg(desc->s, &mhdr, 0);
len = mhdr.msg_namelen;
goto check_result;
}
#endif
n = sock_recvfrom(desc->s, udesc->i_ptr, desc->bufsz,
0, &other.sa, &len);
check_result:
/* Analyse the result: */
if (IS_SOCKET_ERROR(n)) {
int err = sock_errno();
if (err != ERRNO_BLOCK) {
/* real error */
release_buffer(udesc->i_buf);
udesc->i_buf = NULL;
if (!desc->active) {
async_error(desc, err);
driver_cancel_timer(desc->port);
sock_select(desc,FD_READ,0);
}
else {
/* This is for an active desc only: */
packet_error_message(udesc, err);
}
return count;
}
/* would block error - try again */
if (!desc->active
#ifdef HAVE_SCTP
|| short_recv
#endif
) {
sock_select(desc,FD_READ,1);
}
#ifdef HAVE_SCTP
if (!short_recv) {
#endif
release_buffer(udesc->i_buf);
udesc->i_buf = NULL;
#ifdef HAVE_SCTP
}
#endif
return count; /* strange, not ready */
}
#ifdef HAVE_SCTP
if (IS_SCTP(desc) && (short_recv = !(mhdr.msg_flags & MSG_EOR))) {
/* SCTP non-final message fragment */
inet_input_count(desc, n);
udesc->i_ptr += n;
continue; /* wait for more fragments */
}
#endif
{
/* message received */
int code;
void *mp;
char * ptr;
int nsz;
inet_input_count(desc, n);
udesc->i_ptr += n;
inet_get_address(abuf, &other, &len);
/* Copy formatted address to the buffer allocated; "len" is the
actual length which must be <= than the original reserved.
This means that the addr + data in the buffer are contiguous,
but they may start not at the "orig_bytes", instead at "ptr":
*/
ASSERT (len <= sizeof(other));
ptr = udesc->i_buf->orig_bytes + sizeof(other) - len;
sys_memcpy(ptr, abuf, len);
nsz = udesc->i_ptr - ptr;
/* Check if we need to reallocate binary */
if ((desc->mode == INET_MODE_BINARY)
&& (desc->hsz < (nsz - len))
&& (nsz + BIN_REALLOC_MARGIN(desc->bufsz) < udesc->i_bufsz)) {
ErlDrvBinary* tmp;
int bufsz;
bufsz = udesc->i_ptr - udesc->i_buf->orig_bytes;
if ((tmp = realloc_buffer(udesc->i_buf, bufsz)) != NULL) {
udesc->i_buf = tmp;
udesc->i_bufsz = bufsz;
udesc->i_ptr = NULL; /* not used from here */
}
}
mp = NULL;
#ifdef HAVE_SCTP
if (IS_SCTP(desc)) mp = &mhdr;
#endif
#ifndef __WIN32__
if (desc->recv_cmsgflags) mp = &mhdr;
#endif
/* Actual parsing and return of the data received, occur here: */
code = packet_reply_binary_data(desc, len, udesc->i_buf,
(sizeof(other) - len),
nsz,
mp);
free_buffer(udesc->i_buf);
udesc->i_buf = NULL;
if (code < 0)
return count;
count++;
if (!desc->active) {
driver_cancel_timer(desc->port);
sock_select(desc,FD_READ,0);
return count; /* passive mode (read one packet only) */
}
}
} /* while(packet_count--) { */
/* we ran out of tries (packet_count) either on an active socket
* that got that many messages or an SCTP socket that got that
* many message fragments but still not the final
*/
#ifdef HAVE_SCTP
if (short_recv) {
sock_select(desc, FD_READ, 1);
}
#endif
/* We set a timer on the port to trigger now.
This emulates a "yield" operation as that is
what we want to do here. We do *NOT* do a deselect
as that is expensive, instead we check if the
socket it still active when the timeout triggers
and if it is not, then we just ignore the timeout */
driver_set_timer(desc->port, 0);
return count;
}
#endif
/*---------------------------------------------------------------------------*/
#ifdef __WIN32__
/*
* Although we no longer need to lookup all of winsock2 dynamically,
* there are still some function(s) we need to look up.
*/
static void find_dynamic_functions(void)
{
char kernel_dll_name[] = "kernel32";
HMODULE module;
module = GetModuleHandle(kernel_dll_name);
fpSetHandleInformation = (module != NULL) ?
(BOOL (WINAPI *)(HANDLE,DWORD,DWORD))
GetProcAddress(module,"SetHandleInformation") :
NULL;
}
/*
* We must make sure that the socket handles are not inherited
* by port programs (if there are inherited, the sockets will not
* get closed when the emulator terminates, and epmd and other Erlang
* nodes will not notice that we have exited).
*
* XXX It is not clear whether this works/is necessary in Windows 95.
* There could also be problems with Winsock implementations from other
* suppliers than Microsoft.
*/
static SOCKET
make_noninheritable_handle(SOCKET s)
{
if (s != INVALID_SOCKET) {
if (fpSetHandleInformation != NULL) {
(*fpSetHandleInformation)((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
} else {
HANDLE non_inherited;
HANDLE this_process = GetCurrentProcess();
if (DuplicateHandle(this_process, (HANDLE) s,
this_process, &non_inherited, 0,
FALSE, DUPLICATE_SAME_ACCESS)) {
sock_close(s);
s = (SOCKET) non_inherited;
}
}
}
return s;
}
#endif /* UDP for __WIN32__ */
/*
* Multi-timers
*/
static void fire_multi_timers(tcp_descriptor *desc, ErlDrvPort port,
ErlDrvData data)
{
ErlDrvTime next_timeout = 0;
if (!desc->mtd) {
ASSERT(0);
return;
}
#ifdef DEBUG
{
ErlDrvTime chk = erl_drv_monotonic_time(ERL_DRV_MSEC);
ASSERT(chk >= desc->mtd->when);
}
#endif
do {
MultiTimerData save = *desc->mtd;
/* We first remove the timer so that the timeout_functions has
can call clean_multi_timers without breaking anything */
if (desc->mtd_cache == NULL) {
desc->mtd_cache = desc->mtd;
} else {
FREE(desc->mtd);
}
desc->mtd = save.next;
if (desc->mtd != NULL)
desc->mtd->prev = NULL;
if ((*(save.timeout_function))(data,save.caller) < 0)
/* -1 means tcp_descriptor has been deallocated,
so we have to return as soon as possible */
return;
if (desc->mtd == NULL)
return;
next_timeout = desc->mtd->when - erl_drv_monotonic_time(ERL_DRV_MSEC);
} while (next_timeout <= 0);
driver_set_timer(port, (unsigned long) next_timeout);
}
static void clean_multi_timers(tcp_descriptor *desc, ErlDrvPort port)
{
if (desc->mtd) {
driver_cancel_timer(port);
}
while (desc->mtd) {
MultiTimerData *p = desc->mtd;
desc->mtd = p->next;
FREE(p);
}
desc->mtd = NULL;
if (desc->mtd_cache) {
FREE(desc->mtd_cache);
desc->mtd_cache = NULL;
}
}
static void remove_multi_timer(tcp_descriptor *desc, ErlDrvPort port, MultiTimerData *p)
{
if (p->prev != NULL) {
p->prev->next = p->next;
} else {
driver_cancel_timer(port);
desc->mtd = p->next;
if (desc->mtd) {
ErlDrvTime ntmo = desc->mtd->when - erl_drv_monotonic_time(ERL_DRV_MSEC);
if (ntmo < 0)
ntmo = 0;
driver_set_timer(port, (unsigned long) ntmo);
}
}
if (p->next != NULL) {
p->next->prev = p->prev;
}
if (desc->mtd_cache == NULL)
desc->mtd_cache = p;
else
FREE(p);
}
/* Cancel a timer based on the timeout_fun */
static void cancel_multi_timer(tcp_descriptor *desc, ErlDrvPort port,
MultiTimerFunction *timeout_fun)
{
MultiTimerData *timer = desc->mtd;
while(timer && timer->timeout_function != timeout_fun) {
timer = timer->next;
}
if (timer) {
remove_multi_timer(desc, port, timer);
}
}
static MultiTimerData *add_multi_timer(tcp_descriptor *desc, ErlDrvPort port,
ErlDrvTermData caller, unsigned timeout,
MultiTimerFunction *timeout_fun)
{
MultiTimerData *mtd, *p, *s;
/* Use cached timer if available */
if (desc->mtd_cache != NULL) {
mtd = desc->mtd_cache;
desc->mtd_cache = NULL;
} else
mtd = ALLOC(sizeof(MultiTimerData));
if (timeout)
mtd->when = erl_drv_monotonic_time(ERL_DRV_MSEC) + ((ErlDrvTime) timeout);
else
mtd->when = INT64_MIN; /* Don't have to get the time for 0 msec timeouts */
mtd->timeout_function = timeout_fun;
mtd->caller = caller;
mtd->next = mtd->prev = NULL;
/* Find correct slot in timer linked list */
for(p = desc->mtd,s = NULL; p != NULL; s = p, p = p->next) {
if (p->when >= mtd->when) {
break;
}
}
/* Insert in linked list */
if (!p) {
if (!s) {
desc->mtd = mtd;
} else {
s->next = mtd;
mtd->prev = s;
}
} else {
if (!s) {
desc->mtd = mtd;
} else {
s->next = mtd;
mtd->prev = s;
}
mtd->next = p;
p->prev = mtd;
}
/* Possibly set new timer */
if (!s) {
driver_set_timer(port,timeout);
}
return mtd;
}
/*-----------------------------------------------------------------------------
Subscription
-----------------------------------------------------------------------------*/
static int
save_subscriber(subs, subs_pid)
subs_list *subs; ErlDrvTermData subs_pid;
{
subs_list *tmp;
if(NO_SUBSCRIBERS(subs)) {
subs->subscriber = subs_pid;
subs->next = NULL;
}
else {
tmp = subs->next;
subs->next = ALLOC(sizeof(subs_list));
if(subs->next == NULL) {
subs->next = tmp;
return 0;
}
subs->next->subscriber = subs_pid;
subs->next->next = tmp;
}
return 1;
}
static void
free_subscribers(subs)
subs_list *subs;
{
subs_list *this;
subs_list *next;
this = subs->next;
while(this) {
next = this->next;
FREE(this);
this = next;
}
subs->subscriber = NO_PROCESS;
subs->next = NULL;
}
static void send_to_subscribers
(
ErlDrvTermData port,
subs_list *subs,
int free_subs,
ErlDrvTermData msg[],
int msg_len
)
{
subs_list *this;
subs_list *next;
int first = 1;
if(NO_SUBSCRIBERS(subs))
return;
this = subs;
while(this) {
(void) erl_drv_send_term(port, this->subscriber, msg, msg_len);
if(free_subs && !first) {
next = this->next;
FREE(this);
this = next;
}
else
this = this->next;
first = 0;
}
if(free_subs) {
subs->subscriber = NO_PROCESS;
subs->next = NULL;
}
}
|