socket2/sys/unix.rs
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
// Copyright 2015 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cmp::min;
use std::ffi::OsStr;
#[cfg(not(target_os = "redox"))]
use std::io::IoSlice;
use std::marker::PhantomData;
use std::mem::{self, size_of, MaybeUninit};
use std::net::Shutdown;
use std::net::{Ipv4Addr, Ipv6Addr};
#[cfg(all(
feature = "all",
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
))]
use std::num::NonZeroU32;
#[cfg(all(
feature = "all",
any(
target_os = "aix",
target_os = "android",
target_os = "freebsd",
target_os = "ios",
target_os = "linux",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
))]
use std::num::NonZeroUsize;
use std::os::unix::ffi::OsStrExt;
#[cfg(all(
feature = "all",
any(
target_os = "aix",
target_os = "android",
target_os = "freebsd",
target_os = "ios",
target_os = "linux",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
))]
use std::os::unix::io::RawFd;
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd};
#[cfg(feature = "all")]
use std::os::unix::net::{UnixDatagram, UnixListener, UnixStream};
use std::path::Path;
use std::ptr;
use std::time::{Duration, Instant};
use std::{io, slice};
#[cfg(not(any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)))]
use libc::ssize_t;
use libc::{in6_addr, in_addr};
use crate::{Domain, Protocol, SockAddr, TcpKeepalive, Type};
#[cfg(not(target_os = "redox"))]
use crate::{MsgHdr, MsgHdrMut, RecvFlags};
pub(crate) use libc::c_int;
// Used in `Domain`.
pub(crate) use libc::{AF_INET, AF_INET6, AF_UNIX};
// Used in `Type`.
#[cfg(all(feature = "all", target_os = "linux"))]
pub(crate) use libc::SOCK_DCCP;
#[cfg(all(feature = "all", not(any(target_os = "redox", target_os = "espidf"))))]
pub(crate) use libc::SOCK_RAW;
#[cfg(all(feature = "all", not(target_os = "espidf")))]
pub(crate) use libc::SOCK_SEQPACKET;
pub(crate) use libc::{SOCK_DGRAM, SOCK_STREAM};
// Used in `Protocol`.
#[cfg(all(feature = "all", target_os = "linux"))]
pub(crate) use libc::IPPROTO_DCCP;
#[cfg(target_os = "linux")]
pub(crate) use libc::IPPROTO_MPTCP;
#[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux")))]
pub(crate) use libc::IPPROTO_SCTP;
#[cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
)
))]
pub(crate) use libc::IPPROTO_UDPLITE;
pub(crate) use libc::{IPPROTO_ICMP, IPPROTO_ICMPV6, IPPROTO_TCP, IPPROTO_UDP};
// Used in `SockAddr`.
#[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "openbsd")))]
pub(crate) use libc::IPPROTO_DIVERT;
pub(crate) use libc::{
sa_family_t, sockaddr, sockaddr_in, sockaddr_in6, sockaddr_storage, socklen_t,
};
// Used in `RecvFlags`.
#[cfg(not(any(target_os = "redox", target_os = "espidf")))]
pub(crate) use libc::MSG_TRUNC;
#[cfg(not(target_os = "redox"))]
pub(crate) use libc::SO_OOBINLINE;
// Used in `Socket`.
#[cfg(not(target_os = "nto"))]
pub(crate) use libc::ipv6_mreq as Ipv6Mreq;
#[cfg(not(any(
target_os = "dragonfly",
target_os = "fuchsia",
target_os = "illumos",
target_os = "netbsd",
target_os = "openbsd",
target_os = "redox",
target_os = "solaris",
target_os = "haiku",
target_os = "espidf",
target_os = "vita",
)))]
pub(crate) use libc::IPV6_RECVTCLASS;
#[cfg(all(feature = "all", not(any(target_os = "redox", target_os = "espidf"))))]
pub(crate) use libc::IP_HDRINCL;
#[cfg(not(any(
target_os = "aix",
target_os = "dragonfly",
target_os = "fuchsia",
target_os = "illumos",
target_os = "netbsd",
target_os = "openbsd",
target_os = "redox",
target_os = "solaris",
target_os = "haiku",
target_os = "nto",
target_os = "espidf",
target_os = "vita",
)))]
pub(crate) use libc::IP_RECVTOS;
#[cfg(not(any(
target_os = "fuchsia",
target_os = "redox",
target_os = "solaris",
target_os = "illumos",
)))]
pub(crate) use libc::IP_TOS;
#[cfg(not(any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)))]
pub(crate) use libc::SO_LINGER;
#[cfg(any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
))]
pub(crate) use libc::SO_LINGER_SEC as SO_LINGER;
pub(crate) use libc::{
ip_mreq as IpMreq, linger, IPPROTO_IP, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, IPV6_MULTICAST_IF,
IPV6_MULTICAST_LOOP, IPV6_UNICAST_HOPS, IPV6_V6ONLY, IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP,
IP_MULTICAST_IF, IP_MULTICAST_LOOP, IP_MULTICAST_TTL, IP_TTL, MSG_OOB, MSG_PEEK, SOL_SOCKET,
SO_BROADCAST, SO_ERROR, SO_KEEPALIVE, SO_RCVBUF, SO_RCVTIMEO, SO_REUSEADDR, SO_SNDBUF,
SO_SNDTIMEO, SO_TYPE, TCP_NODELAY,
};
#[cfg(not(any(
target_os = "dragonfly",
target_os = "haiku",
target_os = "netbsd",
target_os = "openbsd",
target_os = "redox",
target_os = "fuchsia",
target_os = "nto",
target_os = "espidf",
target_os = "vita",
)))]
pub(crate) use libc::{
ip_mreq_source as IpMreqSource, IP_ADD_SOURCE_MEMBERSHIP, IP_DROP_SOURCE_MEMBERSHIP,
};
#[cfg(not(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "haiku",
target_os = "illumos",
target_os = "ios",
target_os = "macos",
target_os = "netbsd",
target_os = "nto",
target_os = "openbsd",
target_os = "solaris",
target_os = "tvos",
target_os = "watchos",
)))]
pub(crate) use libc::{IPV6_ADD_MEMBERSHIP, IPV6_DROP_MEMBERSHIP};
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "haiku",
target_os = "illumos",
target_os = "ios",
target_os = "macos",
target_os = "netbsd",
target_os = "openbsd",
target_os = "solaris",
target_os = "tvos",
target_os = "watchos",
))]
pub(crate) use libc::{
IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP, IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP,
};
#[cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "illumos",
target_os = "ios",
target_os = "linux",
target_os = "macos",
target_os = "netbsd",
target_os = "tvos",
target_os = "watchos",
)
))]
pub(crate) use libc::{TCP_KEEPCNT, TCP_KEEPINTVL};
// See this type in the Windows file.
pub(crate) type Bool = c_int;
#[cfg(any(
target_os = "ios",
target_os = "macos",
target_os = "nto",
target_os = "tvos",
target_os = "watchos",
))]
use libc::TCP_KEEPALIVE as KEEPALIVE_TIME;
#[cfg(not(any(
target_os = "haiku",
target_os = "ios",
target_os = "macos",
target_os = "nto",
target_os = "openbsd",
target_os = "tvos",
target_os = "watchos",
target_os = "vita",
)))]
use libc::TCP_KEEPIDLE as KEEPALIVE_TIME;
/// Helper macro to execute a system call that returns an `io::Result`.
macro_rules! syscall {
($fn: ident ( $($arg: expr),* $(,)* ) ) => {{
#[allow(unused_unsafe)]
let res = unsafe { libc::$fn($($arg, )*) };
if res == -1 {
Err(std::io::Error::last_os_error())
} else {
Ok(res)
}
}};
}
/// Maximum size of a buffer passed to system call like `recv` and `send`.
#[cfg(not(any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)))]
const MAX_BUF_LEN: usize = ssize_t::MAX as usize;
// The maximum read limit on most posix-like systems is `SSIZE_MAX`, with the
// man page quoting that if the count of bytes to read is greater than
// `SSIZE_MAX` the result is "unspecified".
//
// On macOS, however, apparently the 64-bit libc is either buggy or
// intentionally showing odd behavior by rejecting any read with a size larger
// than or equal to INT_MAX. To handle both of these the read size is capped on
// both platforms.
#[cfg(any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
))]
const MAX_BUF_LEN: usize = c_int::MAX as usize - 1;
// TCP_CA_NAME_MAX isn't defined in user space include files(not in libc)
#[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux")))]
const TCP_CA_NAME_MAX: usize = 16;
#[cfg(any(
all(
target_os = "linux",
any(
target_env = "gnu",
all(target_env = "uclibc", target_pointer_width = "64")
)
),
target_os = "android",
))]
type IovLen = usize;
#[cfg(any(
all(
target_os = "linux",
any(
target_env = "musl",
all(target_env = "uclibc", target_pointer_width = "32")
)
),
target_os = "aix",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "haiku",
target_os = "illumos",
target_os = "ios",
target_os = "macos",
target_os = "netbsd",
target_os = "nto",
target_os = "openbsd",
target_os = "solaris",
target_os = "tvos",
target_os = "watchos",
target_os = "espidf",
target_os = "vita",
))]
type IovLen = c_int;
/// Unix only API.
impl Domain {
/// Domain for low-level packet interface, corresponding to `AF_PACKET`.
#[cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
)))
)]
pub const PACKET: Domain = Domain(libc::AF_PACKET);
/// Domain for low-level VSOCK interface, corresponding to `AF_VSOCK`.
#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
#[cfg_attr(
docsrs,
doc(cfg(all(feature = "all", any(target_os = "android", target_os = "linux"))))
)]
pub const VSOCK: Domain = Domain(libc::AF_VSOCK);
}
impl_debug!(
Domain,
libc::AF_INET,
libc::AF_INET6,
libc::AF_UNIX,
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
#[cfg_attr(
docsrs,
doc(cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux")))
)]
libc::AF_PACKET,
#[cfg(any(target_os = "android", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(any(target_os = "android", target_os = "linux"))))]
libc::AF_VSOCK,
libc::AF_UNSPEC, // = 0.
);
/// Unix only API.
impl Type {
/// Set `SOCK_NONBLOCK` on the `Type`.
#[cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "illumos",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd"
)
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "illumos",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd"
)
)))
)]
pub const fn nonblocking(self) -> Type {
Type(self.0 | libc::SOCK_NONBLOCK)
}
/// Set `SOCK_CLOEXEC` on the `Type`.
#[cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "illumos",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_os = "redox",
target_os = "solaris",
)
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "illumos",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_os = "redox",
target_os = "solaris",
)
)))
)]
pub const fn cloexec(self) -> Type {
self._cloexec()
}
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "illumos",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_os = "redox",
target_os = "solaris",
))]
pub(crate) const fn _cloexec(self) -> Type {
Type(self.0 | libc::SOCK_CLOEXEC)
}
}
impl_debug!(
Type,
libc::SOCK_STREAM,
libc::SOCK_DGRAM,
#[cfg(all(feature = "all", target_os = "linux"))]
libc::SOCK_DCCP,
#[cfg(not(any(target_os = "redox", target_os = "espidf")))]
libc::SOCK_RAW,
#[cfg(not(any(target_os = "redox", target_os = "haiku", target_os = "espidf")))]
libc::SOCK_RDM,
#[cfg(not(target_os = "espidf"))]
libc::SOCK_SEQPACKET,
/* TODO: add these optional bit OR-ed flags:
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd"
))]
libc::SOCK_NONBLOCK,
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd"
))]
libc::SOCK_CLOEXEC,
*/
);
impl_debug!(
Protocol,
libc::IPPROTO_ICMP,
libc::IPPROTO_ICMPV6,
libc::IPPROTO_TCP,
libc::IPPROTO_UDP,
#[cfg(target_os = "linux")]
libc::IPPROTO_MPTCP,
#[cfg(all(feature = "all", target_os = "linux"))]
libc::IPPROTO_DCCP,
#[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux")))]
libc::IPPROTO_SCTP,
#[cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
)
))]
libc::IPPROTO_UDPLITE,
#[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "openbsd")))]
libc::IPPROTO_DIVERT,
);
/// Unix-only API.
#[cfg(not(target_os = "redox"))]
impl RecvFlags {
/// Check if the message terminates a record.
///
/// Not all socket types support the notion of records. For socket types
/// that do support it (such as [`SEQPACKET`]), a record is terminated by
/// sending a message with the end-of-record flag set.
///
/// On Unix this corresponds to the `MSG_EOR` flag.
///
/// [`SEQPACKET`]: Type::SEQPACKET
#[cfg(not(target_os = "espidf"))]
pub const fn is_end_of_record(self) -> bool {
self.0 & libc::MSG_EOR != 0
}
/// Check if the message contains out-of-band data.
///
/// This is useful for protocols where you receive out-of-band data
/// mixed in with the normal data stream.
///
/// On Unix this corresponds to the `MSG_OOB` flag.
pub const fn is_out_of_band(self) -> bool {
self.0 & libc::MSG_OOB != 0
}
}
#[cfg(not(target_os = "redox"))]
impl std::fmt::Debug for RecvFlags {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut s = f.debug_struct("RecvFlags");
#[cfg(not(target_os = "espidf"))]
s.field("is_end_of_record", &self.is_end_of_record());
s.field("is_out_of_band", &self.is_out_of_band());
#[cfg(not(target_os = "espidf"))]
s.field("is_truncated", &self.is_truncated());
s.finish()
}
}
#[repr(transparent)]
pub struct MaybeUninitSlice<'a> {
vec: libc::iovec,
_lifetime: PhantomData<&'a mut [MaybeUninit<u8>]>,
}
unsafe impl<'a> Send for MaybeUninitSlice<'a> {}
unsafe impl<'a> Sync for MaybeUninitSlice<'a> {}
impl<'a> MaybeUninitSlice<'a> {
pub(crate) fn new(buf: &'a mut [MaybeUninit<u8>]) -> MaybeUninitSlice<'a> {
MaybeUninitSlice {
vec: libc::iovec {
iov_base: buf.as_mut_ptr().cast(),
iov_len: buf.len(),
},
_lifetime: PhantomData,
}
}
pub(crate) fn as_slice(&self) -> &[MaybeUninit<u8>] {
unsafe { slice::from_raw_parts(self.vec.iov_base.cast(), self.vec.iov_len) }
}
pub(crate) fn as_mut_slice(&mut self) -> &mut [MaybeUninit<u8>] {
unsafe { slice::from_raw_parts_mut(self.vec.iov_base.cast(), self.vec.iov_len) }
}
}
/// Returns the offset of the `sun_path` member of the passed unix socket address.
pub(crate) fn offset_of_path(storage: &libc::sockaddr_un) -> usize {
let base = storage as *const _ as usize;
let path = ptr::addr_of!(storage.sun_path) as usize;
path - base
}
#[allow(unsafe_op_in_unsafe_fn)]
pub(crate) fn unix_sockaddr(path: &Path) -> io::Result<SockAddr> {
// SAFETY: a `sockaddr_storage` of all zeros is valid.
let mut storage = unsafe { mem::zeroed::<sockaddr_storage>() };
let len = {
let storage = unsafe { &mut *ptr::addr_of_mut!(storage).cast::<libc::sockaddr_un>() };
let bytes = path.as_os_str().as_bytes();
let too_long = match bytes.first() {
None => false,
// linux abstract namespaces aren't null-terminated
Some(&0) => bytes.len() > storage.sun_path.len(),
Some(_) => bytes.len() >= storage.sun_path.len(),
};
if too_long {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"path must be shorter than SUN_LEN",
));
}
storage.sun_family = libc::AF_UNIX as sa_family_t;
// SAFETY: `bytes` and `addr.sun_path` are not overlapping and
// both point to valid memory.
// `storage` was initialized to zero above, so the path is
// already NULL terminated.
unsafe {
ptr::copy_nonoverlapping(
bytes.as_ptr(),
storage.sun_path.as_mut_ptr().cast(),
bytes.len(),
);
}
let sun_path_offset = offset_of_path(storage);
sun_path_offset
+ bytes.len()
+ match bytes.first() {
Some(&0) | None => 0,
Some(_) => 1,
}
};
Ok(unsafe { SockAddr::new(storage, len as socklen_t) })
}
// Used in `MsgHdr`.
#[cfg(not(target_os = "redox"))]
pub(crate) use libc::msghdr;
#[cfg(not(target_os = "redox"))]
pub(crate) fn set_msghdr_name(msg: &mut msghdr, name: &SockAddr) {
msg.msg_name = name.as_ptr() as *mut _;
msg.msg_namelen = name.len();
}
#[cfg(not(target_os = "redox"))]
#[allow(clippy::unnecessary_cast)] // IovLen type can be `usize`.
pub(crate) fn set_msghdr_iov(msg: &mut msghdr, ptr: *mut libc::iovec, len: usize) {
msg.msg_iov = ptr;
msg.msg_iovlen = min(len, IovLen::MAX as usize) as IovLen;
}
#[cfg(not(target_os = "redox"))]
pub(crate) fn set_msghdr_control(msg: &mut msghdr, ptr: *mut libc::c_void, len: usize) {
msg.msg_control = ptr;
msg.msg_controllen = len as _;
}
#[cfg(not(target_os = "redox"))]
pub(crate) fn set_msghdr_flags(msg: &mut msghdr, flags: libc::c_int) {
msg.msg_flags = flags;
}
#[cfg(not(target_os = "redox"))]
pub(crate) fn msghdr_flags(msg: &msghdr) -> RecvFlags {
RecvFlags(msg.msg_flags)
}
/// Unix only API.
impl SockAddr {
/// Constructs a `SockAddr` with the family `AF_VSOCK` and the provided CID/port.
///
/// # Errors
///
/// This function can never fail. In a future version of this library it will be made
/// infallible.
#[allow(unsafe_op_in_unsafe_fn)]
#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
#[cfg_attr(
docsrs,
doc(cfg(all(feature = "all", any(target_os = "android", target_os = "linux"))))
)]
pub fn vsock(cid: u32, port: u32) -> SockAddr {
// SAFETY: a `sockaddr_storage` of all zeros is valid.
let mut storage = unsafe { mem::zeroed::<sockaddr_storage>() };
{
let storage: &mut libc::sockaddr_vm =
unsafe { &mut *((&mut storage as *mut sockaddr_storage).cast()) };
storage.svm_family = libc::AF_VSOCK as sa_family_t;
storage.svm_cid = cid;
storage.svm_port = port;
}
unsafe { SockAddr::new(storage, mem::size_of::<libc::sockaddr_vm>() as socklen_t) }
}
/// Returns this address VSOCK CID/port if it is in the `AF_VSOCK` family,
/// otherwise return `None`.
#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
#[cfg_attr(
docsrs,
doc(cfg(all(feature = "all", any(target_os = "android", target_os = "linux"))))
)]
pub fn as_vsock_address(&self) -> Option<(u32, u32)> {
if self.family() == libc::AF_VSOCK as sa_family_t {
// Safety: if the ss_family field is AF_VSOCK then storage must be a sockaddr_vm.
let addr = unsafe { &*(self.as_ptr() as *const libc::sockaddr_vm) };
Some((addr.svm_cid, addr.svm_port))
} else {
None
}
}
/// Returns true if this address is an unnamed address from the `AF_UNIX` family (for local
/// interprocess communication), false otherwise.
pub fn is_unnamed(&self) -> bool {
self.as_sockaddr_un()
.map(|storage| {
self.len() == offset_of_path(storage) as _
// On some non-linux platforms a zeroed path is returned for unnamed.
// Abstract addresses only exist on Linux.
// NOTE: although Fuchsia does define `AF_UNIX` it's not actually implemented.
// See https://github.com/rust-lang/socket2/pull/403#discussion_r1123557978
|| (cfg!(not(any(target_os = "linux", target_os = "android")))
&& storage.sun_path[0] == 0)
})
.unwrap_or_default()
}
/// Returns the underlying `sockaddr_un` object if this addres is from the `AF_UNIX` family,
/// otherwise returns `None`.
pub(crate) fn as_sockaddr_un(&self) -> Option<&libc::sockaddr_un> {
self.is_unix().then(|| {
// SAFETY: if unix socket, i.e. the `ss_family` field is `AF_UNIX` then storage must be
// a `sockaddr_un`.
unsafe { &*self.as_ptr().cast::<libc::sockaddr_un>() }
})
}
/// Get the length of the path bytes of the address, not including the terminating or initial
/// (for abstract names) null byte.
///
/// Should not be called on unnamed addresses.
fn path_len(&self, storage: &libc::sockaddr_un) -> usize {
debug_assert!(!self.is_unnamed());
self.len() as usize - offset_of_path(storage) - 1
}
/// Get a u8 slice for the bytes of the pathname or abstract name.
///
/// Should not be called on unnamed addresses.
fn path_bytes(&self, storage: &libc::sockaddr_un, abstract_name: bool) -> &[u8] {
debug_assert!(!self.is_unnamed());
// SAFETY: the pointed objects of type `i8` have the same memory layout as `u8`. The path is
// the last field in the storage and so its length is equal to
// TOTAL_LENGTH - OFFSET_OF_PATH -1
// Where the 1 is either a terminating null if we have a pathname address, or the initial
// null byte, if it's an abstract name address. In the latter case, the path bytes start
// after the initial null byte, hence the `offset`.
// There is no safe way to convert a `&[i8]` to `&[u8]`
unsafe {
slice::from_raw_parts(
(storage.sun_path.as_ptr() as *const u8).offset(abstract_name as isize),
self.path_len(storage),
)
}
}
/// Returns this address as Unix `SocketAddr` if it is an `AF_UNIX` pathname
/// address, otherwise returns `None`.
pub fn as_unix(&self) -> Option<std::os::unix::net::SocketAddr> {
let path = self.as_pathname()?;
// SAFETY: we can represent this as a valid pathname, then so can the
// standard library.
Some(std::os::unix::net::SocketAddr::from_pathname(path).unwrap())
}
/// Returns this address as a `Path` reference if it is an `AF_UNIX`
/// pathname address, otherwise returns `None`.
pub fn as_pathname(&self) -> Option<&Path> {
self.as_sockaddr_un().and_then(|storage| {
(self.len() > offset_of_path(storage) as _ && storage.sun_path[0] != 0).then(|| {
let path_slice = self.path_bytes(storage, false);
Path::new::<OsStr>(OsStrExt::from_bytes(path_slice))
})
})
}
/// Returns this address as a slice of bytes representing an abstract address if it is an
/// `AF_UNIX` abstract address, otherwise returns `None`.
///
/// Abstract addresses are a Linux extension, so this method returns `None` on all non-Linux
/// platforms.
pub fn as_abstract_namespace(&self) -> Option<&[u8]> {
// NOTE: although Fuchsia does define `AF_UNIX` it's not actually implemented.
// See https://github.com/rust-lang/socket2/pull/403#discussion_r1123557978
#[cfg(any(target_os = "linux", target_os = "android"))]
{
self.as_sockaddr_un().and_then(|storage| {
(self.len() > offset_of_path(storage) as _ && storage.sun_path[0] == 0)
.then(|| self.path_bytes(storage, true))
})
}
#[cfg(not(any(target_os = "linux", target_os = "android")))]
None
}
}
pub(crate) type Socket = c_int;
pub(crate) unsafe fn socket_from_raw(socket: Socket) -> crate::socket::Inner {
crate::socket::Inner::from_raw_fd(socket)
}
pub(crate) fn socket_as_raw(socket: &crate::socket::Inner) -> Socket {
socket.as_raw_fd()
}
pub(crate) fn socket_into_raw(socket: crate::socket::Inner) -> Socket {
socket.into_raw_fd()
}
pub(crate) fn socket(family: c_int, ty: c_int, protocol: c_int) -> io::Result<Socket> {
syscall!(socket(family, ty, protocol))
}
#[cfg(all(feature = "all", unix))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", unix))))]
pub(crate) fn socketpair(family: c_int, ty: c_int, protocol: c_int) -> io::Result<[Socket; 2]> {
let mut fds = [0, 0];
syscall!(socketpair(family, ty, protocol, fds.as_mut_ptr())).map(|_| fds)
}
pub(crate) fn bind(fd: Socket, addr: &SockAddr) -> io::Result<()> {
syscall!(bind(fd, addr.as_ptr(), addr.len() as _)).map(|_| ())
}
pub(crate) fn connect(fd: Socket, addr: &SockAddr) -> io::Result<()> {
syscall!(connect(fd, addr.as_ptr(), addr.len())).map(|_| ())
}
pub(crate) fn poll_connect(socket: &crate::Socket, timeout: Duration) -> io::Result<()> {
let start = Instant::now();
let mut pollfd = libc::pollfd {
fd: socket.as_raw(),
events: libc::POLLIN | libc::POLLOUT,
revents: 0,
};
loop {
let elapsed = start.elapsed();
if elapsed >= timeout {
return Err(io::ErrorKind::TimedOut.into());
}
let timeout = (timeout - elapsed).as_millis();
let timeout = timeout.clamp(1, c_int::MAX as u128) as c_int;
match syscall!(poll(&mut pollfd, 1, timeout)) {
Ok(0) => return Err(io::ErrorKind::TimedOut.into()),
Ok(_) => {
// Error or hang up indicates an error (or failure to connect).
if (pollfd.revents & libc::POLLHUP) != 0 || (pollfd.revents & libc::POLLERR) != 0 {
match socket.take_error() {
Ok(Some(err)) | Err(err) => return Err(err),
Ok(None) => {
return Err(io::Error::new(
io::ErrorKind::Other,
"no error set after POLLHUP",
))
}
}
}
return Ok(());
}
// Got interrupted, try again.
Err(ref err) if err.kind() == io::ErrorKind::Interrupted => continue,
Err(err) => return Err(err),
}
}
}
pub(crate) fn listen(fd: Socket, backlog: c_int) -> io::Result<()> {
syscall!(listen(fd, backlog)).map(|_| ())
}
pub(crate) fn accept(fd: Socket) -> io::Result<(Socket, SockAddr)> {
// Safety: `accept` initialises the `SockAddr` for us.
unsafe { SockAddr::try_init(|storage, len| syscall!(accept(fd, storage.cast(), len))) }
}
pub(crate) fn getsockname(fd: Socket) -> io::Result<SockAddr> {
// Safety: `accept` initialises the `SockAddr` for us.
unsafe { SockAddr::try_init(|storage, len| syscall!(getsockname(fd, storage.cast(), len))) }
.map(|(_, addr)| addr)
}
pub(crate) fn getpeername(fd: Socket) -> io::Result<SockAddr> {
// Safety: `accept` initialises the `SockAddr` for us.
unsafe { SockAddr::try_init(|storage, len| syscall!(getpeername(fd, storage.cast(), len))) }
.map(|(_, addr)| addr)
}
pub(crate) fn try_clone(fd: Socket) -> io::Result<Socket> {
syscall!(fcntl(fd, libc::F_DUPFD_CLOEXEC, 0))
}
#[cfg(all(feature = "all", unix, not(target_os = "vita")))]
pub(crate) fn nonblocking(fd: Socket) -> io::Result<bool> {
let file_status_flags = fcntl_get(fd, libc::F_GETFL)?;
Ok((file_status_flags & libc::O_NONBLOCK) != 0)
}
#[cfg(all(feature = "all", target_os = "vita"))]
pub(crate) fn nonblocking(fd: Socket) -> io::Result<bool> {
unsafe {
getsockopt::<Bool>(fd, libc::SOL_SOCKET, libc::SO_NONBLOCK).map(|non_block| non_block != 0)
}
}
#[cfg(not(target_os = "vita"))]
pub(crate) fn set_nonblocking(fd: Socket, nonblocking: bool) -> io::Result<()> {
if nonblocking {
fcntl_add(fd, libc::F_GETFL, libc::F_SETFL, libc::O_NONBLOCK)
} else {
fcntl_remove(fd, libc::F_GETFL, libc::F_SETFL, libc::O_NONBLOCK)
}
}
#[cfg(target_os = "vita")]
pub(crate) fn set_nonblocking(fd: Socket, nonblocking: bool) -> io::Result<()> {
unsafe {
setsockopt(
fd,
libc::SOL_SOCKET,
libc::SO_NONBLOCK,
nonblocking as libc::c_int,
)
}
}
pub(crate) fn shutdown(fd: Socket, how: Shutdown) -> io::Result<()> {
let how = match how {
Shutdown::Write => libc::SHUT_WR,
Shutdown::Read => libc::SHUT_RD,
Shutdown::Both => libc::SHUT_RDWR,
};
syscall!(shutdown(fd, how)).map(|_| ())
}
pub(crate) fn recv(fd: Socket, buf: &mut [MaybeUninit<u8>], flags: c_int) -> io::Result<usize> {
syscall!(recv(
fd,
buf.as_mut_ptr().cast(),
min(buf.len(), MAX_BUF_LEN),
flags,
))
.map(|n| n as usize)
}
pub(crate) fn recv_from(
fd: Socket,
buf: &mut [MaybeUninit<u8>],
flags: c_int,
) -> io::Result<(usize, SockAddr)> {
// Safety: `recvfrom` initialises the `SockAddr` for us.
unsafe {
SockAddr::try_init(|addr, addrlen| {
syscall!(recvfrom(
fd,
buf.as_mut_ptr().cast(),
min(buf.len(), MAX_BUF_LEN),
flags,
addr.cast(),
addrlen
))
.map(|n| n as usize)
})
}
}
pub(crate) fn peek_sender(fd: Socket) -> io::Result<SockAddr> {
// Unix-like platforms simply truncate the returned data, so this implementation is trivial.
// However, for Windows this requires suppressing the `WSAEMSGSIZE` error,
// so that requires a different approach.
// NOTE: macOS does not populate `sockaddr` if you pass a zero-sized buffer.
let (_, sender) = recv_from(fd, &mut [MaybeUninit::uninit(); 8], MSG_PEEK)?;
Ok(sender)
}
#[cfg(not(target_os = "redox"))]
pub(crate) fn recv_vectored(
fd: Socket,
bufs: &mut [crate::MaybeUninitSlice<'_>],
flags: c_int,
) -> io::Result<(usize, RecvFlags)> {
let mut msg = MsgHdrMut::new().with_buffers(bufs);
let n = recvmsg(fd, &mut msg, flags)?;
Ok((n, msg.flags()))
}
#[cfg(not(target_os = "redox"))]
pub(crate) fn recv_from_vectored(
fd: Socket,
bufs: &mut [crate::MaybeUninitSlice<'_>],
flags: c_int,
) -> io::Result<(usize, RecvFlags, SockAddr)> {
let mut msg = MsgHdrMut::new().with_buffers(bufs);
// SAFETY: `recvmsg` initialises the address storage and we set the length
// manually.
let (n, addr) = unsafe {
SockAddr::try_init(|storage, len| {
msg.inner.msg_name = storage.cast();
msg.inner.msg_namelen = *len;
let n = recvmsg(fd, &mut msg, flags)?;
// Set the correct address length.
*len = msg.inner.msg_namelen;
Ok(n)
})?
};
Ok((n, msg.flags(), addr))
}
#[cfg(not(target_os = "redox"))]
pub(crate) fn recvmsg(
fd: Socket,
msg: &mut MsgHdrMut<'_, '_, '_>,
flags: c_int,
) -> io::Result<usize> {
syscall!(recvmsg(fd, &mut msg.inner, flags)).map(|n| n as usize)
}
pub(crate) fn send(fd: Socket, buf: &[u8], flags: c_int) -> io::Result<usize> {
syscall!(send(
fd,
buf.as_ptr().cast(),
min(buf.len(), MAX_BUF_LEN),
flags,
))
.map(|n| n as usize)
}
#[cfg(not(target_os = "redox"))]
pub(crate) fn send_vectored(fd: Socket, bufs: &[IoSlice<'_>], flags: c_int) -> io::Result<usize> {
let msg = MsgHdr::new().with_buffers(bufs);
sendmsg(fd, &msg, flags)
}
pub(crate) fn send_to(fd: Socket, buf: &[u8], addr: &SockAddr, flags: c_int) -> io::Result<usize> {
syscall!(sendto(
fd,
buf.as_ptr().cast(),
min(buf.len(), MAX_BUF_LEN),
flags,
addr.as_ptr(),
addr.len(),
))
.map(|n| n as usize)
}
#[cfg(not(target_os = "redox"))]
pub(crate) fn send_to_vectored(
fd: Socket,
bufs: &[IoSlice<'_>],
addr: &SockAddr,
flags: c_int,
) -> io::Result<usize> {
let msg = MsgHdr::new().with_addr(addr).with_buffers(bufs);
sendmsg(fd, &msg, flags)
}
#[cfg(not(target_os = "redox"))]
pub(crate) fn sendmsg(fd: Socket, msg: &MsgHdr<'_, '_, '_>, flags: c_int) -> io::Result<usize> {
syscall!(sendmsg(fd, &msg.inner, flags)).map(|n| n as usize)
}
/// Wrapper around `getsockopt` to deal with platform specific timeouts.
pub(crate) fn timeout_opt(fd: Socket, opt: c_int, val: c_int) -> io::Result<Option<Duration>> {
unsafe { getsockopt(fd, opt, val).map(from_timeval) }
}
const fn from_timeval(duration: libc::timeval) -> Option<Duration> {
if duration.tv_sec == 0 && duration.tv_usec == 0 {
None
} else {
let sec = duration.tv_sec as u64;
let nsec = (duration.tv_usec as u32) * 1000;
Some(Duration::new(sec, nsec))
}
}
/// Wrapper around `setsockopt` to deal with platform specific timeouts.
pub(crate) fn set_timeout_opt(
fd: Socket,
opt: c_int,
val: c_int,
duration: Option<Duration>,
) -> io::Result<()> {
let duration = into_timeval(duration);
unsafe { setsockopt(fd, opt, val, duration) }
}
fn into_timeval(duration: Option<Duration>) -> libc::timeval {
match duration {
// https://github.com/rust-lang/libc/issues/1848
#[cfg_attr(target_env = "musl", allow(deprecated))]
Some(duration) => libc::timeval {
tv_sec: min(duration.as_secs(), libc::time_t::MAX as u64) as libc::time_t,
tv_usec: duration.subsec_micros() as libc::suseconds_t,
},
None => libc::timeval {
tv_sec: 0,
tv_usec: 0,
},
}
}
#[cfg(all(
feature = "all",
not(any(target_os = "haiku", target_os = "openbsd", target_os = "vita"))
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
not(any(target_os = "haiku", target_os = "openbsd", target_os = "vita"))
)))
)]
pub(crate) fn keepalive_time(fd: Socket) -> io::Result<Duration> {
unsafe {
getsockopt::<c_int>(fd, IPPROTO_TCP, KEEPALIVE_TIME)
.map(|secs| Duration::from_secs(secs as u64))
}
}
#[allow(unused_variables)]
pub(crate) fn set_tcp_keepalive(fd: Socket, keepalive: &TcpKeepalive) -> io::Result<()> {
#[cfg(not(any(
target_os = "haiku",
target_os = "openbsd",
target_os = "nto",
target_os = "vita"
)))]
if let Some(time) = keepalive.time {
let secs = into_secs(time);
unsafe { setsockopt(fd, libc::IPPROTO_TCP, KEEPALIVE_TIME, secs)? }
}
#[cfg(any(
target_os = "aix",
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "illumos",
target_os = "ios",
target_os = "linux",
target_os = "macos",
target_os = "netbsd",
target_os = "tvos",
target_os = "watchos",
))]
{
if let Some(interval) = keepalive.interval {
let secs = into_secs(interval);
unsafe { setsockopt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPINTVL, secs)? }
}
if let Some(retries) = keepalive.retries {
unsafe { setsockopt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPCNT, retries as c_int)? }
}
}
#[cfg(target_os = "nto")]
if let Some(time) = keepalive.time {
let secs = into_timeval(Some(time));
unsafe { setsockopt(fd, libc::IPPROTO_TCP, KEEPALIVE_TIME, secs)? }
}
Ok(())
}
#[cfg(not(any(
target_os = "haiku",
target_os = "openbsd",
target_os = "nto",
target_os = "vita"
)))]
fn into_secs(duration: Duration) -> c_int {
min(duration.as_secs(), c_int::MAX as u64) as c_int
}
/// Get the flags using `cmd`.
#[cfg(not(target_os = "vita"))]
fn fcntl_get(fd: Socket, cmd: c_int) -> io::Result<c_int> {
syscall!(fcntl(fd, cmd))
}
/// Add `flag` to the current set flags of `F_GETFD`.
#[cfg(not(target_os = "vita"))]
fn fcntl_add(fd: Socket, get_cmd: c_int, set_cmd: c_int, flag: c_int) -> io::Result<()> {
let previous = fcntl_get(fd, get_cmd)?;
let new = previous | flag;
if new != previous {
syscall!(fcntl(fd, set_cmd, new)).map(|_| ())
} else {
// Flag was already set.
Ok(())
}
}
/// Remove `flag` to the current set flags of `F_GETFD`.
#[cfg(not(target_os = "vita"))]
fn fcntl_remove(fd: Socket, get_cmd: c_int, set_cmd: c_int, flag: c_int) -> io::Result<()> {
let previous = fcntl_get(fd, get_cmd)?;
let new = previous & !flag;
if new != previous {
syscall!(fcntl(fd, set_cmd, new)).map(|_| ())
} else {
// Flag was already set.
Ok(())
}
}
/// Caller must ensure `T` is the correct type for `opt` and `val`.
pub(crate) unsafe fn getsockopt<T>(fd: Socket, opt: c_int, val: c_int) -> io::Result<T> {
let mut payload: MaybeUninit<T> = MaybeUninit::uninit();
let mut len = size_of::<T>() as libc::socklen_t;
syscall!(getsockopt(
fd,
opt,
val,
payload.as_mut_ptr().cast(),
&mut len,
))
.map(|_| {
debug_assert_eq!(len as usize, size_of::<T>());
// Safety: `getsockopt` initialised `payload` for us.
payload.assume_init()
})
}
/// Caller must ensure `T` is the correct type for `opt` and `val`.
pub(crate) unsafe fn setsockopt<T>(
fd: Socket,
opt: c_int,
val: c_int,
payload: T,
) -> io::Result<()> {
let payload = ptr::addr_of!(payload).cast();
syscall!(setsockopt(
fd,
opt,
val,
payload,
mem::size_of::<T>() as libc::socklen_t,
))
.map(|_| ())
}
pub(crate) const fn to_in_addr(addr: &Ipv4Addr) -> in_addr {
// `s_addr` is stored as BE on all machines, and the array is in BE order.
// So the native endian conversion method is used so that it's never
// swapped.
in_addr {
s_addr: u32::from_ne_bytes(addr.octets()),
}
}
pub(crate) fn from_in_addr(in_addr: in_addr) -> Ipv4Addr {
Ipv4Addr::from(in_addr.s_addr.to_ne_bytes())
}
pub(crate) const fn to_in6_addr(addr: &Ipv6Addr) -> in6_addr {
in6_addr {
s6_addr: addr.octets(),
}
}
pub(crate) fn from_in6_addr(addr: in6_addr) -> Ipv6Addr {
Ipv6Addr::from(addr.s6_addr)
}
#[cfg(not(any(
target_os = "aix",
target_os = "haiku",
target_os = "illumos",
target_os = "netbsd",
target_os = "openbsd",
target_os = "redox",
target_os = "solaris",
target_os = "nto",
target_os = "espidf",
target_os = "vita",
)))]
pub(crate) const fn to_mreqn(
multiaddr: &Ipv4Addr,
interface: &crate::socket::InterfaceIndexOrAddress,
) -> libc::ip_mreqn {
match interface {
crate::socket::InterfaceIndexOrAddress::Index(interface) => libc::ip_mreqn {
imr_multiaddr: to_in_addr(multiaddr),
imr_address: to_in_addr(&Ipv4Addr::UNSPECIFIED),
imr_ifindex: *interface as _,
},
crate::socket::InterfaceIndexOrAddress::Address(interface) => libc::ip_mreqn {
imr_multiaddr: to_in_addr(multiaddr),
imr_address: to_in_addr(interface),
imr_ifindex: 0,
},
}
}
/// Unix only API.
impl crate::Socket {
/// Accept a new incoming connection from this listener.
///
/// This function directly corresponds to the `accept4(2)` function.
///
/// This function will block the calling thread until a new connection is
/// established. When established, the corresponding `Socket` and the remote
/// peer's address will be returned.
#[doc = man_links!(unix: accept4(2))]
#[cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "illumos",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
)
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "illumos",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
)
)))
)]
pub fn accept4(&self, flags: c_int) -> io::Result<(crate::Socket, SockAddr)> {
self._accept4(flags)
}
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "illumos",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
))]
pub(crate) fn _accept4(&self, flags: c_int) -> io::Result<(crate::Socket, SockAddr)> {
// Safety: `accept4` initialises the `SockAddr` for us.
unsafe {
SockAddr::try_init(|storage, len| {
syscall!(accept4(self.as_raw(), storage.cast(), len, flags))
.map(crate::Socket::from_raw)
})
}
}
/// Sets `CLOEXEC` on the socket.
///
/// # Notes
///
/// On supported platforms you can use [`Type::cloexec`].
#[cfg_attr(
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos"
),
allow(rustdoc::broken_intra_doc_links)
)]
#[cfg(all(feature = "all", not(target_os = "vita")))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", unix))))]
pub fn set_cloexec(&self, close_on_exec: bool) -> io::Result<()> {
self._set_cloexec(close_on_exec)
}
#[cfg(not(target_os = "vita"))]
pub(crate) fn _set_cloexec(&self, close_on_exec: bool) -> io::Result<()> {
if close_on_exec {
fcntl_add(
self.as_raw(),
libc::F_GETFD,
libc::F_SETFD,
libc::FD_CLOEXEC,
)
} else {
fcntl_remove(
self.as_raw(),
libc::F_GETFD,
libc::F_SETFD,
libc::FD_CLOEXEC,
)
}
}
/// Sets `SO_NOSIGPIPE` on the socket.
#[cfg(all(
feature = "all",
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
)))
)]
pub fn set_nosigpipe(&self, nosigpipe: bool) -> io::Result<()> {
self._set_nosigpipe(nosigpipe)
}
#[cfg(any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
))]
pub(crate) fn _set_nosigpipe(&self, nosigpipe: bool) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
libc::SOL_SOCKET,
libc::SO_NOSIGPIPE,
nosigpipe as c_int,
)
}
}
/// Gets the value of the `TCP_MAXSEG` option on this socket.
///
/// For more information about this option, see [`set_mss`].
///
/// [`set_mss`]: crate::Socket::set_mss
#[cfg(all(feature = "all", not(target_os = "redox")))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", unix, not(target_os = "redox")))))]
pub fn mss(&self) -> io::Result<u32> {
unsafe {
getsockopt::<c_int>(self.as_raw(), libc::IPPROTO_TCP, libc::TCP_MAXSEG)
.map(|mss| mss as u32)
}
}
/// Sets the value of the `TCP_MAXSEG` option on this socket.
///
/// The `TCP_MAXSEG` option denotes the TCP Maximum Segment Size and is only
/// available on TCP sockets.
#[cfg(all(feature = "all", not(target_os = "redox")))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", unix, not(target_os = "redox")))))]
pub fn set_mss(&self, mss: u32) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
libc::IPPROTO_TCP,
libc::TCP_MAXSEG,
mss as c_int,
)
}
}
/// Returns `true` if `listen(2)` was called on this socket by checking the
/// `SO_ACCEPTCONN` option on this socket.
#[cfg(all(
feature = "all",
any(
target_os = "aix",
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
)
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(
target_os = "aix",
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
)
)))
)]
pub fn is_listener(&self) -> io::Result<bool> {
unsafe {
getsockopt::<c_int>(self.as_raw(), libc::SOL_SOCKET, libc::SO_ACCEPTCONN)
.map(|v| v != 0)
}
}
/// Returns the [`Domain`] of this socket by checking the `SO_DOMAIN` option
/// on this socket.
#[cfg(all(
feature = "all",
any(
target_os = "android",
// TODO: add FreeBSD.
// target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
)
))]
#[cfg_attr(docsrs, doc(cfg(all(
feature = "all",
any(
target_os = "android",
// TODO: add FreeBSD.
// target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
)
))))]
pub fn domain(&self) -> io::Result<Domain> {
unsafe { getsockopt::<c_int>(self.as_raw(), libc::SOL_SOCKET, libc::SO_DOMAIN).map(Domain) }
}
/// Returns the [`Protocol`] of this socket by checking the `SO_PROTOCOL`
/// option on this socket.
#[cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
)
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
)
)))
)]
pub fn protocol(&self) -> io::Result<Option<Protocol>> {
unsafe {
getsockopt::<c_int>(self.as_raw(), libc::SOL_SOCKET, libc::SO_PROTOCOL).map(|v| match v
{
0 => None,
p => Some(Protocol(p)),
})
}
}
/// Gets the value for the `SO_MARK` option on this socket.
///
/// This value gets the socket mark field for each packet sent through
/// this socket.
///
/// On Linux this function requires the `CAP_NET_ADMIN` capability.
#[cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
)))
)]
pub fn mark(&self) -> io::Result<u32> {
unsafe {
getsockopt::<c_int>(self.as_raw(), libc::SOL_SOCKET, libc::SO_MARK)
.map(|mark| mark as u32)
}
}
/// Sets the value for the `SO_MARK` option on this socket.
///
/// This value sets the socket mark field for each packet sent through
/// this socket. Changing the mark can be used for mark-based routing
/// without netfilter or for packet filtering.
///
/// On Linux this function requires the `CAP_NET_ADMIN` capability.
#[cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
)))
)]
pub fn set_mark(&self, mark: u32) -> io::Result<()> {
unsafe {
setsockopt::<c_int>(
self.as_raw(),
libc::SOL_SOCKET,
libc::SO_MARK,
mark as c_int,
)
}
}
/// Get the value of the `TCP_CORK` option on this socket.
///
/// For more information about this option, see [`set_cork`].
///
/// [`set_cork`]: crate::Socket::set_cork
#[cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
)))
)]
pub fn cork(&self) -> io::Result<bool> {
unsafe {
getsockopt::<Bool>(self.as_raw(), libc::IPPROTO_TCP, libc::TCP_CORK)
.map(|cork| cork != 0)
}
}
/// Set the value of the `TCP_CORK` option on this socket.
///
/// If set, don't send out partial frames. All queued partial frames are
/// sent when the option is cleared again. There is a 200 millisecond ceiling on
/// the time for which output is corked by `TCP_CORK`. If this ceiling is reached,
/// then queued data is automatically transmitted.
#[cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
)))
)]
pub fn set_cork(&self, cork: bool) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
libc::IPPROTO_TCP,
libc::TCP_CORK,
cork as c_int,
)
}
}
/// Get the value of the `TCP_QUICKACK` option on this socket.
///
/// For more information about this option, see [`set_quickack`].
///
/// [`set_quickack`]: crate::Socket::set_quickack
#[cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
)))
)]
pub fn quickack(&self) -> io::Result<bool> {
unsafe {
getsockopt::<Bool>(self.as_raw(), libc::IPPROTO_TCP, libc::TCP_QUICKACK)
.map(|quickack| quickack != 0)
}
}
/// Set the value of the `TCP_QUICKACK` option on this socket.
///
/// If set, acks are sent immediately, rather than delayed if needed in accordance to normal
/// TCP operation. This flag is not permanent, it only enables a switch to or from quickack mode.
/// Subsequent operation of the TCP protocol will once again enter/leave quickack mode depending on
/// internal protocol processing and factors such as delayed ack timeouts occurring and data transfer.
#[cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
)))
)]
pub fn set_quickack(&self, quickack: bool) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
libc::IPPROTO_TCP,
libc::TCP_QUICKACK,
quickack as c_int,
)
}
}
/// Get the value of the `TCP_THIN_LINEAR_TIMEOUTS` option on this socket.
///
/// For more information about this option, see [`set_thin_linear_timeouts`].
///
/// [`set_thin_linear_timeouts`]: crate::Socket::set_thin_linear_timeouts
#[cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
)))
)]
pub fn thin_linear_timeouts(&self) -> io::Result<bool> {
unsafe {
getsockopt::<Bool>(
self.as_raw(),
libc::IPPROTO_TCP,
libc::TCP_THIN_LINEAR_TIMEOUTS,
)
.map(|timeouts| timeouts != 0)
}
}
/// Set the value of the `TCP_THIN_LINEAR_TIMEOUTS` option on this socket.
///
/// If set, the kernel will dynamically detect a thin-stream connection if there are less than four packets in flight.
/// With less than four packets in flight the normal TCP fast retransmission will not be effective.
/// The kernel will modify the retransmission to avoid the very high latencies that thin stream suffer because of exponential backoff.
#[cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
)))
)]
pub fn set_thin_linear_timeouts(&self, timeouts: bool) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
libc::IPPROTO_TCP,
libc::TCP_THIN_LINEAR_TIMEOUTS,
timeouts as c_int,
)
}
}
/// Gets the value for the `SO_BINDTODEVICE` option on this socket.
///
/// This value gets the socket binded device's interface name.
#[cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
)))
)]
pub fn device(&self) -> io::Result<Option<Vec<u8>>> {
// TODO: replace with `MaybeUninit::uninit_array` once stable.
let mut buf: [MaybeUninit<u8>; libc::IFNAMSIZ] =
unsafe { MaybeUninit::uninit().assume_init() };
let mut len = buf.len() as libc::socklen_t;
syscall!(getsockopt(
self.as_raw(),
libc::SOL_SOCKET,
libc::SO_BINDTODEVICE,
buf.as_mut_ptr().cast(),
&mut len,
))?;
if len == 0 {
Ok(None)
} else {
let buf = &buf[..len as usize - 1];
// TODO: use `MaybeUninit::slice_assume_init_ref` once stable.
Ok(Some(unsafe { &*(buf as *const [_] as *const [u8]) }.into()))
}
}
/// Sets the value for the `SO_BINDTODEVICE` option on this socket.
///
/// If a socket is bound to an interface, only packets received from that
/// particular interface are processed by the socket. Note that this only
/// works for some socket types, particularly `AF_INET` sockets.
///
/// If `interface` is `None` or an empty string it removes the binding.
#[cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
)))
)]
pub fn bind_device(&self, interface: Option<&[u8]>) -> io::Result<()> {
let (value, len) = if let Some(interface) = interface {
(interface.as_ptr(), interface.len())
} else {
(ptr::null(), 0)
};
syscall!(setsockopt(
self.as_raw(),
libc::SOL_SOCKET,
libc::SO_BINDTODEVICE,
value.cast(),
len as libc::socklen_t,
))
.map(|_| ())
}
/// Sets the value for the `SO_SETFIB` option on this socket.
///
/// Bind socket to the specified forwarding table (VRF) on a FreeBSD.
#[cfg(all(feature = "all", target_os = "freebsd"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "freebsd"))))]
pub fn set_fib(&self, fib: u32) -> io::Result<()> {
syscall!(setsockopt(
self.as_raw(),
libc::SOL_SOCKET,
libc::SO_SETFIB,
(&fib as *const u32).cast(),
mem::size_of::<u32>() as libc::socklen_t,
))
.map(|_| ())
}
/// This method is deprecated, use [`crate::Socket::bind_device_by_index_v4`].
#[cfg(all(
feature = "all",
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
)))
)]
#[deprecated = "Use `Socket::bind_device_by_index_v4` instead"]
pub fn bind_device_by_index(&self, interface: Option<NonZeroU32>) -> io::Result<()> {
self.bind_device_by_index_v4(interface)
}
/// Sets the value for `IP_BOUND_IF` option on this socket.
///
/// If a socket is bound to an interface, only packets received from that
/// particular interface are processed by the socket.
///
/// If `interface` is `None`, the binding is removed. If the `interface`
/// index is not valid, an error is returned.
///
/// One can use [`libc::if_nametoindex`] to convert an interface alias to an
/// index.
#[cfg(all(
feature = "all",
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
)))
)]
pub fn bind_device_by_index_v4(&self, interface: Option<NonZeroU32>) -> io::Result<()> {
let index = interface.map_or(0, NonZeroU32::get);
unsafe { setsockopt(self.as_raw(), IPPROTO_IP, libc::IP_BOUND_IF, index) }
}
/// Sets the value for `IPV6_BOUND_IF` option on this socket.
///
/// If a socket is bound to an interface, only packets received from that
/// particular interface are processed by the socket.
///
/// If `interface` is `None`, the binding is removed. If the `interface`
/// index is not valid, an error is returned.
///
/// One can use [`libc::if_nametoindex`] to convert an interface alias to an
/// index.
#[cfg(all(
feature = "all",
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
)))
)]
pub fn bind_device_by_index_v6(&self, interface: Option<NonZeroU32>) -> io::Result<()> {
let index = interface.map_or(0, NonZeroU32::get);
unsafe { setsockopt(self.as_raw(), IPPROTO_IPV6, libc::IPV6_BOUND_IF, index) }
}
/// Gets the value for `IP_BOUND_IF` option on this socket, i.e. the index
/// for the interface to which the socket is bound.
///
/// Returns `None` if the socket is not bound to any interface, otherwise
/// returns an interface index.
#[cfg(all(
feature = "all",
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
)))
)]
pub fn device_index_v4(&self) -> io::Result<Option<NonZeroU32>> {
let index =
unsafe { getsockopt::<libc::c_uint>(self.as_raw(), IPPROTO_IP, libc::IP_BOUND_IF)? };
Ok(NonZeroU32::new(index))
}
/// This method is deprecated, use [`crate::Socket::device_index_v4`].
#[cfg(all(
feature = "all",
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
)))
)]
#[deprecated = "Use `Socket::device_index_v4` instead"]
pub fn device_index(&self) -> io::Result<Option<NonZeroU32>> {
self.device_index_v4()
}
/// Gets the value for `IPV6_BOUND_IF` option on this socket, i.e. the index
/// for the interface to which the socket is bound.
///
/// Returns `None` if the socket is not bound to any interface, otherwise
/// returns an interface index.
#[cfg(all(
feature = "all",
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
)))
)]
pub fn device_index_v6(&self) -> io::Result<Option<NonZeroU32>> {
let index = unsafe {
getsockopt::<libc::c_uint>(self.as_raw(), IPPROTO_IPV6, libc::IPV6_BOUND_IF)?
};
Ok(NonZeroU32::new(index))
}
/// Get the value of the `SO_INCOMING_CPU` option on this socket.
///
/// For more information about this option, see [`set_cpu_affinity`].
///
/// [`set_cpu_affinity`]: crate::Socket::set_cpu_affinity
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn cpu_affinity(&self) -> io::Result<usize> {
unsafe {
getsockopt::<c_int>(self.as_raw(), libc::SOL_SOCKET, libc::SO_INCOMING_CPU)
.map(|cpu| cpu as usize)
}
}
/// Set value for the `SO_INCOMING_CPU` option on this socket.
///
/// Sets the CPU affinity of the socket.
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn set_cpu_affinity(&self, cpu: usize) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
libc::SOL_SOCKET,
libc::SO_INCOMING_CPU,
cpu as c_int,
)
}
}
/// Get the value of the `SO_REUSEPORT` option on this socket.
///
/// For more information about this option, see [`set_reuse_port`].
///
/// [`set_reuse_port`]: crate::Socket::set_reuse_port
#[cfg(all(
feature = "all",
not(any(target_os = "solaris", target_os = "illumos"))
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
unix,
not(any(target_os = "solaris", target_os = "illumos"))
)))
)]
pub fn reuse_port(&self) -> io::Result<bool> {
unsafe {
getsockopt::<c_int>(self.as_raw(), libc::SOL_SOCKET, libc::SO_REUSEPORT)
.map(|reuse| reuse != 0)
}
}
/// Set value for the `SO_REUSEPORT` option on this socket.
///
/// This indicates that further calls to `bind` may allow reuse of local
/// addresses. For IPv4 sockets this means that a socket may bind even when
/// there's a socket already listening on this port.
#[cfg(all(
feature = "all",
not(any(target_os = "solaris", target_os = "illumos"))
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
unix,
not(any(target_os = "solaris", target_os = "illumos"))
)))
)]
pub fn set_reuse_port(&self, reuse: bool) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
libc::SOL_SOCKET,
libc::SO_REUSEPORT,
reuse as c_int,
)
}
}
/// Get the value of the `SO_REUSEPORT_LB` option on this socket.
///
/// For more information about this option, see [`set_reuse_port_lb`].
///
/// [`set_reuse_port_lb`]: crate::Socket::set_reuse_port_lb
#[cfg(all(feature = "all", target_os = "freebsd"))]
pub fn reuse_port_lb(&self) -> io::Result<bool> {
unsafe {
getsockopt::<c_int>(self.as_raw(), libc::SOL_SOCKET, libc::SO_REUSEPORT_LB)
.map(|reuse| reuse != 0)
}
}
/// Set value for the `SO_REUSEPORT_LB` option on this socket.
///
/// This allows multiple programs or threads to bind to the same port and
/// incoming connections will be load balanced using a hash function.
#[cfg(all(feature = "all", target_os = "freebsd"))]
pub fn set_reuse_port_lb(&self, reuse: bool) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
libc::SOL_SOCKET,
libc::SO_REUSEPORT_LB,
reuse as c_int,
)
}
}
/// Get the value of the `IP_FREEBIND` option on this socket.
///
/// For more information about this option, see [`set_freebind`].
///
/// [`set_freebind`]: crate::Socket::set_freebind
#[cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
)))
)]
pub fn freebind(&self) -> io::Result<bool> {
unsafe {
getsockopt::<c_int>(self.as_raw(), libc::SOL_IP, libc::IP_FREEBIND)
.map(|freebind| freebind != 0)
}
}
/// Set value for the `IP_FREEBIND` option on this socket.
///
/// If enabled, this boolean option allows binding to an IP address that is
/// nonlocal or does not (yet) exist. This permits listening on a socket,
/// without requiring the underlying network interface or the specified
/// dynamic IP address to be up at the time that the application is trying
/// to bind to it.
#[cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
)))
)]
pub fn set_freebind(&self, freebind: bool) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
libc::SOL_IP,
libc::IP_FREEBIND,
freebind as c_int,
)
}
}
/// Get the value of the `IPV6_FREEBIND` option on this socket.
///
/// This is an IPv6 counterpart of `IP_FREEBIND` socket option on
/// Android/Linux. For more information about this option, see
/// [`set_freebind`].
///
/// [`set_freebind`]: crate::Socket::set_freebind
#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
#[cfg_attr(
docsrs,
doc(cfg(all(feature = "all", any(target_os = "android", target_os = "linux"))))
)]
pub fn freebind_ipv6(&self) -> io::Result<bool> {
unsafe {
getsockopt::<c_int>(self.as_raw(), libc::SOL_IPV6, libc::IPV6_FREEBIND)
.map(|freebind| freebind != 0)
}
}
/// Set value for the `IPV6_FREEBIND` option on this socket.
///
/// This is an IPv6 counterpart of `IP_FREEBIND` socket option on
/// Android/Linux. For more information about this option, see
/// [`set_freebind`].
///
/// [`set_freebind`]: crate::Socket::set_freebind
///
/// # Examples
///
/// On Linux:
///
/// ```
/// use socket2::{Domain, Socket, Type};
/// use std::io::{self, Error, ErrorKind};
///
/// fn enable_freebind(socket: &Socket) -> io::Result<()> {
/// match socket.domain()? {
/// Domain::IPV4 => socket.set_freebind(true)?,
/// Domain::IPV6 => socket.set_freebind_ipv6(true)?,
/// _ => return Err(Error::new(ErrorKind::Other, "unsupported domain")),
/// };
/// Ok(())
/// }
///
/// # fn main() -> io::Result<()> {
/// # let socket = Socket::new(Domain::IPV6, Type::STREAM, None)?;
/// # enable_freebind(&socket)
/// # }
/// ```
#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
#[cfg_attr(
docsrs,
doc(cfg(all(feature = "all", any(target_os = "android", target_os = "linux"))))
)]
pub fn set_freebind_ipv6(&self, freebind: bool) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
libc::SOL_IPV6,
libc::IPV6_FREEBIND,
freebind as c_int,
)
}
}
/// Get the value for the `SO_ORIGINAL_DST` option on this socket.
///
/// This value contains the original destination IPv4 address of the connection
/// redirected using `iptables` `REDIRECT` or `TPROXY`.
#[cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
)))
)]
pub fn original_dst(&self) -> io::Result<SockAddr> {
// Safety: `getsockopt` initialises the `SockAddr` for us.
unsafe {
SockAddr::try_init(|storage, len| {
syscall!(getsockopt(
self.as_raw(),
libc::SOL_IP,
libc::SO_ORIGINAL_DST,
storage.cast(),
len
))
})
}
.map(|(_, addr)| addr)
}
/// Get the value for the `IP6T_SO_ORIGINAL_DST` option on this socket.
///
/// This value contains the original destination IPv6 address of the connection
/// redirected using `ip6tables` `REDIRECT` or `TPROXY`.
#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
#[cfg_attr(
docsrs,
doc(cfg(all(feature = "all", any(target_os = "android", target_os = "linux"))))
)]
pub fn original_dst_ipv6(&self) -> io::Result<SockAddr> {
// Safety: `getsockopt` initialises the `SockAddr` for us.
unsafe {
SockAddr::try_init(|storage, len| {
syscall!(getsockopt(
self.as_raw(),
libc::SOL_IPV6,
libc::IP6T_SO_ORIGINAL_DST,
storage.cast(),
len
))
})
}
.map(|(_, addr)| addr)
}
/// Copies data between a `file` and this socket using the `sendfile(2)`
/// system call. Because this copying is done within the kernel,
/// `sendfile()` is more efficient than the combination of `read(2)` and
/// `write(2)`, which would require transferring data to and from user
/// space.
///
/// Different OSs support different kinds of `file`s, see the OS
/// documentation for what kind of files are supported. Generally *regular*
/// files are supported by all OSs.
#[doc = man_links!(unix: sendfile(2))]
///
/// The `offset` is the absolute offset into the `file` to use as starting
/// point.
///
/// Depending on the OS this function *may* change the offset of `file`. For
/// the best results reset the offset of the file before using it again.
///
/// The `length` determines how many bytes to send, where a length of `None`
/// means it will try to send all bytes.
#[cfg(all(
feature = "all",
any(
target_os = "aix",
target_os = "android",
target_os = "freebsd",
target_os = "ios",
target_os = "linux",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(
target_os = "aix",
target_os = "android",
target_os = "freebsd",
target_os = "ios",
target_os = "linux",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
)))
)]
pub fn sendfile<F>(
&self,
file: &F,
offset: usize,
length: Option<NonZeroUsize>,
) -> io::Result<usize>
where
F: AsRawFd,
{
self._sendfile(file.as_raw_fd(), offset as _, length)
}
#[cfg(all(
feature = "all",
any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
)
))]
fn _sendfile(
&self,
file: RawFd,
offset: libc::off_t,
length: Option<NonZeroUsize>,
) -> io::Result<usize> {
// On macOS `length` is value-result parameter. It determines the number
// of bytes to write and returns the number of bytes written.
let mut length = match length {
Some(n) => n.get() as libc::off_t,
// A value of `0` means send all bytes.
None => 0,
};
syscall!(sendfile(
file,
self.as_raw(),
offset,
&mut length,
ptr::null_mut(),
0,
))
.map(|_| length as usize)
}
#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
fn _sendfile(
&self,
file: RawFd,
offset: libc::off_t,
length: Option<NonZeroUsize>,
) -> io::Result<usize> {
let count = match length {
Some(n) => n.get() as libc::size_t,
// The maximum the Linux kernel will write in a single call.
None => 0x7ffff000, // 2,147,479,552 bytes.
};
let mut offset = offset;
syscall!(sendfile(self.as_raw(), file, &mut offset, count)).map(|n| n as usize)
}
#[cfg(all(feature = "all", target_os = "freebsd"))]
fn _sendfile(
&self,
file: RawFd,
offset: libc::off_t,
length: Option<NonZeroUsize>,
) -> io::Result<usize> {
let nbytes = match length {
Some(n) => n.get() as libc::size_t,
// A value of `0` means send all bytes.
None => 0,
};
let mut sbytes: libc::off_t = 0;
syscall!(sendfile(
file,
self.as_raw(),
offset,
nbytes,
ptr::null_mut(),
&mut sbytes,
0,
))
.map(|_| sbytes as usize)
}
#[cfg(all(feature = "all", target_os = "aix"))]
fn _sendfile(
&self,
file: RawFd,
offset: libc::off_t,
length: Option<NonZeroUsize>,
) -> io::Result<usize> {
let nbytes = match length {
Some(n) => n.get() as i64,
None => -1,
};
let mut params = libc::sf_parms {
header_data: ptr::null_mut(),
header_length: 0,
file_descriptor: file,
file_size: 0,
file_offset: offset as u64,
file_bytes: nbytes,
trailer_data: ptr::null_mut(),
trailer_length: 0,
bytes_sent: 0,
};
// AIX doesn't support SF_REUSE, socket will be closed after successful transmission.
syscall!(send_file(
&mut self.as_raw() as *mut _,
&mut params as *mut _,
libc::SF_CLOSE as libc::c_uint,
))
.map(|_| params.bytes_sent as usize)
}
/// Set the value of the `TCP_USER_TIMEOUT` option on this socket.
///
/// If set, this specifies the maximum amount of time that transmitted data may remain
/// unacknowledged or buffered data may remain untransmitted before TCP will forcibly close the
/// corresponding connection.
///
/// Setting `timeout` to `None` or a zero duration causes the system default timeouts to
/// be used. If `timeout` in milliseconds is larger than `c_uint::MAX`, the timeout is clamped
/// to `c_uint::MAX`. For example, when `c_uint` is a 32-bit value, this limits the timeout to
/// approximately 49.71 days.
#[cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
)))
)]
pub fn set_tcp_user_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
let timeout = timeout.map_or(0, |to| {
min(to.as_millis(), libc::c_uint::MAX as u128) as libc::c_uint
});
unsafe {
setsockopt(
self.as_raw(),
libc::IPPROTO_TCP,
libc::TCP_USER_TIMEOUT,
timeout,
)
}
}
/// Get the value of the `TCP_USER_TIMEOUT` option on this socket.
///
/// For more information about this option, see [`set_tcp_user_timeout`].
///
/// [`set_tcp_user_timeout`]: crate::Socket::set_tcp_user_timeout
#[cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(target_os = "android", target_os = "fuchsia", target_os = "linux")
)))
)]
pub fn tcp_user_timeout(&self) -> io::Result<Option<Duration>> {
unsafe {
getsockopt::<libc::c_uint>(self.as_raw(), libc::IPPROTO_TCP, libc::TCP_USER_TIMEOUT)
.map(|millis| {
if millis == 0 {
None
} else {
Some(Duration::from_millis(millis as u64))
}
})
}
}
/// Attach Berkeley Packet Filter(BPF) on this socket.
///
/// BPF allows a user-space program to attach a filter onto any socket
/// and allow or disallow certain types of data to come through the socket.
///
/// For more information about this option, see [filter](https://www.kernel.org/doc/html/v5.12/networking/filter.html)
#[cfg(all(feature = "all", any(target_os = "linux", target_os = "android")))]
pub fn attach_filter(&self, filters: &[libc::sock_filter]) -> io::Result<()> {
let prog = libc::sock_fprog {
len: filters.len() as u16,
filter: filters.as_ptr() as *mut _,
};
unsafe {
setsockopt(
self.as_raw(),
libc::SOL_SOCKET,
libc::SO_ATTACH_FILTER,
prog,
)
}
}
/// Detach Berkeley Packet Filter(BPF) from this socket.
///
/// For more information about this option, see [`attach_filter`]
///
/// [`attach_filter`]: crate::Socket::attach_filter
#[cfg(all(feature = "all", any(target_os = "linux", target_os = "android")))]
pub fn detach_filter(&self) -> io::Result<()> {
unsafe { setsockopt(self.as_raw(), libc::SOL_SOCKET, libc::SO_DETACH_FILTER, 0) }
}
/// Gets the value for the `SO_COOKIE` option on this socket.
///
/// The socket cookie is a unique, kernel-managed identifier tied to each socket.
/// Therefore, there is no corresponding `set` helper.
///
/// For more information about this option, see [Linux patch](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=5daab9db7b65df87da26fd8cfa695fb9546a1ddb)
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn cookie(&self) -> io::Result<u64> {
unsafe { getsockopt::<libc::c_ulonglong>(self.as_raw(), libc::SOL_SOCKET, libc::SO_COOKIE) }
}
/// Get the value of the `IPV6_TCLASS` option for this socket.
///
/// For more information about this option, see [`set_tclass_v6`].
///
/// [`set_tclass_v6`]: crate::Socket::set_tclass_v6
#[cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "macos",
target_os = "netbsd",
target_os = "openbsd"
)
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "macos",
target_os = "netbsd",
target_os = "openbsd"
)
)))
)]
pub fn tclass_v6(&self) -> io::Result<u32> {
unsafe {
getsockopt::<c_int>(self.as_raw(), IPPROTO_IPV6, libc::IPV6_TCLASS)
.map(|tclass| tclass as u32)
}
}
/// Set the value of the `IPV6_TCLASS` option for this socket.
///
/// Specifies the traffic class field that is used in every packets
/// sent from this socket.
#[cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "macos",
target_os = "netbsd",
target_os = "openbsd"
)
))]
#[cfg_attr(
docsrs,
doc(cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "macos",
target_os = "netbsd",
target_os = "openbsd"
)
)))
)]
pub fn set_tclass_v6(&self, tclass: u32) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
IPPROTO_IPV6,
libc::IPV6_TCLASS,
tclass as c_int,
)
}
}
/// Get the value of the `TCP_CONGESTION` option for this socket.
///
/// For more information about this option, see [`set_tcp_congestion`].
///
/// [`set_tcp_congestion`]: crate::Socket::set_tcp_congestion
#[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux")))]
#[cfg_attr(
docsrs,
doc(cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux"))))
)]
pub fn tcp_congestion(&self) -> io::Result<Vec<u8>> {
let mut payload: [u8; TCP_CA_NAME_MAX] = [0; TCP_CA_NAME_MAX];
let mut len = payload.len() as libc::socklen_t;
syscall!(getsockopt(
self.as_raw(),
IPPROTO_TCP,
libc::TCP_CONGESTION,
payload.as_mut_ptr().cast(),
&mut len,
))
.map(|_| payload[..len as usize].to_vec())
}
/// Set the value of the `TCP_CONGESTION` option for this socket.
///
/// Specifies the TCP congestion control algorithm to use for this socket.
///
/// The value must be a valid TCP congestion control algorithm name of the
/// platform. For example, Linux may supports "reno", "cubic".
#[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux")))]
#[cfg_attr(
docsrs,
doc(cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux"))))
)]
pub fn set_tcp_congestion(&self, tcp_ca_name: &[u8]) -> io::Result<()> {
syscall!(setsockopt(
self.as_raw(),
IPPROTO_TCP,
libc::TCP_CONGESTION,
tcp_ca_name.as_ptr() as *const _,
tcp_ca_name.len() as libc::socklen_t,
))
.map(|_| ())
}
/// Set value for the `DCCP_SOCKOPT_SERVICE` option on this socket.
///
/// Sets the DCCP service. The specification mandates use of service codes.
/// If this socket option is not set, the socket will fall back to 0 (which
/// means that no meaningful service code is present). On active sockets
/// this is set before [`connect`]. On passive sockets up to 32 service
/// codes can be set before calling [`bind`]
///
/// [`connect`]: crate::Socket::connect
/// [`bind`]: crate::Socket::bind
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn set_dccp_service(&self, code: u32) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
libc::SOL_DCCP,
libc::DCCP_SOCKOPT_SERVICE,
code,
)
}
}
/// Get the value of the `DCCP_SOCKOPT_SERVICE` option on this socket.
///
/// For more information about this option see [`set_dccp_service`]
///
/// [`set_dccp_service`]: crate::Socket::set_dccp_service
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn dccp_service(&self) -> io::Result<u32> {
unsafe { getsockopt(self.as_raw(), libc::SOL_DCCP, libc::DCCP_SOCKOPT_SERVICE) }
}
/// Set value for the `DCCP_SOCKOPT_CCID` option on this socket.
///
/// This option sets both the TX and RX CCIDs at the same time.
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn set_dccp_ccid(&self, ccid: u8) -> io::Result<()> {
unsafe { setsockopt(self.as_raw(), libc::SOL_DCCP, libc::DCCP_SOCKOPT_CCID, ccid) }
}
/// Get the value of the `DCCP_SOCKOPT_TX_CCID` option on this socket.
///
/// For more information about this option see [`set_dccp_ccid`].
///
/// [`set_dccp_ccid`]: crate::Socket::set_dccp_ccid
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn dccp_tx_ccid(&self) -> io::Result<u32> {
unsafe { getsockopt(self.as_raw(), libc::SOL_DCCP, libc::DCCP_SOCKOPT_TX_CCID) }
}
/// Get the value of the `DCCP_SOCKOPT_RX_CCID` option on this socket.
///
/// For more information about this option see [`set_dccp_ccid`].
///
/// [`set_dccp_ccid`]: crate::Socket::set_dccp_ccid
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn dccp_xx_ccid(&self) -> io::Result<u32> {
unsafe { getsockopt(self.as_raw(), libc::SOL_DCCP, libc::DCCP_SOCKOPT_RX_CCID) }
}
/// Set value for the `DCCP_SOCKOPT_SERVER_TIMEWAIT` option on this socket.
///
/// Enables a listening socket to hold timewait state when closing the
/// connection. This option must be set after `accept` returns.
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn set_dccp_server_timewait(&self, hold_timewait: bool) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
libc::SOL_DCCP,
libc::DCCP_SOCKOPT_SERVER_TIMEWAIT,
hold_timewait as c_int,
)
}
}
/// Get the value of the `DCCP_SOCKOPT_SERVER_TIMEWAIT` option on this socket.
///
/// For more information see [`set_dccp_server_timewait`]
///
/// [`set_dccp_server_timewait`]: crate::Socket::set_dccp_server_timewait
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn dccp_server_timewait(&self) -> io::Result<bool> {
unsafe {
getsockopt(
self.as_raw(),
libc::SOL_DCCP,
libc::DCCP_SOCKOPT_SERVER_TIMEWAIT,
)
}
}
/// Set value for the `DCCP_SOCKOPT_SEND_CSCOV` option on this socket.
///
/// Both this option and `DCCP_SOCKOPT_RECV_CSCOV` are used for setting the
/// partial checksum coverage. The default is that checksums always cover
/// the entire packet and that only fully covered application data is
/// accepted by the receiver. Hence, when using this feature on the sender,
/// it must be enabled at the receiver too, with suitable choice of CsCov.
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn set_dccp_send_cscov(&self, level: u32) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
libc::SOL_DCCP,
libc::DCCP_SOCKOPT_SEND_CSCOV,
level,
)
}
}
/// Get the value of the `DCCP_SOCKOPT_SEND_CSCOV` option on this socket.
///
/// For more information on this option see [`set_dccp_send_cscov`].
///
/// [`set_dccp_send_cscov`]: crate::Socket::set_dccp_send_cscov
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn dccp_send_cscov(&self) -> io::Result<u32> {
unsafe { getsockopt(self.as_raw(), libc::SOL_DCCP, libc::DCCP_SOCKOPT_SEND_CSCOV) }
}
/// Set the value of the `DCCP_SOCKOPT_RECV_CSCOV` option on this socket.
///
/// This option is only useful when combined with [`set_dccp_send_cscov`].
///
/// [`set_dccp_send_cscov`]: crate::Socket::set_dccp_send_cscov
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn set_dccp_recv_cscov(&self, level: u32) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
libc::SOL_DCCP,
libc::DCCP_SOCKOPT_RECV_CSCOV,
level,
)
}
}
/// Get the value of the `DCCP_SOCKOPT_RECV_CSCOV` option on this socket.
///
/// For more information on this option see [`set_dccp_recv_cscov`].
///
/// [`set_dccp_recv_cscov`]: crate::Socket::set_dccp_recv_cscov
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn dccp_recv_cscov(&self) -> io::Result<u32> {
unsafe { getsockopt(self.as_raw(), libc::SOL_DCCP, libc::DCCP_SOCKOPT_RECV_CSCOV) }
}
/// Set value for the `DCCP_SOCKOPT_QPOLICY_TXQLEN` option on this socket.
///
/// This option sets the maximum length of the output queue. A zero value is
/// interpreted as unbounded queue length.
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn set_dccp_qpolicy_txqlen(&self, length: u32) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
libc::SOL_DCCP,
libc::DCCP_SOCKOPT_QPOLICY_TXQLEN,
length,
)
}
}
/// Get the value of the `DCCP_SOCKOPT_QPOLICY_TXQLEN` on this socket.
///
/// For more information on this option see [`set_dccp_qpolicy_txqlen`].
///
/// [`set_dccp_qpolicy_txqlen`]: crate::Socket::set_dccp_qpolicy_txqlen
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn dccp_qpolicy_txqlen(&self) -> io::Result<u32> {
unsafe {
getsockopt(
self.as_raw(),
libc::SOL_DCCP,
libc::DCCP_SOCKOPT_QPOLICY_TXQLEN,
)
}
}
/// Get the value of the `DCCP_SOCKOPT_AVAILABLE_CCIDS` option on this socket.
///
/// Returns the list of CCIDs supported by the endpoint.
///
/// The parameter `N` is used to get the maximum number of supported
/// endpoints. The [documentation] recommends a minimum of four at the time
/// of writing.
///
/// [documentation]: https://www.kernel.org/doc/html/latest/networking/dccp.html
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn dccp_available_ccids<const N: usize>(&self) -> io::Result<CcidEndpoints<N>> {
let mut endpoints = [0; N];
let mut length = endpoints.len() as libc::socklen_t;
syscall!(getsockopt(
self.as_raw(),
libc::SOL_DCCP,
libc::DCCP_SOCKOPT_AVAILABLE_CCIDS,
endpoints.as_mut_ptr().cast(),
&mut length,
))?;
Ok(CcidEndpoints { endpoints, length })
}
/// Get the value of the `DCCP_SOCKOPT_GET_CUR_MPS` option on this socket.
///
/// This option retrieves the current maximum packet size (application
/// payload size) in bytes.
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
pub fn dccp_cur_mps(&self) -> io::Result<u32> {
unsafe {
getsockopt(
self.as_raw(),
libc::SOL_DCCP,
libc::DCCP_SOCKOPT_GET_CUR_MPS,
)
}
}
}
/// See [`Socket::dccp_available_ccids`].
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
#[derive(Debug)]
pub struct CcidEndpoints<const N: usize> {
endpoints: [u8; N],
length: u32,
}
#[cfg(all(feature = "all", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
impl<const N: usize> std::ops::Deref for CcidEndpoints<N> {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.endpoints[0..self.length as usize]
}
}
#[cfg_attr(docsrs, doc(cfg(unix)))]
impl AsFd for crate::Socket {
fn as_fd(&self) -> BorrowedFd<'_> {
// SAFETY: lifetime is bound by self.
unsafe { BorrowedFd::borrow_raw(self.as_raw()) }
}
}
#[cfg_attr(docsrs, doc(cfg(unix)))]
impl AsRawFd for crate::Socket {
fn as_raw_fd(&self) -> c_int {
self.as_raw()
}
}
#[cfg_attr(docsrs, doc(cfg(unix)))]
impl From<crate::Socket> for OwnedFd {
fn from(sock: crate::Socket) -> OwnedFd {
// SAFETY: sock.into_raw() always returns a valid fd.
unsafe { OwnedFd::from_raw_fd(sock.into_raw()) }
}
}
#[cfg_attr(docsrs, doc(cfg(unix)))]
impl IntoRawFd for crate::Socket {
fn into_raw_fd(self) -> c_int {
self.into_raw()
}
}
#[cfg_attr(docsrs, doc(cfg(unix)))]
impl From<OwnedFd> for crate::Socket {
fn from(fd: OwnedFd) -> crate::Socket {
// SAFETY: `OwnedFd` ensures the fd is valid.
unsafe { crate::Socket::from_raw_fd(fd.into_raw_fd()) }
}
}
#[cfg_attr(docsrs, doc(cfg(unix)))]
impl FromRawFd for crate::Socket {
unsafe fn from_raw_fd(fd: c_int) -> crate::Socket {
crate::Socket::from_raw(fd)
}
}
#[cfg(feature = "all")]
from!(UnixStream, crate::Socket);
#[cfg(feature = "all")]
from!(UnixListener, crate::Socket);
#[cfg(feature = "all")]
from!(UnixDatagram, crate::Socket);
#[cfg(feature = "all")]
from!(crate::Socket, UnixStream);
#[cfg(feature = "all")]
from!(crate::Socket, UnixListener);
#[cfg(feature = "all")]
from!(crate::Socket, UnixDatagram);
#[test]
fn in_addr_convertion() {
let ip = Ipv4Addr::new(127, 0, 0, 1);
let raw = to_in_addr(&ip);
// NOTE: `in_addr` is packed on NetBSD and it's unsafe to borrow.
let a = raw.s_addr;
assert_eq!(a, u32::from_ne_bytes([127, 0, 0, 1]));
assert_eq!(from_in_addr(raw), ip);
let ip = Ipv4Addr::new(127, 34, 4, 12);
let raw = to_in_addr(&ip);
let a = raw.s_addr;
assert_eq!(a, u32::from_ne_bytes([127, 34, 4, 12]));
assert_eq!(from_in_addr(raw), ip);
}
#[test]
fn in6_addr_convertion() {
let ip = Ipv6Addr::new(0x2000, 1, 2, 3, 4, 5, 6, 7);
let raw = to_in6_addr(&ip);
let want = [32, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7];
assert_eq!(raw.s6_addr, want);
assert_eq!(from_in6_addr(raw), ip);
}