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
|
/** Implementation for GSSocketStream for GNUStep
Copyright (C) 2006-2008 Free Software Foundation, Inc.
Written by: Derek Zhou <derekzhou@gmail.com>
Written by: Richard Frith-Macdonald <rfm@gnu.org>
Date: 2006
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 31 Milk Street #960789 Boston, MA 02196 USA.
*/
#import "common.h"
#import "Foundation/NSArray.h"
#import "Foundation/NSByteOrder.h"
#import "Foundation/NSData.h"
#import "Foundation/NSDictionary.h"
#import "Foundation/NSEnumerator.h"
#import "Foundation/NSException.h"
#import "Foundation/NSHost.h"
#import "Foundation/NSLock.h"
#import "Foundation/NSNotification.h"
#import "Foundation/NSRunLoop.h"
#import "Foundation/NSUserDefaults.h"
#import "Foundation/NSValue.h"
#import "GSPrivate.h"
#import "GSStream.h"
#import "GSSocketStream.h"
#import "GNUstepBase/GSTLS.h"
#ifndef SHUT_RD
# ifdef SD_RECEIVE
# define SHUT_RD SD_RECEIVE
# define SHUT_WR SD_SEND
# define SHUT_RDWR SD_BOTH
# else
# define SHUT_RD 0
# define SHUT_WR 1
# define SHUT_RDWR 2
# endif
#endif
#ifdef _WIN32
#ifdef HAVE_WS2TCPIP_H
#include <ws2tcpip.h>
#endif // HAVE_WS2TCPIP_H
#if !defined(HAVE_INET_NTOP)
extern const char* WSAAPI inet_ntop(int, const void *, char *, size_t);
#endif
#if !defined(HAVE_INET_NTOP)
extern int WSAAPI inet_pton(int , const char *, void *);
#endif
#define OPTLEN int
#else // _WIN32
#define OPTLEN socklen_t
#endif // _WIN32
// Maximum data in single I/O operation
#define NETBUF_SIZE (1024 * 16)
#define READ_SIZE NETBUF_SIZE*10
@implementation GSTcpTune
static int tuneDelay = 0;
static int tuneLinger = -1;
static int tuneReceive = 0;
static BOOL tuneSendAll = NO;
static int tuneRcvBuf = 0;
static int tuneSndBuf = 0;
+ (void) defaultsChanged: (NSNotification*)n
{
NSUserDefaults *defs = (NSUserDefaults*)[n object];
NSString *str;
if (nil == defs)
{
defs = [NSUserDefaults standardUserDefaults];
}
str = [defs stringForKey: @"GSTcpLinger"];
if (nil == str)
{
tuneLinger = -1;
}
else
{
tuneLinger = [str intValue];
}
tuneRcvBuf = (int)[defs integerForKey: @"GSTcpRcvBuf"];
tuneSndBuf = (int)[defs integerForKey: @"GSTcpSndBuf"];
tuneReceive = (int)[defs integerForKey: @"GSTcpReceive"];
tuneSendAll = [defs boolForKey: @"GSTcpSendAll"];
tuneDelay = [defs boolForKey: @"GSTcpDelay"];
}
+ (void) initialize
{
static BOOL beenHere = NO;
if (NO == beenHere)
{
NSNotificationCenter *nc;
NSUserDefaults *defs;
beenHere = YES;
nc = [NSNotificationCenter defaultCenter];
defs = [NSUserDefaults standardUserDefaults];
[nc addObserver: self
selector: @selector(defaultsChanged:)
name: NSUserDefaultsDidChangeNotification
object: defs];
[self defaultsChanged: nil];
}
}
+ (int) delay
{
return tuneDelay; // Milliseconds to delay close
}
+ (int) recvSize
{
if (tuneReceive > 0)
{
return tuneReceive; // Return receive buffer size
}
if (tuneRcvBuf > 0)
{
return tuneRcvBuf; // Return socket receive buffer size
}
return READ_SIZE; // Return hard-coded default
}
+ (int) sendSize: (int)bytesToSend
{
if (YES == tuneSendAll)
{
return bytesToSend; // Try to send all in one go
}
if (tuneSndBuf > 0 && tuneSndBuf <= bytesToSend)
{
return tuneSndBuf; // Limit to socket send buffer
}
if (NETBUF_SIZE <= bytesToSend)
{
return NETBUF_SIZE; // Limit to hard coded default
}
return bytesToSend;
}
+ (void) tune: (void*)handle with: (id)opts
{
int desc = (int)(intptr_t)handle;
int value;
id o;
#ifndef BROKEN_SO_REUSEADDR
/*
* Under decent systems, SO_REUSEADDR means that the port can be reused
* immediately that this process exits. Under some it means
* that multiple processes can serve the same port simultaneously.
* We don't want that broken behavior!
*/
value = 1;
if (setsockopt(desc, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(value))
< 0)
{
NSDebugMLLog(@"GSTcpTune", @"setsockopt reuseaddr failed for %d", desc);
}
#endif
/*
* Enable tcp-level tracking of whether connection is alive.
*/
value = 1;
if (setsockopt(desc, SOL_SOCKET, SO_KEEPALIVE, (char *)&value, sizeof(value))
< 0)
{
NSDebugMLLog(@"GSTcpTune", @"setsockopt keepalive failed for %d", desc);
}
#define OPTS(X) ([opts isKindOfClass: [NSStream class]] \
? [(NSStream*)opts propertyForKey: X] \
: [(NSDictionary*)opts objectForKey: X])
o = OPTS(@"GSTcpLinger");
value = (o ? [o intValue] : tuneLinger);
if (value >= 0)
{
struct linger l;
l.l_onoff = 1;
l.l_linger = tuneLinger;
if (setsockopt(desc, SOL_SOCKET, SO_LINGER, (char *)&l, sizeof(l)) < 0)
{
NSLog(@"Failed to set GSTcpLinger for %d to %d: %@",
desc, value, [NSError _last]);
}
else
{
NSDebugMLLog(@"GSTcpTune", @"Set GSTcpLinger for %d to %d",
desc, value);
}
}
o = OPTS(@"GSTcpRcvBuf");
value = (o ? [o intValue] : tuneRcvBuf);
if (value > 0)
{
/* Set the receive buffer for the socket.
*/
if (setsockopt(desc, SOL_SOCKET, SO_RCVBUF,
(char *)&value, sizeof(value)) < 0)
{
NSLog(@"Failed to set GSTcpRcvBuf for %d to %d: %@",
desc, value, [NSError _last]);
}
else
{
NSDebugMLLog(@"GSTcpTune", @"Set GSTcpRcvBuf for %d to %d",
desc, value);
}
}
o = OPTS(@"GSTcpSndBuf");
value = (o ? [o intValue] : tuneSndBuf);
if (value > 0)
{
/* Set the send buffer for the socket.
*/
if (setsockopt(desc, SOL_SOCKET, SO_SNDBUF,
(char *)&value, sizeof(value)) < 0)
{
NSLog(@"Failed to set GSTcpSndBuf for %d to %d: %@",
desc, value, [NSError _last]);
}
else
{
NSDebugMLLog(@"GSTcpTune", @"Set GSTcpSndBuf for %d to %d",
desc, value);
}
}
}
@end
unsigned
GSPrivateSockaddrLength(struct sockaddr *addr)
{
switch (addr->sa_family) {
case AF_INET: return sizeof(struct sockaddr_in);
#ifdef AF_INET6
case AF_INET6: return sizeof(struct sockaddr_in6);
#endif
#ifndef _WIN32
case AF_LOCAL: return sizeof(struct sockaddr_un);
#endif
default: return 0;
}
}
NSString *
GSPrivateSockaddrHost(struct sockaddr *addr)
{
char buf[40];
#if defined(AF_INET6)
if (AF_INET6 == addr->sa_family)
{
struct sockaddr_in6 *addr6 = (struct sockaddr_in6*)(void*)addr;
inet_ntop(AF_INET, &addr6->sin6_addr, buf, sizeof(buf));
return [NSString stringWithUTF8String: buf];
}
#endif
inet_ntop(AF_INET, &((struct sockaddr_in*)(void*)addr)->sin_addr,
buf, sizeof(buf));
return [NSString stringWithUTF8String: buf];
}
NSString *
GSPrivateSockaddrName(struct sockaddr *addr)
{
return [NSString stringWithFormat: @"%@:%d",
GSPrivateSockaddrHost(addr),
GSPrivateSockaddrPort(addr)];
}
uint16_t
GSPrivateSockaddrPort(struct sockaddr *addr)
{
uint16_t port;
#if defined(AF_INET6)
if (AF_INET6 == addr->sa_family)
{
struct sockaddr_in6 *addr6 = (struct sockaddr_in6*)(void*)addr;
port = addr6->sin6_port;
port = GSSwapBigI16ToHost(port);
return port;
}
#endif
port = ((struct sockaddr_in*)(void*)addr)->sin_port;
port = GSSwapBigI16ToHost(port);
return port;
}
BOOL
GSPrivateSockaddrSetup(NSString *machine, uint16_t port,
NSString *service, NSString *protocol, struct sockaddr *sin)
{
memset(sin, '\0', sizeof(*sin));
sin->sa_family = AF_INET;
/* If we were given a hostname, we use any address for that host.
* Otherwise we expect the given name to be an address unless it is
* a null (any address).
*/
if (0 != [machine length])
{
const char *n;
n = [machine UTF8String];
if ((!isdigit(n[0]) || sscanf(n, "%*d.%*d.%*d.%*d") != 4)
&& 0 == strchr(n, ':'))
{
machine = [[NSHost hostWithName: machine] address];
n = [machine UTF8String];
}
if (0 == n)
{
return NO;
}
if (0 == strchr(n, ':'))
{
struct sockaddr_in *addr = (struct sockaddr_in*)(void*)sin;
if (inet_pton(AF_INET, n, &addr->sin_addr) <= 0)
{
return NO;
}
}
else
{
#if defined(AF_INET6)
struct sockaddr_in6 *addr6 = (struct sockaddr_in6*)(void*)sin;
sin->sa_family = AF_INET6;
if (inet_pton(AF_INET6, n, &addr6->sin6_addr) <= 0)
{
return NO;
}
#else
return NO;
#endif
}
}
else
{
((struct sockaddr_in*)(void*)sin)->sin_addr.s_addr
= GSSwapHostI32ToBig(INADDR_ANY);
}
/* The optional service and protocol parameters may be used to
* look up the port
*/
if (nil != service)
{
const char *sname;
const char *proto;
struct servent *sp;
if (nil == protocol)
{
proto = "tcp";
}
else
{
proto = [protocol UTF8String];
}
sname = [service UTF8String];
if ((sp = getservbyname(sname, proto)) == 0)
{
const char* ptr = sname;
int val = atoi(ptr);
while (isdigit(*ptr))
{
ptr++;
}
if (*ptr == '\0' && val <= 0xffff)
{
port = val;
}
else if (strcmp(ptr, "gdomap") == 0)
{
#ifdef GDOMAP_PORT_OVERRIDE
port = GDOMAP_PORT_OVERRIDE;
#else
port = 538; // IANA allocated port
#endif
}
else
{
return NO;
}
}
else
{
port = GSSwapBigI16ToHost(sp->s_port);
}
}
#if defined(AF_INET6)
if (AF_INET6 == sin->sa_family)
{
((struct sockaddr_in6*)(void*)sin)->sin6_port = GSSwapHostI16ToBig(port);
}
else
{
((struct sockaddr_in*)(void*)sin)->sin_port = GSSwapHostI16ToBig(port);
}
#else
((struct sockaddr_in*)sin)->sin_port = GSSwapHostI16ToBig(port);
#endif
return YES;
}
/** The GSStreamHandler abstract class defines the methods used to
* implement a handler object for a pair of streams.
* The idea is that the handler is installed once the connection is
* open, and a handshake is initiated. During the handshake process
* all stream events are sent to the handler rather than to the
* stream delegate (the streams know to do this because the -handshake
* method returns YES to tell them so).
* While a handler is installed, the -read:maxLength: and -write:maxLength:
* methods of the handle rare called instead of those of the streams (and
* the handler may perform I/O using the streams by calling the private
* -_read:maxLength: and _write:maxLength: methods instead of the public
* methods).
*/
@interface GSStreamHandler : NSObject
{
GSSocketInputStream *istream; // Not retained
GSSocketOutputStream *ostream; // Not retained
BOOL initialised;
BOOL handshake;
BOOL active;
}
+ (void) tryInput: (GSSocketInputStream*)i output: (GSSocketOutputStream*)o;
- (id) initWithInput: (GSSocketInputStream*)i
output: (GSSocketOutputStream*)o;
- (GSSocketInputStream*) istream;
- (GSSocketOutputStream*) ostream;
- (void) bye; /* Close down the handled session. */
- (BOOL) handshake; /* A handshake/hello is in progress. */
- (void) hello; /* Start up the session handshake. */
- (BOOL) readable; /* is there buffered data to read? */
- (NSInteger) read: (uint8_t *)buffer maxLength: (NSUInteger)len;
- (void) remove: (NSStream*)stream; /* Stream no longer available */
- (void) stream: (NSStream*)stream handleEvent: (NSStreamEvent)event;
- (NSInteger) write: (const uint8_t *)buffer maxLength: (NSUInteger)len;
@end
@implementation GSStreamHandler
+ (void) initialize
{
}
+ (void) tryInput: (GSSocketInputStream*)i output: (GSSocketOutputStream*)o
{
[self subclassResponsibility: _cmd];
}
- (void) bye
{
[self subclassResponsibility: _cmd];
}
- (BOOL) handshake
{
return handshake;
}
- (void) hello
{
[self subclassResponsibility: _cmd];
}
- (id) initWithInput: (GSSocketInputStream*)i
output: (GSSocketOutputStream*)o
{
istream = i;
ostream = o;
handshake = YES;
return self;
}
- (GSSocketInputStream*) istream
{
return istream;
}
- (GSSocketOutputStream*) ostream
{
return ostream;
}
- (BOOL) readable
{
return NO;
}
- (NSInteger) read: (uint8_t *)buffer maxLength: (NSUInteger)len
{
[self subclassResponsibility: _cmd];
return 0;
}
- (void) remove: (NSStream*)stream
{
if ((id)stream == (id)istream)
{
istream = nil;
}
if ((id)stream == (id)ostream)
{
ostream = nil;
}
}
- (void) stream: (NSStream*)stream handleEvent: (NSStreamEvent)event
{
[self subclassResponsibility: _cmd];
}
- (NSInteger) write: (const uint8_t *)buffer maxLength: (NSUInteger)len
{
[self subclassResponsibility: _cmd];
return 0;
}
@end
#if defined(HAVE_GNUTLS)
@interface GSTLSHandler : GSStreamHandler
{
@public
GSTLSSession *session;
}
/** Populates the dictionary 'dict', copying in all the properties
* of the supplied streams. If a property is set for both then
* the output stream's one has precedence.
*/
+ (void) populateProperties: (NSMutableDictionary**)dict
withSecurityLevel: (NSString*)l
fromInputStream: (NSStream*)i
orOutputStream: (NSStream*)o;
/** Called on verification of the remote end's certificate to tell the
* delegate of the input stream who the certificate issuer and owner are.
*/
- (void) stream: (NSStream*)stream issuer: (NSString*)i owner: (NSString*)o;
@end
/* Callback to allow the TLS code to pull data from the remote system.
* If the operation fails, this sets the error number.
*/
static ssize_t
GSTLSPull(gnutls_transport_ptr_t handle, void *buffer, size_t len)
{
ssize_t result;
GSTLSHandler *tls = (GSTLSHandler*)handle;
result = [[tls istream] _read: buffer maxLength: len];
if (result < 0)
{
int e;
if ([[tls istream] streamStatus] == NSStreamStatusError)
{
e = [[[(GSTLSHandler*)handle istream] streamError] code];
}
else
{
e = EAGAIN; // Tell GNUTLS this would block.
}
#if HAVE_GNUTLS_TRANSPORT_SET_ERRNO
gnutls_transport_set_errno (tls->session->session, e);
#else
errno = e; // Not thread-safe
#endif
}
return result;
}
/* Callback to allow the TLS code to push data to the remote system.
* If the operation fails, this sets the error number.
*/
static ssize_t
GSTLSPush(gnutls_transport_ptr_t handle, const void *buffer, size_t len)
{
ssize_t result;
GSTLSHandler *tls = (GSTLSHandler*)handle;
result = [[tls ostream] _write: buffer maxLength: len];
if (result < 0)
{
int e;
if ([[tls ostream] streamStatus] == NSStreamStatusError)
{
e = [[[tls ostream] streamError] code];
NSDebugFLLog(@"NSStream",
@"GSTLSPush write for %@ error %d (%s)",
[tls ostream], e, strerror(e));
}
else
{
e = EAGAIN; // Tell GNUTLS this would block.
NSDebugFLLog(@"NSStream",
@"GSTLSPush write for %@ of %lu would block",
[tls ostream], (unsigned long)len);
}
#if HAVE_GNUTLS_TRANSPORT_SET_ERRNO
gnutls_transport_set_errno(tls->session->session, e);
#else
errno = e; // Not thread-safe
#endif
return -1;
}
if (len != result)
{
NSDebugFLLog(@"NSStream", @"GSTLSPush write for %@ of %ld (tried %lu)",
[tls ostream], (long)result, (unsigned long)len);
}
else
{
NSDebugFLLog(@"NSStream", @"GSTLSPush write for %@ of %ld success",
[tls ostream], (long)result);
}
return result;
}
@implementation GSTLSHandler
static NSArray *keys = nil;
+ (void) initialize
{
[GSTLSObject class];
if (nil == keys)
{
keys = [[NSArray alloc] initWithObjects:
GSTLSCAFile,
GSTLSCertificateFile,
GSTLSCertificateKeyFile,
GSTLSCertificateKeyPassword,
GSTLSDebug,
GSTLSIssuers,
GSTLSOwners,
GSTLSPriority,
GSTLSRemoteHosts,
GSTLSRevokeFile,
GSTLSServerName,
GSTLSVerify,
nil];
[[NSObject leakAt: &keys] release];
}
}
+ (void) populateProperties: (NSMutableDictionary**)dict
withSecurityLevel: (NSString*)l
fromInputStream: (NSStream*)i
orOutputStream: (NSStream*)o
{
if (NULL != dict)
{
NSString *str;
NSMutableDictionary *opts = *dict;
NSUInteger count;
if (nil != l)
{
[opts setObject: l forKey: NSStreamSocketSecurityLevelKey];
}
count = [keys count];
while (count-- > 0)
{
NSString *key = [keys objectAtIndex: count];
str = [o propertyForKey: key];
if (nil == str) str = [i propertyForKey: key];
if (nil != str) [opts setObject: str forKey: key];
}
}
else
{
NSWarnLog(@"%@ requires not nil 'dict'", NSStringFromSelector(_cmd));
}
}
+ (void) tryInput: (GSSocketInputStream*)i output: (GSSocketOutputStream*)o
{
NSString *tls;
tls = [i propertyForKey: NSStreamSocketSecurityLevelKey];
if (tls == nil)
{
tls = [o propertyForKey: NSStreamSocketSecurityLevelKey];
if (tls != nil)
{
[i setProperty: tls forKey: NSStreamSocketSecurityLevelKey];
}
}
else
{
[o setProperty: tls forKey: NSStreamSocketSecurityLevelKey];
}
if (tls != nil)
{
GSTLSHandler *h;
h = [[GSTLSHandler alloc] initWithInput: i output: o];
[i _setHandler: h];
[o _setHandler: h];
RELEASE(h);
}
}
- (void) bye
{
handshake = NO;
active = NO;
[session disconnect: NO];
}
- (void) dealloc
{
[self bye];
DESTROY(session);
[super dealloc];
}
- (BOOL) handshake
{
return handshake;
}
- (void) hello
{
if (active == NO)
{
if (handshake == NO)
{
/* Set flag to say we are now doing a handshake.
*/
handshake = YES;
}
if ([session handshake] == YES)
{
handshake = NO; // Handshake is now complete.
active = [session active]; // Is the TLS session now active?
if (NO == active)
{
NSString *problem = [session problem];
NSError *theError;
if (nil == problem)
{
problem = @"TLS handshake failure";
}
theError = [NSError errorWithDomain: NSCocoaErrorDomain
code: 0
userInfo: [NSDictionary dictionaryWithObject: problem
forKey: NSLocalizedDescriptionKey]];
if ([istream streamStatus] != NSStreamStatusError)
{
[istream _recordError: theError];
}
if ([ostream streamStatus] != NSStreamStatusError)
{
[ostream _recordError: theError];
}
[self bye];
}
else
{
NSString *issuer = [session issuer];
NSString *owner = [session owner];
id del = [istream delegate];
if (nil != issuer && nil != owner
&& [del respondsToSelector: @selector(stream:issuer:owner:)])
{
[del stream: istream issuer: issuer owner: owner];
}
}
}
}
}
- (id) initWithInput: (GSSocketInputStream*)i
output: (GSSocketOutputStream*)o
{
NSString *str;
NSMutableDictionary *opts;
BOOL server;
// Check whether the input stream has been accepted by a listening socket
server = [[i propertyForKey: @"IsServer"] boolValue];
str = [o propertyForKey: NSStreamSocketSecurityLevelKey];
if (nil == str) str = [i propertyForKey: NSStreamSocketSecurityLevelKey];
if ([str isEqual: NSStreamSocketSecurityLevelNone] == YES)
{
GSOnceMLog(@"NSStreamSocketSecurityLevelNone is insecure ..."
@" not implemented");
DESTROY(self);
return nil;
}
else if ([str isEqual: NSStreamSocketSecurityLevelSSLv2] == YES)
{
GSOnceMLog(@"NSStreamSocketSecurityLevelTLSv2 is insecure ..."
@" not implemented");
DESTROY(self);
return nil;
}
else if ([str isEqual: NSStreamSocketSecurityLevelSSLv3] == YES)
{
str = @"SSLv3";
}
else if ([str isEqual: NSStreamSocketSecurityLevelTLSv1] == YES)
{
str = @"TLSV1";
}
else
{
str = nil;
}
if ((self = [super initWithInput: i output: o]) == nil)
{
return nil;
}
/* Create the options dictionary, copying in any option from the stream
* properties. GSTLSPriority overrides NSStreamSocketSecurityLevelKey.
*/
opts = [NSMutableDictionary new];
[[self class] populateProperties: &opts
withSecurityLevel: str
fromInputStream: i
orOutputStream: o];
session = [[GSTLSSession alloc] initWithOptions: opts
direction: (server ? NO : YES)
transport: (void*)self
push: GSTLSPush
pull: GSTLSPull];
[opts release];
initialised = YES;
return self;
}
- (GSSocketInputStream*) istream
{
return istream;
}
- (GSSocketOutputStream*) ostream
{
return ostream;
}
- (BOOL) readable
{
if (NO == active || YES == handshake)
{
return NO;
}
return ([session pending] > 0) ? YES : NO;
}
- (NSInteger) read: (uint8_t *)buffer maxLength: (NSUInteger)len
{
return [session read: buffer length: len];
}
- (void) stream: (NSStream*)stream handleEvent: (NSStreamEvent)event
{
NSDebugMLLog(@"NSStream",
@"GSTLSHandler got %@ on %@", [stream stringFromEvent: event], stream);
if (handshake == YES)
{
switch (event)
{
case NSStreamEventHasSpaceAvailable:
case NSStreamEventHasBytesAvailable:
case NSStreamEventOpenCompleted:
/* try to complete the handshake.
*/
[self hello];
break;
case NSStreamEventErrorOccurred:
case NSStreamEventEndEncountered:
/* stream error or close ... handshake fails.
*/
handshake = NO;
break;
default:
break;
}
if (NO == handshake)
{
NSDebugMLLog(@"NSStream",
@"GSTLSHandler completed on %@", stream);
/* Make sure that, if ostream gets released as a result of
* the event we send to istream, it doesn't get deallocated
* and cause a crash when we try to send to it.
*/
AUTORELEASE(RETAIN(ostream));
if ([istream streamStatus] == NSStreamStatusOpen)
{
[istream _resetEvents: NSStreamEventOpenCompleted];
[istream _sendEvent: NSStreamEventOpenCompleted];
[istream _schedule];
}
else
{
[istream _resetEvents: NSStreamEventErrorOccurred];
[istream _sendEvent: NSStreamEventErrorOccurred];
}
if ([ostream streamStatus] == NSStreamStatusOpen)
{
[ostream _resetEvents: NSStreamEventOpenCompleted
| NSStreamEventHasSpaceAvailable];
[ostream _sendEvent: NSStreamEventOpenCompleted];
[ostream _sendEvent: NSStreamEventHasSpaceAvailable];
[ostream _schedule];
}
else
{
[ostream _resetEvents: NSStreamEventErrorOccurred];
[ostream _sendEvent: NSStreamEventErrorOccurred];
}
}
}
}
- (void) stream: (NSStream*)stream issuer: (NSString*)i owner: (NSString*)o
{
return;
}
- (NSInteger) write: (const uint8_t *)buffer maxLength: (NSUInteger)len
{
NSInteger offset = 0;
/* The low level code to perform the TLS session write may return a
* partial write even though the output stream is still writable.
* That means we wouldn't get an event to say there's more space and
* our overall write (for a large amount of data) could hang.
* To avoid that, we try writing more data as long as the stream
* still has space available.
*/
while ([ostream hasSpaceAvailable] && offset < len)
{
NSInteger written;
written = [session write: buffer + offset length: len - offset];
if (written > 0)
{
offset += written;
}
}
return offset;
}
@end
#else /* HAVE_GNUTLS */
/* GNUTLS not available ...
*/
@interface GSTLSHandler : GSStreamHandler
@end
@implementation GSTLSHandler
static NSArray *keys = nil;
+ (void) initialize
{
if (nil == keys)
{
keys = [[NSArray alloc] initWithObjects:
GSTLSCAFile,
GSTLSCertificateFile,
GSTLSCertificateKeyFile,
GSTLSCertificateKeyPassword,
GSTLSDebug,
GSTLSIssuers,
GSTLSOwners,
GSTLSPriority,
GSTLSRemoteHosts,
GSTLSRevokeFile,
GSTLSVerify,
nil];
[[NSObject leakAt: &keys] release];
}
}
+ (void) populateProperties: (NSMutableDictionary**)dict
withSecurityLevel: (NSString*)l
fromInputStream: (NSStream*)i
orOutputStream: (NSStream*)o
{
NSString *str;
NSMutableDictionary *opts = *dict;
NSUInteger count;
if (NULL != dict)
{
if (nil != l)
{
[opts setObject: l forKey: NSStreamSocketSecurityLevelKey];
}
count = [keys count];
while (count-- > 0)
{
NSString *key = [keys objectAtIndex: count];
str = [o propertyForKey: key];
if (nil == str) str = [i propertyForKey: key];
if (nil != str) [opts setObject: str forKey: key];
}
}
else
{
NSWarnLog(@"%@ requires not nil 'dict'", NSStringFromSelector(_cmd));
}
}
+ (void) tryInput: (GSSocketInputStream*)i output: (GSSocketOutputStream*)o
{
NSString *tls;
tls = [i propertyForKey: NSStreamSocketSecurityLevelKey];
if (tls == nil)
{
tls = [o propertyForKey: NSStreamSocketSecurityLevelKey];
}
if (tls != nil
&& [tls isEqualToString: NSStreamSocketSecurityLevelNone] == NO)
{
NSLog(@"Attempt to use SSL/TLS without support.");
NSLog(@"Please reconfigure gnustep-base with GNU TLS.");
}
return;
}
- (id) initWithInput: (GSSocketInputStream*)i
output: (GSSocketOutputStream*)o
{
DESTROY(self);
return nil;
}
@end
#endif /* HAVE_GNUTLS */
/*
* States for socks connection negotiation
*/
static NSString * const GSSOCKSOfferAuth = @"GSSOCKSOfferAuth";
static NSString * const GSSOCKSRecvAuth = @"GSSOCKSRecvAuth";
static NSString * const GSSOCKSSendAuth = @"GSSOCKSSendAuth";
static NSString * const GSSOCKSAckAuth = @"GSSOCKSAckAuth";
static NSString * const GSSOCKSSendConn = @"GSSOCKSSendConn";
static NSString * const GSSOCKSAckConn = @"GSSOCKSAckConn";
@interface GSSOCKS : GSStreamHandler
{
NSString *state; /* Not retained */
NSString *address;
NSString *port;
int roffset;
int woffset;
int rwant;
unsigned char rbuffer[128];
}
- (void) stream: (NSStream*)stream handleEvent: (NSStreamEvent)event;
@end
@implementation GSSOCKS
+ (void) tryInput: (GSSocketInputStream*)i output: (GSSocketOutputStream*)o
{
NSDictionary *conf;
conf = [i propertyForKey: NSStreamSOCKSProxyConfigurationKey];
if (conf == nil)
{
conf = [o propertyForKey: NSStreamSOCKSProxyConfigurationKey];
if (conf != nil)
{
[i setProperty: conf forKey: NSStreamSOCKSProxyConfigurationKey];
}
}
else
{
[o setProperty: conf forKey: NSStreamSOCKSProxyConfigurationKey];
}
if (conf != nil)
{
GSSOCKS *h;
struct sockaddr *sa = [i _address];
NSString *v;
BOOL i6 = NO;
v = [conf objectForKey: NSStreamSOCKSProxyVersionKey];
if ([v isEqualToString: NSStreamSOCKSProxyVersion4] == YES)
{
v = NSStreamSOCKSProxyVersion4;
}
else
{
v = NSStreamSOCKSProxyVersion5;
}
#if defined(AF_INET6)
if (sa->sa_family == AF_INET6)
{
i6 = YES;
}
else
#endif
if (sa->sa_family != AF_INET)
{
GSOnceMLog(@"SOCKS not supported for socket type %d", sa->sa_family);
return;
}
if (v == NSStreamSOCKSProxyVersion5)
{
GSOnceMLog(@"SOCKS 5 not supported yet");
return;
}
else if (i6 == YES)
{
GSOnceMLog(@"INET6 not supported with SOCKS 4");
return;
}
h = [[GSSOCKS alloc] initWithInput: i output: o];
[i _setHandler: h];
[o _setHandler: h];
RELEASE(h);
}
}
- (void) bye
{
if (handshake == YES)
{
GSSocketInputStream *is = RETAIN(istream);
GSSocketOutputStream *os = RETAIN(ostream);
handshake = NO;
[is _setHandler: nil];
[os _setHandler: nil];
[GSTLSHandler tryInput: is output: os];
if ([is streamStatus] == NSStreamStatusOpen)
{
[is _resetEvents: NSStreamEventOpenCompleted];
[is _sendEvent: NSStreamEventOpenCompleted];
}
else
{
[is _resetEvents: NSStreamEventErrorOccurred];
[is _sendEvent: NSStreamEventErrorOccurred];
}
if ([os streamStatus] == NSStreamStatusOpen)
{
[os _resetEvents: NSStreamEventOpenCompleted
| NSStreamEventHasSpaceAvailable];
[os _sendEvent: NSStreamEventOpenCompleted];
[os _sendEvent: NSStreamEventHasSpaceAvailable];
}
else
{
[os _resetEvents: NSStreamEventErrorOccurred];
[os _sendEvent: NSStreamEventErrorOccurred];
}
RELEASE(is);
RELEASE(os);
}
}
- (void) dealloc
{
RELEASE(address);
RELEASE(port);
[super dealloc];
}
- (void) hello
{
if (handshake == NO)
{
handshake = YES;
/* Now send self an event to say we can write, to kick off the
* handshake with the SOCKS server.
*/
[self stream: ostream handleEvent: NSStreamEventHasSpaceAvailable];
}
}
- (id) initWithInput: (GSSocketInputStream*)i
output: (GSSocketOutputStream*)o
{
if ((self = [super initWithInput: i output: o]) != nil)
{
if ([istream isKindOfClass: [GSInetInputStream class]] == NO)
{
NSLog(@"Attempt to use SOCKS with non-INET stream ignored");
DESTROY(self);
}
#if defined(AF_INET6)
else if ([istream isKindOfClass: [GSInet6InputStream class]] == YES)
{
GSOnceMLog(@"INET6 not supported with SOCKS yet...");
DESTROY(self);
}
#endif /* AF_INET6 */
else
{
struct sockaddr_in *addr;
NSDictionary *conf;
NSString *host;
int pnum;
/* Record the host and port that the streams are supposed to be
* connecting to.
*/
addr = (struct sockaddr_in*)(void*)[istream _address];
address = [[NSString alloc] initWithUTF8String:
(char*)inet_ntoa(addr->sin_addr)];
port = [[NSString alloc] initWithFormat: @"%d",
(int)GSSwapBigI16ToHost(addr->sin_port)];
/* Now reconfigure the streams so they will actually connect
* to the socks proxy server.
*/
conf = [istream propertyForKey: NSStreamSOCKSProxyConfigurationKey];
host = [conf objectForKey: NSStreamSOCKSProxyHostKey];
pnum = [[conf objectForKey: NSStreamSOCKSProxyPortKey] intValue];
[istream _setSocketAddress: host port: pnum family: AF_INET];
[ostream _setSocketAddress: host port: pnum family: AF_INET];
}
}
return self;
}
- (NSInteger) read: (uint8_t *)buffer maxLength: (NSUInteger)len
{
return [istream _read: buffer maxLength: len];
}
- (void) stream: (NSStream*)stream handleEvent: (NSStreamEvent)event
{
NSString *error = nil;
NSDictionary *conf;
NSString *user;
NSString *pass;
if (event == NSStreamEventErrorOccurred
|| [stream streamStatus] == NSStreamStatusError
|| [stream streamStatus] == NSStreamStatusClosed)
{
[self bye];
return;
}
conf = [stream propertyForKey: NSStreamSOCKSProxyConfigurationKey];
user = [conf objectForKey: NSStreamSOCKSProxyUserKey];
pass = [conf objectForKey: NSStreamSOCKSProxyPasswordKey];
if ([[conf objectForKey: NSStreamSOCKSProxyVersionKey]
isEqual: NSStreamSOCKSProxyVersion4] == YES)
{
}
else
{
again:
if (state == GSSOCKSOfferAuth)
{
int result;
int want;
unsigned char buf[4];
/*
* Authorisation record is at least three bytes -
* socks version (5)
* authorisation method bytes to follow (1)
* say we do no authorisation (0)
* say we do user/pass authorisation (2)
*/
buf[0] = 5;
if (user && pass)
{
buf[1] = 2;
buf[2] = 2;
buf[3] = 0;
want = 4;
}
else
{
buf[1] = 1;
buf[2] = 0;
want = 3;
}
result = [ostream _write: buf + woffset maxLength: 4 - woffset];
if (result > 0)
{
woffset += result;
if (woffset == want)
{
woffset = 0;
state = GSSOCKSRecvAuth;
goto again;
}
}
}
else if (state == GSSOCKSRecvAuth)
{
int result;
result = [istream _read: rbuffer + roffset maxLength: 2 - roffset];
if (result == 0)
{
error = @"SOCKS end-of-file during negotiation";
}
else if (result > 0)
{
roffset += result;
if (roffset == 2)
{
roffset = 0;
if (rbuffer[0] != 5)
{
error = @"SOCKS authorisation response had wrong version";
}
else if (rbuffer[1] == 0)
{
state = GSSOCKSSendConn;
goto again;
}
else if (rbuffer[1] == 2)
{
state = GSSOCKSSendAuth;
goto again;
}
else
{
error = @"SOCKS authorisation response had wrong method";
}
}
}
}
else if (state == GSSOCKSSendAuth)
{
NSData *u = [user dataUsingEncoding: NSUTF8StringEncoding];
unsigned ul = [u length];
NSData *p = [pass dataUsingEncoding: NSUTF8StringEncoding];
unsigned pl = [p length];
if (ul < 1 || ul > 255)
{
error = @"NSStreamSOCKSProxyUserKey value too long";
}
else if (pl < 1 || pl > 255)
{
error = @"NSStreamSOCKSProxyPasswordKey value too long";
}
else
{
int want = ul + pl + 3;
unsigned char buf[want];
int result;
buf[0] = 5;
buf[1] = ul;
memcpy(buf + 2, [u bytes], ul);
buf[ul + 2] = pl;
memcpy(buf + ul + 3, [p bytes], pl);
result = [ostream _write: buf + woffset
maxLength: want - woffset];
if (result == 0)
{
error = @"SOCKS end-of-file during negotiation";
}
else if (result > 0)
{
woffset += result;
if (woffset == want)
{
state = GSSOCKSAckAuth;
goto again;
}
}
}
}
else if (state == GSSOCKSAckAuth)
{
int result;
result = [istream _read: rbuffer + roffset maxLength: 2 - roffset];
if (result == 0)
{
error = @"SOCKS end-of-file during negotiation";
}
else if (result > 0)
{
roffset += result;
if (roffset == 2)
{
roffset = 0;
if (rbuffer[0] != 5)
{
error = @"SOCKS authorisation response had wrong version";
}
else if (rbuffer[1] == 0)
{
state = GSSOCKSSendConn;
goto again;
}
else if (rbuffer[1] == 2)
{
error = @"SOCKS authorisation failed";
}
}
}
}
else if (state == GSSOCKSSendConn)
{
unsigned char buf[10];
int want = 10;
int result;
const char *ptr;
/*
* Connect command is ten bytes -
* socks version
* connect command
* reserved byte
* address type
* address 4 bytes (big endian)
* port 2 bytes (big endian)
*/
buf[0] = 5; // Socks version number
buf[1] = 1; // Connect command
buf[2] = 0; // Reserved
buf[3] = 1; // Address type (IPV4)
ptr = [address UTF8String];
buf[4] = atoi(ptr);
while (isdigit(*ptr))
ptr++;
ptr++;
buf[5] = atoi(ptr);
while (isdigit(*ptr))
ptr++;
ptr++;
buf[6] = atoi(ptr);
while (isdigit(*ptr))
ptr++;
ptr++;
buf[7] = atoi(ptr);
result = [port intValue];
buf[8] = ((result & 0xff00) >> 8);
buf[9] = (result & 0xff);
result = [ostream _write: buf + woffset maxLength: want - woffset];
if (result == 0)
{
error = @"SOCKS end-of-file during negotiation";
}
else if (result > 0)
{
woffset += result;
if (woffset == want)
{
rwant = 5;
state = GSSOCKSAckConn;
goto again;
}
}
}
else if (state == GSSOCKSAckConn)
{
int result;
result = [istream _read: rbuffer + roffset
maxLength: rwant - roffset];
if (result == 0)
{
error = @"SOCKS end-of-file during negotiation";
}
else if (result > 0)
{
roffset += result;
if (roffset == rwant)
{
if (rbuffer[0] != 5)
{
error = @"connect response from SOCKS had wrong version";
}
else if (rbuffer[1] != 0)
{
switch (rbuffer[1])
{
case 1:
error = @"SOCKS server general failure";
break;
case 2:
error = @"SOCKS server says permission denied";
break;
case 3:
error = @"SOCKS server says network unreachable";
break;
case 4:
error = @"SOCKS server says host unreachable";
break;
case 5:
error = @"SOCKS server says connection refused";
break;
case 6:
error = @"SOCKS server says connection timed out";
break;
case 7:
error = @"SOCKS server says command not supported";
break;
case 8:
error = @"SOCKS server says address not supported";
break;
default:
error = @"connect response from SOCKS was failure";
break;
}
}
else if (rbuffer[3] == 1)
{
rwant = 10; // Fixed size (IPV4) address
}
else if (rbuffer[3] == 3)
{
rwant = 7 + rbuffer[4]; // Domain name leading length
}
else if (rbuffer[3] == 4)
{
rwant = 22; // Fixed size (IPV6) address
}
else
{
error = @"SOCKS server returned unknown address type";
}
if (error == nil)
{
if (roffset < rwant)
{
goto again; // Need address/port bytes
}
else
{
NSString *a;
if (rbuffer[3] == 1)
{
a = [NSString stringWithFormat: @"%d.%d.%d.%d",
rbuffer[4], rbuffer[5], rbuffer[6], rbuffer[7]];
}
else if (rbuffer[3] == 3)
{
rbuffer[rwant] = '\0';
a = [NSString stringWithUTF8String:
(const char*)rbuffer];
}
else
{
unsigned char buf[40];
int i = 4;
int j = 0;
while (i < rwant)
{
int val;
val = rbuffer[i++];
val = val * 256 + rbuffer[i++];
if (i > 4)
{
buf[j++] = ':';
}
snprintf((char*)&buf[j], 5, "%04x", val);
j += 4;
}
a = [NSString stringWithUTF8String:
(const char*)buf];
}
[istream setProperty: a
forKey: GSStreamRemoteAddressKey];
[ostream setProperty: a
forKey: GSStreamRemoteAddressKey];
a = [NSString stringWithFormat: @"%d",
rbuffer[rwant-1] * 256 * rbuffer[rwant-2]];
[istream setProperty: a
forKey: GSStreamRemotePortKey];
[ostream setProperty: a
forKey: GSStreamRemotePortKey];
/* Return immediately after calling -bye as it
* will cause this instance to be deallocated.
*/
[self bye];
return;
}
}
}
}
}
}
if ([error length] > 0)
{
NSError *theError;
theError = [NSError errorWithDomain: NSCocoaErrorDomain
code: 0
userInfo: [NSDictionary dictionaryWithObject: error
forKey: NSLocalizedDescriptionKey]];
if ([istream streamStatus] != NSStreamStatusError)
{
[istream _recordError: theError];
}
if ([ostream streamStatus] != NSStreamStatusError)
{
[ostream _recordError: theError];
}
[self bye];
}
}
- (NSInteger) write: (const uint8_t *)buffer maxLength: (NSUInteger)len
{
return [ostream _write: buffer maxLength: len];
}
@end
static inline BOOL
socketError(int result)
{
#if defined(_WIN32)
return (result == SOCKET_ERROR) ? YES : NO;
#else
return (result < 0) ? YES : NO;
#endif
}
static inline BOOL
socketWouldBlock(long eno)
{
return GSWOULDBLOCK(eno) ? YES : NO;
}
static void
setNonBlocking(SOCKET fd)
{
#if defined(_WIN32)
unsigned long dummy = 1;
if (ioctlsocket(fd, FIONBIO, &dummy) == SOCKET_ERROR)
{
NSLog(@"unable to set non-blocking mode - %@", [NSError _last]);
}
#else
int flags = fcntl(fd, F_GETFL, 0);
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0)
{
NSLog(@"unable to set non-blocking mode - %@",
[NSError _last]);
}
#endif
}
@implementation GSSocketStream
- (void) dealloc
{
if (_sock != INVALID_SOCKET)
{
[self close];
}
[_sibling _setSibling: nil];
_sibling = nil;
[_handler remove: self];
DESTROY(_handler);
[super dealloc];
}
- (NSString*) description
{
return [NSString stringWithFormat: @"<%s: %p sock %lld loopID %p mask %@>",
class_getName(object_getClass(self)), self,
(long long)_sock, _loopID, [self _stringFromEvents]];
}
- (id) init
{
if ((self = [super init]) != nil)
{
// so that unopened access will fail
_sibling = nil;
_closing = NO;
_passive = NO;
#if defined(_WIN32)
_loopID = WSA_INVALID_EVENT;
#else
_loopID = (void*)(intptr_t)-1;
#endif
_sock = INVALID_SOCKET;
_handler = nil;
_address.s.sa_family = AF_UNSPEC;
}
return self;
}
- (struct sockaddr*) _address
{
return &_address.s;
}
- (id) propertyForKey: (NSString *)key
{
id result = [super propertyForKey: key];
if (result == nil && _address.s.sa_family != AF_UNSPEC)
{
SOCKET s = [self _sock];
sockaddr_any sin;
socklen_t size = sizeof(sin);
memset(&sin, '\0', size);
if ([key isEqualToString: GSStreamLocalAddressKey])
{
if (getsockname(s, (struct sockaddr*)&sin, (OPTLEN*)&size) != -1)
{
result = GSPrivateSockaddrHost((struct sockaddr*)&sin);
}
}
else if ([key isEqualToString: GSStreamLocalPortKey])
{
if (getsockname(s, (struct sockaddr*)&sin, (OPTLEN*)&size) != -1)
{
result = [NSString stringWithFormat: @"%d",
(int)GSPrivateSockaddrPort((struct sockaddr*)&sin)];
}
}
else if ([key isEqualToString: GSStreamRemoteAddressKey])
{
if (getpeername(s, (struct sockaddr*)&sin, (OPTLEN*)&size) != -1)
{
result = GSPrivateSockaddrHost((struct sockaddr*)&sin);
}
}
else if ([key isEqualToString: GSStreamRemotePortKey])
{
if (getpeername(s, (struct sockaddr*)&sin, (OPTLEN*)&size) != -1)
{
result = [NSString stringWithFormat: @"%d",
(int)GSPrivateSockaddrPort((struct sockaddr*)&sin)];
}
}
}
return result;
}
- (NSInteger) _read: (uint8_t *)buffer maxLength: (NSUInteger)len
{
[self subclassResponsibility: _cmd];
return -1;
}
- (void) _sendEvent: (NSStreamEvent)event
{
/* If the receiver has a TLS handshake in progress,
* we must send events to the TLS handler rather than
* the stream delegate.
*/
if (_handler != nil && [_handler handshake] == YES)
{
/* Must retain self here to avoid premature deallocation of input
* and/or output stream in case of an error during TLS handshake.
*/
RETAIN(self);
[self _sendEvent: event delegate: _handler];
RELEASE(self);
}
else
{
[super _sendEvent: event];
}
}
- (BOOL) _setSocketAddress: (NSString*)address
port: (NSInteger)port
family: (NSInteger)family
{
uint16_t p = (uint16_t)port;
switch (family)
{
case AF_INET:
{
int ptonReturn;
const char *addr_c;
struct sockaddr_in peer;
addr_c = [address cStringUsingEncoding: NSUTF8StringEncoding];
memset(&peer, '\0', sizeof(peer));
peer.sin_family = AF_INET;
peer.sin_port = GSSwapHostI16ToBig(p);
ptonReturn = inet_pton(AF_INET, addr_c, &peer.sin_addr);
if (ptonReturn <= 0) // error
{
return NO;
}
else
{
[self _setAddress: (struct sockaddr*)&peer];
return YES;
}
}
#if defined(AF_INET6)
case AF_INET6:
{
int ptonReturn;
const char *addr_c;
struct sockaddr_in6 peer;
addr_c = [address cStringUsingEncoding: NSUTF8StringEncoding];
memset(&peer, '\0', sizeof(peer));
peer.sin6_family = AF_INET6;
peer.sin6_port = GSSwapHostI16ToBig(p);
ptonReturn = inet_pton(AF_INET6, addr_c, &peer.sin6_addr);
if (ptonReturn <= 0) // error
{
return NO;
}
else
{
[self _setAddress: (struct sockaddr*)&peer];
return YES;
}
}
#endif
#ifndef _WIN32
case AF_LOCAL:
{
struct sockaddr_un peer;
const char *c_addr;
c_addr = [address fileSystemRepresentation];
memset(&peer, '\0', sizeof(peer));
peer.sun_family = AF_LOCAL;
if (strlen(c_addr) > sizeof(peer.sun_path)-1) // too long
{
return NO;
}
else
{
strncpy(peer.sun_path, c_addr, sizeof(peer.sun_path)-1);
[self _setAddress: (struct sockaddr*)&peer];
return YES;
}
}
#endif
default:
return NO;
}
}
- (void) _setAddress: (struct sockaddr*)address
{
memcpy(&_address.s, address, GSPrivateSockaddrLength(address));
}
- (void) _setLoopID: (void *)ref
{
#if !defined(_WIN32)
_sock = (SOCKET)(intptr_t)ref; // On gnu/linux _sock is _loopID
#endif
_loopID = ref;
}
- (void) _setClosing: (BOOL)closing
{
_closing = closing;
}
- (void) _setPassive: (BOOL)passive
{
_passive = passive;
}
- (void) _setSibling: (GSSocketStream*)sibling
{
_sibling = sibling;
}
- (void) _setSock: (SOCKET)sock
{
setNonBlocking(sock);
_sock = sock;
/* As well as recording the socket, we set up the stream for monitoring it.
* On unix style systems we set the socket descriptor as the _loopID to be
* monitored, and on mswindows systems we create an event object to be
* monitored (the socket events are assoociated with this object later).
*/
#if defined(_WIN32)
_loopID = CreateEvent(NULL, NO, NO, NULL);
#else
_loopID = (void*)(intptr_t)sock; // On gnu/linux _sock is _loopID
#endif
}
- (void) _setHandler: (id)h
{
ASSIGN(_handler, h);
}
- (SOCKET) _sock
{
return _sock;
}
- (NSInteger) _write: (const uint8_t *)buffer maxLength: (NSUInteger)len
{
[self subclassResponsibility: _cmd];
return -1;
}
@end
@implementation GSSocketInputStream
+ (void) initialize
{
if (self == [GSSocketInputStream class])
{
GSObjCAddClassBehavior(self, [GSSocketStream class]);
}
}
- (void) open
{
NSDebugMLLog(@"NSStream", @"%@", self);
// could be opened because of sibling
if ([self _isOpened])
return;
if (_sibling && [_sibling streamStatus] == NSStreamStatusError)
{
[self _setStatus: NSStreamStatusError];
return;
}
if (_passive || (_sibling && [_sibling _isOpened]))
goto open_ok;
// check sibling status, avoid double connect
if (_sibling && [_sibling streamStatus] == NSStreamStatusOpening)
{
[self _setStatus: NSStreamStatusOpening];
return;
}
else
{
int result;
if ([self _sock] == INVALID_SOCKET)
{
SOCKET s;
if (_handler == nil)
{
[GSSOCKS tryInput: self output: _sibling];
}
s = socket(_address.s.sa_family, SOCK_STREAM, 0);
if (BADSOCKET(s))
{
[self _recordError];
return;
}
else
{
[GSTcpTune tune: (void*)(intptr_t)s with: self];
[self _setSock: s];
[_sibling _setSock: s];
}
}
if (nil == _handler)
{
[GSTLSHandler tryInput: self output: _sibling];
}
result = connect([self _sock], &_address.s,
GSPrivateSockaddrLength(&_address.s));
if (socketError(result))
{
long eno = GSNETERROR;
if (socketWouldBlock(eno))
{
/* Need to set the status first, so that the run loop can tell
* it needs to add the stream as waiting on writable, as an
* indication of opened
*/
[self _setStatus: NSStreamStatusOpening];
}
else
{
NSError *e = [NSError _systemError: eno];
/* Had an immediate connect error.
*/
[self _recordError: e];
[_sibling _recordError: e];
}
#if defined(_WIN32)
WSAEventSelect(_sock, _loopID, FD_ALL_EVENTS);
#endif
if (NSCountMapTable(_loops) > 0)
{
[self _schedule];
return;
}
else if (NSStreamStatusOpening == _currentStatus)
{
NSRunLoop *r;
NSDate *d;
/* The stream was not scheduled in any run loop, so we
* implement a blocking connect by running in the default
* run loop mode.
*/
r = [NSRunLoop currentRunLoop];
d = [NSDate distantFuture];
[r addStream: self mode: NSDefaultRunLoopMode];
while ([r runMode: NSDefaultRunLoopMode beforeDate: d] == YES)
{
if (_currentStatus != NSStreamStatusOpening)
{
break;
}
}
[r removeStream: self mode: NSDefaultRunLoopMode];
return;
}
}
}
open_ok:
#if defined(_WIN32)
WSAEventSelect(_sock, _loopID, FD_ALL_EVENTS);
#endif
[super open];
}
- (void) close
{
NSDebugMLLog(@"NSStream", @"%@", self);
/* If the socket descriptor is still present, we need to close it to
* avoid a leak no matter what the nominal state of the stream is.
* The descriptor is created before the stream is formally opened.
*/
if (INVALID_SOCKET == _sock)
{
if (_currentStatus == NSStreamStatusNotOpen)
{
NSDebugMLLog(@"NSStream",
@"Attempt to close unopened stream %@", self);
return;
}
if (_currentStatus == NSStreamStatusClosed)
{
NSDebugMLLog(@"NSStream",
@"Attempt to close already closed stream %@", self);
return;
}
}
[_handler bye];
#if defined(_WIN32)
[super close];
if (_sibling && [_sibling streamStatus] != NSStreamStatusClosed)
{
/*
* Windows only permits a single event to be associated with a socket
* at any time, but the runloop system only allows an event handle to
* be added to the loop once, and we have two streams for each socket.
* So we use two events, one for each stream, and when one stream is
* closed, we must call WSAEventSelect to ensure that the event handle
* of the sibling is used to signal events from now on.
*/
shutdown(_sock, SHUT_RD);
[_sibling _unschedule];
if (WSAEventSelect(_sock, [_sibling _loopID], FD_ALL_EVENTS)
== SOCKET_ERROR)
{
NSDebugMLLog(@"NSStream", @"%@ Error %d transferring to %@",
self, WSAGetLastError(), _sibling);
}
[_sibling _schedule];
}
else
{
closesocket(_sock);
}
WSACloseEvent(_loopID);
_loopID = WSA_INVALID_EVENT;
#else
[super close];
// read shutdown is ignored, because the other side may shutdown first.
if (!_sibling || [_sibling streamStatus] == NSStreamStatusClosed)
close((intptr_t)_loopID);
else
shutdown((intptr_t)_loopID, SHUT_RD);
_loopID = (void*)(intptr_t)-1;
#endif
_sock = INVALID_SOCKET;
}
- (NSInteger) read: (uint8_t *)buffer maxLength: (NSUInteger)len
{
NSInteger result;
if (buffer == 0)
{
[NSException raise: NSInvalidArgumentException
format: @"null pointer for buffer"];
}
if (len == 0)
{
[NSException raise: NSInvalidArgumentException
format: @"zero byte read requested"];
}
if (_handler == nil)
result = [self _read: buffer maxLength: len];
else
result = [_handler read: buffer maxLength: len];
NSDebugMLLog(@"NSStream", @"%@ tried %lld result %lld",
self, (long long)len, (long long) result);
return result;
}
- (NSInteger) _read: (uint8_t *)buffer maxLength: (NSUInteger)len
{
int readLen;
_events &= ~NSStreamEventHasBytesAvailable;
if ([self streamStatus] == NSStreamStatusClosed)
{
return 0;
}
if ([self streamStatus] == NSStreamStatusAtEnd)
{
readLen = 0;
}
else
{
#if defined(_WIN32)
readLen = recv([self _sock], (char*) buffer, (socklen_t) len, 0);
#else
readLen = read([self _sock], buffer, len);
#endif
}
if (socketError(readLen))
{
long eno = GSNETERROR;
if (_closing == YES)
{
/* If a read fails on a closing socket,
* we have reached the end of all data sent by
* the remote end before it shut down.
*/
[self _setClosing: NO];
[self _setStatus: NSStreamStatusAtEnd];
[self _sendEvent: NSStreamEventEndEncountered];
readLen = 0;
}
else
{
#if defined(_WIN32)
if (WSAECONNABORTED == eno)
{
readLen = 0; // Read end of file
readLen = -1;
}
else
#endif
if (socketWouldBlock(eno))
{
/* We need an event from the operating system
* to tell us we can start reading again.
*/
[self _setStatus: NSStreamStatusReading];
}
else
{
NSError *e = [NSError _systemError: eno];
[self _recordError: e];
readLen = -1;
}
}
}
else if (readLen == 0)
{
[self _setStatus: NSStreamStatusAtEnd];
[self _sendEvent: NSStreamEventEndEncountered];
}
else
{
[self _setStatus: NSStreamStatusOpen];
}
return readLen;
}
- (BOOL) getBuffer: (uint8_t **)buffer length: (NSUInteger *)len
{
return NO;
}
- (void) _dispatch
{
#if defined(_WIN32)
AUTORELEASE(RETAIN(self));
/*
* Windows only permits a single event to be associated with a socket
* at any time, but the runloop system only allows an event handle to
* be added to the loop once, and we have two streams for each socket.
* So we use two events, one for each stream, and the _dispatch method
* must handle things for both streams.
*/
if ([self streamStatus] == NSStreamStatusClosed)
{
/*
* It is possible the stream is closed yet recieving event because
* of not closed sibling
*/
NSAssert([_sibling streamStatus] != NSStreamStatusClosed,
@"Received event for closed stream");
[_sibling _dispatch];
}
else if ([self streamStatus] == NSStreamStatusAtEnd)
{
[self _sendEvent: NSStreamEventEndEncountered];
}
else if ([self streamStatus] == NSStreamStatusError)
{
[self _sendEvent: NSStreamEventErrorOccurred];
}
else
{
WSANETWORKEVENTS events;
int error = 0;
int getReturn = -1;
if (WSAEnumNetworkEvents(_sock, _loopID, &events) == SOCKET_ERROR)
{
error = WSAGetLastError();
NSDebugMLLog(@"NSStream", @"%@ Error %d", self, error);
}
#ifndef NDEBUG
else
{
NSDebugMLLog(@"NSStream", @"%@ EVENTS 0x%lx",
self, events.lNetworkEvents);
}
#endif
if ([self streamStatus] == NSStreamStatusOpening)
{
[self _unschedule];
if (error == 0)
{
socklen_t len = sizeof(error);
getReturn = getsockopt(_sock, SOL_SOCKET, SO_ERROR,
(char*)&error, (OPTLEN*)&len);
}
if (getReturn >= 0 && error == 0
&& (events.lNetworkEvents & FD_CONNECT))
{ // finish up the opening
_passive = YES;
[self open];
// notify sibling
if (_sibling)
{
[_sibling open];
[_sibling _sendEvent: NSStreamEventOpenCompleted];
}
[self _sendEvent: NSStreamEventOpenCompleted];
}
}
if (error != 0)
{
NSError *e = [NSError _systemError: error];
errno = error;
[self _recordError: e];
[self _sendEvent: NSStreamEventErrorOccurred];
if ([_sibling streamStatus] == NSStreamStatusOpening)
{
[_sibling _recordError: e];
[_sibling _sendEvent: NSStreamEventErrorOccurred];
}
}
else
{
if (events.lNetworkEvents & FD_WRITE)
{
if (_sibling && NSStreamStatusWriting == [_sibling streamStatus])
{
[_sibling _setStatus: NSStreamStatusOpen];
}
}
/* On winsock a socket is always writable unless it has had
* failure/closure or a write blocked and we have not been
* signalled again.
*/
while ([_sibling _unhandledData] == NO
&& [_sibling hasSpaceAvailable])
{
[_sibling _sendEvent: NSStreamEventHasSpaceAvailable];
}
if (events.lNetworkEvents & FD_READ)
{
[self _setStatus: NSStreamStatusOpen];
while ([self hasBytesAvailable]
&& [self _unhandledData] == NO)
{
[self _sendEvent: NSStreamEventHasBytesAvailable];
}
}
if (events.lNetworkEvents & FD_CLOSE)
{
[self _setClosing: YES];
[_sibling _setClosing: YES];
while ([self hasBytesAvailable]
&& [self _unhandledData] == NO)
{
[self _sendEvent: NSStreamEventHasBytesAvailable];
}
}
if (events.lNetworkEvents == 0)
{
[self _sendEvent: NSStreamEventHasBytesAvailable];
}
}
}
#else
NSStreamEvent myEvent;
if ([self streamStatus] == NSStreamStatusOpening)
{
int error;
int result;
socklen_t len = sizeof(error);
IF_NO_ARC([[self retain] autorelease];)
[self _unschedule];
result = getsockopt([self _sock], SOL_SOCKET, SO_ERROR,
&error, (OPTLEN*)&len);
if (result >= 0 && !error)
{ // finish up the opening
myEvent = NSStreamEventOpenCompleted;
_passive = YES;
[self open];
// notify sibling
[_sibling open];
[_sibling _sendEvent: myEvent];
}
else // must be an error
{
NSError *e = [NSError _systemError: error];
[self _recordError: e];
myEvent = NSStreamEventErrorOccurred;
[_sibling _recordError: e];
[_sibling _sendEvent: myEvent];
}
}
else if ([self streamStatus] == NSStreamStatusAtEnd)
{
myEvent = NSStreamEventEndEncountered;
}
else if ([self streamStatus] == NSStreamStatusError)
{
myEvent = NSStreamEventErrorOccurred;
}
else
{
[self _setStatus: NSStreamStatusOpen];
myEvent = NSStreamEventHasBytesAvailable;
}
[self _sendEvent: myEvent];
#endif
}
- (BOOL) runLoopShouldBlock: (BOOL*)trigger
{
/* If there is a handler in place which has data buffered for reading
* the run loop should trigger immediately so we read it.
*/
if ([_handler readable])
{
*trigger = YES;
return NO;
}
#if defined(_WIN32)
*trigger = YES;
return YES;
#else
return [super runLoopShouldBlock: trigger];
#endif
}
@end
@implementation GSSocketOutputStream
+ (void) initialize
{
if (self == [GSSocketOutputStream class])
{
GSObjCAddClassBehavior(self, [GSSocketStream class]);
}
}
#ifdef _WIN32
/* On windows a stream is considered writable once it is opened, even though the
* system doesn't signal to say so. We therefore override the event sending to
* add the extra event.
*/
- (void) _sendEvent: (NSStreamEvent)event delegate: (id)delegate
{
[super _sendEvent: event delegate: delegate];
if (NSStreamEventOpenCompleted == event)
{
[super _sendEvent: NSStreamEventHasSpaceAvailable delegate: delegate];
}
}
#endif
- (NSInteger) _write: (const uint8_t *)buffer maxLength: (NSUInteger)len
{
int writeLen;
_events &= ~NSStreamEventHasSpaceAvailable;
if ([self streamStatus] == NSStreamStatusClosed)
{
return 0;
}
if ([self streamStatus] == NSStreamStatusAtEnd)
{
[self _sendEvent: NSStreamEventEndEncountered];
return 0;
}
#if defined(_WIN32)
writeLen = send([self _sock], (char*) buffer, (socklen_t) len, 0);
#else
writeLen = write([self _sock], buffer, (socklen_t) len);
#endif
if (socketError(writeLen))
{
long eno = GSNETERROR;
if (_closing == YES)
{
/* If a write fails on a closing socket,
* we know the other end is no longer reading.
*/
[self _setClosing: NO];
[self _setStatus: NSStreamStatusAtEnd];
[self _sendEvent: NSStreamEventEndEncountered];
writeLen = 0;
}
else
{
#if defined(_WIN32)
if (WSAECONNABORTED == eno)
{
[_sibling _setStatus: NSStreamStatusAtEnd];
writeLen = 0;
}
else
#endif
if (socketWouldBlock(eno))
{
/* We need an event from the operating system
* to tell us we can start writing again.
*/
[self _setStatus: NSStreamStatusWriting];
writeLen = -1;
}
else
{
NSError *e = [NSError _systemError: eno];
[self _recordError: e];
writeLen = -1;
}
}
}
else
{
[self _setStatus: NSStreamStatusOpen];
}
return writeLen;
}
- (void) open
{
NSDebugMLLog(@"NSStream", @"%@", self);
// could be opened because of sibling
if ([self _isOpened])
return;
if (_sibling && [_sibling streamStatus] == NSStreamStatusError)
{
[self _setStatus: NSStreamStatusError];
return;
}
if (_passive || (_sibling && [_sibling _isOpened]))
goto open_ok;
// check sibling status, avoid double connect
if (_sibling && [_sibling streamStatus] == NSStreamStatusOpening)
{
[self _setStatus: NSStreamStatusOpening];
return;
}
else
{
int result;
if ([self _sock] == INVALID_SOCKET)
{
SOCKET s;
if (_handler == nil)
{
[GSSOCKS tryInput: _sibling output: self];
}
s = socket(_address.s.sa_family, SOCK_STREAM, 0);
if (BADSOCKET(s))
{
[self _recordError];
return;
}
else
{
[GSTcpTune tune: (void*)(intptr_t)s with: self];
[self _setSock: s];
[_sibling _setSock: s];
}
}
if (nil == _handler)
{
[GSTLSHandler tryInput: _sibling output: self];
}
result = connect([self _sock], &_address.s,
GSPrivateSockaddrLength(&_address.s));
if (socketError(result))
{
long eno = GSNETERROR;
if (socketWouldBlock(eno))
{
/*
* Need to set the status first, so that the run loop can tell
* it needs to add the stream as waiting on writable, as an
* indication of opened
*/
[self _setStatus: NSStreamStatusOpening];
}
else
{
NSError *e = [NSError _systemError: eno];
/* Had an immediate connect error.
*/
[self _recordError: e];
[_sibling _recordError: e];
}
#if defined(_WIN32)
WSAEventSelect(_sock, _loopID, FD_ALL_EVENTS);
#endif
if (NSCountMapTable(_loops) > 0)
{
[self _schedule];
return;
}
else if (NSStreamStatusOpening == _currentStatus)
{
NSRunLoop *r;
NSDate *d;
/* The stream was not scheduled in any run loop, so we
* implement a blocking connect by running in the default
* run loop mode.
*/
r = [NSRunLoop currentRunLoop];
d = [NSDate distantFuture];
[r addStream: self mode: NSDefaultRunLoopMode];
while ([r runMode: NSDefaultRunLoopMode beforeDate: d] == YES)
{
if (_currentStatus != NSStreamStatusOpening)
{
break;
}
}
[r removeStream: self mode: NSDefaultRunLoopMode];
return;
}
}
}
open_ok:
#if defined(_WIN32)
WSAEventSelect(_sock, _loopID, FD_ALL_EVENTS);
#endif
[super open];
}
- (void) close
{
NSDebugMLLog(@"NSStream", @"%@", self);
/* If the socket descriptor is still present, we need to close it to
* avoid a leak no matter what the nominal state of the stream is.
* The descriptor is created before the stream is formally opened.
*/
if (INVALID_SOCKET == _sock)
{
if (_currentStatus == NSStreamStatusNotOpen)
{
NSDebugMLLog(@"NSStream",
@"Attempt to close unopened stream %@", self);
return;
}
if (_currentStatus == NSStreamStatusClosed)
{
NSDebugMLLog(@"NSStream",
@"Attempt to close already closed stream %@", self);
return;
}
}
[_handler bye];
#if defined(_WIN32)
if (_sibling && [_sibling streamStatus] != NSStreamStatusClosed)
{
/*
* Windows only permits a single event to be associated with a socket
* at any time, but the runloop system only allows an event handle to
* be added to the loop once, and we have two streams for each socket.
* So we use two events, one for each stream, and when one stream is
* closed, we must call WSAEventSelect to ensure that the event handle
* of the sibling is used to signal events from now on.
*/
shutdown(_sock, SHUT_WR);
_sock = INVALID_SOCKET;
[_sibling _unschedule];
if (WSAEventSelect([_sibling _sock], [_sibling _loopID], FD_ALL_EVENTS)
== SOCKET_ERROR)
{
NSDebugMLLog(@"NSStream", @"%@ Error %d transferring to %@",
self, WSAGetLastError(), _sibling);
}
[_sibling _schedule];
}
else
{
closesocket(_sock);
}
WSACloseEvent(_loopID);
[super close];
_loopID = WSA_INVALID_EVENT;
#else
// read shutdown is ignored, because the other side may shutdown first.
if (!_sibling || [_sibling streamStatus] == NSStreamStatusClosed)
close((intptr_t)_loopID);
else
shutdown((intptr_t)_loopID, SHUT_WR);
[super close];
_loopID = (void*)(intptr_t)-1;
#endif
_sock = INVALID_SOCKET;
}
- (NSInteger) write: (const uint8_t *)buffer maxLength: (NSUInteger)len
{
NSInteger result;
if (len == 0)
{
/*
* The method allows the 'len' equal to 0. In this case the 'buffer'
* is ignored. This can be useful if there is a necessity to postpone
* actual writing (for no data are ready for example) without leaving
* the stream in the state of unhandled NSStreamEventHasSpaceAvailable
* (to keep receiving of that event from a runloop).
* The delegate's -[stream:handleEvent:] would keep calling of
* -[write: NULL maxLength: 0] until the delegate's state allows it
* to write actual bytes.
* The downside of that is that it produces a busy wait ... with the
* run loop immediately notifying the stream that it has space to
* write, so care should be taken to ensure that the delegate has a
* near constant supply of data to write, or has some mechanism to
* detect that no more data is arriving, and shut down.
*/
_events &= ~NSStreamEventHasSpaceAvailable;
result = 0;
}
else
{
if (buffer == 0)
{
[NSException raise: NSInvalidArgumentException
format: @"null pointer for buffer"];
}
if (_handler == nil)
result = [self _write: buffer maxLength: len];
else
result = [_handler write: buffer maxLength: len];
}
NSDebugMLLog(@"NSStream", @"%@ tried %lld result %lld",
self, (long long)len, (long long) result);
return result;
}
- (void) _dispatch
{
#if defined(_WIN32)
AUTORELEASE(RETAIN(self));
/*
* Windows only permits a single event to be associated with a socket
* at any time, but the runloop system only allows an event handle to
* be added to the loop once, and we have two streams for each socket.
* So we use two events, one for each stream, and the _dispatch method
* must handle things for both streams.
*/
if ([self streamStatus] == NSStreamStatusClosed)
{
/*
* It is possible the stream is closed yet recieving event because
* of not closed sibling
*/
NSAssert([_sibling streamStatus] != NSStreamStatusClosed,
@"Received event for closed stream");
[_sibling _dispatch];
}
else if ([self streamStatus] == NSStreamStatusAtEnd)
{
[self _sendEvent: NSStreamEventEndEncountered];
}
else if ([self streamStatus] == NSStreamStatusError)
{
[self _sendEvent: NSStreamEventErrorOccurred];
}
else
{
WSANETWORKEVENTS events;
int error = 0;
int getReturn = -1;
if (WSAEnumNetworkEvents(_sock, _loopID, &events) == SOCKET_ERROR)
{
error = WSAGetLastError();
NSDebugMLLog(@"NSStream", @"%@ Error %d", self, error);
}
#ifndef NDEBUG
else
{
NSDebugMLLog(@"NSStream", @"%@ EVENTS 0x%lx",
self, events.lNetworkEvents);
}
#endif
if ([self streamStatus] == NSStreamStatusOpening)
{
[self _unschedule];
if (error == 0)
{
socklen_t len = sizeof(error);
getReturn = getsockopt(_sock, SOL_SOCKET, SO_ERROR,
(char*)&error, (OPTLEN*)&len);
}
if (getReturn >= 0 && error == 0
&& (events.lNetworkEvents & FD_CONNECT))
{ // finish up the opening
events.lNetworkEvents ^= FD_CONNECT;
_passive = YES;
[self open];
// notify sibling
if (_sibling)
{
[_sibling open];
[_sibling _sendEvent: NSStreamEventOpenCompleted];
}
[self _sendEvent: NSStreamEventOpenCompleted];
}
}
if (error != 0)
{
NSError *e = [NSError _systemError: error];
[self _recordError: e];
[self _sendEvent: NSStreamEventErrorOccurred];
if ([_sibling streamStatus] == NSStreamStatusOpening)
{
[_sibling _recordError: e];
[_sibling _sendEvent: NSStreamEventErrorOccurred];
}
}
else
{
if (events.lNetworkEvents & FD_WRITE)
{
/* Clear NSStreamStatusWriting if it was set */
[self _setStatus: NSStreamStatusOpen];
}
/* On winsock a socket is always writable unless it has had
* failure/closure or a write blocked and we have not been
* signalled again.
*/
while ([self _unhandledData] == NO && [self hasSpaceAvailable])
{
[self _sendEvent: NSStreamEventHasSpaceAvailable];
}
if (events.lNetworkEvents & FD_READ)
{
[_sibling _setStatus: NSStreamStatusOpen];
while ([_sibling hasBytesAvailable]
&& [_sibling _unhandledData] == NO)
{
[_sibling _sendEvent: NSStreamEventHasBytesAvailable];
}
}
if (events.lNetworkEvents & FD_CLOSE)
{
[self _setClosing: YES];
[_sibling _setClosing: YES];
while ([_sibling hasBytesAvailable]
&& [_sibling _unhandledData] == NO)
{
[_sibling _sendEvent: NSStreamEventHasBytesAvailable];
}
}
if (events.lNetworkEvents == 0)
{
[self _sendEvent: NSStreamEventHasSpaceAvailable];
}
}
}
#else
NSStreamEvent myEvent;
if ([self streamStatus] == NSStreamStatusOpening)
{
int error;
socklen_t len = sizeof(error);
int result;
IF_NO_ARC([[self retain] autorelease];)
[self _schedule];
result = getsockopt((intptr_t)_loopID, SOL_SOCKET, SO_ERROR,
&error, (OPTLEN*)&len);
if (result >= 0 && !error)
{ // finish up the opening
myEvent = NSStreamEventOpenCompleted;
_passive = YES;
[self open];
// notify sibling
[_sibling open];
[_sibling _sendEvent: myEvent];
}
else // must be an error
{
NSError *e = [NSError _systemError: error];
[self _recordError: e];
myEvent = NSStreamEventErrorOccurred;
[_sibling _recordError: e];
[_sibling _sendEvent: myEvent];
}
}
else if ([self streamStatus] == NSStreamStatusAtEnd)
{
myEvent = NSStreamEventEndEncountered;
}
else if ([self streamStatus] == NSStreamStatusError)
{
myEvent = NSStreamEventErrorOccurred;
}
else
{
[self _setStatus: NSStreamStatusOpen];
myEvent = NSStreamEventHasSpaceAvailable;
}
[self _sendEvent: myEvent];
#endif
}
#if defined(_WIN32)
- (BOOL) runLoopShouldBlock: (BOOL*)trigger
{
*trigger = YES;
if ([self _unhandledData] == YES && [self streamStatus] == NSStreamStatusOpen)
{
/* In winsock, a writable status is only signalled if an earlier
* write failed (because it would block), so we must simulate the
* writable event by having the run loop trigger without blocking.
*/
return NO;
}
return YES;
}
#endif
@end
@implementation GSSocketServerStream
+ (void) initialize
{
if (self == [GSSocketServerStream class])
{
GSObjCAddClassBehavior(self, [GSSocketStream class]);
}
}
- (Class) _inputStreamClass
{
[self subclassResponsibility: _cmd];
return Nil;
}
- (Class) _outputStreamClass
{
[self subclassResponsibility: _cmd];
return Nil;
}
- (void) open
{
int bindReturn;
int listenReturn;
SOCKET s;
NSDebugMLLog(@"NSStream", @"%@", self);
if (_currentStatus != NSStreamStatusNotOpen)
{
NSDebugMLLog(@"NSStream",
@"Attempt to re-open stream %@", self);
return;
}
s = socket(_address.s.sa_family, SOCK_STREAM, 0);
if (BADSOCKET(s))
{
[self _recordError];
[self _sendEvent: NSStreamEventErrorOccurred];
return;
}
else
{
[GSTcpTune tune: (void*)(intptr_t)s with: self];
[(GSSocketStream*)self _setSock: s];
}
#ifndef BROKEN_SO_REUSEADDR
if (_address.s.sa_family == AF_INET
#ifdef AF_INET6
|| _address.s.sa_family == AF_INET6
#endif
)
{
/*
* Under decent systems, SO_REUSEADDR means that the port can be reused
* immediately that this process exits. Under some it means
* that multiple processes can serve the same port simultaneously.
* We don't want that broken behavior!
*/
int status = 1;
if (setsockopt([self _sock], SOL_SOCKET, SO_REUSEADDR,
(char *)&status, (OPTLEN)sizeof(status)) < 0)
{
NSDebugMLLog(@"GSTcpTune", @"setsockopt reuseaddr failed");
}
}
#endif
bindReturn = bind([self _sock],
&_address.s, GSPrivateSockaddrLength(&_address.s));
if (socketError(bindReturn))
{
[self _recordError];
[self _sendEvent: NSStreamEventErrorOccurred];
return;
}
listenReturn = listen([self _sock], GSBACKLOG);
if (socketError(listenReturn))
{
[self _recordError];
[self _sendEvent: NSStreamEventErrorOccurred];
return;
}
#if defined(_WIN32)
if (_loopID != WSA_INVALID_EVENT)
{
WSAEventSelect(_sock, _loopID, FD_ALL_EVENTS);
}
#endif
[super open];
}
- (void) close
{
NSDebugMLLog(@"NSStream", @"%@", self);
#if defined(_WIN32)
if (_loopID != WSA_INVALID_EVENT)
{
WSACloseEvent(_loopID);
}
if (_sock != INVALID_SOCKET)
{
closesocket(_sock);
[super close];
_loopID = WSA_INVALID_EVENT;
}
#else
if (_loopID != (void*)(intptr_t)-1)
{
close((intptr_t)_loopID);
[super close];
_loopID = (void*)(intptr_t)-1;
}
#endif
_sock = INVALID_SOCKET;
}
- (void) acceptWithInputStream: (NSInputStream **)inputStream
outputStream: (NSOutputStream **)outputStream
{
NSArray *keys;
NSUInteger count;
NSMutableDictionary *opts;
NSString *str;
GSSocketStream *ins = AUTORELEASE([[self _inputStreamClass] new]);
GSSocketStream *outs = AUTORELEASE([[self _outputStreamClass] new]);
/* Align on a 2 byte boundary for a 16bit port number in the sockaddr
*/
struct {
uint8_t bytes[BUFSIZ];
} __attribute__((aligned(2)))buf;
struct sockaddr *addr = (struct sockaddr*)&buf;
socklen_t len = sizeof(buf);
int acceptReturn;
acceptReturn = accept([self _sock], addr, (OPTLEN*)&len);
_events &= ~NSStreamEventHasBytesAvailable;
if (socketError(acceptReturn))
{ // test for real error
long eno = GSNETERROR;
if (!socketWouldBlock(eno))
{
NSError *e = [NSError _systemError: eno];
[self _recordError: e];
}
ins = nil;
outs = nil;
}
else
{
// no need to connect again
[ins _setPassive: YES];
[outs _setPassive: YES];
// copy the addr to outs
[ins _setAddress: addr];
[outs _setAddress: addr];
[ins _setSock: acceptReturn];
[outs _setSock: acceptReturn];
/* Set property to indicate that the input stream was accepted by
* a listening socket (server) rather than produced by an outgoing
* connection (client).
*/
[ins setProperty: @"YES" forKey: @"IsServer"];
/* At this point, we can insert the handler to deal with TLS
*/
str = [self propertyForKey: NSStreamSocketSecurityLevelKey];
if (nil != str)
{
opts = [NSMutableDictionary new];
[opts setObject: str forKey: NSStreamSocketSecurityLevelKey];
// copy the properties in the 'opts'
[GSTLSHandler populateProperties: &opts
withSecurityLevel: str
fromInputStream: self
orOutputStream: nil];
// and set the input/output streams's properties from the 'opts'
keys = [opts allKeys];
count = [keys count];
while(count-- > 0)
{
NSString *key = [keys objectAtIndex: count];
str = [opts objectForKey: key];
[ins setProperty: str forKey: key];
[outs setProperty: str forKey: key];
}
/* Set the streams to be 'open' in order to have the TLS
* handshake done. On completion the state will be reset.
*/
[ins _setStatus: NSStreamStatusOpen];
[outs _setStatus: NSStreamStatusOpen];
[GSTLSHandler tryInput: (GSSocketInputStream *)ins
output: (GSSocketOutputStream *)outs];
DESTROY(opts);
}
}
if (inputStream)
{
[ins _setSibling: outs];
*inputStream = (NSInputStream*)ins;
}
if (outputStream)
{
[outs _setSibling: ins];
*outputStream = (NSOutputStream*)outs;
}
/* Now the streams are ready to be opened.
*/
}
- (void) _dispatch
{
#if defined(_WIN32)
WSANETWORKEVENTS events;
if (WSAEnumNetworkEvents(_sock, _loopID, &events) == SOCKET_ERROR)
{
errno = WSAGetLastError();
[self _recordError];
[self _sendEvent: NSStreamEventErrorOccurred];
}
else if (events.lNetworkEvents & FD_ACCEPT)
{
events.lNetworkEvents ^= FD_ACCEPT;
[self _setStatus: NSStreamStatusReading];
[self _sendEvent: NSStreamEventHasBytesAvailable];
}
#else
NSStreamEvent myEvent;
[self _setStatus: NSStreamStatusOpen];
myEvent = NSStreamEventHasBytesAvailable;
[self _sendEvent: myEvent];
#endif
}
@end
@implementation GSInetInputStream
- (id) initToAddr: (NSString*)addr port: (NSInteger)port
{
if ((self = [super init]) != nil)
{
if ([self _setSocketAddress: addr port: port family: AF_INET] == NO)
{
DESTROY(self);
}
}
return self;
}
@end
@implementation GSInet6InputStream
#if defined(AF_INET6)
- (id) initToAddr: (NSString*)addr port: (NSInteger)port
{
if ((self = [super init]) != nil)
{
if ([self _setSocketAddress: addr port: port family: AF_INET6] == NO)
{
DESTROY(self);
}
}
return self;
}
#else
- (id) initToAddr: (NSString*)addr port: (NSInteger)port
{
DESTROY(self);
return nil;
}
#endif
@end
@implementation GSInetOutputStream
- (id) initToAddr: (NSString*)addr port: (NSInteger)port
{
if ((self = [super init]) != nil)
{
if ([self _setSocketAddress: addr port: port family: AF_INET] == NO)
{
DESTROY(self);
}
}
return self;
}
@end
@implementation GSInet6OutputStream
#if defined(AF_INET6)
- (id) initToAddr: (NSString*)addr port: (NSInteger)port
{
if ((self = [super init]) != nil)
{
if ([self _setSocketAddress: addr port: port family: AF_INET6] == NO)
{
DESTROY(self);
}
}
return self;
}
#else
- (id) initToAddr: (NSString*)addr port: (NSInteger)port
{
DESTROY(self);
return nil;
}
#endif
@end
@implementation GSInetServerStream
- (Class) _inputStreamClass
{
return [GSInetInputStream class];
}
- (Class) _outputStreamClass
{
return [GSInetOutputStream class];
}
- (id) initToAddr: (NSString*)addr port: (NSInteger)port
{
if ((self = [super init]) != nil)
{
if ([addr length] == 0)
{
addr = @"0.0.0.0";
}
if ([self _setSocketAddress: addr port: port family: AF_INET] == NO)
{
DESTROY(self);
}
}
return self;
}
@end
@implementation GSInet6ServerStream
#if defined(AF_INET6)
- (Class) _inputStreamClass
{
return [GSInet6InputStream class];
}
- (Class) _outputStreamClass
{
return [GSInet6OutputStream class];
}
- (id) initToAddr: (NSString*)addr port: (NSInteger)port
{
if ([super init] != nil)
{
if ([addr length] == 0)
{
addr = @"0:0:0:0:0:0:0:0"; /* Bind on all addresses */
}
if ([self _setSocketAddress: addr port: port family: AF_INET6] == NO)
{
DESTROY(self);
}
}
return self;
}
#else
- (id) initToAddr: (NSString*)addr port: (NSInteger)port
{
DESTROY(self);
return nil;
}
#endif
@end
|